Merge pull request #3101 from booklore-app/develop
Merge develop into master for release
This commit is contained in:
@@ -72,7 +72,7 @@ PASTE OUTPUT HERE
|
||||
> **All boxes must be checked before requesting review.** Incomplete PRs will be closed without review. No exceptions.
|
||||
|
||||
- [ ] This PR is linked to an approved issue
|
||||
- [ ] Code follows project style guidelines and conventions
|
||||
- [ ] Code follows project [backend and frontend conventions](../CONTRIBUTING.md#backend-conventions)
|
||||
- [ ] Branch is up to date with `develop` (merge conflicts resolved)
|
||||
- [ ] I ran the full stack locally (backend + frontend + database) and verified the change works
|
||||
- [ ] Automated tests added or updated to cover changes (backend **and** frontend)
|
||||
|
||||
+38
-18
@@ -9,20 +9,22 @@ Thanks for your interest in contributing to Booklore! Whether you're fixing bugs
|
||||
**Tech Stack:**
|
||||
|
||||
- **Frontend:** Angular 20, TypeScript, PrimeNG 19
|
||||
- **Backend:** Java 21, Spring Boot 3.5
|
||||
- **Backend:** Java 25, Spring Boot 3.5
|
||||
- **Authentication:** Local JWT + optional OIDC (e.g., Authentik)
|
||||
- **Database:** MariaDB
|
||||
- **Deployment:** Docker-compatible, reverse proxy-ready
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Before You Start](#before-you-start)
|
||||
- [Where to Start](#where-to-start)
|
||||
- [Getting Started](#getting-started)
|
||||
- [Development Setup](#development-setup)
|
||||
- [Running Tests](#running-tests)
|
||||
- [Making Changes](#making-changes)
|
||||
- [Submitting a Pull Request](#submitting-a-pull-request)
|
||||
- [Code Style](#code-style)
|
||||
- [Backend Conventions](#backend-conventions)
|
||||
- [Frontend Conventions](#frontend-conventions)
|
||||
- [Reporting Bugs](#reporting-bugs)
|
||||
- [Community & Support](#community--support)
|
||||
- [Code of Conduct](#code-of-conduct)
|
||||
@@ -42,7 +44,7 @@ This protects both your time and ours. It ensures that the work is actually want
|
||||
- No test output pasted in the PR
|
||||
- Bulk AI-generated changes that clearly haven't been reviewed or tested
|
||||
- Unsolicited refactors, cleanups, or "improvements" nobody asked for
|
||||
- PRs over 1000+ changed lines (split them up)
|
||||
- PRs with 1000+ changed lines (split them up)
|
||||
|
||||
## Where to Start
|
||||
|
||||
@@ -51,8 +53,6 @@ Not sure where to begin? Look for issues labeled:
|
||||
- [`good first issue`](https://github.com/booklore-app/booklore/labels/good%20first%20issue) - small, well-scoped tasks ideal for newcomers
|
||||
- [`help wanted`](https://github.com/booklore-app/booklore/labels/help%20wanted) - tasks where maintainers would appreciate a hand
|
||||
|
||||
You can also check the [project roadmap](https://github.com/booklore-app/booklore/projects) for larger initiatives.
|
||||
|
||||
---
|
||||
|
||||
## Getting Started
|
||||
@@ -89,7 +89,7 @@ git push origin develop
|
||||
```
|
||||
booklore/
|
||||
├── booklore-ui/ # Angular frontend (TypeScript, PrimeNG)
|
||||
├── booklore-api/ # Spring Boot backend (Java 21, Gradle)
|
||||
├── booklore-api/ # Spring Boot backend (Java 25, Gradle)
|
||||
├── dev.docker-compose.yml # Development Docker stack
|
||||
├── assets/ # Shared assets (logos, icons)
|
||||
└── local/ # Local development helpers
|
||||
@@ -127,8 +127,8 @@ For full control over each component or IDE integration (debugging, hot-reload,
|
||||
|
||||
| Tool | Version | Download |
|
||||
|---------------|---------|----------------------------------------------|
|
||||
| Java | 21+ | [Adoptium](https://adoptium.net/) |
|
||||
| Node.js + npm | 18+ | [nodejs.org](https://nodejs.org/) |
|
||||
| Java | 25+ | [Adoptium](https://adoptium.net/) |
|
||||
| Node.js + npm | 20+ | [nodejs.org](https://nodejs.org/) |
|
||||
| MariaDB | 10.6+ | [mariadb.org](https://mariadb.org/download/) |
|
||||
| Git | latest | [git-scm.com](https://git-scm.com/) |
|
||||
|
||||
@@ -182,7 +182,7 @@ ng serve
|
||||
|
||||
The UI will be available at http://localhost:4200 with hot-reload enabled.
|
||||
|
||||
> If you hit dependency issues, try `npm install --legacy-peer-deps`.
|
||||
> If you hit dependency issues, try `npm ci --force`.
|
||||
|
||||
---
|
||||
|
||||
@@ -265,8 +265,8 @@ Before opening your PR:
|
||||
- [ ] PR is linked to an **approved** issue (PRs without a linked issue will be closed)
|
||||
- [ ] All tests pass (`./gradlew test` and `ng test`)
|
||||
- [ ] Actual test output is pasted in the PR description
|
||||
- [ ] Code follows project conventions (see [Code Style](#code-style))
|
||||
- [ ] IntelliJ linter shows no errors
|
||||
- [ ] Code follows project conventions (see [Backend Conventions](#backend-conventions), [Frontend Conventions](#frontend-conventions))
|
||||
- [ ] No lint errors
|
||||
- [ ] Branch is up-to-date with `develop`
|
||||
- [ ] You ran the full stack locally and manually verified the change works
|
||||
- [ ] PR description includes a screen recording or screenshots proving it works
|
||||
@@ -276,6 +276,8 @@ Before opening your PR:
|
||||
- [ ] **PR is reasonably sized.** PRs with 1000+ changed lines will be closed without review. Break large changes into small, focused PRs.
|
||||
- [ ] **For user-facing features:** submit a companion docs PR at [booklore-docs](https://github.com/booklore-app/booklore-docs)
|
||||
|
||||
> When you open your PR on GitHub, a **PR template** will appear. Fill it out completely, including test output and screenshots.
|
||||
|
||||
### AI-Assisted Contributions
|
||||
|
||||
Contributions using AI tools (Copilot, Claude, ChatGPT, etc.) are welcome, but the quality bar is the same as human-written code. **If you ship it, you own it.**
|
||||
@@ -293,14 +295,32 @@ We've seen a sharp increase in AI-generated PRs where the contributor clearly ne
|
||||
|
||||
---
|
||||
|
||||
## Code Style
|
||||
## Backend Conventions
|
||||
|
||||
| Area | Convention |
|
||||
|------------|--------------------------------------------------------------------|
|
||||
| Angular | Follow the [official style guide](https://angular.dev/style-guide) |
|
||||
| Java | Modern Java 21 features, clean structure |
|
||||
| Formatting | Use IntelliJ IDEA's built-in linter |
|
||||
| UI | SCSS with PrimeNG components |
|
||||
- Use Spring Data JPA repository methods or JPQL. No native queries unless explicitly approved by a maintainer.
|
||||
- Constructor injection via Lombok `@AllArgsConstructor`. No `@Autowired`.
|
||||
- Logging via Lombok `@Slf4j`. No manual `LoggerFactory.getLogger(...)`.
|
||||
- Throw errors via `ApiError` enum (`ApiError.SOME_ERROR.createException()`). No raw `RuntimeException`.
|
||||
- Entities use `*Entity` suffix; DTOs drop it (e.g., `BookEntity` vs `Book`).
|
||||
- Use MapStruct for entity-to-DTO mapping. No hand-written mapping code.
|
||||
- Security: `@PreAuthorize("@securityUtil.isAdmin()")` or `@CheckBookAccess`. No `@Secured` or `@RolesAllowed`.
|
||||
- Testing: JUnit 5 + Mockito + AssertJ. `@ExtendWith(MockitoExtension.class)` for unit tests, `@SpringBootTest` only for integration tests.
|
||||
- Use modern Java features (records, sealed classes, pattern matching, text blocks, etc.).
|
||||
- No fully qualified class names inline. Always use imports.
|
||||
- Flyway migrations go in `booklore-api/src/main/resources/db/migration/` with naming `V<number>__<Description>.sql`.
|
||||
- Never modify a released migration. Always create a new migration file for changes.
|
||||
- Use idempotent guards in migrations (`CREATE TABLE IF NOT EXISTS`, `ADD COLUMN IF NOT EXISTS`, `DROP ... IF EXISTS` before re-creating).
|
||||
|
||||
---
|
||||
|
||||
## Frontend Conventions
|
||||
|
||||
- Follow the [Angular style guide](https://angular.dev/style-guide).
|
||||
- All components are standalone. No NgModules.
|
||||
- Use `inject()` for dependency injection. No constructor injection.
|
||||
- PrimeNG for UI components. SCSS for styling. Transloco for i18n.
|
||||
- Testing with Vitest (not Karma/Jasmine).
|
||||
- All UI features must be responsive (desktop + mobile).
|
||||
|
||||
---
|
||||
|
||||
|
||||
+2
-2
@@ -5,7 +5,7 @@ WORKDIR /angular-app
|
||||
|
||||
COPY ./booklore-ui/package.json ./booklore-ui/package-lock.json ./
|
||||
RUN --mount=type=cache,target=/root/.npm \
|
||||
npm config set registry http://registry.npmjs.org/ \
|
||||
npm config set registry https://registry.npmjs.org/ \
|
||||
&& npm ci --force
|
||||
|
||||
COPY ./booklore-ui /angular-app/
|
||||
@@ -54,7 +54,7 @@ LABEL org.opencontainers.image.title="BookLore" \
|
||||
org.opencontainers.image.licenses="GPL-3.0" \
|
||||
org.opencontainers.image.base.name="docker.io/library/eclipse-temurin:25-jre-alpine"
|
||||
|
||||
ENV JAVA_TOOL_OPTIONS="-XX:+UseG1GC -XX:MaxGCPauseMillis=200 -XX:+UseStringDeduplication -XX:+UseContainerSupport -XX:+UseCompactObjectHeaders -XX:MaxRAMPercentage=75.0"
|
||||
ENV JAVA_TOOL_OPTIONS="-XX:+UseG1GC -XX:+UseCompactObjectHeaders -XX:+UseStringDeduplication -XX:MaxRAMPercentage=75.0 -XX:+ExitOnOutOfMemoryError"
|
||||
|
||||
ARG TARGETARCH
|
||||
RUN apk update && apk add --no-cache su-exec libstdc++ libgcc && \
|
||||
|
||||
+1
-1
@@ -16,7 +16,7 @@ LABEL org.opencontainers.image.title="BookLore" \
|
||||
org.opencontainers.image.licenses="GPL-3.0" \
|
||||
org.opencontainers.image.base.name="docker.io/library/eclipse-temurin:25-jre-alpine"
|
||||
|
||||
ENV JAVA_TOOL_OPTIONS="-XX:+UseG1GC -XX:MaxGCPauseMillis=200 -XX:+UseStringDeduplication -XX:+UseContainerSupport -XX:+UseCompactObjectHeaders -XX:MaxRAMPercentage=75.0"
|
||||
ENV JAVA_TOOL_OPTIONS="-XX:+UseG1GC -XX:+UseCompactObjectHeaders -XX:+UseStringDeduplication -XX:MaxRAMPercentage=75.0 -XX:+ExitOnOutOfMemoryError"
|
||||
|
||||
ARG TARGETARCH
|
||||
RUN apk update && apk add --no-cache su-exec libstdc++ libgcc
|
||||
|
||||
@@ -212,7 +212,7 @@ volumes:
|
||||
| 💬 **Come hang out** | [Discord Server](https://discord.gg/Ee5hd458Uz) |
|
||||
|
||||
> [!WARNING]
|
||||
> **Before opening a PR:** Open an issue first and get maintainer approval. PRs without a linked issue, without screenshots/video proof, or without pasted test output will be closed. AI-assisted contributions are welcome, but you must run, test, and understand every line you submit. See the [Contributing Guide](CONTRIBUTING.md) for full details.
|
||||
> **Before opening a PR:** Open an issue first and get maintainer approval. PRs without a linked issue, without screenshots/video proof, or without pasted test output will be closed. All code must follow project [backend](CONTRIBUTING.md#backend-conventions) and [frontend](CONTRIBUTING.md#frontend-conventions) conventions. AI-assisted contributions are welcome, but you must run, test, and understand every line you submit. See the [Contributing Guide](CONTRIBUTING.md) for full details.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ plugins {
|
||||
id 'java'
|
||||
id 'org.springframework.boot' version '4.0.3'
|
||||
id 'io.spring.dependency-management' version '1.1.7'
|
||||
id 'org.hibernate.orm' version '7.2.4.Final'
|
||||
id 'org.hibernate.orm' version '7.2.5.Final'
|
||||
id 'com.github.ben-manes.versions' version '0.53.0'
|
||||
id 'jacoco'
|
||||
}
|
||||
@@ -44,7 +44,7 @@ dependencies {
|
||||
// --- Database & Migration ---
|
||||
implementation 'org.mariadb.jdbc:mariadb-java-client:3.5.7'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-flyway'
|
||||
implementation 'org.flywaydb:flyway-mysql:12.0.1'
|
||||
implementation 'org.flywaydb:flyway-mysql:12.0.2'
|
||||
|
||||
// --- Security & Authentication ---
|
||||
implementation 'io.jsonwebtoken:jjwt-api:0.13.0'
|
||||
@@ -65,10 +65,10 @@ dependencies {
|
||||
implementation 'com.github.jai-imageio:jai-imageio-jpeg2000:1.4.0'
|
||||
|
||||
// --- TwelveMonkeys ImageIO ---
|
||||
implementation 'com.twelvemonkeys.imageio:imageio-jpeg:3.13.0'
|
||||
implementation 'com.twelvemonkeys.imageio:imageio-tiff:3.13.0'
|
||||
implementation 'com.twelvemonkeys.imageio:imageio-webp:3.13.0'
|
||||
implementation 'com.twelvemonkeys.imageio:imageio-bmp:3.13.0'
|
||||
implementation 'com.twelvemonkeys.imageio:imageio-jpeg:3.13.1'
|
||||
implementation 'com.twelvemonkeys.imageio:imageio-tiff:3.13.1'
|
||||
implementation 'com.twelvemonkeys.imageio:imageio-webp:3.13.1'
|
||||
implementation 'com.twelvemonkeys.imageio:imageio-bmp:3.13.1'
|
||||
|
||||
implementation 'io.documentnode:epub4j-core:4.2.3'
|
||||
|
||||
@@ -76,7 +76,7 @@ dependencies {
|
||||
implementation 'net.jthink:jaudiotagger:3.0.1'
|
||||
|
||||
// --- UNRAR Support ---
|
||||
implementation 'com.github.junrar:junrar:7.5.7'
|
||||
implementation 'com.github.junrar:junrar:7.5.8'
|
||||
|
||||
// --- JSON & Web Scraping ---
|
||||
implementation 'org.jsoup:jsoup:1.22.1'
|
||||
@@ -99,7 +99,7 @@ dependencies {
|
||||
implementation 'org.freemarker:freemarker:2.3.34'
|
||||
|
||||
// --- Jackson 3 ---
|
||||
implementation platform('tools.jackson:jackson-bom:3.0.4')
|
||||
implementation platform('tools.jackson:jackson-bom:3.1.0')
|
||||
implementation 'tools.jackson.core:jackson-core'
|
||||
implementation 'tools.jackson.core:jackson-databind'
|
||||
implementation 'tools.jackson.module:jackson-module-blackbird'
|
||||
|
||||
@@ -222,6 +222,7 @@ public class SecurityConfig {
|
||||
.headers(headers -> headers
|
||||
.referrerPolicy(referrer -> referrer.policy(
|
||||
ReferrerPolicyHeaderWriter.ReferrerPolicy.STRICT_ORIGIN_WHEN_CROSS_ORIGIN))
|
||||
.contentTypeOptions(contentType -> {})
|
||||
)
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.dispatcherTypeMatchers(DispatcherType.ASYNC).permitAll()
|
||||
@@ -242,6 +243,7 @@ public class SecurityConfig {
|
||||
.frameOptions(HeadersConfigurer.FrameOptionsConfig::sameOrigin)
|
||||
.referrerPolicy(referrer -> referrer.policy(
|
||||
ReferrerPolicyHeaderWriter.ReferrerPolicy.STRICT_ORIGIN_WHEN_CROSS_ORIGIN))
|
||||
.contentTypeOptions(contentType -> {})
|
||||
)
|
||||
.authorizeHttpRequests(auth -> auth.anyRequest().permitAll());
|
||||
return http.build();
|
||||
|
||||
@@ -46,6 +46,7 @@ public class AudiobookReaderController {
|
||||
@ApiResponse(responseCode = "200", description = "Full audio file returned")
|
||||
@ApiResponse(responseCode = "206", description = "Partial content returned (range request)")
|
||||
@ApiResponse(responseCode = "416", description = "Range not satisfiable")
|
||||
@CheckBookAccess(bookIdParam = "bookId")
|
||||
@GetMapping("/{bookId}/stream")
|
||||
public void streamAudiobook(
|
||||
@Parameter(description = "ID of the book") @PathVariable Long bookId,
|
||||
@@ -62,6 +63,7 @@ public class AudiobookReaderController {
|
||||
@ApiResponse(responseCode = "200", description = "Full track file returned")
|
||||
@ApiResponse(responseCode = "206", description = "Partial content returned (range request)")
|
||||
@ApiResponse(responseCode = "416", description = "Range not satisfiable")
|
||||
@CheckBookAccess(bookIdParam = "bookId")
|
||||
@GetMapping("/{bookId}/track/{trackIndex}/stream")
|
||||
public void streamTrack(
|
||||
@Parameter(description = "ID of the book") @PathVariable Long bookId,
|
||||
@@ -79,6 +81,7 @@ public class AudiobookReaderController {
|
||||
"Uses token query parameter for authentication.")
|
||||
@ApiResponse(responseCode = "200", description = "Cover art returned successfully")
|
||||
@ApiResponse(responseCode = "404", description = "No embedded cover art found")
|
||||
@CheckBookAccess(bookIdParam = "bookId")
|
||||
@GetMapping("/{bookId}/cover")
|
||||
public ResponseEntity<byte[]> getEmbeddedCover(
|
||||
@Parameter(description = "ID of the book") @PathVariable Long bookId,
|
||||
|
||||
@@ -12,6 +12,7 @@ import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
@@ -69,7 +70,7 @@ public class AuthorController {
|
||||
@PutMapping("/{authorId}")
|
||||
public ResponseEntity<AuthorDetails> updateAuthor(
|
||||
@Parameter(description = "ID of the author") @PathVariable long authorId,
|
||||
@RequestBody AuthorUpdateRequest request) {
|
||||
@RequestBody @Valid AuthorUpdateRequest request) {
|
||||
return ResponseEntity.ok(authorMetadataService.updateAuthor(authorId, request));
|
||||
}
|
||||
|
||||
@@ -101,7 +102,7 @@ public class AuthorController {
|
||||
@PostMapping("/{authorId}/match")
|
||||
public ResponseEntity<AuthorDetails> matchAuthor(
|
||||
@Parameter(description = "ID of the author") @PathVariable long authorId,
|
||||
@RequestBody AuthorMatchRequest request) {
|
||||
@RequestBody @Valid AuthorMatchRequest request) {
|
||||
return ResponseEntity.ok(authorMetadataService.matchAuthor(authorId, request));
|
||||
}
|
||||
|
||||
|
||||
@@ -36,10 +36,12 @@ import jakarta.servlet.http.HttpServletResponse;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.Max;
|
||||
import jakarta.validation.constraints.Min;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
@@ -47,6 +49,7 @@ import java.util.Set;
|
||||
|
||||
@Tag(name = "Books", description = "Endpoints for managing books, their metadata, progress, and recommendations")
|
||||
@RequestMapping("/api/v1/books")
|
||||
@Validated
|
||||
@RestController
|
||||
@AllArgsConstructor
|
||||
public class BookController {
|
||||
@@ -190,7 +193,7 @@ public class BookController {
|
||||
@PutMapping("/{bookId}/viewer-setting")
|
||||
@CheckBookAccess(bookIdParam = "bookId")
|
||||
public ResponseEntity<Void> updateBookViewerSettings(
|
||||
@Parameter(description = "Viewer settings to update") @RequestBody BookViewerSettings bookViewerSettings,
|
||||
@Parameter(description = "Viewer settings to update") @RequestBody @Valid BookViewerSettings bookViewerSettings,
|
||||
@Parameter(description = "ID of the book") @PathVariable long bookId) {
|
||||
bookService.updateBookViewerSetting(bookId, bookViewerSettings);
|
||||
return ResponseEntity.noContent().build();
|
||||
@@ -237,7 +240,7 @@ public class BookController {
|
||||
})
|
||||
@PostMapping("/reset-progress")
|
||||
public ResponseEntity<List<BookStatusUpdateResponse>> resetProgress(
|
||||
@Parameter(description = "List of book IDs to reset progress for") @RequestBody List<Long> bookIds,
|
||||
@Parameter(description = "List of book IDs to reset progress for") @RequestBody @Size(max = 500) List<Long> bookIds,
|
||||
@Parameter(description = "Type of progress reset") @RequestParam ResetProgressType type) {
|
||||
if (bookIds == null || bookIds.isEmpty()) {
|
||||
throw ApiError.GENERIC_BAD_REQUEST.createException("No book IDs provided");
|
||||
@@ -260,7 +263,7 @@ public class BookController {
|
||||
})
|
||||
@PostMapping("/reset-personal-rating")
|
||||
public ResponseEntity<List<PersonalRatingUpdateResponse>> resetPersonalRating(
|
||||
@Parameter(description = "List of book IDs to reset personal rating for") @RequestBody List<Long> bookIds) {
|
||||
@Parameter(description = "List of book IDs to reset personal rating for") @RequestBody @Size(max = 500) List<Long> bookIds) {
|
||||
if (bookIds == null || bookIds.isEmpty()) {
|
||||
throw ApiError.GENERIC_BAD_REQUEST.createException("No book IDs provided");
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
@@ -18,6 +19,7 @@ import java.util.List;
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/api/v1/bookmarks")
|
||||
@PreAuthorize("isAuthenticated()")
|
||||
@Tag(name = "Bookmarks", description = "Endpoints for managing book bookmarks")
|
||||
public class BookMarkController {
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
@@ -44,7 +45,7 @@ public class EmailProviderV2Controller {
|
||||
@PreAuthorize("@securityUtil.isAdmin() or @securityUtil.canEmailBook()")
|
||||
@PostMapping
|
||||
public ResponseEntity<EmailProviderV2> createEmailProvider(
|
||||
@Parameter(description = "Email provider creation request") @RequestBody CreateEmailProviderRequest createEmailProviderRequest) {
|
||||
@Parameter(description = "Email provider creation request") @RequestBody @Valid CreateEmailProviderRequest createEmailProviderRequest) {
|
||||
return ResponseEntity.ok(service.createEmailProvider(createEmailProviderRequest));
|
||||
}
|
||||
|
||||
@@ -54,7 +55,7 @@ public class EmailProviderV2Controller {
|
||||
@PutMapping("/{id}")
|
||||
public ResponseEntity<EmailProviderV2> updateEmailProvider(
|
||||
@Parameter(description = "ID of the email provider") @PathVariable Long id,
|
||||
@Parameter(description = "Email provider update request") @RequestBody CreateEmailProviderRequest updateRequest) {
|
||||
@Parameter(description = "Email provider update request") @RequestBody @Valid CreateEmailProviderRequest updateRequest) {
|
||||
return ResponseEntity.ok(service.updateEmailProvider(id, updateRequest));
|
||||
}
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
@@ -44,7 +45,7 @@ public class EmailRecipientV2Controller {
|
||||
@PreAuthorize("@securityUtil.isAdmin() or @securityUtil.canEmailBook()")
|
||||
@PostMapping
|
||||
public ResponseEntity<EmailRecipientV2> createEmailRecipient(
|
||||
@Parameter(description = "Email recipient creation request") @RequestBody CreateEmailRecipientRequest createEmailRecipientRequest) {
|
||||
@Parameter(description = "Email recipient creation request") @RequestBody @Valid CreateEmailRecipientRequest createEmailRecipientRequest) {
|
||||
return ResponseEntity.ok(service.createEmailRecipient(createEmailRecipientRequest));
|
||||
}
|
||||
|
||||
@@ -54,7 +55,7 @@ public class EmailRecipientV2Controller {
|
||||
@PutMapping("/{id}")
|
||||
public ResponseEntity<EmailRecipientV2> updateEmailRecipient(
|
||||
@Parameter(description = "ID of the email recipient") @PathVariable Long id,
|
||||
@Parameter(description = "Email recipient update request") @RequestBody CreateEmailRecipientRequest updateRequest) {
|
||||
@Parameter(description = "Email recipient update request") @RequestBody @Valid CreateEmailRecipientRequest updateRequest) {
|
||||
return ResponseEntity.ok(service.updateEmailRecipient(id, updateRequest));
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package org.booklore.controller;
|
||||
|
||||
import org.booklore.config.security.annotation.CheckBookAccess;
|
||||
import org.booklore.model.dto.response.EpubBookInfo;
|
||||
import org.booklore.service.reader.EpubReaderService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
@@ -30,6 +31,7 @@ public class EpubReaderController {
|
||||
@Operation(summary = "Get EPUB book info",
|
||||
description = "Retrieve parsed metadata, spine, manifest, and TOC for an EPUB book.")
|
||||
@ApiResponse(responseCode = "200", description = "Book info returned successfully")
|
||||
@CheckBookAccess(bookIdParam = "bookId")
|
||||
@GetMapping("/{bookId}/info")
|
||||
public ResponseEntity<EpubBookInfo> getBookInfo(
|
||||
@Parameter(description = "ID of the book") @PathVariable Long bookId,
|
||||
@@ -39,6 +41,7 @@ public class EpubReaderController {
|
||||
|
||||
@Operation(summary = "Get file from EPUB", description = "Retrieve a specific file from within the EPUB archive (HTML, CSS, images, fonts, etc.).")
|
||||
@ApiResponse(responseCode = "200", description = "File content returned successfully")
|
||||
@CheckBookAccess(bookIdParam = "bookId")
|
||||
@GetMapping("/{bookId}/file/**")
|
||||
public void getFile(
|
||||
@Parameter(description = "ID of the book") @PathVariable Long bookId,
|
||||
|
||||
@@ -9,6 +9,7 @@ import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
@@ -26,7 +27,7 @@ public class FileMoveController {
|
||||
@ApiResponse(responseCode = "200", description = "Files moved successfully")
|
||||
@PostMapping("/move")
|
||||
@PreAuthorize("@securityUtil.canManageLibrary() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<?> moveFiles(@Parameter(description = "File move request") @RequestBody FileMoveRequest request) {
|
||||
public ResponseEntity<?> moveFiles(@Parameter(description = "File move request") @RequestBody @Valid FileMoveRequest request) {
|
||||
fileMoveService.bulkMoveFiles(request);
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
|
||||
+2
-1
@@ -5,6 +5,7 @@ import org.booklore.service.hardcover.HardcoverSyncSettingsService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
@@ -35,7 +36,7 @@ public class HardcoverSyncSettingsController {
|
||||
@ApiResponse(responseCode = "200", description = "Settings updated successfully")
|
||||
@PutMapping
|
||||
@PreAuthorize("@securityUtil.canSyncKobo() or @securityUtil.canSyncKoReader() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<HardcoverSyncSettings> updateSettings(@RequestBody HardcoverSyncSettings settings) {
|
||||
public ResponseEntity<HardcoverSyncSettings> updateSettings(@RequestBody @Valid HardcoverSyncSettings settings) {
|
||||
HardcoverSyncSettings updated = hardcoverSyncSettingsService.updateCurrentUserSettings(settings);
|
||||
return ResponseEntity.ok(updated);
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import org.booklore.service.kobo.KoboSettingsService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
@@ -41,7 +42,7 @@ public class KoboSettingsController {
|
||||
@ApiResponse(responseCode = "200", description = "Settings updated successfully")
|
||||
@PutMapping
|
||||
@PreAuthorize("@securityUtil.canSyncKobo() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<KoboSyncSettings> updateSettings(@RequestBody KoboSyncSettings settings) {
|
||||
public ResponseEntity<KoboSyncSettings> updateSettings(@RequestBody @Valid KoboSyncSettings settings) {
|
||||
KoboSyncSettings updated = koboService.updateSettings(settings);
|
||||
return ResponseEntity.ok(updated);
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import org.booklore.config.security.annotation.CheckLibraryAccess;
|
||||
import org.booklore.model.dto.Book;
|
||||
import org.booklore.model.dto.Library;
|
||||
import org.booklore.model.dto.request.CreateLibraryRequest;
|
||||
import org.booklore.service.library.LibraryHealthService;
|
||||
import org.booklore.service.library.LibraryService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
@@ -26,6 +27,7 @@ import java.util.Map;
|
||||
public class LibraryController {
|
||||
|
||||
private final LibraryService libraryService;
|
||||
private final LibraryHealthService libraryHealthService;
|
||||
|
||||
@Operation(summary = "Get all libraries", description = "Retrieve a list of all libraries.")
|
||||
@ApiResponse(responseCode = "200", description = "Libraries returned successfully")
|
||||
@@ -34,6 +36,13 @@ public class LibraryController {
|
||||
return ResponseEntity.ok(libraryService.getLibraries());
|
||||
}
|
||||
|
||||
@Operation(summary = "Get library health", description = "Check accessibility of all library paths.")
|
||||
@ApiResponse(responseCode = "200", description = "Library health returned successfully")
|
||||
@GetMapping("/health")
|
||||
public ResponseEntity<Map<Long, Boolean>> getLibraryHealth() {
|
||||
return ResponseEntity.ok(libraryHealthService.getCurrentHealth());
|
||||
}
|
||||
|
||||
@Operation(summary = "Get a library by ID", description = "Retrieve details of a specific library by its ID.")
|
||||
@ApiResponses({
|
||||
@ApiResponse(responseCode = "200", description = "Library details returned successfully"),
|
||||
|
||||
@@ -6,6 +6,7 @@ import org.booklore.mapper.BookMetadataMapper;
|
||||
import org.booklore.model.MetadataUpdateContext;
|
||||
import org.booklore.model.MetadataUpdateWrapper;
|
||||
import org.booklore.model.dto.BookMetadata;
|
||||
import org.booklore.model.dto.request.IsbnLookupRequest;
|
||||
import org.booklore.model.dto.request.*;
|
||||
import org.booklore.model.entity.BookEntity;
|
||||
import org.booklore.model.enums.MetadataProvider;
|
||||
@@ -64,7 +65,8 @@ public class MetadataController {
|
||||
public ResponseEntity<BookMetadata> updateMetadata(
|
||||
@Parameter(description = "Metadata update wrapper") @RequestBody MetadataUpdateWrapper metadataUpdateWrapper,
|
||||
@Parameter(description = "ID of the book") @PathVariable long bookId,
|
||||
@Parameter(description = "Merge categories") @RequestParam(defaultValue = "false") boolean mergeCategories) {
|
||||
@Parameter(description = "Merge categories") @RequestParam(defaultValue = "false") boolean mergeCategories,
|
||||
@Parameter(description = "Replace mode") @RequestParam(defaultValue = "REPLACE_ALL") MetadataReplaceMode replaceMode) {
|
||||
BookEntity bookEntity = bookRepository.findAllWithMetadataByIds(java.util.Collections.singleton(bookId)).stream()
|
||||
.findFirst()
|
||||
.orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||
@@ -74,7 +76,7 @@ public class MetadataController {
|
||||
.metadataUpdateWrapper(metadataUpdateWrapper)
|
||||
.updateThumbnail(true)
|
||||
.mergeCategories(mergeCategories)
|
||||
.replaceMode(MetadataReplaceMode.REPLACE_ALL)
|
||||
.replaceMode(replaceMode)
|
||||
.mergeMoods(false)
|
||||
.mergeTags(false)
|
||||
.build();
|
||||
@@ -142,6 +144,19 @@ public class MetadataController {
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
@Operation(summary = "Lookup metadata by ISBN", description = "Fetch metadata for a book by ISBN. Requires library management permission or admin.")
|
||||
@ApiResponse(responseCode = "200", description = "Metadata found")
|
||||
@ApiResponse(responseCode = "404", description = "No metadata found for the given ISBN")
|
||||
@PostMapping("/metadata/isbn-lookup")
|
||||
@PreAuthorize("@securityUtil.canManageLibrary() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<BookMetadata> lookupByIsbn(@RequestBody IsbnLookupRequest request) {
|
||||
BookMetadata metadata = bookMetadataService.lookupByIsbn(request);
|
||||
if (metadata == null) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
return ResponseEntity.ok(metadata);
|
||||
}
|
||||
|
||||
@Operation(summary = "Get detailed metadata from provider", description = "Fetch full metadata details for a specific item from a provider. Requires metadata edit permission or admin.")
|
||||
@ApiResponse(responseCode = "200", description = "Detailed metadata returned successfully")
|
||||
@GetMapping("/metadata/detail/{provider}/{providerItemId}")
|
||||
|
||||
@@ -8,6 +8,7 @@ import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
@@ -35,7 +36,7 @@ public class OpdsUserV2Controller {
|
||||
@PostMapping
|
||||
@PreAuthorize("@securityUtil.isAdmin() or @securityUtil.canAccessOpds()")
|
||||
public OpdsUserV2 createUser(
|
||||
@Parameter(description = "OPDS user creation request") @RequestBody OpdsUserV2CreateRequest createRequest) {
|
||||
@Parameter(description = "OPDS user creation request") @RequestBody @Valid OpdsUserV2CreateRequest createRequest) {
|
||||
return service.createOpdsUser(createRequest);
|
||||
}
|
||||
|
||||
@@ -54,6 +55,6 @@ public class OpdsUserV2Controller {
|
||||
@PreAuthorize("@securityUtil.isAdmin() or @securityUtil.canAccessOpds()")
|
||||
public OpdsUserV2 updateUser(
|
||||
@Parameter(description = "ID of the OPDS user to update") @PathVariable Long id,
|
||||
@Parameter(description = "OPDS user update request") @RequestBody OpdsUserV2UpdateRequest updateRequest) {
|
||||
@Parameter(description = "OPDS user update request") @RequestBody @Valid OpdsUserV2UpdateRequest updateRequest) {
|
||||
return service.updateOpdsUser(id, updateRequest);
|
||||
}}
|
||||
@@ -7,11 +7,15 @@ import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponses;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.Max;
|
||||
import jakarta.validation.constraints.Min;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@Validated
|
||||
@RestController
|
||||
@AllArgsConstructor
|
||||
@RequestMapping("/api/v1/reading-sessions")
|
||||
@@ -39,8 +43,8 @@ public class ReadingSessionController {
|
||||
@GetMapping("/book/{bookId}")
|
||||
public ResponseEntity<Page<ReadingSessionResponse>> getReadingSessionsForBook(
|
||||
@PathVariable Long bookId,
|
||||
@RequestParam(defaultValue = "0") int page,
|
||||
@RequestParam(defaultValue = "5") int size) {
|
||||
@RequestParam(defaultValue = "0") @Min(0) int page,
|
||||
@RequestParam(defaultValue = "5") @Min(1) @Max(100) int size) {
|
||||
Page<ReadingSessionResponse> sessions = readingSessionService.getReadingSessionsForBook(bookId, page, size);
|
||||
return ResponseEntity.ok(sessions);
|
||||
}
|
||||
|
||||
@@ -75,7 +75,7 @@ public class UserController {
|
||||
@Operation(summary = "Change password", description = "Change the password for the current user.")
|
||||
@ApiResponse(responseCode = "200", description = "Password changed successfully")
|
||||
@PutMapping("/change-password")
|
||||
public ResponseEntity<?> changePassword(@Parameter(description = "Change password request") @RequestBody ChangePasswordRequest request) {
|
||||
public ResponseEntity<?> changePassword(@Parameter(description = "Change password request") @RequestBody @Valid ChangePasswordRequest request) {
|
||||
userService.changePassword(request);
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
@@ -84,7 +84,7 @@ public class UserController {
|
||||
@ApiResponse(responseCode = "200", description = "Password changed successfully")
|
||||
@PutMapping("/change-user-password")
|
||||
@PreAuthorize("@securityUtil.isAdmin()")
|
||||
public ResponseEntity<?> changeUserPassword(@Parameter(description = "Change user password request") @RequestBody ChangeUserPasswordRequest request) {
|
||||
public ResponseEntity<?> changeUserPassword(@Parameter(description = "Change user password request") @RequestBody @Valid ChangeUserPasswordRequest request) {
|
||||
userService.changeUserPassword(request);
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
@@ -95,7 +95,7 @@ public class UserController {
|
||||
@PreAuthorize("@securityUtil.isSelf(#id)")
|
||||
public void updateUserSetting(
|
||||
@Parameter(description = "ID of the user") @PathVariable Long id,
|
||||
@Parameter(description = "Update user setting request") @RequestBody UpdateUserSettingRequest request) {
|
||||
@Parameter(description = "Update user setting request") @RequestBody @Valid UpdateUserSettingRequest request) {
|
||||
userService.updateUserSetting(id, request);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,7 +29,8 @@ public class GlobalExceptionHandler {
|
||||
|
||||
@ExceptionHandler(HttpMessageNotReadableException.class)
|
||||
public ResponseEntity<ErrorResponse> handleHttpMessageNotReadableException(HttpMessageNotReadableException ex) {
|
||||
ErrorResponse errorResponse = new ErrorResponse(HttpStatus.BAD_REQUEST.value(), "Request body is missing or malformed: " + ex.getMostSpecificCause().getMessage());
|
||||
log.warn("Malformed request body: {}", ex.getMessage());
|
||||
ErrorResponse errorResponse = new ErrorResponse(HttpStatus.BAD_REQUEST.value(), "Request body is missing or malformed.");
|
||||
return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
|
||||
@@ -58,7 +59,8 @@ public class GlobalExceptionHandler {
|
||||
|
||||
@ExceptionHandler(DataIntegrityViolationException.class)
|
||||
public ResponseEntity<ErrorResponse> handleDataIntegrityViolation(DataIntegrityViolationException ex) {
|
||||
ErrorResponse errorResponse = new ErrorResponse(HttpStatus.BAD_REQUEST.value(), ex.getMessage());
|
||||
log.warn("Data integrity violation: {}", ex.getMessage());
|
||||
ErrorResponse errorResponse = new ErrorResponse(HttpStatus.BAD_REQUEST.value(), "A data conflict occurred. The operation could not be completed.");
|
||||
return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
|
||||
@@ -114,8 +116,8 @@ public class GlobalExceptionHandler {
|
||||
|
||||
@ExceptionHandler(Exception.class)
|
||||
public ResponseEntity<ErrorResponse> handleGenericException(Exception ex) {
|
||||
ErrorResponse errorResponse = new ErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR.value(), ex.getMessage());
|
||||
log.error(ex.getMessage(), ex);
|
||||
log.error("Unhandled exception: {}", ex.getMessage(), ex);
|
||||
ErrorResponse errorResponse = new ErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR.value(), "An unexpected error occurred.");
|
||||
return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,6 +32,7 @@ import jakarta.persistence.EntityManager;
|
||||
import jakarta.persistence.Tuple;
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@@ -263,7 +264,7 @@ public class MobileBookService {
|
||||
}
|
||||
|
||||
long maxOffset = Math.max(0, totalElements - pageSize);
|
||||
int randomOffset = (int) (Math.random() * (maxOffset + 1));
|
||||
int randomOffset = ThreadLocalRandom.current().nextInt((int) maxOffset + 1);
|
||||
|
||||
Pageable pageable = PageRequest.of(randomOffset / pageSize, pageSize);
|
||||
Page<BookEntity> bookPage = bookRepository.findAll(spec, pageable);
|
||||
|
||||
@@ -87,6 +87,12 @@ public enum RuleField {
|
||||
ABRIDGED,
|
||||
@JsonProperty("audiobookDuration")
|
||||
AUDIOBOOK_DURATION,
|
||||
@JsonProperty("audiobookCodec")
|
||||
AUDIOBOOK_CODEC,
|
||||
@JsonProperty("audiobookChapterCount")
|
||||
AUDIOBOOK_CHAPTER_COUNT,
|
||||
@JsonProperty("audiobookBitrate")
|
||||
AUDIOBOOK_BITRATE,
|
||||
@JsonProperty("isPhysical")
|
||||
IS_PHYSICAL,
|
||||
@JsonProperty("seriesStatus")
|
||||
|
||||
+1
@@ -27,4 +27,5 @@ public class CreatePhysicalBookRequest {
|
||||
private String language;
|
||||
private Integer pageCount;
|
||||
private List<String> categories;
|
||||
private String thumbnailUrl;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
package org.booklore.model.dto.request;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Builder
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class IsbnLookupRequest {
|
||||
private String isbn;
|
||||
}
|
||||
+3
-1
@@ -1,6 +1,8 @@
|
||||
package org.booklore.model.dto.request;
|
||||
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public record PersonalRatingUpdateRequest(List<Long> ids, Integer rating) {
|
||||
public record PersonalRatingUpdateRequest(@Size(max = 500) List<Long> ids, Integer rating) {
|
||||
}
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
package org.booklore.model.websocket;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public record LibraryHealthPayload(Map<Long, Boolean> libraryHealth) {}
|
||||
@@ -15,7 +15,8 @@ public enum Topic {
|
||||
BOOK_METADATA_BATCH_PROGRESS("/queue/book-metadata-batch-progress"),
|
||||
BOOKDROP_FILE("/queue/bookdrop-file"),
|
||||
LOG("/queue/log"),
|
||||
TASK_PROGRESS("/queue/task-progress");
|
||||
TASK_PROGRESS("/queue/task-progress"),
|
||||
LIBRARY_HEALTH("/topic/library-health");
|
||||
|
||||
private final String path;
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
|
||||
@Repository
|
||||
public interface AuthorRepository extends JpaRepository<AuthorEntity, Long> {
|
||||
@@ -23,4 +24,10 @@ public interface AuthorRepository extends JpaRepository<AuthorEntity, Long> {
|
||||
|
||||
@Query("SELECT a, COUNT(bm) FROM AuthorEntity a LEFT JOIN a.bookMetadataEntityList bm GROUP BY a ORDER BY a.name")
|
||||
List<Object[]> findAllWithBookCount();
|
||||
|
||||
@Query("SELECT a, COUNT(DISTINCT bm) FROM AuthorEntity a LEFT JOIN a.bookMetadataEntityList bm JOIN bm.book b WHERE b.library.id IN :libraryIds GROUP BY a ORDER BY a.name")
|
||||
List<Object[]> findAllWithBookCountByLibraryIds(@Param("libraryIds") Set<Long> libraryIds);
|
||||
|
||||
@Query("SELECT COUNT(b) > 0 FROM AuthorEntity a JOIN a.bookMetadataEntityList bm JOIN bm.book b WHERE a.id = :authorId AND b.library.id IN :libraryIds")
|
||||
boolean existsByIdAndLibraryIds(@Param("authorId") Long authorId, @Param("libraryIds") Set<Long> libraryIds);
|
||||
}
|
||||
|
||||
@@ -2,11 +2,16 @@ package org.booklore.repository;
|
||||
|
||||
import org.booklore.model.entity.LibraryPathEntity;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public interface LibraryPathRepository extends JpaRepository<LibraryPathEntity, Long> {
|
||||
Optional<LibraryPathEntity> findByLibraryIdAndPath(Long libraryId, String path);
|
||||
|
||||
@Query("SELECT lp FROM LibraryPathEntity lp JOIN FETCH lp.library")
|
||||
List<LibraryPathEntity> findAllWithLibrary();
|
||||
}
|
||||
|
||||
@@ -3,10 +3,13 @@ package org.booklore.service;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.booklore.exception.ApiError;
|
||||
import org.booklore.config.security.service.AuthenticationService;
|
||||
import org.booklore.model.dto.AuthorDetails;
|
||||
import org.booklore.model.dto.AuthorSearchResult;
|
||||
import org.booklore.model.dto.AuthorSummary;
|
||||
import org.booklore.model.dto.BookLoreUser;
|
||||
import org.booklore.model.dto.CoverImage;
|
||||
import org.booklore.model.dto.Library;
|
||||
import org.booklore.model.dto.request.AuthorMatchRequest;
|
||||
import org.booklore.model.dto.request.AuthorUpdateRequest;
|
||||
import org.booklore.model.entity.AuthorEntity;
|
||||
@@ -32,6 +35,8 @@ import java.nio.file.Paths;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@@ -43,9 +48,19 @@ public class AuthorMetadataService {
|
||||
private final AuditService auditService;
|
||||
private final FileService fileService;
|
||||
private final DuckDuckGoCoverService duckDuckGoCoverService;
|
||||
private final AuthenticationService authenticationService;
|
||||
|
||||
public List<AuthorSummary> getAllAuthors() {
|
||||
List<Object[]> results = authorRepository.findAllWithBookCount();
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
List<Object[]> results;
|
||||
if (user.getPermissions().isAdmin()) {
|
||||
results = authorRepository.findAllWithBookCount();
|
||||
} else {
|
||||
Set<Long> libraryIds = user.getAssignedLibraries().stream()
|
||||
.map(Library::getId)
|
||||
.collect(Collectors.toSet());
|
||||
results = authorRepository.findAllWithBookCountByLibraryIds(libraryIds);
|
||||
}
|
||||
List<AuthorSummary> summaries = new ArrayList<>();
|
||||
for (Object[] row : results) {
|
||||
AuthorEntity author = (AuthorEntity) row[0];
|
||||
@@ -244,12 +259,14 @@ public class AuthorMetadataService {
|
||||
public AuthorDetails getAuthorByName(String name) {
|
||||
AuthorEntity author = authorRepository.findByNameIgnoreCase(name)
|
||||
.orElseThrow(() -> ApiError.AUTHOR_NOT_FOUND.createException(name));
|
||||
verifyAuthorAccess(author.getId());
|
||||
return toAuthorDetails(author);
|
||||
}
|
||||
|
||||
public AuthorDetails getAuthorDetails(Long authorId) {
|
||||
AuthorEntity author = authorRepository.findById(authorId)
|
||||
.orElseThrow(() -> ApiError.AUTHOR_NOT_FOUND.createException(authorId));
|
||||
verifyAuthorAccess(authorId);
|
||||
return toAuthorDetails(author);
|
||||
}
|
||||
|
||||
@@ -277,6 +294,19 @@ public class AuthorMetadataService {
|
||||
return null;
|
||||
}
|
||||
|
||||
private void verifyAuthorAccess(Long authorId) {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
if (user.getPermissions().isAdmin()) {
|
||||
return;
|
||||
}
|
||||
Set<Long> libraryIds = user.getAssignedLibraries().stream()
|
||||
.map(Library::getId)
|
||||
.collect(Collectors.toSet());
|
||||
if (libraryIds.isEmpty() || !authorRepository.existsByIdAndLibraryIds(authorId, libraryIds)) {
|
||||
throw ApiError.AUTHOR_NOT_FOUND.createException(authorId);
|
||||
}
|
||||
}
|
||||
|
||||
private void applyMetadataResult(AuthorEntity author, AuthorSearchResult result) {
|
||||
if (!author.isDescriptionLocked()) {
|
||||
author.setDescription(result.getDescription());
|
||||
|
||||
@@ -772,6 +772,9 @@ public class BookRuleEvaluatorService {
|
||||
case AUDIBLE_REVIEW_COUNT -> root.get("metadata").get("audibleReviewCount");
|
||||
case ABRIDGED -> root.get("metadata").get("abridged");
|
||||
case AUDIOBOOK_DURATION -> root.join("bookFiles", JoinType.LEFT).get("durationSeconds");
|
||||
case AUDIOBOOK_CODEC -> root.join("bookFiles", JoinType.LEFT).get("codec");
|
||||
case AUDIOBOOK_CHAPTER_COUNT -> root.join("bookFiles", JoinType.LEFT).get("chapterCount");
|
||||
case AUDIOBOOK_BITRATE -> root.join("bookFiles", JoinType.LEFT).get("bitrate");
|
||||
case IS_PHYSICAL -> root.get("isPhysical");
|
||||
case READING_PROGRESS -> {
|
||||
Expression<Float> koreader = cb.coalesce(progressJoin.get("koreaderProgressPercent"), 0f);
|
||||
@@ -928,7 +931,8 @@ public class BookRuleEvaluatorService {
|
||||
RuleField.GOODREADS_RATING, RuleField.GOODREADS_REVIEW_COUNT,
|
||||
RuleField.HARDCOVER_RATING, RuleField.HARDCOVER_REVIEW_COUNT,
|
||||
RuleField.LUBIMYCZYTAC_RATING, RuleField.RANOBEDB_RATING,
|
||||
RuleField.AUDIBLE_RATING, RuleField.AUDIBLE_REVIEW_COUNT
|
||||
RuleField.AUDIBLE_RATING, RuleField.AUDIBLE_REVIEW_COUNT,
|
||||
RuleField.AUDIOBOOK_CHAPTER_COUNT, RuleField.AUDIOBOOK_BITRATE
|
||||
);
|
||||
|
||||
private static boolean isNumericField(RuleField field) {
|
||||
|
||||
@@ -150,7 +150,9 @@ public class BookQueryService {
|
||||
m.setExternalUrl(null);
|
||||
m.setThumbnailUrl(null);
|
||||
m.setProvider(null);
|
||||
m.setAudiobookMetadata(null);
|
||||
if (m.getAudiobookMetadata() != null) {
|
||||
m.getAudiobookMetadata().setChapters(null);
|
||||
}
|
||||
m.setBookReviews(null);
|
||||
|
||||
// Strip unused ratings
|
||||
|
||||
@@ -110,8 +110,17 @@ public class BookService {
|
||||
|
||||
public List<Book> getBooksByIds(Set<Long> bookIds, boolean withDescription) {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
boolean isAdmin = user.getPermissions().isAdmin();
|
||||
|
||||
List<BookEntity> bookEntities = bookQueryService.findAllWithMetadataByIds(bookIds);
|
||||
|
||||
if (!isAdmin) {
|
||||
Set<Long> userLibraryIds = getUserLibraryIds(user);
|
||||
bookEntities = bookEntities.stream()
|
||||
.filter(book -> userLibraryIds.contains(book.getLibrary().getId()))
|
||||
.toList();
|
||||
}
|
||||
|
||||
Set<Long> entityIds = bookEntities.stream().map(BookEntity::getId).collect(Collectors.toSet());
|
||||
|
||||
Map<Long, UserBookProgressEntity> progressMap =
|
||||
@@ -363,7 +372,15 @@ public class BookService {
|
||||
|
||||
@Transactional
|
||||
public ResponseEntity<BookDeletionResponse> deleteBooks(Set<Long> ids) {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
List<BookEntity> books = bookQueryService.findAllWithMetadataByIds(ids);
|
||||
|
||||
if (!user.getPermissions().isAdmin()) {
|
||||
Set<Long> userLibraryIds = getUserLibraryIds(user);
|
||||
books = books.stream()
|
||||
.filter(book -> userLibraryIds.contains(book.getLibrary().getId()))
|
||||
.toList();
|
||||
}
|
||||
List<Long> failedFileDeletions = new ArrayList<>();
|
||||
for (BookEntity book : books) {
|
||||
for (BookFileEntity bookFile : book.getBookFiles()) {
|
||||
@@ -408,7 +425,7 @@ public class BookService {
|
||||
}
|
||||
}
|
||||
|
||||
bookRepository.deleteAll(books);
|
||||
bookRepository.deleteAllInBatch(books);
|
||||
auditService.log(AuditAction.BOOK_DELETED, "Deleted " + ids.size() + " book(s)");
|
||||
BookDeletionResponse response = new BookDeletionResponse(ids, failedFileDeletions);
|
||||
return failedFileDeletions.isEmpty()
|
||||
|
||||
@@ -13,6 +13,8 @@ import org.booklore.repository.AuthorRepository;
|
||||
import org.booklore.repository.BookRepository;
|
||||
import org.booklore.repository.CategoryRepository;
|
||||
import org.booklore.repository.LibraryRepository;
|
||||
import org.booklore.util.BookCoverUtils;
|
||||
import org.booklore.util.FileService;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.HttpStatus;
|
||||
@@ -37,6 +39,7 @@ public class PhysicalBookService {
|
||||
private final AuthorRepository authorRepository;
|
||||
private final CategoryRepository categoryRepository;
|
||||
private final BookMapper bookMapper;
|
||||
private final FileService fileService;
|
||||
|
||||
@Transactional
|
||||
public Book createPhysicalBook(CreatePhysicalBookRequest request) {
|
||||
@@ -76,6 +79,17 @@ public class PhysicalBookService {
|
||||
BookEntity savedBook = bookRepository.save(bookEntity);
|
||||
log.info("Created physical book '{}' in library {} with id {}", request.getTitle(), library.getName(), savedBook.getId());
|
||||
|
||||
if (request.getThumbnailUrl() != null && !request.getThumbnailUrl().isBlank()) {
|
||||
try {
|
||||
fileService.createThumbnailFromUrl(savedBook.getId(), request.getThumbnailUrl());
|
||||
savedBook.getMetadata().setCoverUpdatedOn(Instant.now());
|
||||
savedBook.setBookCoverHash(BookCoverUtils.generateCoverHash());
|
||||
savedBook = bookRepository.save(savedBook);
|
||||
} catch (Exception ex) {
|
||||
log.warn("Failed to download cover for physical book {}: {}", savedBook.getId(), ex.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
return bookMapper.toBook(savedBook);
|
||||
}
|
||||
|
||||
|
||||
@@ -30,6 +30,7 @@ import org.springframework.mail.javamail.MimeMessageHelper;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.Properties;
|
||||
|
||||
@Slf4j
|
||||
@@ -80,9 +81,9 @@ public class SendEmailV2Service {
|
||||
notificationService.sendMessage(Topic.LOG, LogNotification.info(successMessage));
|
||||
log.info(successMessage);
|
||||
} catch (Exception e) {
|
||||
String errorMessage = "An error occurred while sending the book: " + bookTitle + " to " + recipientEmail + ". Error: " + e.getMessage();
|
||||
notificationService.sendMessage(Topic.LOG, LogNotification.error(errorMessage));
|
||||
log.error(errorMessage, e);
|
||||
String userMessage = "Failed to send book: " + bookTitle + " to " + recipientEmail + ". " + extractUserFriendlyMessage(e);
|
||||
notificationService.sendMessage(Topic.LOG, LogNotification.error(userMessage));
|
||||
log.error("Email send failed for book '{}' to {}: {}", bookTitle, recipientEmail, e.getMessage(), e);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -202,6 +203,20 @@ public class SendEmailV2Service {
|
||||
.orElseThrow(ApiError.DEFAULT_EMAIL_PROVIDER_NOT_FOUND::createException);
|
||||
}
|
||||
|
||||
private String extractUserFriendlyMessage(Exception e) {
|
||||
Throwable cause = e;
|
||||
while (cause != null) {
|
||||
if (cause instanceof IOException) {
|
||||
return "The email provider rejected or dropped the connection during transfer. This often happens when the attachment exceeds the provider's size limit.";
|
||||
}
|
||||
cause = cause.getCause();
|
||||
}
|
||||
if (e instanceof MessagingException) {
|
||||
return "The email could not be sent due to a mail server error. Please verify your email provider settings.";
|
||||
}
|
||||
return "An unexpected error occurred: " + e.getMessage();
|
||||
}
|
||||
|
||||
private enum ConnectionType {
|
||||
SSL,
|
||||
STARTTLS,
|
||||
|
||||
@@ -2,8 +2,10 @@ package org.booklore.service.file;
|
||||
|
||||
import org.booklore.mapper.AdditionalFileMapper;
|
||||
import org.booklore.model.dto.BookFile;
|
||||
import org.booklore.model.entity.BookEntity;
|
||||
import org.booklore.model.entity.BookFileEntity;
|
||||
import org.booklore.repository.BookAdditionalFileRepository;
|
||||
import org.booklore.repository.BookRepository;
|
||||
import org.booklore.service.monitoring.MonitoringRegistrationService;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -37,6 +39,7 @@ public class AdditionalFileService {
|
||||
private static final Pattern NON_ASCII = Pattern.compile("[^\\x00-\\x7F]");
|
||||
|
||||
private final BookAdditionalFileRepository additionalFileRepository;
|
||||
private final BookRepository bookRepository;
|
||||
private final AdditionalFileMapper additionalFileMapper;
|
||||
private final MonitoringRegistrationService monitoringRegistrationService;
|
||||
|
||||
@@ -58,13 +61,13 @@ public class AdditionalFileService {
|
||||
}
|
||||
|
||||
BookFileEntity file = fileOpt.get();
|
||||
BookEntity book = file.getBook();
|
||||
|
||||
try {
|
||||
monitoringRegistrationService.unregisterSpecificPath(file.getFullFilePath().getParent());
|
||||
|
||||
Path filePath = file.getFullFilePath();
|
||||
if (file.isFolderBased() && Files.isDirectory(filePath)) {
|
||||
// For folder-based audiobooks, delete the entire directory
|
||||
deleteDirectoryRecursively(filePath);
|
||||
log.info("Deleted folder-based audiobook: {}", filePath);
|
||||
} else {
|
||||
@@ -77,6 +80,17 @@ public class AdditionalFileService {
|
||||
log.warn("Failed to delete physical file: {}", file.getFullFilePath(), e);
|
||||
additionalFileRepository.delete(file);
|
||||
}
|
||||
|
||||
if (file.isBook() && book != null) {
|
||||
book.getBookFiles().remove(file);
|
||||
boolean hasRemainingBookFiles = book.getBookFiles().stream()
|
||||
.anyMatch(BookFileEntity::isBook);
|
||||
if (!hasRemainingBookFiles) {
|
||||
book.setIsPhysical(true);
|
||||
bookRepository.save(book);
|
||||
log.info("Book {} reverted to physical (last book file removed)", book.getId());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void deleteDirectoryRecursively(Path path) throws IOException {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package org.booklore.service.file;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.booklore.exception.ApiError;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.IOException;
|
||||
@@ -9,6 +10,7 @@ import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
@@ -16,8 +18,19 @@ import java.util.stream.Stream;
|
||||
@Service
|
||||
public class PathService {
|
||||
|
||||
private static final Set<String> BLOCKED_PATHS = Set.of(
|
||||
"/proc", "/sys", "/dev", "/run", "/var/run"
|
||||
);
|
||||
|
||||
public List<String> getFoldersAtPath(String path) {
|
||||
Path directory = Paths.get(path);
|
||||
Path directory = Paths.get(path).toAbsolutePath().normalize();
|
||||
String normalized = directory.toString();
|
||||
|
||||
if (BLOCKED_PATHS.stream().anyMatch(blocked -> normalized.equals(blocked) || normalized.startsWith(blocked + "/"))) {
|
||||
log.warn("Blocked path browsing attempt to restricted directory: {}", normalized);
|
||||
throw ApiError.GENERIC_BAD_REQUEST.createException("Access to this directory is not allowed");
|
||||
}
|
||||
|
||||
if (!Files.exists(directory) || !Files.isDirectory(directory)) {
|
||||
log.warn("Invalid path or not a directory: {}", path);
|
||||
return Collections.emptyList();
|
||||
|
||||
@@ -39,6 +39,7 @@ public class KoboServerProxy {
|
||||
|
||||
private static final Set<String> HEADERS_OUT_INCLUDE = Set.of(
|
||||
HttpHeaders.AUTHORIZATION.toLowerCase(),
|
||||
HttpHeaders.AUTHORIZATION,
|
||||
HttpHeaders.USER_AGENT,
|
||||
HttpHeaders.ACCEPT,
|
||||
HttpHeaders.ACCEPT_LANGUAGE
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
package org.booklore.service.library;
|
||||
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.booklore.model.entity.LibraryPathEntity;
|
||||
import org.booklore.model.websocket.LibraryHealthPayload;
|
||||
import org.booklore.model.websocket.Topic;
|
||||
import org.booklore.repository.LibraryPathRepository;
|
||||
import org.springframework.messaging.simp.SimpMessagingTemplate;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class LibraryHealthService {
|
||||
|
||||
private final LibraryPathRepository libraryPathRepository;
|
||||
private final SimpMessagingTemplate messagingTemplate;
|
||||
private final ConcurrentHashMap<Long, Boolean> previousHealth = new ConcurrentHashMap<>();
|
||||
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
var health = checkHealth();
|
||||
previousHealth.putAll(health);
|
||||
}
|
||||
|
||||
@Scheduled(fixedDelay = 30, timeUnit = TimeUnit.SECONDS)
|
||||
public void checkAndBroadcast() {
|
||||
var health = checkHealth();
|
||||
if (!health.equals(previousHealth)) {
|
||||
previousHealth.clear();
|
||||
previousHealth.putAll(health);
|
||||
messagingTemplate.convertAndSend(Topic.LIBRARY_HEALTH.getPath(), new LibraryHealthPayload(health));
|
||||
}
|
||||
}
|
||||
|
||||
public Map<Long, Boolean> getCurrentHealth() {
|
||||
return Map.copyOf(previousHealth);
|
||||
}
|
||||
|
||||
private Map<Long, Boolean> checkHealth() {
|
||||
return libraryPathRepository.findAllWithLibrary().stream()
|
||||
.collect(Collectors.groupingBy(
|
||||
lp -> lp.getLibrary().getId(),
|
||||
Collectors.reducing(true, this::isPathAccessible, Boolean::logicalAnd)
|
||||
));
|
||||
}
|
||||
|
||||
private boolean isPathAccessible(LibraryPathEntity libraryPath) {
|
||||
var path = Path.of(libraryPath.getPath());
|
||||
return Files.exists(path) && Files.isReadable(path);
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,8 @@ import org.booklore.service.metadata.extractor.CbxMetadataExtractor;
|
||||
import org.booklore.service.metadata.extractor.MetadataExtractorFactory;
|
||||
import org.booklore.service.metadata.parser.BookParser;
|
||||
import org.booklore.service.metadata.parser.DetailedMetadataProvider;
|
||||
import org.booklore.service.appsettings.AppSettingService;
|
||||
import org.booklore.model.dto.request.MetadataRefreshOptions;
|
||||
import org.booklore.util.FileUtils;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -38,12 +40,13 @@ import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
|
||||
import org.booklore.model.dto.request.IsbnLookupRequest;
|
||||
|
||||
import java.io.File;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@@ -62,6 +65,7 @@ public class BookMetadataService {
|
||||
private final MetadataExtractorFactory metadataExtractorFactory;
|
||||
private final MetadataClearFlagsMapper metadataClearFlagsMapper;
|
||||
private final PlatformTransactionManager transactionManager;
|
||||
private final AppSettingService appSettingService;
|
||||
|
||||
|
||||
public Flux<BookMetadata> getProspectiveMetadataListForBookId(long bookId, FetchMetadataRequest request) {
|
||||
@@ -85,6 +89,52 @@ public class BookMetadataService {
|
||||
}
|
||||
|
||||
|
||||
public BookMetadata lookupByIsbn(IsbnLookupRequest request) {
|
||||
List<MetadataProvider> providers = deriveProviderChainFromSettings();
|
||||
|
||||
FetchMetadataRequest fetchRequest = FetchMetadataRequest.builder()
|
||||
.isbn(request.getIsbn())
|
||||
.providers(providers)
|
||||
.build();
|
||||
|
||||
Book emptyBook = Book.builder().build();
|
||||
|
||||
for (MetadataProvider provider : providers) {
|
||||
try {
|
||||
List<BookMetadata> results = fetchMetadataListFromAProvider(provider, emptyBook, fetchRequest);
|
||||
if (results != null && !results.isEmpty()) {
|
||||
return results.getFirst();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("ISBN lookup failed for provider {}: {}", provider, e.getMessage());
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private List<MetadataProvider> deriveProviderChainFromSettings() {
|
||||
try {
|
||||
MetadataRefreshOptions options = appSettingService.getAppSettings().getDefaultMetadataRefreshOptions();
|
||||
if (options != null && options.getFieldOptions() != null) {
|
||||
MetadataRefreshOptions.FieldProvider titleProvider = options.getFieldOptions().getTitle();
|
||||
if (titleProvider != null) {
|
||||
List<MetadataProvider> chain = Stream.of(
|
||||
titleProvider.getP1(), titleProvider.getP2(),
|
||||
titleProvider.getP3(), titleProvider.getP4())
|
||||
.filter(Objects::nonNull)
|
||||
.distinct()
|
||||
.toList();
|
||||
if (!chain.isEmpty()) {
|
||||
return chain;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to derive provider chain from settings, falling back to default: {}", e.getMessage());
|
||||
}
|
||||
return List.of(MetadataProvider.Google);
|
||||
}
|
||||
|
||||
public BookMetadata getDetailedProviderMetadata(MetadataProvider provider, String providerItemId) {
|
||||
BookParser parser = getParser(provider);
|
||||
if (parser instanceof DetailedMetadataProvider detailedProvider) {
|
||||
|
||||
+4
-1
@@ -96,7 +96,7 @@ public class GoodReadsParser implements BookParser, DetailedMetadataProvider {
|
||||
public List<BookMetadata> fetchMetadata(Book book, FetchMetadataRequest fetchMetadataRequest) {
|
||||
String isbn = ParserUtils.cleanIsbn(fetchMetadataRequest.getIsbn());
|
||||
if (isbn != null && !isbn.isBlank()) {
|
||||
log.info("Goodreads Query URL (ISBN): " + BASE_ISBN_URL + "{}", isbn);
|
||||
log.info("Goodreads Query URL (ISBN): {}{}", BASE_ISBN_URL, isbn);
|
||||
Document doc = fetchDoc(BASE_ISBN_URL + isbn);
|
||||
String ogUrl = Optional.ofNullable(doc.selectFirst("meta[property=og:url]"))
|
||||
.map(e -> e.attr("content"))
|
||||
@@ -417,6 +417,9 @@ public class GoodReadsParser implements BookParser, DetailedMetadataProvider {
|
||||
}
|
||||
|
||||
private LocalDate convertToLocalDate(String timestamp) {
|
||||
if (timestamp == null || timestamp.isBlank() || "null".equals(timestamp)) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
long millis = Long.parseLong(timestamp);
|
||||
return Instant.ofEpochMilli(millis)
|
||||
|
||||
@@ -4,6 +4,7 @@ import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.booklore.config.security.service.AuthenticationService;
|
||||
import org.booklore.exception.ApiError;
|
||||
import org.booklore.config.security.userdetails.OpdsUserDetails;
|
||||
import org.booklore.model.dto.Book;
|
||||
import org.booklore.model.dto.BookFile;
|
||||
@@ -747,9 +748,10 @@ public class OpdsFeedService {
|
||||
|
||||
private Long getUserId() {
|
||||
OpdsUserDetails details = authenticationService.getOpdsUser();
|
||||
return details != null && details.getOpdsUserV2() != null
|
||||
? details.getOpdsUserV2().getUserId()
|
||||
: null;
|
||||
if (details == null || details.getOpdsUserV2() == null) {
|
||||
throw ApiError.FORBIDDEN.createException("OPDS authentication required");
|
||||
}
|
||||
return details.getOpdsUserV2().getUserId();
|
||||
}
|
||||
|
||||
private OpdsSortOrder getSortOrder() {
|
||||
|
||||
@@ -116,11 +116,13 @@ public class FileUploadService {
|
||||
final String fileSubPath;
|
||||
final BookFileType effectiveBookType;
|
||||
|
||||
// Handle physical books that are getting their first file
|
||||
if (wasPhysicalBook) {
|
||||
// Physical book - determine library path and subpath
|
||||
LibraryPathEntity libraryPath = determineLibraryPathForPhysicalBook(book);
|
||||
book.setLibraryPath(libraryPath);
|
||||
// Handle physical books or books that lost all their files
|
||||
if (wasPhysicalBook || book.getPrimaryBookFile() == null) {
|
||||
LibraryPathEntity libraryPath = book.getLibraryPath();
|
||||
if (libraryPath == null) {
|
||||
libraryPath = determineLibraryPathForPhysicalBook(book);
|
||||
book.setLibraryPath(libraryPath);
|
||||
}
|
||||
|
||||
String pattern = fileMovingHelper.getFileNamingPattern(book.getLibrary());
|
||||
String resolvedRelativePath = PathPatternResolver.resolvePattern(book.getMetadata(), pattern, sanitizedFileName);
|
||||
|
||||
@@ -323,8 +323,9 @@ public class FileService {
|
||||
String requestUrl = uri.getScheme() + "://" + hostInUrl + portSuffix + path + (query != null ? "?" + query : "");
|
||||
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
// Set original 'Host' header for server-side virtual hosting
|
||||
headers.set(HttpHeaders.HOST, host);
|
||||
// Host header is set in prepareConnection via setRequestProperty.
|
||||
// Do NOT set it here: Spring's addRequestProperty would add a duplicate,
|
||||
// and duplicate Host headers cause 400 on strict CDNs like CloudFront.
|
||||
headers.set(HttpHeaders.USER_AGENT, "BookLore/1.0 (Book and Comic Metadata Fetcher; +https://github.com/booklore-app/booklore)");
|
||||
headers.set(HttpHeaders.ACCEPT, "image/*");
|
||||
|
||||
|
||||
@@ -46,6 +46,10 @@ spring:
|
||||
request-timeout: 600000
|
||||
application:
|
||||
name: booklore-api
|
||||
data:
|
||||
web:
|
||||
pageable:
|
||||
max-page-size: 100
|
||||
datasource:
|
||||
url: ${DATABASE_URL:jdbc:mariadb://${DATABASE_HOST:${DB_HOST:mariadb}}:${DATABASE_PORT:3306}/${DATABASE_NAME:booklore}?createDatabaseIfNotExist=true}
|
||||
username: ${DATABASE_USERNAME:root}
|
||||
|
||||
@@ -9,6 +9,7 @@ import org.booklore.model.entity.BookEntity;
|
||||
import org.booklore.model.entity.BookMetadataEntity;
|
||||
import org.booklore.repository.BookRepository;
|
||||
import org.booklore.service.audit.AuditService;
|
||||
import org.booklore.model.enums.MetadataReplaceMode;
|
||||
import org.booklore.service.metadata.*;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
@@ -45,7 +46,7 @@ class MetadataControllerTest {
|
||||
@InjectMocks
|
||||
private MetadataController metadataController;
|
||||
|
||||
private MetadataUpdateContext captureContextFromUpdate() {
|
||||
private MetadataUpdateContext captureContextFromUpdate(MetadataReplaceMode replaceMode) {
|
||||
long bookId = 1L;
|
||||
MetadataUpdateWrapper wrapper = MetadataUpdateWrapper.builder().build();
|
||||
BookEntity bookEntity = new BookEntity();
|
||||
@@ -55,7 +56,7 @@ class MetadataControllerTest {
|
||||
when(bookRepository.findAllWithMetadataByIds(java.util.Collections.singleton(bookId))).thenReturn(java.util.List.of(bookEntity));
|
||||
when(bookMetadataMapper.toBookMetadata(any(), anyBoolean())).thenReturn(new BookMetadata());
|
||||
|
||||
metadataController.updateMetadata(wrapper, bookId, true);
|
||||
metadataController.updateMetadata(wrapper, bookId, true, replaceMode);
|
||||
|
||||
ArgumentCaptor<MetadataUpdateContext> captor = ArgumentCaptor.forClass(MetadataUpdateContext.class);
|
||||
verify(bookMetadataUpdater).setBookMetadata(captor.capture());
|
||||
@@ -64,9 +65,23 @@ class MetadataControllerTest {
|
||||
|
||||
@Test
|
||||
void updateMetadata_shouldDisableMergingForTagsAndMoods() {
|
||||
MetadataUpdateContext context = captureContextFromUpdate();
|
||||
MetadataUpdateContext context = captureContextFromUpdate(MetadataReplaceMode.REPLACE_ALL);
|
||||
|
||||
assertFalse(context.isMergeTags(), "mergeTags should be false to allow deletion of tags");
|
||||
assertFalse(context.isMergeMoods(), "mergeMoods should be false to allow deletion of moods");
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateMetadata_shouldPassReplaceModeFromParam() {
|
||||
MetadataUpdateContext context = captureContextFromUpdate(MetadataReplaceMode.REPLACE_WHEN_PROVIDED);
|
||||
|
||||
assertEquals(MetadataReplaceMode.REPLACE_WHEN_PROVIDED, context.getReplaceMode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateMetadata_shouldDefaultToReplaceAll() {
|
||||
MetadataUpdateContext context = captureContextFromUpdate(MetadataReplaceMode.REPLACE_ALL);
|
||||
|
||||
assertEquals(MetadataReplaceMode.REPLACE_ALL, context.getReplaceMode());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import org.booklore.model.entity.BookEntity;
|
||||
import org.booklore.model.entity.BookFileEntity;
|
||||
import org.booklore.model.entity.LibraryPathEntity;
|
||||
import org.booklore.repository.BookAdditionalFileRepository;
|
||||
import org.booklore.repository.BookRepository;
|
||||
import org.booklore.service.file.AdditionalFileService;
|
||||
import org.booklore.service.monitoring.MonitoringRegistrationService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
@@ -38,6 +39,9 @@ class AdditionalFileServiceTest {
|
||||
@Mock
|
||||
private BookAdditionalFileRepository additionalFileRepository;
|
||||
|
||||
@Mock
|
||||
private BookRepository bookRepository;
|
||||
|
||||
@Mock
|
||||
private AdditionalFileMapper additionalFileMapper;
|
||||
|
||||
@@ -175,6 +179,8 @@ class AdditionalFileServiceTest {
|
||||
verify(monitoringRegistrationService).unregisterSpecificPath(parentPath);
|
||||
filesMock.verify(() -> Files.deleteIfExists(fileEntity.getFullFilePath()));
|
||||
verify(additionalFileRepository).delete(fileEntity);
|
||||
verify(bookRepository).save(bookEntity);
|
||||
assertTrue(bookEntity.getIsPhysical());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -194,6 +200,8 @@ class AdditionalFileServiceTest {
|
||||
verify(monitoringRegistrationService).unregisterSpecificPath(parentPath);
|
||||
filesMock.verify(() -> Files.deleteIfExists(fileEntity.getFullFilePath()));
|
||||
verify(additionalFileRepository).delete(fileEntity);
|
||||
verify(bookRepository).save(bookEntity);
|
||||
assertTrue(bookEntity.getIsPhysical());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
package org.booklore.service;
|
||||
|
||||
import org.booklore.config.security.service.AuthenticationService;
|
||||
import org.booklore.exception.APIException;
|
||||
import org.booklore.model.dto.AuthorDetails;
|
||||
import org.booklore.model.dto.AuthorSearchResult;
|
||||
import org.booklore.model.dto.BookLoreUser;
|
||||
import org.booklore.model.dto.request.AuthorMatchRequest;
|
||||
import org.booklore.model.entity.AuthorEntity;
|
||||
import org.booklore.model.enums.AuditAction;
|
||||
@@ -28,6 +30,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.*;
|
||||
import static org.mockito.Mockito.lenient;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class AuthorMetadataServiceTest {
|
||||
@@ -37,6 +40,7 @@ class AuthorMetadataServiceTest {
|
||||
@Mock private AuditService auditService;
|
||||
@Mock private FileService fileService;
|
||||
@Mock private DuckDuckGoCoverService duckDuckGoCoverService;
|
||||
@Mock private AuthenticationService authenticationService;
|
||||
|
||||
private AuthorMetadataService service;
|
||||
|
||||
@@ -45,7 +49,12 @@ class AuthorMetadataServiceTest {
|
||||
Map<AuthorMetadataSource, AuthorParser> authorParserMap = Map.of(
|
||||
AuthorMetadataSource.AUDNEXUS, authorParser
|
||||
);
|
||||
service = new AuthorMetadataService(authorRepository, authorParserMap, auditService, fileService, duckDuckGoCoverService);
|
||||
service = new AuthorMetadataService(authorRepository, authorParserMap, auditService, fileService, duckDuckGoCoverService, authenticationService);
|
||||
|
||||
BookLoreUser.UserPermissions adminPermissions = new BookLoreUser.UserPermissions();
|
||||
adminPermissions.setAdmin(true);
|
||||
BookLoreUser adminUser = BookLoreUser.builder().id(1L).permissions(adminPermissions).build();
|
||||
lenient().when(authenticationService.getAuthenticatedUser()).thenReturn(adminUser);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -374,8 +374,9 @@ class BookServiceTest {
|
||||
Files.createDirectories(filePath.getParent());
|
||||
Files.write(filePath, "abc".getBytes());
|
||||
|
||||
doNothing().when(bookRepository).deleteAll(anyList());
|
||||
doNothing().when(bookRepository).deleteAllInBatch(anyList());
|
||||
when(bookQueryService.findAllWithMetadataByIds(Set.of(11L))).thenReturn(List.of(entity));
|
||||
when(authenticationService.getAuthenticatedUser()).thenReturn(testUser);
|
||||
|
||||
BookDeletionResponse response = bookService.deleteBooks(Set.of(11L)).getBody();
|
||||
|
||||
@@ -403,7 +404,8 @@ class BookServiceTest {
|
||||
entity.setBookFiles(List.of(primaryFile));
|
||||
|
||||
when(bookQueryService.findAllWithMetadataByIds(Set.of(13L))).thenReturn(List.of(entity));
|
||||
doNothing().when(bookRepository).deleteAll(anyList());
|
||||
when(authenticationService.getAuthenticatedUser()).thenReturn(testUser);
|
||||
doNothing().when(bookRepository).deleteAllInBatch(anyList());
|
||||
|
||||
BookDeletionResponse response = bookService.deleteBooks(Set.of(13L)).getBody();
|
||||
|
||||
|
||||
@@ -7,6 +7,9 @@ import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
@@ -86,6 +89,23 @@ class KoboServerProxyTest {
|
||||
.thenReturn(httpResponse);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = { "Authorization", "authorization" })
|
||||
void proxyCurrentRequest_withSquareBracketsInQueryParams_shouldIncludeAuthHeaders(String authHeader) throws Exception {
|
||||
mockRequest.setQueryString("Filter=ALL");
|
||||
mockRequest.addHeader("User-Agent", "Kobo/1.0");
|
||||
mockRequest.addHeader(authHeader, "jwt.looking.token");
|
||||
setupSuccessfulProxyResponse();
|
||||
|
||||
ResponseEntity<JsonNode> response = koboServerProxy.proxyCurrentRequest(null, false);
|
||||
|
||||
assertThat(response).isNotNull();
|
||||
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
ArgumentCaptor<HttpRequest> captor = ArgumentCaptor.forClass(HttpRequest.class);
|
||||
verify(httpClient).<String>send(captor.capture(), any());
|
||||
assertThat(captor.getValue().headers().map().get(authHeader)).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void proxyCurrentRequest_withSquareBracketsInQueryParams_shouldHandleSuccessfully() throws Exception {
|
||||
// Validates fix for: IllegalArgumentException: Invalid character '[' for QUERY_PARAM
|
||||
|
||||
+161
@@ -0,0 +1,161 @@
|
||||
package org.booklore.service.library;
|
||||
|
||||
import org.booklore.model.entity.LibraryEntity;
|
||||
import org.booklore.model.entity.LibraryPathEntity;
|
||||
import org.booklore.model.websocket.LibraryHealthPayload;
|
||||
import org.booklore.model.websocket.Topic;
|
||||
import org.booklore.repository.LibraryPathRepository;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.messaging.simp.SimpMessagingTemplate;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class LibraryHealthServiceTest {
|
||||
|
||||
@Mock
|
||||
private LibraryPathRepository libraryPathRepository;
|
||||
|
||||
@Mock
|
||||
private SimpMessagingTemplate messagingTemplate;
|
||||
|
||||
private LibraryHealthService libraryHealthService;
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
when(libraryPathRepository.findAllWithLibrary()).thenReturn(List.of());
|
||||
libraryHealthService = new LibraryHealthService(libraryPathRepository, messagingTemplate);
|
||||
libraryHealthService.init();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldReportHealthyWhenAllPathsAccessible() {
|
||||
Path validPath = tempDir.resolve("books");
|
||||
validPath.toFile().mkdirs();
|
||||
|
||||
when(libraryPathRepository.findAllWithLibrary()).thenReturn(List.of(
|
||||
createLibraryPath(1L, validPath.toString())
|
||||
));
|
||||
|
||||
libraryHealthService.checkAndBroadcast();
|
||||
|
||||
Map<Long, Boolean> health = libraryHealthService.getCurrentHealth();
|
||||
assertThat(health).containsEntry(1L, true);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldReportUnhealthyWhenPathDoesNotExist() {
|
||||
when(libraryPathRepository.findAllWithLibrary()).thenReturn(List.of(
|
||||
createLibraryPath(1L, "/nonexistent/path/that/does/not/exist")
|
||||
));
|
||||
|
||||
libraryHealthService.checkAndBroadcast();
|
||||
|
||||
Map<Long, Boolean> health = libraryHealthService.getCurrentHealth();
|
||||
assertThat(health).containsEntry(1L, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldReportUnhealthyWhenAnyPathIsDown() {
|
||||
Path validPath = tempDir.resolve("books");
|
||||
validPath.toFile().mkdirs();
|
||||
|
||||
when(libraryPathRepository.findAllWithLibrary()).thenReturn(List.of(
|
||||
createLibraryPath(1L, validPath.toString()),
|
||||
createLibraryPath(1L, "/nonexistent/path")
|
||||
));
|
||||
|
||||
libraryHealthService.checkAndBroadcast();
|
||||
|
||||
Map<Long, Boolean> health = libraryHealthService.getCurrentHealth();
|
||||
assertThat(health).containsEntry(1L, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldTrackMultipleLibrariesIndependently() {
|
||||
Path validPath = tempDir.resolve("lib1");
|
||||
validPath.toFile().mkdirs();
|
||||
|
||||
when(libraryPathRepository.findAllWithLibrary()).thenReturn(List.of(
|
||||
createLibraryPath(1L, validPath.toString()),
|
||||
createLibraryPath(2L, "/nonexistent/path")
|
||||
));
|
||||
|
||||
libraryHealthService.checkAndBroadcast();
|
||||
|
||||
Map<Long, Boolean> health = libraryHealthService.getCurrentHealth();
|
||||
assertThat(health).containsEntry(1L, true);
|
||||
assertThat(health).containsEntry(2L, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldBroadcastOnlyWhenStateChanges() {
|
||||
Path validPath = tempDir.resolve("books");
|
||||
validPath.toFile().mkdirs();
|
||||
|
||||
when(libraryPathRepository.findAllWithLibrary()).thenReturn(List.of(
|
||||
createLibraryPath(1L, validPath.toString())
|
||||
));
|
||||
|
||||
libraryHealthService.checkAndBroadcast();
|
||||
verify(messagingTemplate, times(1)).convertAndSend(eq(Topic.LIBRARY_HEALTH.getPath()), any(LibraryHealthPayload.class));
|
||||
|
||||
// Same state, should not broadcast again
|
||||
libraryHealthService.checkAndBroadcast();
|
||||
verify(messagingTemplate, times(1)).convertAndSend(eq(Topic.LIBRARY_HEALTH.getPath()), any(LibraryHealthPayload.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldBroadcastWhenStateChangesFromHealthyToUnhealthy() throws Exception {
|
||||
Path validPath = tempDir.resolve("books");
|
||||
Files.createDirectories(validPath);
|
||||
|
||||
when(libraryPathRepository.findAllWithLibrary()).thenReturn(List.of(
|
||||
createLibraryPath(1L, validPath.toString())
|
||||
));
|
||||
|
||||
libraryHealthService.checkAndBroadcast();
|
||||
verify(messagingTemplate, times(1)).convertAndSend(eq(Topic.LIBRARY_HEALTH.getPath()), any(LibraryHealthPayload.class));
|
||||
|
||||
// Path disappears
|
||||
Files.delete(validPath);
|
||||
libraryHealthService.checkAndBroadcast();
|
||||
|
||||
ArgumentCaptor<LibraryHealthPayload> captor = ArgumentCaptor.forClass(LibraryHealthPayload.class);
|
||||
verify(messagingTemplate, times(2)).convertAndSend(eq(Topic.LIBRARY_HEALTH.getPath()), captor.capture());
|
||||
assertThat(captor.getValue().libraryHealth()).containsEntry(1L, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldReturnEmptyMapWhenNoLibraries() {
|
||||
when(libraryPathRepository.findAllWithLibrary()).thenReturn(List.of());
|
||||
libraryHealthService.checkAndBroadcast();
|
||||
|
||||
assertThat(libraryHealthService.getCurrentHealth()).isEmpty();
|
||||
}
|
||||
|
||||
private LibraryPathEntity createLibraryPath(Long libraryId, String path) {
|
||||
var library = new LibraryEntity();
|
||||
library.setId(libraryId);
|
||||
|
||||
var libraryPath = new LibraryPathEntity();
|
||||
libraryPath.setLibrary(library);
|
||||
libraryPath.setPath(path);
|
||||
return libraryPath;
|
||||
}
|
||||
}
|
||||
+181
@@ -554,4 +554,185 @@ class BookMetadataUpdaterTest {
|
||||
assertEquals("Existing Title", bookEntity.getMetadata().getTitle(),
|
||||
"Title should NOT be replaced when using REPLACE_MISSING mode and title exists");
|
||||
}
|
||||
|
||||
@Test
|
||||
void setBookMetadata_withReplaceWhenProvided_shouldPreserveExistingAgeRatingWhenIncomingIsNull() {
|
||||
BookEntity bookEntity = createBookEntity();
|
||||
bookEntity.getMetadata().setAgeRating(16);
|
||||
bookEntity.getMetadata().setAgeRatingLocked(false);
|
||||
|
||||
BookMetadata newMetadata = new BookMetadata();
|
||||
newMetadata.setTitle("Some Title");
|
||||
|
||||
MetadataUpdateContext context = buildContext(bookEntity, newMetadata, MetadataReplaceMode.REPLACE_WHEN_PROVIDED);
|
||||
|
||||
bookMetadataUpdater.setBookMetadata(context);
|
||||
|
||||
assertEquals(16, bookEntity.getMetadata().getAgeRating(),
|
||||
"ageRating should be preserved when incoming value is null and mode is REPLACE_WHEN_PROVIDED");
|
||||
}
|
||||
|
||||
@Test
|
||||
void setBookMetadata_withReplaceWhenProvided_shouldPreserveExistingContentRatingWhenIncomingIsNull() {
|
||||
BookEntity bookEntity = createBookEntity();
|
||||
bookEntity.getMetadata().setContentRating("Mature");
|
||||
bookEntity.getMetadata().setContentRatingLocked(false);
|
||||
|
||||
BookMetadata newMetadata = new BookMetadata();
|
||||
newMetadata.setTitle("Some Title");
|
||||
|
||||
MetadataUpdateContext context = buildContext(bookEntity, newMetadata, MetadataReplaceMode.REPLACE_WHEN_PROVIDED);
|
||||
|
||||
bookMetadataUpdater.setBookMetadata(context);
|
||||
|
||||
assertEquals("Mature", bookEntity.getMetadata().getContentRating(),
|
||||
"contentRating should be preserved when incoming value is null and mode is REPLACE_WHEN_PROVIDED");
|
||||
}
|
||||
|
||||
@Test
|
||||
void setBookMetadata_withReplaceAll_shouldClearAgeRatingWhenIncomingIsNull() {
|
||||
BookEntity bookEntity = createBookEntity();
|
||||
bookEntity.getMetadata().setAgeRating(16);
|
||||
bookEntity.getMetadata().setAgeRatingLocked(false);
|
||||
|
||||
BookMetadata newMetadata = new BookMetadata();
|
||||
|
||||
MetadataUpdateContext context = buildContext(bookEntity, newMetadata, MetadataReplaceMode.REPLACE_ALL);
|
||||
|
||||
bookMetadataUpdater.setBookMetadata(context);
|
||||
|
||||
assertNull(bookEntity.getMetadata().getAgeRating(),
|
||||
"ageRating should be cleared when incoming value is null and mode is REPLACE_ALL");
|
||||
}
|
||||
|
||||
@Test
|
||||
void setBookMetadata_withReplaceAll_shouldClearContentRatingWhenIncomingIsNull() {
|
||||
BookEntity bookEntity = createBookEntity();
|
||||
bookEntity.getMetadata().setContentRating("Mature");
|
||||
bookEntity.getMetadata().setContentRatingLocked(false);
|
||||
|
||||
BookMetadata newMetadata = new BookMetadata();
|
||||
|
||||
MetadataUpdateContext context = buildContext(bookEntity, newMetadata, MetadataReplaceMode.REPLACE_ALL);
|
||||
|
||||
bookMetadataUpdater.setBookMetadata(context);
|
||||
|
||||
assertNull(bookEntity.getMetadata().getContentRating(),
|
||||
"contentRating should be cleared when incoming value is null and mode is REPLACE_ALL");
|
||||
}
|
||||
|
||||
@Test
|
||||
void setBookMetadata_withReplaceWhenProvided_shouldUpdateAgeRatingWhenProvided() {
|
||||
BookEntity bookEntity = createBookEntity();
|
||||
bookEntity.getMetadata().setAgeRating(12);
|
||||
bookEntity.getMetadata().setAgeRatingLocked(false);
|
||||
|
||||
BookMetadata newMetadata = new BookMetadata();
|
||||
newMetadata.setAgeRating(18);
|
||||
|
||||
MetadataUpdateContext context = buildContext(bookEntity, newMetadata, MetadataReplaceMode.REPLACE_WHEN_PROVIDED);
|
||||
|
||||
bookMetadataUpdater.setBookMetadata(context);
|
||||
|
||||
assertEquals(18, bookEntity.getMetadata().getAgeRating(),
|
||||
"ageRating should be updated when a new value is provided");
|
||||
}
|
||||
|
||||
@Test
|
||||
void setBookMetadata_withReplaceWhenProvided_shouldUpdateContentRatingWhenProvided() {
|
||||
BookEntity bookEntity = createBookEntity();
|
||||
bookEntity.getMetadata().setContentRating("Teen");
|
||||
bookEntity.getMetadata().setContentRatingLocked(false);
|
||||
|
||||
BookMetadata newMetadata = new BookMetadata();
|
||||
newMetadata.setContentRating("Mature");
|
||||
|
||||
MetadataUpdateContext context = buildContext(bookEntity, newMetadata, MetadataReplaceMode.REPLACE_WHEN_PROVIDED);
|
||||
|
||||
bookMetadataUpdater.setBookMetadata(context);
|
||||
|
||||
assertEquals("Mature", bookEntity.getMetadata().getContentRating(),
|
||||
"contentRating should be updated when a new value is provided");
|
||||
}
|
||||
|
||||
@Test
|
||||
void setBookMetadata_withReplaceWhenProvided_shouldPreserveExistingTitleWhenIncomingIsNull() {
|
||||
BookEntity bookEntity = createBookEntity();
|
||||
bookEntity.getMetadata().setTitle("Existing Title");
|
||||
bookEntity.getMetadata().setTitleLocked(false);
|
||||
|
||||
BookMetadata newMetadata = new BookMetadata();
|
||||
|
||||
MetadataUpdateContext context = buildContext(bookEntity, newMetadata, MetadataReplaceMode.REPLACE_WHEN_PROVIDED);
|
||||
|
||||
bookMetadataUpdater.setBookMetadata(context);
|
||||
|
||||
assertEquals("Existing Title", bookEntity.getMetadata().getTitle(),
|
||||
"Title should be preserved when incoming value is null and mode is REPLACE_WHEN_PROVIDED");
|
||||
}
|
||||
|
||||
@Test
|
||||
void setBookMetadata_withReplaceWhenProvided_shouldPreserveAuthorsWhenIncomingIsEmpty() {
|
||||
BookEntity bookEntity = createBookEntity();
|
||||
Set<AuthorEntity> existingAuthors = new HashSet<>();
|
||||
existingAuthors.add(AuthorEntity.builder().name("Author1").build());
|
||||
bookEntity.getMetadata().setAuthors(existingAuthors);
|
||||
bookEntity.getMetadata().setAuthorsLocked(false);
|
||||
|
||||
BookMetadata newMetadata = new BookMetadata();
|
||||
|
||||
MetadataUpdateContext context = buildContext(bookEntity, newMetadata, MetadataReplaceMode.REPLACE_WHEN_PROVIDED);
|
||||
|
||||
bookMetadataUpdater.setBookMetadata(context);
|
||||
|
||||
assertEquals(1, bookEntity.getMetadata().getAuthors().size(),
|
||||
"Authors should be preserved when incoming is null/empty and mode is REPLACE_WHEN_PROVIDED");
|
||||
}
|
||||
|
||||
@Test
|
||||
void setBookMetadata_withReplaceWhenProvided_lockedFieldShouldNotBeUpdated() {
|
||||
BookEntity bookEntity = createBookEntity();
|
||||
bookEntity.getMetadata().setAgeRating(12);
|
||||
bookEntity.getMetadata().setAgeRatingLocked(true);
|
||||
|
||||
BookMetadata newMetadata = new BookMetadata();
|
||||
newMetadata.setAgeRating(18);
|
||||
|
||||
MetadataUpdateContext context = buildContext(bookEntity, newMetadata, MetadataReplaceMode.REPLACE_WHEN_PROVIDED);
|
||||
|
||||
bookMetadataUpdater.setBookMetadata(context);
|
||||
|
||||
assertEquals(12, bookEntity.getMetadata().getAgeRating(),
|
||||
"Locked ageRating should not be updated even when a new value is provided");
|
||||
}
|
||||
|
||||
private BookEntity createBookEntity() {
|
||||
BookEntity bookEntity = new BookEntity();
|
||||
bookEntity.setId(1L);
|
||||
BookMetadataEntity metadataEntity = new BookMetadataEntity();
|
||||
metadataEntity.setBook(bookEntity);
|
||||
bookEntity.setMetadata(metadataEntity);
|
||||
|
||||
BookFileEntity primaryFile = new BookFileEntity();
|
||||
primaryFile.setBook(bookEntity);
|
||||
primaryFile.setBookType(BookFileType.EPUB);
|
||||
primaryFile.setBookFormat(true);
|
||||
primaryFile.setFileSubPath("sub");
|
||||
primaryFile.setFileName("file.epub");
|
||||
bookEntity.setBookFiles(List.of(primaryFile));
|
||||
|
||||
return bookEntity;
|
||||
}
|
||||
|
||||
private MetadataUpdateContext buildContext(BookEntity bookEntity, BookMetadata newMetadata, MetadataReplaceMode replaceMode) {
|
||||
MetadataUpdateWrapper wrapper = MetadataUpdateWrapper.builder()
|
||||
.metadata(newMetadata)
|
||||
.build();
|
||||
|
||||
return MetadataUpdateContext.builder()
|
||||
.bookEntity(bookEntity)
|
||||
.metadataUpdateWrapper(wrapper)
|
||||
.replaceMode(replaceMode)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@ import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class OpdsFeedServiceTest {
|
||||
@@ -115,10 +116,11 @@ class OpdsFeedServiceTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void generateShelvesNavigation_shouldHandleNullUserDetails() {
|
||||
void generateShelvesNavigation_shouldThrowWhenNotAuthenticated() {
|
||||
when(authenticationService.getOpdsUser()).thenReturn(null);
|
||||
String xml = opdsFeedService.generateShelvesNavigation(request);
|
||||
assertThat(xml).contains("</feed>");
|
||||
assertThatThrownBy(() -> opdsFeedService.generateShelvesNavigation(request))
|
||||
.isInstanceOf(org.booklore.exception.APIException.class)
|
||||
.hasMessageContaining("OPDS authentication required");
|
||||
verify(opdsBookService, never()).getUserShelves(any());
|
||||
}
|
||||
|
||||
@@ -300,14 +302,14 @@ class OpdsFeedServiceTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void getUserId_shouldReturnNullWhenNotAuthenticated() throws Exception {
|
||||
void getUserId_shouldThrowWhenNotAuthenticated() throws Exception {
|
||||
when(authenticationService.getOpdsUser()).thenReturn(null);
|
||||
|
||||
var method = OpdsFeedService.class.getDeclaredMethod("getUserId");
|
||||
method.setAccessible(true);
|
||||
Long userId = (Long) method.invoke(opdsFeedService);
|
||||
|
||||
assertThat(userId).isNull();
|
||||
assertThatThrownBy(() -> method.invoke(opdsFeedService))
|
||||
.hasCauseInstanceOf(org.booklore.exception.APIException.class)
|
||||
.hasRootCauseMessage("OPDS authentication required");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
Generated
+765
-730
File diff suppressed because it is too large
Load Diff
+17
-17
@@ -12,16 +12,16 @@
|
||||
},
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@angular/animations": "^21.1.5",
|
||||
"@angular/cdk": "^21.1.5",
|
||||
"@angular/common": "^21.1.5",
|
||||
"@angular/compiler": "^21.1.5",
|
||||
"@angular/core": "^21.1.5",
|
||||
"@angular/forms": "^21.1.5",
|
||||
"@angular/platform-browser": "^21.1.5",
|
||||
"@angular/platform-browser-dynamic": "^21.1.5",
|
||||
"@angular/router": "^21.1.5",
|
||||
"@angular/service-worker": "^21.1.5",
|
||||
"@angular/animations": "^21.2.0",
|
||||
"@angular/cdk": "^21.2.0",
|
||||
"@angular/common": "^21.2.0",
|
||||
"@angular/compiler": "^21.2.0",
|
||||
"@angular/core": "^21.2.0",
|
||||
"@angular/forms": "^21.2.0",
|
||||
"@angular/platform-browser": "^21.2.0",
|
||||
"@angular/platform-browser-dynamic": "^21.2.0",
|
||||
"@angular/router": "^21.2.0",
|
||||
"@angular/service-worker": "^21.2.0",
|
||||
"@iharbeck/ngx-virtual-scroller": "^20.0.0",
|
||||
"@jsverse/transloco": "^8.2.1",
|
||||
"@primeuix/themes": "^2.0.3",
|
||||
@@ -50,13 +50,13 @@
|
||||
"zone.js": "^0.16.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@analogjs/vite-plugin-angular": "^2.2.3",
|
||||
"@analogjs/vitest-angular": "^2.2.3",
|
||||
"@angular/build": "^21.1.5",
|
||||
"@angular/cli": "^21.1.5",
|
||||
"@angular/compiler-cli": "^21.1.5",
|
||||
"@types/dompurify": "^3.0.5",
|
||||
"@types/node": "^25.3.0",
|
||||
"@analogjs/vite-plugin-angular": "^2.3.0",
|
||||
"@analogjs/vitest-angular": "^2.3.0",
|
||||
"@angular/build": "^21.2.0",
|
||||
"@angular/cli": "^21.2.0",
|
||||
"@angular/compiler-cli": "^21.2.0",
|
||||
"@types/dompurify": "^3.2.0",
|
||||
"@types/node": "^25.3.2",
|
||||
"@types/showdown": "^2.0.6",
|
||||
"@vitest/coverage-v8": "^4.0.17",
|
||||
"angular-eslint": "^21.2.0",
|
||||
|
||||
@@ -11,6 +11,7 @@ import {MetadataProgressService} from './shared/service/metadata-progress.servic
|
||||
import {BookdropFileService} from './features/bookdrop/service/bookdrop-file.service';
|
||||
import {TaskService} from './features/settings/task-management/task.service';
|
||||
import {LibraryService} from './features/book/service/library.service';
|
||||
import {LibraryHealthService} from './features/book/service/library-health.service';
|
||||
import {LibraryLoadingService} from './features/library-creator/library-loading.service';
|
||||
import {TranslocoTestingModule} from '@jsverse/transloco';
|
||||
|
||||
@@ -34,6 +35,7 @@ describe('AppComponent offline detection', () => {
|
||||
{provide: BookdropFileService, useValue: {}},
|
||||
{provide: TaskService, useValue: {}},
|
||||
{provide: LibraryService, useValue: {largeLibraryLoading$: of({isLoading: false, expectedCount: 0})}},
|
||||
{provide: LibraryHealthService, useValue: {initialize: vi.fn()}},
|
||||
{provide: LibraryLoadingService, useValue: {hide: vi.fn()}},
|
||||
]
|
||||
});
|
||||
|
||||
@@ -15,6 +15,7 @@ import {BookdropFileNotification, BookdropFileService} from './features/bookdrop
|
||||
import {Subscription} from 'rxjs';
|
||||
import {TaskProgressPayload, TaskService} from './features/settings/task-management/task.service';
|
||||
import {LibraryService} from './features/book/service/library.service';
|
||||
import {LibraryHealthService} from './features/book/service/library-health.service';
|
||||
import {LibraryLoadingService} from './features/library-creator/library-loading.service';
|
||||
import {scan, withLatestFrom} from 'rxjs/operators';
|
||||
|
||||
@@ -41,6 +42,7 @@ export class AppComponent implements OnInit, OnDestroy {
|
||||
private bookdropFileService = inject(BookdropFileService);
|
||||
private taskService = inject(TaskService);
|
||||
private libraryService = inject(LibraryService);
|
||||
private libraryHealthService = inject(LibraryHealthService);
|
||||
private libraryLoadingService = inject(LibraryLoadingService);
|
||||
|
||||
ngOnInit(): void {
|
||||
@@ -51,6 +53,7 @@ export class AppComponent implements OnInit, OnDestroy {
|
||||
this.loading = !ready;
|
||||
if (ready && !this.subscriptionsInitialized) {
|
||||
this.setupWebSocketSubscriptions();
|
||||
this.libraryHealthService.initialize();
|
||||
this.subscriptionsInitialized = true;
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {ActivatedRouteSnapshot, DetachedRouteHandle, RouteReuseStrategy} from '@angular/router';
|
||||
import {BookBrowserScrollService} from '../features/book/components/book-browser/book-browser-scroll.service';
|
||||
import {BookSelectionService} from '../features/book/components/book-browser/book-selection.service';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
@@ -8,6 +9,7 @@ import {BookBrowserScrollService} from '../features/book/components/book-browser
|
||||
export class CustomReuseStrategy implements RouteReuseStrategy {
|
||||
private storedRoutes = new Map<string, DetachedRouteHandle>();
|
||||
private scrollService = inject(BookBrowserScrollService);
|
||||
private bookSelectionService = inject(BookSelectionService);
|
||||
|
||||
private readonly BOOK_BROWSER_PATHS = [
|
||||
'all-books',
|
||||
@@ -39,6 +41,7 @@ export class CustomReuseStrategy implements RouteReuseStrategy {
|
||||
if (handle && this.isBookBrowserRoute(route)) {
|
||||
const key = this.getRouteKey(route);
|
||||
this.storedRoutes.set(key, handle);
|
||||
this.bookSelectionService.deselectAll();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+71
-53
@@ -38,63 +38,81 @@
|
||||
|
||||
<div class="gradient-divider"></div>
|
||||
|
||||
<div class="form-row">
|
||||
<div class="form-group highlight-group flex-2">
|
||||
<label for="title" class="form-label">
|
||||
<i class="pi pi-tag label-icon"></i>
|
||||
{{ t('titleLabel') }}
|
||||
</label>
|
||||
<div class="input-wrapper">
|
||||
<input
|
||||
id="title"
|
||||
type="text"
|
||||
pInputText
|
||||
[(ngModel)]="title"
|
||||
class="input-full"
|
||||
[placeholder]="t('titlePlaceholder')"
|
||||
[class.filled]="title.trim()"/>
|
||||
<div class="top-section">
|
||||
@if (coverUrl) {
|
||||
<div class="cover-preview">
|
||||
<img [src]="coverUrl" alt="Book cover"/>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
<div class="form-group highlight-group flex-1">
|
||||
<label for="isbn" class="form-label">
|
||||
<i class="pi pi-barcode label-icon"></i>
|
||||
{{ t('isbnLabel') }}
|
||||
</label>
|
||||
<div class="input-wrapper">
|
||||
<input
|
||||
id="isbn"
|
||||
type="text"
|
||||
pInputText
|
||||
[(ngModel)]="isbn"
|
||||
class="input-full"
|
||||
[placeholder]="t('isbnPlaceholder')"/>
|
||||
<div class="top-fields">
|
||||
<div class="form-row">
|
||||
<div class="form-group highlight-group flex-2">
|
||||
<label for="title" class="form-label">
|
||||
<i class="pi pi-tag label-icon"></i>
|
||||
{{ t('titleLabel') }}
|
||||
</label>
|
||||
<div class="input-wrapper">
|
||||
<input
|
||||
id="title"
|
||||
type="text"
|
||||
pInputText
|
||||
[(ngModel)]="title"
|
||||
class="input-full"
|
||||
[placeholder]="t('titlePlaceholder')"
|
||||
[class.filled]="title.trim()"/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-group highlight-group flex-1">
|
||||
<label for="isbn" class="form-label">
|
||||
<i class="pi pi-barcode label-icon"></i>
|
||||
{{ t('isbnLabel') }}
|
||||
</label>
|
||||
<div class="isbn-input-row">
|
||||
<input
|
||||
id="isbn"
|
||||
type="text"
|
||||
pInputText
|
||||
[(ngModel)]="isbn"
|
||||
class="input-full"
|
||||
[placeholder]="t('isbnPlaceholder')"/>
|
||||
<p-button
|
||||
icon="pi pi-search"
|
||||
[rounded]="true"
|
||||
[text]="true"
|
||||
severity="info"
|
||||
(onClick)="fetchMetadataByIsbn()"
|
||||
[disabled]="!isbn.trim() || isFetchingMetadata"
|
||||
[loading]="isFetchingMetadata"
|
||||
[pTooltip]="t('fetchMetadataTooltip')"
|
||||
tooltipPosition="top"/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="gradient-divider"></div>
|
||||
|
||||
<div class="form-group highlight-group">
|
||||
<label for="authors" class="form-label">
|
||||
<i class="pi pi-user label-icon"></i>
|
||||
{{ t('authorsLabel') }}
|
||||
</label>
|
||||
<div class="autocomplete-wrapper">
|
||||
<p-autoComplete
|
||||
appendTo="body"
|
||||
[(ngModel)]="authors"
|
||||
[multiple]="true"
|
||||
[fluid]="true"
|
||||
[dropdown]="false"
|
||||
[suggestions]="filteredAuthors"
|
||||
[forceSelection]="false"
|
||||
[showClear]="false"
|
||||
[placeholder]="t('authorsPlaceholder')"
|
||||
(completeMethod)="filterAuthors($event)"
|
||||
(onKeyUp)="onAutoCompleteKeyUp('authors', $event)"
|
||||
(onSelect)="onAutoCompleteSelect('authors', $event)">
|
||||
</p-autoComplete>
|
||||
<div class="form-group highlight-group">
|
||||
<label for="authors" class="form-label">
|
||||
<i class="pi pi-user label-icon"></i>
|
||||
{{ t('authorsLabel') }}
|
||||
</label>
|
||||
<div class="autocomplete-wrapper">
|
||||
<p-autoComplete
|
||||
appendTo="body"
|
||||
[(ngModel)]="authors"
|
||||
[multiple]="true"
|
||||
[fluid]="true"
|
||||
[dropdown]="false"
|
||||
[suggestions]="filteredAuthors"
|
||||
[forceSelection]="false"
|
||||
[showClear]="false"
|
||||
[placeholder]="t('authorsPlaceholder')"
|
||||
(completeMethod)="filterAuthors($event)"
|
||||
(onKeyUp)="onAutoCompleteKeyUp('authors', $event)"
|
||||
(onSelect)="onAutoCompleteSelect('authors', $event)">
|
||||
</p-autoComplete>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
+48
@@ -106,6 +106,54 @@
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.isbn-input-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.25rem;
|
||||
|
||||
.input-full {
|
||||
flex: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.top-section {
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
align-items: flex-start;
|
||||
|
||||
@media (max-width: 640px) {
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
}
|
||||
}
|
||||
|
||||
.top-fields {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.cover-preview {
|
||||
flex-shrink: 0;
|
||||
padding: 0.5rem;
|
||||
|
||||
img {
|
||||
height: 180px;
|
||||
border-radius: 4px;
|
||||
border: 1px solid var(--border-color);
|
||||
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.12);
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
img {
|
||||
height: 150px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.autocomplete-wrapper {
|
||||
width: 100%;
|
||||
|
||||
|
||||
+30
-1
@@ -9,6 +9,7 @@ import {Textarea} from 'primeng/textarea';
|
||||
import {InputNumber} from 'primeng/inputnumber';
|
||||
import {AutoComplete, AutoCompleteCompleteEvent} from 'primeng/autocomplete';
|
||||
import {BookService} from '../../service/book.service';
|
||||
import {BookMetadataService} from '../../service/book-metadata.service';
|
||||
import {LibraryService} from '../../service/library.service';
|
||||
import {Library} from '../../model/library.model';
|
||||
import {CreatePhysicalBookRequest} from '../../model/book.model';
|
||||
@@ -37,6 +38,7 @@ export class AddPhysicalBookDialogComponent implements OnInit {
|
||||
private dynamicDialogRef = inject(DynamicDialogRef);
|
||||
private dialogConfig = inject(DynamicDialogConfig);
|
||||
private bookService = inject(BookService);
|
||||
private bookMetadataService = inject(BookMetadataService);
|
||||
private libraryService = inject(LibraryService);
|
||||
private destroyRef = inject(DestroyRef);
|
||||
|
||||
@@ -57,7 +59,9 @@ export class AddPhysicalBookDialogComponent implements OnInit {
|
||||
filteredAuthors: string[] = [];
|
||||
filteredCategories: string[] = [];
|
||||
|
||||
coverUrl: string | null = null;
|
||||
isLoading: boolean = false;
|
||||
isFetchingMetadata: boolean = false;
|
||||
|
||||
ngOnInit(): void {
|
||||
this.libraryService.libraryState$
|
||||
@@ -131,6 +135,30 @@ export class AddPhysicalBookDialogComponent implements OnInit {
|
||||
(event.originalEvent.target as HTMLInputElement).value = '';
|
||||
}
|
||||
|
||||
fetchMetadataByIsbn(): void {
|
||||
const isbnValue = this.isbn.trim();
|
||||
if (!isbnValue || this.isFetchingMetadata) return;
|
||||
|
||||
this.isFetchingMetadata = true;
|
||||
this.bookMetadataService.lookupByIsbn(isbnValue).subscribe({
|
||||
next: (metadata) => {
|
||||
if (metadata.title) this.title = metadata.title;
|
||||
if (metadata.authors?.length) this.authors = [...metadata.authors];
|
||||
if (metadata.description) this.description = metadata.description;
|
||||
if (metadata.publisher) this.publisher = metadata.publisher;
|
||||
if (metadata.publishedDate) this.publishedDate = metadata.publishedDate;
|
||||
if (metadata.language) this.language = metadata.language;
|
||||
if (metadata.pageCount) this.pageCount = metadata.pageCount;
|
||||
if (metadata.categories?.length) this.categories = [...metadata.categories];
|
||||
this.coverUrl = metadata.thumbnailUrl || null;
|
||||
this.isFetchingMetadata = false;
|
||||
},
|
||||
error: () => {
|
||||
this.isFetchingMetadata = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
cancel(): void {
|
||||
this.dynamicDialogRef.close();
|
||||
}
|
||||
@@ -154,7 +182,8 @@ export class AddPhysicalBookDialogComponent implements OnInit {
|
||||
publishedDate: this.publishedDate.trim() || undefined,
|
||||
language: this.language.trim() || undefined,
|
||||
pageCount: this.pageCount ?? undefined,
|
||||
categories: this.categories.length > 0 ? this.categories : undefined
|
||||
categories: this.categories.length > 0 ? this.categories : undefined,
|
||||
thumbnailUrl: this.coverUrl || undefined
|
||||
};
|
||||
|
||||
this.bookService.createPhysicalBook(request).subscribe({
|
||||
|
||||
+32
-7
@@ -244,6 +244,7 @@
|
||||
right: 10%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
overflow: hidden;
|
||||
padding: 1rem 0.5rem 0.5rem;
|
||||
z-index: 1;
|
||||
border-radius: 10px 10px 0 0;
|
||||
@@ -260,10 +261,6 @@
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
> .footer-content {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
left: 0;
|
||||
right: 0;
|
||||
@@ -273,23 +270,50 @@
|
||||
.footer-content {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.footer-left {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding-left: 0.5rem;
|
||||
width: 25%;
|
||||
flex-shrink: 0;
|
||||
width: 120px;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
width: auto;
|
||||
}
|
||||
}
|
||||
|
||||
.footer-center {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
width: 50%;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow-x: auto;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
scrollbar-width: none;
|
||||
mask-image: linear-gradient(to right, transparent 0, black 12px, black calc(100% - 32px), transparent 100%);
|
||||
-webkit-mask-image: linear-gradient(to right, transparent 0, black 12px, black calc(100% - 32px), transparent 100%);
|
||||
padding: 0 16px;
|
||||
|
||||
&::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
justify-content: flex-start;
|
||||
}
|
||||
}
|
||||
|
||||
.footer-right {
|
||||
width: 25%;
|
||||
flex-shrink: 0;
|
||||
width: 120px;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
.selected-count-badge {
|
||||
@@ -326,6 +350,7 @@
|
||||
|
||||
.action-buttons-group {
|
||||
display: flex;
|
||||
flex-shrink: 0;
|
||||
gap: 0.5rem;
|
||||
|
||||
@media (min-width: 768px) {
|
||||
|
||||
+1
-1
@@ -34,7 +34,7 @@
|
||||
@if (_isSeriesViewActive) {
|
||||
<p-button [rounded]="true" icon="pi pi-info" class="info-btn" (click)="openSeriesInfo()" [ariaLabel]="'book.card.alt.viewSeriesInfo' | transloco"></p-button>
|
||||
} @else {
|
||||
<a [routerLink]="urlHelper.getBookUrl(book)"><p-button [rounded]="true" icon="pi pi-info" class="info-btn" [ariaLabel]="'book.card.alt.viewDetails' | transloco">
|
||||
<a [routerLink]="urlHelper.getBookUrl(book)" (click)="prepareNavigation(book)"><p-button [rounded]="true" icon="pi pi-info" class="info-btn" [ariaLabel]="'book.card.alt.viewDetails' | transloco">
|
||||
</p-button></a>
|
||||
}
|
||||
|
||||
|
||||
+41
-17
@@ -415,23 +415,40 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
|
||||
label: this.t.translate('book.card.menu.quickSend'),
|
||||
icon: 'pi pi-envelope',
|
||||
command: () => {
|
||||
this.emailService.emailBookQuick(this.book.id).subscribe({
|
||||
next: () => {
|
||||
this.messageService.add({
|
||||
severity: 'info',
|
||||
summary: this.t.translate('common.success'),
|
||||
detail: this.t.translate('book.card.toast.quickSendSuccessDetail'),
|
||||
});
|
||||
},
|
||||
error: (err) => {
|
||||
const errorMessage = err?.error?.message || this.t.translate('book.card.toast.quickSendErrorDetail');
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('common.error'),
|
||||
detail: errorMessage,
|
||||
});
|
||||
},
|
||||
});
|
||||
const doSend = () => {
|
||||
this.emailService.emailBookQuick(this.book.id).subscribe({
|
||||
next: () => {
|
||||
this.messageService.add({
|
||||
severity: 'info',
|
||||
summary: this.t.translate('common.success'),
|
||||
detail: this.t.translate('book.card.toast.quickSendSuccessDetail'),
|
||||
});
|
||||
},
|
||||
error: (err) => {
|
||||
const errorMessage = err?.error?.message || this.t.translate('book.card.toast.quickSendErrorDetail');
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('common.error'),
|
||||
detail: errorMessage,
|
||||
});
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
if (this.book.primaryFile?.fileSizeKb && this.book.primaryFile.fileSizeKb > 25 * 1024) {
|
||||
this.confirmationService.confirm({
|
||||
message: this.t.translate('book.card.confirm.largeFileMessage'),
|
||||
header: this.t.translate('book.card.confirm.largeFileHeader'),
|
||||
icon: 'pi pi-exclamation-triangle',
|
||||
acceptLabel: this.t.translate('book.card.confirm.sendAnyway'),
|
||||
rejectLabel: this.t.translate('common.cancel'),
|
||||
acceptButtonProps: { severity: 'warn' },
|
||||
rejectButtonProps: { severity: 'secondary' },
|
||||
accept: doSend,
|
||||
});
|
||||
} else {
|
||||
doSend();
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -636,6 +653,13 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
|
||||
}
|
||||
}
|
||||
|
||||
prepareNavigation(book: Book): void {
|
||||
const allBookIds = this.bookNavigationService.getAvailableBookIds();
|
||||
if (allBookIds.length > 0) {
|
||||
this.bookNavigationService.setNavigationContext(allBookIds, book.id);
|
||||
}
|
||||
}
|
||||
|
||||
openBookInfo(book: Book): void {
|
||||
const allBookIds = this.bookNavigationService.getAvailableBookIds();
|
||||
if (allBookIds.length > 0) {
|
||||
|
||||
+2
-1
@@ -42,7 +42,8 @@
|
||||
*cdkVirtualFor="let filter of filters; trackBy: trackByFilter"
|
||||
class="filter-row"
|
||||
[ngClass]="{
|
||||
'active': activeFilters[filterType]?.includes(getFilterValueId(filter))
|
||||
'active': activeFilters[filterType]?.includes(getFilterValueId(filter)),
|
||||
'active-not': activeFilters[filterType]?.includes(getFilterValueId(filter)) && selectedFilterMode === 'not'
|
||||
}"
|
||||
(click)="handleFilterClick(filterType, getFilterValueId(filter))">
|
||||
<span class="filter-value-text">{{ getFilterValueDisplay(filter) }}</span>
|
||||
|
||||
+11
-2
@@ -3,7 +3,7 @@
|
||||
}
|
||||
|
||||
:host ::ng-deep .p-togglebutton {
|
||||
--p-togglebutton-content-padding: 0.25rem 0.5rem;
|
||||
--p-togglebutton-content-padding: 0.25rem 0.35rem;
|
||||
}
|
||||
|
||||
:host ::ng-deep .cdk-virtual-scroll-orientation-vertical .cdk-virtual-scroll-content-wrapper {
|
||||
@@ -34,7 +34,11 @@
|
||||
}
|
||||
|
||||
.filter-mode-select {
|
||||
font-size: 0.875rem;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
:host ::ng-deep .filter-mode-select .p-togglebutton-label {
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.filter-content {
|
||||
@@ -84,6 +88,11 @@
|
||||
&.active {
|
||||
color: var(--primary-color);
|
||||
}
|
||||
|
||||
&.active-not {
|
||||
color: var(--p-red-400);
|
||||
text-decoration: line-through;
|
||||
}
|
||||
}
|
||||
|
||||
.filter-value-text {
|
||||
|
||||
+1
@@ -67,6 +67,7 @@ export class BookFilterComponent implements OnInit, OnDestroy {
|
||||
readonly filterModeOptions: FilterModeOption[] = [
|
||||
{label: 'AND', value: 'and'},
|
||||
{label: 'OR', value: 'or'},
|
||||
{label: 'NOT', value: 'not'},
|
||||
{label: '1', value: 'single'}
|
||||
];
|
||||
|
||||
|
||||
+1
-1
@@ -202,7 +202,7 @@ const findExactAgeRating = (ageRating: number | null | undefined): FilterValue[]
|
||||
export const FILTER_EXTRACTORS: Readonly<Record<Exclude<FilterType, 'library'>, (book: Book) => FilterValue[]>> = {
|
||||
author: (book) => extractStringsAsFilters(book.metadata?.authors),
|
||||
category: (book) => extractStringsAsFilters(book.metadata?.categories),
|
||||
series: (book) => extractSingleString(book.metadata?.seriesName),
|
||||
series: (book) => extractSingleString(book.metadata?.seriesName?.trim()),
|
||||
bookType: (book) => extractSingleString(book.primaryFile?.bookType),
|
||||
readStatus: (book) => {
|
||||
const status = book.readStatus ?? ReadStatus.UNSET;
|
||||
|
||||
+17
-14
@@ -60,19 +60,21 @@ export function doesBookMatchFilter(
|
||||
return mode === 'or';
|
||||
}
|
||||
|
||||
const effectiveMode = mode === 'not' ? 'or' : mode;
|
||||
|
||||
switch (filterType) {
|
||||
case 'author':
|
||||
return mode === 'or'
|
||||
return effectiveMode === 'or'
|
||||
? filterValues.some(val => book.metadata?.authors?.includes(val as string))
|
||||
: filterValues.every(val => book.metadata?.authors?.includes(val as string));
|
||||
case 'category':
|
||||
return mode === 'or'
|
||||
return effectiveMode === 'or'
|
||||
? filterValues.some(val => book.metadata?.categories?.includes(val as string))
|
||||
: filterValues.every(val => book.metadata?.categories?.includes(val as string));
|
||||
case 'series':
|
||||
return mode === 'or'
|
||||
? filterValues.some(val => book.metadata?.seriesName === val)
|
||||
: filterValues.every(val => book.metadata?.seriesName === val);
|
||||
return effectiveMode === 'or'
|
||||
? filterValues.some(val => book.metadata?.seriesName?.trim() === val)
|
||||
: filterValues.every(val => book.metadata?.seriesName?.trim() === val);
|
||||
case 'bookType':
|
||||
return filterValues.includes(book.primaryFile?.bookType);
|
||||
case 'readStatus':
|
||||
@@ -80,24 +82,24 @@ export function doesBookMatchFilter(
|
||||
case 'personalRating':
|
||||
return filterValues.some(range => isRatingInRange10(book.personalRating, range as string | number));
|
||||
case 'publisher':
|
||||
return mode === 'or'
|
||||
return effectiveMode === 'or'
|
||||
? filterValues.some(val => book.metadata?.publisher === val)
|
||||
: filterValues.every(val => book.metadata?.publisher === val);
|
||||
case 'matchScore':
|
||||
return filterValues.some(range => isMatchScoreInRange(book.metadataMatchScore, range as string | number));
|
||||
case 'library':
|
||||
return mode === 'or'
|
||||
return effectiveMode === 'or'
|
||||
? filterValues.some(val => val == book.libraryId)
|
||||
: filterValues.every(val => val == book.libraryId);
|
||||
case 'shelf':
|
||||
return mode === 'or'
|
||||
return effectiveMode === 'or'
|
||||
? filterValues.some(val => book.shelves?.some(s => s.id == val))
|
||||
: filterValues.every(val => book.shelves?.some(s => s.id == val));
|
||||
case 'shelfStatus':
|
||||
const shelved = book.shelves && book.shelves.length > 0 ? 'shelved' : 'unshelved';
|
||||
return filterValues.includes(shelved);
|
||||
case 'tag':
|
||||
return mode === 'or'
|
||||
return effectiveMode === 'or'
|
||||
? filterValues.some(val => book.metadata?.tags?.includes(val as string))
|
||||
: filterValues.every(val => book.metadata?.tags?.includes(val as string));
|
||||
case 'publishedDate':
|
||||
@@ -118,7 +120,7 @@ export function doesBookMatchFilter(
|
||||
case 'pageCount':
|
||||
return filterValues.some(range => isPageCountInRange(book.metadata?.pageCount!, range as string | number));
|
||||
case 'mood':
|
||||
return mode === 'or'
|
||||
return effectiveMode === 'or'
|
||||
? filterValues.some(val => book.metadata?.moods?.includes(val as string))
|
||||
: filterValues.every(val => book.metadata?.moods?.includes(val as string));
|
||||
case 'ageRating':
|
||||
@@ -131,15 +133,15 @@ export function doesBookMatchFilter(
|
||||
case 'narrator':
|
||||
return filterValues.includes(book.metadata?.narrator);
|
||||
case 'comicCharacter':
|
||||
return mode === 'or'
|
||||
return effectiveMode === 'or'
|
||||
? filterValues.some(val => book.metadata?.comicMetadata?.characters?.includes(val as string))
|
||||
: filterValues.every(val => book.metadata?.comicMetadata?.characters?.includes(val as string));
|
||||
case 'comicTeam':
|
||||
return mode === 'or'
|
||||
return effectiveMode === 'or'
|
||||
? filterValues.some(val => book.metadata?.comicMetadata?.teams?.includes(val as string))
|
||||
: filterValues.every(val => book.metadata?.comicMetadata?.teams?.includes(val as string));
|
||||
case 'comicLocation':
|
||||
return mode === 'or'
|
||||
return effectiveMode === 'or'
|
||||
? filterValues.some(val => book.metadata?.comicMetadata?.locations?.includes(val as string))
|
||||
: filterValues.every(val => book.metadata?.comicMetadata?.locations?.includes(val as string));
|
||||
case 'comicCreator': {
|
||||
@@ -161,7 +163,7 @@ export function doesBookMatchFilter(
|
||||
}
|
||||
}
|
||||
}
|
||||
return mode === 'or'
|
||||
return effectiveMode === 'or'
|
||||
? filterValues.some(val => allCreators.includes(val as string))
|
||||
: filterValues.every(val => allCreators.includes(val as string));
|
||||
}
|
||||
@@ -187,6 +189,7 @@ export function filterBooksByFilters(
|
||||
const matches = filterEntries.map(([filterType, filterValues]) =>
|
||||
doesBookMatchFilter(book, filterType, filterValues, mode)
|
||||
);
|
||||
if (mode === 'not') return matches.every(m => !m);
|
||||
return mode === 'or' ? matches.some(m => m) : matches.every(m => m);
|
||||
});
|
||||
}
|
||||
|
||||
+15
-6
@@ -8,7 +8,7 @@
|
||||
[(ngModel)]="searchQuery"
|
||||
(input)="onSearchInputChange()"
|
||||
(focus)="isSearchFocused = true"
|
||||
(blur)="onSearchBlur()"
|
||||
(keydown)="onKeydown($event)"
|
||||
[placeholder]="t('placeholder')"
|
||||
class="search-input"
|
||||
/>
|
||||
@@ -27,11 +27,21 @@
|
||||
@if (books.length > 0 || searchQuery) {
|
||||
<div
|
||||
class="search-dropdown layout-menu"
|
||||
[class.show]="(books.length > 0)"
|
||||
[class.show]="isDropdownOpen"
|
||||
>
|
||||
@if (books.length > 0) {
|
||||
@for (book of books; track book) {
|
||||
<div class="search-dropdown-item" (click)="onBookClick(book)">
|
||||
@if (isLoading) {
|
||||
@for (i of [1,2,3]; track i) {
|
||||
<div class="search-skeleton-item">
|
||||
<p-skeleton width="50px" height="67px" borderRadius="4px"/>
|
||||
<div class="search-skeleton-details">
|
||||
<p-skeleton width="80%" height="1rem"/>
|
||||
<p-skeleton width="60%" height="0.8rem"/>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
} @else if (books.length > 0) {
|
||||
@for (book of books; track book; let idx = $index) {
|
||||
<div class="search-dropdown-item" [class.active]="activeIndex === idx" (click)="onBookClick(book)">
|
||||
<div class="search-item-content">
|
||||
<img
|
||||
[attr.src]="urlHelper.getThumbnailUrl(book.id, book.metadata?.coverUpdatedOn)"
|
||||
@@ -60,7 +70,6 @@
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
<p-divider></p-divider>
|
||||
</div>
|
||||
}
|
||||
} @else {
|
||||
|
||||
+26
-30
@@ -45,7 +45,7 @@
|
||||
transform: translateY(-50%);
|
||||
display: none;
|
||||
|
||||
@media (min-width: 1024px) {
|
||||
@media (min-width: 640px) {
|
||||
display: inline-flex;
|
||||
}
|
||||
}
|
||||
@@ -54,7 +54,8 @@
|
||||
position: absolute;
|
||||
top: calc(100% + 0.5rem);
|
||||
left: 0;
|
||||
width: 300px;
|
||||
width: 100%;
|
||||
max-width: 600px;
|
||||
background-color: var(--card-background);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 8px;
|
||||
@@ -62,18 +63,13 @@
|
||||
0 2px 4px -1px rgba(0, 0, 0, 0.06),
|
||||
0 10px 15px -3px rgba(0, 0, 0, 0.1);
|
||||
z-index: 1000;
|
||||
max-height: 70vh;
|
||||
max-height: min(70vh, calc(100dvh - 4rem));
|
||||
overflow-y: auto;
|
||||
opacity: 0;
|
||||
height: 0;
|
||||
transform: translateY(-10px);
|
||||
transition: opacity 0.2s ease, transform 0.2s ease, height 0.2s ease;
|
||||
|
||||
@media (min-width: 640px) {
|
||||
width: 100%;
|
||||
max-width: 600px;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar {
|
||||
width: 8px;
|
||||
}
|
||||
@@ -103,6 +99,7 @@
|
||||
flex-direction: column;
|
||||
cursor: pointer;
|
||||
transition: background-color 0.2s ease;
|
||||
border-bottom: 1px solid color-mix(in srgb, var(--border-color) 50%, transparent);
|
||||
|
||||
&:first-child {
|
||||
border-radius: 8px 8px 0 0;
|
||||
@@ -110,13 +107,11 @@
|
||||
|
||||
&:last-child {
|
||||
border-radius: 0 0 8px 8px;
|
||||
|
||||
::ng-deep .p-divider {
|
||||
display: none;
|
||||
}
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
&:hover {
|
||||
&:hover,
|
||||
&.active {
|
||||
background-color: var(--surface-hover);
|
||||
}
|
||||
|
||||
@@ -126,15 +121,6 @@
|
||||
color: var(--text-secondary-color);
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
::ng-deep .p-divider {
|
||||
margin: 0;
|
||||
|
||||
&::before {
|
||||
border-top-color: var(--border-color);
|
||||
opacity: 0.5;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.search-item-content {
|
||||
@@ -154,6 +140,7 @@
|
||||
border-radius: 4px;
|
||||
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
|
||||
background-color: var(--surface-ground);
|
||||
aspect-ratio: 2/3;
|
||||
}
|
||||
|
||||
.search-book-details {
|
||||
@@ -161,7 +148,7 @@
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
gap: 0.25rem;
|
||||
}
|
||||
|
||||
.search-book-title-container {
|
||||
@@ -254,12 +241,21 @@
|
||||
}
|
||||
|
||||
&.series-badge {
|
||||
background-color: rgba(59, 130, 246, 0.1);
|
||||
color: rgb(59, 130, 246);
|
||||
}
|
||||
|
||||
&.year-badge {
|
||||
background-color: rgba(34, 197, 94, 0.1);
|
||||
color: rgb(34, 197, 94);
|
||||
background-color: color-mix(in srgb, var(--p-primary-color) 10%, transparent);
|
||||
color: var(--p-primary-color);
|
||||
}
|
||||
}
|
||||
|
||||
.search-skeleton-item {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
gap: 1rem;
|
||||
padding: 0.75rem 1rem;
|
||||
}
|
||||
|
||||
.search-skeleton-details {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
+49
-12
@@ -1,13 +1,13 @@
|
||||
import {Component, inject, OnDestroy, OnInit} from '@angular/core';
|
||||
import {Component, ElementRef, HostListener, inject, OnDestroy, OnInit} from '@angular/core';
|
||||
import {BehaviorSubject, of, Subscription} from 'rxjs';
|
||||
import {catchError, switchMap} from 'rxjs/operators';
|
||||
import {catchError, debounceTime, distinctUntilChanged, switchMap, tap} from 'rxjs/operators';
|
||||
import {Book} from '../../model/book.model';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {InputTextModule} from 'primeng/inputtext';
|
||||
import {BookService} from '../../service/book.service';
|
||||
import {Button} from 'primeng/button';
|
||||
import {SlicePipe} from '@angular/common';
|
||||
import {Divider} from 'primeng/divider';
|
||||
import {Skeleton} from 'primeng/skeleton';
|
||||
import {UrlHelperService} from '../../../../shared/service/url-helper.service';
|
||||
import {Router} from '@angular/router';
|
||||
import {IconField} from 'primeng/iconfield';
|
||||
@@ -23,7 +23,7 @@ import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
InputTextModule,
|
||||
Button,
|
||||
SlicePipe,
|
||||
Divider,
|
||||
Skeleton,
|
||||
IconField,
|
||||
InputIcon,
|
||||
TranslocoDirective,
|
||||
@@ -34,6 +34,8 @@ import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
export class BookSearcherComponent implements OnInit, OnDestroy {
|
||||
searchQuery: string = '';
|
||||
books: Book[] = [];
|
||||
isLoading = false;
|
||||
activeIndex = -1;
|
||||
#searchSubject = new BehaviorSubject<string>('');
|
||||
#subscription!: Subscription;
|
||||
isSearchFocused = false;
|
||||
@@ -42,14 +44,24 @@ export class BookSearcherComponent implements OnInit, OnDestroy {
|
||||
private router = inject(Router);
|
||||
protected urlHelper = inject(UrlHelperService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
private headerFilter = new HeaderFilter(this.#searchSubject.asObservable());
|
||||
private elRef = inject(ElementRef);
|
||||
private headerFilter = new HeaderFilter(
|
||||
this.#searchSubject.pipe(debounceTime(200), distinctUntilChanged())
|
||||
);
|
||||
|
||||
ngOnInit(): void {
|
||||
this.#subscription = this.bookService.bookState$.pipe(
|
||||
tap(() => {
|
||||
if (this.searchQuery.trim().length >= 2) {
|
||||
this.isLoading = true;
|
||||
}
|
||||
}),
|
||||
switchMap(bookState => this.headerFilter.filter(bookState)),
|
||||
catchError(() => of({books: [], loaded: true, error: null}))
|
||||
).subscribe({
|
||||
next: (filteredState) => {
|
||||
this.isLoading = false;
|
||||
this.activeIndex = -1;
|
||||
const term = this.searchQuery.trim();
|
||||
this.books = term.length >= 2
|
||||
? (filteredState.books || []).slice(0, 50)
|
||||
@@ -90,18 +102,43 @@ export class BookSearcherComponent implements OnInit, OnDestroy {
|
||||
clearSearch(): void {
|
||||
this.searchQuery = '';
|
||||
this.books = [];
|
||||
this.isLoading = false;
|
||||
}
|
||||
|
||||
get isDropdownOpen(): boolean {
|
||||
return this.books.length > 0;
|
||||
return this.books.length > 0 || this.isLoading;
|
||||
}
|
||||
|
||||
onSearchBlur(): void {
|
||||
setTimeout(() => {
|
||||
if (!this.isDropdownOpen) {
|
||||
this.isSearchFocused = false;
|
||||
}
|
||||
}, 200);
|
||||
@HostListener('document:click', ['$event'])
|
||||
onDocumentClick(event: Event): void {
|
||||
if (!this.elRef.nativeElement.contains(event.target)) {
|
||||
this.clearSearch();
|
||||
this.isSearchFocused = false;
|
||||
}
|
||||
}
|
||||
|
||||
onKeydown(event: KeyboardEvent): void {
|
||||
if (!this.isDropdownOpen) return;
|
||||
|
||||
switch (event.key) {
|
||||
case 'ArrowDown':
|
||||
this.activeIndex = Math.min(this.activeIndex + 1, this.books.length - 1);
|
||||
event.preventDefault();
|
||||
break;
|
||||
case 'ArrowUp':
|
||||
this.activeIndex = Math.max(this.activeIndex - 1, 0);
|
||||
event.preventDefault();
|
||||
break;
|
||||
case 'Enter':
|
||||
if (this.activeIndex >= 0 && this.activeIndex < this.books.length) {
|
||||
this.onBookClick(this.books[this.activeIndex]);
|
||||
}
|
||||
break;
|
||||
case 'Escape':
|
||||
this.clearSearch();
|
||||
(event.target as HTMLElement).blur();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
|
||||
@@ -155,7 +155,7 @@ export class SeriesPageComponent implements OnDestroy, AfterViewChecked {
|
||||
]).pipe(
|
||||
map(([seriesName, books]) => {
|
||||
const inSeries = books.filter(
|
||||
(b) => b.metadata?.seriesName?.toLowerCase() === seriesName
|
||||
(b) => b.metadata?.seriesName?.trim().toLowerCase() === seriesName
|
||||
);
|
||||
return inSeries.sort((a, b) => {
|
||||
const aNum = a.metadata?.seriesNumber ?? Number.MAX_SAFE_INTEGER;
|
||||
|
||||
@@ -413,6 +413,7 @@ export interface CreatePhysicalBookRequest {
|
||||
language?: string;
|
||||
pageCount?: number;
|
||||
categories?: string[];
|
||||
thumbnailUrl?: string;
|
||||
}
|
||||
|
||||
export interface BookStatusUpdateResponse {
|
||||
|
||||
@@ -24,8 +24,8 @@ export class BookMetadataManageService {
|
||||
private bookService = inject(BookService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
|
||||
updateBookMetadata(bookId: number | undefined, wrapper: MetadataUpdateWrapper, mergeCategories: boolean): Observable<BookMetadata> {
|
||||
const params = new HttpParams().set('mergeCategories', mergeCategories.toString());
|
||||
updateBookMetadata(bookId: number | undefined, wrapper: MetadataUpdateWrapper, mergeCategories: boolean, replaceMode: 'REPLACE_ALL' | 'REPLACE_WHEN_PROVIDED' = 'REPLACE_ALL'): Observable<BookMetadata> {
|
||||
const params = new HttpParams().set('mergeCategories', mergeCategories.toString()).set('replaceMode', replaceMode);
|
||||
return this.http.put<BookMetadata>(`${this.url}/${bookId}/metadata`, wrapper, {params}).pipe(
|
||||
map(updatedMetadata => {
|
||||
this.bookSocketService.handleBookMetadataUpdate(bookId!, updatedMetadata);
|
||||
|
||||
@@ -57,4 +57,8 @@ export class BookMetadataService {
|
||||
fetchMetadataDetail(provider: string, providerItemId: string): Observable<BookMetadata> {
|
||||
return this.http.get<BookMetadata>(`${this.url}/metadata/detail/${provider}/${providerItemId}`);
|
||||
}
|
||||
|
||||
lookupByIsbn(isbn: string): Observable<BookMetadata> {
|
||||
return this.http.post<BookMetadata>(`${this.url}/metadata/isbn-lookup`, {isbn});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {LibraryHealthService} from './library-health.service';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {RxStompService} from '../../../shared/websocket/rx-stomp.service';
|
||||
import {of, Subject} from 'rxjs';
|
||||
import {IMessage} from '@stomp/rx-stomp';
|
||||
|
||||
describe('LibraryHealthService', () => {
|
||||
let service: LibraryHealthService;
|
||||
let httpGetSpy: ReturnType<typeof vi.fn>;
|
||||
let wsSubject: Subject<IMessage>;
|
||||
|
||||
beforeEach(() => {
|
||||
httpGetSpy = vi.fn().mockReturnValue(of({}));
|
||||
wsSubject = new Subject<IMessage>();
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
LibraryHealthService,
|
||||
{provide: HttpClient, useValue: {get: httpGetSpy}},
|
||||
{provide: RxStompService, useValue: {watch: vi.fn(() => wsSubject.asObservable())}},
|
||||
]
|
||||
});
|
||||
|
||||
service = TestBed.inject(LibraryHealthService);
|
||||
});
|
||||
|
||||
it('should fetch initial health on initialize', () => {
|
||||
httpGetSpy.mockReturnValue(of({1: true, 2: false}));
|
||||
service.initialize();
|
||||
|
||||
expect(httpGetSpy).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should emit unhealthy for a library with false health', () => {
|
||||
httpGetSpy.mockReturnValue(of({1: true, 2: false}));
|
||||
service.initialize();
|
||||
|
||||
const results: boolean[] = [];
|
||||
service.isUnhealthy$(2).subscribe(v => results.push(v));
|
||||
|
||||
expect(results).toContain(true);
|
||||
});
|
||||
|
||||
it('should emit healthy for a library with true health', () => {
|
||||
httpGetSpy.mockReturnValue(of({1: true}));
|
||||
service.initialize();
|
||||
|
||||
const results: boolean[] = [];
|
||||
service.isUnhealthy$(1).subscribe(v => results.push(v));
|
||||
|
||||
expect(results[results.length - 1]).toBe(false);
|
||||
});
|
||||
|
||||
it('should emit false for unknown library', () => {
|
||||
httpGetSpy.mockReturnValue(of({}));
|
||||
service.initialize();
|
||||
|
||||
const results: boolean[] = [];
|
||||
service.isUnhealthy$(99).subscribe(v => results.push(v));
|
||||
|
||||
expect(results[results.length - 1]).toBe(false);
|
||||
});
|
||||
|
||||
it('should update state from websocket messages', () => {
|
||||
httpGetSpy.mockReturnValue(of({1: true}));
|
||||
service.initialize();
|
||||
|
||||
const results: boolean[] = [];
|
||||
service.isUnhealthy$(1).subscribe(v => results.push(v));
|
||||
|
||||
wsSubject.next({body: JSON.stringify({libraryHealth: {1: false}})} as IMessage);
|
||||
|
||||
expect(results[results.length - 1]).toBe(true);
|
||||
});
|
||||
|
||||
it('should use distinctUntilChanged to avoid duplicate emissions', () => {
|
||||
httpGetSpy.mockReturnValue(of({1: true}));
|
||||
service.initialize();
|
||||
|
||||
const results: boolean[] = [];
|
||||
service.isUnhealthy$(1).subscribe(v => results.push(v));
|
||||
|
||||
// Same state again via websocket
|
||||
wsSubject.next({body: JSON.stringify({libraryHealth: {1: true}})} as IMessage);
|
||||
wsSubject.next({body: JSON.stringify({libraryHealth: {1: true}})} as IMessage);
|
||||
|
||||
expect(results.length).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {BehaviorSubject, Observable} from 'rxjs';
|
||||
import {distinctUntilChanged, map} from 'rxjs/operators';
|
||||
import {RxStompService} from '../../../shared/websocket/rx-stomp.service';
|
||||
import {API_CONFIG} from '../../../core/config/api-config';
|
||||
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class LibraryHealthService {
|
||||
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/libraries/health`;
|
||||
private http = inject(HttpClient);
|
||||
private rxStompService = inject(RxStompService);
|
||||
|
||||
private healthSubject = new BehaviorSubject<Record<number, boolean>>({});
|
||||
|
||||
initialize(): void {
|
||||
this.http.get<Record<number, boolean>>(this.url).subscribe(health => {
|
||||
this.healthSubject.next(health);
|
||||
});
|
||||
|
||||
this.rxStompService.watch('/topic/library-health').subscribe(msg => {
|
||||
const payload = JSON.parse(msg.body);
|
||||
this.healthSubject.next(payload.libraryHealth);
|
||||
});
|
||||
}
|
||||
|
||||
isUnhealthy$(libraryId: number): Observable<boolean> {
|
||||
return this.healthSubject.pipe(
|
||||
map(health => health[libraryId] === false),
|
||||
distinctUntilChanged()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -61,9 +61,7 @@ export class SortService {
|
||||
};
|
||||
|
||||
private readonly fieldExtractors: Record<string, (book: Book) => unknown> = {
|
||||
title: (book) => book.metadata?.seriesName?.toLowerCase()
|
||||
|| book.metadata?.title?.toLowerCase()
|
||||
|| null,
|
||||
title: (book) => book.metadata?.title?.toLowerCase() || null,
|
||||
author: (book) => book.metadata?.authors?.map(a => a.toLowerCase()).join(", ") || null,
|
||||
authorSurnameVorname: (book) => book.metadata?.authors?.map(a => {
|
||||
const parts = a.trim().split(/\s+/);
|
||||
|
||||
@@ -88,6 +88,9 @@ export type RuleField =
|
||||
| 'audibleReviewCount'
|
||||
| 'abridged'
|
||||
| 'audiobookDuration'
|
||||
| 'audiobookCodec'
|
||||
| 'audiobookChapterCount'
|
||||
| 'audiobookBitrate'
|
||||
| 'isPhysical'
|
||||
| 'seriesStatus'
|
||||
| 'seriesGaps'
|
||||
@@ -180,6 +183,9 @@ const FIELD_CONFIGS: Record<RuleField, FullFieldConfig> = {
|
||||
audibleReviewCount: {label: 'audibleReviewCount', type: 'number'},
|
||||
abridged: {label: 'abridged', type: 'boolean'},
|
||||
audiobookDuration: {label: 'audiobookDuration', type: 'number'},
|
||||
audiobookCodec: {label: 'audiobookCodec'},
|
||||
audiobookChapterCount: {label: 'audiobookChapterCount', type: 'number'},
|
||||
audiobookBitrate: {label: 'audiobookBitrate', type: 'number'},
|
||||
isPhysical: {label: 'isPhysical', type: 'boolean'},
|
||||
seriesStatus: {label: 'seriesStatus'},
|
||||
seriesGaps: {label: 'seriesGaps'},
|
||||
@@ -201,7 +207,7 @@ const FIELD_GROUPS: FieldGroup[] = [
|
||||
{ translationKey: 'ratingsReviews', fields: ['personalRating', 'amazonRating', 'amazonReviewCount', 'goodreadsRating', 'goodreadsReviewCount', 'hardcoverRating', 'hardcoverReviewCount', 'ranobedbRating', 'lubimyczytacRating', 'audibleRating', 'audibleReviewCount'] },
|
||||
{ translationKey: 'qualityMetadata', fields: ['metadataScore', 'metadataPresence'] },
|
||||
{ translationKey: 'tagsMoods', fields: ['moods', 'tags'] },
|
||||
{ translationKey: 'audiobook', fields: ['narrator', 'abridged', 'audiobookDuration'] },
|
||||
{ translationKey: 'audiobook', fields: ['narrator', 'abridged', 'audiobookDuration', 'audiobookCodec', 'audiobookChapterCount', 'audiobookBitrate'] },
|
||||
{ translationKey: 'fileIdentifiers', fields: ['fileType', 'fileSize', 'isbn13', 'isbn10', 'isPhysical'] }
|
||||
];
|
||||
|
||||
@@ -279,7 +285,10 @@ export class MagicShelfComponent implements OnInit {
|
||||
{label: 'CB7', value: 'cb7'},
|
||||
{label: 'FB2', value: 'fb2'},
|
||||
{label: 'MOBI', value: 'mobi'},
|
||||
{label: 'AZW3', value: 'azw3'}
|
||||
{label: 'AZW3', value: 'azw3'},
|
||||
{label: 'M4B', value: 'm4b'},
|
||||
{label: 'M4A', value: 'm4a'},
|
||||
{label: 'MP3', value: 'mp3'}
|
||||
];
|
||||
|
||||
get readStatusOptions() {
|
||||
|
||||
@@ -348,6 +348,12 @@ export class BookRuleEvaluatorService {
|
||||
return book.metadata?.abridged;
|
||||
case 'audiobookDuration':
|
||||
return book.metadata?.audiobookMetadata?.durationSeconds ?? null;
|
||||
case 'audiobookCodec':
|
||||
return book.metadata?.audiobookMetadata?.codec?.toLowerCase() ?? null;
|
||||
case 'audiobookChapterCount':
|
||||
return book.metadata?.audiobookMetadata?.chapterCount ?? null;
|
||||
case 'audiobookBitrate':
|
||||
return book.metadata?.audiobookMetadata?.bitrate ?? null;
|
||||
case 'isPhysical':
|
||||
return book.isPhysical;
|
||||
case 'lubimyczytacRating':
|
||||
@@ -538,6 +544,9 @@ export class BookRuleEvaluatorService {
|
||||
case 'comicvineId': return book.metadata?.comicvineId;
|
||||
case 'abridged': return book.metadata?.abridged;
|
||||
case 'audiobookDuration': return book.metadata?.audiobookMetadata?.durationSeconds;
|
||||
case 'audiobookCodec': return book.metadata?.audiobookMetadata?.codec;
|
||||
case 'audiobookChapterCount': return book.metadata?.audiobookMetadata?.chapterCount;
|
||||
case 'audiobookBitrate': return book.metadata?.audiobookMetadata?.bitrate;
|
||||
case 'comicCharacters': return book.metadata?.comicMetadata?.characters;
|
||||
case 'comicTeams': return book.metadata?.comicMetadata?.teams;
|
||||
case 'comicLocations': return book.metadata?.comicMetadata?.locations;
|
||||
|
||||
+10
-2
@@ -1064,11 +1064,19 @@ export class MetadataEditorComponent implements OnInit {
|
||||
}
|
||||
|
||||
onNext() {
|
||||
this.nextBookClicked.emit();
|
||||
if (this.autoSaveEnabled && this.metadataForm.dirty) {
|
||||
this.saveMetadata().pipe(takeUntilDestroyed(this.destroyRef)).subscribe(() => this.nextBookClicked.emit());
|
||||
} else {
|
||||
this.nextBookClicked.emit();
|
||||
}
|
||||
}
|
||||
|
||||
onPrevious() {
|
||||
this.previousBookClicked.emit();
|
||||
if (this.autoSaveEnabled && this.metadataForm.dirty) {
|
||||
this.saveMetadata().pipe(takeUntilDestroyed(this.destroyRef)).subscribe(() => this.previousBookClicked.emit());
|
||||
} else {
|
||||
this.previousBookClicked.emit();
|
||||
}
|
||||
}
|
||||
|
||||
closeDialog() {
|
||||
|
||||
+2
-2
@@ -8,8 +8,8 @@
|
||||
</div>
|
||||
}
|
||||
|
||||
<!-- Column Headers (Desktop) -->
|
||||
<div class="column-headers desktop-only">
|
||||
<!-- Column Headers -->
|
||||
<div class="column-headers">
|
||||
<div class="column-label current">
|
||||
<i class="pi pi-file-edit"></i>
|
||||
<span>{{ t('columnCurrent') }}</span>
|
||||
|
||||
+14
-4
@@ -74,8 +74,9 @@
|
||||
|
||||
// Column Headers - mirrors field-row structure for alignment (desktop only)
|
||||
.column-headers {
|
||||
display: none;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 0.875rem 1rem;
|
||||
margin-bottom: 0.5rem;
|
||||
background: var(--overlay-background);
|
||||
@@ -83,18 +84,23 @@
|
||||
border-radius: 8px;
|
||||
|
||||
@media (min-width: 768px) {
|
||||
display: flex;
|
||||
justify-content: flex-start;
|
||||
}
|
||||
|
||||
// Spacer to match field-label width
|
||||
// Spacer to match field-label width (desktop only)
|
||||
&::before {
|
||||
content: '';
|
||||
min-width: 120px;
|
||||
flex-shrink: 0;
|
||||
display: none;
|
||||
|
||||
@media (min-width: 768px) {
|
||||
display: block;
|
||||
}
|
||||
}
|
||||
|
||||
.column-label {
|
||||
display: flex;
|
||||
display: none;
|
||||
align-items: center;
|
||||
gap: 0.625rem;
|
||||
font-size: 1rem;
|
||||
@@ -103,6 +109,10 @@
|
||||
letter-spacing: 0.05em;
|
||||
flex: 1;
|
||||
|
||||
@media (min-width: 768px) {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
i {
|
||||
font-size: 1.125rem;
|
||||
}
|
||||
|
||||
+2
-2
@@ -289,7 +289,7 @@ export class MetadataPickerComponent implements OnInit {
|
||||
const updatedBookMetadata = this.buildMetadataWrapper(undefined);
|
||||
|
||||
const requests: Observable<unknown>[] = [
|
||||
this.bookMetadataManageService.updateBookMetadata(this.currentBookId, updatedBookMetadata, false)
|
||||
this.bookMetadataManageService.updateBookMetadata(this.currentBookId, updatedBookMetadata, false, 'REPLACE_WHEN_PROVIDED')
|
||||
];
|
||||
|
||||
// Handle audiobook cover upload when fetched from Audible provider
|
||||
@@ -517,7 +517,7 @@ export class MetadataPickerComponent implements OnInit {
|
||||
}
|
||||
|
||||
private updateMetadata(shouldLockAllFields: boolean | undefined): void {
|
||||
this.bookMetadataManageService.updateBookMetadata(this.currentBookId, this.buildMetadataWrapper(shouldLockAllFields), false).subscribe({
|
||||
this.bookMetadataManageService.updateBookMetadata(this.currentBookId, this.buildMetadataWrapper(shouldLockAllFields), false, 'REPLACE_WHEN_PROVIDED').subscribe({
|
||||
next: () => {
|
||||
if (shouldLockAllFields !== undefined) {
|
||||
this.messageService.add({
|
||||
|
||||
+17
-6
@@ -10,7 +10,7 @@ import {AppSettings} from '../../../../../shared/model/app-settings.model';
|
||||
import {AppSettingsService} from '../../../../../shared/service/app-settings.service';
|
||||
|
||||
import {BehaviorSubject, combineLatest, Observable, Subject, Subscription, takeUntil} from 'rxjs';
|
||||
import {distinctUntilChanged, filter, switchMap} from 'rxjs/operators';
|
||||
import {filter, switchMap} from 'rxjs/operators';
|
||||
import {ActivatedRoute} from '@angular/router';
|
||||
import {AsyncPipe} from '@angular/common';
|
||||
import {MetadataPickerComponent} from '../metadata-picker/metadata-picker.component';
|
||||
@@ -111,13 +111,16 @@ export class MetadataSearcherComponent implements OnInit, OnDestroy {
|
||||
return combineLatest([this.book$, this.appSettings$]);
|
||||
}),
|
||||
filter(([book, settings]) => !!book && !!settings),
|
||||
distinctUntilChanged(([prevBook], [currBook]) => prevBook?.id === currBook?.id)
|
||||
)
|
||||
.subscribe(([book, settings]) => {
|
||||
this.resetFormFromBook(book!);
|
||||
|
||||
if (settings!.autoBookSearch) {
|
||||
this.onSubmit();
|
||||
const bookChanged = book!.id !== this.bookId;
|
||||
if (bookChanged) {
|
||||
this.resetFormFromBook(book!);
|
||||
if (settings!.autoBookSearch) {
|
||||
this.onSubmit();
|
||||
}
|
||||
} else {
|
||||
this.updateFormFromBook(book!);
|
||||
}
|
||||
})
|
||||
);
|
||||
@@ -140,6 +143,14 @@ export class MetadataSearcherComponent implements OnInit, OnDestroy {
|
||||
});
|
||||
}
|
||||
|
||||
private updateFormFromBook(book: Book): void {
|
||||
this.form.patchValue({
|
||||
title: book.metadata?.title ?? '',
|
||||
author: book.metadata?.authors?.[0] ?? '',
|
||||
isbn: book.metadata?.isbn13 ?? book.metadata?.isbn10 ?? ''
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.cancelRequest$.next();
|
||||
this.cancelRequest$.complete();
|
||||
|
||||
+4
-6
@@ -593,9 +593,8 @@
|
||||
<p-button
|
||||
icon="pi pi-chevron-left"
|
||||
[disabled]="!canNavigatePrevious()"
|
||||
(onClick)="navigatePrevious()"
|
||||
rounded
|
||||
text
|
||||
(onClick)="navigatePrevious()"`
|
||||
outlined
|
||||
severity="secondary"
|
||||
[pTooltip]="t('goToPreviousBook')"
|
||||
tooltipPosition="bottom">
|
||||
@@ -609,8 +608,7 @@
|
||||
[disabled]="!canNavigateNext()"
|
||||
(onClick)="navigateNext()"
|
||||
severity="secondary"
|
||||
rounded
|
||||
text
|
||||
outlined
|
||||
[pTooltip]="t('goToNextBook')"
|
||||
tooltipPosition="bottom">
|
||||
</p-button>
|
||||
@@ -672,7 +670,7 @@
|
||||
</div>
|
||||
<div class="description-body">
|
||||
<div #descriptionContent [ngClass]="{ 'line-clamp-7': !isExpanded }" class="description-content">
|
||||
<div class="description-html" [innerHTML]="book.metadata!.description"></div>
|
||||
<div class="description-html" [innerHTML]="sanitizeDescription(book.metadata!.description)"></div>
|
||||
</div>
|
||||
@if (isExpanded || isOverflowing) {
|
||||
<button class="expand-toggle" (click)="toggleExpand()">
|
||||
|
||||
+36
-14
@@ -38,6 +38,7 @@ import {TranslocoDirective, TranslocoPipe, TranslocoService} from '@jsverse/tran
|
||||
import {AuthorService} from '../../../../author-browser/service/author.service';
|
||||
import {Dialog} from 'primeng/dialog';
|
||||
import {Checkbox} from 'primeng/checkbox';
|
||||
import DOMPurify from 'dompurify';
|
||||
|
||||
|
||||
@Component({
|
||||
@@ -268,7 +269,7 @@ export class MetadataViewerComponent implements OnInit, OnChanges, AfterViewChec
|
||||
{
|
||||
label: this.t.translate('metadata.viewer.menuQuickSend'),
|
||||
icon: 'pi pi-bolt',
|
||||
command: () => this.quickSend(book.id)
|
||||
command: () => this.quickSend(book)
|
||||
},
|
||||
{
|
||||
label: this.t.translate('metadata.viewer.menuCustomSend'),
|
||||
@@ -490,6 +491,10 @@ export class MetadataViewerComponent implements OnInit, OnChanges, AfterViewChec
|
||||
this.isExpanded = !this.isExpanded;
|
||||
}
|
||||
|
||||
sanitizeDescription(html: string | null | undefined): string {
|
||||
return html ? DOMPurify.sanitize(html) : '';
|
||||
}
|
||||
|
||||
read(bookId: number | undefined, reader?: "epub-streaming", bookType?: BookType): void {
|
||||
if (bookId) this.bookService.readBook(bookId, reader, bookType);
|
||||
}
|
||||
@@ -646,19 +651,36 @@ export class MetadataViewerComponent implements OnInit, OnChanges, AfterViewChec
|
||||
}, 15000);
|
||||
}
|
||||
|
||||
quickSend(bookId: number) {
|
||||
this.emailService.emailBookQuick(bookId).subscribe({
|
||||
next: () => this.messageService.add({
|
||||
severity: 'info',
|
||||
summary: this.t.translate('metadata.viewer.toast.quickSendSuccessSummary'),
|
||||
detail: this.t.translate('metadata.viewer.toast.quickSendSuccessDetail'),
|
||||
}),
|
||||
error: (err) => this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('metadata.viewer.toast.quickSendErrorSummary'),
|
||||
detail: err?.error?.message || this.t.translate('metadata.viewer.toast.quickSendErrorDetail'),
|
||||
})
|
||||
});
|
||||
quickSend(book: Book) {
|
||||
const doSend = () => {
|
||||
this.emailService.emailBookQuick(book.id).subscribe({
|
||||
next: () => this.messageService.add({
|
||||
severity: 'info',
|
||||
summary: this.t.translate('metadata.viewer.toast.quickSendSuccessSummary'),
|
||||
detail: this.t.translate('metadata.viewer.toast.quickSendSuccessDetail'),
|
||||
}),
|
||||
error: (err) => this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('metadata.viewer.toast.quickSendErrorSummary'),
|
||||
detail: err?.error?.message || this.t.translate('metadata.viewer.toast.quickSendErrorDetail'),
|
||||
})
|
||||
});
|
||||
};
|
||||
|
||||
if (book.primaryFile?.fileSizeKb && book.primaryFile.fileSizeKb > 25 * 1024) {
|
||||
this.confirmationService.confirm({
|
||||
message: this.t.translate('metadata.viewer.confirm.largeFileMessage'),
|
||||
header: this.t.translate('metadata.viewer.confirm.largeFileHeader'),
|
||||
icon: 'pi pi-exclamation-triangle',
|
||||
acceptLabel: this.t.translate('metadata.viewer.confirm.sendAnyway'),
|
||||
rejectLabel: this.t.translate('common.cancel'),
|
||||
acceptButtonProps: { severity: 'warn' },
|
||||
rejectButtonProps: { severity: 'secondary' },
|
||||
accept: doSend,
|
||||
});
|
||||
} else {
|
||||
doSend();
|
||||
}
|
||||
}
|
||||
|
||||
assignShelf(bookId: number) {
|
||||
|
||||
+3
-6
@@ -148,9 +148,8 @@ $border-color: rgba(255, 255, 255, 0.1);
|
||||
.cover-container {
|
||||
flex-shrink: 0;
|
||||
width: 100%;
|
||||
max-width: 480px;
|
||||
max-width: min(480px, 40vh);
|
||||
aspect-ratio: 1;
|
||||
margin-top: 1.5rem;
|
||||
|
||||
.cover-wrapper {
|
||||
position: relative;
|
||||
@@ -712,8 +711,7 @@ $border-color: rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
|
||||
.cover-container {
|
||||
max-width: 360px;
|
||||
margin-top: 1rem;
|
||||
max-width: min(360px, 35vh);
|
||||
}
|
||||
|
||||
.secondary-controls {
|
||||
@@ -748,8 +746,7 @@ $border-color: rgba(255, 255, 255, 0.1);
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.cover-container {
|
||||
max-width: 300px;
|
||||
margin-top: 0.5rem;
|
||||
max-width: min(300px, 30vh);
|
||||
}
|
||||
|
||||
.playback-controls {
|
||||
|
||||
@@ -25,7 +25,7 @@ export class SeriesDataService {
|
||||
const seriesName = book.metadata?.seriesName;
|
||||
if (!seriesName) continue;
|
||||
|
||||
const key = seriesName.toLowerCase();
|
||||
const key = seriesName.trim().toLowerCase();
|
||||
if (!seriesMap.has(key)) {
|
||||
seriesMap.set(key, []);
|
||||
}
|
||||
@@ -41,7 +41,7 @@ export class SeriesDataService {
|
||||
return aNum - bNum;
|
||||
});
|
||||
|
||||
const displayName = sorted[0].metadata?.seriesName || '';
|
||||
const displayName = sorted[0].metadata?.seriesName?.trim() || '';
|
||||
const authorSet = new Set<string>();
|
||||
const categorySet = new Set<string>();
|
||||
|
||||
|
||||
+27
@@ -11,6 +11,33 @@
|
||||
</div>
|
||||
|
||||
<div class="settings-content">
|
||||
<div class="preferences-section">
|
||||
<div class="section-header">
|
||||
<h3 class="section-title">
|
||||
<i class="pi pi-palette"></i>
|
||||
{{ t('appearance.sectionTitle') }}
|
||||
</h3>
|
||||
</div>
|
||||
|
||||
<div class="settings-card">
|
||||
<div class="setting-item">
|
||||
<div class="setting-info">
|
||||
<div class="setting-label-row">
|
||||
<label class="setting-label">{{ t('appearance.supportButtonAnimation') }}</label>
|
||||
<p-toggleswitch
|
||||
[(ngModel)]="supportButtonAnimation"
|
||||
(onChange)="onSupportAnimationChange($event.checked)">
|
||||
</p-toggleswitch>
|
||||
</div>
|
||||
<p class="setting-description">
|
||||
<i class="pi pi-info-circle"></i>
|
||||
{{ t('appearance.supportButtonAnimationDesc') }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="preferences-section">
|
||||
<div class="section-header">
|
||||
<h3 class="section-title">
|
||||
|
||||
+10
@@ -14,6 +14,8 @@ import {Slider} from 'primeng/slider';
|
||||
import {ExternalDocLinkComponent} from '../../../shared/components/external-doc-link/external-doc-link.component';
|
||||
import {TranslocoDirective, TranslocoPipe, TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
export const SUPPORT_ANIMATION_KEY = 'booklore-support-animation';
|
||||
|
||||
@Component({
|
||||
selector: 'app-global-preferences',
|
||||
standalone: true,
|
||||
@@ -38,6 +40,8 @@ export class GlobalPreferencesComponent implements OnInit {
|
||||
enableTelemetry: true,
|
||||
};
|
||||
|
||||
supportButtonAnimation = localStorage.getItem(SUPPORT_ANIMATION_KEY) !== 'false';
|
||||
|
||||
coverCroppingSettings: CoverCroppingSettings = {
|
||||
verticalCroppingEnabled: false,
|
||||
horizontalCroppingEnabled: false,
|
||||
@@ -85,6 +89,12 @@ export class GlobalPreferencesComponent implements OnInit {
|
||||
}
|
||||
}
|
||||
|
||||
onSupportAnimationChange(checked: boolean): void {
|
||||
this.supportButtonAnimation = checked;
|
||||
localStorage.setItem(SUPPORT_ANIMATION_KEY, String(checked));
|
||||
window.dispatchEvent(new StorageEvent('storage', {key: SUPPORT_ANIMATION_KEY, newValue: String(checked)}));
|
||||
}
|
||||
|
||||
onCoverCroppingChange(): void {
|
||||
this.saveSetting(AppSettingKey.COVER_CROPPING_SETTINGS, this.coverCroppingSettings);
|
||||
}
|
||||
|
||||
@@ -56,7 +56,7 @@ export interface PerBookSetting {
|
||||
}
|
||||
|
||||
export type PageSpread = 'off' | 'even' | 'odd';
|
||||
export type BookFilterMode = 'and' | 'or' | 'single';
|
||||
export type BookFilterMode = 'and' | 'or' | 'single' | 'not';
|
||||
|
||||
|
||||
export enum CbxPageViewMode {
|
||||
|
||||
@@ -4,6 +4,7 @@ import {DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||
import {IconService} from '../../services/icon.service';
|
||||
import {IconCacheService} from '../../services/icon-cache.service';
|
||||
import {DomSanitizer, SafeHtml} from '@angular/platform-browser';
|
||||
import DOMPurify from 'dompurify';
|
||||
import {UrlHelperService} from '../../service/url-helper.service';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {IconCategoriesHelper} from '../../helpers/icon-categories.helper';
|
||||
@@ -158,7 +159,11 @@ export class IconPickerComponent implements OnInit {
|
||||
}
|
||||
|
||||
try {
|
||||
this.svgPreview = this.sanitizer.bypassSecurityTrustHtml(this.svgContent);
|
||||
const sanitized = DOMPurify.sanitize(this.svgContent, {
|
||||
USE_PROFILES: { svg: true },
|
||||
FORBID_TAGS: ['script', 'style', 'foreignObject']
|
||||
});
|
||||
this.svgPreview = this.sanitizer.bypassSecurityTrustHtml(sanitized);
|
||||
} catch {
|
||||
this.svgPreview = null;
|
||||
this.errorMessage = this.ERROR_MESSAGES.PARSE_ERROR;
|
||||
|
||||
@@ -3,99 +3,99 @@
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0.375rem;
|
||||
padding: 0.25rem 0.5rem;
|
||||
padding: 0.1875rem 0.4375rem;
|
||||
font-size: 0.875rem;
|
||||
font-weight: 700;
|
||||
font-weight: 500;
|
||||
line-height: 1.25rem;
|
||||
border-radius: 0.375rem;
|
||||
white-space: nowrap;
|
||||
|
||||
&-5xs {
|
||||
padding: 0.125rem 0.375rem;
|
||||
padding: 0.09375rem 0.3125rem;
|
||||
font-size: 0.625rem;
|
||||
line-height: 0.875rem;
|
||||
gap: 0.25rem;
|
||||
}
|
||||
|
||||
&-4xs {
|
||||
padding: 0.15625rem 0.40625rem;
|
||||
padding: 0.109375rem 0.328125rem;
|
||||
font-size: 0.6875rem;
|
||||
line-height: 0.9375rem;
|
||||
gap: 0.28125rem;
|
||||
}
|
||||
|
||||
&-3xs {
|
||||
padding: 0.1875rem 0.4375rem;
|
||||
padding: 0.125rem 0.375rem;
|
||||
font-size: 0.75rem;
|
||||
line-height: 1rem;
|
||||
gap: 0.3125rem;
|
||||
}
|
||||
|
||||
&-2xs {
|
||||
padding: 0.203125rem 0.453125rem;
|
||||
padding: 0.140625rem 0.390625rem;
|
||||
font-size: 0.78125rem;
|
||||
line-height: 1.0625rem;
|
||||
gap: 0.328125rem;
|
||||
}
|
||||
|
||||
&-xs {
|
||||
padding: 0.21875rem 0.46875rem;
|
||||
font-size: 0.875rem;
|
||||
padding: 0.15625rem 0.40625rem;
|
||||
font-size: 0.8125rem;
|
||||
line-height: 1.125rem;
|
||||
gap: 0.34375rem;
|
||||
}
|
||||
|
||||
&-s {
|
||||
padding: 0.234375rem 0.484375rem;
|
||||
padding: 0.171875rem 0.421875rem;
|
||||
font-size: 0.84375rem;
|
||||
line-height: 1.1875rem;
|
||||
gap: 0.359375rem;
|
||||
}
|
||||
|
||||
&-m {
|
||||
padding: 0.25rem 0.5rem;
|
||||
padding: 0.1875rem 0.4375rem;
|
||||
font-size: 0.875rem;
|
||||
line-height: 1.25rem;
|
||||
gap: 0.375rem;
|
||||
}
|
||||
|
||||
&-l {
|
||||
padding: 0.265625rem 0.515625rem;
|
||||
padding: 0.203125rem 0.453125rem;
|
||||
font-size: 0.90625rem;
|
||||
line-height: 1.3125rem;
|
||||
gap: 0.390625rem;
|
||||
}
|
||||
|
||||
&-xl {
|
||||
padding: 0.28125rem 0.53125rem;
|
||||
padding: 0.21875rem 0.46875rem;
|
||||
font-size: 0.9375rem;
|
||||
line-height: 1.375rem;
|
||||
gap: 0.40625rem;
|
||||
}
|
||||
|
||||
&-2xl {
|
||||
padding: 0.296875rem 0.546875rem;
|
||||
padding: 0.234375rem 0.484375rem;
|
||||
font-size: 0.96875rem;
|
||||
line-height: 1.4375rem;
|
||||
gap: 0.421875rem;
|
||||
}
|
||||
|
||||
&-3xl {
|
||||
padding: 0.3125rem 0.5625rem;
|
||||
padding: 0.25rem 0.5rem;
|
||||
font-size: 1rem;
|
||||
line-height: 1.5rem;
|
||||
gap: 0.4375rem;
|
||||
}
|
||||
|
||||
&-4xl {
|
||||
padding: 0.34375rem 0.59375rem;
|
||||
padding: 0.28125rem 0.53125rem;
|
||||
font-size: 1.0625rem;
|
||||
line-height: 1.5625rem;
|
||||
gap: 0.46875rem;
|
||||
}
|
||||
|
||||
&-5xl {
|
||||
padding: 0.375rem 0.625rem;
|
||||
padding: 0.3125rem 0.5625rem;
|
||||
font-size: 1.125rem;
|
||||
line-height: 1.625rem;
|
||||
gap: 0.5rem;
|
||||
@@ -110,8 +110,9 @@
|
||||
}
|
||||
|
||||
&-primary {
|
||||
background-color: color-mix(in srgb, var(--p-primary-500), transparent 84%);
|
||||
color: var(--p-primary-200);
|
||||
background-color: color-mix(in srgb, var(--p-primary-500), transparent 82%);
|
||||
color: var(--p-primary-300);
|
||||
border: 1px solid color-mix(in srgb, var(--p-primary-500), transparent 65%);
|
||||
}
|
||||
|
||||
$colors: (
|
||||
@@ -146,19 +147,22 @@
|
||||
|
||||
@each $name, $color in $colors {
|
||||
&-#{$name} {
|
||||
background-color: color-mix(in srgb, var(--p-#{$color}-500), transparent 84%);
|
||||
color: var(--p-#{$color}-200);
|
||||
background-color: color-mix(in srgb, var(--p-#{$color}-500), transparent 82%);
|
||||
color: var(--p-#{$color}-300);
|
||||
border: 1px solid color-mix(in srgb, var(--p-#{$color}-500), transparent 65%);
|
||||
}
|
||||
}
|
||||
|
||||
&-dark {
|
||||
background-color: color-mix(in srgb, var(--p-gray-800), transparent 84%);
|
||||
background-color: color-mix(in srgb, var(--p-gray-800), transparent 82%);
|
||||
color: var(--p-gray-300);
|
||||
border: 1px solid color-mix(in srgb, var(--p-gray-800), transparent 65%);
|
||||
}
|
||||
|
||||
&-light {
|
||||
background-color: color-mix(in srgb, var(--p-gray-300), transparent 84%);
|
||||
background-color: color-mix(in srgb, var(--p-gray-300), transparent 82%);
|
||||
color: var(--p-gray-600);
|
||||
border: 1px solid color-mix(in srgb, var(--p-gray-300), transparent 65%);
|
||||
}
|
||||
|
||||
&-variant-pill {
|
||||
@@ -168,23 +172,27 @@
|
||||
&.app-tag-primary {
|
||||
background-color: var(--p-primary-600);
|
||||
color: var(--p-primary-100);
|
||||
border-color: var(--p-primary-500);
|
||||
}
|
||||
|
||||
@each $name, $color in $colors {
|
||||
&.app-tag-#{$name} {
|
||||
background-color: var(--p-#{$color}-600);
|
||||
color: var(--p-#{$color}-100);
|
||||
border-color: var(--p-#{$color}-500);
|
||||
}
|
||||
}
|
||||
|
||||
&.app-tag-dark {
|
||||
background-color: var(--p-gray-800);
|
||||
color: var(--p-gray-100);
|
||||
border-color: var(--p-gray-700);
|
||||
}
|
||||
|
||||
&.app-tag-light {
|
||||
background-color: var(--p-gray-300);
|
||||
color: var(--p-gray-800);
|
||||
border-color: var(--p-gray-400);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import {AppMenuitemComponent} from './app.menuitem.component';
|
||||
import {AsyncPipe} from '@angular/common';
|
||||
import {MenuModule} from 'primeng/menu';
|
||||
import {LibraryService} from '../../../../features/book/service/library.service';
|
||||
import {LibraryHealthService} from '../../../../features/book/service/library-health.service';
|
||||
import {combineLatest, Observable, of} from 'rxjs';
|
||||
import {filter, map} from 'rxjs/operators';
|
||||
import {ShelfService} from '../../../../features/book/service/shelf.service';
|
||||
@@ -39,6 +40,7 @@ export class AppMenuComponent implements OnInit {
|
||||
dynamicDialogRef: DynamicDialogRef | undefined | null;
|
||||
|
||||
private libraryService = inject(LibraryService);
|
||||
private libraryHealthService = inject(LibraryHealthService);
|
||||
private shelfService = inject(ShelfService);
|
||||
private bookService = inject(BookService);
|
||||
private versionService = inject(VersionService);
|
||||
@@ -156,6 +158,7 @@ export class AppMenuComponent implements OnInit {
|
||||
iconType: (library.iconType || undefined) as 'PRIME_NG' | 'CUSTOM_SVG' | undefined,
|
||||
routerLink: [`/library/${library.id}/books`],
|
||||
bookCount$: this.libraryService.getBookCount(library.id ?? 0),
|
||||
unhealthy$: this.libraryHealthService.isUnhealthy$(library.id ?? 0),
|
||||
})),
|
||||
},
|
||||
];
|
||||
|
||||
@@ -53,6 +53,13 @@
|
||||
tabindex="0"
|
||||
pRipple
|
||||
>
|
||||
@if (item.unhealthy$ | async) {
|
||||
<span
|
||||
class="library-health-dot"
|
||||
[pTooltip]="'common.libraryPathInaccessible' | transloco"
|
||||
tooltipPosition="right"
|
||||
></span>
|
||||
}
|
||||
<app-icon-display
|
||||
[icon]="getIconSelection()"
|
||||
iconClass="layout-menuitem-icon"
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user