Merge pull request #2860 from booklore-app/develop

Merge develop into master for release
This commit is contained in:
ACX
2026-02-23 07:35:03 -07:00
committed by GitHub
2301 changed files with 172066 additions and 42401 deletions
+15
View File
@@ -0,0 +1,15 @@
.git
.github
.idea
.vscode
.angular
booklore-ui/node_modules
booklore-ui/dist
booklore-ui/.angular
booklore-ui/test-results
booklore-api/build/reports
booklore-api/build/test-results
*.md
+1 -1
View File
@@ -3,7 +3,7 @@
github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
patreon: # Replace with a single Patreon username
open_collective: booklore
ko_fi: # Replace with a single Ko-fi username
ko_fi: bookloredev
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
+81 -38
View File
@@ -1,59 +1,102 @@
## 🚀 Pull Request
## 📝 Description
### 📝 Description
<!-- Why is this change needed? Explain in your own words. -->
<!-- Provide a clear and concise summary of the changes introduced in this pull request -->
<!-- Reference related issues using "Fixes #123", "Closes #456", or "Relates to #789" -->
**Linked Issue:** Fixes #<!-- issue number -->
### 🛠️ Changes Implemented
> **Required.** Every PR must reference an approved issue. If no issue exists, [open one](https://github.com/booklore-app/booklore/issues/new) and wait for maintainer approval before submitting a PR. Unsolicited PRs without a linked issue will be closed.
<!-- Detail the specific modifications, additions, or removals made in this pull request -->
-
## 🏷️ Type of Change
### 🧪 Testing Strategy
- [ ] Bug fix
- [ ] New feature
- [ ] Enhancement to existing feature
- [ ] Refactor (no behavior change)
- [ ] Breaking change (existing functionality affected)
- [ ] Documentation update
<!-- Describe the testing methodology used to verify the correctness of these changes -->
<!-- Include testing approach, scenarios covered, and edge cases considered -->
## 🔧 Changes
### 📸 Visual Changes _(if applicable)_
<!-- List the specific modifications made -->
-
<!-- Attach screenshots or videos demonstrating UI/UX modifications -->
## 🧪 Testing (MANDATORY)
> **PRs without this section filled out will be closed.** "Tests pass" or "Tested locally" is not sufficient. You must provide specifics.
**Manual testing steps you performed:**
<!-- Walk through the exact steps you took to verify your change works. Be specific. -->
1.
2.
3.
**Regression testing:**
<!-- How did you verify that existing related features still work after your change? -->
-
**Edge cases covered:**
<!-- What boundary conditions or unusual inputs did you test? -->
-
**Test output:**
<!-- Paste the actual terminal output from running tests. Not "all pass", the real output. -->
<details>
<summary>Backend test output (<code>./gradlew test</code>)</summary>
```
PASTE OUTPUT HERE
```
</details>
<details>
<summary>Frontend test output (<code>ng test</code>)</summary>
```
PASTE OUTPUT HERE
```
</details>
## 📸 Screen Recording / Screenshots (MANDATORY)
> Every PR must include a **screen recording or screenshots** showing the change working end-to-end in a running local instance (both backend and frontend). This means you must have actually built, run, and tested the code yourself. PRs without visual proof will be closed without review.
<!-- Attach screen recording or screenshots here -->
---
## ⚠️ Required Pre-Submission Checklist
## ✅ Pre-Submission Checklist
### **Please Read - This Checklist is Mandatory**
> **All boxes must be checked before requesting review.** Incomplete PRs will be closed without review. No exceptions.
> **Important Notice:** We've experienced several production bugs recently due to incomplete pre-submission checks. To maintain code quality and prevent issues from reaching production, we're enforcing stricter adherence to this checklist.
>
> **All checkboxes below must be completed before requesting review.** PRs that haven't completed these requirements will be sent back for completion.
- [ ] This PR is linked to an approved issue
- [ ] Code follows project style guidelines and conventions
- [ ] Branch is up to date with `develop` (merge conflicts resolved)
- [ ] I ran the full stack locally (backend + frontend + database) and verified the change works
- [ ] Automated tests added or updated to cover changes (backend **and** frontend)
- [ ] All tests pass locally and output is pasted above
- [ ] Screen recording or screenshots are attached above proving the change works
- [ ] PR is a single focused change (one bug fix OR one feature, not multiple unrelated changes)
- [ ] PR is reasonably scoped (PRs over 1000+ changed lines will be closed, split into smaller PRs)
- [ ] No unsolicited refactors, cleanups, or "improvements" are bundled in
- [ ] Flyway migration versioning is correct _(if schema was modified)_
- [ ] Documentation PR submitted to [booklore-docs](https://github.com/booklore-app/booklore-docs) _(if user-facing changes)_
#### **Mandatory Requirements** _(please check ALL boxes)_:
### 🤖 AI-Assisted Contributions
- [ ] **Code adheres to project style guidelines and conventions**
- [ ] **Branch synchronized with latest `develop` branch** _(please resolve any merge conflicts)_
- [ ] **🚨 CRITICAL: Automated unit tests added/updated to cover changes** _(MANDATORY for ALL Spring Boot backend and Angular frontend changes - this is non-negotiable)_
- [ ] **🚨 CRITICAL: All tests pass locally** _(run `./gradlew test` for Spring Boot backend, and `ng test` for Angular frontend - NO EXCEPTIONS)_
- [ ] **🚨 CRITICAL: Manual testing completed in local development environment** _(verify your changes work AND no existing functionality is broken - test related features thoroughly)_
- [ ] **Flyway migration versioning follows correct sequence** _(if database schema was modified)_
- [ ] **Documentation PR submitted to [booklore-docs](https://github.com/booklore-app/booklore-docs)** _(required for features or enhancements that introduce user-facing or visual changes)_
> **If any part of this PR was generated or assisted by AI tools (Copilot, Claude, ChatGPT, etc.), all items below are mandatory.** You are fully responsible for every line you submit. "The AI wrote it" is not an excuse, and AI-generated PRs that clearly haven't been reviewed are the #1 reason PRs get closed.
#### **Why This Matters:**
Recent production incidents have been traced back to:
- **Incomplete testing coverage (especially backend)**
- Merge conflicts not resolved before merge
- Missing documentation for new features
**Backend changes without tests will not be accepted.** By completing this checklist thoroughly, you're helping maintain the quality and stability of Booklore for all users.
**Note to Reviewers:** Please verify the checklist is complete before beginning your review. If items are unchecked, kindly ask the contributor to complete them first.
- [ ] I have read and understand every line of this PR and can explain any part of it during review
- [ ] I personally ran the code and verified it works (not just trusted the AI's output)
- [ ] PR is scoped to a single logical change, not a dump of everything the AI suggested
- [ ] Tests validate actual behavior, not just coverage (AI-generated tests often assert nothing meaningful)
- [ ] No dead code, placeholder comments, `TODO`s, or unused scaffolding left behind by AI
- [ ] I did not submit refactors, style changes, or "improvements" the AI suggested beyond the scope of the issue
---
### 💬 Additional Context _(optional)_
## 💬 Additional Context _(optional)_
<!-- Provide any supplementary information, implementation considerations, or discussion points for reviewers -->
<!-- Any extra information or discussion points for reviewers -->
+3
View File
@@ -27,6 +27,9 @@ categories:
labels:
- 'bug'
- 'fix'
- title: '⚡ Performance'
labels:
- 'performance'
- title: '🛠️ Refactoring & Maintenance'
labels:
- 'refactor'
+56 -12
View File
@@ -31,10 +31,10 @@ jobs:
- name: Checkout Repository
uses: actions/checkout@v6
- name: Set Up JDK 21
- name: Set Up JDK 25
uses: actions/setup-java@v5
with:
java-version: '21'
java-version: '25'
distribution: 'temurin'
cache: gradle
@@ -85,7 +85,7 @@ jobs:
uses: actions/checkout@v6
- name: Set Up Node.js
uses: actions/setup-node@v4
uses: actions/setup-node@v6
with:
node-version: '22'
cache: 'npm'
@@ -140,15 +140,6 @@ jobs:
with:
fetch-depth: 0
# ----------------------------------------
# Environment setup
# ----------------------------------------
- name: Set Up QEMU for Multi-Arch Builds
uses: docker/setup-qemu-action@v3
- name: Set Up Docker Buildx
uses: docker/setup-buildx-action@v3
# ----------------------------------------
# Image tagging
# ----------------------------------------
@@ -166,6 +157,58 @@ jobs:
echo "image_tag=$image_tag" >> $GITHUB_ENV
echo "Image tag: $image_tag"
# ----------------------------------------
# Native Angular build
# ----------------------------------------
- name: Set Up Node.js
uses: actions/setup-node@v6
with:
node-version: '22'
cache: 'npm'
cache-dependency-path: booklore-ui/package-lock.json
- name: Install Frontend Dependencies
working-directory: ./booklore-ui
run: npm ci --force
- name: Build Angular App
working-directory: ./booklore-ui
run: npx ng build --configuration=production
# ----------------------------------------
# Native Gradle build
# ----------------------------------------
- name: Set Up JDK 25
uses: actions/setup-java@v5
with:
java-version: '25'
distribution: 'temurin'
cache: gradle
- name: Copy Angular Dist to Spring Boot Resources
run: cp -r booklore-ui/dist/booklore/browser/. booklore-api/src/main/resources/static/
- name: Inject Version into application.yaml
env:
APP_VERSION: ${{ env.image_tag }}
run: |
sudo wget -qO /usr/local/bin/yq https://github.com/mikefarah/yq/releases/download/v4.52.2/yq_linux_amd64
sudo chmod +x /usr/local/bin/yq
yq eval '.app.version = strenv(APP_VERSION)' -i booklore-api/src/main/resources/application.yaml
- name: Build Spring Boot JAR
working-directory: ./booklore-api
run: ./gradlew clean build -x test --no-daemon --parallel --build-cache
# ----------------------------------------
# Environment setup
# ----------------------------------------
- name: Set Up QEMU for Multi-Arch Builds
uses: docker/setup-qemu-action@v3
- name: Set Up Docker Buildx
uses: docker/setup-buildx-action@v3
# ----------------------------------------
# Docker login (pushes & internal PRs only)
# ----------------------------------------
@@ -192,6 +235,7 @@ jobs:
uses: docker/build-push-action@v6
with:
context: .
file: Dockerfile.ci
platforms: linux/amd64,linux/arm64
push: true
tags: |
+50 -3
View File
@@ -43,10 +43,10 @@ jobs:
- name: Checkout Repository
uses: actions/checkout@v6
- name: Set Up JDK 21
- name: Set Up JDK 25
uses: actions/setup-java@v5
with:
java-version: '21'
java-version: '25'
distribution: 'temurin'
cache: gradle
@@ -97,7 +97,7 @@ jobs:
uses: actions/checkout@v6
- name: Set Up Node.js
uses: actions/setup-node@v4
uses: actions/setup-node@v6
with:
node-version: '22'
cache: 'npm'
@@ -234,10 +234,57 @@ jobs:
echo "bump=$bump" >> $GITHUB_ENV
echo "new_tag=$next_version" >> $GITHUB_ENV
# ----------------------------------------
# Native Angular build
# ----------------------------------------
- name: Set Up Node.js
uses: actions/setup-node@v6
with:
node-version: '22'
cache: 'npm'
cache-dependency-path: booklore-ui/package-lock.json
- name: Install Frontend Dependencies
working-directory: ./booklore-ui
run: npm ci --force
- name: Build Angular App
working-directory: ./booklore-ui
run: npx ng build --configuration=production
# ----------------------------------------
# Native Gradle build
# ----------------------------------------
- name: Set Up JDK 25
uses: actions/setup-java@v5
with:
java-version: '25'
distribution: 'temurin'
cache: gradle
- name: Copy Angular Dist to Spring Boot Resources
run: cp -r booklore-ui/dist/booklore/browser/. booklore-api/src/main/resources/static/
- name: Inject Version into application.yaml
env:
APP_VERSION: ${{ env.new_tag }}
run: |
sudo wget -qO /usr/local/bin/yq https://github.com/mikefarah/yq/releases/download/v4.52.2/yq_linux_amd64
sudo chmod +x /usr/local/bin/yq
yq eval '.app.version = strenv(APP_VERSION)' -i booklore-api/src/main/resources/application.yaml
- name: Build Spring Boot JAR
working-directory: ./booklore-api
run: ./gradlew clean build -x test --no-daemon --parallel --build-cache
# ----------------------------------------
# Docker build & push
# ----------------------------------------
- name: Build and push Docker image
uses: docker/build-push-action@v6
with:
context: .
file: Dockerfile.ci
platforms: linux/amd64,linux/arm64
push: true
tags: |
+1 -1
View File
@@ -45,4 +45,4 @@ local-scripts/
### Dev config, books, and data ###
booklore-ui/test-results/
booklore-api/src/main/resources/application-local.yaml
/shared/
/shared/
+245 -317
View File
@@ -1,440 +1,368 @@
# Contributing to Booklore
🎉 **Thank you for your interest in contributing to Booklore!** Whether you're fixing bugs, adding features, improving documentation, or simply asking questions, every contribution helps make Booklore better for everyone.
Thanks for your interest in contributing to Booklore! Whether you're fixing bugs, adding features, improving documentation, or asking questions, every contribution helps.
---
## What is Booklore?
## 📚 What is Booklore?
**Booklore** is a modern, self-hostable digital library platform for managing and reading books and comics. It's designed with privacy, flexibility, and ease of use in mind.
**Booklore** is a self-hostable digital library platform for managing and reading books and comics.
**Tech Stack:**
- **Frontend**: Angular 20, TypeScript, PrimeNG 19
- **Backend**: Java 21, Spring Boot 3.5
- **Authentication**: Local JWT + optional OIDC (e.g., Authentik)
- **Database**: MariaDB
- **Deployment**: Docker-compatible, reverse proxy-ready
- **Frontend:** Angular 20, TypeScript, PrimeNG 19
- **Backend:** Java 21, Spring Boot 3.5
- **Authentication:** Local JWT + optional OIDC (e.g., Authentik)
- **Database:** MariaDB
- **Deployment:** Docker-compatible, reverse proxy-ready
## Table of Contents
- [Where to Start](#where-to-start)
- [Getting Started](#getting-started)
- [Development Setup](#development-setup)
- [Running Tests](#running-tests)
- [Making Changes](#making-changes)
- [Submitting a Pull Request](#submitting-a-pull-request)
- [Code Style](#code-style)
- [Reporting Bugs](#reporting-bugs)
- [Community & Support](#community--support)
- [Code of Conduct](#code-of-conduct)
- [License](#license)
---
## 📦 Project Structure
## Before You Start
```
booklore/
├── booklore-ui/ # Angular frontend application
├── booklore-api/ # Spring Boot backend API
├── assets/ # Shared assets (logos, icons, etc.)
├── docker-compose.yml # Production Docker setup
└── dev.docker-compose.yml # Development Docker setup
```
> **Issue first, PR second.** Every pull request must be linked to an approved issue. If you want to work on something, [open an issue](https://github.com/booklore-app/booklore/issues/new) (or find an existing one) and wait for a maintainer to approve it before writing code. PRs submitted without a linked, approved issue will be closed.
This protects both your time and ours. It ensures that the work is actually wanted and that you're heading in the right direction before you invest effort.
**What will get your PR closed immediately:**
- No linked issue
- No screenshots or screen recording proving the change works
- No test output pasted in the PR
- Bulk AI-generated changes that clearly haven't been reviewed or tested
- Unsolicited refactors, cleanups, or "improvements" nobody asked for
- PRs over 1000+ changed lines (split them up)
## Where to Start
Not sure where to begin? Look for issues labeled:
- [`good first issue`](https://github.com/booklore-app/booklore/labels/good%20first%20issue) - small, well-scoped tasks ideal for newcomers
- [`help wanted`](https://github.com/booklore-app/booklore/labels/help%20wanted) - tasks where maintainers would appreciate a hand
You can also check the [project roadmap](https://github.com/booklore-app/booklore/projects) for larger initiatives.
---
## 🚀 Getting Started
## Getting Started
### 1. Fork and Clone
### Fork and Clone
First, fork the repository to your GitHub account, then clone it locally:
First, [fork the repository](https://github.com/booklore-app/booklore/fork) on GitHub, then clone your fork locally:
```bash
# Clone your fork
git clone https://github.com/<your-username>/booklore.git
cd booklore
# Add upstream remote to keep your fork in sync
git remote add upstream https://github.com/booklore-app/booklore.git
```
### 2. Keep Your Fork Updated
### Keep Your Fork in Sync
Before starting work on a new feature or fix:
Before starting new work, pull the latest changes from upstream:
```bash
# Fetch latest changes from upstream
git fetch upstream
# Merge upstream changes into your local main branch
git checkout main
git merge upstream/main
# Push updates to your fork
git push origin main
git checkout develop
git merge upstream/develop
git push origin develop
```
> **Note:** All work should be based on the `develop` branch, not `main`.
---
## 🧱 Local Development Setup
## Development Setup
Booklore offers two development approaches: an all-in-one Docker stack for quick setup, or manual installation for more control.
### Project Structure
### Option 1: Docker Development Stack (Recommended for Quick Start)
```
booklore/
├── booklore-ui/ # Angular frontend (TypeScript, PrimeNG)
├── booklore-api/ # Spring Boot backend (Java 21, Gradle)
├── dev.docker-compose.yml # Development Docker stack
├── assets/ # Shared assets (logos, icons)
└── local/ # Local development helpers
```
This option sets up everything with a single command:
### Option 1: Docker Development Stack (Recommended)
The fastest way to get a working environment. No local toolchain required.
```bash
docker compose -f dev.docker-compose.yml up
```
**What you get:**
- ✅ Frontend dev server at `http://localhost:4200/`
- ✅ Backend API at `http://localhost:8080/`
- ✅ MariaDB at `localhost:3366`
- ✅ Remote Java debugging at `localhost:5005`
This starts:
**Note:** All ports are configurable via environment variables in `dev.docker-compose.yml`:
- `FRONTEND_PORT` (default: 4200)
- `BACKEND_PORT` (default: 8080)
- `DB_PORT` (default: 3366)
- `REMOTE_DEBUG_PORT` (default: 5005)
| Service | URL / Port |
|------------|-----------------------|
| Frontend | http://localhost:4200 |
| Backend | http://localhost:8080 |
| MariaDB | localhost:3366 |
| Debug port | localhost:5005 |
All ports are configurable via environment variables (`FRONTEND_PORT`, `BACKEND_PORT`, `DB_PORT`, `REMOTE_DEBUG_PORT`) in the compose file.
**Stopping the stack:**
```bash
# To stop
docker compose -f dev.docker-compose.yml down
```
---
### Option 2: Manual Setup
### Option 2: Manual Local Development
For more control over your development environment, you can run each component separately.
For full control over each component or IDE integration (debugging, hot-reload, etc.).
#### Prerequisites
Ensure you have the following installed:
- **Java 21+** ([Download](https://adoptium.net/))
- **Node.js 18+** and **npm** ([Download](https://nodejs.org/))
- **MariaDB 10.6+** ([Download](https://mariadb.org/download/))
- **Git** ([Download](https://git-scm.com/))
| Tool | Version | Download |
|---------------|---------|----------------------------------------------|
| Java | 21+ | [Adoptium](https://adoptium.net/) |
| Node.js + npm | 18+ | [nodejs.org](https://nodejs.org/) |
| MariaDB | 10.6+ | [mariadb.org](https://mariadb.org/download/) |
| Git | latest | [git-scm.com](https://git-scm.com/) |
#### Frontend Setup
#### 1. Database
```bash
# Navigate to the frontend directory
cd booklore-ui
Start MariaDB and create the database:
# Install dependencies
npm install
# Start the development server
ng serve
# Or use npm script
npm start
```sql
CREATE DATABASE IF NOT EXISTS booklore;
CREATE USER 'booklore_user'@'localhost' IDENTIFIED BY 'your_password';
GRANT ALL PRIVILEGES ON booklore.* TO 'booklore_user'@'localhost';
FLUSH PRIVILEGES;
```
The frontend will be available at `http://localhost:4200/` with hot-reload enabled.
> **Tip:** You can also spin up MariaDB via Docker: `docker compose -f local/docker-compose-maria.yml up -d`
**Common Issues:**
- If you encounter dependency conflicts, try `npm install --legacy-peer-deps`
- Use `--force` only as a last resort
#### 2. Backend
---
#### Backend Setup
##### Step 1: Configure Application Properties
Create a development configuration file at `booklore-api/src/main/resources/application-dev.yml`:
Create a dev config at `booklore-api/src/main/resources/application-dev.yml`:
```yaml
app:
# Path where books and comics are stored
path-book: '/Users/yourname/booklore-data/books'
# Path for thumbnails, metadata cache, and other config files
path-config: '/Users/yourname/booklore-data/config'
path-book: '/path/to/booklore-data/books'
path-config: '/path/to/booklore-data/config'
spring:
datasource:
driver-class-name: org.mariadb.jdbc.Driver
url: jdbc:mariadb://localhost:3306/booklore?createDatabaseIfNotExist=true
username: root
password: your_secure_password
username: booklore_user
password: your_password
```
**Important:**
- Replace `/Users/yourname/...` with actual paths on your system
- Create these directories if they don't exist
- Ensure proper read/write permissions
**Example paths:**
- **macOS/Linux**: `/Users/yourname/booklore-data/books`
- **Windows**: `C:\Users\yourname\booklore-data\books`
##### Step 2: Set Up the Database
Ensure MariaDB is running and create the database:
```bash
# Connect to MariaDB
mysql -u root -p
# Create database and user (optional)
CREATE DATABASE IF NOT EXISTS booklore;
CREATE USER 'booklore_user'@'localhost' IDENTIFIED BY 'your_secure_password';
GRANT ALL PRIVILEGES ON booklore.* TO 'booklore_user'@'localhost';
FLUSH PRIVILEGES;
EXIT;
```
##### Step 3: Run the Backend
Replace the paths with actual directories on your system and ensure they exist with read/write permissions.
```bash
cd booklore-api
./gradlew bootRun --args='--spring.profiles.active=dev'
```
The backend API will be available at `http://localhost:8080/`
**Verify it's running:**
```bash
# Verify
curl http://localhost:8080/actuator/health
```
---
## 🧪 Testing
Always run tests before submitting a pull request to ensure your changes don't break existing functionality.
### Frontend Tests (Angular + Vitest)
Booklore uses [Vitest](https://vitest.dev/) for fast, modern frontend testing in the Angular app.
#### 3. Frontend
```bash
cd booklore-ui
# Run all frontend tests
ng test
# Run tests with coverage report
ng test --coverage
npm install
ng serve
```
- The coverage report will be generated in the `coverage/` directory.
- You can open `coverage/index.html` in your browser to view detailed coverage metrics.
- All new features and bug fixes should include relevant unit tests.
The UI will be available at http://localhost:4200 with hot-reload enabled.
### Backend Tests
> If you hit dependency issues, try `npm install --legacy-peer-deps`.
---
## Running Tests
Always run tests before submitting a pull request.
**Frontend (Vitest):**
```bash
cd booklore-ui
ng test # Run all tests
ng test --coverage # With coverage report (output: coverage/)
```
**Backend (JUnit + Gradle):**
```bash
cd booklore-api
# Run all tests
./gradlew test
# Run tests with detailed output
./gradlew test --info
# Run a specific test class
./gradlew test --tests "com.booklore.api.service.BookServiceTest"
# Generate coverage report
./gradlew test jacocoTestReport
```
**Before creating a PR, always run:**
```bash
./gradlew test
./gradlew test # Run all tests
./gradlew test --tests "com.booklore.api.service.BookServiceTest" # Specific class
./gradlew test jacocoTestReport # Coverage report
```
---
## 🛠️ Contributing Guidelines
## Making Changes
### 💡 Reporting Bugs
### Branch Naming
Found a bug? Help us fix it by providing detailed information:
Create branches from `develop` using these prefixes:
1. **Search existing issues** to avoid duplicates
2. **Create a new issue** with the `bug` label
3. **Include the following:**
- Clear, descriptive title (e.g., "Book import fails with PDF files over 100MB")
- Steps to reproduce the issue
- Expected behavior vs. actual behavior
- Screenshots or error logs if applicable
- Your environment (OS, browser, Docker version, etc.)
**Example Bug Report:**
```markdown
**Title:** Book metadata not updating after manual edit
**Description:**
When I manually edit a book's metadata through the UI and click Save,
the changes appear to save but revert after page refresh.
**Steps to Reproduce:**
1. Navigate to any book detail page
2. Click "Edit Metadata"
3. Change the title from "Old Title" to "New Title"
4. Click "Save"
5. Refresh the page
**Expected:** Title should remain "New Title"
**Actual:** Title reverts to "Old Title"
**Environment:**
- Browser: Chrome 120
- OS: macOS 14.2
- Booklore Version: 1.2.0
```
---
### 🔃 Submitting Code Changes
#### Branch Naming Convention
Create descriptive branches that clearly indicate the purpose of your changes:
| Prefix | Use for | Example |
|-------------|--------------------|------------------------------|
| `feat/` | New features | `feat/epub-reader-support` |
| `fix/` | Bug fixes | `fix/book-import-validation` |
| `refactor/` | Code restructuring | `refactor/auth-flow` |
| `docs/` | Documentation | `docs/update-install-guide` |
```bash
# For new features
git checkout -b feat/add-dark-mode-theme
git checkout -b feat/epub-reader-support
# For bug fixes
git checkout -b fix/book-import-validation
git checkout -b fix/memory-leak-in-scanner
# For documentation
git checkout -b docs/update-installation-guide
# For refactoring
git checkout -b refactor/improve-authentication-flow
git checkout develop
git checkout -b feat/your-feature-name
```
#### Development Workflow
### Commit Messages
1. **Create a branch** from `develop` (not `main`)
2. **Make your changes** in small, logical commits
3. **Test thoroughly** - run both frontend and backend tests
4. **Update documentation** if your changes affect usage
5. **Run the linter** and fix any issues
6. **Commit with clear messages** following Conventional Commits
7. **Push to your fork**
8. **Open a pull request** targeting the `develop` branch
#### Pull Request Checklist
Before submitting, ensure:
- [ ] Code follows project conventions
- [ ] All tests pass (`./gradlew test` for backend)
- [ ] IntelliJ linter shows no errors
- [ ] Changes are documented (README, inline comments)
- [ ] PR description clearly explains what and why
- [ ] PR is linked to a related issue (if applicable)
- [ ] Branch is up-to-date with `develop`
- [ ] **For big features:** Create a documentation PR at [booklore-docs](https://github.com/booklore-app/booklore-docs) with styling similar to other documentation pages
---
## 🧼 Code Style & Conventions
- **Angular**: Follow the [official style guide](https://angular.io/guide/styleguide)
- **Java**: Use modern features (Java 21), clean structure
- **Linter**: Use IntelliJ IDEA's built-in linter for code formatting and style checks
- **UI**: Use SCSS and PrimeNG components consistently
---
## 📝 Commit Message Format
We follow [Conventional Commits](https://www.conventionalcommits.org/) for clear, standardized commit messages.
### Format
We follow [Conventional Commits](https://www.conventionalcommits.org/):
```
<type>(<scope>): <subject>
[optional body]
[optional footer]
```
### Types
**Types:** `feat`, `fix`, `docs`, `style`, `refactor`, `test`, `chore`, `perf`
- `feat`: New feature
- `fix`: Bug fix
- `docs`: Documentation changes
- `style`: Code style changes (formatting, no logic change)
- `refactor`: Code refactoring
- `test`: Adding or updating tests
- `chore`: Maintenance tasks
- `perf`: Performance improvements
Examples:
### Examples
```bash
# Feature addition
```
feat(reader): add keyboard navigation for page turning
# Bug fix
fix(api): resolve memory leak in book scanning service
# Documentation
docs(readme): add troubleshooting section for Docker setup
# Multiple scopes
feat(api,ui): implement book collection management
# Breaking change
feat(auth)!: migrate to OAuth 2.1
BREAKING CHANGE: OAuth 2.0 is no longer supported
```
### Workflow
1. Create a branch from `develop`
2. Make your changes in small, logical commits
3. Run both frontend and backend tests
4. Update documentation if your changes affect usage
5. Run the linter and fix any issues
6. Push to your fork and open a PR targeting `develop`
---
## 🙏 Code of Conduct
## Submitting a Pull Request
Before opening your PR:
- [ ] PR is linked to an **approved** issue (PRs without a linked issue will be closed)
- [ ] All tests pass (`./gradlew test` and `ng test`)
- [ ] Actual test output is pasted in the PR description
- [ ] Code follows project conventions (see [Code Style](#code-style))
- [ ] IntelliJ linter shows no errors
- [ ] Branch is up-to-date with `develop`
- [ ] You ran the full stack locally and manually verified the change works
- [ ] PR description includes a screen recording or screenshots proving it works
- [ ] PR description explains *what* changed and *why*
- [ ] PR contains a single logical change (one bug fix OR one feature)
- [ ] No unrelated refactors, style changes, or "improvements" are bundled in
- [ ] **PR is reasonably sized.** PRs with 1000+ changed lines will be closed without review. Break large changes into small, focused PRs.
- [ ] **For user-facing features:** submit a companion docs PR at [booklore-docs](https://github.com/booklore-app/booklore-docs)
### AI-Assisted Contributions
Contributions using AI tools (Copilot, Claude, ChatGPT, etc.) are welcome, but the quality bar is the same as human-written code. **If you ship it, you own it.**
We've seen a sharp increase in AI-generated PRs where the contributor clearly never ran the code, didn't test it, and can't explain what it does. These waste maintainer time and will be closed on sight.
**If you use AI to help write code, you must still:**
- **Run the code yourself.** Build the project, start the full stack, and manually verify the change works. Trusting the AI's output without running it is not acceptable.
- **Review every line.** You must be able to explain any part of your change during review. If asked "why did you do X?" and your answer is "the AI suggested it," the PR will be closed.
- **Keep PRs focused.** One feature, one fix, or one refactor per PR. Do not submit a dump of everything the AI suggested.
- **Scrutinize AI-generated tests.** They often pass trivially without asserting anything meaningful. Tests that don't validate real behavior will be rejected.
- **Clean up.** Remove dead code, placeholder comments, empty catch blocks, and unnecessary boilerplate.
- **Stay in scope.** Do not submit refactors, style changes, or "improvements" the AI suggested that are outside the scope of the linked issue.
---
## Code Style
| Area | Convention |
|------------|--------------------------------------------------------------------|
| Angular | Follow the [official style guide](https://angular.dev/style-guide) |
| Java | Modern Java 21 features, clean structure |
| Formatting | Use IntelliJ IDEA's built-in linter |
| UI | SCSS with PrimeNG components |
---
## Reporting Bugs
1. **Search [existing issues](https://github.com/booklore-app/booklore/issues)** to avoid duplicates.
2. **Open a new issue** with the `bug` label including:
- Clear, descriptive title (e.g., "Book import fails with PDF files over 100MB")
- Steps to reproduce
- Expected vs. actual behavior
- Screenshots or error logs (if applicable)
- Environment details (OS, browser, Booklore version)
**Example:**
```
Title: Book metadata not updating after manual edit
Steps to Reproduce:
1. Navigate to any book detail page
2. Click "Edit Metadata"
3. Change the title and click "Save"
4. Refresh the page
Expected: Title should persist after refresh
Actual: Title reverts to original value
Environment: Chrome 120, macOS 14.2, Booklore 1.2.0
```
---
## Community & Support
- **Discord:** [Join the server](https://discord.gg/Ee5hd458Uz) for questions and discussion
- **GitHub Issues:** [Report bugs or request features](https://github.com/booklore-app/booklore/issues)
---
## Code of Conduct
We're committed to providing a welcoming and inclusive environment for everyone.
**Our Standards:**
- ✅ Be respectful and considerate
- ✅ Welcome newcomers and help them learn
- ✅ Accept constructive criticism gracefully
- ✅ Focus on what's best for the community
**Do:**
- Be respectful and considerate
- Welcome newcomers and help them learn
- Accept constructive criticism gracefully
- Focus on what's best for the community
**Unacceptable Behavior:**
- ❌ Harassment, trolling, or discrimination
- ❌ Personal attacks or insults
- ❌ Publishing others' private information
- ❌ Any conduct that would be inappropriate in a professional setting
**Don't:**
- Harass, troll, or discriminate
- Make personal attacks or insults
- Publish others' private information
**Enforcement:**
Instances of unacceptable behavior may result in temporary or permanent ban from the project.
---
## 💬 Community & Support
## License
**Need help or want to discuss ideas?**
- 💬 **Discord**: [Join our server](https://discord.gg/Ee5hd458Uz)
- 🐛 **Issues**: [GitHub Issues](https://github.com/booklore-app/booklore/issues)
Booklore is licensed under the [AGPL-3.0 License](./LICENSE). By contributing, you agree that your contributions will be licensed under the same terms.
---
## 📄 License
Booklore is open-source software licensed under the **GPL-3.0 License**.
By contributing, you agree that your contributions will be licensed under the same license. See the [`LICENSE`](./LICENSE) file for full details.
---
## 🎯 What to Work On?
Not sure where to start? Check out:
- Issues labeled [`good first issue`](https://github.com/booklore-app/booklore/labels/good%20first%20issue)
- Issues labeled [`help wanted`](https://github.com/booklore-app/booklore/labels/help%20wanted)
- Our [project roadmap](https://github.com/booklore-app/booklore/projects)
---
## 🎉 Thank You!
Every contribution, no matter how small, makes Booklore better. Thank you for being part of our community!
**Happy Contributing! 📚✨**
Thank you for being part of the Booklore community!
+15 -10
View File
@@ -13,7 +13,7 @@ COPY ./booklore-ui /angular-app/
RUN npm run build --configuration=production
# Stage 2: Build the Spring Boot app with Gradle
FROM gradle:8.14.3-jdk21-alpine AS springboot-build
FROM gradle:9.3.1-jdk25-alpine AS springboot-build
WORKDIR /springboot-app
@@ -26,6 +26,9 @@ RUN --mount=type=cache,target=/home/gradle/.gradle \
COPY ./booklore-api/src /springboot-app/src
# Copy Angular dist into Spring Boot static resources so it's embedded in the JAR
COPY --from=angular-build /angular-app/dist/booklore/browser /springboot-app/src/main/resources/static
# Inject version into application.yaml using yq
ARG APP_VERSION
RUN apk add --no-cache yq && \
@@ -35,7 +38,7 @@ RUN --mount=type=cache,target=/home/gradle/.gradle \
gradle clean build -x test --no-daemon --parallel
# Stage 3: Final image
FROM eclipse-temurin:21.0.9_10-jre-alpine
FROM eclipse-temurin:25-jre-alpine
ARG APP_VERSION
ARG APP_REVISION
@@ -49,16 +52,18 @@ LABEL org.opencontainers.image.title="BookLore" \
org.opencontainers.image.version=$APP_VERSION \
org.opencontainers.image.revision=$APP_REVISION \
org.opencontainers.image.licenses="GPL-3.0" \
org.opencontainers.image.base.name="docker.io/library/eclipse-temurin:21.0.9_10-jre-alpine"
org.opencontainers.image.base.name="docker.io/library/eclipse-temurin:25-jre-alpine"
RUN apk update && apk add nginx gettext su-exec
ENV JAVA_TOOL_OPTIONS="-XX:+UseG1GC -XX:MaxGCPauseMillis=200 -XX:+UseStringDeduplication -XX:+UseContainerSupport -XX:+UseCompactObjectHeaders -XX:MaxRAMPercentage=75.0"
COPY ./nginx.conf /etc/nginx/nginx.conf
COPY --from=angular-build /angular-app/dist/booklore/browser /usr/share/nginx/html
RUN apk update && apk add --no-cache su-exec
COPY entrypoint.sh /usr/local/bin/entrypoint.sh
RUN chmod +x /usr/local/bin/entrypoint.sh
COPY --from=springboot-build /springboot-app/build/libs/booklore-api-0.0.1-SNAPSHOT.jar /app/app.jar
COPY start.sh /start.sh
RUN chmod +x /start.sh
EXPOSE 8080 80
ARG BOOKLORE_PORT=6060
EXPOSE ${BOOKLORE_PORT}
CMD ["/start.sh"]
ENTRYPOINT ["entrypoint.sh"]
CMD ["java", "-jar", "/app/app.jar"]
+31
View File
@@ -0,0 +1,31 @@
# Runtime-only Dockerfile for CI builds.
# Expects the pre-built JAR at booklore-api/build/libs/booklore-api-0.0.1-SNAPSHOT.jar
# and entrypoint.sh in the build context.
FROM eclipse-temurin:25-jre-alpine
ARG APP_VERSION
ARG APP_REVISION
LABEL org.opencontainers.image.title="BookLore" \
org.opencontainers.image.description="BookLore: A self-hosted, multi-user digital library with smart shelves, auto metadata, Kobo & KOReader sync, BookDrop imports, OPDS support, and a built-in reader for EPUB, PDF, and comics." \
org.opencontainers.image.source="https://github.com/booklore-app/booklore" \
org.opencontainers.image.url="https://github.com/booklore-app/booklore" \
org.opencontainers.image.documentation="https://booklore.org/docs/getting-started" \
org.opencontainers.image.version=$APP_VERSION \
org.opencontainers.image.revision=$APP_REVISION \
org.opencontainers.image.licenses="GPL-3.0" \
org.opencontainers.image.base.name="docker.io/library/eclipse-temurin:25-jre-alpine"
ENV JAVA_TOOL_OPTIONS="-XX:+UseG1GC -XX:MaxGCPauseMillis=200 -XX:+UseStringDeduplication -XX:+UseContainerSupport -XX:+UseCompactObjectHeaders -XX:MaxRAMPercentage=75.0"
RUN apk update && apk add --no-cache su-exec
COPY entrypoint.sh /usr/local/bin/entrypoint.sh
RUN chmod +x /usr/local/bin/entrypoint.sh
COPY booklore-api/build/libs/booklore-api-0.0.1-SNAPSHOT.jar /app/app.jar
ARG BOOKLORE_PORT=6060
EXPOSE ${BOOKLORE_PORT}
ENTRYPOINT ["entrypoint.sh"]
CMD ["java", "-jar", "/app/app.jar"]
+161 -306
View File
@@ -1,246 +1,109 @@
<div align="center">
# 📚 BookLore
### *Your Personal Library, Beautifully Organized*
**🌐 Official Website: [https://booklore.org](https://booklore.org/)**
<p align="center">
<img src="assets/demo.gif" alt="BookLore Demo" width="800px" style="border-radius: 10px; box-shadow: 0 4px 6px rgba(0,0,0,0.1);" />
<picture>
<source media="(prefers-color-scheme: dark)" srcset="assets/logo-with-text-dark.svg">
<source media="(prefers-color-scheme: light)" srcset="assets/logo-with-text-light.svg">
<img src="assets/logo-with-text-light.svg" alt="BookLore" height="80" />
</picture>
</p>
[![Release](https://img.shields.io/github/v/release/adityachandelgit/BookLore?color=4c6ef5&style=for-the-badge&logo=github)](https://github.com/booklore-app/booklore/releases)
[![License](https://img.shields.io/github/license/adityachandelgit/BookLore?color=fab005&style=for-the-badge)](LICENSE)
[![Stars](https://img.shields.io/github/stars/adityachandelgit/BookLore?style=for-the-badge&color=ffd43b)](https://github.com/booklore-app/booklore/stargazers)
[![Docker Pulls](https://img.shields.io/docker/pulls/booklore/booklore?color=2496ED&style=for-the-badge&logo=docker&logoColor=white)](https://hub.docker.com/r/booklore/booklore)
<p align="center"><strong>Your books deserve a home. This is it.</strong></p>
[![Discord](https://img.shields.io/badge/Join_Discord-5865F2?style=for-the-badge&logo=discord&logoColor=white)](https://discord.gg/Ee5hd458Uz)
[![Open Collective](https://img.shields.io/opencollective/all/booklore?style=for-the-badge&color=7FADF2&logo=opencollective)](https://opencollective.com/booklore)
<p align="center">
BookLore is a self-hosted app that brings your entire book collection under one roof.<br/>
Organize, read, annotate, sync across devices, and share, all without relying on third-party services.
</p>
<p align="center">
<a href="https://github.com/booklore-app/booklore/releases"><img src="https://img.shields.io/github/v/release/adityachandelgit/BookLore?color=818CF8&style=flat-square&logo=github" alt="Release" /></a>
<a href="LICENSE"><img src="https://img.shields.io/github/license/adityachandelgit/BookLore?color=fab005&style=flat-square" alt="License" /></a>
<a href="https://hub.docker.com/r/booklore/booklore"><img src="https://img.shields.io/docker/pulls/booklore/booklore?color=2496ED&style=flat-square&logo=docker&logoColor=white" alt="Docker Pulls" /></a>
<a href="https://github.com/booklore-app/booklore/stargazers"><img src="https://img.shields.io/github/stars/adityachandelgit/BookLore?style=flat-square&color=ffd43b" alt="Stars" /></a>
<a href="https://discord.gg/Ee5hd458Uz"><img src="https://img.shields.io/badge/Discord-5865F2?style=flat-square&logo=discord&logoColor=white" alt="Discord" /></a>
<a href="https://opencollective.com/booklore"><img src="https://img.shields.io/opencollective/all/booklore?style=flat-square&color=7FADF2&logo=opencollective" alt="Open Collective" /></a>
<a href="https://hosted.weblate.org/engage/booklore/"><img src="https://img.shields.io/weblate/progress/booklore?style=flat-square&logo=weblate&logoColor=white&color=2ECCAA" alt="Translate" /></a>
</p>
<p align="center">
<a href="https://booklore.org/">🌐 Website</a> ·
<a href="https://booklore.org/docs/getting-started">📖 Docs</a> ·
<a href="#🎮-live-demo">🎮 Demo</a> ·
<a href="#🚀-quick-start">🚀 Quick Start</a> ·
<a href="https://discord.gg/Ee5hd458Uz">💬 Discord</a>
</p>
<p align="center">
<img src="assets/demo.gif" alt="BookLore Demo" width="800" />
</p>
---
**BookLore** is a powerful, self-hosted web application designed to organize and manage your personal book collection with elegance and ease. Build your dream library with an intuitive interface, robust metadata management, and seamless multi-user support.
## ✨ Features
[🚀 Get Started](#-getting-started-with-booklore) • [📖 Documentation](https://booklore.org/docs/getting-started) • [🎮 Try Demo](#-live-demo-explore-booklore-in-action) • [💬 Community](https://discord.gg/Ee5hd458Uz)
</div>
| | Feature | Description |
|:---:|:---|:---|
| 📚 | **Smart Shelves** | Custom and dynamic shelves that organize themselves with rule-based Magic Shelves, filters, and full-text search |
| 🔍 | **Automatic Metadata** | Covers, descriptions, reviews, and ratings pulled from Google Books, Open Library, and Amazon, all editable |
| 📖 | **Built-in Reader** | Open PDFs, EPUBs, and comics right in the browser with annotations, highlights, and reading progress |
| 🔄 | **Device Sync** | Connect your Kobo, use any OPDS-compatible app, or sync progress with KOReader. Your library follows you everywhere |
| 👥 | **Multi-User Ready** | Individual shelves, progress, and preferences per user with local or OIDC authentication |
| 📥 | **BookDrop** | Drop files into a watched folder and BookLore detects, enriches, and queues them for import automatically |
| 📧 | **One-Click Sharing** | Send any book to a Kindle, an email address, or a friend instantly |
---
<div align="center">
## 🚀 Quick Start
## ✨ **Features That Make BookLore Shine**
> [!TIP]
> Looking for OIDC setup, advanced config, or upgrade guides? See the [full documentation](https://booklore.org/docs/getting-started).
</div>
<table>
<tr>
<td width="50%">
### 📖 **Library Management**
- **Smart Organization**: Custom shelves with powerful filters
- **Magic Shelves**: Dynamic, auto-updating collections
- **Auto Metadata**: Rich details from multiple sources
- **Advanced Search**: Find any book instantly
</td>
<td width="50%">
### 🌐 **Connectivity**
- **Kobo Integration**: Seamless device sync
- **OPDS Support**: Connect any reading app
- **KOReader Sync**: Cross-platform progress tracking
- **Email Sharing**: One-click book sending
</td>
</tr>
<tr>
<td width="50%">
### 👥 **User Experience**
- **Multi-User Support**: Granular permissions
- **Flexible Auth**: Local or OIDC providers
- **Mobile Ready**: Responsive on all devices
- **Built-in Reader**: PDFs, EPUBs, comics
</td>
<td width="50%">
### 🚀 **Smart Features**
- **BookDrop Import**: Auto-detect bulk files
- **Private Notes**: Personal reading annotations
- **Community Reviews**: Enriched book data
- **Progress Tracking**: Reading statistics
</td>
</tr>
</table>
---
<div align="center">
## 💖 **Support the Project**
</div>
<div align="center">
Your support helps BookLore grow and improve! 🌱
<table>
<tr>
<td align="center" width="33%">
### ⭐ **Star Us**
Give us a star to show your support and help others discover BookLore!
[![Star this repo](https://img.shields.io/github/stars/adityachandelgit/BookLore?style=social)](https://github.com/booklore-app/booklore)
</td>
<td align="center" width="33%">
### 💰 **Sponsor**
Support development, hosting, and testing costs
[![Open Collective](https://img.shields.io/badge/Open_Collective-7FADF2?style=for-the-badge&logo=opencollective&logoColor=white)](https://opencollective.com/booklore)
</td>
<td align="center" width="34%">
### 📢 **Spread the Word**
Share BookLore with fellow book lovers and developers!
</td>
</tr>
</table>
> 🎯 **Current Goal:** Raising funds for a **Kobo device** to implement native Kobo sync support
> [💡 Support the Kobo Sync Bounty →](https://opencollective.com/booklore/projects/kobo-device-for-testing)
</div>
---
<div align="center">
## 🎮 **Live Demo: Explore BookLore in Action**
</div>
<div align="center">
Experience BookLore's features in a live environment before deploying your own instance!
| 🌐 Demo URL | 👤 Username | 🔑 Password |
|----------------------------------------------------|-------------|--------------------|
| **[demo.booklore.org](https://demo.booklore.org)** | `booklore` | `9HC20PGGfitvWaZ1` |
> ⚠️ **Note:** Demo account has standard user permissions only.
> Admin features (user management, library setup) require a self-hosted instance.
</div>
---
<div align="center">
## 🚀 **Getting Started with BookLore**
### Choose Your Path
<table>
<tr>
<td align="center" width="50%">
### 📘 **Documentation**
Guides for installation, setup, features, and more
[![Read the Docs](https://img.shields.io/badge/📖_Read_the_Docs-4c6ef5?style=for-the-badge)](https://booklore.org/docs/getting-started)
*Contribute to the docs at: [booklore-docs](https://github.com/booklore-app/booklore-docs)*
</td>
<td align="center" width="50%">
### 🐳 **Quick Deploy**
Get up and running in minutes with Docker
[![Deploy with Docker](https://img.shields.io/badge/🐳_Deploy_Now-2496ED?style=for-the-badge)](#-deploy-with-docker)
*Easiest way to self-host BookLore*
</td>
</tr>
</table>
</div>
---
<div align="center">
## 🐳 **Deploy with Docker**
</div>
### **Prerequisites**
Ensure you have [Docker](https://docs.docker.com/get-docker/) and [Docker Compose](https://docs.docker.com/compose/install/) installed.
All you need is [Docker](https://docs.docker.com/get-docker/) and [Docker Compose](https://docs.docker.com/compose/install/).
<details>
<summary><b>📦 Image Repositories</b></summary>
<summary><strong>📦 Image Repositories</strong></summary>
- 🐳 **Docker Hub:** `booklore/booklore`
- 📦 **GitHub Container Registry:** `ghcr.io/booklore-app/booklore`
| Registry | Image |
|----------|-------|
| Docker Hub | `booklore/booklore` |
| GitHub Container Registry | `ghcr.io/booklore-app/booklore` |
> 💡 Legacy images at `ghcr.io/adityachandelgit/booklore-app` remain available but won't receive updates.
> Legacy images at `ghcr.io/adityachandelgit/booklore-app` remain available but won't receive updates.
</details>
### **Step 1️⃣: Create Environment Configuration**
### Step 1: Environment Configuration
Create a `.env` file in your project directory:
Create a `.env` file:
```ini
# 🎯 BookLore Application Settings
APP_USER_ID=0
APP_GROUP_ID=0
# Application
APP_USER_ID=1000
APP_GROUP_ID=1000
TZ=Etc/UTC
BOOKLORE_PORT=6060
# 🗄️ Database Connection (BookLore)
# Database
DATABASE_URL=jdbc:mariadb://mariadb:3306/booklore
DB_USER=booklore
DB_PASSWORD=ChangeMe_BookLoreApp_2025!
# 🔧 MariaDB Container Settings
# Storage: LOCAL (default) or NETWORK (for NFS/SMB, disables file reorganization)
DISK_TYPE=LOCAL
# MariaDB
DB_USER_ID=1000
DB_GROUP_ID=1000
MYSQL_ROOT_PASSWORD=ChangeMe_MariaDBRoot_2025!
MYSQL_DATABASE=booklore
```
### **Step 2️⃣: Create Docker Compose File**
### Step 2: Docker Compose
Create a `docker-compose.yml` file:
Create a `docker-compose.yml`:
```yaml
services:
booklore:
image: booklore/booklore:latest
# Alternative: Use GitHub Container Registry
# image: ghcr.io/booklore-app/booklore:latest
# Alternative: ghcr.io/booklore-app/booklore:latest
container_name: booklore
environment:
- USER_ID=${APP_USER_ID}
@@ -249,18 +112,17 @@ services:
- DATABASE_URL=${DATABASE_URL}
- DATABASE_USERNAME=${DB_USER}
- DATABASE_PASSWORD=${DB_PASSWORD}
- BOOKLORE_PORT=${BOOKLORE_PORT}
depends_on:
mariadb:
condition: service_healthy
ports:
- "${BOOKLORE_PORT}:${BOOKLORE_PORT}"
- "6060:6060"
volumes:
- ./data:/app/data
- ./books:/books
- ./bookdrop:/bookdrop
healthcheck:
test: wget -q -O - http://localhost:${BOOKLORE_PORT}/api/v1/healthcheck
test: wget -q -O - http://localhost:6060/api/v1/healthcheck
interval: 60s
retries: 5
start_period: 60s
@@ -288,33 +150,34 @@ services:
retries: 10
```
### **Step 3️⃣: Launch BookLore**
### Step 3: Launch
```bash
docker compose up -d
```
### **Step 4️⃣: Access Your Library**
Open your browser and navigate to:
**🌐 http://localhost:6060**
🎉 **Welcome to your personal library!**
Open **http://localhost:6060**, create your admin account, and start building your library.
---
<div align="center">
## 🎮 Live Demo
## 📥 **BookDrop: Automatic Import**
See BookLore in action before deploying your own instance.
### *Drop Files, Import Automatically*
| | |
|:---|:---|
| 🌐 **URL** | **[demo.booklore.org](https://demo.booklore.org)** |
| 👤 **Username** | `booklore` |
| 🔑 **Password** | `9HC20PGGfitvWaZ1` |
</div>
> [!NOTE]
> This is a standard user account. Admin features like library creation, user management, and system settings are only available on your own instance.
BookLore's **BookDrop** feature automatically detects and processes book files dropped into a designated folder.
---
### **How It Works**
## 📥 BookDrop: Zero-Effort Import
Drop book files into a folder. BookLore picks them up, pulls metadata, and queues everything for your review.
```mermaid
graph LR
@@ -323,80 +186,63 @@ graph LR
C --> D[✅ Review & Import]
```
1. **File Watcher**: Monitors the BookDrop folder continuously
2. **Auto-Detection**: Processes new files and extracts metadata
3. **Metadata Enrichment**: Fetches details from Google Books, Open Library
4. **Review & Finalize**: Review, edit, and import to your library
| Step | What Happens |
|:---|:---|
| 1. **Watch** | BookLore monitors the BookDrop folder around the clock |
| 2. **Detect** | New files are picked up and parsed automatically |
| 3. **Enrich** | Metadata is fetched from Google Books and Open Library |
| 4. **Import** | You review, tweak if needed, and add to your library |
### **Docker Configuration**
Add the BookDrop volume to your `docker-compose.yml`:
Mount the volume in `docker-compose.yml`:
```yaml
services:
booklore:
volumes:
- ./data:/app/data
- ./books:/books
- ./bookdrop:/bookdrop # 👈 BookDrop magic happens here
volumes:
- ./bookdrop:/bookdrop
```
---
<div align="center">
## 🤝 Community & Support
## 🤝 **Community & Support**
<table>
<tr>
<td align="center">
### 🐞 **Bug Reports**
Found an issue?
[![Open Issue](https://img.shields.io/badge/Report-ff6b6b?style=for-the-badge)](https://github.com/booklore-app/booklore/issues/new?template=bug_report.yml)
</td>
<td align="center">
### 💡 **Feature Req**
Have an idea?
[![Request Feature](https://img.shields.io/badge/Suggest-4ecdc4?style=for-the-badge)](https://github.com/booklore-app/booklore/issues/new?template=feature_request.yml)
</td>
<td align="center">
### 🤝 **Contribute**
Join development!
[![Contributing](https://img.shields.io/badge/Contribute-95e1d3?style=for-the-badge)](CONTRIBUTING.md)
</td>
<td align="center">
### 💬 **Chat**
Join community!
[![Discord](https://img.shields.io/badge/Discord-5865F2?style=for-the-badge&logo=discord&logoColor=white)](https://discord.gg/Ee5hd458Uz)
</td>
</tr>
</table>
</div>
| | |
|:---|:---|
| 🐞 **Something not working?** | [Report a Bug](https://github.com/booklore-app/booklore/issues/new?template=bug_report.yml) |
| 💡 **Got an idea?** | [Request a Feature](https://github.com/booklore-app/booklore/issues/new?template=feature_request.yml) |
| 🛠️ **Want to help build?** | [Contributing Guide](CONTRIBUTING.md) |
| 💬 **Come hang out** | [Discord Server](https://discord.gg/Ee5hd458Uz) |
> [!WARNING]
> **Before opening a PR:** Open an issue first and get maintainer approval. PRs without a linked issue, without screenshots/video proof, or without pasted test output will be closed. AI-assisted contributions are welcome, but you must run, test, and understand every line you submit. See the [Contributing Guide](CONTRIBUTING.md) for full details.
---
<div align="center">
## 💜 Support BookLore
## 📊 **Project Analytics**
BookLore is free, open source, and built with care. Here's how you can give back:
### Repository Activity
| Action | How |
|:---|:---|
| ⭐ **Star this repo** | It's the simplest way to help others find BookLore |
| 💰 **Sponsor development** | [Open Collective](https://opencollective.com/booklore) funds hosting, testing, and new features |
| 📢 **Tell someone** | Share BookLore with a friend, a subreddit, or your local book club |
> [!IMPORTANT]
> We're raising funds for a Kobo device to build and test native Kobo sync support.
> [Contribute to the Kobo Bounty →](https://opencollective.com/booklore/projects/kobo-device-for-testing)
---
## 🌍 Translations
BookLore is used by readers around the world. Help make it accessible in your language on [Weblate](https://hosted.weblate.org/engage/booklore/).
<a href="https://hosted.weblate.org/engage/booklore/">
<img src="https://hosted.weblate.org/widget/booklore/multi-auto.svg?v=1" alt="Translation status" />
</a>
---
## 📊 Project Analytics
![Repository Activity](https://repobeats.axiom.co/api/embed/44a04220bfc5136e7064181feb07d5bf0e59e27e.svg)
@@ -410,39 +256,53 @@ Join community!
</picture>
</a>
</div>
---
<div align="center">
## 👨‍💻 **Contributors**
### Thanks to all our amazing contributors! 🙏
## 👥 Contributors
[![Contributors](https://contrib.rocks/image?repo=adityachandelgit/BookLore)](https://github.com/booklore-app/booklore/graphs/contributors)
**Want to see your face here?** [Start contributing today!](CONTRIBUTING.md)
</div>
Every contribution matters. [See how you can help →](CONTRIBUTING.md)
---
<div align="center">
## 🌟 **Sponsors**
## 🌟 Sponsors & Partners
### Thank you to our amazing sponsors!
<table>
<tr>
<td align="center" width="33%">
<a href="https://www.pikapods.com/pods?run=booklore">
<img src="https://www.pikapods.com/static/run-button.svg" alt="Run on PikaPods" height="40">
</a>
&nbsp;&nbsp;&nbsp;&nbsp;
<a href="https://docs.elfhosted.com/app/booklore">
<img src="https://docs.elfhosted.com/images/logo.svg" alt="ElfHosted" height="40">
<img src="https://www.pikapods.com/static/run-button.svg" alt="Run on PikaPods" height="40" />
</a>
*Become a sponsor and get your logo here! [Support us on Open Collective](https://opencollective.com/booklore)*
**PikaPods**
</td>
<td align="center" width="33%">
<a href="https://docs.elfhosted.com/app/booklore">
<img src="https://docs.elfhosted.com/images/logo.svg" alt="ElfHosted" height="40" />
</a>
**ElfHosted**
</td>
<td align="center" width="34%">
<a href="https://jb.gg/OpenSource">
<img src="https://resources.jetbrains.com/storage/products/company/brand/logos/jetbrains.svg" alt="JetBrains" height="40" />
</a>
**JetBrains**
</td>
</tr>
</table>
*Want your logo here? [Become a sponsor →](https://opencollective.com/booklore)*
</div>
@@ -450,17 +310,12 @@ Join community!
<div align="center">
## ⚖️ **License**
## ⚖️ License
**GNU Affero General Public License v3.0 (AGPL-3.0)**
**GNU Affero General Public License v3.0**
Copyright © 2024-2026 BookLore
Copyright 2024–2026 BookLore
[![License: AGPL v3](https://img.shields.io/badge/License-AGPLv3-blue.svg?style=for-the-badge)](https://www.gnu.org/licenses/agpl-3.0.html)
---
<sub>Made with ❤️ by the BookLore community</sub>
**[⬆ Back to Top](#-booklore)**
[![License: AGPL v3](https://img.shields.io/badge/License-AGPL_v3-blue.svg?style=for-the-badge)](https://www.gnu.org/licenses/agpl-3.0.html)
</div>

Before

Width:  |  Height:  |  Size: 6.3 KiB

After

Width:  |  Height:  |  Size: 6.3 KiB

+6
View File
@@ -0,0 +1,6 @@
<svg width="500" height="126" viewBox="0 0 500 126" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M189.08 83.28C191.107 83.6 192.947 84.4267 194.6 85.76C196.307 87.0933 197.64 88.7467 198.6 90.72C199.613 92.6933 200.12 94.8 200.12 97.04C200.12 99.8667 199.4 102.427 197.96 104.72C196.52 106.96 194.413 108.747 191.64 110.08C188.92 111.36 185.693 112 181.96 112H161.16V56.24H181.16C184.947 56.24 188.173 56.88 190.84 58.16C193.507 59.3867 195.507 61.0667 196.84 63.2C198.173 65.3333 198.84 67.7333 198.84 70.4C198.84 73.7067 197.933 76.4533 196.12 78.64C194.36 80.7733 192.013 82.32 189.08 83.28ZM168.44 80.32H180.68C184.093 80.32 186.733 79.52 188.6 77.92C190.467 76.32 191.4 74.1067 191.4 71.28C191.4 68.4533 190.467 66.24 188.6 64.64C186.733 63.04 184.04 62.24 180.52 62.24H168.44V80.32ZM181.32 106C184.947 106 187.773 105.147 189.8 103.44C191.827 101.733 192.84 99.36 192.84 96.32C192.84 93.2267 191.773 90.8 189.64 89.04C187.507 87.2267 184.653 86.32 181.08 86.32H168.44V106H181.32ZM229.343 112.72C225.236 112.72 221.503 111.787 218.143 109.92C214.836 108.053 212.223 105.413 210.303 102C208.436 98.5333 207.503 94.5333 207.503 90C207.503 85.52 208.463 81.5733 210.383 78.16C212.356 74.6933 215.023 72.0533 218.383 70.24C221.743 68.3733 225.503 67.44 229.663 67.44C233.823 67.44 237.583 68.3733 240.943 70.24C244.303 72.0533 246.943 74.6667 248.863 78.08C250.836 81.4933 251.823 85.4667 251.823 90C251.823 94.5333 250.809 98.5333 248.783 102C246.809 105.413 244.116 108.053 240.703 109.92C237.289 111.787 233.503 112.72 229.343 112.72ZM229.343 106.32C231.956 106.32 234.409 105.707 236.703 104.48C238.996 103.253 240.836 101.413 242.223 98.96C243.663 96.5067 244.383 93.52 244.383 90C244.383 86.48 243.689 83.4933 242.303 81.04C240.916 78.5867 239.103 76.7733 236.863 75.6C234.623 74.3733 232.196 73.76 229.583 73.76C226.916 73.76 224.463 74.3733 222.223 75.6C220.036 76.7733 218.276 78.5867 216.943 81.04C215.609 83.4933 214.943 86.48 214.943 90C214.943 93.5733 215.583 96.5867 216.863 99.04C218.196 101.493 219.956 103.333 222.143 104.56C224.329 105.733 226.729 106.32 229.343 106.32ZM280.514 112.72C276.408 112.72 272.674 111.787 269.314 109.92C266.008 108.053 263.394 105.413 261.474 102C259.608 98.5333 258.674 94.5333 258.674 90C258.674 85.52 259.634 81.5733 261.554 78.16C263.528 74.6933 266.194 72.0533 269.554 70.24C272.914 68.3733 276.674 67.44 280.834 67.44C284.994 67.44 288.754 68.3733 292.114 70.24C295.474 72.0533 298.114 74.6667 300.034 78.08C302.008 81.4933 302.994 85.4667 302.994 90C302.994 94.5333 301.981 98.5333 299.954 102C297.981 105.413 295.288 108.053 291.874 109.92C288.461 111.787 284.674 112.72 280.514 112.72ZM280.514 106.32C283.128 106.32 285.581 105.707 287.874 104.48C290.168 103.253 292.008 101.413 293.394 98.96C294.834 96.5067 295.554 93.52 295.554 90C295.554 86.48 294.861 83.4933 293.474 81.04C292.088 78.5867 290.274 76.7733 288.034 75.6C285.794 74.3733 283.368 73.76 280.754 73.76C278.088 73.76 275.634 74.3733 273.394 75.6C271.208 76.7733 269.448 78.5867 268.114 81.04C266.781 83.4933 266.114 86.48 266.114 90C266.114 93.5733 266.754 96.5867 268.034 99.04C269.368 101.493 271.128 103.333 273.314 104.56C275.501 105.733 277.901 106.32 280.514 106.32ZM337.046 112L319.846 92.64V112H312.566V52.8H319.846V87.6L336.726 68.16H346.886L326.246 90L346.966 112H337.046Z" fill="#1e293b"/>
<path d="M361.018 52.8V112H353.738V52.8H361.018ZM392.546 112.72C388.439 112.72 384.706 111.787 381.346 109.92C378.039 108.053 375.426 105.413 373.506 102C371.639 98.5333 370.706 94.5333 370.706 90C370.706 85.52 371.666 81.5733 373.586 78.16C375.559 74.6933 378.226 72.0533 381.586 70.24C384.946 68.3733 388.706 67.44 392.866 67.44C397.026 67.44 400.786 68.3733 404.146 70.24C407.506 72.0533 410.146 74.6667 412.066 78.08C414.039 81.4933 415.026 85.4667 415.026 90C415.026 94.5333 414.012 98.5333 411.986 102C410.012 105.413 407.319 108.053 403.906 109.92C400.492 111.787 396.706 112.72 392.546 112.72ZM392.546 106.32C395.159 106.32 397.612 105.707 399.906 104.48C402.199 103.253 404.039 101.413 405.426 98.96C406.866 96.5067 407.586 93.52 407.586 90C407.586 86.48 406.892 83.4933 405.506 81.04C404.119 78.5867 402.306 76.7733 400.066 75.6C397.826 74.3733 395.399 73.76 392.786 73.76C390.119 73.76 387.666 74.3733 385.426 75.6C383.239 76.7733 381.479 78.5867 380.146 81.04C378.812 83.4933 378.146 86.48 378.146 90C378.146 93.5733 378.786 96.5867 380.066 99.04C381.399 101.493 383.159 103.333 385.346 104.56C387.532 105.733 389.932 106.32 392.546 106.32ZM431.878 75.28C433.158 72.7733 434.971 70.8267 437.318 69.44C439.718 68.0533 442.624 67.36 446.038 67.36V74.88H444.118C435.958 74.88 431.878 79.3067 431.878 88.16V112H424.598V68.16H431.878V75.28ZM494.441 88.4C494.441 89.7867 494.361 91.2533 494.201 92.8H459.161C459.428 97.12 460.895 100.507 463.561 102.96C466.281 105.36 469.561 106.56 473.401 106.56C476.548 106.56 479.161 105.84 481.241 104.4C483.375 102.907 484.868 100.933 485.721 98.48H493.561C492.388 102.693 490.041 106.133 486.521 108.8C483.001 111.413 478.628 112.72 473.401 112.72C469.241 112.72 465.508 111.787 462.201 109.92C458.948 108.053 456.388 105.413 454.521 102C452.655 98.5333 451.721 94.5333 451.721 90C451.721 85.4667 452.628 81.4933 454.441 78.08C456.255 74.6667 458.788 72.0533 462.041 70.24C465.348 68.3733 469.135 67.44 473.401 67.44C477.561 67.44 481.241 68.3467 484.441 70.16C487.641 71.9733 490.095 74.48 491.801 77.68C493.561 80.8267 494.441 84.4 494.441 88.4ZM486.921 86.88C486.921 84.1067 486.308 81.7333 485.081 79.76C483.855 77.7333 482.175 76.2133 480.041 75.2C477.961 74.1333 475.641 73.6 473.081 73.6C469.401 73.6 466.255 74.7733 463.641 77.12C461.081 79.4667 459.615 82.72 459.241 86.88H486.921Z" fill="#818CF8"/>
<path d="M59 4.79297C71.5051 11.5557 80 24.7854 80 40C80 40.5959 79.987 41.1888 79.9609 41.7783C79.8609 44.0406 81.7355 46 84 46C106.091 46 124 63.9086 124 86C124 108.091 106.091 126 84 126H10C4.47715 126 0 121.523 0 116V39.0068L0.0126953 38.9941C0.357624 25.0252 7.86506 12.8347 19 5.95215V63.832C19 64.8345 20.0676 65.4391 20.9121 64.9902L21.0771 64.8867L38.2227 52.3428C38.6819 52.0068 39.3064 52.0068 39.7656 52.3428L56.9229 64.8945L57.0879 64.998C57.9324 65.447 59 64.8423 59 63.8398V4.79297Z" fill="#818CF8"/>
<path d="M40 0C43.8745 0 47.6199 0.552381 51.1631 1.58008V50.9697L44.3926 46.0176L44.0879 45.8037C40.9061 43.6679 36.7098 43.7393 33.5957 46.0176L26.8369 50.9619V2.21875C30.9593 0.782634 35.3881 0 40 0Z" fill="white"/>
</svg>

After

Width:  |  Height:  |  Size: 6.3 KiB

+45 -12
View File
@@ -1,17 +1,18 @@
plugins {
id 'java'
id 'org.springframework.boot' version '3.5.8'
id 'org.springframework.boot' version '4.0.3'
id 'io.spring.dependency-management' version '1.1.7'
id 'org.hibernate.orm' version '6.6.36.Final'
id 'org.hibernate.orm' version '7.2.4.Final'
id 'com.github.ben-manes.versions' version '0.53.0'
id 'jacoco'
}
group = 'com.adityachandel'
group = 'org.booklore'
version = '0.0.1-SNAPSHOT'
java {
toolchain {
languageVersion = JavaLanguageVersion.of(21)
languageVersion = JavaLanguageVersion.of(25)
}
}
@@ -41,8 +42,9 @@ dependencies {
implementation 'io.projectreactor:reactor-core'
// --- Database & Migration ---
implementation 'org.mariadb.jdbc:mariadb-java-client:3.5.6'
implementation 'org.flywaydb:flyway-mysql:11.19.0'
implementation 'org.mariadb.jdbc:mariadb-java-client:3.5.7'
implementation 'org.springframework.boot:spring-boot-starter-flyway'
implementation 'org.flywaydb:flyway-mysql:12.0.1'
// --- Security & Authentication ---
implementation 'io.jsonwebtoken:jjwt-api:0.13.0'
@@ -68,34 +70,52 @@ dependencies {
implementation 'com.twelvemonkeys.imageio:imageio-webp:3.13.0'
implementation 'com.twelvemonkeys.imageio:imageio-bmp:3.13.0'
implementation 'io.documentnode:epub4j-core:4.2.2'
implementation 'io.documentnode:epub4j-core:4.2.3'
// --- Audio Metadata (Audiobook Support) ---
implementation 'net.jthink:jaudiotagger:3.0.1'
// --- UNRAR Support ---
implementation 'com.github.junrar:junrar:7.5.7'
// --- JSON & Web Scraping ---
implementation 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.20.1'
implementation 'org.jsoup:jsoup:1.21.2'
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-ui:2.8.14'
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:3.0.1'
implementation 'org.apache.commons:commons-compress:1.28.0'
implementation 'org.tukaani:xz:1.11' // Required by commons-compress for 7z support
implementation 'org.apache.commons:commons-text:1.15.0'
// --- XML Support (JAXB) ---
implementation 'jakarta.xml.bind:jakarta.xml.bind-api:4.0.5'
runtimeOnly 'org.glassfish.jaxb:jaxb-runtime:4.0.6'
// --- Template Engine ---
implementation 'org.freemarker:freemarker:2.3.34'
// --- Jackson 3 ---
implementation platform('tools.jackson:jackson-bom:3.0.4')
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 'com.github.ben-manes.caffeine:caffeine:3.2.0'
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.assertj:assertj-core:3.27.6'
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'
}
@@ -109,6 +129,15 @@ hibernate {
test {
useJUnitPlatform()
jvmArgs("-XX:+EnableDynamicAgentLoading")
finalizedBy jacocoTestReport
}
jacocoTestReport {
dependsOn test
reports {
xml.required = true
html.required = true
}
}
bootRun {
@@ -116,4 +145,8 @@ bootRun {
if (debug.equals("true")) {
jvmArgs("-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005")
}
}
bootJar {
mainClass = 'org.booklore.BookloreApplication'
}
+1 -1
View File
@@ -1,6 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-9.3.1-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
@@ -1,44 +0,0 @@
package com.adityachandel.booklore.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
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(Jackson2ObjectMapperBuilder builder) {
ObjectMapper mapper = builder.build();
// Register the custom serializer modifier on this dedicated mapper only
mapper.setSerializerFactory(
mapper.getSerializerFactory().withSerializerModifier(new BeanSerializerModifier() {
@Override
public List<BeanPropertyWriter> changeProperties(
com.fasterxml.jackson.databind.SerializationConfig config,
com.fasterxml.jackson.databind.BeanDescription beanDesc,
List<BeanPropertyWriter> beanProperties) {
return beanProperties.stream()
.map(KomgaCleanBeanPropertyWriter::new)
.collect(Collectors.toList());
}
})
);
return mapper;
}
}
@@ -1,22 +0,0 @@
package com.adityachandel.booklore.config;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import jakarta.servlet.MultipartConfigElement;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.unit.DataSize;
@Configuration
public class MultipartConfig {
@Bean
public MultipartConfigElement multipartConfigElement(AppSettingService appSettingService) {
MultipartConfigFactory factory = new MultipartConfigFactory();
long maxSizeMb = appSettingService.getAppSettings().getMaxFileUploadSizeInMb();
factory.setMaxFileSize(DataSize.ofMegabytes(maxSizeMb));
factory.setMaxRequestSize(DataSize.ofMegabytes(maxSizeMb));
return factory.createMultipartConfig();
}
}
@@ -1,42 +0,0 @@
package com.adityachandel.booklore.config;
import io.swagger.v3.oas.models.Components;
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 io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import io.swagger.v3.oas.models.servers.Server;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class OpenApiConfig {
@Bean
public OpenAPI customOpenAPI() {
final String securitySchemeName = "bearerAuth";
return new OpenAPI()
.info(new Info()
.title("Booklore API")
.version("1.0")
.description("Booklore is a personal library management system. This API allows you to manage books, libraries, users, shelves, and more.")
.contact(new Contact()
.name("Booklore")
.url("https://github.com/booklore-app/booklore"))
.license(new License()
.name("GNU General Public License v3.0")
.url("https://www.gnu.org/licenses/gpl-3.0.html"))
)
.addServersItem(new Server().url("/").description("Current server"))
.addSecurityItem(new SecurityRequirement().addList(securitySchemeName))
.components(new Components().addSecuritySchemes(securitySchemeName,
new SecurityScheme()
.name(securitySchemeName)
.type(SecurityScheme.Type.HTTP)
.scheme("bearer")
.bearerFormat("JWT")));
}
}
@@ -1,17 +0,0 @@
package com.adityachandel.booklore.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
@Configuration
public class TaskExecutorConfig {
@Bean(name = "taskExecutor")
public Executor taskExecutor() {
return Executors.newVirtualThreadPerTaskExecutor();
}
}
@@ -1,28 +0,0 @@
package com.adityachandel.booklore.config;
import com.adityachandel.booklore.interceptor.KomgaCleanInterceptor;
import com.adityachandel.booklore.interceptor.KomgaEnabledInterceptor;
import com.adityachandel.booklore.interceptor.OpdsEnabledInterceptor;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@RequiredArgsConstructor
public class WebMvcConfig implements WebMvcConfigurer {
private final OpdsEnabledInterceptor opdsEnabledInterceptor;
private final KomgaEnabledInterceptor komgaEnabledInterceptor;
private final KomgaCleanInterceptor komgaCleanInterceptor;
@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/**");
}
}
@@ -1,29 +0,0 @@
package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.service.AuthorService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Tag(name = "Authors", description = "Endpoints for retrieving authors related to books")
@RequestMapping("/api/v1/authors")
@RestController
@AllArgsConstructor
public class AuthorController {
private final AuthorService authorService;
@Operation(summary = "Get authors by book ID", description = "Retrieve a list of authors for a specific book.")
@ApiResponse(responseCode = "200", description = "Authors returned successfully")
@GetMapping("/book/{bookId}")
public ResponseEntity<List<String>> getAuthorsByBookId(
@Parameter(description = "ID of the book") @PathVariable long bookId) {
return ResponseEntity.ok(authorService.getAuthorsByBookId(bookId));
}
}
@@ -1,162 +0,0 @@
package com.adityachandel.booklore.mapper;
import com.adityachandel.booklore.model.dto.BookFile;
import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.dto.LibraryPath;
import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.model.entity.*;
import org.mapstruct.Context;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Named;
import org.mapstruct.ReportingPolicy;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@Mapper(componentModel = "spring", uses = {BookMetadataMapper.class, ShelfMapper.class, AdditionalFileMapper.class}, unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface BookMapper {
@Mapping(source = "library.id", target = "libraryId")
@Mapping(source = "library.name", target = "libraryName")
@Mapping(source = "libraryPath", target = "libraryPath", qualifiedByName = "mapLibraryPathIdOnly")
@Mapping(source = "metadata", target = "metadata")
@Mapping(source = "shelves", target = "shelves")
@Mapping(source = "bookFiles", target = "bookType", qualifiedByName = "mapPrimaryBookType")
@Mapping(source = "bookFiles", target = "fileName", qualifiedByName = "mapPrimaryFileName")
@Mapping(source = "bookFiles", target = "filePath", qualifiedByName = "mapPrimaryFilePath")
@Mapping(source = "bookFiles", target = "fileSubPath", qualifiedByName = "mapPrimaryFileSubPath")
@Mapping(source = "bookFiles", target = "fileSizeKb", qualifiedByName = "mapPrimaryFileSizeKb")
@Mapping(source = "bookFiles", target = "alternativeFormats", qualifiedByName = "mapAlternativeFormats")
@Mapping(source = "bookFiles", target = "supplementaryFiles", qualifiedByName = "mapSupplementaryFiles")
Book toBook(BookEntity bookEntity);
@Mapping(source = "library.id", target = "libraryId")
@Mapping(source = "library.name", target = "libraryName")
@Mapping(source = "libraryPath", target = "libraryPath", qualifiedByName = "mapLibraryPathIdOnly")
@Mapping(source = "metadata", target = "metadata")
@Mapping(source = "shelves", target = "shelves")
@Mapping(source = "bookFiles", target = "bookType", qualifiedByName = "mapPrimaryBookType")
@Mapping(source = "bookFiles", target = "fileName", qualifiedByName = "mapPrimaryFileName")
@Mapping(source = "bookFiles", target = "filePath", qualifiedByName = "mapPrimaryFilePath")
@Mapping(source = "bookFiles", target = "fileSubPath", qualifiedByName = "mapPrimaryFileSubPath")
@Mapping(source = "bookFiles", target = "fileSizeKb", qualifiedByName = "mapPrimaryFileSizeKb")
@Mapping(source = "bookFiles", target = "alternativeFormats", qualifiedByName = "mapAlternativeFormats")
@Mapping(source = "bookFiles", target = "supplementaryFiles", qualifiedByName = "mapSupplementaryFiles")
Book toBookWithDescription(BookEntity bookEntity, @Context boolean includeDescription);
default Set<String> mapAuthors(Set<AuthorEntity> authors) {
if (authors == null) return null;
return authors.stream()
.map(AuthorEntity::getName)
.collect(Collectors.toSet());
}
default Set<String> mapCategories(Set<CategoryEntity> categories) {
if (categories == null) return null;
return categories.stream()
.map(CategoryEntity::getName)
.collect(Collectors.toSet());
}
default Set<String> mapMoods(Set<MoodEntity> moods) {
if (moods == null) return null;
return moods.stream()
.map(MoodEntity::getName)
.collect(Collectors.toSet());
}
default Set<String> mapTags(Set<TagEntity> tags) {
if (tags == null) return null;
return tags.stream()
.map(TagEntity::getName)
.collect(Collectors.toSet());
}
@Named("mapLibraryPathIdOnly")
default LibraryPath mapLibraryPathIdOnly(LibraryPathEntity entity) {
if (entity == null) return null;
return LibraryPath.builder()
.id(entity.getId())
.build();
}
@Named("mapPrimaryBookType")
default BookFileType mapPrimaryBookType(List<BookFileEntity> bookFiles) {
BookFileEntity primary = getPrimaryBookFile(bookFiles);
return primary == null ? null : primary.getBookType();
}
@Named("mapPrimaryFileName")
default String mapPrimaryFileName(List<BookFileEntity> bookFiles) {
BookFileEntity primary = getPrimaryBookFile(bookFiles);
return primary == null ? null : primary.getFileName();
}
@Named("mapPrimaryFilePath")
default String mapPrimaryFilePath(List<BookFileEntity> bookFiles) {
BookFileEntity primary = getPrimaryBookFile(bookFiles);
return primary == null ? null : primary.getFullFilePath().toString();
}
@Named("mapPrimaryFileSubPath")
default String mapPrimaryFileSubPath(List<BookFileEntity> bookFiles) {
BookFileEntity primary = getPrimaryBookFile(bookFiles);
return primary == null ? null : primary.getFileSubPath();
}
@Named("mapPrimaryFileSizeKb")
default Long mapPrimaryFileSizeKb(List<BookFileEntity> bookFiles) {
BookFileEntity primary = getPrimaryBookFile(bookFiles);
return primary == null ? null : primary.getFileSizeKb();
}
@Named("mapAlternativeFormats")
default List<BookFile> mapAlternativeFormats(List<BookFileEntity> bookFiles) {
if (bookFiles == null) return null;
return bookFiles.stream()
.filter(bf -> bf.isBook())
.filter(bf -> !bf.equals(getPrimaryBookFile(bookFiles)))
.map(this::toBookFile)
.toList();
}
@Named("mapSupplementaryFiles")
default List<BookFile> mapSupplementaryFiles(List<BookFileEntity> bookFiles) {
if (bookFiles == null)
return null;
return bookFiles.stream()
.filter(bf -> !bf.isBook())
.map(this::toBookFile)
.toList();
}
/*
* TODO: evolve the logic so that the user can select the primary book file format to be used.
* For now, we just return the first book file in the list.
*/
default BookFileEntity getPrimaryBookFile(List<BookFileEntity> bookFiles) {
if (bookFiles == null || bookFiles.isEmpty()) return null;
return bookFiles.stream()
.filter(bf -> bf.isBook())
.findFirst()
.orElse(null);
}
default BookFile toBookFile(BookFileEntity entity) {
if (entity == null) return null;
return BookFile.builder()
.id(entity.getId())
.bookId(entity.getBook().getId())
.fileName(entity.getFileName())
.filePath(entity.getFullFilePath().toString())
.fileSubPath(entity.getFileSubPath())
.isBook(entity.isBook())
.bookType(entity.getBookType())
.fileSizeKb(entity.getFileSizeKb())
.description(entity.getDescription())
.addedOn(entity.getAddedOn())
.build();
}
}
@@ -1,11 +0,0 @@
package com.adityachandel.booklore.mapper;
import com.adityachandel.booklore.model.dto.CustomFontDto;
import com.adityachandel.booklore.model.entity.CustomFontEntity;
import org.mapstruct.Mapper;
@Mapper(componentModel = "spring")
public interface CustomFontMapper {
CustomFontDto toDto(CustomFontEntity entity);
}
@@ -1,76 +0,0 @@
package com.adityachandel.booklore.mapper.v2;
import com.adityachandel.booklore.mapper.ShelfMapper;
import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.dto.BookMetadata;
import com.adityachandel.booklore.model.dto.LibraryPath;
import com.adityachandel.booklore.model.entity.*;
import com.adityachandel.booklore.model.enums.BookFileType;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Named;
import org.mapstruct.ReportingPolicy;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@Mapper(componentModel = "spring", uses = ShelfMapper.class, unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface BookMapperV2 {
@Mapping(source = "library.id", target = "libraryId")
@Mapping(source = "library.name", target = "libraryName")
@Mapping(source = "libraryPath", target = "libraryPath", qualifiedByName = "mapLibraryPathIdOnly")
@Mapping(source = "bookFiles", target = "bookType", qualifiedByName = "mapPrimaryBookType")
@Mapping(target = "metadata", qualifiedByName = "mapMetadata")
Book toDTO(BookEntity bookEntity);
@Named("mapMetadata")
@Mapping(target = "authors", source = "authors", qualifiedByName = "mapAuthors")
@Mapping(target = "categories", source = "categories", qualifiedByName = "mapCategories")
@Mapping(target = "moods", source = "moods", qualifiedByName = "mapMoods")
@Mapping(target = "tags", source = "tags", qualifiedByName = "mapTags")
BookMetadata mapMetadata(BookMetadataEntity metadataEntity);
@Named("mapAuthors")
default Set<String> mapAuthors(Set<AuthorEntity> authors) {
return authors == null ? Set.of() :
authors.stream().map(AuthorEntity::getName).collect(Collectors.toSet());
}
@Named("mapCategories")
default Set<String> mapCategories(Set<CategoryEntity> categories) {
return categories == null ? Set.of() :
categories.stream().map(CategoryEntity::getName).collect(Collectors.toSet());
}
@Named("mapMoods")
default Set<String> mapMoods(Set<MoodEntity> moods) {
return moods == null ? Set.of() :
moods.stream().map(MoodEntity::getName).collect(Collectors.toSet());
}
@Named("mapTags")
default Set<String> mapTags(Set<TagEntity> tags) {
return tags == null ? Set.of() :
tags.stream().map(TagEntity::getName).collect(Collectors.toSet());
}
@Named("mapPrimaryBookType")
default BookFileType mapPrimaryBookType(List<BookFileEntity> bookFiles) {
if (bookFiles == null || bookFiles.isEmpty()) return null;
return bookFiles.stream()
.filter(BookFileEntity::isBook)
.map(BookFileEntity::getBookType)
.findFirst()
.orElse(null);
}
@Named("mapLibraryPathIdOnly")
default LibraryPath mapLibraryPathIdOnly(LibraryPathEntity entity) {
if (entity == null) return null;
return LibraryPath.builder()
.id(entity.getId())
.build();
}
}
@@ -1,17 +0,0 @@
package com.adityachandel.booklore.model;
import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.enums.FileProcessStatus;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.ToString;
@Builder
@Getter
@ToString
@AllArgsConstructor
public class FileProcessResult {
private final Book book;
private final FileProcessStatus status;
}
@@ -1,27 +0,0 @@
package com.adityachandel.booklore.model.dto;
import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.model.enums.IconType;
import com.adityachandel.booklore.model.enums.LibraryScanMode;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Builder;
import lombok.Data;
import java.util.List;
@Builder
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Library {
private Long id;
private String name;
private Sort sort;
private String icon;
private IconType iconType;
private String fileNamingPattern;
private boolean watch;
private List<LibraryPath> paths;
private LibraryScanMode scanMode;
private BookFileType defaultBookFormat;
}
@@ -1,4 +0,0 @@
package com.adityachandel.booklore.model.dto.kobo;
public interface Entitlement {
}
@@ -1,16 +0,0 @@
package com.adityachandel.booklore.model.dto.kobo;
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import lombok.Builder;
import lombok.Data;
import java.util.List;
@Data
@Builder
@JsonNaming(PropertyNamingStrategies.UpperCamelCaseStrategy.class)
public class KoboReadingStateWrapper {
private List<KoboReadingState> readingStates;
}
@@ -1,10 +0,0 @@
package com.adityachandel.booklore.model.dto.progress;
import lombok.Builder;
import lombok.Data;
@Builder
@Data
public class KoProgress {
private Float percentage;
}
@@ -1,10 +0,0 @@
package com.adityachandel.booklore.model.dto.progress;
import lombok.Builder;
import lombok.Data;
@Builder
@Data
public class KoboProgress {
private Float percentage;
}
@@ -1,12 +0,0 @@
package com.adityachandel.booklore.model.dto.request;
import lombok.Builder;
import lombok.Data;
@Builder
@Data
public class CoverFetchRequest {
private String isbn;
private String title;
private String author;
}
@@ -1,24 +0,0 @@
package com.adityachandel.booklore.model.dto.request;
import com.adityachandel.booklore.model.dto.progress.CbxProgress;
import com.adityachandel.booklore.model.dto.progress.EpubProgress;
import com.adityachandel.booklore.model.dto.progress.PdfProgress;
import jakarta.validation.constraints.AssertTrue;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
import java.time.Instant;
@Data
public class ReadProgressRequest {
@NotNull
private Long bookId;
private EpubProgress epubProgress;
private PdfProgress pdfProgress;
private CbxProgress cbxProgress;
private Instant dateFinished;
@AssertTrue(message = "At least one progress field must be provided")
public boolean isProgressValid() {
return epubProgress != null || pdfProgress != null || cbxProgress != null || dateFinished != null;
}
}
@@ -1,10 +0,0 @@
package com.adityachandel.booklore.model.dto.request;
import lombok.Builder;
import lombok.Data;
@Data
@Builder
public class SetMetadataRequest {
private String googleBookId;
}
@@ -1,9 +0,0 @@
package com.adityachandel.booklore.model.dto.request;
import lombok.Data;
@Data
public class UserLoginRequest {
private String username;
private String password;
}
@@ -1,14 +0,0 @@
package com.adityachandel.booklore.model.dto.response;
import com.adityachandel.booklore.task.TaskStatus;
import com.adityachandel.booklore.model.enums.TaskType;
import lombok.Builder;
import lombok.Data;
@Builder
@Data
public class TaskCreateResponse {
private String taskId;
private TaskType taskType;
private TaskStatus status;
}
@@ -1,75 +0,0 @@
package com.adityachandel.booklore.model.entity;
import com.adityachandel.booklore.util.ArchiveUtils;
import com.adityachandel.booklore.model.enums.BookFileType;
import jakarta.persistence.*;
import lombok.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
@Entity
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "book_file")
public class BookFileEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
@JoinColumn(name = "book_id", nullable = false)
private BookEntity book;
@Column(name = "file_name", length = 1000, nullable = false)
private String fileName;
@Column(name = "file_sub_path", length = 512, nullable = false)
private String fileSubPath;
@Column(name = "is_book", nullable = false)
private boolean isBookFormat;
@Enumerated(EnumType.STRING)
@Column(name = "book_type", nullable = false)
private BookFileType bookType;
@Column(name = "archive_type")
@Enumerated(EnumType.STRING)
private ArchiveUtils.ArchiveType archiveType;
@Column(name = "file_size_kb")
private Long fileSizeKb;
@Column(name = "initial_hash", length = 128)
private String initialHash;
@Column(name = "current_hash", length = 128)
private String currentHash;
@Column(name = "alt_format_current_hash", insertable = false, updatable = false)
private String altFormatCurrentHash;
@Column(name = "description", columnDefinition = "TEXT")
private String description;
@Column(name = "added_on")
private Instant addedOn;
public boolean isBook() {
return isBookFormat;
}
public Path getFullFilePath() {
if (book == null || book.getLibraryPath() == null || book.getLibraryPath().getPath() == null
|| fileSubPath == null || fileName == null) {
throw new IllegalStateException("Cannot construct file path: missing book, library path, file subpath, or file name");
}
return Paths.get(book.getLibraryPath().getPath(), fileSubPath, fileName);
}
}
@@ -1,6 +0,0 @@
package com.adityachandel.booklore.model.enums;
public enum LibraryScanMode {
FILE_AS_BOOK,
FOLDER_AS_BOOK
}
@@ -1,5 +0,0 @@
package com.adityachandel.booklore.model.enums;
public enum Lock {
LOCK, UNLOCK
}
@@ -1,9 +0,0 @@
package com.adityachandel.booklore.model.websocket;
import com.adityachandel.booklore.model.dto.Book;
import lombok.Data;
@Data
public class BookAddNotification {
private Book addedBook;
}
@@ -1,12 +0,0 @@
package com.adityachandel.booklore.repository;
import com.adityachandel.booklore.model.entity.KoboReadingStateEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface KoboReadingStateRepository extends JpaRepository<KoboReadingStateEntity, Long> {
Optional<KoboReadingStateEntity> findByEntitlementId(String entitlementId);
}
@@ -1,125 +0,0 @@
package com.adityachandel.booklore.repository;
import com.adityachandel.booklore.model.dto.*;
import com.adityachandel.booklore.model.entity.ReadingSessionEntity;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.time.Instant;
import java.util.List;
@Repository
public interface ReadingSessionRepository extends JpaRepository<ReadingSessionEntity, Long> {
@Query("""
SELECT CAST(rs.startTime AS LocalDate) as date, COUNT(rs) as count
FROM ReadingSessionEntity rs
WHERE rs.user.id = :userId
AND YEAR(rs.startTime) = :year
GROUP BY CAST(rs.startTime AS LocalDate)
ORDER BY date
""")
List<ReadingSessionCountDto> findSessionCountsByUserAndYear(@Param("userId") Long userId, @Param("year") int year);
@Query("""
SELECT
b.id as bookId,
COALESCE(b.metadata.title,
(SELECT bf.fileName FROM BookFileEntity bf WHERE bf.book.id = b.id ORDER BY bf.id ASC LIMIT 1),
'Unknown Book') as bookTitle,
rs.bookType as bookFileType,
rs.startTime as startDate,
rs.endTime as endDate,
1L as totalSessions,
rs.durationSeconds as totalDurationSeconds
FROM ReadingSessionEntity rs
JOIN rs.book b
WHERE rs.user.id = :userId
AND rs.startTime >= :startOfWeek AND rs.startTime < :endOfWeek
ORDER BY rs.startTime
""")
List<ReadingSessionTimelineDto> findSessionTimelineByUserAndWeek(
@Param("userId") Long userId,
@Param("startOfWeek") Instant startOfWeek,
@Param("endOfWeek") Instant endOfWeek);
@Query("""
SELECT
CAST(rs.createdAt AS LocalDate) as date,
AVG(rs.progressDelta / (rs.durationSeconds / 60.0)) as avgProgressPerMinute,
COUNT(rs) as totalSessions
FROM ReadingSessionEntity rs
WHERE rs.user.id = :userId
AND rs.durationSeconds > 0
AND rs.progressDelta > 0
AND YEAR(rs.createdAt) = :year
GROUP BY CAST(rs.createdAt AS LocalDate)
ORDER BY date
""")
List<ReadingSpeedDto> findReadingSpeedByUserAndYear(@Param("userId") Long userId, @Param("year") int year);
@Query("""
SELECT
HOUR(rs.startTime) as hourOfDay,
COUNT(rs) as sessionCount,
SUM(rs.durationSeconds) as totalDurationSeconds
FROM ReadingSessionEntity rs
WHERE rs.user.id = :userId
AND (:year IS NULL OR YEAR(rs.startTime) = :year)
AND (:month IS NULL OR MONTH(rs.startTime) = :month)
GROUP BY HOUR(rs.startTime)
ORDER BY hourOfDay
""")
List<PeakReadingHourDto> findPeakReadingHoursByUser(
@Param("userId") Long userId,
@Param("year") Integer year,
@Param("month") Integer month);
@Query("""
SELECT
DAYOFWEEK(rs.startTime) as dayOfWeek,
COUNT(rs) as sessionCount,
COALESCE(SUM(rs.durationSeconds), 0) as totalDurationSeconds
FROM ReadingSessionEntity rs
WHERE rs.user.id = :userId
AND (:year IS NULL OR YEAR(rs.startTime) = :year)
AND (:month IS NULL OR MONTH(rs.startTime) = :month)
GROUP BY DAYOFWEEK(rs.startTime)
ORDER BY dayOfWeek
""")
List<FavoriteReadingDayDto> findFavoriteReadingDaysByUser(
@Param("userId") Long userId,
@Param("year") Integer year,
@Param("month") Integer month);
@Query("""
SELECT
c.name as genre,
COUNT(DISTINCT b.id) as bookCount,
COUNT(rs) as totalSessions,
SUM(rs.durationSeconds) as totalDurationSeconds
FROM ReadingSessionEntity rs
JOIN rs.book b
JOIN b.metadata.categories c
WHERE rs.user.id = :userId
GROUP BY c.name
ORDER BY totalSessions DESC
""")
List<GenreStatisticsDto> findGenreStatisticsByUser(@Param("userId") Long userId);
@Query("""
SELECT rs
FROM ReadingSessionEntity rs
WHERE rs.user.id = :userId
AND rs.book.id = :bookId
ORDER BY rs.startTime DESC
""")
Page<ReadingSessionEntity> findByUserIdAndBookId(
@Param("userId") Long userId,
@Param("bookId") Long bookId,
Pageable pageable);
}
@@ -1,462 +0,0 @@
package com.adityachandel.booklore.service;
import com.adityachandel.booklore.model.dto.GroupRule;
import com.adityachandel.booklore.model.dto.Rule;
import com.adityachandel.booklore.model.dto.RuleField;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.UserBookProgressEntity;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.persistence.criteria.*;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.BiFunction;
import java.util.stream.Collectors;
@Slf4j
@Service
@AllArgsConstructor
public class BookRuleEvaluatorService {
private final ObjectMapper objectMapper;
public Specification<BookEntity> toSpecification(GroupRule groupRule, Long userId) {
return (root, query, cb) -> {
Join<BookEntity, UserBookProgressEntity> progressJoin = root.join("userBookProgress", JoinType.LEFT);
Predicate userPredicate = cb.or(
cb.isNull(progressJoin.get("user").get("id")),
cb.equal(progressJoin.get("user").get("id"), userId)
);
Predicate rulePredicate = buildPredicate(groupRule, cb, root, progressJoin);
return cb.and(userPredicate, rulePredicate);
};
}
private Predicate buildPredicate(GroupRule group, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
if (group.getRules() == null || group.getRules().isEmpty()) {
return cb.conjunction();
}
List<Predicate> predicates = new ArrayList<>();
for (Object ruleObj : group.getRules()) {
if (ruleObj == null) continue;
Map<String, Object> ruleMap = objectMapper.convertValue(ruleObj, new TypeReference<>() {
});
String type = (String) ruleMap.get("type");
if ("group".equals(type)) {
GroupRule subGroup = objectMapper.convertValue(ruleObj, GroupRule.class);
predicates.add(buildPredicate(subGroup, cb, root, progressJoin));
} else {
try {
Rule rule = objectMapper.convertValue(ruleObj, Rule.class);
Predicate rulePredicate = buildRulePredicate(rule, cb, root, progressJoin);
if (rulePredicate != null) {
predicates.add(rulePredicate);
}
} catch (Exception e) {
log.error("Failed to parse rule: {}, error: {}", ruleObj, e.getMessage(), e);
}
}
}
if (predicates.isEmpty()) {
return cb.conjunction();
}
return group.getJoin() == com.adityachandel.booklore.model.dto.JoinType.AND
? cb.and(predicates.toArray(new Predicate[0]))
: cb.or(predicates.toArray(new Predicate[0]));
}
private Predicate buildRulePredicate(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
if (rule.getField() == null || rule.getOperator() == null) return null;
return switch (rule.getOperator()) {
case EQUALS -> buildEquals(rule, cb, root, progressJoin);
case NOT_EQUALS -> buildNotEquals(rule, cb, root, progressJoin);
case CONTAINS -> buildContains(rule, cb, root, progressJoin);
case DOES_NOT_CONTAIN -> cb.not(buildContains(rule, cb, root, progressJoin));
case STARTS_WITH -> buildStartsWith(rule, cb, root, progressJoin);
case ENDS_WITH -> buildEndsWith(rule, cb, root, progressJoin);
case GREATER_THAN -> buildGreaterThan(rule, cb, root, progressJoin);
case GREATER_THAN_EQUAL_TO -> buildGreaterThanEqual(rule, cb, root, progressJoin);
case LESS_THAN -> buildLessThan(rule, cb, root, progressJoin);
case LESS_THAN_EQUAL_TO -> buildLessThanEqual(rule, cb, root, progressJoin);
case IN_BETWEEN -> buildInBetween(rule, cb, root, progressJoin);
case IS_EMPTY -> buildIsEmpty(rule, cb, root, progressJoin);
case IS_NOT_EMPTY -> cb.not(buildIsEmpty(rule, cb, root, progressJoin));
case INCLUDES_ANY -> buildIncludesAny(rule, cb, root, progressJoin);
case EXCLUDES_ALL -> buildExcludesAll(rule, cb, root, progressJoin);
case INCLUDES_ALL -> buildIncludesAll(rule, cb, root, progressJoin);
};
}
private Predicate buildEquals(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
List<String> ruleList = toStringList(rule.getValue());
if (isArrayField(rule.getField())) {
return buildArrayFieldPredicate(rule.getField(), ruleList, cb, root, false);
}
Expression<?> field = getFieldExpression(rule.getField(), cb, root, progressJoin);
if (field == null) return cb.conjunction();
Object value = normalizeValue(rule.getValue(), rule.getField());
if (value instanceof LocalDateTime) {
return cb.equal(field, value);
} else if (rule.getField() == RuleField.READ_STATUS) {
if ("UNSET".equals(value.toString())) {
return cb.isNull(field);
}
return cb.equal(field, value.toString());
} else if (value instanceof Number) {
return cb.equal(field, value);
}
return cb.equal(cb.lower(field.as(String.class)), value.toString().toLowerCase());
}
private Predicate buildNotEquals(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
return cb.not(buildEquals(rule, cb, root, progressJoin));
}
private Predicate buildContains(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
String ruleVal = rule.getValue().toString().toLowerCase();
return buildStringPredicate(rule.getField(), root, progressJoin, cb,
nameField -> cb.like(cb.lower(nameField), "%" + escapeLike(ruleVal) + "%"));
}
private Predicate buildStartsWith(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
String ruleVal = rule.getValue().toString().toLowerCase();
return buildStringPredicate(rule.getField(), root, progressJoin, cb,
nameField -> cb.like(cb.lower(nameField), escapeLike(ruleVal) + "%"));
}
private Predicate buildEndsWith(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
String ruleVal = rule.getValue().toString().toLowerCase();
return buildStringPredicate(rule.getField(), root, progressJoin, cb,
nameField -> cb.like(cb.lower(nameField), "%" + escapeLike(ruleVal)));
}
private Predicate buildStringPredicate(RuleField field, Root<BookEntity> root,
Join<BookEntity, UserBookProgressEntity> progressJoin,
CriteriaBuilder cb,
java.util.function.Function<Expression<String>, Predicate> predicateBuilder) {
if (isArrayField(field)) {
Join<?, ?> arrayJoin = createArrayFieldJoin(field, root);
Expression<String> nameField = getArrayFieldNameExpression(field, arrayJoin);
return predicateBuilder.apply(nameField);
}
Expression<?> fieldExpr = getFieldExpression(field, cb, root, progressJoin);
if (fieldExpr == null) return cb.conjunction();
return predicateBuilder.apply(fieldExpr.as(String.class));
}
private Predicate buildGreaterThan(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
return buildComparisonPredicate(rule, cb, root, progressJoin,
(field, dateValue) -> cb.greaterThan(field.as(LocalDateTime.class), dateValue),
(field, numValue) -> cb.gt(field.as(Number.class), numValue));
}
private Predicate buildGreaterThanEqual(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
return buildComparisonPredicate(rule, cb, root, progressJoin,
(field, dateValue) -> cb.greaterThanOrEqualTo(field.as(LocalDateTime.class), dateValue),
(field, numValue) -> cb.ge(field.as(Number.class), numValue));
}
private Predicate buildLessThan(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
return buildComparisonPredicate(rule, cb, root, progressJoin,
(field, dateValue) -> cb.lessThan(field.as(LocalDateTime.class), dateValue),
(field, numValue) -> cb.lt(field.as(Number.class), numValue));
}
private Predicate buildLessThanEqual(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
return buildComparisonPredicate(rule, cb, root, progressJoin,
(field, dateValue) -> cb.lessThanOrEqualTo(field.as(LocalDateTime.class), dateValue),
(field, numValue) -> cb.le(field.as(Number.class), numValue));
}
private Predicate buildComparisonPredicate(Rule rule, CriteriaBuilder cb, Root<BookEntity> root,
Join<BookEntity, UserBookProgressEntity> progressJoin,
BiFunction<Expression<?>, LocalDateTime, Predicate> dateComparator,
BiFunction<Expression<?>, Double, Predicate> numberComparator) {
Expression<?> field = getFieldExpression(rule.getField(), cb, root, progressJoin);
if (field == null) return cb.conjunction();
Object value = normalizeValue(rule.getValue(), rule.getField());
if (value instanceof LocalDateTime) {
return dateComparator.apply(field, (LocalDateTime) value);
}
return numberComparator.apply(field, ((Number) value).doubleValue());
}
private Predicate buildInBetween(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
Expression<?> field = getFieldExpression(rule.getField(), cb, root, progressJoin);
if (field == null) return cb.conjunction();
Object start = normalizeValue(rule.getValueStart(), rule.getField());
Object end = normalizeValue(rule.getValueEnd(), rule.getField());
if (start == null || end == null) return cb.conjunction();
if (start instanceof LocalDateTime && end instanceof LocalDateTime) {
return cb.between(field.as(LocalDateTime.class), (LocalDateTime) start, (LocalDateTime) end);
}
if (!(start instanceof Number) || !(end instanceof Number)) {
return cb.conjunction();
}
return cb.between(field.as(Double.class), ((Number) start).doubleValue(), ((Number) end).doubleValue());
}
private Predicate buildIsEmpty(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
if (isArrayField(rule.getField())) {
Subquery<Long> subquery = cb.createQuery().subquery(Long.class);
Root<BookEntity> subRoot = subquery.from(BookEntity.class);
if (rule.getField() == RuleField.SHELF) {
subRoot.join("shelves", JoinType.INNER);
} else {
Join<Object, Object> metadataJoin = subRoot.join("metadata", JoinType.INNER);
joinArrayField(rule.getField(), metadataJoin);
}
subquery.select(cb.literal(1L)).where(cb.equal(subRoot.get("id"), root.get("id")));
return cb.not(cb.exists(subquery));
}
Expression<?> field = getFieldExpression(rule.getField(), cb, root, progressJoin);
if (field == null) return cb.conjunction();
return cb.or(cb.isNull(field), cb.equal(cb.trim(field.as(String.class)), ""));
}
private Predicate buildIncludesAny(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
List<String> ruleList = toStringList(rule.getValue());
if (isArrayField(rule.getField())) {
return buildArrayFieldPredicate(rule.getField(), ruleList, cb, root, false);
}
return buildFieldInPredicate(rule.getField(), field -> field, ruleList, cb, progressJoin);
}
private Predicate buildExcludesAll(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
List<String> ruleList = toStringList(rule.getValue());
if (isArrayField(rule.getField())) {
return cb.not(buildArrayFieldPredicate(rule.getField(), ruleList, cb, root, false));
}
return cb.not(buildFieldInPredicate(rule.getField(), field -> field, ruleList, cb, progressJoin));
}
private Predicate buildIncludesAll(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
List<String> ruleList = toStringList(rule.getValue());
if (isArrayField(rule.getField())) {
return buildArrayFieldPredicate(rule.getField(), ruleList, cb, root, true);
}
return buildFieldInPredicate(rule.getField(), field -> field, ruleList, cb, progressJoin);
}
private Predicate buildFieldInPredicate(RuleField ruleField,
java.util.function.Function<Expression<?>, Expression<?>> fieldTransformer,
List<String> ruleList,
CriteriaBuilder cb,
Join<BookEntity, UserBookProgressEntity> progressJoin) {
Expression<?> field = fieldTransformer.apply(getFieldExpression(ruleField, cb, null, progressJoin));
if (field == null) return cb.conjunction();
if (ruleField == RuleField.READ_STATUS) {
boolean hasUnset = ruleList.stream().anyMatch("UNSET"::equals);
List<String> nonUnsetValues = ruleList.stream()
.filter(v -> !"UNSET".equals(v))
.collect(Collectors.toList());
if (hasUnset && !nonUnsetValues.isEmpty()) {
return cb.or(
cb.isNull(field),
field.as(String.class).in(nonUnsetValues)
);
} else if (hasUnset) {
return cb.isNull(field);
} else {
return field.as(String.class).in(nonUnsetValues);
}
}
List<String> lowerList = ruleList.stream().map(String::toLowerCase).collect(Collectors.toList());
return cb.lower(field.as(String.class)).in(lowerList);
}
private Expression<?> getFieldExpression(RuleField field, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
return switch (field) {
case LIBRARY -> root.get("library").get("id");
case SHELF -> null; // Shelf is handled specially as a join field
case READ_STATUS -> progressJoin.get("readStatus");
case DATE_FINISHED -> progressJoin.get("dateFinished");
case LAST_READ_TIME -> progressJoin.get("lastReadTime");
case PERSONAL_RATING -> progressJoin.get("personalRating");
case FILE_SIZE -> root.get("fileSizeKb");
case METADATA_SCORE -> root.get("metadataMatchScore");
case TITLE -> root.get("metadata").get("title");
case SUBTITLE -> root.get("metadata").get("subtitle");
case PUBLISHER -> root.get("metadata").get("publisher");
case PUBLISHED_DATE -> root.get("metadata").get("publishedDate");
case PAGE_COUNT -> root.get("metadata").get("pageCount");
case LANGUAGE -> root.get("metadata").get("language");
case SERIES_NAME -> root.get("metadata").get("seriesName");
case SERIES_NUMBER -> root.get("metadata").get("seriesNumber");
case SERIES_TOTAL -> root.get("metadata").get("seriesTotal");
case ISBN13 -> root.get("metadata").get("isbn13");
case ISBN10 -> root.get("metadata").get("isbn10");
case AMAZON_RATING -> root.get("metadata").get("amazonRating");
case AMAZON_REVIEW_COUNT -> root.get("metadata").get("amazonReviewCount");
case GOODREADS_RATING -> root.get("metadata").get("goodreadsRating");
case GOODREADS_REVIEW_COUNT -> root.get("metadata").get("goodreadsReviewCount");
case HARDCOVER_RATING -> root.get("metadata").get("hardcoverRating");
case HARDCOVER_REVIEW_COUNT -> root.get("metadata").get("hardcoverReviewCount");
case RANOBEDB_RATING -> root.get("metadata").get("ranobedbRating");
case FILE_TYPE -> cb.function("SUBSTRING_INDEX", String.class,
root.get("fileName"), cb.literal("."), cb.literal(-1));
default -> null;
};
}
private boolean isArrayField(RuleField field) {
return field == RuleField.AUTHORS || field == RuleField.CATEGORIES ||
field == RuleField.MOODS || field == RuleField.TAGS ||
field == RuleField.GENRE || field == RuleField.SHELF;
}
private Join<?, ?> createArrayFieldJoin(RuleField field, Root<BookEntity> root) {
if (field == RuleField.SHELF) {
return root.join("shelves", JoinType.INNER);
}
Join<Object, Object> metadataJoin = root.join("metadata", JoinType.INNER);
return joinArrayField(field, metadataJoin);
}
private Expression<String> getArrayFieldNameExpression(RuleField field, Join<?, ?> arrayJoin) {
if (field == RuleField.SHELF) {
return arrayJoin.get("id").as(String.class);
}
return arrayJoin.get("name");
}
private Join<?, ?> joinArrayField(RuleField field, Join<Object, Object> metadataJoin) {
return switch (field) {
case AUTHORS -> metadataJoin.join("authors", JoinType.INNER);
case CATEGORIES -> metadataJoin.join("categories", JoinType.INNER);
case MOODS -> metadataJoin.join("moods", JoinType.INNER);
case TAGS -> metadataJoin.join("tags", JoinType.INNER);
case GENRE -> metadataJoin.join("categories", JoinType.INNER);
default -> throw new IllegalArgumentException("Not an array field: " + field);
};
}
private Predicate buildArrayFieldPredicate(RuleField field, List<String> values, CriteriaBuilder cb, Root<BookEntity> root, boolean includesAll) {
if (values.isEmpty()) {
return cb.conjunction();
}
if (includesAll) {
List<Predicate> predicates = values.stream()
.map(value -> {
Join<?, ?> arrayJoin = createArrayFieldJoin(field, root);
Expression<String> nameField = getArrayFieldNameExpression(field, arrayJoin);
return cb.equal(cb.lower(nameField), value.toLowerCase());
})
.toList();
return cb.and(predicates.toArray(new Predicate[0]));
} else {
Join<?, ?> arrayJoin = createArrayFieldJoin(field, root);
Expression<String> nameField = getArrayFieldNameExpression(field, arrayJoin);
List<String> lowerValues = values.stream()
.map(String::toLowerCase)
.collect(Collectors.toList());
return cb.lower(nameField).in(lowerValues);
}
}
private Object normalizeValue(Object value, RuleField field) {
if (value == null) return null;
if (field == RuleField.PUBLISHED_DATE) {
return parseDate(value);
}
if (field == RuleField.DATE_FINISHED || field == RuleField.LAST_READ_TIME) {
LocalDateTime parsed = parseDate(value);
if (parsed != null) {
return parsed.atZone(ZoneId.systemDefault()).toInstant();
}
return null;
}
if (field == RuleField.READ_STATUS) {
return value.toString();
}
if (value instanceof Number) {
return value;
}
return value.toString().toLowerCase();
}
private LocalDateTime parseDate(Object value) {
if (value == null) return null;
if (value instanceof LocalDateTime) return (LocalDateTime) value;
try {
return LocalDateTime.parse(value.toString(), DateTimeFormatter.ISO_DATE_TIME);
} catch (Exception e) {
try {
return LocalDate.parse(value.toString()).atStartOfDay();
} catch (Exception ex) {
return null;
}
}
}
private List<String> toStringList(Object value) {
if (value == null) return Collections.emptyList();
if (value instanceof List) {
return ((Collection<?>) value).stream()
.map(Object::toString)
.collect(Collectors.toList());
}
return Collections.singletonList(value.toString());
}
private String escapeLike(String value) {
return value.replace("\\", "\\\\")
.replace("%", "\\%")
.replace("_", "\\_");
}
}
@@ -1,256 +0,0 @@
package com.adityachandel.booklore.service;
import com.adityachandel.booklore.config.security.service.AuthenticationService;
import com.adityachandel.booklore.exception.ApiError;
import com.adityachandel.booklore.model.dto.BookLoreUser;
import com.adityachandel.booklore.model.dto.request.ReadingSessionRequest;
import com.adityachandel.booklore.model.dto.response.CompletionTimelineResponse;
import com.adityachandel.booklore.model.dto.response.FavoriteReadingDaysResponse;
import com.adityachandel.booklore.model.dto.response.GenreStatisticsResponse;
import com.adityachandel.booklore.model.dto.response.PeakReadingHoursResponse;
import com.adityachandel.booklore.model.dto.response.ReadingSessionHeatmapResponse;
import com.adityachandel.booklore.model.dto.response.ReadingSessionResponse;
import com.adityachandel.booklore.model.dto.response.ReadingSessionTimelineResponse;
import com.adityachandel.booklore.model.dto.response.ReadingSpeedResponse;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
import com.adityachandel.booklore.model.entity.ReadingSessionEntity;
import com.adityachandel.booklore.model.enums.ReadStatus;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.repository.ReadingSessionRepository;
import com.adityachandel.booklore.repository.UserBookProgressRepository;
import com.adityachandel.booklore.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.TemporalAdjusters;
import java.time.temporal.WeekFields;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Slf4j
@Service
@RequiredArgsConstructor
public class ReadingSessionService {
private final AuthenticationService authenticationService;
private final ReadingSessionRepository readingSessionRepository;
private final BookRepository bookRepository;
private final UserRepository userRepository;
private final UserBookProgressRepository userBookProgressRepository;
@Transactional
public void recordSession(ReadingSessionRequest request) {
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
Long userId = authenticatedUser.getId();
BookLoreUserEntity userEntity = userRepository.findById(userId).orElseThrow(() -> new UsernameNotFoundException("User not found with ID: " + userId));
BookEntity book = bookRepository.findById(request.getBookId()).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(request.getBookId()));
ReadingSessionEntity session = ReadingSessionEntity.builder()
.user(userEntity)
.book(book)
.bookType(request.getBookType())
.startTime(request.getStartTime())
.endTime(request.getEndTime())
.durationSeconds(request.getDurationSeconds())
.startProgress(request.getStartProgress())
.endProgress(request.getEndProgress())
.progressDelta(request.getProgressDelta())
.startLocation(request.getStartLocation())
.endLocation(request.getEndLocation())
.build();
readingSessionRepository.save(session);
log.info("Reading session persisted successfully: sessionId={}, userId={}, bookId={}, duration={}s", session.getId(), userId, request.getBookId(), request.getDurationSeconds());
}
@Transactional(readOnly = true)
public List<ReadingSessionHeatmapResponse> getSessionHeatmapForYear(int year) {
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
Long userId = authenticatedUser.getId();
return readingSessionRepository.findSessionCountsByUserAndYear(userId, year)
.stream()
.map(dto -> ReadingSessionHeatmapResponse.builder()
.date(dto.getDate())
.count(dto.getCount())
.build())
.collect(Collectors.toList());
}
@Transactional(readOnly = true)
public List<ReadingSessionTimelineResponse> getSessionTimelineForWeek(int year, int week) {
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
Long userId = authenticatedUser.getId();
LocalDate date = LocalDate.of(year, 1, 1)
.with(WeekFields.of(DayOfWeek.MONDAY, 1).weekOfYear(), week);
LocalDateTime startOfWeek = date.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY)).atStartOfDay();
LocalDateTime endOfWeek = date.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY)).plusDays(1).atStartOfDay();
return readingSessionRepository.findSessionTimelineByUserAndWeek(userId, startOfWeek.atZone(ZoneId.systemDefault()).toInstant(), endOfWeek.atZone(ZoneId.systemDefault()).toInstant())
.stream()
.map(dto -> ReadingSessionTimelineResponse.builder()
.bookId(dto.getBookId())
.bookType(dto.getBookFileType())
.bookTitle(dto.getBookTitle())
.startDate(dto.getStartDate())
.endDate(dto.getEndDate())
.totalSessions(dto.getTotalSessions())
.totalDurationSeconds(dto.getTotalDurationSeconds())
.build())
.collect(Collectors.toList());
}
@Transactional(readOnly = true)
public List<ReadingSpeedResponse> getReadingSpeedForYear(int year) {
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
Long userId = authenticatedUser.getId();
return readingSessionRepository.findReadingSpeedByUserAndYear(userId, year)
.stream()
.map(dto -> ReadingSpeedResponse.builder()
.date(dto.getDate())
.avgProgressPerMinute(dto.getAvgProgressPerMinute())
.totalSessions(dto.getTotalSessions())
.build())
.collect(Collectors.toList());
}
@Transactional(readOnly = true)
public List<PeakReadingHoursResponse> getPeakReadingHours(Integer year, Integer month) {
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
Long userId = authenticatedUser.getId();
return readingSessionRepository.findPeakReadingHoursByUser(userId, year, month)
.stream()
.map(dto -> PeakReadingHoursResponse.builder()
.hourOfDay(dto.getHourOfDay())
.sessionCount(dto.getSessionCount())
.totalDurationSeconds(dto.getTotalDurationSeconds())
.build())
.collect(Collectors.toList());
}
@Transactional(readOnly = true)
public List<FavoriteReadingDaysResponse> getFavoriteReadingDays(Integer year, Integer month) {
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
Long userId = authenticatedUser.getId();
String[] dayNames = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
return readingSessionRepository.findFavoriteReadingDaysByUser(userId, year, month)
.stream()
.map(dto -> FavoriteReadingDaysResponse.builder()
.dayOfWeek(dto.getDayOfWeek())
.dayName(dayNames[dto.getDayOfWeek() - 1])
.sessionCount(dto.getSessionCount())
.totalDurationSeconds(dto.getTotalDurationSeconds())
.build())
.collect(Collectors.toList());
}
@Transactional(readOnly = true)
public List<GenreStatisticsResponse> getGenreStatistics() {
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
Long userId = authenticatedUser.getId();
return readingSessionRepository.findGenreStatisticsByUser(userId)
.stream()
.map(dto -> {
double avgSessionsPerBook = dto.getBookCount() > 0
? (double) dto.getTotalSessions() / dto.getBookCount()
: 0.0;
return GenreStatisticsResponse.builder()
.genre(dto.getGenre())
.bookCount(dto.getBookCount())
.totalSessions(dto.getTotalSessions())
.totalDurationSeconds(dto.getTotalDurationSeconds())
.averageSessionsPerBook(Math.round(avgSessionsPerBook * 100.0) / 100.0)
.build();
})
.collect(Collectors.toList());
}
@Transactional(readOnly = true)
public List<CompletionTimelineResponse> getCompletionTimeline(int year) {
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
Long userId = authenticatedUser.getId();
Map<String, EnumMap<ReadStatus, Long>> timelineMap = new HashMap<>();
userBookProgressRepository.findCompletionTimelineByUser(userId, year).forEach(dto -> {
String key = dto.getYear() + "-" + dto.getMonth();
timelineMap.computeIfAbsent(key, k -> new EnumMap<>(ReadStatus.class))
.put(dto.getReadStatus(), dto.getBookCount());
});
return timelineMap.entrySet().stream()
.map(entry -> {
String[] parts = entry.getKey().split("-");
int yearPart = Integer.parseInt(parts[0]);
int month = Integer.parseInt(parts[1]);
Map<ReadStatus, Long> statusBreakdown = entry.getValue();
long totalBooks = statusBreakdown.values().stream().mapToLong(Long::longValue).sum();
long finishedBooks = statusBreakdown.getOrDefault(ReadStatus.READ, 0L);
double completionRate = totalBooks > 0 ? (finishedBooks * 100.0 / totalBooks) : 0.0;
return CompletionTimelineResponse.builder()
.year(yearPart)
.month(month)
.totalBooks(totalBooks)
.statusBreakdown(statusBreakdown)
.finishedBooks(finishedBooks)
.completionRate(Math.round(completionRate * 100.0) / 100.0)
.build();
})
.sorted((a, b) -> {
int cmp = b.getYear().compareTo(a.getYear());
return cmp != 0 ? cmp : b.getMonth().compareTo(a.getMonth());
})
.collect(Collectors.toList());
}
@Transactional(readOnly = true)
public Page<ReadingSessionResponse> getReadingSessionsForBook(Long bookId, int page) {
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
Long userId = authenticatedUser.getId();
bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
Pageable pageable = PageRequest.of(page, 5);
Page<ReadingSessionEntity> sessions = readingSessionRepository.findByUserIdAndBookId(userId, bookId, pageable);
return sessions.map(session -> ReadingSessionResponse.builder()
.id(session.getId())
.bookId(session.getBook().getId())
.bookTitle(session.getBook().getMetadata().getTitle())
.bookType(session.getBookType())
.startTime(session.getStartTime())
.endTime(session.getEndTime())
.durationSeconds(session.getDurationSeconds())
.startProgress(session.getStartProgress())
.endProgress(session.getEndProgress())
.progressDelta(session.getProgressDelta())
.startLocation(session.getStartLocation())
.endLocation(session.getEndLocation())
.createdAt(session.getCreatedAt())
.build());
}
}
@@ -1,110 +0,0 @@
package com.adityachandel.booklore.service.book;
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
import com.adityachandel.booklore.model.entity.*;
import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.repository.*;
import com.adityachandel.booklore.service.file.FileFingerprint;
import com.adityachandel.booklore.util.FileUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.time.Instant;
import java.util.*;
@Slf4j
@Service
@AllArgsConstructor
public class BookCreatorService {
private final AuthorRepository authorRepository;
private final CategoryRepository categoryRepository;
private final BookRepository bookRepository;
private final BookMetadataRepository bookMetadataRepository;
public BookEntity createShellBook(LibraryFile libraryFile, BookFileType bookFileType) {
Optional<BookEntity> existingBookOpt = bookRepository.findByLibraryIdAndLibraryPathIdAndFileSubPathAndFileName(
libraryFile.getLibraryEntity().getId(),
libraryFile.getLibraryPathEntity().getId(),
libraryFile.getFileSubPath(),
libraryFile.getFileName());
if (existingBookOpt.isPresent()) {
log.warn("Book already exists for file: {}", libraryFile.getFileName());
String newHash = FileFingerprint.generateHash(libraryFile.getFullPath());
long fileSizeKb = FileUtils.getFileSizeInKb(libraryFile.getFullPath());
BookEntity existingBook = existingBookOpt.get();
BookFileEntity primaryFile = existingBook.getPrimaryBookFile();
primaryFile.setCurrentHash(newHash);
primaryFile.setInitialHash(newHash);
primaryFile.setFileSizeKb(fileSizeKb);
existingBook.setDeleted(false);
return existingBook;
}
long fileSizeKb = FileUtils.getFileSizeInKb(libraryFile.getFullPath());
BookEntity bookEntity = BookEntity.builder()
.library(libraryFile.getLibraryEntity())
.libraryPath(libraryFile.getLibraryPathEntity())
.addedOn(Instant.now())
.bookFiles(new ArrayList<>())
.build();
BookFileEntity bookFileEntity = BookFileEntity.builder()
.book(bookEntity)
.fileName(libraryFile.getFileName())
.fileSubPath(libraryFile.getFileSubPath())
.isBookFormat(true)
.bookType(bookFileType)
.fileSizeKb(fileSizeKb)
.addedOn(Instant.now())
.build();
bookEntity.getBookFiles().add(bookFileEntity);
BookMetadataEntity metadata = BookMetadataEntity.builder()
.book(bookEntity)
.build();
bookEntity.setMetadata(metadata);
return bookRepository.saveAndFlush(bookEntity);
}
public void addCategoriesToBook(Set<String> categories, BookEntity bookEntity) {
if (bookEntity.getMetadata().getCategories() == null) {
bookEntity.getMetadata().setCategories(new HashSet<>());
}
categories.stream()
.map(cat -> truncate(cat, 255))
.map(truncated -> categoryRepository.findByName(truncated)
.orElseGet(() -> categoryRepository.save(CategoryEntity.builder().name(truncated).build())))
.forEach(catEntity -> bookEntity.getMetadata().getCategories().add(catEntity));
}
public void addAuthorsToBook(Set<String> authors, BookEntity bookEntity) {
if (bookEntity.getMetadata().getAuthors() == null) {
bookEntity.getMetadata().setAuthors(new HashSet<>());
}
authors.stream()
.map(authorName -> truncate(authorName, 255))
.map(authorName -> authorRepository.findByName(authorName)
.orElseGet(() -> authorRepository.save(AuthorEntity.builder().name(authorName).build())))
.forEach(authorEntity -> bookEntity.getMetadata().getAuthors().add(authorEntity));
bookEntity.getMetadata().updateSearchText(); // Manually trigger search text update since collection modification doesn't trigger @PreUpdate
}
private String truncate(String input, int maxLength) {
if (input == null)
return null;
return input.length() <= maxLength ? input : input.substring(0, maxLength);
}
public void saveConnections(BookEntity bookEntity) {
if (bookEntity.getMetadata().getAuthors() != null && !bookEntity.getMetadata().getAuthors().isEmpty()) {
authorRepository.saveAll(bookEntity.getMetadata().getAuthors());
}
bookRepository.save(bookEntity);
bookMetadataRepository.save(bookEntity.getMetadata());
}
}
@@ -1,160 +0,0 @@
package com.adityachandel.booklore.service.book;
import com.adityachandel.booklore.exception.ApiError;
import com.adityachandel.booklore.model.dto.settings.KoboSettings;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import com.adityachandel.booklore.service.kobo.KepubConversionService;
import com.adityachandel.booklore.service.kobo.CbxConversionService;
import com.adityachandel.booklore.util.FileUtils;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.FileSystemUtils;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.regex.Pattern;
@Slf4j
@AllArgsConstructor
@Service
public class BookDownloadService {
private static final Pattern NON_ASCII_PATTERN = Pattern.compile("[^\\x00-\\x7F]");
private final BookRepository bookRepository;
private final KepubConversionService kepubConversionService;
private final CbxConversionService cbxConversionService;
private final AppSettingService appSettingService;
public ResponseEntity<Resource> downloadBook(Long bookId) {
try {
BookEntity bookEntity = bookRepository.findById(bookId)
.orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
Path file = Paths.get(FileUtils.getBookFullPath(bookEntity)).toAbsolutePath().normalize();
File bookFile = file.toFile();
if (!bookFile.exists()) {
throw ApiError.FAILED_TO_DOWNLOAD_FILE.createException(bookId);
}
// Use FileSystemResource which properly handles file resources and closing
Resource resource = new FileSystemResource(bookFile);
String encodedFilename = URLEncoder.encode(file.getFileName().toString(), StandardCharsets.UTF_8)
.replace("+", "%20");
String fallbackFilename = NON_ASCII_PATTERN.matcher(file.getFileName().toString()).replaceAll("_");
String contentDisposition = String.format("attachment; filename=\"%s\"; filename*=UTF-8''%s",
fallbackFilename, encodedFilename);
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.contentLength(bookFile.length())
.header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition)
.header(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate")
.header(HttpHeaders.PRAGMA, "no-cache")
.header(HttpHeaders.EXPIRES, "0")
.body(resource);
} catch (Exception e) {
log.error("Failed to download book {}: {}", bookId, e.getMessage(), e);
throw ApiError.FAILED_TO_DOWNLOAD_FILE.createException(bookId);
}
}
public void downloadKoboBook(Long bookId, HttpServletResponse response) {
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
var primaryFile = bookEntity.getPrimaryBookFile();
boolean isEpub = primaryFile.getBookType() == BookFileType.EPUB;
boolean isCbx = primaryFile.getBookType() == BookFileType.CBX;
if (!isEpub && !isCbx) {
throw ApiError.GENERIC_BAD_REQUEST.createException("The requested book is not an EPUB or CBX file.");
}
KoboSettings koboSettings = appSettingService.getAppSettings().getKoboSettings();
if (koboSettings == null) {
throw ApiError.GENERIC_BAD_REQUEST.createException("Kobo settings not found.");
}
boolean convertEpubToKepub = isEpub && koboSettings.isConvertToKepub() && primaryFile.getFileSizeKb() <= (long) koboSettings.getConversionLimitInMb() * 1024;
boolean convertCbxToEpub = isCbx && koboSettings.isConvertCbxToEpub() && primaryFile.getFileSizeKb() <= (long) koboSettings.getConversionLimitInMbForCbx() * 1024;
int compressionPercentage = koboSettings.getConversionImageCompressionPercentage();
Path tempDir = null;
try {
File inputFile = new File(FileUtils.getBookFullPath(bookEntity));
File fileToSend = inputFile;
if (convertCbxToEpub || convertEpubToKepub) {
tempDir = Files.createTempDirectory("kobo-conversion");
}
if (convertCbxToEpub) {
fileToSend = cbxConversionService.convertCbxToEpub(inputFile, tempDir.toFile(), bookEntity,compressionPercentage);
}
if (convertEpubToKepub) {
fileToSend = kepubConversionService.convertEpubToKepub(inputFile, tempDir.toFile(),
koboSettings.isForceEnableHyphenation());
}
setResponseHeaders(response, fileToSend);
streamFileToResponse(fileToSend, response);
log.info("Successfully streamed {} ({} bytes) to client", fileToSend.getName(), fileToSend.length());
} catch (Exception e) {
log.error("Failed to download kobo book {}: {}", bookId, e.getMessage(), e);
throw ApiError.FAILED_TO_DOWNLOAD_FILE.createException(bookId);
} finally {
cleanupTempDirectory(tempDir);
}
}
private void setResponseHeaders(HttpServletResponse response, File file) {
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
response.setContentLengthLong(file.length());
String encodedFilename = URLEncoder.encode(file.getName(), StandardCharsets.UTF_8).replace("+", "%20");
String fallbackFilename = NON_ASCII_PATTERN.matcher(file.getName()).replaceAll("_");
String contentDisposition = String.format("attachment; filename=\"%s\"; filename*=UTF-8''%s",
fallbackFilename, encodedFilename);
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, contentDisposition);
}
private void streamFileToResponse(File file, HttpServletResponse response) {
try (InputStream in = Files.newInputStream(file.toPath())) {
in.transferTo(response.getOutputStream());
response.getOutputStream().flush();
} catch (IOException e) {
throw new UncheckedIOException("Failed to stream file to response", e);
}
}
private void cleanupTempDirectory(Path tempDir) {
if (tempDir != null) {
try {
FileSystemUtils.deleteRecursively(tempDir);
log.debug("Deleted temporary directory {}", tempDir);
} catch (Exception e) {
log.warn("Failed to delete temporary directory {}: {}", tempDir, e.getMessage());
}
}
}
}
@@ -1,64 +0,0 @@
package com.adityachandel.booklore.service.book;
import com.adityachandel.booklore.mapper.v2.BookMapperV2;
import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.repository.BookRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@RequiredArgsConstructor
@Service
public class BookQueryService {
private final BookRepository bookRepository;
private final BookMapperV2 bookMapperV2;
public List<Book> getAllBooks(boolean includeDescription) {
List<BookEntity> books = bookRepository.findAllWithMetadata();
return mapBooksToDto(books, includeDescription, null);
}
public List<Book> getAllBooksByLibraryIds(Set<Long> libraryIds, boolean includeDescription, Long userId) {
List<BookEntity> books = bookRepository.findAllWithMetadataByLibraryIds(libraryIds);
return mapBooksToDto(books, includeDescription, userId);
}
public List<BookEntity> findAllWithMetadataByIds(Set<Long> bookIds) {
return bookRepository.findAllWithMetadataByIds(bookIds);
}
public List<BookEntity> getAllFullBookEntities() {
return bookRepository.findAllFullBooks();
}
public void saveAll(List<BookEntity> books) {
bookRepository.saveAll(books);
}
private List<Book> mapBooksToDto(List<BookEntity> books, boolean includeDescription, Long userId) {
return books.stream()
.map(book -> mapBookToDto(book, includeDescription, userId))
.collect(Collectors.toList());
}
private Book mapBookToDto(BookEntity bookEntity, boolean includeDescription, Long userId) {
Book dto = bookMapperV2.toDTO(bookEntity);
if (!includeDescription && dto.getMetadata() != null) {
dto.getMetadata().setDescription(null);
}
if (dto.getShelves() != null && userId != null) {
dto.setShelves(dto.getShelves().stream()
.filter(shelf -> userId.equals(shelf.getUserId()))
.collect(Collectors.toSet()));
}
return dto;
}
}
@@ -1,41 +0,0 @@
package com.adityachandel.booklore.service.file;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class FileFingerprint {
public static String generateHash(Path filePath) {
final long base = 1024L;
final int blockSize = 1024;
try (RandomAccessFile raf = new RandomAccessFile(filePath.toFile(), "r")) {
MessageDigest md5 = MessageDigest.getInstance("MD5");
byte[] buffer = new byte[blockSize];
for (int i = -1; i <= 10; i++) {
long position = base << (2 * i);
if (position >= raf.length()) break;
raf.seek(position);
int read = raf.read(buffer);
if (read > 0) {
md5.update(buffer, 0, read);
}
}
byte[] hash = md5.digest();
StringBuilder result = new StringBuilder(hash.length * 2);
for (byte b : hash) {
result.append(String.format("%02x", b));
}
return result.toString();
} catch (IOException | NoSuchAlgorithmException e) {
throw new RuntimeException("Failed to compute partial MD5 hash for: " + filePath, e);
}
}
}
@@ -1,265 +0,0 @@
package com.adityachandel.booklore.service.file;
import com.adityachandel.booklore.mapper.BookMapper;
import com.adityachandel.booklore.mapper.LibraryMapper;
import com.adityachandel.booklore.model.dto.FileMoveResult;
import com.adityachandel.booklore.model.dto.Library;
import com.adityachandel.booklore.model.dto.request.FileMoveRequest;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.LibraryEntity;
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
import com.adityachandel.booklore.model.websocket.Topic;
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.repository.LibraryRepository;
import com.adityachandel.booklore.service.NotificationService;
import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService;
import jakarta.persistence.EntityManager;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
@AllArgsConstructor
@Service
@Slf4j
public class FileMoveService {
private static final long EVENT_DRAIN_TIMEOUT_MS = 300;
private final BookRepository bookRepository;
private final BookAdditionalFileRepository bookFileRepository;
private final LibraryRepository libraryRepository;
private final FileMoveHelper fileMoveHelper;
private final MonitoringRegistrationService monitoringRegistrationService;
private final LibraryMapper libraryMapper;
private final BookMapper bookMapper;
private final NotificationService notificationService;
private final EntityManager entityManager;
@Transactional
public void bulkMoveFiles(FileMoveRequest request) {
List<FileMoveRequest.Move> moves = request.getMoves();
Set<Long> allAffectedLibraryIds = collectAllAffectedLibraryIds(moves);
Set<Path> libraryPaths = monitoringRegistrationService.getPathsForLibraries(allAffectedLibraryIds);
log.info("Unregistering {} libraries before bulk file move", allAffectedLibraryIds.size());
monitoringRegistrationService.unregisterLibraries(allAffectedLibraryIds);
monitoringRegistrationService.waitForEventsDrainedByPaths(libraryPaths, EVENT_DRAIN_TIMEOUT_MS);
try {
for (FileMoveRequest.Move move : moves) {
processSingleMove(move);
}
// Ensure any file system events from the moves are drained/ignored while we are still unregistered
sleep(EVENT_DRAIN_TIMEOUT_MS);
} finally {
for (Long libraryId : allAffectedLibraryIds) {
libraryRepository.findById(libraryId)
.ifPresent(library -> monitoringRegistrationService.registerLibrary(libraryMapper.toLibrary(library)));
}
}
}
private Set<Long> collectAllAffectedLibraryIds(List<FileMoveRequest.Move> moves) {
Set<Long> libraryIds = new HashSet<>();
for (FileMoveRequest.Move move : moves) {
libraryIds.add(move.getTargetLibraryId());
bookRepository.findById(move.getBookId())
.ifPresent(book -> libraryIds.add(book.getLibrary().getId()));
}
return libraryIds;
}
private void processSingleMove(FileMoveRequest.Move move) {
Long bookId = move.getBookId();
Long targetLibraryId = move.getTargetLibraryId();
Long targetLibraryPathId = move.getTargetLibraryPathId();
record PlannedMove(Path source, Path temp, Path target) {}
Map<Long, PlannedMove> plannedMovesByBookFileId = new HashMap<>();
Set<Path> sourceParentsToCleanup = new HashSet<>();
try {
Optional<BookEntity> optionalBook = bookRepository.findByIdWithBookFiles(bookId);
Optional<LibraryEntity> optionalLibrary = libraryRepository.findById(targetLibraryId);
if (optionalBook.isEmpty()) {
log.warn("Book not found for move operation: bookId={}", bookId);
return;
}
if (optionalLibrary.isEmpty()) {
log.warn("Target library not found for move operation: libraryId={}", targetLibraryId);
return;
}
BookEntity bookEntity = optionalBook.get();
LibraryEntity targetLibrary = optionalLibrary.get();
Optional<LibraryPathEntity> optionalLibraryPathEntity = targetLibrary.getLibraryPaths().stream()
.filter(libraryPath -> Objects.equals(libraryPath.getId(), targetLibraryPathId))
.findFirst();
if (optionalLibraryPathEntity.isEmpty()) {
log.warn("Target library path not found for move operation: libraryId={}, pathId={}", targetLibraryId, targetLibraryPathId);
return;
}
LibraryPathEntity libraryPathEntity = optionalLibraryPathEntity.get();
if (bookEntity.getBookFiles() == null || bookEntity.getBookFiles().isEmpty()) {
log.warn("Book has no files to move: bookId={}", bookId);
return;
}
Path currentPrimaryFilePath = bookEntity.getFullFilePath();
String pattern = fileMoveHelper.getFileNamingPattern(targetLibrary);
Path newFilePath = fileMoveHelper.generateNewFilePath(bookEntity, libraryPathEntity, pattern);
if (currentPrimaryFilePath.equals(newFilePath)) {
return;
}
String newFileSubPath = fileMoveHelper.extractSubPath(newFilePath, libraryPathEntity);
Path targetParentDir = newFilePath.getParent();
if (targetParentDir == null) {
log.warn("Target parent directory could not be determined for move operation: bookId={}", bookId);
return;
}
for (var bookFile : bookEntity.getBookFiles()) {
Path sourcePath = bookFile.getFullFilePath();
Path targetPath;
if (bookFile.isBook()) {
targetPath = fileMoveHelper.generateNewFilePath(bookEntity, bookFile, libraryPathEntity, pattern);
} else {
targetPath = targetParentDir.resolve(bookFile.getFileName());
}
if (sourcePath.equals(targetPath)) {
continue;
}
Path tempPath = fileMoveHelper.moveFileWithBackup(sourcePath);
plannedMovesByBookFileId.put(bookFile.getId(), new PlannedMove(sourcePath, tempPath, targetPath));
if (sourcePath.getParent() != null) {
sourceParentsToCleanup.add(sourcePath.getParent());
}
}
if (plannedMovesByBookFileId.isEmpty()) {
return;
}
for (var bookFile : bookEntity.getBookFiles()) {
String newFileName;
if (bookFile.isBook()) {
Path targetPath = fileMoveHelper.generateNewFilePath(bookEntity, bookFile, libraryPathEntity, pattern);
newFileName = targetPath.getFileName().toString();
} else {
newFileName = bookFile.getFileName();
}
bookFileRepository.updateFileNameAndSubPath(bookFile.getId(), newFileName, newFileSubPath);
}
bookRepository.updateLibrary(bookEntity.getId(), targetLibrary.getId(), libraryPathEntity);
for (PlannedMove planned : plannedMovesByBookFileId.values()) {
fileMoveHelper.commitMove(planned.temp(), planned.target());
}
plannedMovesByBookFileId.clear();
Path libraryRoot = Paths.get(libraryPathEntity.getPath()).toAbsolutePath().normalize();
for (Path sourceParent : sourceParentsToCleanup) {
fileMoveHelper.deleteEmptyParentDirsUpToLibraryFolders(sourceParent, Set.of(libraryRoot));
}
entityManager.clear();
BookEntity fresh = bookRepository.findById(bookId).orElseThrow();
notificationService.sendMessage(Topic.BOOK_UPDATE, bookMapper.toBookWithDescription(fresh, false));
} catch (Exception e) {
log.error("Error moving file for book ID {}: {}", bookId, e.getMessage(), e);
} finally {
for (PlannedMove planned : plannedMovesByBookFileId.values()) {
fileMoveHelper.rollbackMove(planned.temp(), planned.source());
}
}
}
@Transactional
public FileMoveResult moveSingleFile(BookEntity bookEntity) {
Long libraryId = bookEntity.getLibraryPath().getLibrary().getId();
Path libraryRoot = Paths.get(bookEntity.getLibraryPath().getPath()).toAbsolutePath().normalize();
boolean isLibraryMonitoredWhenCalled = false;
try {
Set<Path> existingPaths = monitoringRegistrationService.getPathsForLibraries(Set.of(libraryId));
isLibraryMonitoredWhenCalled = monitoringRegistrationService.isLibraryMonitored(libraryId) || !existingPaths.isEmpty();
String pattern = fileMoveHelper.getFileNamingPattern(bookEntity.getLibraryPath().getLibrary());
Path currentFilePath = bookEntity.getFullFilePath();
Path expectedFilePath = fileMoveHelper.generateNewFilePath(bookEntity, bookEntity.getLibraryPath(), pattern);
if (currentFilePath.equals(expectedFilePath)) {
return FileMoveResult.builder().moved(false).build();
}
log.info("File for book ID {} needs to be moved from {} to {} to match library pattern", bookEntity.getId(), currentFilePath, expectedFilePath);
if (isLibraryMonitoredWhenCalled) {
log.debug("Unregistering library {} before moving a single file", libraryId);
fileMoveHelper.unregisterLibrary(libraryId);
monitoringRegistrationService.waitForEventsDrainedByPaths(existingPaths, EVENT_DRAIN_TIMEOUT_MS);
}
fileMoveHelper.moveFile(currentFilePath, expectedFilePath);
fileMoveHelper.deleteEmptyParentDirsUpToLibraryFolders(currentFilePath.getParent(), Set.of(libraryRoot));
if (isLibraryMonitoredWhenCalled) {
// Ensure any file system events from the move and cleanup are drained/ignored while we are still unregistered
sleep(EVENT_DRAIN_TIMEOUT_MS);
}
String newFileName = expectedFilePath.getFileName().toString();
String newFileSubPath = fileMoveHelper.extractSubPath(expectedFilePath, bookEntity.getLibraryPath());
return FileMoveResult.builder()
.moved(true)
.newFileName(newFileName)
.newFileSubPath(newFileSubPath)
.build();
} catch (Exception e) {
log.error("Failed to move file for book ID {}: {}", bookEntity.getId(), e.getMessage(), e);
} finally {
if (isLibraryMonitoredWhenCalled) {
log.debug("Registering library paths for library {} with root {}", libraryId, libraryRoot);
LibraryEntity libraryEntity = bookEntity.getLibraryPath().getLibrary();
Library library = libraryMapper.toLibrary(libraryEntity);
library.setWatch(true);
monitoringRegistrationService.registerLibrary(library);
}
}
return FileMoveResult.builder().moved(false).build();
}
protected void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("Sleep interrupted", e);
}
}
}
@@ -1,16 +0,0 @@
package com.adityachandel.booklore.service.fileprocessor;
import com.adityachandel.booklore.model.FileProcessResult;
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.enums.BookFileType;
import java.util.List;
public interface BookFileProcessor {
List<BookFileType> getSupportedTypes();
FileProcessResult processFile(LibraryFile libraryFile);
boolean generateCover(BookEntity bookEntity);
}
@@ -1,227 +0,0 @@
package com.adityachandel.booklore.service.kobo;
import com.adityachandel.booklore.config.security.service.AuthenticationService;
import com.adityachandel.booklore.mapper.KoboReadingStateMapper;
import com.adityachandel.booklore.model.dto.BookLoreUser;
import com.adityachandel.booklore.model.dto.KoboSyncSettings;
import com.adityachandel.booklore.model.dto.kobo.KoboReadingState;
import com.adityachandel.booklore.model.dto.kobo.KoboReadingStateWrapper;
import com.adityachandel.booklore.model.dto.response.kobo.KoboReadingStateResponse;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
import com.adityachandel.booklore.model.entity.KoboReadingStateEntity;
import com.adityachandel.booklore.model.entity.UserBookProgressEntity;
import com.adityachandel.booklore.model.enums.ReadStatus;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.repository.KoboReadingStateRepository;
import com.adityachandel.booklore.repository.UserBookProgressRepository;
import com.adityachandel.booklore.repository.UserRepository;
import com.adityachandel.booklore.service.hardcover.HardcoverSyncService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
@Slf4j
@Service
@RequiredArgsConstructor
public class KoboReadingStateService {
private static final int STATUS_SYNC_BUFFER_SECONDS = 10;
private final KoboReadingStateRepository repository;
private final KoboReadingStateMapper mapper;
private final UserBookProgressRepository progressRepository;
private final BookRepository bookRepository;
private final UserRepository userRepository;
private final AuthenticationService authenticationService;
private final KoboSettingsService koboSettingsService;
private final KoboReadingStateBuilder readingStateBuilder;
private final HardcoverSyncService hardcoverSyncService;
@Transactional
public KoboReadingStateResponse saveReadingState(List<KoboReadingState> readingStates) {
List<KoboReadingState> koboReadingStates = saveAll(readingStates);
List<KoboReadingStateResponse.UpdateResult> updateResults = koboReadingStates.stream()
.map(state -> KoboReadingStateResponse.UpdateResult.builder()
.entitlementId(state.getEntitlementId())
.currentBookmarkResult(KoboReadingStateResponse.Result.success())
.statisticsResult(KoboReadingStateResponse.Result.success())
.statusInfoResult(KoboReadingStateResponse.Result.success())
.build())
.collect(Collectors.toList());
return KoboReadingStateResponse.builder()
.requestResult("Success")
.updateResults(updateResults)
.build();
}
private List<KoboReadingState> saveAll(List<KoboReadingState> dtos) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
return dtos.stream()
.map(dto -> {
KoboReadingStateEntity entity = repository.findByEntitlementId(dto.getEntitlementId())
.map(existing -> {
existing.setCurrentBookmarkJson(mapper.toJson(dto.getCurrentBookmark()));
existing.setStatisticsJson(mapper.toJson(dto.getStatistics()));
existing.setStatusInfoJson(mapper.toJson(dto.getStatusInfo()));
existing.setLastModifiedString(mapper.cleanString(String.valueOf(dto.getLastModified())));
return existing;
})
.orElseGet(() -> {
KoboReadingStateEntity newEntity = mapper.toEntity(dto);
newEntity.setCreated(mapper.cleanString(String.valueOf(dto.getCreated())));
return newEntity;
});
KoboReadingStateEntity savedEntity = repository.save(entity);
syncKoboProgressToUserBookProgress(dto, user.getId());
return savedEntity;
})
.map(mapper::toDto)
.collect(Collectors.toList());
}
@Transactional
public void deleteReadingState(Long bookId) {
repository.findByEntitlementId(String.valueOf(bookId)).ifPresent(repository::delete);
}
public KoboReadingStateWrapper getReadingState(String entitlementId) {
Optional<KoboReadingState> readingState = repository.findByEntitlementId(entitlementId)
.map(mapper::toDto)
.or(() -> constructReadingStateFromProgress(entitlementId));
return readingState.map(state -> KoboReadingStateWrapper.builder()
.readingStates(List.of(state))
.build()).orElse(null);
}
private Optional<KoboReadingState> constructReadingStateFromProgress(String entitlementId) {
try {
Long bookId = Long.parseLong(entitlementId);
BookLoreUser user = authenticationService.getAuthenticatedUser();
return progressRepository.findByUserIdAndBookId(user.getId(), bookId)
.filter(progress -> progress.getKoboProgressPercent() != null || progress.getKoboLocation() != null)
.map(progress -> readingStateBuilder.buildReadingStateFromProgress(entitlementId, progress));
} catch (NumberFormatException e) {
log.warn("Invalid entitlement ID format when constructing reading state: {}", entitlementId);
return Optional.empty();
}
}
private void syncKoboProgressToUserBookProgress(KoboReadingState readingState, Long userId) {
try {
Long bookId = Long.parseLong(readingState.getEntitlementId());
Optional<BookEntity> bookOpt = bookRepository.findById(bookId);
if (bookOpt.isEmpty()) {
log.warn("Book not found for entitlement ID: {}", readingState.getEntitlementId());
return;
}
BookEntity book = bookOpt.get();
Optional<BookLoreUserEntity> userOpt = userRepository.findById(userId);
if (userOpt.isEmpty()) {
log.warn("User not found: {}", userId);
return;
}
UserBookProgressEntity progress = progressRepository.findByUserIdAndBookId(userId, bookId)
.orElseGet(() -> {
UserBookProgressEntity newProgress = new UserBookProgressEntity();
newProgress.setUser(userOpt.get());
newProgress.setBook(book);
return newProgress;
});
KoboReadingState.CurrentBookmark bookmark = readingState.getCurrentBookmark();
if (bookmark != null) {
if (bookmark.getProgressPercent() != null) {
progress.setKoboProgressPercent(bookmark.getProgressPercent().floatValue());
}
KoboReadingState.CurrentBookmark.Location location = bookmark.getLocation();
if (location != null) {
log.debug("Kobo location data: value={}, type={}, source={} (length={})",
location.getValue(), location.getType(), location.getSource(),
location.getSource() != null ? location.getSource().length() : 0);
progress.setKoboLocation(location.getValue());
progress.setKoboLocationType(location.getType());
progress.setKoboLocationSource(location.getSource());
}
}
Instant now = Instant.now();
progress.setKoboProgressReceivedTime(now);
progress.setLastReadTime(now);
if (progress.getKoboProgressPercent() != null) {
updateReadStatusFromKoboProgress(progress, now);
}
progressRepository.save(progress);
log.debug("Synced Kobo progress: bookId={}, progress={}%", bookId, progress.getKoboProgressPercent());
// Sync progress to Hardcover asynchronously (if enabled for this user)
hardcoverSyncService.syncProgressToHardcover(book.getId(), progress.getKoboProgressPercent(), userId);
} catch (NumberFormatException e) {
log.warn("Invalid entitlement ID format: {}", readingState.getEntitlementId());
}
}
private void updateReadStatusFromKoboProgress(UserBookProgressEntity userProgress, Instant now) {
if (shouldPreserveCurrentStatus(userProgress, now)) {
return;
}
double koboProgressPercent = userProgress.getKoboProgressPercent();
ReadStatus derivedStatus = deriveStatusFromProgress(koboProgressPercent);
userProgress.setReadStatus(derivedStatus);
if (derivedStatus == ReadStatus.READ && userProgress.getDateFinished() == null) {
userProgress.setDateFinished(Instant.now());
}
}
private boolean shouldPreserveCurrentStatus(UserBookProgressEntity progress, Instant now) {
Instant statusModifiedTime = progress.getReadStatusModifiedTime();
if (statusModifiedTime == null) {
return false;
}
Instant statusSentTime = progress.getKoboStatusSentTime();
boolean hasPendingStatusUpdate = statusSentTime == null || statusModifiedTime.isAfter(statusSentTime);
if (hasPendingStatusUpdate) {
return true;
}
return now.isBefore(statusSentTime.plusSeconds(STATUS_SYNC_BUFFER_SECONDS));
}
private ReadStatus deriveStatusFromProgress(double progressPercent) {
KoboSyncSettings settings = koboSettingsService.getCurrentUserSettings();
float finishedThreshold = settings.getProgressMarkAsFinishedThreshold() != null
? settings.getProgressMarkAsFinishedThreshold() : 99f;
float readingThreshold = settings.getProgressMarkAsReadingThreshold() != null
? settings.getProgressMarkAsReadingThreshold() : 1f;
if (progressPercent >= finishedThreshold) return ReadStatus.READ;
if (progressPercent >= readingThreshold) return ReadStatus.READING;
return ReadStatus.UNREAD;
}
}
@@ -1,67 +0,0 @@
package com.adityachandel.booklore.service.library;
import com.adityachandel.booklore.model.FileProcessResult;
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
import com.adityachandel.booklore.model.entity.LibraryEntity;
import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.model.enums.LibraryScanMode;
import com.adityachandel.booklore.service.event.BookEventBroadcaster;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry;
import com.adityachandel.booklore.service.kobo.KoboAutoShelfService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@AllArgsConstructor
@Component
@Slf4j
public class FileAsBookProcessor implements LibraryFileProcessor {
private final BookEventBroadcaster bookEventBroadcaster;
private final BookFileProcessorRegistry processorRegistry;
private final KoboAutoShelfService koboAutoShelfService;
@Override
public LibraryScanMode getScanMode() {
return LibraryScanMode.FILE_AS_BOOK;
}
@Override
@Transactional
public void processLibraryFiles(List<LibraryFile> libraryFiles, LibraryEntity libraryEntity) {
for (LibraryFile libraryFile : libraryFiles) {
processFileWithErrorHandling(libraryFile);
}
log.info("Finished processing library '{}'", libraryEntity.getName());
}
private void processFileWithErrorHandling(LibraryFile libraryFile) {
log.info("Processing file: {}", libraryFile.getFileName());
try {
FileProcessResult result = processLibraryFile(libraryFile);
if (result != null) {
bookEventBroadcaster.broadcastBookAddEvent(result.getBook());
koboAutoShelfService.autoAddBookToKoboShelves(result.getBook().getId());
}
} catch (Exception e) {
log.error("Failed to process file '{}': {}", libraryFile.getFileName(), e.getMessage());
}
}
@Transactional
protected FileProcessResult processLibraryFile(LibraryFile libraryFile) {
BookFileType type = libraryFile.getBookFileType();
if (type == null) {
log.warn("Unsupported file type for file: {}", libraryFile.getFileName());
return null;
}
BookFileProcessor processor = processorRegistry.getProcessorOrThrow(type);
return processor.processFile(libraryFile);
}
}
@@ -1,255 +0,0 @@
package com.adityachandel.booklore.service.library;
import com.adityachandel.booklore.model.FileProcessResult;
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
import com.adityachandel.booklore.model.entity.BookFileEntity;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.LibraryEntity;
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
import com.adityachandel.booklore.model.enums.BookFileExtension;
import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.model.enums.LibraryScanMode;
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.service.file.FileFingerprint;
import com.adityachandel.booklore.service.event.AdminEventBroadcaster;
import com.adityachandel.booklore.service.event.BookEventBroadcaster;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry;
import com.adityachandel.booklore.util.FileUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.nio.file.Path;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
@Service
@AllArgsConstructor
@Slf4j
public class FolderAsBookFileProcessor implements LibraryFileProcessor {
private final BookRepository bookRepository;
private final BookAdditionalFileRepository bookAdditionalFileRepository;
private final BookEventBroadcaster bookEventBroadcaster;
private final AdminEventBroadcaster adminEventBroadcaster;
private final BookFileProcessorRegistry bookFileProcessorRegistry;
@Override
public LibraryScanMode getScanMode() {
return LibraryScanMode.FOLDER_AS_BOOK;
}
@Override
public boolean supportsSupplementaryFiles() {
return true;
}
@Override
public void processLibraryFiles(List<LibraryFile> libraryFiles, LibraryEntity libraryEntity) {
Map<Path, List<LibraryFile>> filesByDirectory = libraryFiles.stream()
.collect(Collectors.groupingBy(libraryFile -> libraryFile.getFullPath().getParent()));
log.info("Processing {} directories with {} total files for library: {}",
filesByDirectory.size(), libraryFiles.size(), libraryEntity.getName());
var sortedDirectories = filesByDirectory.entrySet()
.stream()
.sorted(Map.Entry.comparingByKey())
.toList();
for (Map.Entry<Path, List<LibraryFile>> entry : sortedDirectories) {
Path directoryPath = entry.getKey();
List<LibraryFile> filesInDirectory = entry.getValue();
log.debug("Processing directory: {} with {} files", directoryPath, filesInDirectory.size());
processDirectory(directoryPath, filesInDirectory, libraryEntity);
}
}
private void processDirectory(Path directoryPath, List<LibraryFile> filesInDirectory, LibraryEntity libraryEntity) {
var bookCreationResult = getOrCreateBookInDirectory(directoryPath, filesInDirectory, libraryEntity);
if (bookCreationResult.bookEntity.isEmpty()) {
log.warn("No book created for directory: {}", directoryPath);
return;
}
processAdditionalFiles(bookCreationResult.bookEntity.get(), bookCreationResult.remainingFiles);
}
private GetOrCreateBookResult getOrCreateBookInDirectory(Path directoryPath, List<LibraryFile> filesInDirectory, LibraryEntity libraryEntity) {
var existingBook = findExistingBookInDirectory(directoryPath, libraryEntity);
if (existingBook.isPresent()) {
log.debug("Found existing book in directory {}: {}", directoryPath, existingBook.get().getPrimaryBookFile().getFileName());
return new GetOrCreateBookResult(existingBook, filesInDirectory);
}
Optional<BookEntity> parentBook = findBookInParentDirectories(directoryPath, libraryEntity);
if (parentBook.isPresent()) {
log.debug("Found parent book for directory {}: {}", directoryPath, parentBook.get().getPrimaryBookFile().getFileName());
return new GetOrCreateBookResult(parentBook, filesInDirectory);
}
log.debug("No existing book found, creating new book from directory: {}", directoryPath);
Optional<CreateBookResult> newBook = createNewBookFromDirectory(directoryPath, filesInDirectory, libraryEntity);
if (newBook.isPresent()) {
log.info("Created new book: {}", newBook.get().bookEntity.getPrimaryBookFile().getFileName());
var remainingFiles = filesInDirectory.stream()
.filter(file -> !file.equals(newBook.get().libraryFile))
.toList();
return new GetOrCreateBookResult(Optional.of(newBook.get().bookEntity), remainingFiles);
} else {
log.warn("Failed to create book from directory: {}", directoryPath);
return new GetOrCreateBookResult(Optional.empty(), filesInDirectory);
}
}
private Optional<BookEntity> findExistingBookInDirectory(Path directoryPath, LibraryEntity libraryEntity) {
return libraryEntity.getLibraryPaths().stream()
.flatMap(libPath -> {
String filesSearchPath = Path.of(libPath.getPath())
.relativize(directoryPath)
.toString()
.replace("\\", "/");
return bookRepository
.findAllByLibraryPathIdAndFileSubPathStartingWith(libPath.getId(), filesSearchPath)
.stream();
})
.filter(book -> book.getFullFilePath().getParent().equals(directoryPath))
.findFirst();
}
private Optional<BookEntity> findBookInParentDirectories(Path directoryPath, LibraryEntity libraryEntity) {
Path parent = directoryPath.getParent();
LibraryPathEntity directoryLibraryPathEntity = libraryEntity.getLibraryPaths().stream()
.filter(libPath -> directoryPath.startsWith(libPath.getPath()))
.findFirst()
.orElseThrow(() -> new IllegalStateException("No library path found for directory: " + directoryPath));
Path directoryLibraryPath = Path.of(directoryLibraryPathEntity.getPath());
while (parent != null) {
final String parentPath = directoryLibraryPath
.relativize(parent)
.toString()
.replace("\\", "/");
Optional<BookEntity> parentBook =
bookRepository.findAllByLibraryPathIdAndFileSubPathStartingWith(
directoryLibraryPathEntity.getId(), parentPath).stream()
.filter(book -> book.getPrimaryBookFile().getFileSubPath().equals(parentPath))
.findFirst();
if (parentBook.isPresent()) {
return parentBook;
}
parent = parent.getParent();
}
return Optional.empty();
}
private Optional<CreateBookResult> createNewBookFromDirectory(Path directoryPath, List<LibraryFile> filesInDirectory, LibraryEntity libraryEntity) {
Optional<LibraryFile> mainBookFile = findBestMainBookFile(filesInDirectory, libraryEntity);
if (mainBookFile.isEmpty()) {
log.debug("No suitable book file found in directory: {}", directoryPath);
return Optional.empty();
}
LibraryFile bookFile = mainBookFile.get();
try {
log.info("Creating new book from file: {}", bookFile.getFileName());
BookFileProcessor processor = bookFileProcessorRegistry.getProcessorOrThrow(bookFile.getBookFileType());
FileProcessResult result = processor.processFile(bookFile);
if (result.getBook() != null) {
bookEventBroadcaster.broadcastBookAddEvent(result.getBook());
BookEntity bookEntity = bookRepository.getReferenceById(result.getBook().getId());
if (bookEntity.getFullFilePath().equals(bookFile.getFullPath())) {
log.info("Successfully created new book: {}", bookEntity.getPrimaryBookFile().getFileName());
} else {
log.warn("Found duplicate book with different path: {} vs {}", bookEntity.getFullFilePath(), bookFile.getFullPath());
}
return Optional.of(new CreateBookResult(bookEntity, bookFile));
} else {
log.warn("Book processor returned null for file: {}", bookFile.getFileName());
adminEventBroadcaster.broadcastAdminEvent("Failed to create book from file: " + bookFile.getFileName());
return Optional.empty();
}
} catch (Exception e) {
log.error("Error processing book file {}: {}", bookFile.getFileName(), e.getMessage(), e);
adminEventBroadcaster.broadcastAdminEvent("Error processing book file: " + bookFile.getFileName() + " - " + e.getMessage());
return Optional.empty();
}
}
private Optional<LibraryFile> findBestMainBookFile(List<LibraryFile> filesInDirectory, LibraryEntity libraryEntity) {
var defaultBookFormat = libraryEntity.getDefaultBookFormat();
return filesInDirectory.stream()
.filter(f -> f.getBookFileType() != null)
.min(Comparator.comparingInt(f -> {
BookFileType bookFileType = f.getBookFileType();
return bookFileType == defaultBookFormat
? -1
: bookFileType.ordinal();
}));
}
private void processAdditionalFiles(BookEntity existingBook, List<LibraryFile> filesInDirectory) {
for (LibraryFile file : filesInDirectory) {
Optional<BookFileExtension> extension = BookFileExtension.fromFileName(file.getFileName());
boolean isBook = extension.isPresent();
BookFileType bookType = extension.map(BookFileExtension::getType).orElse(null);
createAdditionalFileIfNotExists(existingBook, file, isBook, bookType);
}
}
private void createAdditionalFileIfNotExists(BookEntity bookEntity, LibraryFile file, boolean isBook, BookFileType bookType) {
Optional<BookFileEntity> existingFile = bookAdditionalFileRepository
.findByLibraryPath_IdAndFileSubPathAndFileName(
file.getLibraryPathEntity().getId(), file.getFileSubPath(), file.getFileName());
if (existingFile.isPresent()) {
log.debug("Additional file already exists: {}", file.getFileName());
return;
}
String hash = FileFingerprint.generateHash(file.getFullPath());
BookFileEntity additionalFile = BookFileEntity.builder()
.book(bookEntity)
.fileName(file.getFileName())
.fileSubPath(file.getFileSubPath())
.isBookFormat(isBook)
.bookType(bookType)
.fileSizeKb(FileUtils.getFileSizeInKb(file.getFullPath()))
.initialHash(hash)
.currentHash(hash)
.addedOn(java.time.Instant.now())
.build();
try {
log.debug("Creating additional file: {} (isBook: {}, type: {})", file.getFileName(), isBook, bookType);
bookAdditionalFileRepository.save(additionalFile);
log.debug("Successfully created additional file: {}", file.getFileName());
} catch (Exception e) {
bookEntity.getBookFiles().removeIf(a -> a.equals(additionalFile));
log.error("Error creating additional file {}: {}", file.getFileName(), e.getMessage(), e);
}
}
public record GetOrCreateBookResult(Optional<BookEntity> bookEntity, List<LibraryFile> remainingFiles) {
}
public record CreateBookResult(BookEntity bookEntity, LibraryFile libraryFile) {
}
}
@@ -1,85 +0,0 @@
package com.adityachandel.booklore.service.library;
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
import com.adityachandel.booklore.model.entity.LibraryEntity;
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
import com.adityachandel.booklore.model.enums.BookFileExtension;
import com.adityachandel.booklore.util.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.jspecify.annotations.NonNull;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.nio.file.FileVisitOption;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.Optional;
@Component
@Slf4j
public class LibraryFileHelper {
public List<LibraryFile> getLibraryFiles(LibraryEntity libraryEntity, LibraryFileProcessor processor) throws IOException {
List<LibraryFile> allFiles = new ArrayList<>();
for (LibraryPathEntity pathEntity : libraryEntity.getLibraryPaths()) {
allFiles.addAll(findLibraryFiles(pathEntity, libraryEntity, processor));
}
return allFiles;
}
private List<LibraryFile> findLibraryFiles(LibraryPathEntity pathEntity, LibraryEntity libraryEntity, LibraryFileProcessor processor) throws IOException {
Path libraryPath = Path.of(pathEntity.getPath());
boolean supportsSupplementaryFiles = processor.supportsSupplementaryFiles();
List<LibraryFile> libraryFiles = new ArrayList<>();
Files.walkFileTree(libraryPath, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, new SimpleFileVisitor<>() {
@Override
@NonNull
public FileVisitResult visitFile(@NonNull Path file, @NonNull BasicFileAttributes attrs) {
if (FileUtils.shouldIgnore(file) || !Files.isReadable(file) || !Files.isRegularFile(file)) {
return FileVisitResult.CONTINUE;
}
String fileName = file.getFileName().toString();
Optional<BookFileExtension> bookExtension = BookFileExtension.fromFileName(fileName);
if (bookExtension.isEmpty() && !supportsSupplementaryFiles) {
return FileVisitResult.CONTINUE;
}
libraryFiles.add(LibraryFile.builder()
.libraryEntity(libraryEntity)
.libraryPathEntity(pathEntity)
.fileSubPath(FileUtils.getRelativeSubPath(pathEntity.getPath(), file))
.fileName(fileName)
.bookFileType(bookExtension.map(BookFileExtension::getType).orElse(null))
.build());
return FileVisitResult.CONTINUE;
}
@Override
@NonNull
public FileVisitResult visitFileFailed(@NonNull Path file, IOException e) {
log.error("Failed read path [{}]: {}", file, e.getMessage(), e);
return FileVisitResult.CONTINUE;
}
@Override
@NonNull
public FileVisitResult preVisitDirectory(@NonNull Path dir, @NonNull BasicFileAttributes attrs) throws IOException {
if (FileUtils.shouldIgnore(dir) || !Files.isReadable(dir)) {
return FileVisitResult.SKIP_SUBTREE;
}
return super.preVisitDirectory(dir, attrs);
}
});
return libraryFiles;
}
}
@@ -1,22 +0,0 @@
package com.adityachandel.booklore.service.library;
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
import com.adityachandel.booklore.model.entity.LibraryEntity;
import java.util.List;
import com.adityachandel.booklore.model.enums.LibraryScanMode;
public interface LibraryFileProcessor {
LibraryScanMode getScanMode();
void processLibraryFiles(List<LibraryFile> libraryFiles, LibraryEntity libraryEntity);
/**
* Indicates whether this processor supports supplementary files (any file type)
* in addition to book files.
* @return true if supplementary files are supported, false otherwise
*/
default boolean supportsSupplementaryFiles() {
return false;
}
}
@@ -1,25 +0,0 @@
package com.adityachandel.booklore.service.library;
import com.adityachandel.booklore.model.entity.LibraryEntity;
import com.adityachandel.booklore.model.enums.LibraryScanMode;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
@Component
public class LibraryFileProcessorRegistry {
private final Map<LibraryScanMode, LibraryFileProcessor> processorMap;
public LibraryFileProcessorRegistry(List<LibraryFileProcessor> processors) {
this.processorMap = processors.stream()
.collect(Collectors.toMap(LibraryFileProcessor::getScanMode, Function.identity()));
}
public LibraryFileProcessor getProcessor(LibraryEntity libraryEntity) {
return processorMap.get(libraryEntity.getScanMode());
}
}
@@ -1,11 +0,0 @@
package com.adityachandel.booklore.service.metadata;
import com.adityachandel.booklore.model.dto.CoverImage;
import com.adityachandel.booklore.model.dto.request.CoverFetchRequest;
import java.util.List;
public interface BookCoverProvider {
List<CoverImage> getCovers(CoverFetchRequest request);
}
@@ -1,8 +0,0 @@
package com.adityachandel.booklore.service.metadata;
import com.adityachandel.booklore.model.dto.BookMetadata;
@FunctionalInterface
interface FieldValueExtractor {
String extract(BookMetadata metadata);
}
@@ -1,4 +0,0 @@
package com.adityachandel.booklore.service.metadata;
public class UserPermissionService {
}
@@ -1,14 +0,0 @@
package com.adityachandel.booklore.service.metadata.parser;
import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.dto.BookMetadata;
import com.adityachandel.booklore.model.dto.request.FetchMetadataRequest;
import java.util.List;
public interface BookParser {
List<BookMetadata> fetchMetadata(Book book, FetchMetadataRequest fetchMetadataRequest);
BookMetadata fetchTopMetadata(Book book, FetchMetadataRequest fetchMetadataRequest);
}
@@ -1,304 +0,0 @@
package com.adityachandel.booklore.service.metadata.writer;
import com.adityachandel.booklore.model.MetadataClearFlags;
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import com.adityachandel.booklore.model.dto.settings.MetadataPersistenceSettings;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.io.IOUtils;
import org.apache.pdfbox.io.RandomAccessReadBufferedFile;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
import org.apache.pdfbox.pdmodel.common.PDMetadata;
import org.apache.xmpbox.XMPMetadata;
import org.apache.xmpbox.schema.DublinCoreSchema;
import org.apache.xmpbox.xml.XmpSerializer;
import org.springframework.stereotype.Component;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Calendar;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
@Slf4j
@Component
@RequiredArgsConstructor
public class PdfMetadataWriter implements MetadataWriter {
private final AppSettingService appSettingService;
@Override
public void saveMetadataToFile(File file, BookMetadataEntity metadataEntity, String thumbnailUrl, MetadataClearFlags clear) {
if (!shouldSaveMetadataToFile(file)) {
return;
}
if (!file.exists() || !file.getName().toLowerCase().endsWith(".pdf")) {
log.warn("Invalid PDF file: {}", file.getAbsolutePath());
return;
}
Path filePath = file.toPath();
Path backupPath = null;
boolean backupCreated = false;
File tempFile = null;
try {
String prefix = "pdfBackup-" + UUID.randomUUID() + "-";
backupPath = Files.createTempFile(prefix, ".pdf");
Files.copy(filePath, backupPath, StandardCopyOption.REPLACE_EXISTING);
backupCreated = true;
} catch (IOException e) {
log.warn("Could not create PDF temp backup for {}: {}", file.getName(), e.getMessage());
}
try (RandomAccessReadBufferedFile randomAccessRead = new RandomAccessReadBufferedFile(file);
PDDocument pdf = Loader.loadPDF(randomAccessRead, IOUtils.createMemoryOnlyStreamCache())) {
pdf.setAllSecurityToBeRemoved(true);
applyMetadataToDocument(pdf, metadataEntity, clear);
tempFile = File.createTempFile("pdfmeta-", ".pdf");
// PDFBox 3.x saves in compressed mode by default
pdf.save(tempFile);
Files.move(tempFile.toPath(), filePath, StandardCopyOption.REPLACE_EXISTING);
log.info("Successfully embedded metadata into PDF: {}", file.getName());
} catch (Exception e) {
log.warn("Failed to write metadata to PDF {}: {}", file.getName(), e.getMessage(), e);
if (backupCreated) {
try {
Files.copy(backupPath, filePath, StandardCopyOption.REPLACE_EXISTING);
log.info("Restored PDF {} from temp backup after failure", file.getName());
} catch (IOException ex) {
log.error("Failed to restore PDF temp backup for {}: {}", file.getName(), ex.getMessage(), ex);
}
}
} finally {
if (tempFile != null && tempFile.exists()) {
tempFile.delete();
}
if (backupCreated) {
try {
Files.deleteIfExists(backupPath);
} catch (IOException e) {
log.warn("Could not delete PDF temp backup for {}: {}", file.getName(), e.getMessage());
}
}
}
}
@Override
public BookFileType getSupportedBookType() {
return BookFileType.PDF;
}
public boolean shouldSaveMetadataToFile(File pdfFile) {
MetadataPersistenceSettings.SaveToOriginalFile settings = appSettingService.getAppSettings().getMetadataPersistenceSettings().getSaveToOriginalFile();
MetadataPersistenceSettings.FormatSettings pdfSettings = settings.getPdf();
if (pdfSettings == null || !pdfSettings.isEnabled()) {
log.debug("PDF metadata writing is disabled. Skipping: {}", pdfFile.getName());
return false;
}
long fileSizeInMb = pdfFile.length() / (1024 * 1024);
if (fileSizeInMb > pdfSettings.getMaxFileSizeInMb()) {
log.info("PDF file {} ({} MB) exceeds max size limit ({} MB). Skipping metadata write.", pdfFile.getName(), fileSizeInMb, pdfSettings.getMaxFileSizeInMb());
return false;
}
return true;
}
private void applyMetadataToDocument(PDDocument pdf, BookMetadataEntity entity, MetadataClearFlags clear) {
PDDocumentInformation info = pdf.getDocumentInformation();
MetadataCopyHelper helper = new MetadataCopyHelper(entity);
helper.copyTitle(clear != null && clear.isTitle(), title -> info.setTitle(title != null ? title : ""));
helper.copyPublisher(clear != null && clear.isPublisher(), pub -> info.setProducer(pub != null ? pub : ""));
helper.copyAuthors(clear != null && clear.isAuthors(), authors -> info.setAuthor(authors != null ? String.join(", ", authors) : ""));
helper.copyCategories(clear != null && clear.isCategories(), cats -> info.setKeywords(cats != null ? String.join(", ", cats) : ""));
try {
XMPMetadata xmp = XMPMetadata.createXMPMetadata();
DublinCoreSchema dc = xmp.createAndAddDublinCoreSchema();
helper.copyTitle(clear != null && clear.isTitle(), title -> dc.setTitle(title != null ? title : ""));
helper.copyDescription(clear != null && clear.isDescription(), desc -> dc.setDescription(desc != null ? desc : ""));
helper.copyPublisher(clear != null && clear.isPublisher(), pub -> dc.addPublisher(pub != null ? pub : ""));
helper.copyLanguage(clear != null && clear.isLanguage(), lang -> dc.addLanguage(lang != null ? lang : ""));
helper.copyPublishedDate(clear != null && clear.isPublishedDate(), date -> {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis((date != null ? date : ZonedDateTime.now().toLocalDate())
.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli());
dc.addDate(cal);
});
helper.copyAuthors(clear != null && clear.isAuthors(), authors -> (authors != null ? authors : List.of("")).forEach(dc::addCreator));
helper.copyCategories(clear != null && clear.isCategories(), cats -> (cats != null ? cats : List.of("")).forEach(dc::addSubject));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
new XmpSerializer().serialize(xmp, baos, true);
byte[] baseXmpBytes = baos.toByteArray();
byte[] newXmpBytes = addCustomIdentifiersToXmp(baseXmpBytes, entity, helper, clear);
byte[] existingXmpBytes = null;
PDMetadata existingMetadata = pdf.getDocumentCatalog().getMetadata();
if (existingMetadata != null) {
try {
existingXmpBytes = existingMetadata.toByteArray();
} catch (IOException ignore) {
}
}
if (!isXmpMetadataDifferent(existingXmpBytes, newXmpBytes)) {
log.info("XMP metadata unchanged, skipping write");
return;
}
PDMetadata pdMetadata = new PDMetadata(pdf);
pdMetadata.importXMPMetadata(newXmpBytes);
pdf.getDocumentCatalog().setMetadata(pdMetadata);
log.info("XMP metadata updated for PDF");
} catch (Exception e) {
log.warn("Failed to embed XMP metadata: {}", e.getMessage(), e);
}
}
private byte[] addCustomIdentifiersToXmp(byte[] xmpBytes, BookMetadataEntity metadata, MetadataCopyHelper helper, MetadataClearFlags clear) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new ByteArrayInputStream(xmpBytes));
Element rdfRoot = (Element) doc.getElementsByTagNameNS("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "RDF").item(0);
if (rdfRoot == null) throw new IllegalStateException("RDF root missing in XMP");
Element rdfDescription = doc.createElementNS("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "rdf:Description");
rdfDescription.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xmp", "http://ns.adobe.com/xap/1.0/");
rdfDescription.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xmpidq", "http://ns.adobe.com/xmp/Identifier/qual/1.0/");
rdfDescription.setAttributeNS("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "rdf:about", "");
Element xmpIdentifier = doc.createElementNS("http://ns.adobe.com/xap/1.0/", "xmp:Identifier");
Element rdfBag = doc.createElementNS("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "rdf:Bag");
helper.copyGoogleId(clear != null && clear.isGoogleId(), id -> appendIdentifier(doc, rdfBag, "google", id != null ? id : ""));
helper.copyGoodreadsId(clear != null && clear.isGoodreadsId(), id -> appendIdentifier(doc, rdfBag, "goodreads", id != null ? id : ""));
helper.copyComicvineId(clear != null && clear.isComicvineId(), id -> appendIdentifier(doc, rdfBag, "comicvine", id != null ? id : ""));
helper.copyHardcoverId(clear != null && clear.isHardcoverId(), id -> appendIdentifier(doc, rdfBag, "hardcover", id != null ? id : ""));
helper.copyRanobedbId(clear != null && clear.isRanobedbId(), id -> appendIdentifier(doc, rdfBag, "ranobedb", id != null ? id : ""));
helper.copyAsin(clear != null && clear.isAsin(), id -> appendIdentifier(doc, rdfBag, "amazon", id != null ? id : ""));
helper.copyIsbn13(clear != null && clear.isIsbn13(), id -> appendIdentifier(doc, rdfBag, "isbn", id != null ? id : ""));
if (rdfBag.hasChildNodes()) {
xmpIdentifier.appendChild(rdfBag);
rdfDescription.appendChild(xmpIdentifier);
}
rdfDescription.appendChild(createSimpleElement(doc, "xmp:MetadataDate", ZonedDateTime.now().toString()));
rdfDescription.appendChild(createSimpleElement(doc, "xmp:CreateDate", metadata.getPublishedDate() != null
? metadata.getPublishedDate().atStartOfDay(ZoneId.systemDefault()).toString()
: ZonedDateTime.now().toString()));
rdfDescription.appendChild(createSimpleElement(doc, "xmp:CreatorTool", "Booklore"));
rdfDescription.appendChild(createSimpleElement(doc, "xmp:ModifyDate", ZonedDateTime.now().toString()));
rdfRoot.appendChild(rdfDescription);
Element calibreDescription = doc.createElementNS("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "rdf:Description");
calibreDescription.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:calibre", "http://calibre-ebook.com/xmp-namespace");
calibreDescription.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:calibreSI", "http://calibre-ebook.com/xmp-namespace-series-index");
calibreDescription.setAttributeNS("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "rdf:about", "");
helper.copySeriesName(clear != null && clear.isSeriesName(), series -> {
Element seriesElem = doc.createElementNS("http://calibre-ebook.com/xmp-namespace", "calibre:series");
seriesElem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:calibreSI", "http://calibre-ebook.com/xmp-namespace-series-index");
seriesElem.setAttributeNS("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "rdf:parseType", "Resource");
Element valueElem = doc.createElementNS("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "rdf:value");
valueElem.setTextContent(series != null ? series : "");
seriesElem.appendChild(valueElem);
helper.copySeriesNumber(clear != null && clear.isSeriesNumber(), index -> {
Element indexElem = doc.createElementNS("http://calibre-ebook.com/xmp-namespace-series-index", "calibreSI:series_index");
indexElem.setTextContent(index != null ? String.format("%.2f", index) : "0.00");
seriesElem.appendChild(indexElem);
});
calibreDescription.appendChild(seriesElem);
});
rdfRoot.appendChild(calibreDescription);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Transformer tf = TransformerFactory.newInstance().newTransformer();
tf.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
tf.setOutputProperty(OutputKeys.INDENT, "yes");
tf.transform(new DOMSource(doc), new StreamResult(baos));
return baos.toByteArray();
}
private void appendIdentifier(Document doc, Element bag, String scheme, String value) {
if (StringUtils.isBlank(value)) return;
Element li = doc.createElementNS("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "rdf:li");
li.setAttributeNS("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "rdf:parseType", "Resource");
Element schemeElem = doc.createElementNS("http://ns.adobe.com/xmp/Identifier/qual/1.0/", "xmpidq:Scheme");
schemeElem.setTextContent(scheme);
Element valueElem = doc.createElementNS("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "rdf:value");
valueElem.setTextContent(value);
li.appendChild(schemeElem);
li.appendChild(valueElem);
bag.appendChild(li);
}
private Element createSimpleElement(Document doc, String name, String content) {
String namespace = name.startsWith("calibre:")
? "http://calibre-ebook.com/xmp-namespace"
: "http://ns.adobe.com/xap/1.0/";
Element el = doc.createElementNS(namespace, name);
el.setTextContent(content);
return el;
}
private boolean isXmpMetadataDifferent(byte[] existingBytes, byte[] newBytes) {
if (existingBytes == null || newBytes == null) return true;
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc1 = builder.parse(new ByteArrayInputStream(existingBytes));
Document doc2 = builder.parse(new ByteArrayInputStream(newBytes));
return !Objects.equals(
doc1.getDocumentElement().getTextContent().trim(),
doc2.getDocumentElement().getTextContent().trim()
);
} catch (Exception e) {
log.warn("XMP diff failed: {}", e.getMessage());
return true;
}
}
}
@@ -1,22 +0,0 @@
package com.adityachandel.booklore.service.user;
import com.adityachandel.booklore.model.entity.UserBookProgressEntity;
import com.adityachandel.booklore.repository.UserBookProgressRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
@RequiredArgsConstructor
@Service
public class UserProgressService {
private final UserBookProgressRepository userBookProgressRepository;
public Map<Long, UserBookProgressEntity> fetchUserProgress(Long userId, Set<Long> bookIds) {
return userBookProgressRepository.findByUserIdAndBookIdIn(userId, bookIds).stream()
.collect(Collectors.toMap(p -> p.getBook().getId(), p -> p));
}
}
@@ -1,63 +0,0 @@
package com.adityachandel.booklore.service.watcher;
import com.adityachandel.booklore.exception.ApiError;
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
import com.adityachandel.booklore.model.entity.LibraryEntity;
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
import com.adityachandel.booklore.model.enums.BookFileExtension;
import com.adityachandel.booklore.model.websocket.LogNotification;
import com.adityachandel.booklore.model.websocket.Topic;
import com.adityachandel.booklore.repository.LibraryRepository;
import com.adityachandel.booklore.service.NotificationService;
import com.adityachandel.booklore.service.library.LibraryProcessingService;
import com.adityachandel.booklore.util.FileUtils;
import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.nio.file.Path;
import java.util.List;
import java.util.Set;
import static com.adityachandel.booklore.model.enums.PermissionType.ADMIN;
import static com.adityachandel.booklore.model.enums.PermissionType.MANAGE_LIBRARY;
@Slf4j
@Service
@RequiredArgsConstructor
public class BookFileTransactionalHandler {
private final BookFilePersistenceService bookFilePersistenceService;
private final LibraryProcessingService libraryProcessingService;
private final NotificationService notificationService;
private final LibraryRepository libraryRepository;
@Transactional()
public void handleNewBookFile(long libraryId, Path path) {
LibraryEntity libraryEntity = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
String filePath = path.toString();
String fileName = path.getFileName().toString();
String libraryPath = bookFilePersistenceService.findMatchingLibraryPath(libraryEntity, path);
notificationService.sendMessageToPermissions(Topic.LOG, LogNotification.info("Started processing file: " + filePath), Set.of(ADMIN, MANAGE_LIBRARY));
LibraryPathEntity libraryPathEntity = bookFilePersistenceService.getLibraryPathEntityForFile(libraryEntity, libraryPath);
LibraryFile libraryFile = LibraryFile.builder()
.libraryEntity(libraryEntity)
.libraryPathEntity(libraryPathEntity)
.fileSubPath(FileUtils.getRelativeSubPath(libraryPathEntity.getPath(), path))
.fileName(fileName)
.bookFileType(BookFileExtension.fromFileName(fileName)
.map(BookFileExtension::getType)
.orElseThrow(() -> new IllegalArgumentException("Unsupported book file type: " + fileName)))
.build();
libraryProcessingService.processLibraryFiles(List.of(libraryFile), libraryEntity);
notificationService.sendMessageToPermissions(Topic.LOG, LogNotification.info("Finished processing file: " + filePath), Set.of(ADMIN, MANAGE_LIBRARY));
log.info("[CREATE] Completed processing for file '{}'", filePath);
}
}
@@ -1,194 +0,0 @@
package com.adityachandel.booklore.service.watcher;
import com.adityachandel.booklore.exception.ApiError;
import com.adityachandel.booklore.model.entity.LibraryEntity;
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
import com.adityachandel.booklore.model.enums.BookFileExtension;
import com.adityachandel.booklore.model.enums.PermissionType;
import com.adityachandel.booklore.model.websocket.Topic;
import com.adityachandel.booklore.repository.LibraryRepository;
import com.adityachandel.booklore.service.NotificationService;
import com.adityachandel.booklore.util.FileUtils;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.nio.file.*;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.*;
@Slf4j
@Service
@AllArgsConstructor
public class LibraryFileEventProcessor {
private static final long DEBOUNCE_MS = 500L;
private final BlockingQueue<FileEvent> eventQueue = new LinkedBlockingQueue<>();
private final LibraryRepository libraryRepository;
private final BookFileTransactionalHandler bookFileTransactionalHandler;
private final BookFilePersistenceService bookFilePersistenceService;
private final NotificationService notificationService;
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
private final ConcurrentMap<Path, ScheduledFuture<?>> pendingDeletes = new ConcurrentHashMap<>();
@PostConstruct
public void init() {
Thread.ofVirtual().start(() -> {
log.info("LibraryFileEventProcessor virtual thread started.");
while (!Thread.currentThread().isInterrupted()) {
try {
handleEvent(eventQueue.take());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.warn("LibraryFileEventProcessor virtual thread interrupted.");
} catch (Exception e) {
log.error("Error while processing file event", e);
}
}
});
}
public void processFile(WatchEvent.Kind<?> eventKind, long libraryId, String libraryPath, String filePath) {
Path path = Paths.get(filePath).toAbsolutePath().normalize();
if (eventKind == StandardWatchEventKinds.ENTRY_DELETE) {
// Schedule DELETE after debounce
ScheduledFuture<?> existing = pendingDeletes.put(path, scheduler.schedule(() -> {
eventQueue.offer(new FileEvent(eventKind, libraryId, libraryPath, filePath));
pendingDeletes.remove(path);
}, DEBOUNCE_MS, TimeUnit.MILLISECONDS));
if (existing != null) existing.cancel(false);
} else if (eventKind == StandardWatchEventKinds.ENTRY_CREATE) {
// If a DELETE is pending for this path, cancel both DELETE and CREATE
ScheduledFuture<?> pendingDelete = pendingDeletes.remove(path);
if (pendingDelete != null) {
pendingDelete.cancel(false);
log.debug("[DEBOUNCE] CREATE ignored because pending DELETE exists for '{}'", path);
return;
}
// Otherwise process CREATE immediately
eventQueue.offer(new FileEvent(eventKind, libraryId, libraryPath, filePath));
} else {
// Other events
eventQueue.offer(new FileEvent(eventKind, libraryId, libraryPath, filePath));
}
}
private void handleEvent(FileEvent event) {
Path path = Paths.get(event.filePath()).toAbsolutePath().normalize();
String fileName = path.getFileName().toString();
log.info("[PROCESS] '{}' event for '{}'", event.eventKind().name(), fileName);
LibraryEntity library = libraryRepository.findById(event.libraryId())
.orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(event.libraryId()));
if (library.getLibraryPaths().stream().noneMatch(lp -> path.startsWith(lp.getPath()))) {
log.warn("[SKIP] Path outside of library: '{}'", path);
return;
}
if (isFolder(path)) {
switch (event.eventKind().name()) {
case "ENTRY_CREATE" -> handleFolderCreate(library, path);
case "ENTRY_DELETE" -> handleFolderDelete(library, path);
default -> log.warn("[SKIP] Folder event '{}' ignored for '{}'", event.eventKind().name(), fileName);
}
return;
}
if (!isBookFile(fileName)) {
log.debug("[SKIP] Ignored non-book file '{}'", fileName);
return;
}
switch (event.eventKind().name()) {
case "ENTRY_CREATE" -> handleFileCreate(library, path);
case "ENTRY_DELETE" -> handleFileDelete(library, path);
default -> log.debug("[SKIP] File event '{}' ignored for '{}'", event.eventKind().name(), fileName);
}
}
private void handleFileCreate(LibraryEntity library, Path path) {
log.info("[FILE_CREATE] '{}'", path);
bookFileTransactionalHandler.handleNewBookFile(library.getId(), path);
}
private void handleFileDelete(LibraryEntity library, Path path) {
log.info("[FILE_DELETE] '{}'", path);
try {
String libPath = bookFilePersistenceService.findMatchingLibraryPath(library, path);
LibraryPathEntity libPathEntity = bookFilePersistenceService.getLibraryPathEntityForFile(library, libPath);
Path relPath = Paths.get(libPathEntity.getPath()).relativize(path);
String fileName = relPath.getFileName().toString();
String fileSubPath = Optional.ofNullable(relPath.getParent()).map(Path::toString).orElse("");
bookFilePersistenceService.findByLibraryPathSubPathAndFileName(libPathEntity.getId(), fileSubPath, fileName)
.ifPresentOrElse(book -> {
book.setDeleted(true);
bookFilePersistenceService.save(book);
notificationService.sendMessageToPermissions(Topic.BOOKS_REMOVE, Set.of(book.getId()),
Set.of(PermissionType.ADMIN, PermissionType.MANAGE_LIBRARY));
log.info("[MARKED_DELETED] Book '{}' marked as deleted", fileName);
}, () -> log.warn("[NOT_FOUND] Book for deleted path '{}' not found", path));
} catch (Exception e) {
log.warn("[ERROR] While handling file delete '{}': {}", path, e.getMessage());
}
}
private void handleFolderCreate(LibraryEntity library, Path folderPath) {
log.info("[FOLDER_CREATE] '{}'", folderPath);
try (var stream = Files.walk(folderPath)) {
stream.filter(Files::isRegularFile)
.filter(p -> isBookFile(p.getFileName().toString()))
.forEach(p -> {
try {
bookFileTransactionalHandler.handleNewBookFile(library.getId(), p);
} catch (Exception e) {
log.warn("[ERROR] Processing file '{}': {}", p, e.getMessage());
}
});
} catch (IOException e) {
log.warn("[ERROR] Walking folder '{}': {}", folderPath, e.getMessage());
}
}
private void handleFolderDelete(LibraryEntity library, Path folderPath) {
log.info("[FOLDER_DELETE] '{}'", folderPath);
try {
String libPath = bookFilePersistenceService.findMatchingLibraryPath(library, folderPath);
LibraryPathEntity libPathEntity = bookFilePersistenceService.getLibraryPathEntityForFile(library, libPath);
String relativePrefix = FileUtils.getRelativeSubPath(libPathEntity.getPath(), folderPath);
int count = bookFilePersistenceService.markAllBooksUnderPathAsDeleted(libPathEntity.getId(), relativePrefix);
log.info("[MARKED_DELETED] {} books under '{}'", count, folderPath);
} catch (Exception e) {
log.warn("[ERROR] Folder delete '{}': {}", folderPath, e.getMessage());
}
}
private boolean isFolder(Path path) {
return !path.getFileName().toString().contains(".");
}
private boolean isBookFile(String fileName) {
return BookFileExtension.fromFileName(fileName).isPresent();
}
@PreDestroy
public void shutdown() {
scheduler.shutdownNow();
log.info("Shutting down LibraryFileEventProcessor...");
}
public record FileEvent(WatchEvent.Kind<?> eventKind, long libraryId, String libraryPath, String filePath) {
}
}
@@ -1,19 +0,0 @@
package com.adityachandel.booklore.task.tasks;
import com.adityachandel.booklore.model.dto.BookLoreUser;
import com.adityachandel.booklore.model.dto.request.TaskCreateRequest;
import com.adityachandel.booklore.model.dto.response.TaskCreateResponse;
import com.adityachandel.booklore.model.enums.TaskType;
public interface Task {
TaskCreateResponse execute(TaskCreateRequest request);
TaskType getTaskType();
default String getMetadata() {
return null;
}
void validatePermissions(BookLoreUser user, TaskCreateRequest request);
}
@@ -1,58 +0,0 @@
package com.adityachandel.booklore.util;
import com.adityachandel.booklore.model.dto.*;
import com.adityachandel.booklore.model.dto.progress.*;
import com.adityachandel.booklore.model.entity.UserBookProgressEntity;
import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.model.enums.ReadStatus;
public class BookProgressUtil {
public static void setBookProgress(Book book, UserBookProgressEntity progress) {
if (progress.getKoboProgressPercent() != null) {
book.setKoboProgress(KoboProgress.builder()
.percentage(progress.getKoboProgressPercent())
.build());
}
BookFileType type = book.getBookType();
if (type == null) return;
switch (type) {
case EPUB -> {
book.setEpubProgress(EpubProgress.builder()
.cfi(progress.getEpubProgress())
.href(progress.getEpubProgressHref())
.percentage(progress.getEpubProgressPercent())
.build());
book.setKoreaderProgress(KoProgress.builder()
.percentage(progress.getKoreaderProgressPercent() != null ? progress.getKoreaderProgressPercent() * 100 : null)
.build());
}
case FB2, MOBI, AZW3 -> book.setEpubProgress(EpubProgress.builder()
.cfi(progress.getEpubProgress())
.href(progress.getEpubProgressHref())
.percentage(progress.getEpubProgressPercent())
.build());
case PDF -> book.setPdfProgress(PdfProgress.builder()
.page(progress.getPdfProgress())
.percentage(progress.getPdfProgressPercent())
.build());
case CBX -> book.setCbxProgress(CbxProgress.builder()
.page(progress.getCbxProgress())
.percentage(progress.getCbxProgressPercent())
.build());
}
}
public static void enrichBookWithProgress(Book book, UserBookProgressEntity progress) {
if (progress != null) {
setBookProgress(book, progress);
book.setLastReadTime(progress.getLastReadTime());
book.setReadStatus(progress.getReadStatus() == null ? String.valueOf(ReadStatus.UNSET) : String.valueOf(progress.getReadStatus()));
book.setDateFinished(progress.getDateFinished());
book.setPersonalRating(progress.getPersonalRating());
}
}
}
@@ -1,107 +0,0 @@
package com.adityachandel.booklore.util;
import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.BookFileEntity;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import com.adityachandel.booklore.model.entity.BookEntity;
@UtilityClass
@Slf4j
public class FileUtils {
private final String FILE_NOT_FOUND_MESSAGE = "File does not exist: ";
public String getBookFullPath(BookEntity bookEntity) {
BookFileEntity bookFile = bookEntity.getPrimaryBookFile();
return Path.of(bookEntity.getLibraryPath().getPath(), bookFile.getFileSubPath(), bookFile.getFileName())
.normalize()
.toString()
.replace("\\", "/");
}
public String getBookFullPath(Book book) {
return Path.of(book.getLibraryPath().getPath(), book.getFileSubPath(), book.getFileName())
.normalize()
.toString()
.replace("\\", "/");
}
public String getRelativeSubPath(String basePath, Path fullFilePath) {
return Optional.ofNullable(Path.of(basePath)
.relativize(fullFilePath)
.getParent())
.map(path -> path.toString().replace("\\", "/"))
.orElse("");
}
public Long getFileSizeInKb(BookEntity bookEntity) {
Path filePath = Path.of(getBookFullPath(bookEntity));
return getFileSizeInKb(filePath);
}
public Long getFileSizeInKb(Path filePath) {
try {
if (!Files.exists(filePath)) {
log.warn(FILE_NOT_FOUND_MESSAGE + "{}", filePath.toAbsolutePath());
return null;
}
return Files.size(filePath) / 1024;
} catch (IOException e) {
log.error("Failed to get file size for path [{}]: {}", filePath, e.getMessage(), e);
return null;
}
}
public void deleteDirectoryRecursively(Path path) throws IOException {
if (!Files.exists(path)) return;
try (var walk = Files.walk(path)) {
walk.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.forEach(File::delete);
}
}
public String getExtension(String fileName) {
if (fileName == null) {
return "";
}
int i = fileName.lastIndexOf('.');
if (i >= 0 && i < fileName.length() - 1) {
return fileName.substring(i + 1);
}
return "";
}
final private List<String> systemDirs = Arrays.asList(
// synology
"#recycle",
"@eaDir",
// calibre
".caltrash"
);
public boolean shouldIgnore(Path path) {
if (!path.getFileName().toString().isEmpty() && path.getFileName().toString().charAt(0) == '.') {
return true;
}
for (Path part : path) {
if (systemDirs.contains(part.toString())) {
return true;
}
}
return false;
}
}
@@ -1,212 +0,0 @@
package com.adityachandel.booklore.util;
import com.adityachandel.booklore.model.MetadataClearFlags;
import com.adityachandel.booklore.model.dto.BookMetadata;
import com.adityachandel.booklore.model.entity.*;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import java.util.*;
import java.util.function.BooleanSupplier;
import java.util.stream.Collectors;
import static org.apache.commons.lang3.BooleanUtils.isTrue;
@UtilityClass
@Slf4j
public class MetadataChangeDetector {
public static boolean isDifferent(BookMetadata newMeta, BookMetadataEntity existingMeta, MetadataClearFlags clear) {
if (clear == null) return true;
List<String> changes = new ArrayList<>();
compare(changes, "title", clear.isTitle(), newMeta.getTitle(), existingMeta.getTitle(), () -> !isTrue(existingMeta.getTitleLocked()), newMeta.getTitleLocked(), existingMeta.getTitleLocked());
compare(changes, "subtitle", clear.isSubtitle(), newMeta.getSubtitle(), existingMeta.getSubtitle(), () -> !isTrue(existingMeta.getSubtitleLocked()), newMeta.getSubtitleLocked(), existingMeta.getSubtitleLocked());
compare(changes, "publisher", clear.isPublisher(), newMeta.getPublisher(), existingMeta.getPublisher(), () -> !isTrue(existingMeta.getPublisherLocked()), newMeta.getPublisherLocked(), existingMeta.getPublisherLocked());
compare(changes, "publishedDate", clear.isPublishedDate(), newMeta.getPublishedDate(), existingMeta.getPublishedDate(), () -> !isTrue(existingMeta.getPublishedDateLocked()), newMeta.getPublishedDateLocked(), existingMeta.getPublishedDateLocked());
compare(changes, "description", clear.isDescription(), newMeta.getDescription(), existingMeta.getDescription(), () -> !isTrue(existingMeta.getDescriptionLocked()), newMeta.getDescriptionLocked(), existingMeta.getDescriptionLocked());
compare(changes, "seriesName", clear.isSeriesName(), newMeta.getSeriesName(), existingMeta.getSeriesName(), () -> !isTrue(existingMeta.getSeriesNameLocked()), newMeta.getSeriesNameLocked(), existingMeta.getSeriesNameLocked());
compare(changes, "seriesNumber", clear.isSeriesNumber(), newMeta.getSeriesNumber(), existingMeta.getSeriesNumber(), () -> !isTrue(existingMeta.getSeriesNumberLocked()), newMeta.getSeriesNumberLocked(), existingMeta.getSeriesNumberLocked());
compare(changes, "seriesTotal", clear.isSeriesTotal(), newMeta.getSeriesTotal(), existingMeta.getSeriesTotal(), () -> !isTrue(existingMeta.getSeriesTotalLocked()), newMeta.getSeriesTotalLocked(), existingMeta.getSeriesTotalLocked());
compare(changes, "isbn13", clear.isIsbn13(), newMeta.getIsbn13(), existingMeta.getIsbn13(), () -> !isTrue(existingMeta.getIsbn13Locked()), newMeta.getIsbn13Locked(), existingMeta.getIsbn13Locked());
compare(changes, "isbn10", clear.isIsbn10(), newMeta.getIsbn10(), existingMeta.getIsbn10(), () -> !isTrue(existingMeta.getIsbn10Locked()), newMeta.getIsbn10Locked(), existingMeta.getIsbn10Locked());
compare(changes, "asin", clear.isAsin(), newMeta.getAsin(), existingMeta.getAsin(), () -> !isTrue(existingMeta.getAsinLocked()), newMeta.getAsinLocked(), existingMeta.getAsinLocked());
compare(changes, "goodreadsId", clear.isGoodreadsId(), newMeta.getGoodreadsId(), existingMeta.getGoodreadsId(), () -> !isTrue(existingMeta.getGoodreadsIdLocked()), newMeta.getGoodreadsIdLocked(), existingMeta.getGoodreadsIdLocked());
compare(changes, "comicvineId", clear.isComicvineId(), newMeta.getComicvineId(), existingMeta.getComicvineId(), () -> !isTrue(existingMeta.getComicvineIdLocked()), newMeta.getComicvineIdLocked(), existingMeta.getComicvineIdLocked());
compare(changes, "hardcoverId", clear.isHardcoverId(), newMeta.getHardcoverId(), existingMeta.getHardcoverId(), () -> !isTrue(existingMeta.getHardcoverIdLocked()), newMeta.getHardcoverIdLocked(), existingMeta.getHardcoverIdLocked());
compare(changes, "hardcoverBookId", clear.isHardcoverBookId(), newMeta.getHardcoverBookId(), existingMeta.getHardcoverBookId(), () -> !isTrue(existingMeta.getHardcoverBookIdLocked()), newMeta.getHardcoverBookIdLocked(), existingMeta.getHardcoverBookIdLocked());
compare(changes, "googleId", clear.isGoogleId(), newMeta.getGoogleId(), existingMeta.getGoogleId(), () -> !isTrue(existingMeta.getGoogleIdLocked()), newMeta.getGoogleIdLocked(), existingMeta.getGoogleIdLocked());
compare(changes, "pageCount", clear.isPageCount(), newMeta.getPageCount(), existingMeta.getPageCount(), () -> !isTrue(existingMeta.getPageCountLocked()), newMeta.getPageCountLocked(), existingMeta.getPageCountLocked());
compare(changes, "language", clear.isLanguage(), newMeta.getLanguage(), existingMeta.getLanguage(), () -> !isTrue(existingMeta.getLanguageLocked()), newMeta.getLanguageLocked(), existingMeta.getLanguageLocked());
compare(changes, "amazonRating", clear.isAmazonRating(), newMeta.getAmazonRating(), existingMeta.getAmazonRating(), () -> !isTrue(existingMeta.getAmazonRatingLocked()), newMeta.getAmazonRatingLocked(), existingMeta.getAmazonRatingLocked());
compare(changes, "amazonReviewCount", clear.isAmazonReviewCount(), newMeta.getAmazonReviewCount(), existingMeta.getAmazonReviewCount(), () -> !isTrue(existingMeta.getAmazonReviewCountLocked()), newMeta.getAmazonReviewCountLocked(), existingMeta.getAmazonReviewCountLocked());
compare(changes, "goodreadsRating", clear.isGoodreadsRating(), newMeta.getGoodreadsRating(), existingMeta.getGoodreadsRating(), () -> !isTrue(existingMeta.getGoodreadsRatingLocked()), newMeta.getGoodreadsRatingLocked(), existingMeta.getGoodreadsRatingLocked());
compare(changes, "goodreadsReviewCount", clear.isGoodreadsReviewCount(), newMeta.getGoodreadsReviewCount(), existingMeta.getGoodreadsReviewCount(), () -> !isTrue(existingMeta.getGoodreadsReviewCountLocked()), newMeta.getGoodreadsReviewCountLocked(), existingMeta.getGoodreadsReviewCountLocked());
compare(changes, "hardcoverRating", clear.isHardcoverRating(), newMeta.getHardcoverRating(), existingMeta.getHardcoverRating(), () -> !isTrue(existingMeta.getHardcoverRatingLocked()), newMeta.getHardcoverRatingLocked(), existingMeta.getHardcoverRatingLocked());
compare(changes, "hardcoverReviewCount", clear.isHardcoverReviewCount(), newMeta.getHardcoverReviewCount(), existingMeta.getHardcoverReviewCount(), () -> !isTrue(existingMeta.getHardcoverReviewCountLocked()), newMeta.getHardcoverReviewCountLocked(), existingMeta.getHardcoverReviewCountLocked());
compare(changes, "lubimyczytacId", clear.isLubimyczytacId(), newMeta.getLubimyczytacId(), existingMeta.getLubimyczytacId(), () -> !isTrue(existingMeta.getLubimyczytacIdLocked()), newMeta.getLubimyczytacIdLocked(), existingMeta.getLubimyczytacIdLocked());
compare(changes, "lubimyczytacRating", clear.isLubimyczytacRating(), newMeta.getLubimyczytacRating(), existingMeta.getLubimyczytacRating(), () -> !isTrue(existingMeta.getLubimyczytacRatingLocked()), newMeta.getLubimyczytacRatingLocked(), existingMeta.getLubimyczytacRatingLocked());
compare(changes, "ranobedbId", clear.isRanobedbId(), newMeta.getRanobedbId(), existingMeta.getRanobedbId(), () -> !isTrue(existingMeta.getRanobedbIdLocked()), newMeta.getRanobedbIdLocked(), existingMeta.getRanobedbIdLocked());
compare(changes, "ranobedbRating", clear.isRanobedbRating(), newMeta.getRanobedbRating(), existingMeta.getRanobedbRating(), () -> !isTrue(existingMeta.getRanobedbRatingLocked()), newMeta.getRanobedbRatingLocked(), existingMeta.getRanobedbRatingLocked());
compare(changes, "authors", clear.isAuthors(), newMeta.getAuthors(), toNameSet(existingMeta.getAuthors()), () -> !isTrue(existingMeta.getAuthorsLocked()), newMeta.getAuthorsLocked(), existingMeta.getAuthorsLocked());
compare(changes, "categories", clear.isCategories(), newMeta.getCategories(), toNameSet(existingMeta.getCategories()), () -> !isTrue(existingMeta.getCategoriesLocked()), newMeta.getCategoriesLocked(), existingMeta.getCategoriesLocked());
compare(changes, "moods", clear.isMoods(), newMeta.getMoods(), toNameSet(existingMeta.getMoods()), () -> !isTrue(existingMeta.getMoodsLocked()), newMeta.getMoodsLocked(), existingMeta.getMoodsLocked());
compare(changes, "tags", clear.isTags(), newMeta.getTags(), toNameSet(existingMeta.getTags()), () -> !isTrue(existingMeta.getTagsLocked()), newMeta.getTagsLocked(), existingMeta.getTagsLocked());
Boolean coverLockedNew = newMeta.getCoverLocked();
Boolean coverLockedExisting = existingMeta.getCoverLocked();
if (differsLock(coverLockedNew, coverLockedExisting)) {
changes.add("cover lock: [" + isTrue(coverLockedExisting) + "] → [" + isTrue(coverLockedNew) + "]");
}
/*changes.forEach(change -> log.info("Metadata change: {}", change));*/
return !changes.isEmpty();
}
public static boolean hasValueChanges(BookMetadata newMeta, BookMetadataEntity existingMeta, MetadataClearFlags clear) {
List<String> diffs = new ArrayList<>();
compareValue(diffs, "title", clear.isTitle(), newMeta.getTitle(), existingMeta.getTitle(), () -> !isTrue(existingMeta.getTitleLocked()));
compareValue(diffs, "subtitle", clear.isSubtitle(), newMeta.getSubtitle(), existingMeta.getSubtitle(), () -> !isTrue(existingMeta.getSubtitleLocked()));
compareValue(diffs, "publisher", clear.isPublisher(), newMeta.getPublisher(), existingMeta.getPublisher(), () -> !isTrue(existingMeta.getPublisherLocked()));
compareValue(diffs, "publishedDate", clear.isPublishedDate(), newMeta.getPublishedDate(), existingMeta.getPublishedDate(), () -> !isTrue(existingMeta.getPublishedDateLocked()));
compareValue(diffs, "description", clear.isDescription(), newMeta.getDescription(), existingMeta.getDescription(), () -> !isTrue(existingMeta.getDescriptionLocked()));
compareValue(diffs, "seriesName", clear.isSeriesName(), newMeta.getSeriesName(), existingMeta.getSeriesName(), () -> !isTrue(existingMeta.getSeriesNameLocked()));
compareValue(diffs, "seriesNumber", clear.isSeriesNumber(), newMeta.getSeriesNumber(), existingMeta.getSeriesNumber(), () -> !isTrue(existingMeta.getSeriesNumberLocked()));
compareValue(diffs, "seriesTotal", clear.isSeriesTotal(), newMeta.getSeriesTotal(), existingMeta.getSeriesTotal(), () -> !isTrue(existingMeta.getSeriesTotalLocked()));
compareValue(diffs, "isbn13", clear.isIsbn13(), newMeta.getIsbn13(), existingMeta.getIsbn13(), () -> !isTrue(existingMeta.getIsbn13Locked()));
compareValue(diffs, "isbn10", clear.isIsbn10(), newMeta.getIsbn10(), existingMeta.getIsbn10(), () -> !isTrue(existingMeta.getIsbn10Locked()));
compareValue(diffs, "asin", clear.isAsin(), newMeta.getAsin(), existingMeta.getAsin(), () -> !isTrue(existingMeta.getAsinLocked()));
compareValue(diffs, "goodreadsId", clear.isGoodreadsId(), newMeta.getGoodreadsId(), existingMeta.getGoodreadsId(), () -> !isTrue(existingMeta.getGoodreadsIdLocked()));
compareValue(diffs, "comicvineId", clear.isComicvineId(), newMeta.getComicvineId(), existingMeta.getComicvineId(), () -> !isTrue(existingMeta.getComicvineIdLocked()));
compareValue(diffs, "hardcoverId", clear.isHardcoverId(), newMeta.getHardcoverId(), existingMeta.getHardcoverId(), () -> !isTrue(existingMeta.getHardcoverIdLocked()));
compareValue(diffs, "hardcoverBookId", clear.isHardcoverBookId(), newMeta.getHardcoverBookId(), existingMeta.getHardcoverBookId(), () -> !isTrue(existingMeta.getHardcoverBookIdLocked()));
compareValue(diffs, "googleId", clear.isGoogleId(), newMeta.getGoogleId(), existingMeta.getGoogleId(), () -> !isTrue(existingMeta.getGoogleIdLocked()));
compareValue(diffs, "pageCount", clear.isPageCount(), newMeta.getPageCount(), existingMeta.getPageCount(), () -> !isTrue(existingMeta.getPageCountLocked()));
compareValue(diffs, "language", clear.isLanguage(), newMeta.getLanguage(), existingMeta.getLanguage(), () -> !isTrue(existingMeta.getLanguageLocked()));
compareValue(diffs, "amazonRating", clear.isAmazonRating(), newMeta.getAmazonRating(), existingMeta.getAmazonRating(), () -> !isTrue(existingMeta.getAmazonRatingLocked()));
compareValue(diffs, "amazonReviewCount", clear.isAmazonReviewCount(), newMeta.getAmazonReviewCount(), existingMeta.getAmazonReviewCount(), () -> !isTrue(existingMeta.getAmazonReviewCountLocked()));
compareValue(diffs, "goodreadsRating", clear.isGoodreadsRating(), newMeta.getGoodreadsRating(), existingMeta.getGoodreadsRating(), () -> !isTrue(existingMeta.getGoodreadsRatingLocked()));
compareValue(diffs, "goodreadsReviewCount", clear.isGoodreadsReviewCount(), newMeta.getGoodreadsReviewCount(), existingMeta.getGoodreadsReviewCount(), () -> !isTrue(existingMeta.getGoodreadsReviewCountLocked()));
compareValue(diffs, "hardcoverRating", clear.isHardcoverRating(), newMeta.getHardcoverRating(), existingMeta.getHardcoverRating(), () -> !isTrue(existingMeta.getHardcoverRatingLocked()));
compareValue(diffs, "hardcoverReviewCount", clear.isHardcoverReviewCount(), newMeta.getHardcoverReviewCount(), existingMeta.getHardcoverReviewCount(), () -> !isTrue(existingMeta.getHardcoverReviewCountLocked()));
compareValue(diffs, "lubimyczytacId", clear.isLubimyczytacId(), newMeta.getLubimyczytacId(), existingMeta.getLubimyczytacId(), () -> !isTrue(existingMeta.getLubimyczytacIdLocked()));
compareValue(diffs, "lubimyczytacRating", clear.isLubimyczytacRating(), newMeta.getLubimyczytacRating(), existingMeta.getLubimyczytacRating(), () -> !isTrue(existingMeta.getLubimyczytacRatingLocked()));
compareValue(diffs, "ranobedbId", clear.isRanobedbId(), newMeta.getRanobedbId(), existingMeta.getRanobedbId(), () -> !isTrue(existingMeta.getRanobedbIdLocked()));
compareValue(diffs, "ranobedbRating", clear.isRanobedbRating(), newMeta.getRanobedbRating(), existingMeta.getRanobedbRating(), () -> !isTrue(existingMeta.getRanobedbRatingLocked()));
compareValue(diffs, "authors", clear.isAuthors(), newMeta.getAuthors(), toNameSet(existingMeta.getAuthors()), () -> !isTrue(existingMeta.getAuthorsLocked()));
compareValue(diffs, "categories", clear.isCategories(), newMeta.getCategories(), toNameSet(existingMeta.getCategories()), () -> !isTrue(existingMeta.getCategoriesLocked()));
compareValue(diffs, "moods", clear.isMoods(), newMeta.getMoods(), toNameSet(existingMeta.getMoods()), () -> !isTrue(existingMeta.getMoodsLocked()));
compareValue(diffs, "tags", clear.isTags(), newMeta.getTags(), toNameSet(existingMeta.getTags()), () -> !isTrue(existingMeta.getTagsLocked()));
return !diffs.isEmpty();
}
public static boolean hasValueChangesForFileWrite(BookMetadata newMeta, BookMetadataEntity existingMeta, MetadataClearFlags clear) {
List<String> diffs = new ArrayList<>();
compareValue(diffs, "title", clear.isTitle(), newMeta.getTitle(), existingMeta.getTitle(), () -> !isTrue(existingMeta.getTitleLocked()));
compareValue(diffs, "subtitle", clear.isSubtitle(), newMeta.getSubtitle(), existingMeta.getSubtitle(), () -> !isTrue(existingMeta.getSubtitleLocked()));
compareValue(diffs, "publisher", clear.isPublisher(), newMeta.getPublisher(), existingMeta.getPublisher(), () -> !isTrue(existingMeta.getPublisherLocked()));
compareValue(diffs, "publishedDate", clear.isPublishedDate(), newMeta.getPublishedDate(), existingMeta.getPublishedDate(), () -> !isTrue(existingMeta.getPublishedDateLocked()));
compareValue(diffs, "description", clear.isDescription(), newMeta.getDescription(), existingMeta.getDescription(), () -> !isTrue(existingMeta.getDescriptionLocked()));
compareValue(diffs, "seriesName", clear.isSeriesName(), newMeta.getSeriesName(), existingMeta.getSeriesName(), () -> !isTrue(existingMeta.getSeriesNameLocked()));
compareValue(diffs, "seriesNumber", clear.isSeriesNumber(), newMeta.getSeriesNumber(), existingMeta.getSeriesNumber(), () -> !isTrue(existingMeta.getSeriesNumberLocked()));
compareValue(diffs, "seriesTotal", clear.isSeriesTotal(), newMeta.getSeriesTotal(), existingMeta.getSeriesTotal(), () -> !isTrue(existingMeta.getSeriesTotalLocked()));
compareValue(diffs, "isbn13", clear.isIsbn13(), newMeta.getIsbn13(), existingMeta.getIsbn13(), () -> !isTrue(existingMeta.getIsbn13Locked()));
compareValue(diffs, "isbn10", clear.isIsbn10(), newMeta.getIsbn10(), existingMeta.getIsbn10(), () -> !isTrue(existingMeta.getIsbn10Locked()));
compareValue(diffs, "asin", clear.isAsin(), newMeta.getAsin(), existingMeta.getAsin(), () -> !isTrue(existingMeta.getAsinLocked()));
compareValue(diffs, "goodreadsId", clear.isGoodreadsId(), newMeta.getGoodreadsId(), existingMeta.getGoodreadsId(), () -> !isTrue(existingMeta.getGoodreadsIdLocked()));
compareValue(diffs, "comicvineId", clear.isComicvineId(), newMeta.getComicvineId(), existingMeta.getComicvineId(), () -> !isTrue(existingMeta.getComicvineIdLocked()));
compareValue(diffs, "hardcoverId", clear.isHardcoverId(), newMeta.getHardcoverId(), existingMeta.getHardcoverId(), () -> !isTrue(existingMeta.getHardcoverIdLocked()));
compareValue(diffs, "hardcoverBookId", clear.isHardcoverBookId(), newMeta.getHardcoverBookId(), existingMeta.getHardcoverBookId(), () -> !isTrue(existingMeta.getHardcoverBookIdLocked()));
compareValue(diffs, "googleId", clear.isGoogleId(), newMeta.getGoogleId(), existingMeta.getGoogleId(), () -> !isTrue(existingMeta.getGoogleIdLocked()));
compareValue(diffs, "ranobedbId", clear.isRanobedbId(), newMeta.getRanobedbId(), existingMeta.getRanobedbId(), () -> !isTrue(existingMeta.getRanobedbIdLocked()));
compareValue(diffs, "language", clear.isLanguage(), newMeta.getLanguage(), existingMeta.getLanguage(), () -> !isTrue(existingMeta.getLanguageLocked()));
compareValue(diffs, "authors", clear.isAuthors(), newMeta.getAuthors(), toNameSet(existingMeta.getAuthors()), () -> !isTrue(existingMeta.getAuthorsLocked()));
compareValue(diffs, "categories", clear.isCategories(), newMeta.getCategories(), toNameSet(existingMeta.getCategories()), () -> !isTrue(existingMeta.getCategoriesLocked()));
return !diffs.isEmpty();
}
private static void compare(List<String> diffs, String field, boolean shouldClear, Object newVal, Object oldVal, BooleanSupplier isUnlocked, Boolean newLock, Boolean oldLock) {
boolean valueChanged = differs(shouldClear, newVal, oldVal, isUnlocked);
boolean lockChanged = differsLock(newLock, oldLock);
if (valueChanged || lockChanged) {
StringBuilder sb = new StringBuilder();
sb.append(field);
if (valueChanged) sb.append(" value: [").append(safe(oldVal)).append("] → [").append(safe(newVal)).append("]");
if (lockChanged) sb.append(" lock: [").append(isTrue(oldLock)).append("] → [").append(isTrue(newLock)).append("]");
diffs.add(sb.toString());
}
}
private static <T> void compareValue(List<String> diffs,
String field,
boolean shouldClear,
T newVal,
T oldVal,
BooleanSupplier isUnlocked) {
if (differs(shouldClear, newVal, oldVal, isUnlocked)) {
diffs.add(field + " changed");
}
}
private static boolean differs(boolean shouldClear, Object newVal, Object oldVal, BooleanSupplier isUnlocked) {
if (!isUnlocked.getAsBoolean()) return false;
Object normNew = normalize(newVal);
Object normOld = normalize(oldVal);
// Ignore transitions from null to empty string or empty set
if (normOld == null && isEffectivelyEmpty(normNew)) return false;
if (shouldClear) return normOld != null;
return !Objects.equals(normNew, normOld);
}
private static boolean isEffectivelyEmpty(Object value) {
return switch (value) {
case null -> true;
case String s -> s.isBlank();
case Collection<?> c -> c.isEmpty();
default -> false;
};
}
private static boolean differsLock(Boolean dtoLock, Boolean entityLock) {
return !Objects.equals(Boolean.TRUE.equals(dtoLock), Boolean.TRUE.equals(entityLock));
}
private static String safe(Object val) {
if (val == null) return "null";
if (val instanceof Set<?> set) return set.stream().map(String::valueOf).sorted().collect(Collectors.joining(", ", "[", "]"));
return val.toString().strip();
}
private static Object normalize(Object value) {
if (value instanceof String s) return s.strip();
return value;
}
private static Set<String> toNameSet(Set<?> entities) {
if (entities == null) {
return Collections.emptySet();
}
return entities.stream()
.map(e -> {
if (e instanceof AuthorEntity author) {
return author.getName();
}
if (e instanceof CategoryEntity category) {
return category.getName();
}
if (e instanceof MoodEntity mood) {
return mood.getName();
}
if (e instanceof TagEntity tag) {
return tag.getName();
}
return e.toString();
})
.collect(Collectors.toSet());
}
}
@@ -1,4 +1,4 @@
package com.adityachandel.booklore;
package org.booklore;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@@ -6,7 +6,7 @@ import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import com.adityachandel.booklore.config.BookmarkProperties;
import org.booklore.config.BookmarkProperties;
@EnableScheduling
@EnableAsync
@@ -1,4 +1,4 @@
package com.adityachandel.booklore.config;
package org.booklore.config;
import lombok.Getter;
import lombok.Setter;
@@ -14,10 +14,17 @@ public class AppProperties {
private String bookdropFolder;
private String version;
private RemoteAuth remoteAuth;
private Swagger swagger = new Swagger();
private Boolean forceDisableOidc = false;
private Telemetry telemetry = new Telemetry();
/**
* 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";
@Getter
@Setter
public static class RemoteAuth {
@@ -31,12 +38,6 @@ public class AppProperties {
private String groupsDelimiter = "\\s+"; // Default to whitespace for backward compatibility
}
@Getter
@Setter
public static class Swagger {
private boolean enabled = true;
}
@Getter
@Setter
public static class Telemetry {
@@ -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
);
}
}
@@ -1,13 +1,14 @@
package com.adityachandel.booklore.config;
package org.booklore.config;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.JdkClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.socket.config.WebSocketMessageBrokerStats;
import java.net.http.HttpClient;
import java.time.Duration;
@Configuration
@@ -17,13 +18,16 @@ public class BeanConfig {
private WebSocketMessageBrokerStats webSocketMessageBrokerStats;
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.connectTimeout(Duration.ofSeconds(10)).readTimeout(Duration.ofSeconds(15))
.build();
public RestTemplate restTemplate(HttpClient httpClient) {
JdkClientHttpRequestFactory factory = new JdkClientHttpRequestFactory(httpClient);
factory.setReadTimeout(Duration.ofSeconds(15));
return new RestTemplate(factory);
}
@PostConstruct
public void init() {
webSocketMessageBrokerStats.setLoggingPeriod(30 * 24 * 60 * 60 * 1000L); // 30 days
}
}
@@ -1,7 +1,7 @@
package com.adityachandel.booklore.config;
package org.booklore.config;
import com.adityachandel.booklore.model.enums.MetadataProvider;
import com.adityachandel.booklore.service.metadata.parser.*;
import org.booklore.model.enums.MetadataProvider;
import org.booklore.service.metadata.parser.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -12,7 +12,7 @@ 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) {
GoodReadsParser goodReadsParser, HardcoverParser hardcoverParser, ComicvineBookParser comicvineBookParser, DoubanBookParser doubanBookParser, RanobeDbParser ranobedbParser, LubimyCzytacParser lubimyczytacParser, AudibleParser audibleParser) {
return Map.of(
MetadataProvider.Amazon, amazonBookParser,
MetadataProvider.GoodReads, goodReadsParser,
@@ -21,7 +21,8 @@ public class BookParserConfig {
MetadataProvider.Comicvine, comicvineBookParser,
MetadataProvider.Douban, doubanBookParser,
MetadataProvider.Lubimyczytac, lubimyczytacParser,
MetadataProvider.Ranobedb, ranobedbParser
MetadataProvider.Ranobedb, ranobedbParser,
MetadataProvider.Audible, audibleParser
);
}
}
@@ -1,4 +1,4 @@
package com.adityachandel.booklore.config;
package org.booklore.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
@@ -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");
cacheManager.setCaffeine(Caffeine.newBuilder()
.expireAfterWrite(Duration.ofMinutes(5))
.maximumSize(10));
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,22 @@
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.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();
}
}
@@ -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();
}
}
@@ -1,9 +1,9 @@
package com.adityachandel.booklore.config;
package org.booklore.config;
import com.adityachandel.booklore.context.KomgaCleanContext;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
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;
@@ -21,7 +21,7 @@ public class KomgaCleanBeanPropertyWriter extends BeanPropertyWriter {
}
@Override
public void serializeAsField(Object bean, JsonGenerator gen, SerializerProvider prov) throws Exception {
public void serializeAsProperty(Object bean, JsonGenerator gen, SerializationContext prov) throws Exception {
if (KomgaCleanContext.isCleanMode()) {
String propertyName = getName();
@@ -43,6 +43,6 @@ public class KomgaCleanBeanPropertyWriter extends BeanPropertyWriter {
}
// Default behavior
super.serializeAsField(bean, gen, prov);
super.serializeAsProperty(bean, gen, prov);
}
}
@@ -1,4 +1,4 @@
package com.adityachandel.booklore.config;
package org.booklore.config;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
@@ -1,4 +1,4 @@
package com.adityachandel.booklore.config;
package org.booklore.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
@@ -0,0 +1,24 @@
package org.booklore.config;
import jakarta.servlet.MultipartConfigElement;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.unit.DataSize;
@Configuration
public class MultipartConfig {
private static final long DEFAULT_MAX_UPLOAD_SIZE_MB = 1024;
/**
* Provides a MultipartConfigElement with a generous default max upload size.
* The actual user-configured limit from app_settings is enforced at the service layer.
* This bean is created during servlet container initialization (before Flyway migrations run),
* so it must NOT query the database.
*/
@Bean
public MultipartConfigElement multipartConfigElement() {
long maxSizeBytes = DataSize.ofMegabytes(DEFAULT_MAX_UPLOAD_SIZE_MB).toBytes();
return new MultipartConfigElement("", maxSizeBytes, maxSizeBytes, 0);
}
}
@@ -1,4 +1,4 @@
package com.adityachandel.booklore.config;
package org.booklore.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -0,0 +1,26 @@
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.concurrent.SimpleAsyncTaskScheduler;
@Configuration
public class TaskExecutorConfig {
@Bean(name = "taskExecutor")
public AsyncTaskExecutor taskExecutor() {
return new VirtualThreadTaskExecutor("async-");
}
@Bean
public TaskScheduler taskScheduler() {
SimpleAsyncTaskScheduler scheduler = new SimpleAsyncTaskScheduler();
scheduler.setVirtualThreads(true);
scheduler.setThreadNamePrefix("scheduler-");
return scheduler;
}
}
@@ -1,6 +1,6 @@
package com.adityachandel.booklore.config;
package org.booklore.config;
import com.adityachandel.booklore.service.task.TaskService;
import org.booklore.service.task.TaskService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationReadyEvent;
@@ -1,4 +1,4 @@
package com.adityachandel.booklore.config;
package org.booklore.config;
import jakarta.persistence.EntityManagerFactory;
import org.springframework.context.annotation.Bean;
@@ -0,0 +1,61 @@
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);
return resource.exists() && resource.isReadable()
? resource
: new ClassPathResource("/static/index.html");
}
});
}
@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/**");
}
}
@@ -1,6 +1,6 @@
package com.adityachandel.booklore.config;
package org.booklore.config;
import com.adityachandel.booklore.config.security.interceptor.WebSocketAuthInterceptor;
import org.booklore.config.security.interceptor.WebSocketAuthInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.ChannelRegistration;
@@ -1,6 +1,6 @@
package com.adityachandel.booklore.config.security;
package org.booklore.config.security;
import com.adityachandel.booklore.config.security.filter.ImageCachingFilter;
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;
@@ -1,7 +1,7 @@
package com.adityachandel.booklore.config.security;
package org.booklore.config.security;
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
import com.adityachandel.booklore.service.security.JwtSecretService;
import org.booklore.model.entity.BookLoreUserEntity;
import org.booklore.service.security.JwtSecretService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtException;
@@ -1,8 +1,7 @@
package com.adityachandel.booklore.config.security;
package org.booklore.config.security;
import com.adityachandel.booklore.config.AppProperties;
import com.adityachandel.booklore.config.security.filter.*;
import com.adityachandel.booklore.config.security.service.OpdsUserDetailsService;
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;
@@ -35,13 +34,6 @@ public class SecurityConfig {
private final OpdsUserDetailsService opdsUserDetailsService;
private final DualJwtAuthenticationFilter dualJwtAuthenticationFilter;
private final AppProperties appProperties;
private static final String[] SWAGGER_ENDPOINTS = {
"/api/v1/swagger-ui.html",
"/api/v1/swagger-ui/**",
"/api/v1/api-docs/**"
};
private static final String[] COMMON_PUBLIC_ENDPOINTS = {
"/ws/**", // WebSocket connections (auth handled in WebSocketAuthInterceptor)
@@ -183,12 +175,25 @@ public class SecurityConfig {
@Bean
@Order(7)
public SecurityFilterChain audiobookStreamingSecurityChain(HttpSecurity http, AudiobookStreamingJwtFilter audiobookStreamingJwtFilter) throws Exception {
http
.securityMatcher("/api/v1/audiobook/*/stream/**", "/api/v1/audiobook/*/track/*/stream/**", "/api/v1/audiobook/*/cover")
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
.csrf(AbstractHttpConfigurer::disable)
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(auth -> auth
.anyRequest().permitAll()
)
.addFilterBefore(audiobookStreamingJwtFilter, UsernamePasswordAuthenticationFilter.class);
return http.build();
}
@Bean
@Order(8)
public SecurityFilterChain jwtApiSecurityChain(HttpSecurity http) throws Exception {
List<String> publicEndpoints = new ArrayList<>(Arrays.asList(COMMON_PUBLIC_ENDPOINTS));
if (appProperties.getSwagger().isEnabled()) {
publicEndpoints.addAll(Arrays.asList(SWAGGER_ENDPOINTS));
}
http
.securityMatcher("/api/**", "/komga/**", "/ws/**")
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
.csrf(AbstractHttpConfigurer::disable)
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
@@ -201,6 +206,17 @@ public class SecurityConfig {
return http.build();
}
@Bean
@Order(9)
public SecurityFilterChain staticResourcesSecurityChain(HttpSecurity http) throws Exception {
http
.csrf(AbstractHttpConfigurer::disable)
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.headers(headers -> headers.frameOptions(HeadersConfigurer.FrameOptionsConfig::sameOrigin))
.authorizeHttpRequests(auth -> auth.anyRequest().permitAll());
return http.build();
}
@Bean
public AuthenticationManager authenticationManager(HttpSecurity http) throws Exception {
AuthenticationManagerBuilder auth = http.getSharedObject(AuthenticationManagerBuilder.class);
@@ -213,8 +229,8 @@ public class SecurityConfig {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOriginPatterns(List.of("*"));
configuration.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"));
configuration.setAllowedHeaders(List.of("Authorization", "Cache-Control", "Content-Type"));
configuration.setExposedHeaders(List.of("Content-Disposition"));
configuration.setAllowedHeaders(List.of("Authorization", "Cache-Control", "Content-Type", "Range", "If-None-Match"));
configuration.setExposedHeaders(List.of("Content-Disposition", "Accept-Ranges", "Content-Range", "Content-Length", "ETag", "Date"));
configuration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
@@ -1,7 +1,7 @@
package com.adityachandel.booklore.config.security;
package org.booklore.config.security;
import com.adityachandel.booklore.model.dto.BookLoreUser;
import com.adityachandel.booklore.repository.ShelfRepository;
import org.booklore.model.dto.BookLoreUser;
import org.booklore.repository.ShelfRepository;
import lombok.AllArgsConstructor;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
@@ -1,4 +1,4 @@
package com.adityachandel.booklore.config.security.annotation;
package org.booklore.config.security.annotation;
import java.lang.annotation.*;
@@ -1,4 +1,4 @@
package com.adityachandel.booklore.config.security.annotation;
package org.booklore.config.security.annotation;
import java.lang.annotation.*;
@@ -1,11 +1,12 @@
package com.adityachandel.booklore.config.security.aspect;
package org.booklore.config.security.aspect;
import com.adityachandel.booklore.config.security.service.AuthenticationService;
import com.adityachandel.booklore.config.security.annotation.CheckBookAccess;
import com.adityachandel.booklore.exception.ApiError;
import com.adityachandel.booklore.model.dto.BookLoreUser;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.repository.BookRepository;
import org.booklore.config.security.service.AuthenticationService;
import org.booklore.config.security.annotation.CheckBookAccess;
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 lombok.RequiredArgsConstructor;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
@@ -14,6 +15,7 @@ import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Objects;
import java.util.regex.Pattern;
@@ -25,8 +27,9 @@ 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(com.adityachandel.booklore.config.security.annotation.CheckBookAccess)")
@Before("@annotation(org.booklore.config.security.annotation.CheckBookAccess)")
public void checkBookAccess(JoinPoint joinPoint) {
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
Method method = methodSignature.getMethod();
@@ -49,9 +52,14 @@ public class BookAccessAspect {
return;
}
boolean hasAccess = user.getAssignedLibraries().stream().anyMatch(library -> library.getId().equals(bookEntity.getLibrary().getId()));
boolean hasLibraryAccess = user.getAssignedLibraries().stream().anyMatch(library -> library.getId().equals(bookEntity.getLibrary().getId()));
if (!hasAccess) {
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.");
}
}
@@ -1,9 +1,9 @@
package com.adityachandel.booklore.config.security.aspect;
package org.booklore.config.security.aspect;
import com.adityachandel.booklore.config.security.service.AuthenticationService;
import com.adityachandel.booklore.config.security.annotation.CheckLibraryAccess;
import com.adityachandel.booklore.exception.ApiError;
import com.adityachandel.booklore.model.dto.BookLoreUser;
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;
@@ -23,7 +23,7 @@ public class LibraryAccessAspect {
private static final Pattern NUMERIC_PATTERN = Pattern.compile("\\d+");
private final AuthenticationService authenticationService;
@Before("@annotation(com.adityachandel.booklore.config.security.annotation.CheckLibraryAccess)")
@Before("@annotation(org.booklore.config.security.annotation.CheckLibraryAccess)")
public void checkLibraryAccess(JoinPoint joinPoint) {
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
Method method = methodSignature.getMethod();
@@ -1,14 +1,14 @@
package com.adityachandel.booklore.config.security.filter;
package org.booklore.config.security.filter;
import com.adityachandel.booklore.config.security.JwtUtils;
import com.adityachandel.booklore.config.security.service.DynamicOidcJwtProcessor;
import com.adityachandel.booklore.config.security.userdetails.UserAuthenticationDetails;
import com.adityachandel.booklore.mapper.custom.BookLoreUserTransformer;
import com.adityachandel.booklore.model.dto.BookLoreUser;
import com.adityachandel.booklore.model.dto.settings.OidcProviderDetails;
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
import com.adityachandel.booklore.repository.UserRepository;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import org.booklore.config.security.JwtUtils;
import org.booklore.config.security.service.DynamicOidcJwtProcessor;
import org.booklore.config.security.userdetails.UserAuthenticationDetails;
import org.booklore.mapper.custom.BookLoreUserTransformer;
import org.booklore.model.dto.BookLoreUser;
import org.booklore.model.dto.settings.OidcProviderDetails;
import org.booklore.model.entity.BookLoreUserEntity;
import org.booklore.repository.UserRepository;
import org.booklore.service.appsettings.AppSettingService;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
@@ -0,0 +1,114 @@
package org.booklore.config.security.filter;
import org.booklore.config.security.JwtUtils;
import org.booklore.config.security.service.DynamicOidcJwtProcessor;
import org.booklore.config.security.userdetails.UserAuthenticationDetails;
import org.booklore.mapper.custom.BookLoreUserTransformer;
import org.booklore.model.dto.BookLoreUser;
import org.booklore.model.dto.settings.OidcProviderDetails;
import org.booklore.model.entity.BookLoreUserEntity;
import org.booklore.repository.UserRepository;
import org.booklore.service.appsettings.AppSettingService;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
import java.time.Instant;
import java.util.regex.Pattern;
@Component
@AllArgsConstructor
public class AudiobookStreamingJwtFilter extends OncePerRequestFilter {
private static final Pattern AUDIOBOOK_STREAMING_ENDPOINT_PATTERN =
Pattern.compile("/api/v1/audiobook/\\d+/(stream|track/\\d+/stream|cover).*");
private final JwtUtils jwtUtils;
private final UserRepository userRepository;
private final BookLoreUserTransformer bookLoreUserTransformer;
private final AppSettingService appSettingService;
private final DynamicOidcJwtProcessor dynamicOidcJwtProcessor;
@Override
protected boolean shouldNotFilter(HttpServletRequest request) {
String path = request.getRequestURI();
return !AUDIOBOOK_STREAMING_ENDPOINT_PATTERN.matcher(path).matches();
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
String token = extractTokenFromHeader(request);
if (token == null) {
token = request.getParameter("token");
}
if (token == null || token.isEmpty()) {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Missing authentication token");
return;
}
try {
if (jwtUtils.validateToken(token)) {
authenticateLocalUser(token, request);
} else if (appSettingService.getAppSettings().isOidcEnabled()) {
authenticateOidcUser(token, request);
} else {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid token");
return;
}
} catch (Exception ex) {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication failed: " + ex.getMessage());
return;
}
chain.doFilter(request, response);
}
private String extractTokenFromHeader(HttpServletRequest request) {
String bearer = request.getHeader("Authorization");
return (bearer != null && bearer.startsWith("Bearer ")) ? bearer.substring(7) : null;
}
private void authenticateLocalUser(String token, HttpServletRequest request) {
Long userId = jwtUtils.extractUserId(token);
BookLoreUserEntity entity = userRepository.findById(userId)
.orElseThrow(() -> new UsernameNotFoundException("User not found with ID: " + userId));
BookLoreUser user = bookLoreUserTransformer.toDTO(entity);
UsernamePasswordAuthenticationToken authentication =
new UsernamePasswordAuthenticationToken(user, null, null);
authentication.setDetails(new UserAuthenticationDetails(request, user.getId()));
SecurityContextHolder.getContext().setAuthentication(authentication);
}
private void authenticateOidcUser(String token, HttpServletRequest request) throws Exception {
var processor = dynamicOidcJwtProcessor.getProcessor();
var claimsSet = processor.process(token, null);
if (claimsSet.getExpirationTime() == null ||
claimsSet.getExpirationTime().toInstant().isBefore(Instant.now())) {
throw new RuntimeException("OIDC token expired or invalid");
}
OidcProviderDetails providerDetails = appSettingService.getAppSettings().getOidcProviderDetails();
OidcProviderDetails.ClaimMapping claimMapping = providerDetails.getClaimMapping();
String username = claimsSet.getStringClaim(claimMapping.getUsername());
BookLoreUserEntity entity = userRepository.findByUsername(username)
.orElseThrow(() -> new UsernameNotFoundException("OIDC user not found: " + username));
BookLoreUser user = bookLoreUserTransformer.toDTO(entity);
UsernamePasswordAuthenticationToken authentication =
new UsernamePasswordAuthenticationToken(user, null, null);
authentication.setDetails(new UserAuthenticationDetails(request, user.getId()));
SecurityContextHolder.getContext().setAuthentication(authentication);
}
}
@@ -1,10 +1,10 @@
package com.adityachandel.booklore.config.security.filter;
package org.booklore.config.security.filter;
import com.adityachandel.booklore.config.security.JwtUtils;
import com.adityachandel.booklore.config.security.service.DynamicOidcJwtProcessor;
import com.adityachandel.booklore.mapper.custom.BookLoreUserTransformer;
import com.adityachandel.booklore.repository.UserRepository;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import org.booklore.config.security.JwtUtils;
import org.booklore.config.security.service.DynamicOidcJwtProcessor;
import org.booklore.mapper.custom.BookLoreUserTransformer;
import org.booklore.repository.UserRepository;
import org.booklore.service.appsettings.AppSettingService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Component;
@@ -1,10 +1,10 @@
package com.adityachandel.booklore.config.security.filter;
package org.booklore.config.security.filter;
import com.adityachandel.booklore.config.security.JwtUtils;
import com.adityachandel.booklore.config.security.service.DynamicOidcJwtProcessor;
import com.adityachandel.booklore.mapper.custom.BookLoreUserTransformer;
import com.adityachandel.booklore.repository.UserRepository;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import org.booklore.config.security.JwtUtils;
import org.booklore.config.security.service.DynamicOidcJwtProcessor;
import org.booklore.mapper.custom.BookLoreUserTransformer;
import org.booklore.repository.UserRepository;
import org.booklore.service.appsettings.AppSettingService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Component;
@@ -1,17 +1,17 @@
package com.adityachandel.booklore.config.security.filter;
package org.booklore.config.security.filter;
import com.adityachandel.booklore.config.security.JwtUtils;
import com.adityachandel.booklore.config.security.service.DynamicOidcJwtProcessor;
import com.adityachandel.booklore.config.security.userdetails.UserAuthenticationDetails;
import com.adityachandel.booklore.exception.ApiError;
import com.adityachandel.booklore.mapper.custom.BookLoreUserTransformer;
import com.adityachandel.booklore.model.dto.BookLoreUser;
import com.adityachandel.booklore.model.dto.settings.OidcAutoProvisionDetails;
import com.adityachandel.booklore.model.dto.settings.OidcProviderDetails;
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
import com.adityachandel.booklore.repository.UserRepository;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import com.adityachandel.booklore.service.user.UserProvisioningService;
import org.booklore.config.security.JwtUtils;
import org.booklore.config.security.service.DynamicOidcJwtProcessor;
import org.booklore.config.security.userdetails.UserAuthenticationDetails;
import org.booklore.exception.ApiError;
import org.booklore.mapper.custom.BookLoreUserTransformer;
import org.booklore.model.dto.BookLoreUser;
import org.booklore.model.dto.settings.OidcAutoProvisionDetails;
import org.booklore.model.dto.settings.OidcProviderDetails;
import org.booklore.model.entity.BookLoreUserEntity;
import org.booklore.repository.UserRepository;
import org.booklore.service.appsettings.AppSettingService;
import org.booklore.service.user.UserProvisioningService;
import com.nimbusds.jwt.JWTClaimsSet;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;

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