Merge pull request #836 from booklore-app/develop

Merge Develop into Master for release
This commit is contained in:
Aditya Chandel
2025-08-06 14:53:42 -06:00
committed by GitHub
97 changed files with 5226 additions and 3692 deletions
+15
View File
@@ -0,0 +1,15 @@
# These are supported funding model platforms
github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
patreon: # Replace with a single Patreon username
open_collective: booklore
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
polar: # Replace with a single Polar username
buy_me_a_coffee: # Replace with a single Buy Me a Coffee username
thanks_dev: # Replace with a single thanks.dev username
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
+34
View File
@@ -0,0 +1,34 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''
---
# Bug Report Template for Booklore
**What happened?**
Please describe the problem or issue you encountered in Booklore.
**How can we see it happen?**
Steps to reproduce the issue:
1. Open Booklore and go to ‘…’
2. Do ‘…’ (like adding a book, editing details, etc.)
3. Notice what goes wrong
**What did you expect to happen?**
Tell us what you thought should happen instead.
**Screenshots or Error Messages**
If you can, please share screenshots or any error messages you saw. It really helps!
**About your setup:**
- Booklore version (e.g., v0.35.0)
- What computer or device are you using? (Windows, Mac, Linux, etc.)
- Which browser and version? (Chrome, Firefox, Safari, etc.)
- How did you install Booklore? (Docker, manual install, etc.)
**Anything else we should know?**
Any other info that might help us understand the issue better.
+22
View File
@@ -0,0 +1,22 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: ''
---
# Feature Request Template for Booklore
**What problem or limitation are you encountering?**
Describe the challenge or issue you’re facing that this feature would address.
**What solution or improvement do you propose?**
Explain clearly what you’d like Booklore to do or how it could work better.
**Have you found any workarounds or alternatives?**
Share any other solutions you’ve tried or considered, if any.
**Additional details**
Add any extra context, examples, or screenshots that might help us understand your request.
+33 -5
View File
@@ -20,8 +20,18 @@ jobs:
with:
fetch-depth: 0
- name: Log in to Docker Hub
uses: docker/login-action@v2
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Log in to GitHub Container Registry
run: echo "${{ secrets.GITHUB_TOKEN }}" | docker login ghcr.io -u ${{ github.actor }} --password-stdin
uses: docker/login-action@v2
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Set up QEMU for multi-arch builds
uses: docker/setup-qemu-action@v3
@@ -113,13 +123,14 @@ jobs:
git tag ${{ env.new_tag }}
git push origin ${{ env.new_tag }}
- name: Build and Push Docker Image
- name: Build and Push Docker Image (Docker Hub & GHCR)
run: |
docker buildx create --use
docker buildx build \
--platform linux/amd64,linux/arm64 \
--build-arg APP_VERSION=${{ env.image_tag }} \
--tag ghcr.io/${{ github.actor }}/booklore-app:${{ env.image_tag }} \
--tag booklore/booklore:${{ env.image_tag }} \
--tag ghcr.io/booklore-app/booklore:${{ env.image_tag }} \
--push .
- name: Push Latest Tag (Only for Master)
@@ -128,7 +139,8 @@ jobs:
docker buildx build \
--platform linux/amd64,linux/arm64 \
--build-arg APP_VERSION=${{ env.new_tag }} \
--tag ghcr.io/${{ github.actor }}/booklore-app:latest \
--tag booklore/booklore:latest \
--tag ghcr.io/booklore-app/booklore:latest \
--push .
- name: Update Release Draft (Only for Master)
@@ -145,4 +157,20 @@ jobs:
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
gh release edit ${{ env.new_tag }} --draft=false
gh release edit ${{ env.new_tag }} --draft=false
- name: Notify Discord of New Release
if: github.ref == 'refs/heads/master'
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
DISCORD_WEBHOOK_URL: ${{ secrets.DISCORD_WEBHOOK_URL }}
run: |
release_json=$(gh release view ${{ env.new_tag }} --json name,body,url)
release_name=$(echo "$release_json" | jq -r '.name')
release_body=$(echo "$release_json" | jq -r '.body')
release_url=$(echo "$release_json" | jq -r '.url')
dockerhub_image="https://hub.docker.com/r/booklore/booklore/tags"
ghcr_image="https://github.com/booklore-app/booklore/pkgs/container/booklore"
content=":tada: **New Release:** [$release_name]($release_url)\n\n$release_body\n\n**Docker Images:**\n- Docker Hub: \`booklore/booklore:${{ env.new_tag }}\` ([View]($dockerhub_image))\n- GHCR: \`ghcr.io/booklore-app/booklore:${{ env.new_tag }}\` ([View]($ghcr_image))"
payload="{\"content\": \"$content\"}"
curl -H "Content-Type: application/json" -X POST -d "$payload" $DISCORD_WEBHOOK_URL
+3
View File
@@ -5,6 +5,9 @@ build/
!**/src/main/**/build/
!**/src/test/**/build/
## MacOS ###
.DS_Store
### STS ###
.apt_generated
.classpath
+48 -37
View File
@@ -4,39 +4,57 @@
![Issues](https://img.shields.io/github/issues/adityachandelgit/BookLore)
![Stars](https://img.shields.io/github/stars/adityachandelgit/BookLore?style=social)
[![Join us on Discord](https://img.shields.io/badge/Chat-Discord-blue?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=blue)](https://opencollective.com/booklore)
[![Venmo](https://img.shields.io/badge/Venmo-Donate-blue?logo=venmo)](https://venmo.com/AdityaChandel)
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
Try it for yourself with the [public live demo](https://demo-booklore.elfhosted.com), sponsored by [ElfHosted](https://elfhosted.com) :heart:, using the following details:
* User: `bookgeek`
* Pass: `elfhosted`
(*the demo resets every hour, on the hour, no copyrighted content uploads please*)
## ✨ Key Features
- 📚 **Powerful Book Organization**: Keep your library tidy with **Libraries** and **Shelves**. Whether you're sorting by genre, author, or mood, finding the right book is effortless.
- 🧠 **Intelligent Metadata Management**: Instantly fetch rich metadata from **Goodreads**, **Amazon**, **Google Books**, **Hardcover**, and more, or fine-tune every detail yourself with our advanced editor.
- 👥 **Multi-User Access with Permissions**: Add users, assign libraries, and control who can edit, upload, or download. Perfect for families, friends, or teams.
- 📖 **Built-in PDF, ePub, and CBX Reader**: Enjoy a smooth, distraction-free reading experience directly in your browser. Supports themes and adjustable settings.
- 🌐 **OPDS 1.2 Integration**: Connect BookLore to your favorite reading apps with full **OPDS** support for seamless downloads.
- 🔐 **Flexible Authentication**: Secure your library with optional **OIDC login** via providers like **Authentik** and **Pocket ID**, or stick with local **JWT**, the choice is yours.
- 📤 **Smart Batch Upload with BookDrop Folder**: Drop dozens of books into the **BookDrop Folder**, and BookLore will automatically scan, organize, and fetch metadata for all of them, hands-free and efficient.
- 📧 **Send Books by Email**: Seamlessly share books with friends or your own devices by sending them directly via email from within BookLore. Just one click, and it’s delivered.
- 📱 **Mobile-Optimized UI**: Sleek, responsive design tailored for phones and tablets. Manage your library from anywhere, effortlessly.
- 🔄 **Open Source & Self-Hosted**: Take full control of your digital library with BookLore’s open-source, self-hosted design.
- 🚀 **Active Development**: BookLore is under continuous improvement with regular updates to features, UI, and performance.
- 📚 **Book Organization**: Organize with Libraries and Shelves. Sort by genre, author, or mood.
- 🧠 **Smart Metadata**: Auto-fetch from Goodreads, Amazon, Google Books, Hardcover, and more.
- 👥 **Multi-User with Permissions**: Add users, assign libraries, control edit/upload/download access.
- 📖 **Built-in Reader**: Read PDFs, ePubs, and CBX files in your browser with customizable themes.
- 🌐 **OPDS 1.2 Support**: Connect to reading apps for seamless downloads.
- 🔐 **Flexible Auth**: Optional OIDC login (Authentik, Pocket ID) or local JWT.
- 📤 **BookDrop Auto-Import**: Drop books in a folder for automatic scanning and metadata fetching.
- 📧 **Email Sharing**: Send books directly via email with one click.
- 📱 **Mobile-Optimized**: Responsive design for phones and tablets.
- 🔄 **Open Source & Self-Hosted**: Full control of your digital library.
- 🚀 **Active Development**: Regular updates to features, UI, and performance.
## 💖 Support the Project
If you find **BookLore** helpful, please consider supporting its development:
- ⭐ 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)
- ⚡ Prefer one-time support? You can also donate via [Venmo](https://venmo.com/AdityaChandel).
## 🌐 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`
> ⚠️ **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.
📘 [BookLore Documentation: Getting Started](https://adityachandelgit.github.io/booklore-docs/docs/getting-started)
📘 [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.
🎥 [BookLore Tutorials: YouTube](https://www.youtube.com/watch?v=UMrn_fIeFRo&list=PLi0fq0zaM7lqY7dX0R66jQtKW64z4_Tdz)
@@ -141,8 +159,8 @@ services:
- /your/local/path/to/booklore/data:/app/data
- /your/local/path/to/booklore/books:/books
- /your/local/path/to/booklore/bookdrop:/bookdrop # 👈 Bookdrop directory
```
```
## 🔑 OIDC/OAuth2 Authentication (Authentik, Pocket ID, etc.)
@@ -155,6 +173,13 @@ For detailed instructions on setting up OIDC authentication:
- 📺 [YouTube video on configuring Authentik with BookLore](https://www.youtube.com/watch?v=r6Ufh9ldF9M)
- 📘 [Step-by-step setup guide for Pocket ID](docs/OIDC-Setup-With-PocketID.md)
## 🛡️ Forward Auth with Reverse Proxy
BookLore also supports **Forward Auth** (also known as Remote Auth) for authentication through reverse proxies like **Traefik**, **Nginx**, or **Caddy**. Forward Auth works by having your reverse proxy handle authentication and pass user information via HTTP headers to BookLore. This can be set up with providers like **Authelia** and **Authentik**.
For detailed setup instructions and configuration examples:
- 📘 [Complete Forward Auth Setup Guide](docs/forward-auth-with-proxy.md)
## 🤝 Community & Support
- 🐞 Found a bug? [Open an issue](https://github.com/adityachandelgit/BookLore/issues)
@@ -168,19 +193,6 @@ 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)
## ⭐ Star History
[![Star History Chart](https://api.star-history.com/svg?repos=adityachandelgit/BookLore&type=Date&theme=dark)](https://star-history.com/#adityachandelgit/BookLore&Date&theme=dark)
## 💖 Support the Project
If you find BookLore helpful, consider ⭐ starring the repo!
Or support the project via [Venmo](https://venmo.com/AdityaChandel):
[![Venmo](https://img.shields.io/badge/Venmo-Donate-blue?logo=venmo)](https://venmo.com/AdityaChandel)
## 🧰 Tech Stack
<p align="left">
@@ -194,4 +206,3 @@ Or support the project via [Venmo](https://venmo.com/AdityaChandel):
* [GNU GPL v3](http://www.gnu.org/licenses/gpl.html)
* Copyright 2024-2025
+21
View File
@@ -0,0 +1,21 @@
# Security Policy
## Supported Versions
Use this section to tell people about which versions of your project are
currently being supported with security updates.
| Version | Supported |
| ------- | ------------------ |
| 5.1.x | :white_check_mark: |
| 5.0.x | :x: |
| 4.0.x | :white_check_mark: |
| < 4.0 | :x: |
## Reporting a Vulnerability
Use this section to tell people how to report a vulnerability.
Tell them where to go, how often they can expect to get an update on a
reported vulnerability, what to expect if the vulnerability is accepted or
declined, etc.
@@ -12,12 +12,13 @@ public class BookParserConfig {
@Bean
public Map<MetadataProvider, BookParser> parserMap(GoogleParser googleParser, AmazonBookParser amazonBookParser,
GoodReadsParser goodReadsParser, HardcoverParser hardcoverParser) {
GoodReadsParser goodReadsParser, HardcoverParser hardcoverParser, ComicvineBookParser comicvineBookParser) {
return Map.of(
MetadataProvider.Amazon, amazonBookParser,
MetadataProvider.GoodReads, goodReadsParser,
MetadataProvider.Google, googleParser,
MetadataProvider.Hardcover, hardcoverParser
MetadataProvider.Hardcover, hardcoverParser,
MetadataProvider.Comicvine, comicvineBookParser
);
}
}
@@ -120,9 +120,9 @@ public class BookController {
}
@PutMapping("/read-status")
public ResponseEntity<Void> updateReadStatus(@RequestBody @Valid ReadStatusUpdateRequest request) {
bookService.updateReadStatus(request.ids(), request.status());
return ResponseEntity.noContent().build();
public ResponseEntity<List<Book>> updateReadStatus(@RequestBody @Valid ReadStatusUpdateRequest request) {
List<Book> updatedBooks = bookService.updateReadStatus(request.ids(), request.status());
return ResponseEntity.ok(updatedBooks);
}
@PostMapping("/reset-progress")
@@ -1,62 +1,40 @@
package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.mapper.BookdropFileMapper;
import com.adityachandel.booklore.model.dto.BookdropFile;
import com.adityachandel.booklore.model.dto.BookdropFileNotification;
import com.adityachandel.booklore.model.dto.request.BookdropFinalizeRequest;
import com.adityachandel.booklore.model.dto.request.BookdropSelectionRequest;
import com.adityachandel.booklore.model.dto.response.BookdropFinalizeResult;
import com.adityachandel.booklore.model.entity.BookdropFileEntity;
import com.adityachandel.booklore.repository.BookdropFileRepository;
import com.adityachandel.booklore.service.bookdrop.BookDropService;
import lombok.AllArgsConstructor;
import org.springframework.core.io.Resource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.time.Instant;
import java.util.List;
import java.util.stream.Collectors;
@AllArgsConstructor
@RestController
@RequestMapping("/api/bookdrop")
public class BookdropFileController {
private final BookdropFileRepository repository;
private final BookdropFileMapper mapper;
private final BookDropService bookDropService;
@GetMapping("/notification")
public BookdropFileNotification getSummary() {
long pendingCount = repository.countByStatus(BookdropFileEntity.Status.PENDING_REVIEW);
long totalCount = repository.count();
return new BookdropFileNotification(
(int) pendingCount,
(int) totalCount,
Instant.now().toString()
);
return bookDropService.getFileNotificationSummary();
}
@GetMapping("/files")
public List<BookdropFile> getFilesByStatus(@RequestParam(required = false) String status) {
if ("pending".equalsIgnoreCase(status)) {
return repository.findAllByStatus(BookdropFileEntity.Status.PENDING_REVIEW)
.stream()
.map(mapper::toDto)
.collect(Collectors.toList());
}
return repository.findAll()
.stream()
.map(mapper::toDto)
.collect(Collectors.toList());
public Page<BookdropFile> getFilesByStatus(@RequestParam(required = false) String status, Pageable pageable) {
return bookDropService.getFilesByStatus(status, pageable);
}
@DeleteMapping("/files")
public ResponseEntity<Void> discardAllFiles() {
bookDropService.discardAllFiles();
@PostMapping("/files/discard")
public ResponseEntity<Void> discardSelectedFiles(@RequestBody BookdropSelectionRequest request) {
bookDropService.discardSelectedFiles(request.isSelectAll(), request.getExcludedIds(), request.getSelectedIds());
return ResponseEntity.ok().build();
}
@@ -69,12 +47,11 @@ public class BookdropFileController {
@GetMapping("/{bookdropId}/cover")
public ResponseEntity<Resource> getBookdropCover(@PathVariable long bookdropId) {
Resource file = bookDropService.getBookdropCover(bookdropId);
if (file == null) {
return ResponseEntity.noContent().build();
}
return ResponseEntity.ok()
return (file != null)
? ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=cover.jpg")
.contentType(MediaType.IMAGE_JPEG)
.body(file);
.body(file)
: ResponseEntity.noContent().build();
}
}
@@ -6,7 +6,10 @@ import com.adityachandel.booklore.model.entity.AuthorEntity;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.CategoryEntity;
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
import org.mapstruct.*;
import org.mapstruct.Context;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Named;
import java.util.Set;
import java.util.stream.Collectors;
@@ -5,7 +5,10 @@ import com.adityachandel.booklore.model.dto.FetchedProposal;
import com.adityachandel.booklore.model.entity.MetadataFetchProposalEntity;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.mapstruct.*;
import org.mapstruct.AfterMapping;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.MappingTarget;
import org.springframework.beans.factory.annotation.Autowired;
@Mapper(componentModel = "spring")
@@ -5,8 +5,6 @@ import com.adityachandel.booklore.model.entity.LibraryEntity;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import java.util.List;
@Mapper(componentModel = "spring")
public interface LibraryMapper {
@@ -1,13 +1,8 @@
package com.adityachandel.booklore.mapper;
import com.adityachandel.booklore.model.dto.LibraryPath;
import com.adityachandel.booklore.model.dto.Shelf;
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
import com.adityachandel.booklore.model.entity.ShelfEntity;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import java.util.List;
@Mapper(componentModel = "spring")
public interface LibraryPathMapper {
@@ -20,6 +20,7 @@ public interface MetadataClearFlagsMapper {
@Mapping(target = "isbn10", source = "clearIsbn10")
@Mapping(target = "asin", source = "clearAsin")
@Mapping(target = "goodreadsId", source = "clearGoodreadsId")
@Mapping(target = "comicvineId", source = "clearComicvineId")
@Mapping(target = "hardcoverId", source = "clearHardcoverId")
@Mapping(target = "googleId", source = "clearGoogleId")
@Mapping(target = "pageCount", source = "clearPageCount")
@@ -1,9 +1,7 @@
package com.adityachandel.booklore.mapper;
import com.adityachandel.booklore.model.dto.OpdsUser;
import com.adityachandel.booklore.model.dto.Shelf;
import com.adityachandel.booklore.model.entity.OpdsUserEntity;
import com.adityachandel.booklore.model.entity.ShelfEntity;
import org.mapstruct.Mapper;
@Mapper(componentModel = "spring")
@@ -13,7 +13,6 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
@Slf4j
@@ -3,12 +3,10 @@ package com.adityachandel.booklore.mapper.v2;
import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.dto.BookMetadata;
import com.adityachandel.booklore.model.dto.LibraryPath;
import com.adityachandel.booklore.model.entity.AuthorEntity;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
import com.adityachandel.booklore.model.entity.CategoryEntity;
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
import org.mapstruct.*;
import com.adityachandel.booklore.model.entity.*;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Named;
import java.util.Set;
import java.util.stream.Collectors;
@@ -17,6 +17,7 @@ public class MetadataClearFlags {
private boolean isbn10;
private boolean asin;
private boolean goodreadsId;
private boolean comicvineId;
private boolean hardcoverId;
private boolean googleId;
private boolean pageCount;
@@ -29,5 +29,6 @@ public class Book {
private CbxProgress cbxProgress;
private Set<Shelf> shelves;
private String readStatus;
private Instant dateFinished;
private LibraryPath libraryPath;
}
@@ -34,6 +34,7 @@ public class BookMetadata {
private Double amazonRating;
private Integer amazonReviewCount;
private String goodreadsId;
private String comicvineId;
private Double goodreadsRating;
private Integer goodreadsReviewCount;
private String hardcoverId;
@@ -59,6 +60,7 @@ public class BookMetadata {
private Boolean isbn10Locked;
private Boolean asinLocked;
private Boolean goodreadsIdLocked;
private Boolean comicvineIdLocked;
private Boolean hardcoverIdLocked;
private Boolean googleIdLocked;
private Boolean pageCountLocked;
@@ -35,6 +35,7 @@ public class EpubMetadata {
private Double amazonRating;
private Integer amazonReviewCount;
private String goodreadsId;
private String comicvineId;
private Double goodreadsRating;
private Integer goodreadsReviewCount;
private String hardcoverId;
@@ -8,7 +8,11 @@ import java.util.List;
@Data
public class BookdropFinalizeRequest {
private String uploadPattern;
private Boolean selectAll;
private List<Long> excludedIds;
private List<BookdropFinalizeFile> files;
private Long defaultLibraryId;
private Long defaultPathId;
@Data
public static class BookdropFinalizeFile {
@@ -17,4 +21,4 @@ public class BookdropFinalizeRequest {
private Long pathId;
private BookMetadata metadata;
}
}
}
@@ -0,0 +1,12 @@
package com.adityachandel.booklore.model.dto.request;
import lombok.Data;
import java.util.List;
@Data
public class BookdropSelectionRequest {
private boolean selectAll;
private List<Long> excludedIds;
private List<Long> selectedIds;
}
@@ -0,0 +1,83 @@
package com.adityachandel.booklore.model.dto.response.comicvineapi;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class Comic {
private int id;
@JsonProperty("api_detail_url")
private String apiDetailUrl;
@JsonProperty("cover_date")
private String coverDate;
private String description;
private String name;
@JsonProperty("issue_number")
private String issueNumber;
private Image image;
private Volume volume;
@JsonProperty("resource_type")
private String resourceType;
@Data
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public static class Image {
@JsonProperty("icon_url")
private String iconUrl;
@JsonProperty("medium_url")
private String mediumUrl;
@JsonProperty("screen_url")
private String screenUrl;
@JsonProperty("screen_large_url")
private String screenLargeUrl;
@JsonProperty("small_url")
private String smallUrl;
@JsonProperty("super_url")
private String superUrl;
@JsonProperty("thumb_url")
private String thumbUrl;
@JsonProperty("tiny_url")
private String tinyUrl;
@JsonProperty("original_url")
private String originalUrl;
@JsonProperty("image_tags")
private String imageTags;
}
@Data
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public static class Volume {
private int id;
private String name;
@JsonProperty("api_detail_url")
private String apiDetailUrl;
@JsonProperty("site_detail_url")
private String siteDetailUrl;
}
}
@@ -0,0 +1,28 @@
package com.adityachandel.booklore.model.dto.response.comicvineapi;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class ComicvineApiResponse {
private String error;
private int limit;
private int offset;
@JsonProperty("number_of_page_results")
private int numberOfPageResults;
@JsonProperty("number_of_total_results")
private int numberOfTotalResults;
@JsonProperty("status_code")
private int statusCode;
private List<Comic> results;
private String version;
}
@@ -0,0 +1,35 @@
package com.adityachandel.booklore.model.dto.response.comicvineapi;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import java.util.List;
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class ComicvineIssueResponse {
private String error;
private int limit;
private int offset;
private int number_of_page_results;
private int number_of_total_results;
private int status_code;
private IssueResults results;
private String version;
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public static class IssueResults {
@JsonProperty("person_credits")
private List<PersonCredit> personCredits;
}
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public static class PersonCredit {
private long id;
private String name;
private String role;
}
}
@@ -8,6 +8,7 @@ public class MetadataProviderSettings {
private Google google;
private Goodreads goodReads;
private Hardcover hardcover;
private Comicvine comicvine;
@Data
public static class Amazon {
@@ -31,4 +32,9 @@ public class MetadataProviderSettings {
private boolean enabled;
private String apiKey;
}
@Data
public static class Comicvine {
private boolean enabled;
private String apiKey;
}
}
@@ -105,6 +105,9 @@ public class BookMetadataEntity {
@Column(name = "google_id", length = 100)
private String googleId;
@Column(name = "comicvine_id", length = 100)
private String comicvineId;
// Locking fields
@Column(name = "title_locked")
@@ -185,6 +188,9 @@ public class BookMetadataEntity {
@Column(name = "google_id_locked")
private Boolean googleIdLocked = Boolean.FALSE;
@Column(name = "comicvine_id_locked")
private Boolean comicvineIdLocked = Boolean.FALSE;
@OneToOne(fetch = FetchType.LAZY)
@MapsId
@JoinColumn(name = "book_id")
@@ -231,6 +237,7 @@ public class BookMetadataEntity {
this.goodreadsReviewCountLocked = lock;
this.hardcoverRatingLocked = lock;
this.hardcoverReviewCountLocked = lock;
this.comicvineIdLocked = lock;
this.personalRatingLocked = lock;
this.goodreadsIdLocked = lock;
this.hardcoverIdLocked = lock;
@@ -262,6 +269,7 @@ public class BookMetadataEntity {
&& Boolean.TRUE.equals(this.hardcoverReviewCountLocked)
&& Boolean.TRUE.equals(this.personalRatingLocked)
&& Boolean.TRUE.equals(this.goodreadsIdLocked)
&& Boolean.TRUE.equals(this.comicvineIdLocked)
&& Boolean.TRUE.equals(this.hardcoverIdLocked)
&& Boolean.TRUE.equals(this.googleIdLocked)
;
@@ -51,4 +51,7 @@ public class UserBookProgressEntity {
@Enumerated(EnumType.STRING)
@Column(name = "read_status")
private ReadStatus readStatus;
@Column(name = "date_finished")
private Instant dateFinished;
}
@@ -1,5 +1,5 @@
package com.adityachandel.booklore.model.enums;
public enum MetadataProvider {
Amazon, GoodReads, Google, Hardcover
Amazon, GoodReads, Google, Hardcover, Comicvine
}
@@ -4,6 +4,8 @@ package com.adityachandel.booklore.repository;
import com.adityachandel.booklore.model.entity.BookdropFileEntity;
import com.adityachandel.booklore.model.entity.BookdropFileEntity.Status;
import jakarta.transaction.Transactional;
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.Modifying;
import org.springframework.data.jpa.repository.Query;
@@ -18,7 +20,7 @@ public interface BookdropFileRepository extends JpaRepository<BookdropFileEntity
Optional<BookdropFileEntity> findByFilePath(String filePath);
List<BookdropFileEntity> findAllByStatus(Status status);
Page<BookdropFileEntity> findAllByStatus(Status status, Pageable pageable);
long countByStatus(Status status);
@@ -26,4 +28,7 @@ public interface BookdropFileRepository extends JpaRepository<BookdropFileEntity
@Modifying
@Query("DELETE FROM BookdropFileEntity f WHERE f.filePath LIKE CONCAT(:prefix, '%')")
int deleteAllByFilePathStartingWith(@Param("prefix") String prefix);
@Query("SELECT f.id FROM BookdropFileEntity f WHERE f.id NOT IN :excludedIds")
List<Long> findAllExcludingIdsFlat(@Param("excludedIds") List<Long> excludedIds);
}
@@ -56,13 +56,15 @@ public class BookCreatorService {
bookEntity.getMetadata().setAuthors(new HashSet<>());
}
authors.stream()
.map(authorName -> truncate(authorName, 255))
.map(authorName -> authorRepository.findByName(authorName)
.orElseGet(() -> authorRepository.save(AuthorEntity.builder().name(authorName).build())))
.forEach(authorEntity -> bookEntity.getMetadata().getAuthors().add(authorEntity));
}
private String truncate(String input, int maxLength) {
if (input == null) return null;
if (input == null)
return null;
return input.length() <= maxLength ? input : input.substring(0, maxLength);
}
@@ -55,6 +55,33 @@ public class BookService {
private final BookQueryService bookQueryService;
private final UserProgressService userProgressService;
private void setBookProgress(Book book, UserBookProgressEntity progress) {
switch (book.getBookType()) {
case EPUB -> book.setEpubProgress(EpubProgress.builder()
.cfi(progress.getEpubProgress())
.percentage(progress.getEpubProgressPercent())
.build());
case PDF -> book.setPdfProgress(PdfProgress.builder()
.page(progress.getPdfProgress())
.percentage(progress.getPdfProgressPercent())
.build());
case CBX -> book.setCbxProgress(CbxProgress.builder()
.page(progress.getCbxProgress())
.percentage(progress.getCbxProgressPercent())
.build());
}
}
private void enrichBookWithProgress(Book book, UserBookProgressEntity progress) {
if (progress != null) {
setBookProgress(book, progress);
book.setLastReadTime(progress.getLastReadTime());
book.setReadStatus(String.valueOf(progress.getReadStatus()));
book.setDateFinished(progress.getDateFinished());
}
}
public List<Book> getBookDTOs(boolean includeDescription) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
boolean isAdmin = user.getPermissions().isAdmin();
@@ -74,14 +101,7 @@ public class BookService {
books.stream().map(Book::getId).collect(Collectors.toSet())
);
books.forEach(book -> {
UserBookProgressEntity progress = progressMap.get(book.getId());
if (progress != null) {
setBookProgress(book, progress);
book.setLastReadTime(progress.getLastReadTime());
book.setReadStatus(String.valueOf(progress.getReadStatus()));
}
});
books.forEach(book -> enrichBookWithProgress(book, progressMap.get(book.getId())));
return books;
}
@@ -89,9 +109,7 @@ public class BookService {
public List<Book> getBooksByIds(Set<Long> bookIds, boolean withDescription) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
List<BookEntity> bookEntities;
bookEntities = bookQueryService.findAllWithMetadataByIds(bookIds);
List<BookEntity> bookEntities = bookQueryService.findAllWithMetadataByIds(bookIds);
Map<Long, UserBookProgressEntity> progressMap = userProgressService.fetchUserProgress(
user.getId(), bookEntities.stream().map(BookEntity::getId).collect(Collectors.toSet()));
@@ -99,36 +117,48 @@ public class BookService {
return bookEntities.stream().map(bookEntity -> {
Book book = bookMapper.toBook(bookEntity);
book.setFilePath(FileUtils.getBookFullPath(bookEntity));
if (!withDescription) {
book.getMetadata().setDescription(null);
}
UserBookProgressEntity progress = progressMap.get(bookEntity.getId());
if (progress != null) {
setBookProgress(book, progress);
book.setLastReadTime(progress.getLastReadTime());
}
if (!withDescription) book.getMetadata().setDescription(null);
enrichBookWithProgress(book, progressMap.get(bookEntity.getId()));
return book;
}).collect(Collectors.toList());
}
private void setBookProgress(Book book, UserBookProgressEntity progress) {
switch (book.getBookType()) {
case EPUB -> book.setEpubProgress(EpubProgress.builder()
.cfi(progress.getEpubProgress())
.percentage(progress.getEpubProgressPercent())
.build());
case PDF -> book.setPdfProgress(PdfProgress.builder()
.page(progress.getPdfProgress())
.percentage(progress.getPdfProgressPercent())
.build());
case CBX -> book.setCbxProgress(CbxProgress.builder()
.page(progress.getCbxProgress())
.percentage(progress.getCbxProgressPercent())
public Book getBook(long bookId, boolean withDescription) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
UserBookProgressEntity userProgress = userBookProgressRepository.findByUserIdAndBookId(user.getId(), bookId).orElse(new UserBookProgressEntity());
Book book = bookMapper.toBook(bookEntity);
book.setLastReadTime(userProgress.getLastReadTime());
if (bookEntity.getBookType() == BookFileType.PDF) {
book.setPdfProgress(PdfProgress.builder()
.page(userProgress.getPdfProgress())
.percentage(userProgress.getPdfProgressPercent())
.build());
}
if (bookEntity.getBookType() == BookFileType.EPUB) {
book.setEpubProgress(EpubProgress.builder()
.cfi(userProgress.getEpubProgress())
.percentage(userProgress.getEpubProgressPercent())
.build());
}
if (bookEntity.getBookType() == BookFileType.CBX) {
book.setCbxProgress(CbxProgress.builder()
.page(userProgress.getCbxProgress())
.percentage(userProgress.getCbxProgressPercent())
.build());
}
book.setFilePath(FileUtils.getBookFullPath(bookEntity));
book.setReadStatus(String.valueOf(userProgress.getReadStatus()));
book.setDateFinished(userProgress.getDateFinished());
if (!withDescription) {
book.getMetadata().setDescription(null);
}
return book;
}
public BookViewerSettings getBookViewerSetting(long bookId) {
@@ -248,41 +278,69 @@ public class BookService {
}
}
public Book getBook(long bookId, boolean withDescription) {
@Transactional
public void updateReadProgress(ReadProgressRequest request) {
BookEntity book = bookRepository.findById(request.getBookId()).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(request.getBookId()));
BookLoreUser user = authenticationService.getAuthenticatedUser();
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
UserBookProgressEntity userProgress = userBookProgressRepository.findByUserIdAndBookId(user.getId(), bookId).orElse(new UserBookProgressEntity());
Book book = bookMapper.toBook(bookEntity);
book.setLastReadTime(userProgress.getLastReadTime());
if (bookEntity.getBookType() == BookFileType.PDF) {
book.setPdfProgress(PdfProgress.builder()
.page(userProgress.getPdfProgress())
.percentage(userProgress.getPdfProgressPercent())
.build());
UserBookProgressEntity userBookProgress = userBookProgressRepository.findByUserIdAndBookId(user.getId(), book.getId()).orElse(new UserBookProgressEntity());
userBookProgress.setUser(userRepository.findById(user.getId()).orElseThrow(() -> new UsernameNotFoundException("User not found")));
userBookProgress.setBook(book);
userBookProgress.setLastReadTime(Instant.now());
if (book.getBookType() == BookFileType.EPUB && request.getEpubProgress() != null) {
userBookProgress.setEpubProgress(request.getEpubProgress().getCfi());
userBookProgress.setEpubProgressPercent(request.getEpubProgress().getPercentage());
} else if (book.getBookType() == BookFileType.PDF && request.getPdfProgress() != null) {
userBookProgress.setPdfProgress(request.getPdfProgress().getPage());
userBookProgress.setPdfProgressPercent(request.getPdfProgress().getPercentage());
} else if (book.getBookType() == BookFileType.CBX && request.getCbxProgress() != null) {
userBookProgress.setCbxProgress(request.getCbxProgress().getPage());
userBookProgress.setCbxProgressPercent(request.getCbxProgress().getPercentage());
}
if (bookEntity.getBookType() == BookFileType.EPUB) {
book.setEpubProgress(EpubProgress.builder()
.cfi(userProgress.getEpubProgress())
.percentage(userProgress.getEpubProgressPercent())
.build());
}
if (bookEntity.getBookType() == BookFileType.CBX) {
book.setCbxProgress(CbxProgress.builder()
.page(userProgress.getCbxProgress())
.percentage(userProgress.getCbxProgressPercent())
.build());
}
book.setFilePath(FileUtils.getBookFullPath(bookEntity));
book.setReadStatus(String.valueOf(userProgress.getReadStatus()));
userBookProgressRepository.save(userBookProgress);
}
if (!withDescription) {
book.getMetadata().setDescription(null);
@Transactional
public List<Book> updateReadStatus(List<Long> bookIds, String status) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
ReadStatus readStatus = EnumUtils.getEnumIgnoreCase(ReadStatus.class, status);
List<BookEntity> books = bookRepository.findAllById(bookIds);
if (books.size() != bookIds.size()) {
throw ApiError.BOOK_NOT_FOUND.createException("One or more books not found");
}
return book;
BookLoreUserEntity userEntity = userRepository.findById(user.getId()).orElseThrow(() -> new UsernameNotFoundException("User not found"));
for (BookEntity book : books) {
UserBookProgressEntity progress = userBookProgressRepository
.findByUserIdAndBookId(user.getId(), book.getId())
.orElse(new UserBookProgressEntity());
progress.setUser(userEntity);
progress.setBook(book);
progress.setReadStatus(readStatus);
userBookProgressRepository.save(progress);
}
return books.stream()
.map(bookEntity -> {
Book book = bookMapper.toBook(bookEntity);
book.setFilePath(FileUtils.getBookFullPath(bookEntity));
UserBookProgressEntity progress = userBookProgressRepository
.findByUserIdAndBookId(user.getId(), bookEntity.getId())
.orElse(null);
if (progress != null) {
setBookProgress(book, progress);
book.setLastReadTime(progress.getLastReadTime());
book.setReadStatus(String.valueOf(progress.getReadStatus()));
book.setDateFinished(progress.getDateFinished());
}
return book;
})
.collect(Collectors.toList());
}
public List<Book> resetProgress(List<Long> bookIds) {
@@ -307,6 +365,7 @@ public class BookService {
progress.setEpubProgressPercent(null);
progress.setCbxProgress(null);
progress.setCbxProgressPercent(null);
progress.setDateFinished(null);
userBookProgressRepository.save(progress);
updatedBooks.add(bookMapper.toBook(bookEntity));
@@ -315,15 +374,12 @@ public class BookService {
return updatedBooks;
}
@Transactional
public List<Book> assignShelvesToBooks(Set<Long> bookIds, Set<Long> shelfIdsToAssign, Set<Long> shelfIdsToUnassign) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
BookLoreUserEntity userEntity = userRepository.findById(user.getId()).orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(user.getId()));
Set<Long> userShelfIds = userEntity.getShelves().stream()
.map(ShelfEntity::getId)
.collect(Collectors.toSet());
Set<Long> userShelfIds = userEntity.getShelves().stream().map(ShelfEntity::getId).collect(Collectors.toSet());
if (!userShelfIds.containsAll(shelfIdsToAssign)) {
throw ApiError.UNAUTHORIZED.createException("Cannot assign shelves that do not belong to the user.");
@@ -336,7 +392,6 @@ public class BookService {
List<ShelfEntity> shelvesToAssign = shelfRepository.findAllById(shelfIdsToAssign);
for (BookEntity bookEntity : bookEntities) {
bookEntity.getShelves().removeIf(shelf -> shelfIdsToUnassign.contains(shelf.getId()));
for (ShelfEntity shelf : shelvesToAssign) {
if (!bookEntity.getShelves().contains(shelf)) {
bookEntity.getShelves().add(shelf);
@@ -344,7 +399,16 @@ public class BookService {
}
}
bookRepository.saveAll(bookEntities);
return bookEntities.stream().map(bookMapper::toBook).collect(Collectors.toList());
Map<Long, UserBookProgressEntity> progressMap = userProgressService.fetchUserProgress(
user.getId(), bookEntities.stream().map(BookEntity::getId).collect(Collectors.toSet()));
return bookEntities.stream().map(bookEntity -> {
Book book = bookMapper.toBook(bookEntity);
book.setFilePath(FileUtils.getBookFullPath(bookEntity));
enrichBookWithProgress(book, progressMap.get(bookEntity.getId()));
return book;
}).collect(Collectors.toList());
}
public Resource getBookCover(long bookId) {
@@ -352,50 +416,6 @@ public class BookService {
return fileService.getBookCover(bookEntity.getMetadata().getThumbnail());
}
@Transactional
public void updateReadProgress(ReadProgressRequest request) {
BookEntity book = bookRepository.findById(request.getBookId()).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(request.getBookId()));
BookLoreUser user = authenticationService.getAuthenticatedUser();
UserBookProgressEntity userBookProgress = userBookProgressRepository.findByUserIdAndBookId(user.getId(), book.getId()).orElse(new UserBookProgressEntity());
userBookProgress.setUser(userRepository.findById(user.getId()).orElseThrow(() -> new UsernameNotFoundException("User not found")));
userBookProgress.setBook(book);
userBookProgress.setLastReadTime(Instant.now());
if (book.getBookType() == BookFileType.EPUB && request.getEpubProgress() != null) {
userBookProgress.setEpubProgress(request.getEpubProgress().getCfi());
userBookProgress.setEpubProgressPercent(request.getEpubProgress().getPercentage());
} else if (book.getBookType() == BookFileType.PDF && request.getPdfProgress() != null) {
userBookProgress.setPdfProgress(request.getPdfProgress().getPage());
userBookProgress.setPdfProgressPercent(request.getPdfProgress().getPercentage());
} else if (book.getBookType() == BookFileType.CBX && request.getCbxProgress() != null) {
userBookProgress.setCbxProgress(request.getCbxProgress().getPage());
userBookProgress.setCbxProgressPercent(request.getCbxProgress().getPercentage());
}
userBookProgressRepository.save(userBookProgress);
}
@Transactional
public void updateReadStatus(List<Long> bookIds, String status) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
ReadStatus readStatus = EnumUtils.getEnumIgnoreCase(ReadStatus.class, status);
List<BookEntity> books = bookRepository.findAllById(bookIds);
if (books.size() != bookIds.size()) {
throw ApiError.BOOK_NOT_FOUND.createException("One or more books not found");
}
BookLoreUserEntity userEntity = userRepository.findById(user.getId()).orElseThrow(() -> new UsernameNotFoundException("User not found"));
for (BookEntity book : books) {
UserBookProgressEntity progress = userBookProgressRepository
.findByUserIdAndBookId(user.getId(), book.getId())
.orElse(new UserBookProgressEntity());
progress.setUser(userEntity);
progress.setBook(book);
progress.setReadStatus(readStatus);
userBookProgressRepository.save(progress);
}
}
public ResponseEntity<Resource> downloadBook(Long bookId) {
try {
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
@@ -515,4 +535,4 @@ public class BookService {
}
}
}
}
}
@@ -21,7 +21,7 @@ public class VersionService {
@Value("${app.version:unknown}")
private String appVersion;
private static final String GITHUB_REPO = "adityachandelgit/BookLore";
private static final String GITHUB_REPO = "booklore-app/booklore";
public VersionInfo getVersionInfo() {
String latestVersion = fetchLatestGitHubReleaseVersion();
@@ -78,10 +78,15 @@ public class SettingPersistenceHelper {
defaultHardcover.setEnabled(false);
defaultHardcover.setApiKey(null);
MetadataProviderSettings.Comicvine defaultComicvine = new MetadataProviderSettings.Comicvine();
defaultComicvine.setEnabled(false);
defaultComicvine.setApiKey(null);
defaultMetadataProviderSettings.setAmazon(defaultAmazon);
defaultMetadataProviderSettings.setGoogle(defaultGoogle);
defaultMetadataProviderSettings.setGoodReads(defaultGoodreads);
defaultMetadataProviderSettings.setHardcover(defaultHardcover);
defaultMetadataProviderSettings.setComicvine(defaultComicvine);
return defaultMetadataProviderSettings;
}
@@ -2,34 +2,55 @@ package com.adityachandel.booklore.service.bookdrop;
import com.adityachandel.booklore.config.AppProperties;
import com.adityachandel.booklore.exception.ApiError;
import com.adityachandel.booklore.mapper.BookdropFileMapper;
import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.dto.BookMetadata;
import com.adityachandel.booklore.model.dto.BookdropFile;
import com.adityachandel.booklore.model.dto.BookdropFileNotification;
import com.adityachandel.booklore.model.dto.request.BookdropFinalizeRequest;
import com.adityachandel.booklore.model.dto.response.BookdropFinalizeResult;
import com.adityachandel.booklore.model.dto.response.BookdropFileResult;
import com.adityachandel.booklore.model.dto.response.BookdropFinalizeResult;
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
import com.adityachandel.booklore.model.entity.*;
import com.adityachandel.booklore.model.enums.*;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.BookdropFileEntity;
import com.adityachandel.booklore.model.entity.LibraryEntity;
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
import com.adityachandel.booklore.model.enums.BookFileExtension;
import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.model.websocket.Topic;
import com.adityachandel.booklore.repository.*;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.repository.BookdropFileRepository;
import com.adityachandel.booklore.repository.LibraryRepository;
import com.adityachandel.booklore.service.NotificationService;
import com.adityachandel.booklore.service.fileprocessor.*;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry;
import com.adityachandel.booklore.service.metadata.MetadataRefreshService;
import com.adityachandel.booklore.service.monitoring.*;
import com.adityachandel.booklore.service.monitoring.MonitoringService;
import com.adityachandel.booklore.util.FileUtils;
import com.adityachandel.booklore.util.PathPatternResolver;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.core.io.PathResource;
import org.springframework.core.io.Resource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@Slf4j
@@ -47,6 +68,22 @@ public class BookDropService {
private final BookdropNotificationService bookdropNotificationService;
private final BookFileProcessorRegistry processorRegistry;
private final AppProperties appProperties;
private final BookdropFileMapper mapper;
private final ObjectMapper objectMapper;
public BookdropFileNotification getFileNotificationSummary() {
long pendingCount = bookdropFileRepository.countByStatus(BookdropFileEntity.Status.PENDING_REVIEW);
long totalCount = bookdropFileRepository.count();
return new BookdropFileNotification((int) pendingCount, (int) totalCount, Instant.now().toString());
}
public Page<BookdropFile> getFilesByStatus(String status, Pageable pageable) {
if ("pending".equalsIgnoreCase(status)) {
return bookdropFileRepository.findAllByStatus(BookdropFileEntity.Status.PENDING_REVIEW, pageable).map(mapper::toDto);
} else {
return bookdropFileRepository.findAll(pageable).map(mapper::toDto);
}
}
public BookdropFinalizeResult finalizeImport(BookdropFinalizeRequest request) {
boolean monitoringWasActive = !monitoringService.isPaused();
@@ -54,36 +91,91 @@ public class BookDropService {
bookdropMonitoringService.pauseMonitoring();
BookdropFinalizeResult results = BookdropFinalizeResult.builder().build();
Long defaultLibraryId = request.getDefaultLibraryId();
Long defaultPathId = request.getDefaultPathId();
for (BookdropFinalizeRequest.BookdropFinalizeFile fileReq : request.getFiles()) {
try {
BookdropFileEntity fileEntity = bookdropFileRepository.findById(fileReq.getFileId()).orElseThrow(() -> ApiError.FILE_NOT_FOUND.createException(fileReq.getFileId()));
Map<Long, BookdropFinalizeRequest.BookdropFinalizeFile> metadataById = Optional.ofNullable(request.getFiles())
.orElse(List.of())
.stream()
.collect(Collectors.toMap(BookdropFinalizeRequest.BookdropFinalizeFile::getFileId, Function.identity()));
BookdropFileResult result = moveFile(
fileReq.getLibraryId(),
fileReq.getPathId(),
request.getUploadPattern(),
fileReq.getMetadata(),
fileEntity
);
results.getResults().add(result);
} catch (Exception e) {
String msg = String.format("Failed to finalize file [id=%s]: %s", fileReq.getFileId(), e.getMessage());
log.error(msg, e);
notificationService.sendMessage(Topic.LOG, msg);
final int CHUNK_SIZE = 100;
AtomicInteger failedCount = new AtomicInteger();
log.info("Starting finalizeImport: selectAll={}, provided file count={}, defaultLibraryId={}, defaultPathId={}",
request.getSelectAll(), metadataById.size(), defaultLibraryId, defaultPathId);
if (Boolean.TRUE.equals(request.getSelectAll())) {
List<Long> excludedIds = Optional.ofNullable(request.getExcludedIds()).orElse(List.of());
List<Long> allIds = bookdropFileRepository.findAllExcludingIdsFlat(excludedIds); // You need to write this
log.info("SelectAll: Total files to finalize (after exclusions): {}, Excluded IDs: {}", allIds.size(), excludedIds);
for (int i = 0; i < allIds.size(); i += CHUNK_SIZE) {
int end = Math.min(i + CHUNK_SIZE, allIds.size());
List<Long> chunk = allIds.subList(i, end);
log.info("Processing chunk {}/{} ({} files): IDs={}", (i / CHUNK_SIZE + 1), (int) Math.ceil((double) allIds.size() / CHUNK_SIZE), chunk.size(), chunk);
List<BookdropFileEntity> chunkFiles = bookdropFileRepository.findAllById(chunk);
Map<Long, BookdropFileEntity> fileMap = chunkFiles.stream().collect(Collectors.toMap(BookdropFileEntity::getId, Function.identity()));
for (Long id : chunk) {
BookdropFileEntity file = fileMap.get(id);
if (file == null) {
log.warn("File ID {} missing in DB during finalizeImport chunk processing", id);
failedCount.incrementAndGet();
continue;
}
processFile(file, metadataById.get(id), defaultLibraryId, defaultPathId, request.getUploadPattern(), results, failedCount);
}
}
} else {
List<Long> ids = Optional.ofNullable(request.getFiles())
.orElse(List.of())
.stream()
.map(BookdropFinalizeRequest.BookdropFinalizeFile::getFileId)
.toList();
log.info("Processing {} manually selected files in chunks of {}. File IDs: {}", ids.size(), CHUNK_SIZE, ids);
for (int i = 0; i < ids.size(); i += CHUNK_SIZE) {
int end = Math.min(i + CHUNK_SIZE, ids.size());
List<Long> chunkIds = ids.subList(i, end);
List<BookdropFileEntity> chunkFiles = bookdropFileRepository.findAllById(chunkIds);
log.info("Processing chunk {} of {} ({} files): IDs={}", (i / CHUNK_SIZE + 1), (int) Math.ceil((double) ids.size() / CHUNK_SIZE), chunkFiles.size(), chunkIds);
Map<Long, BookdropFileEntity> fileMap = chunkFiles.stream()
.collect(Collectors.toMap(BookdropFileEntity::getId, Function.identity()));
for (Long id : chunkIds) {
BookdropFileEntity file = fileMap.get(id);
if (file == null) {
log.error("File ID {} not found in DB during finalizeImport chunk processing", id);
failedCount.incrementAndGet();
continue;
}
processFile(file, metadataById.get(id), defaultLibraryId, defaultPathId, request.getUploadPattern(), results, failedCount);
}
}
}
log.info("Finalization complete. Success: {}, Failed: {}, Total processed: {}",
results.getResults().stream().filter(BookdropFileResult::isSuccess).count(),
failedCount.get(),
results.getResults().size());
if (monitoringWasActive) {
Thread.startVirtualThread(() -> {
try {
Thread.sleep(5000);
monitoringService.resumeMonitoring();
bookdropMonitoringService.resumeMonitoring();
log.info("Monitoring resumed after 5s delay");
log.info("Monitoring resumed after 5s delay following finalizeImport");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.warn("Interrupted while delaying resume of monitoring");
log.warn("Interrupted while delaying resume of monitoring after finalizeImport");
}
});
}
@@ -91,6 +183,64 @@ public class BookDropService {
return results;
}
private void processFile(
BookdropFileEntity fileEntity,
BookdropFinalizeRequest.BookdropFinalizeFile fileReq,
Long defaultLibraryId,
Long defaultPathId,
String uploadPattern,
BookdropFinalizeResult results,
AtomicInteger failedCount
) {
try {
Long libraryId;
Long pathId;
BookMetadata metadata;
if (fileReq != null) {
libraryId = fileReq.getLibraryId() != null ? fileReq.getLibraryId() : defaultLibraryId;
pathId = fileReq.getPathId() != null ? fileReq.getPathId() : defaultPathId;
metadata = fileReq.getMetadata();
log.debug("Processing fileId={}, fileName={} with provided metadata, libraryId={}, pathId={}", fileEntity.getId(), fileEntity.getFileName(), libraryId, pathId);
} else {
if (defaultLibraryId == null || defaultPathId == null) {
log.warn("Missing default metadata for fileId={}", fileEntity.getId());
throw ApiError.BAD_REQUEST.createException("Missing metadata and defaults for fileId=" + fileEntity.getId());
}
metadata = fileEntity.getFetchedMetadata() != null
? objectMapper.readValue(fileEntity.getFetchedMetadata(), BookMetadata.class)
: objectMapper.readValue(fileEntity.getOriginalMetadata(), BookMetadata.class);
libraryId = defaultLibraryId;
pathId = defaultPathId;
log.debug("Processing fileId={}, fileName={} with default metadata, libraryId={}, pathId={}", fileEntity.getId(), fileEntity.getFileName(), libraryId, pathId);
}
BookdropFileResult result = moveFile(
libraryId,
pathId,
uploadPattern,
metadata,
fileEntity
);
results.getResults().add(result);
if (!result.isSuccess()) {
log.warn("Finalization failed (non-exception) for file id={}, name={}, message={}", fileEntity.getId(), fileEntity.getFileName(), result.getMessage());
failedCount.incrementAndGet();
} else {
log.info("Successfully finalized file id={}, name={}", fileEntity.getId(), fileEntity.getFileName());
}
} catch (Exception e) {
failedCount.incrementAndGet();
String msg = String.format("Error finalizing file [id=%s, name=%s]: %s", fileEntity.getId(), fileEntity.getFileName(), e.getMessage());
log.error(msg, e);
notificationService.sendMessage(Topic.LOG, msg);
}
}
private BookdropFileResult moveFile(long libraryId, long pathId, String filePattern, BookMetadata metadata, BookdropFileEntity bookdropFile) throws Exception {
LibraryEntity library = libraryRepository.findById(libraryId)
.orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
@@ -109,20 +259,26 @@ public class BookDropService {
Path target = Paths.get(path.getPath(), relativePath);
File targetFile = target.toFile();
log.debug("Preparing to move file id={}, name={}, source={}, target={}, library={}, path={}",
bookdropFile.getId(), bookdropFile.getFileName(), source, target, library.getName(), path.getPath());
if (!Files.exists(source)) {
bookdropFileRepository.deleteById(bookdropFile.getId());
log.warn("Source file [id={}] not found. Deleting entry.", bookdropFile.getId());
log.warn("Source file [id={}] not found at '{}'. Deleting entry from DB.", bookdropFile.getId(), source);
bookdropNotificationService.sendBookdropFileSummaryNotification();
return failureResult(targetFile.getName(), "Source file does not exist in bookdrop folder");
}
if (targetFile.exists()) {
log.warn("Target file already exists: id={}, name={}, target={}", bookdropFile.getId(), bookdropFile.getFileName(), target);
return failureResult(targetFile.getName(), "File already exists in the library '" + library.getName() + "'");
}
Files.createDirectories(target.getParent());
Files.move(source, target);
log.info("Moved file id={}, name={} from '{}' to '{}'", bookdropFile.getId(), bookdropFile.getFileName(), source, target);
Book processedBook = processFile(targetFile.getName(), library, path, targetFile,
BookFileExtension.fromFileName(bookdropFile.getFileName())
.orElseThrow(() -> ApiError.INVALID_FILE_FORMAT.createException("Unsupported file extension"))
@@ -143,6 +299,8 @@ public class BookDropService {
log.debug("Deleted cached cover image for bookdropId={}: {}", bookdropFile.getId(), deleted);
}
log.info("File import completed: id={}, name={}, library={}, path={}", bookdropFile.getId(), targetFile.getName(), library.getName(), path.getPath());
return BookdropFileResult.builder()
.fileName(targetFile.getName())
.message("File successfully imported into the '" + library.getName() + "' library from the Bookdrop folder")
@@ -171,7 +329,7 @@ public class BookDropService {
return processor.processFile(libraryFile);
}
public void discardAllFiles() {
public void discardSelectedFiles(boolean selectAll, List<Long> excludedIds, List<Long> selectedIds) {
bookdropMonitoringService.pauseMonitoring();
Path bookdropPath = Path.of(appProperties.getBookdropFolder());
@@ -185,52 +343,62 @@ public class BookDropService {
return;
}
try (Stream<Path> paths = Files.walk(bookdropPath)) {
paths.sorted(Comparator.reverseOrder())
.filter(p -> !p.equals(bookdropPath))
.forEach(path -> {
try {
if (Files.isRegularFile(path) && Files.deleteIfExists(path)) {
deletedFiles.incrementAndGet();
} else if (Files.isDirectory(path) && Files.deleteIfExists(path)) {
deletedDirs.incrementAndGet();
}
} catch (IOException e) {
log.warn("Failed to delete path: {}", path, e);
}
});
List<BookdropFileEntity> filesToDelete;
if (selectAll) {
filesToDelete = bookdropFileRepository.findAll().stream()
.filter(f -> excludedIds == null || !excludedIds.contains(f.getId()))
.toList();
log.info("Discarding all files except excluded IDs: {}", excludedIds);
} else {
filesToDelete = bookdropFileRepository.findAllById(selectedIds == null ? List.of() : selectedIds);
log.info("Discarding selected files: {}", selectedIds);
}
long removedDbCount = bookdropFileRepository.count();
bookdropFileRepository.deleteAll();
Path tempCoverDir = Paths.get(appProperties.getPathConfig(), "bookdrop_temp");
if (Files.exists(tempCoverDir)) {
try (Stream<Path> files = Files.walk(tempCoverDir)) {
files
.filter(Files::isRegularFile)
.filter(p -> p.toString().endsWith(".jpg"))
.forEach(p -> {
try {
Files.delete(p);
deletedCovers.incrementAndGet();
} catch (IOException e) {
log.warn("Failed to delete cached cover: {}", p, e);
}
});
for (BookdropFileEntity entity : filesToDelete) {
try {
Path filePath = Path.of(entity.getFilePath());
if (Files.exists(filePath) && Files.isRegularFile(filePath) && Files.deleteIfExists(filePath)) {
deletedFiles.incrementAndGet();
log.debug("Deleted file from disk: id={}, path={}", entity.getId(), filePath);
}
Path coverPath = Paths.get(appProperties.getPathConfig(), "bookdrop_temp", entity.getId() + ".jpg");
if (Files.exists(coverPath) && Files.deleteIfExists(coverPath)) {
deletedCovers.incrementAndGet();
log.debug("Deleted cover image: id={}, path={}", entity.getId(), coverPath);
}
} catch (IOException e) {
log.warn("Failed to clean bookdrop_temp folder", e);
log.warn("Failed to delete file or cover for bookdropId={}: {}", entity.getId(), e.getMessage());
}
}
bookdropFileRepository.deleteAllById(filesToDelete.stream().map(BookdropFileEntity::getId).toList());
log.info("Deleted {} bookdrop DB entries", filesToDelete.size());
try (Stream<Path> paths = Files.walk(bookdropPath)) {
paths.sorted(Comparator.reverseOrder())
.filter(p -> !p.equals(bookdropPath) && Files.isDirectory(p))
.forEach(p -> {
try (Stream<Path> subPaths = Files.list(p)) {
if (subPaths.findAny().isEmpty()) {
Files.deleteIfExists(p);
deletedDirs.incrementAndGet();
log.debug("Deleted empty directory: {}", p);
}
} catch (IOException e) {
log.warn("Failed to delete folder: {}", p, e);
}
});
} catch (IOException e) {
log.warn("Failed to scan bookdrop folder for empty directories", e);
}
bookdropNotificationService.sendBookdropFileSummaryNotification();
log.info("Bookdrop cleanup summary: deleted {} files, {} folders, {} DB entries, {} covers",
deletedFiles.get(), deletedDirs.get(), filesToDelete.size(), deletedCovers.get());
log.info("Discarded all files: deleted {} files, {} folders, {} DB entries, and {} cover images", deletedFiles.get(), deletedDirs.get(), removedDbCount, deletedCovers.get());
} catch (IOException e) {
throw new RuntimeException("Failed to clean bookdrop folder", e);
} finally {
bookdropMonitoringService.resumeMonitoring();
log.info("Bookdrop monitoring resumed after cleanup");
}
}
@@ -243,4 +411,4 @@ public class BookDropService {
return null;
}
}
}
}
@@ -93,7 +93,7 @@ public class BookdropEventHandlerService {
}
if (bookdropFileRepository.findByFilePath(filePath).isPresent()) {
log.info("File already processed in bookdrop, ignoring: {}", filePath);
log.info("File already exists in Bookdrop and is pending review or acceptance: {}", filePath);
return;
}
@@ -131,6 +131,7 @@ public class EpubProcessor extends AbstractFileProcessor implements BookFileProc
metadata.setHardcoverRating(epubMetadata.getHardcoverRating());
metadata.setHardcoverReviewCount(epubMetadata.getHardcoverReviewCount());
metadata.setGoogleId(truncate(epubMetadata.getGoogleId(), 100));
metadata.setComicvineId(truncate(epubMetadata.getComicvineId(), 100));
bookCreatorService.addAuthorsToBook(epubMetadata.getAuthors(), bookEntity);
@@ -114,6 +114,9 @@ public class PdfProcessor extends AbstractFileProcessor implements BookFileProce
if (StringUtils.isNotBlank(extracted.getGoodreadsId())) {
bookEntity.getMetadata().setGoodreadsId(extracted.getGoodreadsId());
}
if (StringUtils.isNotBlank(extracted.getComicvineId())){
bookEntity.getMetadata().setComicvineId(extracted.getComicvineId());
}
if (StringUtils.isNotBlank(extracted.getIsbn10())) {
bookEntity.getMetadata().setIsbn10(extracted.getIsbn10());
}
@@ -138,6 +138,7 @@ public class BookMetadataUpdater {
handleFieldUpdate(e.getIsbn10Locked(), clear.isIsbn10(), m.getIsbn10(), v -> e.setIsbn10(nullIfBlank(v)));
handleFieldUpdate(e.getAsinLocked(), clear.isAsin(), m.getAsin(), v -> e.setAsin(nullIfBlank(v)));
handleFieldUpdate(e.getGoodreadsIdLocked(), clear.isGoodreadsId(), m.getGoodreadsId(), v -> e.setGoodreadsId(nullIfBlank(v)));
handleFieldUpdate(e.getComicvineIdLocked(), clear.isComicvineId(), m.getComicvineId(), v -> e.setComicvineId(nullIfBlank(v)));
handleFieldUpdate(e.getHardcoverIdLocked(), clear.isHardcoverId(), m.getHardcoverId(), v -> e.setHardcoverId(nullIfBlank(v)));
handleFieldUpdate(e.getGoogleIdLocked(), clear.isGoogleId(), m.getGoogleId(), v -> e.setGoogleId(nullIfBlank(v)));
handleFieldUpdate(e.getPageCountLocked(), clear.isPageCount(), m.getPageCount(), e::setPageCount);
@@ -227,6 +228,7 @@ public class BookMetadataUpdater {
Pair.of(m.getIsbn10Locked(), e::setIsbn10Locked),
Pair.of(m.getAsinLocked(), e::setAsinLocked),
Pair.of(m.getGoodreadsIdLocked(), e::setGoodreadsIdLocked),
Pair.of(m.getComicvineIdLocked(), e::setComicvineIdLocked),
Pair.of(m.getHardcoverIdLocked(), e::setHardcoverIdLocked),
Pair.of(m.getGoogleIdLocked(), e::setGoogleIdLocked),
Pair.of(m.getPageCountLocked(), e::setPageCountLocked),
@@ -309,6 +309,11 @@ public class MetadataRefreshService {
if (metadataMap.containsKey(Google)) {
metadata.setGoogleId(metadataMap.get(Google).getGoogleId());
}
if (metadataMap.containsKey(Comicvine)){
metadata.setComicvineId(metadataMap.get(Comicvine).getComicvineId());
}
if (request.getRefreshOptions().isMergeCategories()) {
metadata.setCategories(getAllCategories(metadataMap, fieldOptions.getCategories(), BookMetadata::getCategories));
@@ -56,6 +56,7 @@ public class BookMetadataRestorer {
if (!isLocked(metadata.getIsbn10Locked())) metadata.setIsbn10(backup.getIsbn10());
if (!isLocked(metadata.getAsinLocked())) metadata.setAsin(backup.getAsin());
if (!isLocked(metadata.getGoodreadsIdLocked())) metadata.setGoodreadsId(backup.getGoodreadsId());
if (!isLocked(metadata.getComicvineIdLocked())) metadata.setComicvineId(backup.getComicvineId());
if (!isLocked(metadata.getHardcoverIdLocked())) metadata.setHardcoverId(backup.getHardcoverId());
if (!isLocked(metadata.getGoogleIdLocked())) metadata.setGoogleId(backup.getGoogleId());
@@ -109,6 +109,7 @@ public class EpubMetadataExtractor implements FileMetadataExtractor {
else if (value.length() == 10) builderMeta.isbn10(value);
}
case "GOODREADS" -> builderMeta.goodreadsId(value);
case "COMICVINE" -> builderMeta.comicvineId(value);
case "GOOGLE" -> builderMeta.googleId(value);
case "AMAZON" -> builderMeta.asin(value);
case "HARDCOVER" -> builderMeta.hardcoverId(value);
@@ -148,6 +149,7 @@ public class EpubMetadataExtractor implements FileMetadataExtractor {
switch (prop) {
case "booklore:asin" -> builderMeta.asin(content);
case "booklore:goodreads_id" -> builderMeta.goodreadsId(content);
case "booklore:comicvine_id" -> builderMeta.comicvineId(content);
case "booklore:hardcover_id" -> builderMeta.hardcoverId(content);
case "booklore:google_books_id" -> builderMeta.googleId(content);
case "booklore:page_count" -> safeParseInt(content, builderMeta::pageCount);
@@ -165,6 +165,11 @@ public class PdfMetadataExtractor implements FileMetadataExtractor {
metadataBuilder.goodreadsId(goodreads);
}
String comicvine = identifiers.get("comicvine");
if (StringUtils.isNotBlank(comicvine)) {
metadataBuilder.comicvineId(comicvine);
}
String hardcover = identifiers.get("hardcover");
if (StringUtils.isNotBlank(hardcover)) {
metadataBuilder.hardcoverId(hardcover);
@@ -0,0 +1,201 @@
package com.adityachandel.booklore.service.metadata.parser;
import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.dto.BookMetadata;
import com.adityachandel.booklore.model.dto.request.FetchMetadataRequest;
import com.adityachandel.booklore.model.dto.response.comicvineapi.Comic;
import com.adityachandel.booklore.model.dto.response.comicvineapi.ComicvineApiResponse;
import com.adityachandel.booklore.model.enums.MetadataProvider;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import com.adityachandel.booklore.util.BookUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.util.UriComponentsBuilder;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;
@Slf4j
@Service
@RequiredArgsConstructor
public class ComicvineBookParser implements BookParser {
private static final String COMICVINE_URL = "https://comicvine.gamespot.com/api/";
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
private final ObjectMapper objectMapper;
private final AppSettingService appSettingService;
private final HttpClient httpClient = HttpClient.newHttpClient();
@Override
public List<BookMetadata> fetchMetadata(Book book, FetchMetadataRequest fetchMetadataRequest) {
String searchTerm = getSearchTerm(book, fetchMetadataRequest);
if (searchTerm == null) {
log.warn("No valid search term provided for metadata fetch.");
return Collections.emptyList();
}
return getMetadataListByTerm(searchTerm);
}
@Override
public BookMetadata fetchTopMetadata(Book book, FetchMetadataRequest fetchMetadataRequest) {
List<BookMetadata> metadataList = fetchMetadata(book, fetchMetadataRequest);
return metadataList.isEmpty() ? null : metadataList.getFirst();
}
public List<BookMetadata> getMetadataListByTerm(String term) {
String apiToken = getApiToken();
if (apiToken == null) return Collections.emptyList();
log.info("Comicvine: Fetching metadata for term: '{}'", term);
try {
String fieldsList = String.join(",", "api_detail_url", "cover_date", "description", "id", "image", "issue_number", "name", "publisher", "volume");
String resources = "volume,issue";
URI uri = UriComponentsBuilder.fromUriString(COMICVINE_URL)
.path("/search/")
.queryParam("api_key", apiToken)
.queryParam("format", "json")
.queryParam("resources", resources)
.queryParam("query", term)
.queryParam("limit", 10)
.queryParam("field_list", fieldsList)
.build()
.toUri();
HttpRequest request = HttpRequest.newBuilder()
.uri(uri)
.header("User-Agent", "Booklore/1.0")
.GET()
.build();
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == 200) {
return parseComicvineApiResponse(response.body());
} else {
log.error("Comicvine Search API returned status code {}", response.statusCode());
}
} catch (IOException | InterruptedException e) {
log.error("Error fetching metadata from Comicvine Search API", e);
}
return Collections.emptyList();
}
private String getSearchTerm(Book book, FetchMetadataRequest request) {
if (request.getTitle() != null && !request.getTitle().isEmpty()) {
return request.getTitle();
} else if (book.getFileName() != null && !book.getFileName().isEmpty()) {
return BookUtils.cleanFileName(book.getFileName());
}
return null;
}
private List<BookMetadata> parseComicvineApiResponse(String responseBody) throws IOException {
ComicvineApiResponse apiResponse = objectMapper.readValue(responseBody, ComicvineApiResponse.class);
if (apiResponse.getResults() == null) {
return Collections.emptyList();
}
return apiResponse.getResults().stream()
.map(this::convertToBookMetadata)
.collect(Collectors.toList());
}
private BookMetadata convertToBookMetadata(Comic comic) {
return BookMetadata.builder()
.provider(MetadataProvider.Comicvine)
.comicvineId(String.valueOf(comic.getId()))
.title(comic.getName())
.authors(new HashSet<>())
.thumbnailUrl(comic.getImage() != null ? comic.getImage().getMediumUrl() : null)
.description(comic.getDescription())
.seriesName(comic.getVolume() != null ? comic.getVolume().getName() : null)
.seriesNumber(safeParseFloat(comic.getIssueNumber()))
.publishedDate(safeParseDate(comic.getCoverDate()))
.build();
}
private static LocalDate safeParseDate(String dateStr) {
if (dateStr == null || dateStr.isEmpty()) return null;
try {
return LocalDate.parse(dateStr, DATE_FORMATTER);
} catch (DateTimeParseException e) {
log.warn("Invalid date '{}'", dateStr);
return null;
}
}
private static Float safeParseFloat(String numStr) {
if (numStr == null || numStr.isEmpty()) return null;
try {
return Float.valueOf(numStr);
} catch (NumberFormatException e) {
return null;
}
}
private String getApiToken() {
String apiToken = appSettingService.getAppSettings().getMetadataProviderSettings().getComicvine().getApiKey();
if (apiToken == null || apiToken.isEmpty()) {
log.warn("Comicvine API token not set");
return null;
}
return apiToken;
}
/*public Set<String> fetchAuthors(int issueId) {
String apiToken = getApiToken();
if (apiToken == null) return Collections.emptySet();
try {
String fieldsList = String.join(",", "person_credits");
URI uri = UriComponentsBuilder.fromUriString(COMICVINE_URL)
.path("/issue/4000-" + issueId + "/")
.queryParam("api_key", apiToken)
.queryParam("format", "json")
.queryParam("field_list", fieldsList)
.build()
.toUri();
HttpRequest request = HttpRequest.newBuilder()
.uri(uri)
.header("User-Agent", "Booklore/1.0")
.GET()
.build();
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == 200) {
ComicvineIssueResponse issueResponse = objectMapper.readValue(response.body(), ComicvineIssueResponse.class);
if (issueResponse.getResults() == null || issueResponse.getResults().getPersonCredits() == null) {
log.warn("No person credits found for issue ID {}", issueId);
return Collections.emptySet();
}
return issueResponse.getResults().getPersonCredits().stream()
.filter(pc -> pc.getRole() != null && pc.getRole().toLowerCase().contains("writer"))
.map(ComicvineIssueResponse.PersonCredit::getName)
.collect(Collectors.toSet());
} else {
log.error("Comicvine Issue API returned status code {}", response.statusCode());
}
} catch (IOException | InterruptedException e) {
log.error("Error fetching issue metadata from Comicvine Issue API", e);
}
return Collections.emptySet();
}*/
}
@@ -119,6 +119,7 @@ public class EpubMetadataWriter implements MetadataWriter {
boolean clearFlag = clear != null && switch (scheme) {
case "AMAZON" -> clear.isAsin();
case "GOOGLE" -> clear.isGoogleId();
case "COMICVINE" -> clear.isComicvineId();
case "GOODREADS" -> clear.isGoodreadsId();
case "HARDCOVER" -> clear.isHardcoverId();
case "ISBN" -> clear.isIsbn10();
@@ -135,6 +136,9 @@ public class EpubMetadataWriter implements MetadataWriter {
case "GOODREADS" -> helper.copyGoodreadsId(restoreMode, clearFlag, idValue -> {
updateIdentifier(metadataElement, opfDoc, scheme, idValue, hasChanges);
});
case "COMICVINE" -> helper.copyComicvineId(restoreMode, clearFlag, idValue -> {
updateIdentifier(metadataElement, opfDoc, scheme, idValue, hasChanges);
});
case "HARDCOVER" -> helper.copyHardcoverId(restoreMode, clearFlag, idValue -> {
updateIdentifier(metadataElement, opfDoc, scheme, idValue, hasChanges);
});
@@ -126,6 +126,13 @@ public class MetadataCopyHelper {
}
}
public void copyComicvineId(boolean restore, boolean clear, Consumer<String> consumer) {
if (!isLocked(metadata.getComicvineIdLocked())) {
if (clear) consumer.accept(null);
else if (metadata.getComicvineId() != null || restore) consumer.accept(metadata.getComicvineId());
}
}
public void copyHardcoverId(boolean restore, boolean clear, Consumer<String> consumer) {
if (!isLocked(metadata.getHardcoverIdLocked())) {
if (clear) consumer.accept(null);
@@ -151,6 +151,7 @@ public class PdfMetadataWriter implements MetadataWriter {
helper.copyGoogleId(restoreMode, clear != null && clear.isGoogleId(), id -> appendIdentifier(doc, rdfBag, "google", id != null ? id : ""));
helper.copyGoodreadsId(restoreMode, clear != null && clear.isGoodreadsId(), id -> appendIdentifier(doc, rdfBag, "goodreads", id != null ? id : ""));
helper.copyComicvineId(restoreMode, clear != null && clear.isComicvineId(), id -> appendIdentifier(doc, rdfBag, "comicvine", id != null ? id : ""));
helper.copyHardcoverId(restoreMode, clear != null && clear.isHardcoverId(), id -> appendIdentifier(doc, rdfBag, "hardcover", id != null ? id : ""));
helper.copyAsin(restoreMode, clear != null && clear.isAsin(), id -> appendIdentifier(doc, rdfBag, "amazon", id != null ? id : ""));
helper.copyIsbn13(restoreMode, clear != null && clear.isIsbn13(), id -> appendIdentifier(doc, rdfBag, "isbn", id != null ? id : ""));
@@ -9,6 +9,7 @@ import com.adityachandel.booklore.model.entity.*;
import com.adityachandel.booklore.model.enums.*;
import com.adityachandel.booklore.repository.LibraryRepository;
import com.adityachandel.booklore.repository.UserRepository;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import jakarta.transaction.Transactional;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@@ -28,6 +29,7 @@ public class UserProvisioningService {
private final LibraryRepository libraryRepository;
private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
private final UserDefaultsService userDefaultsService;
private final AppSettingService appSettingService;
public boolean isInitialUserAlreadyProvisioned() {
return userRepository.count() > 0;
@@ -107,7 +109,7 @@ public class UserProvisioningService {
perms.setPermissionEditMetadata(defaultPermissions.contains("permissionEditMetadata"));
perms.setPermissionManipulateLibrary(defaultPermissions.contains("permissionManipulateLibrary"));
perms.setPermissionEmailBook(defaultPermissions.contains("permissionEmailBook"));
perms.setPermissionDeleteBook(defaultPermissions.contains("permissionDeleteBooks"));
perms.setPermissionDeleteBook(defaultPermissions.contains("permissionDeleteBook"));
}
user.setPermissions(perms);
@@ -142,19 +144,37 @@ public class UserProvisioningService {
user.setProvisioningMethod(ProvisioningMethod.REMOTE);
user.setPasswordHash("RemoteUser_" + RandomStringUtils.secure().nextAlphanumeric(32));
OidcAutoProvisionDetails oidcAutoProvisionDetails = appSettingService.getAppSettings().getOidcAutoProvisionDetails();
UserPermissionsEntity permissions = new UserPermissionsEntity();
permissions.setUser(user);
permissions.setPermissionUpload(true);
permissions.setPermissionDownload(true);
permissions.setPermissionEditMetadata(true);
permissions.setPermissionEmailBook(true);
permissions.setPermissionDeleteBook(true);
if (oidcAutoProvisionDetails != null && oidcAutoProvisionDetails.getDefaultPermissions() != null) {
List<String> defaultPermissions = oidcAutoProvisionDetails.getDefaultPermissions();
permissions.setPermissionUpload(defaultPermissions.contains("permissionUpload"));
permissions.setPermissionDownload(defaultPermissions.contains("permissionDownload"));
permissions.setPermissionEditMetadata(defaultPermissions.contains("permissionEditMetadata"));
permissions.setPermissionManipulateLibrary(defaultPermissions.contains("permissionManipulateLibrary"));
permissions.setPermissionEmailBook(defaultPermissions.contains("permissionEmailBook"));
permissions.setPermissionDeleteBook(defaultPermissions.contains("permissionDeleteBook"));
} else {
permissions.setPermissionUpload(true);
permissions.setPermissionDownload(true);
permissions.setPermissionEditMetadata(true);
permissions.setPermissionManipulateLibrary(false);
permissions.setPermissionEmailBook(true);
permissions.setPermissionDeleteBook(true);
}
permissions.setPermissionAdmin(isAdmin);
user.setPermissions(permissions);
if (isAdmin) {
List<LibraryEntity> libraries = libraryRepository.findAll();
user.setLibraries(new ArrayList<>(libraries));
} else if (oidcAutoProvisionDetails != null && oidcAutoProvisionDetails.getDefaultLibraryIds() != null && !oidcAutoProvisionDetails.getDefaultLibraryIds().isEmpty()) {
List<LibraryEntity> libraries = libraryRepository.findAllById(oidcAutoProvisionDetails.getDefaultLibraryIds());
user.setLibraries(new ArrayList<>(libraries));
}
return createUser(user);
@@ -166,4 +186,4 @@ public class UserProvisioningService {
userDefaultsService.addDefaultSettings(user);
return user;
}
}
}
@@ -31,6 +31,7 @@ public class MetadataChangeDetector {
compare(changes, "isbn10", clear.isIsbn10(), newMeta.getIsbn10(), existingMeta.getIsbn10(), () -> !isTrue(existingMeta.getIsbn10Locked()), newMeta.getIsbn10Locked(), existingMeta.getIsbn10Locked());
compare(changes, "asin", clear.isAsin(), newMeta.getAsin(), existingMeta.getAsin(), () -> !isTrue(existingMeta.getAsinLocked()), newMeta.getAsinLocked(), existingMeta.getAsinLocked());
compare(changes, "goodreadsId", clear.isGoodreadsId(), newMeta.getGoodreadsId(), existingMeta.getGoodreadsId(), () -> !isTrue(existingMeta.getGoodreadsIdLocked()), newMeta.getGoodreadsIdLocked(), existingMeta.getGoodreadsIdLocked());
compare(changes, "comicvineId", clear.isComicvineId(), newMeta.getComicvineId(), existingMeta.getComicvineId(), () -> !isTrue(existingMeta.getComicvineIdLocked()), newMeta.getComicvineIdLocked(), existingMeta.getComicvineIdLocked());
compare(changes, "hardcoverId", clear.isHardcoverId(), newMeta.getHardcoverId(), existingMeta.getHardcoverId(), () -> !isTrue(existingMeta.getHardcoverIdLocked()), newMeta.getHardcoverIdLocked(), existingMeta.getHardcoverIdLocked());
compare(changes, "googleId", clear.isGoogleId(), newMeta.getGoogleId(), existingMeta.getGoogleId(), () -> !isTrue(existingMeta.getGoogleIdLocked()), newMeta.getGoogleIdLocked(), existingMeta.getGoogleIdLocked());
compare(changes, "pageCount", clear.isPageCount(), newMeta.getPageCount(), existingMeta.getPageCount(), () -> !isTrue(existingMeta.getPageCountLocked()), newMeta.getPageCountLocked(), existingMeta.getPageCountLocked());
@@ -0,0 +1,3 @@
ALTER TABLE `user_book_progress`
ADD COLUMN `date_finished` timestamp NULL DEFAULT NULL,
ADD INDEX `idx_user_book_progress_date_finished` (`date_finished`);
@@ -0,0 +1,3 @@
ALTER TABLE book_metadata
ADD COLUMN comicvine_id VARCHAR(100),
ADD COLUMN comicvine_id_locked BOOLEAN DEFAULT FALSE;
@@ -1,121 +0,0 @@
package com.adityachandel.booklore.service;
import com.adityachandel.booklore.config.AppProperties;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.repository.BookdropFileRepository;
import com.adityachandel.booklore.repository.LibraryRepository;
import com.adityachandel.booklore.service.bookdrop.BookDropService;
import com.adityachandel.booklore.service.bookdrop.BookdropNotificationService;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry;
import com.adityachandel.booklore.service.metadata.MetadataRefreshService;
import com.adityachandel.booklore.service.bookdrop.BookdropMonitoringService;
import com.adityachandel.booklore.service.monitoring.MonitoringService;
import com.adityachandel.booklore.service.NotificationService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.core.io.PathResource;
import org.springframework.core.io.Resource;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.*;
class BookDropServiceTest {
private BookdropFileRepository bookdropFileRepository;
private LibraryRepository libraryRepository;
private BookRepository bookRepository;
private MonitoringService monitoringService;
private BookdropMonitoringService bookdropMonitoringService;
private NotificationService notificationService;
private MetadataRefreshService metadataRefreshService;
private BookdropNotificationService bookdropNotificationService;
private AppProperties appProperties;
private BookDropService bookDropService;
@BeforeEach
void setUp() {
bookdropFileRepository = mock(BookdropFileRepository.class);
libraryRepository = mock(LibraryRepository.class);
bookRepository = mock(BookRepository.class);
monitoringService = mock(MonitoringService.class);
bookdropMonitoringService = mock(BookdropMonitoringService.class);
notificationService = mock(NotificationService.class);
metadataRefreshService = mock(MetadataRefreshService.class);
bookdropNotificationService = mock(BookdropNotificationService.class);
BookFileProcessorRegistry processorRegistry = mock(BookFileProcessorRegistry.class);
appProperties = mock(AppProperties.class);
bookDropService = new BookDropService(
bookdropFileRepository, libraryRepository, bookRepository,
monitoringService, bookdropMonitoringService,
notificationService, metadataRefreshService,
bookdropNotificationService,
processorRegistry,
appProperties
);
}
@Test
void discardAllFiles_shouldDeleteFilesDirsAndNotify() throws Exception {
Path bookdropPath = Paths.get("/tmp/bookdrop");
when(appProperties.getBookdropFolder()).thenReturn(bookdropPath.toString());
Files.createDirectories(bookdropPath);
Path testFile = bookdropPath.resolve("testfile.txt");
Files.createFile(testFile);
when(bookdropFileRepository.count()).thenReturn(1L);
Path tempCoverDir = Paths.get("/tmp/config/bookdrop_temp");
when(appProperties.getPathConfig()).thenReturn("/tmp/config");
Files.createDirectories(tempCoverDir);
Path tempCover = tempCoverDir.resolve("1.jpg");
Files.createFile(tempCover);
bookDropService.discardAllFiles();
verify(bookdropFileRepository).deleteAll();
verify(bookdropNotificationService).sendBookdropFileSummaryNotification();
verify(bookdropMonitoringService).pauseMonitoring();
verify(bookdropMonitoringService).resumeMonitoring();
Files.deleteIfExists(testFile);
Files.deleteIfExists(bookdropPath);
Files.deleteIfExists(tempCover);
Files.deleteIfExists(tempCoverDir);
}
@Test
void getBookdropCover_shouldReturnResourceIfExists() throws Exception {
when(appProperties.getPathConfig()).thenReturn("/tmp/config");
long bookdropId = 123L;
Path coverPath = Paths.get("/tmp/config/bookdrop_temp", bookdropId + ".jpg");
File coverFile = coverPath.toFile();
coverFile.getParentFile().mkdirs();
coverFile.createNewFile();
Resource resource = bookDropService.getBookdropCover(bookdropId);
assertThat(resource).isInstanceOf(PathResource.class);
assertThat(resource.getFilename()).isEqualTo(bookdropId + ".jpg");
coverFile.delete();
}
@Test
void getBookdropCover_shouldReturnNullIfNotExists() {
when(appProperties.getPathConfig()).thenReturn("/tmp/config");
long bookdropId = 99999L;
Resource resource = bookDropService.getBookdropCover(bookdropId);
assertThat(resource).isNull();
}
}
+2965 -2357
View File
File diff suppressed because it is too large Load Diff
@@ -193,6 +193,8 @@ export class BookRuleEvaluatorService {
return book.metadata?.publisher?.toLowerCase() ?? null;
case 'publishedDate':
return book.metadata?.publishedDate ? new Date(book.metadata.publishedDate) : null;
case 'dateFinished':
return book.dateFinished ? new Date(book.dateFinished) : null;
case 'seriesName':
return book.metadata?.seriesName?.toLowerCase() ?? null;
case 'seriesNumber':
@@ -81,59 +81,26 @@ const SORT_DIRECTION = {
standalone: true,
templateUrl: './book-browser.component.html',
styleUrls: ['./book-browser.component.scss'],
imports: [Button, VirtualScrollerModule, BookCardComponent, AsyncPipe, ProgressSpinner, Menu, InputText, FormsModule, BookTableComponent, BookFilterComponent, Tooltip, NgClass, PrimeTemplate, NgStyle, OverlayPanelModule, DropdownModule, Checkbox, Popover, Slider, Select, Divider, MultiSelect, TieredMenu],
imports: [
Button, VirtualScrollerModule, BookCardComponent, AsyncPipe, ProgressSpinner, Menu, InputText, FormsModule,
BookTableComponent, BookFilterComponent, Tooltip, NgClass, PrimeTemplate, NgStyle, OverlayPanelModule,
DropdownModule, Checkbox, Popover, Slider, Select, Divider, MultiSelect, TieredMenu
],
providers: [SeriesCollapseFilter],
animations: [
trigger('slideInOut', [
state('void', style({
transform: 'translateY(100%)'
})),
state('*', style({
transform: 'translateY(0)'
})),
transition(':enter', [
animate('0.1s ease-in')
]),
transition(':leave', [
animate('0.1s ease-out')
])
state('void', style({ transform: 'translateY(100%)' })),
state('*', style({ transform: 'translateY(0)' })),
transition(':enter', [ animate('0.1s ease-in') ]),
transition(':leave', [ animate('0.1s ease-out') ])
])
]
})
export class BookBrowserComponent implements OnInit, AfterViewInit {
bookState$: Observable<BookState> | undefined;
entity$: Observable<Library | Shelf | MagicShelf | null> | undefined;
entityType$: Observable<EntityType> | undefined;
searchTerm$ = new BehaviorSubject<string>('');
entity: Library | Shelf | MagicShelf | null = null;
entityType: EntityType | undefined;
bookTitle: string = '';
entityOptions: MenuItem[] | undefined;
selectedBooks = new Set<number>();
isDrawerVisible: boolean = false;
dynamicDialogRef: DynamicDialogRef | undefined;
EntityType = EntityType;
currentFilterLabel: string | null = null;
rawFilterParamFromUrl: string | null = null;
hasSearchTerm: boolean = false;
@ViewChild(BookTableComponent) bookTableComponent!: BookTableComponent;
@ViewChild(BookFilterComponent) bookFilterComponent!: BookFilterComponent;
visibleColumns: { field: string; header: string }[] = [];
selectedFilter = new BehaviorSubject<Record<string, any> | null>(null);
selectedFilterMode = new BehaviorSubject<'and' | 'or'>('and');
protected resetFilterSubject = new Subject<void>();
entityViewPreferences!: EntityViewPreferences;
protected userService = inject(UserService);
protected coverScalePreferenceService = inject(CoverScalePreferenceService);
protected filterSortPreferenceService = inject(FilterSortPreferenceService);
protected columnPreferenceService = inject(TableColumnPreferenceService);
private activatedRoute = inject(ActivatedRoute);
private messageService = inject(MessageService);
private libraryService = inject(LibraryService);
@@ -150,47 +117,53 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
protected magicShelfService = inject(MagicShelfService);
protected bookRuleEvaluatorService = inject(BookRuleEvaluatorService);
private sideBarFilter = new SideBarFilter(this.selectedFilter, this.selectedFilterMode);
private headerFilter = new HeaderFilter(this.searchTerm$);
protected bookSorter = new BookSorter((selectedSort) => this.applySortOption(selectedSort));
currentViewMode: string | undefined = undefined;
bookState$: Observable<BookState> | undefined;
entity$: Observable<Library | Shelf | MagicShelf | null> | undefined;
entityType$: Observable<EntityType> | undefined;
searchTerm$ = new BehaviorSubject<string>('');
selectedFilter = new BehaviorSubject<Record<string, any> | null>(null);
selectedFilterMode = new BehaviorSubject<'and' | 'or'>('and');
protected resetFilterSubject = new Subject<void>();
entity: Library | Shelf | MagicShelf | null = null;
entityType: EntityType | undefined;
bookTitle = '';
entityOptions: MenuItem[] | undefined;
selectedBooks = new Set<number>();
isDrawerVisible = false;
dynamicDialogRef: DynamicDialogRef | undefined;
EntityType = EntityType;
currentFilterLabel: string | null = null;
rawFilterParamFromUrl: string | null = null;
hasSearchTerm = false;
visibleColumns: { field: string; header: string }[] = [];
entityViewPreferences!: EntityViewPreferences;
currentViewMode: string | undefined;
lastAppliedSort: SortOption | null = null;
private settingFiltersFromUrl = false;
protected metadataMenuItems: MenuItem[] | undefined;
protected tieredMenuItems: MenuItem[] | undefined;
currentBooks: Book[] = [];
lastSelectedIndex: number | null = null;
showFilter: boolean = false;
showFilter = false;
private sideBarFilter = new SideBarFilter(this.selectedFilter, this.selectedFilterMode);
private headerFilter = new HeaderFilter(this.searchTerm$);
protected bookSorter = new BookSorter(selectedSort => this.applySortOption(selectedSort));
get currentCardSize() {
return this.coverScalePreferenceService.currentCardSize;
}
@ViewChild(BookTableComponent) bookTableComponent!: BookTableComponent;
@ViewChild(BookFilterComponent) bookFilterComponent!: BookFilterComponent;
get gridColumnMinWidth(): string {
return this.coverScalePreferenceService.gridColumnMinWidth;
}
updateScale(): void {
this.coverScalePreferenceService.setScale(this.coverScalePreferenceService.scaleFactor);
}
onVisibleColumnsChange(selected: any[]) {
const allFields = this.bookTableComponent.allColumns.map(col => col.field);
this.visibleColumns = selected.sort(
(a, b) => allFields.indexOf(a.field) - allFields.indexOf(b.field)
);
}
get currentCardSize() { return this.coverScalePreferenceService.currentCardSize; }
get gridColumnMinWidth(): string { return this.coverScalePreferenceService.gridColumnMinWidth; }
get viewIcon(): string { return this.currentViewMode === VIEW_MODES.GRID ? 'pi pi-objects-column' : 'pi pi-table'; }
get hasSidebarFilters(): boolean { return !!this.selectedFilter.value && Object.keys(this.selectedFilter.value).length > 0; }
get isFilterActive(): boolean { return this.selectedFilter.value !== null; }
ngOnInit(): void {
this.coverScalePreferenceService.scaleChange$.pipe(debounceTime(1000)).subscribe();
this.bookService.loadBooks();
const currentPath = this.activatedRoute.snapshot.routeConfig?.path;
if (currentPath === 'all-books' || currentPath === 'unshelved-books') {
const entityType = currentPath === 'all-books' ? EntityType.ALL_BOOKS : EntityType.UNSHELVED;
this.entityType = entityType;
@@ -198,12 +171,10 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
this.entity$ = of(null);
} else {
const routeEntityInfo$ = this.getEntityInfoFromRoute();
this.entityType$ = routeEntityInfo$.pipe(map(info => info.entityType));
this.entity$ = routeEntityInfo$.pipe(
switchMap(({entityId, entityType}) => this.fetchEntity(entityId, entityType))
);
this.entity$.subscribe(entity => {
this.entity = entity ?? null;
this.entityOptions = entity
@@ -228,12 +199,10 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
() => this.bulkEditMetadata(),
() => this.multiBookEditMetadata()
);
this.tieredMenuItems = this.bookMenuService.getTieredMenuItems(this.selectedBooks);
}
ngAfterViewInit() {
ngAfterViewInit(): void {
combineLatest({
paramMap: this.activatedRoute.queryParamMap,
user: this.userService.userState$.pipe(
@@ -378,172 +347,14 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
});
}
private isLibrary(entity: Library | Shelf | MagicShelf): entity is Library {
return (entity as Library).paths !== undefined;
updateScale(): void {
this.coverScalePreferenceService.setScale(this.coverScalePreferenceService.scaleFactor);
}
private isMagicShelf(entity: any): entity is MagicShelf {
return entity && 'filterJson' in entity;
}
get viewIcon(): string {
return this.currentViewMode === VIEW_MODES.GRID ? 'pi pi-objects-column' : 'pi pi-table';
}
private getEntityInfoFromRoute(): Observable<{ entityId: number; entityType: EntityType }> {
return this.activatedRoute.paramMap.pipe(
map(params => {
const libraryId = Number(params.get('libraryId') || NaN);
const shelfId = Number(params.get('shelfId') || NaN);
const magicShelfId = Number(params.get('magicShelfId') || NaN);
if (!isNaN(libraryId)) {
this.entityType = EntityType.LIBRARY;
return {entityId: libraryId, entityType: EntityType.LIBRARY};
} else if (!isNaN(shelfId)) {
this.entityType = EntityType.SHELF;
return {entityId: shelfId, entityType: EntityType.SHELF};
} else if (!isNaN(magicShelfId)) {
this.entityType = EntityType.MAGIC_SHELF;
return {entityId: magicShelfId, entityType: EntityType.MAGIC_SHELF};
} else {
this.entityType = EntityType.ALL_BOOKS;
return {entityId: NaN, entityType: EntityType.ALL_BOOKS};
}
})
);
}
private fetchEntity(entityId: number, entityType: EntityType): Observable<Library | Shelf | MagicShelf | null> {
switch (entityType) {
case EntityType.LIBRARY:
return this.fetchLibrary(entityId);
case EntityType.SHELF:
return this.fetchShelf(entityId);
case EntityType.MAGIC_SHELF:
return this.fetchMagicShelf(entityId);
default:
return of(null);
}
}
private fetchBooksByEntity(entityId: number, entityType: EntityType): Observable<BookState> {
switch (entityType) {
case EntityType.LIBRARY:
return this.fetchBooks(book => book.libraryId === entityId);
case EntityType.SHELF:
return this.fetchBooks(book =>
book.shelves?.some(shelf => shelf.id === entityId) ?? false
);
case EntityType.MAGIC_SHELF:
return this.fetchBooksMagicShelfBooks(entityId);
case EntityType.ALL_BOOKS:
default:
return this.fetchAllBooks();
}
}
private fetchAllBooks(): Observable<BookState> {
return this.bookService.bookState$.pipe(
map(bookState => this.processBookState(bookState)),
switchMap(bookState => this.applyBookFilters(bookState))
);
}
private fetchUnshelvedBooks(): Observable<BookState> {
return this.bookService.bookState$.pipe(
map(bookState => ({
...bookState,
books: (bookState.books || []).filter(book => !book.shelves || book.shelves.length === 0)
})),
map(bookState => this.processBookState(bookState)),
switchMap(bookState => this.applyBookFilters(bookState))
);
}
private fetchBooksMagicShelfBooks(magicShelfId: number): Observable<BookState> {
return combineLatest([
this.bookService.bookState$,
this.magicShelfService.getShelf(magicShelfId)
]).pipe(
map(([bookState, magicShelf]) => {
if (!bookState.loaded || bookState.error || !magicShelf?.filterJson) {
return bookState;
}
const filteredBooks: Book[] | undefined = bookState.books?.filter(book =>
this.bookRuleEvaluatorService.evaluateGroup(book, JSON.parse(magicShelf.filterJson!) as GroupRule)
);
const sortedBooks = this.sortService.applySort(filteredBooks ?? [], this.bookSorter.selectedSort!);
return {...bookState, books: sortedBooks};
}),
switchMap(bookState => this.applyBookFilters(bookState))
);
}
private fetchBooks(bookFilter: (book: Book) => boolean): Observable<BookState> {
return this.bookService.bookState$.pipe(
map(bookState => {
if (bookState.loaded && !bookState.error) {
const filteredBooks = bookState.books?.filter(bookFilter) || [];
const sortedBooks = this.sortService.applySort(filteredBooks, this.bookSorter.selectedSort!);
return {...bookState, books: sortedBooks};
}
return bookState;
}),
switchMap(bookState => this.applyBookFilters(bookState))
);
}
private applyBookFilters(bookState: BookState): Observable<BookState> {
return this.headerFilter.filter(bookState).pipe(
switchMap(filtered => this.sideBarFilter.filter(filtered)),
switchMap(filtered => this.seriesCollapseFilter.filter(filtered))
);
}
private processBookState(bookState: BookState): BookState {
if (bookState.loaded && !bookState.error) {
const sortedBooks = this.sortService.applySort(bookState.books || [], this.bookSorter.selectedSort!);
return {...bookState, books: sortedBooks};
}
return bookState;
}
private fetchLibrary(libraryId: number): Observable<Library | null> {
return this.libraryService.libraryState$.pipe(
map(libraryState => {
if (libraryState.libraries) {
return libraryState.libraries.find(lib => lib.id === libraryId) || null;
}
return null;
})
);
}
private fetchShelf(shelfId: number): Observable<Shelf | null> {
return this.shelfService.shelfState$.pipe(
map(shelfState => {
if (shelfState.shelves) {
return shelfState.shelves.find(shelf => shelf.id === shelfId) || null;
}
return null;
})
);
}
private fetchMagicShelf(magicShelfId: number): Observable<MagicShelf | null> {
return this.magicShelfService.shelvesState$.pipe(
take(1),
switchMap((state) => {
const cached = state.shelves?.find(s => s.id === magicShelfId) ?? null;
if (cached) {
return of(cached);
}
return this.magicShelfService.getShelf(magicShelfId).pipe(
map(shelf => shelf ?? null),
catchError(() => of(null))
);
})
onVisibleColumnsChange(selected: any[]) {
const allFields = this.bookTableComponent.allColumns.map(col => col.field);
this.visibleColumns = selected.sort(
(a, b) => allFields.indexOf(a.field) - allFields.indexOf(b.field)
);
}
@@ -659,14 +470,6 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
this.resetFilterSubject.next();
}
get hasSidebarFilters(): boolean {
return this.selectedFilter && Object.keys(this.selectedFilter.getValue() || {}).length > 0;
}
get isFilterActive(): boolean {
return this.selectedFilter.value !== null;
}
clearFilter() {
if (this.selectedFilter.value !== null) {
this.selectedFilter.next(null);
@@ -674,10 +477,6 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
this.clearSearch();
}
private capitalize(str: string): string {
return str.charAt(0).toUpperCase() + str.slice(1);
}
toggleFilterSidebar() {
this.showFilter = !this.showFilter;
this.router.navigate([], {
@@ -740,4 +539,184 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
moveFiles() {
this.dialogHelperService.openFileMoverDialog(this.selectedBooks);
}
private isLibrary(entity: Library | Shelf | MagicShelf): entity is Library {
return (entity as Library).paths !== undefined;
}
private isMagicShelf(entity: any): entity is MagicShelf {
return entity && 'filterJson' in entity;
}
private getEntityInfoFromRoute(): Observable<{ entityId: number; entityType: EntityType }> {
return this.activatedRoute.paramMap.pipe(
map(params => {
const libraryId = Number(params.get('libraryId') || NaN);
const shelfId = Number(params.get('shelfId') || NaN);
const magicShelfId = Number(params.get('magicShelfId') || NaN);
if (!isNaN(libraryId)) {
this.entityType = EntityType.LIBRARY;
return {entityId: libraryId, entityType: EntityType.LIBRARY};
} else if (!isNaN(shelfId)) {
this.entityType = EntityType.SHELF;
return {entityId: shelfId, entityType: EntityType.SHELF};
} else if (!isNaN(magicShelfId)) {
this.entityType = EntityType.MAGIC_SHELF;
return {entityId: magicShelfId, entityType: EntityType.MAGIC_SHELF};
} else {
this.entityType = EntityType.ALL_BOOKS;
return {entityId: NaN, entityType: EntityType.ALL_BOOKS};
}
})
);
}
private fetchEntity(entityId: number, entityType: EntityType): Observable<Library | Shelf | MagicShelf | null> {
switch (entityType) {
case EntityType.LIBRARY:
return this.fetchLibrary(entityId);
case EntityType.SHELF:
return this.fetchShelf(entityId);
case EntityType.MAGIC_SHELF:
return this.fetchMagicShelf(entityId);
default:
return of(null);
}
}
private fetchBooksByEntity(entityId: number, entityType: EntityType): Observable<BookState> {
switch (entityType) {
case EntityType.LIBRARY:
return this.fetchBooks(book => book.libraryId === entityId);
case EntityType.SHELF:
return this.fetchBooks(book =>
book.shelves?.some(shelf => shelf.id === entityId) ?? false
);
case EntityType.MAGIC_SHELF:
return this.fetchBooksMagicShelfBooks(entityId);
case EntityType.ALL_BOOKS:
default:
return this.fetchAllBooks();
}
}
private fetchAllBooks(): Observable<BookState> {
return this.bookService.bookState$.pipe(
map(bookState => this.processBookState(bookState)),
switchMap(bookState => this.applyBookFilters(bookState))
);
}
private fetchUnshelvedBooks(): Observable<BookState> {
return this.bookService.bookState$.pipe(
map(bookState => ({
...bookState,
books: (bookState.books || []).filter(book => !book.shelves || book.shelves.length === 0)
})),
map(bookState => this.processBookState(bookState)),
switchMap(bookState => this.applyBookFilters(bookState))
);
}
private fetchBooksMagicShelfBooks(magicShelfId: number): Observable<BookState> {
return combineLatest([
this.bookService.bookState$,
this.magicShelfService.getShelf(magicShelfId)
]).pipe(
map(([bookState, magicShelf]) => {
if (!bookState.loaded || bookState.error || !magicShelf?.filterJson) {
return bookState;
}
const filteredBooks: Book[] | undefined = bookState.books?.filter(book =>
this.bookRuleEvaluatorService.evaluateGroup(book, JSON.parse(magicShelf.filterJson!) as GroupRule)
);
const sortedBooks = this.sortService.applySort(filteredBooks ?? [], this.bookSorter.selectedSort!);
return {...bookState, books: sortedBooks};
}),
switchMap(bookState => this.applyBookFilters(bookState))
);
}
private fetchBooks(bookFilter: (book: Book) => boolean): Observable<BookState> {
return this.bookService.bookState$.pipe(
map(bookState => {
if (bookState.loaded && !bookState.error) {
const filteredBooks = bookState.books?.filter(bookFilter) || [];
const sortedBooks = this.sortService.applySort(filteredBooks, this.bookSorter.selectedSort!);
return {...bookState, books: sortedBooks};
}
return bookState;
}),
switchMap(bookState => this.applyBookFilters(bookState))
);
}
private shouldForceExpandSeries(): boolean {
const queryParams = this.activatedRoute.snapshot.queryParams;
const filterParam = queryParams[QUERY_PARAMS.FILTER];
return (
filterParam &&
typeof filterParam === 'string' &&
filterParam.split(',').some(pair => pair.trim().startsWith('series:'))
);
}
private applyBookFilters(bookState: BookState): Observable<BookState> {
const forceExpandSeries = this.shouldForceExpandSeries();
return this.headerFilter.filter(bookState).pipe(
switchMap(filtered => this.sideBarFilter.filter(filtered)),
switchMap(filtered => this.seriesCollapseFilter.filter(filtered, forceExpandSeries))
);
}
private processBookState(bookState: BookState): BookState {
if (bookState.loaded && !bookState.error) {
const sortedBooks = this.sortService.applySort(bookState.books || [], this.bookSorter.selectedSort!);
return {...bookState, books: sortedBooks};
}
return bookState;
}
private fetchLibrary(libraryId: number): Observable<Library | null> {
return this.libraryService.libraryState$.pipe(
map(libraryState => {
if (libraryState.libraries) {
return libraryState.libraries.find(lib => lib.id === libraryId) || null;
}
return null;
})
);
}
private fetchShelf(shelfId: number): Observable<Shelf | null> {
return this.shelfService.shelfState$.pipe(
map(shelfState => {
if (shelfState.shelves) {
return shelfState.shelves.find(shelf => shelf.id === shelfId) || null;
}
return null;
})
);
}
private fetchMagicShelf(magicShelfId: number): Observable<MagicShelf | null> {
return this.magicShelfService.shelvesState$.pipe(
take(1),
switchMap((state) => {
const cached = state.shelves?.find(s => s.id === magicShelfId) ?? null;
if (cached) {
return of(cached);
}
return this.magicShelfService.getShelf(magicShelfId).pipe(
map(shelf => shelf ?? null),
catchError(() => of(null))
);
})
);
}
private capitalize(str: string): string {
return str.charAt(0).toUpperCase() + str.slice(1);
}
}
@@ -44,10 +44,11 @@ export class SeriesCollapseFilter implements BookFilter {
this.seriesCollapseSubject.next(value);
}
filter(bookState: BookState): Observable<BookState> {
filter(bookState: BookState, forceExpandSeries?: boolean): Observable<BookState> {
return this.seriesCollapse$.pipe(
map(isCollapsed => {
if (!isCollapsed || !bookState.books) return bookState;
const shouldCollapse = forceExpandSeries ? false : isCollapsed;
if (!shouldCollapse || !bookState.books) return bookState;
const books = [...bookState.books];
@@ -32,7 +32,8 @@ export class LockUnlockMetadataDialogComponent implements OnInit {
'isbn13Locked', 'isbn10Locked', 'asinLocked', 'pageCountLocked', 'thumbnailLocked', 'languageLocked', 'coverLocked',
'seriesNameLocked', 'seriesNumberLocked', 'seriesTotalLocked', 'authorsLocked', 'categoriesLocked',
'amazonRatingLocked', 'amazonReviewCountLocked', 'goodreadsRatingLocked', 'goodreadsReviewCountLocked',
'hardcoverRatingLocked', 'hardcoverReviewCountLocked', 'goodreadsIdLocked', 'hardcoverIdLocked', 'googleIdLocked'
'hardcoverRatingLocked', 'hardcoverReviewCountLocked', 'goodreadsIdLocked', 'hardcoverIdLocked', 'googleIdLocked',
'comicvineIdLocked'
];
fieldLabels: Record<string, string> = {
@@ -62,6 +63,7 @@ export class LockUnlockMetadataDialogComponent implements OnInit {
goodreadsIdLocked: 'Goodreads ID',
hardcoverIdLocked: 'Hardcover ID',
googleIdLocked: 'Google ID',
comicvineIdLocked: 'Comicvine ID',
};
isSaving = false;
@@ -65,6 +65,9 @@
@if (backupMetadata.amazonReviewCount !== null) {
<div><strong>Amazon Review Count:</strong> {{ backupMetadata.amazonReviewCount }}</div>
}
@if (backupMetadata.comicvineId) {
<div><strong>Comicvine ID:</strong> {{ backupMetadata.comicvineId }}</div>
}
@if (backupMetadata.goodreadsId) {
<div><strong>Goodreads ID:</strong> {{ backupMetadata.goodreadsId }}</div>
}
@@ -9,7 +9,7 @@
<p-step-panel [value]="1">
<ng-template #content let-activateCallback="activateCallback">
<div class="flex flex-col justify-between w-full md:w-[40rem] max-w-[50rem] mx-auto">
<div class="flex flex-col justify-between w-full md:w-[45rem] max-w-[50rem] mx-auto">
<div class="flex-grow flex items-center justify-center">
<div class="grid grid-cols-[auto,1fr] gap-x-6 gap-y-10 border border-[var(--border-color)] p-6 rounded-xl w-full">
@@ -46,7 +46,6 @@
tooltipPosition="right"></i>
</div>
</div>
<app-icon-picker (iconSelected)="onIconSelected($event)"></app-icon-picker>
</div>
<div class="flex justify-end pt-6">
@@ -63,7 +62,7 @@
<p-step-panel [value]="2">
<ng-template #content let-activateCallback="activateCallback">
<div class="flex flex-col justify-between w-[24rem] md:w-[40rem] max-w-[50rem] mx-auto">
<div class="flex flex-col justify-between w-[24rem] md:w-[45rem] max-w-[50rem] mx-auto">
<div class="flex-grow flex items-center justify-center">
<div class="flex flex-col gap-6 border border-[var(--border-color)] px-2 py-4 md:p-6 rounded-xl w-full">
@@ -1,10 +1,9 @@
import {Component, inject, OnInit, ViewChild} from '@angular/core';
import {Component, inject, OnInit} from '@angular/core';
import {DialogService, DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
import {DirectoryPickerComponent} from '../../../utilities/component/directory-picker/directory-picker.component';
import {MessageService} from 'primeng/api';
import {Router} from '@angular/router';
import {LibraryService} from '../../service/library.service';
import {IconPickerComponent} from '../../../utilities/component/icon-picker/icon-picker.component';
import {Button} from 'primeng/button';
import {TableModule} from 'primeng/table';
import {Step, StepList, StepPanel, StepPanels, Stepper} from 'primeng/stepper';
@@ -13,18 +12,16 @@ import {InputText} from 'primeng/inputtext';
import {Library} from '../../model/library.model';
import {ToggleSwitch} from 'primeng/toggleswitch';
import {Tooltip} from 'primeng/tooltip';
import { IconPickerService } from '../../../utilities/services/icon-picker.service';
@Component({
selector: 'app-library-creator',
standalone: true,
templateUrl: './library-creator.component.html',
imports: [Button, TableModule, StepPanel, IconPickerComponent, FormsModule, InputText, Stepper, StepList, Step, StepPanels, ToggleSwitch, Tooltip],
imports: [Button, TableModule, StepPanel, FormsModule, InputText, Stepper, StepList, Step, StepPanels, ToggleSwitch, Tooltip],
styleUrl: './library-creator.component.scss'
})
export class LibraryCreatorComponent implements OnInit {
@ViewChild(IconPickerComponent) iconPicker: IconPickerComponent | undefined;
chosenLibraryName: string = '';
folders: string[] = [];
selectedIcon: string | null = null;
@@ -35,13 +32,13 @@ export class LibraryCreatorComponent implements OnInit {
directoryPickerDialogRef!: DynamicDialogRef<DirectoryPickerComponent>;
watch: boolean = false;
private dialogService = inject(DialogService);
private dynamicDialogRef = inject(DynamicDialogRef);
private dialogService = inject(DialogService);
private dynamicDialogRef = inject(DynamicDialogRef);
private dynamicDialogConfig = inject(DynamicDialogConfig);
private libraryService = inject(LibraryService);
private messageService = inject(MessageService);
private router = inject(Router);
private libraryService = inject(LibraryService);
private messageService = inject(MessageService);
private router = inject(Router);
private iconPicker = inject(IconPickerService);
ngOnInit(): void {
const data = this.dynamicDialogConfig?.data;
@@ -59,7 +56,7 @@ export class LibraryCreatorComponent implements OnInit {
}
}
openDirectoryPicker() {
openDirectoryPicker(): void {
this.directoryPickerDialogRef = this.dialogService.open(DirectoryPickerComponent, {
header: 'Select Media Directory',
modal: true,
@@ -74,6 +71,14 @@ export class LibraryCreatorComponent implements OnInit {
});
}
openIconPicker(): void {
this.iconPicker.open().subscribe(icon => {
if (icon) {
this.selectedIcon = icon;
}
});
}
addFolder(folder: string): void {
this.folders.push(folder);
}
@@ -82,17 +87,7 @@ export class LibraryCreatorComponent implements OnInit {
this.folders.splice(index, 1);
}
openIconPicker() {
if (this.iconPicker) {
this.iconPicker.open();
}
}
onIconSelected(icon: string) {
this.selectedIcon = icon;
}
clearSelectedIcon() {
clearSelectedIcon(): void {
this.selectedIcon = null;
}
@@ -104,7 +99,25 @@ export class LibraryCreatorComponent implements OnInit {
return this.folders.length > 0;
}
createOrUpdateLibrary() {
validateLibraryNameAndProceed(activateCallback: Function): void {
let trimmedLibraryName = this.chosenLibraryName.trim();
if (trimmedLibraryName && trimmedLibraryName != this.editModeLibraryName) {
let exists = this.libraryService.doesLibraryExistByName(trimmedLibraryName);
if (exists) {
this.messageService.add({
severity: 'error',
summary: 'Library Name Exists',
detail: 'This library name is already taken.',
});
} else {
activateCallback(2);
}
} else {
activateCallback(2);
}
}
createOrUpdateLibrary(): void {
if (this.mode === 'edit') {
const library: Library = {
name: this.chosenLibraryName,
@@ -142,23 +155,4 @@ export class LibraryCreatorComponent implements OnInit {
});
}
}
validateLibraryNameAndProceed(activateCallback: Function) {
let trimmedLibraryName = this.chosenLibraryName.trim();
if (trimmedLibraryName && trimmedLibraryName != this.editModeLibraryName) {
let exists = this.libraryService.doesLibraryExistByName(trimmedLibraryName);
if (exists) {
this.messageService.add({
severity: 'error',
summary: 'Library Name Exists',
detail: 'This library name is already taken.',
});
} else {
activateCallback(2);
}
} else {
activateCallback(2);
}
}
}
@@ -1,7 +1,7 @@
<div class="p-4 min-w-[26rem] min-h-[30rem] flex flex-col">
<div class="flex flex-col flex-grow">
<!-- Dynamic shelves content -->
@for (shelf of (shelfState$ | async)?.shelves; track shelf) {
<div>
<div class="flex flex-row items-center gap-4 py-2">
@@ -11,7 +11,6 @@
</div>
}
<!-- Button section, anchored to the bottom -->
<div class="flex justify-between items-center pt-4 mt-auto">
<p-button outlined="true" label="Create Shelf" (onClick)="createShelfDialog()"></p-button>
<div class="flex gap-4">
@@ -21,10 +20,6 @@
</div>
</div>
<!-- Icon picker component -->
<app-icon-picker (iconSelected)="onIconSelected($event)"></app-icon-picker>
<!-- Shelf dialog component -->
<p-dialog [style]="{ width: '26rem', height: '30rem' }" [(visible)]="displayShelfDialog" header="Create Shelf" [modal]="true" [draggable]="false" [closable]="true" (onHide)="closeShelfDialog()">
<div class="py-2">
<label for="shelfName">Shelf Name</label>
@@ -1,5 +1,5 @@
import {Component, inject, OnInit, ViewChild} from '@angular/core';
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
import {Component, inject, OnInit} from '@angular/core';
import {DialogService, DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
import {Book} from '../../model/book.model';
import {MessageService, PrimeTemplate} from 'primeng/api';
import {ShelfService} from '../../service/shelf.service';
@@ -7,14 +7,14 @@ import {Observable} from 'rxjs';
import {BookService} from '../../service/book.service';
import {map, tap} from 'rxjs/operators';
import {Shelf} from '../../model/shelf.model';
import {IconPickerComponent} from '../../../utilities/component/icon-picker/icon-picker.component';
import {ShelfState} from '../../model/state/shelf-state.model';
import {Button} from 'primeng/button';
import { AsyncPipe } from '@angular/common';
import {AsyncPipe} from '@angular/common';
import {Checkbox} from 'primeng/checkbox';
import {FormsModule} from '@angular/forms';
import {Dialog} from 'primeng/dialog';
import {InputText} from 'primeng/inputtext';
import {IconPickerService} from '../../../utilities/services/icon-picker.service';
@Component({
selector: 'app-shelf-assigner',
@@ -25,7 +25,6 @@ import {InputText} from 'primeng/inputtext';
Checkbox,
AsyncPipe,
FormsModule,
IconPickerComponent,
Dialog,
InputText,
PrimeTemplate
@@ -39,6 +38,7 @@ export class ShelfAssignerComponent implements OnInit {
private dynamicDialogRef = inject(DynamicDialogRef);
private messageService = inject(MessageService);
private bookService = inject(BookService);
private iconPickerService = inject(IconPickerService);
shelfState$: Observable<ShelfState> = this.shelfService.shelfState$;
book: Book = this.dynamicDialogConfig.data.book;
@@ -49,8 +49,6 @@ export class ShelfAssignerComponent implements OnInit {
isMultiBooks: boolean = this.dynamicDialogConfig.data.isMultiBooks;
selectedIcon: string | null = null;
@ViewChild(IconPickerComponent) iconPicker: IconPickerComponent | undefined;
ngOnInit(): void {
if (!this.isMultiBooks && this.book.shelves) {
this.shelfState$.pipe(
@@ -124,16 +122,14 @@ export class ShelfAssignerComponent implements OnInit {
}
openIconPicker() {
if (this.iconPicker) {
this.iconPicker.open();
}
this.iconPickerService.open().subscribe(icon => {
if (icon) {
this.selectedIcon = icon;
}
})
}
clearSelectedIcon() {
this.selectedIcon = null;
}
onIconSelected(icon: string) {
this.selectedIcon = icon;
}
}
@@ -23,4 +23,3 @@
<p-button label="Save" icon="pi pi-check" (onClick)="save()"></p-button>
</div>
</div>
<app-icon-picker (iconSelected)="onIconSelected($event)"></app-icon-picker>
@@ -1,19 +1,18 @@
import {Component, inject, OnInit, ViewChild} from '@angular/core';
import {Component, inject, OnInit} from '@angular/core';
import {ShelfService} from '../../service/shelf.service';
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
import {DialogService, DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
import {Button} from 'primeng/button';
import {IconPickerComponent} from '../../../utilities/component/icon-picker/icon-picker.component';
import {InputText} from 'primeng/inputtext';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
import {Shelf} from '../../model/shelf.model';
import {MessageService} from 'primeng/api';
import {IconPickerService} from '../../../utilities/services/icon-picker.service';
@Component({
selector: 'app-shelf-edit-dialog',
imports: [
Button,
IconPickerComponent,
InputText,
ReactiveFormsModule,
FormsModule
@@ -28,13 +27,12 @@ export class ShelfEditDialogComponent implements OnInit{
private dynamicDialogConfig = inject(DynamicDialogConfig);
private dynamicDialogRef = inject(DynamicDialogRef);
private messageService = inject(MessageService);
private iconPickerService = inject(IconPickerService);
shelfName: string = '';
selectedIcon: string | null = null;
shelf!: Shelf | undefined;
@ViewChild(IconPickerComponent) iconPicker: IconPickerComponent | undefined;
ngOnInit(): void {
const shelfId = this.dynamicDialogConfig?.data.shelfId;
this.shelf = this.shelfService.getShelfById(shelfId);
@@ -45,19 +43,17 @@ export class ShelfEditDialogComponent implements OnInit{
}
openIconPicker() {
if (this.iconPicker) {
this.iconPicker.open();
}
this.iconPickerService.open().subscribe(icon => {
if (icon) {
this.selectedIcon = icon;
}
})
}
clearSelectedIcon() {
this.selectedIcon = null;
}
onIconSelected(icon: string) {
this.selectedIcon = icon;
}
save() {
const shelf: Shelf = {
name: this.shelfName,
@@ -21,6 +21,7 @@ export interface Book {
seriesCount?: number | null;
metadataMatchScore?: number | null;
readStatus?: ReadStatus;
dateFinished?: string;
libraryPath?: { id: number };
}
@@ -53,6 +54,7 @@ export interface BookMetadata {
isbn10?: string;
asin?: string;
goodreadsId?: string;
comicvineId?: string;
hardcoverId?: string;
googleId?: string;
pageCount?: number | null;
@@ -84,6 +86,7 @@ export interface BookMetadata {
isbn13Locked?: boolean;
isbn10Locked?: boolean;
asinLocked?: boolean;
comicvineIdLocked?: boolean;
goodreadsIdLocked?: boolean;
hardcoverIdLocked?: boolean;
googleIdLocked?: boolean;
@@ -117,6 +120,7 @@ export interface MetadataClearFlags {
isbn10?: boolean;
asin?: boolean;
goodreadsId?: boolean;
comicvineId?: boolean;
hardcoverId?: boolean;
googleId?: boolean;
pageCount?: boolean;
@@ -408,16 +408,12 @@ export class BookService {
);
}
updateBookReadStatus(bookIds: number | number[], status: ReadStatus): Observable<void> {
updateBookReadStatus(bookIds: number | number[], status: ReadStatus): Observable<Book[]> {
const ids = Array.isArray(bookIds) ? bookIds : [bookIds];
return this.http.put<void>(`${this.url}/read-status`, {ids, status}).pipe(
tap(() => {
const currentState = this.bookStateSubject.value;
if (!currentState.books) return;
const updatedBooks = currentState.books.map(book =>
ids.includes(book.id) ? {...book, readStatus: status} : book
);
this.bookStateSubject.next({...currentState, books: updatedBooks});
return this.http.put<Book[]>(`${this.url}/read-status`, {ids, status}).pipe(
tap(updatedBooks => {
// Update the books in the state with the actual response from the API
updatedBooks.forEach(updatedBook => this.handleBookUpdate(updatedBook));
})
);
}
@@ -1,5 +1,5 @@
@if (fetchedMetadata) {
<form [formGroup]="metadataForm" class="flex flex-col h-[30rem] w-full">
<form [formGroup]="metadataForm" class="flex flex-col h-[35rem] w-full">
<div class="flex-grow overflow-auto">
<div class="relative flex items-center justify-between pb-3">
<div class="absolute left-1/2 transform -translate-x-1/2 flex items-center pl-24">
@@ -68,6 +68,7 @@ export class BookdropFileMetadataPickerComponent {
{label: 'HC Reviews', controlName: 'hardcoverReviewCount', lockedKey: 'hardcoverReviewCountLocked', fetchedKey: 'hardcoverReviewCount'},
{label: 'HC Rating', controlName: 'hardcoverRating', lockedKey: 'hardcoverRatingLocked', fetchedKey: 'hardcoverRating'},
{label: 'Google ID', controlName: 'googleId', lockedKey: 'googleIdLocked', fetchedKey: 'googleIdRating'},
{label: 'Comicvine ID', controlName: 'comicvineId', lockedKey: 'comicvineIdLocked', fetchedKey: 'comicvineId'},
{label: 'Pages', controlName: 'pageCount', lockedKey: 'pageCountLocked', fetchedKey: 'pageCount'}
];
@@ -155,6 +156,7 @@ export class BookdropFileMetadataPickerComponent {
hardcoverRating: this.originalMetadata.hardcoverRating || null,
hardcoverReviewCount: this.originalMetadata.hardcoverReviewCount || null,
googleId: this.originalMetadata.googleId || null,
comicvineId: this.originalMetadata.comicvineId || null,
seriesName: this.originalMetadata.seriesName || null,
seriesNumber: this.originalMetadata.seriesNumber || null,
seriesTotal: this.originalMetadata.seriesTotal || null,
@@ -10,28 +10,30 @@
</div>
@if (loading) {
<div class="absolute inset-0 flex items-center justify-center z-50 rounded-xl">
<div class="flex flex-col items-center space-y-3">
<p-progressSpinner styleClass="w-8 h-8" strokeWidth="4"/>
<span class="text-gray-300">
Loading Bookdrop files. Please wait...
</span>
<span class="text-gray-300">Loading Bookdrop files. Please wait...</span>
</div>
</div>
} @else {
<div class="px-6 pb-2">
@if (saving) {
<div class="absolute inset-0 bg-black bg-opacity-50 flex flex-col items-center justify-center z-50 rounded-xl space-y-3">
<p-progressSpinner styleClass="w-8 h-8" strokeWidth="4"/>
<div class="bg-gray-900/90 px-4 py-2 rounded-md">
<span class="text-sm text-gray-200 text-center">
Organizing and moving files to their designated libraries. Please wait...
</span>
<span class="text-sm text-gray-200 text-center">
Organizing and moving files to their designated libraries. Please wait...
</span>
</div>
</div>
}
@if (bookdropFileUis.length !== 0) {
<div class="flex gap-2 items-center px-1 pb-4 w-full">
<label for="uploadPatternInput" class="text-sm text-gray-300 font-medium">File Naming Pattern:</label>
<input
@@ -42,17 +44,16 @@
type="text"
pInputText
[(ngModel)]="uploadPattern"
placeholder="e.g., {title} - {authors}"
/>
placeholder="e.g., {title} - {authors}"/>
<i
class="pi pi-info-circle text-blue-500 cursor-help"
pTooltip="Sets the filename pattern used when moving files from bookdrop folder to the library, using metadata placeholders like {title}, {authors}, etc."
tooltipPosition="top"
style="font-size: 1rem; margin-left: 0.25rem;"
></i>
style="font-size: 1rem; margin-left: 0.25rem;"></i>
</div>
<div class="flex justify-between items-center gap-4 px-1">
<div class="flex gap-4 items-center">
<span class="text-sm text-gray-300 font-medium">Library for All Files:</span>
<p-select
@@ -109,6 +110,7 @@
pTooltip="For all files, replace current metadata with fetched metadata, excluding cover images"
tooltipPosition="top">
</p-button>
<p-button
size="small"
outlined
@@ -123,6 +125,7 @@
</div>
}
</div>
<div class="flex-1 overflow-y-auto px-6 space-y-2 pb-4">
@if (bookdropFileUis.length === 0) {
<div class="h-full w-full flex items-center justify-center text-gray-400 italic py-8">
@@ -130,68 +133,60 @@
</div>
} @else {
@for (file of bookdropFileUis; track file) {
<div class="flex flex-col">
<div class="flex items-center gap-4 custom-border rounded-xl px-4 py-2">
@if (file.file.fetchedMetadata) {
<i
class="pi pi-circle-fill"
style="color: green; font-size: 0.75rem"
pTooltip="Fetched metadata is available."
tooltipPosition="top">
</i>
} @else {
<i
class="pi pi-circle-fill"
style="color: darkorange; font-size: 0.75rem"
pTooltip="No fetched metadata available."
tooltipPosition="top">
</i>
}
<p-checkbox
[binary]="true"
[(ngModel)]="file.selected"
(ngModelChange)="toggleFileSelection(file.file.id, $event)">
</p-checkbox>
<i
class="pi pi-circle-fill"
[ngStyle]="{'color': file.file.fetchedMetadata ? 'green' : 'darkorange'}"
style="font-size: 0.75rem"
pTooltip="{{file.file.fetchedMetadata ? 'Fetched metadata is available.' : 'No fetched metadata available.'}}"
tooltipPosition="top">
</i>
@if (file.metadataForm.get('thumbnailUrl')?.value) {
<img
[src]="file.metadataForm.get('thumbnailUrl')?.value"
alt="Cover"
title="Original cover"
(click)="file.showDetails = !file.showDetails"
class="w-6 h-8 flex-shrink-0 rounded-sm object-cover cursor-pointer transition-transform duration-200 hover:scale-105 hover:shadow-md"
/>
class="w-6 h-8 rounded-sm object-cover cursor-pointer hover:scale-105 hover:shadow-md transition-transform duration-200"
(click)="file.showDetails = !file.showDetails"/>
}
@if (file.file.fetchedMetadata?.thumbnailUrl) {
<img
[src]="file.file.fetchedMetadata?.thumbnailUrl"
alt="Cover"
alt="Fetched Cover"
title="Fetched cover"
(click)="file.showDetails = !file.showDetails"
class="w-6 h-8 flex-shrink-0 rounded-sm object-cover cursor-pointer transition-transform duration-200 hover:scale-105 hover:shadow-md"
/>
class="w-6 h-8 rounded-sm object-cover cursor-pointer hover:scale-105 hover:shadow-md transition-transform duration-200"
(click)="file.showDetails = !file.showDetails"/>
}
<div class="flex-1 font-medium text-sm truncate" (click)="file.showDetails = !file.showDetails">
{{ file.file.fileName }}
</div>
@if (copiedFlags[file.file.id]) {
<i
class="pi pi-check-circle text-green-500"
pTooltip="Fetched metadata has been applied."
tooltipPosition="top">
</i>
} @else if (!file.file.fetchedMetadata) {
<i
class="pi pi-check-circle text-blue-500"
pTooltip="No fetched metadata available. Original metadata will used."
tooltipPosition="top">
</i>
} @else {
<i
class="pi pi-exclamation-triangle text-red-500"
pTooltip="Fetched metadata hasn’t been applied yet. You can open the metadata picker using the dropdown on the right, or skip and keep the original metadata."
tooltipPosition="top">
</i>
}
<i
class="pi"
[ngClass]="{
'pi-check-circle text-green-500': copiedFlags[file.file.id],
'pi-check-circle text-blue-500': !file.file.fetchedMetadata,
'pi-exclamation-triangle text-red-500': file.file.fetchedMetadata && !copiedFlags[file.file.id]
}"
[pTooltip]="copiedFlags[file.file.id]
? 'Fetched metadata has been applied.'
: !file.file.fetchedMetadata
? 'No fetched metadata available. Original metadata will be used.'
: 'Fetched metadata hasn’t been applied yet. Open metadata picker to review.'"
tooltipPosition="top">
</i>
<p-select
size="small"
@@ -223,12 +218,9 @@
</p-button>
</div>
@if (file.showDetails) {
<app-bookdrop-file-metadata-picker-component
class="px-12 py-8 custom-border1"
style="transition: opacity 0.3s ease"
#metadataPicker
[originalMetadata]="file.file.originalMetadata"
[fetchedMetadata]="file.file.fetchedMetadata!"
[metadataForm]="file.metadataForm"
@@ -242,29 +234,72 @@
}
}
</div>
<p-divider></p-divider>
<div class="pb-4 px-6 gap-4 flex justify-end">
@if (bookdropFileUis.length !== 0) {
<div class="pb-2 px-4 flex items-center justify-between gap-4">
<div class="flex gap-4 items-center min-w-[160px] justify-start">
@if (bookdropFileUis.length > 0) {
<p-button
label="Select All"
icon="pi pi-check-square"
severity="info"
(click)="selectAll(true)"
outlined
pTooltip="Select all files across all pages you have navigated"
tooltipPosition="top">
</p-button>
<p-button
label="Clear All"
icon="pi pi-times-circle"
severity="warn"
(click)="selectAll(false)"
outlined
pTooltip="Deselect all files across all pages you have navigated"
tooltipPosition="top">
</p-button>
} @else {
<div class="min-w-[160px]"></div>
}
</div>
<!-- Center container: paginator, flex-grow and centered -->
<div class="flex-grow flex justify-center">
<p-paginator
[rows]="pageSize"
[totalRecords]="totalRecords"
[first]="currentPage * pageSize"
(onPageChange)="loadPage($event.page ?? 0)"
[showCurrentPageReport]="true"
currentPageReportTemplate="Showing files {first} - {last} of {totalRecords}">
</p-paginator>
</div>
<!-- Right container: fixed width, right aligned -->
<div class="flex gap-4 items-center min-w-[200px] justify-end">
<p-button
label="Delete Files"
[label]="'Delete ' + selectedCount + ' File' + (selectedCount !== 1 ? 's' : '')"
icon="pi pi-times"
severity="danger"
[disabled]="!hasSelectedFiles"
outlined
pTooltip="Permanently delete all Bookdrop files and discard any changes"
tooltipPosition="top"
(click)="confirmDelete()">
(click)="confirmDelete()"
pTooltip="Permanently delete selected Bookdrop files and discard any changes"
tooltipPosition="top">
</p-button>
}
<p-button
[label]="saving ? ('Finalizing ' + selectedCount + ' File' + (selectedCount !== 1 ? 's' : '') + '...') : ('Finalize ' + selectedCount + ' File' + (selectedCount !== 1 ? 's' : ''))"
[icon]="saving ? 'pi pi-spin pi-spinner' : 'pi pi-save'"
severity="success"
outlined
[disabled]="!canFinalize || saving"
(click)="confirmFinalize()"
pTooltip="Move selected files into the chosen library and subpath">
</p-button>
</div>
<p-button
[label]="saving ? 'Finalize Imports...' : 'Finalize Imports'"
[icon]="saving ? 'pi pi-spin pi-spinner' : 'pi pi-save'"
severity="success"
outlined
pTooltip="This will move all staged files into the selected library and subpath."
(click)="confirmFinalize()"
[disabled]="!canFinalize || saving">
</p-button>
</div>
}
</div>
@@ -25,6 +25,9 @@ import {BookdropFinalizeResultDialogComponent} from '../bookdrop-finalize-result
import {DialogService} from 'primeng/dynamicdialog';
import {BookMetadata} from '../../book/model/book.model';
import {UrlHelperService} from '../../utilities/service/url-helper.service';
import {Checkbox} from 'primeng/checkbox';
import {NgClass, NgStyle} from '@angular/common';
import {Paginator} from 'primeng/paginator';
export interface BookdropFileUI {
file: BookdropFile;
@@ -53,7 +56,10 @@ export interface BookdropFileUI {
Tooltip,
Divider,
InputText,
Checkbox,
NgStyle,
NgClass,
Paginator,
],
})
export class BookdropFileReviewComponent implements OnInit {
@@ -64,28 +70,32 @@ export class BookdropFileReviewComponent implements OnInit {
private readonly dialogService = inject(DialogService);
private readonly appSettingsService = inject(AppSettingsService);
private readonly messageService = inject(MessageService);
private readonly urlHelper = inject(UrlHelperService);
@ViewChildren('metadataPicker') metadataPickers!: QueryList<BookdropFileMetadataPickerComponent>;
appSettings$: Observable<AppSettings | null> = this.appSettingsService.appSettings$;
uploadPattern = '';
defaultLibraryId: string | null = null;
defaultPathId: string | null = null;
bookdropFileUis: BookdropFileUI[] = [];
libraries: Library[] = [];
bookdropFileUis: BookdropFileUI[] = [];
fileUiCache: Record<number, BookdropFileUI> = {};
copiedFlags: Record<number, boolean> = {};
loading = true;
saving = false;
appSettings$: Observable<AppSettings | null> = this.appSettingsService.appSettings$;
protected urlHelper = inject(UrlHelperService);
pageSize = 50;
totalRecords = 0;
currentPage = 0;
selectAllAcrossPages = false;
excludedFiles = new Set<number>();
ngOnInit(): void {
this.bookdropFileService.getPendingFiles()
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(files => {
this.bookdropFileUis = files.map(file => this.createFileUI(file));
this.loading = false;
});
this.loading = true;
this.loadPage(0);
this.libraryService.libraryState$
.pipe(filter(state => !!state?.loaded), take(1))
@@ -101,14 +111,82 @@ export class BookdropFileReviewComponent implements OnInit {
}
get libraryOptions() {
if (!this.libraries) return [];
return this.libraries.map(lib => ({label: lib.name, value: String(lib.id ?? '')}));
}
get selectedLibraryPaths() {
if (!this.libraries) return [];
const selectedLibrary = this.libraries.find(lib => String(lib.id) === this.defaultLibraryId);
return selectedLibrary?.paths.map(path => ({label: path.path, value: String(path.id ?? '')})) ?? [];
}
get canApplyDefaults(): boolean {
return !!(this.defaultLibraryId && this.defaultPathId);
}
get canFinalize(): boolean {
if (this.selectAllAcrossPages) {
return (this.totalRecords - this.excludedFiles.size) > 0 && this.areAllSelectedHaveLibraryAndPath();
}
const selectedFiles = this.bookdropFileUis.filter(f => f.selected);
if (selectedFiles.length === 0) return false;
return selectedFiles.every(f => f.selectedLibraryId && f.selectedPathId);
}
get hasSelectedFiles(): boolean {
if (this.selectAllAcrossPages) {
return this.totalRecords > this.excludedFiles.size;
} else {
return Object.values(this.fileUiCache).some(file => file.selected);
}
}
get selectedCount(): number {
if (this.selectAllAcrossPages) {
return this.totalRecords - this.excludedFiles.size;
} else {
return Object.values(this.fileUiCache).filter(file => file.selected).length;
}
}
loadPage(page: number): void {
this.bookdropFileService.getPendingFiles(page, this.pageSize)
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe({
next: response => {
this.bookdropFileUis = response.content.map(file => {
const cached = this.fileUiCache[file.id];
if (cached) {
cached.file = file;
return cached;
} else {
const fresh = this.createFileUI(file);
if (this.defaultLibraryId) {
const selectedLib = this.libraries.find(l => String(l.id) === this.defaultLibraryId);
const selectedPaths = selectedLib?.paths ?? [];
fresh.selectedLibraryId = this.defaultLibraryId;
fresh.availablePaths = selectedPaths.map(p => ({id: String(p.id ?? ''), name: p.path}));
fresh.selectedPathId = this.defaultPathId ?? null;
}
this.fileUiCache[file.id] = fresh;
return fresh;
}
});
this.totalRecords = response.totalElements;
this.currentPage = page;
this.loading = false;
this.syncCurrentPageSelection();
},
error: err => {
console.error('Error loading files:', err);
this.loading = false;
}
});
}
onLibraryChange(file: BookdropFileUI): void {
const lib = this.libraries.find(l => String(l.id) === file.selectedLibraryId);
file.availablePaths = lib?.paths.map(p => ({id: String(p.id ?? ''), name: p.path})) ?? [];
@@ -120,27 +198,23 @@ export class BookdropFileReviewComponent implements OnInit {
}
applyDefaultsToAll(): void {
if (!this.defaultLibraryId) return;
if (!this.defaultLibraryId || !this.libraries) return;
const selectedLib = this.libraries.find(l => String(l.id) === this.defaultLibraryId);
const selectedPaths = selectedLib?.paths ?? [];
for (const file of this.bookdropFileUis) {
Object.values(this.fileUiCache).forEach(file => {
file.selectedLibraryId = this.defaultLibraryId;
file.availablePaths = selectedPaths.map(path => ({id: String(path.id), name: path.path}));
file.selectedPathId = this.defaultPathId ?? null;
}
}
get canApplyDefaults(): boolean {
return !!(this.defaultLibraryId && this.defaultPathId);
});
}
copyAll(includeThumbnail: boolean): void {
for (const fileUi of this.bookdropFileUis) {
Object.values(this.fileUiCache).forEach(fileUi => {
const fetched = fileUi.file.fetchedMetadata;
const form = fileUi.metadataForm;
if (!fetched) continue;
if (!fetched) return;
for (const key of Object.keys(fetched)) {
if (!includeThumbnail && key === 'thumbnailUrl') continue;
const value = fetched[key as keyof typeof fetched];
@@ -150,11 +224,11 @@ export class BookdropFileReviewComponent implements OnInit {
}
}
this.onMetadataCopied(fileUi.file.id, true);
}
});
}
resetAll(): void {
for (const fileUi of this.bookdropFileUis) {
Object.values(this.fileUiCache).forEach(fileUi => {
const original = fileUi.file.originalMetadata;
fileUi.metadataForm.patchValue({
title: original.title || null,
@@ -163,40 +237,76 @@ export class BookdropFileReviewComponent implements OnInit {
categories: [...(original.categories ?? [])].sort(),
publisher: original.publisher || null,
publishedDate: original.publishedDate || null,
isbn10: original.isbn10 || null,
isbn13: original.isbn13 || null,
description: original.description || null,
pageCount: original.pageCount || null,
language: original.language || null,
asin: original.asin || null,
amazonRating: original.amazonRating || null,
amazonReviewCount: original.amazonReviewCount || null,
goodreadsId: original.goodreadsId || null,
goodreadsRating: original.goodreadsRating || null,
goodreadsReviewCount: original.goodreadsReviewCount || null,
hardcoverId: original.hardcoverId || null,
hardcoverRating: original.hardcoverRating || null,
hardcoverReviewCount: original.hardcoverReviewCount || null,
googleId: original.googleId || null,
seriesName: original.seriesName || null,
seriesNumber: original.seriesNumber || null,
seriesTotal: original.seriesTotal || null,
isbn10: original.isbn10 ?? null,
isbn13: original.isbn13 ?? null,
description: original.description ?? null,
pageCount: original.pageCount ?? null,
language: original.language ?? null,
asin: original.asin ?? null,
amazonRating: original.amazonRating ?? null,
amazonReviewCount: original.amazonReviewCount ?? null,
goodreadsId: original.goodreadsId ?? null,
goodreadsRating: original.goodreadsRating ?? null,
goodreadsReviewCount: original.goodreadsReviewCount ?? null,
hardcoverId: original.hardcoverId ?? null,
hardcoverRating: original.hardcoverRating ?? null,
hardcoverReviewCount: original.hardcoverReviewCount ?? null,
googleId: original.googleId ?? null,
comicvineId: original.comicvineId ?? null,
seriesName: original.seriesName ?? null,
seriesNumber: original.seriesNumber ?? null,
seriesTotal: original.seriesTotal ?? null,
thumbnailUrl: this.urlHelper.getBookdropCoverUrl(fileUi.file.id),
});
fileUi.copiedFields = {};
fileUi.savedFields = {};
}
});
this.copiedFlags = {};
}
get canFinalize(): boolean {
return this.bookdropFileUis.length > 0 &&
this.bookdropFileUis.every(file => file.selectedLibraryId && file.selectedPathId);
selectAll(selected: boolean): void {
if (selected) {
this.selectAllAcrossPages = true;
this.excludedFiles.clear();
Object.values(this.fileUiCache).forEach(file => file.selected = true);
this.bookdropFileUis.forEach(file => file.selected = true);
} else {
this.selectAllAcrossPages = false;
this.excludedFiles.clear();
Object.values(this.fileUiCache).forEach(file => file.selected = false);
this.bookdropFileUis.forEach(file => file.selected = false);
}
}
toggleFileSelection(fileId: number, selected: boolean): void {
if (this.selectAllAcrossPages) {
if (!selected) {
this.excludedFiles.add(fileId);
} else {
this.excludedFiles.delete(fileId);
}
const cachedFile = this.fileUiCache[fileId];
if (cachedFile) cachedFile.selected = selected;
} else {
const cachedFile = this.fileUiCache[fileId];
if (cachedFile) cachedFile.selected = selected;
}
this.syncCurrentPageSelection();
}
confirmFinalize(): void {
const selectedCount = this.selectedCount;
if (selectedCount === 0) {
this.messageService.add({
severity: 'warn',
summary: 'No files selected',
detail: 'Please select files to finalize.',
});
return;
}
this.confirmationService.confirm({
message: 'Are you sure you want to finalize the import?',
message: `Are you sure you want to finalize the import of ${selectedCount} file${selectedCount !== 1 ? 's' : ''}?`,
header: 'Confirm Finalize',
icon: 'pi pi-exclamation-triangle',
acceptLabel: 'Yes',
@@ -205,9 +315,123 @@ export class BookdropFileReviewComponent implements OnInit {
});
}
confirmDelete(): void {
const selectedCount = this.selectedCount;
if (selectedCount === 0) {
this.messageService.add({
severity: 'warn',
summary: 'No files selected',
detail: 'Please select files to delete.',
});
return;
}
this.confirmationService.confirm({
message: `Are you sure you want to delete ${selectedCount} selected Bookdrop file${selectedCount !== 1 ? 's' : ''}? This action cannot be undone.`,
header: 'Confirm Delete',
icon: 'pi pi-exclamation-triangle',
accept: () => {
const payload: any = {
selectAll: this.selectAllAcrossPages,
};
if (this.selectAllAcrossPages) {
payload.excludedIds = Array.from(this.excludedFiles);
} else {
payload.selectedIds = Object.values(this.fileUiCache)
.filter(file => file.selected)
.map(file => file.file.id);
}
this.bookdropFileService.discardFiles(payload).subscribe({
next: () => {
this.messageService.add({
severity: 'success',
summary: 'Files Deleted',
detail: 'Selected Bookdrop files were deleted successfully.',
});
const toDelete = Object.values(this.fileUiCache).filter(file => {
return this.selectAllAcrossPages
? !this.excludedFiles.has(file.file.id)
: file.selected;
});
toDelete.forEach(file => delete this.fileUiCache[file.file.id]);
this.selectAllAcrossPages = false;
this.excludedFiles.clear();
this.loadPage(this.currentPage);
},
error: (err) => {
console.error('Error deleting files:', err);
this.messageService.add({
severity: 'error',
summary: 'Delete Failed',
detail: 'An error occurred while deleting Bookdrop files.',
});
},
});
},
});
}
private areAllSelectedHaveLibraryAndPath(): boolean {
return Object.values(this.fileUiCache).every(file => {
if (this.selectAllAcrossPages) {
if (this.excludedFiles.has(file.file.id)) return true;
return file.selectedLibraryId != null && file.selectedPathId != null;
} else {
if (!file.selected) return true;
return file.selectedLibraryId != null && file.selectedPathId != null;
}
});
}
private syncCurrentPageSelection(): void {
if (this.selectAllAcrossPages) {
this.bookdropFileUis.forEach(fileUi => {
fileUi.selected = !this.excludedFiles.has(fileUi.file.id);
const cachedFile = this.fileUiCache[fileUi.file.id];
if (cachedFile) cachedFile.selected = fileUi.selected;
});
}
}
private finalizeImport(): void {
this.saving = true;
const payload = this.buildFinalizePayload();
const selectedFiles = Object.values(this.fileUiCache).filter(file => {
if (this.selectAllAcrossPages) {
return !this.excludedFiles.has(file.file.id);
} else {
return file.selected;
}
});
const files = selectedFiles.map(fileUi => {
const rawMetadata = fileUi.metadataForm.value;
const metadata = {...rawMetadata};
if (metadata.thumbnailUrl?.includes('/api/bookdrop/')) {
delete metadata.thumbnailUrl;
}
return {
fileId: fileUi.file.id,
libraryId: Number(fileUi.selectedLibraryId),
pathId: Number(fileUi.selectedPathId),
metadata,
};
});
const payload: BookdropFinalizePayload = {
uploadPattern: this.uploadPattern,
selectAll: this.selectAllAcrossPages,
excludedIds: this.selectAllAcrossPages ? Array.from(this.excludedFiles) : undefined,
defaultLibraryId: this.defaultLibraryId ? Number(this.defaultLibraryId) : undefined,
defaultPathId: this.defaultPathId ? Number(this.defaultPathId) : undefined,
files,
};
this.bookdropFileService.finalizeImport(payload).subscribe({
next: (result: BookdropFinalizeResult) => {
@@ -224,12 +448,18 @@ export class BookdropFileReviewComponent implements OnInit {
modal: true,
closable: true,
closeOnEscape: true,
data: {
results: result.results
}
data: {results: result.results},
});
this.reloadPendingFiles();
const finalizedIds = new Set(files.map(f => f.fileId));
Object.keys(this.fileUiCache).forEach(idStr => {
const id = Number(idStr);
if (finalizedIds.has(id)) delete this.fileUiCache[id];
});
this.selectAllAcrossPages = false;
this.excludedFiles.clear();
this.loadPage(this.currentPage);
},
error: (err) => {
console.error('Error finalizing import:', err);
@@ -243,70 +473,6 @@ export class BookdropFileReviewComponent implements OnInit {
});
}
private buildFinalizePayload(): BookdropFinalizePayload {
return {
uploadPattern: this.uploadPattern,
files: this.bookdropFileUis.map((fileUi, index) => {
const rawMetadata = this.bookdropFileUis[index].metadataForm.value;
const metadata = {...rawMetadata};
if (metadata.thumbnailUrl?.includes('/api/bookdrop/')) {
delete metadata.thumbnailUrl;
}
return {
fileId: fileUi.file.id,
libraryId: Number(fileUi.selectedLibraryId),
pathId: Number(fileUi.selectedPathId),
metadata,
};
}),
};
}
private reloadPendingFiles(): void {
this.loading = true;
this.bookdropFileService.getPendingFiles()
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe({
next: files => {
this.bookdropFileUis = files.map(file => this.createFileUI(file));
this.loading = false;
this.saving = false;
},
error: err => {
console.error('Error loading pending files:', err);
this.loading = false;
this.saving = false;
}
});
}
confirmDelete(): void {
this.confirmationService.confirm({
message: 'Are you sure you want to delete all Bookdrop files? This action cannot be undone.',
header: 'Confirm Delete',
icon: 'pi pi-exclamation-triangle',
accept: () => {
this.bookdropFileService.discardAllFile().subscribe({
next: () => {
this.messageService.add({
severity: 'success',
summary: 'Files Deleted',
detail: 'All Bookdrop files were deleted successfully.',
});
this.reloadPendingFiles();
},
error: (err) => {
this.messageService.add({
severity: 'error',
summary: 'Delete Failed',
detail: 'An error occurred while deleting Bookdrop files.',
});
},
});
},
});
}
private createMetadataForm(original: BookMetadata, bookdropFileId: number): FormGroup {
return new FormGroup({
title: new FormControl(original.title ?? ''),
@@ -330,6 +496,7 @@ export class BookdropFileReviewComponent implements OnInit {
hardcoverRating: new FormControl(original.hardcoverRating ?? ''),
hardcoverReviewCount: new FormControl(original.hardcoverReviewCount ?? ''),
googleId: new FormControl(original.googleId ?? ''),
comicvineId: new FormControl(original.comicvineId ?? ''),
seriesName: new FormControl(original.seriesName ?? ''),
seriesNumber: new FormControl(original.seriesNumber ?? ''),
seriesTotal: new FormControl(original.seriesTotal ?? ''),
@@ -12,7 +12,11 @@ export enum BookdropFileStatus {
export interface BookdropFinalizePayload {
uploadPattern: string;
files: {
selectAll?: boolean;
excludedIds?: number[];
defaultLibraryId?: number;
defaultPathId?: number;
files?: {
fileId: number;
libraryId: number;
pathId: number;
@@ -43,22 +47,27 @@ export interface BookdropFinalizeResult {
results: BookdropFileResult[];
}
@Injectable({
providedIn: 'root',
})
export interface Page<T> {
content: T[];
totalElements: number;
totalPages: number;
number: number;
}
@Injectable({providedIn: 'root'})
export class BookdropFileTaskService {
private readonly url = `${API_CONFIG.BASE_URL}/api/bookdrop`;
private http = inject(HttpClient);
getPendingFiles(): Observable<BookdropFile[]> {
return this.http.get<BookdropFile[]>(`${this.url}/files?status=pending`);
getPendingFiles(page: number = 0, size: number = 50): Observable<Page<BookdropFile>> {
return this.http.get<Page<BookdropFile>>(`${this.url}/files?status=pending&page=${page}&size=${size}`);
}
finalizeImport(payload: BookdropFinalizePayload): Observable<BookdropFinalizeResult> {
return this.http.post<BookdropFinalizeResult>(`${this.url}/imports/finalize`, payload);
}
discardAllFile(): Observable<void> {
return this.http.delete<void>(`${this.url}/files`);
discardFiles(payload: { selectAll: boolean; excludedIds?: number[]; selectedIds?: number[] }): Observable<void> {
return this.http.post<void>(`${this.url}/files/discard`, payload);
}
}
@@ -46,6 +46,7 @@ export interface MetadataProviderSettings {
google: Google;
goodReads: Goodreads;
hardcover: Hardcover;
comicvine: Comicvine;
}
export interface Amazon {
@@ -66,7 +67,10 @@ export interface Hardcover {
enabled: boolean;
apiKey: string;
}
export interface Comicvine {
enabled: boolean;
apiKey: string;
}
export interface MetadataPersistenceSettings {
saveToOriginalFile: boolean;
backupMetadata: boolean;
@@ -1,71 +0,0 @@
import {Component, EventEmitter, inject, Output} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {DynamicDialogRef} from 'primeng/dynamicdialog';
@Component({
selector: 'app-icon-picker-v2-component',
imports: [
FormsModule
],
templateUrl: './icon-picker-v2-component.html',
styleUrl: './icon-picker-v2-component.scss'
})
export class IconPickerV2Component {
iconCategories: string[] = [
"address-book", "align-center", "align-justify", "align-left", "align-right", "android",
"angle-double-down", "angle-double-left", "angle-double-right", "angle-double-up", "angle-down", "angle-left",
"angle-right", "angle-up", "apple", "arrow-circle-down", "arrow-circle-left", "arrow-circle-right",
"arrow-circle-up", "arrow-down-left-and-arrow-up-right-to-center", "arrow-down-left", "arrow-down-right", "arrow-down", "arrow-left",
"arrow-right-arrow-left", "arrow-right", "arrow-up-left", "arrow-up-right-and-arrow-down-left-from-center", "arrow-up-right", "arrow-up",
"arrows-alt", "arrows-h", "arrows-v", "asterisks", "at", "backward", "ban", "barcode", "bars", "bell-slash", "bell", "bitcoin",
"bolt", "book", "bookmark-fill", "bookmark", "box", "briefcase", "building-columns", "building", "bullseye", "calculator", "calendar-clock", "calendar-minus",
"calendar-plus", "calendar-times", "calendar", "camera", "car", "caret-down", "caret-left", "caret-right", "caret-up", "cart-arrow-down", "cart-minus", "cart-plus",
"chart-bar", "chart-line", "chart-pie", "chart-scatter", "check-circle", "check-square", "check", "chevron-circle-down", "chevron-circle-left", "chevron-circle-right",
"chevron-circle-up", "chevron-down", "chevron-left", "chevron-right", "chevron-up", "circle-fill", "circle-off", "circle-on", "circle", "clipboard", "clock", "clone", "cloud-download", "cloud-upload",
"cloud", "code", "cog", "comment", "comments", "compass", "copy", "credit-card", "crown", "database", "delete-left", "desktop",
"directions-alt", "directions", "discord", "dollar", "download", "eject", "ellipsis-h", "ellipsis-v", "envelope", "equals", "eraser", "ethereum",
"euro", "exclamation-circle", "exclamation-triangle", "expand", "external-link", "eye-slash", "eye", "face-smile", "facebook", "fast-backward", "fast-forward", "file-arrow-up",
"file-check", "file-edit", "file-excel", "file-export", "file-import", "file-o", "file-pdf", "file-plus", "file-word", "file", "filter-fill", "filter-slash",
"filter", "flag-fill", "flag", "folder-open", "folder-plus", "folder", "forward", "gauge", "gift", "github", "globe", "google",
"graduation-cap", "hammer", "hashtag", "headphones", "heart-fill", "heart", "history", "home", "hourglass", "id-card", "image", "images",
"inbox", "indian-rupee", "info-circle", "info", "instagram", "key", "language", "lightbulb", "link", "linkedin", "list-check", "list",
"lock-open", "lock", "map-marker", "map", "mars", "megaphone", "microchip-ai", "microchip", "microphone", "microsoft", "minus-circle", "minus",
"mobile", "money-bill", "moon", "objects-column", "palette", "paperclip", "pause-circle", "pause", "paypal", "pen-to-square", "pencil", "percentage",
"phone", "pinterest", "play-circle", "play", "plus-circle", "plus", "pound", "power-off", "prime", "print", "qrcode", "question-circle",
"question", "receipt", "reddit", "refresh", "replay", "reply", "save", "search-minus", "search-plus", "search", "send", "server",
"share-alt", "shield", "shop", "shopping-bag", "shopping-cart", "sign-in", "sign-out", "sitemap", "slack", "sliders-h", "sliders-v", "sort-alpha-alt-down",
"sort-alpha-alt-up", "sort-alpha-down", "sort-alpha-up", "sort-alt-slash", "sort-alt", "sort-amount-down-alt", "sort-amount-down", "sort-amount-up-alt",
"sort-amount-up", "sort-down-fill", "sort-down", "sort-numeric-alt-down",
"sort-numeric-alt-up", "sort-numeric-down", "sort-numeric-up", "sort-up-fill", "sort-up", "sort", "sparkles", "spinner-dotted", "spinner", "star-fill", "star-half-fill", "star-half",
"star", "step-backward-alt", "step-backward", "step-forward-alt", "step-forward", "stop-circle", "stop", "stopwatch", "sun", "sync", "table", "tablet",
"tag", "tags", "telegram", "th-large", "thumbs-down-fill", "thumbs-down", "thumbs-up-fill", "thumbs-up", "thumbtack", "ticket", "tiktok", "times-circle",
"times", "trash", "trophy", "truck", "turkish-lira", "twitch", "twitter", "undo", "unlock", "upload", "user-edit", "user-minus",
"user-plus", "user", "users", "venus", "verified", "video", "vimeo", "volume-down", "volume-off", "volume-up", "wallet", "warehouse",
"wave-pulse", "whatsapp", "wifi", "window-maximize", "window-minimize", "wrench", "youtube"
];
searchText: string = '';
selectedIcon: string | null = null;
icons: string[] = this.createIconList(this.iconCategories);
ref = inject(DynamicDialogRef);
createIconList(categories: string[]): string[] {
return categories.map(iconName => `pi pi-${iconName}`);
}
filteredIcons(): string[] {
if (!this.searchText) return this.icons;
return this.icons.filter(icon => icon.toLowerCase().includes(this.searchText.toLowerCase()));
}
selectIcon(icon: string) {
this.selectedIcon = icon;
this.ref.close(icon);
}
cancel() {
this.ref.close();
}
}
@@ -108,7 +108,7 @@
<div class="flex gap-6">
<li>
<a class="topbar-item"
href="https://adityachandelgit.github.io/booklore-docs/docs/getting-started/"
href="https://booklore-app.github.io/booklore-docs/docs/getting-started/"
target="_blank"
rel="noopener noreferrer"
pTooltip="Documentation"
@@ -171,7 +171,7 @@
<li>
<a
class="flex items-center gap-2 w-full text-left p-2 hover:bg-surface-200 dark:hover:bg-surface-700 rounded"
href="https://adityachandelgit.github.io/booklore-docs/docs/getting-started/"
href="https://booklore-app.github.io/booklore-docs/docs/getting-started/"
target="_blank"
rel="noopener noreferrer">
<i class="pi pi-info-circle text-surface-100"></i>
@@ -62,6 +62,9 @@
@if (ruleCtrl.get('field')?.value === 'publishedDate') {
<p-datepicker [formControl]="ruleCtrl.get('valueStart')" dateFormat="dd-M-yy" placeholder="Start Year" appendTo="body" fluid class="w-full"></p-datepicker>
<p-datepicker [formControl]="ruleCtrl.get('valueEnd')" dateFormat="dd-M-yy" placeholder="End Year" appendTo="body" fluid class="w-full"></p-datepicker>
} @else if (ruleCtrl.get('field')?.value === 'dateFinished') {
<p-datepicker [formControl]="ruleCtrl.get('valueStart')" dateFormat="dd-M-yy" placeholder="Start Date" appendTo="body" fluid class="w-full"></p-datepicker>
<p-datepicker [formControl]="ruleCtrl.get('valueEnd')" dateFormat="dd-M-yy" placeholder="End Date" appendTo="body" fluid class="w-full"></p-datepicker>
} @else if (numericFieldConfigMap.get(ruleCtrl.get('field')?.value)?.type === 'number') {
<p-inputNumber [formControl]="ruleCtrl.get('valueStart')" [min]="0" class="w-full" placeholder="Start Value" [showButtons]="true"></p-inputNumber>
<p-inputNumber [formControl]="ruleCtrl.get('valueEnd')" [min]="0" class="w-full" placeholder="End Value" [showButtons]="true"></p-inputNumber>
@@ -75,6 +78,8 @@
} @else {
@if (ruleCtrl.get('field')?.value === 'publishedDate') {
<p-datepicker formControlName="value" dateFormat="dd-M-yy" appendTo="body" fluid class="w-full"></p-datepicker>
} @else if (ruleCtrl.get('field')?.value === 'dateFinished') {
<p-datepicker formControlName="value" dateFormat="dd-M-yy" appendTo="body" fluid class="w-full"></p-datepicker>
} @else if (numericFieldConfigMap.get(ruleCtrl.get('field')?.value)?.type === 'number') {
<p-inputNumber formControlName="value" class="w-full" mode="decimal" placeholder="Value" [showButtons]="true"></p-inputNumber>
} @else if (numericFieldConfigMap.get(ruleCtrl.get('field')?.value)?.type === 'decimal') {
@@ -12,11 +12,11 @@ import {LibraryService} from '../book/service/library.service';
import {Library} from '../book/model/library.model';
import {MagicShelfService} from '../magic-shelf-service';
import {MessageService} from 'primeng/api';
import {IconPickerV2Component} from '../icon-picker-v2-component/icon-picker-v2-component';
import {DialogService, DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
import {DynamicDialogConfig} from 'primeng/dynamicdialog';
import {Chips} from 'primeng/chips';
import {MultiSelect} from 'primeng/multiselect';
import {EMPTY_CHECK_OPERATORS, MULTI_VALUE_OPERATORS, parseValue, removeNulls, serializeDateRules} from '../magic-shelf-utils';
import { IconPickerService } from '../utilities/services/icon-picker.service';
export type RuleOperator =
| 'equals'
@@ -59,6 +59,7 @@ export type RuleField =
| 'fileType'
| 'fileSize'
| 'readStatus'
| 'dateFinished'
| 'metadataScore';
@@ -107,6 +108,7 @@ export type GroupFormGroup = FormGroup<{
const FIELD_CONFIGS: Record<RuleField, FullFieldConfig> = {
library: {label: 'Library'},
readStatus: {label: 'Read Status'},
dateFinished: {label: 'Date Finished', type: 'date'},
metadataScore: {label: 'Metadata Score', type: 'decimal', max: 100},
title: {label: 'Title'},
authors: {label: 'Authors'},
@@ -189,11 +191,11 @@ export class MagicShelfComponent implements OnInit {
shelfId: number | null = null;
libraryService = inject(LibraryService);
libraryService = inject(LibraryService);
magicShelfService = inject(MagicShelfService);
messageService = inject(MessageService);
dialogService = inject(DialogService);
config = inject(DynamicDialogConfig);
messageService = inject(MessageService);
config = inject(DynamicDialogConfig);
private iconPicker = inject(IconPickerService);
trackByFn(ruleCtrl: AbstractControl, index: number): any {
return ruleCtrl;
@@ -388,21 +390,7 @@ export class MagicShelfComponent implements OnInit {
}
openIconPicker() {
const isMobile = window.innerWidth <= 768;
const ref: DynamicDialogRef = this.dialogService.open(IconPickerV2Component, {
header: 'Choose an Icon',
style: {
position: 'absolute',
top: '10%',
bottom: '10%',
width: isMobile ? '90vw' : '800px',
maxWidth: isMobile ? '90vw' : '800px',
minWidth: isMobile ? '90vw' : '800px',
},
dismissableMask: true,
});
ref.onClose.subscribe((icon: string) => {
this.iconPicker.open().subscribe(icon => {
if (icon) {
this.form.get('icon')?.setValue(icon);
}
+1 -1
View File
@@ -49,7 +49,7 @@ export function serializeDateRules(ruleOrGroup: any): any {
};
}
const isDateField = ruleOrGroup.field === 'publishedDate';
const isDateField = ruleOrGroup.field === 'publishedDate' || ruleOrGroup.field === 'dateFinished';
const serialize = (val: any) => (val instanceof Date ? val.toISOString().split('T')[0] : val);
return {
@@ -355,6 +355,18 @@
}
</div>
</div>
<div class="flex flex-col gap-1 w-1/6">
<label for="comicvineId">Comicvine ID</label>
<div class="flex justify-between items-center gap-2">
<input pInputText id="comicvineId" formControlName="comicvineId" class="w-full"/>
@if (!book.metadata!['comicvineIdLocked']) {
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('comicvineId')" severity="success"></p-button>
}
@if (book.metadata!['comicvineIdLocked']) {
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('comicvineId')" severity="warn"></p-button>
}
</div>
</div>
</div>
</div>
</div>
@@ -97,6 +97,7 @@ export class MetadataEditorComponent implements OnInit {
amazonRating: new FormControl(''),
amazonReviewCount: new FormControl(''),
goodreadsId: new FormControl(''),
comicvineId: new FormControl(''),
goodreadsRating: new FormControl(''),
goodreadsReviewCount: new FormControl(''),
hardcoverId: new FormControl(''),
@@ -123,6 +124,7 @@ export class MetadataEditorComponent implements OnInit {
amazonRatingLocked: new FormControl(false),
amazonReviewCountLocked: new FormControl(false),
goodreadsIdLocked: new FormControl(''),
comicvineIdLocked: new FormControl(false),
goodreadsRatingLocked: new FormControl(false),
goodreadsReviewCountLocked: new FormControl(false),
hardcoverIdLocked: new FormControl(false),
@@ -189,6 +191,7 @@ export class MetadataEditorComponent implements OnInit {
amazonRating: metadata.amazonRating ?? null,
amazonReviewCount: metadata.amazonReviewCount ?? null,
goodreadsId: metadata.goodreadsId ?? null,
comicvineId: metadata.comicvineId ?? null,
goodreadsRating: metadata.goodreadsRating ?? null,
goodreadsReviewCount: metadata.goodreadsReviewCount ?? null,
hardcoverId: metadata.hardcoverId ?? null,
@@ -214,6 +217,7 @@ export class MetadataEditorComponent implements OnInit {
amazonRatingLocked: metadata.amazonRatingLocked ?? false,
amazonReviewCountLocked: metadata.amazonReviewCountLocked ?? false,
goodreadsIdLocked: metadata.goodreadsIdLocked ?? false,
comicvineIdLocked: metadata.comicvineIdLocked ?? false,
goodreadsRatingLocked: metadata.goodreadsRatingLocked ?? false,
goodreadsReviewCountLocked: metadata.goodreadsReviewCountLocked ?? false,
hardcoverIdLocked: metadata.hardcoverIdLocked ?? false,
@@ -241,6 +245,7 @@ export class MetadataEditorComponent implements OnInit {
{key: 'amazonRatingLocked', control: 'amazonRating'},
{key: 'personalRatingLocked', control: 'personalRating'},
{key: 'goodreadsIdLocked', control: 'goodreadsId'},
{key: 'comicvineIdLocked', control: 'comicvineId'},
{key: 'goodreadsReviewCountLocked', control: 'goodreadsReviewCount'},
{key: 'goodreadsRatingLocked', control: 'goodreadsRating'},
{key: 'hardcoverIdLocked', control: 'hardcoverId'},
@@ -352,6 +357,7 @@ export class MetadataEditorComponent implements OnInit {
amazonRating: form.get('amazonRating')?.value,
amazonReviewCount: form.get('amazonReviewCount')?.value,
goodreadsId: form.get('goodreadsId')?.value,
comicvineId: form.get('comicvineId')?.value,
goodreadsRating: form.get('goodreadsRating')?.value,
goodreadsReviewCount: form.get('goodreadsReviewCount')?.value,
hardcoverId: form.get('hardcoverId')?.value,
@@ -380,6 +386,7 @@ export class MetadataEditorComponent implements OnInit {
personalRatingLocked: form.get('personalRatingLocked')?.value,
amazonReviewCountLocked: form.get('amazonReviewCountLocked')?.value,
goodreadsIdLocked: form.get('goodreadsIdLocked')?.value,
comicvineIdLocked: form.get('comicvineIdLocked')?.value,
goodreadsRatingLocked: form.get('goodreadsRatingLocked')?.value,
goodreadsReviewCountLocked: form.get('goodreadsReviewCountLocked')?.value,
hardcoverIdLocked: form.get('hardcoverIdLocked')?.value,
@@ -423,6 +430,7 @@ export class MetadataEditorComponent implements OnInit {
amazonRating: wasCleared('personalRating'),
amazonReviewCount: wasCleared('amazonReviewCount'),
goodreadsId: wasCleared('goodreadsId'),
comicvineId: wasCleared('comicvineId'),
goodreadsRating: wasCleared('goodreadsRating'),
goodreadsReviewCount: wasCleared('goodreadsReviewCount'),
hardcoverId: wasCleared('hardcoverId'),
@@ -61,10 +61,11 @@ export class MetadataPickerComponent implements OnInit {
{label: 'ASIN', controlName: 'asin', lockedKey: 'asinLocked', fetchedKey: 'asin'},
{label: 'Amz Reviews', controlName: 'amazonReviewCount', lockedKey: 'amazonReviewCountLocked', fetchedKey: 'amazonReviewCount'},
{label: 'Amz Rating', controlName: 'amazonRating', lockedKey: 'amazonRatingLocked', fetchedKey: 'amazonRating'},
{label: 'GR ID', controlName: 'goodreadsId', lockedKey: 'goodreadsIdLocked', fetchedKey: 'goodreadsId'},
{label: 'Comicvine ID', controlName: 'comicvineId', lockedKey: 'comicvineIdLocked', fetchedKey: 'comicvineId'},
{label: 'Goodreads ID', controlName: 'goodreadsId', lockedKey: 'goodreadsIdLocked', fetchedKey: 'goodreadsId'},
{label: 'GR Reviews', controlName: 'goodreadsReviewCount', lockedKey: 'goodreadsReviewCountLocked', fetchedKey: 'goodreadsReviewCount'},
{label: 'GR Rating', controlName: 'goodreadsRating', lockedKey: 'goodreadsRatingLocked', fetchedKey: 'goodreadsRating'},
{label: 'HC ID', controlName: 'hardcoverId', lockedKey: 'hardcoverIdLocked', fetchedKey: 'hardcoverId'},
{label: 'Hardcover ID', controlName: 'hardcoverId', lockedKey: 'hardcoverIdLocked', fetchedKey: 'hardcoverId'},
{label: 'HC Reviews', controlName: 'hardcoverReviewCount', lockedKey: 'hardcoverReviewCountLocked', fetchedKey: 'hardcoverReviewCount'},
{label: 'HC Rating', controlName: 'hardcoverRating', lockedKey: 'hardcoverRatingLocked', fetchedKey: 'hardcoverRating'},
{label: 'Google ID', controlName: 'googleId', lockedKey: 'googleIdLocked', fetchedKey: 'googleIdRating'},
@@ -105,6 +106,7 @@ export class MetadataPickerComponent implements OnInit {
amazonRating: new FormControl(''),
amazonReviewCount: new FormControl(''),
goodreadsId: new FormControl(''),
comicvineId: new FormControl(''),
goodreadsRating: new FormControl(''),
goodreadsReviewCount: new FormControl(''),
hardcoverId: new FormControl(''),
@@ -132,6 +134,7 @@ export class MetadataPickerComponent implements OnInit {
amazonRatingLocked: new FormControl(false),
amazonReviewCountLocked: new FormControl(false),
goodreadsIdLocked: new FormControl(false),
comicvineIdLocked: new FormControl(false),
goodreadsRatingLocked: new FormControl(false),
goodreadsReviewCountLocked: new FormControl(false),
hardcoverIdLocked: new FormControl(false),
@@ -180,6 +183,7 @@ export class MetadataPickerComponent implements OnInit {
amazonRating: metadata.amazonRating || null,
amazonReviewCount: metadata.amazonReviewCount || null,
goodreadsId: metadata.goodreadsId || null,
comicvineId: metadata.comicvineId || null,
goodreadsRating: metadata.goodreadsRating || null,
goodreadsReviewCount: metadata.goodreadsReviewCount || null,
hardcoverId: metadata.hardcoverId || null,
@@ -207,6 +211,7 @@ export class MetadataPickerComponent implements OnInit {
amazonRatingLocked: metadata.amazonRatingLocked || false,
amazonReviewCountLocked: metadata.amazonReviewCountLocked || false,
goodreadsIdLocked: metadata.goodreadsIdLocked || false,
comicvineIdLocked: metadata.comicvineIdLocked || false,
goodreadsRatingLocked: metadata.goodreadsRatingLocked || false,
goodreadsReviewCountLocked: metadata.goodreadsReviewCountLocked || false,
hardcoverIdLocked: metadata.hardcoverIdLocked || false,
@@ -287,6 +292,7 @@ export class MetadataPickerComponent implements OnInit {
amazonRating: this.metadataForm.get('amazonRating')?.value || this.copiedFields['amazonRating'] ? this.getNumberOrCopied('amazonRating') : null,
amazonReviewCount: this.metadataForm.get('amazonReviewCount')?.value || this.copiedFields['amazonReviewCount'] ? this.getNumberOrCopied('amazonReviewCount') : null,
goodreadsId: this.metadataForm.get('goodreadsId')?.value || this.copiedFields['goodreadsId'] ? this.getValueOrCopied('goodreadsId') : '',
comicvineId: this.metadataForm.get('comicvineId')?.value || this.copiedFields['comicvineId'] ? this.getValueOrCopied('comicvineId') : '',
goodreadsRating: this.metadataForm.get('goodreadsRating')?.value || this.copiedFields['goodreadsRating'] ? this.getNumberOrCopied('goodreadsRating') : null,
goodreadsReviewCount: this.metadataForm.get('goodreadsReviewCount')?.value || this.copiedFields['goodreadsReviewCount'] ? this.getNumberOrCopied('goodreadsReviewCount') : null,
hardcoverId: this.metadataForm.get('hardcoverId')?.value || this.copiedFields['hardcoverId'] ? this.getValueOrCopied('hardcoverId') : '',
@@ -314,6 +320,7 @@ export class MetadataPickerComponent implements OnInit {
amazonRatingLocked: this.metadataForm.get('amazonRatingLocked')?.value,
amazonReviewCountLocked: this.metadataForm.get('amazonReviewCountLocked')?.value,
goodreadsIdLocked: this.metadataForm.get('goodreadsIdLocked')?.value,
comicvineIdLocked: this.metadataForm.get('comicvineIdLocked')?.value,
goodreadsRatingLocked: this.metadataForm.get('goodreadsRatingLocked')?.value,
goodreadsReviewCountLocked: this.metadataForm.get('goodreadsReviewCountLocked')?.value,
hardcoverIdLocked: this.metadataForm.get('hardcoverIdLocked')?.value,
@@ -353,6 +360,7 @@ export class MetadataPickerComponent implements OnInit {
amazonRating: current.amazonRating === null && original.amazonRating !== null,
amazonReviewCount: current.amazonReviewCount === null && original.amazonReviewCount !== null,
goodreadsId: !current.goodreadsId && !!original.goodreadsId,
comicvineId: !current.comicvineId && !!original.comicvineId,
goodreadsRating: current.goodreadsRating === null && original.goodreadsRating !== null,
goodreadsReviewCount: current.goodreadsReviewCount === null && original.goodreadsReviewCount !== null,
hardcoverId: !current.hardcoverId && !!original.hardcoverId,
@@ -80,14 +80,18 @@
<div class="flex flex-col md:flex-row gap-2 md:gap-4 justify-between">
<p class="font-bold">{{ truncateText(metadata['title']!, 90) }}</p>
<div class="flex flex-wrap gap-2 text-sm">
<p>ISBN: {{ metadata['isbn10'] || metadata['asin'] }}</p>
<span class="hidden md:inline">|</span>
@if (metadata['isbn10'] || metadata['asin']) {
<p>ISBN: {{ metadata['isbn10'] || metadata['asin'] }}</p>
<span class="hidden md:inline">|</span>
}
<p>Published: {{ metadata['publishedDate'] }}</p>
</div>
</div>
<div class="flex flex-wrap gap-2 text-sm">
<p>by {{ truncateText(metadata['authors']!.join(', '), 70) }}</p>
<span class="hidden md:inline">|</span>
@if (metadata['authors'] && metadata['authors'].length > 0) {
<p>by {{ truncateText(metadata['authors'].join(', '), 70) }}</p>
<span class="hidden md:inline">|</span>
}
<p>Source: <span [innerHTML]="buildProviderLink(metadata)"></span></p>
</div>
<p class="mt-4 truncate-text p-secondary">
@@ -83,8 +83,9 @@ export class MetadataSearcherComponent implements OnInit, OnDestroy {
distinctUntilChanged(([prevBook], [currBook]) => prevBook?.id === currBook?.id)
)
.subscribe(([book, settings]) => {
this.providers = Object.entries(settings!.metadataProviderSettings)
.filter(([_, value]) => value.enabled)
const providerSettings = settings?.metadataProviderSettings ?? {};
this.providers = Object.entries(providerSettings)
.filter(([_, value]) => !!value && typeof value === 'object' && 'enabled' in value && (value as any).enabled)
.map(([key]) => key.charAt(0).toUpperCase() + key.slice(1));
this.resetFormFromBook(book!);
@@ -183,7 +184,14 @@ export class MetadataSearcherComponent implements OnInit, OnDestroy {
} else if (metadata.hardcoverId) {
return `<a href="https://hardcover.app/books/${metadata.hardcoverId}" target="_blank">Hardcover</a>`;
}
else if (metadata.comicvineId) {
if( metadata.comicvineId.startsWith('4000')) {
const name = metadata.seriesName ? metadata.seriesName.replace(/ /g, '-').toLowerCase() + "-" + metadata.seriesNumber : '';
return `<a href="https://comicvine.gamespot.com/${name}/${metadata.comicvineId}" target="_blank">Comicvine</a>`;
}
const name = metadata.seriesName;
return `<a href="https://comicvine.gamespot.com/volume/${metadata.comicvineId}" target="_blank">Comicvine</a>`;
}
throw new Error("No provider ID found in metadata.");
}
}
@@ -91,6 +91,15 @@
[style.--p-rating-icon-active-color]="getStarColorScaled(book?.metadata!.personalRating, 10)">
</p-rating>
</div>
<p-button
text
size="small"
icon="pi pi-undo"
severity="warn"
(onClick)="resetPersonalRating(book)"
pTooltip="Reset Rating"
tooltipPosition="top">
</p-button>
</div>
@if (book?.metadata?.amazonRating || book?.metadata?.goodreadsRating || book?.metadata?.hardcoverRating || book?.metadata?.googleId) {
@@ -172,9 +181,25 @@
/>
</a>
}
@if (book?.metadata?.comicvineId) {
<a
class="flex items-center gap-1"
[href]="'https://comicvine.gamespot.com/' + book.metadata!.comicvineId"
target="_blank"
rel="noopener noreferrer"
>
<img
src="https://www.comicvine.com/favicon.ico"
alt="Comic Vine"
class="w-5 h-5 object-contain transform transition duration-200 hover:scale-125 hover:drop-shadow-lg"
/>
</a>
}
</div>
</div>
@if (book?.metadata?.categories?.length) {
<div class="overflow-x-auto scrollbar-hide max-w-7xl pt-2 md:pt-0">
<div class="flex gap-2 w-max max-w-[1150px]">
@@ -231,6 +256,11 @@
{{ getStatusLabel(selectedReadStatus) }}
</span>
<p-menu #menu [popup]="true" [model]="readStatusMenuItems"></p-menu>
@if (selectedReadStatus === 'READ' && book?.dateFinished) {
<span class="text-xs text-gray-400 ml-2">
Finished on {{ formatDate(book.dateFinished) }}
</span>
}
</p>
<p class="whitespace-nowrap flex items-center">
<span class="font-bold mr-2">Progress:</span>
@@ -1,4 +1,4 @@
import {Component, DestroyRef, inject, Input, OnChanges, OnInit, Optional, SimpleChanges, ViewChild} from '@angular/core';
import {Component, DestroyRef, inject, Input, OnChanges, OnInit, SimpleChanges, ViewChild} from '@angular/core';
import {Button} from 'primeng/button';
import {AsyncPipe, DecimalPipe, NgClass} from '@angular/common';
import {Observable} from 'rxjs';
@@ -24,7 +24,7 @@ import {MetadataFetchOptionsComponent} from '../../metadata-options-dialog/metad
import {MetadataRefreshType} from '../../model/request/metadata-refresh-type.enum';
import {MetadataRefreshRequest} from '../../model/request/metadata-refresh-request.model';
import {Router} from '@angular/router';
import {filter, map, take} from 'rxjs/operators';
import {filter, map, switchMap, take, tap} from 'rxjs/operators';
import {Menu} from 'primeng/menu';
import {InfiniteScrollDirective} from 'ngx-infinite-scroll';
import {BookCardLiteComponent} from '../../../book/components/book-card-lite/book-card-lite-component';
@@ -37,7 +37,6 @@ import {BookCardLiteComponent} from '../../../book/components/book-card-lite/boo
imports: [Button, AsyncPipe, Rating, FormsModule, Tag, Divider, SplitButton, NgClass, Tooltip, DecimalPipe, Editor, ProgressBar, Menu, InfiniteScrollDirective, BookCardLiteComponent]
})
export class MetadataViewerComponent implements OnInit, OnChanges {
@Input() book$!: Observable<Book | null>;
@Input() recommendedBooks: BookRecommendation[] = [];
@ViewChild(Editor) quillEditor!: Editor;
@@ -49,40 +48,34 @@ export class MetadataViewerComponent implements OnInit, OnChanges {
private bookService = inject(BookService);
protected urlHelper = inject(UrlHelperService);
protected userService = inject(UserService);
private destroyRef = inject(DestroyRef);
private confirmationService = inject(ConfirmationService);
private router = inject(Router);
private destroyRef = inject(DestroyRef);
private dialogRef?: DynamicDialogRef;
constructor(@Optional() dialogRef?: DynamicDialogRef) {
this.dialogRef = dialogRef;
}
emailMenuItems$!: Observable<MenuItem[]>;
readMenuItems$!: Observable<MenuItem[]>;
refreshMenuItems$!: Observable<MenuItem[]>;
otherItems$!: Observable<MenuItem[]>;
bookInSeries: Book[] = [];
bookInSeries: Book[] = [];
isExpanded = false;
showFilePath = false;
isAutoFetching = false;
private metadataCenterViewMode: 'route' | 'dialog' = 'route';
readStatusOptions = [
{label: 'Unread', value: ReadStatus.UNREAD},
{label: 'Reading', value: ReadStatus.READING},
{label: 'Re-reading', value: ReadStatus.RE_READING},
{label: 'Partially Read', value: ReadStatus.PARTIALLY_READ},
{label: 'Paused', value: ReadStatus.PAUSED},
{label: 'Read', value: ReadStatus.READ},
{label: 'Won’t Read', value: ReadStatus.WONT_READ},
{label: 'Abandoned', value: ReadStatus.ABANDONED}
];
selectedReadStatus: ReadStatus = ReadStatus.UNREAD;
readStatusOptions: { value: ReadStatus, label: string }[] = [
{value: ReadStatus.UNREAD, label: 'Unread'},
{value: ReadStatus.PAUSED, label: 'Paused'},
{value: ReadStatus.READING, label: 'Reading'},
{value: ReadStatus.RE_READING, label: 'Re-reading'},
{value: ReadStatus.READ, label: 'Read'},
{value: ReadStatus.PARTIALLY_READ, label: 'Partially Read'},
{value: ReadStatus.ABANDONED, label: 'Abandoned'},
{value: ReadStatus.WONT_READ, label: 'Won\'t Read'},
];
ngOnInit(): void {
this.emailMenuItems$ = this.book$.pipe(
map(book => book?.metadata ?? null),
@@ -195,17 +188,24 @@ export class MetadataViewerComponent implements OnInit, OnChanges {
ngOnChanges(changes: SimpleChanges): void {
if (changes['recommendedBooks']) {
this.originalRecommendedBooks = [...this.recommendedBooks];
this.book$.pipe(take(1)).subscribe(book => this.filterRecommendations(book));
this.withCurrentBook(book => this.filterRecommendations(book));
}
}
private withCurrentBook(callback: (book: Book | null) => void): void {
this.book$.pipe(take(1)).subscribe(callback);
}
private loadBooksInSeriesAndFilterRecommended(bookId: number): void {
this.bookService.getBooksInSeries(bookId).subscribe(bookInSeries => {
bookInSeries.sort((a, b) => (a.metadata?.seriesNumber ?? 0) - (b.metadata?.seriesNumber ?? 0));
this.bookInSeries = bookInSeries;
this.originalRecommendedBooks = [...this.recommendedBooks];
this.book$.pipe(take(1)).subscribe(book => this.filterRecommendations(book));
});
this.bookService.getBooksInSeries(bookId).pipe(
tap(series => {
series.sort((a, b) => (a.metadata?.seriesNumber ?? 0) - (b.metadata?.seriesNumber ?? 0));
this.bookInSeries = series;
this.originalRecommendedBooks = [...this.recommendedBooks];
}),
switchMap(() => this.book$.pipe(take(1))),
takeUntilDestroyed(this.destroyRef)
).subscribe(book => this.filterRecommendations(book));
}
private filterRecommendations(book: Book | null): void {
@@ -268,6 +268,157 @@ export class MetadataViewerComponent implements OnInit, OnChanges {
});
}
updateReadStatus(status: ReadStatus): void {
if (!status) {
return;
}
this.book$.pipe(take(1)).subscribe(book => {
if (!book || !book.id) {
return;
}
this.bookService.updateBookReadStatus(book.id, status).subscribe({
next: (updatedBooks) => {
this.selectedReadStatus = status;
this.messageService.add({
severity: 'success',
summary: 'Read Status Updated',
detail: `Marked as "${this.getStatusLabel(status)}"`,
life: 2000
});
},
error: (err) => {
console.error('Failed to update read status:', err);
this.messageService.add({
severity: 'error',
summary: 'Update Failed',
detail: 'Could not update read status.',
life: 3000
});
}
});
});
}
resetProgress(book: Book): void {
this.confirmationService.confirm({
message: `Reset reading progress for "${book.metadata?.title}"?`,
header: 'Confirm Reset',
icon: 'pi pi-exclamation-triangle',
acceptLabel: 'Yes',
rejectLabel: 'Cancel',
acceptButtonStyleClass: 'p-button-danger',
accept: () => {
this.bookService.resetProgress(book.id).subscribe({
next: () => {
this.messageService.add({
severity: 'success',
summary: 'Progress Reset',
detail: 'Reading progress has been reset.',
life: 1500
});
},
error: () => {
this.messageService.add({
severity: 'error',
summary: 'Failed',
detail: 'Could not reset progress.',
life: 1500
});
}
});
}
});
}
onPersonalRatingChange(book: Book, {value: personalRating}: RatingRateEvent): void {
if (!book?.metadata) return;
const updatedMetadata = {...book.metadata, personalRating};
this.bookService.updateBookMetadata(book.id, {
metadata: updatedMetadata,
clearFlags: {personalRating: false}
}, false).subscribe({
next: () => {
this.messageService.add({
severity: 'success',
summary: 'Rating Saved',
detail: 'Personal rating updated successfully'
});
},
error: err => {
console.error('Failed to update personal rating:', err);
this.messageService.add({
severity: 'error',
summary: 'Update Failed',
detail: 'Could not update personal rating'
});
}
});
}
resetPersonalRating(book: Book): void {
if (!book?.metadata) return;
const updatedMetadata = {...book.metadata, personalRating: null};
this.bookService.updateBookMetadata(book.id, {
metadata: updatedMetadata,
clearFlags: {personalRating: true}
}, false).subscribe({
next: () => {
this.messageService.add({
severity: 'info',
summary: 'Rating Reset',
detail: 'Personal rating has been cleared.'
});
},
error: err => {
console.error('Failed to reset personal rating:', err);
this.messageService.add({
severity: 'error',
summary: 'Reset Failed',
detail: 'Could not reset personal rating'
});
}
});
}
goToAuthorBooks(author: string): void {
this.handleMetadataClick('author', author);
}
goToCategory(category: string): void {
this.handleMetadataClick('category', category);
}
goToSeries(seriesName: string): void {
this.handleMetadataClick('series', seriesName);
}
goToPublisher(publisher: string): void {
this.handleMetadataClick('publisher', publisher);
}
private navigateToFilteredBooks(filterKey: string, filterValue: string): void {
this.router.navigate(['/all-books'], {
queryParams: {
view: 'grid',
sort: 'title',
direction: 'asc',
sidebar: true,
filter: `${filterKey}:${filterValue}`
}
});
}
private handleMetadataClick(filterKey: string, filterValue: string): void {
if (this.metadataCenterViewMode === 'dialog') {
this.dialogRef?.close();
setTimeout(() => this.navigateToFilteredBooks(filterKey, filterValue), 200);
} else {
this.navigateToFilteredBooks(filterKey, filterValue);
}
}
isMetadataFullyLocked(metadata: BookMetadata): boolean {
const lockedKeys = Object.keys(metadata).filter(k => k.endsWith('Locked'));
return lockedKeys.length > 0 && lockedKeys.every(k => metadata[k] === true);
@@ -369,70 +520,6 @@ export class MetadataViewerComponent implements OnInit, OnChanges {
return 'bg-blue-500';
}
onPersonalRatingChange(book: Book, {value: personalRating}: RatingRateEvent): void {
if (!book?.metadata) return;
const updatedMetadata = {...book.metadata, personalRating};
this.bookService.updateBookMetadata(book.id, {
metadata: updatedMetadata,
clearFlags: {personalRating: false}
}, false).subscribe({
next: () => {
this.messageService.add({
severity: 'success',
summary: 'Rating Saved',
detail: 'Personal rating updated successfully'
});
},
error: err => {
console.error('Failed to update personal rating:', err);
this.messageService.add({
severity: 'error',
summary: 'Update Failed',
detail: 'Could not update personal rating'
});
}
});
}
goToAuthorBooks(author: string): void {
this.handleMetadataClick('author', author);
}
goToCategory(category: string): void {
this.handleMetadataClick('category', category);
}
goToSeries(seriesName: string): void {
this.handleMetadataClick('series', seriesName);
}
goToPublisher(publisher: string): void {
this.handleMetadataClick('publisher', publisher);
}
private navigateToFilteredBooks(filterKey: string, filterValue: string): void {
this.router.navigate(['/all-books'], {
queryParams: {
view: 'grid',
sort: 'title',
direction: 'asc',
sidebar: true,
filter: `${filterKey}:${filterValue}`
}
});
}
private handleMetadataClick(filterKey: string, filterValue: string): void {
if (this.metadataCenterViewMode === 'dialog') {
this.dialogRef?.close();
setTimeout(() => this.navigateToFilteredBooks(filterKey, filterValue), 200);
} else {
this.navigateToFilteredBooks(filterKey, filterValue);
}
}
getRatingTooltip(book: Book, source: 'amazon' | 'goodreads' | 'hardcover'): string {
const meta = book?.metadata;
if (!meta) return '';
@@ -469,67 +556,14 @@ export class MetadataViewerComponent implements OnInit, OnChanges {
return this.readStatusOptions.find(o => o.value === value)?.label.toUpperCase() ?? 'UNSET';
}
updateReadStatus(status: ReadStatus): void {
if (!status) {
return;
}
this.book$.pipe(take(1)).subscribe(book => {
if (!book || !book.id) {
return;
}
this.bookService.updateBookReadStatus(book.id, status).subscribe({
next: () => {
this.selectedReadStatus = status;
this.messageService.add({
severity: 'success',
summary: 'Read Status Updated',
detail: `Marked as "${this.getStatusLabel(status)}"`,
life: 2000
});
},
error: (err) => {
console.error('Failed to update read status:', err);
this.messageService.add({
severity: 'error',
summary: 'Update Failed',
detail: 'Could not update read status.',
life: 3000
});
}
});
});
}
resetProgress(book: Book): void {
this.confirmationService.confirm({
message: `Reset reading progress for "${book.metadata?.title}"?`,
header: 'Confirm Reset',
icon: 'pi pi-exclamation-triangle',
acceptLabel: 'Yes',
rejectLabel: 'Cancel',
acceptButtonStyleClass: 'p-button-danger',
accept: () => {
this.bookService.resetProgress(book.id).subscribe({
next: () => {
this.messageService.add({
severity: 'success',
summary: 'Progress Reset',
detail: 'Reading progress has been reset.',
life: 1500
});
},
error: () => {
this.messageService.add({
severity: 'error',
summary: 'Failed',
detail: 'Could not reset progress.',
life: 1500
});
}
});
}
formatDate(dateString: string | undefined): string {
if (!dateString) return '';
const date = new Date(dateString);
return date.toLocaleDateString('en-US', {
year: 'numeric',
month: 'short',
day: 'numeric'
});
}
}
@@ -32,7 +32,7 @@ export class MetadataAdvancedFetchOptionsComponent implements OnChanges {
'seriesName', 'seriesNumber', 'seriesTotal', 'isbn13', 'isbn10',
'language', 'categories', 'cover'
];
providers: string[] = ['Amazon', 'Google', 'GoodReads', 'Hardcover'];
providers: string[] = ['Amazon', 'Google', 'GoodReads', 'Hardcover', 'Comicvine'];
refreshCovers: boolean = false;
mergeCategories: boolean = false;
@@ -52,6 +52,7 @@
<p-checkbox [(ngModel)]="googleEnabled" [binary]="true"></p-checkbox>
<label class="font-medium">Google</label>
</div>
<div class="flex flex-col gap-2">
<div class="flex items-center gap-4">
@@ -72,7 +73,33 @@
[(ngModel)]="hardcoverToken"
(ngModelChange)="onTokenChange($event)" />
</div>
</div>
<div class="flex flex-col gap-2">
<div class="flex items-center gap-4">
<p-checkbox
[binary]="true"
[(ngModel)]="comicvineEnabled"
[disabled]="!comicvineToken">
</p-checkbox>
<label class="font-medium">Comic Vine</label>
</div>
<div class="flex flex-col gap-2 pl-9 pt-1">
<label class="font-medium text-sm">API Token</label>
<input
type="text"
pInputText
placeholder="Enter Comic Vine API token"
class="w-full max-w-3xl"
[(ngModel)]="comicvineToken"
(ngModelChange)="onComicTokenChange($event)" />
</div>
</div>
</div>
<div class="flex justify-start px-4">
@@ -58,6 +58,8 @@ export class MetadataProviderSettingsComponent implements OnInit {
amazonEnabled: boolean = false;
goodreadsEnabled: boolean = false;
googleEnabled: boolean = false;
comicvineEnabled: boolean = false;
comicvineToken: string = '';
private appSettingsService = inject(AppSettingsService);
private messageService = inject(MessageService);
@@ -79,6 +81,8 @@ export class MetadataProviderSettingsComponent implements OnInit {
this.googleEnabled = metadataProviderSettings?.google?.enabled ?? false;
this.hardcoverToken = metadataProviderSettings?.hardcover?.apiKey ?? '';
this.hardcoverEnabled = metadataProviderSettings?.hardcover?.enabled ?? false;
this.comicvineEnabled = metadataProviderSettings?.comicvine?.enabled ?? false;
this.comicvineToken = metadataProviderSettings?.comicvine?.apiKey ?? '';
});
}
@@ -89,6 +93,13 @@ export class MetadataProviderSettingsComponent implements OnInit {
}
}
onComicTokenChange(newToken: string): void {
this.comicvineToken = newToken;
if (!newToken.trim()) {
this.comicvineEnabled = false;
}
}
saveSettings(): void {
const payload = [
{
@@ -99,6 +110,12 @@ export class MetadataProviderSettingsComponent implements OnInit {
cookie: this.amazonCookie,
domain: this.selectedAmazonDomain
},
comicvine: {
enabled: this.comicvineEnabled,
apiKey: this.comicvineToken.trim()
},
goodReads: {enabled: this.goodreadsEnabled},
google: {enabled: this.googleEnabled},
hardcover: {
@@ -0,0 +1,77 @@
import {Component, EventEmitter, inject, Output} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {DynamicDialogRef} from 'primeng/dynamicdialog';
@Component({
selector: 'app-icon-picker-component',
imports: [
FormsModule
],
templateUrl: './icon-picker-component.html',
styleUrl: './icon-picker-component.scss'
})
export class IconPickerComponent {
iconCategories: string[] = [
"address-book", "align-center", "align-justify", "align-left", "align-right", "amazon", "android",
"angle-double-down", "angle-double-left", "angle-double-right", "angle-double-up", "angle-down", "angle-left",
"angle-right", "angle-up", "apple", "arrow-circle-down", "arrow-circle-left", "arrow-circle-right", "arrow-circle-up",
"arrow-down", "arrow-down-left", "arrow-down-left-and-arrow-up-right-to-center", "arrow-down-right", "arrow-left",
"arrow-right", "arrow-right-arrow-left", "arrow-up", "arrow-up-left", "arrow-up-right", "arrow-up-right-and-arrow-down-left-from-center",
"arrows-alt", "arrows-h", "arrows-v", "asterisk", "at", "backward", "ban", "barcode", "bars", "bell", "bell-slash",
"bitcoin", "bolt", "book", "bookmark", "bookmark-fill", "box", "briefcase", "building", "building-columns", "bullseye",
"calculator", "calendar", "calendar-clock", "calendar-minus", "calendar-plus", "calendar-times", "camera", "car",
"caret-down", "caret-left", "caret-right", "caret-up", "cart-arrow-down", "cart-minus", "cart-plus", "chart-bar",
"chart-line", "chart-pie", "chart-scatter", "check", "check-circle", "check-square", "chevron-circle-down",
"chevron-circle-left", "chevron-circle-right", "chevron-circle-up", "chevron-down", "chevron-left", "chevron-right",
"chevron-up", "circle", "circle-fill", "circle-off", "circle-on", "clipboard", "clock", "clone", "cloud", "cloud-download",
"cloud-upload", "code", "cog", "comment", "comments", "compass", "copy", "credit-card", "crown", "database", "delete-left",
"desktop", "directions", "directions-alt", "discord", "dollar", "download", "eject", "ellipsis-h", "ellipsis-v",
"envelope", "equals", "eraser", "ethereum", "euro", "exclamation-circle", "exclamation-triangle", "expand",
"external-link", "eye", "eye-slash", "face-smile", "facebook", "fast-backward", "fast-forward", "file", "file-arrow-up",
"file-check", "file-edit", "file-excel", "file-export", "file-import", "file-o", "file-pdf", "file-plus", "file-word",
"filter", "filter-fill", "filter-slash", "flag", "flag-fill", "folder", "folder-open", "folder-plus", "forward", "gauge",
"gift", "github", "globe", "google", "graduation-cap", "hammer", "hashtag", "headphones", "heart", "heart-fill", "history",
"home", "hourglass", "id-card", "image", "images", "inbox", "indian-rupee", "info", "info-circle", "instagram", "key",
"language", "lightbulb", "link", "linkedin", "list", "list-check", "lock", "lock-open", "map", "map-marker", "mars", "megaphone",
"microchip", "microchip-ai", "microphone", "microsoft", "minus", "minus-circle", "mobile", "money-bill", "moon", "objects-column",
"palette", "paperclip", "pause", "pause-circle", "paypal", "pen-to-square", "pencil", "percentage", "phone", "pinterest", "play",
"play-circle", "plus", "plus-circle", "pound", "power-off", "prime", "print", "qrcode", "question", "question-circle", "receipt",
"reddit", "refresh", "replay", "reply", "save", "search", "search-minus", "search-plus", "send", "server", "share-alt", "shield",
"shop", "shopping-bag", "shopping-cart", "sign-in", "sign-out", "sitemap", "slack", "sliders-h", "sliders-v", "sort",
"sort-alpha-down", "sort-alpha-down-alt", "sort-alpha-up", "sort-alpha-up-alt", "sort-alt", "sort-alt-slash",
"sort-amount-down", "sort-amount-down-alt", "sort-amount-up", "sort-amount-up-alt", "sort-down", "sort-down-fill",
"sort-numeric-down", "sort-numeric-down-alt", "sort-numeric-up", "sort-numeric-up-alt", "sort-up", "sort-up-fill", "sparkles",
"spinner", "spinner-dotted", "star", "star-fill", "star-half", "star-half-fill", "step-backward", "step-backward-alt",
"step-forward", "step-forward-alt", "stop", "stop-circle", "stopwatch", "sun", "sync", "table", "tablet", "tag", "tags",
"telegram", "th-large", "thumbs-down", "thumbs-down-fill", "thumbs-up", "thumbs-up-fill", "thumbtack", "ticket", "tiktok",
"times", "times-circle", "trash", "trophy", "truck", "turkish-lira", "twitch", "twitter", "undo", "unlock", "upload", "user",
"user-edit", "user-minus", "user-plus", "users", "venus", "verified", "video", "vimeo", "volume-down", "volume-off",
"volume-up", "wallet", "warehouse", "wave-pulse", "whatsapp", "wifi", "window-maximize", "window-minimize", "wrench",
"youtube"
];
searchText: string = '';
selectedIcon: string | null = null;
icons: string[] = this.createIconList(this.iconCategories);
ref = inject(DynamicDialogRef);
createIconList(categories: string[]): string[] {
return categories.map(iconName => `pi pi-${iconName}`);
}
filteredIcons(): string[] {
if (!this.searchText) return this.icons;
return this.icons.filter(icon => icon.toLowerCase().includes(this.searchText.toLowerCase()));
}
selectIcon(icon: string) {
this.selectedIcon = icon;
this.ref.close(icon);
}
cancel() {
this.ref.close();
}
}
@@ -1,18 +0,0 @@
<p-dialog
[(visible)]="iconDialogVisible"
header="Select an Icon"
[modal]="true"
[draggable]="false"
[style]="{ width: '500px', height: '500px' }">
<input type="text" placeholder="Search icons..." [(ngModel)]="searchText" class="icon-search"/>
<div class="icon-grid">
@for (icon of filteredIcons(); track icon) {
<div
class="icon-item"
(click)="selectIcon(icon)"
[class.selected]="icon === selectedIcon">
<i [class]="icon"></i>
</div>
}
</div>
</p-dialog>
@@ -1,32 +0,0 @@
.icon-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(25px, 1fr));
gap: 30px;
}
.icon-item {
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
}
.icon-search {
width: 100%;
padding: 8px 12px;
font-size: 16px;
border: 1px solid var(--text-color-secondary);
border-radius: 4px;
margin-bottom: 15px;
box-sizing: border-box;
}
.icon-search:focus {
border-color: var(--primary-color);
outline: none;
}
.icon-search::placeholder {
color: var(--text-color-secondary);
opacity: 1;
}
@@ -1,78 +0,0 @@
import {Component, EventEmitter, Input, Output} from '@angular/core';
import {DialogModule} from 'primeng/dialog';
import {FormsModule} from '@angular/forms';
@Component({
selector: 'app-icon-picker',
templateUrl: './icon-picker.component.html',
styleUrls: ['./icon-picker.component.scss'],
imports: [
DialogModule,
FormsModule
],
standalone: true
})
export class IconPickerComponent {
iconCategories: string[] = [
"address-book", "align-center", "align-justify", "align-left", "align-right", "android",
"angle-double-down", "angle-double-left", "angle-double-right", "angle-double-up", "angle-down", "angle-left",
"angle-right", "angle-up", "apple", "arrow-circle-down", "arrow-circle-left", "arrow-circle-right",
"arrow-circle-up", "arrow-down-left-and-arrow-up-right-to-center", "arrow-down-left", "arrow-down-right", "arrow-down", "arrow-left",
"arrow-right-arrow-left", "arrow-right", "arrow-up-left", "arrow-up-right-and-arrow-down-left-from-center", "arrow-up-right", "arrow-up",
"arrows-alt", "arrows-h", "arrows-v", "asterisks", "at", "backward", "ban", "barcode", "bars", "bell-slash", "bell", "bitcoin",
"bolt", "book", "bookmark-fill", "bookmark", "box", "briefcase", "building-columns", "building", "bullseye", "calculator", "calendar-clock", "calendar-minus",
"calendar-plus", "calendar-times", "calendar", "camera", "car", "caret-down", "caret-left", "caret-right", "caret-up", "cart-arrow-down", "cart-minus", "cart-plus",
"chart-bar", "chart-line", "chart-pie", "chart-scatter", "check-circle", "check-square", "check", "chevron-circle-down", "chevron-circle-left", "chevron-circle-right",
"chevron-circle-up", "chevron-down", "chevron-left", "chevron-right", "chevron-up", "circle-fill", "circle-off", "circle-on", "circle", "clipboard", "clock", "clone", "cloud-download", "cloud-upload",
"cloud", "code", "cog", "comment", "comments", "compass", "copy", "credit-card", "crown", "database", "delete-left", "desktop",
"directions-alt", "directions", "discord", "dollar", "download", "eject", "ellipsis-h", "ellipsis-v", "envelope", "equals", "eraser", "ethereum",
"euro", "exclamation-circle", "exclamation-triangle", "expand", "external-link", "eye-slash", "eye", "face-smile", "facebook", "fast-backward", "fast-forward", "file-arrow-up",
"file-check", "file-edit", "file-excel", "file-export", "file-import", "file-o", "file-pdf", "file-plus", "file-word", "file", "filter-fill", "filter-slash",
"filter", "flag-fill", "flag", "folder-open", "folder-plus", "folder", "forward", "gauge", "gift", "github", "globe", "google",
"graduation-cap", "hammer", "hashtag", "headphones", "heart-fill", "heart", "history", "home", "hourglass", "id-card", "image", "images",
"inbox", "indian-rupee", "info-circle", "info", "instagram", "key", "language", "lightbulb", "link", "linkedin", "list-check", "list",
"lock-open", "lock", "map-marker", "map", "mars", "megaphone", "microchip-ai", "microchip", "microphone", "microsoft", "minus-circle", "minus",
"mobile", "money-bill", "moon", "objects-column", "palette", "paperclip", "pause-circle", "pause", "paypal", "pen-to-square", "pencil", "percentage",
"phone", "pinterest", "play-circle", "play", "plus-circle", "plus", "pound", "power-off", "prime", "print", "qrcode", "question-circle",
"question", "receipt", "reddit", "refresh", "replay", "reply", "save", "search-minus", "search-plus", "search", "send", "server",
"share-alt", "shield", "shop", "shopping-bag", "shopping-cart", "sign-in", "sign-out", "sitemap", "slack", "sliders-h", "sliders-v", "sort-alpha-alt-down",
"sort-alpha-alt-up", "sort-alpha-down", "sort-alpha-up", "sort-alt-slash", "sort-alt", "sort-amount-down-alt", "sort-amount-down", "sort-amount-up-alt",
"sort-amount-up", "sort-down-fill", "sort-down", "sort-numeric-alt-down",
"sort-numeric-alt-up", "sort-numeric-down", "sort-numeric-up", "sort-up-fill", "sort-up", "sort", "sparkles", "spinner-dotted", "spinner", "star-fill", "star-half-fill", "star-half",
"star", "step-backward-alt", "step-backward", "step-forward-alt", "step-forward", "stop-circle", "stop", "stopwatch", "sun", "sync", "table", "tablet",
"tag", "tags", "telegram", "th-large", "thumbs-down-fill", "thumbs-down", "thumbs-up-fill", "thumbs-up", "thumbtack", "ticket", "tiktok", "times-circle",
"times", "trash", "trophy", "truck", "turkish-lira", "twitch", "twitter", "undo", "unlock", "upload", "user-edit", "user-minus",
"user-plus", "user", "users", "venus", "verified", "video", "vimeo", "volume-down", "volume-off", "volume-up", "wallet", "warehouse",
"wave-pulse", "whatsapp", "wifi", "window-maximize", "window-minimize", "wrench", "youtube"
];
icons: string[] = this.createIconList(this.iconCategories);
iconDialogVisible: boolean = false;
searchText: string = '';
selectedIcon: string | null = null;
@Output() iconSelected = new EventEmitter<string>();
createIconList(categories: string[]): string[] {
return categories.map(iconName => `pi pi-${iconName}`);
}
filteredIcons(): string[] {
if (!this.searchText) {
return this.icons;
}
return this.icons.filter(icon => icon.toLowerCase().includes(this.searchText.toLowerCase()));
}
open() {
this.iconDialogVisible = true;
}
selectIcon(icon: string) {
this.selectedIcon = icon;
this.iconDialogVisible = false;
this.iconSelected.emit(icon);
}
}
@@ -0,0 +1,27 @@
import { Injectable, inject } from '@angular/core';
import { DialogService, DynamicDialogRef } from 'primeng/dynamicdialog';
import { IconPickerComponent } from '../component/icon-picker-component/icon-picker-component';
import { Observable } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class IconPickerService {
private dialog = inject(DialogService);
open(): Observable<string> {
const isMobile = window.innerWidth <= 768;
const ref: DynamicDialogRef = this.dialog.open(IconPickerComponent, {
header: 'Choose an Icon',
modal: true,
closable: true,
style: {
position: 'absolute',
top: '10%',
bottom: '10%',
width: isMobile ? '90vw' : '800px',
maxWidth: isMobile ? '90vw' : '800px',
minWidth: isMobile ? '90vw' : '800px',
}
});
return ref.onClose as Observable<string>;
}
}
+68
View File
@@ -0,0 +1,68 @@
# Forward Auth with Reverse Proxy
BookLore supports **Forward Auth**, allowing you to specify when a user is logged in using a reverse proxy and existing SSO provider.
## ⚠️ Security
** Important**: Enabling forward auth means BookLore will **fully trust headers sent by the reverse proxy**. Never expose BookLore directly to the internet when using forward auth - always route through your authenticated proxy, otherwise outsiders can attempt to impersonate any username they know about.
## Configuration
Provide BookLore with the following environment variables:
```bash
# Allows Forward Auth
REMOTE_AUTH_ENABLED=true
# Enable automatic user creation (recommended)
REMOTE_AUTH_CREATE_NEW_USERS=true
# Header names (your proxy will specify what header names to use)
REMOTE_AUTH_HEADER_USER=Remote-User # Username (required)
REMOTE_AUTH_HEADER_NAME=Remote-Name # Display name
REMOTE_AUTH_HEADER_EMAIL=Remote-Email # Email address
REMOTE_AUTH_HEADER_GROUPS=Remote-Groups # Groups/roles
# Admin group name (optional)
REMOTE_AUTH_ADMIN_GROUP=admin # Specify this if you want a group to automatically get admin rights
```
### Docker Compose Example
```yaml
services:
booklore:
image: ghcr.io/adityachandelgit/booklore-app:latest
environment:
# Forward Auth Configuration
- REMOTE_AUTH_ENABLED=true
- REMOTE_AUTH_CREATE_NEW_USERS=true
- REMOTE_AUTH_HEADER_NAME=Remote-Name
- REMOTE_AUTH_HEADER_USER=Remote-User
- REMOTE_AUTH_HEADER_EMAIL=Remote-Email
- REMOTE_AUTH_HEADER_GROUPS=Remote-Groups
- REMOTE_AUTH_ADMIN_GROUP=admin
# ... rest of configuration ...
```
## Setting Up Defaults Permissions
1. **Access Admin Settings**: Log in to Booklore as an admin user
2. **Navigate to Authentication Settings**: Go to Settings → Authentication
3. **Configure OIDC Auto-Provision** (even if not using OIDC):
- Enable "Auto User Provisioning". You might need to enter a bogus URL to enable it temporarily.
- Select the default permissions and libraries for new users.
4. **Save Settings**
## Example: Caddyfile for Authelia Forward Auth
```caddyfile
books.example.com {
forward_auth authelia:9091 {
uri /api/authz/forward-auth
copy_headers Remote-User Remote-Name Remote-Email Remote-Groups
}
reverse_proxy booklore:6060
}
```