Merge pull request #2029 from booklore-app/develop

Merge develop into master for release
This commit is contained in:
ACX
2025-12-28 22:23:14 -07:00
committed by GitHub
196 changed files with 12007 additions and 4781 deletions
-47
View File
@@ -1,47 +0,0 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: bug
assignees: ''
---
# 🐛 Bug Report
## 📝 Description
<!-- Describe what went wrong -->
## 🔄 Steps to Reproduce
<!-- Provide detailed steps to reproduce the behavior. Be specific about what you clicked, typed, or configured -->
1.
2.
3.
4.
**Result:** <!-- What happened after these steps? -->
## ✅ Expected Behavior
<!-- Describe what should have happened instead -->
## 📸 Screenshots / Error Messages _(Optional)_
<!-- Share any screenshots or error messages here (just drag & drop) -->
## 💻 Environment
<!-- Provide details about your setup - every detail helps! -->
- **Booklore Version:** (e.g., v1.1.0)
- **OS:** (e.g., Windows 11, macOS Sonoma, Ubuntu 22.04)
- **Browser:** (e.g., Chrome 120, Firefox 121, Safari 17)
- **Installation:** (e.g., Docker, Unraid, Manual)
- **Storage Type:** (e.g., Local HDD/SSD, Synology NAS, SMB Share, NFS Mount, S3 Bucket)
## 💡 Possible Solution _(Optional)_
<!-- Share any ideas on how to fix this issue -->
## 📌 Additional Context _(Optional)_
<!-- Add any other relevant information: recent changes, specific books, configuration details, etc. -->
+79
View File
@@ -0,0 +1,79 @@
name: Bug Report
description: Report a bug to help us improve Booklore
title: "[Bug] "
labels: [ "bug" ]
body:
- type: markdown
attributes:
value: |
Please fill out the details below so we can investigate and fix the issue.
- type: checkboxes
id: prerequisites
attributes:
label: Quick Check
options:
- label: I've searched existing issues and this bug hasn't been reported yet
required: true
- type: textarea
id: description
attributes:
label: What Went Wrong?
description: Give us a clear description of the bug
placeholder: "Example: When I try to add a book to my 'Want to Read' shelf, the page refreshes but the book doesn't appear on the shelf"
validations:
required: true
- type: textarea
id: steps
attributes:
label: How Can We Reproduce This?
description: Walk us through the steps to reproduce the bug
placeholder: |
1. Go to the book details page for "The Hobbit"
2. Click on the "Add to Shelf" dropdown
3. Select "Want to Read"
4. Click "Save"
5. Navigate to the "Want to Read" shelf
Result: The book doesn't appear on the shelf
validations:
required: true
- type: textarea
id: expected
attributes:
label: What Should Have Happened?
description: Tell us what you expected to happen instead
placeholder: "Example: The book should appear on my 'Want to Read' shelf immediately after clicking Save"
validations:
required: true
- type: textarea
id: screenshots
attributes:
label: Screenshots or Error Messages (Optional)
description: If you have any screenshots or error messages, feel free to share them here
placeholder: "Just drag and drop images or paste error messages here"
- type: textarea
id: solution
attributes:
label: Any Ideas on How to Fix This? (Optional)
description: If you have thoughts on what might be causing this or how to fix it, we'd love to hear them
- type: textarea
id: environment
attributes:
label: Your Setup
description: Help us understand your environment
placeholder: |
- Booklore Version: v1.1.0
- OS: macOS Sonoma 14.2
- Browser: Chrome 120
- Installation: Docker
- Storage Type: Local SSD
validations:
required: true
+5
View File
@@ -0,0 +1,5 @@
blank_issues_enabled: false
contact_links:
- name: Questions & Support
url: https://discord.gg/Ee5hd458Uz
about: Join our Discord community to chat with other users and maintainers.
-35
View File
@@ -1,35 +0,0 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: ''
---
# ✨ Feature Request
## 📝 Description
<!-- Describe the problem you're facing and the solution you're proposing -->
## 🌟 Benefits
<!-- Explain the value this feature would bring and who would benefit from it -->
## 💻 Use Cases
<!-- Describe specific scenarios where this feature would be useful -->
1.
2.
3.
## 📸 Visual References _(Optional)_
<!-- Add screenshots, mockups, wireframes, or examples from other applications -->
## 🎨 Technical Details _(Optional)_
<!-- Share implementation ideas, alternative solutions, or related features -->
## 📌 Additional Context _(Optional)_
<!-- Any other information, research, or context that would be helpful -->
@@ -0,0 +1,59 @@
name: Feature Request
description: Suggest a new feature or enhancement for Booklore
title: "[Feature] "
labels: ["feature"]
body:
- type: markdown
attributes:
value: |
Please share as much detail as you can to help us understand your suggestion.
- type: checkboxes
id: prerequisites
attributes:
label: Quick Check
options:
- label: I've searched existing issues and this feature hasn't been requested yet
required: true
- type: textarea
id: description
attributes:
label: What's Your Idea?
description: Tell us about the feature you'd like to see
placeholder: "Example: Add a 'Currently Reading' shelf where I can track books I'm reading and see my progress"
validations:
required: true
- type: textarea
id: problem
attributes:
label: Why Would This Be Helpful?
description: Help us understand the problem this solves or the value it brings
placeholder: "Example: Right now, it's hard to keep track of multiple books I'm reading at once. Having a dedicated shelf with progress tracking would help me stay organized"
validations:
required: true
- type: textarea
id: additional-context
attributes:
label: Anything Else? (Optional)
description: Feel free to add screenshots, mockups, examples from other apps, or implementation ideas
placeholder: |
You might want to include:
- Screenshots or mockups showing what you envision
- Examples from other apps you like (Goodreads, StoryGraph, etc.)
- Ideas for how it could work (progress bars, page counters, etc.)
- Alternative approaches you've thought about
- type: dropdown
id: willing-to-contribute
attributes:
label: Want to Help Out?
description: Let us know if you'd like to be involved in making this happen
options:
- "Yes! I'd love to help implement this"
- "I'm happy to help test and give feedback"
- "Just sharing the idea for now"
validations:
required: true
+146
View File
@@ -0,0 +1,146 @@
name: Develop & PR – Build, Test, and Container Publish
on:
push:
branches:
- develop
pull_request:
branches:
- '**'
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
jobs:
migration-check:
name: Flyway Migration Check
uses: ./.github/workflows/migrations-check.yml
with:
base_ref: 'origin/develop'
head_ref: 'HEAD'
build-and-push:
needs: [ migration-check ]
if: needs.migration-check.result == 'success' || needs.migration-check.result == 'skipped'
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
checks: write
pull-requests: write
steps:
- name: Checkout Repository
uses: actions/checkout@v6
with:
fetch-depth: 0
# ----------------------------------------
# Environment setup
# ----------------------------------------
- name: Set Up QEMU for Multi-Arch Builds
uses: docker/setup-qemu-action@v3
- name: Set Up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Set Up JDK 21
uses: actions/setup-java@v5
with:
java-version: '21'
distribution: 'temurin'
cache: gradle
# ----------------------------------------
# Backend tests
# ----------------------------------------
- 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: 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
# ----------------------------------------
# Image tagging
# ----------------------------------------
- name: Generate Image Tag
id: set_image_tag
run: |
short_sha=$(git rev-parse --short HEAD)
if [ "${{ github.event_name }}" = "pull_request" ]; then
image_tag="pr-${{ github.event.pull_request.number }}-${short_sha}"
else
image_tag="develop-${short_sha}"
fi
echo "image_tag=$image_tag" >> $GITHUB_ENV
echo "Image tag: $image_tag"
# ----------------------------------------
# Docker login (pushes & internal PRs only)
# ----------------------------------------
- name: Authenticate to Docker Hub
if: github.event_name == 'push' || github.event.pull_request.head.repo.full_name == github.repository
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Authenticate to GitHub Container Registry
if: github.event_name == 'push' || github.event.pull_request.head.repo.full_name == github.repository
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ github.token }}
# ----------------------------------------
# Docker build & push (push + internal PRs)
# ----------------------------------------
- name: Build and push Docker image
if: github.event_name == 'push' || github.event.pull_request.head.repo.full_name == github.repository
uses: docker/build-push-action@v6
with:
context: .
platforms: linux/amd64,linux/arm64
push: true
tags: |
booklore/booklore:${{ env.image_tag }}
ghcr.io/booklore-app/booklore:${{ env.image_tag }}
build-args: |
APP_VERSION=${{ env.image_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
-305
View File
@@ -1,305 +0,0 @@
name: Build, Tag, Push, and Release to GitHub Container Registry
on:
push:
branches:
- 'master'
- 'develop'
pull_request:
branches:
- '**'
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
jobs:
check-for-migrations:
name: Check for DB Migrations
if: github.event_name == 'pull_request' && ((github.base_ref == 'master' && github.head_ref == 'develop') || github.base_ref == 'develop')
runs-on: ubuntu-latest
outputs:
has_migrations: ${{ steps.check_migrations.outputs.has_migrations }}
steps:
- name: Checkout Repository for Diff
uses: actions/checkout@v6
with:
fetch-depth: 0
- name: Detect Flyway Migration Changes
id: check_migrations
run: |
# Compare PR head with the target base branch
if git diff --name-only origin/${{ github.base_ref }}...HEAD | grep -q "booklore-api/src/main/resources/db/migration/V.*.sql"; then
echo "Migration file changes detected. Proceeding with migration preview."
echo "has_migrations=true" >> $GITHUB_OUTPUT
else
echo "No migration file changes detected. Skipping migration preview."
echo "has_migrations=false" >> $GITHUB_OUTPUT
fi
flyway-migration-preview:
name: Flyway DB Migration Preview
needs: [ check-for-migrations ]
if: needs.check-for-migrations.outputs.has_migrations == 'true'
runs-on: ubuntu-latest
services:
mariadb:
image: mariadb:10.6
env:
MYSQL_ROOT_PASSWORD: root
MYSQL_DATABASE: booklore_test
ports:
- 3306:3306
options: >-
--health-cmd="mysqladmin ping --silent"
--health-interval=5s
--health-timeout=5s
--health-retries=10
steps:
- name: Checkout Base Branch
uses: actions/checkout@v6
with:
ref: '${{ github.base_ref }}'
- name: Apply Migrations from Base Branch
run: |
echo "Applying migrations from '${{ github.base_ref }}' branch..."
docker run --network host \
-v ${{ github.workspace }}:/flyway/sql \
flyway/flyway:11.19.0-alpine \
-url=jdbc:mariadb://127.0.0.1:3306/booklore_test \
-user=root -password=root \
-locations=filesystem:/flyway/sql/booklore-api/src/main/resources/db/migration \
migrate
- name: Checkout Pull Request Branch
uses: actions/checkout@v6
- name: Apply Migrations from PR Branch
run: |
echo "Applying new migrations from PR branch..."
docker run --network host \
-v ${{ github.workspace }}:/flyway/sql \
flyway/flyway:11.19.0-alpine \
-url=jdbc:mariadb://127.0.0.1:3306/booklore_test \
-user=root -password=root \
-locations=filesystem:/flyway/sql/booklore-api/src/main/resources/db/migration \
migrate
- name: Confirm Flyway Dry Run Success
run: echo "✅ Flyway migration preview successful. Migrations can be applied cleanly."
build-and-push:
needs: [ check-for-migrations, flyway-migration-preview ]
if: always() && (needs.flyway-migration-preview.result == 'success' || needs.flyway-migration-preview.result == 'skipped')
runs-on: ubuntu-latest
permissions:
contents: write
packages: write
issues: read
checks: write
pull-requests: write
steps:
- name: Checkout Repository
uses: actions/checkout@v6
with:
fetch-depth: 0
- name: Authenticate to Docker Hub
if: github.event_name == 'push'
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Authenticate to GitHub Container Registry
if: github.event_name == 'push'
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ github.token }}
- name: Set Up QEMU for Multi-Architecture Builds
uses: docker/setup-qemu-action@v3
- name: Set Up Docker Buildx
uses: docker/setup-buildx-action@v3
- 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 with testcontainers..."
./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
comment_title: Backend Test Results
report_individual_runs: true
report_suite_logs: 'any'
- name: Upload Backend Test Reports
uses: actions/upload-artifact@v6
if: always()
with:
name: 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! Check the test results above."
exit 1
- name: Retrieve Latest Master Version Tag
id: get_version
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"
- name: Determine Version Bump (Master Only)
if: github.ref == 'refs/heads/master'
id: determine_bump
env:
GH_TOKEN: ${{ github.token }}
run: |
echo "Determining version bump from PR labels..."
# 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
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)
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: Generate Image Tag
id: set_image_tag
run: |
branch="${GITHUB_REF#refs/heads/}"
if [[ "$branch" == "master" ]]; then
image_tag="${{ env.new_tag }}"
elif [[ "$branch" == "develop" ]]; then
short_sha=$(git rev-parse --short HEAD)
image_tag="${{ env.latest_tag }}-develop-${short_sha}"
else
short_sha=$(git rev-parse --short HEAD)
image_tag="${short_sha}"
fi
echo "image_tag=$image_tag" >> $GITHUB_ENV
echo "Image tag: $image_tag"
- name: Build and push Docker image
if: github.event_name == 'push'
uses: docker/build-push-action@v6
with:
context: .
platforms: linux/amd64,linux/arm64
push: true
tags: |
booklore/booklore:${{ env.image_tag }}
ghcr.io/booklore-app/booklore:${{ env.image_tag }}
build-args: |
APP_VERSION=${{ env.image_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: Push Latest Tag (Master Only)
if: github.ref == 'refs/heads/master' && github.event_name == 'push'
uses: docker/build-push-action@v6
with:
context: .
platforms: linux/amd64,linux/arm64
push: true
tags: |
booklore/booklore:latest
booklore/booklore:${{ env.new_tag }}
ghcr.io/booklore-app/booklore:latest
ghcr.io/booklore-app/booklore:${{ env.new_tag }}
build-args: |
APP_VERSION=${{ env.new_tag }}
APP_REVISION=${{ github.sha }}
cache-from: type=gha
- name: Update GitHub Release Draft (Master Only)
if: github.ref == 'refs/heads/master'
uses: release-drafter/release-drafter@v6
with:
tag: ${{ env.new_tag }}
name: "Release ${{ env.new_tag }}"
env:
GITHUB_TOKEN: ${{ github.token }}
- name: Publish GitHub Draft Release (Master Only)
if: github.ref == 'refs/heads/master'
env:
GITHUB_TOKEN: ${{ github.token }}
run: |
gh release edit ${{ env.new_tag }} --draft=true
+154
View File
@@ -0,0 +1,154 @@
name: Master - Build, Tag, Push, and Release
on:
push:
branches:
- 'master'
jobs:
migration-check:
name: Flyway Migration Check on Master
uses: ./.github/workflows/migrations-check.yml
with:
base_ref: 'HEAD~1'
head_ref: 'HEAD'
build-and-release:
needs: [ migration-check ]
if: needs.migration-check.result == 'success' || needs.migration-check.result == 'skipped'
runs-on: ubuntu-latest
permissions:
contents: write
packages: write
pull-requests: read
steps:
- name: Checkout Repository
uses: actions/checkout@v6
with:
fetch-depth: 0
- 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 }}
- name: Set Up QEMU for Multi-Architecture Builds
uses: docker/setup-qemu-action@v3
- name: Set Up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Set Up JDK 21
uses: actions/setup-java@v5
with:
java-version: '21'
distribution: 'temurin'
cache: 'gradle'
- name: Retrieve Latest Master Version Tag
id: get_version
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"
- name: Determine Version Bump
id: determine_bump
env:
GH_TOKEN: ${{ github.token }}
run: |
echo "Determining version bump from PR labels..."
# 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
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)
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
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
build-args: |
APP_VERSION=${{ env.new_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: Update GitHub Release Draft
uses: release-drafter/release-drafter@v6
with:
tag: ${{ env.new_tag }}
name: "Release ${{ env.new_tag }}"
env:
GITHUB_TOKEN: ${{ github.token }}
- name: Publish GitHub Draft Release
env:
GITHUB_TOKEN: ${{ github.token }}
run: |
gh release edit ${{ env.new_tag }} --draft=true
+97
View File
@@ -0,0 +1,97 @@
name: Reusable - Flyway Migration Check
on:
workflow_call:
inputs:
base_ref:
description: 'The base ref for comparison'
required: true
type: string
head_ref:
description: 'The head ref for comparison'
required: true
type: string
outputs:
has_migrations:
description: "Boolean indicating if migration files were changed"
value: ${{ jobs.check-for-migrations.outputs.has_migrations }}
jobs:
check-for-migrations:
name: Check for DB Migrations
runs-on: ubuntu-latest
outputs:
has_migrations: ${{ steps.check_migrations.outputs.has_migrations }}
steps:
- name: Checkout Repository
uses: actions/checkout@v6
with:
fetch-depth: 0
- name: Detect Flyway Migration Changes
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
echo "Migration file changes detected. Proceeding with migration preview."
echo "has_migrations=true" >> $GITHUB_OUTPUT
else
echo "No migration file changes detected. Skipping migration preview."
echo "has_migrations=false" >> $GITHUB_OUTPUT
fi
flyway-migration-preview:
name: Flyway DB Migration Preview
needs: [ check-for-migrations ]
if: needs.check-for-migrations.outputs.has_migrations == 'true'
runs-on: ubuntu-latest
services:
mariadb:
image: mariadb:10.6
env:
MYSQL_ROOT_PASSWORD: root
MYSQL_DATABASE: booklore_test
ports:
- 3306:3306
options: >-
--health-cmd="mysqladmin ping --silent"
--health-interval=5s
--health-timeout=5s
--health-retries=10
steps:
- name: Checkout Base Branch
uses: actions/checkout@v6
with:
ref: ${{ inputs.base_ref }}
- name: Apply Migrations from Base Branch
run: |
echo "Applying migrations from base ref (${{ inputs.base_ref }})..."
docker run --network host \
-v ${{ github.workspace }}:/flyway/sql \
flyway/flyway:11.19.0-alpine \
-url=jdbc:mariadb://127.0.0.1:3306/booklore_test \
-user=root -password=root \
-locations=filesystem:/flyway/sql/booklore-api/src/main/resources/db/migration \
migrate
- name: Checkout Head Branch
uses: actions/checkout@v6
with:
ref: ${{ inputs.head_ref }}
- name: Apply Migrations from Head Branch
run: |
echo "Applying new migrations from head ref (${{ inputs.head_ref }})..."
docker run --network host \
-v ${{ github.workspace }}:/flyway/sql \
flyway/flyway:11.19.0-alpine \
-url=jdbc:mariadb://127.0.0.1:3306/booklore_test \
-user=root -password=root \
-locations=filesystem:/flyway/sql/booklore-api/src/main/resources/db/migration \
migrate
- name: Confirm Flyway Dry Run Success
run: echo "✅ Flyway migration preview successful. Migrations can be applied cleanly."
+311 -96
View File
@@ -1,107 +1,237 @@
# BookLore
<div align="center">
![GitHub release (latest by date)](https://img.shields.io/github/v/release/adityachandelgit/BookLore?color=green)
![License](https://img.shields.io/github/license/adityachandelgit/BookLore?color=orange)
![Stars](https://img.shields.io/github/stars/adityachandelgit/BookLore?style=social)
![Docker Pulls](https://img.shields.io/docker/pulls/booklore/booklore?color=2496ED)
[![Join us on Discord](https://img.shields.io/badge/Chat-Discord-5865F2?logo=discord&style=flat)](https://discord.gg/Ee5hd458Uz)
[![Open Collective backers and sponsors](https://img.shields.io/opencollective/all/booklore?label=Open%20Collective&logo=opencollective&color=7FADF2)](https://opencollective.com/booklore)
# 📚 BookLore
BookLore is a self-hosted web app for organizing and managing your personal book collection. It provides an intuitive interface to browse, read, and track your progress across PDFs and eBooks. With robust metadata management, multi-user support, and a sleek, modern UI, BookLore makes it easy to
build and explore your personal library.
### *Your Personal Library, Beautifully Organized*
![BookLore Demo](assets/demo.gif)
<p align="center">
<img src="assets/demo.gif" alt="BookLore Demo" width="800px" style="border-radius: 10px; box-shadow: 0 4px 6px rgba(0,0,0,0.1);" />
</p>
## ✨ Key Features
[![Release](https://img.shields.io/github/v/release/adityachandelgit/BookLore?color=4c6ef5&style=for-the-badge&logo=github)](https://github.com/adityachandelgit/BookLore/releases)
[![License](https://img.shields.io/github/license/adityachandelgit/BookLore?color=fab005&style=for-the-badge)](LICENSE)
[![Stars](https://img.shields.io/github/stars/adityachandelgit/BookLore?style=for-the-badge&color=ffd43b)](https://github.com/adityachandelgit/BookLore/stargazers)
[![Docker Pulls](https://img.shields.io/docker/pulls/booklore/booklore?color=2496ED&style=for-the-badge&logo=docker&logoColor=white)](https://hub.docker.com/r/booklore/booklore)
- 📚 **Smart Organization**: Build your dream library with custom shelves, smart sorting, and powerful filters to find any book instantly
- 👥 **Multi-User Management**: Add users with granular permissions for library access and content control
- 📲 **Kobo Integration**: Seamlessly sync your library with Kobo devices and convert EPUBs to KEPUB automatically
- ✨ **Magic Shelves**: Create dynamic, rule-based smart collections that auto-update in real time - like smart playlists for your books
- 🧠 **Auto Metadata**: Fetch rich book details from Goodreads, Amazon, Google Books, and Hardcover
- 📤 **BookDrop Import**: Drop files in a folder for automatic detection and bulk import
- 🌐 **OPDS Support**: Connect reading apps directly to your library for wireless downloads
- 🔑 **Flexible Authentication**: Choose between local accounts or external OIDC providers (Authentik, Pocket ID)
- 🔄 **KOReader Sync**: Track reading progress across KOReader and BookLore
- 📧 **One-Click Sharing**: Send books via email directly from the interface
- 🔐 **Private Notes**: Save personal reading notes visible only to you
- 🌍 **Community Reviews**: Auto-fetch public reviews to enrich your library
- 📖 **Built-in Reader**: Read PDFs, EPUBs, and comics with customizable themes
- 📱 **Mobile Ready**: Fully responsive design optimized for all devices
[![Discord](https://img.shields.io/badge/Join_Discord-5865F2?style=for-the-badge&logo=discord&logoColor=white)](https://discord.gg/Ee5hd458Uz)
[![Open Collective](https://img.shields.io/opencollective/all/booklore?style=for-the-badge&color=7FADF2&logo=opencollective)](https://opencollective.com/booklore)
## 💖 Support the Project
---
If you find **BookLore** helpful, please consider supporting its development:
**BookLore** is a powerful, self-hosted web application designed to organize and manage your personal book collection with elegance and ease. Build your dream library with an intuitive interface, robust metadata management, and seamless multi-user support.
- ⭐ Star this repository to show your appreciation and help others discover it.
- 💸 Contribute via [Open Collective](https://opencollective.com/booklore) to help fund development, hosting, and testing costs.
> 📌 Currently raising funds for a **Kobo device** to implement and test native Kobo sync support.
> 💡 [Support the Kobo Sync Bounty →](https://opencollective.com/booklore/projects/kobo-device-for-testing)
[🚀 Get Started](#-getting-started-with-booklore) • [📖 Documentation](https://booklore-app.github.io/booklore-docs/) • [🎮 Try Demo](#-live-demo-explore-booklore-in-action) • [💬 Community](https://discord.gg/Ee5hd458Uz)
## 🌐 Live Demo: Explore BookLore in Action
</div>
Evaluate BookLore’s features and user experience in a live environment:
---
**Demo Access:**
<div align="center">
- 🌐 **URL:** [demo.booklore.dev](https://demo.booklore.dev)
- 👤 **Username:** `booklore`
- 🔑 **Password:** `9HC20PGGfitvWaZ1`
## ✨ **Features That Make BookLore Shine**
> ⚠️ **Note:**
> The demo account has standard user permissions only.
> - **Admin features** (user management, library setup, advanced configuration) are not available in this demo.
> - To explore all capabilities, including administration and multi-user management, please deploy your own instance as described below.
</div>
## 🚀 Getting Started with BookLore
<table>
<tr>
<td width="50%">
Kick off your BookLore journey with our official documentation and helpful video guides.
### 📖 **Library Management**
📘 [BookLore Documentation: Getting Started](https://booklore-app.github.io/booklore-docs/docs/getting-started/)
Our up-to-date docs walk you through installation, setup, configuration, and key features, everything you need to get up and running smoothly.
- **Smart Organization**: Custom shelves with powerful filters
- **Magic Shelves**: Dynamic, auto-updating collections
- **Auto Metadata**: Rich details from multiple sources
- **Advanced Search**: Find any book instantly
> 💡 **Want to improve the documentation?**
> You can update the docs at [booklore-app/booklore-docs](https://github.com/booklore-app/booklore-docs) and create a pull request to contribute your changes!
</td>
<td width="50%">
## 🐳 Deploy with Docker
### 🌐 **Connectivity**
You can quickly set up and run BookLore using Docker.
- **Kobo Integration**: Seamless device sync
- **OPDS Support**: Connect any reading app
- **KOReader Sync**: Cross-platform progress tracking
- **Email Sharing**: One-click book sending
### 1️⃣ Install Docker & Docker Compose
</td>
</tr>
<tr>
<td width="50%">
### 👥 **User Experience**
- **Multi-User Support**: Granular permissions
- **Flexible Auth**: Local or OIDC providers
- **Mobile Ready**: Responsive on all devices
- **Built-in Reader**: PDFs, EPUBs, comics
</td>
<td width="50%">
### 🚀 **Smart Features**
- **BookDrop Import**: Auto-detect bulk files
- **Private Notes**: Personal reading annotations
- **Community Reviews**: Enriched book data
- **Progress Tracking**: Reading statistics
</td>
</tr>
</table>
---
<div align="center">
## 💖 **Support the Project**
</div>
<div align="center">
Your support helps BookLore grow and improve! 🌱
<table>
<tr>
<td align="center" width="33%">
### ⭐ **Star Us**
Give us a star to show your support and help others discover BookLore!
[![Star this repo](https://img.shields.io/github/stars/adityachandelgit/BookLore?style=social)](https://github.com/adityachandelgit/BookLore)
</td>
<td align="center" width="33%">
### 💰 **Sponsor**
Support development, hosting, and testing costs
[![Open Collective](https://img.shields.io/badge/Open_Collective-7FADF2?style=for-the-badge&logo=opencollective&logoColor=white)](https://opencollective.com/booklore)
</td>
<td align="center" width="34%">
### 📢 **Spread the Word**
Share BookLore with fellow book lovers and developers!
</td>
</tr>
</table>
> 🎯 **Current Goal:** Raising funds for a **Kobo device** to implement native Kobo sync support
> [💡 Support the Kobo Sync Bounty →](https://opencollective.com/booklore/projects/kobo-device-for-testing)
</div>
---
<div align="center">
## 🎮 **Live Demo: Explore BookLore in Action**
</div>
<div align="center">
Experience BookLore's features in a live environment before deploying your own instance!
| 🌐 Demo URL | 👤 Username | 🔑 Password |
|----------------------------------------------------|-------------|--------------------|
| **[demo.booklore.dev](https://demo.booklore.dev)** | `booklore` | `9HC20PGGfitvWaZ1` |
> ⚠️ **Note:** Demo account has standard user permissions only.
> Admin features (user management, library setup) require a self-hosted instance.
</div>
---
<div align="center">
## 🚀 **Getting Started with BookLore**
### Choose Your Path
<table>
<tr>
<td align="center" width="50%">
### 📘 **Documentation**
Guides for installation, setup, features, and more
[![Read the Docs](https://img.shields.io/badge/📖_Read_the_Docs-4c6ef5?style=for-the-badge)](https://booklore-app.github.io/booklore-docs/docs/getting-started/)
*Contribute to the docs at: [booklore-docs](https://github.com/booklore-app/booklore-docs)*
</td>
<td align="center" width="50%">
### 🐳 **Quick Deploy**
Get up and running in minutes with Docker
[![Deploy with Docker](https://img.shields.io/badge/🐳_Deploy_Now-2496ED?style=for-the-badge)](#-deploy-with-docker)
*Easiest way to self-host BookLore*
</td>
</tr>
</table>
</div>
---
<div align="center">
## 🐳 **Deploy with Docker**
</div>
### **Prerequisites**
Ensure you have [Docker](https://docs.docker.com/get-docker/) and [Docker Compose](https://docs.docker.com/compose/install/) installed.
**Image Repositories:**
<details>
<summary><b>📦 Image Repositories</b></summary>
- Docker Hub: `https://hub.docker.com/r/booklore/booklore`
- GitHub Container Registry: `https://ghcr.io/booklore-app/booklore`
- 🐳 **Docker Hub:** `booklore/booklore`
- 📦 **GitHub Container Registry:** `ghcr.io/booklore-app/booklore`
> **Note:** Legacy images under `https://ghcr.io/adityachandelgit/booklore-app` will remain available but will not receive new updates.
> 💡 Legacy images at `ghcr.io/adityachandelgit/booklore-app` remain available but won't receive updates.
### 2️⃣ Set Up Your docker-compose.yml Configuration
</details>
**Step 1: Create a `.env` file** in the same directory as your `docker-compose.yml`:
### **Step 1️⃣: Create Environment Configuration**
Create a `.env` file in your project directory:
```ini
# BookLore Application Settings
# 🎯 BookLore Application Settings
APP_USER_ID=0
APP_GROUP_ID=0
TZ=Etc/UTC
BOOKLORE_PORT=6060
# Database Connection (BookLore)
# 🗄️ Database Connection (BookLore)
DATABASE_URL=jdbc:mariadb://mariadb:3306/booklore
DB_USER=booklore
DB_PASSWORD=ChangeMe_BookLoreApp_2025!
# MariaDB Container Settings
# 🔧 MariaDB Container Settings
DB_USER_ID=1000
DB_GROUP_ID=1000
MYSQL_ROOT_PASSWORD=ChangeMe_MariaDBRoot_2025!
MYSQL_DATABASE=booklore
```
**Step 2: Create a `docker-compose.yml` file** that references the `.env` variables:
### **Step 2️⃣: Create Docker Compose File**
Create a `docker-compose.yml` file:
```yaml
services:
@@ -150,75 +280,160 @@ services:
retries: 10
```
### 3️⃣ Start the Containers
### **Step 3️⃣: Launch BookLore**
Run the following command to start the services:
```ini
```bash
docker compose up -d
```
### 4️⃣ Access BookLore
### **Step 4️⃣: Access Your Library**
Once the containers are up, access BookLore in your browser at:
Open your browser and navigate to:
```ini
http://localhost:6060
**🌐 http://localhost:6060**
🎉 **Welcome to your personal library!**
---
<div align="center">
## 📥 **BookDrop: Automatic Import**
### *Drop Files, Import Automatically*
</div>
BookLore's **BookDrop** feature automatically detects and processes book files dropped into a designated folder.
### **How It Works**
```mermaid
graph LR
A[📁 Drop Files] --> B[🔍 Auto-Detect]
B --> C[📊 Extract Metadata]
C --> D[✅ Review & Import]
```
## 📥 Bookdrop Folder: Auto-Import Files
1. **File Watcher**: Monitors the BookDrop folder continuously
2. **Auto-Detection**: Processes new files and extracts metadata
3. **Metadata Enrichment**: Fetches details from Google Books, Open Library
4. **Review & Finalize**: Review, edit, and import to your library
BookLore now supports a **Bookdrop folder**, a special directory where you can drop your book files (`.pdf`, `.epub`, `.cbz`, etc.), and BookLore will automatically detect, process, and prepare them for import. This makes it easy to bulk add new books without manually uploading each one.
### **Docker Configuration**
### 🔍 How It Works
1. **File Watcher:** A background process continuously monitors the Bookdrop folder.
2. **File Detection:** When new files are added, BookLore automatically reads them and extracts basic metadata (title, author, etc.) from filenames or embedded data.
3. **Optional Metadata Fetching:** If enabled, BookLore can query metadata sources like Google Books or Open Library to enrich the book information.
4. **Review & Finalize:** You can then review the detected books in the Bookdrop UI, edit metadata if needed, and assign each book to a library and folder structure before finalizing the import.
### ⚙️ Configuration (Docker Setup)
To enable the Bookdrop feature in Docker:
Add the BookDrop volume to your `docker-compose.yml`:
```yaml
services:
booklore:
...
volumes:
- ./data:/app/data
- ./books:/books
- ./bookdrop:/bookdrop # 👈 Bookdrop directory
- ./bookdrop:/bookdrop # 👈 BookDrop magic happens here
```
## 🤝 Community & Support
---
- 🐞 Found a bug? [Open an issue](https://github.com/adityachandelgit/BookLore/issues)
- ✨ Want to contribute? [Check out CONTRIBUTING.md](https://github.com/adityachandelgit/BookLore/blob/master/CONTRIBUTING.md)
- 💬 **Join our Discord**: [Click here to chat with the community](https://discord.gg/Ee5hd458Uz)
<div align="center">
## 📊 Repository Activity
## 🤝 **Community & Support**
<table>
<tr>
<td align="center">
![Alt](https://repobeats.axiom.co/api/embed/44a04220bfc5136e7064181feb07d5bf0e59e27e.svg "Repobeats analytics image")
### 🐞 **Bug Reports**
Found an issue?
[![Open Issue](https://img.shields.io/badge/Report-ff6b6b?style=for-the-badge)](https://github.com/booklore-app/booklore/issues)
</td>
<td align="center">
### 💡 **Feature Req**
Have an idea?
[![Request Feature](https://img.shields.io/badge/Suggest-4ecdc4?style=for-the-badge)](https://github.com/booklore-app/booklore/issues/new?template=feature_request.md)
</td>
<td align="center">
### 🤝 **Contribute**
Join development!
[![Contributing](https://img.shields.io/badge/Contribute-95e1d3?style=for-the-badge)](CONTRIBUTING.md)
</td>
<td align="center">
### 💬 **Chat**
Join community!
[![Discord](https://img.shields.io/badge/Discord-5865F2?style=for-the-badge&logo=discord&logoColor=white)](https://discord.gg/Ee5hd458Uz)
</td>
</tr>
</table>
</div>
## ⭐ Star History
---
<div align="center">
## 📊 **Project Analytics**
### Repository Activity
![Repository Activity](https://repobeats.axiom.co/api/embed/44a04220bfc5136e7064181feb07d5bf0e59e27e.svg)
### ⭐ Star History
<a href="https://www.star-history.com/#booklore-app/booklore&type=date&legend=top-left">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=booklore-app/booklore&type=date&theme=dark&legend=top-left" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=booklore-app/booklore&type=date&legend=top-left" />
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=booklore-app/booklore&type=date&legend=top-left" />
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=booklore-app/booklore&type=date&legend=top-left" width="600" />
</picture>
</a>
## 👨‍💻 Contributors & Developers
</div>
Thanks to all the amazing people who contribute to Booklore.
---
[![Contributors List](https://contrib.rocks/image?repo=adityachandelgit/BookLore)](https://github.com/adityachandelgit/BookLore/graphs/contributors)
<div align="center">
## ⚖️ License
## 👨‍💻 **Contributors**
* [GNU GPL v3](http://www.gnu.org/licenses/gpl.html)
* Copyright 2024-2025
### Thanks to all our amazing contributors! 🙏
[![Contributors](https://contrib.rocks/image?repo=adityachandelgit/BookLore)](https://github.com/adityachandelgit/BookLore/graphs/contributors)
**Want to see your face here?** [Start contributing today!](CONTRIBUTING.md)
</div>
---
<div align="center">
## ⚖️ **License**
**GNU General Public License v3.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)
---
<sub>Made with ❤️ by the BookLore community</sub>
**[⬆ Back to Top](#-booklore)**
</div>
@@ -12,14 +12,15 @@ public class BookParserConfig {
@Bean
public Map<MetadataProvider, BookParser> parserMap(GoogleParser googleParser, AmazonBookParser amazonBookParser,
GoodReadsParser goodReadsParser, HardcoverParser hardcoverParser, ComicvineBookParser comicvineBookParser, DoubanBookParser doubanBookParser) {
GoodReadsParser goodReadsParser, HardcoverParser hardcoverParser, ComicvineBookParser comicvineBookParser, DoubanBookParser doubanBookParser, LubimyCzytacParser lubimyczytacParser) {
return Map.of(
MetadataProvider.Amazon, amazonBookParser,
MetadataProvider.GoodReads, goodReadsParser,
MetadataProvider.Google, googleParser,
MetadataProvider.Hardcover, hardcoverParser,
MetadataProvider.Comicvine, comicvineBookParser,
MetadataProvider.Douban, doubanBookParser
MetadataProvider.Douban, doubanBookParser,
MetadataProvider.Lubimyczytac, lubimyczytacParser
);
}
}
@@ -0,0 +1,16 @@
package com.adityachandel.booklore.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestClient;
@Configuration
public class RestClientConfig {
@Bean
public RestClient restClient() {
return RestClient.builder()
.build();
}
}
@@ -10,8 +10,11 @@ import com.adityachandel.booklore.model.dto.request.ReadProgressRequest;
import com.adityachandel.booklore.model.dto.request.ReadStatusUpdateRequest;
import com.adityachandel.booklore.model.dto.request.ShelvesAssignmentRequest;
import com.adityachandel.booklore.model.dto.response.BookDeletionResponse;
import com.adityachandel.booklore.model.dto.response.BookStatusUpdateResponse;
import com.adityachandel.booklore.model.dto.response.PersonalRatingUpdateResponse;
import com.adityachandel.booklore.model.enums.ResetProgressType;
import com.adityachandel.booklore.service.book.BookService;
import com.adityachandel.booklore.service.book.BookUpdateService;
import com.adityachandel.booklore.service.metadata.BookMetadataService;
import com.adityachandel.booklore.service.recommender.BookRecommendationService;
import io.swagger.v3.oas.annotations.Operation;
@@ -40,6 +43,7 @@ import java.util.Set;
public class BookController {
private final BookService bookService;
private final BookUpdateService bookUpdateService;
private final BookRecommendationService bookRecommendationService;
private final BookMetadataService bookMetadataService;
@@ -54,8 +58,8 @@ public class BookController {
@Operation(summary = "Get a book by ID", description = "Retrieve details of a specific book by its ID.")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Book details returned successfully"),
@ApiResponse(responseCode = "404", description = "Book not found")
@ApiResponse(responseCode = "200", description = "Book details returned successfully"),
@ApiResponse(responseCode = "404", description = "Book not found")
})
@GetMapping("/{bookId}")
@CheckBookAccess(bookIdParam = "bookId")
@@ -67,8 +71,8 @@ public class BookController {
@Operation(summary = "Delete books", description = "Delete one or more books by their IDs. Requires admin or delete permission.")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Books deleted successfully"),
@ApiResponse(responseCode = "403", description = "Forbidden")
@ApiResponse(responseCode = "200", description = "Books deleted successfully"),
@ApiResponse(responseCode = "403", description = "Forbidden")
})
@PreAuthorize("@securityUtil.canDeleteBook() or @securityUtil.isAdmin()")
@DeleteMapping
@@ -105,8 +109,8 @@ public class BookController {
@Operation(summary = "Download book", description = "Download the book file. Requires download permission or admin.")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Book downloaded successfully"),
@ApiResponse(responseCode = "403", description = "Forbidden")
@ApiResponse(responseCode = "200", description = "Book downloaded successfully"),
@ApiResponse(responseCode = "403", description = "Forbidden")
})
@GetMapping("/{bookId}/download")
@PreAuthorize("@securityUtil.canDownload() or @securityUtil.isAdmin()")
@@ -165,50 +169,46 @@ public class BookController {
@Operation(summary = "Update read status", description = "Update the read status for one or more books.")
@ApiResponse(responseCode = "200", description = "Read status updated successfully")
@PutMapping("/read-status")
public ResponseEntity<List<Book>> updateReadStatus(
@Parameter(description = "Read status update request") @RequestBody @Valid ReadStatusUpdateRequest request) {
List<Book> updatedBooks = bookService.updateReadStatus(request.ids(), request.status());
return ResponseEntity.ok(updatedBooks);
@PostMapping("/status")
public List<BookStatusUpdateResponse> updateReadStatus(@RequestBody @Valid ReadStatusUpdateRequest request) {
return bookService.updateReadStatus(request.getBookIds(), request.getStatus());
}
@Operation(summary = "Reset reading progress", description = "Reset the reading progress for one or more books.")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Progress reset successfully"),
@ApiResponse(responseCode = "400", description = "No book IDs provided")
@ApiResponse(responseCode = "200", description = "Progress reset successfully"),
@ApiResponse(responseCode = "400", description = "No book IDs provided")
})
@PostMapping("/reset-progress")
public ResponseEntity<List<Book>> resetProgress(
public ResponseEntity<List<BookStatusUpdateResponse>> resetProgress(
@Parameter(description = "List of book IDs to reset progress for") @RequestBody List<Long> bookIds,
@Parameter(description = "Type of progress reset") @RequestParam ResetProgressType type) {
if (bookIds == null || bookIds.isEmpty()) {
throw ApiError.GENERIC_BAD_REQUEST.createException("No book IDs provided");
}
List<Book> updatedBooks = bookService.resetProgress(bookIds, type);
return ResponseEntity.ok(updatedBooks);
return ResponseEntity.ok(bookUpdateService.resetProgress(bookIds, type));
}
@Operation(summary = "Update personal rating", description = "Update the personal rating for one or more books.")
@ApiResponse(responseCode = "200", description = "Personal rating updated successfully")
@PutMapping("/personal-rating")
public ResponseEntity<List<Book>> updatePersonalRating(
public ResponseEntity<List<PersonalRatingUpdateResponse>> updatePersonalRating(
@Parameter(description = "Personal rating update request") @RequestBody @Valid PersonalRatingUpdateRequest request) {
List<Book> updatedBooks = bookService.updatePersonalRating(request.ids(), request.rating());
return ResponseEntity.ok(updatedBooks);
return ResponseEntity.ok(bookUpdateService.updatePersonalRating(request.ids(), request.rating()));
}
@Operation(summary = "Reset personal rating", description = "Reset the personal rating for one or more books.")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Personal rating reset successfully"),
@ApiResponse(responseCode = "400", description = "No book IDs provided")
@ApiResponse(responseCode = "200", description = "Personal rating reset successfully"),
@ApiResponse(responseCode = "400", description = "No book IDs provided")
})
@PostMapping("/reset-personal-rating")
public ResponseEntity<List<Book>> resetPersonalRating(
public ResponseEntity<List<PersonalRatingUpdateResponse>> resetPersonalRating(
@Parameter(description = "List of book IDs to reset personal rating for") @RequestBody List<Long> bookIds) {
if (bookIds == null || bookIds.isEmpty()) {
throw ApiError.GENERIC_BAD_REQUEST.createException("No book IDs provided");
}
List<Book> updatedBooks = bookService.resetPersonalRating(bookIds);
List<PersonalRatingUpdateResponse> updatedBooks = bookUpdateService.resetPersonalRating(bookIds);
return ResponseEntity.ok(updatedBooks);
}
}
@@ -15,6 +15,8 @@ import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
@Tag(name = "Icons", description = "Endpoints for managing SVG icons")
@AllArgsConstructor
@RestController
@@ -69,4 +71,12 @@ public class IconController {
iconService.deleteSvgIcon(svgName);
return ResponseEntity.ok().build();
}
@Operation(summary = "Get all icon contents", description = "Retrieve all SVG icons as a map of icon names to their content.")
@ApiResponse(responseCode = "200", description = "All icon contents retrieved successfully")
@GetMapping("/all/content")
public ResponseEntity<Map<String, String>> getAllIconsContent() {
Map<String, String> iconsMap = iconService.getAllIconsContent();
return ResponseEntity.ok(iconsMap);
}
}
@@ -1,22 +1,17 @@
package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.model.dto.request.ReadingSessionRequest;
import com.adityachandel.booklore.model.dto.response.ReadingSessionHeatmapResponse;
import com.adityachandel.booklore.model.dto.response.ReadingSessionTimelineResponse;
import com.adityachandel.booklore.model.dto.response.ReadingSessionResponse;
import com.adityachandel.booklore.service.ReadingSessionService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
import java.util.List;
@RestController
@AllArgsConstructor
@RequestMapping("/api/v1/reading-sessions")
@@ -35,30 +30,15 @@ public class ReadingSessionController {
return ResponseEntity.accepted().build();
}
@Operation(summary = "Get reading session heatmap for a year", description = "Returns daily reading session counts for the authenticated user for a specific year")
@Operation(summary = "Get reading sessions for a book", description = "Returns paginated reading sessions for a specific book for the authenticated user")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Heatmap data retrieved successfully"),
@ApiResponse(responseCode = "401", description = "Unauthorized")
@ApiResponse(responseCode = "200", description = "Reading sessions retrieved successfully"),
@ApiResponse(responseCode = "401", description = "Unauthorized"),
@ApiResponse(responseCode = "404", description = "Book not found")
})
@GetMapping("/heatmap/year/{year}")
@PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()")
public ResponseEntity<List<ReadingSessionHeatmapResponse>> getHeatmapForYear(@PathVariable int year) {
List<ReadingSessionHeatmapResponse> heatmapData = readingSessionService.getSessionHeatmapForYear(year);
return ResponseEntity.ok(heatmapData);
}
@Operation(summary = "Get reading session timeline for a week", description = "Returns reading sessions grouped by book for calendar timeline view")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Timeline data retrieved successfully"),
@ApiResponse(responseCode = "400", description = "Invalid week or year"),
@ApiResponse(responseCode = "401", description = "Unauthorized")
})
@GetMapping("/timeline/week/{year}/{week}")
@PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()")
public ResponseEntity<List<ReadingSessionTimelineResponse>> getTimelineForWeek(
@PathVariable int year,
@PathVariable int week) {
List<ReadingSessionTimelineResponse> timelineData = readingSessionService.getSessionTimelineForWeek(year, week);
return ResponseEntity.ok(timelineData);
@GetMapping("/book/{bookId}")
public ResponseEntity<Page<ReadingSessionResponse>> getReadingSessionsForBook(@PathVariable Long bookId, @RequestParam(defaultValue = "0") int page) {
Page<ReadingSessionResponse> sessions = readingSessionService.getReadingSessionsForBook(bookId, page);
return ResponseEntity.ok(sessions);
}
}
@@ -0,0 +1,114 @@
package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.model.dto.response.*;
import com.adityachandel.booklore.service.ReadingSessionService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@AllArgsConstructor
@RequestMapping("/api/v1/user-stats")
public class UserStatsController {
private final ReadingSessionService readingSessionService;
@Operation(summary = "Get reading session heatmap for a year", description = "Returns daily reading session counts for the authenticated user for a specific year")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Heatmap data retrieved successfully"),
@ApiResponse(responseCode = "401", description = "Unauthorized")
})
@GetMapping("/heatmap")
@PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()")
public ResponseEntity<List<ReadingSessionHeatmapResponse>> getHeatmapForYear(@RequestParam int year) {
List<ReadingSessionHeatmapResponse> heatmapData = readingSessionService.getSessionHeatmapForYear(year);
return ResponseEntity.ok(heatmapData);
}
@Operation(summary = "Get reading session timeline for a week", description = "Returns reading sessions grouped by book for calendar timeline view")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Timeline data retrieved successfully"),
@ApiResponse(responseCode = "400", description = "Invalid week, month, or year"),
@ApiResponse(responseCode = "401", description = "Unauthorized")
})
@GetMapping("/timeline")
@PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()")
public ResponseEntity<List<ReadingSessionTimelineResponse>> getTimelineForWeek(
@RequestParam int year,
@RequestParam int month,
@RequestParam int week) {
List<ReadingSessionTimelineResponse> timelineData = readingSessionService.getSessionTimelineForWeek(year, month, week);
return ResponseEntity.ok(timelineData);
}
@Operation(summary = "Get reading speed analysis", description = "Returns average reading speed (progress per minute) over time for a specific year")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Reading speed data retrieved successfully"),
@ApiResponse(responseCode = "401", description = "Unauthorized")
})
@GetMapping("/speed")
@PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()")
public ResponseEntity<List<ReadingSpeedResponse>> getReadingSpeedForYear(@RequestParam int year) {
List<ReadingSpeedResponse> speedData = readingSessionService.getReadingSpeedForYear(year);
return ResponseEntity.ok(speedData);
}
@Operation(summary = "Get peak reading hours", description = "Returns reading activity distribution by hour of day. Can be filtered by year and/or month.")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Peak reading hours retrieved successfully"),
@ApiResponse(responseCode = "401", description = "Unauthorized")
})
@GetMapping("/peak-hours")
@PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()")
public ResponseEntity<List<PeakReadingHoursResponse>> getPeakReadingHours(
@RequestParam(required = false) Integer year,
@RequestParam(required = false) Integer month) {
List<PeakReadingHoursResponse> peakHours = readingSessionService.getPeakReadingHours(year, month);
return ResponseEntity.ok(peakHours);
}
@Operation(summary = "Get favorite reading days", description = "Returns reading activity distribution by day of week. Can be filtered by year and/or month.")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Favorite reading days retrieved successfully"),
@ApiResponse(responseCode = "401", description = "Unauthorized")
})
@GetMapping("/favorite-days")
@PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()")
public ResponseEntity<List<FavoriteReadingDaysResponse>> getFavoriteReadingDays(
@RequestParam(required = false) Integer year,
@RequestParam(required = false) Integer month) {
List<FavoriteReadingDaysResponse> favoriteDays = readingSessionService.getFavoriteReadingDays(year, month);
return ResponseEntity.ok(favoriteDays);
}
@Operation(summary = "Get genre statistics", description = "Returns reading statistics grouped by book genres/categories")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Genre statistics retrieved successfully"),
@ApiResponse(responseCode = "401", description = "Unauthorized")
})
@GetMapping("/genres")
@PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()")
public ResponseEntity<List<GenreStatisticsResponse>> getGenreStatistics() {
List<GenreStatisticsResponse> genreStats = readingSessionService.getGenreStatistics();
return ResponseEntity.ok(genreStats);
}
@Operation(summary = "Get completion timeline", description = "Returns reading completion statistics over time with status breakdown for a specific year")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Completion timeline retrieved successfully"),
@ApiResponse(responseCode = "401", description = "Unauthorized")
})
@GetMapping("/completion-timeline")
@PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()")
public ResponseEntity<List<CompletionTimelineResponse>> getCompletionTimeline(@RequestParam int year) {
List<CompletionTimelineResponse> timeline = readingSessionService.getCompletionTimeline(year);
return ResponseEntity.ok(timeline);
}
}
@@ -0,0 +1,38 @@
package com.adityachandel.booklore.crons;
import com.adityachandel.booklore.model.dto.BookloreTelemetry;
import com.adityachandel.booklore.service.TelemetryService;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClient;
import java.util.concurrent.TimeUnit;
@Service
@AllArgsConstructor
@Slf4j
public class CronService {
private final TelemetryService telemetryService;
private final RestClient restClient;
private final AppSettingService appSettingService;
@Scheduled(fixedDelay = 24, timeUnit = TimeUnit.HOURS, initialDelay = 24)
public void sendTelemetryData() {
if (appSettingService.getAppSettings().isTelemetryEnabled()) {
try {
BookloreTelemetry telemetry = telemetryService.collectTelemetry();
restClient.post()
.uri("https://telemetry.booklore.dev/api/v1/ingest")
.body(telemetry)
.retrieve()
.body(String.class);
} catch (Exception ignored) {
}
}
}
}
@@ -33,6 +33,7 @@ public enum ApiError {
SCHEDULE_REFRESH_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "Failed to schedule metadata refresh job. Error: %s"),
ANOTHER_METADATA_JOB_RUNNING(HttpStatus.CONFLICT, "A metadata refresh job is currently running. Please wait for it to complete before initiating a new one."),
METADATA_SOURCE_NOT_IMPLEMENT_OR_DOES_NOT_EXIST(HttpStatus.BAD_REQUEST, "Metadata source not implement or does not exist"),
FAILED_TO_REGENERATE_COVER(HttpStatus.BAD_REQUEST, "Failed to regenerate cover"),
FAILED_TO_DOWNLOAD_FILE(HttpStatus.INTERNAL_SERVER_ERROR, "Error while downloading file, bookId: %s"),
INVALID_REFRESH_TYPE(HttpStatus.BAD_REQUEST, "The refresh type is invalid"),
METADATA_LOCKED(HttpStatus.FORBIDDEN, "Attempt to update locked metadata"),
@@ -29,6 +29,8 @@ public class MetadataClearFlags {
private boolean goodreadsReviewCount;
private boolean hardcoverRating;
private boolean hardcoverReviewCount;
private boolean lubimyczytacId;
private boolean lubimyczytacRating;
private boolean authors;
private boolean categories;
private boolean moods;
@@ -43,7 +43,9 @@ public class BookMetadata {
private String doubanId;
private Double doubanRating;
private Integer doubanReviewCount;
private Double lubimyczytacRating;
private String googleId;
private String lubimyczytacId;
private Instant coverUpdatedOn;
private Set<String> authors;
private Set<String> categories;
@@ -80,6 +82,8 @@ public class BookMetadata {
private Boolean hardcoverReviewCountLocked;
private Boolean doubanRatingLocked;
private Boolean doubanReviewCountLocked;
private Boolean lubimyczytacIdLocked;
private Boolean lubimyczytacRatingLocked;
private Boolean coverLocked;
private Boolean authorsLocked;
private Boolean categoriesLocked;
@@ -0,0 +1,100 @@
package com.adityachandel.booklore.model.dto;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
import java.util.Map;
@Builder
@Setter
@Getter
public class BookloreTelemetry {
private int telemetryVersion = 1;
private String installationId;
private String appVersion;
private int totalLibraries;
private long totalBooks;
private long totalAdditionalBookFiles;
private long totalAuthors;
private long totalBookNotes;
private long totalBookmarks;
private int totalShelves;
private int totalMagicShelves;
private int totalCategories;
private int totalTags;
private int totalMoods;
private int totalKoreaderUsers;
private UserStatistics userStatistics;
private MetadataStatistics metadataStatistics;
private OpdsStatistics opdsStatistics;
private KoboStatistics koboStatistics;
private EmailStatistics emailStatistics;
private BookStatistics bookStatistics;
private List<LibraryStatistics> libraryStatisticsList;
@Builder
@Getter
public static class UserStatistics {
private int totalUsers;
private int totalLocalUsers;
private int totalOidcUsers;
private boolean oidcEnabled;
}
@Builder
@Getter
public static class MetadataStatistics {
private int[] enabledMetadataProviders;
private int[] enabledReviewMetadataProviders;
private boolean saveMetadataToFile;
private boolean moveFileViaPattern;
private boolean autoBookSearchEnabled;
private boolean similarBookRecommendationsEnabled;
private boolean metadataDownloadOnBookdropEnabled;
}
@Builder
@Getter
public static class OpdsStatistics {
private boolean opdsEnabled;
private int totalOpdsUsers;
}
@Builder
@Getter
public static class KoboStatistics {
private int totalKoboUsers;
private int totalHardcoverSyncEnabled;
private int totalAutoAddToShelf;
private boolean convertToKepubEnabled;
}
@Builder
@Getter
public static class EmailStatistics {
private int totalEmailProviders;
private int totalEmailRecipients;
}
@Builder
@Getter
public static class BookStatistics {
private long totalBooks;
private Map<Integer, Long> bookCountByType;
}
@Builder
@Getter
public static class LibraryStatistics {
private String libraryName;
private long bookCount;
private int totalLibraryPaths;
private boolean watchEnabled;
private int iconType;
private int scanMode;
}
}
@@ -0,0 +1,11 @@
package com.adityachandel.booklore.model.dto;
import com.adityachandel.booklore.model.enums.ReadStatus;
public interface CompletionTimelineDto {
Integer getYear();
Integer getMonth();
ReadStatus getReadStatus();
Long getBookCount();
}
@@ -0,0 +1,8 @@
package com.adityachandel.booklore.model.dto;
public interface FavoriteReadingDayDto {
Integer getDayOfWeek();
Long getSessionCount();
Long getTotalDurationSeconds();
}
@@ -0,0 +1,9 @@
package com.adityachandel.booklore.model.dto;
public interface GenreStatisticsDto {
String getGenre();
Long getBookCount();
Long getTotalSessions();
Long getTotalDurationSeconds();
}
@@ -0,0 +1,8 @@
package com.adityachandel.booklore.model.dto;
public interface PeakReadingHourDto {
Integer getHourOfDay();
Long getSessionCount();
Long getTotalDurationSeconds();
}
@@ -0,0 +1,11 @@
package com.adityachandel.booklore.model.dto;
import java.time.LocalDate;
public interface ReadingSpeedDto {
Integer getTotalSessions();
Double getAvgProgressPerMinute();
LocalDate getDate();
}
@@ -1,6 +1,16 @@
package com.adityachandel.booklore.model.dto.request;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
import java.util.List;
public record ReadStatusUpdateRequest(List<Long> ids, String status) {
@Data
public class ReadStatusUpdateRequest {
@NotEmpty(message = "Book IDs cannot be empty")
private List<Long> bookIds;
@NotNull(message = "Status cannot be null")
private String status;
}
@@ -0,0 +1,21 @@
package com.adityachandel.booklore.model.dto.response;
import com.adityachandel.booklore.model.enums.ReadStatus;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.Instant;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class BookStatusUpdateResponse {
private Long bookId;
private ReadStatus readStatus;
private Instant readStatusModifiedTime;
private Instant dateFinished;
}
@@ -0,0 +1,23 @@
package com.adityachandel.booklore.model.dto.response;
import com.adityachandel.booklore.model.enums.ReadStatus;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Map;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class CompletionTimelineResponse {
private Integer year;
private Integer month;
private Long totalBooks;
private Map<ReadStatus, Long> statusBreakdown;
private Long finishedBooks;
private Double completionRate;
}
@@ -0,0 +1,18 @@
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 FavoriteReadingDaysResponse {
private Integer dayOfWeek; // 1=Monday, 7=Sunday
private String dayName;
private Long sessionCount;
private Long totalDurationSeconds;
}
@@ -0,0 +1,19 @@
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 GenreStatisticsResponse {
private String genre;
private Long bookCount;
private Long totalSessions;
private Long totalDurationSeconds;
private Double averageSessionsPerBook;
}
@@ -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 PeakReadingHoursResponse {
private Integer hourOfDay;
private Long sessionCount;
private Long totalDurationSeconds;
}
@@ -0,0 +1,16 @@
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 PersonalRatingUpdateResponse {
private Long bookId;
private Integer personalRating;
}
@@ -0,0 +1,31 @@
package com.adityachandel.booklore.model.dto.response;
import com.adityachandel.booklore.model.enums.BookFileType;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.Instant;
import java.time.LocalDateTime;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ReadingSessionResponse {
private Long id;
private Long bookId;
private String bookTitle;
private BookFileType bookType;
private Instant startTime;
private Instant endTime;
private Integer durationSeconds;
private Float startProgress;
private Float endProgress;
private Float progressDelta;
private String startLocation;
private String endLocation;
private LocalDateTime createdAt;
}
@@ -0,0 +1,19 @@
package com.adityachandel.booklore.model.dto.response;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDate;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ReadingSpeedResponse {
private LocalDate date;
private Double avgProgressPerMinute;
private Integer totalSessions;
}
@@ -33,6 +33,7 @@ public enum AppSettingKey {
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)),
// No specific permissions required
SIDEBAR_LIBRARY_SORTING ("sidebar_library_sorting", true, false, List.of()),
@@ -25,6 +25,7 @@ public class AppSettings {
private boolean remoteAuthEnabled;
private boolean metadataDownloadOnBookdrop;
private boolean oidcEnabled;
private boolean telemetryEnabled;
private OidcProviderDetails oidcProviderDetails;
private OidcAutoProvisionDetails oidcAutoProvisionDetails;
private MetadataProviderSettings metadataProviderSettings;
@@ -1,5 +1,6 @@
package com.adityachandel.booklore.model.dto.settings;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
@Data
@@ -10,6 +11,8 @@ public class MetadataProviderSettings {
private Hardcover hardcover;
private Comicvine comicvine;
private Douban douban;
@JsonProperty("lubimyczytac")
private Lubimyczytac lubimyczytac;
@Data
public static class Amazon {
@@ -45,4 +48,9 @@ public class MetadataProviderSettings {
public static class Douban {
private boolean enabled;
}
@Data
public static class Lubimyczytac {
private boolean enabled;
}
}
@@ -106,6 +106,11 @@ public class BookMetadataEntity {
@Column(name = "comicvine_id", length = 100)
private String comicvineId;
@Column(name = "lubimyczytac_id", length = 100)
private String lubimyczytacId;
@Column(name = "lubimyczytac_rating")
private Double lubimyczytacRating;
@Column(name = "title_locked")
@Builder.Default
@@ -223,6 +228,14 @@ public class BookMetadataEntity {
@Builder.Default
private Boolean comicvineIdLocked = Boolean.FALSE;
@Column(name = "lubimyczytac_id_locked")
@Builder.Default
private Boolean lubimyczytacIdLocked = Boolean.FALSE;
@Column(name = "lubimyczytac_rating_locked")
@Builder.Default
private Boolean lubimyczytacRatingLocked = Boolean.FALSE;
@Column(name = "reviews_locked")
@Builder.Default
private Boolean reviewsLocked = Boolean.FALSE;
@@ -313,11 +326,13 @@ public class BookMetadataEntity {
this.goodreadsReviewCountLocked = lock;
this.hardcoverRatingLocked = lock;
this.hardcoverReviewCountLocked = lock;
this.lubimyczytacRatingLocked = lock;
this.comicvineIdLocked = lock;
this.goodreadsIdLocked = lock;
this.hardcoverIdLocked = lock;
this.hardcoverBookIdLocked = lock;
this.googleIdLocked = lock;
this.lubimyczytacIdLocked = lock;
this.reviewsLocked = lock;
}
@@ -346,11 +361,13 @@ public class BookMetadataEntity {
&& Boolean.TRUE.equals(this.goodreadsReviewCountLocked)
&& Boolean.TRUE.equals(this.hardcoverRatingLocked)
&& Boolean.TRUE.equals(this.hardcoverReviewCountLocked)
&& Boolean.TRUE.equals(this.lubimyczytacRatingLocked)
&& Boolean.TRUE.equals(this.goodreadsIdLocked)
&& Boolean.TRUE.equals(this.comicvineIdLocked)
&& Boolean.TRUE.equals(this.hardcoverIdLocked)
&& Boolean.TRUE.equals(this.hardcoverBookIdLocked)
&& Boolean.TRUE.equals(this.googleIdLocked)
&& Boolean.TRUE.equals(this.lubimyczytacIdLocked)
&& Boolean.TRUE.equals(this.reviewsLocked)
;
}
@@ -1,5 +1,5 @@
package com.adityachandel.booklore.model.enums;
public enum MetadataProvider {
Amazon, GoodReads, Google, Hardcover, Comicvine, Douban
Amazon, GoodReads, Google, Hardcover, Comicvine, Douban, Lubimyczytac
}
@@ -8,6 +8,7 @@ import lombok.Getter;
public enum Topic {
BOOK_ADD("/queue/book-add"),
BOOK_UPDATE("/queue/book-update"),
BOOKS_COVER_UPDATE("/queue/books-cover-update"),
BOOKS_REMOVE("/queue/books-remove"),
BOOK_METADATA_UPDATE("/queue/book-metadata-update"),
BOOK_METADATA_BATCH_UPDATE("/queue/book-metadata-batch-update"),
@@ -2,6 +2,7 @@ package com.adityachandel.booklore.repository;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
import com.adityachandel.booklore.model.enums.BookFileType;
import jakarta.transaction.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
@@ -89,22 +90,6 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpec
""")
List<BookEntity> findBooksWithMetadataAndAuthors(@Param("bookIds") List<Long> bookIds);
@Query(value = """
SELECT DISTINCT b FROM BookEntity b
LEFT JOIN b.metadata m
WHERE (b.deleted IS NULL OR b.deleted = false) AND (
m.searchText LIKE CONCAT('%', :text, '%')
)
""",
countQuery = """
SELECT COUNT(DISTINCT b.id) FROM BookEntity b
LEFT JOIN b.metadata m
WHERE (b.deleted IS NULL OR b.deleted = false) AND (
m.searchText LIKE CONCAT('%', :text, '%')
)
""")
Page<BookEntity> searchByMetadata(@Param("text") String text, Pageable pageable);
@Modifying
@Transactional
@Query("DELETE FROM BookEntity b WHERE b.deleted IS TRUE")
@@ -135,17 +120,26 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpec
@Param("libraryPath") LibraryPathEntity libraryPath);
@Query(value = """
SELECT *
FROM book
WHERE library_id = :libraryId
AND library_path_id = :libraryPathId
AND file_sub_path = :fileSubPath
AND file_name = :fileName
LIMIT 1
""", nativeQuery = true)
SELECT *
FROM book
WHERE library_id = :libraryId
AND library_path_id = :libraryPathId
AND file_sub_path = :fileSubPath
AND file_name = :fileName
LIMIT 1
""", nativeQuery = true)
Optional<BookEntity> findByLibraryIdAndLibraryPathIdAndFileSubPathAndFileName(
@Param("libraryId") Long libraryId,
@Param("libraryPathId") Long libraryPathId,
@Param("fileSubPath") String fileSubPath,
@Param("fileName") String fileName);
@Query("SELECT COUNT(b.id) FROM BookEntity b WHERE b.id IN :bookIds AND (b.deleted IS NULL OR b.deleted = false)")
long countByIdIn(@Param("bookIds") List<Long> bookIds);
@Query("SELECT COUNT(b) FROM BookEntity b WHERE b.bookType = :type AND (b.deleted IS NULL OR b.deleted = false)")
long countByBookType(@Param("type") BookFileType type);
@Query("SELECT COUNT(b) FROM BookEntity b WHERE b.library.id = :libraryId AND (b.deleted IS NULL OR b.deleted = false)")
long countByLibraryId(@Param("libraryId") Long libraryId);
}
@@ -15,4 +15,8 @@ public interface KoboUserSettingsRepository extends JpaRepository<KoboUserSettin
Optional<KoboUserSettingsEntity> findByToken(String token);
List<KoboUserSettingsEntity> findByAutoAddToShelfTrueAndSyncEnabledTrue();
long countByHardcoverSyncEnabledTrue();
long countByAutoAddToShelfTrue();
}
@@ -1,8 +1,9 @@
package com.adityachandel.booklore.repository;
import com.adityachandel.booklore.model.dto.ReadingSessionCountDto;
import com.adityachandel.booklore.model.dto.ReadingSessionTimelineDto;
import com.adityachandel.booklore.model.dto.*;
import com.adityachandel.booklore.model.entity.ReadingSessionEntity;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
@@ -36,12 +37,90 @@ public interface ReadingSessionRepository extends JpaRepository<ReadingSessionEn
JOIN rs.book b
WHERE rs.user.id = :userId
AND YEAR(rs.startTime) = :year
AND WEEK(rs.startTime) = :weekOfYear
AND MONTH(rs.startTime) = :month
AND WEEK(rs.startTime) = :week
GROUP BY b.id, b.metadata.title, rs.bookType
ORDER BY MIN(rs.startTime)
""")
List<ReadingSessionTimelineDto> findSessionTimelineByUserAndWeek(
@Param("userId") Long userId,
@Param("year") int year,
@Param("weekOfYear") int weekOfYear);
@Param("month") int month,
@Param("week") int week);
@Query("""
SELECT
CAST(rs.createdAt AS LocalDate) as date,
AVG(rs.progressDelta / (rs.durationSeconds / 60.0)) as avgProgressPerMinute,
COUNT(rs) as totalSessions
FROM ReadingSessionEntity rs
WHERE rs.user.id = :userId
AND rs.durationSeconds > 0
AND rs.progressDelta > 0
AND YEAR(rs.createdAt) = :year
GROUP BY CAST(rs.createdAt AS LocalDate)
ORDER BY date
""")
List<ReadingSpeedDto> findReadingSpeedByUserAndYear(@Param("userId") Long userId, @Param("year") int year);
@Query("""
SELECT
HOUR(rs.startTime) as hourOfDay,
COUNT(rs) as sessionCount,
SUM(rs.durationSeconds) as totalDurationSeconds
FROM ReadingSessionEntity rs
WHERE rs.user.id = :userId
AND (:year IS NULL OR YEAR(rs.startTime) = :year)
AND (:month IS NULL OR MONTH(rs.startTime) = :month)
GROUP BY HOUR(rs.startTime)
ORDER BY hourOfDay
""")
List<PeakReadingHourDto> findPeakReadingHoursByUser(
@Param("userId") Long userId,
@Param("year") Integer year,
@Param("month") Integer month);
@Query("""
SELECT
DAYOFWEEK(rs.startTime) as dayOfWeek,
COUNT(rs) as sessionCount,
SUM(rs.durationSeconds) as totalDurationSeconds
FROM ReadingSessionEntity rs
WHERE rs.user.id = :userId
AND (:year IS NULL OR YEAR(rs.startTime) = :year)
AND (:month IS NULL OR MONTH(rs.startTime) = :month)
GROUP BY DAYOFWEEK(rs.startTime)
ORDER BY dayOfWeek
""")
List<FavoriteReadingDayDto> findFavoriteReadingDaysByUser(
@Param("userId") Long userId,
@Param("year") Integer year,
@Param("month") Integer month);
@Query("""
SELECT
c.name as genre,
COUNT(DISTINCT b.id) as bookCount,
COUNT(rs) as totalSessions,
SUM(rs.durationSeconds) as totalDurationSeconds
FROM ReadingSessionEntity rs
JOIN rs.book b
JOIN b.metadata.categories c
WHERE rs.user.id = :userId
GROUP BY c.name
ORDER BY totalSessions DESC
""")
List<GenreStatisticsDto> findGenreStatisticsByUser(@Param("userId") Long userId);
@Query("""
SELECT rs
FROM ReadingSessionEntity rs
WHERE rs.user.id = :userId
AND rs.book.id = :bookId
ORDER BY rs.startTime DESC
""")
Page<ReadingSessionEntity> findByUserIdAndBookId(
@Param("userId") Long userId,
@Param("bookId") Long bookId,
Pageable pageable);
}
@@ -1,7 +1,9 @@
package com.adityachandel.booklore.repository;
import com.adityachandel.booklore.model.dto.CompletionTimelineDto;
import com.adityachandel.booklore.model.entity.UserBookProgressEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
@@ -40,4 +42,100 @@ public interface UserBookProgressRepository extends JpaRepository<UserBookProgre
@Param("userId") Long userId,
@Param("snapshotId") String snapshotId
);
@Query("""
SELECT
YEAR(COALESCE(ubp.dateFinished, ubp.readStatusModifiedTime, ubp.lastReadTime)) as year,
MONTH(COALESCE(ubp.dateFinished, ubp.readStatusModifiedTime, ubp.lastReadTime)) as month,
ubp.readStatus as readStatus,
COUNT(ubp) as bookCount
FROM UserBookProgressEntity ubp
WHERE ubp.user.id = :userId
AND ubp.readStatus IS NOT NULL
AND ubp.readStatus NOT IN (com.adityachandel.booklore.model.enums.ReadStatus.UNSET, com.adityachandel.booklore.model.enums.ReadStatus.UNREAD)
AND COALESCE(ubp.dateFinished, ubp.readStatusModifiedTime, ubp.lastReadTime) IS NOT NULL
AND YEAR(COALESCE(ubp.dateFinished, ubp.readStatusModifiedTime, ubp.lastReadTime)) = :year
GROUP BY YEAR(COALESCE(ubp.dateFinished, ubp.readStatusModifiedTime, ubp.lastReadTime)),
MONTH(COALESCE(ubp.dateFinished, ubp.readStatusModifiedTime, ubp.lastReadTime)),
ubp.readStatus
ORDER BY year DESC, month DESC
""")
List<CompletionTimelineDto> findCompletionTimelineByUser(@Param("userId") Long userId, @Param("year") int year);
@Modifying
@Query("""
UPDATE UserBookProgressEntity ubp
SET ubp.readStatus = :readStatus,
ubp.readStatusModifiedTime = :modifiedTime,
ubp.dateFinished = :dateFinished
WHERE ubp.user.id = :userId
AND ubp.book.id IN :bookIds
""")
int bulkUpdateReadStatus(
@Param("userId") Long userId,
@Param("bookIds") List<Long> bookIds,
@Param("readStatus") com.adityachandel.booklore.model.enums.ReadStatus readStatus,
@Param("modifiedTime") java.time.Instant modifiedTime,
@Param("dateFinished") java.time.Instant dateFinished
);
@Query("""
SELECT ubp.book.id FROM UserBookProgressEntity ubp
WHERE ubp.user.id = :userId
AND ubp.book.id IN :bookIds
""")
Set<Long> findExistingProgressBookIds(@Param("userId") Long userId, @Param("bookIds") Set<Long> bookIds);
@Modifying
@Query("""
UPDATE UserBookProgressEntity ubp
SET ubp.readStatus = NULL,
ubp.readStatusModifiedTime = :modifiedTime,
ubp.lastReadTime = NULL,
ubp.dateFinished = NULL,
ubp.pdfProgress = NULL,
ubp.pdfProgressPercent = NULL,
ubp.epubProgress = NULL,
ubp.epubProgressPercent = NULL,
ubp.cbxProgress = NULL,
ubp.cbxProgressPercent = NULL
WHERE ubp.user.id = :userId
AND ubp.book.id IN :bookIds
""")
int bulkResetBookloreProgress(@Param("userId") Long userId, @Param("bookIds") List<Long> bookIds, @Param("modifiedTime") java.time.Instant modifiedTime);
@Modifying
@Query("""
UPDATE UserBookProgressEntity ubp
SET ubp.koreaderProgress = NULL,
ubp.koreaderProgressPercent = NULL,
ubp.koreaderDeviceId = NULL,
ubp.koreaderDevice = NULL,
ubp.koreaderLastSyncTime = NULL
WHERE ubp.user.id = :userId
AND ubp.book.id IN :bookIds
""")
int bulkResetKoreaderProgress(@Param("userId") Long userId, @Param("bookIds") List<Long> bookIds);
@Modifying
@Query("""
UPDATE UserBookProgressEntity ubp
SET ubp.koboProgressPercent = NULL,
ubp.koboLocation = NULL,
ubp.koboLocationType = NULL,
ubp.koboLocationSource = NULL,
ubp.koboProgressReceivedTime = NULL
WHERE ubp.user.id = :userId
AND ubp.book.id IN :bookIds
""")
int bulkResetKoboProgress(@Param("userId") Long userId, @Param("bookIds") List<Long> bookIds);
@Modifying
@Query("""
UPDATE UserBookProgressEntity ubp
SET ubp.personalRating = :rating
WHERE ubp.user.id = :userId
AND ubp.book.id IN :bookIds
""")
int bulkUpdatePersonalRating(@Param("userId") Long userId, @Param("bookIds") List<Long> bookIds, @Param("rating") Integer rating);
}
@@ -1,10 +1,11 @@
package com.adityachandel.booklore.repository;
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
import com.adityachandel.booklore.model.enums.ProvisioningMethod;
import org.jspecify.annotations.NonNull;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
@Repository
@@ -14,7 +15,8 @@ public interface UserRepository extends JpaRepository<BookLoreUserEntity, Long>
Optional<BookLoreUserEntity> findByEmail(String email);
Optional<BookLoreUserEntity> findById(Long id);
Optional<BookLoreUserEntity> findById(@NonNull Long id);
List<BookLoreUserEntity> findAllByLibraries_Id(Long libraryId);
long countByProvisioningMethod(ProvisioningMethod provisioningMethod);
}
@@ -1,12 +0,0 @@
package com.adityachandel.booklore.repository;
import com.adityachandel.booklore.model.entity.UserSettingEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
import java.util.Optional;
public interface UserSettingRepository extends JpaRepository<UserSettingEntity, Long> {
Optional<UserSettingEntity> findByUserIdAndSettingKey(Long userId, String settingKey);
List<UserSettingEntity> findByUserId(Long userId);
}
@@ -19,7 +19,9 @@ import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;
import java.util.stream.Stream;
@@ -271,4 +273,35 @@ public class IconService {
ConcurrentHashMap<String, String> getSvgCache() {
return svgCache;
}
public Map<String, String> getAllIconsContent() {
Path iconsPath = getIconsSvgPath();
if (!Files.exists(iconsPath)) {
return Collections.emptyMap();
}
try (Stream<Path> paths = Files.list(iconsPath)) {
Map<String, String> iconMap = new HashMap<>();
paths.filter(Files::isRegularFile)
.filter(path -> path.toString().endsWith(SVG_EXTENSION))
.forEach(path -> {
try {
String filename = path.getFileName().toString();
String iconName = filename.replace(SVG_EXTENSION, "");
String content = svgCache.getOrDefault(filename, Files.readString(path));
iconMap.put(iconName, content);
} catch (IOException e) {
log.warn("Failed to read icon: {}", path.getFileName(), e);
}
});
log.info("Retrieved {} icons for bulk content request", iconMap.size());
return iconMap;
} catch (IOException e) {
log.error("Failed to read icons directory: {}", e.getMessage(), e);
throw ApiError.FILE_READ_ERROR.createException("Failed to read icons: " + e.getMessage());
}
}
}
@@ -4,21 +4,34 @@ import com.adityachandel.booklore.config.security.service.AuthenticationService;
import com.adityachandel.booklore.exception.ApiError;
import com.adityachandel.booklore.model.dto.BookLoreUser;
import com.adityachandel.booklore.model.dto.request.ReadingSessionRequest;
import com.adityachandel.booklore.model.dto.response.CompletionTimelineResponse;
import com.adityachandel.booklore.model.dto.response.FavoriteReadingDaysResponse;
import com.adityachandel.booklore.model.dto.response.GenreStatisticsResponse;
import com.adityachandel.booklore.model.dto.response.PeakReadingHoursResponse;
import com.adityachandel.booklore.model.dto.response.ReadingSessionHeatmapResponse;
import com.adityachandel.booklore.model.dto.response.ReadingSessionResponse;
import com.adityachandel.booklore.model.dto.response.ReadingSessionTimelineResponse;
import com.adityachandel.booklore.model.dto.response.ReadingSpeedResponse;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
import com.adityachandel.booklore.model.entity.ReadingSessionEntity;
import com.adityachandel.booklore.model.enums.ReadStatus;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.repository.ReadingSessionRepository;
import com.adityachandel.booklore.repository.UserBookProgressRepository;
import com.adityachandel.booklore.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Slf4j
@@ -30,6 +43,7 @@ public class ReadingSessionService {
private final ReadingSessionRepository readingSessionRepository;
private final BookRepository bookRepository;
private final UserRepository userRepository;
private final UserBookProgressRepository userBookProgressRepository;
@Transactional
public void recordSession(ReadingSessionRequest request) {
@@ -73,11 +87,11 @@ public class ReadingSessionService {
}
@Transactional(readOnly = true)
public List<ReadingSessionTimelineResponse> getSessionTimelineForWeek(int year, int week) {
public List<ReadingSessionTimelineResponse> getSessionTimelineForWeek(int year, int month, int week) {
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
Long userId = authenticatedUser.getId();
return readingSessionRepository.findSessionTimelineByUserAndWeek(userId, year, week)
return readingSessionRepository.findSessionTimelineByUserAndWeek(userId, year, month, week)
.stream()
.map(dto -> ReadingSessionTimelineResponse.builder()
.bookId(dto.getBookId())
@@ -90,4 +104,141 @@ public class ReadingSessionService {
.build())
.collect(Collectors.toList());
}
@Transactional(readOnly = true)
public List<ReadingSpeedResponse> getReadingSpeedForYear(int year) {
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
Long userId = authenticatedUser.getId();
return readingSessionRepository.findReadingSpeedByUserAndYear(userId, year)
.stream()
.map(dto -> ReadingSpeedResponse.builder()
.date(dto.getDate())
.avgProgressPerMinute(dto.getAvgProgressPerMinute())
.totalSessions(dto.getTotalSessions())
.build())
.collect(Collectors.toList());
}
@Transactional(readOnly = true)
public List<PeakReadingHoursResponse> getPeakReadingHours(Integer year, Integer month) {
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
Long userId = authenticatedUser.getId();
return readingSessionRepository.findPeakReadingHoursByUser(userId, year, month)
.stream()
.map(dto -> PeakReadingHoursResponse.builder()
.hourOfDay(dto.getHourOfDay())
.sessionCount(dto.getSessionCount())
.totalDurationSeconds(dto.getTotalDurationSeconds())
.build())
.collect(Collectors.toList());
}
@Transactional(readOnly = true)
public List<FavoriteReadingDaysResponse> getFavoriteReadingDays(Integer year, Integer month) {
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
Long userId = authenticatedUser.getId();
String[] dayNames = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
return readingSessionRepository.findFavoriteReadingDaysByUser(userId, year, month)
.stream()
.map(dto -> FavoriteReadingDaysResponse.builder()
.dayOfWeek(dto.getDayOfWeek())
.dayName(dayNames[dto.getDayOfWeek() - 1])
.sessionCount(dto.getSessionCount())
.totalDurationSeconds(dto.getTotalDurationSeconds())
.build())
.collect(Collectors.toList());
}
@Transactional(readOnly = true)
public List<GenreStatisticsResponse> getGenreStatistics() {
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
Long userId = authenticatedUser.getId();
return readingSessionRepository.findGenreStatisticsByUser(userId)
.stream()
.map(dto -> {
double avgSessionsPerBook = dto.getBookCount() > 0
? (double) dto.getTotalSessions() / dto.getBookCount()
: 0.0;
return GenreStatisticsResponse.builder()
.genre(dto.getGenre())
.bookCount(dto.getBookCount())
.totalSessions(dto.getTotalSessions())
.totalDurationSeconds(dto.getTotalDurationSeconds())
.averageSessionsPerBook(Math.round(avgSessionsPerBook * 100.0) / 100.0)
.build();
})
.collect(Collectors.toList());
}
@Transactional(readOnly = true)
public List<CompletionTimelineResponse> getCompletionTimeline(int year) {
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
Long userId = authenticatedUser.getId();
Map<String, Map<ReadStatus, Long>> timelineMap = new HashMap<>();
userBookProgressRepository.findCompletionTimelineByUser(userId, year).forEach(dto -> {
String key = dto.getYear() + "-" + dto.getMonth();
timelineMap.computeIfAbsent(key, k -> new HashMap<>())
.put(dto.getReadStatus(), dto.getBookCount());
});
return timelineMap.entrySet().stream()
.map(entry -> {
String[] parts = entry.getKey().split("-");
int yearPart = Integer.parseInt(parts[0]);
int month = Integer.parseInt(parts[1]);
Map<ReadStatus, Long> statusBreakdown = entry.getValue();
long totalBooks = statusBreakdown.values().stream().mapToLong(Long::longValue).sum();
long finishedBooks = statusBreakdown.getOrDefault(ReadStatus.READ, 0L);
double completionRate = totalBooks > 0 ? (finishedBooks * 100.0 / totalBooks) : 0.0;
return CompletionTimelineResponse.builder()
.year(yearPart)
.month(month)
.totalBooks(totalBooks)
.statusBreakdown(statusBreakdown)
.finishedBooks(finishedBooks)
.completionRate(Math.round(completionRate * 100.0) / 100.0)
.build();
})
.sorted((a, b) -> {
int cmp = b.getYear().compareTo(a.getYear());
return cmp != 0 ? cmp : b.getMonth().compareTo(a.getMonth());
})
.collect(Collectors.toList());
}
@Transactional(readOnly = true)
public Page<ReadingSessionResponse> getReadingSessionsForBook(Long bookId, int page) {
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
Long userId = authenticatedUser.getId();
bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
Pageable pageable = PageRequest.of(page, 5);
Page<ReadingSessionEntity> sessions = readingSessionRepository.findByUserIdAndBookId(userId, bookId, pageable);
return sessions.map(session -> ReadingSessionResponse.builder()
.id(session.getId())
.bookId(session.getBook().getId())
.bookTitle(session.getBook().getMetadata().getTitle())
.bookType(session.getBookType())
.startTime(session.getStartTime())
.endTime(session.getEndTime())
.durationSeconds(session.getDurationSeconds())
.startProgress(session.getStartProgress())
.endProgress(session.getEndProgress())
.progressDelta(session.getProgressDelta())
.startLocation(session.getStartLocation())
.endLocation(session.getEndLocation())
.createdAt(session.getCreatedAt())
.build());
}
}
@@ -0,0 +1,209 @@
package com.adityachandel.booklore.service;
import com.adityachandel.booklore.model.dto.BookloreTelemetry;
import com.adityachandel.booklore.model.dto.settings.AppSettings;
import com.adityachandel.booklore.model.dto.settings.MetadataProviderSettings;
import com.adityachandel.booklore.model.dto.settings.MetadataPublicReviewsSettings;
import com.adityachandel.booklore.model.entity.AppSettingEntity;
import com.adityachandel.booklore.model.entity.LibraryEntity;
import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.model.enums.ProvisioningMethod;
import com.adityachandel.booklore.model.enums.IconType;
import com.adityachandel.booklore.model.enums.LibraryScanMode;
import com.adityachandel.booklore.model.enums.MetadataProvider;
import com.adityachandel.booklore.repository.*;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.stream.Collectors;
@Service
@AllArgsConstructor
public class TelemetryService {
private static class EnumMappings {
static final Map<BookFileType, Integer> BOOK_FILE_TYPE = Map.of(
BookFileType.PDF, 1,
BookFileType.EPUB, 2,
BookFileType.CBX, 3,
BookFileType.FB2, 4
);
static final Map<IconType, Integer> ICON_TYPE = Map.of(
IconType.PRIME_NG, 1,
IconType.CUSTOM_SVG, 2
);
static final Map<LibraryScanMode, Integer> LIBRARY_SCAN_MODE = Map.of(
LibraryScanMode.FILE_AS_BOOK, 1,
LibraryScanMode.FOLDER_AS_BOOK, 2
);
static final Map<MetadataProvider, Integer> METADATA_PROVIDER = Map.of(
MetadataProvider.Amazon, 1,
MetadataProvider.Google, 2,
MetadataProvider.GoodReads, 3,
MetadataProvider.Hardcover, 4,
MetadataProvider.Comicvine, 5,
MetadataProvider.Douban, 6
);
static final Map<MetadataProvider, Integer> REVIEW_PROVIDER = Map.of(
MetadataProvider.Amazon, 1,
MetadataProvider.Google, 2,
MetadataProvider.GoodReads, 3,
MetadataProvider.Hardcover, 4,
MetadataProvider.Comicvine, 5,
MetadataProvider.Douban, 6
);
}
private static final String INSTALLATION_ID_KEY = "installation_id";
private final AppSettingsRepository appSettingsRepository;
private final VersionService versionService;
private final LibraryRepository libraryRepository;
private final BookRepository bookRepository;
private final BookMarkRepository bookMarkRepository;
private final BookNoteRepository bookNoteRepository;
private final BookAdditionalFileRepository bookAdditionalFileRepository;
private final AuthorRepository authorRepository;
private final ShelfRepository shelfRepository;
private final MagicShelfRepository magicShelfRepository;
private final CategoryRepository categoryRepository;
private final TagRepository tagRepository;
private final MoodRepository moodRepository;
private final UserRepository userRepository;
private final EmailProviderV2Repository emailProviderV2Repository;
private final EmailRecipientV2Repository emailRecipientV2Repository;
private final AppSettingService appSettingService;
private final KoboUserSettingsRepository koboUserSettingsRepository;
private final KoreaderUserRepository koreaderUserRepository;
private final OpdsUserV2Repository opdsUserV2Repository;
public BookloreTelemetry collectTelemetry() {
long totalUsers = userRepository.count();
long localUsers = userRepository.countByProvisioningMethod(ProvisioningMethod.LOCAL);
long oidcUsers = userRepository.countByProvisioningMethod(ProvisioningMethod.OIDC);
AppSettings settings = appSettingService.getAppSettings();
BookloreTelemetry.BookStatistics bookStatistics = BookloreTelemetry.BookStatistics.builder()
.totalBooks(bookRepository.count())
.bookCountByType(getBookFileTypeCounts())
.build();
List<BookloreTelemetry.LibraryStatistics> libraryStatisticsList = libraryRepository.findAll().stream()
.map(this::mapLibraryStatistics)
.collect(Collectors.toList());
int[] enabledMetadataProviders = getEnabledMetadataProvidersAsInt(settings.getMetadataProviderSettings());
int[] enabledReviewMetadataProviders = getEnabledReviewMetadataProvidersAsInt(settings.getMetadataPublicReviewsSettings());
return BookloreTelemetry.builder()
.installationId(getInstallationId())
.appVersion(versionService.appVersion)
.totalLibraries((int) libraryRepository.count())
.totalBooks(bookRepository.count())
.totalAdditionalBookFiles(bookAdditionalFileRepository.count())
.totalAuthors(authorRepository.count())
.totalBookmarks(bookMarkRepository.count())
.totalBookNotes(bookNoteRepository.count())
.totalShelves((int) shelfRepository.count())
.totalMagicShelves((int) magicShelfRepository.count())
.totalCategories((int) categoryRepository.count())
.totalTags((int) tagRepository.count())
.totalMoods((int) moodRepository.count())
.totalKoreaderUsers((int) koreaderUserRepository.count())
.userStatistics(BookloreTelemetry.UserStatistics.builder()
.totalUsers((int) totalUsers)
.totalLocalUsers((int) localUsers)
.totalOidcUsers((int) oidcUsers)
.oidcEnabled(oidcUsers > 0)
.build())
.metadataStatistics(BookloreTelemetry.MetadataStatistics.builder()
.enabledMetadataProviders(enabledMetadataProviders)
.enabledReviewMetadataProviders(enabledReviewMetadataProviders)
.saveMetadataToFile(settings.getMetadataPersistenceSettings().isSaveToOriginalFile())
.moveFileViaPattern(settings.getMetadataPersistenceSettings().isMoveFilesToLibraryPattern())
.autoBookSearchEnabled(settings.isAutoBookSearch())
.similarBookRecommendationsEnabled(settings.isSimilarBookRecommendation())
.metadataDownloadOnBookdropEnabled(settings.isMetadataDownloadOnBookdrop())
.build())
.opdsStatistics(BookloreTelemetry.OpdsStatistics.builder()
.opdsEnabled(settings.isOpdsServerEnabled())
.totalOpdsUsers((int) opdsUserV2Repository.count())
.build())
.emailStatistics(BookloreTelemetry.EmailStatistics.builder()
.totalEmailProviders((int) emailProviderV2Repository.count())
.totalEmailRecipients((int) emailRecipientV2Repository.count())
.build())
.koboStatistics(BookloreTelemetry.KoboStatistics.builder()
.convertToKepubEnabled(settings.getKoboSettings().isConvertToKepub())
.totalKoboUsers((int) koboUserSettingsRepository.count())
.totalHardcoverSyncEnabled((int) koboUserSettingsRepository.countByHardcoverSyncEnabledTrue())
.totalAutoAddToShelf((int) koboUserSettingsRepository.countByAutoAddToShelfTrue())
.build())
.bookStatistics(bookStatistics)
.libraryStatisticsList(libraryStatisticsList)
.build();
}
private Map<Integer, Long> getBookFileTypeCounts() {
Map<Integer, Long> countByType = new HashMap<>();
for (BookFileType type : BookFileType.values()) {
Integer mapped = EnumMappings.BOOK_FILE_TYPE.get(type);
if (mapped != null) {
countByType.put(mapped, bookRepository.countByBookType(type));
}
}
return countByType;
}
private BookloreTelemetry.LibraryStatistics mapLibraryStatistics(LibraryEntity lib) {
return BookloreTelemetry.LibraryStatistics.builder()
.libraryName(lib.getName())
.totalLibraryPaths(lib.getLibraryPaths() != null ? lib.getLibraryPaths().size() : 0)
.bookCount(bookRepository.countByLibraryId(lib.getId()))
.watchEnabled(lib.isWatch())
.iconType(lib.getIconType() != null ? EnumMappings.ICON_TYPE.getOrDefault(lib.getIconType(), -1) : -1)
.scanMode(lib.getScanMode() != null ? EnumMappings.LIBRARY_SCAN_MODE.getOrDefault(lib.getScanMode(), -1) : -1)
.build();
}
private int[] getEnabledMetadataProvidersAsInt(MetadataProviderSettings providers) {
List<Integer> enabled = new ArrayList<>();
if (providers.getAmazon() != null && providers.getAmazon().isEnabled())
enabled.add(EnumMappings.METADATA_PROVIDER.get(MetadataProvider.Amazon));
if (providers.getGoogle() != null && providers.getGoogle().isEnabled())
enabled.add(EnumMappings.METADATA_PROVIDER.get(MetadataProvider.Google));
if (providers.getGoodReads() != null && providers.getGoodReads().isEnabled())
enabled.add(EnumMappings.METADATA_PROVIDER.get(MetadataProvider.GoodReads));
if (providers.getHardcover() != null && providers.getHardcover().isEnabled())
enabled.add(EnumMappings.METADATA_PROVIDER.get(MetadataProvider.Hardcover));
if (providers.getComicvine() != null && providers.getComicvine().isEnabled())
enabled.add(EnumMappings.METADATA_PROVIDER.get(MetadataProvider.Comicvine));
if (providers.getDouban() != null && providers.getDouban().isEnabled())
enabled.add(EnumMappings.METADATA_PROVIDER.get(MetadataProvider.Douban));
return enabled.stream().mapToInt(i -> i).toArray();
}
private int[] getEnabledReviewMetadataProvidersAsInt(MetadataPublicReviewsSettings reviewSettings) {
List<Integer> enabled = new ArrayList<>();
if (reviewSettings.getProviders() != null) {
reviewSettings.getProviders().stream()
.filter(MetadataPublicReviewsSettings.ReviewProviderConfig::isEnabled)
.forEach(cfg -> {
try {
MetadataProvider provider = MetadataProvider.valueOf(cfg.getProvider().name());
Integer mapped = EnumMappings.REVIEW_PROVIDER.get(provider);
if (mapped != null) enabled.add(mapped);
} catch (IllegalArgumentException ignored) {
}
});
}
return enabled.stream().mapToInt(i -> i).toArray();
}
private String getInstallationId() {
AppSettingEntity setting = appSettingsRepository.findByName(INSTALLATION_ID_KEY);
return setting != null ? setting.getVal() : "unknown";
}
}
@@ -73,7 +73,7 @@ public class AppSettingService {
}
boolean hasPermission = requiredPermissions.stream().anyMatch(permission ->
UserPermissionUtils.hasPermission(user.getPermissions(), permission)
UserPermissionUtils.hasPermission(user.getPermissions(), permission)
);
if (!hasPermission) {
@@ -131,6 +131,7 @@ public class AppSettingService {
builder.uploadPattern(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.UPLOAD_FILE_PATTERN, "{authors}/<{series}/><{seriesIndex}. >{title}< - {authors}>< ({year})>"));
builder.similarBookRecommendation(Boolean.parseBoolean(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.SIMILAR_BOOK_RECOMMENDATION, "true")));
builder.opdsServerEnabled(Boolean.parseBoolean(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.OPDS_SERVER_ENABLED, "false")));
builder.telemetryEnabled(Boolean.parseBoolean(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.TELEMETRY_ENABLED, "true")));
builder.cbxCacheSizeInMb(Integer.parseInt(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.CBX_CACHE_SIZE_IN_MB, "5120")));
builder.pdfCacheSizeInMb(Integer.parseInt(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.PDF_CACHE_SIZE_IN_MB, "5120")));
builder.maxFileUploadSizeInMb(Integer.parseInt(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.MAX_FILE_UPLOAD_SIZE_IN_MB, "100")));
@@ -12,7 +12,7 @@ import com.adityachandel.booklore.util.FileUtils;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
@@ -56,8 +56,8 @@ public class BookDownloadService {
throw ApiError.FAILED_TO_DOWNLOAD_FILE.createException(bookId);
}
InputStream inputStream = new FileInputStream(bookFile);
InputStreamResource resource = new InputStreamResource(inputStream);
// Use FileSystemResource which properly handles file resources and closing
Resource resource = new FileSystemResource(bookFile);
String encodedFilename = URLEncoder.encode(file.getFileName().toString(), StandardCharsets.UTF_8)
.replace("+", "%20");
@@ -4,31 +4,29 @@ import com.adityachandel.booklore.config.security.service.AuthenticationService;
import com.adityachandel.booklore.exception.ApiError;
import com.adityachandel.booklore.mapper.BookMapper;
import com.adityachandel.booklore.model.dto.*;
import com.adityachandel.booklore.model.dto.progress.CbxProgress;
import com.adityachandel.booklore.model.dto.progress.EpubProgress;
import com.adityachandel.booklore.model.dto.progress.KoProgress;
import com.adityachandel.booklore.model.dto.progress.KoboProgress;
import com.adityachandel.booklore.model.dto.progress.PdfProgress;
import com.adityachandel.booklore.model.dto.progress.*;
import com.adityachandel.booklore.model.dto.request.ReadProgressRequest;
import com.adityachandel.booklore.model.dto.response.BookDeletionResponse;
import com.adityachandel.booklore.model.entity.*;
import com.adityachandel.booklore.model.dto.response.BookStatusUpdateResponse;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
import com.adityachandel.booklore.model.entity.UserBookProgressEntity;
import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.model.enums.ReadStatus;
import com.adityachandel.booklore.model.enums.ResetProgressType;
import com.adityachandel.booklore.repository.*;
import com.adityachandel.booklore.service.kobo.KoboReadingStateService;
import com.adityachandel.booklore.service.user.UserProgressService;
import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService;
import com.adityachandel.booklore.service.user.UserProgressService;
import com.adityachandel.booklore.util.FileService;
import com.adityachandel.booklore.util.FileUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.EnumUtils;
import org.springframework.core.io.*;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@@ -39,7 +37,6 @@ import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.util.*;
import java.util.stream.Collectors;
@@ -53,17 +50,15 @@ public class BookService {
private final EpubViewerPreferencesRepository epubViewerPreferencesRepository;
private final CbxViewerPreferencesRepository cbxViewerPreferencesRepository;
private final NewPdfViewerPreferencesRepository newPdfViewerPreferencesRepository;
private final ShelfRepository shelfRepository;
private final FileService fileService;
private final BookMapper bookMapper;
private final UserRepository userRepository;
private final UserBookProgressRepository userBookProgressRepository;
private final AuthenticationService authenticationService;
private final BookQueryService bookQueryService;
private final UserProgressService userProgressService;
private final BookDownloadService bookDownloadService;
private final MonitoringRegistrationService monitoringRegistrationService;
private final KoboReadingStateService koboReadingStateService;
private final BookUpdateService bookUpdateService;
private void setBookProgress(Book book, UserBookProgressEntity progress) {
@@ -248,336 +243,22 @@ public class BookService {
}
public void updateBookViewerSetting(long bookId, BookViewerSettings bookViewerSettings) {
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
BookLoreUser user = authenticationService.getAuthenticatedUser();
if (bookEntity.getBookType() == BookFileType.PDF) {
if (bookViewerSettings.getPdfSettings() != null) {
PdfViewerPreferencesEntity pdfPrefs = pdfViewerPreferencesRepository
.findByBookIdAndUserId(bookId, user.getId())
.orElseGet(() -> {
PdfViewerPreferencesEntity newPrefs = PdfViewerPreferencesEntity.builder()
.bookId(bookId)
.userId(user.getId())
.build();
return pdfViewerPreferencesRepository.save(newPrefs);
});
PdfViewerPreferences pdfSettings = bookViewerSettings.getPdfSettings();
pdfPrefs.setZoom(pdfSettings.getZoom());
pdfPrefs.setSpread(pdfSettings.getSpread());
pdfViewerPreferencesRepository.save(pdfPrefs);
}
if (bookViewerSettings.getNewPdfSettings() != null) {
NewPdfViewerPreferencesEntity pdfPrefs = newPdfViewerPreferencesRepository.findByBookIdAndUserId(bookId, user.getId())
.orElseGet(() -> {
NewPdfViewerPreferencesEntity entity = NewPdfViewerPreferencesEntity.builder()
.bookId(bookId)
.userId(user.getId())
.build();
return newPdfViewerPreferencesRepository.save(entity);
});
NewPdfViewerPreferences pdfSettings = bookViewerSettings.getNewPdfSettings();
pdfPrefs.setPageSpread(pdfSettings.getPageSpread());
pdfPrefs.setPageViewMode(pdfSettings.getPageViewMode());
newPdfViewerPreferencesRepository.save(pdfPrefs);
}
} else if (bookEntity.getBookType() == BookFileType.EPUB) {
EpubViewerPreferencesEntity epubPrefs = epubViewerPreferencesRepository
.findByBookIdAndUserId(bookId, user.getId())
.orElseGet(() -> {
EpubViewerPreferencesEntity newPrefs = EpubViewerPreferencesEntity.builder()
.bookId(bookId)
.userId(user.getId())
.build();
return epubViewerPreferencesRepository.save(newPrefs);
});
EpubViewerPreferences epubSettings = bookViewerSettings.getEpubSettings();
epubPrefs.setFont(epubSettings.getFont());
epubPrefs.setFontSize(epubSettings.getFontSize());
epubPrefs.setTheme(epubSettings.getTheme());
epubPrefs.setFlow(epubSettings.getFlow());
epubPrefs.setSpread(epubSettings.getSpread());
epubPrefs.setLetterSpacing(epubSettings.getLetterSpacing());
epubPrefs.setLineHeight(epubSettings.getLineHeight());
epubViewerPreferencesRepository.save(epubPrefs);
} else if (bookEntity.getBookType() == BookFileType.CBX) {
CbxViewerPreferencesEntity cbxPrefs = cbxViewerPreferencesRepository
.findByBookIdAndUserId(bookId, user.getId())
.orElseGet(() -> {
CbxViewerPreferencesEntity newPrefs = CbxViewerPreferencesEntity.builder()
.bookId(bookId)
.userId(user.getId())
.build();
return cbxViewerPreferencesRepository.save(newPrefs);
});
CbxViewerPreferences cbxSettings = bookViewerSettings.getCbxSettings();
cbxPrefs.setPageSpread(cbxSettings.getPageSpread());
cbxPrefs.setPageViewMode(cbxSettings.getPageViewMode());
cbxPrefs.setFitMode(cbxSettings.getFitMode());
cbxPrefs.setScrollMode(cbxSettings.getScrollMode());
cbxPrefs.setBackgroundColor(cbxSettings.getBackgroundColor());
cbxViewerPreferencesRepository.save(cbxPrefs);
} else {
throw ApiError.UNSUPPORTED_BOOK_TYPE.createException();
}
bookUpdateService.updateBookViewerSetting(bookId, bookViewerSettings);
}
@Transactional
public void updateReadProgress(ReadProgressRequest request) {
BookEntity book = bookRepository.findById(request.getBookId())
.orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(request.getBookId()));
BookLoreUser user = authenticationService.getAuthenticatedUser();
UserBookProgressEntity progress = userBookProgressRepository
.findByUserIdAndBookId(user.getId(), book.getId())
.orElseGet(UserBookProgressEntity::new);
BookLoreUserEntity userEntity = userRepository.findById(user.getId())
.orElseThrow(() -> new UsernameNotFoundException("User not found"));
progress.setUser(userEntity);
progress.setBook(book);
progress.setLastReadTime(Instant.now());
Float percentage = null;
switch (book.getBookType()) {
case EPUB -> {
if (request.getEpubProgress() != null) {
progress.setEpubProgress(request.getEpubProgress().getCfi());
percentage = request.getEpubProgress().getPercentage();
}
}
case PDF -> {
if (request.getPdfProgress() != null) {
progress.setPdfProgress(request.getPdfProgress().getPage());
percentage = request.getPdfProgress().getPercentage();
}
}
case CBX -> {
if (request.getCbxProgress() != null) {
progress.setCbxProgress(request.getCbxProgress().getPage());
percentage = request.getCbxProgress().getPercentage();
}
}
}
if (percentage != null) {
progress.setReadStatus(getStatus(percentage));
setProgressPercent(progress, book.getBookType(), percentage);
}
if (request.getDateFinished() != null) {
progress.setDateFinished(request.getDateFinished());
}
userBookProgressRepository.save(progress);
}
private void setProgressPercent(UserBookProgressEntity progress, BookFileType type, Float percentage) {
switch (type) {
case EPUB -> progress.setEpubProgressPercent(percentage);
case PDF -> progress.setPdfProgressPercent(percentage);
case CBX -> progress.setCbxProgressPercent(percentage);
}
}
private ReadStatus getStatus(Float percentage) {
if (percentage >= 99.5f) return ReadStatus.READ;
if (percentage > 0.5f) return ReadStatus.READING;
return ReadStatus.UNREAD;
bookUpdateService.updateReadProgress(request);
}
@Transactional
public List<Book> updateReadStatus(List<Long> bookIds, String status) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
ReadStatus readStatus = EnumUtils.getEnumIgnoreCase(ReadStatus.class, status);
List<BookEntity> books = bookRepository.findAllById(bookIds);
if (books.size() != bookIds.size()) {
throw ApiError.BOOK_NOT_FOUND.createException("One or more books not found");
}
BookLoreUserEntity userEntity = userRepository.findById(user.getId()).orElseThrow(() -> new UsernameNotFoundException("User not found"));
for (BookEntity book : books) {
UserBookProgressEntity progress = userBookProgressRepository
.findByUserIdAndBookId(user.getId(), book.getId())
.orElse(new UserBookProgressEntity());
progress.setUser(userEntity);
progress.setBook(book);
progress.setReadStatus(readStatus);
progress.setReadStatusModifiedTime(Instant.now());
if (readStatus == ReadStatus.READ) {
progress.setDateFinished(Instant.now());
} else {
progress.setDateFinished(null);
}
userBookProgressRepository.save(progress);
}
return books.stream()
.map(bookEntity -> {
Book book = bookMapper.toBook(bookEntity);
book.setFilePath(FileUtils.getBookFullPath(bookEntity));
UserBookProgressEntity progress = userBookProgressRepository
.findByUserIdAndBookId(user.getId(), bookEntity.getId())
.orElse(null);
this.enrichBookWithProgress(book, progress);
return book;
})
.collect(Collectors.toList());
}
public List<Book> resetProgress(List<Long> bookIds, ResetProgressType type) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
List<Book> updatedBooks = new ArrayList<>();
Optional<BookLoreUserEntity> userEntity = userRepository.findById(user.getId());
for (Long bookId : bookIds) {
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
UserBookProgressEntity progress = userBookProgressRepository
.findByUserIdAndBookId(user.getId(), bookId)
.orElse(new UserBookProgressEntity());
progress.setBook(bookEntity);
progress.setUser(userEntity.orElseThrow());
if (progress.getReadStatus() != null) {
progress.setReadStatusModifiedTime(Instant.now());
}
progress.setReadStatus(null);
progress.setLastReadTime(null);
progress.setDateFinished(null);
if (type == ResetProgressType.BOOKLORE) {
progress.setPdfProgress(null);
progress.setPdfProgressPercent(null);
progress.setEpubProgress(null);
progress.setEpubProgressPercent(null);
progress.setCbxProgress(null);
progress.setCbxProgressPercent(null);
} else if (type == ResetProgressType.KOREADER) {
progress.setKoreaderProgress(null);
progress.setKoreaderProgressPercent(null);
progress.setKoreaderDeviceId(null);
progress.setKoreaderDevice(null);
progress.setKoreaderLastSyncTime(null);
} else if (type == ResetProgressType.KOBO) {
progress.setKoboProgressPercent(null);
progress.setKoboLocation(null);
progress.setKoboLocationType(null);
progress.setKoboLocationSource(null);
progress.setKoboProgressReceivedTime(null);
koboReadingStateService.deleteReadingState(bookId);
}
userBookProgressRepository.save(progress);
updatedBooks.add(bookMapper.toBook(bookEntity));
}
return updatedBooks;
}
@Transactional
public List<Book> updatePersonalRating(List<Long> bookIds, Integer rating) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
List<BookEntity> books = bookRepository.findAllById(bookIds);
if (books.size() != bookIds.size()) {
throw ApiError.BOOK_NOT_FOUND.createException("One or more books not found");
}
BookLoreUserEntity userEntity = userRepository.findById(user.getId()).orElseThrow(() -> new UsernameNotFoundException("User not found"));
for (BookEntity book : books) {
UserBookProgressEntity progress = userBookProgressRepository
.findByUserIdAndBookId(user.getId(), book.getId())
.orElse(new UserBookProgressEntity());
progress.setUser(userEntity);
progress.setBook(book);
progress.setPersonalRating(rating);
userBookProgressRepository.save(progress);
}
return books.stream()
.map(bookEntity -> {
Book book = bookMapper.toBook(bookEntity);
book.setFilePath(FileUtils.getBookFullPath(bookEntity));
UserBookProgressEntity progress = userBookProgressRepository
.findByUserIdAndBookId(user.getId(), bookEntity.getId())
.orElse(null);
this.enrichBookWithProgress(book, progress);
return book;
})
.collect(Collectors.toList());
}
public List<Book> resetPersonalRating(List<Long> bookIds) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
List<Book> updatedBooks = new ArrayList<>();
Optional<BookLoreUserEntity> userEntity = userRepository.findById(user.getId());
for (Long bookId : bookIds) {
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
UserBookProgressEntity progress = userBookProgressRepository
.findByUserIdAndBookId(user.getId(), bookId)
.orElse(new UserBookProgressEntity());
progress.setBook(bookEntity);
progress.setUser(userEntity.orElseThrow());
progress.setPersonalRating(null);
userBookProgressRepository.save(progress);
updatedBooks.add(bookMapper.toBook(bookEntity));
}
return updatedBooks;
public List<BookStatusUpdateResponse> updateReadStatus(List<Long> bookIds, String status) {
return bookUpdateService.updateReadStatus(bookIds, status);
}
@Transactional
public List<Book> assignShelvesToBooks(Set<Long> bookIds, Set<Long> shelfIdsToAssign, Set<Long> shelfIdsToUnassign) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
BookLoreUserEntity userEntity = userRepository.findById(user.getId()).orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(user.getId()));
Set<Long> userShelfIds = userEntity.getShelves().stream().map(ShelfEntity::getId).collect(Collectors.toSet());
if (!userShelfIds.containsAll(shelfIdsToAssign)) {
throw ApiError.GENERIC_UNAUTHORIZED.createException("Cannot assign shelves that do not belong to the user.");
}
if (!userShelfIds.containsAll(shelfIdsToUnassign)) {
throw ApiError.GENERIC_UNAUTHORIZED.createException("Cannot unassign shelves that do not belong to the user.");
}
List<BookEntity> bookEntities = bookQueryService.findAllWithMetadataByIds(bookIds);
List<ShelfEntity> shelvesToAssign = shelfRepository.findAllById(shelfIdsToAssign);
for (BookEntity bookEntity : bookEntities) {
bookEntity.getShelves().removeIf(shelf -> shelfIdsToUnassign.contains(shelf.getId()));
bookEntity.getShelves().addAll(shelvesToAssign);
}
bookRepository.saveAll(bookEntities);
Map<Long, UserBookProgressEntity> progressMap = userProgressService.fetchUserProgress(
user.getId(), bookEntities.stream().map(BookEntity::getId).collect(Collectors.toSet()));
return bookEntities.stream().map(bookEntity -> {
Book book = bookMapper.toBook(bookEntity);
book.setShelves(filterShelvesByUserId(book.getShelves(), user.getId()));
book.setFilePath(FileUtils.getBookFullPath(bookEntity));
enrichBookWithProgress(book, progressMap.get(bookEntity.getId()));
return book;
}).collect(Collectors.toList());
return bookUpdateService.assignShelvesToBooks(bookIds, shelfIdsToAssign, shelfIdsToUnassign);
}
public Resource getBookThumbnail(long bookId) {
@@ -639,7 +320,11 @@ public class BookService {
Path fullFilePath = book.getFullFilePath();
try {
if (Files.exists(fullFilePath)) {
monitoringRegistrationService.unregisterSpecificPath(fullFilePath.getParent());
try {
monitoringRegistrationService.unregisterSpecificPath(fullFilePath.getParent());
} catch (Exception ex) {
log.warn("Failed to unregister monitoring for path: {}", fullFilePath.getParent(), ex);
}
Files.delete(fullFilePath);
log.info("Deleted book file: {}", fullFilePath);
@@ -736,4 +421,5 @@ public class BookService {
.filter(shelf -> userId.equals(shelf.getUserId()))
.collect(Collectors.toSet());
}
}
}
@@ -0,0 +1,419 @@
package com.adityachandel.booklore.service.book;
import com.adityachandel.booklore.config.security.service.AuthenticationService;
import com.adityachandel.booklore.exception.ApiError;
import com.adityachandel.booklore.mapper.BookMapper;
import com.adityachandel.booklore.model.dto.*;
import com.adityachandel.booklore.model.dto.request.ReadProgressRequest;
import com.adityachandel.booklore.model.dto.response.BookStatusUpdateResponse;
import com.adityachandel.booklore.model.dto.response.PersonalRatingUpdateResponse;
import com.adityachandel.booklore.model.entity.*;
import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.model.enums.ReadStatus;
import com.adityachandel.booklore.model.enums.ResetProgressType;
import com.adityachandel.booklore.repository.*;
import com.adityachandel.booklore.service.kobo.KoboReadingStateService;
import com.adityachandel.booklore.service.user.UserProgressService;
import com.adityachandel.booklore.util.FileUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.EnumUtils;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.Instant;
import java.util.*;
import java.util.stream.Collectors;
@Slf4j
@AllArgsConstructor
@Service
public class BookUpdateService {
private final BookRepository bookRepository;
private final PdfViewerPreferencesRepository pdfViewerPreferencesRepository;
private final EpubViewerPreferencesRepository epubViewerPreferencesRepository;
private final CbxViewerPreferencesRepository cbxViewerPreferencesRepository;
private final NewPdfViewerPreferencesRepository newPdfViewerPreferencesRepository;
private final ShelfRepository shelfRepository;
private final BookMapper bookMapper;
private final UserRepository userRepository;
private final UserBookProgressRepository userBookProgressRepository;
private final AuthenticationService authenticationService;
private final BookQueryService bookQueryService;
private final UserProgressService userProgressService;
private final KoboReadingStateService koboReadingStateService;
public void updateBookViewerSetting(long bookId, BookViewerSettings bookViewerSettings) {
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
BookLoreUser user = authenticationService.getAuthenticatedUser();
if (bookEntity.getBookType() == BookFileType.PDF) {
if (bookViewerSettings.getPdfSettings() != null) {
PdfViewerPreferencesEntity pdfPrefs = pdfViewerPreferencesRepository
.findByBookIdAndUserId(bookId, user.getId())
.orElseGet(() -> {
PdfViewerPreferencesEntity newPrefs = PdfViewerPreferencesEntity.builder()
.bookId(bookId)
.userId(user.getId())
.build();
return pdfViewerPreferencesRepository.save(newPrefs);
});
PdfViewerPreferences pdfSettings = bookViewerSettings.getPdfSettings();
pdfPrefs.setZoom(pdfSettings.getZoom());
pdfPrefs.setSpread(pdfSettings.getSpread());
pdfViewerPreferencesRepository.save(pdfPrefs);
}
if (bookViewerSettings.getNewPdfSettings() != null) {
NewPdfViewerPreferencesEntity pdfPrefs = newPdfViewerPreferencesRepository.findByBookIdAndUserId(bookId, user.getId())
.orElseGet(() -> {
NewPdfViewerPreferencesEntity entity = NewPdfViewerPreferencesEntity.builder()
.bookId(bookId)
.userId(user.getId())
.build();
return newPdfViewerPreferencesRepository.save(entity);
});
NewPdfViewerPreferences pdfSettings = bookViewerSettings.getNewPdfSettings();
pdfPrefs.setPageSpread(pdfSettings.getPageSpread());
pdfPrefs.setPageViewMode(pdfSettings.getPageViewMode());
newPdfViewerPreferencesRepository.save(pdfPrefs);
}
} else if (bookEntity.getBookType() == BookFileType.EPUB) {
EpubViewerPreferencesEntity epubPrefs = epubViewerPreferencesRepository
.findByBookIdAndUserId(bookId, user.getId())
.orElseGet(() -> {
EpubViewerPreferencesEntity newPrefs = EpubViewerPreferencesEntity.builder()
.bookId(bookId)
.userId(user.getId())
.build();
return epubViewerPreferencesRepository.save(newPrefs);
});
EpubViewerPreferences epubSettings = bookViewerSettings.getEpubSettings();
epubPrefs.setFont(epubSettings.getFont());
epubPrefs.setFontSize(epubSettings.getFontSize());
epubPrefs.setTheme(epubSettings.getTheme());
epubPrefs.setFlow(epubSettings.getFlow());
epubPrefs.setSpread(epubSettings.getSpread());
epubPrefs.setLetterSpacing(epubSettings.getLetterSpacing());
epubPrefs.setLineHeight(epubSettings.getLineHeight());
epubViewerPreferencesRepository.save(epubPrefs);
} else if (bookEntity.getBookType() == BookFileType.CBX) {
CbxViewerPreferencesEntity cbxPrefs = cbxViewerPreferencesRepository
.findByBookIdAndUserId(bookId, user.getId())
.orElseGet(() -> {
CbxViewerPreferencesEntity newPrefs = CbxViewerPreferencesEntity.builder()
.bookId(bookId)
.userId(user.getId())
.build();
return cbxViewerPreferencesRepository.save(newPrefs);
});
CbxViewerPreferences cbxSettings = bookViewerSettings.getCbxSettings();
cbxPrefs.setPageSpread(cbxSettings.getPageSpread());
cbxPrefs.setPageViewMode(cbxSettings.getPageViewMode());
cbxPrefs.setFitMode(cbxSettings.getFitMode());
cbxPrefs.setScrollMode(cbxSettings.getScrollMode());
cbxPrefs.setBackgroundColor(cbxSettings.getBackgroundColor());
cbxViewerPreferencesRepository.save(cbxPrefs);
} else {
throw ApiError.UNSUPPORTED_BOOK_TYPE.createException();
}
}
@Transactional
public void updateReadProgress(ReadProgressRequest request) {
BookEntity book = bookRepository.findById(request.getBookId()).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(request.getBookId()));
BookLoreUser user = authenticationService.getAuthenticatedUser();
UserBookProgressEntity progress = userBookProgressRepository
.findByUserIdAndBookId(user.getId(), book.getId())
.orElseGet(UserBookProgressEntity::new);
BookLoreUserEntity userEntity = userRepository.findById(user.getId())
.orElseThrow(() -> new UsernameNotFoundException("User not found"));
progress.setUser(userEntity);
progress.setBook(book);
progress.setLastReadTime(Instant.now());
Float percentage = null;
switch (book.getBookType()) {
case EPUB -> {
if (request.getEpubProgress() != null) {
progress.setEpubProgress(request.getEpubProgress().getCfi());
percentage = request.getEpubProgress().getPercentage();
}
}
case PDF -> {
if (request.getPdfProgress() != null) {
progress.setPdfProgress(request.getPdfProgress().getPage());
percentage = request.getPdfProgress().getPercentage();
}
}
case CBX -> {
if (request.getCbxProgress() != null) {
progress.setCbxProgress(request.getCbxProgress().getPage());
percentage = request.getCbxProgress().getPercentage();
}
}
}
if (percentage != null) {
progress.setReadStatus(getStatus(percentage));
setProgressPercent(progress, book.getBookType(), percentage);
}
if (request.getDateFinished() != null) {
progress.setDateFinished(request.getDateFinished());
}
userBookProgressRepository.save(progress);
}
@Transactional
public List<BookStatusUpdateResponse> updateReadStatus(List<Long> bookIds, String status) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
ReadStatus readStatus = EnumUtils.getEnumIgnoreCase(ReadStatus.class, status);
Set<Long> existingProgressBookIds = validateBooksAndGetExistingProgress(user.getId(), bookIds);
Instant now = Instant.now();
Instant dateFinished = readStatus == ReadStatus.READ ? now : null;
if (!existingProgressBookIds.isEmpty()) {
userBookProgressRepository.bulkUpdateReadStatus(user.getId(), new ArrayList<>(existingProgressBookIds), readStatus, now, dateFinished);
}
Set<Long> newProgressBookIds = bookIds.stream()
.filter(id -> !existingProgressBookIds.contains(id))
.collect(Collectors.toSet());
if (!newProgressBookIds.isEmpty()) {
BookLoreUserEntity userEntity = userRepository.findById(user.getId()).orElseThrow(() -> new UsernameNotFoundException("User not found"));
List<UserBookProgressEntity> newProgressEntities = newProgressBookIds.stream()
.map(bookId -> {
UserBookProgressEntity progress = new UserBookProgressEntity();
progress.setUser(userEntity);
BookEntity bookEntity = new BookEntity();
bookEntity.setId(bookId);
progress.setBook(bookEntity);
progress.setReadStatus(readStatus);
progress.setReadStatusModifiedTime(now);
progress.setDateFinished(dateFinished);
return progress;
})
.collect(Collectors.toList());
userBookProgressRepository.saveAll(newProgressEntities);
}
return bookIds.stream()
.map(bookId -> BookStatusUpdateResponse.builder()
.bookId(bookId)
.readStatus(readStatus)
.readStatusModifiedTime(now)
.dateFinished(dateFinished)
.build())
.collect(Collectors.toList());
}
@Transactional
public List<BookStatusUpdateResponse> resetProgress(List<Long> bookIds, ResetProgressType type) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
Set<Long> existingProgressBookIds = validateBooksAndGetExistingProgress(user.getId(), bookIds);
Instant now = Instant.now();
if (!existingProgressBookIds.isEmpty()) {
if (type == ResetProgressType.BOOKLORE) {
userBookProgressRepository.bulkResetBookloreProgress(user.getId(), new ArrayList<>(existingProgressBookIds), now);
} else if (type == ResetProgressType.KOREADER) {
userBookProgressRepository.bulkResetKoreaderProgress(user.getId(), new ArrayList<>(existingProgressBookIds));
} else if (type == ResetProgressType.KOBO) {
userBookProgressRepository.bulkResetKoboProgress(user.getId(), new ArrayList<>(existingProgressBookIds));
existingProgressBookIds.forEach(koboReadingStateService::deleteReadingState);
}
}
return bookIds.stream()
.map(bookId -> BookStatusUpdateResponse.builder()
.bookId(bookId)
.readStatus(null)
.readStatusModifiedTime(existingProgressBookIds.contains(bookId) ? now : null)
.dateFinished(null)
.build())
.collect(Collectors.toList());
}
@Transactional
public List<PersonalRatingUpdateResponse> updatePersonalRating(List<Long> bookIds, Integer rating) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
Set<Long> existingProgressBookIds = validateBooksAndGetExistingProgress(user.getId(), bookIds);
if (!existingProgressBookIds.isEmpty()) {
userBookProgressRepository.bulkUpdatePersonalRating(user.getId(), new ArrayList<>(existingProgressBookIds), rating);
}
Set<Long> newProgressBookIds = bookIds.stream()
.filter(id -> !existingProgressBookIds.contains(id))
.collect(Collectors.toSet());
if (!newProgressBookIds.isEmpty()) {
BookLoreUserEntity userEntity = userRepository.findById(user.getId()).orElseThrow(() -> new UsernameNotFoundException("User not found"));
List<UserBookProgressEntity> newProgressEntities = newProgressBookIds.stream()
.map(bookId -> {
UserBookProgressEntity progress = new UserBookProgressEntity();
progress.setUser(userEntity);
BookEntity bookEntity = new BookEntity();
bookEntity.setId(bookId);
progress.setBook(bookEntity);
progress.setPersonalRating(rating);
return progress;
})
.collect(Collectors.toList());
userBookProgressRepository.saveAll(newProgressEntities);
}
return bookIds.stream()
.map(bookId -> PersonalRatingUpdateResponse.builder()
.bookId(bookId)
.personalRating(rating)
.build())
.collect(Collectors.toList());
}
@Transactional
public List<PersonalRatingUpdateResponse> resetPersonalRating(List<Long> bookIds) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
Set<Long> existingProgressBookIds = validateBooksAndGetExistingProgress(user.getId(), bookIds);
if (!existingProgressBookIds.isEmpty()) {
userBookProgressRepository.bulkUpdatePersonalRating(user.getId(), new ArrayList<>(existingProgressBookIds), null);
}
return bookIds.stream()
.map(bookId -> PersonalRatingUpdateResponse.builder()
.bookId(bookId)
.personalRating(null)
.build())
.collect(Collectors.toList());
}
@Transactional
public List<Book> assignShelvesToBooks(Set<Long> bookIds, Set<Long> shelfIdsToAssign, Set<Long> shelfIdsToUnassign) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
BookLoreUserEntity userEntity = userRepository.findById(user.getId()).orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(user.getId()));
Set<Long> userShelfIds = userEntity.getShelves().stream().map(ShelfEntity::getId).collect(Collectors.toSet());
if (!userShelfIds.containsAll(shelfIdsToAssign)) {
throw ApiError.GENERIC_UNAUTHORIZED.createException("Cannot assign shelves that do not belong to the user.");
}
if (!userShelfIds.containsAll(shelfIdsToUnassign)) {
throw ApiError.GENERIC_UNAUTHORIZED.createException("Cannot unassign shelves that do not belong to the user.");
}
List<BookEntity> bookEntities = bookQueryService.findAllWithMetadataByIds(bookIds);
List<ShelfEntity> shelvesToAssign = shelfRepository.findAllById(shelfIdsToAssign);
for (BookEntity bookEntity : bookEntities) {
bookEntity.getShelves().removeIf(shelf -> shelfIdsToUnassign.contains(shelf.getId()));
bookEntity.getShelves().addAll(shelvesToAssign);
}
bookRepository.saveAll(bookEntities);
Map<Long, UserBookProgressEntity> progressMap = userProgressService.fetchUserProgress(
user.getId(), bookEntities.stream().map(BookEntity::getId).collect(Collectors.toSet()));
return bookEntities.stream().map(bookEntity -> {
Book book = bookMapper.toBook(bookEntity);
book.setShelves(filterShelvesByUserId(book.getShelves(), user.getId()));
book.setFilePath(FileUtils.getBookFullPath(bookEntity));
enrichBookWithProgress(book, progressMap.get(bookEntity.getId()));
return book;
}).collect(Collectors.toList());
}
private Set<Long> validateBooksAndGetExistingProgress(Long userId, List<Long> bookIds) {
long existingBooksCount = bookRepository.countByIdIn(bookIds);
if (existingBooksCount != bookIds.size()) {
throw ApiError.BOOK_NOT_FOUND.createException("One or more books not found");
}
return userBookProgressRepository.findExistingProgressBookIds(userId, new HashSet<>(bookIds));
}
private void setProgressPercent(UserBookProgressEntity progress, BookFileType type, Float percentage) {
switch (type) {
case EPUB -> progress.setEpubProgressPercent(percentage);
case PDF -> progress.setPdfProgressPercent(percentage);
case CBX -> progress.setCbxProgressPercent(percentage);
}
}
private ReadStatus getStatus(Float percentage) {
if (percentage >= 99.5f) return ReadStatus.READ;
if (percentage > 0.5f) return ReadStatus.READING;
return ReadStatus.UNREAD;
}
private void enrichBookWithProgress(Book book, UserBookProgressEntity progress) {
if (progress != null) {
setBookProgress(book, progress);
book.setLastReadTime(progress.getLastReadTime());
book.setReadStatus(progress.getReadStatus() == null ? String.valueOf(ReadStatus.UNSET) : String.valueOf(progress.getReadStatus()));
book.setDateFinished(progress.getDateFinished());
book.setPersonalRating(progress.getPersonalRating());
}
}
private void setBookProgress(Book book, UserBookProgressEntity progress) {
if (progress.getKoboProgressPercent() != null) {
book.setKoboProgress(com.adityachandel.booklore.model.dto.progress.KoboProgress.builder()
.percentage(progress.getKoboProgressPercent())
.build());
}
switch (book.getBookType()) {
case EPUB -> {
book.setEpubProgress(com.adityachandel.booklore.model.dto.progress.EpubProgress.builder()
.cfi(progress.getEpubProgress())
.percentage(progress.getEpubProgressPercent())
.build());
book.setKoreaderProgress(com.adityachandel.booklore.model.dto.progress.KoProgress.builder()
.percentage(progress.getKoreaderProgressPercent() != null ? progress.getKoreaderProgressPercent() * 100 : null)
.build());
}
case PDF -> book.setPdfProgress(com.adityachandel.booklore.model.dto.progress.PdfProgress.builder()
.page(progress.getPdfProgress())
.percentage(progress.getPdfProgressPercent())
.build());
case CBX -> book.setCbxProgress(com.adityachandel.booklore.model.dto.progress.CbxProgress.builder()
.page(progress.getCbxProgress())
.percentage(progress.getCbxProgressPercent())
.build());
}
}
private Set<Shelf> filterShelvesByUserId(Set<Shelf> shelves, Long userId) {
if (shelves == null) return Collections.emptySet();
return shelves.stream()
.filter(shelf -> userId.equals(shelf.getUserId()))
.collect(Collectors.toSet());
}
}
@@ -79,10 +79,14 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce
boolean saved = fileService.saveCoverImages(image, bookEntity.getId());
if (saved) {
return true;
} else {
log.warn("Could not save image extracted from CBZ as cover for '{}'", bookEntity.getFileName());
}
} finally {
image.flush(); // Release resources after processing
}
} else {
log.warn("Could not find cover image in CBZ file '{}'", bookEntity.getFileName());
}
} catch (Exception e) {
log.error("Error generating cover for '{}': {}", bookEntity.getFileName(), e.getMessage());
@@ -110,24 +114,45 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce
}
private Optional<BufferedImage> extractFirstImageFromZip(File file) {
try (ZipFile zipFile = ZipFile.builder().setFile(file).get()) {
return Collections.list(zipFile.getEntries()).stream()
.filter(e -> !e.isDirectory() && IMAGE_EXTENSION_CASE_INSENSITIVE_PATTERN.matcher(e.getName()).matches())
.min(Comparator.comparing(ZipArchiveEntry::getName))
.map(entry -> {
try (InputStream is = zipFile.getInputStream(entry)) {
return ImageIO.read(is);
} catch (Exception e) {
log.warn("Failed to read image from ZIP entry {}: {}", entry.getName(), e.getMessage());
return null;
}
});
// Fast path: Try reading from Central Directory
try (ZipFile zipFile = ZipFile.builder()
.setFile(file)
.setUseUnicodeExtraFields(true)
.setIgnoreLocalFileHeader(true)
.get()) {
Optional<BufferedImage> image = findAndReadFirstImage(zipFile);
if (image.isPresent()) return image;
} catch (Exception e) {
log.debug("Fast path failed for ZIP extraction: {}", e.getMessage());
}
// Slow path: Fallback to scanning local file headers
try (ZipFile zipFile = ZipFile.builder()
.setFile(file)
.setUseUnicodeExtraFields(true)
.setIgnoreLocalFileHeader(false)
.get()) {
return findAndReadFirstImage(zipFile);
} catch (Exception e) {
log.error("Error extracting ZIP: {}", e.getMessage());
return Optional.empty();
}
}
private Optional<BufferedImage> findAndReadFirstImage(ZipFile zipFile) {
return Collections.list(zipFile.getEntries()).stream()
.filter(e -> !e.isDirectory() && IMAGE_EXTENSION_CASE_INSENSITIVE_PATTERN.matcher(e.getName()).matches())
.min(Comparator.comparing(ZipArchiveEntry::getName))
.map(entry -> {
try (InputStream is = zipFile.getInputStream(entry)) {
return ImageIO.read(is);
} catch (Exception e) {
log.warn("Failed to read image from ZIP entry {}: {}", entry.getName(), e.getMessage());
return null;
}
});
}
private Optional<BufferedImage> extractFirstImageFrom7z(File file) {
try (SevenZFile sevenZFile = SevenZFile.builder().setFile(file).get()) {
List<SevenZArchiveEntry> imageEntries = new ArrayList<>();
@@ -196,23 +196,44 @@ public class CbxConversionService {
}
private List<Path> extractImagesFromZip(File cbzFile, Path extractedImagesDir) throws IOException {
// Fast path: Try reading from Central Directory
try (ZipFile zipFile = ZipFile.builder()
.setFile(cbzFile)
.setUseUnicodeExtraFields(true)
.setIgnoreLocalFileHeader(true)
.get()) {
List<Path> paths = extractImagesFromZipFile(zipFile, extractedImagesDir);
if (!paths.isEmpty()) return paths;
} catch (Exception e) {
log.debug("Fast path extraction failed for {}: {}", cbzFile.getName(), e.getMessage());
}
// Slow path: Fallback to scanning local file headers
try (ZipFile zipFile = ZipFile.builder()
.setFile(cbzFile)
.setUseUnicodeExtraFields(true)
.setIgnoreLocalFileHeader(false)
.get()) {
return extractImagesFromZipFile(zipFile, extractedImagesDir);
}
}
private List<Path> extractImagesFromZipFile(ZipFile zipFile, Path extractedImagesDir) {
List<Path> imagePaths = new ArrayList<>();
try (ZipFile zipFile = ZipFile.builder().setFile(cbzFile).get()) {
for (ZipArchiveEntry entry : Collections.list(zipFile.getEntries())) {
if (entry.isDirectory() || !isImageFile(entry.getName())) {
continue;
}
for (ZipArchiveEntry entry : Collections.list(zipFile.getEntries())) {
if (entry.isDirectory() || !isImageFile(entry.getName())) {
continue;
}
try {
validateImageSize(entry.getName(), entry.getSize());
Path outputPath = extractedImagesDir.resolve(extractFileName(entry.getName()));
try (InputStream inputStream = zipFile.getInputStream(entry)) {
Path outputPath = extractedImagesDir.resolve(extractFileName(entry.getName()));
Files.copy(inputStream, outputPath);
imagePaths.add(outputPath);
} catch (Exception e) {
log.warn("Error extracting image {}: {}", entry.getName(), e.getMessage());
}
} catch (Exception e) {
log.warn("Error extracting image {}: {}", entry.getName(), e.getMessage());
}
}
@@ -74,6 +74,7 @@ public class BookMetadataService {
private final CbxMetadataExtractor cbxMetadataExtractor;
private final MetadataWriterFactory metadataWriterFactory;
private final MetadataClearFlagsMapper metadataClearFlagsMapper;
private final org.springframework.transaction.PlatformTransactionManager transactionManager;
public List<BookMetadata> getProspectiveMetadataListForBookId(long bookId, FetchMetadataRequest request) {
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
@@ -269,8 +270,7 @@ public class BookMetadataService {
public void regenerateCoversForBooks(Set<Long> bookIds) {
List<BookRegenerationInfo> unlockedBooks = getUnlockedBookRegenerationInfos(bookIds);
SecurityContextVirtualThread.runWithSecurityContext(() ->
processBulkCoverRegeneration(unlockedBooks));
SecurityContextVirtualThread.runWithSecurityContext(() -> processBulkCoverRegeneration(unlockedBooks));
}
private List<BookRegenerationInfo> getUnlockedBookRegenerationInfos(Set<Long> bookIds) {
@@ -286,18 +286,48 @@ public class BookMetadataService {
notificationService.sendMessage(Topic.LOG, LogNotification.info("Started regenerating covers for " + total + " selected book(s)"));
int current = 1;
List<Long> refreshedIds = new ArrayList<>();
for (BookRegenerationInfo bookInfo : books) {
try {
String progress = "(" + current + "/" + total + ") ";
notificationService.sendMessage(Topic.LOG, LogNotification.info(progress + "Regenerating cover for: " + bookInfo.title()));
regenerateCoverForBookId(bookInfo);
log.info("{}Successfully regenerated cover for book ID {} ({})", progress, bookInfo.id(), bookInfo.title());
refreshedIds.add(bookInfo.id());
} catch (Exception e) {
log.error("Failed to regenerate cover for book ID {}: {}", bookInfo.id(), e.getMessage(), e);
}
pauseAfterBatchIfNeeded(current, total);
current++;
}
List<Book> updatedBooks = new ArrayList<>();
if (!refreshedIds.isEmpty()) {
org.springframework.transaction.support.TransactionTemplate tx = new org.springframework.transaction.support.TransactionTemplate(transactionManager);
List<java.util.Map<String, Object>> refreshedPatches = tx.execute(status -> {
List<BookEntity> entities = bookQueryService.findAllWithMetadataByIds(new java.util.HashSet<>(refreshedIds));
if (entities == null || entities.isEmpty()) return List.<java.util.Map<String, Object>>of();
entities.forEach(e -> {
if (e.getMetadata() != null) e.getMetadata().getCoverUpdatedOn();
});
return entities.stream()
.map(e -> java.util.Map.<String, Object>of(
"id", e.getId(),
"coverUpdatedOn", e.getMetadata() == null ? null : e.getMetadata().getCoverUpdatedOn()
))
.toList();
});
if (refreshedPatches != null && !refreshedPatches.isEmpty()) {
notificationService.sendMessage(Topic.BOOKS_COVER_UPDATE, refreshedPatches);
}
}
notificationService.sendMessage(Topic.LOG, LogNotification.info("Finished regenerating covers for selected books"));
} catch (Exception e) {
log.error("Error during cover regeneration: {}", e.getMessage(), e);
@@ -356,9 +386,12 @@ public class BookMetadataService {
notificationService.sendMessage(Topic.LOG, LogNotification.info(progress + "Regenerating cover for: " + title));
BookFileProcessor processor = processorRegistry.getProcessorOrThrow(book.getBookType());
processor.generateCover(book);
boolean success = processor.generateCover(book);
log.info("{}regenerated cover regeneration for book ID {} ({}) finished with success={}", progress, book.getId(), title, success);
if (!success) {
throw ApiError.FAILED_TO_REGENERATE_COVER.createException();
}
log.info("{}Successfully regenerated cover for book ID {} ({})", progress, book.getId(), title);
}
public BookMetadata getComicInfoMetadata(long bookId) {
@@ -170,6 +170,8 @@ public class BookMetadataUpdater {
handleFieldUpdate(e.getGoodreadsReviewCountLocked(), clear.isGoodreadsReviewCount(), m.getGoodreadsReviewCount(), e::setGoodreadsReviewCount, e::getGoodreadsReviewCount, replaceMode);
handleFieldUpdate(e.getHardcoverRatingLocked(), clear.isHardcoverRating(), m.getHardcoverRating(), e::setHardcoverRating, e::getHardcoverRating, replaceMode);
handleFieldUpdate(e.getHardcoverReviewCountLocked(), clear.isHardcoverReviewCount(), m.getHardcoverReviewCount(), e::setHardcoverReviewCount, e::getHardcoverReviewCount, replaceMode);
handleFieldUpdate(e.getLubimyczytacIdLocked(), clear.isLubimyczytacId(), m.getLubimyczytacId(), v -> e.setLubimyczytacId(nullIfBlank(v)), e::getLubimyczytacId, replaceMode);
handleFieldUpdate(e.getLubimyczytacRatingLocked(), clear.isLubimyczytacRating(), m.getLubimyczytacRating(), e::setLubimyczytacRating, e::getLubimyczytacRating, replaceMode);
}
private <T> void handleFieldUpdate(Boolean locked, boolean shouldClear, T newValue, Consumer<T> setter, Supplier<T> getter, MetadataReplaceMode mode) {
@@ -356,7 +358,12 @@ public class BookMetadataUpdater {
}
if (!set) return;
if (!StringUtils.hasText(m.getThumbnailUrl()) || isLocalOrPrivateUrl(m.getThumbnailUrl())) return;
fileService.createThumbnailFromUrl(bookId, m.getThumbnailUrl());
try {
fileService.createThumbnailFromUrl(bookId, m.getThumbnailUrl());
} catch (Exception ex) {
log.warn("Failed to download cover for book {}: {}", bookId, ex.getMessage());
// Don't rethrow - cover failures shouldn't roll back metadata updates
}
}
private void updateLocks(BookMetadata m, BookMetadataEntity e) {
@@ -21,6 +21,8 @@ import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.util.HashMap;
@@ -34,6 +36,7 @@ import java.util.regex.Pattern;
public class EpubMetadataExtractor implements FileMetadataExtractor {
private static final Pattern YEAR_ONLY_PATTERN = Pattern.compile("^\\d{4}$");
private static final String OPF_NS = "http://www.idpf.org/2007/opf";
@Override
public byte[] extractCover(File epubFile) {
@@ -98,7 +101,6 @@ public class EpubMetadataExtractor implements FileMetadataExtractor {
if (metadata == null) return null;
BookMetadata.BookMetadataBuilder builderMeta = BookMetadata.builder();
Set<String> authors = new HashSet<>();
Set<String> categories = new HashSet<>();
boolean seriesFound = false;
@@ -106,6 +108,11 @@ public class EpubMetadataExtractor implements FileMetadataExtractor {
NodeList children = metadata.getChildNodes();
Map<String, String> creatorsById = new HashMap<>();
Map<String, String> creatorRoleById = new HashMap<>();
Map<String, Set<String>> creatorsByRole = new HashMap<>();
creatorsByRole.put("aut", new HashSet<>());
Map<String, String> titlesById = new HashMap<>();
Map<String, String> titleTypeById = new HashMap<>();
@@ -134,6 +141,10 @@ public class EpubMetadataExtractor implements FileMetadataExtractor {
titleTypeById.put(refines.substring(1), content.toLowerCase());
}
if ("role".equals(prop) && StringUtils.isNotBlank(refines)) {
creatorRoleById.put(refines.substring(1), content.toLowerCase());
}
if (!seriesFound && ("booklore:series".equals(prop) || "calibre:series".equals(name) || "belongs-to-collection".equals(prop))) {
builderMeta.seriesName(content);
seriesFound = true;
@@ -174,13 +185,25 @@ public class EpubMetadataExtractor implements FileMetadataExtractor {
case "booklore:page_count" -> safeParseInt(content, builderMeta::pageCount);
}
}
case "creator" -> authors.add(text);
case "creator" -> {
String role = el.getAttributeNS(OPF_NS, "role");
if (StringUtils.isNotBlank(role)) {
creatorsByRole.computeIfAbsent(role, k -> new HashSet<>()).add(text);
} else {
String id = el.getAttribute("id");
if (StringUtils.isNotBlank(id)) {
creatorsById.put(id, text);
} else {
creatorsByRole.get("aut").add(text);
}
}
}
case "subject" -> categories.add(text);
case "description" -> builderMeta.description(text);
case "publisher" -> builderMeta.publisher(text);
case "language" -> builderMeta.language(text);
case "identifier" -> {
String scheme = el.getAttributeNS("http://www.idpf.org/2007/opf", "scheme").toUpperCase();
String scheme = el.getAttributeNS(OPF_NS, "scheme").toUpperCase();
String value = text.toLowerCase().startsWith("isbn:") ? text.substring(5) : text;
if (!scheme.isEmpty()) {
@@ -233,7 +256,14 @@ public class EpubMetadataExtractor implements FileMetadataExtractor {
}
}
builderMeta.authors(authors);
for (Map.Entry<String, String> entry : creatorsById.entrySet()) {
String id = entry.getKey();
String value = entry.getValue();
String role = creatorRoleById.getOrDefault(id, "aut");
creatorsByRole.computeIfAbsent(role, k -> new HashSet<>()).add(value);
}
builderMeta.authors(creatorsByRole.get("aut"));
builderMeta.categories(categories);
BookMetadata extractedMetadata = builderMeta.build();
@@ -332,7 +362,8 @@ public class EpubMetadataExtractor implements FileMetadataExtractor {
String properties = item.getAttribute("properties");
if (properties != null && properties.contains("cover-image")) {
String href = item.getAttribute("href");
return resolvePath(opfPath, href);
String decodedHref = URLDecoder.decode(href, StandardCharsets.UTF_8);
return resolvePath(opfPath, decodedHref);
}
}
}
@@ -354,14 +354,14 @@ public class Fb2MetadataExtractor implements FileMetadataExtractor {
private InputStream getInputStream(File file) throws Exception {
FileInputStream fis = new FileInputStream(file);
try {
if (file.getName().toLowerCase().endsWith(".gz")) {
if (file.getName().toLowerCase().endsWith(".gz")) {
try {
return new GZIPInputStream(fis);
} catch (Exception e) {
fis.close();
throw e;
}
return fis;
} catch (Exception e) {
fis.close();
throw e;
}
return fis;
}
}
@@ -46,6 +46,24 @@ public class GoodReadsParser implements BookParser {
@Override
public BookMetadata fetchTopMetadata(Book book, FetchMetadataRequest fetchMetadataRequest) {
// If book already has a Goodreads ID, use it directly instead of searching
// This ensures we fetch ratings for previously matched books
String existingGoodreadsId = getExistingGoodreadsId(book);
if (existingGoodreadsId != null) {
log.info("GoodReads: Using existing Goodreads ID: {}", existingGoodreadsId);
try {
Document document = fetchDoc(BASE_BOOK_URL + existingGoodreadsId);
BookMetadata metadata = parseBookDetails(document, existingGoodreadsId);
if (metadata != null) {
return metadata;
}
log.warn("GoodReads: Failed to parse details for existing ID: {}, falling back to search", existingGoodreadsId);
} catch (Exception e) {
log.warn("GoodReads: Error fetching existing ID {}: {}, falling back to search", existingGoodreadsId, e.getMessage());
}
}
// Fall back to search-based approach
Optional<BookMetadata> preview = fetchMetadataPreviews(book, fetchMetadataRequest).stream().findFirst();
if (preview.isEmpty()) {
return null;
@@ -54,6 +72,30 @@ public class GoodReadsParser implements BookParser {
return fetchedMetadata.isEmpty() ? null : fetchedMetadata.getFirst();
}
/**
* Extracts existing Goodreads ID from book metadata if available.
* Returns null if no valid ID exists.
*/
private String getExistingGoodreadsId(Book book) {
if (book == null || book.getMetadata() == null) {
return null;
}
String goodreadsId = book.getMetadata().getGoodreadsId();
if (goodreadsId == null || goodreadsId.isBlank()) {
return null;
}
// Validate it looks like a Goodreads ID (numeric, possibly with suffix like "11590-salems-lot")
// Strip any non-numeric suffix for the URL
String numericId = goodreadsId.split("-")[0].split("\\.")[0];
try {
Long.parseLong(numericId);
return goodreadsId; // Return original ID (Goodreads handles both formats)
} catch (NumberFormatException e) {
log.debug("GoodReads: Invalid Goodreads ID format: {}", goodreadsId);
return null;
}
}
@Override
public List<BookMetadata> fetchMetadata(Book book, FetchMetadataRequest fetchMetadataRequest) {
String isbn = ParserUtils.cleanIsbn(fetchMetadataRequest.getIsbn());
@@ -0,0 +1,441 @@
package com.adityachandel.booklore.service.metadata.parser;
import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.dto.BookMetadata;
import com.adityachandel.booklore.model.dto.request.FetchMetadataRequest;
import com.adityachandel.booklore.model.enums.MetadataProvider;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
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.Matcher;
import java.util.regex.Pattern;
@Service
@Slf4j
@RequiredArgsConstructor
public class LubimyCzytacParser implements BookParser {
private static final String BASE_URL = "https://lubimyczytac.pl";
private static final String SEARCH_URL = BASE_URL + "/szukaj/ksiazki";
private static final String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36";
private static final int CONNECTION_TIMEOUT_MS = 10000;
private static final int MAX_RESULTS = 10;
private static final double RATING_SCALE_DIVISOR = 2.0; // Convert 10-point scale to 5-point scale
private static final Pattern SERIES_NUMBER_PATTERN = Pattern.compile("\\(tom\\s+(\\d+)\\)");
private static final Pattern BOOK_ID_PATTERN = Pattern.compile("/ksiazka/(\\d+)");
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private final AppSettingService appSettingService;
@Override
public List<BookMetadata> fetchMetadata(Book book, FetchMetadataRequest fetchMetadataRequest) {
log.info("Fetching LubimyCzytac metadata for book: {}", book.getTitle());
// Check if provider is enabled
var settings = appSettingService.getAppSettings().getMetadataProviderSettings();
if (settings == null || settings.getLubimyczytac() == null || !settings.getLubimyczytac().isEnabled()) {
log.info("LubimyCzytac provider is disabled");
return new ArrayList<>();
}
try {
// Build search query
String query = buildSearchQuery(fetchMetadataRequest);
if (query.isEmpty()) {
log.warn("Empty search query for book: {}", book.getTitle());
return new ArrayList<>();
}
String author = fetchMetadataRequest.getAuthor();
String searchIsbn = fetchMetadataRequest.getIsbn();
boolean searchingByIsbn = searchIsbn != null && !searchIsbn.isEmpty();
// Search for books
List<String> bookUrls = searchBooks(query, author);
if (bookUrls.isEmpty()) {
log.info("No results found for query: {}", query);
return new ArrayList<>();
}
// Parse details for each book
List<BookMetadata> results = new ArrayList<>();
for (String url : bookUrls) {
BookMetadata metadata = parseBookDetails(url);
if (metadata != null) {
// If searching by ISBN, validate that the book's ISBN matches
if (searchingByIsbn) {
if (isbnMatches(metadata, searchIsbn)) {
results.add(metadata);
} else {
log.debug("Skipping book {} - ISBN doesn't match search ISBN {}",
metadata.getTitle(), searchIsbn);
}
} else {
results.add(metadata);
}
}
// Limit results to avoid excessive scraping
if (results.size() >= MAX_RESULTS) {
break;
}
}
log.info("Found {} LubimyCzytac results for query: {}", results.size(), query);
return results;
} catch (Exception e) {
log.error("Error fetching LubimyCzytac metadata", e);
return new ArrayList<>();
}
}
@Override
public BookMetadata fetchTopMetadata(Book book, FetchMetadataRequest fetchMetadataRequest) {
List<BookMetadata> results = fetchMetadata(book, fetchMetadataRequest);
return results.isEmpty() ? null : results.get(0);
}
private String buildSearchQuery(FetchMetadataRequest request) {
String isbn = request.getIsbn();
if (isbn != null && !isbn.isEmpty()) {
return isbn;
}
String title = request.getTitle();
if (title != null && !title.isEmpty()) {
return title.trim();
}
return "";
}
private String buildSearchUrl(String query, String author) {
String encodedQuery = URLEncoder.encode(query, StandardCharsets.UTF_8);
String url = SEARCH_URL + "?phrase=" + encodedQuery;
if (author != null && !author.isEmpty()) {
String encodedAuthor = URLEncoder.encode(author, StandardCharsets.UTF_8);
url += "&author=" + encodedAuthor;
}
return url;
}
private List<String> searchBooks(String query, String author) {
List<String> bookUrls = new ArrayList<>();
try {
String searchUrl = buildSearchUrl(query, author);
log.info("Searching LubimyCzytac: {}", searchUrl);
Document doc = Jsoup.connect(searchUrl)
.userAgent(USER_AGENT)
.timeout(CONNECTION_TIMEOUT_MS)
.get();
Elements results = doc.select(".authorAllBooks__single");
log.info("Found {} search results", results.size());
for (Element result : results) {
Element titleLink = result.selectFirst(".authorAllBooks__singleTextTitle");
if (titleLink != null) {
String href = titleLink.attr("href");
if (href != null && !href.isEmpty()) {
String fullUrl = href.startsWith("http") ? href : BASE_URL + href;
bookUrls.add(fullUrl);
}
}
}
} catch (IOException e) {
log.error("Error searching LubimyCzytac", e);
}
return bookUrls;
}
private BookMetadata parseBookDetails(String url) {
try {
log.info("Parsing book details from: {}", url);
Document doc = Jsoup.connect(url)
.userAgent(USER_AGENT)
.timeout(CONNECTION_TIMEOUT_MS)
.get();
BookMetadata metadata = new BookMetadata();
metadata.setProvider(MetadataProvider.Lubimyczytac);
// Extract LubimyCzytac ID from URL (e.g., /ksiazka/123456/title -> 123456)
String id = extractIdFromUrl(url);
metadata.setLubimyczytacId(id);
Element titleElement = doc.selectFirst("h1.book__title");
if (titleElement != null) {
metadata.setTitle(titleElement.text().trim());
}
Element coverElement = doc.selectFirst(".book-cover img");
if (coverElement != null) {
String coverUrl = coverElement.attr("src");
if (coverUrl != null && !coverUrl.isEmpty()) {
metadata.setThumbnailUrl(coverUrl.startsWith("http") ? coverUrl : BASE_URL + coverUrl);
}
}
Element publisherElement = doc.selectFirst("a[href*=/wydawnictwo/]");
if (publisherElement != null) {
metadata.setPublisher(publisherElement.text().trim());
}
Elements languageElements = doc.select("dt:contains(Język:) + dd");
if (!languageElements.isEmpty()) {
String language = languageElements.first().text().trim().toLowerCase();
metadata.setLanguage(mapLanguage(language));
}
Element descElement = doc.selectFirst(".collapse-content");
if (descElement != null) {
String description = descElement.text();
if (description != null && !description.isBlank()) {
metadata.setDescription(description);
}
}
Element isbnMeta = doc.selectFirst("meta[property=books:isbn]");
if (isbnMeta != null) {
String isbn = isbnMeta.attr("content").trim();
if (isbn.length() == 13) {
metadata.setIsbn13(isbn);
} else if (isbn.length() == 10) {
metadata.setIsbn10(isbn);
}
}
// Convert from 10-point to 5-point scale
Element ratingMeta = doc.selectFirst("meta[property=books:rating:value]");
if (ratingMeta != null) {
try {
String ratingStr = ratingMeta.attr("content").trim();
if (!ratingStr.isEmpty()) {
double rating = Double.parseDouble(ratingStr);
metadata.setLubimyczytacRating(rating / RATING_SCALE_DIVISOR);
}
} catch (NumberFormatException e) {
log.warn("Failed to parse rating for book: {}", url, e);
}
}
Set<String> tags = new HashSet<>();
Elements tagElements = doc.select("a[href*=/ksiazki/t/]");
for (Element tagElement : tagElements) {
String tag = tagElement.text().trim();
if (!tag.isEmpty()) {
tags.add(tag);
}
}
if (!tags.isEmpty()) {
metadata.setTags(tags);
}
// Series format: "Cykl: Series Name (tom 3)" or "Cykl: Series Name"
Elements seriesElements = doc.select("span.d-none.d-sm-block.mt-1:contains(Cykl:)");
if (!seriesElements.isEmpty()) {
String seriesText = seriesElements.first().text().trim();
parseSeriesInfo(seriesText, metadata);
}
// Extract authors, categories, pages, and publish date from JSON-LD structured data
Elements jsonLdElements = doc.select("script[type=application/ld+json]");
for (Element jsonLdElement : jsonLdElements) {
try {
String jsonLd = jsonLdElement.html();
parseJsonLd(jsonLd, metadata);
} catch (Exception e) {
log.warn("Failed to parse JSON-LD", e);
}
}
return metadata;
} catch (IOException e) {
log.error("Error parsing book details from: {}", url, e);
return null;
}
}
private String extractIdFromUrl(String url) {
// Extract ID from URL like https://lubimyczytac.pl/ksiazka/123456/title
try {
Matcher matcher = BOOK_ID_PATTERN.matcher(url);
if (matcher.find()) {
return matcher.group(1);
}
} catch (Exception e) {
log.warn("Could not extract ID from URL: {}", url);
}
return null;
}
private boolean isbnMatches(BookMetadata metadata, String searchIsbn) {
// Normalize ISBN by removing hyphens and spaces for comparison
String normalizedSearch = searchIsbn.replaceAll("[\\s-]", "");
// Check ISBN-13
if (metadata.getIsbn13() != null) {
String normalized13 = metadata.getIsbn13().replaceAll("[\\s-]", "");
if (normalized13.equals(normalizedSearch)) {
return true;
}
}
// Check ISBN-10
if (metadata.getIsbn10() != null) {
String normalized10 = metadata.getIsbn10().replaceAll("[\\s-]", "");
if (normalized10.equals(normalizedSearch)) {
return true;
}
}
return false;
}
private String mapLanguage(String polishLanguage) {
switch (polishLanguage) {
case "polski":
return "pl";
case "angielski":
return "en";
case "niemiecki":
return "de";
case "francuski":
return "fr";
case "hiszpański":
return "es";
case "włoski":
return "it";
default:
return polishLanguage;
}
}
private void parseSeriesInfo(String seriesText, BookMetadata metadata) {
// Format: "Cykl: Series Name (tom 3)" or "Cykl: Series Name"
if (seriesText.startsWith("Cykl:")) {
seriesText = seriesText.substring(5).trim();
}
// Extract series number if present
var matcher = SERIES_NUMBER_PATTERN.matcher(seriesText);
if (matcher.find()) {
try {
float seriesNumber = Float.parseFloat(matcher.group(1));
metadata.setSeriesNumber(seriesNumber);
// Remove the "(tom X)" part to get series name
String seriesName = SERIES_NUMBER_PATTERN.matcher(seriesText).replaceAll("").trim();
metadata.setSeriesName(seriesName);
} catch (NumberFormatException e) {
log.warn("Failed to parse series number from: {}", seriesText);
metadata.setSeriesName(seriesText);
}
} else {
metadata.setSeriesName(seriesText);
}
}
private void parseJsonLd(String jsonLd, BookMetadata metadata) {
try {
JsonNode root = OBJECT_MAPPER.readTree(jsonLd);
// Pages
if (root.has("numberOfPages")) {
try {
int pages = root.get("numberOfPages").asInt();
metadata.setPageCount(pages);
} catch (Exception e) {
log.warn("Failed to parse numberOfPages from JSON-LD");
}
}
// Publish date
if (root.has("datePublished")) {
try {
String dateStr = root.get("datePublished").asText();
LocalDate date = LocalDate.parse(dateStr, DateTimeFormatter.ISO_DATE);
metadata.setPublishedDate(date);
} catch (Exception e) {
log.warn("Failed to parse datePublished from JSON-LD: {}", e.getMessage());
}
}
// Author(s) - can be single Person or array of Person objects
if (root.has("author")) {
try {
Set<String> authors = new HashSet<>();
JsonNode authorNode = root.get("author");
if (authorNode.isArray()) {
// Multiple authors
for (JsonNode author : authorNode) {
if (author.has("name")) {
authors.add(author.get("name").asText());
}
}
} else if (authorNode.isObject() && authorNode.has("name")) {
// Single author
authors.add(authorNode.get("name").asText());
}
if (!authors.isEmpty()) {
metadata.setAuthors(authors);
}
} catch (Exception e) {
log.warn("Failed to parse author from JSON-LD: {}", e.getMessage());
}
}
// Genre/Category - extracted from genre URL
if (root.has("genre")) {
try {
String genreUrl = root.get("genre").asText();
// Extract category name from URL like "https://lubimyczytac.pl/ksiazki/k/69/poradniki"
// Get the last segment after the final slash
String[] urlParts = genreUrl.split("/");
if (urlParts.length > 0) {
String categoryName = urlParts[urlParts.length - 1];
if (!categoryName.isEmpty()) {
Set<String> categories = new HashSet<>();
categories.add(categoryName);
metadata.setCategories(categories);
}
}
} catch (Exception e) {
log.warn("Failed to parse genre from JSON-LD: {}", e.getMessage());
}
}
} catch (Exception e) {
log.warn("Failed to parse JSON-LD structure", e);
}
}
}
@@ -29,6 +29,8 @@ import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
@@ -84,7 +86,8 @@ public class EpubMetadataWriter implements MetadataWriter {
helper.copyLanguage(clear != null && clear.isLanguage(), val -> replaceAndTrackChange(opfDoc, metadataElement, "language", DC_NS, val, hasChanges));
helper.copyAuthors(clear != null && clear.isAuthors(), names -> {
removeElementsByTagNameNS(metadataElement, DC_NS, "creator");
removeCreatorsByRole(metadataElement, "");
removeCreatorsByRole(metadataElement, "aut");
if (names != null) {
for (String name : names) {
String[] parts = name.split(" ", 2);
@@ -406,7 +409,8 @@ public class EpubMetadataWriter implements MetadataWriter {
}
String coverHref = existingCoverItem.getAttribute("href");
if (coverHref == null || coverHref.isBlank()) {
String decodedCoverHref = URLDecoder.decode(coverHref, StandardCharsets.UTF_8);
if (decodedCoverHref == null || decodedCoverHref.isBlank()) {
throw new IOException("Cover item has no href attribute");
}
@@ -418,7 +422,7 @@ public class EpubMetadataWriter implements MetadataWriter {
}
Path opfDir = opfPath.getParent();
Path coverFilePath = opfDir.resolve(coverHref).normalize();
Path coverFilePath = opfDir.resolve(decodedCoverHref).normalize();
Files.createDirectories(coverFilePath.getParent());
Files.write(coverFilePath, coverData);
@@ -488,6 +492,16 @@ public class EpubMetadataWriter implements MetadataWriter {
}
}
private void removeMetaByRefines(Element metadataElement, String refines) {
NodeList metas = metadataElement.getElementsByTagNameNS("*", "meta");
for (int i = metas.getLength() - 1; i >= 0; i--) {
Element meta = (Element) metas.item(i);
if (refines.equals(meta.getAttribute("refines"))) {
metadataElement.removeChild(meta);
}
}
}
private Element createMetaElement(Document doc, String name, String content) {
Element meta = doc.createElementNS(doc.getDocumentElement().getNamespaceURI(), "meta");
meta.setAttribute("name", name);
@@ -520,6 +534,28 @@ public class EpubMetadataWriter implements MetadataWriter {
}
}
private void removeCreatorsByRole(Element metadataElement, String role) {
NodeList creators = metadataElement.getElementsByTagNameNS("*", "creator");
for (int i = creators.getLength() - 1; i >= 0; i--) {
Element creatorElement = (Element) creators.item(i);
String id = creatorElement.getAttribute("id");
String creatorRole = creatorElement.getAttributeNS(OPF_NS, "role");
if (StringUtils.isNotBlank(id) && StringUtils.isBlank(creatorRole)) {
// Finds any matching role meta tags for this creator ID
Element meta = getMetaElementByFilter(metadataElement, el -> ("role".equals(el.getAttribute("property")) && "#".concat(id).equals(el.getAttribute("refines"))));
if ( meta != null ) {
creatorRole = meta.hasAttribute("content") ? meta.getAttribute("content").trim() : meta.getTextContent().trim();
}
}
if (role.equalsIgnoreCase(creatorRole)) {
metadataElement.removeChild(creatorElement);
if (StringUtils.isNotBlank(id)){
removeMetaByRefines(metadataElement, "#".concat(id));
}
}
}
}
private Element createCreatorElement(Document doc, String fullName, String fileAs, String role) {
Element creator = doc.createElementNS("http://purl.org/dc/elements/1.1/", "creator");
creator.setPrefix("dc");
@@ -540,17 +576,25 @@ public class EpubMetadataWriter implements MetadataWriter {
return subj;
}
private String getMetaContentByName(Element metadataElement, String name) {
private Element getMetaElementByFilter(Element metadataElement, java.util.function.Predicate<Element> filter) {
NodeList metas = metadataElement.getElementsByTagNameNS("*", "meta");
for (int i = 0; i < metas.getLength(); i++) {
Element meta = (Element) metas.item(i);
if (name.equals(meta.getAttribute("name"))) {
return meta.getAttribute("content");
if (filter.test(meta)) {
return meta;
}
}
return null;
}
private String getMetaContentByName(Element metadataElement, String name) {
Element meta = getMetaElementByFilter( metadataElement, el -> name.equals(el.getAttribute("name")) );
if (meta != null) {
return meta.getAttribute("content");
}
return null;
}
private void deleteDirectoryRecursively(Path dir) {
try (var pathStream = Files.walk(dir)) {
pathStream
@@ -2,9 +2,11 @@ package com.adityachandel.booklore.service.migration;
import com.adityachandel.booklore.config.AppProperties;
import com.adityachandel.booklore.model.entity.AppMigrationEntity;
import com.adityachandel.booklore.model.entity.AppSettingEntity;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
import com.adityachandel.booklore.repository.AppMigrationRepository;
import com.adityachandel.booklore.repository.AppSettingsRepository;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.service.book.BookQueryService;
import com.adityachandel.booklore.service.file.FileFingerprint;
@@ -24,26 +26,73 @@ import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.List;
import java.util.UUID;
@Slf4j
@AllArgsConstructor
@Service
public class AppMigrationService {
private static final String INSTALLATION_ID_KEY = "installation_id";
private AppMigrationRepository migrationRepository;
private AppSettingsRepository appSettingsRepository;
private BookRepository bookRepository;
private BookQueryService bookQueryService;
private MetadataMatchService metadataMatchService;
private AppProperties appProperties;
private FileService fileService;
@Transactional
public void generateInstallationId() {
if (migrationRepository.existsById("generateInstallationId")) return;
AppSettingEntity setting = appSettingsRepository.findByName(INSTALLATION_ID_KEY);
if (setting == null) {
LocalDateTime now = LocalDateTime.now();
String uuid = UUID.randomUUID().toString();
String combined = now + "_" + uuid;
String installationId = hashToSha256(combined).substring(0, 24);
setting = new AppSettingEntity();
setting.setName(INSTALLATION_ID_KEY);
setting.setVal(installationId);
appSettingsRepository.save(setting);
log.info("Generated new installation ID");
}
migrationRepository.save(new AppMigrationEntity("generateInstallationId", LocalDateTime.now(), "Generate unique installation ID using timestamp and UUID"));
}
private String hashToSha256(String input) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(input.getBytes(StandardCharsets.UTF_8));
StringBuilder hexString = new StringBuilder();
for (byte b : hash) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("SHA-256 algorithm not found", e);
}
}
@Transactional
public void populateSearchTextOnce() {
if (migrationRepository.existsById("populateSearchText")) return;
@@ -51,14 +100,14 @@ public class AppMigrationService {
int batchSize = 1000;
int processedCount = 0;
int offset = 0;
while (true) {
List<BookEntity> bookBatch = bookRepository.findBooksForMigrationBatch(offset, batchSize);
if (bookBatch.isEmpty()) break;
List<Long> bookIds = bookBatch.stream().map(BookEntity::getId).toList();
List<BookEntity> books = bookRepository.findBooksWithMetadataAndAuthors(bookIds);
for (BookEntity book : books) {
BookMetadataEntity m = book.getMetadata();
if (m != null) {
@@ -69,13 +118,13 @@ public class AppMigrationService {
}
}
}
bookRepository.saveAll(books);
processedCount += books.size();
offset += batchSize;
log.info("Migration progress: {} books processed", processedCount);
if (bookBatch.size() < batchSize) break;
}
@@ -13,6 +13,7 @@ public class AppMigrationStartup {
@EventListener(ApplicationReadyEvent.class)
public void runMigrationsOnce() {
appMigrationService.generateInstallationId();
appMigrationService.populateMissingFileSizesOnce();
appMigrationService.populateMetadataScoresOnce();
appMigrationService.populateFileHashesOnce();
@@ -137,25 +137,36 @@ public class CbxReaderService {
String[] encodingsToTry = {"UTF-8", "Shift_JIS", "ISO-8859-1", "CP437", "MS932"};
for (String encoding : encodingsToTry) {
Charset charset = Charset.forName(encoding);
try {
extractZipWithEncoding(cbzPath, targetDir, Charset.forName(encoding));
return;
} catch (IllegalArgumentException | java.util.zip.ZipException e) {
log.debug("Failed to extract with encoding {}: {}", encoding, e.getMessage());
// Fast path: Try reading from Central Directory only
if (extractZipWithEncoding(cbzPath, targetDir, charset, true)) return;
} catch (Exception e) {
log.debug("Fast path failed for encoding {}: {}", encoding, e.getMessage());
}
try {
// Slow path: Fallback to scanning local file headers
if (extractZipWithEncoding(cbzPath, targetDir, charset, false)) return;
} catch (Exception e) {
log.debug("Slow path failed for encoding {}: {}", encoding, e.getMessage());
}
}
throw new IOException("Unable to extract ZIP archive with any supported encoding");
}
private void extractZipWithEncoding(Path cbzPath, Path targetDir, Charset charset) throws IOException {
private boolean extractZipWithEncoding(Path cbzPath, Path targetDir, Charset charset, boolean useFastPath) throws IOException {
try (org.apache.commons.compress.archivers.zip.ZipFile zipFile =
org.apache.commons.compress.archivers.zip.ZipFile.builder()
.setPath(cbzPath)
.setCharset(charset)
.setUseUnicodeExtraFields(true)
.setIgnoreLocalFileHeader(useFastPath)
.get()) {
var entries = zipFile.getEntries();
boolean foundImages = false;
while (entries.hasMoreElements()) {
ZipArchiveEntry entry = entries.nextElement();
if (!entry.isDirectory() && isImageFile(entry.getName())) {
@@ -163,9 +174,11 @@ public class CbxReaderService {
Path target = targetDir.resolve(fileName);
try (InputStream in = zipFile.getInputStream(entry)) {
Files.copy(in, target, StandardCopyOption.REPLACE_EXISTING);
foundImages = true;
}
}
}
return foundImages;
}
}
@@ -333,10 +346,19 @@ public class CbxReaderService {
String[] encodingsToTry = {"UTF-8", "Shift_JIS", "ISO-8859-1", "CP437", "MS932"};
for (String encoding : encodingsToTry) {
Charset charset = Charset.forName(encoding);
try {
return estimateCbzWithEncoding(cbxPath, Charset.forName(encoding));
} catch (IllegalArgumentException | java.util.zip.ZipException e) {
log.debug("Failed to estimate with encoding {}: {}", encoding, e.getMessage());
long size = estimateCbzWithEncoding(cbxPath, charset, true);
if (size > 0) return size;
} catch (Exception e) {
log.debug("Fast path estimation failed for encoding {}: {}", encoding, e.getMessage());
}
try {
long size = estimateCbzWithEncoding(cbxPath, charset, false);
if (size > 0) return size;
} catch (Exception e) {
log.debug("Slow path estimation failed for encoding {}: {}", encoding, e.getMessage());
}
}
@@ -344,11 +366,13 @@ public class CbxReaderService {
return Long.MAX_VALUE;
}
private long estimateCbzWithEncoding(Path cbxPath, Charset charset) throws IOException {
private long estimateCbzWithEncoding(Path cbxPath, Charset charset, boolean useFastPath) throws IOException {
try (org.apache.commons.compress.archivers.zip.ZipFile zipFile =
org.apache.commons.compress.archivers.zip.ZipFile.builder()
.setPath(cbxPath)
.setCharset(charset)
.setUseUnicodeExtraFields(true)
.setIgnoreLocalFileHeader(useFastPath)
.get()) {
long total = 0;
@@ -1,27 +0,0 @@
package com.adityachandel.booklore.service.recommender;
import com.adityachandel.booklore.service.book.BookQueryService;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Slf4j
@Component
@RequiredArgsConstructor
public class BookRecommendationScheduler {
private final BookQueryService bookQueryService;
private final AppSettingService appSettingService;
private final BookVectorService vectorService;
private static final int RECOMMENDATION_LIMIT = 25;
@Scheduled(cron = "0 0 2 * * *")
@Transactional
public void updateAllSimilarBooks() {
}
}
@@ -11,8 +11,8 @@ public class BookUtils {
private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\s+");
private static final Pattern SPECIAL_CHARACTERS_PATTERN = Pattern.compile("[!@$%^&*_=|~`<>?/\"]");
private static final Pattern PARENTHESES_WITH_OPTIONAL_SPACE_PATTERN = Pattern.compile("\\s?\\(.*?\\)");
private static final Pattern DIACRITICAL_MARKS_PATTERN = Pattern.compile("\\p{InCombiningDiacriticalMarks}+");
private static final Pattern PARENTHESIS_PATTERN = Pattern.compile("\\s?\\([^()]*\\)");
public static String buildSearchText(BookMetadataEntity e) {
if (e == null) return null;
@@ -60,11 +60,20 @@ public class BookUtils {
return null;
}
name = name.replace("(Z-Library)", "").trim();
name = PARENTHESES_WITH_OPTIONAL_SPACE_PATTERN.matcher(name).replaceAll("").trim(); // Remove the author name inside parentheses (e.g. (Jon Yablonski))
String previous;
do {
previous = name;
name = PARENTHESIS_PATTERN.matcher(name).replaceAll("").trim();
} while (!name.equals(previous));
int dotIndex = name.lastIndexOf('.'); // Remove the file extension (e.g., .pdf, .docx)
if (dotIndex > 0) {
name = name.substring(0, dotIndex).trim();
}
name = WHITESPACE_PATTERN.matcher(name).replaceAll(" ").trim();
return name;
}
@@ -45,6 +45,8 @@ public class MetadataChangeDetector {
compare(changes, "goodreadsReviewCount", clear.isGoodreadsReviewCount(), newMeta.getGoodreadsReviewCount(), existingMeta.getGoodreadsReviewCount(), () -> !isTrue(existingMeta.getGoodreadsReviewCountLocked()), newMeta.getGoodreadsReviewCountLocked(), existingMeta.getGoodreadsReviewCountLocked());
compare(changes, "hardcoverRating", clear.isHardcoverRating(), newMeta.getHardcoverRating(), existingMeta.getHardcoverRating(), () -> !isTrue(existingMeta.getHardcoverRatingLocked()), newMeta.getHardcoverRatingLocked(), existingMeta.getHardcoverRatingLocked());
compare(changes, "hardcoverReviewCount", clear.isHardcoverReviewCount(), newMeta.getHardcoverReviewCount(), existingMeta.getHardcoverReviewCount(), () -> !isTrue(existingMeta.getHardcoverReviewCountLocked()), newMeta.getHardcoverReviewCountLocked(), existingMeta.getHardcoverReviewCountLocked());
compare(changes, "lubimyczytacId", clear.isLubimyczytacId(), newMeta.getLubimyczytacId(), existingMeta.getLubimyczytacId(), () -> !isTrue(existingMeta.getLubimyczytacIdLocked()), newMeta.getLubimyczytacIdLocked(), existingMeta.getLubimyczytacIdLocked());
compare(changes, "lubimyczytacRating", clear.isLubimyczytacRating(), newMeta.getLubimyczytacRating(), existingMeta.getLubimyczytacRating(), () -> !isTrue(existingMeta.getLubimyczytacRatingLocked()), newMeta.getLubimyczytacRatingLocked(), existingMeta.getLubimyczytacRatingLocked());
compare(changes, "authors", clear.isAuthors(), newMeta.getAuthors(), toNameSet(existingMeta.getAuthors()), () -> !isTrue(existingMeta.getAuthorsLocked()), newMeta.getAuthorsLocked(), existingMeta.getAuthorsLocked());
compare(changes, "categories", clear.isCategories(), newMeta.getCategories(), toNameSet(existingMeta.getCategories()), () -> !isTrue(existingMeta.getCategoriesLocked()), newMeta.getCategoriesLocked(), existingMeta.getCategoriesLocked());
compare(changes, "moods", clear.isMoods(), newMeta.getMoods(), toNameSet(existingMeta.getMoods()), () -> !isTrue(existingMeta.getMoodsLocked()), newMeta.getMoodsLocked(), existingMeta.getMoodsLocked());
@@ -86,6 +88,8 @@ public class MetadataChangeDetector {
compareValue(diffs, "goodreadsReviewCount", clear.isGoodreadsReviewCount(), newMeta.getGoodreadsReviewCount(), existingMeta.getGoodreadsReviewCount(), () -> !isTrue(existingMeta.getGoodreadsReviewCountLocked()));
compareValue(diffs, "hardcoverRating", clear.isHardcoverRating(), newMeta.getHardcoverRating(), existingMeta.getHardcoverRating(), () -> !isTrue(existingMeta.getHardcoverRatingLocked()));
compareValue(diffs, "hardcoverReviewCount", clear.isHardcoverReviewCount(), newMeta.getHardcoverReviewCount(), existingMeta.getHardcoverReviewCount(), () -> !isTrue(existingMeta.getHardcoverReviewCountLocked()));
compareValue(diffs, "lubimyczytacId", clear.isLubimyczytacId(), newMeta.getLubimyczytacId(), existingMeta.getLubimyczytacId(), () -> !isTrue(existingMeta.getLubimyczytacIdLocked()));
compareValue(diffs, "lubimyczytacRating", clear.isLubimyczytacRating(), newMeta.getLubimyczytacRating(), existingMeta.getLubimyczytacRating(), () -> !isTrue(existingMeta.getLubimyczytacRatingLocked()));
compareValue(diffs, "authors", clear.isAuthors(), newMeta.getAuthors(), toNameSet(existingMeta.getAuthors()), () -> !isTrue(existingMeta.getAuthorsLocked()));
compareValue(diffs, "categories", clear.isCategories(), newMeta.getCategories(), toNameSet(existingMeta.getCategories()), () -> !isTrue(existingMeta.getCategoriesLocked()));
compareValue(diffs, "moods", clear.isMoods(), newMeta.getMoods(), toNameSet(existingMeta.getMoods()), () -> !isTrue(existingMeta.getMoodsLocked()));
@@ -0,0 +1,6 @@
-- Add LubimyCzytac metadata columns
ALTER TABLE book_metadata
ADD COLUMN IF NOT EXISTS lubimyczytac_id VARCHAR(100),
ADD COLUMN IF NOT EXISTS lubimyczytac_rating FLOAT,
ADD COLUMN IF NOT EXISTS lubimyczytac_id_locked BOOLEAN DEFAULT FALSE,
ADD COLUMN IF NOT EXISTS lubimyczytac_rating_locked BOOLEAN DEFAULT FALSE;
@@ -6,9 +6,9 @@ import com.adityachandel.booklore.repository.*;
import com.adityachandel.booklore.service.book.BookDownloadService;
import com.adityachandel.booklore.service.book.BookQueryService;
import com.adityachandel.booklore.service.book.BookService;
import com.adityachandel.booklore.service.book.BookUpdateService;
import com.adityachandel.booklore.service.user.UserProgressService;
import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService;
import com.adityachandel.booklore.service.kobo.KoboReadingStateService;
import com.adityachandel.booklore.util.FileService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -41,17 +41,15 @@ class BookServiceDeleteTests {
EpubViewerPreferencesRepository epubViewerPreferencesRepository = Mockito.mock(EpubViewerPreferencesRepository.class);
CbxViewerPreferencesRepository cbxViewerPreferencesRepository = Mockito.mock(CbxViewerPreferencesRepository.class);
NewPdfViewerPreferencesRepository newPdfViewerPreferencesRepository = Mockito.mock(NewPdfViewerPreferencesRepository.class);
ShelfRepository shelfRepository = Mockito.mock(ShelfRepository.class);
FileService fileService = Mockito.mock(FileService.class);
BookMapper bookMapper = Mockito.mock(BookMapper.class);
UserRepository userRepository = Mockito.mock(UserRepository.class);
UserBookProgressRepository userBookProgressRepository = Mockito.mock(UserBookProgressRepository.class);
AuthenticationService authenticationService = Mockito.mock(AuthenticationService.class);
BookQueryService bookQueryService = Mockito.mock(BookQueryService.class);
UserProgressService userProgressService = Mockito.mock(UserProgressService.class);
BookDownloadService bookDownloadService = Mockito.mock(BookDownloadService.class);
MonitoringRegistrationService monitoringRegistrationService = Mockito.mock(MonitoringRegistrationService.class);
KoboReadingStateService koboReadingStateService = Mockito.mock(KoboReadingStateService.class);
BookUpdateService bookUpdateService = Mockito.mock(BookUpdateService.class);
bookService = new BookService(
bookRepository,
@@ -59,17 +57,15 @@ class BookServiceDeleteTests {
epubViewerPreferencesRepository,
cbxViewerPreferencesRepository,
newPdfViewerPreferencesRepository,
shelfRepository,
fileService,
bookMapper,
userRepository,
userBookProgressRepository,
authenticationService,
bookQueryService,
userProgressService,
bookDownloadService,
monitoringRegistrationService,
koboReadingStateService
bookUpdateService
);
}
@@ -0,0 +1,394 @@
package com.adityachandel.booklore.service.book;
import com.adityachandel.booklore.config.security.service.AuthenticationService;
import com.adityachandel.booklore.exception.APIException;
import com.adityachandel.booklore.mapper.BookMapper;
import com.adityachandel.booklore.model.dto.*;
import com.adityachandel.booklore.model.dto.request.ReadProgressRequest;
import com.adityachandel.booklore.model.dto.response.BookDeletionResponse;
import com.adityachandel.booklore.model.dto.response.BookStatusUpdateResponse;
import com.adityachandel.booklore.model.entity.*;
import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.repository.*;
import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService;
import com.adityachandel.booklore.service.user.UserProgressService;
import com.adityachandel.booklore.util.FileService;
import com.adityachandel.booklore.util.FileUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
@ExtendWith(org.mockito.junit.jupiter.MockitoExtension.class)
class BookServiceTest {
@Mock private BookRepository bookRepository;
@Mock private PdfViewerPreferencesRepository pdfViewerPreferencesRepository;
@Mock private EpubViewerPreferencesRepository epubViewerPreferencesRepository;
@Mock private CbxViewerPreferencesRepository cbxViewerPreferencesRepository;
@Mock private NewPdfViewerPreferencesRepository newPdfViewerPreferencesRepository;
@Mock private FileService fileService;
@Mock private BookMapper bookMapper;
@Mock private UserBookProgressRepository userBookProgressRepository;
@Mock private AuthenticationService authenticationService;
@Mock private BookQueryService bookQueryService;
@Mock private UserProgressService userProgressService;
@Mock private BookDownloadService bookDownloadService;
@Mock private MonitoringRegistrationService monitoringRegistrationService;
@Mock private BookUpdateService bookUpdateService;
@InjectMocks
private BookService bookService;
private BookLoreUser testUser;
@BeforeEach
void setUp() {
BookLoreUser.UserPermissions perms = new BookLoreUser.UserPermissions();
perms.setAdmin(true);
testUser = BookLoreUser.builder()
.id(1L)
.permissions(perms)
.assignedLibraries(List.of())
.build();
}
@Test
void getBookDTOs_adminUser_returnsBooksWithProgress() {
Book book = Book.builder().id(1L).bookType(BookFileType.PDF).shelves(Set.of()).build();
when(bookQueryService.getAllBooks(anyBoolean())).thenReturn(List.of(book));
when(userProgressService.fetchUserProgress(anyLong(), anySet())).thenReturn(Map.of(1L, new UserBookProgressEntity()));
when(authenticationService.getAuthenticatedUser()).thenReturn(testUser);
List<Book> result = bookService.getBookDTOs(true);
assertEquals(1, result.size());
verify(bookQueryService).getAllBooks(true);
}
@Test
void getBooksByIds_returnsMappedBooksWithProgress() {
BookEntity entity = new BookEntity();
entity.setId(2L);
entity.setBookType(BookFileType.EPUB);
LibraryPathEntity libPath = new LibraryPathEntity();
libPath.setPath("/tmp/library");
LibraryEntity library = new LibraryEntity();
library.setLibraryPaths(List.of(libPath));
entity.setLibrary(library);
when(bookQueryService.findAllWithMetadataByIds(anySet())).thenReturn(List.of(entity));
when(userProgressService.fetchUserProgress(anyLong(), anySet())).thenReturn(Map.of(2L, new UserBookProgressEntity()));
Book mappedBook = Book.builder().id(2L).bookType(BookFileType.EPUB).metadata(BookMetadata.builder().build()).build();
when(bookMapper.toBook(entity)).thenReturn(mappedBook);
when(authenticationService.getAuthenticatedUser()).thenReturn(testUser);
try (MockedStatic<FileUtils> fileUtilsMock = mockStatic(FileUtils.class)) {
fileUtilsMock.when(() -> FileUtils.getBookFullPath(entity)).thenReturn("/tmp/library/book.epub");
List<Book> result = bookService.getBooksByIds(Set.of(2L), false);
assertEquals(1, result.size());
assertEquals(2L, result.get(0).getId());
}
}
@Test
void getBook_existingBook_returnsBookWithProgress() {
BookEntity entity = new BookEntity();
entity.setId(3L);
entity.setBookType(BookFileType.PDF);
LibraryPathEntity libPath = new LibraryPathEntity();
libPath.setPath("/tmp/library");
LibraryEntity library = new LibraryEntity();
library.setLibraryPaths(List.of(libPath));
entity.setLibrary(library);
when(bookRepository.findById(3L)).thenReturn(Optional.of(entity));
when(userBookProgressRepository.findByUserIdAndBookId(anyLong(), eq(3L))).thenReturn(Optional.of(new UserBookProgressEntity()));
Book mappedBook = Book.builder().id(3L).bookType(BookFileType.PDF).metadata(BookMetadata.builder().build()).shelves(Set.of()).build();
when(bookMapper.toBook(entity)).thenReturn(mappedBook);
when(authenticationService.getAuthenticatedUser()).thenReturn(testUser);
try (MockedStatic<FileUtils> fileUtilsMock = mockStatic(FileUtils.class)) {
fileUtilsMock.when(() -> FileUtils.getBookFullPath(entity)).thenReturn("/tmp/library/book.pdf");
Book result = bookService.getBook(3L, true);
assertEquals(3L, result.getId());
verify(bookRepository).findById(3L);
}
}
@Test
void getBook_notFound_throwsException() {
when(bookRepository.findById(99L)).thenReturn(Optional.empty());
when(authenticationService.getAuthenticatedUser()).thenReturn(testUser);
assertThrows(APIException.class, () -> bookService.getBook(99L, true));
}
@Test
void getBookViewerSetting_epub_returnsEpubSettings() {
BookEntity entity = new BookEntity();
entity.setId(4L);
entity.setBookType(BookFileType.EPUB);
when(bookRepository.findById(4L)).thenReturn(Optional.of(entity));
EpubViewerPreferencesEntity epubPref = new EpubViewerPreferencesEntity();
epubPref.setFont("Arial");
when(epubViewerPreferencesRepository.findByBookIdAndUserId(4L, testUser.getId())).thenReturn(Optional.of(epubPref));
when(authenticationService.getAuthenticatedUser()).thenReturn(testUser);
BookViewerSettings settings = bookService.getBookViewerSetting(4L);
assertNotNull(settings.getEpubSettings());
assertEquals("Arial", settings.getEpubSettings().getFont());
}
@Test
void getBookViewerSetting_unsupportedType_throwsException() {
BookEntity entity = new BookEntity();
entity.setId(5L);
entity.setBookType(null);
when(bookRepository.findById(5L)).thenReturn(Optional.of(entity));
when(authenticationService.getAuthenticatedUser()).thenReturn(testUser);
assertThrows(APIException.class, () -> bookService.getBookViewerSetting(5L));
}
@Test
void updateBookViewerSetting_delegatesToUpdateService() {
BookViewerSettings settings = BookViewerSettings.builder().build();
bookService.updateBookViewerSetting(1L, settings);
verify(bookUpdateService).updateBookViewerSetting(1L, settings);
}
@Test
void updateReadProgress_delegatesToUpdateService() {
ReadProgressRequest req = new ReadProgressRequest();
bookService.updateReadProgress(req);
verify(bookUpdateService).updateReadProgress(req);
}
@Test
void updateReadStatus_delegatesToUpdateService() {
List<Long> ids = List.of(1L, 2L);
List<BookStatusUpdateResponse> responses = List.of(new BookStatusUpdateResponse());
when(bookUpdateService.updateReadStatus(ids, "READ")).thenReturn(responses);
List<BookStatusUpdateResponse> result = bookService.updateReadStatus(ids, "READ");
assertEquals(responses, result);
}
@Test
void assignShelvesToBooks_delegatesToUpdateService() {
Set<Long> bookIds = Set.of(1L);
Set<Long> assign = Set.of(2L);
Set<Long> unassign = Set.of(3L);
List<Book> books = List.of(Book.builder().id(1L).build());
when(bookUpdateService.assignShelvesToBooks(bookIds, assign, unassign)).thenReturn(books);
List<Book> result = bookService.assignShelvesToBooks(bookIds, assign, unassign);
assertEquals(books, result);
}
@Test
void getBookThumbnail_fileExists_returnsUrlResource() throws Exception {
when(fileService.getThumbnailFile(1L)).thenReturn("/tmp/cover.jpg");
Path path = Paths.get("/tmp/cover.jpg");
Files.createFile(path);
try {
Resource res = bookService.getBookThumbnail(1L);
assertTrue(res instanceof UrlResource);
} finally {
Files.deleteIfExists(path);
}
}
@Test
void getBookThumbnail_fileMissing_returnsDefault() throws Exception {
when(fileService.getThumbnailFile(1L)).thenReturn("/tmp/nonexistent.jpg");
Resource res = bookService.getBookThumbnail(1L);
assertTrue(res instanceof UrlResource);
}
@Test
void getBookThumbnail_malformedPath_throwsRuntimeException() {
when(fileService.getThumbnailFile(123L)).thenReturn("\0illegal:path");
assertThrows(RuntimeException.class, () -> bookService.getBookThumbnail(123L));
}
@Test
void getBookCover_fileExists_returnsUrlResource() throws Exception {
when(fileService.getCoverFile(1L)).thenReturn("/tmp/cover2.jpg");
Path path = Paths.get("/tmp/cover2.jpg");
Files.createFile(path);
try {
Resource res = bookService.getBookCover(1L);
assertTrue(res instanceof UrlResource);
} finally {
Files.deleteIfExists(path);
}
}
@Test
void getBookCover_fileMissing_returnsClassPathResource() {
when(fileService.getCoverFile(1L)).thenReturn("/tmp/nonexistent2.jpg");
Resource res = bookService.getBookCover(1L);
assertTrue(res instanceof ClassPathResource);
}
@Test
void getBookCover_malformedPath_throwsRuntimeException() {
when(fileService.getCoverFile(123L)).thenReturn("\0illegal:path");
assertThrows(RuntimeException.class, () -> bookService.getBookCover(123L));
}
@Test
void getBackgroundImage_returnsResource() {
Resource mockResource = mock(Resource.class);
when(fileService.getBackgroundResource(testUser.getId())).thenReturn(mockResource);
when(authenticationService.getAuthenticatedUser()).thenReturn(testUser);
Resource res = bookService.getBackgroundImage();
assertEquals(mockResource, res);
}
@Test
void downloadBook_delegatesToDownloadService() {
ResponseEntity<Resource> response = ResponseEntity.ok(mock(Resource.class));
when(bookDownloadService.downloadBook(1L)).thenReturn(response);
ResponseEntity<Resource> result = bookService.downloadBook(1L);
assertEquals(response, result);
}
@Test
void getBookContent_returnsByteArrayResource() throws Exception {
BookEntity entity = new BookEntity();
entity.setId(10L);
when(bookRepository.findById(10L)).thenReturn(Optional.of(entity));
Path path = Paths.get("/tmp/bookcontent.txt");
Files.write(path, "hello".getBytes());
try (MockedStatic<FileUtils> fileUtilsMock = mockStatic(FileUtils.class)) {
fileUtilsMock.when(() -> FileUtils.getBookFullPath(entity)).thenReturn(path.toString());
ResponseEntity<ByteArrayResource> response = bookService.getBookContent(10L);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertArrayEquals("hello".getBytes(), response.getBody().getByteArray());
} finally {
Files.deleteIfExists(path);
}
}
@Test
void getBookContent_bookNotFound_throwsException() {
when(bookRepository.findById(404L)).thenReturn(Optional.empty());
assertThrows(APIException.class, () -> bookService.getBookContent(404L));
}
@Test
void getBookContent_fileIoError_throwsIOException() throws Exception {
BookEntity entity = new BookEntity();
entity.setId(12L);
when(bookRepository.findById(12L)).thenReturn(Optional.of(entity));
try (MockedStatic<FileUtils> fileUtilsMock = mockStatic(FileUtils.class)) {
fileUtilsMock.when(() -> FileUtils.getBookFullPath(entity)).thenReturn("/tmp/nonexistentfile.txt");
assertThrows(java.io.FileNotFoundException.class, () -> bookService.getBookContent(12L));
}
}
@Test
void deleteBooks_deletesFilesAndEntities() throws Exception {
BookEntity entity = new BookEntity();
entity.setId(11L);
LibraryEntity library = new LibraryEntity();
LibraryPathEntity libPath = new LibraryPathEntity();
libPath.setPath("/tmp/library");
library.setLibraryPaths(List.of(libPath));
entity.setLibrary(library);
Path filePath = Paths.get("/tmp/bookfile.txt");
Files.createDirectories(filePath.getParent());
Files.write(filePath, "abc".getBytes());
when(bookQueryService.findAllWithMetadataByIds(Set.of(11L))).thenReturn(List.of(entity));
doNothing().when(bookRepository).deleteAll(anyList());
BookEntity spyEntity = spy(entity);
doReturn(filePath).when(spyEntity).getFullFilePath();
when(bookQueryService.findAllWithMetadataByIds(Set.of(11L))).thenReturn(List.of(spyEntity));
BookDeletionResponse response = bookService.deleteBooks(Set.of(11L)).getBody();
assertNotNull(response);
assertTrue(response.getFailedFileDeletions().isEmpty());
assertEquals(Set.of(11L), response.getDeleted());
Files.deleteIfExists(filePath);
}
@Test
void deleteBooks_fileDoesNotExist_deletesEntityOnly() {
BookEntity entity = new BookEntity();
entity.setId(13L);
LibraryEntity library = new LibraryEntity();
LibraryPathEntity libPath = new LibraryPathEntity();
libPath.setPath("/tmp/library");
library.setLibraryPaths(List.of(libPath));
entity.setLibrary(library);
BookEntity spyEntity = spy(entity);
doReturn(Paths.get("/tmp/nonexistentfile.txt")).when(spyEntity).getFullFilePath();
when(bookQueryService.findAllWithMetadataByIds(Set.of(13L))).thenReturn(List.of(spyEntity));
doNothing().when(bookRepository).deleteAll(anyList());
BookDeletionResponse response = bookService.deleteBooks(Set.of(13L)).getBody();
assertNotNull(response);
assertTrue(response.getFailedFileDeletions().isEmpty());
assertEquals(Set.of(13L), response.getDeleted());
}
@Test
void deleteEmptyParentDirsUpToLibraryFolders_deletesEmptyDirs() throws Exception {
Path root = Files.createTempDirectory("libroot");
Path subdir = Files.createDirectory(root.resolve("subdir"));
Path file = subdir.resolve(".DS_Store");
Files.createFile(file);
Set<Path> roots = Set.of(root);
bookService.deleteEmptyParentDirsUpToLibraryFolders(subdir, roots);
assertFalse(Files.exists(subdir));
Files.deleteIfExists(root);
}
@Test
void filterShelvesByUserId_returnsOnlyUserShelves() {
Shelf shelf1 = Shelf.builder().id(1L).userId(1L).build();
Shelf shelf2 = Shelf.builder().id(2L).userId(2L).build();
Set<Shelf> shelves = Set.of(shelf1, shelf2);
Set<Shelf> result = org.springframework.test.util.ReflectionTestUtils.invokeMethod(
bookService, "filterShelvesByUserId", shelves, 1L);
assertEquals(1, result.size());
assertTrue(result.contains(shelf1));
}
}
@@ -0,0 +1,343 @@
package com.adityachandel.booklore.service.book;
import com.adityachandel.booklore.config.security.service.AuthenticationService;
import com.adityachandel.booklore.exception.APIException;
import com.adityachandel.booklore.mapper.BookMapper;
import com.adityachandel.booklore.model.dto.*;
import com.adityachandel.booklore.model.dto.progress.EpubProgress;
import com.adityachandel.booklore.model.dto.progress.PdfProgress;
import com.adityachandel.booklore.model.dto.request.ReadProgressRequest;
import com.adityachandel.booklore.model.dto.response.BookStatusUpdateResponse;
import com.adityachandel.booklore.model.dto.response.PersonalRatingUpdateResponse;
import com.adityachandel.booklore.model.entity.*;
import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.model.enums.ReadStatus;
import com.adityachandel.booklore.model.enums.ResetProgressType;
import com.adityachandel.booklore.repository.*;
import com.adityachandel.booklore.service.kobo.KoboReadingStateService;
import com.adityachandel.booklore.service.user.UserProgressService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.util.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class BookUpdateServiceTest {
@Mock private BookRepository bookRepository;
@Mock private PdfViewerPreferencesRepository pdfViewerPreferencesRepository;
@Mock private EpubViewerPreferencesRepository epubViewerPreferencesRepository;
@Mock private CbxViewerPreferencesRepository cbxViewerPreferencesRepository;
@Mock private NewPdfViewerPreferencesRepository newPdfViewerPreferencesRepository;
@Mock private ShelfRepository shelfRepository;
@Mock private BookMapper bookMapper;
@Mock private UserRepository userRepository;
@Mock private UserBookProgressRepository userBookProgressRepository;
@Mock private AuthenticationService authenticationService;
@Mock private BookQueryService bookQueryService;
@Mock private UserProgressService userProgressService;
@Mock private KoboReadingStateService koboReadingStateService;
@InjectMocks
private BookUpdateService bookUpdateService;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
bookUpdateService = new BookUpdateService(
bookRepository,
pdfViewerPreferencesRepository,
epubViewerPreferencesRepository,
cbxViewerPreferencesRepository,
newPdfViewerPreferencesRepository,
shelfRepository,
bookMapper,
userRepository,
userBookProgressRepository,
authenticationService,
bookQueryService,
userProgressService,
koboReadingStateService
);
}
@Test
void updateBookViewerSetting_pdf_shouldUpdatePdfPrefs() {
long bookId = 1L;
BookEntity book = new BookEntity();
book.setId(bookId);
book.setBookType(BookFileType.PDF);
BookLoreUser user = mock(BookLoreUser.class);
when(bookRepository.findById(bookId)).thenReturn(Optional.of(book));
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
when(user.getId()).thenReturn(2L);
PdfViewerPreferencesEntity pdfPrefs = new PdfViewerPreferencesEntity();
when(pdfViewerPreferencesRepository.findByBookIdAndUserId(bookId, 2L)).thenReturn(Optional.of(pdfPrefs));
BookViewerSettings settings = BookViewerSettings.builder()
.pdfSettings(PdfViewerPreferences.builder()
.zoom("1.5")
.spread("spread")
.build())
.build();
bookUpdateService.updateBookViewerSetting(bookId, settings);
verify(pdfViewerPreferencesRepository).save(pdfPrefs);
assertEquals("1.5", pdfPrefs.getZoom());
assertEquals("spread", pdfPrefs.getSpread());
}
@Test
void updateBookViewerSetting_epub_shouldUpdateEpubPrefs() {
long bookId = 1L;
BookEntity book = new BookEntity();
book.setId(bookId);
book.setBookType(BookFileType.EPUB);
BookLoreUser user = mock(BookLoreUser.class);
when(bookRepository.findById(bookId)).thenReturn(Optional.of(book));
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
when(user.getId()).thenReturn(2L);
EpubViewerPreferencesEntity epubPrefs = new EpubViewerPreferencesEntity();
when(epubViewerPreferencesRepository.findByBookIdAndUserId(bookId, 2L)).thenReturn(Optional.of(epubPrefs));
BookViewerSettings settings = BookViewerSettings.builder()
.epubSettings(EpubViewerPreferences.builder()
.font("font")
.fontSize(12)
.theme("theme")
.flow("flow")
.spread("spread")
.letterSpacing(1.2f)
.lineHeight(1.3f)
.build())
.build();
bookUpdateService.updateBookViewerSetting(bookId, settings);
verify(epubViewerPreferencesRepository).save(epubPrefs);
assertEquals("font", epubPrefs.getFont());
assertEquals(12, epubPrefs.getFontSize());
assertEquals("theme", epubPrefs.getTheme());
assertEquals("flow", epubPrefs.getFlow());
assertEquals("spread", epubPrefs.getSpread());
assertEquals(1.2f, epubPrefs.getLetterSpacing());
assertEquals(1.3f, epubPrefs.getLineHeight());
}
@Test
void updateBookViewerSetting_unsupportedType_shouldThrow() {
long bookId = 1L;
BookEntity book = new BookEntity();
book.setId(bookId);
book.setBookType(null);
when(bookRepository.findById(bookId)).thenReturn(Optional.of(book));
when(authenticationService.getAuthenticatedUser()).thenReturn(mock(BookLoreUser.class));
BookViewerSettings settings = BookViewerSettings.builder().build();
assertThrows(APIException.class, () -> bookUpdateService.updateBookViewerSetting(bookId, settings));
}
@Test
void updateReadProgress_epub_shouldUpdateProgress() {
long bookId = 1L;
BookEntity book = new BookEntity();
book.setId(bookId);
book.setBookType(BookFileType.EPUB);
BookLoreUser user = mock(BookLoreUser.class);
when(bookRepository.findById(bookId)).thenReturn(Optional.of(book));
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
when(user.getId()).thenReturn(2L);
UserBookProgressEntity progress = new UserBookProgressEntity();
when(userBookProgressRepository.findByUserIdAndBookId(2L, bookId)).thenReturn(Optional.of(progress));
BookLoreUserEntity userEntity = new BookLoreUserEntity();
when(userRepository.findById(2L)).thenReturn(Optional.of(userEntity));
ReadProgressRequest req = new ReadProgressRequest();
req.setBookId(bookId);
EpubProgress epubProgress = EpubProgress.builder().cfi("cfi").percentage(100f).build();
req.setEpubProgress(epubProgress);
bookUpdateService.updateReadProgress(req);
verify(userBookProgressRepository).save(progress);
assertEquals("cfi", progress.getEpubProgress());
assertEquals(ReadStatus.READ, progress.getReadStatus());
assertEquals(100f, progress.getEpubProgressPercent());
}
@Test
void updateReadProgress_pdf_shouldUpdateProgress() {
long bookId = 1L;
BookEntity book = new BookEntity();
book.setId(bookId);
book.setBookType(BookFileType.PDF);
BookLoreUser user = mock(BookLoreUser.class);
when(bookRepository.findById(bookId)).thenReturn(Optional.of(book));
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
when(user.getId()).thenReturn(2L);
UserBookProgressEntity progress = new UserBookProgressEntity();
when(userBookProgressRepository.findByUserIdAndBookId(2L, bookId)).thenReturn(Optional.of(progress));
BookLoreUserEntity userEntity = new BookLoreUserEntity();
when(userRepository.findById(2L)).thenReturn(Optional.of(userEntity));
ReadProgressRequest req = new ReadProgressRequest();
req.setBookId(bookId);
PdfProgress pdfProgress = PdfProgress.builder().page(5).percentage(50f).build();
req.setPdfProgress(pdfProgress);
bookUpdateService.updateReadProgress(req);
verify(userBookProgressRepository).save(progress);
assertEquals(5, progress.getPdfProgress());
assertEquals(ReadStatus.READING, progress.getReadStatus());
assertEquals(50f, progress.getPdfProgressPercent());
}
@Test
void updateReadStatus_shouldUpdateExistingAndCreateNew() {
BookLoreUser user = mock(BookLoreUser.class);
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
when(user.getId()).thenReturn(1L);
List<Long> bookIds = Arrays.asList(1L, 2L, 3L);
when(bookRepository.countByIdIn(bookIds)).thenReturn(3L);
Set<Long> existing = new HashSet<>(Arrays.asList(1L, 2L));
when(userBookProgressRepository.findExistingProgressBookIds(1L, new HashSet<>(bookIds))).thenReturn(existing);
BookLoreUserEntity userEntity = new BookLoreUserEntity();
when(userRepository.findById(1L)).thenReturn(Optional.of(userEntity));
List<BookStatusUpdateResponse> result = bookUpdateService.updateReadStatus(bookIds, "READ");
verify(userBookProgressRepository).bulkUpdateReadStatus(eq(1L), eq(new ArrayList<>(existing)), eq(ReadStatus.READ), any(), any());
verify(userBookProgressRepository).saveAll(anyList());
assertEquals(3, result.size());
assertEquals(ReadStatus.READ, result.get(0).getReadStatus());
}
@Test
void resetProgress_shouldCallBulkReset() {
BookLoreUser user = mock(BookLoreUser.class);
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
when(user.getId()).thenReturn(1L);
List<Long> bookIds = Arrays.asList(1L, 2L);
when(bookRepository.countByIdIn(bookIds)).thenReturn(2L);
Set<Long> existing = new HashSet<>(bookIds);
when(userBookProgressRepository.findExistingProgressBookIds(1L, new HashSet<>(bookIds))).thenReturn(existing);
List<BookStatusUpdateResponse> result = bookUpdateService.resetProgress(bookIds, ResetProgressType.BOOKLORE);
verify(userBookProgressRepository).bulkResetBookloreProgress(eq(1L), eq(new ArrayList<>(bookIds)), any());
assertEquals(2, result.size());
}
@Test
void updatePersonalRating_shouldUpdateAndCreate() {
BookLoreUser user = mock(BookLoreUser.class);
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
when(user.getId()).thenReturn(1L);
List<Long> bookIds = Arrays.asList(1L, 2L, 3L);
when(bookRepository.countByIdIn(bookIds)).thenReturn(3L);
Set<Long> existing = new HashSet<>(Arrays.asList(1L, 2L));
when(userBookProgressRepository.findExistingProgressBookIds(1L, new HashSet<>(bookIds))).thenReturn(existing);
BookLoreUserEntity userEntity = new BookLoreUserEntity();
when(userRepository.findById(1L)).thenReturn(Optional.of(userEntity));
List<PersonalRatingUpdateResponse> result = bookUpdateService.updatePersonalRating(bookIds, 5);
verify(userBookProgressRepository).bulkUpdatePersonalRating(eq(1L), eq(new ArrayList<>(existing)), eq(5));
verify(userBookProgressRepository).saveAll(anyList());
assertEquals(3, result.size());
assertEquals(5, result.get(0).getPersonalRating());
}
@Test
void resetPersonalRating_shouldUpdateExisting() {
BookLoreUser user = mock(BookLoreUser.class);
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
when(user.getId()).thenReturn(1L);
List<Long> bookIds = Arrays.asList(1L, 2L);
when(bookRepository.countByIdIn(bookIds)).thenReturn(2L);
Set<Long> existing = new HashSet<>(bookIds);
when(userBookProgressRepository.findExistingProgressBookIds(1L, new HashSet<>(bookIds))).thenReturn(existing);
List<PersonalRatingUpdateResponse> result = bookUpdateService.resetPersonalRating(bookIds);
verify(userBookProgressRepository).bulkUpdatePersonalRating(eq(1L), eq(new ArrayList<>(bookIds)), isNull());
assertEquals(2, result.size());
assertNull(result.get(0).getPersonalRating());
}
@Test
void assignShelvesToBooks_shouldAssignAndReturnBooks() {
BookLoreUser user = mock(BookLoreUser.class);
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
when(user.getId()).thenReturn(1L);
BookLoreUserEntity userEntity = new BookLoreUserEntity();
ShelfEntity shelf1 = new ShelfEntity(); shelf1.setId(10L);
ShelfEntity shelf2 = new ShelfEntity(); shelf2.setId(20L);
userEntity.setShelves(new HashSet<>(Arrays.asList(shelf1, shelf2)));
when(userRepository.findById(1L)).thenReturn(Optional.of(userEntity));
Set<Long> bookIds = new HashSet<>(Arrays.asList(1L, 2L));
Set<Long> assignIds = new HashSet<>(Collections.singletonList(10L));
Set<Long> unassignIds = new HashSet<>(Collections.singletonList(20L));
BookEntity bookEntity1 = spy(new BookEntity());
bookEntity1.setId(1L);
bookEntity1.setShelves(new HashSet<>());
LibraryPathEntity libraryPath1 = new LibraryPathEntity();
libraryPath1.setPath("/mock/path/1");
doReturn(libraryPath1).when(bookEntity1).getLibraryPath();
bookEntity1.setFileSubPath("sub1");
bookEntity1.setFileName("file1.pdf");
BookEntity bookEntity2 = spy(new BookEntity());
bookEntity2.setId(2L);
bookEntity2.setShelves(new HashSet<>());
LibraryPathEntity libraryPath2 = new LibraryPathEntity();
libraryPath2.setPath("/mock/path/2");
doReturn(libraryPath2).when(bookEntity2).getLibraryPath();
bookEntity2.setFileSubPath("sub2");
bookEntity2.setFileName("file2.pdf");
when(bookQueryService.findAllWithMetadataByIds(bookIds)).thenReturn(Arrays.asList(bookEntity1, bookEntity2));
ShelfEntity assignShelf = new ShelfEntity(); assignShelf.setId(10L);
when(shelfRepository.findAllById(assignIds)).thenReturn(Collections.singletonList(assignShelf));
Book mockBook = mock(Book.class);
when(bookMapper.toBook(any())).thenReturn(mockBook);
when(userProgressService.fetchUserProgress(eq(1L), anySet())).thenReturn(Collections.emptyMap());
List<Book> result = bookUpdateService.assignShelvesToBooks(bookIds, assignIds, unassignIds);
verify(bookRepository).saveAll(anyList());
assertEquals(2, result.size());
}
@Test
void assignShelvesToBooks_shouldThrowIfUnauthorized() {
BookLoreUser user = mock(BookLoreUser.class);
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
when(user.getId()).thenReturn(1L);
BookLoreUserEntity userEntity = new BookLoreUserEntity();
ShelfEntity shelf1 = new ShelfEntity(); shelf1.setId(10L);
userEntity.setShelves(new HashSet<>(Collections.singletonList(shelf1)));
when(userRepository.findById(1L)).thenReturn(Optional.of(userEntity));
Set<Long> bookIds = new HashSet<>(Collections.singletonList(1L));
Set<Long> assignIds = new HashSet<>(Collections.singletonList(99L));
Set<Long> unassignIds = new HashSet<>();
assertThrows(APIException.class, () -> bookUpdateService.assignShelvesToBooks(bookIds, assignIds, unassignIds));
}
}
@@ -232,6 +232,21 @@ class EpubMetadataExtractorTest {
assertEquals(2, result.getAuthors().size());
}
@Test
@DisplayName("Should not extract non-authors from EPUB metadata")
void extractMetadata_withExtraCreators_returnsOnlyAuthors() throws IOException {
File epubFile = createEpubWithExtraCreators(DEFAULT_TITLE, DEFAULT_AUTHOR, "Jane Smith", "Alice", "Bob");
BookMetadata result = extractor.extractMetadata(epubFile);
assertNotNull(result);
assertTrue(result.getAuthors().contains(DEFAULT_AUTHOR));
assertTrue(result.getAuthors().contains("Jane Smith"));
assertFalse(result.getAuthors().contains("Alice"));
assertFalse(result.getAuthors().contains("Bob"));
assertEquals(2, result.getAuthors().size());
}
@Test
@DisplayName("Should extract publisher from EPUB metadata")
void extractMetadata_withPublisher_returnsPublisher() throws IOException {
@@ -533,6 +548,23 @@ class EpubMetadataExtractorTest {
return createEpubWithOpf(opfContent, "test-multiauthor-" + System.nanoTime() + ".epub");
}
private File createEpubWithExtraCreators(String title, String author1, String author2, String illustrator, String editor) throws IOException {
String opfContent = String.format("""
<?xml version="1.0" encoding="UTF-8"?>
<package xmlns="http://www.idpf.org/2007/opf" version="3.0">
<metadata xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:opf="http://www.idpf.org/2007/opf">
<dc:title>%s</dc:title>
<dc:creator>%s</dc:creator>
<dc:creator opf:role="aut">%s</dc:creator>
<dc:creator opf:role="ill">%s</dc:creator>
<dc:creator id="creator04">%s</dc:creator>
<meta property="role" refines="#creator04" scheme="marc:relators">edt</meta>
</metadata>
</package>
""", title, author1, author2, illustrator, editor);
return createEpubWithOpf(opfContent, "test-extracreator-" + System.nanoTime() + ".epub");
}
private File createEpubWithCalibreSeries(String title, String seriesName, String seriesIndex) throws IOException {
String opfContent = String.format("""
<?xml version="1.0" encoding="UTF-8"?>
@@ -721,5 +753,96 @@ class EpubMetadataExtractorTest {
return epubFile;
}
@Nested
@DisplayName("URL Decoding Tests")
class UrlDecodingTests {
@Test
@DisplayName("Should properly decode unicode characters in cover href")
void extractCover_withUnicodeHref_decodesCorrectly() throws IOException {
byte[] pngImage = createMinimalPngImage();
String encodedHref = "cover%C3%A1.png"; // coverá.png URL-encoded
File epubFile = createEpubWithUnicodeCover(pngImage, "cover_image", encodedHref);
byte[] cover = extractor.extractCover(epubFile);
assertNotNull(cover, "Cover should be extracted from EPUB with URL-encoded href");
assertTrue(cover.length > 0);
}
@Test
@DisplayName("Should extract cover with URL-encoded characters in manifest")
void findCoverImageHrefInOpf_withEncodedHref_returnsDecodedPath() throws IOException {
byte[] pngImage = createMinimalPngImage();
String encodedHref = "images%2Fcover%C3%A1.jpg"; // images/coverá.jpg URL-encoded
File epubFile = createEpubWithUnicodeCover(pngImage, "cover_image", encodedHref);
byte[] cover = extractor.extractCover(epubFile);
assertNotNull(cover, "Cover should be extracted even with encoded path");
assertArrayEquals(pngImage, cover, "Extracted cover should match original image");
}
@Test
@DisplayName("Should handle multiple encoded unicode characters")
void extractCover_withMultipleEncodedChars_handlesCorrectly() throws IOException {
byte[] pngImage = createMinimalPngImage();
String encodedHref = "c%C3%B3ver%20t%C3%ADtle%20%C3%A1nd%20%C3%B1ame.png";
File epubFile = createEpubWithUnicodeCover(pngImage, "multi_unicode_cover", encodedHref);
byte[] cover = extractor.extractCover(epubFile);
assertNotNull(cover, "Cover should be extracted from filename with multiple encoded chars");
assertTrue(cover.length > 0);
}
}
private File createEpubWithUnicodeCover(byte[] coverImageData, String id, String encodedHref) throws IOException {
String opfContent = String.format("""
<?xml version="1.0" encoding="UTF-8"?>
<package xmlns="http://www.idpf.org/2007/opf" version="3.0">
<metadata xmlns:dc="http://purl.org/dc/elements/1.1/">
<dc:title>Book with Unicode Cover</dc:title>
</metadata>
<manifest>
<item id="%s" href="%s" media-type="image/png" properties="cover-image"/>
</manifest>
</package>
""", id, encodedHref);
File epubFile = tempDir.resolve("test-unicode-cover-" + System.nanoTime() + ".epub").toFile();
String containerXml = """
<?xml version="1.0" encoding="UTF-8"?>
<container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">
<rootfiles>
<rootfile full-path="OEBPS/content.opf" media-type="application/oebps-package+xml"/>
</rootfiles>
</container>
""";
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(epubFile))) {
zos.putNextEntry(new ZipEntry("mimetype"));
zos.write("application/epub+zip".getBytes(StandardCharsets.UTF_8));
zos.closeEntry();
zos.putNextEntry(new ZipEntry("META-INF/container.xml"));
zos.write(containerXml.getBytes(StandardCharsets.UTF_8));
zos.closeEntry();
zos.putNextEntry(new ZipEntry("OEBPS/content.opf"));
zos.write(opfContent.getBytes(StandardCharsets.UTF_8));
zos.closeEntry();
// The actual file path in the zip should match the decoded href
String decodedPath = java.net.URLDecoder.decode(encodedHref, java.nio.charset.StandardCharsets.UTF_8);
zos.putNextEntry(new ZipEntry("OEBPS/" + decodedPath));
zos.write(coverImageData);
zos.closeEntry();
}
return epubFile;
}
}
@@ -0,0 +1,156 @@
package com.adityachandel.booklore.service.metadata.parser;
import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.dto.BookMetadata;
import com.adityachandel.booklore.model.dto.request.FetchMetadataRequest;
import com.adityachandel.booklore.model.dto.settings.AppSettings;
import com.adityachandel.booklore.model.dto.settings.MetadataProviderSettings;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class LubimyCzytacParserTest {
@Mock
private AppSettingService appSettingService;
@InjectMocks
private LubimyCzytacParser parser;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
}
@Test
void testFetchMetadata_ProviderDisabled() {
// Given
Book book = Book.builder()
.title("Test Book")
.build();
FetchMetadataRequest request = FetchMetadataRequest.builder()
.title("Test Book")
.build();
// Mock disabled provider
AppSettings appSettings = new AppSettings();
MetadataProviderSettings providerSettings = new MetadataProviderSettings();
MetadataProviderSettings.Lubimyczytac lubimyCzytac = new MetadataProviderSettings.Lubimyczytac();
lubimyCzytac.setEnabled(false);
providerSettings.setLubimyczytac(lubimyCzytac);
appSettings.setMetadataProviderSettings(providerSettings);
when(appSettingService.getAppSettings()).thenReturn(appSettings);
// When
List<BookMetadata> results = parser.fetchMetadata(book, request);
// Then
assertNotNull(results);
assertTrue(results.isEmpty(), "Should return empty list when provider is disabled");
verify(appSettingService).getAppSettings();
}
@Test
void testFetchMetadata_ProviderSettingsNull() {
// Given
Book book = Book.builder()
.title("Test Book")
.build();
FetchMetadataRequest request = FetchMetadataRequest.builder()
.title("Test Book")
.build();
// Mock null settings
AppSettings appSettings = new AppSettings();
appSettings.setMetadataProviderSettings(null);
when(appSettingService.getAppSettings()).thenReturn(appSettings);
// When
List<BookMetadata> results = parser.fetchMetadata(book, request);
// Then
assertNotNull(results);
assertTrue(results.isEmpty(), "Should return empty list when settings are null");
verify(appSettingService).getAppSettings();
}
@Test
void testFetchMetadata_EmptyQuery() {
// Given
Book book = Book.builder()
.title("Test Book")
.build();
FetchMetadataRequest request = FetchMetadataRequest.builder()
.build();
// Empty query - no title or ISBN
// Mock enabled provider
AppSettings appSettings = new AppSettings();
MetadataProviderSettings providerSettings = new MetadataProviderSettings();
MetadataProviderSettings.Lubimyczytac lubimyCzytac = new MetadataProviderSettings.Lubimyczytac();
lubimyCzytac.setEnabled(true);
providerSettings.setLubimyczytac(lubimyCzytac);
appSettings.setMetadataProviderSettings(providerSettings);
when(appSettingService.getAppSettings()).thenReturn(appSettings);
// When
List<BookMetadata> results = parser.fetchMetadata(book, request);
// Then
assertNotNull(results);
assertTrue(results.isEmpty(), "Should return empty list when query is empty");
verify(appSettingService).getAppSettings();
}
@Test
@Disabled("Integration test - requires network access to LubimyCzytac.pl")
void testFetchMetadata_Integration_RealBook() {
// Given
Book book = Book.builder()
.title("Wiedźmin")
.build();
FetchMetadataRequest request = FetchMetadataRequest.builder()
.title("Wiedźmin")
.author("Andrzej Sapkowski")
.build();
// Mock enabled provider
AppSettings appSettings = new AppSettings();
MetadataProviderSettings providerSettings = new MetadataProviderSettings();
MetadataProviderSettings.Lubimyczytac lubimyCzytac = new MetadataProviderSettings.Lubimyczytac();
lubimyCzytac.setEnabled(true);
providerSettings.setLubimyczytac(lubimyCzytac);
appSettings.setMetadataProviderSettings(providerSettings);
when(appSettingService.getAppSettings()).thenReturn(appSettings);
// When
List<BookMetadata> results = parser.fetchMetadata(book, request);
// Then
assertNotNull(results);
assertFalse(results.isEmpty(), "Should return results for real book");
BookMetadata firstResult = results.get(0);
assertNotNull(firstResult.getTitle(), "Title should be present");
assertNotNull(firstResult.getLubimyczytacId(), "LubimyCzytac ID should be present");
assertTrue(firstResult.getAuthors() != null && !firstResult.getAuthors().isEmpty(),
"Authors should be present");
}
}
@@ -0,0 +1,276 @@
package com.adityachandel.booklore.service.metadata.writer;
import com.adityachandel.booklore.model.MetadataClearFlags;
import com.adityachandel.booklore.model.entity.AuthorEntity;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
import java.util.zip.ZipFile;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static org.junit.jupiter.api.Assertions.*;
class EpubMetadataWriterTest {
private EpubMetadataWriter writer;
private BookMetadataEntity metadata;
private BookEntity bookEntity;
@TempDir
Path tempDir;
@BeforeEach
void setUp() {
writer = new EpubMetadataWriter();
metadata = new BookMetadataEntity();
metadata.setTitle("Test Book");
AuthorEntity author = new AuthorEntity();
author.setName("Test Author");
metadata.setAuthors(Collections.singleton(author));
bookEntity = new BookEntity();
LibraryPathEntity libraryPath = new LibraryPathEntity();
libraryPath.setPath(tempDir.toString());
bookEntity.setLibraryPath(libraryPath);
bookEntity.setFileSubPath("");
bookEntity.setFileName("test.epub");
}
@Nested
@DisplayName("Metadata writing Tests")
class MetadataWritingTests {
@Test
@DisplayName("Should only overwrite authors of EPUB metadata")
void writeMetadata_withAuthor_onlyAuthor() throws IOException {
StringBuilder existingMetadata = new StringBuilder();
existingMetadata.append("<metadata xmlns:dc=\"http://purl.org/dc/elements/1.1/\">");
existingMetadata.append("<dc:creator id=\"creator02\">Alice</dc:creator>");
existingMetadata.append("<meta property=\"role\" refines=\"#creator02\">ill</meta>");
existingMetadata.append("</metadata>");
String opfContent = String.format("""
<?xml version="1.0" encoding="UTF-8"?>
<package xmlns="http://www.idpf.org/2007/opf" version="3.0">
%s
</package>
""", existingMetadata);
File epubFile = createEpubWithOpf(opfContent, "test-metadata-" + System.nanoTime() + ".epub");
assertDoesNotThrow(() -> writer.writeMetadataToFile(epubFile, metadata, null, new MetadataClearFlags()));
assertTrue(epubFile.exists());
assertTrue(epubFile.length() > 0);
try (ZipFile zf = new ZipFile(epubFile)) {
ZipEntry ze = zf.getEntry("OEBPS/content.opf");
try (InputStream is = zf.getInputStream(ze)) {
byte[] fileBytes = is.readAllBytes();
String fileString = new String(fileBytes);
assertTrue(fileString.contains("id=\"creator02\""));
}
}
}
}
@Nested
@DisplayName("URL Decoding Tests")
class UrlDecodingTests {
@Test
@DisplayName("Should properly handle URL-encoded href values in manifest")
void writeMetadataToFile_withUnicodeHref_handlesDecoding() throws IOException {
byte[] epubContent = createEpubWithUnicodeCoverHref();
File epubFile = tempDir.resolve("test_unicode.epub").toFile();
Files.write(epubFile.toPath(), epubContent);
assertDoesNotThrow(() -> writer.writeMetadataToFile(epubFile, metadata, null, new MetadataClearFlags()));
assertTrue(epubFile.exists());
assertTrue(epubFile.length() > 0);
}
@Test
@DisplayName("Should handle URL-encoded cover href during cover replacement")
void replaceCoverImageFromUpload_withUnicodeHref_handlesDecoding() throws IOException {
byte[] epubContent = createEpubWithUnicodeCoverHref();
File epubFile = tempDir.resolve("test_cover_unicode.epub").toFile();
Files.write(epubFile.toPath(), epubContent);
byte[] imageBytes = createMinimalPngImage();
MultipartFile coverFile = new MockMultipartFile(
"cover.png",
"cover.png",
"image/png",
imageBytes
);
assertDoesNotThrow(() -> {
writer.replaceCoverImageFromUpload(bookEntity, coverFile);
});
}
}
private File createEpubWithOpf(String opfContent, String filename) throws IOException {
File epubFile = tempDir.resolve(filename).toFile();
String containerXml = """
<?xml version="1.0" encoding="UTF-8"?>
<container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">
<rootfiles>
<rootfile full-path="OEBPS/content.opf" media-type="application/oebps-package+xml"/>
</rootfiles>
</container>
""";
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(epubFile))) {
zos.putNextEntry(new ZipEntry("mimetype"));
zos.write("application/epub+zip".getBytes(StandardCharsets.UTF_8));
zos.closeEntry();
zos.putNextEntry(new ZipEntry("META-INF/container.xml"));
zos.write(containerXml.getBytes(StandardCharsets.UTF_8));
zos.closeEntry();
zos.putNextEntry(new ZipEntry("OEBPS/content.opf"));
zos.write(opfContent.getBytes(StandardCharsets.UTF_8));
zos.closeEntry();
}
return epubFile;
}
private byte[] createEpubWithUnicodeCoverHref() throws IOException {
String opfContent = """
<?xml version="1.0" encoding="UTF-8"?>
<package xmlns="http://www.idpf.org/2007/opf" version="3.0">
<metadata xmlns:dc="http://purl.org/dc/elements/1.1/">
<dc:title>Test Book with Unicode Cover</dc:title>
<dc:creator>Test Author</dc:creator>
<meta name="cover" content="cover-image"/>
</metadata>
<manifest>
<item id="ncx" href="toc.ncx" media-type="application/x-dtbncx+xml"/>
<item id="cover-image" href="cover%C3%A1.png" media-type="image/png" properties="cover-image"/>
<item id="text" href="index.html" media-type="application/xhtml+xml"/>
</manifest>
<spine toc="ncx">
<itemref idref="text"/>
</spine>
</package>
""";
String containerXml = """
<?xml version="1.0" encoding="UTF-8"?>
<container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">
<rootfiles>
<rootfile full-path="OEBPS/content.opf" media-type="application/oebps-package+xml"/>
</rootfiles>
</container>
""";
String htmlContent = """
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test</title>
</head>
<body>
<h1>Test Content</h1>
</body>
</html>
""";
String ncxContent = """
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE ncx PUBLIC "-//NISO//DTD ncx 2005-1//EN"
"http://www.daisy.org/z3986/2005/ncx-2005-1.dtd">
<ncx version="2005-1" xml:lang="en">
<head>
<meta name="dtb:uid" content="test-book"/>
</head>
<docTitle>
<text>Test Book</text>
</docTitle>
<navMap>
<navPoint id="navpoint-1" playOrder="1">
<navLabel>
<text>Test</text>
</navLabel>
<content src="index.html"/>
</navPoint>
</navMap>
</ncx>
""";
byte[] coverImage = createMinimalPngImage();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ZipOutputStream zos = new ZipOutputStream(baos)) {
zos.putNextEntry(new ZipEntry("mimetype"));
zos.write("application/epub+zip".getBytes(StandardCharsets.UTF_8));
zos.closeEntry();
zos.putNextEntry(new ZipEntry("META-INF/container.xml"));
zos.write(containerXml.getBytes(StandardCharsets.UTF_8));
zos.closeEntry();
zos.putNextEntry(new ZipEntry("OEBPS/content.opf"));
zos.write(opfContent.getBytes(StandardCharsets.UTF_8));
zos.closeEntry();
zos.putNextEntry(new ZipEntry("OEBPS/index.html"));
zos.write(htmlContent.getBytes(StandardCharsets.UTF_8));
zos.closeEntry();
zos.putNextEntry(new ZipEntry("OEBPS/toc.ncx"));
zos.write(ncxContent.getBytes(StandardCharsets.UTF_8));
zos.closeEntry();
String decodedCoverPath = java.net.URLDecoder.decode("cover%C3%A1.png", java.nio.charset.StandardCharsets.UTF_8);
zos.putNextEntry(new ZipEntry("OEBPS/" + decodedCoverPath));
zos.write(coverImage);
zos.closeEntry();
}
return baos.toByteArray();
}
private byte[] createMinimalPngImage() {
return new byte[]{
(byte) 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A,
0x00, 0x00, 0x00, 0x0D,
0x49, 0x48, 0x44, 0x52,
0x00, 0x00, 0x00, 0x01,
0x00, 0x00, 0x00, 0x01,
0x08, 0x06,
0x00, 0x00, 0x00,
(byte) 0x90, (byte) 0x77, (byte) 0x53, (byte) 0xDE,
0x00, 0x00, 0x00, 0x0A,
0x49, 0x44, 0x41, 0x54,
0x78, (byte) 0x9C, 0x63, 0x00, 0x01, 0x00, 0x00, 0x05,
0x00, 0x01,
0x0D, (byte) 0x0A, 0x2D, (byte) 0xB4,
0x00, 0x00, 0x00, 0x00,
0x49, 0x45, 0x4E, 0x44,
(byte) 0xAE, 0x42, 0x60, (byte) 0x82
};
}
}
@@ -3,6 +3,8 @@ package com.adityachandel.booklore.util;
import com.adityachandel.booklore.model.entity.AuthorEntity;
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import java.util.HashSet;
import java.util.Set;
@@ -11,6 +13,8 @@ import static org.junit.jupiter.api.Assertions.*;
class BookUtilsTest {
private static final int MAX_SEARCH_TERM_LENGTH = 60; // From BookUtils.cleanAndTruncateSearchTerm
@Test
void testBuildSearchText() {
BookMetadataEntity metadata = new BookMetadataEntity();
@@ -123,7 +127,8 @@ class BookUtilsTest {
void testCleanAndTruncateSearchTerm_longText() {
String longText = "This is a very long search term that should be truncated because it exceeds sixty characters in length and needs to be shortened";
String result = BookUtils.cleanAndTruncateSearchTerm(longText);
assertTrue(result.length() <= 60);
assertTrue(result.length() <= MAX_SEARCH_TERM_LENGTH,
String.format("Result length %d should not exceed max %d", result.length(), MAX_SEARCH_TERM_LENGTH));
assertEquals("This is a very long search term that should be truncated", result);
}
@@ -131,16 +136,18 @@ class BookUtilsTest {
void testCleanAndTruncateSearchTerm_longTextWithSpecialChars() {
String longText = "This-is,a@very#long$search%term^with&special*chars(that)should[be]truncated{because}it<exceeds>sixty?characters";
String result = BookUtils.cleanAndTruncateSearchTerm(longText);
assertTrue(result.length() <= 60);
assertTrue(result.length() <= MAX_SEARCH_TERM_LENGTH,
String.format("Result length %d should not exceed max %d", result.length(), MAX_SEARCH_TERM_LENGTH));
assertEquals("This-is,avery#longsearchtermwithspecialchars(that)should[be]", result);
}
@Test
void testCleanAndTruncateSearchTerm_exactly60Chars() {
String text = "A".repeat(60);
String text = "A".repeat(MAX_SEARCH_TERM_LENGTH);
String result = BookUtils.cleanAndTruncateSearchTerm(text);
assertEquals(text, result);
assertEquals(60, result.length());
assertEquals(MAX_SEARCH_TERM_LENGTH, result.length(),
"Text at max length should not be truncated");
}
@Test
@@ -327,4 +334,130 @@ class BookUtilsTest {
assertNotNull(searchText);
assertEquals("test book", searchText);
}
@Test
void testBuildSearchText_withNullMetadata() {
String result = BookUtils.buildSearchText(null);
assertNull(result);
}
@Test
void testBuildSearchText_withAllNullFields() {
BookMetadataEntity metadata = new BookMetadataEntity();
String searchText = BookUtils.buildSearchText(metadata);
assertNotNull(searchText);
}
@Test
void testBuildSearchText_withNullAuthors() {
BookMetadataEntity metadata = new BookMetadataEntity();
metadata.setTitle("Test Book");
metadata.setAuthors(null); // null authors set
String searchText = BookUtils.buildSearchText(metadata);
assertNotNull(searchText);
assertTrue(searchText.contains("test book"));
}
@Test
void testCleanAndTruncateSearchTerm_singleLongWord() {
String longWord = "A".repeat(100);
String result = BookUtils.cleanAndTruncateSearchTerm(longWord);
assertEquals(MAX_SEARCH_TERM_LENGTH, result.length(),
"Single long word should be truncated to max length");
}
@Test
void testCleanAndTruncateSearchTerm_exactly60CharsWithWords() {
String text = "word ".repeat(12); // 60 chars exactly
String result = BookUtils.cleanAndTruncateSearchTerm(text);
assertEquals(text.trim(), result);
}
@ParameterizedTest
@CsvSource({
"'Book (Author) (Year) (Z-Library).pdf', 'Book'",
"'Book (Z-Library) More Text.pdf', 'Book More Text'",
"'Book ((Nested)) (Author).pdf', 'Book'",
"'Simple Book.epub', 'Simple Book'",
"'Book (Author Name).pdf', 'Book'",
"'Complex (Nested (Deep)) (Multiple) File.epub', 'Complex File'"
})
void testCleanFileName_parameterized(String input, String expected) {
String result = BookUtils.cleanFileName(input);
assertEquals(expected, result,
String.format("Input: '%s' should result in: '%s'", input, expected));
}
@Test
void testCleanFileName_withMultipleParentheses() {
String result = BookUtils.cleanFileName("Book (Author) (Year) (Z-Library).pdf");
assertEquals("Book", result);
}
@Test
void testCleanFileName_withNestedParentheses() {
String result = BookUtils.cleanFileName("Book ((Nested)) (Author).pdf");
assertEquals("Book", result);
}
@Test
void testCleanFileName_withZLibraryInMiddle() {
String result = BookUtils.cleanFileName("Book (Z-Library) More Text.pdf");
assertEquals("Book More Text", result);
}
@Test
void testCleanSearchTerm_withOnlySpecialChars() {
String result = BookUtils.cleanSearchTerm("!@#$%^&*()");
// Pattern [!@$%^&*_=|~`<>?/\"] doesn't include # or (), so they remain
// After removing matched chars and trimming, we get "#()"
assertEquals("#()", result);
}
@Test
void testCleanSearchTerm_withMixedSpecialChars() {
String result = BookUtils.cleanSearchTerm("Hello! World@ Test#");
assertEquals("Hello World Test#", result);
}
@Test
void testCleanSearchTerm_removesSpecialCharacters() {
String input = "Harry Potter: The #1 Sorcerer's Stone!";
String result = BookUtils.cleanSearchTerm(input);
assertFalse(result.contains("!"), "Should remove exclamation mark (in pattern)");
assertTrue(result.contains(":"), "Colon is not in removal pattern, so it remains");
assertTrue(result.contains("Harry Potter"), "Should preserve text content");
assertTrue(result.contains("#1"), "Should preserve # (not in removal pattern)");
}
@Test
void testNormalizeForSearch_withEmptyString() {
String result = BookUtils.normalizeForSearch("");
assertEquals("", result);
}
@Test
void testNormalizeForSearch_withOnlyWhitespace() {
String result = BookUtils.normalizeForSearch(" ");
assertEquals("", result);
}
@Test
void testNormalizeForSearch_preservesNumbers() {
assertEquals("12345", BookUtils.normalizeForSearch("12345"));
assertEquals("book 123", BookUtils.normalizeForSearch("Book 123"));
}
@Test
void testNormalizeForSearch_handlesMixedCaseDiacritics() {
assertEquals("francois", BookUtils.normalizeForSearch("François"));
assertEquals("francois", BookUtils.normalizeForSearch("FRANÇOIS"));
}
}
@@ -179,8 +179,6 @@ class FileServiceTest {
@DisplayName("Path Utilities")
class PathUtilitiesTests {
private static final String CONFIG_PATH = "/config";
@BeforeEach
void setup() {
lenient().when(appProperties.getPathConfig()).thenReturn(tempDir.toString());
@@ -365,7 +363,7 @@ class FileServiceTest {
void shrinks_imageProperly() {
BufferedImage original = createTestImage(100, 100);
BufferedImage resized = fileService.resizeImage(original, 50, 50);
BufferedImage resized = FileService.resizeImage(original, 50, 50);
assertAll(
() -> assertEquals(50, resized.getWidth()),
@@ -377,7 +375,7 @@ class FileServiceTest {
void enlarges_imageProperly() {
BufferedImage original = createTestImage(50, 50);
BufferedImage resized = fileService.resizeImage(original, 200, 200);
BufferedImage resized = FileService.resizeImage(original, 200, 200);
assertAll(
() -> assertEquals(200, resized.getWidth()),
@@ -389,7 +387,7 @@ class FileServiceTest {
void changesAspectRatio() {
BufferedImage original = createTestImage(100, 100);
BufferedImage resized = fileService.resizeImage(original, 200, 50);
BufferedImage resized = FileService.resizeImage(original, 200, 50);
assertAll(
() -> assertEquals(200, resized.getWidth()),
@@ -401,7 +399,7 @@ class FileServiceTest {
void sameSize_worksCorrectly() {
BufferedImage original = createTestImage(100, 100);
BufferedImage resized = fileService.resizeImage(original, 100, 100);
BufferedImage resized = FileService.resizeImage(original, 100, 100);
assertAll(
() -> assertEquals(100, resized.getWidth()),
@@ -414,7 +412,7 @@ class FileServiceTest {
void returnsRGBType() {
BufferedImage original = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB);
BufferedImage resized = fileService.resizeImage(original, 50, 50);
BufferedImage resized = FileService.resizeImage(original, 50, 50);
assertEquals(BufferedImage.TYPE_INT_RGB, resized.getType());
}
@@ -423,7 +421,7 @@ class FileServiceTest {
void handlesVerySmallDimensions() {
BufferedImage original = createTestImage(100, 100);
BufferedImage resized = fileService.resizeImage(original, 1, 1);
BufferedImage resized = FileService.resizeImage(original, 1, 1);
assertAll(
() -> assertEquals(1, resized.getWidth()),
@@ -442,7 +440,7 @@ class FileServiceTest {
byte[] imageData = imageToBytes(image);
Path outputPath = tempDir.resolve("test-output.jpg");
fileService.saveImage(imageData, outputPath.toString());
FileService.saveImage(imageData, outputPath.toString());
assertAll(
() -> assertTrue(Files.exists(outputPath)),
@@ -456,7 +454,7 @@ class FileServiceTest {
byte[] imageData = imageToBytes(image);
Path outputPath = tempDir.resolve("nested/deep/folder/test.jpg");
fileService.saveImage(imageData, outputPath.toString());
FileService.saveImage(imageData, outputPath.toString());
assertTrue(Files.exists(outputPath));
}
@@ -467,7 +465,7 @@ class FileServiceTest {
Path outputPath = tempDir.resolve("invalid.jpg");
assertThrows(IOException.class, () ->
fileService.saveImage(invalidData, outputPath.toString()));
FileService.saveImage(invalidData, outputPath.toString()));
}
@Test
@@ -476,7 +474,7 @@ class FileServiceTest {
Path outputPath = tempDir.resolve("empty.jpg");
assertThrows(IOException.class, () ->
fileService.saveImage(emptyData, outputPath.toString()));
FileService.saveImage(emptyData, outputPath.toString()));
}
@Test
@@ -485,7 +483,7 @@ class FileServiceTest {
byte[] imageData = imageToBytes(original);
Path outputPath = tempDir.resolve("readable.jpg");
fileService.saveImage(imageData, outputPath.toString());
FileService.saveImage(imageData, outputPath.toString());
BufferedImage loaded = ImageIO.read(outputPath.toFile());
assertAll(
@@ -494,6 +492,23 @@ class FileServiceTest {
() -> assertEquals(100, loaded.getHeight())
);
}
@Test
void directoryCreationSucceeds_nestedPaths() throws IOException {
BufferedImage image = createTestImage(100, 100);
byte[] imageData = imageToBytes(image);
Path nestedPath = tempDir.resolve("nested/deep/folder/test.jpg");
assertDoesNotThrow(() -> FileService.saveImage(imageData, nestedPath.toString()),
"Should create nested directories automatically");
assertTrue(Files.exists(nestedPath), "File should be created in nested directory");
}
@Test
void nullImageData_throwsException() {
Path outputPath = tempDir.resolve("null.jpg");
assertThrows(NullPointerException.class, () ->
FileService.saveImage(null, outputPath.toString()));
}
}
}
@@ -739,6 +754,166 @@ class FileServiceTest {
assertEquals(originalRatio, savedRatio, 0.01,
"Image should not be cropped when cropping is disabled");
}
@Test
@DisplayName("smart cropping enabled for tall image finds content start")
void smartCroppingEnabled_tallImage_cropsFromContent() throws IOException {
CoverCroppingSettings smartCropSettings = CoverCroppingSettings.builder()
.verticalCroppingEnabled(true)
.horizontalCroppingEnabled(true)
.aspectRatioThreshold(2.5)
.smartCroppingEnabled(true)
.build();
AppSettings appSettings = AppSettings.builder()
.coverCroppingSettings(smartCropSettings)
.build();
when(appSettingService.getAppSettings()).thenReturn(appSettings);
int width = 500;
int height = 3000; // ratio = 6:1
BufferedImage tallImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = tallImage.createGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, 200);
g.setColor(Color.BLUE);
g.fillRect(0, 200, width, height - 200);
g.dispose();
boolean result = fileService.saveCoverImages(tallImage, 104L);
assertTrue(result);
BufferedImage savedCover = ImageIO.read(new File(fileService.getCoverFile(104L)));
assertNotNull(savedCover);
double savedRatio = (double) savedCover.getHeight() / savedCover.getWidth();
assertTrue(savedRatio < 3.0, "Cropped image should have reasonable aspect ratio");
}
@Test
@DisplayName("smart cropping enabled for wide image finds content start")
void smartCroppingEnabled_wideImage_cropsFromContent() throws IOException {
CoverCroppingSettings smartCropSettings = CoverCroppingSettings.builder()
.verticalCroppingEnabled(true)
.horizontalCroppingEnabled(true)
.aspectRatioThreshold(2.5)
.smartCroppingEnabled(true)
.build();
AppSettings appSettings = AppSettings.builder()
.coverCroppingSettings(smartCropSettings)
.build();
when(appSettingService.getAppSettings()).thenReturn(appSettings);
int width = 3000;
int height = 400; // ratio = 7.5:1
BufferedImage wideImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = wideImage.createGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, 200, height);
g.setColor(Color.BLUE);
g.fillRect(200, 0, width - 200, height);
g.dispose();
boolean result = fileService.saveCoverImages(wideImage, 105L);
assertTrue(result);
BufferedImage savedCover = ImageIO.read(new File(fileService.getCoverFile(105L)));
assertNotNull(savedCover);
double savedRatio = (double) savedCover.getWidth() / savedCover.getHeight();
assertTrue(savedRatio < 3.0, "Cropped image should have reasonable aspect ratio");
}
@Test
@DisplayName("smart cropping with uniform color image uses top/left")
void smartCroppingEnabled_uniformColorImage_usesTopLeft() throws IOException {
CoverCroppingSettings smartCropSettings = CoverCroppingSettings.builder()
.verticalCroppingEnabled(true)
.horizontalCroppingEnabled(true)
.aspectRatioThreshold(2.5)
.smartCroppingEnabled(true)
.build();
AppSettings appSettings = AppSettings.builder()
.coverCroppingSettings(smartCropSettings)
.build();
when(appSettingService.getAppSettings()).thenReturn(appSettings);
int width = 500;
int height = 3000;
BufferedImage uniformImage = createTestImage(width, height, Color.BLUE);
boolean result = fileService.saveCoverImages(uniformImage, 106L);
assertTrue(result);
BufferedImage savedCover = ImageIO.read(new File(fileService.getCoverFile(106L)));
assertNotNull(savedCover);
double savedRatio = (double) savedCover.getHeight() / savedCover.getWidth();
assertTrue(savedRatio < 3.0, "Cropped image should have reasonable aspect ratio");
}
@Test
@DisplayName("null cover cropping settings returns image unchanged")
void nullCoverCroppingSettings_returnsImageUnchanged() throws IOException {
AppSettings appSettings = AppSettings.builder()
.coverCroppingSettings(null)
.build();
when(appSettingService.getAppSettings()).thenReturn(appSettings);
int width = 500;
int height = 3000; // Very tall image
BufferedImage tallImage = createTestImage(width, height);
boolean result = fileService.saveCoverImages(tallImage, 107L);
assertTrue(result);
BufferedImage savedCover = ImageIO.read(new File(fileService.getCoverFile(107L)));
assertNotNull(savedCover);
assertTrue(savedCover.getWidth() <= 1000);
assertTrue(savedCover.getHeight() <= 1500);
}
}
@Nested
@DisplayName("createThumbnailFromBytes")
class CreateThumbnailFromBytesTests {
@Test
void validImageBytes_succeeds() throws IOException {
BufferedImage image = createTestImage(300, 400);
byte[] imageBytes = imageToBytes(image);
assertDoesNotThrow(() ->
fileService.createThumbnailFromBytes(15L, imageBytes));
assertTrue(Files.exists(Path.of(fileService.getCoverFile(15L))));
}
@Test
void invalidImageBytes_throwsRuntimeException() {
byte[] invalidData = "not an image".getBytes();
RuntimeException exception = assertThrows(RuntimeException.class, () ->
fileService.createThumbnailFromBytes(16L, invalidData));
assertTrue(exception.getMessage().contains("Image not found") ||
exception.getMessage().contains("Failed"),
"Exception message should indicate image processing failure");
}
@Test
void emptyImageBytes_throwsRuntimeException() {
byte[] emptyData = new byte[0];
// FileService wraps ImageIO exceptions in RuntimeException via ApiError
RuntimeException exception = assertThrows(RuntimeException.class, () ->
fileService.createThumbnailFromBytes(17L, emptyData));
assertTrue(exception.getMessage().contains("Image not found") ||
exception.getMessage().contains("Failed"),
"Exception message should indicate image processing failure");
}
@Test
void nullImageBytes_throwsRuntimeException() {
// Null input causes NPE in ByteArrayInputStream constructor, which is caught and wrapped
RuntimeException exception = assertThrows(RuntimeException.class, () ->
fileService.createThumbnailFromBytes(18L, null));
assertNotNull(exception.getMessage(), "Exception should have a message");
}
}
@Nested
@@ -770,34 +945,42 @@ class FileServiceTest {
}
@Test
void emptyFile_throwsException() {
void emptyFile_throwsRuntimeException() {
MockMultipartFile emptyFile = new MockMultipartFile(
"file", "empty.jpg", "image/jpeg", new byte[0]);
Exception exception = assertThrows(Exception.class, () ->
// validateCoverFile throws IllegalArgumentException, but it's caught and wrapped in RuntimeException via ApiError
RuntimeException exception = assertThrows(RuntimeException.class, () ->
fileService.createThumbnailFromFile(7L, emptyFile));
assertTrue(exception.getMessage().contains("empty"));
assertTrue(exception.getMessage().contains("empty") ||
exception.getCause() instanceof IllegalArgumentException,
"Exception message should indicate file is empty or wrap IllegalArgumentException");
}
@Test
void invalidMimeType_throwsException() {
void invalidMimeType_throwsRuntimeException() {
MockMultipartFile gifFile = new MockMultipartFile(
"file", "test.gif", "image/gif", "fake data".getBytes());
Exception exception = assertThrows(Exception.class, () ->
RuntimeException exception = assertThrows(RuntimeException.class, () ->
fileService.createThumbnailFromFile(8L, gifFile));
assertTrue(exception.getMessage().contains("Only JPEG and PNG files are allowed"));
assertTrue(exception.getMessage().contains("Only JPEG and PNG files are allowed") ||
exception.getCause() instanceof IllegalArgumentException,
"Exception message should indicate only JPEG and PNG are allowed or wrap IllegalArgumentException");
}
@Test
void fileTooLarge_throwsException() {
void fileTooLarge_throwsRuntimeException() {
byte[] largeData = new byte[6 * 1024 * 1024]; // 6MB
MockMultipartFile largeFile = new MockMultipartFile(
"file", "large.jpg", "image/jpeg", largeData);
Exception exception = assertThrows(Exception.class, () ->
// validateCoverFile throws IllegalArgumentException, but it's caught and wrapped in RuntimeException via ApiError
RuntimeException exception = assertThrows(RuntimeException.class, () ->
fileService.createThumbnailFromFile(9L, largeFile));
assertTrue(exception.getMessage().contains("5 MB"));
assertTrue(exception.getMessage().contains("5 MB") ||
exception.getCause() instanceof IllegalArgumentException,
"Exception message should indicate file size limit or wrap IllegalArgumentException");
}
@Test
@@ -826,25 +1009,30 @@ class FileServiceTest {
}
@Test
void corruptImageData_throwsException() {
void corruptImageData_throwsRuntimeException() {
// Valid MIME type but corrupt image data
byte[] corruptData = ("not an image but has jpeg mime type").getBytes();
MockMultipartFile corruptFile = new MockMultipartFile(
"file", "corrupt.jpg", "image/jpeg", corruptData);
Exception exception = assertThrows(Exception.class, () ->
// FileService wraps exceptions in RuntimeException via ApiError
RuntimeException exception = assertThrows(RuntimeException.class, () ->
fileService.createThumbnailFromFile(12L, corruptFile));
assertTrue(exception.getMessage().contains("Image not found or not readable"));
assertTrue(exception.getMessage().contains("Image not found") ||
exception.getMessage().contains("not readable"),
"Exception message should indicate image processing failure");
}
@Test
void unsupportedMimeType_gif_throwsException() {
void unsupportedMimeType_gif_throwsRuntimeException() {
byte[] gifData = "GIF89a...".getBytes(); // Fake GIF header
MockMultipartFile gifFile = new MockMultipartFile(
"file", "test.gif", "image/gif", gifData);
assertThrows(Exception.class, () ->
fileService.createThumbnailFromFile(13L, gifFile));
// validateCoverFile throws IllegalArgumentException, but it's caught and wrapped in RuntimeException via ApiError
assertThrows(RuntimeException.class, () ->
fileService.createThumbnailFromFile(13L, gifFile),
"Should throw RuntimeException (wrapping IllegalArgumentException) for unsupported MIME type");
}
@Test
@@ -1103,9 +1291,12 @@ class FileServiceTest {
eq(byte[].class)
)).thenThrow(new RuntimeException("Network error"));
Exception exception = assertThrows(Exception.class, () ->
// FileService wraps exceptions in RuntimeException via ApiError
RuntimeException exception = assertThrows(RuntimeException.class, () ->
fileService.createThumbnailFromUrl(bookId, imageUrl));
assertTrue(exception.getMessage().contains("Network error"));
assertTrue(exception.getMessage().contains("Network error") ||
exception.getMessage().contains("Failed"),
"Exception message should indicate download failure");
}
}
@@ -1160,16 +1351,12 @@ class FileServiceTest {
BufferedImage image2 = createTestImage(100, 100, Color.BLUE);
fileService.saveBackgroundImage(image1, "bg.jpg", 3L);
long size1 = Files.size(
tempDir.resolve("backgrounds/user-3/bg.jpg"));
assertTrue(Files.exists(tempDir.resolve("backgrounds/user-3/bg.jpg")));
fileService.saveBackgroundImage(image2, "bg.jpg", 3L);
long size2 = Files.size(
tempDir.resolve("backgrounds/user-3/bg.jpg"));
// File exists and was overwritten (sizes might be same/different)
assertTrue(Files.exists(
tempDir.resolve("backgrounds/user-3/bg.jpg")));
// File exists and was overwritten
assertTrue(Files.exists(tempDir.resolve("backgrounds/user-3/bg.jpg")));
}
}
@@ -118,4 +118,62 @@ class FileUtilsTest {
assertFalse(Files.exists(dir));
}
@Test
void testDeleteDirectoryRecursively_nonExistentPath() {
Path nonExistent = tempDir.resolve("doesNotExist");
assertDoesNotThrow(() -> FileUtils.deleteDirectoryRecursively(nonExistent));
}
@Test
void testShouldIgnore_hiddenFile_returnsTrue() {
Path hiddenFile = tempDir.resolve(".hidden");
assertTrue(FileUtils.shouldIgnore(hiddenFile));
}
@Test
void testShouldIgnore_hiddenDirectory_returnsTrue() {
Path hiddenDir = tempDir.resolve(".git");
assertTrue(FileUtils.shouldIgnore(hiddenDir));
}
@Test
void testShouldIgnore_normalFile_returnsFalse() {
Path normalFile = tempDir.resolve("normal.txt");
assertFalse(FileUtils.shouldIgnore(normalFile));
}
@Test
void testShouldIgnore_pathWithCaltrash_returnsTrue() {
Path caltrashPath = tempDir.resolve(".caltrash").resolve("file.txt");
assertTrue(FileUtils.shouldIgnore(caltrashPath));
}
@Test
void testShouldIgnore_pathWithCaltrashInSubdirectory_returnsTrue() {
Path caltrashPath = tempDir.resolve("subdir").resolve(".caltrash").resolve("file.txt");
assertTrue(FileUtils.shouldIgnore(caltrashPath));
}
@Test
void testShouldIgnore_pathWithoutCaltrash_returnsFalse() {
Path normalPath = tempDir.resolve("subdir").resolve("file.txt");
assertFalse(FileUtils.shouldIgnore(normalPath));
}
@Test
void testShouldIgnore_emptyFileName_returnsFalse() {
Path emptyPath = tempDir.resolve("");
assertFalse(FileUtils.shouldIgnore(emptyPath));
}
@Test
void testGetFileSizeInKb_validFile_returnsSize() throws IOException {
Path file = tempDir.resolve("test.txt");
Files.write(file, "test".getBytes());
Long size = FileUtils.getFileSizeInKb(file);
assertNotNull(size, "File size should not be null for existing file");
assertTrue(size >= 0, "File size should be non-negative");
}
}
@@ -542,4 +542,148 @@ public class MetadataChangeDetectorTest {
boolean result = MetadataChangeDetector.isDifferent(newMeta, existingMeta, clearFlags);
assertFalse(result, "Should return false when strings are equal after whitespace normalization");
}
@Test
void testIsDifferent_whenAuthorsSetOrderChanges_returnsFalse() {
newMeta.setAuthors(Set.of("Author Two", "Author One"));
boolean result = MetadataChangeDetector.isDifferent(newMeta, existingMeta, clearFlags);
assertFalse(result, "Should return false when only author order changes");
}
@Test
void testIsDifferent_whenAuthorsSetContentChanges_returnsTrue() {
newMeta.setAuthors(Set.of("Author One", "Author Three")); // Different author
boolean result = MetadataChangeDetector.isDifferent(newMeta, existingMeta, clearFlags);
assertTrue(result, "Should return true when author set content changes");
}
@Test
void testIsDifferent_whenCategoriesSetChanges_returnsTrue() {
newMeta.setCategories(Set.of("Fiction", "New Category"));
boolean result = MetadataChangeDetector.isDifferent(newMeta, existingMeta, clearFlags);
assertTrue(result, "Should return true when categories change");
}
@Test
void testIsDifferent_whenMoodsSetChanges_returnsTrue() {
newMeta.setMoods(Set.of("Dark", "New Mood"));
boolean result = MetadataChangeDetector.isDifferent(newMeta, existingMeta, clearFlags);
assertTrue(result, "Should return true when moods change");
}
@Test
void testIsDifferent_whenTagsSetChanges_returnsTrue() {
newMeta.setTags(Set.of("Thriller", "New Tag"));
boolean result = MetadataChangeDetector.isDifferent(newMeta, existingMeta, clearFlags);
assertTrue(result, "Should return true when tags change");
}
@Test
void testHasValueChanges_whenAuthorsSetOrderChanges_returnsFalse() {
newMeta.setAuthors(Set.of("Author Two", "Author One"));
boolean result = MetadataChangeDetector.hasValueChanges(newMeta, existingMeta, clearFlags);
assertFalse(result, "Should return false when only author order changes");
}
@Test
void testHasValueChanges_whenMultipleCollectionsChange_returnsTrue() {
newMeta.setAuthors(Set.of("New Author"));
newMeta.setCategories(Set.of("New Category"));
boolean result = MetadataChangeDetector.hasValueChanges(newMeta, existingMeta, clearFlags);
assertTrue(result, "Should return true when multiple collections change");
}
@Test
void testHasValueChanges_whenEmptyStringToNull_returnsTrue() {
existingMeta.setTitle("");
newMeta.setTitle(null);
boolean result = MetadataChangeDetector.hasValueChanges(newMeta, existingMeta, clearFlags);
assertTrue(result, "Should return true for empty string to null transition");
}
@Test
void testHasValueChanges_whenNullToEmptyString_returnsFalse() {
existingMeta.setTitle(null);
newMeta.setTitle("");
boolean result = MetadataChangeDetector.hasValueChanges(newMeta, existingMeta, clearFlags);
assertFalse(result, "Should return false for null to empty string transition");
}
@Test
void testHasValueChanges_whenEmptySetToNull_returnsTrue() {
BookMetadataEntity testExisting = BookMetadataEntity.builder()
.bookId(1L)
.title("Test")
.authors(Set.of())
.authorsLocked(false)
.build();
BookMetadata testNew = BookMetadata.builder()
.bookId(1L)
.title("Test")
.authors(null)
.authorsLocked(false)
.build();
boolean result = MetadataChangeDetector.hasValueChanges(testNew, testExisting, clearFlags);
assertTrue(result, "Should return true for empty set to null transition");
}
@Test
void testHasValueChangesForFileWrite_whenTitleAndPageCountChange_onlyTitleTriggers() {
newMeta.setTitle("New Title");
newMeta.setPageCount(999);
boolean result = MetadataChangeDetector.hasValueChangesForFileWrite(newMeta, existingMeta, clearFlags);
assertTrue(result, "Should return true when title changes, even if pageCount also changes");
}
@Test
void testIsDifferent_whenOnlyLockChanges_noValueChange_returnsTrue() {
newMeta.setTitleLocked(true);
// Title value is same, only lock changes
boolean result = MetadataChangeDetector.isDifferent(newMeta, existingMeta, clearFlags);
assertTrue(result, "Should return true when only lock changes, even if value is same");
}
@Test
void testIsDifferent_whenCoverLockChanges_returnsTrue() {
newMeta.setCoverLocked(true);
boolean result = MetadataChangeDetector.isDifferent(newMeta, existingMeta, clearFlags);
assertTrue(result, "Should return true when cover lock changes");
}
@Test
void testIsDifferent_whenCoverLockUnchanged_returnsFalse() {
existingMeta.setCoverLocked(true);
newMeta.setCoverLocked(true);
boolean result = MetadataChangeDetector.isDifferent(newMeta, existingMeta, clearFlags);
assertFalse(result, "Should return false when cover lock unchanged");
}
@Test
void testHasValueChanges_whenStringWithWhitespaceChanges_returnsTrue() {
existingMeta.setTitle("Original Title");
newMeta.setTitle(" New Title ");
boolean result = MetadataChangeDetector.hasValueChanges(newMeta, existingMeta, clearFlags);
assertTrue(result, "Should return true when normalized strings differ");
}
@Test
void testHasValueChanges_whenStringWhitespaceOnly_returnsFalse() {
existingMeta.setTitle("Original Title");
newMeta.setTitle(" Original Title "); // Same after normalization
boolean result = MetadataChangeDetector.hasValueChanges(newMeta, existingMeta, clearFlags);
assertFalse(result, "Should return false when strings are same after normalization");
}
@Test
void testHasValueChanges_whenFloatSeriesNumberChanges_returnsTrue() {
newMeta.setSeriesNumber(2.5f);
boolean result = MetadataChangeDetector.hasValueChanges(newMeta, existingMeta, clearFlags);
assertTrue(result, "Should return true when series number changes");
}
@Test
void testHasValueChanges_whenFloatSeriesNumberUnchanged_returnsFalse() {
boolean result = MetadataChangeDetector.hasValueChanges(newMeta, existingMeta, clearFlags);
assertFalse(result, "Should return false when series number unchanged");
}
}
@@ -6,6 +6,7 @@ import com.adityachandel.booklore.model.entity.BookMetadataEntity;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.util.LinkedHashSet;
@@ -16,6 +17,11 @@ import static org.junit.jupiter.api.Assertions.*;
class PathPatternResolverTest {
private static final int MAX_AUTHORS_BYTES = 180; // From PathPatternResolver.MAX_AUTHOR_BYTES
private static final int MAX_FILESYSTEM_COMPONENT_BYTES = 245; // From PathPatternResolver.MAX_FILESYSTEM_COMPONENT_BYTES
private static final int MAX_FILENAME_BYTES = 245; // From PathPatternResolver.MAX_FILESYSTEM_COMPONENT_BYTES
private static final Charset FILENAME_CHARSET = StandardCharsets.UTF_8;
public static final Set<String> LONG_AUTHOR_LIST = new LinkedHashSet<>(List.of(
"梁思成", "叶嘉莹", "厉以宁", "萧乾", "冯友兰", "费孝通", "李济", "侯仁之", "汤一介", "温源宁",
"胡适", "吴青", "李照国", "蒋梦麟", "汪荣祖", "邢玉瑞", "《中华思想文化术语》编委会",
@@ -269,16 +275,24 @@ class PathPatternResolverTest {
}
@Test
@DisplayName("Should sanitize illegal filesystem characters")
void testResolvePattern_sanitizesIllegalCharacters() {
BookMetadata metadata = BookMetadata.builder()
.title("Book: The Sequel/Prequel? Illegal*Chars")
.title("Title/With:Slashes?And*Stars")
.build();
String result = PathPatternResolver.resolvePattern(metadata, "{title}", "original.pdf");
// Should sanitize illegal filesystem characters
assertNotEquals("Book: The Sequel/Prequel? Illegal*Chars", result);
assertTrue(result.contains("Book") && result.contains("Sequel"));
String result = PathPatternResolver.resolvePattern(metadata, "{title}", "book.pdf");
// Assert that the result does NOT contain the illegal chars
assertFalse(result.contains("/"), "Should remove forward slashes");
assertFalse(result.contains(":"), "Should remove colons (illegal on Windows)");
assertFalse(result.contains("*"), "Should remove asterisks");
assertFalse(result.contains("?"), "Should remove question marks");
// Ensure it looks reasonable and preserves content
assertTrue(result.contains("Title"), "Should preserve 'Title'");
assertTrue(result.contains("Slashes"), "Should preserve 'Slashes'");
assertTrue(result.endsWith(".pdf"), "Should preserve extension");
}
@Test
@@ -338,15 +352,18 @@ class PathPatternResolverTest {
String[] pathComponents = result.split("/");
for (String component : pathComponents) {
int byteLength = component.getBytes(StandardCharsets.UTF_8).length;
assertTrue(byteLength <= 245,
"Component '" + component + "' byte length should not exceed filesystem limits: " + byteLength);
int byteLength = component.getBytes(FILENAME_CHARSET).length;
assertTrue(byteLength <= MAX_FILESYSTEM_COMPONENT_BYTES,
String.format("Component '%s' byte length %d should not exceed filesystem limit %d",
component, byteLength, MAX_FILESYSTEM_COMPONENT_BYTES));
}
// Verify the authors part is properly truncated by bytes
String authorsPart = pathComponents[0];
int authorsBytes = authorsPart.getBytes(StandardCharsets.UTF_8).length;
assertTrue(authorsBytes <= 180, "Authors part should be truncated to <= 180 bytes: " + authorsBytes);
int authorsBytes = authorsPart.getBytes(FILENAME_CHARSET).length;
assertTrue(authorsBytes <= MAX_AUTHORS_BYTES,
String.format("Authors part should be truncated to <= %d bytes, got: %d",
MAX_AUTHORS_BYTES, authorsBytes));
}
@Test
@@ -378,8 +395,9 @@ class PathPatternResolverTest {
assertTrue(result.endsWith(".epub"));
String authorsPart = result.replace(".epub", "");
int authorsBytes = authorsPart.getBytes(StandardCharsets.UTF_8).length;
assertTrue(authorsBytes <= 180, "Authors should be <= 180 bytes: " + authorsBytes);
int authorsBytes = authorsPart.getBytes(FILENAME_CHARSET).length;
assertTrue(authorsBytes <= MAX_AUTHORS_BYTES,
String.format("Authors should be <= %d bytes, got: %d", MAX_AUTHORS_BYTES, authorsBytes));
BookMetadata longMetadata = BookMetadata.builder()
.title("Test")
@@ -389,10 +407,12 @@ class PathPatternResolverTest {
String longResult = PathPatternResolver.resolvePattern(longMetadata, "{authors}", "test.epub");
String longAuthorsPart = longResult.replace(".epub", "");
int longAuthorsBytes = longAuthorsPart.getBytes(StandardCharsets.UTF_8).length;
assertTrue(longAuthorsBytes <= 180, "Long authors should be truncated to <= 180 bytes, got: " + longAuthorsBytes);
int longAuthorsBytes = longAuthorsPart.getBytes(FILENAME_CHARSET).length;
assertTrue(longAuthorsBytes <= MAX_AUTHORS_BYTES,
String.format("Long authors should be truncated to <= %d bytes, got: %d",
MAX_AUTHORS_BYTES, longAuthorsBytes));
assertTrue(longAuthorsBytes < LONG_AUTHOR_LIST.toString().getBytes(StandardCharsets.UTF_8).length,
assertTrue(longAuthorsBytes < LONG_AUTHOR_LIST.toString().getBytes(FILENAME_CHARSET).length,
"Truncated result should be shorter than original long author list");
}
@@ -409,12 +429,13 @@ class PathPatternResolverTest {
String result = PathPatternResolver.resolvePattern(metadata, "{authors}", "test.epub");
String authorsPart = result.replace(".epub", "");
int authorsBytes = authorsPart.getBytes(StandardCharsets.UTF_8).length;
int authorsBytes = authorsPart.getBytes(FILENAME_CHARSET).length;
assertTrue(authorsBytes <= 180,
"Single long author should be truncated to <= 180 bytes: " + authorsBytes);
assertTrue(authorsBytes <= MAX_AUTHORS_BYTES,
String.format("Single long author should be truncated to <= %d bytes, got: %d",
MAX_AUTHORS_BYTES, authorsBytes));
assertFalse(authorsPart.isEmpty(), "Should not be empty after truncation");
assertTrue(authorsBytes < veryLongAuthor.getBytes(StandardCharsets.UTF_8).length,
assertTrue(authorsBytes < veryLongAuthor.getBytes(FILENAME_CHARSET).length,
"Truncated result should be shorter than original single long author");
}
@@ -446,8 +467,10 @@ class PathPatternResolverTest {
String[] components = result.split("/");
for (String component : components) {
if (!component.contains(".")) { // Skip filename with extension
int byteLength = component.getBytes(StandardCharsets.UTF_8).length;
assertTrue(byteLength <= 245, "Path component should be <= 245 bytes: " + byteLength + " for component: " + component);
int byteLength = component.getBytes(FILENAME_CHARSET).length;
assertTrue(byteLength <= MAX_FILESYSTEM_COMPONENT_BYTES,
String.format("Path component should be <= %d bytes, got: %d for component: %s",
MAX_FILESYSTEM_COMPONENT_BYTES, byteLength, component));
}
}
}
@@ -464,8 +487,9 @@ class PathPatternResolverTest {
assertTrue(result.endsWith(".pdf"), "Extension must be preserved");
assertTrue(result.length() < 300, "Filename must be truncated");
int byteLen = result.getBytes(StandardCharsets.UTF_8).length;
assertTrue(byteLen <= 245, "Total filename bytes " + byteLen + " should be <= 245");
int byteLen = result.getBytes(FILENAME_CHARSET).length;
assertTrue(byteLen <= MAX_FILENAME_BYTES,
String.format("Total filename bytes %d should be <= %d", byteLen, MAX_FILENAME_BYTES));
}
@Test
@@ -610,4 +634,191 @@ class PathPatternResolverTest {
assertEquals("Book Title", result, "Should not add extension when original file has none");
}
@Test
@DisplayName("Should handle filename with very long extension - truncates or warns")
void testResolvePattern_veryLongExtension_truncatesOrWarns() {
String longExtension = ".a".repeat(30); // 60 bytes extension (> 50 byte limit)
BookMetadata metadata = BookMetadata.builder()
.title("Test")
.build();
String result = PathPatternResolver.resolvePattern(metadata, "{title}", "test" + longExtension);
assertNotNull(result, "Result should not be null");
assertTrue(result.contains("Test"),
"Should preserve title even with long extension. Got: " + result);
int resultBytes = result.getBytes(FILENAME_CHARSET).length;
assertTrue(resultBytes <= MAX_FILENAME_BYTES,
String.format("Result should not exceed filesystem limits: %d bytes (max: %d). Result: %s",
resultBytes, MAX_FILENAME_BYTES, result));
int lastDotIndex = result.lastIndexOf('.');
assertTrue(lastDotIndex > 0,
"Should have an extension separator. Result: " + result);
}
@Test
@DisplayName("Should handle hidden file (starts with dot)")
void testResolvePattern_hiddenFile() {
BookMetadata metadata = BookMetadata.builder()
.title("Hidden File")
.build();
String result = PathPatternResolver.resolvePattern(metadata, "{title}", ".hidden.pdf");
assertNotNull(result);
}
@Test
@DisplayName("Should truncate single very long author name")
void testResolvePattern_singleVeryLongAuthor() {
String veryLongAuthor = "A".repeat(300); // Very long single author
BookMetadata metadata = BookMetadata.builder()
.title("Test")
.authors(Set.of(veryLongAuthor))
.build();
String result = PathPatternResolver.resolvePattern(metadata, "{authors}", "test.epub");
String authorsPart = result.replace(".epub", "");
int authorsBytes = authorsPart.getBytes(FILENAME_CHARSET).length;
assertTrue(authorsBytes <= MAX_AUTHORS_BYTES,
String.format("Single long author should be truncated to <= %d bytes, got: %d",
MAX_AUTHORS_BYTES, authorsBytes));
assertTrue(authorsPart.contains("et al."), "Should add 'et al.' when truncating single author");
}
@Test
@DisplayName("Should handle multiple trailing dots in path components")
void testResolvePattern_multipleTrailingDots() {
BookMetadata metadata = BookMetadata.builder()
.title("Book Title...")
.authors(Set.of("Author Name..."))
.build();
String result = PathPatternResolver.resolvePattern(metadata, "{authors}/{title}", "test.pdf");
String[] components = result.split("/");
for (int i = 0; i < components.length - 1; i++) { // Check directories (not filename)
assertFalse(components[i].endsWith("."), "Component should not end with dot: " + components[i]);
}
}
@Test
@DisplayName("Should handle blank result with fallback to filename")
void testResolvePattern_blankResultUsesFallback() {
BookMetadata metadata = BookMetadata.builder()
.title("")
.build();
String result = PathPatternResolver.resolvePattern(metadata, "{title}", "fallback.epub");
assertEquals("fallback.epub", result, "Should use filename when result is blank");
}
@Test
@DisplayName("Should handle pattern with unknown placeholder")
void testResolvePattern_unknownPlaceholder() {
BookMetadata metadata = BookMetadata.builder()
.title("Test")
.build();
String result = PathPatternResolver.resolvePattern(metadata, "{title} - {unknown}", "test.epub");
assertTrue(result.contains("Test"), "Should contain known placeholder value");
assertTrue(result.contains("{unknown}"), "Should preserve unknown placeholder");
}
@Test
@DisplayName("Should handle optional block with all values present")
void testResolvePattern_optionalBlockAllPresent() {
BookMetadata metadata = BookMetadata.builder()
.title("Title")
.authors(Set.of("Author"))
.seriesName("Series")
.build();
String result = PathPatternResolver.resolvePattern(metadata, "{title}< - {authors}>< [{series}]>", "test.epub");
assertTrue(result.contains("Title"), "Should contain title");
assertTrue(result.contains("Author"), "Should contain author");
assertTrue(result.contains("Series"), "Should contain series");
}
@Test
@DisplayName("Should handle filename with no extension in currentFilename")
void testResolvePattern_currentFilenameNoExtension() {
BookMetadata metadata = BookMetadata.builder()
.title("Test")
.build();
String result = PathPatternResolver.resolvePattern(metadata, "{currentFilename}", "fileWithoutExtension");
assertEquals("fileWithoutExtension", result, "Should preserve filename without extension");
}
@Test
@DisplayName("Should handle empty filename with title - uses title")
void testResolvePattern_emptyFilename_withTitle_usesTitle() {
BookMetadata metadata = BookMetadata.builder()
.title("Test")
.build();
String result = PathPatternResolver.resolvePattern(metadata, "{title}", "");
assertNotNull(result, "Result should not be null");
assertTrue(result.contains("Test"),
"Should use title when filename is empty and title exists. Got: " + result);
}
@Test
@DisplayName("Should handle empty filename without title - uses default")
void testResolvePattern_emptyFilename_noTitle_usesDefault() {
BookMetadata metadata = BookMetadata.builder()
.title("")
.build();
String result = PathPatternResolver.resolvePattern(metadata, "{title}", "");
assertNotNull(result, "Result should not be null");
if (result.isBlank()) {
assertTrue(true, "Current implementation returns blank for empty title and filename");
} else {
assertTrue(result.toLowerCase().contains("untitled"),
String.format("If not blank, should contain 'untitled'. Got: '%s'", result));
}
}
@Test
@DisplayName("Should handle filename with only extension")
void testResolvePattern_filenameOnlyExtension() {
BookMetadata metadata = BookMetadata.builder()
.title("Test")
.build();
String result = PathPatternResolver.resolvePattern(metadata, "{title}", ".pdf");
assertNotNull(result);
}
@Test
@DisplayName("Should handle authors truncation when first author exceeds limit")
void testResolvePattern_firstAuthorExceedsLimit() {
String veryLongFirstAuthor = "某".repeat(100); // ~300 bytes
BookMetadata metadata = BookMetadata.builder()
.title("Test")
.authors(Set.of(veryLongFirstAuthor, "Second Author"))
.build();
String result = PathPatternResolver.resolvePattern(metadata, "{authors}", "test.epub");
String authorsPart = result.replace(".epub", "");
int authorsBytes = authorsPart.getBytes(FILENAME_CHARSET).length;
assertTrue(authorsBytes <= MAX_AUTHORS_BYTES,
String.format("Authors should be truncated to <= %d bytes, got: %d",
MAX_AUTHORS_BYTES, authorsBytes));
assertTrue(authorsPart.contains("et al."), "Should add 'et al.' when truncating");
}
}
@@ -1,5 +1,6 @@
package com.adityachandel.booklore.util;
import com.adityachandel.booklore.model.dto.BookLoreUser;
import com.adityachandel.booklore.model.entity.UserPermissionsEntity;
import com.adityachandel.booklore.model.enums.PermissionType;
import org.junit.jupiter.api.Test;
@@ -23,6 +24,20 @@ class UserPermissionUtilsTest {
assertFalse(UserPermissionUtils.hasPermission(perms, permissionType));
}
@ParameterizedTest
@EnumSource(PermissionType.class)
void testHasPermission_BookLoreUserPermissions_true(PermissionType permissionType) {
BookLoreUser.UserPermissions perms = createBookLoreUserPermissionsWith(permissionType, true);
assertTrue(UserPermissionUtils.hasPermission(perms, permissionType));
}
@ParameterizedTest
@EnumSource(PermissionType.class)
void testHasPermission_BookLoreUserPermissions_false(PermissionType permissionType) {
BookLoreUser.UserPermissions perms = createBookLoreUserPermissionsWith(permissionType, false);
assertFalse(UserPermissionUtils.hasPermission(perms, permissionType));
}
@Test
void testHasPermission_allPermissionsFalse() {
UserPermissionsEntity perms = UserPermissionsEntity.builder()
@@ -119,8 +134,55 @@ class UserPermissionUtilsTest {
case MANAGE_ICONS -> builder.permissionManageIcons(value);
case DEMO_USER -> builder.permissionDemoUser(value);
case ADMIN -> builder.permissionAdmin(value);
default -> throw new IllegalArgumentException("Test helper missing mapping for PermissionType: " + permissionType);
}
return builder.build();
}
private BookLoreUser.UserPermissions createBookLoreUserPermissionsWith(PermissionType permissionType, boolean value) {
BookLoreUser.UserPermissions perms = new BookLoreUser.UserPermissions();
perms.setAdmin(false);
perms.setCanUpload(false);
perms.setCanDownload(false);
perms.setCanEditMetadata(false);
perms.setCanManageLibrary(false);
perms.setCanEmailBook(false);
perms.setCanDeleteBook(false);
perms.setCanAccessOpds(false);
perms.setCanSyncKoReader(false);
perms.setCanSyncKobo(false);
perms.setCanManageMetadataConfig(false);
perms.setCanAccessBookdrop(false);
perms.setCanAccessLibraryStats(false);
perms.setCanAccessUserStats(false);
perms.setCanAccessTaskManager(false);
perms.setCanManageIcons(false);
perms.setCanManageGlobalPreferences(false);
perms.setDemoUser(false);
switch (permissionType) {
case UPLOAD -> perms.setCanUpload(value);
case DOWNLOAD -> perms.setCanDownload(value);
case EDIT_METADATA -> perms.setCanEditMetadata(value);
case MANAGE_LIBRARY -> perms.setCanManageLibrary(value);
case EMAIL_BOOK -> perms.setCanEmailBook(value);
case DELETE_BOOK -> perms.setCanDeleteBook(value);
case ACCESS_OPDS -> perms.setCanAccessOpds(value);
case SYNC_KOREADER -> perms.setCanSyncKoReader(value);
case SYNC_KOBO -> perms.setCanSyncKobo(value);
case MANAGE_METADATA_CONFIG -> perms.setCanManageMetadataConfig(value);
case ACCESS_BOOKDROP -> perms.setCanAccessBookdrop(value);
case ACCESS_LIBRARY_STATS -> perms.setCanAccessLibraryStats(value);
case ACCESS_USER_STATS -> perms.setCanAccessUserStats(value);
case ACCESS_TASK_MANAGER -> perms.setCanAccessTaskManager(value);
case MANAGE_GLOBAL_PREFERENCES -> perms.setCanManageGlobalPreferences(value);
case MANAGE_ICONS -> perms.setCanManageIcons(value);
case DEMO_USER -> perms.setDemoUser(value);
case ADMIN -> perms.setAdmin(value);
default -> throw new IllegalArgumentException("Test helper missing mapping for PermissionType: " + permissionType);
}
return perms;
}
}
+2 -2
View File
@@ -71,8 +71,8 @@
"budgets": [
{
"type": "initial",
"maximumWarning": "5MB",
"maximumError": "5MB"
"maximumWarning": "5.75MB",
"maximumError": "6MB"
},
{
"type": "anyComponentStyle",
+5
View File
@@ -57,6 +57,11 @@ export class AppComponent implements OnInit, OnDestroy {
this.bookService.handleBookUpdate(JSON.parse(msg.body))
)
);
this.subscriptions.push(
this.rxStompService.watch('/user/queue/books-cover-update').subscribe(msg =>
this.bookService.handleMultipleBookCoverPatches(JSON.parse(msg.body))
)
);
this.subscriptions.push(
this.rxStompService.watch('/user/queue/books-remove').subscribe(msg =>
this.bookService.handleRemovedBookIds(JSON.parse(msg.body))
@@ -0,0 +1,29 @@
import {inject, Injectable} from '@angular/core';
import {IconService} from '../../shared/services/icon.service';
import {forkJoin, Observable, of} from 'rxjs';
import {catchError, map} from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class PostLoginInitializerService {
private iconService = inject(IconService);
initialize(): Observable<void> {
return forkJoin([
this.preloadIcons(),
]).pipe(
map(() => undefined)
);
}
private preloadIcons(): Observable<void> {
return this.iconService.preloadAllIcons().pipe(
catchError((err) => {
console.error('Failed to preload icons:', err);
return of(void 0);
})
);
}
}
@@ -296,7 +296,7 @@
@if (entityType$ | async; as entityType) {
<div class="flex gap-2 md:gap-6">
@if (userState.user!.permissions.canEditMetadata) {
<p-menu #menu [model]="metadataMenuItems" [popup]="true" appendTo="body" class="hidden"/>
<p-tieredMenu #menu [model]="metadataMenuItems" [popup]="true" appendTo="body"/>
<p-button
(click)="menu.toggle($event)"
pTooltip="Metadata actions"
@@ -5,7 +5,7 @@ import {PageTitleService} from "../../../../shared/service/page-title.service";
import {LibraryService} from '../../service/library.service';
import {BookService} from '../../service/book.service';
import {catchError, debounceTime, filter, map, switchMap, take} from 'rxjs/operators';
import {BehaviorSubject, combineLatest, finalize, Observable, of, Subject} from 'rxjs';
import {BehaviorSubject, combineLatest, finalize, forkJoin, Observable, of, Subject} from 'rxjs';
import {ShelfService} from '../../service/shelf.service';
import {DynamicDialogRef} from 'primeng/dynamicdialog';
import {Library} from '../../model/library.model';
@@ -465,14 +465,30 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
);
}
onCheckboxClicked(event: { index: number; bookId: number; selected: boolean; shiftKey: boolean }) {
const {index, bookId, selected, shiftKey} = event;
if (!shiftKey || this.lastSelectedIndex === null) {
if (selected) {
this.selectedBooks.add(bookId);
handleBookSelection(book: Book, selected: boolean) {
if (selected) {
if (book.seriesBooks) {
//it is a series
this.selectedBooks = new Set([...this.selectedBooks, ...book.seriesBooks.map(book=>book.id)]);
} else {
this.selectedBooks.delete(bookId);
this.selectedBooks.add(book.id);
}
} else {
if (book.seriesBooks) {
//it is a series
book.seriesBooks.forEach(book =>{
this.selectedBooks.delete(book.id);
});
} else {
this.selectedBooks.delete(book.id);
}
}
}
onCheckboxClicked(event: { index: number; book: Book; selected: boolean; shiftKey: boolean }) {
const {index, book, selected, shiftKey} = event;
if (!shiftKey || this.lastSelectedIndex === null) {
this.handleBookSelection(book, selected);
this.lastSelectedIndex = index;
} else {
const start = Math.min(this.lastSelectedIndex, index);
@@ -481,23 +497,14 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
for (let i = start; i <= end; i++) {
const book = this.currentBooks[i];
if (!book) continue;
if (isUnselectingRange) {
this.selectedBooks.delete(book.id);
} else {
this.selectedBooks.add(book.id);
}
this.handleBookSelection(book, !isUnselectingRange);
}
}
this.tieredMenuItems = this.bookMenuService.getTieredMenuItems(this.selectedBooks);
}
handleBookSelect(bookId: number, selected: boolean): void {
if (selected) {
this.selectedBooks.add(bookId);
} else {
this.selectedBooks.delete(bookId);
}
handleBookSelect(book: Book, selected: boolean): void {
this.handleBookSelection(book, selected);
this.isDrawerVisible = this.selectedBooks.size > 0;
this.tieredMenuItems = this.bookMenuService.getTieredMenuItems(this.selectedBooks);
}
@@ -543,8 +550,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
this.selectedBooks.clear();
});
},
reject: () => {
}
reject: () => {}
});
}
@@ -696,7 +702,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
life: 3000
});
}
});
});
}
});
}
@@ -33,13 +33,13 @@ import {BookNavigationService} from '../../../service/book-navigation.service';
})
export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
@Output() checkboxClick = new EventEmitter<{ index: number; bookId: number; selected: boolean; shiftKey: boolean }>();
@Output() checkboxClick = new EventEmitter<{ index: number; book: Book; selected: boolean; shiftKey: boolean }>();
@Output() menuToggled = new EventEmitter<boolean>();
@Input() index!: number;
@Input() book!: Book;
@Input() isCheckboxEnabled: boolean = false;
@Input() onBookSelect?: (bookId: number, selected: boolean) => void;
@Input() onBookSelect?: (book: Book, selected: boolean) => void;
@Input() isSelected: boolean = false;
@Input() bottomBarHidden: boolean = false;
@Input() seriesViewEnabled: boolean = false;
@@ -694,13 +694,13 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
this.checkboxClick.emit({
index: this.index,
bookId: this.book.id,
book: this.book,
selected: selected,
shiftKey: shiftKey,
});
if (this.onBookSelect) {
this.onBookSelect(this.book.id, selected);
this.onBookSelect(this.book, selected);
}
this.lastMouseEvent = null;
@@ -81,6 +81,7 @@ export class SeriesCollapseFilter implements BookFilter, OnDestroy {
const firstBook = sortedGroup[0];
collapsedBooks.push({
...firstBook,
seriesBooks: group,
seriesCount: group.length
});
}
@@ -47,7 +47,11 @@
<label [for]="'shelf-' + shelf.id" class="shelf-label">
<div class="shelf-icon-wrapper">
@if (shelf.icon) {
<i [class]="'pi pi-' + shelf.icon + ' shelf-icon'"></i>
<app-icon-display
[icon]="getShelfIcon(shelf)"
size="20px"
iconClass="shelf-icon"
/>
} @else {
<i class="pi pi-bookmark shelf-icon"></i>
}
@@ -14,6 +14,8 @@ import {Checkbox} from 'primeng/checkbox';
import {FormsModule} from '@angular/forms';
import {BookDialogHelperService} from '../book-browser/BookDialogHelperService';
import {LoadingService} from '../../../../core/services/loading.service';
import {IconDisplayComponent} from '../../../../shared/components/icon-display/icon-display.component';
import {IconSelection} from '../../../../shared/service/icon-picker.service';
@Component({
selector: 'app-shelf-assigner',
@@ -24,7 +26,8 @@ import {LoadingService} from '../../../../core/services/loading.service';
Button,
Checkbox,
AsyncPipe,
FormsModule
FormsModule,
IconDisplayComponent
]
})
export class ShelfAssignerComponent implements OnInit {
@@ -107,4 +110,12 @@ export class ShelfAssignerComponent implements OnInit {
isShelfSelected(shelf: Shelf): boolean {
return this.selectedShelves.some(s => s.id === shelf.id);
}
getShelfIcon(shelf: Shelf): IconSelection {
if (shelf.iconType === 'PRIME_NG') {
return {type: 'PRIME_NG', value: `pi pi-${shelf.icon}`};
} else {
return {type: 'CUSTOM_SVG', value: shelf.icon};
}
}
}
@@ -40,6 +40,7 @@ export interface Book extends FileInfo {
koreaderProgress?: KoReaderProgress;
koboProgress?: KoboProgress;
seriesCount?: number | null;
seriesBooks?: Book[] | null;
metadataMatchScore?: number | null;
personalRating?: number | null;
readStatus?: ReadStatus;
@@ -100,6 +101,8 @@ export interface BookMetadata {
goodreadsReviewCount?: number | null;
hardcoverRating?: number | null;
hardcoverReviewCount?: number | null;
lubimyczytacId?: string;
lubimyczytacRating?: number | null;
coverUpdatedOn?: string;
authors?: string[];
categories?: string[];
@@ -133,6 +136,8 @@ export interface BookMetadata {
goodreadsReviewCountLocked?: boolean;
hardcoverRatingLocked?: boolean;
hardcoverReviewCountLocked?: boolean;
lubimyczytacIdLocked?: boolean;
lubimyczytacRatingLocked?: boolean;
coverUpdatedOnLocked?: boolean;
authorsLocked?: boolean;
categoriesLocked?: boolean;
@@ -168,6 +173,8 @@ export interface MetadataClearFlags {
goodreadsReviewCount?: boolean;
hardcoverRating?: boolean;
hardcoverReviewCount?: boolean;
lubimyczytacId?: boolean;
lubimyczytacRating?: boolean;
authors?: boolean;
categories?: boolean;
moods?: boolean;
@@ -0,0 +1,200 @@
import {inject, Injectable} from '@angular/core';
import {HttpClient, HttpParams} from '@angular/common/http';
import {Observable} from 'rxjs';
import {tap} from 'rxjs/operators';
import {Book, ReadStatus} from '../model/book.model';
import {BookStateService} from './book-state.service';
import {API_CONFIG} from '../../../core/config/api-config';
import {ResetProgressType, ResetProgressTypes} from '../../../shared/constants/reset-progress-type';
import {BookStatusUpdateResponse, PersonalRatingUpdateResponse} from './book.service';
@Injectable({
providedIn: 'root',
})
export class BookPatchService {
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/books`;
private http = inject(HttpClient);
private bookStateService = inject(BookStateService);
updateBookShelves(bookIds: Set<number | undefined>, shelvesToAssign: Set<number | null | undefined>, shelvesToUnassign: Set<number | null | undefined>): Observable<Book[]> {
const requestPayload = {
bookIds: Array.from(bookIds),
shelvesToAssign: Array.from(shelvesToAssign),
shelvesToUnassign: Array.from(shelvesToUnassign),
};
return this.http.post<Book[]>(`${this.url}/shelves`, requestPayload).pipe(
tap(updatedBooks => {
const currentState = this.bookStateService.getCurrentBookState();
const currentBooks = currentState.books || [];
updatedBooks.forEach(updatedBook => {
const index = currentBooks.findIndex(b => b.id === updatedBook.id);
if (index !== -1) {
currentBooks[index] = updatedBook;
}
});
this.bookStateService.updateBookState({...currentState, books: [...currentBooks]});
})
);
}
savePdfProgress(bookId: number, page: number, percentage: number): Observable<void> {
const body = {
bookId: bookId,
pdfProgress: {
page: page,
percentage: percentage
}
};
return this.http.post<void>(`${this.url}/progress`, body);
}
saveEpubProgress(bookId: number, cfi: string, percentage: number): Observable<void> {
const body = {
bookId: bookId,
epubProgress: {
cfi: cfi,
percentage: percentage
}
};
return this.http.post<void>(`${this.url}/progress`, body);
}
saveCbxProgress(bookId: number, page: number, percentage: number): Observable<void> {
const body = {
bookId: bookId,
cbxProgress: {
page: page,
percentage: percentage
}
};
return this.http.post<void>(`${this.url}/progress`, body);
}
updateDateFinished(bookId: number, dateFinished: string | null): Observable<void> {
const body = {
bookId: bookId,
dateFinished: dateFinished
};
return this.http.post<void>(`${this.url}/progress`, body).pipe(
tap(() => {
const currentState = this.bookStateService.getCurrentBookState();
if (currentState.books) {
const updatedBooks = currentState.books.map(book => {
if (book.id === bookId) {
return {...book, dateFinished: dateFinished || undefined};
}
return book;
});
this.bookStateService.updateBookState({
...currentState,
books: updatedBooks
});
}
})
);
}
resetProgress(bookIds: number | number[], type: ResetProgressType): Observable<BookStatusUpdateResponse[]> {
const ids = Array.isArray(bookIds) ? bookIds : [bookIds];
const params = new HttpParams().set('type', ResetProgressTypes[type]);
return this.http.post<BookStatusUpdateResponse[]>(`${this.url}/reset-progress`, ids, {params}).pipe(
tap(responses => {
const currentState = this.bookStateService.getCurrentBookState();
const updatedBooks = (currentState.books || []).map(book => {
const response = responses.find(r => r.bookId === book.id);
if (response) {
return {
...book,
readStatus: response.readStatus,
readStatusModifiedTime: response.readStatusModifiedTime,
dateFinished: response.dateFinished
};
}
return book;
});
this.bookStateService.updateBookState({...currentState, books: updatedBooks});
})
);
}
updateBookReadStatus(bookIds: number | number[], status: ReadStatus): Observable<BookStatusUpdateResponse[]> {
const ids = Array.isArray(bookIds) ? bookIds : [bookIds];
const requestBody = {
bookIds: ids,
status: status
};
return this.http.post<BookStatusUpdateResponse[]>(`${this.url}/status`, requestBody).pipe(
tap(responses => {
const currentState = this.bookStateService.getCurrentBookState();
const updatedBooks = (currentState.books || []).map(book => {
const response = responses.find(r => r.bookId === book.id);
if (response) {
return {
...book,
readStatus: response.readStatus,
readStatusModifiedTime: response.readStatusModifiedTime,
dateFinished: response.dateFinished
};
}
return book;
});
this.bookStateService.updateBookState({...currentState, books: updatedBooks});
})
);
}
resetPersonalRating(bookIds: number | number[]): Observable<PersonalRatingUpdateResponse[]> {
const ids = Array.isArray(bookIds) ? bookIds : [bookIds];
return this.http.post<PersonalRatingUpdateResponse[]>(`${this.url}/reset-personal-rating`, ids).pipe(
tap(responses => {
const currentState = this.bookStateService.getCurrentBookState();
const updatedBooks = (currentState.books || []).map(book => {
const response = responses.find(r => r.bookId === book.id);
if (response) {
return {
...book,
personalRating: response.personalRating
};
}
return book;
});
this.bookStateService.updateBookState({...currentState, books: updatedBooks});
})
);
}
updatePersonalRating(bookIds: number | number[], rating: number): Observable<PersonalRatingUpdateResponse[]> {
const ids = Array.isArray(bookIds) ? bookIds : [bookIds];
return this.http.put<PersonalRatingUpdateResponse[]>(`${this.url}/personal-rating`, {ids, rating}).pipe(
tap(responses => {
const currentState = this.bookStateService.getCurrentBookState();
const updatedBooks = (currentState.books || []).map(book => {
const response = responses.find(r => r.bookId === book.id);
if (response) {
return {
...book,
personalRating: response.personalRating
};
}
return book;
});
this.bookStateService.updateBookState({...currentState, books: updatedBooks});
})
);
}
updateLastReadTime(bookId: number): void {
const timestamp = new Date().toISOString();
const currentState = this.bookStateService.getCurrentBookState();
const updatedBooks = (currentState.books || []).map(book =>
book.id === bookId ? {...book, lastReadTime: timestamp} : book
);
this.bookStateService.updateBookState({...currentState, books: updatedBooks});
}
}
@@ -0,0 +1,71 @@
import {inject, Injectable} from '@angular/core';
import {BookStateService} from './book-state.service';
import {Book, BookMetadata} from '../model/book.model';
@Injectable({
providedIn: 'root',
})
export class BookSocketService {
private bookStateService = inject(BookStateService);
handleNewlyCreatedBook(book: Book): void {
const currentState = this.bookStateService.getCurrentBookState();
const updatedBooks = currentState.books ? [...currentState.books] : [];
const bookIndex = updatedBooks.findIndex(existingBook => existingBook.id === book.id);
if (bookIndex > -1) {
updatedBooks[bookIndex] = book;
} else {
updatedBooks.push(book);
}
this.bookStateService.updateBookState({...currentState, books: updatedBooks});
}
handleRemovedBookIds(removedBookIds: number[]): void {
const currentState = this.bookStateService.getCurrentBookState();
const filteredBooks = (currentState.books || []).filter(book => !removedBookIds.includes(book.id));
this.bookStateService.updateBookState({...currentState, books: filteredBooks});
}
handleBookUpdate(updatedBook: Book): void {
const currentState = this.bookStateService.getCurrentBookState();
const updatedBooks = (currentState.books || []).map(book =>
book.id === updatedBook.id ? updatedBook : book
);
this.bookStateService.updateBookState({...currentState, books: updatedBooks});
}
handleMultipleBookUpdates(updatedBooks: Book[]): void {
const currentState = this.bookStateService.getCurrentBookState();
const currentBooks = currentState.books || [];
const updatedMap = new Map(updatedBooks.map(book => [book.id, book]));
const mergedBooks = currentBooks.map(book =>
updatedMap.has(book.id) ? updatedMap.get(book.id)! : book
);
this.bookStateService.updateBookState({...currentState, books: mergedBooks});
}
handleBookMetadataUpdate(bookId: number, updatedMetadata: BookMetadata): void {
const currentState = this.bookStateService.getCurrentBookState();
const updatedBooks = (currentState.books || []).map(book => {
return book.id === bookId ? {...book, metadata: updatedMetadata} : book;
});
this.bookStateService.updateBookState({...currentState, books: updatedBooks});
}
handleMultipleBookCoverPatches(patches: { id: number; coverUpdatedOn: string }[]): void {
if (!patches || patches.length === 0) return;
const currentState = this.bookStateService.getCurrentBookState();
const books = currentState.books || [];
patches.forEach(p => {
const index = books.findIndex(b => b.id === p.id);
if (index !== -1 && books[index].metadata) {
books[index].metadata.coverUpdatedOn = p.coverUpdatedOn;
}
});
this.bookStateService.updateBookState({...currentState, books});
}
}
@@ -0,0 +1,40 @@
import {Injectable} from '@angular/core';
import {BehaviorSubject, Observable} from 'rxjs';
import {BookState} from '../model/state/book-state.model';
@Injectable({
providedIn: 'root',
})
export class BookStateService {
private bookStateSubject = new BehaviorSubject<BookState>({
books: null,
loaded: false,
error: null,
});
public readonly bookState$ = this.bookStateSubject.asObservable();
getCurrentBookState(): BookState {
return this.bookStateSubject.value;
}
updateBookState(state: BookState): void {
this.bookStateSubject.next(state);
}
updatePartialBookState(partialState: Partial<BookState>): void {
this.bookStateSubject.next({
...this.bookStateSubject.value,
...partialState
});
}
resetBookState(): void {
this.bookStateSubject.next({
books: null,
loaded: true,
error: null,
});
}
}
@@ -1,17 +1,31 @@
import {inject, Injectable} from '@angular/core';
import {BehaviorSubject, first, Observable, of, throwError} from 'rxjs';
import {first, Observable, of, throwError} from 'rxjs';
import {HttpClient, HttpParams} from '@angular/common/http';
import {catchError, filter, map, tap, shareReplay, finalize, distinctUntilChanged} from 'rxjs/operators';
import {Book, BookDeletionResponse, BookMetadata, BookRecommendation, BookSetting, BulkMetadataUpdateRequest, MetadataUpdateWrapper, ReadStatus, AdditionalFileType, AdditionalFile} from '../model/book.model';
import {catchError, distinctUntilChanged, filter, finalize, map, shareReplay, tap} from 'rxjs/operators';
import {AdditionalFile, AdditionalFileType, Book, BookDeletionResponse, BookMetadata, BookRecommendation, BookSetting, BulkMetadataUpdateRequest, MetadataUpdateWrapper, ReadStatus} from '../model/book.model';
import {BookState} from '../model/state/book-state.model';
import {API_CONFIG} from '../../../core/config/api-config';
import {FetchMetadataRequest} from '../../metadata/model/request/fetch-metadata-request.model';
import {MetadataRefreshRequest} from '../../metadata/model/request/metadata-refresh-request.model';
import {MessageService} from 'primeng/api';
import {ResetProgressType, ResetProgressTypes} from '../../../shared/constants/reset-progress-type';
import {ResetProgressType} from '../../../shared/constants/reset-progress-type';
import {AuthService} from '../../../shared/service/auth.service';
import {FileDownloadService} from '../../../shared/service/file-download.service';
import {Router} from '@angular/router';
import {BookStateService} from './book-state.service';
import {BookSocketService} from './book-socket.service';
import {BookPatchService} from './book-patch.service';
export interface BookStatusUpdateResponse {
bookId: number;
readStatus: ReadStatus;
readStatusModifiedTime: string;
dateFinished?: string;
}
export interface PersonalRatingUpdateResponse {
bookId: number;
personalRating?: number;
}
@Injectable({
providedIn: 'root',
@@ -25,12 +39,9 @@ export class BookService {
private authService = inject(AuthService);
private fileDownloadService = inject(FileDownloadService);
private router = inject(Router);
private bookStateSubject = new BehaviorSubject<BookState>({
books: null,
loaded: false,
error: null,
});
private bookStateService = inject(BookStateService);
private bookSocketService = inject(BookSocketService);
private bookPatchService = inject(BookPatchService);
private loading$: Observable<Book[]> | null = null;
@@ -39,16 +50,12 @@ export class BookService {
distinctUntilChanged()
).subscribe(token => {
if (token === null) {
this.bookStateSubject.next({
books: null,
loaded: true,
error: null,
});
this.bookStateService.resetBookState();
this.loading$ = null;
} else {
const current = this.bookStateSubject.value;
const current = this.bookStateService.getCurrentBookState();
if (current.loaded && !current.books) {
this.bookStateSubject.next({
this.bookStateService.updateBookState({
books: null,
loaded: false,
error: null,
@@ -59,7 +66,9 @@ export class BookService {
});
}
bookState$ = this.bookStateSubject.asObservable().pipe(
/*------------------ State Management ------------------*/
bookState$ = this.bookStateService.bookState$.pipe(
tap(state => {
if (!state.loaded && !state.error && !this.loading$) {
this.loading$ = this.fetchBooks().pipe(
@@ -72,21 +81,21 @@ export class BookService {
);
getCurrentBookState(): BookState {
return this.bookStateSubject.value;
return this.bookStateService.getCurrentBookState();
}
private fetchBooks(): Observable<Book[]> {
return this.http.get<Book[]>(this.url).pipe(
tap(books => {
this.bookStateSubject.next({
this.bookStateService.updateBookState({
books: books || [],
loaded: true,
error: null,
});
}),
catchError(error => {
const curr = this.bookStateSubject.value;
this.bookStateSubject.next({
const curr = this.bookStateService.getCurrentBookState();
this.bookStateService.updateBookState({
books: curr.books,
loaded: true,
error: error.message,
@@ -99,14 +108,14 @@ export class BookService {
refreshBooks(): void {
this.http.get<Book[]>(this.url).pipe(
tap(books => {
this.bookStateSubject.next({
this.bookStateService.updateBookState({
books: books || [],
loaded: true,
error: null,
});
}),
catchError(error => {
this.bookStateSubject.next({
this.bookStateService.updateBookState({
books: null,
loaded: true,
error: error.message,
@@ -116,118 +125,39 @@ export class BookService {
).subscribe();
}
removeBooksByLibraryId(libraryId: number): void {
const currentState = this.bookStateService.getCurrentBookState();
const currentBooks = currentState.books || [];
const filteredBooks = currentBooks.filter(book => book.libraryId !== libraryId);
this.bookStateService.updateBookState({...currentState, books: filteredBooks});
}
removeBooksFromShelf(shelfId: number): void {
const currentState = this.bookStateService.getCurrentBookState();
const currentBooks = currentState.books || [];
const updatedBooks = currentBooks.map(book => ({
...book,
shelves: book.shelves?.filter(shelf => shelf.id !== shelfId),
}));
this.bookStateService.updateBookState({...currentState, books: updatedBooks});
}
/*------------------ Book Retrieval ------------------*/
getBookByIdFromState(bookId: number): Book | undefined {
const currentState = this.bookStateSubject.value;
const currentState = this.bookStateService.getCurrentBookState();
return currentState.books?.find(book => +book.id === +bookId);
}
getBooksByIdsFromState(bookIds: number[]): Book[] {
const currentState = this.bookStateSubject.value;
const currentState = this.bookStateService.getCurrentBookState();
if (!currentState.books || bookIds.length === 0) return [];
const idSet = new Set(bookIds.map(id => +id));
return currentState.books.filter(book => idSet.has(+book.id));
}
updateBookShelves(bookIds: Set<number | undefined>, shelvesToAssign: Set<number | null | undefined>, shelvesToUnassign: Set<number | null | undefined>): Observable<Book[]> {
const requestPayload = {
bookIds: Array.from(bookIds),
shelvesToAssign: Array.from(shelvesToAssign),
shelvesToUnassign: Array.from(shelvesToUnassign),
};
return this.http.post<Book[]>(`${this.url}/shelves`, requestPayload).pipe(
map(updatedBooks => {
const currentState = this.bookStateSubject.value;
const currentBooks = currentState.books || [];
updatedBooks.forEach(updatedBook => {
const index = currentBooks.findIndex(b => b.id === updatedBook.id);
if (index !== -1) {
currentBooks[index] = updatedBook;
}
});
this.bookStateSubject.next({...currentState, books: [...currentBooks]});
return updatedBooks;
}),
catchError(error => {
const currentState = this.bookStateSubject.value;
this.bookStateSubject.next({...currentState, error: error.message});
throw error;
})
);
}
removeBooksByLibraryId(libraryId: number): void {
const currentState = this.bookStateSubject.value;
const currentBooks = currentState.books || [];
const filteredBooks = currentBooks.filter(book => book.libraryId !== libraryId);
this.bookStateSubject.next({...currentState, books: filteredBooks});
}
removeBooksFromShelf(shelfId: number): void {
const currentState = this.bookStateSubject.value;
const currentBooks = currentState.books || [];
const updatedBooks = currentBooks.map(book => ({
...book,
shelves: book.shelves?.filter(shelf => shelf.id !== shelfId),
}));
this.bookStateSubject.next({...currentState, books: updatedBooks});
}
getBookSetting(bookId: number): Observable<BookSetting> {
return this.http.get<BookSetting>(`${this.url}/${bookId}/viewer-setting`);
}
updateViewerSetting(bookSetting: BookSetting, bookId: number): Observable<void> {
return this.http.put<void>(`${this.url}/${bookId}/viewer-setting`, bookSetting);
}
updateLastReadTime(bookId: number) {
const timestamp = new Date().toISOString();
const currentState = this.bookStateSubject.value;
const updatedBooks = (currentState.books || []).map(book =>
book.id === bookId ? {...book, lastReadTime: timestamp} : book
);
this.bookStateSubject.next({...currentState, books: updatedBooks});
}
readBook(bookId: number, reader?: 'ngx' | 'streaming'): void {
const book = this.bookStateSubject.value.books?.find(b => b.id === bookId);
if (!book) {
console.error('Book not found');
return;
}
let url: string;
switch (book.bookType) {
case 'PDF':
url = !reader || reader === 'ngx'
? `/pdf-reader/book/${book.id}`
: `/cbx-reader/book/${book.id}`;
break;
case 'EPUB':
url = `/epub-reader/book/${book.id}`;
break;
case 'CBX':
url = `/cbx-reader/book/${book.id}`;
break;
default:
console.error('Unsupported book type:', book.bookType);
return;
}
this.router.navigate([url]);
this.updateLastReadTime(book.id);
}
getFileContent(bookId: number): Observable<Blob> {
return this.http.get<Blob>(`${this.url}/${bookId}/content`, {responseType: 'blob' as 'json'});
}
getBookByIdFromAPI(bookId: number, withDescription: boolean) {
getBookByIdFromAPI(bookId: number, withDescription: boolean): Observable<Book> {
return this.http.get<Book>(`${this.url}/${bookId}`, {
params: {
withDescription: withDescription.toString()
@@ -235,18 +165,44 @@ export class BookService {
});
}
getBooksInSeries(bookId: number): Observable<Book[]> {
return this.bookStateService.bookState$.pipe(
filter(state => state.loaded),
first(),
map(state => {
const allBooks = state.books || [];
const currentBook = allBooks.find(b => b.id === bookId);
if (!currentBook || !currentBook.metadata?.seriesName) {
return [];
}
const seriesName = currentBook.metadata.seriesName.toLowerCase();
return allBooks.filter(b => b.metadata?.seriesName?.toLowerCase() === seriesName);
})
);
}
getBookRecommendations(bookId: number, limit: number = 20): Observable<BookRecommendation[]> {
return this.http.get<BookRecommendation[]>(`${this.url}/${bookId}/recommendations`, {
params: {limit: limit.toString()}
});
}
/*------------------ Book Operations ------------------*/
deleteBooks(ids: Set<number>): Observable<BookDeletionResponse> {
const idList = Array.from(ids);
const params = new HttpParams().set('ids', idList.join(','));
return this.http.delete<BookDeletionResponse>(this.url, {params}).pipe(
tap(response => {
const currentState = this.bookStateSubject.value;
const currentState = this.bookStateService.getCurrentBookState();
const remainingBooks = (currentState.books || []).filter(
book => !ids.has(book.id)
);
this.bookStateSubject.next({
this.bookStateService.updateBookState({
books: remainingBooks,
loaded: true,
error: null,
@@ -277,11 +233,72 @@ export class BookService {
);
}
updateBookShelves(bookIds: Set<number | undefined>, shelvesToAssign: Set<number | null | undefined>, shelvesToUnassign: Set<number | null | undefined>): Observable<Book[]> {
return this.bookPatchService.updateBookShelves(bookIds, shelvesToAssign, shelvesToUnassign).pipe(
catchError(error => {
const currentState = this.bookStateService.getCurrentBookState();
this.bookStateService.updateBookState({...currentState, error: error.message});
throw error;
})
);
}
/*------------------ Reading & Viewer Settings ------------------*/
readBook(bookId: number, reader: 'ngx' | 'streaming' = 'ngx'): void {
const book = this.bookStateService
.getCurrentBookState()
.books?.find(b => b.id === bookId);
if (!book) {
console.error('Book not found');
return;
}
const baseUrl =
book.bookType === 'PDF'
? reader === 'ngx'
? 'pdf-reader'
: 'cbx-reader'
: book.bookType === 'EPUB'
? 'epub-reader'
: book.bookType === 'CBX'
? 'cbx-reader'
: null;
if (!baseUrl) {
console.error('Unsupported book type:', book.bookType);
return;
}
this.router.navigate([`/${baseUrl}/book/${book.id}`]);
this.updateLastReadTime(book.id);
}
getBookSetting(bookId: number): Observable<BookSetting> {
return this.http.get<BookSetting>(`${this.url}/${bookId}/viewer-setting`);
}
updateViewerSetting(bookSetting: BookSetting, bookId: number): Observable<void> {
return this.http.put<void>(`${this.url}/${bookId}/viewer-setting`, bookSetting);
}
/*------------------ File Operations ------------------*/
getFileContent(bookId: number): Observable<Blob> {
return this.http.get<Blob>(`${this.url}/${bookId}/content`, {responseType: 'blob' as 'json'});
}
downloadFile(book: Book): void {
const downloadUrl = `${this.url}/${book.id}/download`;
this.fileDownloadService.downloadFile(downloadUrl, book.fileName!);
}
deleteAdditionalFile(bookId: number, fileId: number): Observable<void> {
const deleteUrl = `${this.url}/${bookId}/files/${fileId}`;
return this.http.delete<void>(deleteUrl).pipe(
tap(() => {
const currentState = this.bookStateSubject.value;
const currentState = this.bookStateService.getCurrentBookState();
const updatedBooks = (currentState.books || []).map(book => {
if (book.id === bookId) {
return {
@@ -293,7 +310,7 @@ export class BookService {
return book;
});
this.bookStateSubject.next({
this.bookStateService.updateBookState({
...currentState,
books: updatedBooks
});
@@ -325,7 +342,7 @@ export class BookService {
return this.http.post<AdditionalFile>(`${this.url}/${bookId}/files`, formData).pipe(
tap((newFile) => {
const currentState = this.bookStateSubject.value;
const currentState = this.bookStateService.getCurrentBookState();
const updatedBooks = (currentState.books || []).map(book => {
if (book.id === bookId) {
const updatedBook = {...book};
@@ -339,7 +356,7 @@ export class BookService {
return book;
});
this.bookStateSubject.next({
this.bookStateService.updateBookState({
...currentState,
books: updatedBooks
});
@@ -361,96 +378,53 @@ export class BookService {
);
}
downloadFile(book: Book): void {
const downloadUrl = `${this.url}/${book.id}/download`;
this.fileDownloadService.downloadFile(downloadUrl, book.fileName!);
}
downloadAdditionalFile(book: Book, fileId: number): void {
const additionalFile = book.alternativeFormats!.find((f: AdditionalFile) => f.id === fileId);
const downloadUrl = `${this.url}/${additionalFile!.id}/files/${fileId}/download`;
this.fileDownloadService.downloadFile(downloadUrl, additionalFile!.fileName!);
}
/*------------------ Progress & Status Tracking ------------------*/
updateLastReadTime(bookId: number): void {
this.bookPatchService.updateLastReadTime(bookId);
}
savePdfProgress(bookId: number, page: number, percentage: number): Observable<void> {
const body = {
bookId: bookId,
pdfProgress: {
page: page,
percentage: percentage
}
}
return this.http.post<void>(`${this.url}/progress`, body);
return this.bookPatchService.savePdfProgress(bookId, page, percentage);
}
saveEpubProgress(bookId: number, cfi: string, percentage: number): Observable<void> {
const body = {
bookId: bookId,
epubProgress: {
cfi: cfi,
percentage: percentage
}
};
return this.http.post<void>(`${this.url}/progress`, body);
return this.bookPatchService.saveEpubProgress(bookId, cfi, percentage);
}
saveCbxProgress(bookId: number, page: number, percentage: number): Observable<void> {
const body = {
bookId: bookId,
cbxProgress: {
page: page,
percentage: percentage
}
};
return this.http.post<void>(`${this.url}/progress`, body);
return this.bookPatchService.saveCbxProgress(bookId, page, percentage);
}
updateDateFinished(bookId: number, dateFinished: string | null): Observable<void> {
const body = {
bookId: bookId,
dateFinished: dateFinished
};
return this.http.post<void>(`${this.url}/progress`, body).pipe(
tap(() => {
// Update the book in the state
const currentState = this.bookStateSubject.value;
if (currentState.books) {
const updatedBooks = currentState.books.map(book => {
if (book.id === bookId) {
return {...book, dateFinished: dateFinished || undefined};
}
return book;
});
this.bookStateSubject.next({
...currentState,
books: updatedBooks
});
}
})
);
return this.bookPatchService.updateDateFinished(bookId, dateFinished);
}
regenerateCovers(): Observable<void> {
return this.http.post<void>(`${this.url}/regenerate-covers`, {});
resetProgress(bookIds: number | number[], type: ResetProgressType): Observable<BookStatusUpdateResponse[]> {
return this.bookPatchService.resetProgress(bookIds, type);
}
regenerateCover(bookId: number): Observable<void> {
return this.http.post<void>(`${this.url}/${bookId}/regenerate-cover`, {});
updateBookReadStatus(bookIds: number | number[], status: ReadStatus): Observable<BookStatusUpdateResponse[]> {
return this.bookPatchService.updateBookReadStatus(bookIds, status);
}
regenerateCoversForBooks(bookIds: number[]): Observable<void> {
return this.http.post<void>(`${this.url}/bulk-regenerate-covers`, { bookIds });
/*------------------ Personal Rating ------------------*/
resetPersonalRating(bookIds: number | number[]): Observable<PersonalRatingUpdateResponse[]> {
return this.bookPatchService.resetPersonalRating(bookIds);
}
bulkUploadCover(bookIds: number[], file: File): Observable<void> {
const formData = new FormData();
formData.append('file', file);
formData.append('bookIds', bookIds.join(','));
return this.http.post<void>(`${this.url}/bulk-upload-cover`, formData);
updatePersonalRating(bookIds: number | number[], rating: number): Observable<PersonalRatingUpdateResponse[]> {
return this.bookPatchService.updatePersonalRating(bookIds, rating);
}
/*------------------ All the metadata related calls go here ------------------*/
/*------------------ Metadata Operations ------------------*/
fetchBookMetadata(bookId: number, request: FetchMetadataRequest): Observable<BookMetadata[]> {
return this.http.post<BookMetadata[]>(`${this.url}/${bookId}/metadata/prospective`, request);
@@ -458,12 +432,7 @@ export class BookService {
updateBookMetadata(bookId: number | undefined, wrapper: MetadataUpdateWrapper, mergeCategories: boolean): Observable<BookMetadata> {
const params = new HttpParams().set('mergeCategories', mergeCategories.toString());
return this.http.put<BookMetadata>(`${this.url}/${bookId}/metadata`, wrapper, {params}).pipe(
map(updatedMetadata => {
this.handleBookMetadataUpdate(bookId!, updatedMetadata);
return updatedMetadata;
})
);
return this.http.put<BookMetadata>(`${this.url}/${bookId}/metadata`, wrapper, {params});
}
updateBooksMetadata(request: BulkMetadataUpdateRequest): Observable<void> {
@@ -479,12 +448,12 @@ export class BookService {
};
return this.http.put<BookMetadata[]>(`${this.url}/metadata/toggle-all-lock`, requestBody).pipe(
tap((updatedMetadataList) => {
const currentState = this.bookStateSubject.value;
const currentState = this.bookStateService.getCurrentBookState();
const updatedBooks = (currentState.books || []).map(book => {
const updatedMetadata = updatedMetadataList.find(meta => meta.bookId === book.id);
return updatedMetadata ? {...book, metadata: updatedMetadata} : book;
});
this.bookStateSubject.next({...currentState, books: updatedBooks});
this.bookStateService.updateBookState({...currentState, books: updatedBooks});
}),
map(() => void 0),
catchError((error) => {
@@ -493,73 +462,43 @@ export class BookService {
);
}
getUploadCoverUrl(bookId: number): string {
return this.url + '/' + bookId + "/metadata/cover/upload"
}
toggleFieldLocks(bookIds: number[] | Set<number>, fieldActions: Record<string, 'LOCK' | 'UNLOCK'>): Observable<void> {
const bookIdSet = bookIds instanceof Set ? bookIds : new Set(bookIds);
uploadCoverFromUrl(bookId: number, url: string): Observable<BookMetadata> {
return this.http
.post<BookMetadata>(`${this.url}/${bookId}/metadata/cover/from-url`, {url})
.pipe(
tap(updatedMetadata =>
this.handleBookMetadataUpdate(bookId, updatedMetadata)
)
);
}
const requestBody = {
bookIds: Array.from(bookIdSet),
fieldActions
};
getBookRecommendations(bookId: number, limit: number = 20): Observable<BookRecommendation[]> {
return this.http.get<BookRecommendation[]>(`${this.url}/${bookId}/recommendations`, {
params: {limit: limit.toString()}
});
}
getBooksInSeries(bookId: number): Observable<Book[]> {
return this.bookStateSubject.asObservable().pipe(
filter(state => state.loaded),
first(),
map(state => {
const allBooks = state.books || [];
const currentBook = allBooks.find(b => b.id === bookId);
if (!currentBook || !currentBook.metadata?.seriesName) {
return [];
}
const seriesName = currentBook.metadata.seriesName.toLowerCase();
return allBooks.filter(b => b.metadata?.seriesName?.toLowerCase() === seriesName);
})
);
}
resetProgress(bookIds: number | number[], type: ResetProgressType): Observable<Book[]> {
const ids = Array.isArray(bookIds) ? bookIds : [bookIds];
const params = new HttpParams().set('type', ResetProgressTypes[type]);
return this.http.post<Book[]>(`${this.url}/reset-progress`, ids, {params}).pipe(
tap(updatedBooks => updatedBooks.forEach(book => this.handleBookUpdate(book)))
);
}
updateBookReadStatus(bookIds: number | number[], status: ReadStatus): Observable<Book[]> {
const ids = Array.isArray(bookIds) ? bookIds : [bookIds];
return this.http.put<Book[]>(`${this.url}/read-status`, {ids, status}).pipe(
tap(updatedBooks => {
updatedBooks.forEach(updatedBook => this.handleBookUpdate(updatedBook));
})
);
}
resetPersonalRating(bookIds: number | number[]): Observable<Book[]> {
const ids = Array.isArray(bookIds) ? bookIds : [bookIds];
return this.http.post<Book[]>(`${this.url}/reset-personal-rating`, ids).pipe(
tap(updatedBooks => updatedBooks.forEach(book => this.handleBookUpdate(book)))
);
}
updatePersonalRating(bookIds: number | number[], rating: number): Observable<Book[]> {
const ids = Array.isArray(bookIds) ? bookIds : [bookIds];
return this.http.put<Book[]>(`${this.url}/personal-rating`, {ids, rating}).pipe(
tap(updatedBooks => {
updatedBooks.forEach(updatedBook => this.handleBookUpdate(updatedBook));
return this.http.put<void>(`${this.url}/metadata/toggle-field-locks`, requestBody).pipe(
tap(() => {
const currentState = this.bookStateService.getCurrentBookState();
const updatedBooks = (currentState.books || []).map(book => {
if (!bookIdSet.has(book.id)) return book;
const updatedMetadata = {...book.metadata};
for (const [field, action] of Object.entries(fieldActions)) {
const lockField = field.endsWith('Locked') ? field : `${field}Locked`;
if (lockField in updatedMetadata) {
(updatedMetadata as any)[lockField] = action === 'LOCK';
}
}
return {
...book,
metadata: updatedMetadata
};
});
this.bookStateService.updateBookState({
...currentState,
books: updatedBooks as Book[]
});
}),
catchError(error => {
this.messageService.add({
severity: 'error',
summary: 'Field Lock Update Failed',
detail: 'Failed to update metadata field locks. Please try again.',
});
throw error;
})
);
}
@@ -582,95 +521,64 @@ export class BookService {
);
}
/*------------------ Cover Operations ------------------*/
/*------------------ All the websocket handlers go below ------------------*/
getUploadCoverUrl(bookId: number): string {
return this.url + '/' + bookId + "/metadata/cover/upload"
}
uploadCoverFromUrl(bookId: number, url: string): Observable<BookMetadata> {
return this.http
.post<BookMetadata>(`${this.url}/${bookId}/metadata/cover/from-url`, {url})
.pipe(
tap(updatedMetadata =>
this.handleBookMetadataUpdate(bookId, updatedMetadata)
)
);
}
regenerateCovers(): Observable<void> {
return this.http.post<void>(`${this.url}/regenerate-covers`, {});
}
regenerateCover(bookId: number): Observable<void> {
return this.http.post<void>(`${this.url}/${bookId}/regenerate-cover`, {});
}
regenerateCoversForBooks(bookIds: number[]): Observable<void> {
return this.http.post<void>(`${this.url}/bulk-regenerate-covers`, {bookIds});
}
bulkUploadCover(bookIds: number[], file: File): Observable<void> {
const formData = new FormData();
formData.append('file', file);
formData.append('bookIds', bookIds.join(','));
return this.http.post<void>(`${this.url}/bulk-upload-cover`, formData);
}
/*------------------ Websocket Handlers ------------------*/
handleNewlyCreatedBook(book: Book): void {
const currentState = this.bookStateSubject.value;
const updatedBooks = currentState.books ? [...currentState.books] : [];
const bookIndex = updatedBooks.findIndex(existingBook => existingBook.id === book.id);
if (bookIndex > -1) {
updatedBooks[bookIndex] = book;
} else {
updatedBooks.push(book);
}
this.bookStateSubject.next({...currentState, books: updatedBooks});
this.bookSocketService.handleNewlyCreatedBook(book);
}
handleRemovedBookIds(removedBookIds: number[]): void {
const currentState = this.bookStateSubject.value;
const filteredBooks = (currentState.books || []).filter(book => !removedBookIds.includes(book.id));
this.bookStateSubject.next({...currentState, books: filteredBooks});
this.bookSocketService.handleRemovedBookIds(removedBookIds);
}
handleBookUpdate(updatedBook: Book) {
const currentState = this.bookStateSubject.value;
const updatedBooks = (currentState.books || []).map(book =>
book.id === updatedBook.id ? updatedBook : book
);
this.bookStateSubject.next({...currentState, books: updatedBooks});
handleBookUpdate(updatedBook: Book): void {
this.bookSocketService.handleBookUpdate(updatedBook);
}
handleMultipleBookUpdates(updatedBooks: Book[]): void {
const currentState = this.bookStateSubject.value;
const currentBooks = currentState.books || [];
const updatedMap = new Map(updatedBooks.map(book => [book.id, book]));
const mergedBooks = currentBooks.map(book =>
updatedMap.has(book.id) ? updatedMap.get(book.id)! : book
);
this.bookStateSubject.next({...currentState, books: mergedBooks});
this.bookSocketService.handleMultipleBookUpdates(updatedBooks);
}
handleBookMetadataUpdate(bookId: number, updatedMetadata: BookMetadata) {
const currentState = this.bookStateSubject.value;
const updatedBooks = (currentState.books || []).map(book => {
return book.id == bookId ? {...book, metadata: updatedMetadata} : book
});
this.bookStateSubject.next({...currentState, books: updatedBooks})
handleBookMetadataUpdate(bookId: number, updatedMetadata: BookMetadata): void {
this.bookSocketService.handleBookMetadataUpdate(bookId, updatedMetadata);
}
toggleFieldLocks(bookIds: number[] | Set<number>, fieldActions: Record<string, 'LOCK' | 'UNLOCK'>): Observable<void> {
const bookIdSet = bookIds instanceof Set ? bookIds : new Set(bookIds);
const requestBody = {
bookIds: Array.from(bookIdSet),
fieldActions
};
return this.http.put<void>(`${this.url}/metadata/toggle-field-locks`, requestBody).pipe(
tap(() => {
const currentState = this.bookStateSubject.value;
const updatedBooks = (currentState.books || []).map(book => {
if (!bookIdSet.has(book.id)) return book;
const updatedMetadata = {...book.metadata};
for (const [field, action] of Object.entries(fieldActions)) {
const lockField = field.endsWith('Locked') ? field : `${field}Locked`;
if (lockField in updatedMetadata) {
(updatedMetadata as any)[lockField] = action === 'LOCK';
}
}
return {
...book,
metadata: updatedMetadata
};
});
this.bookStateSubject.next({
...currentState,
books: updatedBooks as Book[]
});
}),
catchError(error => {
this.messageService.add({
severity: 'error',
summary: 'Field Lock Update Failed',
detail: 'Failed to update metadata field locks. Please try again.',
});
throw error;
})
);
handleMultipleBookCoverPatches(patches: { id: number; coverUpdatedOn: string }[]): void {
this.bookSocketService.handleMultipleBookCoverPatches(patches);
}
}
@@ -1,143 +1,154 @@
<div class="dashboard-settings">
<div class="settings-info">
<h3 class="settings-info-title">
<i class="pi pi-info-circle"></i>
Dashboard Configuration
</h3>
<p class="settings-info-text">
Customize your dashboard by adding up to 5 scrollers. Each scroller can display different book collections.
Choose from Continue Reading, Recently Added, Random Discovery, or create custom views using Magic Shelves.
Enable/disable, reorder, and configure the number of items shown in each scroller.
</p>
</div>
<div class="add-scroller-wrapper">
<div class="panel-header">
<div class="header-icon-wrapper">
<i class="pi pi-sliders-h header-icon"></i>
</div>
<div class="header-text">
<h2 class="panel-title">Dashboard Configuration</h2>
<p class="panel-description">Add up to 5 scrollers from different book collections and customize their behavior</p>
</div>
<p-button
label="Add Scroller"
icon="pi pi-plus"
size="small"
(click)="addScroller()"
[disabled]="config.scrollers.length >= 5">
</p-button>
icon="pi pi-times"
[text]="true"
[rounded]="true"
severity="secondary"
(onClick)="cancel()"
class="close-button"
/>
</div>
@for (scroller of config.scrollers; track scroller.id; let i = $index) {
<div class="scroller-item">
<div class="scroller-content">
<div class="scroller-controls-left">
<p-checkbox [(ngModel)]="scroller.enabled" [binary]="true"></p-checkbox>
</div>
<div class="scroller-fields">
<div class="scroller-field" [class.expanded]="scroller.type !== 'magicShelf'">
<label>Type</label>
<p-select
fluid
[options]="availableScrollerTypes"
[(ngModel)]="scroller.type"
(onChange)="onScrollerTypeChange(scroller)"
placeholder="Select type"
appendTo="body">
</p-select>
<div class="scrollers-container">
@for (scroller of config.scrollers; track scroller.id; let i = $index) {
<div class="scroller-item">
<div class="scroller-content">
<div class="scroller-controls-left">
<p-checkbox [(ngModel)]="scroller.enabled" [binary]="true"></p-checkbox>
</div>
@if (scroller.type === 'magicShelf') {
<div class="scroller-field">
<label>Magic Shelf</label>
<div class="scroller-fields">
<div class="scroller-field" [class.expanded]="scroller.type !== 'magicShelf'">
<label>Type</label>
<p-select
fluid
[options]="(magicShelves$ | async)!"
[(ngModel)]="scroller.magicShelfId"
placeholder="Select magic shelf"
[options]="availableScrollerTypes"
[(ngModel)]="scroller.type"
(onChange)="onScrollerTypeChange(scroller)"
placeholder="Select type"
appendTo="body">
</p-select>
</div>
<div class="scroller-field">
<label>Sort Field</label>
<p-select
fluid
[options]="sortFieldOptions"
[(ngModel)]="scroller.sortField"
placeholder="Select field"
appendTo="body">
</p-select>
</div>
@if (scroller.type === 'magicShelf') {
<div class="scroller-field">
<label>Magic Shelf</label>
<p-select
fluid
[options]="(magicShelves$ | async)!"
[(ngModel)]="scroller.magicShelfId"
placeholder="Select magic shelf"
appendTo="body">
</p-select>
</div>
<div class="scroller-field">
<label>Direction</label>
<p-select
fluid
[options]="sortDirectionOptions"
[(ngModel)]="scroller.sortDirection"
placeholder="Select direction"
appendTo="body">
</p-select>
</div>
}
</div>
<div class="scroller-field">
<label>Sort Field</label>
<p-select
fluid
[options]="sortFieldOptions"
[(ngModel)]="scroller.sortField"
placeholder="Select field"
appendTo="body">
</p-select>
</div>
<div class="scroller-field max-items-field">
<label>Max Items</label>
<p-inputNumber
fluid
[(ngModel)]="scroller.maxItems"
[min]="MIN_ITEMS"
[max]="MAX_ITEMS"
[showButtons]="true">
</p-inputNumber>
</div>
<div class="scroller-field">
<label>Direction</label>
<p-select
fluid
[options]="sortDirectionOptions"
[(ngModel)]="scroller.sortDirection"
placeholder="Select direction"
appendTo="body">
</p-select>
</div>
}
</div>
<div class="scroller-controls-right">
<p-button
icon="pi pi-arrow-up"
outlined
rounded
severity="info"
size="small"
[disabled]="i === 0"
(click)="moveUp(i)">
</p-button>
<p-button
icon="pi pi-arrow-down"
outlined
rounded
severity="info"
size="small"
[disabled]="i === config.scrollers.length - 1"
(click)="moveDown(i)">
</p-button>
<p-button
icon="pi pi-trash"
outlined
rounded
size="small"
severity="danger"
(click)="removeScroller(i)"
[disabled]="config.scrollers.length === 1">
</p-button>
<div class="scroller-field max-items-field">
<label>Max Items</label>
<p-inputNumber
fluid
[(ngModel)]="scroller.maxItems"
[min]="MIN_ITEMS"
[max]="MAX_ITEMS"
[showButtons]="true">
</p-inputNumber>
</div>
<div class="scroller-controls-right">
<p-button
icon="pi pi-arrow-up"
outlined
rounded
severity="info"
size="small"
[disabled]="i === 0"
(click)="moveUp(i)">
</p-button>
<p-button
icon="pi pi-arrow-down"
outlined
rounded
severity="info"
size="small"
[disabled]="i === config.scrollers.length - 1"
(click)="moveDown(i)">
</p-button>
<p-button
icon="pi pi-trash"
outlined
rounded
size="small"
severity="danger"
(click)="removeScroller(i)"
[disabled]="config.scrollers.length === 1">
</p-button>
</div>
</div>
</div>
</div>
}
}
</div>
<div class="footer-actions">
<p-button
label="Reset to Default"
severity="warn"
text
(click)="resetToDefault()">
</p-button>
<p-button
label="Cancel"
outlined
severity="secondary"
(click)="cancel()">
</p-button>
<p-button
label="Save"
severity="success"
(click)="save()">
</p-button>
<div class="dialog-footer">
<div class="footer-left">
<p-button
label="Add Scroller"
icon="pi pi-plus"
severity="primary"
(click)="addScroller()"
[disabled]="config.scrollers.length >= 5">
</p-button>
<p-button
label="Reset to Default"
icon="pi pi-refresh"
severity="secondary"
text
(click)="resetToDefault()">
</p-button>
</div>
<div class="footer-actions">
<p-button
label="Cancel"
[outlined]="true"
severity="secondary"
(click)="cancel()">
</p-button>
<p-button
label="Save"
icon="pi pi-check"
severity="success"
(click)="save()">
</p-button>
</div>
</div>
</div>
@@ -1,13 +1,174 @@
.dashboard-settings {
max-width: 600px;
min-height: 300px;
padding: 2rem 1rem 0 1rem;
margin: 0 auto;
width: 1000px;
max-width: 1000px;
display: flex;
flex-direction: column;
@media (max-width: 768px) {
@media (max-width: 640px) {
width: 100%;
padding: 3rem 1rem 0 1rem;
box-sizing: border-box;
max-width: 100%;
}
}
.panel-header {
position: relative;
display: flex;
align-items: center;
gap: 1rem;
padding: 1.5rem 1.5rem 1.25rem 1.5rem;
border-radius: 10px 10px 0 0;
border: 1px solid var(--border-color);
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
.header-icon-wrapper {
display: flex;
align-items: center;
justify-content: center;
width: 48px;
height: 48px;
background: var(--primary-color);
border-radius: 10px;
box-shadow: 0 3px 8px rgba(0, 0, 0, 0.2);
.header-icon {
font-size: 1.5rem;
color: var(--primary-contrast-color);
}
}
.header-text {
flex: 1;
.panel-title {
margin: 0 0 0.25rem 0;
font-size: 1.25rem;
font-weight: 600;
color: var(--text-color);
}
.panel-description {
margin: 0;
font-size: 0.875rem;
color: var(--text-secondary-color);
}
}
::ng-deep .close-button {
position: absolute;
top: 0.75rem;
right: 0.75rem;
}
@media (max-width: 480px) {
padding: 1rem;
.header-icon-wrapper {
width: 40px;
height: 40px;
.header-icon {
font-size: 1.25rem;
}
}
.header-text {
.panel-title {
font-size: 1.125rem;
}
.panel-description {
font-size: 0.8rem;
}
}
::ng-deep .close-button {
top: 0.5rem;
right: 0.5rem;
}
}
}
.settings-controls {
display: flex;
flex-direction: column;
gap: 0.75rem;
padding: 1rem 2rem;
background: var(--card-background);
border: 1px solid var(--border-color);
border-top: none;
.settings-info {
.info-content {
display: flex;
gap: 0.75rem;
padding: 0.75rem;
background: var(--overlay-background);
border-radius: 6px;
border: 1px solid var(--p-primary-300);
.info-icon {
color: var(--primary-color);
font-size: 1.125rem;
flex-shrink: 0;
margin-top: 0.125rem;
}
.info-text {
flex: 1;
p {
margin: 0;
line-height: 1.5;
font-size: 0.875rem;
color: var(--text-color-secondary);
}
}
}
}
@media (max-width: 480px) {
padding: 1rem;
gap: 0.5rem;
.settings-info {
.info-content {
flex-direction: column;
gap: 0.5rem;
}
}
}
}
.scrollers-container {
padding: 1.5rem 2rem;
background: var(--card-background);
border: 1px solid var(--border-color);
border-top: none;
min-height: 200px;
max-height: 450px;
overflow-y: auto;
&::-webkit-scrollbar {
width: 6px;
}
&::-webkit-scrollbar-track {
background: var(--overlay-background);
border-radius: 3px;
}
&::-webkit-scrollbar-thumb {
background: var(--border-color);
border-radius: 3px;
&:hover {
background: var(--primary-color);
}
}
@media (max-width: 480px) {
padding: 1rem;
max-height: 400px;
}
}
@@ -59,22 +220,6 @@
}
}
.scroller-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
margin-bottom: 1rem;
padding-bottom: 1rem;
border-bottom: 1px solid var(--p-content-border-color);
@media (max-width: 768px) {
flex-direction: column;
align-items: flex-start;
gap: 0.75rem;
}
}
.scroller-fields {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
@@ -121,61 +266,55 @@ label {
font-weight: 500;
}
.footer-actions {
.dialog-footer {
display: flex;
justify-content: flex-end;
gap: 0.75rem;
margin-top: 2rem;
padding-top: 1.5rem;
border-top: 1px solid var(--p-content-border-color);
justify-content: space-between;
align-items: center;
gap: 1rem;
padding: 1.25rem 1.5rem;
background: var(--card-background);
border: 1px solid var(--border-color);
border-top: none;
border-radius: 0 0 10px 10px;
box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.06);
@media (max-width: 768px) {
flex-wrap: wrap;
justify-content: stretch;
.footer-left {
display: flex;
align-items: center;
gap: 0.5rem;
flex: 1;
}
::ng-deep button {
flex: 1;
.footer-actions {
display: flex;
gap: 0.75rem;
}
@media (max-width: 640px) {
flex-direction: column;
padding: 1rem;
gap: 0.75rem;
.footer-left {
width: 100%;
flex-direction: column;
gap: 0.5rem;
::ng-deep .p-button {
width: 100%;
}
}
.footer-actions {
width: 100%;
::ng-deep .p-button {
flex: 1;
}
}
}
}
.settings-info {
border: 1px solid var(--p-primary-300);
margin-bottom: 2rem;
padding: 0.75rem;
border-radius: 0.375rem;
@media (max-width: 768px) {
padding: 0.75rem !important;
}
}
.settings-info-title {
color: var(--p-primary-600);
font-size: 1.125rem;
font-weight: 600;
margin-bottom: 0.5rem;
i {
margin-right: 0.25rem;
}
@media (max-width: 768px) {
font-size: 1rem;
}
}
.settings-info-text {
margin: 0;
line-height: 1.5;
font-size: 0.875rem;
color: var(--text-color-secondary);
@media (max-width: 768px) {
font-size: 0.813rem;
}
}
.add-scroller-wrapper {
margin-bottom: 1rem;
margin-bottom: 0;
}
@@ -0,0 +1,65 @@
<div class="reading-sessions-container">
@if (loading && sessions.length === 0) {
<div class="loading-state">
<p-progressSpinner strokeWidth="4" fill="transparent" animationDuration=".8s"></p-progressSpinner>
<p class="loading-text">Loading reading sessions...</p>
</div>
} @else if (sessions.length === 0) {
<div class="empty-state">
<i class="pi pi-clock" style="font-size: 3rem; color: var(--text-color-secondary);"></i>
<p>No reading sessions recorded yet</p>
</div>
} @else {
<p-table
[value]="sessions"
[lazy]="true"
[paginator]="true"
[rows]="rows"
[totalRecords]="totalRecords"
[loading]="loading"
[first]="first"
(onLazyLoad)="onPageChange($event)"
[showCurrentPageReport]="true"
currentPageReportTemplate="Showing {first} to {last} of {totalRecords} sessions"
class="p-datatable-sm">
<ng-template #header>
<tr>
<th>Start Time</th>
<th>End Time</th>
<th>Duration</th>
<th>Progress</th>
<th>Progress Delta</th>
<th>Location</th>
</tr>
</ng-template>
<ng-template #body let-session>
<tr>
<td>{{ formatDate(session.startTime) }}</td>
<td>{{ formatDate(session.endTime) }}</td>
<td>{{ formatDuration(session.durationSeconds) }}</td>
<td>
@if (session.startProgress !== null && session.startProgress !== undefined && session.endProgress !== null && session.endProgress !== undefined) {
<span>{{ session.startProgress }}% → {{ session.endProgress }}%</span>
} @else {
<span class="text-color-secondary">-</span>
}
</td>
<td>
@if (session.progressDelta !== null && session.progressDelta !== undefined) {
<p-tag [value]="(session.progressDelta > 0 ? '+' : '') + session.progressDelta + '%'" [severity]="getProgressColor(session.progressDelta)"></p-tag>
} @else {
<span class="text-color-secondary">N/A</span>
}
</td>
<td>
@if (session.startLocation && session.endLocation && isPageNumber(session.startLocation)) {
<span class="location-text">Page {{ session.startLocation }} → Page {{ session.endLocation }}</span>
} @else {
<span class="text-color-secondary">-</span>
}
</td>
</tr>
</ng-template>
</p-table>
}
</div>
@@ -0,0 +1,51 @@
.reading-sessions-container {
padding: 1rem 0;
}
.loading-state,
.empty-state {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 3rem;
gap: 1rem;
}
.loading-text {
color: var(--text-color-secondary);
font-size: 0.9rem;
}
.empty-state p {
color: var(--text-color-secondary);
font-size: 1rem;
}
.location-text {
font-size: 0.875rem;
color: var(--text-color);
}
:host ::ng-deep {
.p-datatable {
.p-datatable-thead > tr > th {
background-color: var(--card-background);
color: var(--text-color);
font-weight: 600;
font-size: 0.875rem;
white-space: nowrap;
border-color: var(--border-color);
}
.p-datatable-tbody > tr > td {
padding: 0.35rem 0.65rem;
font-size: 0.875rem;
border-color: var(--border-color);
}
.p-datatable-wrapper {
overflow-x: auto;
}
}
}

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