From b649433ec3cf432fa8610f79bb97123d1fabe09d Mon Sep 17 00:00:00 2001 From: acx10 Date: Wed, 24 Dec 2025 23:18:06 -0700 Subject: [PATCH 01/25] Update readme styling --- README.md | 350 ++++++++++++++++++++++++++++++++++++++---------------- 1 file changed, 248 insertions(+), 102 deletions(-) diff --git a/README.md b/README.md index 7818b86b9..7d162c62e 100644 --- a/README.md +++ b/README.md @@ -1,114 +1,196 @@ -# BookLore +
-![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, Reimagined* + +[![Release](https://img.shields.io/github/v/release/adityachandelgit/BookLore?style=for-the-badge&color=4c1d95&logo=github)](https://github.com/adityachandelgit/BookLore/releases) +[![License](https://img.shields.io/github/license/adityachandelgit/BookLore?style=for-the-badge&color=059669)](LICENSE) +[![Stars](https://img.shields.io/github/stars/adityachandelgit/BookLore?style=for-the-badge&color=f59e0b&logo=github)](https://github.com/adityachandelgit/BookLore/stargazers) +[![Docker](https://img.shields.io/docker/pulls/booklore/booklore?style=for-the-badge&logo=docker&color=2496ED)](https://hub.docker.com/r/booklore/booklore) + +[![Discord](https://img.shields.io/badge/Discord-Join_Community-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&logo=opencollective&label=Backers&color=7FADF2)](https://opencollective.com/booklore) + +--- + +**A self-hosted, feature-rich platform for organizing and managing your digital book collection.** +*Built for book lovers, by book lovers.* ![BookLore Demo](assets/demo.gif) -## โœจ Key Features +[**โœจ Live Demo**](https://demo.booklore.dev) โ€ข [**๐Ÿ“– Documentation**](https://booklore-app.github.io/booklore-docs/) โ€ข [**๐Ÿ› Report Bug**](https://github.com/adityachandelgit/BookLore/issues) โ€ข [**๐Ÿ’ก Request Feature**](https://github.com/adityachandelgit/BookLore/issues) -- ๐Ÿ“š **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 +
-## ๐Ÿ’– Support the Project +--- -If you find **BookLore** helpful, please consider supporting its development: +## ๐ŸŒŸ Why BookLore? -- โญ 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) +BookLore transforms the way you interact with your digital library. Whether you're a casual reader or a bibliophile with thousands of titles, BookLore provides the tools you need to organize, discover, and enjoy your collection. -## ๐ŸŒ Live Demo: Explore BookLore in Action + + + + + + + + + +
-Evaluate BookLoreโ€™s features and user experience in a live environment: +### ๐Ÿ“š **Smart Library Management** +- Custom shelves with intelligent filtering +- Dynamic smart collections that auto-update +- Powerful search across your entire library +- Bulk operations for efficient management -**Demo Access:** + -- ๐ŸŒ **URL:** [demo.booklore.dev](https://demo.booklore.dev) -- ๐Ÿ‘ค **Username:** `booklore` -- ๐Ÿ”‘ **Password:** `9HC20PGGfitvWaZ1` +### ๐Ÿ”„ **Seamless Integration** +- Native Kobo device synchronization +- KOReader progress tracking +- OPDS protocol support +- Email sharing capabilities -> โš ๏ธ **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. +
-## ๐Ÿš€ Getting Started with BookLore +### ๐Ÿง  **Intelligent Metadata** +- Auto-fetch from multiple sources +- Goodreads, Amazon, Google Books integration +- Community reviews and ratings +- Custom metadata editing -Kick off your BookLore journey with our official documentation and helpful video guides. + -๐Ÿ“˜ [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. +### ๐Ÿ‘ฅ **Multi-User Ready** +- Granular permission controls +- OIDC authentication support +- Private notes per user +- Shared library management -> ๐Ÿ’ก **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! +
-## ๐Ÿณ Deploy with Docker +--- -You can quickly set up and run BookLore using Docker. +## โœจ Feature Highlights -### 1๏ธโƒฃ Install Docker & Docker Compose +
+๐Ÿ“– Reading Experience -Ensure you have [Docker](https://docs.docker.com/get-docker/) and [Docker Compose](https://docs.docker.com/compose/install/) installed. +- **Built-in Reader**: Enjoy PDFs, EPUBs, and comics with customizable themes +- **Progress Tracking**: Sync reading progress across devices +- **Personal Notes**: Save private annotations visible only to you +- **Mobile Optimized**: Fully responsive design for reading anywhere -**Image Repositories:** +
-- Docker Hub: `https://hub.docker.com/r/booklore/booklore` -- GitHub Container Registry: `https://ghcr.io/booklore-app/booklore` +
+๐Ÿ”ง Power Features -> **Note:** Legacy images under `https://ghcr.io/adityachandelgit/booklore-app` will remain available but will not receive new updates. +- **BookDrop Import**: Auto-detect and bulk import from a watched folder +- **Magic Shelves**: Create rule-based collections that update automatically +- **Format Conversion**: Automatic EPUB to KEPUB conversion +- **Metadata Enrichment**: Pull rich details from multiple online sources -### 2๏ธโƒฃ Set Up Your docker-compose.yml Configuration +
-**Step 1: Create a `.env` file** in the same directory as your `docker-compose.yml`: +
+๐ŸŒ Connectivity + +- **OPDS Server**: Connect any compatible reading app wirelessly +- **Kobo Integration**: Seamless sync with Kobo e-readers +- **API Access**: Programmatic access to your library +- **Email Distribution**: One-click book sharing via email + +
+ +--- + +## ๐Ÿ’– Support Development + +
+ +Your support helps keep BookLore growing and improving! + +[![Open Collective](https://img.shields.io/badge/Support_on-Open_Collective-7FADF2?style=for-the-badge&logo=opencollective)](https://opencollective.com/booklore) +[![Star Repository](https://img.shields.io/badge/โญ_Star-Repository-fbbf24?style=for-the-badge&logo=github)](https://github.com/adityachandelgit/BookLore) + +
+ +**Current Fundraising Goal:** ๐ŸŽฏ Kobo Device for Testing +Help us implement and test native Kobo sync support by [contributing to our bounty โ†’](https://opencollective.com/booklore/projects/kobo-device-for-testing) + +--- + +## ๐ŸŒ Try the Live Demo + +Experience BookLore before deploying your own instance: + +
+ +| ๐Ÿ”— | **[demo.booklore.dev](https://demo.booklore.dev)** | +|:---:|:---| +| ๐Ÿ‘ค | **Username:** `booklore` | +| ๐Ÿ”‘ | **Password:** `9HC20PGGfitvWaZ1` | + +
+ +> **๐Ÿ“Œ Note:** Demo has standard user permissions. Admin features require a self-hosted instance. + +--- + +## ๐Ÿš€ Quick Start + +### Prerequisites + +Ensure you have [Docker](https://docs.docker.com/get-docker/) and [Docker Compose](https://docs.docker.com/compose/install/) installed on your system. + +### ๐Ÿ“ฆ Available Images + +| Registry | Image URL | +|----------|-----------| +| ๐Ÿณ Docker Hub | `booklore/booklore:latest` | +| ๐Ÿ“ฆ GitHub | `ghcr.io/booklore-app/booklore:latest` | + +> โš ๏ธ Legacy images at `ghcr.io/adityachandelgit/booklore-app` remain available but won't receive updates. + +--- + +## ๐Ÿณ Docker Deployment + +### Step 1: Create Environment Configuration + +Create a `.env` file with your configuration: ```ini -# BookLore Application Settings +# Application Settings APP_USER_ID=0 APP_GROUP_ID=0 TZ=Etc/UTC BOOKLORE_PORT=6060 -# Database Connection (BookLore) +# Database Connection DATABASE_URL=jdbc:mariadb://mariadb:3306/booklore DB_USER=booklore DB_PASSWORD=ChangeMe_BookLoreApp_2025! -# MariaDB Container Settings +# MariaDB Configuration 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 `docker-compose.yml`: ```yaml services: booklore: image: booklore/booklore:latest - # Alternative: Use GitHub Container Registry - # image: ghcr.io/booklore-app/booklore:latest container_name: booklore environment: - USER_ID=${APP_USER_ID} @@ -144,81 +226,145 @@ services: - ./mariadb/config:/config restart: unless-stopped healthcheck: - test: [ "CMD", "mariadb-admin", "ping", "-h", "localhost" ] + test: ["CMD", "mariadb-admin", "ping", "-h", "localhost"] interval: 5s timeout: 5s 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 ``` -## ๐Ÿ“ฅ Bookdrop Folder: Auto-Import Files +--- -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. +## ๐Ÿ“ฅ BookDrop: Automated Import -### ๐Ÿ” How It Works +The **BookDrop** feature enables effortless bulk importing of books into your library. -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. +### How It Works -### โš™๏ธ Configuration (Docker Setup) - -To enable the Bookdrop feature in Docker: - -```yaml -services: - booklore: - ... - volumes: - - ./data:/app/data - - ./books:/books - - ./bookdrop:/bookdrop # ๐Ÿ‘ˆ Bookdrop directory +```mermaid +graph LR + A[Drop Files] --> B[Auto-Detection] + B --> C[Metadata Extraction] + C --> D[Review & Edit] + D --> E[Import to Library] ``` -## ๐Ÿค Community & Support +1. **๐Ÿ“ Drop Files**: Place books in the BookDrop folder +2. **๐Ÿ” Detection**: Automatic file monitoring and recognition +3. **๐Ÿ“Š Metadata**: Extract or fetch book information +4. **โœ๏ธ Review**: Edit metadata before final import +5. **โœ… Import**: Add to your organized library -- ๐Ÿž 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) +### Configuration -## ๐Ÿ“Š Repository Activity +The BookDrop folder is automatically configured in the Docker setup: -![Alt](https://repobeats.axiom.co/api/embed/44a04220bfc5136e7064181feb07d5bf0e59e27e.svg "Repobeats analytics image") +```yaml +volumes: + - ./bookdrop:/bookdrop # ๐Ÿ‘ˆ Auto-import directory +``` +Simply drop your `.pdf`, `.epub`, `.cbz`, or other supported files into this folder, and BookLore handles the rest! -## โญ Star History +--- + +## ๐Ÿ“š Documentation + +For comprehensive guides, configuration options, and troubleshooting: + +
+ +### **[๐Ÿ“– Visit Full Documentation โ†’](https://booklore-app.github.io/booklore-docs/docs/getting-started/)** + +*Installation โ€ข Configuration โ€ข Features โ€ข API โ€ข Troubleshooting* + +
+ +๐Ÿ’ก **Contribute to Docs**: Improve our documentation at [booklore-app/booklore-docs](https://github.com/booklore-app/booklore-docs) + +--- + +## ๐Ÿค Community & Contribution + +
+ +[![Discord](https://img.shields.io/badge/๐Ÿ’ฌ_Chat-Discord-5865F2?style=for-the-badge&logo=discord&logoColor=white)](https://discord.gg/Ee5hd458Uz) +[![Contributing](https://img.shields.io/badge/๐Ÿ“_Read-Contributing_Guide-4c1d95?style=for-the-badge)](CONTRIBUTING.md) +[![Issues](https://img.shields.io/badge/๐Ÿ›_Report-Issues-ef4444?style=for-the-badge&logo=github)](https://github.com/adityachandelgit/BookLore/issues) + +
+ +We welcome contributions of all kinds! Whether it's: +- ๐Ÿ› Bug reports and fixes +- โœจ Feature requests and implementations +- ๐Ÿ“– Documentation improvements +- ๐ŸŒ Translations and localization + +--- + +## ๐Ÿ“Š Project Stats + +
+ +### Repository Activity + +![Activity](https://repobeats.axiom.co/api/embed/44a04220bfc5136e7064181feb07d5bf0e59e27e.svg "Repobeats analytics") + +### โญ Star History - Star History Chart + Star History Chart -## ๐Ÿ‘จโ€๐Ÿ’ป Contributors & Developers +
-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) +## ๐Ÿ™ Contributors + +Thank you to all our amazing contributors who help make BookLore better! + +
+ +[![Contributors](https://contrib.rocks/image?repo=adityachandelgit/BookLore)](https://github.com/adityachandelgit/BookLore/graphs/contributors) + +
+ +--- ## โš–๏ธ License -* [GNU GPL v3](http://www.gnu.org/licenses/gpl.html) -* Copyright 2024-2025 +
+ +**[GNU General Public License v3.0](http://www.gnu.org/licenses/gpl.html)** + +Copyright ยฉ 2024-2025 BookLore Contributors + +
+ +--- + +
+ +**Made with โค๏ธ by the BookLore Community** + +*Star โญ this repository if you find it helpful!* + +
From e85dab8580224e33ef4e1b38f569acca2ed61f03 Mon Sep 17 00:00:00 2001 From: acx10 Date: Wed, 24 Dec 2025 23:35:12 -0700 Subject: [PATCH 02/25] Revert --- README.md | 344 ++++++++++++++++-------------------------------------- 1 file changed, 99 insertions(+), 245 deletions(-) diff --git a/README.md b/README.md index 7d162c62e..7818b86b9 100644 --- a/README.md +++ b/README.md @@ -1,196 +1,114 @@ -
+# BookLore -# ๐Ÿ“š BookLore +![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) -### *Your Personal Library, Reimagined* - -[![Release](https://img.shields.io/github/v/release/adityachandelgit/BookLore?style=for-the-badge&color=4c1d95&logo=github)](https://github.com/adityachandelgit/BookLore/releases) -[![License](https://img.shields.io/github/license/adityachandelgit/BookLore?style=for-the-badge&color=059669)](LICENSE) -[![Stars](https://img.shields.io/github/stars/adityachandelgit/BookLore?style=for-the-badge&color=f59e0b&logo=github)](https://github.com/adityachandelgit/BookLore/stargazers) -[![Docker](https://img.shields.io/docker/pulls/booklore/booklore?style=for-the-badge&logo=docker&color=2496ED)](https://hub.docker.com/r/booklore/booklore) - -[![Discord](https://img.shields.io/badge/Discord-Join_Community-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&logo=opencollective&label=Backers&color=7FADF2)](https://opencollective.com/booklore) - ---- - -**A self-hosted, feature-rich platform for organizing and managing your digital book collection.** -*Built for book lovers, by book lovers.* +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. ![BookLore Demo](assets/demo.gif) -[**โœจ Live Demo**](https://demo.booklore.dev) โ€ข [**๐Ÿ“– Documentation**](https://booklore-app.github.io/booklore-docs/) โ€ข [**๐Ÿ› Report Bug**](https://github.com/adityachandelgit/BookLore/issues) โ€ข [**๐Ÿ’ก Request Feature**](https://github.com/adityachandelgit/BookLore/issues) +## โœจ Key Features -
+- ๐Ÿ“š **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 ---- +## ๐Ÿ’– Support the Project -## ๐ŸŒŸ Why BookLore? +If you find **BookLore** helpful, please consider supporting its development: -BookLore transforms the way you interact with your digital library. Whether you're a casual reader or a bibliophile with thousands of titles, BookLore provides the tools you need to organize, discover, and enjoy your collection. +- โญ 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) - - - - - - - - - -
+## ๐ŸŒ Live Demo: Explore BookLore in Action -### ๐Ÿ“š **Smart Library Management** -- Custom shelves with intelligent filtering -- Dynamic smart collections that auto-update -- Powerful search across your entire library -- Bulk operations for efficient management +Evaluate BookLoreโ€™s features and user experience in a live environment: - +**Demo Access:** -### ๐Ÿ”„ **Seamless Integration** -- Native Kobo device synchronization -- KOReader progress tracking -- OPDS protocol support -- Email sharing capabilities +- ๐ŸŒ **URL:** [demo.booklore.dev](https://demo.booklore.dev) +- ๐Ÿ‘ค **Username:** `booklore` +- ๐Ÿ”‘ **Password:** `9HC20PGGfitvWaZ1` -
+> โš ๏ธ **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. -### ๐Ÿง  **Intelligent Metadata** -- Auto-fetch from multiple sources -- Goodreads, Amazon, Google Books integration -- Community reviews and ratings -- Custom metadata editing +## ๐Ÿš€ Getting Started with BookLore - +Kick off your BookLore journey with our official documentation and helpful video guides. -### ๐Ÿ‘ฅ **Multi-User Ready** -- Granular permission controls -- OIDC authentication support -- Private notes per user -- Shared 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. -
+> ๐Ÿ’ก **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! ---- +## ๐Ÿณ Deploy with Docker -## โœจ Feature Highlights +You can quickly set up and run BookLore using Docker. -
-๐Ÿ“– Reading Experience +### 1๏ธโƒฃ Install Docker & Docker Compose -- **Built-in Reader**: Enjoy PDFs, EPUBs, and comics with customizable themes -- **Progress Tracking**: Sync reading progress across devices -- **Personal Notes**: Save private annotations visible only to you -- **Mobile Optimized**: Fully responsive design for reading anywhere +Ensure you have [Docker](https://docs.docker.com/get-docker/) and [Docker Compose](https://docs.docker.com/compose/install/) installed. -
+**Image Repositories:** -
-๐Ÿ”ง Power Features +- Docker Hub: `https://hub.docker.com/r/booklore/booklore` +- GitHub Container Registry: `https://ghcr.io/booklore-app/booklore` -- **BookDrop Import**: Auto-detect and bulk import from a watched folder -- **Magic Shelves**: Create rule-based collections that update automatically -- **Format Conversion**: Automatic EPUB to KEPUB conversion -- **Metadata Enrichment**: Pull rich details from multiple online sources +> **Note:** Legacy images under `https://ghcr.io/adityachandelgit/booklore-app` will remain available but will not receive new updates. -
+### 2๏ธโƒฃ Set Up Your docker-compose.yml Configuration -
-๐ŸŒ Connectivity - -- **OPDS Server**: Connect any compatible reading app wirelessly -- **Kobo Integration**: Seamless sync with Kobo e-readers -- **API Access**: Programmatic access to your library -- **Email Distribution**: One-click book sharing via email - -
- ---- - -## ๐Ÿ’– Support Development - -
- -Your support helps keep BookLore growing and improving! - -[![Open Collective](https://img.shields.io/badge/Support_on-Open_Collective-7FADF2?style=for-the-badge&logo=opencollective)](https://opencollective.com/booklore) -[![Star Repository](https://img.shields.io/badge/โญ_Star-Repository-fbbf24?style=for-the-badge&logo=github)](https://github.com/adityachandelgit/BookLore) - -
- -**Current Fundraising Goal:** ๐ŸŽฏ Kobo Device for Testing -Help us implement and test native Kobo sync support by [contributing to our bounty โ†’](https://opencollective.com/booklore/projects/kobo-device-for-testing) - ---- - -## ๐ŸŒ Try the Live Demo - -Experience BookLore before deploying your own instance: - -
- -| ๐Ÿ”— | **[demo.booklore.dev](https://demo.booklore.dev)** | -|:---:|:---| -| ๐Ÿ‘ค | **Username:** `booklore` | -| ๐Ÿ”‘ | **Password:** `9HC20PGGfitvWaZ1` | - -
- -> **๐Ÿ“Œ Note:** Demo has standard user permissions. Admin features require a self-hosted instance. - ---- - -## ๐Ÿš€ Quick Start - -### Prerequisites - -Ensure you have [Docker](https://docs.docker.com/get-docker/) and [Docker Compose](https://docs.docker.com/compose/install/) installed on your system. - -### ๐Ÿ“ฆ Available Images - -| Registry | Image URL | -|----------|-----------| -| ๐Ÿณ Docker Hub | `booklore/booklore:latest` | -| ๐Ÿ“ฆ GitHub | `ghcr.io/booklore-app/booklore:latest` | - -> โš ๏ธ Legacy images at `ghcr.io/adityachandelgit/booklore-app` remain available but won't receive updates. - ---- - -## ๐Ÿณ Docker Deployment - -### Step 1: Create Environment Configuration - -Create a `.env` file with your configuration: +**Step 1: Create a `.env` file** in the same directory as your `docker-compose.yml`: ```ini -# Application Settings +# BookLore Application Settings APP_USER_ID=0 APP_GROUP_ID=0 TZ=Etc/UTC BOOKLORE_PORT=6060 -# Database Connection +# Database Connection (BookLore) DATABASE_URL=jdbc:mariadb://mariadb:3306/booklore DB_USER=booklore DB_PASSWORD=ChangeMe_BookLoreApp_2025! -# MariaDB Configuration +# MariaDB Container Settings DB_USER_ID=1000 DB_GROUP_ID=1000 MYSQL_ROOT_PASSWORD=ChangeMe_MariaDBRoot_2025! MYSQL_DATABASE=booklore ``` -### Step 2: Create Docker Compose File - -Create `docker-compose.yml`: +**Step 2: Create a `docker-compose.yml` file** that references the `.env` variables: ```yaml services: booklore: image: booklore/booklore:latest + # Alternative: Use GitHub Container Registry + # image: ghcr.io/booklore-app/booklore:latest container_name: booklore environment: - USER_ID=${APP_USER_ID} @@ -226,145 +144,81 @@ services: - ./mariadb/config:/config restart: unless-stopped healthcheck: - test: ["CMD", "mariadb-admin", "ping", "-h", "localhost"] + test: [ "CMD", "mariadb-admin", "ping", "-h", "localhost" ] interval: 5s timeout: 5s retries: 10 ``` -### Step 3: Launch BookLore +### 3๏ธโƒฃ Start the Containers -```bash +Run the following command to start the services: + +```ini docker compose up -d ``` -### Step 4: Access Your Library +### 4๏ธโƒฃ Access BookLore -Open your browser and navigate to: +Once the containers are up, access BookLore in your browser at: -``` +```ini http://localhost:6060 ``` ---- +## ๐Ÿ“ฅ Bookdrop Folder: Auto-Import Files -## ๐Ÿ“ฅ BookDrop: Automated Import +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. -The **BookDrop** feature enables effortless bulk importing of books into your library. +### ๐Ÿ” How It Works -### 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. -```mermaid -graph LR - A[Drop Files] --> B[Auto-Detection] - B --> C[Metadata Extraction] - C --> D[Review & Edit] - D --> E[Import to Library] -``` +### โš™๏ธ Configuration (Docker Setup) -1. **๐Ÿ“ Drop Files**: Place books in the BookDrop folder -2. **๐Ÿ” Detection**: Automatic file monitoring and recognition -3. **๐Ÿ“Š Metadata**: Extract or fetch book information -4. **โœ๏ธ Review**: Edit metadata before final import -5. **โœ… Import**: Add to your organized library - -### Configuration - -The BookDrop folder is automatically configured in the Docker setup: +To enable the Bookdrop feature in Docker: ```yaml -volumes: - - ./bookdrop:/bookdrop # ๐Ÿ‘ˆ Auto-import directory +services: + booklore: + ... + volumes: + - ./data:/app/data + - ./books:/books + - ./bookdrop:/bookdrop # ๐Ÿ‘ˆ Bookdrop directory ``` -Simply drop your `.pdf`, `.epub`, `.cbz`, or other supported files into this folder, and BookLore handles the rest! +## ๐Ÿค 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) -## ๐Ÿ“š Documentation +## ๐Ÿ“Š Repository Activity -For comprehensive guides, configuration options, and troubleshooting: +![Alt](https://repobeats.axiom.co/api/embed/44a04220bfc5136e7064181feb07d5bf0e59e27e.svg "Repobeats analytics image") -
-### **[๐Ÿ“– Visit Full Documentation โ†’](https://booklore-app.github.io/booklore-docs/docs/getting-started/)** - -*Installation โ€ข Configuration โ€ข Features โ€ข API โ€ข Troubleshooting* - -
- -๐Ÿ’ก **Contribute to Docs**: Improve our documentation at [booklore-app/booklore-docs](https://github.com/booklore-app/booklore-docs) - ---- - -## ๐Ÿค Community & Contribution - -
- -[![Discord](https://img.shields.io/badge/๐Ÿ’ฌ_Chat-Discord-5865F2?style=for-the-badge&logo=discord&logoColor=white)](https://discord.gg/Ee5hd458Uz) -[![Contributing](https://img.shields.io/badge/๐Ÿ“_Read-Contributing_Guide-4c1d95?style=for-the-badge)](CONTRIBUTING.md) -[![Issues](https://img.shields.io/badge/๐Ÿ›_Report-Issues-ef4444?style=for-the-badge&logo=github)](https://github.com/adityachandelgit/BookLore/issues) - -
- -We welcome contributions of all kinds! Whether it's: -- ๐Ÿ› Bug reports and fixes -- โœจ Feature requests and implementations -- ๐Ÿ“– Documentation improvements -- ๐ŸŒ Translations and localization - ---- - -## ๐Ÿ“Š Project Stats - -
- -### Repository Activity - -![Activity](https://repobeats.axiom.co/api/embed/44a04220bfc5136e7064181feb07d5bf0e59e27e.svg "Repobeats analytics") - -### โญ Star History +## โญ Star History - Star History Chart + Star History Chart -
+## ๐Ÿ‘จโ€๐Ÿ’ป Contributors & Developers ---- +Thanks to all the amazing people who contribute to Booklore. -## ๐Ÿ™ Contributors - -Thank you to all our amazing contributors who help make BookLore better! - -
- -[![Contributors](https://contrib.rocks/image?repo=adityachandelgit/BookLore)](https://github.com/adityachandelgit/BookLore/graphs/contributors) - -
- ---- +[![Contributors List](https://contrib.rocks/image?repo=adityachandelgit/BookLore)](https://github.com/adityachandelgit/BookLore/graphs/contributors) ## โš–๏ธ License -
- -**[GNU General Public License v3.0](http://www.gnu.org/licenses/gpl.html)** - -Copyright ยฉ 2024-2025 BookLore Contributors - -
- ---- - -
- -**Made with โค๏ธ by the BookLore Community** - -*Star โญ this repository if you find it helpful!* - -
+* [GNU GPL v3](http://www.gnu.org/licenses/gpl.html) +* Copyright 2024-2025 From b4b4d8f492352630a32becf746d4903726416285 Mon Sep 17 00:00:00 2001 From: ACX <8075870+acx10@users.noreply.github.com> Date: Thu, 25 Dec 2025 00:17:19 -0700 Subject: [PATCH 03/25] Readme styling (#1982) Co-authored-by: acx10 --- README.md | 407 +++++++++++++++++++++++++++++++++++++++++------------- 1 file changed, 311 insertions(+), 96 deletions(-) diff --git a/README.md b/README.md index 7818b86b9..c1fd26554 100644 --- a/README.md +++ b/README.md @@ -1,107 +1,237 @@ -# BookLore +
-![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) +

+ BookLore Demo +

-## โœจ 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 +
-Evaluate BookLoreโ€™s features and user experience in a live environment: +--- -**Demo Access:** +
-- ๐ŸŒ **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. +
-## ๐Ÿš€ Getting Started with BookLore + + + + + + + + + +
-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! + -## ๐Ÿณ 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 +
+ +### ๐Ÿ‘ฅ **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 + + + +### ๐Ÿš€ **Smart Features** + +- **BookDrop Import**: Auto-detect bulk files +- **Private Notes**: Personal reading annotations +- **Community Reviews**: Enriched book data +- **Progress Tracking**: Reading statistics + +
+ +--- + +
+ +## ๐Ÿ’– **Support the Project** + +
+ +
+ +Your support helps BookLore grow and improve! ๐ŸŒฑ + + + + + + + +
+ +### โญ **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) + + + +### ๐Ÿ’ฐ **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) + + + +### ๐Ÿ“ข **Spread the Word** + +Share BookLore with fellow book lovers and developers! + +
+ +> ๐ŸŽฏ **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) + +
+ +--- + +
+ +## ๐ŸŽฎ **Live Demo: Explore BookLore in Action** + +
+ +
+ +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. + +
+ +--- + +
+ +## ๐Ÿš€ **Getting Started with BookLore** + +### Choose Your Path + + + + + + +
+ +### ๐Ÿ“˜ **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)* + + + +### ๐Ÿณ **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* + +
+ +
+ +--- + +
+ +## ๐Ÿณ **Deploy with Docker** + +
+ +### **Prerequisites** Ensure you have [Docker](https://docs.docker.com/get-docker/) and [Docker Compose](https://docs.docker.com/compose/install/) installed. -**Image Repositories:** +
+๐Ÿ“ฆ Image Repositories -- 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 +
-**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!** + +--- + +
+ +## ๐Ÿ“ฅ **BookDrop: Automatic Import** + +### *Drop Files, Import Automatically* + +
+ +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) +
-## ๐Ÿ“Š Repository Activity +## ๐Ÿค **Community & Support** + + + + + + + +
-![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/adityachandelgit/BookLore/issues) + + + +### ๐Ÿ’ก **Feature Req** + +Have an idea? + +[![Request Feature](https://img.shields.io/badge/Suggest-4ecdc4?style=for-the-badge)](https://github.com/adityachandelgit/BookLore/issues/new) + + + +### ๐Ÿค **Contribute** + +Join development! + +[![Contributing](https://img.shields.io/badge/Contribute-95e1d3?style=for-the-badge)](CONTRIBUTING.md) + + + +### ๐Ÿ’ฌ **Chat** + +Join community! + +[![Discord](https://img.shields.io/badge/Discord-5865F2?style=for-the-badge&logo=discord&logoColor=white)](https://discord.gg/Ee5hd458Uz) + +
+ +
-## โญ Star History +--- + +
+ +## ๐Ÿ“Š **Project Analytics** + +### Repository Activity + +![Repository Activity](https://repobeats.axiom.co/api/embed/44a04220bfc5136e7064181feb07d5bf0e59e27e.svg) + +### โญ Star History - Star History Chart + Star History Chart -## ๐Ÿ‘จโ€๐Ÿ’ป Contributors & Developers +
-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) +
-## โš–๏ธ 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) + +
+ +--- + +
+ +## โš–๏ธ **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) + +--- + +Made with โค๏ธ by the BookLore community + +**[โฌ† Back to Top](#-booklore)** + +
From 77e06b868ea587f62860319543fc52df4ace81f4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bal=C3=A1zs=20Sz=C3=BCcs?= <127139797+balazs-szucs@users.noreply.github.com> Date: Thu, 25 Dec 2025 18:05:24 +0100 Subject: [PATCH 04/25] fix(epub-metadata): properly decode URL-encoded cover image hrefs in EPUB files (#1983) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Ensure cover image paths in EPUB manifest are URL-decoded before file access - Update EpubMetadataExtractor and EpubMetadataWriter to handle encoded hrefs - Add comprehensive tests for unicode and URL-encoded cover image filenames Signed-off-by: Balรกzs Szรผcs --- .../extractor/EpubMetadataExtractor.java | 5 +- .../metadata/writer/EpubMetadataWriter.java | 7 +- .../extractor/EpubMetadataExtractorTest.java | 91 ++++++++ .../writer/EpubMetadataWriterTest.java | 210 ++++++++++++++++++ 4 files changed, 310 insertions(+), 3 deletions(-) create mode 100644 booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/writer/EpubMetadataWriterTest.java diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/extractor/EpubMetadataExtractor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/extractor/EpubMetadataExtractor.java index 01a7da24a..72f40fdf4 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/extractor/EpubMetadataExtractor.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/extractor/EpubMetadataExtractor.java @@ -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; @@ -332,7 +334,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); } } } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/writer/EpubMetadataWriter.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/writer/EpubMetadataWriter.java index ef5995c7f..30d439931 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/writer/EpubMetadataWriter.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/writer/EpubMetadataWriter.java @@ -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; @@ -406,7 +408,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 +421,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); diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/extractor/EpubMetadataExtractorTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/extractor/EpubMetadataExtractorTest.java index 07dfa0df9..255de003a 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/extractor/EpubMetadataExtractorTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/extractor/EpubMetadataExtractorTest.java @@ -721,5 +721,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(""" + + + + Book with Unicode Cover + + + + + + """, id, encodedHref); + + File epubFile = tempDir.resolve("test-unicode-cover-" + System.nanoTime() + ".epub").toFile(); + + String containerXml = """ + + + + + + + """; + + 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; + } } diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/writer/EpubMetadataWriterTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/writer/EpubMetadataWriterTest.java new file mode 100644 index 000000000..9a04018e2 --- /dev/null +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/writer/EpubMetadataWriterTest.java @@ -0,0 +1,210 @@ +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.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Collections; +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("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 byte[] createEpubWithUnicodeCoverHref() throws IOException { + String opfContent = """ + + + + Test Book with Unicode Cover + Test Author + + + + + + + + + + + + """; + + String containerXml = """ + + + + + + + """; + + String htmlContent = """ + + + + + Test + + +

Test Content

+ + + """; + + String ncxContent = """ + + + + + + + + Test Book + + + + + Test + + + + + + """; + + 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 + }; + } +} \ No newline at end of file From f5e99d52c13790a2f82c978ca3aa9dc1f9b0982f Mon Sep 17 00:00:00 2001 From: farfromrefuge Date: Thu, 25 Dec 2025 18:09:33 +0100 Subject: [PATCH 05/25] Fix: regenerate improvements (#1981) * chore: report error on cover regeneration fail * refactor: use RxJS forkJoin instead of Promise.all - Replace Promise-based approach with RxJS forkJoin for better consistency - Remove console.log debug statement - Improve error handling with proper RxJS operators Co-authored-by: farfromrefug <655344+farfromrefug@users.noreply.github.com> * chore: cleanup * chore: rework per development upstream * chore: updating books on bulk cover regenerate * chore: working * chore: metadata regenerateCover pdate UI * chore: review per comments --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- .../booklore/exception/ApiError.java | 1 + .../booklore/model/websocket/Topic.java | 1 + .../service/fileprocessor/CbxProcessor.java | 4 ++ .../service/metadata/BookMetadataService.java | 41 +++++++++++++++++-- booklore-ui/src/app/app.component.ts | 5 +++ .../book-browser/book-browser.component.ts | 4 +- .../app/features/book/service/book.service.ts | 18 ++++++++ .../metadata-editor.component.ts | 28 +++++++------ 8 files changed, 84 insertions(+), 18 deletions(-) diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/exception/ApiError.java b/booklore-api/src/main/java/com/adityachandel/booklore/exception/ApiError.java index f1042ffec..cc089b949 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/exception/ApiError.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/exception/ApiError.java @@ -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"), diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/websocket/Topic.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/websocket/Topic.java index 5d39cc048..79b023c28 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/websocket/Topic.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/websocket/Topic.java @@ -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"), diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/CbxProcessor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/CbxProcessor.java index b99e74473..90e857875 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/CbxProcessor.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/CbxProcessor.java @@ -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()); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookMetadataService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookMetadataService.java index fa81873ed..c6ffa69ad 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookMetadataService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookMetadataService.java @@ -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 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 bookIds) { List unlockedBooks = getUnlockedBookRegenerationInfos(bookIds); - SecurityContextVirtualThread.runWithSecurityContext(() -> - processBulkCoverRegeneration(unlockedBooks)); + SecurityContextVirtualThread.runWithSecurityContext(() -> processBulkCoverRegeneration(unlockedBooks)); } private List getUnlockedBookRegenerationInfos(Set 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 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 updatedBooks = new ArrayList<>(); + if (!refreshedIds.isEmpty()) { + org.springframework.transaction.support.TransactionTemplate tx = new org.springframework.transaction.support.TransactionTemplate(transactionManager); + + List> refreshedPatches = tx.execute(status -> { + List entities = bookQueryService.findAllWithMetadataByIds(new java.util.HashSet<>(refreshedIds)); + if (entities == null || entities.isEmpty()) return List.>of(); + + entities.forEach(e -> { + if (e.getMetadata() != null) e.getMetadata().getCoverUpdatedOn(); + }); + + return entities.stream() + .map(e -> java.util.Map.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) { diff --git a/booklore-ui/src/app/app.component.ts b/booklore-ui/src/app/app.component.ts index f35ce3914..de85f2508 100644 --- a/booklore-ui/src/app/app.component.ts +++ b/booklore-ui/src/app/app.component.ts @@ -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)) diff --git a/booklore-ui/src/app/features/book/components/book-browser/book-browser.component.ts b/booklore-ui/src/app/features/book/components/book-browser/book-browser.component.ts index 04c4dfd42..7a25085b2 100644 --- a/booklore-ui/src/app/features/book/components/book-browser/book-browser.component.ts +++ b/booklore-ui/src/app/features/book/components/book-browser/book-browser.component.ts @@ -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'; @@ -696,7 +696,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit { life: 3000 }); } - }); + }); } }); } diff --git a/booklore-ui/src/app/features/book/service/book.service.ts b/booklore-ui/src/app/features/book/service/book.service.ts index a0cbb9162..8f6e720ba 100644 --- a/booklore-ui/src/app/features/book/service/book.service.ts +++ b/booklore-ui/src/app/features/book/service/book.service.ts @@ -632,6 +632,24 @@ export class BookService { this.bookStateSubject.next({...currentState, books: updatedBooks}) } + + /** + * Incoming payload: [{ id: number, coverUpdatedOn: "2025-12-25T00:48:17Z" }, ...] + * Apply minimal patch to local state so UI updates the cover image (and can use cache-busting). + */ + handleMultipleBookCoverPatches(patches: { id: number; coverUpdatedOn: string }[]): void { + if (!patches || patches.length === 0) return; + const currentState = this.bookStateSubject.value; + 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.bookStateSubject.next({...currentState, books}); + } + toggleFieldLocks(bookIds: number[] | Set, fieldActions: Record): Observable { const bookIdSet = bookIds instanceof Set ? bookIds : new Set(bookIds); diff --git a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.ts b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.ts index b9256ce4f..1fa4a3aea 100644 --- a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.ts +++ b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.ts @@ -654,18 +654,22 @@ export class MetadataEditorComponent implements OnInit { regenerateCover(bookId: number) { this.bookService.regenerateCover(bookId).subscribe({ next: () => { - this.messageService.add({ - severity: "success", - summary: "Success", - detail: - "Book cover regenerated successfully. Refresh page to see the new cover.", - }); - }, - error: () => { - this.messageService.add({ - severity: "error", - summary: "Error", - detail: "Failed to start cover regeneration", + this.bookService.getBookByIdFromAPI(bookId, false).subscribe({ + next: (updatedBook) => { + this.bookService.handleBookUpdate(updatedBook); + this.messageService.add({ + severity: "success", + summary: "Success", + detail: "Book cover regenerated successfully.", + }); + }, + error: () => { + this.messageService.add({ + severity: "warning", + summary: "Partial Success", + detail: "Cover regenerated but failed to refresh display. Please refresh the page.", + }); + }, }); }, }); From 21bcc7d38283f8fa7e74dc17e1cd5f66461ca5bd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bal=C3=A1zs=20Sz=C3=BCcs?= <127139797+balazs-szucs@users.noreply.github.com> Date: Thu, 25 Dec 2025 18:10:14 +0100 Subject: [PATCH 06/25] perf(cbz): optimize CBZ reading (#1980) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * perf(cbz): improve zip file compatibility by enabling Unicode extra fields and ignoring local file headers Signed-off-by: Balรกzs Szรผcs * feat(perf): Implement robust ZipFile optimization with fallback Updated ZipFile reading logic in CbxReaderService, CbxProcessor, and CbxConversionService. Implemented a 'Fast Path' (Central Directory only) for speed (20x faster on large archives). Implemented a 'Slow Path' (Local Header scanning) fallback if the fast path fails or finds no images. Ensures compatibility with older or malformed archives where Unicode names are only present in local headers. Refactored extraction logic to helper methods where appropriate to support retry mechanism. --------- Signed-off-by: Balรกzs Szรผcs --- .../service/fileprocessor/CbxProcessor.java | 45 ++++++++++++++----- .../service/kobo/CbxConversionService.java | 43 +++++++++++++----- .../service/reader/CbxReaderService.java | 42 +++++++++++++---- 3 files changed, 98 insertions(+), 32 deletions(-) diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/CbxProcessor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/CbxProcessor.java index 90e857875..18ed419a0 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/CbxProcessor.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/CbxProcessor.java @@ -114,24 +114,45 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce } private Optional 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 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 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 extractFirstImageFrom7z(File file) { try (SevenZFile sevenZFile = SevenZFile.builder().setFile(file).get()) { List imageEntries = new ArrayList<>(); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/CbxConversionService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/CbxConversionService.java index 31a3ad517..150d39922 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/CbxConversionService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/CbxConversionService.java @@ -196,23 +196,44 @@ public class CbxConversionService { } private List 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 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 extractImagesFromZipFile(ZipFile zipFile, Path extractedImagesDir) { List 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()); } } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/reader/CbxReaderService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/reader/CbxReaderService.java index ba5224fc2..c40ef6492 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/reader/CbxReaderService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/reader/CbxReaderService.java @@ -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; From cb91a4ae6e47cab3a5080db60b0d270891f5982e Mon Sep 17 00:00:00 2001 From: cwar Date: Thu, 25 Dec 2025 13:17:28 -0500 Subject: [PATCH 07/25] fix: Prevent transaction rollback when cover download fails (#1971) Cover download failures in updateThumbnailIfNeeded() were propagating exceptions that poisoned the @Transactional method, causing the entire book's metadata update to roll back - even though the metadata itself was fetched successfully. This commonly occurs when CDNs serve WebP images with JPEG extensions/ headers (e.g., Amazon CDN), causing ImageIO to fail validation. The fix wraps the thumbnail download in a try-catch and logs a warning instead of propagating the exception. Cover failures are non-critical and shouldn't prevent metadata updates from persisting. --- .../booklore/service/metadata/BookMetadataUpdater.java | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookMetadataUpdater.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookMetadataUpdater.java index fca899ff7..90a009bff 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookMetadataUpdater.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookMetadataUpdater.java @@ -356,7 +356,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) { From 811a7e0906c8c4c5c850d158eaf5410a08e4cb48 Mon Sep 17 00:00:00 2001 From: cwar Date: Thu, 25 Dec 2025 13:35:53 -0500 Subject: [PATCH 08/25] fix(metadata): Use existing Goodreads ID for batch refresh instead of searching (#1973) When refreshing metadata for books that already have a goodreadsId stored, the GoodReadsParser now fetches directly from the book page instead of performing a title search first. Problem: - Books with goodreadsId populated but missing goodreadsRating - Batch refresh would search by title, ignoring the stored ID - If search failed (rate limits, transient errors), ratings never populated Solution: - Check for existing goodreadsId before searching - If valid ID exists, fetch directly from /book/show/{id} - Fall back to search only if no ID or direct fetch fails This ensures previously matched books get their ratings updated reliably. --- .../metadata/parser/GoodReadsParser.java | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/parser/GoodReadsParser.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/parser/GoodReadsParser.java index c14233caf..8e3ba5b99 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/parser/GoodReadsParser.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/parser/GoodReadsParser.java @@ -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 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 fetchMetadata(Book book, FetchMetadataRequest fetchMetadataRequest) { String isbn = ParserUtils.cleanIsbn(fetchMetadataRequest.getIsbn()); From 5f2000f085df0ff8a3433c110e6894e022ca6583 Mon Sep 17 00:00:00 2001 From: farfromrefuge Date: Thu, 25 Dec 2025 19:42:30 +0100 Subject: [PATCH 09/25] fix: when selecting a series, select all books from the series (#1979) --- .../book-browser/book-browser.component.ts | 46 +++++++++++-------- .../book-card/book-card.component.ts | 8 ++-- .../filters/SeriesCollapseFilter.ts | 1 + .../src/app/features/book/model/book.model.ts | 1 + 4 files changed, 32 insertions(+), 24 deletions(-) diff --git a/booklore-ui/src/app/features/book/components/book-browser/book-browser.component.ts b/booklore-ui/src/app/features/book/components/book-browser/book-browser.component.ts index 7a25085b2..cc618bf89 100644 --- a/booklore-ui/src/app/features/book/components/book-browser/book-browser.component.ts +++ b/booklore-ui/src/app/features/book/components/book-browser/book-browser.component.ts @@ -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: () => {} }); } diff --git a/booklore-ui/src/app/features/book/components/book-browser/book-card/book-card.component.ts b/booklore-ui/src/app/features/book/components/book-browser/book-card/book-card.component.ts index bcc39ee6a..099226e88 100644 --- a/booklore-ui/src/app/features/book/components/book-browser/book-card/book-card.component.ts +++ b/booklore-ui/src/app/features/book/components/book-browser/book-card/book-card.component.ts @@ -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(); @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; diff --git a/booklore-ui/src/app/features/book/components/book-browser/filters/SeriesCollapseFilter.ts b/booklore-ui/src/app/features/book/components/book-browser/filters/SeriesCollapseFilter.ts index 3a21f641d..207a6d9f6 100644 --- a/booklore-ui/src/app/features/book/components/book-browser/filters/SeriesCollapseFilter.ts +++ b/booklore-ui/src/app/features/book/components/book-browser/filters/SeriesCollapseFilter.ts @@ -81,6 +81,7 @@ export class SeriesCollapseFilter implements BookFilter, OnDestroy { const firstBook = sortedGroup[0]; collapsedBooks.push({ ...firstBook, + seriesBooks: group, seriesCount: group.length }); } diff --git a/booklore-ui/src/app/features/book/model/book.model.ts b/booklore-ui/src/app/features/book/model/book.model.ts index 31f9f3812..e536596fb 100644 --- a/booklore-ui/src/app/features/book/model/book.model.ts +++ b/booklore-ui/src/app/features/book/model/book.model.ts @@ -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; From 97cb7812291a5d2d6f5e99b515a525f0925e7d5d Mon Sep 17 00:00:00 2001 From: ACX <8075870+acx10@users.noreply.github.com> Date: Thu, 25 Dec 2025 12:20:09 -0700 Subject: [PATCH 10/25] Fix Reading Session Timeline bars (#1978) * Fix Reading Session Timeline bars * Remove header --------- Co-authored-by: acx10 --- .github/workflows/develop-pipeline.yml | 146 +++++++++ .github/workflows/docker-build-publish.yml | 305 ------------------ .github/workflows/master-pipeline.yml | 154 +++++++++ .github/workflows/migrations-check.yml | 97 ++++++ README.md | 4 +- .../reading-session-heatmap.component.html | 7 +- .../reading-session-heatmap.component.scss | 7 + .../reading-session-heatmap.component.ts | 7 + .../reading-session-timeline.component.html | 25 +- .../reading-session-timeline.component.scss | 7 + .../reading-session-timeline.component.ts | 53 ++- .../user-stats/user-stats.component.html | 13 +- 12 files changed, 483 insertions(+), 342 deletions(-) create mode 100644 .github/workflows/develop-pipeline.yml delete mode 100644 .github/workflows/docker-build-publish.yml create mode 100644 .github/workflows/master-pipeline.yml create mode 100644 .github/workflows/migrations-check.yml diff --git a/.github/workflows/develop-pipeline.yml b/.github/workflows/develop-pipeline.yml new file mode 100644 index 000000000..db3f7a93f --- /dev/null +++ b/.github/workflows/develop-pipeline.yml @@ -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 \ No newline at end of file diff --git a/.github/workflows/docker-build-publish.yml b/.github/workflows/docker-build-publish.yml deleted file mode 100644 index 1a200a08e..000000000 --- a/.github/workflows/docker-build-publish.yml +++ /dev/null @@ -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 diff --git a/.github/workflows/master-pipeline.yml b/.github/workflows/master-pipeline.yml new file mode 100644 index 000000000..11d45904c --- /dev/null +++ b/.github/workflows/master-pipeline.yml @@ -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 + diff --git a/.github/workflows/migrations-check.yml b/.github/workflows/migrations-check.yml new file mode 100644 index 000000000..b0d072b06 --- /dev/null +++ b/.github/workflows/migrations-check.yml @@ -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." + diff --git a/README.md b/README.md index c1fd26554..2a97b74aa 100644 --- a/README.md +++ b/README.md @@ -346,7 +346,7 @@ services: Found an issue? -[![Open Issue](https://img.shields.io/badge/Report-ff6b6b?style=for-the-badge)](https://github.com/adityachandelgit/BookLore/issues) +[![Open Issue](https://img.shields.io/badge/Report-ff6b6b?style=for-the-badge)](https://github.com/booklore-app/booklore/issues) @@ -355,7 +355,7 @@ Found an issue? Have an idea? -[![Request Feature](https://img.shields.io/badge/Suggest-4ecdc4?style=for-the-badge)](https://github.com/adityachandelgit/BookLore/issues/new) +[![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) diff --git a/booklore-ui/src/app/features/stats/component/reading-session-heatmap/reading-session-heatmap.component.html b/booklore-ui/src/app/features/stats/component/reading-session-heatmap/reading-session-heatmap.component.html index aec24e1c4..c5e44c0e9 100644 --- a/booklore-ui/src/app/features/stats/component/reading-session-heatmap/reading-session-heatmap.component.html +++ b/booklore-ui/src/app/features/stats/component/reading-session-heatmap/reading-session-heatmap.component.html @@ -1,8 +1,11 @@
-

Reading Session Activity

-

Daily reading session activity throughout the year

+

+ + {{ getTitle() }} +

+

Daily overview of your reading sessions across the year

+ {{ currentYear }} + +
+
+
+ + +
+
+ diff --git a/booklore-ui/src/app/features/stats/component/completion-timeline-chart/completion-timeline-chart.component.scss b/booklore-ui/src/app/features/stats/component/completion-timeline-chart/completion-timeline-chart.component.scss new file mode 100644 index 000000000..eded2fdc3 --- /dev/null +++ b/booklore-ui/src/app/features/stats/component/completion-timeline-chart/completion-timeline-chart.component.scss @@ -0,0 +1,132 @@ +.completion-timeline-container { + width: 100%; +} + +.chart-header { + display: flex; + justify-content: space-between; + align-items: flex-start; + margin-bottom: 0.5rem; + gap: 1rem; + + .chart-title { + flex: 1; + + h3 { + color: var(--text-color, #ffffff); + font-size: 1.25rem; + font-weight: 500; + margin: 0 0 0.5rem 0; + display: flex; + align-items: center; + gap: 0.5rem; + } + + .chart-description { + color: var(--text-secondary-color); + font-size: 0.9rem; + margin: 0; + line-height: 1.4; + } + } +} + +.year-selector { + display: flex; + align-items: center; + gap: 0.5rem; + flex-shrink: 0; + + .year-nav-btn { + background: rgba(255, 255, 255, 0.1); + border: 1px solid rgba(255, 255, 255, 0.2); + border-radius: 6px; + padding: 0.6rem 0.6rem; + color: #ffffff; + cursor: pointer; + transition: all 0.3s ease; + display: flex; + align-items: center; + justify-content: center; + + &:hover { + background: rgba(255, 255, 255, 0.2); + border-color: rgba(255, 255, 255, 0.3); + transform: translateY(-1px); + } + + &:active { + transform: translateY(0); + } + + i { + font-size: 0.875rem; + } + } + + .current-year { + font-size: 1.125rem; + font-weight: 600; + color: #ffffff; + min-width: 4.5rem; + text-align: center; + } +} + +.completion-title-icon { + font-size: 1.5rem; + color: rgba(251, 191, 36, 1); +} + +.chart-wrapper { + position: relative; + height: 350px; + width: 100%; +} + +@media (max-width: 768px) { + .chart-header { + flex-direction: column; + align-items: stretch; + + .chart-title { + h3 { + font-size: 1.1rem; + } + + .chart-description { + font-size: 0.85rem; + } + } + + .year-selector { + justify-content: center; + margin-top: 0.5rem; + } + } +} + +@media (max-width: 480px) { + .chart-header { + .chart-title { + h3 { + font-size: 1.1rem; + } + + .chart-description { + font-size: 0.85rem; + } + } + } + + .year-selector { + .current-year { + font-size: 1rem; + min-width: 4rem; + } + + .year-nav-btn { + padding: 0.6rem 0.6rem; + } + } +} diff --git a/booklore-ui/src/app/features/stats/component/completion-timeline-chart/completion-timeline-chart.component.ts b/booklore-ui/src/app/features/stats/component/completion-timeline-chart/completion-timeline-chart.component.ts new file mode 100644 index 000000000..92361dc17 --- /dev/null +++ b/booklore-ui/src/app/features/stats/component/completion-timeline-chart/completion-timeline-chart.component.ts @@ -0,0 +1,235 @@ +import {Component, inject, Input, OnDestroy, OnInit} from '@angular/core'; +import {CommonModule} from '@angular/common'; +import {BaseChartDirective} from 'ng2-charts'; +import {ChartConfiguration, ChartData} from 'chart.js'; +import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs'; +import {catchError, takeUntil} from 'rxjs/operators'; +import {CompletionTimelineResponse, UserStatsService} from '../../../settings/user-management/user-stats.service'; + +type CompletionChartData = ChartData<'bar', number[], string>; + +@Component({ + selector: 'app-completion-timeline-chart', + standalone: true, + imports: [CommonModule, BaseChartDirective], + templateUrl: './completion-timeline-chart.component.html', + styleUrls: ['./completion-timeline-chart.component.scss'] +}) +export class CompletionTimelineChartComponent implements OnInit, OnDestroy { + @Input() initialYear: number = new Date().getFullYear(); + + public currentYear: number = new Date().getFullYear(); + public readonly chartType = 'bar' as const; + public readonly chartData$: Observable; + public readonly chartOptions: ChartConfiguration['options']; + + private readonly userStatsService = inject(UserStatsService); + private readonly destroy$ = new Subject(); + private readonly chartDataSubject: BehaviorSubject; + + private readonly monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; + + constructor() { + this.chartDataSubject = new BehaviorSubject({ + labels: [], + datasets: [] + }); + this.chartData$ = this.chartDataSubject.asObservable(); + + this.chartOptions = { + responsive: true, + maintainAspectRatio: false, + layout: { + padding: {top: 10, bottom: 10, left: 10, right: 10} + }, + plugins: { + legend: { + display: true, + position: 'top', + labels: { + color: '#ffffff', + font: {family: "'Inter', sans-serif", size: 11}, + boxWidth: 12, + padding: 10 + } + }, + tooltip: { + enabled: true, + backgroundColor: 'rgba(0, 0, 0, 0.9)', + titleColor: '#ffffff', + bodyColor: '#ffffff', + borderColor: '#ffffff', + borderWidth: 1, + cornerRadius: 6, + displayColors: true, + padding: 12, + titleFont: {size: 14, weight: 'bold'}, + bodyFont: {size: 13}, + callbacks: { + label: (context) => { + const label = context.dataset.label || ''; + const value = context.parsed.y; + return `${label}: ${value} book${value !== 1 ? 's' : ''}`; + } + } + }, + datalabels: {display: false} + }, + scales: { + x: { + title: { + display: true, + text: 'Month', + color: '#ffffff', + font: { + family: "'Inter', sans-serif", + size: 13, + weight: 'bold' + } + }, + ticks: { + color: '#ffffff', + font: {family: "'Inter', sans-serif", size: 11} + }, + grid: {display: false}, + border: {display: false} + }, + y: { + title: { + display: true, + text: 'Number of Books', + color: '#ffffff', + font: { + family: "'Inter', sans-serif", + size: 13, + weight: 'bold' + } + }, + beginAtZero: true, + ticks: { + color: '#ffffff', + font: {family: "'Inter', sans-serif", size: 11}, + stepSize: 1 + }, + grid: { + color: 'rgba(255, 255, 255, 0.1)' + }, + border: {display: false} + } + } + }; + } + + ngOnInit(): void { + this.currentYear = this.initialYear; + this.loadCompletionTimeline(this.currentYear); + } + + ngOnDestroy(): void { + this.destroy$.next(); + this.destroy$.complete(); + } + + public changeYear(delta: number): void { + this.currentYear += delta; + this.loadCompletionTimeline(this.currentYear); + } + + private loadCompletionTimeline(year: number): void { + this.userStatsService.getCompletionTimelineForYear(year) + .pipe( + takeUntil(this.destroy$), + catchError((error) => { + console.error('Error loading completion timeline:', error); + return EMPTY; + }) + ) + .subscribe((data) => { + this.updateChartData(data); + }); + } + + private updateChartData(timeline: CompletionTimelineResponse[]): void { + const monthlyData = new Map(); + timeline.forEach(item => { + monthlyData.set(item.month, item); + }); + + const labels = this.monthNames; + + const completedBooks = this.monthNames.map((_, index) => { + const monthData = monthlyData.get(index + 1); + if (!monthData) return 0; + const read = monthData.statusBreakdown['READ'] || 0; + const partiallyRead = monthData.statusBreakdown['PARTIALLY_READ'] || 0; + return read + partiallyRead; + }); + + const activeReading = this.monthNames.map((_, index) => { + const monthData = monthlyData.get(index + 1); + if (!monthData) return 0; + const reading = monthData.statusBreakdown['READING'] || 0; + const reReading = monthData.statusBreakdown['RE_READING'] || 0; + return reading + reReading; + }); + + const pausedBooks = this.monthNames.map((_, index) => { + const monthData = monthlyData.get(index + 1); + return monthData?.statusBreakdown['PAUSED'] || 0; + }); + + const discontinuedBooks = this.monthNames.map((_, index) => { + const monthData = monthlyData.get(index + 1); + if (!monthData) return 0; + const abandoned = monthData.statusBreakdown['ABANDONED'] || 0; + const wontRead = monthData.statusBreakdown['WONT_READ'] || 0; + return abandoned + wontRead; + }); + + this.chartDataSubject.next({ + labels, + datasets: [ + { + label: 'Completed', + data: completedBooks, + backgroundColor: 'rgba(106, 176, 76, 0.8)', + borderColor: 'rgba(106, 176, 76, 1)', + borderWidth: 1, + borderRadius: 4, + barPercentage: 0.8, + categoryPercentage: 0.6 + }, + { + label: 'Active Reading', + data: activeReading, + backgroundColor: 'rgba(59, 130, 246, 0.8)', + borderColor: 'rgba(59, 130, 246, 1)', + borderWidth: 1, + borderRadius: 4, + barPercentage: 0.8, + categoryPercentage: 0.6 + }, + { + label: 'Paused', + data: pausedBooks, + backgroundColor: 'rgba(255, 193, 7, 0.8)', + borderColor: 'rgba(255, 193, 7, 1)', + borderWidth: 1, + borderRadius: 4, + barPercentage: 0.8, + categoryPercentage: 0.6 + }, + { + label: 'Discontinued', + data: discontinuedBooks, + backgroundColor: 'rgba(239, 68, 68, 0.8)', + borderColor: 'rgba(239, 68, 68, 1)', + borderWidth: 1, + borderRadius: 4, + barPercentage: 0.8, + categoryPercentage: 0.6 + } + ] + }); + } +} diff --git a/booklore-ui/src/app/features/stats/component/favorite-days-chart/favorite-days-chart.component.html b/booklore-ui/src/app/features/stats/component/favorite-days-chart/favorite-days-chart.component.html new file mode 100644 index 000000000..3552a1ac0 --- /dev/null +++ b/booklore-ui/src/app/features/stats/component/favorite-days-chart/favorite-days-chart.component.html @@ -0,0 +1,38 @@ +
+
+
+

+ + Favorite Reading Days +

+

Reading sessions and duration by day of the week

+
+
+ + + + +
+
+
+ + +
+
diff --git a/booklore-ui/src/app/features/stats/component/favorite-days-chart/favorite-days-chart.component.scss b/booklore-ui/src/app/features/stats/component/favorite-days-chart/favorite-days-chart.component.scss new file mode 100644 index 000000000..ef2fc6ec3 --- /dev/null +++ b/booklore-ui/src/app/features/stats/component/favorite-days-chart/favorite-days-chart.component.scss @@ -0,0 +1,95 @@ +.favorite-days-container { + width: 100%; +} + +.chart-header { + display: flex; + justify-content: space-between; + align-items: flex-start; + margin-bottom: 0.5rem; + gap: 1rem; + + .chart-title { + flex: 1; + + h3 { + color: var(--text-color, #ffffff); + font-size: 1.25rem; + font-weight: 500; + margin: 0 0 0.5rem 0; + display: flex; + align-items: center; + gap: 0.5rem; + } + + .chart-description { + color: var(--text-secondary-color); + font-size: 0.9rem; + margin: 0; + line-height: 1.4; + } + } + + .filter-controls { + display: flex; + gap: 0.75rem; + align-items: center; + flex-shrink: 0; + } +} + +.favorite-days-icon { + font-size: 1.5rem; + color: rgba(139, 92, 246, 1); +} + +.chart-wrapper { + position: relative; + height: 350px; + width: 100%; +} + +@media (max-width: 768px) { + .chart-header { + flex-direction: column; + align-items: stretch; + + .filter-controls { + width: 100%; + flex-direction: column; + gap: 0.5rem; + + ::ng-deep p-select { + width: 100%; + + .p-select { + width: 100% !important; + } + } + } + + .chart-title { + h3 { + font-size: 1.1rem; + } + + .chart-description { + font-size: 0.85rem; + } + } + } +} + +@media (max-width: 480px) { + .chart-header { + .chart-title { + h3 { + font-size: 1rem; + } + + .chart-description { + font-size: 0.8rem; + } + } + } +} diff --git a/booklore-ui/src/app/features/stats/component/favorite-days-chart/favorite-days-chart.component.ts b/booklore-ui/src/app/features/stats/component/favorite-days-chart/favorite-days-chart.component.ts new file mode 100644 index 000000000..d105918ba --- /dev/null +++ b/booklore-ui/src/app/features/stats/component/favorite-days-chart/favorite-days-chart.component.ts @@ -0,0 +1,261 @@ +import {Component, inject, Input, OnDestroy, OnInit} from '@angular/core'; +import {CommonModule} from '@angular/common'; +import {BaseChartDirective} from 'ng2-charts'; +import {ChartConfiguration, ChartData} from 'chart.js'; +import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs'; +import {catchError, takeUntil} from 'rxjs/operators'; +import {FavoriteDaysResponse, UserStatsService} from '../../../settings/user-management/user-stats.service'; +import {Select} from 'primeng/select'; +import {FormsModule} from '@angular/forms'; + +type FavoriteDaysChartData = ChartData<'bar', number[], string>; + +@Component({ + selector: 'app-favorite-days-chart', + standalone: true, + imports: [CommonModule, BaseChartDirective, Select, FormsModule], + templateUrl: './favorite-days-chart.component.html', + styleUrls: ['./favorite-days-chart.component.scss'] +}) +export class FavoriteDaysChartComponent implements OnInit, OnDestroy { + public readonly chartType = 'bar' as const; + public readonly chartData$: Observable; + public readonly chartOptions: ChartConfiguration['options']; + + private readonly userStatsService = inject(UserStatsService); + private readonly destroy$ = new Subject(); + private readonly chartDataSubject: BehaviorSubject; + + private readonly allDays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; + + public selectedYear: number | null = null; + public selectedMonth: number | null = null; + public yearOptions: { label: string; value: number | null }[] = []; + public monthOptions: { label: string; value: number | null }[] = [ + { label: 'All Months', value: null }, + { label: 'January', value: 1 }, + { label: 'February', value: 2 }, + { label: 'March', value: 3 }, + { label: 'April', value: 4 }, + { label: 'May', value: 5 }, + { label: 'June', value: 6 }, + { label: 'July', value: 7 }, + { label: 'August', value: 8 }, + { label: 'September', value: 9 }, + { label: 'October', value: 10 }, + { label: 'November', value: 11 }, + { label: 'December', value: 12 } + ]; + + constructor() { + this.chartDataSubject = new BehaviorSubject({ + labels: [], + datasets: [] + }); + this.chartData$ = this.chartDataSubject.asObservable(); + + this.chartOptions = { + responsive: true, + maintainAspectRatio: false, + layout: { + padding: {top: 10, bottom: 10, left: 10, right: 10} + }, + plugins: { + legend: { + display: true, + position: 'top', + labels: { + color: '#ffffff', + font: {family: "'Inter', sans-serif", size: 11}, + boxWidth: 12, + padding: 10 + } + }, + tooltip: { + enabled: true, + backgroundColor: 'rgba(0, 0, 0, 0.9)', + titleColor: '#ffffff', + bodyColor: '#ffffff', + borderColor: '#ffffff', + borderWidth: 1, + cornerRadius: 6, + displayColors: true, + padding: 12, + titleFont: {size: 14, weight: 'bold'}, + bodyFont: {size: 13}, + callbacks: { + label: (context) => { + const label = context.dataset.label || ''; + const value = context.parsed.y; + if (label === 'Sessions') { + return `${label}: ${value} session${value !== 1 ? 's' : ''}`; + } else { + const hours = Math.floor(value / 3600); + const minutes = Math.floor((value % 3600) / 60); + return `${label}: ${hours}h ${minutes}m`; + } + } + } + }, + datalabels: {display: false} + }, + scales: { + x: { + title: { + display: true, + text: 'Day of Week', + color: '#ffffff', + font: { + family: "'Inter', sans-serif", + size: 13, + weight: 'bold' + } + }, + ticks: { + color: '#ffffff', + font: {family: "'Inter', sans-serif", size: 11} + }, + grid: {display: false}, + border: {display: false} + }, + y: { + type: 'linear', + display: true, + position: 'left', + title: { + display: true, + text: 'Number of Sessions', + color: 'rgba(139, 92, 246, 1)', + font: { + family: "'Inter', sans-serif", + size: 13, + weight: 'bold' + } + }, + beginAtZero: true, + ticks: { + color: '#ffffff', + font: {family: "'Inter', sans-serif", size: 11}, + stepSize: 1 + }, + grid: { + color: 'rgba(255, 255, 255, 0.1)' + }, + border: {display: false} + }, + y1: { + type: 'linear', + display: true, + position: 'right', + title: { + display: true, + text: 'Duration (hours)', + color: 'rgba(236, 72, 153, 1)', + font: { + family: "'Inter', sans-serif", + size: 13, + weight: 'bold' + } + }, + beginAtZero: true, + ticks: { + color: '#ffffff', + font: {family: "'Inter', sans-serif", size: 11}, + callback: function(value) { + return (typeof value === 'number' ? value.toFixed(1) : '0.0') + 'h'; + } + }, + grid: { + drawOnChartArea: false + }, + border: {display: false} + } + } + }; + this.initializeYearOptions(); + } + + ngOnInit(): void { + this.loadFavoriteDays(); + } + + ngOnDestroy(): void { + this.destroy$.next(); + this.destroy$.complete(); + } + + private initializeYearOptions(): void { + const currentYear = new Date().getFullYear(); + this.yearOptions = [{ label: 'All Years', value: null }]; + for (let year = currentYear; year >= currentYear - 10; year--) { + this.yearOptions.push({ label: year.toString(), value: year }); + } + } + + public onFilterChange(): void { + this.loadFavoriteDays(); + } + + private loadFavoriteDays(): void { + const year = this.selectedYear ?? undefined; + const month = this.selectedMonth ?? undefined; + + this.userStatsService.getFavoriteDays(year, month) + .pipe( + takeUntil(this.destroy$), + catchError((error) => { + console.error('Error loading favorite days:', error); + return EMPTY; + }) + ) + .subscribe((data) => { + this.updateChartData(data); + }); + } + + private updateChartData(favoriteDays: FavoriteDaysResponse[]): void { + const dayMap = new Map(); + favoriteDays.forEach(item => { + dayMap.set(item.dayOfWeek, item); + }); + + const labels = this.allDays; + const sessionCounts = this.allDays.map((_, index) => { + const dayData = dayMap.get(index); + return dayData?.sessionCount || 0; + }); + + const durations = this.allDays.map((_, index) => { + const dayData = dayMap.get(index); + return dayData ? dayData.totalDurationSeconds / 3600 : 0; // Convert to hours + }); + + this.chartDataSubject.next({ + labels, + datasets: [ + { + label: 'Sessions', + data: sessionCounts, + backgroundColor: 'rgba(139, 92, 246, 0.8)', + borderColor: 'rgba(139, 92, 246, 1)', + borderWidth: 1, + borderRadius: 4, + barPercentage: 0.8, + categoryPercentage: 0.6, + yAxisID: 'y' + }, + { + label: 'Duration (hours)', + data: durations, + backgroundColor: 'rgba(236, 72, 153, 0.8)', + borderColor: 'rgba(236, 72, 153, 1)', + borderWidth: 1, + borderRadius: 4, + barPercentage: 0.8, + categoryPercentage: 0.6, + yAxisID: 'y1' + } + ] + }); + } +} diff --git a/booklore-ui/src/app/features/stats/component/genre-stats-chart/genre-stats-chart.component.html b/booklore-ui/src/app/features/stats/component/genre-stats-chart/genre-stats-chart.component.html new file mode 100644 index 000000000..ee415eb5a --- /dev/null +++ b/booklore-ui/src/app/features/stats/component/genre-stats-chart/genre-stats-chart.component.html @@ -0,0 +1,18 @@ +
+
+
+

+ + Reading by Genre +

+

Top genres by total reading time

+
+
+
+ + +
+
diff --git a/booklore-ui/src/app/features/stats/component/genre-stats-chart/genre-stats-chart.component.scss b/booklore-ui/src/app/features/stats/component/genre-stats-chart/genre-stats-chart.component.scss new file mode 100644 index 000000000..6881f034b --- /dev/null +++ b/booklore-ui/src/app/features/stats/component/genre-stats-chart/genre-stats-chart.component.scss @@ -0,0 +1,57 @@ +.genre-stats-container { + width: 100%; +} + +.chart-header { + display: flex; + justify-content: space-between; + align-items: flex-start; + margin-bottom: 1.5rem; + + .chart-title { + flex: 1; + + h3 { + color: var(--text-color, #ffffff); + font-size: 1.25rem; + font-weight: 500; + margin: 0 0 0.5rem 0; + display: flex; + align-items: center; + gap: 0.5rem; + } + + .chart-description { + color: var(--text-secondary-color); + font-size: 0.9rem; + margin: 0; + line-height: 1.4; + } + } +} + +.genre-title-icon { + font-size: 1.5rem; + color: rgba(34, 197, 94, 1); +} + +.chart-wrapper { + position: relative; + height: 350px; + width: 100%; +} + +@media (max-width: 768px) { + + .chart-header { + .chart-title { + h3 { + font-size: 1.1rem; + } + + .chart-description { + font-size: 0.85rem; + } + } + } +} diff --git a/booklore-ui/src/app/features/stats/component/genre-stats-chart/genre-stats-chart.component.ts b/booklore-ui/src/app/features/stats/component/genre-stats-chart/genre-stats-chart.component.ts new file mode 100644 index 000000000..3f51e23fd --- /dev/null +++ b/booklore-ui/src/app/features/stats/component/genre-stats-chart/genre-stats-chart.component.ts @@ -0,0 +1,199 @@ +import {Component, inject, Input, OnDestroy, OnInit} from '@angular/core'; +import {CommonModule} from '@angular/common'; +import {BaseChartDirective} from 'ng2-charts'; +import {ChartConfiguration, ChartData} from 'chart.js'; +import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs'; +import {catchError, takeUntil} from 'rxjs/operators'; +import {GenreStatsResponse, UserStatsService} from '../../../settings/user-management/user-stats.service'; + +type GenreChartData = ChartData<'bar', number[], string>; + +@Component({ + selector: 'app-genre-stats-chart', + standalone: true, + imports: [CommonModule, BaseChartDirective], + templateUrl: './genre-stats-chart.component.html', + styleUrls: ['./genre-stats-chart.component.scss'] +}) +export class GenreStatsChartComponent implements OnInit, OnDestroy { + @Input() maxGenres: number = 35; + + public readonly chartType = 'bar' as const; + public readonly chartData$: Observable; + public readonly chartOptions: ChartConfiguration['options']; + + private readonly userStatsService = inject(UserStatsService); + private readonly destroy$ = new Subject(); + private readonly chartDataSubject: BehaviorSubject; + + constructor() { + this.chartDataSubject = new BehaviorSubject({ + labels: [], + datasets: [] + }); + this.chartData$ = this.chartDataSubject.asObservable(); + + this.chartOptions = { + responsive: true, + maintainAspectRatio: false, + layout: { + padding: {top: 10, bottom: 10, left: 10, right: 10} + }, + plugins: { + legend: {display: false}, + tooltip: { + enabled: true, + backgroundColor: 'rgba(0, 0, 0, 0.9)', + titleColor: '#ffffff', + bodyColor: '#ffffff', + borderColor: '#ffffff', + borderWidth: 1, + cornerRadius: 6, + displayColors: true, + padding: 12, + titleFont: {size: 14, weight: 'bold'}, + bodyFont: {size: 13}, + callbacks: { + label: (context) => { + const dataIndex = context.dataIndex; + const dataset = context.dataset; + const label = context.chart.data.labels?.[dataIndex] as string; + const minutes = Math.floor((dataset.data[dataIndex] as number) / 60); + const hours = Math.floor(minutes / 60); + const mins = minutes % 60; + + const timeStr = hours > 0 + ? `${hours}h ${mins}m` + : `${mins}m`; + + return `${label}: ${timeStr}`; + } + } + }, + datalabels: {display: false} + }, + scales: { + x: { + title: { + display: true, + text: 'Genres', + color: '#ffffff', + font: { + family: "'Inter', sans-serif", + size: 12 + } + }, + ticks: { + color: '#ffffff', + font: {family: "'Inter', sans-serif", size: 11}, + maxRotation: 90, + minRotation: 90, + callback: (value, index) => { + const label = this.chartDataSubject.value.labels?.[index] as string; + const maxLength = 12; + if (label && label.length > maxLength) { + return label.substring(0, maxLength) + '...'; + } + return label; + } + }, + grid: {display: false}, + border: {display: false} + }, + y: { + title: { + display: true, + text: 'Time Read', + color: '#ffffff', + font: { + family: "'Inter', sans-serif", + size: 12 + } + }, + beginAtZero: true, + ticks: { + color: '#ffffff', + font: {family: "'Inter', sans-serif", size: 11}, + callback: (value) => { + const seconds = value as number; + const minutes = Math.floor(seconds / 60); + const hours = Math.floor(minutes / 60); + const days = Math.floor(hours / 24); + + if (days > 0) { + const remainingHours = hours % 24; + if (remainingHours > 0) { + return `${days} ${days === 1 ? 'day' : 'days'} ${remainingHours} ${remainingHours === 1 ? 'hr' : 'hrs'}`; + } + return `${days} ${days === 1 ? 'day' : 'days'}`; + } else if (hours > 0) { + const remainingMinutes = minutes % 60; + if (remainingMinutes > 0) { + return `${hours} ${hours === 1 ? 'hr' : 'hrs'} ${remainingMinutes} min`; + } + return `${hours} ${hours === 1 ? 'hr' : 'hrs'}`; + } else if (minutes > 0) { + return `${minutes} min`; + } + return `${seconds} sec`; + }, + stepSize: undefined, + maxTicksLimit: 8 + }, + grid: { + color: 'rgba(255, 255, 255, 0.1)' + }, + border: {display: false} + } + } + }; + } + + ngOnInit(): void { + this.loadGenreStats(); + } + + ngOnDestroy(): void { + this.destroy$.next(); + this.destroy$.complete(); + } + + private loadGenreStats(): void { + this.userStatsService.getGenreStats() + .pipe( + takeUntil(this.destroy$), + catchError((error) => { + console.error('Error loading genre stats:', error); + return EMPTY; + }) + ) + .subscribe((data) => { + this.updateChartData(data); + }); + } + + private updateChartData(genreStats: GenreStatsResponse[]): void { + const sortedStats = [...genreStats] + .sort((a, b) => b.totalDurationSeconds - a.totalDurationSeconds) + .slice(0, this.maxGenres); + + const labels = sortedStats.map(stat => stat.genre); + const durations = sortedStats.map(stat => stat.totalDurationSeconds); + + this.chartDataSubject.next({ + labels, + datasets: [ + { + label: 'Reading Time', + data: durations, + backgroundColor: 'rgba(34, 197, 94, 0.8)', + borderColor: 'rgba(34, 197, 94, 1)', + borderWidth: 1, + borderRadius: 4, + barPercentage: 0.8, + categoryPercentage: 0.6 + } + ] + }); + } +} diff --git a/booklore-ui/src/app/features/stats/component/peak-hours-chart/peak-hours-chart.component.html b/booklore-ui/src/app/features/stats/component/peak-hours-chart/peak-hours-chart.component.html new file mode 100644 index 000000000..59df2e711 --- /dev/null +++ b/booklore-ui/src/app/features/stats/component/peak-hours-chart/peak-hours-chart.component.html @@ -0,0 +1,38 @@ +
+
+
+

+ + Peak Reading Hours +

+

Reading activity by hour of the day

+
+
+ + + + +
+
+
+ + +
+
diff --git a/booklore-ui/src/app/features/stats/component/peak-hours-chart/peak-hours-chart.component.scss b/booklore-ui/src/app/features/stats/component/peak-hours-chart/peak-hours-chart.component.scss new file mode 100644 index 000000000..a2672e615 --- /dev/null +++ b/booklore-ui/src/app/features/stats/component/peak-hours-chart/peak-hours-chart.component.scss @@ -0,0 +1,95 @@ +.peak-hours-container { + width: 100%; +} + +.chart-header { + display: flex; + justify-content: space-between; + align-items: flex-start; + margin-bottom: 0.5rem; + gap: 1rem; + + .chart-title { + flex: 1; + + h3 { + color: var(--text-color, #ffffff); + font-size: 1.25rem; + font-weight: 500; + margin: 0 0 0.5rem 0; + display: flex; + align-items: center; + gap: 0.5rem; + } + + .chart-description { + color: var(--text-secondary-color); + font-size: 0.9rem; + margin: 0; + line-height: 1.4; + } + } + + .filter-controls { + display: flex; + gap: 0.75rem; + align-items: center; + flex-shrink: 0; + } +} + +.peak-hours-icon { + font-size: 1.5rem; + color: rgba(34, 197, 94, 1); +} + +.chart-wrapper { + position: relative; + height: 350px; + width: 100%; +} + +@media (max-width: 768px) { + .chart-header { + flex-direction: column; + align-items: stretch; + + .filter-controls { + width: 100%; + flex-direction: column; + gap: 0.5rem; + + ::ng-deep p-select { + width: 100%; + + .p-select { + width: 100% !important; + } + } + } + + .chart-title { + h3 { + font-size: 1.1rem; + } + + .chart-description { + font-size: 0.85rem; + } + } + } +} + +@media (max-width: 480px) { + .chart-header { + .chart-title { + h3 { + font-size: 1rem; + } + + .chart-description { + font-size: 0.8rem; + } + } + } +} diff --git a/booklore-ui/src/app/features/stats/component/peak-hours-chart/peak-hours-chart.component.ts b/booklore-ui/src/app/features/stats/component/peak-hours-chart/peak-hours-chart.component.ts new file mode 100644 index 000000000..1dab8237c --- /dev/null +++ b/booklore-ui/src/app/features/stats/component/peak-hours-chart/peak-hours-chart.component.ts @@ -0,0 +1,278 @@ +import {Component, inject, OnDestroy, OnInit} from '@angular/core'; +import {CommonModule} from '@angular/common'; +import {BaseChartDirective} from 'ng2-charts'; +import {ChartConfiguration, ChartData} from 'chart.js'; +import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs'; +import {catchError, takeUntil} from 'rxjs/operators'; +import {PeakHoursResponse, UserStatsService} from '../../../settings/user-management/user-stats.service'; +import {Select} from 'primeng/select'; +import {FormsModule} from '@angular/forms'; + +type PeakHoursChartData = ChartData<'line', number[], string>; + +@Component({ + selector: 'app-peak-hours-chart', + standalone: true, + imports: [CommonModule, BaseChartDirective, Select, FormsModule], + templateUrl: './peak-hours-chart.component.html', + styleUrls: ['./peak-hours-chart.component.scss'] +}) +export class PeakHoursChartComponent implements OnInit, OnDestroy { + public readonly chartType = 'line' as const; + public readonly chartData$: Observable; + public readonly chartOptions: ChartConfiguration['options']; + + private readonly userStatsService = inject(UserStatsService); + private readonly destroy$ = new Subject(); + private readonly chartDataSubject: BehaviorSubject; + + public selectedYear: number | null = null; + public selectedMonth: number | null = null; + public yearOptions: { label: string; value: number | null }[] = []; + public monthOptions: { label: string; value: number | null }[] = [ + { label: 'All Months', value: null }, + { label: 'January', value: 1 }, + { label: 'February', value: 2 }, + { label: 'March', value: 3 }, + { label: 'April', value: 4 }, + { label: 'May', value: 5 }, + { label: 'June', value: 6 }, + { label: 'July', value: 7 }, + { label: 'August', value: 8 }, + { label: 'September', value: 9 }, + { label: 'October', value: 10 }, + { label: 'November', value: 11 }, + { label: 'December', value: 12 } + ]; + + constructor() { + this.chartDataSubject = new BehaviorSubject({ + labels: [], + datasets: [] + }); + this.chartData$ = this.chartDataSubject.asObservable(); + + this.chartOptions = { + responsive: true, + maintainAspectRatio: false, + layout: { + padding: {top: 10, bottom: 10, left: 10, right: 10} + }, + plugins: { + legend: { + display: true, + position: 'top', + labels: { + color: '#ffffff', + font: {family: "'Inter', sans-serif", size: 11}, + boxWidth: 12, + padding: 10 + } + }, + tooltip: { + enabled: true, + backgroundColor: 'rgba(0, 0, 0, 0.9)', + titleColor: '#ffffff', + bodyColor: '#ffffff', + borderColor: '#ffffff', + borderWidth: 1, + cornerRadius: 6, + displayColors: true, + padding: 12, + titleFont: {size: 14, weight: 'bold'}, + bodyFont: {size: 13}, + callbacks: { + label: (context) => { + const label = context.dataset.label || ''; + const value = context.parsed.y; + if (label === 'Sessions') { + return `${label}: ${value} session${value !== 1 ? 's' : ''}`; + } else { + const hours = Math.floor(value / 3600); + const minutes = Math.floor((value % 3600) / 60); + return `${label}: ${hours}h ${minutes}m`; + } + } + } + }, + datalabels: {display: false} + }, + scales: { + x: { + title: { + display: true, + text: 'Hour of Day', + color: '#ffffff', + font: { + family: "'Inter', sans-serif", + size: 13, + weight: 'bold' + } + }, + ticks: { + color: '#ffffff', + font: {family: "'Inter', sans-serif", size: 11} + }, + grid: { + color: 'rgba(255, 255, 255, 0.1)' + }, + border: {display: false} + }, + y: { + type: 'linear', + display: true, + position: 'left', + title: { + display: true, + text: 'Number of Sessions', + color: 'rgba(34, 197, 94, 0.9)', + font: { + family: "'Inter', sans-serif", + size: 13, + weight: 'bold' + } + }, + beginAtZero: true, + ticks: { + color: '#ffffff', + font: {family: "'Inter', sans-serif", size: 11}, + stepSize: 1 + }, + grid: { + color: 'rgba(255, 255, 255, 0.1)' + }, + border: {display: false} + }, + y1: { + type: 'linear', + display: true, + position: 'right', + title: { + display: true, + text: 'Duration (minutes)', + color: 'rgba(251, 191, 36, 0.9)', + font: { + family: "'Inter', sans-serif", + size: 13, + weight: 'bold' + } + }, + beginAtZero: true, + ticks: { + color: '#ffffff', + font: {family: "'Inter', sans-serif", size: 11}, + callback: function (value) { + return (typeof value === 'number' ? Math.round(value) : '0') + 'm'; + } + }, + grid: { + drawOnChartArea: false + }, + border: {display: false} + } + } + }; + this.initializeYearOptions(); + } + + ngOnInit(): void { + this.loadPeakHours(); + } + + ngOnDestroy(): void { + this.destroy$.next(); + this.destroy$.complete(); + } + + private initializeYearOptions(): void { + const currentYear = new Date().getFullYear(); + this.yearOptions = [{ label: 'All Years', value: null }]; + for (let year = currentYear; year >= currentYear - 10; year--) { + this.yearOptions.push({ label: year.toString(), value: year }); + } + } + + public onFilterChange(): void { + this.loadPeakHours(); + } + + private loadPeakHours(): void { + const year = this.selectedYear ?? undefined; + const month = this.selectedMonth ?? undefined; + + this.userStatsService.getPeakHours(year, month) + .pipe( + takeUntil(this.destroy$), + catchError((error) => { + console.error('Error loading peak hours:', error); + return EMPTY; + }) + ) + .subscribe((data) => { + this.updateChartData(data); + }); + } + + private updateChartData(peakHours: PeakHoursResponse[]): void { + const hourMap = new Map(); + peakHours.forEach(item => { + hourMap.set(item.hourOfDay, item); + }); + + const allHours = Array.from({length: 24}, (_, i) => i); + const labels = allHours.map(h => this.formatHour(h)); + + const sessionCounts = allHours.map(hour => { + const hourData = hourMap.get(hour); + return hourData?.sessionCount || 0; + }); + + const durations = allHours.map(hour => { + const hourData = hourMap.get(hour); + return hourData ? hourData.totalDurationSeconds / 60 : 0; // Convert to minutes + }); + + this.chartDataSubject.next({ + labels, + datasets: [ + { + label: 'Sessions', + data: sessionCounts, + borderColor: 'rgba(34, 197, 94, 0.9)', + backgroundColor: 'rgba(34, 197, 94, 0.1)', + borderWidth: 2, + tension: 0.4, + fill: true, + pointRadius: 4, + pointHoverRadius: 6, + pointBackgroundColor: 'rgba(34, 197, 94, 0.9)', + pointBorderColor: '#ffffff', + pointBorderWidth: 2, + yAxisID: 'y' + }, + { + label: 'Duration (minutes)', + data: durations, + borderColor: 'rgba(251, 191, 36, 0.9)', + backgroundColor: 'rgba(251, 191, 36, 0.1)', + borderWidth: 2, + tension: 0.4, + fill: true, + pointRadius: 4, + pointHoverRadius: 6, + pointBackgroundColor: 'rgba(251, 191, 36, 0.9)', + pointBorderColor: '#ffffff', + pointBorderWidth: 2, + yAxisID: 'y1' + } + ] + }); + } + + private formatHour(hour: number): string { + if (hour === 0) return '12 AM'; + if (hour === 12) return '12 PM'; + if (hour < 12) return `${hour} AM`; + return `${hour - 12} PM`; + } +} diff --git a/booklore-ui/src/app/features/stats/component/reading-dna-chart/reading-dna-chart.component.html b/booklore-ui/src/app/features/stats/component/reading-dna-chart/reading-dna-chart.component.html new file mode 100644 index 000000000..d7328d158 --- /dev/null +++ b/booklore-ui/src/app/features/stats/component/reading-dna-chart/reading-dna-chart.component.html @@ -0,0 +1,37 @@ +
+
+
+

+ + Reading DNA Profile +

+

Your unique reading personality across 8 key dimensions

+
+
+
+ + +
+ @if (personalityInsights.length > 0) { +
+

Your Reading Personality Traits

+
+ @for (insight of personalityInsights; track insight.trait) { +
+
+ {{ insight.trait }} + {{ insight.score.toFixed(0) }}% +
+
+
+
+

{{ insight.description }}

+
+ } +
+
+ } +
diff --git a/booklore-ui/src/app/features/stats/component/reading-dna-chart/reading-dna-chart.component.scss b/booklore-ui/src/app/features/stats/component/reading-dna-chart/reading-dna-chart.component.scss new file mode 100644 index 000000000..26cce315e --- /dev/null +++ b/booklore-ui/src/app/features/stats/component/reading-dna-chart/reading-dna-chart.component.scss @@ -0,0 +1,137 @@ +.reading-dna-container { + width: 100%; +} + +.chart-header { + display: flex; + justify-content: space-between; + align-items: flex-start; + margin-bottom: 0.5rem; + + .chart-title { + flex: 1; + + h3 { + color: var(--text-color, #ffffff); + font-size: 1.25rem; + font-weight: 500; + margin: 0 0 0.5rem 0; + display: flex; + align-items: center; + gap: 0.5rem; + } + + .chart-description { + color: var(--text-secondary-color); + font-size: 0.9rem; + margin: 0; + line-height: 1.4; + } + } +} + +.reading-dna-icon { + font-size: 1.5rem; + color: rgba(79, 195, 247, 1); +} + +.chart-wrapper { + position: relative; + height: 450px; + width: 100%; + margin-bottom: 2rem; +} + +.personality-insights { + margin-top: 2rem; + + h4 { + color: var(--text-color, #ffffff); + font-size: 1.1rem; + font-weight: 500; + margin: 0 0 1rem 0; + } + + .insights-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); + gap: 1rem; + } + + .insight-card { + background: rgba(255, 255, 255, 0.05); + border-radius: 8px; + padding: 1rem; + border: 1px solid rgba(255, 255, 255, 0.1); + + .insight-header { + display: flex; + justify-content: space-between; + align-items: center; + margin-bottom: 0.5rem; + + .insight-trait { + color: var(--text-color, #ffffff); + font-weight: 500; + font-size: 0.95rem; + } + + .insight-score { + font-weight: 600; + font-size: 1rem; + } + } + + .insight-progress { + height: 6px; + background: rgba(255, 255, 255, 0.1); + border-radius: 3px; + overflow: hidden; + margin-bottom: 0.5rem; + + .progress-bar { + height: 100%; + border-radius: 3px; + transition: width 0.3s ease; + } + } + + .insight-description { + color: var(--text-secondary-color); + font-size: 0.85rem; + margin: 0; + line-height: 1.4; + } + } +} + +@media (max-width: 768px) { + .chart-wrapper { + height: 350px; + } + + .personality-insights { + .insights-grid { + grid-template-columns: 1fr; + } + } +} + +@media (max-width: 480px) { + .chart-header { + .chart-title { + h3 { + font-size: 1rem; + } + + .chart-description { + font-size: 0.8rem; + } + } + } + + .chart-wrapper { + height: 300px; + } +} + diff --git a/booklore-ui/src/app/features/stats/service/reading-dna-chart.service.ts b/booklore-ui/src/app/features/stats/component/reading-dna-chart/reading-dna-chart.component.ts similarity index 81% rename from booklore-ui/src/app/features/stats/service/reading-dna-chart.service.ts rename to booklore-ui/src/app/features/stats/component/reading-dna-chart/reading-dna-chart.component.ts index 8246de8bc..3ec6f76e8 100644 --- a/booklore-ui/src/app/features/stats/service/reading-dna-chart.service.ts +++ b/booklore-ui/src/app/features/stats/component/reading-dna-chart/reading-dna-chart.component.ts @@ -1,21 +1,21 @@ -import {inject, Injectable, OnDestroy} from '@angular/core'; -import {BehaviorSubject, EMPTY, Observable, Subject, of} from 'rxjs'; -import {map, takeUntil, catchError, filter, first, switchMap} from 'rxjs/operators'; +import {Component, inject, OnDestroy, OnInit} from '@angular/core'; +import {CommonModule} from '@angular/common'; +import {BaseChartDirective} from 'ng2-charts'; +import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs'; +import {catchError, filter, first, takeUntil} from 'rxjs/operators'; import {ChartConfiguration, ChartData} from 'chart.js'; - -import {LibraryFilterService} from './library-filter.service'; -import {BookService} from '../../book/service/book.service'; -import {Book, ReadStatus} from '../../book/model/book.model'; +import {BookService} from '../../../book/service/book.service'; +import {Book, ReadStatus} from '../../../book/model/book.model'; interface ReadingDNAProfile { - adventurous: number; // Genre diversity and experimental reading - perfectionist: number; // Completion rate and quality focus - intellectual: number; // Non-fiction preference and complex books - emotional: number; // Fiction preference and rating engagement - patient: number; // Long book preference and series completion - social: number; // Popular books and mainstream choices - nostalgic: number; // Older books and classic literature - ambitious: number; // Reading volume and challenging material + adventurous: number; + perfectionist: number; + intellectual: number; + emotional: number; + patient: number; + social: number; + nostalgic: number; + ambitious: number; } interface PersonalityInsight { @@ -27,17 +27,20 @@ interface PersonalityInsight { type ReadingDNAChartData = ChartData<'radar', number[], string>; -@Injectable({ - providedIn: 'root' +@Component({ + selector: 'app-reading-dna-chart', + standalone: true, + imports: [CommonModule, BaseChartDirective], + templateUrl: './reading-dna-chart.component.html', + styleUrls: ['./reading-dna-chart.component.scss'] }) -export class ReadingDNAChartService implements OnDestroy { +export class ReadingDNAChartComponent implements OnInit, OnDestroy { private readonly bookService = inject(BookService); - private readonly libraryFilterService = inject(LibraryFilterService); private readonly destroy$ = new Subject(); - public readonly readingDNAChartType = 'radar' as const; + public readonly chartType = 'radar' as const; - public readonly readingDNAChartOptions: ChartConfiguration<'radar'>['options'] = { + public readonly chartOptions: ChartConfiguration<'radar'>['options'] = { responsive: true, maintainAspectRatio: false, scales: { @@ -107,8 +110,7 @@ export class ReadingDNAChartService implements OnDestroy { }, label: (context) => { const score = context.parsed.r; - const insights = this.getPersonalityInsights(); - const insight = insights.find(i => i.trait === context.label); + const insight = this.personalityInsights.find(i => i.trait === context.label); return [ `Score: ${score.toFixed(1)}/100`, @@ -137,7 +139,7 @@ export class ReadingDNAChartService implements OnDestroy { } }; - private readonly readingDNAChartDataSubject = new BehaviorSubject({ + private readonly chartDataSubject = new BehaviorSubject({ labels: [ 'Adventurous', 'Perfectionist', 'Intellectual', 'Emotional', 'Patient', 'Social', 'Nostalgic', 'Ambitious' @@ -145,23 +147,19 @@ export class ReadingDNAChartService implements OnDestroy { datasets: [] }); - public readonly readingDNAChartData$: Observable = this.readingDNAChartDataSubject.asObservable(); - private lastCalculatedInsights: PersonalityInsight[] = []; + public readonly chartData$: Observable = this.chartDataSubject.asObservable(); + public personalityInsights: PersonalityInsight[] = []; - constructor() { + ngOnInit(): void { this.bookService.bookState$ .pipe( filter(state => state.loaded), first(), - switchMap(() => - this.libraryFilterService.selectedLibrary$.pipe( - takeUntil(this.destroy$) - ) - ), catchError((error) => { console.error('Error processing reading DNA data:', error); return EMPTY; - }) + }), + takeUntil(this.destroy$) ) .subscribe(() => { const profile = this.calculateReadingDNAData(); @@ -177,10 +175,11 @@ export class ReadingDNAChartService implements OnDestroy { private updateChartData(profile: ReadingDNAProfile | null): void { try { if (!profile) { - this.readingDNAChartDataSubject.next({ + this.chartDataSubject.next({ labels: [], datasets: [] }); + this.personalityInsights = []; return; } @@ -195,13 +194,12 @@ export class ReadingDNAChartService implements OnDestroy { profile.ambitious ]; - // Create gradient effect colors const gradientColors = [ '#ff6b9d', '#45aaf2', '#96f7d2', '#feca57', '#ff9ff3', '#54a0ff', '#5f27cd', '#00d2d3' ]; - this.readingDNAChartDataSubject.next({ + this.chartDataSubject.next({ labels: [ 'Adventurous', 'Perfectionist', 'Intellectual', 'Emotional', 'Patient', 'Social', 'Nostalgic', 'Ambitious' @@ -221,8 +219,7 @@ export class ReadingDNAChartService implements OnDestroy { }] }); - // Store insights for tooltip - this.lastCalculatedInsights = this.convertToPersonalityInsights(profile); + this.personalityInsights = this.convertToPersonalityInsights(profile); } catch (error) { console.error('Error updating reading DNA chart data:', error); } @@ -230,26 +227,18 @@ export class ReadingDNAChartService implements OnDestroy { private calculateReadingDNAData(): ReadingDNAProfile | null { const currentState = this.bookService.getCurrentBookState(); - const selectedLibraryId = this.libraryFilterService.getCurrentSelectedLibrary(); if (!this.isValidBookState(currentState)) { return null; } - const filteredBooks = this.filterBooksByLibrary(currentState.books!, String(selectedLibraryId)); - return this.analyzeReadingDNA(filteredBooks); + return this.analyzeReadingDNA(currentState.books!); } private isValidBookState(state: any): boolean { return state?.loaded && state?.books && Array.isArray(state.books) && state.books.length > 0; } - private filterBooksByLibrary(books: Book[], selectedLibraryId: string | null): Book[] { - return selectedLibraryId && selectedLibraryId !== 'null' - ? books.filter(book => String(book.libraryId) === selectedLibraryId) - : books; - } - private analyzeReadingDNA(books: Book[]): ReadingDNAProfile { if (books.length === 0) { return this.getDefaultProfile(); @@ -268,7 +257,6 @@ export class ReadingDNAChartService implements OnDestroy { } private calculateAdventurousScore(books: Book[]): number { - // Genre diversity + experimental choices + different formats const genres = new Set(); const languages = new Set(); const formats = new Set(); @@ -279,9 +267,9 @@ export class ReadingDNAChartService implements OnDestroy { formats.add(book.bookType); }); - const genreScore = Math.min(60, genres.size * 4); // Max 60 for 15+ genres - const languageScore = Math.min(20, languages.size * 10); // Max 20 for 2+ languages - const formatScore = Math.min(20, formats.size * 7); // Max 20 for 3+ formats + const genreScore = Math.min(60, genres.size * 4); + const languageScore = Math.min(20, languages.size * 10); + const formatScore = Math.min(20, formats.size * 7); return genreScore + languageScore + formatScore; } @@ -290,7 +278,6 @@ export class ReadingDNAChartService implements OnDestroy { const completedBooks = books.filter(b => b.readStatus === ReadStatus.READ); const completionRate = completedBooks.length / books.length; - // High-quality book preference const qualityBooks = books.filter(book => { const metadata = book.metadata; if (!metadata) return false; @@ -300,8 +287,8 @@ export class ReadingDNAChartService implements OnDestroy { }); const qualityRate = qualityBooks.length / books.length; - const completionScore = completionRate * 60; // Max 60 - const qualityScore = qualityRate * 40; // Max 40 + const completionScore = completionRate * 60; + const qualityScore = qualityRate * 40; return Math.min(100, completionScore + qualityScore); } @@ -329,7 +316,6 @@ export class ReadingDNAChartService implements OnDestroy { ); }); - // Long books indicate patience for complex material const longBooks = books.filter(book => book.metadata?.pageCount && book.metadata.pageCount > 400 ); @@ -365,7 +351,6 @@ export class ReadingDNAChartService implements OnDestroy { ); }); - // Personal rating engagement shows emotional connection const personallyRatedBooks = books.filter(book => book.personalRating); const emotionalRate = emotionalBooks.length / books.length; @@ -375,7 +360,6 @@ export class ReadingDNAChartService implements OnDestroy { } private calculatePatienceScore(books: Book[]): number { - // Long books + series completion + slow reading pace const longBooks = books.filter(book => book.metadata?.pageCount && book.metadata.pageCount > 500 ); @@ -384,7 +368,6 @@ export class ReadingDNAChartService implements OnDestroy { book.metadata?.seriesName && book.metadata?.seriesNumber ); - // Books with high progress indicate patience to work through them const progressBooks = books.filter(book => { const progress = Math.max( book.epubProgress?.percentage || 0, @@ -404,7 +387,6 @@ export class ReadingDNAChartService implements OnDestroy { } private calculateSocialScore(books: Book[]): number { - // Popular books (high ratings, many reviews) + mainstream genres const popularBooks = books.filter(book => { const metadata = book.metadata; if (!metadata) return false; @@ -446,7 +428,7 @@ export class ReadingDNAChartService implements OnDestroy { private calculateNostalgicScore(books: Book[]): number { const currentYear = new Date().getFullYear(); - const classicThreshold = currentYear - 30; // Books older than 30 years + const classicThreshold = currentYear - 30; const oldBooks = books.filter(book => { if (!book.metadata?.publishedDate) return false; @@ -480,9 +462,8 @@ export class ReadingDNAChartService implements OnDestroy { } private calculateAmbitiousScore(books: Book[]): number { - // Volume + challenging material + completion of difficult books const totalBooks = books.length; - const volumeScore = Math.min(40, totalBooks * 2); // Max 40 for 20+ books + const volumeScore = Math.min(40, totalBooks * 2); const challengingBooks = books.filter(book => book.metadata?.pageCount && book.metadata.pageCount > 600 @@ -496,8 +477,8 @@ export class ReadingDNAChartService implements OnDestroy { const completionRate = challengingBooks.length > 0 ? completedChallenging.length / challengingBooks.length : 0; - const challengingScore = challengingRate * 35; // Max 35 - const completionBonus = completionRate * 25; // Max 25 + const challengingScore = challengingRate * 35; + const completionBonus = completionRate * 25; return Math.min(100, volumeScore + challengingScore + completionBonus); } @@ -567,8 +548,4 @@ export class ReadingDNAChartService implements OnDestroy { } ]; } - - public getPersonalityInsights(): PersonalityInsight[] { - return this.lastCalculatedInsights; - } } diff --git a/booklore-ui/src/app/features/stats/component/reading-habits-chart/reading-habits-chart.component.html b/booklore-ui/src/app/features/stats/component/reading-habits-chart/reading-habits-chart.component.html new file mode 100644 index 000000000..9b60e17e1 --- /dev/null +++ b/booklore-ui/src/app/features/stats/component/reading-habits-chart/reading-habits-chart.component.html @@ -0,0 +1,37 @@ +
+
+
+

+ + Reading Habits Analysis +

+

Your behavioral reading patterns across 8 key dimensions

+
+
+
+ + +
+ @if (habitInsights.length > 0) { +
+

Your Reading Habit Patterns

+
+ @for (insight of habitInsights; track insight.habit) { +
+
+ {{ insight.habit }} + {{ insight.score.toFixed(0) }}% +
+
+
+
+

{{ insight.description }}

+
+ } +
+
+ } +
diff --git a/booklore-ui/src/app/features/stats/component/reading-habits-chart/reading-habits-chart.component.scss b/booklore-ui/src/app/features/stats/component/reading-habits-chart/reading-habits-chart.component.scss new file mode 100644 index 000000000..8f197c4bd --- /dev/null +++ b/booklore-ui/src/app/features/stats/component/reading-habits-chart/reading-habits-chart.component.scss @@ -0,0 +1,137 @@ +.reading-habits-container { + width: 100%; +} + +.chart-header { + display: flex; + justify-content: space-between; + align-items: flex-start; + margin-bottom: 0.5rem; + + .chart-title { + flex: 1; + + h3 { + color: var(--text-color, #ffffff); + font-size: 1.25rem; + font-weight: 500; + margin: 0 0 0.5rem 0; + display: flex; + align-items: center; + gap: 0.5rem; + } + + .chart-description { + color: var(--text-secondary-color); + font-size: 0.9rem; + margin: 0; + line-height: 1.4; + } + } +} + +.reading-habits-icon { + font-size: 1.5rem; + color: rgba(156, 39, 176, 1); +} + +.chart-wrapper { + position: relative; + height: 450px; + width: 100%; + margin-bottom: 2rem; +} + +.habit-insights { + margin-top: 2rem; + + h4 { + color: var(--text-color, #ffffff); + font-size: 1.1rem; + font-weight: 500; + margin: 0 0 1rem 0; + } + + .insights-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); + gap: 1rem; + } + + .insight-card { + background: rgba(255, 255, 255, 0.05); + border-radius: 8px; + padding: 1rem; + border: 1px solid rgba(255, 255, 255, 0.1); + + .insight-header { + display: flex; + justify-content: space-between; + align-items: center; + margin-bottom: 0.5rem; + + .insight-trait { + color: var(--text-color, #ffffff); + font-weight: 500; + font-size: 0.95rem; + } + + .insight-score { + font-weight: 600; + font-size: 1rem; + } + } + + .insight-progress { + height: 6px; + background: rgba(255, 255, 255, 0.1); + border-radius: 3px; + overflow: hidden; + margin-bottom: 0.5rem; + + .progress-bar { + height: 100%; + border-radius: 3px; + transition: width 0.3s ease; + } + } + + .insight-description { + color: var(--text-secondary-color); + font-size: 0.85rem; + margin: 0; + line-height: 1.4; + } + } +} + +@media (max-width: 768px) { + .chart-wrapper { + height: 350px; + } + + .habit-insights { + .insights-grid { + grid-template-columns: 1fr; + } + } +} + +@media (max-width: 480px) { + .chart-header { + .chart-title { + h3 { + font-size: 1rem; + } + + .chart-description { + font-size: 0.8rem; + } + } + } + + .chart-wrapper { + height: 300px; + } +} + diff --git a/booklore-ui/src/app/features/stats/service/reading-habits-chart.service.ts b/booklore-ui/src/app/features/stats/component/reading-habits-chart/reading-habits-chart.component.ts similarity index 76% rename from booklore-ui/src/app/features/stats/service/reading-habits-chart.service.ts rename to booklore-ui/src/app/features/stats/component/reading-habits-chart/reading-habits-chart.component.ts index 9b3a60e1a..0f08422cb 100644 --- a/booklore-ui/src/app/features/stats/service/reading-habits-chart.service.ts +++ b/booklore-ui/src/app/features/stats/component/reading-habits-chart/reading-habits-chart.component.ts @@ -1,21 +1,21 @@ -import {inject, Injectable, OnDestroy} from '@angular/core'; -import {BehaviorSubject, EMPTY, Observable, Subject, of} from 'rxjs'; -import {map, takeUntil, catchError, filter, first, switchMap} from 'rxjs/operators'; +import {Component, inject, OnDestroy, OnInit} from '@angular/core'; +import {CommonModule} from '@angular/common'; +import {BaseChartDirective} from 'ng2-charts'; +import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs'; +import {catchError, filter, first, takeUntil} from 'rxjs/operators'; import {ChartConfiguration, ChartData} from 'chart.js'; - -import {LibraryFilterService} from './library-filter.service'; -import {BookService} from '../../book/service/book.service'; -import {Book, ReadStatus} from '../../book/model/book.model'; +import {BookService} from '../../../book/service/book.service'; +import {Book, ReadStatus} from '../../../book/model/book.model'; interface ReadingHabitsProfile { - consistency: number; // Regular reading patterns vs sporadic - multitasking: number; // Multiple books at once - completionism: number; // Finishing vs abandoning books - exploration: number; // Trying new vs sticking to familiar - organization: number; // Series order, metadata attention - intensity: number; // Reading session length preferences - methodology: number; // Systematic vs random book selection - momentum: number; // Reading streaks and continuity + consistency: number; + multitasking: number; + completionism: number; + exploration: number; + organization: number; + intensity: number; + methodology: number; + momentum: number; } interface HabitInsight { @@ -27,17 +27,20 @@ interface HabitInsight { type ReadingHabitsChartData = ChartData<'radar', number[], string>; -@Injectable({ - providedIn: 'root' +@Component({ + selector: 'app-reading-habits-chart', + standalone: true, + imports: [CommonModule, BaseChartDirective], + templateUrl: './reading-habits-chart.component.html', + styleUrls: ['./reading-habits-chart.component.scss'] }) -export class ReadingHabitsChartService implements OnDestroy { +export class ReadingHabitsChartComponent implements OnInit, OnDestroy { private readonly bookService = inject(BookService); - private readonly libraryFilterService = inject(LibraryFilterService); private readonly destroy$ = new Subject(); - public readonly readingHabitsChartType = 'radar' as const; + public readonly chartType = 'radar' as const; - public readonly readingHabitsChartOptions: ChartConfiguration<'radar'>['options'] = { + public readonly chartOptions: ChartConfiguration<'radar'>['options'] = { responsive: true, maintainAspectRatio: false, scales: { @@ -107,8 +110,7 @@ export class ReadingHabitsChartService implements OnDestroy { }, label: (context) => { const score = context.parsed.r; - const insights = this.getHabitInsights(); - const insight = insights.find(i => i.habit === context.label); + const insight = this.habitInsights.find(i => i.habit === context.label); return [ `Score: ${score.toFixed(1)}/100`, @@ -137,7 +139,7 @@ export class ReadingHabitsChartService implements OnDestroy { } }; - private readonly readingHabitsChartDataSubject = new BehaviorSubject({ + private readonly chartDataSubject = new BehaviorSubject({ labels: [ 'Consistency', 'Multitasking', 'Completionism', 'Exploration', 'Organization', 'Intensity', 'Methodology', 'Momentum' @@ -145,23 +147,19 @@ export class ReadingHabitsChartService implements OnDestroy { datasets: [] }); - public readonly readingHabitsChartData$: Observable = this.readingHabitsChartDataSubject.asObservable(); - private lastCalculatedInsights: HabitInsight[] = []; + public readonly chartData$: Observable = this.chartDataSubject.asObservable(); + public habitInsights: HabitInsight[] = []; - constructor() { + ngOnInit(): void { this.bookService.bookState$ .pipe( filter(state => state.loaded), first(), - switchMap(() => - this.libraryFilterService.selectedLibrary$.pipe( - takeUntil(this.destroy$) - ) - ), catchError((error) => { console.error('Error processing reading habits data:', error); return EMPTY; - }) + }), + takeUntil(this.destroy$) ) .subscribe(() => { const profile = this.calculateReadingHabitsData(); @@ -177,10 +175,11 @@ export class ReadingHabitsChartService implements OnDestroy { private updateChartData(profile: ReadingHabitsProfile | null): void { try { if (!profile) { - this.readingHabitsChartDataSubject.next({ + this.chartDataSubject.next({ labels: [], datasets: [] }); + this.habitInsights = []; return; } @@ -195,13 +194,12 @@ export class ReadingHabitsChartService implements OnDestroy { profile.momentum ]; - // Purple gradient colors for habits theme const habitColors = [ '#9c27b0', '#e91e63', '#ff5722', '#ff9800', '#ffc107', '#4caf50', '#2196f3', '#673ab7' ]; - this.readingHabitsChartDataSubject.next({ + this.chartDataSubject.next({ labels: [ 'Consistency', 'Multitasking', 'Completionism', 'Exploration', 'Organization', 'Intensity', 'Methodology', 'Momentum' @@ -221,8 +219,7 @@ export class ReadingHabitsChartService implements OnDestroy { }] }); - // Store insights for tooltip - this.lastCalculatedInsights = this.convertToHabitInsights(profile); + this.habitInsights = this.convertToHabitInsights(profile); } catch (error) { console.error('Error updating reading habits chart data:', error); } @@ -230,26 +227,18 @@ export class ReadingHabitsChartService implements OnDestroy { private calculateReadingHabitsData(): ReadingHabitsProfile | null { const currentState = this.bookService.getCurrentBookState(); - const selectedLibraryId = this.libraryFilterService.getCurrentSelectedLibrary(); if (!this.isValidBookState(currentState)) { return null; } - const filteredBooks = this.filterBooksByLibrary(currentState.books!, String(selectedLibraryId)); - return this.analyzeReadingHabits(filteredBooks); + return this.analyzeReadingHabits(currentState.books!); } private isValidBookState(state: any): boolean { return state?.loaded && state?.books && Array.isArray(state.books) && state.books.length > 0; } - private filterBooksByLibrary(books: Book[], selectedLibraryId: string | null): Book[] { - return selectedLibraryId && selectedLibraryId !== 'null' - ? books.filter(book => String(book.libraryId) === selectedLibraryId) - : books; - } - private analyzeReadingHabits(books: Book[]): ReadingHabitsProfile { if (books.length === 0) { return this.getDefaultProfile(); @@ -268,28 +257,24 @@ export class ReadingHabitsChartService implements OnDestroy { } private calculateConsistencyScore(books: Book[]): number { - // Look for consistent reading patterns through completion dates and progress + // ...existing code from service... const booksWithDates = books.filter(book => book.dateFinished || book.addedOn); if (booksWithDates.length === 0) return 30; - // Books completed in sequence suggest consistent reading habits const completedBooks = books.filter(book => book.readStatus === ReadStatus.READ && book.dateFinished); if (completedBooks.length < 2) return 25; - // Calculate time intervals between completed books - const sortedByCompletion = completedBooks - .sort((a, b) => new Date(a.dateFinished!).getTime() - new Date(b.dateFinished!).getTime()); - let consistencyScore = 50; - // Books in progress suggest active reading habit const inProgress = books.filter(book => book.readStatus === ReadStatus.READING || book.readStatus === ReadStatus.RE_READING ); const progressRate = inProgress.length / books.length; consistencyScore += progressRate * 30; - // Regular completion pattern + const sortedByCompletion = completedBooks + .sort((a, b) => new Date(a.dateFinished!).getTime() - new Date(b.dateFinished!).getTime()); + if (sortedByCompletion.length >= 3) { consistencyScore += 20; } @@ -298,12 +283,11 @@ export class ReadingHabitsChartService implements OnDestroy { } private calculateMultitaskingScore(books: Book[]): number { - // Multiple books in reading status indicates multitasking + // ...existing code from service... const currentlyReading = books.filter(book => book.readStatus === ReadStatus.READING); const reReading = books.filter(book => book.readStatus === ReadStatus.RE_READING); const activeBooks = currentlyReading.length + reReading.length; - // Books with partial progress suggest juggling multiple reads const booksWithProgress = books.filter(book => { const progress = Math.max( book.epubProgress?.percentage || 0, @@ -315,14 +299,14 @@ export class ReadingHabitsChartService implements OnDestroy { return progress > 0 && progress < 100; }); - const multitaskingScore = Math.min(60, activeBooks * 15); // Max 60 for 4+ concurrent books - const progressScore = Math.min(40, (booksWithProgress.length / books.length) * 80); // Max 40 + const multitaskingScore = Math.min(60, activeBooks * 15); + const progressScore = Math.min(40, (booksWithProgress.length / books.length) * 80); return Math.min(100, multitaskingScore + progressScore); } private calculateCompletionismScore(books: Book[]): number { - // High completion rate vs abandonment + // ...existing code from service... const completed = books.filter(book => book.readStatus === ReadStatus.READ); const abandoned = books.filter(book => book.readStatus === ReadStatus.ABANDONED); const unfinished = books.filter(book => book.readStatus === ReadStatus.UNREAD || book.readStatus === ReadStatus.UNSET); @@ -330,14 +314,14 @@ export class ReadingHabitsChartService implements OnDestroy { const completionRate = completed.length / (books.length - unfinished.length); const abandonmentRate = abandoned.length / books.length; - const completionScore = completionRate * 70; // Max 70 - const abandonmentPenalty = abandonmentRate * 30; // Max 30 penalty + const completionScore = completionRate * 70; + const abandonmentPenalty = abandonmentRate * 30; return Math.max(0, Math.min(100, completionScore - abandonmentPenalty + 30)); } private calculateExplorationScore(books: Book[]): number { - // Trying new authors vs sticking to favorites + // ...existing code from service... const authors = new Set(); const authorCounts = new Map(); @@ -349,38 +333,32 @@ export class ReadingHabitsChartService implements OnDestroy { }); }); - // Calculate author diversity - const authorDiversityScore = Math.min(50, authors.size * 2); // Max 50 - - // Penalty for too many books by same author (indicates less exploration) + const authorDiversityScore = Math.min(50, authors.size * 2); const maxBooksPerAuthor = Math.max(...Array.from(authorCounts.values())); - const concentrationPenalty = Math.max(0, (maxBooksPerAuthor - 3) * 5); // Penalty after 3 books per author + const concentrationPenalty = Math.max(0, (maxBooksPerAuthor - 3) * 5); - // Different publication years indicate temporal exploration const years = new Set(); books.forEach(book => { if (book.metadata?.publishedDate) { years.add(new Date(book.metadata.publishedDate).getFullYear()); } }); - const temporalScore = Math.min(30, years.size * 2); // Max 30 + const temporalScore = Math.min(30, years.size * 2); - // Different languages indicate linguistic exploration const languages = new Set(); books.forEach(book => { if (book.metadata?.language) languages.add(book.metadata.language); }); - const languageScore = Math.min(20, (languages.size - 1) * 10); // Max 20 + const languageScore = Math.min(20, (languages.size - 1) * 10); return Math.max(10, Math.min(100, authorDiversityScore + temporalScore + languageScore - concentrationPenalty)); } private calculateOrganizationScore(books: Book[]): number { - // Series reading in order, metadata completion + // ...existing code from service... const seriesBooks = books.filter(book => book.metadata?.seriesName && book.metadata?.seriesNumber); - const seriesScore = (seriesBooks.length / books.length) * 40; // Max 40 + const seriesScore = (seriesBooks.length / books.length) * 40; - // Books with comprehensive metadata suggest organized approach const wellOrganizedBooks = books.filter(book => { const metadata = book.metadata; if (!metadata) return false; @@ -392,24 +370,22 @@ export class ReadingHabitsChartService implements OnDestroy { return hasBasicInfo && (hasDetailedInfo || hasCategories); }); - const metadataScore = (wellOrganizedBooks.length / books.length) * 35; // Max 35 + const metadataScore = (wellOrganizedBooks.length / books.length) * 35; - // Personal ratings suggest systematic tracking const ratedBooks = books.filter(book => book.personalRating); - const ratingScore = (ratedBooks.length / books.length) * 25; // Max 25 + const ratingScore = (ratedBooks.length / books.length) * 25; return Math.min(100, seriesScore + metadataScore + ratingScore); } private calculateIntensityScore(books: Book[]): number { - // Preference for longer books suggests intensive reading sessions + // ...existing code from service... const booksWithPages = books.filter(book => book.metadata?.pageCount && book.metadata.pageCount > 0); if (booksWithPages.length === 0) return 40; const averagePages = booksWithPages.reduce((sum, book) => sum + (book.metadata?.pageCount || 0), 0) / booksWithPages.length; - const intensityFromLength = Math.min(50, averagePages / 8); // Max 50 for 400+ page average + const intensityFromLength = Math.min(50, averagePages / 8); - // High progress percentages on multiple books suggest intensive reading const highProgressBooks = books.filter(book => { const progress = Math.max( book.epubProgress?.percentage || 0, @@ -420,19 +396,18 @@ export class ReadingHabitsChartService implements OnDestroy { return progress > 75; }); - const progressScore = (highProgressBooks.length / books.length) * 30; // Max 30 + const progressScore = (highProgressBooks.length / books.length) * 30; - // Series completion suggests sustained intensive reading const completedSeriesBooks = books.filter(book => book.metadata?.seriesName && book.readStatus === ReadStatus.READ ); - const seriesIntensityScore = (completedSeriesBooks.length / books.length) * 20; // Max 20 + const seriesIntensityScore = (completedSeriesBooks.length / books.length) * 20; return Math.min(100, intensityFromLength + progressScore + seriesIntensityScore); } private calculateMethodologyScore(books: Book[]): number { - // Series reading in order vs random selection + // ...existing code from service... const seriesBooks = books.filter(book => book.metadata?.seriesName); const seriesGroups = new Map(); @@ -456,7 +431,6 @@ export class ReadingHabitsChartService implements OnDestroy { } }); - // Author exploration in systematic way (multiple books per favored author) const authorBooks = new Map(); books.forEach(book => { book.metadata?.authors?.forEach(author => { @@ -469,9 +443,8 @@ export class ReadingHabitsChartService implements OnDestroy { }); const systematicAuthors = Array.from(authorBooks.values()).filter(books => books.length >= 2).length; - const authorMethodologyScore = Math.min(30, systematicAuthors * 5); // Max 30 + const authorMethodologyScore = Math.min(30, systematicAuthors * 5); - // Genre consistency suggests methodical selection const categoryBooks = new Map(); books.forEach(book => { book.metadata?.categories?.forEach(category => { @@ -481,33 +454,30 @@ export class ReadingHabitsChartService implements OnDestroy { }); const majorCategories = Array.from(categoryBooks.values()).filter(count => count >= 3).length; - const categoryMethodologyScore = Math.min(25, majorCategories * 8); // Max 25 + const categoryMethodologyScore = Math.min(25, majorCategories * 8); - const baseMethodologyScore = books.length >= 10 ? 15 : Math.max(5, books.length); // Base score + const baseMethodologyScore = books.length >= 10 ? 15 : Math.max(5, books.length); return Math.min(100, systematicSeriesScore + authorMethodologyScore + categoryMethodologyScore + baseMethodologyScore); } private calculateMomentumScore(books: Book[]): number { - // Reading streaks and continuity + // ...existing code from service... const completedBooks = books.filter(book => book.readStatus === ReadStatus.READ && book.dateFinished); if (completedBooks.length === 0) { - // Score based on current activity const activeBooks = books.filter(book => book.readStatus === ReadStatus.READING || book.readStatus === ReadStatus.RE_READING ); return Math.min(40, activeBooks.length * 10); } - // Sort by completion date const sortedBooks = completedBooks.sort((a, b) => new Date(a.dateFinished!).getTime() - new Date(b.dateFinished!).getTime() ); - let momentumScore = 20; // Base score + let momentumScore = 20; - // Recent completion activity (last 6 months) const sixMonthsAgo = new Date(); sixMonthsAgo.setMonth(sixMonthsAgo.getMonth() - 6); @@ -515,16 +485,14 @@ export class ReadingHabitsChartService implements OnDestroy { new Date(book.dateFinished!) > sixMonthsAgo ); - momentumScore += Math.min(40, recentCompletions.length * 5); // Max 40 + momentumScore += Math.min(40, recentCompletions.length * 5); - // Currently reading books add to momentum const currentlyReading = books.filter(book => book.readStatus === ReadStatus.READING || book.readStatus === ReadStatus.RE_READING ); - momentumScore += Math.min(25, currentlyReading.length * 8); // Max 25 + momentumScore += Math.min(25, currentlyReading.length * 8); - // High progress books indicate active momentum const highProgressBooks = books.filter(book => { const progress = Math.max( book.epubProgress?.percentage || 0, @@ -535,7 +503,7 @@ export class ReadingHabitsChartService implements OnDestroy { return progress > 50 && progress < 100; }); - momentumScore += Math.min(15, highProgressBooks.length * 3); // Max 15 + momentumScore += Math.min(15, highProgressBooks.length * 3); return Math.min(100, momentumScore); } @@ -605,8 +573,5 @@ export class ReadingHabitsChartService implements OnDestroy { } ]; } - - public getHabitInsights(): HabitInsight[] { - return this.lastCalculatedInsights; - } } + diff --git a/booklore-ui/src/app/features/stats/component/reading-session-heatmap/reading-session-heatmap.component.html b/booklore-ui/src/app/features/stats/component/reading-session-heatmap/reading-session-heatmap.component.html index c5e44c0e9..5190aa567 100644 --- a/booklore-ui/src/app/features/stats/component/reading-session-heatmap/reading-session-heatmap.component.html +++ b/booklore-ui/src/app/features/stats/component/reading-session-heatmap/reading-session-heatmap.component.html @@ -3,7 +3,7 @@

- {{ getTitle() }} + Reading Session Activity

Daily overview of your reading sessions across the year

@@ -22,6 +22,7 @@ +
; }) export class ReadingSessionHeatmapComponent implements OnInit, OnDestroy { @Input() initialYear: number = new Date().getFullYear(); - @Input() userName: string = ''; public currentYear: number = new Date().getFullYear(); public readonly chartType = 'matrix' as const; @@ -212,8 +211,8 @@ export class ReadingSessionHeatmapComponent implements OnInit, OnDestroy { if (!point?.v) return 'rgba(255, 255, 255, 0.05)'; const intensity = point.v / this.maxSessionCount; - const alpha = Math.max(0.2, Math.min(1.0, intensity * 0.8 + 0.2)); - return `rgba(106, 176, 76, ${alpha})`; + const alpha = Math.max(0.3, Math.min(0.9, intensity * 0.6 + 0.3)); + return `rgba(59, 130, 246, ${alpha})`; }, borderColor: 'rgba(255, 255, 255, 0.1)', borderWidth: 1 @@ -226,10 +225,4 @@ export class ReadingSessionHeatmapComponent implements OnInit, OnDestroy { date.setDate(date.getDate() + (week * 7) - date.getDay()); return date; } - - public getTitle(): string { - return this.userName - ? `${this.userName}'s Reading Session Activity` - : 'Reading Session Activity'; - } } diff --git a/booklore-ui/src/app/features/stats/component/reading-session-timeline/reading-session-timeline.component.html b/booklore-ui/src/app/features/stats/component/reading-session-timeline/reading-session-timeline.component.html index 715ff0910..fdecb466c 100644 --- a/booklore-ui/src/app/features/stats/component/reading-session-timeline/reading-session-timeline.component.html +++ b/booklore-ui/src/app/features/stats/component/reading-session-timeline/reading-session-timeline.component.html @@ -3,18 +3,18 @@

- {{ getTitle() }} + Reading Session Timeline

Weekly overview of your reading sessions and patterns

-
+
-
+
Week {{ currentWeek }} {{ getWeekDateRange() }}
@@ -25,6 +25,26 @@
+
+ + + + +
diff --git a/booklore-ui/src/app/features/stats/component/reading-session-timeline/reading-session-timeline.component.scss b/booklore-ui/src/app/features/stats/component/reading-session-timeline/reading-session-timeline.component.scss index 86a42bf37..7ff6f9ddd 100644 --- a/booklore-ui/src/app/features/stats/component/reading-session-timeline/reading-session-timeline.component.scss +++ b/booklore-ui/src/app/features/stats/component/reading-session-timeline/reading-session-timeline.component.scss @@ -3,15 +3,13 @@ } .timeline-header { - display: flex; - justify-content: space-between; + display: grid; + grid-template-columns: 1fr auto 1fr; align-items: flex-start; - margin-bottom: 0.5rem; + margin-bottom: 1rem; gap: 1rem; .header-title { - flex: 1; - h3 { color: var(--text-color, #ffffff); font-size: 1.25rem; @@ -27,17 +25,16 @@ } } - .week-selector { + .week-info { display: flex; align-items: center; - gap: 1rem; - flex-shrink: 0; + justify-self: center; .week-nav-btn { background: rgba(255, 255, 255, 0.1); border: 1px solid rgba(255, 255, 255, 0.2); border-radius: 6px; - padding: 0.5rem 0.75rem; + padding: 0.6rem 0.6rem; color: #ffffff; cursor: pointer; transition: all 0.3s ease; @@ -60,26 +57,96 @@ } } - .week-info { + .week-display { display: flex; flex-direction: column; align-items: center; - min-width: 100px; + min-width: 120px; .week-label { - font-size: 1.125rem; + font-size: 1rem; font-weight: 600; color: #ffffff; white-space: nowrap; + line-height: 1.2; } .week-dates { - font-size: 0.8rem; + font-size: 0.75rem; color: var(--text-secondary-color); white-space: nowrap; + margin-top: 0.1rem; + line-height: 1.2; } } } + + .filter-controls { + display: flex; + gap: 0.75rem; + align-items: center; + justify-self: end; + } +} + +.week-info-bar { + display: flex; + align-items: center; + justify-content: center; + gap: 1rem; + margin-bottom: 1rem; + padding: 0.75rem; + background: rgba(255, 255, 255, 0.05); + border-radius: 8px; + border: 1px solid rgba(255, 255, 255, 0.1); + + .week-nav-btn { + background: rgba(255, 255, 255, 0.1); + border: 1px solid rgba(255, 255, 255, 0.2); + border-radius: 6px; + padding: 0.6rem 6rem; + color: #ffffff; + cursor: pointer; + transition: all 0.3s ease; + display: flex; + align-items: center; + justify-content: center; + + &:hover { + background: rgba(255, 255, 255, 0.2); + border-color: rgba(255, 255, 255, 0.3); + transform: translateY(-1px); + } + + &:active { + transform: translateY(0); + } + + i { + font-size: 0.875rem; + } + } + + .week-display { + display: flex; + flex-direction: column; + align-items: center; + min-width: 150px; + + .week-label { + font-size: 1.125rem; + font-weight: 600; + color: #ffffff; + white-space: nowrap; + } + + .week-dates { + font-size: 0.85rem; + color: var(--text-secondary-color); + white-space: nowrap; + margin-top: 0.25rem; + } + } } .timeline-content { @@ -153,7 +220,7 @@ background: rgba(255, 255, 255, 0.02); border-radius: 4px; border: 1px solid rgba(255, 255, 255, 0.1); - min-height: 40px; + min-height: 35px; } } @@ -188,29 +255,32 @@ box-sizing: border-box; &.book-type-epub, &.book-type-default { - background: linear-gradient(135deg, #4a90e2 0%, #357abd 100%); - box-shadow: 0 2px 8px rgba(74, 144, 226, 0.3); + background: rgba(59, 130, 246, 0.8); + border: 1px solid rgba(59, 130, 246, 1); + box-shadow: 0 2px 4px rgba(59, 130, 246, 0.3); &:hover { - box-shadow: 0 4px 16px rgba(74, 144, 226, 0.5); + box-shadow: 0 4px 8px rgba(59, 130, 246, 0.5); } } &.book-type-pdf { - background: linear-gradient(135deg, #e24a4a 0%, #bd3535 100%); - box-shadow: 0 2px 8px rgba(226, 74, 74, 0.3); + background: rgba(239, 68, 68, 0.8); + border: 1px solid rgba(239, 68, 68, 1); + box-shadow: 0 2px 4px rgba(239, 68, 68, 0.3); &:hover { - box-shadow: 0 4px 16px rgba(226, 74, 74, 0.5); + box-shadow: 0 4px 8px rgba(239, 68, 68, 0.5); } } &.book-type-cbx { - background: linear-gradient(135deg, #e2b74a 0%, #bd9635 100%); - box-shadow: 0 2px 8px rgba(226, 183, 74, 0.3); + background: rgba(255, 193, 7, 0.8); + border: 1px solid rgba(255, 193, 7, 1); + box-shadow: 0 2px 4px rgba(255, 193, 7, 0.3); &:hover { - box-shadow: 0 4px 16px rgba(226, 183, 74, 0.5); + box-shadow: 0 4px 8px rgba(255, 193, 7, 0.5); } } @@ -311,7 +381,7 @@ i { font-size: 1.1rem; - color: #4a90e2; + color: rgba(239, 68, 68, 1); } .tooltip-title { @@ -384,22 +454,77 @@ .timeline-title-icon { font-size: 1.5rem; - color: var(--primary-color); + color: rgba(239, 68, 68, 1); vertical-align: middle; margin-right: 0.25em; } +@media (max-width: 1024px) { + .timeline-header { + grid-template-columns: 1fr; + gap: 0.75rem; + + .header-title { + grid-column: 1; + } + + .week-info { + grid-column: 1; + justify-self: stretch; + justify-content: center; + } + + .filter-controls { + grid-column: 1; + justify-self: stretch; + display: grid; + grid-template-columns: 1fr 1fr; + gap: 0.5rem; + + ::ng-deep p-select { + width: 100%; + + .p-select { + width: 100% !important; + } + } + } + } +} + @media (max-width: 768px) { .timeline-header { - flex-direction: column; - align-items: stretch; + .header-title { + h3 { + font-size: 1.1rem; + } - .week-selector { - justify-content: center; - margin-top: 0.5rem; + .timeline-subtitle { + font-size: 0.85rem; + } + } - .week-info { - min-width: 120px; + .week-info { + padding: 0.6rem 0.6rem; + + .week-display { + min-width: 100px; + + .week-label { + font-size: 0.9rem; + } + + .week-dates { + font-size: 0.7rem; + } + } + + .week-nav-btn { + padding: 0.35rem 0.5rem; + + i { + font-size: 0.8rem; + } } } } @@ -467,24 +592,30 @@ .timeline-header { .header-title { h3 { - font-size: 1.1rem; + font-size: 1rem; } .timeline-subtitle { - font-size: 0.85rem; + font-size: 0.8rem; } } - } - .week-selector { + .filter-controls { + grid-template-columns: 1fr; + } + .week-info { - .week-label { - font-size: 1rem; - } - } + .week-display { + min-width: 90px; - .week-nav-btn { - padding: 0.4rem 0.6rem; + .week-label { + font-size: 0.85rem; + } + + .week-dates { + font-size: 0.65rem; + } + } } } } diff --git a/booklore-ui/src/app/features/stats/component/reading-session-timeline/reading-session-timeline.component.ts b/booklore-ui/src/app/features/stats/component/reading-session-timeline/reading-session-timeline.component.ts index 9a0f72a99..863247940 100644 --- a/booklore-ui/src/app/features/stats/component/reading-session-timeline/reading-session-timeline.component.ts +++ b/booklore-ui/src/app/features/stats/component/reading-session-timeline/reading-session-timeline.component.ts @@ -3,6 +3,10 @@ import {CommonModule} from '@angular/common'; import {ReadingSessionTimelineResponse, UserStatsService} from '../../../settings/user-management/user-stats.service'; import {UrlHelperService} from '../../../../shared/service/url-helper.service'; import {BookType} from '../../../book/model/book.model'; +import {catchError} from 'rxjs/operators'; +import {of} from 'rxjs'; +import {Select} from 'primeng/select'; +import {FormsModule} from '@angular/forms'; interface ReadingSession { startTime: Date; @@ -37,14 +41,13 @@ interface DayTimeline { @Component({ selector: 'app-reading-session-timeline', standalone: true, - imports: [CommonModule], + imports: [CommonModule, Select, FormsModule], templateUrl: './reading-session-timeline.component.html', styleUrls: ['./reading-session-timeline.component.scss'] }) export class ReadingSessionTimelineComponent implements OnInit { @Input() initialYear: number = new Date().getFullYear(); @Input() weekNumber: number = this.getCurrentWeekNumber(); - @Input() userName: string = ''; private userStatsService = inject(UserStatsService); private urlHelperService = inject(UrlHelperService); @@ -54,14 +57,52 @@ export class ReadingSessionTimelineComponent implements OnInit { public timelineData: DayTimeline[] = []; public currentYear: number = new Date().getFullYear(); public currentWeek: number = this.getCurrentWeekNumber(); + public currentMonth: number = new Date().getMonth() + 1; + + public yearOptions: { label: string; value: number }[] = []; + public weekOptions: { label: string; value: number }[] = []; ngOnInit(): void { this.currentYear = this.initialYear; this.currentWeek = this.weekNumber; + this.updateCurrentMonth(); + this.initializeYearOptions(); + this.updateWeekOptions(); this.initializeHourLabels(); this.loadReadingSessions(); } + private initializeYearOptions(): void { + const currentYear = new Date().getFullYear(); + this.yearOptions = []; + for (let year = currentYear; year >= currentYear - 10; year--) { + this.yearOptions.push({ label: year.toString(), value: year }); + } + } + + private updateWeekOptions(): void { + const weeksInYear = this.getWeeksInYear(this.currentYear); + this.weekOptions = []; + for (let week = 1; week <= weeksInYear; week++) { + this.weekOptions.push({ label: `Week ${week}`, value: week }); + } + } + + public onYearChange(): void { + this.updateWeekOptions(); + const maxWeeks = this.getWeeksInYear(this.currentYear); + if (this.currentWeek > maxWeeks) { + this.currentWeek = maxWeeks; + } + this.updateCurrentMonth(); + this.loadReadingSessions(); + } + + public onWeekChange(): void { + this.updateCurrentMonth(); + this.loadReadingSessions(); + } + private initializeHourLabels(): void { for (let i = 0; i < 24; i++) { const hour = i === 0 ? 12 : i > 12 ? i - 12 : i; @@ -71,15 +112,17 @@ export class ReadingSessionTimelineComponent implements OnInit { } private loadReadingSessions(): void { - this.userStatsService.getTimelineForWeek(this.currentYear, this.currentWeek) + this.userStatsService.getTimelineForWeek(this.currentYear, this.currentMonth, this.currentWeek) + .pipe( + catchError((error) => { + console.error('Error loading reading sessions:', error); + return of([]); + }) + ) .subscribe({ next: (response) => { const sessions = this.convertResponseToSessions(response); this.processSessionData(sessions); - }, - error: (error) => { - console.error('Error loading reading sessions:', error); - this.processSessionData([]); } }); } @@ -119,14 +162,28 @@ export class ReadingSessionTimelineComponent implements OnInit { if (this.currentWeek > weeksInYear) { this.currentWeek = 1; this.currentYear++; + this.updateWeekOptions(); } else if (this.currentWeek < 1) { this.currentYear--; this.currentWeek = this.getWeeksInYear(this.currentYear); + this.updateWeekOptions(); } + this.updateCurrentMonth(); this.loadReadingSessions(); } + private updateCurrentMonth(): void { + const startOfYear = new Date(this.currentYear, 0, 1); + const daysToAdd = (this.currentWeek - 1) * 7; + const weekStart = new Date(startOfYear.getTime() + daysToAdd * 24 * 60 * 60 * 1000); + + const dayOfWeek = weekStart.getDay(); + weekStart.setDate(weekStart.getDate() - dayOfWeek); + + this.currentMonth = weekStart.getMonth() + 1; + } + private getWeeksInYear(year: number): number { const lastDay = new Date(year, 11, 31); const startOfYear = new Date(year, 0, 1); @@ -325,10 +382,4 @@ export class ReadingSessionTimelineComponent implements OnInit { public getCoverUrl(bookId: number): string { return this.urlHelperService.getThumbnailUrl1(bookId); } - - public getTitle(): string { - return this.userName - ? `${this.userName}'s Reading Session Timeline` - : 'Reading Session Timeline'; - } } diff --git a/booklore-ui/src/app/features/stats/component/stats-component.html b/booklore-ui/src/app/features/stats/component/stats-component.html index 0f4197391..1c87f1d22 100644 --- a/booklore-ui/src/app/features/stats/component/stats-component.html +++ b/booklore-ui/src/app/features/stats/component/stats-component.html @@ -328,70 +328,6 @@
} - @case ('readingDNA') { -

Your Reading DNA Profile

-
- Discover your unique reading personality based on behavioral patterns and preferences -
-
- - -
-
- @if ((readingDNAChartService.readingDNAChartData$ | async)?.datasets?.[0]?.data?.length) { -
- @for (insight of readingDNAChartService.getPersonalityInsights(); track trackByTrait($index, insight)) { -
-
-
- {{ insight.trait }} - {{ insight.score.toFixed(0) }}% -
-
-
-
-

{{ insight.description }}

-
- } -
- } -
- } - @case ('readingHabits') { -

Reading Habits Analysis

-
- Analyze your behavioral reading patterns, routines, and systematic approaches -
-
- - -
-
- @if ((readingHabitsChartService.readingHabitsChartData$ | async)?.datasets?.[0]?.data?.length) { -
- @for (habit of readingHabitsChartService.getHabitInsights(); track trackByHabit($index, habit)) { -
-
-
- {{ habit.habit }} - {{ habit.score.toFixed(0) }}% -
-
-
-
-

{{ habit.description }}

-
- } -
- } -
- } }
} diff --git a/booklore-ui/src/app/features/stats/component/stats-component.scss b/booklore-ui/src/app/features/stats/component/stats-component.scss index 0e8deb826..3d46106e1 100644 --- a/booklore-ui/src/app/features/stats/component/stats-component.scss +++ b/booklore-ui/src/app/features/stats/component/stats-component.scss @@ -715,7 +715,7 @@ display: flex; align-items: center; justify-content: center; - gap: 1rem; + gap: 0.5rem; .year-nav-btn { background: rgba(255, 255, 255, 0.1); @@ -908,7 +908,7 @@ &.publisher-chart, &.author-rating-chart, &.book-size-chart { - height: 350px; + height: 100px; } &.year-chart, diff --git a/booklore-ui/src/app/features/stats/component/stats-component.ts b/booklore-ui/src/app/features/stats/component/stats-component.ts index 88a1b0cf1..d7801c41c 100644 --- a/booklore-ui/src/app/features/stats/component/stats-component.ts +++ b/booklore-ui/src/app/features/stats/component/stats-component.ts @@ -28,8 +28,6 @@ import {BookSizeChartService} from '../service/book-size-chart.service'; import {ReadingVelocityTimelineChartService} from '../service/reading-velocity-timeline-chart.service'; import {MonthlyReadingPatternsChartService} from '../service/monthly-reading-patterns-chart.service'; import {TopSeriesChartService} from '../service/top-series-chart.service'; -import {ReadingDNAChartService} from '../service/reading-dna-chart.service'; -import {ReadingHabitsChartService} from '../service/reading-habits-chart.service'; import {ChartConfig, ChartConfigService} from '../service/chart-config.service'; @Component({ @@ -67,8 +65,6 @@ export class StatsComponent implements OnInit, OnDestroy { protected readonly readingVelocityTimelineChartService = inject(ReadingVelocityTimelineChartService); protected readonly monthlyReadingPatternsChartService = inject(MonthlyReadingPatternsChartService); protected readonly topSeriesChartService = inject(TopSeriesChartService); - protected readonly readingDNAChartService = inject(ReadingDNAChartService); - protected readonly readingHabitsChartService = inject(ReadingHabitsChartService); protected readonly chartConfigService = inject(ChartConfigService); private readonly pageTitle = inject(PageTitleService); diff --git a/booklore-ui/src/app/features/stats/component/user-stats/user-stats.component.html b/booklore-ui/src/app/features/stats/component/user-stats/user-stats.component.html index 400165534..bfc8e2e43 100644 --- a/booklore-ui/src/app/features/stats/component/user-stats/user-stats.component.html +++ b/booklore-ui/src/app/features/stats/component/user-stats/user-stats.component.html @@ -1,11 +1,99 @@
-
-
- -
- -
- +
+
+
+ +

{{ userName }}'s Reading Statistics

+
+
+ + + +
+
+ @for (chart of charts; track chart.id) { +
+
+ +
+ {{ chart.title }} + +
+ } +
+
+ + + + + Reset Layout + + + + Hide All + + + + Show All + + + Close + + +
+ + +
+ @for (chart of visibleCharts; track chart.id) { +
+
+ +
+ + @switch (chart.id) { + @case ('heatmap') { + + } + @case ('timeline') { + + } + @case ('genre-stats') { + + } + @case ('completion-timeline') { + + } + @case ('favorite-days') { + + } + @case ('peak-hours') { + + } + @case ('reading-dna') { + + } + @case ('reading-habits') { + + } + } +
+ } +
diff --git a/booklore-ui/src/app/features/stats/component/user-stats/user-stats.component.scss b/booklore-ui/src/app/features/stats/component/user-stats/user-stats.component.scss index 432d5ae9c..9a48607bc 100644 --- a/booklore-ui/src/app/features/stats/component/user-stats/user-stats.component.scss +++ b/booklore-ui/src/app/features/stats/component/user-stats/user-stats.component.scss @@ -9,16 +9,12 @@ .header-section { background: var(--card-background); border-radius: 12px; - padding: 1.5rem; + padding: 1rem; backdrop-filter: blur(10px); border: 1px solid var(--p-content-border-color); box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); margin-bottom: 2rem; - margin-left: auto; - margin-right: auto; transition: all 0.3s ease; - width: fit-content; - max-width: 100%; &:hover { border-color: rgba(255, 255, 255, 0.2); @@ -27,16 +23,19 @@ .header-content { display: flex; - flex-direction: column; - gap: 0.5rem; + justify-content: center; align-items: center; - text-align: center; + gap: 2rem; + position: relative; } .greeting { display: flex; align-items: center; gap: 0.75rem; + position: absolute; + left: 50%; + transform: translateX(-50%); i { font-size: 1.5rem; @@ -51,12 +50,147 @@ white-space: nowrap; } } + + .config-toggle-btn { + margin-left: auto; + } +} + +.config-header { + display: flex; + justify-content: flex-end; + margin-bottom: 1rem; +} + +.config-toggle-btn { + display: flex; + align-items: center; + gap: 0.5rem; + padding: 0.75rem 1.25rem; + background: var(--card-background); + border: 1px solid var(--p-content-border-color); + border-radius: 8px; + color: var(--text-color); + cursor: pointer; + transition: all 0.3s ease; + font-size: 0.9rem; + white-space: nowrap; + + &:hover { + background: var(--p-primary-color); + color: white; + border-color: var(--p-primary-color); + } + + i { + font-size: 1rem; + } +} + +// Dialog styles +::ng-deep .config-dialog { + .p-dialog-header { + border-bottom: 1px solid var(--p-content-border-color); + } + + .p-dialog-content { + background: var(--card-background); + padding: 1.5rem; + } + + .p-dialog-footer { + border-top: 1px solid var(--p-content-border-color); + padding: 1rem 1.5rem; + display: flex; + gap: 0.75rem; + justify-content: flex-end; + + .reset-btn { + margin-right: auto; + } + + .hide-all-btn, + .show-all-btn { + display: flex; + align-items: center; + gap: 0.5rem; + } + } +} + +.config-dialog-content { + .config-list { + display: flex; + flex-direction: column; + gap: 0.75rem; + } + + .config-item { + display: flex; + align-items: center; + gap: 1rem; + padding: 0.5rem 1.25rem; + background: rgba(255, 255, 255, 0.03); + border: 1px solid var(--p-content-border-color); + border-radius: 8px; + cursor: move; + transition: all 0.2s ease; + + &:hover { + background: rgba(255, 255, 255, 0.05); + border-color: var(--p-primary-color); + } + + .drag-handle { + cursor: grab; + color: var(--text-color-secondary); + display: flex; + align-items: center; + + &:active { + cursor: grabbing; + } + } + + .chart-title { + flex: 1; + color: var(--text-color); + font-size: 0.95rem; + } + + .visibility-toggle { + padding: 0.5rem; + background: transparent; + border: 1px solid var(--p-content-border-color); + border-radius: 6px; + color: var(--p-primary-color); + cursor: pointer; + transition: all 0.2s ease; + + &:hover { + background: var(--p-primary-color); + color: white; + border-color: var(--p-primary-color); + } + + &.disabled { + color: var(--text-color-secondary); + opacity: 0.5; + + &:hover { + background: transparent; + color: var(--text-color-secondary); + border-color: var(--p-content-border-color); + } + } + } + } } .charts-container { - display: flex; - flex-direction: column; - gap: 2rem; + display: grid; + grid-template-columns: repeat(12, 1fr); + gap: 1.5rem; } .chart-card { @@ -67,11 +201,77 @@ border: 1px solid var(--p-content-border-color); box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); transition: all 0.3s ease; + position: relative; + overflow: hidden; &:hover { border-color: rgba(255, 255, 255, 0.2); box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15); + + .chart-drag-handle { + opacity: 1; + } } + + .chart-drag-handle { + position: absolute; + top: 0.5rem; + right: 0.5rem; + padding: 0.5rem; + background: rgba(0, 0, 0, 0.3); + border-radius: 6px; + cursor: grab; + opacity: 0; + transition: opacity 0.2s ease; + z-index: 10; + color: var(--text-color); + + &:active { + cursor: grabbing; + } + + &:hover { + background: rgba(0, 0, 0, 0.5); + } + } + + &.chart-small-square { + grid-column: span 3; + } + + &.chart-small { + grid-column: span 4; + } + + &.chart-medium { + grid-column: span 6; + } + + &.chart-large { + grid-column: span 8; + } + + &.chart-wide { + grid-column: span 9; + } + + &.chart-full { + grid-column: span 12; + } +} + +.cdk-drag-preview { + opacity: 0.8; + box-shadow: 0 8px 16px rgba(0, 0, 0, 0.3); +} + +.cdk-drag-placeholder { + opacity: 0.3; + border: 2px dashed var(--p-primary-color); +} + +.cdk-drag-animating { + transition: transform 250ms cubic-bezier(0, 0, 0.2, 1); } @media (max-width: 768px) { @@ -79,10 +279,60 @@ padding: 1rem; } + .config-toggle-btn { + span { + display: none; + } + } + + ::ng-deep .config-dialog { + .p-dialog-content { + padding: 1rem; + } + + .p_dialog_footer { + flex-direction: column; + gap: 0.5rem; + + .reset-btn { + margin-right: 0; + width: 100%; + } + + button { + width: 100%; + } + } + } + + .config-panel { + padding: 1rem; + + .config-panel-header { + flex-direction: column; + align-items: flex-start; + gap: 1rem; + + .reset-btn { + width: 100%; + justify-content: center; + } + } + } + .header-section { padding: 1rem; + .header-content { + flex-direction: column; + gap: 1rem; + position: static; + } + .greeting { + position: static; + transform: none; + i { font-size: 1.25rem; } @@ -94,8 +344,36 @@ } } + .config-toggle-btn { + width: 100%; + justify-content: center; + margin-left: 0; + + span { + display: inline; + } + } + + .charts-container { + grid-template-columns: repeat(6, 1fr); + gap: 1rem; + } + .chart-card { padding: 1rem; + + .chart-drag-handle { + opacity: 1; + } + + &.chart-small-square, + &.chart-small, + &.chart-medium, + &.chart-large, + &.chart-wide, + &.chart-full { + grid-column: span 6; + } } } @@ -104,6 +382,20 @@ padding: 0.75rem; } + .config-toggle-btn { + padding: 0.5rem 0.75rem; + } + + ::ng-deep .config-dialog { + .p-dialog-content { + padding: 0.75rem; + } + } + + .config-panel { + padding: 0.75rem; + } + .header-section { padding: 0.75rem; @@ -121,7 +413,21 @@ } } + .charts-container { + grid-template-columns: 1fr; + gap: 0.75rem; + } + .chart-card { padding: 0.75rem; + + &.chart-small-square, + &.chart-small, + &.chart-medium, + &.chart-large, + &.chart-wide, + &.chart-full { + grid-column: span 1; + } } } diff --git a/booklore-ui/src/app/features/stats/component/user-stats/user-stats.component.ts b/booklore-ui/src/app/features/stats/component/user-stats/user-stats.component.ts index 55069ea59..ad8a9fbe2 100644 --- a/booklore-ui/src/app/features/stats/component/user-stats/user-stats.component.ts +++ b/booklore-ui/src/app/features/stats/component/user-stats/user-stats.component.ts @@ -1,22 +1,38 @@ import {Component, inject, OnDestroy, OnInit} from '@angular/core'; import {CommonModule} from '@angular/common'; import {Subject} from 'rxjs'; +import {CdkDragDrop, DragDropModule} from '@angular/cdk/drag-drop'; +import {DialogModule} from 'primeng/dialog'; +import {ButtonModule} from 'primeng/button'; import {ReadingSessionHeatmapComponent} from '../reading-session-heatmap/reading-session-heatmap.component'; import {ReadingSessionTimelineComponent} from '../reading-session-timeline/reading-session-timeline.component'; +import {GenreStatsChartComponent} from '../genre-stats-chart/genre-stats-chart.component'; +import {CompletionTimelineChartComponent} from '../completion-timeline-chart/completion-timeline-chart.component'; import {UserService} from '../../../settings/user-management/user.service'; import {takeUntil} from 'rxjs/operators'; - -interface UserChartConfig { - id: string; - component: any; - enabled: boolean; - order: number; -} +import {FavoriteDaysChartComponent} from '../favorite-days-chart/favorite-days-chart.component'; +import {PeakHoursChartComponent} from '../peak-hours-chart/peak-hours-chart.component'; +import {ReadingDNAChartComponent} from '../reading-dna-chart/reading-dna-chart.component'; +import {ReadingHabitsChartComponent} from '../reading-habits-chart/reading-habits-chart.component'; +import {UserChartConfig, UserChartConfigService} from '../../service/user-chart-config.service'; @Component({ selector: 'app-user-stats', standalone: true, - imports: [CommonModule, ReadingSessionHeatmapComponent, ReadingSessionTimelineComponent], + imports: [ + CommonModule, + DragDropModule, + DialogModule, + ButtonModule, + ReadingSessionHeatmapComponent, + ReadingSessionTimelineComponent, + GenreStatsChartComponent, + CompletionTimelineChartComponent, + FavoriteDaysChartComponent, + PeakHoursChartComponent, + ReadingDNAChartComponent, + ReadingHabitsChartComponent + ], templateUrl: './user-stats.component.html', styleUrls: ['./user-stats.component.scss'] }) @@ -24,10 +40,22 @@ export class UserStatsComponent implements OnInit, OnDestroy { private readonly destroy$ = new Subject(); private userService = inject(UserService); + private chartConfigService = inject(UserChartConfigService); + public currentYear = new Date().getFullYear(); public userName: string = ''; + public showConfigPanel = false; + public charts: UserChartConfig[] = []; + public visibleCharts: UserChartConfig[] = []; ngOnInit(): void { + this.chartConfigService.charts$ + .pipe(takeUntil(this.destroy$)) + .subscribe(charts => { + this.charts = charts; + this.visibleCharts = this.chartConfigService.getVisibleCharts(); + }); + this.userService.userState$ .pipe(takeUntil(this.destroy$)) .subscribe(state => { @@ -41,4 +69,36 @@ export class UserStatsComponent implements OnInit, OnDestroy { this.destroy$.next(); this.destroy$.complete(); } + + toggleChart(chartId: string): void { + this.chartConfigService.toggleChart(chartId); + } + + drop(event: CdkDragDrop): void { + this.chartConfigService.reorderCharts(event.previousIndex, event.currentIndex); + } + + toggleConfigPanel(): void { + this.showConfigPanel = !this.showConfigPanel; + } + + resetLayout(): void { + this.chartConfigService.resetLayout(); + } + + hideAllCharts(): void { + this.charts.forEach(chart => { + if (chart.enabled) { + this.chartConfigService.toggleChart(chart.id); + } + }); + } + + showAllCharts(): void { + this.charts.forEach(chart => { + if (!chart.enabled) { + this.chartConfigService.toggleChart(chart.id); + } + }); + } } diff --git a/booklore-ui/src/app/features/stats/service/author-series-portfolio-chart.service.ts b/booklore-ui/src/app/features/stats/service/author-series-portfolio-chart.service.ts deleted file mode 100644 index 2bebec38d..000000000 --- a/booklore-ui/src/app/features/stats/service/author-series-portfolio-chart.service.ts +++ /dev/null @@ -1,355 +0,0 @@ -import {inject, Injectable, OnDestroy} from '@angular/core'; -import {BehaviorSubject, combineLatest, Observable, Subject} from 'rxjs'; -import {map, takeUntil, catchError} from 'rxjs/operators'; -import {ChartConfiguration, ChartData} from 'chart.js'; - -import {LibraryFilterService} from './library-filter.service'; -import {BookService} from '../../book/service/book.service'; -import {Book} from '../../book/model/book.model'; - -interface AuthorSeriesStats { - category: string; - count: number; - authorNames: string[]; - totalSeries: number; - averageSeriesLength: number; - description: string; -} - -const CHART_COLORS = [ - '#e74c3c', '#3498db', '#2ecc71', '#f39c12', '#9b59b6', - '#e67e22', '#1abc9c', '#34495e', '#95a5a6', '#27ae60', - '#2980b9', '#c0392b', '#d35400', '#8e44ad', '#16a085' -] as const; - -const CHART_DEFAULTS = { - borderColor: '#ffffff', - borderWidth: 2, - hoverBorderWidth: 3, - hoverBorderColor: '#ffffff' -} as const; - -type AuthorSeriesChartData = ChartData<'polarArea', number[], string>; - -@Injectable({ - providedIn: 'root' -}) -export class AuthorSeriesPortfolioChartService implements OnDestroy { - private readonly bookService = inject(BookService); - private readonly libraryFilterService = inject(LibraryFilterService); - private readonly destroy$ = new Subject(); - - public readonly authorSeriesChartType = 'polarArea' as const; - - public readonly authorSeriesChartOptions: ChartConfiguration<'polarArea'>['options'] = { - responsive: true, - maintainAspectRatio: false, - scales: { - r: { - beginAtZero: true, - ticks: { - color: '#ffffff', - font: { - family: "'Inter', sans-serif", - size: 11 - }, - stepSize: 1, - backdropColor: 'transparent' - }, - grid: { - color: 'rgba(255, 255, 255, 0.15)' - }, - angleLines: { - color: 'rgba(255, 255, 255, 0.15)' - }, - pointLabels: { - color: '#ffffff', - font: { - family: "'Inter', sans-serif", - size: 11 - }, - } - } - }, - plugins: { - legend: { - display: true, - position: 'bottom', - labels: { - color: '#ffffff', - font: { - family: "'Inter', sans-serif", - size: 11 - }, - padding: 10, - usePointStyle: true, - generateLabels: this.generateLegendLabels.bind(this) - } - }, - tooltip: { - backgroundColor: 'rgba(0, 0, 0, 0.9)', - titleColor: '#ffffff', - bodyColor: '#ffffff', - borderColor: '#ffffff', - borderWidth: 1, - cornerRadius: 6, - displayColors: true, - padding: 12, - titleFont: {size: 14, weight: 'bold'}, - bodyFont: {size: 12}, - callbacks: { - title: (context) => context[0]?.label || '', - label: this.formatTooltipLabel.bind(this) - } - } - }, - interaction: { - intersect: false, - mode: 'point' - } - }; - - private readonly authorSeriesChartDataSubject = new BehaviorSubject({ - labels: [], - datasets: [{ - data: [], - backgroundColor: [...CHART_COLORS], - ...CHART_DEFAULTS - }] - }); - - public readonly authorSeriesChartData$: Observable = this.authorSeriesChartDataSubject.asObservable(); - - constructor() { - this.initializeChartDataSubscription(); - } - - ngOnDestroy(): void { - this.destroy$.next(); - this.destroy$.complete(); - } - - private initializeChartDataSubscription(): void { - this.getAuthorSeriesStats() - .pipe( - takeUntil(this.destroy$), - catchError((error) => { - console.error('Error processing author series stats:', error); - return []; - }) - ) - .subscribe((stats) => this.updateChartData(stats)); - } - - private updateChartData(stats: AuthorSeriesStats[]): void { - try { - this.lastCalculatedStats = stats; - const labels = stats.map(s => s.category); - const dataValues = stats.map(s => s.count); - const colors = this.getColorsForData(stats.length); - - this.authorSeriesChartDataSubject.next({ - labels, - datasets: [{ - data: dataValues, - backgroundColor: colors, - ...CHART_DEFAULTS - }] - }); - } catch (error) { - console.error('Error updating author series chart data:', error); - } - } - - private getColorsForData(dataLength: number): string[] { - const colors = [...CHART_COLORS]; - while (colors.length < dataLength) { - colors.push(...CHART_COLORS); - } - return colors.slice(0, dataLength); - } - - public getAuthorSeriesStats(): Observable { - return combineLatest([ - this.bookService.bookState$, - this.libraryFilterService.selectedLibrary$ - ]).pipe( - map(([state, selectedLibraryId]) => { - if (!this.isValidBookState(state)) { - return []; - } - - const filteredBooks = this.filterBooksByLibrary(state.books!, String(selectedLibraryId)); - return this.processAuthorSeriesStats(filteredBooks); - }), - catchError((error) => { - console.error('Error getting author series stats:', error); - return []; - }) - ); - } - - private isValidBookState(state: any): boolean { - return state?.loaded && state?.books && Array.isArray(state.books) && state.books.length > 0; - } - - private filterBooksByLibrary(books: Book[], selectedLibraryId: string | null): Book[] { - return selectedLibraryId && selectedLibraryId !== 'null' - ? books.filter(book => String(book.libraryId) === selectedLibraryId) - : books; - } - - private processAuthorSeriesStats(books: Book[]): AuthorSeriesStats[] { - if (books.length === 0) { - return []; - } - - const authorSeriesMap = new Map>(); - - books.forEach(book => { - if (!book.metadata?.authors || !book.metadata.seriesName) return; - - book.metadata.authors.forEach(author => { - if (!authorSeriesMap.has(author)) { - authorSeriesMap.set(author, new Map()); - } - - const authorSeries = authorSeriesMap.get(author)!; - const seriesName = book.metadata!.seriesName!; - - if (!authorSeries.has(seriesName)) { - authorSeries.set(seriesName, []); - } - authorSeries.get(seriesName)!.push(book); - }); - }); - - const authorPatterns = new Map(); - - const categories = [ - 'Single Series Masters', - 'Prolific Series Writers', - 'Multi-Series Creators', - 'Series Experimenters', - 'Franchise Builders', - 'Diverse Portfolio Authors' - ]; - - categories.forEach(cat => { - authorPatterns.set(cat, {authors: [], totalSeries: 0, totalSeriesLength: 0}); - }); - - for (const [author, authorSeries] of authorSeriesMap) { - const seriesCount = authorSeries.size; - const seriesLengths: number[] = []; - let totalBooks = 0; - - for (const [_, seriesBooks] of authorSeries) { - const seriesTotals = seriesBooks - .map(book => book.metadata?.seriesTotal) - .filter((total): total is number => total != null && total > 0); - - const seriesLength = seriesTotals.length > 0 - ? Math.max(...seriesTotals) - : seriesBooks.length; - - seriesLengths.push(seriesLength); - totalBooks += seriesBooks.length; - } - - const averageSeriesLength = seriesLengths.reduce((sum, length) => sum + length, 0) / seriesLengths.length; - const maxSeriesLength = Math.max(...seriesLengths); - - let category: string; - - if (seriesCount === 1 && maxSeriesLength >= 10) { - category = 'Single Series Masters'; - } else if (seriesCount >= 5 && averageSeriesLength >= 5) { - category = 'Prolific Series Writers'; - } else if (seriesCount >= 3 && seriesCount <= 4) { - category = 'Multi-Series Creators'; - } else if (seriesCount >= 2 && averageSeriesLength <= 3) { - category = 'Series Experimenters'; - } else if (seriesCount >= 2 && maxSeriesLength >= 15) { - category = 'Franchise Builders'; - } else { - category = 'Diverse Portfolio Authors'; - } - - const categoryData = authorPatterns.get(category)!; - categoryData.authors.push(author); - categoryData.totalSeries += seriesCount; - categoryData.totalSeriesLength += Math.round(averageSeriesLength); - } - - const descriptions: Record = { - 'Single Series Masters': 'Authors focused on one long-running series', - 'Prolific Series Writers': 'Authors with multiple substantial series', - 'Multi-Series Creators': 'Authors balancing several series', - 'Series Experimenters': 'Authors exploring shorter series formats', - 'Franchise Builders': 'Authors creating extensive fictional universes', - 'Diverse Portfolio Authors': 'Authors with varied series approaches' - }; - - return Array.from(authorPatterns.entries()) - .filter(([_, data]) => data.authors.length > 0) - .map(([category, data]) => ({ - category, - count: data.authors.length, - authorNames: data.authors, - totalSeries: data.totalSeries, - averageSeriesLength: data.authors.length > 0 - ? Math.round(data.totalSeriesLength / data.authors.length) - : 0, - description: descriptions[category] || 'Various series approaches' - })) - .sort((a, b) => b.count - a.count); - } - - private generateLegendLabels(chart: any) { - const data = chart.data; - if (!data.labels?.length || !data.datasets?.[0]?.data?.length) { - return []; - } - - const dataset = data.datasets[0]; - const dataValues = dataset.data as number[]; - - return data.labels.map((label: string, index: number) => { - const isVisible = typeof chart.getDataVisibility === 'function' - ? chart.getDataVisibility(index) - : !((chart.getDatasetMeta && chart.getDatasetMeta(0)?.data?.[index]?.hidden) || false); - - return { - text: `${label} (${dataValues[index]})`, - fillStyle: (dataset.backgroundColor as string[])[index], - strokeStyle: '#ffffff', - lineWidth: 1, - hidden: !isVisible, - index, - fontColor: '#ffffff' - }; - }); - } - - private formatTooltipLabel(context: any): string { - const dataIndex = context.dataIndex; - const stats = this.getLastCalculatedStats(); - - if (!stats || dataIndex >= stats.length) { - return `${context.parsed} authors`; - } - - const categoryStats = stats[dataIndex]; - const exampleAuthors = categoryStats.authorNames.slice(0, 3).join(', '); - const moreAuthors = categoryStats.authorNames.length > 3 ? `... +${categoryStats.authorNames.length - 3} more` : ''; - - return `${categoryStats.count} authors | ${categoryStats.totalSeries} total series | Avg ${categoryStats.averageSeriesLength} books/series | ${categoryStats.description} | Examples: ${exampleAuthors}${moreAuthors}`; - } - - private lastCalculatedStats: AuthorSeriesStats[] = []; - - private getLastCalculatedStats(): AuthorSeriesStats[] { - return this.lastCalculatedStats; - } -} diff --git a/booklore-ui/src/app/features/stats/service/chart-config.service.ts b/booklore-ui/src/app/features/stats/service/chart-config.service.ts index 177da01eb..1296b6b1b 100644 --- a/booklore-ui/src/app/features/stats/service/chart-config.service.ts +++ b/booklore-ui/src/app/features/stats/service/chart-config.service.ts @@ -30,9 +30,7 @@ export class ChartConfigService { {id: 'pageCount', name: 'Page Count Distribution', enabled: true, category: 'medium', order: 11}, {id: 'topBooksBySize', name: 'Top 20 Largest Books', enabled: true, category: 'large', order: 12}, {id: 'topSeries', name: 'Top 20 Series', enabled: true, category: 'large', order: 13}, - {id: 'readingDNA', name: 'Reading DNA Profile', enabled: true, category: 'large', order: 14}, - {id: 'readingHabits', name: 'Reading Habits Analysis', enabled: true, category: 'large', order: 15}, - {id: 'publicationYear', name: 'Publication Year Timeline', enabled: true, category: 'full-width', order: 16} + {id: 'publicationYear', name: 'Publication Year Timeline', enabled: true, category: 'full-width', order: 14} ]; private chartsConfigSubject = new BehaviorSubject(this.loadConfig()); diff --git a/booklore-ui/src/app/features/stats/service/finished-books-timeline-chart.service.ts b/booklore-ui/src/app/features/stats/service/finished-books-timeline-chart.service.ts deleted file mode 100644 index 939f5e928..000000000 --- a/booklore-ui/src/app/features/stats/service/finished-books-timeline-chart.service.ts +++ /dev/null @@ -1,54 +0,0 @@ -// ...existing code... - - private processFinishedBooksStats(books: Book[]): FinishedBooksStats[] { - const yearMonthMap = new Map(); - - books.forEach(book => { - if (book.dateFinished) { - const finishedDate = new Date(book.dateFinished); - const yearMonth = `${finishedDate.getFullYear()}-${(finishedDate.getMonth() + 1).toString().padStart(2, '0')}`; - yearMonthMap.set(yearMonth, (yearMonthMap.get(yearMonth) || 0) + 1); - } - }); - - // Get the range of months - const monthsWithData = Array.from(yearMonthMap.keys()).sort(); - - if (monthsWithData.length === 0) { - return []; - } - - // Fill in all missing months between first and last data points - const startDate = this.parseYearMonth(monthsWithData[0]); - const endDate = this.parseYearMonth(monthsWithData[monthsWithData.length - 1]); - - const completeStats: FinishedBooksStats[] = []; - let currentDate = new Date(startDate.year, startDate.month - 1, 1); - const endDateObj = new Date(endDate.year, endDate.month - 1, 1); - - while (currentDate <= endDateObj) { - const year = currentDate.getFullYear(); - const month = currentDate.getMonth() + 1; - const yearMonth = `${year}-${month.toString().padStart(2, '0')}`; - - completeStats.push({ - yearMonth, - count: yearMonthMap.get(yearMonth) || 0, - year, - month - }); - - // Move to next month - currentDate.setMonth(currentDate.getMonth() + 1); - } - - return completeStats.sort((a, b) => a.yearMonth.localeCompare(b.yearMonth)); - } - - private parseYearMonth(yearMonthStr: string): { year: number, month: number } { - const [year, month] = yearMonthStr.split('-').map(Number); - return { year, month }; - } - -// ...existing code... - diff --git a/booklore-ui/src/app/features/stats/service/reading-velocity-chart.service.ts b/booklore-ui/src/app/features/stats/service/reading-velocity-chart.service.ts deleted file mode 100644 index 250c93f2e..000000000 --- a/booklore-ui/src/app/features/stats/service/reading-velocity-chart.service.ts +++ /dev/null @@ -1,380 +0,0 @@ -import {inject, Injectable, OnDestroy} from '@angular/core'; -import {BehaviorSubject, combineLatest, Observable, Subject} from 'rxjs'; -import {map, takeUntil, catchError} from 'rxjs/operators'; -import {ChartConfiguration, ChartData} from 'chart.js'; - -import {LibraryFilterService} from './library-filter.service'; -import {BookService} from '../../book/service/book.service'; -import {Book, ReadStatus} from '../../book/model/book.model'; - -interface ReadingVelocityStats { - category: string; - count: number; - averagePages: number; - averageRating: number; - description: string; -} - -const CHART_COLORS = [ - '#ff6b9d', '#45aaf2', '#96f7d2', '#feca57', '#ff9ff3', - '#54a0ff', '#5f27cd', '#00d2d3', '#ff9f43', '#10ac84', - '#ee5a6f', '#60a3bc', '#130f40', '#30336b', '#535c68' -] as const; - -const CHART_DEFAULTS = { - borderColor: '#ffffff', - borderWidth: 2, - hoverBorderWidth: 3, - hoverBorderColor: '#ffffff' -} as const; - -type VelocityChartData = ChartData<'polarArea', number[], string>; - -@Injectable({ - providedIn: 'root' -}) -export class ReadingVelocityChartService implements OnDestroy { - private readonly bookService = inject(BookService); - private readonly libraryFilterService = inject(LibraryFilterService); - private readonly destroy$ = new Subject(); - - public readonly velocityChartType = 'polarArea' as const; - - public readonly velocityChartOptions: ChartConfiguration<'polarArea'>['options'] = { - responsive: true, - maintainAspectRatio: false, - scales: { - r: { - beginAtZero: true, - ticks: { - color: '#ffffff', - font: {size: 10}, - stepSize: 1, - backdropColor: 'transparent' - }, - grid: { - color: 'rgba(255, 255, 255, 0.15)' - }, - angleLines: { - color: 'rgba(255, 255, 255, 0.15)' - }, - pointLabels: { - color: '#ffffff', - font: {size: 10} - } - } - }, - plugins: { - legend: { - display: true, - position: 'bottom', - labels: { - color: '#ffffff', - font: {size: 10}, - padding: 10, - usePointStyle: true, - generateLabels: this.generateLegendLabels.bind(this) - } - }, - tooltip: { - enabled: true, - backgroundColor: 'rgba(0, 0, 0, 0.9)', - titleColor: '#ffffff', - bodyColor: '#ffffff', - borderColor: '#ffffff', - borderWidth: 1, - cornerRadius: 6, - displayColors: true, - padding: 12, - titleFont: {size: 14, weight: 'bold'}, - bodyFont: {size: 12}, - position: 'nearest', - callbacks: { - title: (context) => context[0]?.label || '', - label: this.formatTooltipLabel.bind(this) - } - } - }, - interaction: { - intersect: false, - mode: 'point' - } - }; - - private readonly velocityChartDataSubject = new BehaviorSubject({ - labels: [], - datasets: [{ - data: [], - backgroundColor: [...CHART_COLORS], - ...CHART_DEFAULTS - }] - }); - - public readonly velocityChartData$: Observable = this.velocityChartDataSubject.asObservable(); - - constructor() { - this.initializeChartDataSubscription(); - } - - ngOnDestroy(): void { - this.destroy$.next(); - this.destroy$.complete(); - } - - private initializeChartDataSubscription(): void { - this.getReadingVelocityStats() - .pipe( - takeUntil(this.destroy$), - catchError((error) => { - console.error('Error processing reading velocity stats:', error); - return []; - }) - ) - .subscribe((stats) => this.updateChartData(stats)); - } - - private updateChartData(stats: ReadingVelocityStats[]): void { - try { - this.lastCalculatedStats = stats; - const labels = stats.map(s => s.category); - const dataValues = stats.map(s => s.count); - const colors = this.getColorsForData(stats.length); - - this.velocityChartDataSubject.next({ - labels, - datasets: [{ - data: dataValues, - backgroundColor: colors, - ...CHART_DEFAULTS - }] - }); - } catch (error) { - console.error('Error updating velocity chart data:', error); - } - } - - private getColorsForData(dataLength: number): string[] { - const colors = [...CHART_COLORS]; - while (colors.length < dataLength) { - colors.push(...CHART_COLORS); - } - return colors.slice(0, dataLength); - } - - public getReadingVelocityStats(): Observable { - return combineLatest([ - this.bookService.bookState$, - this.libraryFilterService.selectedLibrary$ - ]).pipe( - map(([state, selectedLibraryId]) => { - if (!this.isValidBookState(state)) { - return []; - } - - const filteredBooks = this.filterBooksByLibrary(state.books!, String(selectedLibraryId)); - return this.processReadingVelocityStats(filteredBooks); - }), - catchError((error) => { - console.error('Error getting reading velocity stats:', error); - return []; - }) - ); - } - - private isValidBookState(state: any): boolean { - return state?.loaded && state?.books && Array.isArray(state.books) && state.books.length > 0; - } - - private filterBooksByLibrary(books: Book[], selectedLibraryId: string | null): Book[] { - return selectedLibraryId && selectedLibraryId !== 'null' - ? books.filter(book => String(book.libraryId) === selectedLibraryId) - : books; - } - - private processReadingVelocityStats(books: Book[]): ReadingVelocityStats[] { - if (books.length === 0) { - return []; - } - - const velocityCategories = this.categorizeByReadingVelocity(books); - return this.convertToVelocityStats(velocityCategories); - } - - private categorizeByReadingVelocity(books: Book[]): Map { - const categories = new Map(); - - // Initialize categories - categories.set('Speed Readers', []); - categories.set('Consistent Readers', []); - categories.set('Selective Readers', []); - categories.set('Exploratory Readers', []); - categories.set('Deep Readers', []); - categories.set('Casual Readers', []); - categories.set('Quality Seekers', []); - - const readBooks = books.filter(book => - book.readStatus === ReadStatus.READ && - book.metadata?.pageCount && - book.metadata.pageCount > 0 - ); - - const completedBooks = readBooks.length; - const totalBooks = books.length; - const completionRate = completedBooks / totalBooks; - - const averagePageCount = readBooks.reduce((sum, book) => sum + (book.metadata?.pageCount || 0), 0) / readBooks.length || 0; - const averageRating = this.calculateAverageRating(readBooks); - - for (const book of books) { - const pageCount = book.metadata?.pageCount || 0; - const hasHighRating = this.hasHighQualityRating(book); - const isCompleted = book.readStatus === ReadStatus.READ; - const isCurrentlyReading = book.readStatus === ReadStatus.READING; - const progress = this.getReadingProgress(book); - - // Speed Readers: High completion rate + prefer shorter books - if (completionRate > 0.6 && pageCount > 0 && pageCount < averagePageCount * 0.8) { - categories.get('Speed Readers')!.push(book); - } - // Deep Readers: Prefer longer, high-quality books - else if (pageCount > averagePageCount * 1.5 && hasHighRating) { - categories.get('Deep Readers')!.push(book); - } - // Quality Seekers: Focus on highly-rated books regardless of length - else if (hasHighRating && (isCompleted || progress > 0.5)) { - categories.get('Quality Seekers')!.push(book); - } - // Exploratory Readers: Wide variety of books, many started but not finished - else if (!isCompleted && (progress > 0.1 && progress < 0.8)) { - categories.get('Exploratory Readers')!.push(book); - } - // Consistent Readers: Steady reading pattern, average book length - else if (isCompleted && pageCount > averagePageCount * 0.8 && pageCount < averagePageCount * 1.2) { - categories.get('Consistent Readers')!.push(book); - } - // Selective Readers: Few books but high completion rate - else if (completionRate > 0.4 && totalBooks < 50) { - categories.get('Selective Readers')!.push(book); - } - // Casual Readers: Everything else - else { - categories.get('Casual Readers')!.push(book); - } - } - - return categories; - } - - private hasHighQualityRating(book: Book): boolean { - const metadata = book.metadata; - if (!metadata) return false; - - const goodreadsRating = metadata.goodreadsRating || 0; - const amazonRating = metadata.amazonRating || 0; - const personalRating = book.personalRating || 0; - - return goodreadsRating >= 4.0 || amazonRating >= 4.0 || personalRating >= 4; - } - - private getReadingProgress(book: Book): number { - if (book.readStatus === ReadStatus.READ) return 1.0; - - const epubProgress = book.epubProgress?.percentage || 0; - const pdfProgress = book.pdfProgress?.percentage || 0; - const cbxProgress = book.cbxProgress?.percentage || 0; - const koreaderProgress = book.koreaderProgress?.percentage || 0; - const koboProgress = book.koboProgress?.percentage || 0; - - return Math.max(epubProgress, pdfProgress, cbxProgress, koreaderProgress, koboProgress) / 100; - } - - private calculateAverageRating(books: Book[]): number { - const ratingsBooks = books.filter(book => { - const metadata = book.metadata; - return metadata && (metadata.goodreadsRating || metadata.amazonRating || book.personalRating); - }); - - if (ratingsBooks.length === 0) return 0; - - const totalRating = ratingsBooks.reduce((sum, book) => { - const metadata = book.metadata!; - const rating = metadata.goodreadsRating || metadata.amazonRating || book.personalRating || 0; - return sum + rating; - }, 0); - - return totalRating / ratingsBooks.length; - } - - private convertToVelocityStats(categoriesMap: Map): ReadingVelocityStats[] { - const descriptions: Record = { - 'Speed Readers': 'High completion rate with shorter books', - 'Consistent Readers': 'Steady reading pattern with average-length books', - 'Selective Readers': 'Few books but high completion rate', - 'Exploratory Readers': 'Wide variety, many started but not finished', - 'Deep Readers': 'Prefer longer, high-quality books', - 'Casual Readers': 'Mixed reading patterns', - 'Quality Seekers': 'Focus on highly-rated books' - }; - - return Array.from(categoriesMap.entries()) - .filter(([_, books]) => books.length > 0) - .map(([category, books]) => { - const completedBooks = books.filter(book => book.readStatus === ReadStatus.READ); - const averagePages = books.reduce((sum, book) => sum + (book.metadata?.pageCount || 0), 0) / books.length; - const averageRating = this.calculateAverageRating(books); - - return { - category, - count: books.length, - averagePages: Math.round(averagePages), - averageRating: Number(averageRating.toFixed(1)), - description: descriptions[category] || 'Mixed reading patterns' - }; - }) - .sort((a, b) => b.count - a.count); - } - - private generateLegendLabels(chart: any) { - const data = chart.data; - if (!data.labels?.length || !data.datasets?.[0]?.data?.length) { - return []; - } - - const dataset = data.datasets[0]; - const dataValues = dataset.data as number[]; - - return data.labels.map((label: string, index: number) => { - const isVisible = typeof chart.getDataVisibility === 'function' - ? chart.getDataVisibility(index) - : !((chart.getDatasetMeta && chart.getDatasetMeta(0)?.data?.[index]?.hidden) || false); - - return { - text: `${label} (${dataValues[index]})`, - fillStyle: (dataset.backgroundColor as string[])[index], - strokeStyle: '#ffffff', - lineWidth: 1, - hidden: !isVisible, - index, - fontColor: '#ffffff' - }; - }); - } - - private formatTooltipLabel(context: any): string { - const dataIndex = context.dataIndex; - const velocityStats = this.getLastCalculatedStats(); - - if (!velocityStats || dataIndex >= velocityStats.length) { - return `${context.parsed} books`; - } - - const stats = velocityStats[dataIndex]; - return `${stats.count} books | Avg. ${stats.averagePages} pages | Avg. rating: ${stats.averageRating}/5 | ${stats.description}`; - } - - private lastCalculatedStats: ReadingVelocityStats[] = []; - - private getLastCalculatedStats(): ReadingVelocityStats[] { - return this.lastCalculatedStats; - } -} diff --git a/booklore-ui/src/app/features/stats/service/series-completion-progress-chart.service.ts b/booklore-ui/src/app/features/stats/service/series-completion-progress-chart.service.ts deleted file mode 100644 index dd4e52799..000000000 --- a/booklore-ui/src/app/features/stats/service/series-completion-progress-chart.service.ts +++ /dev/null @@ -1,327 +0,0 @@ -import {inject, Injectable, OnDestroy} from '@angular/core'; -import {BehaviorSubject, combineLatest, Observable, Subject} from 'rxjs'; -import {map, takeUntil, catchError} from 'rxjs/operators'; -import {ChartConfiguration, ChartData} from 'chart.js'; - -import {LibraryFilterService} from './library-filter.service'; -import {BookService} from '../../book/service/book.service'; -import {Book, ReadStatus} from '../../book/model/book.model'; - -interface SeriesCompletionStats { - seriesName: string; - totalBooks: number; - ownedBooks: number; - readBooks: number; - completionPercentage: number; - collectionPercentage: number; - isComplete: boolean; - averageRating: number; -} - -const CHART_COLORS = [ - '#2ecc71', '#3498db', '#e74c3c', '#f39c12', '#9b59b6', - '#1abc9c', '#34495e', '#e67e22', '#95a5a6', '#27ae60', - '#2980b9', '#c0392b', '#d35400', '#8e44ad', '#16a085' -] as const; - -const CHART_DEFAULTS = { - borderColor: '#ffffff', - borderWidth: 1, - hoverBorderWidth: 2, - hoverBorderColor: '#ffffff' -} as const; - -type SeriesCompletionChartData = ChartData<'bar', number[], string>; - -@Injectable({ - providedIn: 'root' -}) -export class SeriesCompletionProgressChartService implements OnDestroy { - private readonly bookService = inject(BookService); - private readonly libraryFilterService = inject(LibraryFilterService); - private readonly destroy$ = new Subject(); - - public readonly seriesCompletionChartType = 'bar' as const; - - public readonly seriesCompletionChartOptions: ChartConfiguration<'bar'>['options'] = { - responsive: true, - maintainAspectRatio: false, - scales: { - x: { - ticks: { - color: '#ffffff', - font: { size: 10 }, - maxRotation: 45 - }, - grid: { - color: 'rgba(255, 255, 255, 0.1)' - }, - title: { - display: true, - text: 'Series', - color: '#ffffff', - font: { size: 12 } - } - }, - y: { - beginAtZero: true, - max: 100, - ticks: { - color: '#ffffff', - font: { size: 10 }, - callback: function(value) { - return value + '%'; - } - }, - grid: { - color: 'rgba(255, 255, 255, 0.1)' - }, - title: { - display: true, - text: 'Completion %', - color: '#ffffff', - font: { size: 12 } - } - } - }, - plugins: { - legend: { - display: true, - position: 'top', - labels: { - color: '#ffffff', - font: { size: 11 }, - padding: 15, - usePointStyle: true - } - }, - tooltip: { - backgroundColor: 'rgba(0, 0, 0, 0.9)', - titleColor: '#ffffff', - bodyColor: '#ffffff', - borderColor: '#ffffff', - borderWidth: 1, - cornerRadius: 6, - displayColors: true, - padding: 12, - titleFont: { size: 14, weight: 'bold' }, - bodyFont: { size: 12 }, - callbacks: { - title: (context) => context[0]?.label || '', - label: this.formatTooltipLabel.bind(this) - } - } - }, - interaction: { - intersect: false, - mode: 'index' - } - }; - - private readonly seriesCompletionChartDataSubject = new BehaviorSubject({ - labels: [], - datasets: [] - }); - - public readonly seriesCompletionChartData$: Observable = this.seriesCompletionChartDataSubject.asObservable(); - - constructor() { - this.initializeChartDataSubscription(); - } - - ngOnDestroy(): void { - this.destroy$.next(); - this.destroy$.complete(); - } - - private initializeChartDataSubscription(): void { - this.getSeriesCompletionStats() - .pipe( - takeUntil(this.destroy$), - catchError((error) => { - console.error('Error processing series completion stats:', error); - return []; - }) - ) - .subscribe((stats) => this.updateChartData(stats)); - } - - private updateChartData(stats: SeriesCompletionStats[]): void { - try { - this.lastCalculatedStats = stats; - const labels = stats.map(s => this.truncateSeriesName(s.seriesName, 20)); - - const datasets = [ - { - label: 'Reading Progress', - data: stats.map(s => s.completionPercentage), - backgroundColor: '#2ecc71', - ...CHART_DEFAULTS - }, - { - label: 'Collection Progress', - data: stats.map(s => s.collectionPercentage), - backgroundColor: '#3498db', - ...CHART_DEFAULTS - } - ]; - - this.seriesCompletionChartDataSubject.next({ - labels, - datasets - }); - } catch (error) { - console.error('Error updating series completion chart data:', error); - } - } - - private truncateSeriesName(name: string, maxLength: number): string { - if (name.length <= maxLength) return name; - return name.substring(0, maxLength - 3) + '...'; - } - - public getSeriesCompletionStats(): Observable { - return combineLatest([ - this.bookService.bookState$, - this.libraryFilterService.selectedLibrary$ - ]).pipe( - map(([state, selectedLibraryId]) => { - if (!this.isValidBookState(state)) { - return []; - } - - const filteredBooks = this.filterBooksByLibrary(state.books!, String(selectedLibraryId)); - return this.processSeriesCompletionStats(filteredBooks); - }), - catchError((error) => { - console.error('Error getting series completion stats:', error); - return []; - }) - ); - } - - private isValidBookState(state: any): boolean { - return state?.loaded && state?.books && Array.isArray(state.books) && state.books.length > 0; - } - - private filterBooksByLibrary(books: Book[], selectedLibraryId: string | null): Book[] { - return selectedLibraryId && selectedLibraryId !== 'null' - ? books.filter(book => String(book.libraryId) === selectedLibraryId) - : books; - } - - private processSeriesCompletionStats(books: Book[]): SeriesCompletionStats[] { - if (books.length === 0) { - return []; - } - - // Group books by series - const seriesMap = new Map(); - - books.forEach(book => { - const seriesName = book.metadata?.seriesName; - if (seriesName && seriesName.trim()) { - if (!seriesMap.has(seriesName)) { - seriesMap.set(seriesName, []); - } - seriesMap.get(seriesName)!.push(book); - } - }); - - // Calculate completion stats for each series - const seriesStats: SeriesCompletionStats[] = []; - - for (const [seriesName, seriesBooks] of seriesMap) { - const stats = this.calculateSeriesStats(seriesName, seriesBooks); - if (stats.totalBooks > 1) { // Only include actual series (more than 1 book) - seriesStats.push(stats); - } - } - - return seriesStats - .sort((a, b) => { - // Sort by completion percentage, then by collection percentage - if (a.completionPercentage !== b.completionPercentage) { - return b.completionPercentage - a.completionPercentage; - } - return b.collectionPercentage - a.collectionPercentage; - }) - .slice(0, 15); // Top 15 series - } - - private calculateSeriesStats(seriesName: string, books: Book[]): SeriesCompletionStats { - // Determine total books in series - const seriesTotals = books - .map(book => book.metadata?.seriesTotal) - .filter((total): total is number => total != null && total > 0); - - const totalBooks = seriesTotals.length > 0 - ? Math.max(...seriesTotals) - : books.length; // Fallback to owned books count - - const ownedBooks = books.length; - const readBooks = books.filter(book => book.readStatus === ReadStatus.READ).length; - - // Calculate completion and collection percentages - const completionPercentage = totalBooks > 0 - ? Math.round((readBooks / totalBooks) * 100) - : 0; - - const collectionPercentage = totalBooks > 0 - ? Math.round((ownedBooks / totalBooks) * 100) - : 100; - - const isComplete = ownedBooks >= totalBooks; - - // Calculate average rating - const ratedBooks = books.filter(book => { - const rating = book.personalRating || book.metadata?.goodreadsRating; - return rating && rating > 0; - }); - - const averageRating = ratedBooks.length > 0 - ? Number((ratedBooks.reduce((sum, book) => { - const rating = book.personalRating || book.metadata?.goodreadsRating || 0; - return sum + rating; - }, 0) / ratedBooks.length).toFixed(1)) - : 0; - - return { - seriesName, - totalBooks, - ownedBooks, - readBooks, - completionPercentage, - collectionPercentage, - isComplete, - averageRating - }; - } - - private formatTooltipLabel(context: any): string { - const dataIndex = context.dataIndex; - const datasetLabel = context.dataset.label; - const value = context.parsed.y; - const stats = this.getLastCalculatedStats(); - - if (!stats || dataIndex >= stats.length) { - return `${datasetLabel}: ${value}%`; - } - - const series = stats[dataIndex]; - - if (datasetLabel === 'Reading Progress') { - return `${value}% read (${series.readBooks}/${series.totalBooks} books) | Avg rating: ${series.averageRating}/5`; - } else if (datasetLabel === 'Collection Progress') { - return `${value}% collected (${series.ownedBooks}/${series.totalBooks} books) | ${series.isComplete ? 'Complete!' : 'Incomplete'}`; - } - - return `${datasetLabel}: ${value}%`; - } - - private lastCalculatedStats: SeriesCompletionStats[] = []; - - private getLastCalculatedStats(): SeriesCompletionStats[] { - return this.lastCalculatedStats; - } -} diff --git a/booklore-ui/src/app/features/stats/service/series-length-distribution-chart.service.ts b/booklore-ui/src/app/features/stats/service/series-length-distribution-chart.service.ts deleted file mode 100644 index 181f2b9a5..000000000 --- a/booklore-ui/src/app/features/stats/service/series-length-distribution-chart.service.ts +++ /dev/null @@ -1,298 +0,0 @@ -import {inject, Injectable, OnDestroy} from '@angular/core'; -import {BehaviorSubject, combineLatest, Observable, Subject} from 'rxjs'; -import {map, takeUntil, catchError} from 'rxjs/operators'; -import {ChartConfiguration, ChartData} from 'chart.js'; - -import {LibraryFilterService} from './library-filter.service'; -import {BookService} from '../../book/service/book.service'; -import {Book} from '../../book/model/book.model'; - -interface SeriesLengthStats { - category: string; - count: number; - percentage: number; - seriesNames: string[]; - averageBooksOwned: number; -} - -const CHART_COLORS = [ - '#3498db', '#2ecc71', '#e74c3c', '#f39c12', '#9b59b6', - '#1abc9c', '#34495e', '#e67e22', '#95a5a6', '#27ae60' -] as const; - -const CHART_DEFAULTS = { - borderColor: '#ffffff', - borderWidth: 2, - hoverBorderWidth: 3, - hoverBorderColor: '#ffffff' -} as const; - -type SeriesLengthChartData = ChartData<'doughnut', number[], string>; - -@Injectable({ - providedIn: 'root' -}) -export class SeriesLengthDistributionChartService implements OnDestroy { - private readonly bookService = inject(BookService); - private readonly libraryFilterService = inject(LibraryFilterService); - private readonly destroy$ = new Subject(); - - public readonly seriesLengthChartType = 'doughnut' as const; - - public readonly seriesLengthChartOptions: ChartConfiguration<'doughnut'>['options'] = { - responsive: true, - maintainAspectRatio: false, - plugins: { - legend: { - display: true, - position: 'bottom', - labels: { - color: '#ffffff', - font: { size: 11 }, - padding: 12, - usePointStyle: true, - generateLabels: this.generateLegendLabels.bind(this) - } - }, - tooltip: { - backgroundColor: 'rgba(0, 0, 0, 0.9)', - titleColor: '#ffffff', - bodyColor: '#ffffff', - borderColor: '#ffffff', - borderWidth: 1, - cornerRadius: 6, - displayColors: true, - padding: 12, - titleFont: { size: 14, weight: 'bold' }, - bodyFont: { size: 12 }, - callbacks: { - title: (context) => context[0]?.label || '', - label: this.formatTooltipLabel.bind(this) - } - } - }, - interaction: { - intersect: false, - mode: 'point' - }, - cutout: '50%' - }; - - private readonly seriesLengthChartDataSubject = new BehaviorSubject({ - labels: [], - datasets: [{ - data: [], - backgroundColor: [...CHART_COLORS], - ...CHART_DEFAULTS - }] - }); - - public readonly seriesLengthChartData$: Observable = this.seriesLengthChartDataSubject.asObservable(); - - constructor() { - this.initializeChartDataSubscription(); - } - - ngOnDestroy(): void { - this.destroy$.next(); - this.destroy$.complete(); - } - - private initializeChartDataSubscription(): void { - this.getSeriesLengthStats() - .pipe( - takeUntil(this.destroy$), - catchError((error) => { - console.error('Error processing series length stats:', error); - return []; - }) - ) - .subscribe((stats) => this.updateChartData(stats)); - } - - private updateChartData(stats: SeriesLengthStats[]): void { - try { - this.lastCalculatedStats = stats; - const labels = stats.map(s => s.category); - const dataValues = stats.map(s => s.count); - const colors = this.getColorsForData(stats.length); - - this.seriesLengthChartDataSubject.next({ - labels, - datasets: [{ - data: dataValues, - backgroundColor: colors, - ...CHART_DEFAULTS - }] - }); - } catch (error) { - console.error('Error updating series length chart data:', error); - } - } - - private getColorsForData(dataLength: number): string[] { - const colors = [...CHART_COLORS]; - while (colors.length < dataLength) { - colors.push(...CHART_COLORS); - } - return colors.slice(0, dataLength); - } - - public getSeriesLengthStats(): Observable { - return combineLatest([ - this.bookService.bookState$, - this.libraryFilterService.selectedLibrary$ - ]).pipe( - map(([state, selectedLibraryId]) => { - if (!this.isValidBookState(state)) { - return []; - } - - const filteredBooks = this.filterBooksByLibrary(state.books!, String(selectedLibraryId)); - return this.processSeriesLengthStats(filteredBooks); - }), - catchError((error) => { - console.error('Error getting series length stats:', error); - return []; - }) - ); - } - - private isValidBookState(state: any): boolean { - return state?.loaded && state?.books && Array.isArray(state.books) && state.books.length > 0; - } - - private filterBooksByLibrary(books: Book[], selectedLibraryId: string | null): Book[] { - return selectedLibraryId && selectedLibraryId !== 'null' - ? books.filter(book => String(book.libraryId) === selectedLibraryId) - : books; - } - - private processSeriesLengthStats(books: Book[]): SeriesLengthStats[] { - if (books.length === 0) { - return []; - } - - // Group books by series - const seriesMap = new Map(); - - books.forEach(book => { - const seriesName = book.metadata?.seriesName; - if (seriesName && seriesName.trim()) { - if (!seriesMap.has(seriesName)) { - seriesMap.set(seriesName, []); - } - seriesMap.get(seriesName)!.push(book); - } - }); - - // Categorize series by length - const categories = new Map(); - - // Initialize categories - const categoryRanges = [ - { name: 'Duologies (2 books)', min: 2, max: 2 }, - { name: 'Trilogies (3 books)', min: 3, max: 3 }, - { name: 'Short Series (4-5 books)', min: 4, max: 5 }, - { name: 'Medium Series (6-10 books)', min: 6, max: 10 }, - { name: 'Long Series (11-20 books)', min: 11, max: 20 }, - { name: 'Epic Series (21+ books)', min: 21, max: Infinity }, - { name: 'Unknown Length', min: 0, max: 0 } - ]; - - categoryRanges.forEach(range => { - categories.set(range.name, { count: 0, seriesNames: [], totalBooksOwned: 0 }); - }); - - // Categorize each series - for (const [seriesName, seriesBooks] of seriesMap) { - if (seriesBooks.length < 2) continue; // Skip single books - - // Determine series total length - const seriesTotals = seriesBooks - .map(book => book.metadata?.seriesTotal) - .filter((total): total is number => typeof total === 'number' && total > 0); - - const seriesLength = seriesTotals.length > 0 - ? Math.max(...seriesTotals) - : 0; // Unknown length - - let categoryName = 'Unknown Length'; - - if (seriesLength > 0) { - for (const range of categoryRanges) { - if (seriesLength >= range.min && seriesLength <= range.max) { - categoryName = range.name; - break; - } - } - } - - const categoryData = categories.get(categoryName)!; - categoryData.count++; - categoryData.seriesNames.push(seriesName); - categoryData.totalBooksOwned += seriesBooks.length; - } - - // Convert to stats array - const totalSeries = Array.from(categories.values()).reduce((sum, cat) => sum + cat.count, 0); - - return Array.from(categories.entries()) - .filter(([_, data]) => data.count > 0) - .map(([category, data]) => ({ - category, - count: data.count, - percentage: Number(((data.count / totalSeries) * 100).toFixed(1)), - seriesNames: data.seriesNames, - averageBooksOwned: data.count > 0 ? Math.round(data.totalBooksOwned / data.count) : 0 - })) - .sort((a, b) => b.count - a.count); - } - - private generateLegendLabels(chart: any) { - const data = chart.data; - if (!data.labels?.length || !data.datasets?.[0]?.data?.length) { - return []; - } - - const dataset = data.datasets[0]; - const dataValues = dataset.data as number[]; - - return data.labels.map((label: string, index: number) => { - const isVisible = typeof chart.getDataVisibility === 'function' - ? chart.getDataVisibility(index) - : !((chart.getDatasetMeta && chart.getDatasetMeta(0)?.data?.[index]?.hidden) || false); - - return { - text: `${label} (${dataValues[index]})`, - fillStyle: (dataset.backgroundColor as string[])[index], - strokeStyle: '#ffffff', - lineWidth: 1, - hidden: !isVisible, - index, - fontColor: '#ffffff' - }; - }); - } - - private formatTooltipLabel(context: any): string { - const dataIndex = context.dataIndex; - const stats = this.getLastCalculatedStats(); - - if (!stats || dataIndex >= stats.length) { - return `${context.parsed} series`; - } - - const categoryStats = stats[dataIndex]; - const total = context.chart.data.datasets[0].data.reduce((a: number, b: number) => a + b, 0); - const percentage = ((categoryStats.count / total) * 100).toFixed(1); - - return `${categoryStats.count} series (${percentage}%) | Avg ${categoryStats.averageBooksOwned} books owned | Examples: ${categoryStats.seriesNames.slice(0, 3).join(', ')}${categoryStats.seriesNames.length > 3 ? '...' : ''}`; - } - - private lastCalculatedStats: SeriesLengthStats[] = []; - - private getLastCalculatedStats(): SeriesLengthStats[] { - return this.lastCalculatedStats; - } -} diff --git a/booklore-ui/src/app/features/stats/service/series-standalone-chart.service.ts b/booklore-ui/src/app/features/stats/service/series-standalone-chart.service.ts deleted file mode 100644 index 5bd9b6ab7..000000000 --- a/booklore-ui/src/app/features/stats/service/series-standalone-chart.service.ts +++ /dev/null @@ -1,309 +0,0 @@ -import {inject, Injectable, OnDestroy} from '@angular/core'; -import {BehaviorSubject, combineLatest, Observable, Subject} from 'rxjs'; -import {map, takeUntil, catchError} from 'rxjs/operators'; -import {ChartConfiguration, ChartData} from 'chart.js'; - -import {LibraryFilterService} from './library-filter.service'; -import {BookService} from '../../book/service/book.service'; -import {Book} from '../../book/model/book.model'; - -interface SeriesStats { - category: string; - count: number; - percentage: number; - description: string; -} - -const CHART_COLORS = [ - '#ff6b6b', '#4ecdc4', '#45b7d1', '#96ceb4', '#ffeaa7', - '#dda0dd', '#98d8c8', '#ff7675', '#74b9ff', '#fdcb6e' -] as const; - -const CHART_DEFAULTS = { - borderColor: '#ffffff', - borderWidth: 2, - hoverBorderWidth: 3, - hoverBorderColor: '#ffffff' -} as const; - -type SeriesChartData = ChartData<'polarArea', number[], string>; - -@Injectable({ - providedIn: 'root' -}) -export class SeriesStandaloneChartService implements OnDestroy { - private readonly bookService = inject(BookService); - private readonly libraryFilterService = inject(LibraryFilterService); - private readonly destroy$ = new Subject(); - - public readonly seriesChartType = 'polarArea' as const; - - public readonly seriesChartOptions: ChartConfiguration<'polarArea'>['options'] = { - responsive: true, - maintainAspectRatio: false, - scales: { - r: { - beginAtZero: true, - ticks: { - color: '#ffffff', - font: {size: 10}, - stepSize: 1 - }, - grid: { - color: 'rgba(255, 255, 255, 0.2)' - }, - angleLines: { - color: 'rgba(255, 255, 255, 0.2)' - }, - pointLabels: { - color: '#ffffff', - font: {size: 11} - } - } - }, - plugins: { - legend: { - display: true, - position: 'bottom', - labels: { - color: '#ffffff', - font: {size: 11}, - padding: 12, - usePointStyle: true, - generateLabels: this.generateLegendLabels.bind(this) - } - }, - tooltip: { - enabled: true, - backgroundColor: 'rgba(0, 0, 0, 0.9)', - titleColor: '#ffffff', - bodyColor: '#ffffff', - borderColor: '#ffffff', - borderWidth: 1, - cornerRadius: 6, - displayColors: true, - padding: 12, - titleFont: {size: 14, weight: 'bold'}, - bodyFont: {size: 13}, - position: 'nearest', - callbacks: { - title: (context) => context[0]?.label || '', - label: this.formatTooltipLabel - } - } - }, - interaction: { - intersect: false, - mode: 'point' - } - }; - - private readonly seriesChartDataSubject = new BehaviorSubject({ - labels: [], - datasets: [{ - data: [], - backgroundColor: [...CHART_COLORS], - ...CHART_DEFAULTS - }] - }); - - public readonly seriesChartData$: Observable = this.seriesChartDataSubject.asObservable(); - - constructor() { - this.initializeChartDataSubscription(); - } - - ngOnDestroy(): void { - this.destroy$.next(); - this.destroy$.complete(); - } - - private initializeChartDataSubscription(): void { - this.getSeriesStats() - .pipe( - takeUntil(this.destroy$), - catchError((error) => { - console.error('Error processing series stats:', error); - return []; - }) - ) - .subscribe((stats) => this.updateChartData(stats)); - } - - private updateChartData(stats: SeriesStats[]): void { - try { - const labels = stats.map(s => s.category); - const dataValues = stats.map(s => s.count); - const colors = this.getColorsForData(stats.length); - - this.seriesChartDataSubject.next({ - labels, - datasets: [{ - data: dataValues, - backgroundColor: colors, - ...CHART_DEFAULTS - }] - }); - } catch (error) { - console.error('Error updating series chart data:', error); - } - } - - private getColorsForData(dataLength: number): string[] { - const colors = [...CHART_COLORS]; - while (colors.length < dataLength) { - colors.push(...CHART_COLORS); - } - return colors.slice(0, dataLength); - } - - public getSeriesStats(): Observable { - return combineLatest([ - this.bookService.bookState$, - this.libraryFilterService.selectedLibrary$ - ]).pipe( - map(([state, selectedLibraryId]) => { - if (!this.isValidBookState(state)) { - return []; - } - - const filteredBooks = this.filterBooksByLibrary(state.books!, String(selectedLibraryId)); - return this.processSeriesStats(filteredBooks); - }), - catchError((error) => { - console.error('Error getting series stats:', error); - return []; - }) - ); - } - - private isValidBookState(state: any): boolean { - return state?.loaded && state?.books && Array.isArray(state.books) && state.books.length > 0; - } - - private filterBooksByLibrary(books: Book[], selectedLibraryId: string | null): Book[] { - return selectedLibraryId && selectedLibraryId !== 'null' - ? books.filter(book => String(book.libraryId) === selectedLibraryId) - : books; - } - - private processSeriesStats(books: Book[]): SeriesStats[] { - if (books.length === 0) { - return []; - } - - const stats = this.categorizeBooks(books); - return this.convertToStats(stats, books.length); - } - - private categorizeBooks(books: Book[]): Map { - const categories = new Map(); - - // Initialize categories - categories.set('Standalone Books', { count: 0, description: 'Books not part of any series' }); - categories.set('Series Books', { count: 0, description: 'Books that are part of a series' }); - categories.set('Complete Series', { count: 0, description: 'Books in complete series' }); - categories.set('Incomplete Series', { count: 0, description: 'Books in incomplete series' }); - categories.set('Unknown Series Status', { count: 0, description: 'Books with unclear series information' }); - - // Group books by series - const seriesMap = new Map(); - const standaloneBooks: Book[] = []; - - for (const book of books) { - const seriesName = book.metadata?.seriesName; - if (seriesName && seriesName.trim()) { - if (!seriesMap.has(seriesName)) { - seriesMap.set(seriesName, []); - } - seriesMap.get(seriesName)!.push(book); - } else { - standaloneBooks.push(book); - } - } - - // Count standalone books - categories.get('Standalone Books')!.count = standaloneBooks.length; - - // Process series books - let seriesBooks = 0; - let completeSeriesBooks = 0; - let incompleteSeriesBooks = 0; - let unknownSeriesBooks = 0; - - for (const [seriesName, seriesBookList] of seriesMap) { - seriesBooks += seriesBookList.length; - - // Check if series is complete - const seriesTotal = seriesBookList[0]?.metadata?.seriesTotal; - const hasSeriesNumbers = seriesBookList.every(book => book.metadata?.seriesNumber); - - if (seriesTotal && hasSeriesNumbers) { - const uniqueNumbers = new Set(seriesBookList.map(book => book.metadata?.seriesNumber)); - if (uniqueNumbers.size === seriesTotal) { - completeSeriesBooks += seriesBookList.length; - } else { - incompleteSeriesBooks += seriesBookList.length; - } - } else { - unknownSeriesBooks += seriesBookList.length; - } - } - - categories.get('Series Books')!.count = seriesBooks; - categories.get('Complete Series')!.count = completeSeriesBooks; - categories.get('Incomplete Series')!.count = incompleteSeriesBooks; - categories.get('Unknown Series Status')!.count = unknownSeriesBooks; - - return categories; - } - - private convertToStats(categoriesMap: Map, totalBooks: number): SeriesStats[] { - return Array.from(categoriesMap.entries()) - .filter(([_, data]) => data.count > 0) // Only include categories with books - .map(([category, data]) => ({ - category, - count: data.count, - percentage: Number(((data.count / totalBooks) * 100).toFixed(1)), - description: data.description - })) - .sort((a, b) => b.count - a.count); - } - - private generateLegendLabels(chart: any) { - const data = chart.data; - if (!data.labels?.length || !data.datasets?.[0]?.data?.length) { - return []; - } - - const dataset = data.datasets[0]; - const dataValues = dataset.data as number[]; - - return data.labels.map((label: string, index: number) => { - const isVisible = typeof chart.getDataVisibility === 'function' - ? chart.getDataVisibility(index) - : !((chart.getDatasetMeta && chart.getDatasetMeta(0)?.data?.[index]?.hidden) || false); - - return { - text: `${label} (${dataValues[index]})`, - fillStyle: (dataset.backgroundColor as string[])[index], - strokeStyle: '#ffffff', - lineWidth: 1, - hidden: !isVisible, - index, - fontColor: '#ffffff' - }; - }); - } - - private formatTooltipLabel(context: any): string { - const dataIndex = context.dataIndex; - const dataset = context.dataset; - const value = dataset.data[dataIndex] as number; - const label = context.chart.data.labels?.[dataIndex] || 'Unknown'; - const total = (dataset.data as number[]).reduce((a: number, b: number) => a + b, 0); - const percentage = ((value / total) * 100).toFixed(1); - return `${label}: ${value} books (${percentage}%)`; - } -} - diff --git a/booklore-ui/src/app/features/stats/service/user-chart-config.service.ts b/booklore-ui/src/app/features/stats/service/user-chart-config.service.ts new file mode 100644 index 000000000..973a91e5f --- /dev/null +++ b/booklore-ui/src/app/features/stats/service/user-chart-config.service.ts @@ -0,0 +1,166 @@ +import {Injectable} from '@angular/core'; +import {BehaviorSubject, Observable} from 'rxjs'; +import {ReadingSessionHeatmapComponent} from '../component/reading-session-heatmap/reading-session-heatmap.component'; +import {ReadingSessionTimelineComponent} from '../component/reading-session-timeline/reading-session-timeline.component'; +import {GenreStatsChartComponent} from '../component/genre-stats-chart/genre-stats-chart.component'; +import {CompletionTimelineChartComponent} from '../component/completion-timeline-chart/completion-timeline-chart.component'; +import {FavoriteDaysChartComponent} from '../component/favorite-days-chart/favorite-days-chart.component'; +import {PeakHoursChartComponent} from '../component/peak-hours-chart/peak-hours-chart.component'; +import {ReadingDNAChartComponent} from '../component/reading-dna-chart/reading-dna-chart.component'; +import {ReadingHabitsChartComponent} from '../component/reading-habits-chart/reading-habits-chart.component'; + +export interface UserChartConfig { + id: string; + title: string; + component: any; + enabled: boolean; + sizeClass: string; + order: number; +} + +@Injectable({ + providedIn: 'root' +}) +export class UserChartConfigService { + private readonly STORAGE_KEY = 'userStatsChartConfig'; + private readonly defaultCharts: UserChartConfig[] = [ + { + id: 'heatmap', + title: 'Reading Session Heatmap', + component: ReadingSessionHeatmapComponent, + enabled: true, + sizeClass: 'chart-full', + order: 0 + }, + { + id: 'favorite-days', + title: 'Favorite Reading Days', + component: FavoriteDaysChartComponent, + enabled: true, + sizeClass: 'chart-medium', + order: 1 + }, + { + id: 'peak-hours', + title: 'Peak Reading Hours', + component: PeakHoursChartComponent, + enabled: true, + sizeClass: 'chart-medium', + order: 2 + }, + { + id: 'genre-stats', + title: 'Genre Statistics', + component: GenreStatsChartComponent, + enabled: true, + sizeClass: 'chart-medium', + order: 3 + }, + { + id: 'completion-timeline', + title: 'Completion Timeline', + component: CompletionTimelineChartComponent, + enabled: true, + sizeClass: 'chart-medium', + order: 4 + }, + { + id: 'reading-dna', + title: 'Reading DNA Profile', + component: ReadingDNAChartComponent, + enabled: true, + sizeClass: 'chart-medium', + order: 5 + }, + { + id: 'reading-habits', + title: 'Reading Habits Analysis', + component: ReadingHabitsChartComponent, + enabled: true, + sizeClass: 'chart-medium', + order: 6 + }, + { + id: 'timeline', + title: 'Reading Session Timeline', + component: ReadingSessionTimelineComponent, + enabled: true, + sizeClass: 'chart-full', + order: 7 + }, + ]; + + private chartsSubject = new BehaviorSubject(this.loadChartConfig()); + public charts$: Observable = this.chartsSubject.asObservable(); + + getVisibleCharts(): UserChartConfig[] { + return this.chartsSubject.value.filter(chart => chart.enabled); + } + + toggleChart(chartId: string): void { + const charts = this.chartsSubject.value; + const chart = charts.find(c => c.id === chartId); + if (chart) { + chart.enabled = !chart.enabled; + this.saveChartConfig(charts); + this.chartsSubject.next([...charts]); + } + } + + reorderCharts(previousIndex: number, currentIndex: number): void { + const charts = [...this.chartsSubject.value]; + const [movedChart] = charts.splice(previousIndex, 1); + charts.splice(currentIndex, 0, movedChart); + + charts.forEach((chart, index) => { + chart.order = index; + }); + + this.saveChartConfig(charts); + this.chartsSubject.next(charts); + } + + resetLayout(): void { + const resetCharts = JSON.parse(JSON.stringify(this.defaultCharts)); + this.saveChartConfig(resetCharts); + this.chartsSubject.next(resetCharts); + } + + private saveChartConfig(charts: UserChartConfig[]): void { + const config = charts.map(chart => ({ + id: chart.id, + enabled: chart.enabled, + sizeClass: chart.sizeClass, + order: chart.order + })); + localStorage.setItem(this.STORAGE_KEY, JSON.stringify(config)); + } + + private loadChartConfig(): UserChartConfig[] { + const savedConfig = localStorage.getItem(this.STORAGE_KEY); + if (!savedConfig) { + return JSON.parse(JSON.stringify(this.defaultCharts)); + } + + try { + const config = JSON.parse(savedConfig); + const charts = JSON.parse(JSON.stringify(this.defaultCharts)); + + config.forEach((saved: any) => { + const chart = charts.find((c: UserChartConfig) => c.id === saved.id); + if (chart) { + chart.enabled = saved.enabled; + chart.sizeClass = saved.sizeClass; + chart.order = saved.order ?? chart.order; + } + }); + + charts.sort((a: UserChartConfig, b: UserChartConfig) => a.order - b.order); + + return charts; + } catch (e) { + console.error('Failed to load chart config', e); + return JSON.parse(JSON.stringify(this.defaultCharts)); + } + } +} From 4712f53b8ea6ca2d69fa420df8bfded3c1dacc0b Mon Sep 17 00:00:00 2001 From: ACX <8075870+acx10@users.noreply.github.com> Date: Fri, 26 Dec 2025 16:44:44 -0700 Subject: [PATCH 13/25] Display paginated reading sessions in the book metadata view (#2003) Co-authored-by: acx10 --- .../controller/ReadingSessionController.java | 102 ++-------------- .../controller/UserStatsController.java | 114 ++++++++++++++++++ .../dto/response/ReadingSessionResponse.java | 31 +++++ .../repository/ReadingSessionRepository.java | 14 +++ .../service/ReadingSessionService.java | 31 +++++ .../book-reading-sessions.component.html | 65 ++++++++++ .../book-reading-sessions.component.scss | 51 ++++++++ .../book-reading-sessions.component.ts | 85 +++++++++++++ .../metadata-viewer.component.html | 8 +- .../metadata-viewer.component.ts | 3 +- .../user-management/user-stats.service.ts | 17 +-- .../service/reading-session-api.service.ts | 97 +++++++++++++++ .../shared/service/reading-session.service.ts | 32 ++--- 13 files changed, 533 insertions(+), 117 deletions(-) create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/controller/UserStatsController.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/ReadingSessionResponse.java create mode 100644 booklore-ui/src/app/features/metadata/component/book-metadata-center/book-reading-sessions/book-reading-sessions.component.html create mode 100644 booklore-ui/src/app/features/metadata/component/book-metadata-center/book-reading-sessions/book-reading-sessions.component.scss create mode 100644 booklore-ui/src/app/features/metadata/component/book-metadata-center/book-reading-sessions/book-reading-sessions.component.ts create mode 100644 booklore-ui/src/app/shared/service/reading-session-api.service.ts diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/controller/ReadingSessionController.java b/booklore-api/src/main/java/com/adityachandel/booklore/controller/ReadingSessionController.java index 1c7ba343e..6c17b2bee 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/controller/ReadingSessionController.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/controller/ReadingSessionController.java @@ -1,19 +1,17 @@ package com.adityachandel.booklore.controller; import com.adityachandel.booklore.model.dto.request.ReadingSessionRequest; -import com.adityachandel.booklore.model.dto.response.*; +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.data.domain.Page; 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/reading-sessions") @@ -32,95 +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> getHeatmapForYear(@PathVariable int year) { - List 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/week/{year}/{month}/{week}") - @PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()") - public ResponseEntity> getTimelineForWeek( - @PathVariable int year, - @PathVariable int month, - @PathVariable int week) { - List 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("/stats/speed/year/{year}") - @PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()") - public ResponseEntity> getReadingSpeedForYear(@PathVariable int year) { - List 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("/stats/peak-hours") - @PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()") - public ResponseEntity> getPeakReadingHours( - @RequestParam(required = false) Integer year, - @RequestParam(required = false) Integer month) { - List 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("/stats/favorite-days") - @PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()") - public ResponseEntity> getFavoriteReadingDays( - @RequestParam(required = false) Integer year, - @RequestParam(required = false) Integer month) { - List 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("/stats/genres") - @PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()") - public ResponseEntity> getGenreStatistics() { - List 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("/stats/completion-timeline/year/{year}") - @PreAuthorize("@securityUtil.canAccessUserStats() or @securityUtil.isAdmin()") - public ResponseEntity> getCompletionTimeline(@PathVariable int year) { - List timeline = readingSessionService.getCompletionTimeline(year); - return ResponseEntity.ok(timeline); + @GetMapping("/book/{bookId}") + public ResponseEntity> getReadingSessionsForBook(@PathVariable Long bookId, @RequestParam(defaultValue = "0") int page) { + Page sessions = readingSessionService.getReadingSessionsForBook(bookId, page); + return ResponseEntity.ok(sessions); } } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/controller/UserStatsController.java b/booklore-api/src/main/java/com/adityachandel/booklore/controller/UserStatsController.java new file mode 100644 index 000000000..ad51e202f --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/controller/UserStatsController.java @@ -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> getHeatmapForYear(@RequestParam int year) { + List 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> getTimelineForWeek( + @RequestParam int year, + @RequestParam int month, + @RequestParam int week) { + List 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> getReadingSpeedForYear(@RequestParam int year) { + List 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> getPeakReadingHours( + @RequestParam(required = false) Integer year, + @RequestParam(required = false) Integer month) { + List 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> getFavoriteReadingDays( + @RequestParam(required = false) Integer year, + @RequestParam(required = false) Integer month) { + List 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> getGenreStatistics() { + List 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> getCompletionTimeline(@RequestParam int year) { + List timeline = readingSessionService.getCompletionTimeline(year); + return ResponseEntity.ok(timeline); + } +} + diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/ReadingSessionResponse.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/ReadingSessionResponse.java new file mode 100644 index 000000000..29dcb40ef --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/ReadingSessionResponse.java @@ -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; +} + diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/repository/ReadingSessionRepository.java b/booklore-api/src/main/java/com/adityachandel/booklore/repository/ReadingSessionRepository.java index 3bfbc41c1..1094df900 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/repository/ReadingSessionRepository.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/repository/ReadingSessionRepository.java @@ -2,6 +2,8 @@ package com.adityachandel.booklore.repository; import com.adityachandel.booklore.model.dto.*; import com.adityachandel.booklore.model.entity.ReadingSessionEntity; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; @@ -109,4 +111,16 @@ public interface ReadingSessionRepository extends JpaRepository 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 findByUserIdAndBookId( + @Param("userId") Long userId, + @Param("bookId") Long bookId, + Pageable pageable); } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/ReadingSessionService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/ReadingSessionService.java index b423117b5..fef5299b9 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/ReadingSessionService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/ReadingSessionService.java @@ -9,6 +9,7 @@ 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; @@ -21,6 +22,9 @@ 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; @@ -210,4 +214,31 @@ public class ReadingSessionService { }) .collect(Collectors.toList()); } + + @Transactional(readOnly = true) + public Page 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 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()); + } } diff --git a/booklore-ui/src/app/features/metadata/component/book-metadata-center/book-reading-sessions/book-reading-sessions.component.html b/booklore-ui/src/app/features/metadata/component/book-metadata-center/book-reading-sessions/book-reading-sessions.component.html new file mode 100644 index 000000000..cc1fac852 --- /dev/null +++ b/booklore-ui/src/app/features/metadata/component/book-metadata-center/book-reading-sessions/book-reading-sessions.component.html @@ -0,0 +1,65 @@ +
+ @if (loading && sessions.length === 0) { +
+ +

Loading reading sessions...

+
+ } @else if (sessions.length === 0) { +
+ +

No reading sessions recorded yet

+
+ } @else { + + + + Start Time + End Time + Duration + Progress + Progress Delta + Location + + + + + {{ formatDate(session.startTime) }} + {{ formatDate(session.endTime) }} + {{ formatDuration(session.durationSeconds) }} + + @if (session.startProgress !== null && session.startProgress !== undefined && session.endProgress !== null && session.endProgress !== undefined) { + {{ session.startProgress }}% โ†’ {{ session.endProgress }}% + } @else { + - + } + + + @if (session.progressDelta !== null && session.progressDelta !== undefined) { + + } @else { + N/A + } + + + @if (session.startLocation && session.endLocation && isPageNumber(session.startLocation)) { + Page {{ session.startLocation }} โ†’ Page {{ session.endLocation }} + } @else { + - + } + + + + + } +
diff --git a/booklore-ui/src/app/features/metadata/component/book-metadata-center/book-reading-sessions/book-reading-sessions.component.scss b/booklore-ui/src/app/features/metadata/component/book-metadata-center/book-reading-sessions/book-reading-sessions.component.scss new file mode 100644 index 000000000..41289dce5 --- /dev/null +++ b/booklore-ui/src/app/features/metadata/component/book-metadata-center/book-reading-sessions/book-reading-sessions.component.scss @@ -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; + } + } +} diff --git a/booklore-ui/src/app/features/metadata/component/book-metadata-center/book-reading-sessions/book-reading-sessions.component.ts b/booklore-ui/src/app/features/metadata/component/book-metadata-center/book-reading-sessions/book-reading-sessions.component.ts new file mode 100644 index 000000000..c3c798d51 --- /dev/null +++ b/booklore-ui/src/app/features/metadata/component/book-metadata-center/book-reading-sessions/book-reading-sessions.component.ts @@ -0,0 +1,85 @@ +import {Component, inject, Input, OnInit, OnChanges, SimpleChanges} from '@angular/core'; +import {CommonModule} from '@angular/common'; +import {ReadingSessionApiService, ReadingSessionResponse} from '../../../../../shared/service/reading-session-api.service'; +import {TableModule} from 'primeng/table'; +import {ProgressSpinnerModule} from 'primeng/progressspinner'; +import {TagModule} from 'primeng/tag'; + +@Component({ + selector: 'app-book-reading-sessions', + standalone: true, + imports: [CommonModule, TableModule, ProgressSpinnerModule, TagModule], + templateUrl: './book-reading-sessions.component.html', + styleUrls: ['./book-reading-sessions.component.scss'] +}) +export class BookReadingSessionsComponent implements OnInit, OnChanges { + @Input() bookId!: number; + + private readonly readingSessionService = inject(ReadingSessionApiService); + + sessions: ReadingSessionResponse[] = []; + totalRecords = 0; + first = 0; + rows = 5; + loading = false; + + ngOnInit() { + this.loadSessions(); + } + + ngOnChanges(changes: SimpleChanges) { + if (changes['bookId'] && !changes['bookId'].firstChange) { + this.first = 0; + this.loadSessions(); + } + } + + loadSessions(page: number = 0) { + this.loading = true; + this.readingSessionService.getSessionsByBookId(this.bookId, page, this.rows) + .subscribe({ + next: (response) => { + this.sessions = response.content; + this.totalRecords = response.totalElements; + this.loading = false; + }, + error: () => { + this.loading = false; + } + }); + } + + onPageChange(event: any) { + this.first = event.first; + const page = Math.floor(event.first / event.rows); + this.loadSessions(page); + } + + formatDuration(seconds: number): string { + const hours = Math.floor(seconds / 3600); + const minutes = Math.floor((seconds % 3600) / 60); + const secs = seconds % 60; + + if (hours > 0) { + return `${hours}h ${minutes}m`; + } else if (minutes > 0) { + return `${minutes}m ${secs}s`; + } + return `${secs}s`; + } + + formatDate(dateString: string): string { + return new Date(dateString).toLocaleString(); + } + + getProgressColor(delta: number): 'success' | 'secondary' | 'danger' { + if (delta > 0) return 'success'; + if (delta < 0) return 'danger'; + return 'secondary'; + } + + isPageNumber(location: string | undefined): boolean { + if (!location) return false; + return !isNaN(Number(location)) && location.trim() !== ''; + } +} diff --git a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.html b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.html index efa1c6351..fc921e4fe 100644 --- a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.html +++ b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.html @@ -19,7 +19,7 @@
} -
@let progress = getProgressPercent(book); @@ -605,6 +605,9 @@ Notes + Reading Sessions + + Reviews @@ -641,6 +644,9 @@ + + + diff --git a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.ts b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.ts index 8a379004f..845b6bb47 100644 --- a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.ts +++ b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.ts @@ -41,13 +41,14 @@ import { import {BookNavigationService} from '../../../../book/service/book-navigation.service'; import {Divider} from 'primeng/divider'; import {BookMetadataHostService} from '../../../../../shared/service/book-metadata-host-service'; +import { BookReadingSessionsComponent } from '../book-reading-sessions/book-reading-sessions.component'; @Component({ selector: 'app-metadata-viewer', standalone: true, templateUrl: './metadata-viewer.component.html', styleUrl: './metadata-viewer.component.scss', - imports: [Button, AsyncPipe, Rating, FormsModule, SplitButton, NgClass, Tooltip, DecimalPipe, Editor, ProgressBar, Menu, InfiniteScrollDirective, BookCardLiteComponent, DatePicker, Tab, TabList, TabPanel, TabPanels, Tabs, BookReviewsComponent, BookNotesComponent, ProgressSpinner, TieredMenu, Image, TagComponent, UpperCasePipe, Divider] + imports: [Button, AsyncPipe, Rating, FormsModule, SplitButton, NgClass, Tooltip, DecimalPipe, Editor, ProgressBar, Menu, InfiniteScrollDirective, BookCardLiteComponent, DatePicker, Tab, TabList, TabPanel, TabPanels, Tabs, BookReviewsComponent, BookNotesComponent, ProgressSpinner, TieredMenu, Image, TagComponent, UpperCasePipe, Divider, BookReadingSessionsComponent] }) export class MetadataViewerComponent implements OnInit, OnChanges { @Input() book$!: Observable; diff --git a/booklore-ui/src/app/features/settings/user-management/user-stats.service.ts b/booklore-ui/src/app/features/settings/user-management/user-stats.service.ts index daf2113dc..e7abf734f 100644 --- a/booklore-ui/src/app/features/settings/user-management/user-stats.service.ts +++ b/booklore-ui/src/app/features/settings/user-management/user-stats.service.ts @@ -53,30 +53,33 @@ export interface PeakHoursResponse { providedIn: 'root' }) export class UserStatsService { - private readonly readingSessionsUrl = `${API_CONFIG.BASE_URL}/api/v1/reading-sessions`; + private readonly readingSessionsUrl = `${API_CONFIG.BASE_URL}/api/v1/user-stats`; private http = inject(HttpClient); getHeatmapForYear(year: number): Observable { return this.http.get( - `${this.readingSessionsUrl}/heatmap/year/${year}` + `${this.readingSessionsUrl}/heatmap`, + { params: { year: year.toString() } } ); } getTimelineForWeek(year: number, month: number, week: number): Observable { return this.http.get( - `${this.readingSessionsUrl}/timeline/week/${year}/${month}/${week}` + `${this.readingSessionsUrl}/timeline`, + { params: { year: year.toString(), month: month.toString(), week: week.toString() } } ); } getGenreStats(): Observable { return this.http.get( - `${this.readingSessionsUrl}/stats/genres` + `${this.readingSessionsUrl}/genres` ); } getCompletionTimelineForYear(year: number): Observable { return this.http.get( - `${this.readingSessionsUrl}/stats/completion-timeline/year/${year}` + `${this.readingSessionsUrl}/completion-timeline`, + { params: { year: year.toString() } } ); } @@ -90,7 +93,7 @@ export class UserStatsService { } return this.http.get( - `${this.readingSessionsUrl}/stats/favorite-days`, + `${this.readingSessionsUrl}/favorite-days`, {params} ); } @@ -105,7 +108,7 @@ export class UserStatsService { } return this.http.get( - `${this.readingSessionsUrl}/stats/peak-hours`, + `${this.readingSessionsUrl}/peak-hours`, {params} ); } diff --git a/booklore-ui/src/app/shared/service/reading-session-api.service.ts b/booklore-ui/src/app/shared/service/reading-session-api.service.ts new file mode 100644 index 000000000..48e6add6f --- /dev/null +++ b/booklore-ui/src/app/shared/service/reading-session-api.service.ts @@ -0,0 +1,97 @@ +import {inject, Injectable} from '@angular/core'; +import {HttpClient, HttpParams} from '@angular/common/http'; +import {Observable} from 'rxjs'; +import {API_CONFIG} from '../../core/config/api-config'; +import {BookType} from '../../features/book/model/book.model'; + +export interface ReadingSessionResponse { + id: number; + bookId: number; + bookTitle: string; + bookType: BookType; + startTime: string; + endTime: string; + durationSeconds: number; + startProgress: number; + endProgress: number; + progressDelta: number; + startLocation?: string; + endLocation?: string; + createdAt: string; +} + +export interface PageableResponse { + content: T[]; + pageable: { + pageNumber: number; + pageSize: number; + sort: { + empty: boolean; + sorted: boolean; + unsorted: boolean; + }; + offset: number; + paged: boolean; + unpaged: boolean; + }; + totalElements: number; + last: boolean; + totalPages: number; + numberOfElements: number; + first: boolean; + size: number; + number: number; + sort: { + empty: boolean; + sorted: boolean; + unsorted: boolean; + }; + empty: boolean; +} + +export interface CreateReadingSessionDto { + bookId: number; + bookType: BookType; + startTime: string; + endTime: string; + durationSeconds: number; + durationFormatted: string; + startProgress?: number; + endProgress?: number; + progressDelta?: number; + startLocation?: string; + endLocation?: string; +} + +@Injectable({ + providedIn: 'root' +}) +export class ReadingSessionApiService { + private readonly http = inject(HttpClient); + private readonly url = `${API_CONFIG.BASE_URL}/api/v1/reading-sessions`; + + createSession(sessionData: CreateReadingSessionDto): Observable { + return this.http.post(this.url, sessionData); + } + + getSessionsByBookId(bookId: number, page: number = 0, size: number = 5): Observable> { + const params = new HttpParams() + .set('page', page.toString()) + .set('size', size.toString()); + + return this.http.get>( + `${this.url}/book/${bookId}`, + {params} + ); + } + + sendSessionBeacon(sessionData: CreateReadingSessionDto): boolean { + try { + const blob = new Blob([JSON.stringify(sessionData)], {type: 'application/json'}); + return navigator.sendBeacon(this.url, blob); + } catch { + return false; + } + } +} + diff --git a/booklore-ui/src/app/shared/service/reading-session.service.ts b/booklore-ui/src/app/shared/service/reading-session.service.ts index 4a21f1b25..1119a1445 100644 --- a/booklore-ui/src/app/shared/service/reading-session.service.ts +++ b/booklore-ui/src/app/shared/service/reading-session.service.ts @@ -1,9 +1,12 @@ import { inject, Injectable } from '@angular/core'; -import { HttpClient, HttpErrorResponse } from '@angular/common/http'; +import { HttpErrorResponse } from '@angular/common/http'; import { fromEvent, merge, Subscription } from 'rxjs'; import { debounceTime } from 'rxjs/operators'; -import { API_CONFIG } from '../../core/config/api-config'; -import {BookType} from '../../features/book/model/book.model'; +import { BookType } from '../../features/book/model/book.model'; +import { + ReadingSessionApiService, + CreateReadingSessionDto +} from './reading-session-api.service'; export interface ReadingSession { bookId: number; @@ -22,8 +25,7 @@ export interface ReadingSession { providedIn: 'root' }) export class ReadingSessionService { - private readonly http = inject(HttpClient); - private readonly url = `${API_CONFIG.BASE_URL}/api/v1/reading-sessions`; + private readonly apiService = inject(ReadingSessionApiService); private currentSession: ReadingSession | null = null; private idleTimer: ReturnType | null = null; @@ -139,15 +141,9 @@ export class ReadingSessionService { this.log('Reading session ended (sync)', sessionData); - try { - const blob = new Blob([JSON.stringify(sessionData)], { type: 'application/json' }); - const success = navigator.sendBeacon(this.url, blob); - - if (!success) { - this.logError('sendBeacon failed, request may not have been queued'); - } - } catch (error) { - this.logError('Failed to send session data', error); + const success = this.apiService.sendSessionBeacon(sessionData); + if (!success) { + this.logError('sendBeacon failed, request may not have been queued'); } this.cleanup(); @@ -167,13 +163,17 @@ export class ReadingSessionService { this.log('Reading session completed', sessionData); - this.http.post(this.url, sessionData).subscribe({ + this.apiService.createSession(sessionData).subscribe({ next: () => this.log('Session saved to backend'), error: (err: HttpErrorResponse) => this.logError('Failed to save session', err) }); } - private buildSessionData(session: ReadingSession, endTime: Date, durationSeconds: number) { + private buildSessionData( + session: ReadingSession, + endTime: Date, + durationSeconds: number + ): CreateReadingSessionDto { return { bookId: session.bookId, bookType: session.bookType, From 87fe405455a234de185659e3c7a7817c3e4b290a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bal=C3=A1zs=20Sz=C3=BCcs?= <127139797+balazs-szucs@users.noreply.github.com> Date: Sat, 27 Dec 2025 00:45:55 +0100 Subject: [PATCH 14/25] test(util): expand and improve utility test coverage for BookUtils, FileUtils, PathPatternResolver, MetadataChangeDetector, and UserPermissionUtils (#1985) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Balรกzs Szรผcs --- .../booklore/util/BookUtils.java | 13 +- .../booklore/util/BookUtilsTest.java | 141 +++++++++- .../booklore/util/FileServiceTest.java | 261 +++++++++++++++--- .../booklore/util/FileUtilsTest.java | 58 ++++ .../util/MetadataChangeDetectorTest.java | 144 ++++++++++ .../util/PathPatternResolverTest.java | 259 +++++++++++++++-- .../util/UserPermissionUtilsTest.java | 62 +++++ 7 files changed, 871 insertions(+), 67 deletions(-) diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/util/BookUtils.java b/booklore-api/src/main/java/com/adityachandel/booklore/util/BookUtils.java index 3219bb6c8..9476356b9 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/util/BookUtils.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/util/BookUtils.java @@ -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; } diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/util/BookUtilsTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/util/BookUtilsTest.java index 085167b19..601542711 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/util/BookUtilsTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/util/BookUtilsTest.java @@ -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}itsixty?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")); + } } diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/util/FileServiceTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/util/FileServiceTest.java index c370c1319..adf9c4bfd 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/util/FileServiceTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/util/FileServiceTest.java @@ -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"))); } } diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/util/FileUtilsTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/util/FileUtilsTest.java index b4ca57e8a..5e850b0ca 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/util/FileUtilsTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/util/FileUtilsTest.java @@ -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"); + } } \ No newline at end of file diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/util/MetadataChangeDetectorTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/util/MetadataChangeDetectorTest.java index d699aba92..71ce6c8da 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/util/MetadataChangeDetectorTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/util/MetadataChangeDetectorTest.java @@ -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"); + } } diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/util/PathPatternResolverTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/util/PathPatternResolverTest.java index c4aa64f1e..ae4879157 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/util/PathPatternResolverTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/util/PathPatternResolverTest.java @@ -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 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"); + } } \ No newline at end of file diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/util/UserPermissionUtilsTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/util/UserPermissionUtilsTest.java index 3ca591f8d..ec8a9b66a 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/util/UserPermissionUtilsTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/util/UserPermissionUtilsTest.java @@ -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; + } } From 4d8092e5bcf762d18ce557d6301a23791918be13 Mon Sep 17 00:00:00 2001 From: MightyHalfGinger Date: Fri, 26 Dec 2025 15:47:24 -0800 Subject: [PATCH 15/25] Fix(metadata): Improve handling of non-author creator roles (#1987) * Fix(metadata): Don't import creators with a non-author role as author Looks at either the meta tag for the creators or the opf role attribute to determine the role of a creator. If no role is specified its assumed to be an author. Also only prunes handled created roles when writing the epub data back out to prevent clobbering any extra data that might be present in the epub already. * Fix(metadata): Add testcases for non-author creator handling Just adds testcases for the previous changes to the extraction and writer logic. --- .../extractor/EpubMetadataExtractor.java | 36 ++++++++-- .../metadata/writer/EpubMetadataWriter.java | 49 ++++++++++++-- .../extractor/EpubMetadataExtractorTest.java | 32 +++++++++ .../writer/EpubMetadataWriterTest.java | 66 +++++++++++++++++++ 4 files changed, 175 insertions(+), 8 deletions(-) diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/extractor/EpubMetadataExtractor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/extractor/EpubMetadataExtractor.java index 72f40fdf4..1c51ff3d2 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/extractor/EpubMetadataExtractor.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/extractor/EpubMetadataExtractor.java @@ -36,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) { @@ -100,7 +101,6 @@ public class EpubMetadataExtractor implements FileMetadataExtractor { if (metadata == null) return null; BookMetadata.BookMetadataBuilder builderMeta = BookMetadata.builder(); - Set authors = new HashSet<>(); Set categories = new HashSet<>(); boolean seriesFound = false; @@ -108,6 +108,11 @@ public class EpubMetadataExtractor implements FileMetadataExtractor { NodeList children = metadata.getChildNodes(); + Map creatorsById = new HashMap<>(); + Map creatorRoleById = new HashMap<>(); + Map> creatorsByRole = new HashMap<>(); + creatorsByRole.put("aut", new HashSet<>()); + Map titlesById = new HashMap<>(); Map titleTypeById = new HashMap<>(); @@ -136,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; @@ -176,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()) { @@ -235,7 +256,14 @@ public class EpubMetadataExtractor implements FileMetadataExtractor { } } - builderMeta.authors(authors); + for (Map.Entry 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(); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/writer/EpubMetadataWriter.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/writer/EpubMetadataWriter.java index 30d439931..68b6feb2e 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/writer/EpubMetadataWriter.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/writer/EpubMetadataWriter.java @@ -86,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); @@ -491,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); @@ -523,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"); @@ -543,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 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 diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/extractor/EpubMetadataExtractorTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/extractor/EpubMetadataExtractorTest.java index 255de003a..8bb77f8d9 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/extractor/EpubMetadataExtractorTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/extractor/EpubMetadataExtractorTest.java @@ -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(""" + + + + %s + %s + %s + %s + %s + edt + + + """, 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(""" diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/writer/EpubMetadataWriterTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/writer/EpubMetadataWriterTest.java index 9a04018e2..df9b71493 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/writer/EpubMetadataWriterTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/writer/EpubMetadataWriterTest.java @@ -15,11 +15,14 @@ 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; @@ -51,6 +54,40 @@ class EpubMetadataWriterTest { 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(""); + existingMetadata.append("Alice"); + existingMetadata.append("ill"); + existingMetadata.append(""); + String opfContent = String.format(""" + + + %s + + """, 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 { @@ -89,6 +126,35 @@ class EpubMetadataWriterTest { } } + private File createEpubWithOpf(String opfContent, String filename) throws IOException { + File epubFile = tempDir.resolve(filename).toFile(); + + String containerXml = """ + + + + + + + """; + + 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 = """ From fb162cb2ad77c41cdca230e083ef81333e286e4c Mon Sep 17 00:00:00 2001 From: descensus <134628590+descensus@users.noreply.github.com> Date: Sat, 27 Dec 2025 00:50:11 +0100 Subject: [PATCH 16/25] Disable nginx IPv6 listener when disabled on host (#1998) * Disable nginx IPv6 listener when disabled on host Patch nginx.conf when host has IPv6 disabled so nginx does not fail to start. * clarified comment --- start.sh | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/start.sh b/start.sh index fa44bc22e..fc36e13ac 100644 --- a/start.sh +++ b/start.sh @@ -11,8 +11,11 @@ envsubst '${BOOKLORE_PORT}' < /etc/nginx/nginx.conf > "$TMP_CONF" # Move to final location mv "$TMP_CONF" /etc/nginx/nginx.conf +# Disable nginx IPv6 listener when IPv6 is disabled on host +[ "$(cat /proc/sys/net/ipv6/conf/all/disable_ipv6 2>/dev/null)" = "0" ] || sed -i '/^[[:space:]]*listen \[\:\:\]:6060;$/d' /etc/nginx/nginx.conf + # Start nginx in background nginx -g 'daemon off;' & # Start Spring Boot in foreground -su-exec ${USER_ID:-0}:${GROUP_ID:-0} java -jar /app/app.jar \ No newline at end of file +su-exec ${USER_ID:-0}:${GROUP_ID:-0} java -jar /app/app.jar From 65a439f9c17628ee7e094fb3b514aae1ee0e2a3f Mon Sep 17 00:00:00 2001 From: acx10 Date: Fri, 26 Dec 2025 16:56:43 -0700 Subject: [PATCH 17/25] Increase angular budget --- booklore-ui/angular.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/booklore-ui/angular.json b/booklore-ui/angular.json index e1b8b3382..f0336f036 100644 --- a/booklore-ui/angular.json +++ b/booklore-ui/angular.json @@ -71,8 +71,8 @@ "budgets": [ { "type": "initial", - "maximumWarning": "5MB", - "maximumError": "5MB" + "maximumWarning": "5.75MB", + "maximumError": "6MB" }, { "type": "anyComponentStyle", From 71617a77ffcebe9632202a914ff2c9b8a330a6e5 Mon Sep 17 00:00:00 2001 From: acx10 Date: Fri, 26 Dec 2025 18:32:31 -0700 Subject: [PATCH 18/25] Misc. layout fixes --- .../book-browser/book-browser.component.html | 2 +- .../dashboard-settings.component.html | 257 ++++++----- .../dashboard-settings.component.scss | 283 +++++++++--- .../create-user-dialog.component.html | 420 +++++++++++------- .../create-user-dialog.component.scss | 78 +++- .../create-user-dialog.component.ts | 10 +- .../user-management.component.scss | 291 ++++++++++++ .../services/dialog-launcher.service.ts | 3 +- 8 files changed, 992 insertions(+), 352 deletions(-) diff --git a/booklore-ui/src/app/features/book/components/book-browser/book-browser.component.html b/booklore-ui/src/app/features/book/components/book-browser/book-browser.component.html index 178e551f2..48663c95c 100644 --- a/booklore-ui/src/app/features/book/components/book-browser/book-browser.component.html +++ b/booklore-ui/src/app/features/book/components/book-browser/book-browser.component.html @@ -296,7 +296,7 @@ @if (entityType$ | async; as entityType) {
@if (userState.user!.permissions.canEditMetadata) { -