Merge pull request #2396 from booklore-app/release/1.18

Release v1.18.0
This commit is contained in:
ACX
2026-01-22 10:50:45 -07:00
committed by GitHub
723 changed files with 58298 additions and 23174 deletions
+357
View File
@@ -0,0 +1,357 @@
# Release Workflow
This document describes the branch strategy, CI/CD pipelines, and release process for Booklore.
## Branch Strategy
```
master Stable releases only. Tagged with vX.Y.Z
↑
release/X.Y Release stabilization. RC builds published here
↑
develop Active development. All feature PRs merge here
```
| Branch | Purpose | Stability |
|--------|---------|-----------|
| `master` | Production releases | Stable |
| `release/X.Y` | Release candidates, bug fixes | Stabilizing |
| `develop` | New features, active development | Unstable |
## CI/CD Pipelines
### 1. Develop Pipeline (`develop-pipeline.yml`)
**Triggers:**
- Push to `develop`
- PRs targeting `develop`, `release/**`, or `master`
**Actions:**
- Flyway migration check
- Backend tests (Gradle)
- Frontend tests (Angular/Vitest)
- Docker build and push (for pushes and internal PRs)
**Image Tags:** `develop-{sha}`, `pr-{number}-{sha}`
---
### 2. Release Pipeline (`release-pipeline.yml`)
**Triggers:**
- Push to `release/**` branches
- PRs targeting `release/**` branches
**Actions:**
- Flyway migration check (against `master`)
- Backend and frontend tests
- Docker build and push with RC tags
**Image Tags:** `v1.18.0-rc.1`, `v1.18.0-rc.2`, `release-1.18-{sha}`
**Validations:**
- Branch name must be `release/X.Y` or `release/X.Y.Z`
- Version must be newer than latest tag
- Rejects suspicious version jumps (typo protection)
---
### 3. Master Tag Pipeline (`master-pipeline.yml`)
**Triggers:**
- Push of tags matching `v*`
**Actions:**
- Tag format validation
- Flyway migration check
- Backend and frontend tests
- Docker build and push
- GitHub Release publication (publishes the draft release)
**Image Tags:** `v1.18.0`, `latest` (stable releases only)
**Validations:**
- Tag must be valid semver (`vX.Y.Z` or `vX.Y.Z-prerelease.N`)
- Version must be newer than latest stable tag
- Rejects suspicious version jumps (typo protection)
- Blocks prereleases if stable version already exists
---
### 4. Draft Release Pipeline (`draft-release.yml`)
**Triggers:**
- Push to `master`
**Actions:**
- Updates draft GitHub Release with changelog from merged PRs
- Categorizes changes based on PR labels (feature, bug, enhancement, etc.)
- Auto-resolves next version based on labels (major/minor/patch)
**Configuration:** `.github/release-drafter.yml`
**How it works:**
1. Each PR merged to `master` triggers this workflow
2. Release-drafter accumulates changes into a draft release
3. When you push a `v*` tag, the master-pipeline publishes the draft
**Label → Version mapping:**
| Label | Version Bump |
|-------|--------------|
| `major` | X.0.0 |
| `minor` | 0.X.0 |
| `patch` | 0.0.X |
**Label → Changelog category:**
| Labels | Category |
|--------|----------|
| `feature` | New Features |
| `enhancement` | Enhancements |
| `bug`, `fix` | Bug Fixes |
| `refactor`, `cleanup`, `chore` | Refactoring & Maintenance |
| `dependencies`, `deps` | Dependencies |
| `ci`, `cd`, `workflow` | CI/CD |
| `docs`, `documentation` | Documentation |
PRs with the `skip changelog` label are excluded from release notes.
---
## Release Flow Diagram
```
v1.17.0 (current)
│
develop ────●────●────●────●─────────────────●──▶ (continues)
│ ↑
│ (1) cut branch │ (5) merge back
▼ │
release/1.18 ──●──●──●────────────────┼──▶ (delete)
│ │ │ │
▼ ▼ ▼ │
rc.1 rc.2 rc.3 │
│
master ──────────────────────────────────────●──▶
│
(4) tag v1.18.0
│
▼
Docker: v1.18.0 + latest
GitHub Release created
```
## Step-by-Step Release Process
### Phase 1: Cut Release Branch
When `develop` is feature-complete for the release:
```bash
git checkout develop && git pull
git checkout -b release/1.18
git push -u origin release/1.18
```
**What happens:**
- Release pipeline runs tests
- Publishes `v1.18.0-rc.1` to Docker Hub and GHCR
- RC number increments with each subsequent push
---
### Phase 2: Stabilize (Optional)
If bugs are found during RC testing, fix them on the release branch:
```bash
git checkout release/1.18
git checkout -b fix/critical-bug
# ... make fixes ...
git commit -m "Fix critical bug in authentication"
git push -u origin fix/critical-bug
# Create PR targeting the release branch
gh pr create --base release/1.18 --title "Fix critical bug"
gh pr merge --squash
```
**What happens:**
- Each merge to `release/1.18` publishes a new RC (`v1.18.0-rc.2`, `rc.3`, etc.)
- Testers can pull specific RC versions to validate fixes
---
### Phase 3: Merge to Master
When the RC is validated and stable:
```bash
# Create PR from release branch to master
gh pr create --base master --head release/1.18 --title "Release v1.18.0"
# After approval, merge (use merge commit, not squash)
gh pr merge --merge
```
**What happens:**
- Develop pipeline runs tests on the PR
- Merge commit lands on `master`
- No release is published yet (waiting for tag)
---
### Phase 4: Tag and Release
Create the release tag to trigger the final release:
```bash
git checkout master && git pull
git tag v1.18.0
git push origin v1.18.0
```
**What happens:**
- Master Tag pipeline validates the tag
- Runs full test suite
- Builds and pushes Docker images: `v1.18.0` + `latest`
- Publishes the draft GitHub Release (created by `draft-release.yml`) with changelog
---
### Phase 5: Post-Release Cleanup
Sync the release back to `develop` and clean up:
```bash
# Merge master back to develop (includes any RC fixes)
git checkout develop && git pull
git merge master
git push origin develop
# Delete the release branch
git push origin --delete release/1.18
git branch -d release/1.18
```
---
## Quick Reference Commands
### New Minor Release (v1.17.0 → v1.18.0)
```bash
# Cut release
git checkout develop && git pull
git checkout -b release/1.18
git push -u origin release/1.18
# When stable, merge to master
gh pr create --base master --head release/1.18 --title "Release v1.18.0"
gh pr merge --merge
# Tag release
git checkout master && git pull
git tag v1.18.0
git push origin v1.18.0
# Cleanup
git checkout develop && git pull && git merge master && git push
git push origin --delete release/1.18
git branch -d release/1.18
```
### New Patch Release (v1.18.0 → v1.18.1)
```bash
# Cut release from master (or existing release branch)
git checkout master && git pull
git checkout -b release/1.18
git push -u origin release/1.18
# Cherry-pick or fix bugs, then merge and tag
gh pr create --base master --head release/1.18 --title "Release v1.18.1"
gh pr merge --merge
git checkout master && git pull
git tag v1.18.1
git push origin v1.18.1
# Cleanup
git checkout develop && git pull && git merge master && git push
git push origin --delete release/1.18
```
### Hotfix (urgent production fix)
```bash
# Create hotfix branch from master
git checkout master && git pull
git checkout -b hotfix/1.18.1
# ... make urgent fix ...
git commit -m "Fix critical security issue"
git push -u origin hotfix/1.18.1
# Merge to master and tag
gh pr create --base master --head hotfix/1.18.1 --title "Hotfix v1.18.1"
gh pr merge --merge
git checkout master && git pull
git tag v1.18.1
git push origin v1.18.1
# Merge fix to develop
git checkout develop && git pull && git merge master && git push
git push origin --delete hotfix/1.18.1
```
---
## Version Validation Rules
The pipelines enforce these rules to prevent mistakes:
| Rule | Example | Result |
|------|---------|--------|
| No backwards versions | `v1.17.0` after `v1.18.0` | Blocked |
| No duplicate stable versions | `v1.18.0` after `v1.18.0` | Blocked |
| No prerelease after stable | `v1.18.0-rc.1` after `v1.18.0` | Blocked |
| Major jump ≤ 1 | `v3.0.0` after `v1.18.0` | Blocked |
| Minor jump ≤ 5 | `v1.25.0` after `v1.18.0` | Blocked |
| Patch jump ≤ 10 | `v1.18.15` after `v1.18.0` | Blocked |
These rules catch typos like `release/1.118` instead of `release/1.18`.
---
## Docker Image Tags
| Event | Tags Published |
|-------|---------------|
| Push to `develop` | `develop-abc1234` |
| PR #42 | `pr-42-abc1234` |
| Push to `release/1.18` | `v1.18.0-rc.1`, `release-1.18-abc1234` |
| Tag `v1.18.0` | `v1.18.0`, `latest` |
| Tag `v1.18.1-rc.1` | `v1.18.1-rc.1` (no `latest`) |
---
## FAQ
**Q: Can I have multiple release branches simultaneously?**
A: Yes. `release/1.18` and `release/1.19` can coexist. Each gets independent RC numbers.
**Q: What if I need to release a patch for an older version?**
A: Create `release/1.17` from the `v1.17.0` tag, make fixes, and tag `v1.17.1`.
**Q: Why use merge commits instead of squash for release PRs?**
A: Merge commits preserve the full history of RC fixes, making it easier to track what changed.
**Q: Can I skip the RC phase for urgent fixes?**
A: Yes. For hotfixes, you can merge directly to master and tag. The release pipeline is optional.
**Q: What happens if I push a tag that fails validation?**
A: The pipeline fails before publishing anything. Delete the tag (`git push --delete origin v1.18.0`), fix the issue, and re-tag.
**Q: How do I preview release notes before publishing?**
A: Go to GitHub Releases. The draft release is automatically updated as PRs merge to `master`. Review and edit the draft before tagging.
**Q: Why don't I see changes in the draft release?**
A: Ensure PRs have appropriate labels (`feature`, `bug`, `enhancement`, etc.). PRs without recognized labels still appear but won't be categorized. PRs with `skip changelog` label are excluded.
+7 -7
View File
@@ -6,18 +6,17 @@ on:
- develop
pull_request:
branches:
- '**'
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
- develop
- 'release/**'
- master
jobs:
migration-check:
name: Flyway Migration Check
uses: ./.github/workflows/migrations-check.yml
with:
base_ref: 'develop'
# For PRs, compare against target branch; for pushes, compare against develop
base_ref: ${{ github.event_name == 'pull_request' && github.base_ref || 'develop' }}
head_ref: 'HEAD'
backend-tests:
@@ -209,4 +208,5 @@ jobs:
type=registry,ref=ghcr.io/booklore-app/booklore:buildcache
cache-to: |
type=gha,mode=max
type=registry,ref=ghcr.io/booklore-app/booklore:buildcache,mode=max
type=registry,ref=ghcr.io/booklore-app/booklore:buildcache,mode=max
+21
View File
@@ -0,0 +1,21 @@
name: Draft Release
on:
push:
branches:
- master
jobs:
draft-release:
name: Update Draft Release
runs-on: ubuntu-latest
permissions:
contents: write
pull-requests: read
steps:
- name: Draft Release Notes
uses: release-drafter/release-drafter@v6
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+155 -87
View File
@@ -1,32 +1,126 @@
name: Master - Build, Tag, Push, and Release
name: Master Tag – Build, Push, and Publish
on:
push:
branches:
- 'master'
tags:
- 'v*'
jobs:
get-base-ref:
name: Get Base Ref
validate-tag:
name: Validate Release Tag
runs-on: ubuntu-latest
outputs:
base_ref: ${{ steps.get_base.outputs.base_ref }}
version: ${{ steps.parse.outputs.version }}
is_prerelease: ${{ steps.parse.outputs.is_prerelease }}
steps:
- name: Checkout Repository
uses: actions/checkout@v6
with:
fetch-depth: 2
- name: Get Base Ref
id: get_base
run: echo "base_ref=$(git rev-parse HEAD~1)" >> $GITHUB_OUTPUT
fetch-depth: 0
- name: Parse and Validate Tag
id: parse
run: |
tag="${{ github.ref_name }}"
echo "Processing tag: $tag"
# Validate semver format (v1.2.3 or v1.2.3-rc.1, v1.2.3-beta.2, etc.)
if ! echo "$tag" | grep -qE '^v[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z]+\.[0-9]+)?$'; then
echo "::error::Invalid tag format. Expected 'vX.Y.Z' or 'vX.Y.Z-prerelease.N', got '$tag'"
exit 1
fi
# Check if this is a prerelease (contains hyphen after version)
if echo "$tag" | grep -qE '^v[0-9]+\.[0-9]+\.[0-9]+-'; then
is_prerelease="true"
else
is_prerelease="false"
fi
# ----------------------------------------
# Version sanity check against latest tag
# ----------------------------------------
# Get latest stable tag (excluding prereleases and current tag)
latest_tag=$(git tag --list "v*" --sort=-v:refname | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$' | grep -v "^${tag}$" | head -n 1)
latest_tag=${latest_tag:-"v0.0.0"}
echo "Latest stable tag: $latest_tag"
# Extract base version (strip prerelease suffix if present)
base_version=$(echo "$tag" | sed 's/^v//' | sed 's/-.*//')
# Parse latest version
latest_semver=$(echo "$latest_tag" | sed 's/^v//')
latest_major=$(echo "$latest_semver" | cut -d. -f1)
latest_minor=$(echo "$latest_semver" | cut -d. -f2)
latest_patch=$(echo "$latest_semver" | cut -d. -f3)
# Parse target version
target_major=$(echo "$base_version" | cut -d. -f1)
target_minor=$(echo "$base_version" | cut -d. -f2)
target_patch=$(echo "$base_version" | cut -d. -f3)
echo "Latest: v${latest_major}.${latest_minor}.${latest_patch}"
echo "Target: v${target_major}.${target_minor}.${target_patch}"
# Check for backwards version (target < latest)
if [ "$target_major" -lt "$latest_major" ]; then
echo "::error::Target version v${base_version} is older than latest tag ${latest_tag}"
exit 1
elif [ "$target_major" -eq "$latest_major" ] && [ "$target_minor" -lt "$latest_minor" ]; then
echo "::error::Target version v${base_version} is older than latest tag ${latest_tag}"
exit 1
elif [ "$target_major" -eq "$latest_major" ] && [ "$target_minor" -eq "$latest_minor" ] && [ "$target_patch" -lt "$latest_patch" ]; then
echo "::error::Target version v${base_version} is older than latest tag ${latest_tag}"
exit 1
fi
# For stable releases, ensure version is strictly newer
if [ "$is_prerelease" = "false" ]; then
if [ "$target_major" -eq "$latest_major" ] && [ "$target_minor" -eq "$latest_minor" ] && [ "$target_patch" -eq "$latest_patch" ]; then
echo "::error::Stable release v${base_version} already exists as ${latest_tag}"
exit 1
fi
fi
# For prereleases, check if a stable version already exists for this base version
if [ "$is_prerelease" = "true" ]; then
existing_stable=$(git tag --list "v${base_version}" | head -n 1)
if [ -n "$existing_stable" ]; then
echo "::error::Cannot create prerelease ${tag} - stable version v${base_version} already exists"
exit 1
fi
fi
# Check for suspicious jumps (likely typos)
major_jump=$((target_major - latest_major))
minor_jump=$((target_minor - latest_minor))
patch_jump=$((target_patch - latest_patch))
# Flag suspicious patterns
if [ "$major_jump" -gt 1 ]; then
echo "::error::Suspicious major version jump: ${latest_tag} → ${tag} (jumping ${major_jump} major versions). Typo?"
exit 1
elif [ "$major_jump" -eq 0 ] && [ "$minor_jump" -gt 5 ]; then
echo "::error::Suspicious minor version jump: ${latest_tag} → ${tag} (jumping ${minor_jump} minor versions). Typo?"
exit 1
elif [ "$major_jump" -eq 0 ] && [ "$minor_jump" -eq 0 ] && [ "$patch_jump" -gt 10 ]; then
echo "::error::Suspicious patch version jump: ${latest_tag} → ${tag} (jumping ${patch_jump} patch versions). Typo?"
exit 1
fi
echo "✅ Version sanity check passed: ${latest_tag} → ${tag}"
echo "version=$tag" >> $GITHUB_OUTPUT
echo "is_prerelease=$is_prerelease" >> $GITHUB_OUTPUT
echo "Version: $tag, Prerelease: $is_prerelease"
migration-check:
name: Flyway Migration Check on Master
needs: [ get-base-ref ]
name: Flyway Migration Check
needs: [ validate-tag ]
uses: ./.github/workflows/migrations-check.yml
with:
base_ref: ${{ needs.get-base-ref.outputs.base_ref }}
head_ref: ${{ github.sha }}
base_ref: 'master~1'
head_ref: 'master'
backend-tests:
name: Backend Tests
@@ -138,13 +232,12 @@ jobs:
exit 1
build-and-release:
needs: [ backend-tests, frontend-tests ]
needs: [ validate-tag, backend-tests, frontend-tests ]
if: needs.backend-tests.result == 'success' && needs.frontend-tests.result == 'success'
runs-on: ubuntu-latest
permissions:
contents: write
packages: write
pull-requests: read
steps:
- name: Checkout Repository
@@ -171,82 +264,34 @@ jobs:
- name: Set Up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Retrieve Latest Master Version Tag
id: get_version
- name: Compute Docker Tags
id: docker_tags
run: |
latest_tag=$(git tag --list "v*" --sort=-v:refname | head -n 1)
latest_tag=${latest_tag:-"v0.0.0"}
echo "latest_tag=$latest_tag" >> $GITHUB_ENV
echo "Latest master tag: $latest_tag"
version="${{ needs.validate-tag.outputs.version }}"
is_prerelease="${{ needs.validate-tag.outputs.is_prerelease }}"
- name: Determine Version Bump
id: determine_bump
env:
GH_TOKEN: ${{ github.token }}
run: |
echo "Determining version bump from PR labels..."
# Always include the version tag
tags="booklore/booklore:${version}"
tags="${tags},ghcr.io/booklore-app/booklore:${version}"
# Extract PR number from merge commit
pr_number=$(git log -1 --pretty=%B | grep -oE 'Merge pull request #[0-9]+' | grep -oE '[0-9]+') || true
if [ -z "$pr_number" ]; then
pr_number=$(gh pr list --state merged --base master --limit 1 --json number --jq '.[0].number')
fi
echo "PR number: $pr_number"
labels=$(gh pr view "$pr_number" --json labels --jq '.labels[].name' || echo "")
echo "PR labels: $labels"
if echo "$labels" | grep -q 'bump:major'; then
bump="major"
elif echo "$labels" | grep -q 'bump:minor'; then
bump="minor"
elif echo "$labels" | grep -q 'bump:patch'; then
bump="patch"
else
last_commit_msg=$(git log -1 --pretty=%B)
if echo "$last_commit_msg" | grep -iq '#major'; then
bump="major"
elif echo "$last_commit_msg" | grep -iq '#minor'; then
bump="minor"
elif echo "$last_commit_msg" | grep -iq '#patch'; then
bump="patch"
else
bump="patch"
fi
# Only add 'latest' tag for stable releases (not prereleases)
if [ "$is_prerelease" = "false" ]; then
tags="${tags},booklore/booklore:latest"
tags="${tags},ghcr.io/booklore-app/booklore:latest"
fi
# Calculate next version
semver=$(echo ${{ env.latest_tag }} | sed 's/^v//')
major=$(echo $semver | cut -d. -f1)
minor=$(echo $semver | cut -d. -f2)
patch=$(echo $semver | cut -d. -f3)
echo "tags=$tags" >> $GITHUB_OUTPUT
echo "Docker tags: $tags"
case "$bump" in
major) major=$((major+1)); minor=0; patch=0 ;;
minor) minor=$((minor+1)); patch=0 ;;
patch) patch=$((patch+1)) ;;
esac
next_version="v${major}.${minor}.${patch}"
echo "Version bump type: $bump"
echo "Next version: $next_version"
echo "bump=$bump" >> $GITHUB_ENV
echo "new_tag=$next_version" >> $GITHUB_ENV
- name: Build and push Docker image
- name: Build and Push Docker Image
uses: docker/build-push-action@v6
with:
context: .
platforms: linux/amd64,linux/arm64
push: true
tags: |
booklore/booklore:${{ env.new_tag }}
booklore/booklore:latest
ghcr.io/booklore-app/booklore:${{ env.new_tag }}
ghcr.io/booklore-app/booklore:latest
tags: ${{ steps.docker_tags.outputs.tags }}
build-args: |
APP_VERSION=${{ env.new_tag }}
APP_VERSION=${{ needs.validate-tag.outputs.version }}
APP_REVISION=${{ github.sha }}
cache-from: |
type=gha
@@ -255,16 +300,39 @@ jobs:
type=gha,mode=max
type=registry,ref=ghcr.io/booklore-app/booklore:buildcache,mode=max
- name: Update GitHub Release Draft
- name: Create GitHub Release
uses: release-drafter/release-drafter@v6
with:
tag: ${{ env.new_tag }}
name: "Release ${{ env.new_tag }}"
tag: ${{ needs.validate-tag.outputs.version }}
name: "Release ${{ needs.validate-tag.outputs.version }}"
prerelease: ${{ needs.validate-tag.outputs.is_prerelease }}
publish: true
env:
GITHUB_TOKEN: ${{ github.token }}
- name: Publish GitHub Draft Release
env:
GITHUB_TOKEN: ${{ github.token }}
- name: Release Summary
run: |
gh release edit ${{ env.new_tag }} --draft=true
version="${{ needs.validate-tag.outputs.version }}"
is_prerelease="${{ needs.validate-tag.outputs.is_prerelease }}"
echo "## Release Published" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "**Version:** \`${version}\`" >> $GITHUB_STEP_SUMMARY
if [ "$is_prerelease" = "true" ]; then
echo "**Type:** Prerelease" >> $GITHUB_STEP_SUMMARY
else
echo "**Type:** Stable Release" >> $GITHUB_STEP_SUMMARY
fi
echo "" >> $GITHUB_STEP_SUMMARY
echo "**Docker Images:**" >> $GITHUB_STEP_SUMMARY
echo "- \`booklore/booklore:${version}\`" >> $GITHUB_STEP_SUMMARY
echo "- \`ghcr.io/booklore-app/booklore:${version}\`" >> $GITHUB_STEP_SUMMARY
if [ "$is_prerelease" = "false" ]; then
echo "- \`booklore/booklore:latest\`" >> $GITHUB_STEP_SUMMARY
echo "- \`ghcr.io/booklore-app/booklore:latest\`" >> $GITHUB_STEP_SUMMARY
fi
echo "" >> $GITHUB_STEP_SUMMARY
echo "**Install:**" >> $GITHUB_STEP_SUMMARY
echo "\`\`\`bash" >> $GITHUB_STEP_SUMMARY
echo "docker pull booklore/booklore:${version}" >> $GITHUB_STEP_SUMMARY
echo "\`\`\`" >> $GITHUB_STEP_SUMMARY
+2 -1
View File
@@ -32,7 +32,8 @@ jobs:
id: check_migrations
run: |
echo "Comparing ${{ inputs.base_ref }}...${{ inputs.head_ref }}"
if git diff --name-only ${{ inputs.base_ref }}...${{ inputs.head_ref }} | grep -q "booklore-api/src/main/resources/db/migration/V.*.sql"; then
# Use explicit regex: V followed by digits, then double underscore, then any name, ending in .sql
if git diff --name-only ${{ inputs.base_ref }}...${{ inputs.head_ref }} | grep -qE "booklore-api/src/main/resources/db/migration/V[0-9]+__.*\.sql"; then
echo "Migration file changes detected. Proceeding with migration preview."
echo "has_migrations=true" >> $GITHUB_OUTPUT
else
+320
View File
@@ -0,0 +1,320 @@
name: Release Branch – Build, Test, and RC Publish
on:
push:
branches:
- 'release/**'
pull_request:
branches:
- 'release/**'
jobs:
migration-check:
name: Flyway Migration Check
uses: ./.github/workflows/migrations-check.yml
with:
base_ref: 'master'
head_ref: 'HEAD'
backend-tests:
name: Backend Tests
needs: [ migration-check ]
if: needs.migration-check.result == 'success' || needs.migration-check.result == 'skipped'
runs-on: ubuntu-latest
permissions:
contents: read
checks: write
pull-requests: write
steps:
- name: Checkout Repository
uses: actions/checkout@v6
- name: Set Up JDK 21
uses: actions/setup-java@v5
with:
java-version: '21'
distribution: 'temurin'
cache: gradle
- name: Execute Backend Tests
id: backend_tests
working-directory: ./booklore-api
run: |
echo "Running backend tests..."
./gradlew test --no-daemon --parallel --build-cache
continue-on-error: true
- name: Publish Backend Test Results
uses: EnricoMi/publish-unit-test-result-action@v2
if: always()
with:
files: booklore-api/build/test-results/**/*.xml
check_name: Backend Test Results
- name: Upload Backend Test Reports
uses: actions/upload-artifact@v6
if: always()
with:
name: backend-test-reports
path: |
booklore-api/build/reports/tests/
booklore-api/build/test-results/
retention-days: 30
- name: Validate Backend Test Results
if: steps.backend_tests.outcome == 'failure'
run: |
echo "❌ Backend tests failed"
exit 1
frontend-tests:
name: Frontend Tests
needs: [ migration-check ]
if: needs.migration-check.result == 'success' || needs.migration-check.result == 'skipped'
runs-on: ubuntu-latest
permissions:
contents: read
checks: write
pull-requests: write
steps:
- name: Checkout Repository
uses: actions/checkout@v6
- name: Set Up Node.js
uses: actions/setup-node@v4
with:
node-version: '22'
cache: 'npm'
cache-dependency-path: booklore-ui/package-lock.json
- name: Install Frontend Dependencies
working-directory: ./booklore-ui
run: npm ci --force
- name: Execute Frontend Tests
id: frontend_tests
working-directory: ./booklore-ui
run: |
echo "Running frontend tests..."
npx ng test
continue-on-error: true
- name: Publish Frontend Test Results
uses: EnricoMi/publish-unit-test-result-action@v2
if: always()
with:
files: booklore-ui/test-results/vitest-results.xml
check_name: Frontend Test Results
- name: Upload Frontend Test Reports
uses: actions/upload-artifact@v6
if: always()
with:
name: frontend-test-reports
path: |
booklore-ui/test-results/vitest-results.xml
retention-days: 30
- name: Validate Frontend Test Results
if: steps.frontend_tests.outcome == 'failure'
run: |
echo "❌ Frontend tests failed"
exit 1
build-and-push-rc:
name: Build and Push RC Container
needs: [ backend-tests, frontend-tests ]
if: github.event_name == 'push'
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- name: Checkout Repository
uses: actions/checkout@v6
with:
fetch-depth: 0
# ----------------------------------------
# Environment setup
# ----------------------------------------
- name: Set Up QEMU for Multi-Arch Builds
uses: docker/setup-qemu-action@v3
- name: Set Up Docker Buildx
uses: docker/setup-buildx-action@v3
# ----------------------------------------
# RC version tagging
# ----------------------------------------
- name: Generate RC Version Tag
id: version
run: |
# Extract version from branch name (release/1.2 → 1.2)
branch_name="${{ github.ref_name }}"
branch_version=$(echo "$branch_name" | sed 's|release/||')
# Validate version format (must be X.Y or X.Y.Z)
if ! echo "$branch_version" | grep -qE '^[0-9]+\.[0-9]+(\.[0-9]+)?$'; then
echo "::error::Invalid release branch format. Expected 'release/X.Y' or 'release/X.Y.Z', got '$branch_name'"
exit 1
fi
# Normalize to X.Y.Z format (append .0 if only X.Y)
if echo "$branch_version" | grep -qE '^[0-9]+\.[0-9]+$'; then
full_version="${branch_version}.0"
else
full_version="$branch_version"
fi
# ----------------------------------------
# Version sanity check against latest tag
# ----------------------------------------
latest_tag=$(git tag --list "v*" --sort=-v:refname | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$' | head -n 1)
latest_tag=${latest_tag:-"v0.0.0"}
echo "Latest stable tag: $latest_tag"
# Parse latest version
latest_semver=$(echo "$latest_tag" | sed 's/^v//')
latest_major=$(echo "$latest_semver" | cut -d. -f1)
latest_minor=$(echo "$latest_semver" | cut -d. -f2)
latest_patch=$(echo "$latest_semver" | cut -d. -f3)
# Parse target version
target_major=$(echo "$full_version" | cut -d. -f1)
target_minor=$(echo "$full_version" | cut -d. -f2)
target_patch=$(echo "$full_version" | cut -d. -f3)
echo "Latest: v${latest_major}.${latest_minor}.${latest_patch}"
echo "Target: v${target_major}.${target_minor}.${target_patch}"
# Check for backwards version (target < latest)
if [ "$target_major" -lt "$latest_major" ]; then
echo "::error::Target version v${full_version} is older than latest tag ${latest_tag}"
exit 1
elif [ "$target_major" -eq "$latest_major" ] && [ "$target_minor" -lt "$latest_minor" ]; then
echo "::error::Target version v${full_version} is older than latest tag ${latest_tag}"
exit 1
elif [ "$target_major" -eq "$latest_major" ] && [ "$target_minor" -eq "$latest_minor" ] && [ "$target_patch" -lt "$latest_patch" ]; then
echo "::error::Target version v${full_version} is older than latest tag ${latest_tag}"
exit 1
fi
# Check for suspicious jumps (likely typos)
major_jump=$((target_major - latest_major))
minor_jump=$((target_minor - latest_minor))
patch_jump=$((target_patch - latest_patch))
# Flag suspicious patterns
if [ "$major_jump" -gt 1 ]; then
echo "::error::Suspicious major version jump: ${latest_tag} → v${full_version} (jumping ${major_jump} major versions). Typo?"
exit 1
elif [ "$major_jump" -eq 0 ] && [ "$minor_jump" -gt 5 ]; then
echo "::error::Suspicious minor version jump: ${latest_tag} → v${full_version} (jumping ${minor_jump} minor versions). Typo?"
exit 1
elif [ "$major_jump" -eq 0 ] && [ "$minor_jump" -eq 0 ] && [ "$patch_jump" -gt 10 ]; then
echo "::error::Suspicious patch version jump: ${latest_tag} → v${full_version} (jumping ${patch_jump} patch versions). Typo?"
exit 1
fi
# Warn (but don't fail) for moderate jumps
if [ "$minor_jump" -gt 1 ] && [ "$minor_jump" -le 5 ]; then
echo "::warning::Skipping minor versions: ${latest_tag} → v${full_version}. Is this intentional?"
fi
echo "✅ Version sanity check passed: ${latest_tag} → v${full_version}"
# ----------------------------------------
# Calculate RC number
# ----------------------------------------
# Find the merge-base with develop to count commits accurately
# This ensures RC numbers are stable even if develop moves forward
if git rev-parse origin/develop >/dev/null 2>&1; then
merge_base=$(git merge-base origin/develop HEAD 2>/dev/null || echo "")
if [ -n "$merge_base" ]; then
rc_number=$(git rev-list --count ${merge_base}..HEAD 2>/dev/null || echo "1")
else
rc_number=$(git rev-list --count HEAD 2>/dev/null || echo "1")
fi
else
rc_number=$(git rev-list --count HEAD 2>/dev/null || echo "1")
fi
# Ensure RC number is at least 1
rc_number=$((rc_number > 0 ? rc_number : 1))
rc_tag="v${full_version}-rc.${rc_number}"
short_sha=$(git rev-parse --short HEAD)
# Sanitize branch name for Docker tag (replace / with -)
safe_branch_name=$(echo "$branch_name" | tr '/' '-')
echo "rc_tag=$rc_tag" >> $GITHUB_ENV
echo "branch_version=$branch_version" >> $GITHUB_ENV
echo "full_version=$full_version" >> $GITHUB_ENV
echo "short_sha=$short_sha" >> $GITHUB_ENV
echo "safe_branch_name=$safe_branch_name" >> $GITHUB_ENV
echo "Release branch: $branch_name"
echo "Full version: $full_version"
echo "RC tag: $rc_tag"
# ----------------------------------------
# Docker login
# ----------------------------------------
- name: Authenticate to Docker Hub
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Authenticate to GitHub Container Registry
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ github.token }}
# ----------------------------------------
# Docker build & push
# ----------------------------------------
- name: Build and Push RC Docker Image
uses: docker/build-push-action@v6
with:
context: .
platforms: linux/amd64,linux/arm64
push: true
tags: |
booklore/booklore:${{ env.rc_tag }}
booklore/booklore:${{ env.safe_branch_name }}-${{ env.short_sha }}
ghcr.io/booklore-app/booklore:${{ env.rc_tag }}
ghcr.io/booklore-app/booklore:${{ env.safe_branch_name }}-${{ env.short_sha }}
build-args: |
APP_VERSION=${{ env.rc_tag }}
APP_REVISION=${{ github.sha }}
cache-from: |
type=gha
type=registry,ref=ghcr.io/booklore-app/booklore:buildcache
cache-to: |
type=gha,mode=max
type=registry,ref=ghcr.io/booklore-app/booklore:buildcache,mode=max
- name: Summary
run: |
echo "## RC Build Published" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "**Version:** \`${{ env.rc_tag }}\`" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "**Images:**" >> $GITHUB_STEP_SUMMARY
echo "- \`booklore/booklore:${{ env.rc_tag }}\`" >> $GITHUB_STEP_SUMMARY
echo "- \`ghcr.io/booklore-app/booklore:${{ env.rc_tag }}\`" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "**Test this RC:**" >> $GITHUB_STEP_SUMMARY
echo "\`\`\`bash" >> $GITHUB_STEP_SUMMARY
echo "docker pull booklore/booklore:${{ env.rc_tag }}" >> $GITHUB_STEP_SUMMARY
echo "\`\`\`" >> $GITHUB_STEP_SUMMARY
+1
View File
@@ -40,6 +40,7 @@ out/
### VS Code ###
.vscode/
local/
local-scripts/
### Dev config, books, and data ###
booklore-ui/test-results/
+65 -78
View File
@@ -1,5 +1,5 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
@@ -7,17 +7,15 @@
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
@@ -26,44 +24,34 @@ them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
@@ -72,7 +60,7 @@ modification follow.
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
@@ -549,35 +537,45 @@ to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
@@ -635,40 +633,29 @@ the "copyright" line and a pointer to where the full notice is found.
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
GNU Affero General Public License for more details.
You should have received a copy of the GNU General Public License
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
+7 -4
View File
@@ -437,6 +437,10 @@ Join community!
<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">
</a>
*Become a sponsor and get your logo here! [Support us on Open Collective](https://opencollective.com/booklore)*
@@ -448,12 +452,11 @@ Join community!
## ⚖️ **License**
**GNU General Public License v3.0**
**GNU Affero General Public License v3.0 (AGPL-3.0)**
Copyright © 2024-2025 BookLore
[![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg?style=for-the-badge)](http://www.gnu.org/licenses/gpl.html)
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>
+7
View File
@@ -58,6 +58,9 @@ dependencies {
implementation 'org.apache.pdfbox:pdfbox-io:3.0.6'
implementation 'org.apache.pdfbox:xmpbox:3.0.6'
implementation 'org.apache.pdfbox:jbig2-imageio:3.0.4'
// Required for JPEG2000 support in PDFBox (not covered by TwelveMonkeys)
implementation 'com.github.jai-imageio:jai-imageio-core:1.4.0'
implementation 'com.github.jai-imageio:jai-imageio-jpeg2000:1.4.0'
// --- TwelveMonkeys ImageIO ---
implementation 'com.twelvemonkeys.imageio:imageio-jpeg:3.13.0'
@@ -87,10 +90,14 @@ dependencies {
// --- Template Engine ---
implementation 'org.freemarker:freemarker:2.3.34'
// --- Caching ---
implementation 'com.github.ben-manes.caffeine:caffeine:3.2.0'
// --- Test Dependencies ---
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.assertj:assertj-core:3.27.6'
testImplementation "org.mockito:mockito-inline:5.2.0"
testRuntimeOnly 'com.h2database:h2'
}
hibernate {
@@ -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, LubimyCzytacParser lubimyczytacParser) {
GoodReadsParser goodReadsParser, HardcoverParser hardcoverParser, ComicvineBookParser comicvineBookParser, DoubanBookParser doubanBookParser, RanobeDbParser ranobedbParser, LubimyCzytacParser lubimyczytacParser) {
return Map.of(
MetadataProvider.Amazon, amazonBookParser,
MetadataProvider.GoodReads, goodReadsParser,
@@ -20,7 +20,8 @@ public class BookParserConfig {
MetadataProvider.Hardcover, hardcoverParser,
MetadataProvider.Comicvine, comicvineBookParser,
MetadataProvider.Douban, doubanBookParser,
MetadataProvider.Lubimyczytac, lubimyczytacParser
MetadataProvider.Lubimyczytac, lubimyczytacParser,
MetadataProvider.Ranobedb, ranobedbParser
);
}
}
@@ -0,0 +1,44 @@
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;
}
}
@@ -0,0 +1,48 @@
package com.adityachandel.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 java.util.Collection;
/**
* Custom BeanPropertyWriter that handles clean mode filtering.
* When clean mode is enabled:
* - Fields ending with "Lock" are excluded
* - Null values are excluded
* - Empty arrays/collections are excluded
*/
public class KomgaCleanBeanPropertyWriter extends BeanPropertyWriter {
protected KomgaCleanBeanPropertyWriter(BeanPropertyWriter base) {
super(base);
}
@Override
public void serializeAsField(Object bean, JsonGenerator gen, SerializerProvider prov) throws Exception {
if (KomgaCleanContext.isCleanMode()) {
String propertyName = getName();
// Exclude properties ending with "Lock"
if (propertyName.endsWith("Lock")) {
return;
}
// Exclude null values
Object value = get(bean);
if (value == null) {
return;
}
// Exclude empty collections/arrays
if (value instanceof Collection && ((Collection<?>) value).isEmpty()) {
return;
}
}
// Default behavior
super.serializeAsField(bean, gen, prov);
}
}
@@ -1,5 +1,7 @@
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;
@@ -11,10 +13,16 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
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/**");
}
}
@@ -88,6 +88,28 @@ public class SecurityConfig {
@Bean
@Order(2)
public SecurityFilterChain komgaBasicAuthSecurityChain(HttpSecurity http) throws Exception {
http
.securityMatcher("/komga/api/v1/**", "/komga/api/v2/**")
.csrf(AbstractHttpConfigurer::disable)
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(auth -> auth
.anyRequest().authenticated()
)
.httpBasic(basic -> basic
.realmName("Booklore Komga API")
.authenticationEntryPoint((request, response, authException) -> {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setHeader("WWW-Authenticate", "Basic realm=\"Booklore Komga API\"");
response.getWriter().write("HTTP Status 401 - " + authException.getMessage());
})
);
return http.build();
}
@Bean
@Order(3)
public SecurityFilterChain koreaderSecurityChain(HttpSecurity http, KoreaderAuthFilter koreaderAuthFilter) throws Exception {
http
.securityMatcher("/api/koreader/**")
@@ -146,6 +168,21 @@ public class SecurityConfig {
@Bean
@Order(6)
public SecurityFilterChain epubStreamingSecurityChain(HttpSecurity http, EpubStreamingJwtFilter epubStreamingJwtFilter) throws Exception {
http
.securityMatcher("/api/v1/epub/*/file/**")
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
.csrf(AbstractHttpConfigurer::disable)
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(auth -> auth
.anyRequest().permitAll()
)
.addFilterBefore(epubStreamingJwtFilter, UsernamePasswordAuthenticationFilter.class);
return http.build();
}
@Bean
@Order(7)
public SecurityFilterChain jwtApiSecurityChain(HttpSecurity http) throws Exception {
List<String> publicEndpoints = new ArrayList<>(Arrays.asList(COMMON_PUBLIC_ENDPOINTS));
if (appProperties.getSwagger().isEnabled()) {
@@ -185,4 +222,4 @@ public class SecurityConfig {
return source;
}
}
}
@@ -129,4 +129,14 @@ public class SecurityUtil {
var user = getCurrentUser();
return user != null && user.getPermissions().isCanAccessTaskManager();
}
public boolean canReadShelf(Long shelfId) {
var user = getCurrentUser();
if (user != null) {
return shelfRepository.findById(shelfId)
.map(shelf -> shelf.isPublic() || shelf.getUser().getId().equals(user.getId()))
.orElse(false);
}
return false;
}
}
@@ -0,0 +1,119 @@
package com.adityachandel.booklore.config.security.filter;
import com.adityachandel.booklore.config.security.JwtUtils;
import com.adityachandel.booklore.config.security.service.DynamicOidcJwtProcessor;
import com.adityachandel.booklore.config.security.userdetails.UserAuthenticationDetails;
import com.adityachandel.booklore.mapper.custom.BookLoreUserTransformer;
import com.adityachandel.booklore.model.dto.BookLoreUser;
import com.adityachandel.booklore.model.dto.settings.OidcProviderDetails;
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
import com.adityachandel.booklore.repository.UserRepository;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
import java.time.Instant;
import java.util.regex.Pattern;
/**
* JWT filter for EPUB streaming endpoints that supports both:
* 1. Authorization header (Bearer token) - for fetch() requests
* 2. Query parameter (token) - for browser-initiated requests (fonts, images in CSS)
*/
@Component
@AllArgsConstructor
public class EpubStreamingJwtFilter extends OncePerRequestFilter {
private static final Pattern EPUB_STREAMING_ENDPOINT_PATTERN = Pattern.compile("/api/v1/epub/\\d+/file/.*");
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();
// Only filter requests to EPUB file streaming endpoint
return !EPUB_STREAMING_ENDPOINT_PATTERN.matcher(path).matches();
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
// Try Authorization header first, then fall back to query parameter
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);
}
}
@@ -16,7 +16,9 @@ public class ImageCachingFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
String uri = request.getRequestURI();
if (uri.startsWith("/api/v1/media/book/") && (uri.contains("/cover") || uri.contains("/thumbnail") || uri.contains("/backup-cover"))) {
if (uri.startsWith("/api/v1/media/book/") &&
(uri.contains("/cover") || uri.contains("/thumbnail") || uri.contains("/backup-cover") ||
uri.contains("/pdf/pages/") || uri.contains("/cbx/pages/"))) {
response.setHeader(HttpHeaders.CACHE_CONTROL, "public, max-age=3600");
response.setHeader(HttpHeaders.EXPIRES, String.valueOf(System.currentTimeMillis() + 3600_000));
}
@@ -49,6 +49,7 @@ public class KoreaderAuthFilter extends OncePerRequestFilter {
user.getUsername(),
user.getPasswordMD5(),
user.isSyncEnabled(),
user.isSyncWithBookloreReader(),
bookLoreUserId,
List.of(new SimpleGrantedAuthority("ROLE_USER"))
);
@@ -22,11 +22,13 @@ import java.time.Duration;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
@Slf4j
@Component
@RequiredArgsConstructor
public class DynamicOidcJwtProcessor {
private static final Pattern TRAILING_SLASH_PATTERN = Pattern.compile("/$");
private final AppSettingService appSettingService;
private volatile ConfigurableJWTProcessor<SecurityContext> jwtProcessor;
@@ -48,7 +50,7 @@ public class DynamicOidcJwtProcessor {
throw new IllegalStateException("OIDC issuer URI is not configured in app settings.");
}
String discoveryUri = providerDetails.getIssuerUri().replaceAll("/$", "") + "/.well-known/openid-configuration";
String discoveryUri = TRAILING_SLASH_PATTERN.matcher(providerDetails.getIssuerUri()).replaceAll("") + "/.well-known/openid-configuration";
log.info("Fetching OIDC discovery document from {}", discoveryUri);
URI jwksUri = fetchJwksUri(discoveryUri);
@@ -13,13 +13,16 @@ public class KoreaderUserDetails implements UserDetails {
@Getter
private final boolean syncEnabled;
@Getter
private final boolean syncWithBookloreReader;
@Getter
private final Long bookLoreUserId;
private final Collection<? extends GrantedAuthority> authorities;
public KoreaderUserDetails(String username, String password, boolean syncEnabled, Long bookLoreUserId, Collection<? extends GrantedAuthority> authorities) {
public KoreaderUserDetails(String username, String password, boolean syncEnabled, boolean syncWithBookloreReader, Long bookLoreUserId, Collection<? extends GrantedAuthority> authorities) {
this.username = username;
this.password = password;
this.syncEnabled = syncEnabled;
this.syncWithBookloreReader = syncWithBookloreReader;
this.bookLoreUserId = bookLoreUserId;
this.authorities = authorities;
}
@@ -0,0 +1,24 @@
package com.adityachandel.booklore.context;
/**
* ThreadLocal context to track whether the Komga API "clean" mode is enabled.
* When clean mode is enabled:
* - Fields ending with "Lock" are excluded from JSON serialization
* - Null values are excluded from JSON serialization
* - Metadata fields (language, summary, etc.) are allowed to be null
*/
public class KomgaCleanContext {
private static final ThreadLocal<Boolean> cleanModeEnabled = ThreadLocal.withInitial(() -> false);
public static void setCleanMode(boolean enabled) {
cleanModeEnabled.set(enabled);
}
public static boolean isCleanMode() {
return cleanModeEnabled.get();
}
public static void clear() {
cleanModeEnabled.remove();
}
}
@@ -1,8 +1,8 @@
package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.config.security.annotation.CheckBookAccess;
import com.adityachandel.booklore.model.dto.AdditionalFile;
import com.adityachandel.booklore.model.enums.AdditionalFileType;
import com.adityachandel.booklore.model.dto.BookFile;
import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.service.file.AdditionalFileService;
import com.adityachandel.booklore.service.upload.FileUploadService;
import lombok.AllArgsConstructor;
@@ -25,29 +25,30 @@ public class AdditionalFileController {
@GetMapping
@CheckBookAccess(bookIdParam = "bookId")
public ResponseEntity<List<AdditionalFile>> getAdditionalFiles(@PathVariable Long bookId) {
List<AdditionalFile> files = additionalFileService.getAdditionalFilesByBookId(bookId);
public ResponseEntity<List<BookFile>> getAdditionalFiles(@PathVariable Long bookId) {
List<BookFile> files = additionalFileService.getAdditionalFilesByBookId(bookId);
return ResponseEntity.ok(files);
}
@GetMapping(params = "type")
@GetMapping(params = "isBook")
@CheckBookAccess(bookIdParam = "bookId")
public ResponseEntity<List<AdditionalFile>> getAdditionalFilesByType(
public ResponseEntity<List<BookFile>> getFilesByIsBook(
@PathVariable Long bookId,
@RequestParam AdditionalFileType type) {
List<AdditionalFile> files = additionalFileService.getAdditionalFilesByBookIdAndType(bookId, type);
@RequestParam boolean isBook) {
List<BookFile> files = additionalFileService.getAdditionalFilesByBookIdAndIsBook(bookId, isBook);
return ResponseEntity.ok(files);
}
@PostMapping(consumes = "multipart/form-data")
@CheckBookAccess(bookIdParam = "bookId")
@PreAuthorize("@securityUtil.canUpload() or @securityUtil.isAdmin()")
public ResponseEntity<AdditionalFile> uploadAdditionalFile(
public ResponseEntity<BookFile> uploadAdditionalFile(
@PathVariable Long bookId,
@RequestParam("file") MultipartFile file,
@RequestParam AdditionalFileType additionalFileType,
@RequestParam boolean isBook,
@RequestParam(required = false) BookFileType bookType,
@RequestParam(required = false) String description) {
AdditionalFile additionalFile = fileUploadService.uploadAdditionalFile(bookId, file, additionalFileType, description);
BookFile additionalFile = fileUploadService.uploadAdditionalFile(bookId, file, isBook, bookType, description);
return ResponseEntity.ok(additionalFile);
}
@@ -0,0 +1,67 @@
package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.model.dto.Annotation;
import com.adityachandel.booklore.model.dto.CreateAnnotationRequest;
import com.adityachandel.booklore.model.dto.UpdateAnnotationRequest;
import com.adityachandel.booklore.service.book.AnnotationService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/v1/annotations")
@Tag(name = "Annotations", description = "Endpoints for managing book annotations (highlights, underlines, etc.)")
public class AnnotationController {
private final AnnotationService annotationService;
@Operation(summary = "Get annotations for a book", description = "Retrieve all annotations for a specific book.")
@ApiResponse(responseCode = "200", description = "Annotations returned successfully")
@GetMapping("/book/{bookId}")
public List<Annotation> getAnnotationsForBook(
@Parameter(description = "ID of the book") @PathVariable Long bookId) {
return annotationService.getAnnotationsForBook(bookId);
}
@Operation(summary = "Get a specific annotation", description = "Retrieve a specific annotation by its ID.")
@ApiResponse(responseCode = "200", description = "Annotation returned successfully")
@GetMapping("/{annotationId}")
public Annotation getAnnotationById(
@Parameter(description = "ID of the annotation") @PathVariable Long annotationId) {
return annotationService.getAnnotationById(annotationId);
}
@Operation(summary = "Create an annotation", description = "Create a new annotation (highlight, underline, etc.) for a book.")
@ApiResponse(responseCode = "200", description = "Annotation created successfully")
@PostMapping
public Annotation createAnnotation(
@Parameter(description = "Annotation creation request") @Valid @RequestBody CreateAnnotationRequest request) {
return annotationService.createAnnotation(request);
}
@Operation(summary = "Update an annotation", description = "Update an existing annotation's properties (color, style, note).")
@ApiResponse(responseCode = "200", description = "Annotation updated successfully")
@PutMapping("/{annotationId}")
public Annotation updateAnnotation(
@Parameter(description = "ID of the annotation to update") @PathVariable Long annotationId,
@Parameter(description = "Annotation update request") @Valid @RequestBody UpdateAnnotationRequest request) {
return annotationService.updateAnnotation(annotationId, request);
}
@Operation(summary = "Delete an annotation", description = "Delete a specific annotation by its ID.")
@ApiResponse(responseCode = "204", description = "Annotation deleted successfully")
@DeleteMapping("/{annotationId}")
public ResponseEntity<Void> deleteAnnotation(
@Parameter(description = "ID of the annotation to delete") @PathVariable Long annotationId) {
annotationService.deleteAnnotation(annotationId);
return ResponseEntity.noContent().build();
}
}
@@ -102,8 +102,7 @@ public class BookController {
@ApiResponse(responseCode = "200", description = "Book content returned successfully")
@GetMapping("/{bookId}/content")
@CheckBookAccess(bookIdParam = "bookId")
public ResponseEntity<ByteArrayResource> getBookContent(
@Parameter(description = "ID of the book") @PathVariable long bookId) throws IOException {
public ResponseEntity<ByteArrayResource> getBookContent(@Parameter(description = "ID of the book") @PathVariable long bookId) throws IOException {
return bookService.getBookContent(bookId);
}
@@ -115,8 +114,7 @@ public class BookController {
@GetMapping("/{bookId}/download")
@PreAuthorize("@securityUtil.canDownload() or @securityUtil.isAdmin()")
@CheckBookAccess(bookIdParam = "bookId")
public ResponseEntity<Resource> downloadBook(
@Parameter(description = "ID of the book to download") @PathVariable("bookId") Long bookId) {
public ResponseEntity<Resource> downloadBook(@Parameter(description = "ID of the book to download") @PathVariable("bookId") Long bookId) {
return bookService.downloadBook(bookId);
}
@@ -124,8 +122,7 @@ public class BookController {
@ApiResponse(responseCode = "200", description = "Viewer settings returned successfully")
@GetMapping("/{bookId}/viewer-setting")
@CheckBookAccess(bookIdParam = "bookId")
public ResponseEntity<BookViewerSettings> getBookViewerSettings(
@Parameter(description = "ID of the book") @PathVariable long bookId) {
public ResponseEntity<BookViewerSettings> getBookViewerSettings(@Parameter(description = "ID of the book") @PathVariable long bookId) {
return ResponseEntity.ok(bookService.getBookViewerSetting(bookId));
}
@@ -85,6 +85,14 @@ public class BookCoverController {
bookCoverService.regenerateCoversForBooks(request.getBookIds());
}
@Operation(summary = "Generate custom covers for selected books", description = "Generate custom covers for a list of books. Requires metadata edit permission or admin.")
@ApiResponse(responseCode = "204", description = "Custom cover generation started successfully")
@PostMapping("/bulk-generate-custom-covers")
@PreAuthorize("@securityUtil.canBulkRegenerateCover() or @securityUtil.isAdmin()")
public void generateCustomCoversForBooks(@Parameter(description = "List of book IDs") @Validated @RequestBody BulkBookIdsRequest request) {
bookCoverService.generateCustomCoversForBooks(request.getBookIds());
}
@Operation(summary = "Upload cover image for multiple books", description = "Upload a cover image to apply to multiple books. Requires metadata edit permission or admin.")
@ApiResponse(responseCode = "204", description = "Cover upload started successfully")
@PostMapping("/bulk-upload-cover")
@@ -4,7 +4,6 @@ import com.adityachandel.booklore.service.book.BookService;
import com.adityachandel.booklore.service.bookdrop.BookDropService;
import com.adityachandel.booklore.service.reader.CbxReaderService;
import com.adityachandel.booklore.service.reader.PdfReaderService;
import com.adityachandel.booklore.service.IconService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
@@ -21,9 +20,6 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.regex.Pattern;
@Tag(name = "Book Media", description = "Endpoints for retrieving book media such as covers, thumbnails, and pages")
@AllArgsConstructor
@@ -31,27 +27,22 @@ import java.util.regex.Pattern;
@RequestMapping("/api/v1/media")
public class BookMediaController {
private static final Pattern NON_ASCII_PATTERN = Pattern.compile("[^\\x00-\\x7F]");
private final BookService bookService;
private final PdfReaderService pdfReaderService;
private final CbxReaderService cbxReaderService;
private final BookDropService bookDropService;
private final IconService iconService;
@Operation(summary = "Get book thumbnail", description = "Retrieve the thumbnail image for a specific book.")
@ApiResponse(responseCode = "200", description = "Book thumbnail returned successfully")
@GetMapping("/book/{bookId}/thumbnail")
public ResponseEntity<Resource> getBookThumbnail(
@Parameter(description = "ID of the book") @PathVariable long bookId) {
public ResponseEntity<Resource> getBookThumbnail(@Parameter(description = "ID of the book") @PathVariable long bookId) {
return ResponseEntity.ok(bookService.getBookThumbnail(bookId));
}
@Operation(summary = "Get book cover", description = "Retrieve the cover image for a specific book.")
@ApiResponse(responseCode = "200", description = "Book cover returned successfully")
@GetMapping("/book/{bookId}/cover")
public ResponseEntity<Resource> getBookCover(
@Parameter(description = "ID of the book") @PathVariable long bookId) {
public ResponseEntity<Resource> getBookCover(@Parameter(description = "ID of the book") @PathVariable long bookId) {
return ResponseEntity.ok(bookService.getBookCover(bookId));
}
@@ -80,8 +71,7 @@ public class BookMediaController {
@Operation(summary = "Get bookdrop cover", description = "Retrieve the cover image for a specific bookdrop file.")
@ApiResponse(responseCode = "200", description = "Bookdrop cover returned successfully")
@GetMapping("/bookdrop/{bookdropId}/cover")
public ResponseEntity<Resource> getBookdropCover(
@Parameter(description = "ID of the bookdrop file") @PathVariable long bookdropId) {
public ResponseEntity<Resource> getBookdropCover(@Parameter(description = "ID of the bookdrop file") @PathVariable long bookdropId) {
Resource file = bookDropService.getBookdropCover(bookdropId);
String contentDisposition = "inline; filename=\"cover.jpg\"; filename*=UTF-8''cover.jpg";
return (file != null)
@@ -0,0 +1,67 @@
package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.model.dto.BookNoteV2;
import com.adityachandel.booklore.model.dto.CreateBookNoteV2Request;
import com.adityachandel.booklore.model.dto.UpdateBookNoteV2Request;
import com.adityachandel.booklore.service.book.BookNoteV2Service;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/v2/book-notes")
@Tag(name = "Book Notes V2", description = "Endpoints for managing CFI-based book notes with text selection context")
public class BookNotesV2Controller {
private final BookNoteV2Service bookNoteV2Service;
@Operation(summary = "Get notes for a book", description = "Retrieve all notes for a specific book.")
@ApiResponse(responseCode = "200", description = "Notes returned successfully")
@GetMapping("/book/{bookId}")
public List<BookNoteV2> getNotesForBook(
@Parameter(description = "ID of the book") @PathVariable Long bookId) {
return bookNoteV2Service.getNotesForBook(bookId);
}
@Operation(summary = "Get a specific note", description = "Retrieve a specific note by its ID.")
@ApiResponse(responseCode = "200", description = "Note returned successfully")
@GetMapping("/{noteId}")
public BookNoteV2 getNoteById(
@Parameter(description = "ID of the note") @PathVariable Long noteId) {
return bookNoteV2Service.getNoteById(noteId);
}
@Operation(summary = "Create a note", description = "Create a new note at a specific location in a book.")
@ApiResponse(responseCode = "200", description = "Note created successfully")
@PostMapping
public BookNoteV2 createNote(
@Parameter(description = "Note creation request") @Valid @RequestBody CreateBookNoteV2Request request) {
return bookNoteV2Service.createNote(request);
}
@Operation(summary = "Update a note", description = "Update an existing note's content or color.")
@ApiResponse(responseCode = "200", description = "Note updated successfully")
@PutMapping("/{noteId}")
public BookNoteV2 updateNote(
@Parameter(description = "ID of the note to update") @PathVariable Long noteId,
@Parameter(description = "Note update request") @Valid @RequestBody UpdateBookNoteV2Request request) {
return bookNoteV2Service.updateNote(noteId, request);
}
@Operation(summary = "Delete a note", description = "Delete a specific note by its ID.")
@ApiResponse(responseCode = "204", description = "Note deleted successfully")
@DeleteMapping("/{noteId}")
public ResponseEntity<Void> deleteNote(
@Parameter(description = "ID of the note to delete") @PathVariable Long noteId) {
bookNoteV2Service.deleteNote(noteId);
return ResponseEntity.noContent().build();
}
}
@@ -1,5 +1,6 @@
package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.model.dto.response.CbxPageInfo;
import com.adityachandel.booklore.service.reader.CbxReaderService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
@@ -24,8 +25,14 @@ public class CbxReaderController {
@Operation(summary = "List pages in a CBX book", description = "Retrieve a list of available page numbers for a CBX book.")
@ApiResponse(responseCode = "200", description = "Page numbers returned successfully")
@GetMapping("/{bookId}/pages")
public List<Integer> listPages(
@Parameter(description = "ID of the book") @PathVariable Long bookId) {
public List<Integer> listPages(@Parameter(description = "ID of the book") @PathVariable Long bookId) {
return cbxReaderService.getAvailablePages(bookId);
}
@Operation(summary = "Get page info for a CBX book", description = "Retrieve page information including display names for a CBX book.")
@ApiResponse(responseCode = "200", description = "Page info returned successfully")
@GetMapping("/{bookId}/page-info")
public List<CbxPageInfo> getPageInfo(@Parameter(description = "ID of the book") @PathVariable Long bookId) {
return cbxReaderService.getPageInfo(bookId);
}
}
@@ -0,0 +1,71 @@
package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.model.dto.response.EpubBookInfo;
import com.adityachandel.booklore.service.reader.EpubReaderService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.HandlerMapping;
import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
@RestController
@RequestMapping("/api/v1/epub")
@RequiredArgsConstructor
@Tag(name = "EPUB Reader", description = "Endpoints for reading EPUB format books with streaming support")
public class EpubReaderController {
private final EpubReaderService epubReaderService;
@Operation(summary = "Get EPUB book info",
description = "Retrieve parsed metadata, spine, manifest, and TOC for an EPUB book.")
@ApiResponse(responseCode = "200", description = "Book info returned successfully")
@GetMapping("/{bookId}/info")
public ResponseEntity<EpubBookInfo> getBookInfo(@Parameter(description = "ID of the book") @PathVariable Long bookId) {
return ResponseEntity.ok(epubReaderService.getBookInfo(bookId));
}
@Operation(summary = "Get file from EPUB", description = "Retrieve a specific file from within the EPUB archive (HTML, CSS, images, fonts, etc.).")
@ApiResponse(responseCode = "200", description = "File content returned successfully")
@GetMapping("/{bookId}/file/**")
public void getFile(
@Parameter(description = "ID of the book") @PathVariable Long bookId,
HttpServletRequest request,
HttpServletResponse response) throws IOException {
String fullPath = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
String prefix = "/api/v1/epub/" + bookId + "/file/";
String filePath = fullPath.substring(prefix.length());
filePath = URLDecoder.decode(filePath, StandardCharsets.UTF_8);
String contentType = epubReaderService.getContentType(bookId, filePath);
response.setContentType(contentType);
long fileSize = epubReaderService.getFileSize(bookId, filePath);
if (fileSize > 0) {
response.setContentLengthLong(fileSize);
}
if (contentType.startsWith("font/") ||
"application/font-woff".equals(contentType) ||
"application/font-woff2".equals(contentType) ||
"application/vnd.ms-fontobject".equals(contentType)) {
response.setHeader("Access-Control-Allow-Origin", "*");
}
response.setHeader("Cache-Control", "public, max-age=3600");
epubReaderService.streamFile(bookId, filePath, response.getOutputStream());
}
}
@@ -1,21 +1,36 @@
package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.model.dto.HealthcheckResponse;
import com.adityachandel.booklore.model.dto.response.SuccessResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
@RestController
@RequestMapping("/api/v1/healthcheck")
@Tag(name = "Healthcheck", description = "Endpoints for checking the healch of the application")
public class HealthcheckController {
@Operation(summary = "Get a ping response", description = "Check if the application is responding to requests")
@Value("${app.version}")
private String appVersion;
@Operation(summary = "Get a ping response", description = "Check if the application is responding")
@ApiResponse(responseCode = "200", description = "Health status returned successfully")
@GetMapping
public ResponseEntity<?> getPing() {
return ResponseEntity.ok(new SuccessResponse<>(200, "Pong"));
public ResponseEntity<SuccessResponse<HealthcheckResponse>> getPing() {
HealthcheckResponse healthData = HealthcheckResponse.builder()
.status("UP")
.message("Application is running smoothly.")
.version(appVersion) // ex) 'development' Insert
.timestamp(LocalDateTime.now())
.build();
return ResponseEntity.ok(new SuccessResponse<>(200, "Pong", healthData));
}
}
@@ -217,4 +217,4 @@ public class KoboController {
}
return koboServerProxy.proxyCurrentRequest(body, false);
}
}
}
@@ -0,0 +1,208 @@
package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.config.JacksonConfig;
import com.adityachandel.booklore.mapper.komga.KomgaMapper;
import com.adityachandel.booklore.model.dto.komga.*;
import com.adityachandel.booklore.service.book.BookService;
import com.adityachandel.booklore.service.komga.KomgaService;
import com.adityachandel.booklore.service.opds.OpdsUserV2Service;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Tag(name = "Komga API", description = "Komga-compatible API endpoints. " +
"All endpoints support a 'clean' query parameter (default: false). " +
"When present (?clean or ?clean=true), responses exclude fields ending with 'Lock', null values, and empty arrays, " +
"resulting in smaller and cleaner JSON payloads.")
@Slf4j
@RestController
@RequestMapping(value = "/komga/api", produces = "application/json")
@RequiredArgsConstructor
public class KomgaController {
private final KomgaService komgaService;
private final BookService bookService;
private final OpdsUserV2Service opdsUserV2Service;
private final KomgaMapper komgaMapper;
// Inject the dedicated komga mapper bean
private final @Qualifier(JacksonConfig.KOMGA_CLEAN_OBJECT_MAPPER) ObjectMapper komgaCleanObjectMapper;
// Helper to serialize using the komga-clean mapper
private ResponseEntity<String> writeJson(Object body) {
try {
String json = komgaCleanObjectMapper.writeValueAsString(body);
return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(json);
} catch (Exception e) {
log.error("Failed to serialize Komga response", e);
return ResponseEntity.status(500).build();
}
}
// ==================== Libraries ====================
@Operation(summary = "List all libraries")
@GetMapping("/v1/libraries")
public ResponseEntity<String> getAllLibraries() {
List<KomgaLibraryDto> libraries = komgaService.getAllLibraries();
return writeJson(libraries);
}
@Operation(summary = "Get library details")
@GetMapping("/v1/libraries/{libraryId}")
public ResponseEntity<String> getLibrary(
@Parameter(description = "Library ID") @PathVariable Long libraryId) {
return writeJson(komgaService.getLibraryById(libraryId));
}
// ==================== Series ====================
@Operation(summary = "List series")
@GetMapping("/v1/series")
public ResponseEntity<String> getAllSeries(
@Parameter(description = "Library ID filter") @RequestParam(required = false, name = "library_id") Long libraryId,
@Parameter(description = "Page number") @RequestParam(defaultValue = "0") int page,
@Parameter(description = "Page size") @RequestParam(defaultValue = "20") int size,
@Parameter(description = "Return all books without paging") @RequestParam(defaultValue = "false") boolean unpaged) {
KomgaPageableDto<KomgaSeriesDto> result = komgaService.getAllSeries(libraryId, page, size, unpaged);
return writeJson(result);
}
@Operation(summary = "Get series details")
@GetMapping("/v1/series/{seriesId}")
public ResponseEntity<String> getSeries(
@Parameter(description = "Series ID") @PathVariable String seriesId) {
return writeJson(komgaService.getSeriesById(seriesId));
}
@Operation(summary = "List books in series")
@GetMapping("/v1/series/{seriesId}/books")
public ResponseEntity<String> getSeriesBooks(
@Parameter(description = "Series ID") @PathVariable String seriesId,
@Parameter(description = "Page number") @RequestParam(defaultValue = "0") int page,
@Parameter(description = "Page size") @RequestParam(defaultValue = "20") int size,
@Parameter(description = "Return all books without paging") @RequestParam(defaultValue = "false") boolean unpaged) {
return writeJson(komgaService.getBooksBySeries(seriesId, page, size, unpaged));
}
@Operation(summary = "Get series thumbnail")
@GetMapping("/v1/series/{seriesId}/thumbnail")
public ResponseEntity<Resource> getSeriesThumbnail(
@Parameter(description = "Series ID") @PathVariable String seriesId) {
KomgaPageableDto<KomgaBookDto> books = komgaService.getBooksBySeries(seriesId, 0, 1, false);
if (books.getContent().isEmpty()) {
return ResponseEntity.notFound().build();
}
Long firstBookId = Long.parseLong(books.getContent().get(0).getId());
Resource coverImage = bookService.getBookThumbnail(firstBookId);
return ResponseEntity.ok()
.header("Content-Type", "image/jpeg")
.body(coverImage);
}
// ==================== Books ====================
@Operation(summary = "List books")
@GetMapping("/v1/books")
public ResponseEntity<String> getAllBooks(
@Parameter(description = "Library ID filter") @RequestParam(required = false, name = "library_id") Long libraryId,
@Parameter(description = "Page number") @RequestParam(defaultValue = "0") int page,
@Parameter(description = "Page size") @RequestParam(defaultValue = "20") int size) {
KomgaPageableDto<KomgaBookDto> result = komgaService.getAllBooks(libraryId, page, size);
return writeJson(result);
}
@Operation(summary = "Get book details")
@GetMapping("/v1/books/{bookId}")
public ResponseEntity<String> getBook(
@Parameter(description = "Book ID") @PathVariable Long bookId) {
return writeJson(komgaService.getBookById(bookId));
}
@Operation(summary = "Get book pages metadata")
@GetMapping("/v1/books/{bookId}/pages")
public ResponseEntity<String> getBookPages(
@Parameter(description = "Book ID") @PathVariable Long bookId) {
return writeJson(komgaService.getBookPages(bookId));
}
@Operation(summary = "Get book page image")
@GetMapping("/v1/books/{bookId}/pages/{pageNumber}")
public ResponseEntity<Resource> getBookPage(
@Parameter(description = "Book ID") @PathVariable Long bookId,
@Parameter(description = "Page number") @PathVariable Integer pageNumber,
@Parameter(description = "Convert image format (e.g., 'png')") @RequestParam(required = false) String convert) {
try {
boolean convertToPng = "png".equalsIgnoreCase(convert);
Resource pageImage = komgaService.getBookPageImage(bookId, pageNumber, convertToPng);
// Note: When not converting, we assume JPEG as most CBZ files contain JPEG images,
// but the actual format may vary (PNG, WebP, etc.)
String contentType = convertToPng ? "image/png" : "image/jpeg";
return ResponseEntity.ok()
.header("Content-Type", contentType)
.body(pageImage);
} catch (Exception e) {
log.error("Failed to get page {} from book {}", pageNumber, bookId, e);
return ResponseEntity.notFound().build();
}
}
@Operation(summary = "Download book file")
@GetMapping("/v1/books/{bookId}/file")
public ResponseEntity<Resource> downloadBook(
@Parameter(description = "Book ID") @PathVariable Long bookId) {
return bookService.downloadBook(bookId);
}
@Operation(summary = "Get book thumbnail")
@GetMapping("/v1/books/{bookId}/thumbnail")
public ResponseEntity<Resource> getBookThumbnail(
@Parameter(description = "Book ID") @PathVariable Long bookId) {
Resource coverImage = bookService.getBookThumbnail(bookId);
return ResponseEntity.ok()
.header("Content-Type", "image/jpeg")
.body(coverImage);
}
// ==================== Users ====================
@Operation(summary = "Get current user details")
@GetMapping("/v2/users/me")
public ResponseEntity<String> getCurrentUser(Authentication authentication) {
if (authentication == null || authentication.getName() == null) {
return ResponseEntity.status(401).build();
}
String username = authentication.getName();
var opdsUser = opdsUserV2Service.findByUsername(username);
if (opdsUser == null) {
return ResponseEntity.notFound().build();
}
return writeJson(komgaMapper.toKomgaUserDto(opdsUser));
}
// ==================== Collections ====================
@Operation(summary = "List collections")
@GetMapping("/v1/collections")
public ResponseEntity<String> getCollections(
@Parameter(description = "Page number") @RequestParam(defaultValue = "0") int page,
@Parameter(description = "Page size") @RequestParam(defaultValue = "20") int size,
@Parameter(description = "Return all collections without paging") @RequestParam(defaultValue = "false") boolean unpaged) {
return writeJson(komgaService.getCollections(page, size, unpaged));
}
}
@@ -50,4 +50,14 @@ public class KoreaderUserController {
koreaderUserService.toggleSync(enabled);
return ResponseEntity.noContent().build();
}
@Operation(summary = "Toggle sync progress with Booklore reader", description = "Enable or disable syncing reading progress with Booklore reader.")
@ApiResponse(responseCode = "204", description = "Sync progress toggled successfully")
@PatchMapping("/me/sync-progress-with-booklore")
@PreAuthorize("@securityUtil.canSyncKoReader() or @securityUtil.isAdmin()")
public ResponseEntity<Void> toggleSyncProgressWithBooklore(
@Parameter(description = "Enable or disable sync progress") @RequestParam boolean enabled) {
koreaderUserService.toggleSyncProgressWithBooklore(enabled);
return ResponseEntity.noContent().build();
}
}
@@ -60,7 +60,7 @@ public class MetadataController {
public ResponseEntity<BookMetadata> updateMetadata(
@Parameter(description = "Metadata update wrapper") @RequestBody MetadataUpdateWrapper metadataUpdateWrapper,
@Parameter(description = "ID of the book") @PathVariable long bookId,
@Parameter(description = "Merge categories") @RequestParam(defaultValue = "true") boolean mergeCategories) {
@Parameter(description = "Merge categories") @RequestParam(defaultValue = "false") boolean mergeCategories) {
BookEntity bookEntity = bookRepository.findAllWithMetadataByIds(java.util.Collections.singleton(bookId)).stream()
.findFirst()
.orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
@@ -1,5 +1,6 @@
package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.model.dto.response.PdfBookInfo;
import com.adityachandel.booklore.service.reader.PdfReaderService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
@@ -11,7 +12,6 @@ import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.util.List;
@RestController
@@ -25,8 +25,14 @@ public class PdfReaderController {
@Operation(summary = "List pages in a PDF book", description = "Retrieve a list of available page numbers for a PDF book.")
@ApiResponse(responseCode = "200", description = "Page numbers returned successfully")
@GetMapping("/{bookId}/pages")
public List<Integer> listPages(
@Parameter(description = "ID of the book") @PathVariable Long bookId) throws IOException {
public List<Integer> listPages(@Parameter(description = "ID of the book") @PathVariable Long bookId) {
return pdfReaderService.getAvailablePages(bookId);
}
}
@Operation(summary = "Get book info for a PDF book", description = "Retrieve book information including page count and hierarchical outline/table of contents.")
@ApiResponse(responseCode = "200", description = "Book info returned successfully")
@GetMapping("/{bookId}/info")
public PdfBookInfo getBookInfo(@Parameter(description = "ID of the book") @PathVariable Long bookId) {
return pdfReaderService.getBookInfo(bookId);
}
}
@@ -39,7 +39,7 @@ public class ShelfController {
@ApiResponse(responseCode = "403", description = "Forbidden")
})
@GetMapping("/{shelfId}")
@PreAuthorize("@securityUtil.isShelfOwner(#shelfId)")
@PreAuthorize("@securityUtil.canReadShelf(#shelfId)")
public ResponseEntity<Shelf> getShelf(
@Parameter(description = "ID of the shelf") @PathVariable Long shelfId) {
return ResponseEntity.ok(shelfService.getShelf(shelfId));
@@ -76,7 +76,7 @@ public class ShelfController {
@Operation(summary = "Get books on a shelf", description = "Retrieve all books assigned to a specific shelf.")
@ApiResponse(responseCode = "200", description = "Books returned successfully")
@GetMapping("/{shelfId}/books")
@PreAuthorize("@securityUtil.isShelfOwner(#shelfId)")
@PreAuthorize("@securityUtil.canReadShelf(#shelfId)")
public ResponseEntity<List<Book>> getShelfBooks(
@Parameter(description = "ID of the shelf") @PathVariable Long shelfId) {
return ResponseEntity.ok(shelfService.getShelfBooks(shelfId));
@@ -59,7 +59,8 @@ public enum ApiError {
TASK_ALREADY_RUNNING(HttpStatus.CONFLICT, "Task is already running: %s"),
ICON_ALREADY_EXISTS(HttpStatus.CONFLICT, "SVG icon with name '%s' already exists"),
DEMO_USER_PASSWORD_CHANGE_NOT_ALLOWED(HttpStatus.FORBIDDEN, "Demo user password change not allowed."),
PERMISSION_DENIED(HttpStatus.FORBIDDEN, "Permission denied: %s");
PERMISSION_DENIED(HttpStatus.FORBIDDEN, "Permission denied: %s"),
LIBRARY_PATH_NOT_ACCESSIBLE(HttpStatus.SERVICE_UNAVAILABLE, "Library scan aborted: path not accessible or empty: %s");
private final HttpStatus status;
private final String message;
@@ -0,0 +1,39 @@
package com.adityachandel.booklore.interceptor;
import com.adityachandel.booklore.context.KomgaCleanContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
/**
* Interceptor to handle the "clean" query parameter for Komga API endpoints.
* When the "clean" parameter is present (with or without a value) or set to "true",
* it enables clean mode which filters out "Lock" fields, null values, and empty arrays
* from the JSON response. Supports both ?clean and ?clean=true syntax.
*/
@Component
public class KomgaCleanInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String requestURI = request.getRequestURI();
// Only apply to Komga API endpoints
if (requestURI != null && requestURI.startsWith("/komga/api")) {
String cleanParam = request.getParameter("clean");
// Enable clean mode if parameter is present (even without value) or explicitly set to "true"
// Supports both ?clean and ?clean=true
boolean cleanMode = cleanParam != null && (cleanParam.isEmpty() || "true".equalsIgnoreCase(cleanParam));
KomgaCleanContext.setCleanMode(cleanMode);
}
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
// Clean up ThreadLocal to prevent memory leaks
KomgaCleanContext.clear();
}
}
@@ -0,0 +1,30 @@
package com.adityachandel.booklore.interceptor;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
@Component
@RequiredArgsConstructor
public class KomgaEnabledInterceptor implements HandlerInterceptor {
private final AppSettingService appSettingService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String uri = request.getRequestURI();
if (uri.startsWith("/komga/api/")) {
boolean komgaEnabled = appSettingService.getAppSettings().isKomgaApiEnabled();
if (!komgaEnabled) {
response.sendError(HttpServletResponse.SC_FORBIDDEN, "Komga API is disabled.");
return false;
}
}
return true;
}
}
@@ -1,7 +1,7 @@
package com.adityachandel.booklore.mapper;
import com.adityachandel.booklore.model.dto.AdditionalFile;
import com.adityachandel.booklore.model.entity.BookAdditionalFileEntity;
import com.adityachandel.booklore.model.dto.BookFile;
import com.adityachandel.booklore.model.entity.BookFileEntity;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Named;
@@ -13,12 +13,13 @@ public interface AdditionalFileMapper {
@Mapping(source = "book.id", target = "bookId")
@Mapping(source = ".", target = "filePath", qualifiedByName = "mapFilePath")
AdditionalFile toAdditionalFile(BookAdditionalFileEntity entity);
@Mapping(source = "bookFormat", target = "isBook")
BookFile toAdditionalFile(BookFileEntity entity);
List<AdditionalFile> toAdditionalFiles(List<BookAdditionalFileEntity> entities);
List<BookFile> toAdditionalFiles(List<BookFileEntity> entities);
@Named("mapFilePath")
default String mapFilePath(BookAdditionalFileEntity entity) {
default String mapFilePath(BookFileEntity entity) {
if (entity == null) return null;
try {
return entity.getFullFilePath().toString();
@@ -0,0 +1,14 @@
package com.adityachandel.booklore.mapper;
import com.adityachandel.booklore.model.dto.Annotation;
import com.adityachandel.booklore.model.entity.AnnotationEntity;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
@Mapper(componentModel = "spring")
public interface AnnotationMapper {
@Mapping(source = "book.id", target = "bookId")
@Mapping(source = "user.id", target = "userId")
Annotation toDto(AnnotationEntity entity);
}
@@ -1,10 +1,10 @@
package com.adityachandel.booklore.mapper;
import com.adityachandel.booklore.model.dto.AdditionalFile;
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 com.adityachandel.booklore.model.enums.AdditionalFileType;
import org.mapstruct.Context;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
@@ -23,8 +23,13 @@ public interface BookMapper {
@Mapping(source = "libraryPath", target = "libraryPath", qualifiedByName = "mapLibraryPathIdOnly")
@Mapping(source = "metadata", target = "metadata")
@Mapping(source = "shelves", target = "shelves")
@Mapping(source = "additionalFiles", target = "alternativeFormats", qualifiedByName = "mapAlternativeFormats")
@Mapping(source = "additionalFiles", target = "supplementaryFiles", qualifiedByName = "mapSupplementaryFiles")
@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")
@@ -32,8 +37,13 @@ public interface BookMapper {
@Mapping(source = "libraryPath", target = "libraryPath", qualifiedByName = "mapLibraryPathIdOnly")
@Mapping(source = "metadata", target = "metadata")
@Mapping(source = "shelves", target = "shelves")
@Mapping(source = "additionalFiles", target = "alternativeFormats", qualifiedByName = "mapAlternativeFormats")
@Mapping(source = "additionalFiles", target = "supplementaryFiles", qualifiedByName = "mapSupplementaryFiles")
@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) {
@@ -72,33 +82,78 @@ public interface BookMapper {
.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<AdditionalFile> mapAlternativeFormats(List<BookAdditionalFileEntity> additionalFiles) {
if (additionalFiles == null) return null;
return additionalFiles.stream()
.filter(af -> AdditionalFileType.ALTERNATIVE_FORMAT.equals(af.getAdditionalFileType()))
.map(this::toAdditionalFile)
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<AdditionalFile> mapSupplementaryFiles(List<BookAdditionalFileEntity> additionalFiles) {
if (additionalFiles == null) return null;
return additionalFiles.stream()
.filter(af -> AdditionalFileType.SUPPLEMENTARY.equals(af.getAdditionalFileType()))
.map(this::toAdditionalFile)
default List<BookFile> mapSupplementaryFiles(List<BookFileEntity> bookFiles) {
if (bookFiles == null)
return null;
return bookFiles.stream()
.filter(bf -> !bf.isBook())
.map(this::toBookFile)
.toList();
}
default AdditionalFile toAdditionalFile(BookAdditionalFileEntity entity) {
/*
* 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 AdditionalFile.builder()
return BookFile.builder()
.id(entity.getId())
.bookId(entity.getBook().getId())
.fileName(entity.getFileName())
.filePath(entity.getFullFilePath().toString())
.fileSubPath(entity.getFileSubPath())
.additionalFileType(entity.getAdditionalFileType())
.isBook(entity.isBook())
.bookType(entity.getBookType())
.fileSizeKb(entity.getFileSizeKb())
.description(entity.getDescription())
.addedOn(entity.getAddedOn())
@@ -0,0 +1,14 @@
package com.adityachandel.booklore.mapper;
import com.adityachandel.booklore.model.dto.BookNoteV2;
import com.adityachandel.booklore.model.entity.BookNoteV2Entity;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
@Mapper(componentModel = "spring")
public interface BookNoteV2Mapper {
@Mapping(source = "book.id", target = "bookId")
@Mapping(source = "user.id", target = "userId")
BookNoteV2 toDto(BookNoteV2Entity entity);
}
@@ -9,5 +9,7 @@ import org.mapstruct.Mapping;
public interface ShelfMapper {
@Mapping(source = "user.id", target = "userId")
@Mapping(source = "public", target = "publicShelf")
@Mapping(target = "bookCount", expression = "java(shelfEntity.getBookEntities() != null ? shelfEntity.getBookEntities().size() : 0)")
Shelf toShelf(ShelfEntity shelfEntity);
}
@@ -49,6 +49,7 @@ public class BookLoreUserTransformer {
case PER_BOOK_SETTING -> userSettings.setPerBookSetting(objectMapper.readValue(value, BookLoreUser.UserSettings.PerBookSetting.class));
case PDF_READER_SETTING -> userSettings.setPdfReaderSetting(objectMapper.readValue(value, BookLoreUser.UserSettings.PdfReaderSetting.class));
case EPUB_READER_SETTING -> userSettings.setEpubReaderSetting(objectMapper.readValue(value, BookLoreUser.UserSettings.EpubReaderSetting.class));
case EBOOK_READER_SETTING -> userSettings.setEbookReaderSetting(objectMapper.readValue(value, BookLoreUser.UserSettings.EbookReaderSetting.class));
case CBX_READER_SETTING -> userSettings.setCbxReaderSetting(objectMapper.readValue(value, BookLoreUser.UserSettings.CbxReaderSetting.class));
case NEW_PDF_READER_SETTING -> userSettings.setNewPdfReaderSetting(objectMapper.readValue(value, BookLoreUser.UserSettings.NewPdfReaderSetting.class));
case SIDEBAR_LIBRARY_SORTING -> userSettings.setSidebarLibrarySorting(objectMapper.readValue(value, SidebarSortOption.class));
@@ -65,6 +66,7 @@ public class BookLoreUserTransformer {
case FILTER_SORTING_MODE -> userSettings.setFilterSortingMode(value);
case METADATA_CENTER_VIEW_MODE -> userSettings.setMetadataCenterViewMode(value);
case ENABLE_SERIES_VIEW -> userSettings.setEnableSeriesView(Boolean.parseBoolean(value));
case AUTO_SAVE_METADATA -> userSettings.setAutoSaveMetadata(Boolean.parseBoolean(value));
}
}
} catch (IllegalArgumentException e) {
@@ -0,0 +1,375 @@
package com.adityachandel.booklore.mapper.komga;
import com.adityachandel.booklore.context.KomgaCleanContext;
import com.adityachandel.booklore.model.dto.MagicShelf;
import com.adityachandel.booklore.model.dto.komga.*;
import com.adityachandel.booklore.model.entity.*;
import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
@Component
@RequiredArgsConstructor
public class KomgaMapper {
private static final Pattern NON_ALPHANUMERIC_PATTERN = Pattern.compile("[^a-z0-9]+");
private final AppSettingService appSettingService;
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ISO_LOCAL_DATE;
private static final String UNKNOWN_SERIES = "Unknown Series";
public KomgaLibraryDto toKomgaLibraryDto(LibraryEntity library) {
return KomgaLibraryDto.builder()
.id(library.getId().toString())
.name(library.getName())
.root(library.getLibraryPaths() != null && !library.getLibraryPaths().isEmpty()
? library.getLibraryPaths().get(0).getPath()
: "")
.unavailable(false)
.build();
}
public KomgaBookDto toKomgaBookDto(BookEntity book) {
BookMetadataEntity metadata = book.getMetadata();
BookFileEntity bookFile = book.getPrimaryBookFile();
String seriesId = generateSeriesId(book);
return KomgaBookDto.builder()
.id(book.getId().toString())
.seriesId(seriesId)
.seriesTitle(getBookSeriesName(book))
.libraryId(book.getLibrary().getId().toString())
.name(metadata != null ? metadata.getTitle() : bookFile.getFileName())
.url("/komga/api/v1/books/" + book.getId())
.number(metadata != null && metadata.getSeriesNumber() != null
? metadata.getSeriesNumber().intValue()
: 1)
.created(book.getAddedOn())
.lastModified(book.getAddedOn())
.fileLastModified(book.getAddedOn())
.sizeBytes(bookFile.getFileSizeKb() != null ? bookFile.getFileSizeKb() * 1024 : 0L)
.size(formatFileSize(bookFile.getFileSizeKb()))
.media(toKomgaMediaDto(book, metadata))
.metadata(toKomgaBookMetadataDto(metadata))
.deleted(book.getDeleted())
.fileHash(bookFile.getCurrentHash())
.oneshot(false)
.build();
}
public KomgaSeriesDto toKomgaSeriesDto(String seriesName, Long libraryId, List<BookEntity> books) {
if (books == null || books.isEmpty()) {
return null;
}
BookEntity firstBook = books.get(0);
String seriesId = generateSeriesId(firstBook);
// Aggregate metadata from all books
KomgaSeriesMetadataDto metadata = aggregateSeriesMetadata(seriesName, books);
KomgaBookMetadataAggregationDto booksMetadata = aggregateBooksMetadata(books);
return KomgaSeriesDto.builder()
.id(seriesId)
.libraryId(libraryId.toString())
.name(seriesName)
.url("/komga/api/v1/series/" + seriesId)
.created(firstBook.getAddedOn())
.lastModified(firstBook.getAddedOn())
.fileLastModified(firstBook.getAddedOn())
.booksCount(books.size())
.booksReadCount(0)
.booksUnreadCount(books.size())
.booksInProgressCount(0)
.metadata(metadata)
.booksMetadata(booksMetadata)
.deleted(false)
.oneshot(books.size() == 1)
.build();
}
private KomgaMediaDto toKomgaMediaDto(BookEntity book, BookMetadataEntity metadata) {
BookFileEntity bookFile = book.getPrimaryBookFile();
String mediaType = getMediaType(bookFile.getBookType());
Integer pageCount = metadata != null && metadata.getPageCount() != null ? metadata.getPageCount() : 0;
return KomgaMediaDto.builder()
.status("READY")
.mediaType(mediaType)
.mediaProfile(getMediaProfile(bookFile.getBookType()))
.pagesCount(pageCount)
.build();
}
private KomgaBookMetadataDto toKomgaBookMetadataDto(BookMetadataEntity metadata) {
if (metadata == null) {
return KomgaBookMetadataDto.builder().build();
}
List<KomgaAuthorDto> authors = new ArrayList<>();
if (metadata.getAuthors() != null) {
authors = metadata.getAuthors().stream()
.map(author -> KomgaAuthorDto.builder()
.name(author.getName())
.role("writer")
.build())
.collect(Collectors.toList());
}
List<String> tags = new ArrayList<>();
if (metadata.getTags() != null) {
tags = metadata.getTags().stream()
.map(TagEntity::getName)
.collect(Collectors.toList());
}
return KomgaBookMetadataDto.builder()
.title(nullIfEmptyInCleanMode(metadata.getTitle(), ""))
.titleLock(metadata.getTitleLocked())
.summary(nullIfEmptyInCleanMode(metadata.getDescription(), ""))
.summaryLock(metadata.getDescriptionLocked())
.number(nullIfEmptyInCleanMode(metadata.getSeriesNumber(), 1.0F).toString())
.numberLock(metadata.getSeriesNumberLocked())
.numberSort(nullIfEmptyInCleanMode(metadata.getSeriesNumber(), 1.0F))
.numberSortLock(metadata.getSeriesNumberLocked())
.releaseDate(metadata.getPublishedDate() != null
? metadata.getPublishedDate().format(DATE_FORMATTER)
: null)
.releaseDateLock(metadata.getPublishedDateLocked())
.authors(authors)
.authorsLock(metadata.getAuthorsLocked())
.tags(tags)
.tagsLock(metadata.getTagsLocked())
.isbn(metadata.getIsbn13() != null ? metadata.getIsbn13() : metadata.getIsbn10())
.isbnLock(metadata.getIsbn13Locked())
.build();
}
private KomgaSeriesMetadataDto aggregateSeriesMetadata(String seriesName, List<BookEntity> books) {
BookEntity firstBook = books.get(0);
BookMetadataEntity firstMetadata = firstBook.getMetadata();
List<String> genres = new ArrayList<>();
List<String> tags = new ArrayList<>();
if (firstMetadata != null) {
if (firstMetadata.getCategories() != null) {
genres = firstMetadata.getCategories().stream()
.map(CategoryEntity::getName)
.collect(Collectors.toList());
}
if (firstMetadata.getTags() != null) {
tags = firstMetadata.getTags().stream()
.map(TagEntity::getName)
.collect(Collectors.toList());
}
}
String language = firstMetadata != null ? firstMetadata.getLanguage() : null;
String description = firstMetadata != null ? firstMetadata.getDescription() : null;
String publisher = firstMetadata != null ? firstMetadata.getPublisher() : null;
return KomgaSeriesMetadataDto.builder()
.status("ONGOING")
.statusLock(false)
.title(seriesName)
.titleLock(false)
.titleSort(seriesName)
.titleSortLock(false)
.summary(nullIfEmptyInCleanMode(description, ""))
.summaryLock(false)
.publisher(nullIfEmptyInCleanMode(publisher, ""))
.publisherLock(false)
.language(nullIfEmptyInCleanMode(language, "en"))
.languageLock(false)
.genres(genres)
.genresLock(false)
.tags(tags)
.tagsLock(false)
.totalBookCount(books.size())
.totalBookCountLock(false)
// not used but required right now by Mihon/komga apps
.ageRatingLock(false)
.readingDirection("LEFT_TO_RIGHT")
.readingDirectionLock(false)
.build();
}
private KomgaBookMetadataAggregationDto aggregateBooksMetadata(List<BookEntity> books) {
Set<String> authorNames = new HashSet<>();
Set<String> allTags = new HashSet<>();
String releaseDate = null;
String summary = null;
BookEntity firstBook = books.get(0);
for (BookEntity book : books) {
BookMetadataEntity metadata = book.getMetadata();
if (metadata != null) {
if (metadata.getAuthors() != null) {
metadata.getAuthors().forEach(author -> authorNames.add(author.getName()));
}
if (metadata.getTags() != null) {
metadata.getTags().forEach(tag -> allTags.add(tag.getName()));
}
if (releaseDate == null && metadata.getPublishedDate() != null) {
releaseDate = metadata.getPublishedDate().format(DATE_FORMATTER);
}
if (summary == null && metadata.getDescription() != null) {
summary = metadata.getDescription();
}
}
}
List<KomgaAuthorDto> authors = authorNames.stream()
.map(name -> KomgaAuthorDto.builder().name(name).role("writer").build())
.collect(Collectors.toList());
return KomgaBookMetadataAggregationDto.builder()
.authors(authors)
.tags(new ArrayList<>(allTags))
.created(firstBook.getAddedOn())
.lastModified(firstBook.getAddedOn())
.releaseDate(releaseDate)
.summary(nullIfEmptyInCleanMode(summary, ""))
// summaryNumber is typically empty, but in clean mode should be null to be filtered
.summaryNumber(nullIfEmptyInCleanMode(null, ""))
.summaryLock(false)
.build();
}
public String getBookSeriesName(BookEntity book) {
boolean groupUnknown = appSettingService.getAppSettings().isKomgaGroupUnknown();
BookMetadataEntity metadata = book.getMetadata();
BookFileEntity bookFile = book.getPrimaryBookFile();
String bookSeriesName = metadata != null && metadata.getSeriesName() != null
? metadata.getSeriesName()
: (groupUnknown ? UNKNOWN_SERIES : (metadata.getTitle() != null ? metadata.getTitle() : bookFile.getFileName() ));
return bookSeriesName;
}
public String getUnknownSeriesName() {
return UNKNOWN_SERIES;
}
private String generateSeriesId(BookEntity book) {
String seriesName = getBookSeriesName(book);
Long libraryId = book.getLibrary().getId();
// Generate a pseudo-ID based on library and series name
return libraryId + "-" + NON_ALPHANUMERIC_PATTERN.matcher(seriesName.toLowerCase()).replaceAll("-");
}
private String getMediaType(BookFileType bookType) {
if (bookType == null) {
return "application/zip";
}
return switch (bookType) {
case PDF -> "application/pdf";
case EPUB -> "application/epub+zip";
case CBX -> "application/x-cbz";
case FB2 -> "application/fictionbook2+zip";
case MOBI -> "application/x-mobipocket-ebook";
case AZW3 -> "application/vnd.amazon.ebook";
};
}
private String getMediaProfile(BookFileType bookType) {
if (bookType == null) {
return "UNKNOWN";
}
return switch (bookType) {
case PDF -> "PDF";
case MOBI -> "EPUB";
case AZW3 -> "EPUB";
case EPUB -> "EPUB";
case CBX -> "DIVINA"; // DIVINA is for comic books
case FB2 -> "DIVINA";
};
}
private String formatFileSize(Long fileSizeKb) {
if (fileSizeKb == null || fileSizeKb == 0) {
return "0 B";
}
long bytes = fileSizeKb * 1024;
if (bytes < 1024) {
return bytes + " B";
} else if (bytes < 1024 * 1024) {
return (bytes / 1024) + " KB";
} else if (bytes < 1024 * 1024 * 1024) {
return (bytes / (1024 * 1024)) + " MB";
} else {
return (bytes / (1024 * 1024 * 1024)) + " GB";
}
}
/**
* Helper method to return null for empty strings in clean mode.
* In clean mode, we want to allow null values so they can be filtered out.
*/
private String nullIfEmptyInCleanMode(String value, String defaultValue) {
if (KomgaCleanContext.isCleanMode()) {
return (value != null && !value.isEmpty()) ? value : null;
}
return value != null ? value : defaultValue;
}
/**
* Helper method to return null for empty integer in clean mode.
* In clean mode, we want to allow null values so they can be filtered out.
*/
private Integer nullIfEmptyInCleanMode(Integer value, Integer defaultValue) {
if (KomgaCleanContext.isCleanMode()) {
return (value != null) ? value : null;
}
return value != null ? value : defaultValue;
}
/**
* Helper method to return null for empty float in clean mode.
* In clean mode, we want to allow null values so they can be filtered out.
*/
private Float nullIfEmptyInCleanMode(Float value, Float defaultValue) {
if (KomgaCleanContext.isCleanMode()) {
return (value != null) ? value : null;
}
return value != null ? value : defaultValue;
}
public KomgaUserDto toKomgaUserDto(OpdsUserV2Entity opdsUser) {
return KomgaUserDto.builder()
.id(opdsUser.getId().toString())
.email(opdsUser.getUsername() + "@booklore.local")
.roles(List.of("USER"))
.sharedAllLibraries(true)
.build();
}
public KomgaCollectionDto toKomgaCollectionDto(MagicShelf magicShelf, int seriesCount) {
String now = Instant.now()
.atZone(ZoneId.systemDefault())
.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
return KomgaCollectionDto.builder()
.id(magicShelf.getId().toString())
.name(magicShelf.getName())
.ordered(false)
.seriesCount(seriesCount)
.createdDate(now)
.lastModifiedDate(now)
.build();
}
}
@@ -5,11 +5,13 @@ 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;
@@ -19,6 +21,7 @@ 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);
@@ -53,6 +56,16 @@ public interface BookMapperV2 {
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;
@@ -31,6 +31,8 @@ public class MetadataClearFlags {
private boolean hardcoverReviewCount;
private boolean lubimyczytacId;
private boolean lubimyczytacRating;
private boolean ranobedbId;
private boolean ranobedbRating;
private boolean authors;
private boolean categories;
private boolean moods;
@@ -0,0 +1,26 @@
package com.adityachandel.booklore.model.dto;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDateTime;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Annotation {
private Long id;
private Long userId;
private Long bookId;
private String cfi;
private String text;
private String color;
private String style;
private String note;
private String chapterTitle;
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
}
@@ -2,10 +2,10 @@ package com.adityachandel.booklore.model.dto;
import com.adityachandel.booklore.model.dto.progress.*;
import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.util.ArchiveUtils;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Builder;
import lombok.Data;
import java.time.Instant;
import java.util.List;
import java.util.Set;
@@ -16,6 +16,7 @@ import java.util.Set;
public class Book {
private Long id;
private BookFileType bookType;
private ArchiveUtils.ArchiveType archiveType;
private Long libraryId;
private String libraryName;
private String fileName;
@@ -37,6 +38,6 @@ public class Book {
private String readStatus;
private Instant dateFinished;
private LibraryPath libraryPath;
private List<AdditionalFile> alternativeFormats;
private List<AdditionalFile> supplementaryFiles;
private List<BookFile> alternativeFormats;
private List<BookFile> supplementaryFiles;
}
@@ -1,6 +1,6 @@
package com.adityachandel.booklore.model.dto;
import com.adityachandel.booklore.model.enums.AdditionalFileType;
import com.adityachandel.booklore.model.enums.BookFileType;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Builder;
import lombok.Data;
@@ -10,13 +10,14 @@ import java.time.Instant;
@Builder
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class AdditionalFile {
public class BookFile {
private Long id;
private Long bookId;
private String fileName;
private String filePath;
private String fileSubPath;
private AdditionalFileType additionalFileType;
private boolean isBook;
private BookFileType bookType;
private Long fileSizeKb;
private String description;
private Instant addedOn;
@@ -63,6 +63,7 @@ public class BookLoreUser {
public PdfReaderSetting pdfReaderSetting;
public NewPdfReaderSetting newPdfReaderSetting;
public EpubReaderSetting epubReaderSetting;
public EbookReaderSetting ebookReaderSetting;
public CbxReaderSetting cbxReaderSetting;
public SidebarSortOption sidebarLibrarySorting;
public SidebarSortOption sidebarShelfSorting;
@@ -74,6 +75,7 @@ public class BookLoreUser {
public String metadataCenterViewMode;
public boolean koReaderEnabled;
public boolean enableSeriesView;
public boolean autoSaveMetadata;
public DashboardConfig dashboardConfig;
@Data
@@ -106,6 +108,7 @@ public class BookLoreUser {
private Float coverSize;
@JsonAlias("seriesCollapse")
private Boolean seriesCollapsed;
private Boolean overlayBookType;
}
@Data
@@ -128,6 +131,7 @@ public class BookLoreUser {
private String view;
@JsonAlias("seriesCollapse")
private Boolean seriesCollapsed;
private Boolean overlayBookType;
}
@Data
@@ -144,6 +148,25 @@ public class BookLoreUser {
private String spread;
}
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public static class EbookReaderSetting {
private String fontFamily;
private Integer fontSize;
private Float gap;
private Boolean hyphenate;
private Boolean isDark;
private Boolean justify;
private Float lineHeight;
private Integer maxBlockSize;
private Integer maxColumnCount;
private Integer maxInlineSize;
private String theme;
private String flow;
}
@Data
@Builder
@AllArgsConstructor
@@ -172,6 +195,9 @@ public class BookLoreUser {
public static class NewPdfReaderSetting {
private NewPdfPageSpread pageSpread;
private NewPdfPageViewMode pageViewMode;
private NewPdfBackgroundColor backgroundColor;
private NewPdfPageFitMode fitMode;
private NewPdfPageScrollMode scrollMode;
}
@Data
@@ -182,6 +208,7 @@ public class BookLoreUser {
private GlobalOrIndividual pdf;
private GlobalOrIndividual epub;
private GlobalOrIndividual cbx;
private GlobalOrIndividual newPdf;
public enum GlobalOrIndividual {
Global, Individual
@@ -46,6 +46,8 @@ public class BookMetadata {
private Double lubimyczytacRating;
private String googleId;
private String lubimyczytacId;
private String ranobedbId;
private Double ranobedbRating;
private String externalUrl;
private Instant coverUpdatedOn;
private Set<String> authors;
@@ -85,6 +87,8 @@ public class BookMetadata {
private Boolean doubanReviewCountLocked;
private Boolean lubimyczytacIdLocked;
private Boolean lubimyczytacRatingLocked;
private Boolean ranobedbIdLocked;
private Boolean ranobedbRatingLocked;
private Boolean externalUrlLocked;
private Boolean coverLocked;
private Boolean authorsLocked;
@@ -92,4 +96,4 @@ public class BookMetadata {
private Boolean moodsLocked;
private Boolean tagsLocked;
private Boolean reviewsLocked;
}
}
@@ -0,0 +1,25 @@
package com.adityachandel.booklore.model.dto;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDateTime;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class BookNoteV2 {
private Long id;
private Long userId;
private Long bookId;
private String cfi;
private String selectedText;
private String noteContent;
private String color;
private String chapterTitle;
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
}
@@ -8,6 +8,6 @@ import lombok.Data;
public class BookViewerSettings {
private PdfViewerPreferences pdfSettings;
private NewPdfViewerPreferences newPdfSettings;
private EpubViewerPreferences epubSettings;
private EbookViewerPreferences ebookSettings;
private CbxViewerPreferences cbxSettings;
}
@@ -0,0 +1,40 @@
package com.adityachandel.booklore.model.dto;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class CreateAnnotationRequest {
@NotNull(message = "Book ID is required")
private Long bookId;
@NotEmpty(message = "CFI is required")
@Size(max = 1000, message = "CFI must not exceed 1000 characters")
private String cfi;
@NotEmpty(message = "Text is required")
@Size(max = 5000, message = "Text must not exceed 5000 characters")
private String text;
@Pattern(regexp = "^#[0-9A-Fa-f]{6}$", message = "Color must be a valid hex color (e.g., #FFFF00)")
private String color;
@Pattern(regexp = "^(highlight|underline|strikethrough|squiggly)$", message = "Style must be one of: highlight, underline, strikethrough, squiggly")
private String style;
@Size(max = 5000, message = "Note must not exceed 5000 characters")
private String note;
@Size(max = 500, message = "Chapter title must not exceed 500 characters")
private String chapterTitle;
}
@@ -0,0 +1,36 @@
package com.adityachandel.booklore.model.dto;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class CreateBookNoteV2Request {
@NotNull(message = "Book ID is required")
private Long bookId;
@NotEmpty(message = "CFI is required")
@Size(max = 1000, message = "CFI must not exceed 1000 characters")
private String cfi;
@Size(max = 5000, message = "Selected text must not exceed 5000 characters")
private String selectedText;
@NotEmpty(message = "Note content is required")
private String noteContent;
@Pattern(regexp = "^#[0-9A-Fa-f]{6}$", message = "Color must be a valid hex color (e.g., #FFFF00)")
private String color;
@Size(max = 500, message = "Chapter title must not exceed 500 characters")
private String chapterTitle;
}
@@ -0,0 +1,24 @@
package com.adityachandel.booklore.model.dto;
import lombok.Builder;
import lombok.Data;
@Data
@Builder
public class EbookViewerPreferences {
private Long bookId;
private Long userId;
private String fontFamily;
private Integer fontSize;
private Float gap;
private Boolean hyphenate;
private Boolean isDark;
private Boolean justify;
private Float lineHeight;
private Integer maxBlockSize;
private Integer maxColumnCount;
private Integer maxInlineSize;
private String theme;
private String flow;
}
@@ -35,6 +35,8 @@ public class EpubMetadata {
private Double hardcoverRating;
private Integer hardcoverReviewCount;
private String googleId;
private String ranobedbId;
private Double ranobedbRating;
private Set<String> authors;
private Set<String> categories;
}
@@ -0,0 +1,15 @@
package com.adityachandel.booklore.model.dto;
import lombok.Builder;
import lombok.Data;
import java.time.LocalDateTime;
@Data
@Builder
public class HealthcheckResponse {
private String status;
private String message;
private LocalDateTime timestamp;
private String version;
}
@@ -1,7 +1,6 @@
package com.adityachandel.booklore.model.dto;
import com.adityachandel.booklore.model.enums.NewPdfPageViewMode;
import com.adityachandel.booklore.model.enums.NewPdfPageSpread;
import com.adityachandel.booklore.model.enums.*;
import lombok.Builder;
import lombok.Data;
@@ -11,4 +10,7 @@ public class NewPdfViewerPreferences {
private Long bookId;
private NewPdfPageSpread pageSpread;
private NewPdfPageViewMode pageViewMode;
private NewPdfBackgroundColor backgroundColor;
private NewPdfPageFitMode fitMode;
private NewPdfPageScrollMode scrollMode;
}
@@ -5,6 +5,8 @@ import com.fasterxml.jackson.annotation.JsonProperty;
public enum RuleField {
@JsonProperty("library")
LIBRARY,
@JsonProperty("shelf")
SHELF,
@JsonProperty("title")
TITLE,
@JsonProperty("subtitle")
@@ -43,6 +45,8 @@ public enum RuleField {
HARDCOVER_RATING,
@JsonProperty("hardcoverReviewCount")
HARDCOVER_REVIEW_COUNT,
@JsonProperty("ranobedbRating")
RANOBEDB_RATING,
@JsonProperty("personalRating")
PERSONAL_RATING,
@JsonProperty("fileType")
@@ -15,4 +15,6 @@ public class Shelf {
private IconType iconType;
private Sort sort;
private Long userId;
private boolean publicShelf;
private int bookCount;
}
@@ -0,0 +1,24 @@
package com.adityachandel.booklore.model.dto;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class UpdateAnnotationRequest {
@Pattern(regexp = "^#[0-9A-Fa-f]{6}$", message = "Color must be a valid hex color (e.g., #FFFF00)")
private String color;
@Pattern(regexp = "^(highlight|underline|strikethrough|squiggly)$", message = "Style must be one of: highlight, underline, strikethrough, squiggly")
private String style;
@Size(max = 5000, message = "Note must not exceed 5000 characters")
private String note;
}
@@ -0,0 +1,23 @@
package com.adityachandel.booklore.model.dto;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class UpdateBookNoteV2Request {
private String noteContent;
@Pattern(regexp = "^#[0-9A-Fa-f]{6}$", message = "Color must be a valid hex color (e.g., #FFFF00)")
private String color;
@Size(max = 500, message = "Chapter title must not exceed 500 characters")
private String chapterTitle;
}
@@ -0,0 +1,15 @@
package com.adityachandel.booklore.model.dto.komga;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class KomgaAlternateTitleDto {
private String label;
private String title;
}
@@ -0,0 +1,15 @@
package com.adityachandel.booklore.model.dto.komga;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class KomgaAuthorDto {
private String name;
private String role;
}
@@ -0,0 +1,35 @@
package com.adityachandel.booklore.model.dto.komga;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.Instant;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class KomgaBookDto {
private String id;
private String seriesId;
private String seriesTitle;
private String libraryId;
private String name;
private String url;
private Integer number;
private Instant created;
private Instant lastModified;
private Instant fileLastModified;
private Long sizeBytes;
private String size;
private KomgaMediaDto media;
private KomgaBookMetadataDto metadata;
private KomgaReadProgressDto readProgress;
private Boolean deleted;
private String fileHash;
private Boolean oneshot;
}
@@ -0,0 +1,34 @@
package com.adityachandel.booklore.model.dto.komga;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.ArrayList;
import java.util.List;
import java.time.Instant;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class KomgaBookMetadataAggregationDto {
@Builder.Default
private List<KomgaAuthorDto> authors = new ArrayList<>();
@Builder.Default
private List<String> tags = new ArrayList<>();
private String releaseDate;
private String summary;
private String summaryNumber;
private Boolean summaryLock;
private Instant created;
private Instant lastModified;
}
@@ -0,0 +1,51 @@
package com.adityachandel.booklore.model.dto.komga;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class KomgaBookMetadataDto {
private String title;
private Boolean titleLock;
private String summary;
private Boolean summaryLock;
private String number;
private Boolean numberLock;
private Float numberSort;
private Boolean numberSortLock;
private String releaseDate;
private Boolean releaseDateLock;
@Builder.Default
private List<KomgaAuthorDto> authors = new ArrayList<>();
private Boolean authorsLock;
@Builder.Default
private List<String> tags = new ArrayList<>();
private Boolean tagsLock;
private String isbn;
private Boolean isbnLock;
@Builder.Default
private List<KomgaWebLinkDto> links = new ArrayList<>();
private Boolean linksLock;
private Instant created;
private Instant lastModified;
}
@@ -0,0 +1,19 @@
package com.adityachandel.booklore.model.dto.komga;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class KomgaCollectionDto {
private String id;
private String name;
private Boolean ordered;
private Integer seriesCount;
private String createdDate;
private String lastModifiedDate;
}
@@ -0,0 +1,73 @@
package com.adityachandel.booklore.model.dto.komga;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class KomgaLibraryDto {
private String id;
private String name;
private String root;
private Boolean unavailable;
// Scan options
@Builder.Default
private Boolean scanCbx = true;
@Builder.Default
private Boolean scanEpub = true;
@Builder.Default
private Boolean scanPdf = true;
@Builder.Default
private Boolean scanOnStartup = false;
@Builder.Default
private String scanInterval = "EVERY_6H";
@Builder.Default
private Boolean scanForceModifiedTime = false;
// Import options
@Builder.Default
private Boolean importComicInfoBook = true;
@Builder.Default
private Boolean importComicInfoSeries = true;
@Builder.Default
private Boolean importComicInfoCollection = true;
@Builder.Default
private Boolean importComicInfoReadList = true;
@Builder.Default
private Boolean importComicInfoSeriesAppendVolume = false;
@Builder.Default
private Boolean importEpubBook = true;
@Builder.Default
private Boolean importEpubSeries = true;
@Builder.Default
private Boolean importLocalArtwork = true;
@Builder.Default
private Boolean importBarcodeIsbn = true;
@Builder.Default
private Boolean importMylarSeries = true;
// Other options
@Builder.Default
private Boolean repairExtensions = false;
@Builder.Default
private Boolean convertToCbz = false;
@Builder.Default
private Boolean emptyTrashAfterScan = false;
@Builder.Default
private String seriesCover = "FIRST";
@Builder.Default
private Boolean hashFiles = true;
@Builder.Default
private Boolean hashPages = false;
@Builder.Default
private Boolean hashKoreader = false;
@Builder.Default
private Boolean analyzeDimensions = true;
}
@@ -0,0 +1,22 @@
package com.adityachandel.booklore.model.dto.komga;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class KomgaMediaDto {
private String status;
private String mediaType;
private String mediaProfile;
private Integer pagesCount;
private String comment;
private Boolean epubDivinaCompatible;
private Boolean epubIsKepub;
}
@@ -0,0 +1,21 @@
package com.adityachandel.booklore.model.dto.komga;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class KomgaPageDto {
private Integer number;
private String fileName;
private String mediaType;
private Integer width;
private Integer height;
private Long fileSize;
}
@@ -0,0 +1,26 @@
package com.adityachandel.booklore.model.dto.komga;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class KomgaPageableDto<T> {
private List<T> content;
private Integer number;
private Integer size;
private Integer numberOfElements;
private Integer totalElements;
private Integer totalPages;
private Boolean first;
private Boolean last;
private Boolean empty;
}
@@ -0,0 +1,22 @@
package com.adityachandel.booklore.model.dto.komga;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.Instant;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class KomgaReadProgressDto {
private Integer page;
private Boolean completed;
private Instant readDate;
private Instant created;
private Instant lastModified;
}
@@ -0,0 +1,32 @@
package com.adityachandel.booklore.model.dto.komga;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.Instant;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class KomgaSeriesDto {
private String id;
private String libraryId;
private String name;
private String url;
private Instant created;
private Instant lastModified;
private Instant fileLastModified;
private Integer booksCount;
private Integer booksReadCount;
private Integer booksUnreadCount;
private Integer booksInProgressCount;
private KomgaSeriesMetadataDto metadata;
private KomgaBookMetadataAggregationDto booksMetadata;
private Boolean deleted;
private Boolean oneshot;
}
@@ -0,0 +1,68 @@
package com.adityachandel.booklore.model.dto.komga;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class KomgaSeriesMetadataDto {
private String status;
private Boolean statusLock;
private String title;
private Boolean titleLock;
private String titleSort;
private Boolean titleSortLock;
private String summary;
private Boolean summaryLock;
private String readingDirection;
private Boolean readingDirectionLock;
private String publisher;
private Boolean publisherLock;
private Integer ageRating;
private Boolean ageRatingLock;
private String language;
private Boolean languageLock;
@Builder.Default
private List<String> genres = new ArrayList<>();
private Boolean genresLock;
@Builder.Default
private List<String> tags = new ArrayList<>();
private Boolean tagsLock;
private Integer totalBookCount;
private Boolean totalBookCountLock;
@Builder.Default
private List<KomgaAlternateTitleDto> alternateTitles = new ArrayList<>();
private Boolean alternateTitlesLock;
@Builder.Default
private List<KomgaWebLinkDto> links = new ArrayList<>();
private Boolean linksLock;
@Builder.Default
private List<String> sharingLabels = new ArrayList<>();
private Boolean sharingLabelsLock;
private Instant created;
private Instant lastModified;
}
@@ -0,0 +1,35 @@
package com.adityachandel.booklore.model.dto.komga;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.ArrayList;
import java.util.List;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class KomgaUserDto {
private String id;
private String email;
@Builder.Default
private List<String> roles = new ArrayList<>();
@Builder.Default
private Boolean sharedAllLibraries = true;
@Builder.Default
private List<String> sharedLibrariesIds = new ArrayList<>();
@Builder.Default
private List<String> labelsAllow = new ArrayList<>();
@Builder.Default
private List<String> labelsExclude = new ArrayList<>();
}
@@ -0,0 +1,15 @@
package com.adityachandel.booklore.model.dto.komga;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class KomgaWebLinkDto {
private String label;
private String url;
}
@@ -9,6 +9,7 @@ import lombok.Data;
public class EpubProgress {
@NotNull
String cfi;
String href;
@NotNull
Float percentage;
}
@@ -1,12 +1,9 @@
package com.adityachandel.booklore.model.dto.request;
import com.adityachandel.booklore.model.enums.MetadataProvider;
import com.adityachandel.booklore.model.enums.MetadataReplaceMode;
import jakarta.validation.constraints.NotNull;
import lombok.Getter;
import lombok.Setter;
import lombok.NoArgsConstructor;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.*;
@Getter
@Setter
@@ -18,6 +15,14 @@ public class MetadataRefreshOptions {
private boolean refreshCovers;
private boolean mergeCategories;
private Boolean reviewBeforeApply;
/**
* Controls how fetched metadata replaces existing metadata.
* REPLACE_ALL: Replace all fields with fetched values (even if existing values are present)
* REPLACE_MISSING: Only fill in fields that are currently empty/null
* Default is REPLACE_MISSING to preserve existing metadata unless user explicitly wants to overwrite.
*/
@Builder.Default
private MetadataReplaceMode replaceMode = MetadataReplaceMode.REPLACE_MISSING;
@NotNull(message = "Field options cannot be null")
@Builder.Default
private FieldOptions fieldOptions = new FieldOptions();
@@ -59,6 +64,8 @@ public class MetadataRefreshOptions {
private FieldProvider hardcoverRating;
private FieldProvider hardcoverReviewCount;
private FieldProvider lubimyczytacRating;
private FieldProvider ranobedbId;
private FieldProvider ranobedbRating;
private FieldProvider moods;
private FieldProvider tags;
}
@@ -77,39 +84,113 @@ public class MetadataRefreshOptions {
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public static class EnabledFields {
private boolean title;
private boolean subtitle;
private boolean description;
private boolean authors;
private boolean publisher;
private boolean publishedDate;
private boolean seriesName;
private boolean seriesNumber;
private boolean seriesTotal;
private boolean isbn13;
private boolean isbn10;
private boolean language;
private boolean categories;
private boolean cover;
private boolean pageCount;
private boolean asin;
private boolean goodreadsId;
private boolean comicvineId;
private boolean hardcoverId;
private boolean googleId;
private boolean lubimyczytacId;
private boolean amazonRating;
private boolean amazonReviewCount;
private boolean goodreadsRating;
private boolean goodreadsReviewCount;
private boolean hardcoverRating;
private boolean hardcoverReviewCount;
private boolean lubimyczytacRating;
private boolean moods;
private boolean tags;
// All fields default to true so metadata fetcher updates fields by default
// unless explicitly disabled by the user
@Builder.Default
private boolean title = true;
@Builder.Default
private boolean subtitle = true;
@Builder.Default
private boolean description = true;
@Builder.Default
private boolean authors = true;
@Builder.Default
private boolean publisher = true;
@Builder.Default
private boolean publishedDate = true;
@Builder.Default
private boolean seriesName = true;
@Builder.Default
private boolean seriesNumber = true;
@Builder.Default
private boolean seriesTotal = true;
@Builder.Default
private boolean isbn13 = true;
@Builder.Default
private boolean isbn10 = true;
@Builder.Default
private boolean language = true;
@Builder.Default
private boolean categories = true;
@Builder.Default
private boolean cover = true;
@Builder.Default
private boolean pageCount = true;
@Builder.Default
private boolean asin = true;
@Builder.Default
private boolean goodreadsId = true;
@Builder.Default
private boolean comicvineId = true;
@Builder.Default
private boolean hardcoverId = true;
@Builder.Default
private boolean googleId = true;
@Builder.Default
private boolean lubimyczytacId = true;
@Builder.Default
private boolean amazonRating = true;
@Builder.Default
private boolean amazonReviewCount = true;
@Builder.Default
private boolean goodreadsRating = true;
@Builder.Default
private boolean goodreadsReviewCount = true;
@Builder.Default
private boolean hardcoverRating = true;
@Builder.Default
private boolean hardcoverReviewCount = true;
@Builder.Default
private boolean lubimyczytacRating = true;
@Builder.Default
private boolean ranobedbId = true;
@Builder.Default
private boolean ranobedbRating = true;
@Builder.Default
private boolean moods = true;
@Builder.Default
private boolean tags = true;
/**
* Default constructor that initializes all fields to true.
* This ensures that by default, all metadata fields are enabled for fetching/updating.
*/
public EnabledFields() {
this.title = true;
this.subtitle = true;
this.description = true;
this.authors = true;
this.publisher = true;
this.publishedDate = true;
this.seriesName = true;
this.seriesNumber = true;
this.seriesTotal = true;
this.isbn13 = true;
this.isbn10 = true;
this.language = true;
this.categories = true;
this.cover = true;
this.pageCount = true;
this.asin = true;
this.goodreadsId = true;
this.comicvineId = true;
this.hardcoverId = true;
this.googleId = true;
this.lubimyczytacId = true;
this.amazonRating = true;
this.amazonReviewCount = true;
this.goodreadsRating = true;
this.goodreadsReviewCount = true;
this.hardcoverRating = true;
this.hardcoverReviewCount = true;
this.lubimyczytacRating = true;
this.ranobedbId = true;
this.ranobedbRating = true;
this.moods = true;
this.tags = true;
}
}
}
@@ -21,4 +21,6 @@ public class ShelfCreateRequest {
@NotNull(message = "Shelf icon type must not be null.")
private IconType iconType;
private boolean publicShelf;
}
@@ -0,0 +1,15 @@
package com.adityachandel.booklore.model.dto.response;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class CbxPageInfo {
private int pageNumber;
private String displayName;
}
@@ -0,0 +1,23 @@
package com.adityachandel.booklore.model.dto.response;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
import java.util.Map;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class EpubBookInfo {
private String containerPath;
private String rootPath;
private List<EpubSpineItem> spine;
private List<EpubManifestItem> manifest;
private EpubTocItem toc;
private Map<String, Object> metadata;
private String coverPath;
}
@@ -0,0 +1,20 @@
package com.adityachandel.booklore.model.dto.response;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class EpubManifestItem {
private String id;
private String href;
private String mediaType;
private List<String> properties;
private long size;
}
@@ -0,0 +1,17 @@
package com.adityachandel.booklore.model.dto.response;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class EpubSpineItem {
private String idref;
private String href;
private String mediaType;
private boolean linear;
}
@@ -0,0 +1,18 @@
package com.adityachandel.booklore.model.dto.response;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class EpubTocItem {
private String label;
private String href;
private List<EpubTocItem> children;
}
@@ -2,20 +2,25 @@ package com.adityachandel.booklore.model.dto.response;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
import java.util.List;
import java.util.Set;
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class GoogleBooksApiResponse {
private Integer totalItems;
private List<Item> items;
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public static class Item {
private String id;
private String selfLink;
private VolumeInfo volumeInfo;
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public static class VolumeInfo {
private String title;
private String subtitle;
@@ -25,18 +30,29 @@ public class GoogleBooksApiResponse {
private String description;
private List<IndustryIdentifier> industryIdentifiers;
private Integer pageCount;
private Integer printedPageCount;
private ImageLinks imageLinks;
private String language;
private Set<String> categories;
private Double averageRating;
private Integer ratingsCount;
private String maturityRating;
private String printType;
private String previewLink;
private String infoLink;
private String canonicalVolumeLink;
private SeriesInfo seriesInfo;
}
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public static class IndustryIdentifier {
private String type;
private String identifier;
}
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public static class ImageLinks {
private String smallThumbnail;
private String thumbnail;
@@ -45,5 +61,22 @@ public class GoogleBooksApiResponse {
private String large;
private String extraLarge;
}
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public static class SeriesInfo {
private String kind;
private String shortSeriesBookTitle;
private String bookDisplayNumber;
private List<VolumeSeries> volumeSeries;
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public static class VolumeSeries {
private String seriesId;
private String seriesBookType;
private Integer orderNumber;
}
}
}
}
@@ -0,0 +1,17 @@
package com.adityachandel.booklore.model.dto.response;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class PdfBookInfo {
private int pageCount;
private List<PdfOutlineItem> outline;
}
@@ -0,0 +1,18 @@
package com.adityachandel.booklore.model.dto.response;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class PdfOutlineItem {
private String title;
private Integer pageNumber;
private List<PdfOutlineItem> children;
}
@@ -20,10 +20,17 @@ public class Comic {
@JsonProperty("cover_date")
private String coverDate;
@JsonProperty("store_date")
private String storeDate;
private String description;
private String deck;
private String name;
private String aliases;
@JsonProperty("issue_number")
private String issueNumber;
@@ -37,6 +44,18 @@ public class Comic {
@JsonProperty("person_credits")
private List<PersonCredit> personCredits;
@JsonProperty("character_credits")
private List<CharacterCredit> characterCredits;
@JsonProperty("team_credits")
private List<TeamCredit> teamCredits;
@JsonProperty("story_arc_credits")
private List<StoryArcCredit> storyArcCredits;
@JsonProperty("location_credits")
private List<LocationCredit> locationCredits;
@JsonProperty("start_year")
private String startYear;
@@ -46,6 +65,12 @@ public class Comic {
@JsonProperty("site_detail_url")
private String siteDetailUrl;
@JsonProperty("first_issue")
private FirstLastIssue firstIssue;
@JsonProperty("last_issue")
private FirstLastIssue lastIssue;
private Publisher publisher;
@Data
@@ -121,4 +146,56 @@ public class Comic {
private String name;
private String role;
}
@Data
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public static class CharacterCredit {
private long id;
private String name;
@JsonProperty("api_detail_url")
private String apiDetailUrl;
}
@Data
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public static class TeamCredit {
private long id;
private String name;
@JsonProperty("api_detail_url")
private String apiDetailUrl;
}
@Data
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public static class StoryArcCredit {
private long id;
private String name;
@JsonProperty("api_detail_url")
private String apiDetailUrl;
}
@Data
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public static class LocationCredit {
private long id;
private String name;
@JsonProperty("api_detail_url")
private String apiDetailUrl;
}
@Data
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public static class FirstLastIssue {
private int id;
private String name;
@JsonProperty("api_detail_url")
private String apiDetailUrl;
@JsonProperty("issue_number")
private String issueNumber;
}
}
@@ -24,16 +24,35 @@ public class ComicvineIssueResponse {
@JsonProperty("person_credits")
private List<Comic.PersonCredit> personCredits;
@JsonProperty("character_credits")
private List<Comic.CharacterCredit> characterCredits;
@JsonProperty("team_credits")
private List<Comic.TeamCredit> teamCredits;
@JsonProperty("story_arc_credits")
private List<Comic.StoryArcCredit> storyArcCredits;
@JsonProperty("location_credits")
private List<Comic.LocationCredit> locationCredits;
private String description;
private String deck;
private String name;
private String aliases;
@JsonProperty("issue_number")
private String issueNumber;
@JsonProperty("cover_date")
private String coverDate;
@JsonProperty("store_date")
private String storeDate;
private Comic.Image image;
private Comic.Volume volume;
@@ -0,0 +1,206 @@
package com.adityachandel.booklore.model.dto.response.ranobedbapi;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;
import java.util.List;
import java.util.Set;
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class RanobedbBookResponse {
private Book book;
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public static class Book {
private String description;
private String lang;
private Long id;
private String romaji;
@JsonProperty("description_ja")
private String descriptionJa;
private Boolean hidden;
@JsonProperty("image_id")
private Long imageId;
private String olang;
private Boolean locked;
@JsonProperty("c_release_date")
private Long cReleaseDate;
private String title;
@JsonProperty("title_orig")
private String titleOrig;
@JsonProperty("romaji_orig")
private String romajiOrig;
private Image image;
private Rating rating;
private List<TitleEntry> titles;
private List<Edition> editions;
private List<Release> releases;
private List<Publisher> publishers;
private Series series;
}
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public static class Rating {
private Double score;
private Integer count;
}
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public static class Image {
private Long id;
private String filename;
private Integer height;
private Boolean nsfw;
private Boolean spoiler;
private Integer width;
}
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public static class TitleEntry {
private String lang;
private String romaji;
@JsonProperty("book_id")
private Long bookId;
private Boolean official;
private String title;
}
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public static class Edition {
@JsonProperty("book_id")
private Long bookId;
private String lang;
private String title;
private Long eid;
private List<Staff> staff;
}
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public static class Staff {
private String note;
@JsonProperty("role_type")
private RoleType roleType;
private String romaji;
private String name;
@JsonProperty("staff_id")
private Long staffId;
@JsonProperty("staff_alias_id")
private Long staffAliasId;
}
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public static class Release {
private String lang;
private Long id;
private String romaji;
private String description;
private Boolean hidden;
private Boolean locked;
@JsonProperty("release_date")
private Long releaseDate;
private String title;
private String website;
private String amazon;
private String bookwalker;
private Format format;
private String isbn13;
private Integer pages;
private String rakuten;
}
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public static class Publisher {
private String lang;
private Long id;
private String romaji;
private String name;
@JsonProperty("publisher_type")
private PublisherType publisherType;
}
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public static class Series {
private List<SeriesBook> books;
private List<Tag> tags;
private String lang;
private Long id;
private String romaji;
private String title;
@JsonProperty("title_orig")
private String titleOrig;
@JsonProperty("romaji_orig")
private String romajiOrig;
}
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public static class SeriesBook {
private Long id;
private String lang;
private String romaji;
private String title;
@JsonProperty("title_orig")
private String titleOrig;
@JsonProperty("romaji_orig")
private String romajiOrig;
private Image image;
}
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public static class Tag {
private Long id;
private String name;
private TagType ttype;
}
// --- Enums for strict typing ---
public enum RoleType {
@JsonProperty("editor") EDITOR,
@JsonProperty("staff") STAFF,
@JsonProperty("author") AUTHOR,
@JsonProperty("artist") ARTIST,
@JsonProperty("translator") TRANSLATOR,
@JsonProperty("narrator") NARRATOR
}
public enum Format {
@JsonProperty("digital") DIGITAL,
@JsonProperty("print") PRINT,
@JsonProperty("audio") AUDIO
}
public enum PublisherType {
@JsonProperty("publisher") PUBLISHER,
@JsonProperty("imprint") IMPRINT
}
public enum TagType {
@JsonProperty("tag") TAG,
@JsonProperty("content") CONTENT,
@JsonProperty("demographic") DEMOGRAPHIC,
@JsonProperty("genre") GENRE
}
}
@@ -0,0 +1,21 @@
package com.adityachandel.booklore.model.dto.response.ranobedbapi;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
import java.util.List;
import java.util.Set;
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class RanobedbSearchResponse{
private List<Book> books;
private String count;
private int currentPage;
private int totalPages;
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public static class Book {
private int id;
}
}
@@ -14,6 +14,8 @@ public enum AppSettingKey {
OIDC_AUTO_PROVISION_DETAILS ("oidc_auto_provision_details", true, false, List.of(PermissionType.ADMIN)),
KOBO_SETTINGS ("kobo_settings", true, false, List.of(PermissionType.ADMIN)),
OPDS_SERVER_ENABLED ("opds_server_enabled", false, false, List.of(PermissionType.ADMIN)),
KOMGA_API_ENABLED ("komga_api_enabled", false, false, List.of(PermissionType.ADMIN)),
KOMGA_GROUP_UNKNOWN ("komga_group_unknown", false, false, List.of(PermissionType.ADMIN)),
// ADMIN + MANAGE_METADATA_CONFIG
QUICK_BOOK_MATCH ("quick_book_match", true, false, List.of(PermissionType.ADMIN, PermissionType.MANAGE_METADATA_CONFIG)),
@@ -25,12 +27,12 @@ public enum AppSettingKey {
UPLOAD_FILE_PATTERN ("upload_file_pattern", false, false, List.of(PermissionType.ADMIN, PermissionType.MANAGE_METADATA_CONFIG)),
MOVE_FILE_PATTERN ("move_file_pattern", false, false, List.of(PermissionType.ADMIN, PermissionType.MANAGE_METADATA_CONFIG)),
METADATA_DOWNLOAD_ON_BOOKDROP ("metadata_download_on_bookdrop", false, false, List.of(PermissionType.ADMIN, PermissionType.MANAGE_METADATA_CONFIG)),
METADATA_PROVIDER_SPECIFIC_FIELDS ("metadata_provider_specific_fields", true, false, List.of(PermissionType.ADMIN, PermissionType.MANAGE_METADATA_CONFIG)),
// ADMIN + MANAGE_GLOBAL_PREFERENCES
COVER_CROPPING_SETTINGS ("cover_cropping_settings", true, false, List.of(PermissionType.ADMIN, PermissionType.MANAGE_GLOBAL_PREFERENCES)),
AUTO_BOOK_SEARCH ("auto_book_search", false, false, List.of(PermissionType.ADMIN, PermissionType.MANAGE_GLOBAL_PREFERENCES)),
SIMILAR_BOOK_RECOMMENDATION ("similar_book_recommendation", false, false, List.of(PermissionType.ADMIN, PermissionType.MANAGE_GLOBAL_PREFERENCES)),
CBX_CACHE_SIZE_IN_MB ("cbx_cache_size_in_mb", false, false, List.of(PermissionType.ADMIN, PermissionType.MANAGE_GLOBAL_PREFERENCES)),
PDF_CACHE_SIZE_IN_MB ("pdf_cache_size_in_mb", false, false, List.of(PermissionType.ADMIN, PermissionType.MANAGE_GLOBAL_PREFERENCES)),
MAX_FILE_UPLOAD_SIZE_IN_MB ("max_file_upload_size_in_mb", false, false, List.of(PermissionType.ADMIN, PermissionType.MANAGE_GLOBAL_PREFERENCES)),
TELEMETRY_ENABLED ("telemetryEnabled", false, false, List.of(PermissionType.ADMIN, PermissionType.MANAGE_GLOBAL_PREFERENCES)),
@@ -18,8 +18,9 @@ public class AppSettings {
private boolean autoBookSearch;
private boolean similarBookRecommendation;
private boolean opdsServerEnabled;
private boolean komgaApiEnabled;
private boolean komgaGroupUnknown;
private String uploadPattern;
private Integer cbxCacheSizeInMb;
private Integer pdfCacheSizeInMb;
private Integer maxFileUploadSizeInMb;
private boolean remoteAuthEnabled;
@@ -34,4 +35,5 @@ public class AppSettings {
private MetadataPublicReviewsSettings metadataPublicReviewsSettings;
private KoboSettings koboSettings;
private CoverCroppingSettings coverCroppingSettings;
private MetadataProviderSpecificFields metadataProviderSpecificFields;
}
@@ -33,6 +33,7 @@ public class MetadataMatchWeights {
private int hardcoverReviewCount;
private int doubanRating;
private int doubanReviewCount;
private int ranobedbRating;
private int coverImage;
public int totalWeight() {
@@ -40,6 +41,7 @@ public class MetadataMatchWeights {
seriesName + seriesNumber + seriesTotal + isbn13 + isbn10 + language +
pageCount + categories + amazonRating + amazonReviewCount +
goodreadsRating + goodreadsReviewCount + hardcoverRating +
hardcoverReviewCount + doubanRating + doubanReviewCount + coverImage;
hardcoverReviewCount + doubanRating + doubanReviewCount +
ranobedbRating + coverImage;
}
}
@@ -24,7 +24,9 @@ public class MetadataPersistenceSettings {
private FormatSettings cbx;
public boolean isAnyFormatEnabled() {
return (epub != null && epub.isEnabled()) || (pdf != null && pdf.isEnabled() || (cbx != null && cbx.isEnabled()));
return (epub != null && epub.isEnabled())
|| (pdf != null && pdf.isEnabled())
|| (cbx != null && cbx.isEnabled());
}
}

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