Merge pull request #1433 from booklore-app/develop

Merge develop into master for release
This commit is contained in:
Aditya Chandel
2025-10-24 11:20:28 -06:00
committed by GitHub
204 changed files with 5259 additions and 4629 deletions
+107
View File
@@ -0,0 +1,107 @@
## Set Git attributes for paths including line ending
## normalization, diff behavior, etc.
##
## Get latest from `dotnet new gitattributes`
# Auto detect text files and perform LF normalization
* text=auto
#
# The above will handle all files NOT found below
#
*.cs text diff=csharp
*.cshtml text diff=html
*.csx text diff=csharp
*.sln text eol=crlf
# Content below from: https://github.com/gitattributes/gitattributes/blob/master/Common.gitattributes
# Documents
*.bibtex text diff=bibtex
*.doc diff=astextplain
*.DOC diff=astextplain
*.docx diff=astextplain
*.DOCX diff=astextplain
*.dot diff=astextplain
*.DOT diff=astextplain
*.pdf diff=astextplain
*.PDF diff=astextplain
*.rtf diff=astextplain
*.RTF diff=astextplain
*.md text diff=markdown
*.mdx text diff=markdown
*.tex text diff=tex
*.adoc text
*.textile text
*.mustache text
# Per RFC 4180, .csv should be CRLF
*.csv text eol=crlf
*.tab text
*.tsv text
*.txt text
*.sql text
*.epub diff=astextplain
# Graphics
*.png binary
*.jpg binary
*.jpeg binary
*.gif binary
*.tif binary
*.tiff binary
*.ico binary
# SVG treated as text by default.
*.svg text
# If you want to treat it as binary,
# use the following line instead.
# *.svg binary
*.eps binary
# Scripts
# Force Unix scripts to always use lf line endings so that if a repo is accessed
# in Unix via a file share from Windows, the scripts will work
*.bash text eol=lf
*.fish text eol=lf
*.ksh text eol=lf
*.sh text eol=lf
*.zsh text eol=lf
# Likewise, force cmd and batch scripts to always use crlf
*.bat text eol=crlf
*.cmd text eol=crlf
# Serialization
*.json text
*.toml text
*.xml text
*.yaml text
*.yml text
# Archives
*.7z binary
*.bz binary
*.bz2 binary
*.bzip2 binary
*.gz binary
*.lz binary
*.lzma binary
*.rar binary
*.tar binary
*.taz binary
*.tbz binary
*.tbz2 binary
*.tgz binary
*.tlz binary
*.txz binary
*.xz binary
*.Z binary
*.zip binary
*.zst binary
# Text files where line endings should be preserved
*.patch -text
# Exclude files from exporting
.gitattributes export-ignore
.gitignore export-ignore
.gitkeep export-ignore
+46 -61
View File
@@ -91,54 +91,70 @@ Ensure you have [Docker](https://docs.docker.com/get-docker/) and [Docker Compos
> **Note:** Legacy images under `https://ghcr.io/adityachandelgit/booklore-app` will remain available but will not receive new updates.
### 2️⃣ Create docker-compose.yml
### 2️⃣ Set Up Your docker-compose.yml Configuration
> ⚠️ If you intend to run the container as a non-root user, you must manually create all of your `/your/local/path/to/booklore` directories with read and write permissions for your intended user **before first run**.
**Step 1: Create a `.env` file** in the same directory as your `docker-compose.yml`:
Create a `docker-compose.yml` file with content:
```ini
# BookLore Application Settings
APP_USER_ID=0
APP_GROUP_ID=0
TZ=Etc/UTC
BOOKLORE_PORT=6060
# Database Connection (BookLore)
DATABASE_URL=jdbc:mariadb://mariadb:3306/booklore
DB_USER=booklore
DB_PASSWORD=ChangeMe_BookLoreApp_2025!
# MariaDB Container Settings
DB_USER_ID=1000
DB_GROUP_ID=1000
MYSQL_ROOT_PASSWORD=ChangeMe_MariaDBRoot_2025!
MYSQL_DATABASE=booklore
```
**Step 2: Create a `docker-compose.yml` file** that references the `.env` variables:
```yaml
services:
booklore:
# Official Docker Hub image:
image: booklore/booklore:latest
# Or the GHCR image:
# Alternative: Use GitHub Container Registry
# image: ghcr.io/booklore-app/booklore:latest
container_name: booklore
environment:
- USER_ID=0
- GROUP_ID=0
- TZ=Etc/UTC
- DATABASE_URL=jdbc:mariadb://mariadb:3306/booklore
- DATABASE_USERNAME=booklore # Must match MYSQL_USER defined in the mariadb container
- DATABASE_PASSWORD=your_secure_password
- BOOKLORE_PORT=6060 # Port BookLore listens on inside the container; must match container port below
- USER_ID=${APP_USER_ID}
- GROUP_ID=${APP_GROUP_ID}
- TZ=${TZ}
- DATABASE_URL=${DATABASE_URL}
- DATABASE_USERNAME=${DB_USER}
- DATABASE_PASSWORD=${DB_PASSWORD}
- BOOKLORE_PORT=${BOOKLORE_PORT}
depends_on:
mariadb:
condition: service_healthy
ports:
- "6060:6060" # HostPort:ContainerPort → Keep both numbers the same, and also ensure the container port matches BOOKLORE_PORT, no exceptions.
# All three (host port, container port, BOOKLORE_PORT) must be identical for BookLore to function properly.
# Example: To expose on host port 7070, set BOOKLORE_PORT=7070 and use "7070:7070".
- "${BOOKLORE_PORT}:${BOOKLORE_PORT}"
volumes:
- /your/local/path/to/booklore/data:/app/data # Application data (settings, metadata, cache, etc.). Persist this folder to retain your library state across container restarts.
- /your/local/path/to/booklore/books:/books # Primary book library folder. Mount your collection here so BookLore can access and organize your books.
- /your/local/path/to/booklore/bookdrop:/bookdrop # BookDrop folder. Files placed here are automatically detected and prepared for import.
- ./data:/app/data
- ./books:/books
- ./bookdrop:/bookdrop
restart: unless-stopped
mariadb:
image: lscr.io/linuxserver/mariadb:11.4.5
container_name: mariadb
environment:
- PUID=1000
- PGID=1000
- TZ=Etc/UTC
- MYSQL_ROOT_PASSWORD=super_secure_password # Use a strong password for the database's root user, should be different from MYSQL_PASSWORD
- MYSQL_DATABASE=booklore
- MYSQL_USER=booklore # Must match DATABASE_USERNAME defined in the booklore container
- MYSQL_PASSWORD=your_secure_password # Use a strong password; must match DATABASE_PASSWORD defined in the booklore container
- PUID=${DB_USER_ID}
- PGID=${DB_GROUP_ID}
- TZ=${TZ}
- MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD}
- MYSQL_DATABASE=${MYSQL_DATABASE}
- MYSQL_USER=${DB_USER}
- MYSQL_PASSWORD=${DB_PASSWORD}
volumes:
- /your/local/path/to/mariadb/config:/config
- ./mariadb/config:/config
restart: unless-stopped
healthcheck:
test: [ "CMD", "mariadb-admin", "ping", "-h", "localhost" ]
@@ -147,9 +163,6 @@ services:
retries: 10
```
Note: You can find the latest BookLore image tag `BOOKLORE_IMAGE_TAG` (e.g. v.0.x.x) from the Releases section:
📦 [Latest Image Tag – GitHub Releases](https://github.com/adityachandelgit/BookLore/releases)
### 3️⃣ Start the Containers
Run the following command to start the services:
@@ -163,37 +176,9 @@ docker compose up -d
Once the containers are up, access BookLore in your browser at:
```ini
http : //localhost:6060
http://localhost:6060
```
## ⚙️ Supported Environment Variables
### BookLore Container
| Key | Default Value | Description |
|----------------------|----------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `USER_ID` | `0` | User ID for file ownership within the container. Set this to match your host user's UID if running as non-root (e.g., `1000`). Use `id -u` on Linux to find your UID. |
| `GROUP_ID` | `0` | Group ID for file ownership within the container. Set this to match your host user's GID if running as non-root (e.g., `1000`). Use `id -g` on Linux to find your GID. |
| `TZ` | `Etc/UTC` | Timezone for the application. Controls timestamps in logs and UI. Use standard timezone identifiers (e.g., `America/New_York`, `Europe/London`, `Asia/Tokyo`). See [List of tz database time zones](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). |
| `DATABASE_URL` | `jdbc:mariadb://mariadb:3306/booklore` | JDBC connection string for MariaDB/MySQL database. Format: `jdbc:mariadb://hostname:port/database_name`. Only modify if using a custom database host, port, or external database server. |
| `DATABASE_USERNAME` | `booklore` | Username for database authentication. Must match `MYSQL_USER` in your MariaDB container configuration. |
| `DATABASE_PASSWORD` | - | Password for database authentication. **Required**. Use a strong, unique password. Must match `MYSQL_PASSWORD` in your MariaDB container configuration. Store securely and never commit to version control. |
| `BOOKLORE_PORT` | `6060` | Internal port BookLore listens on. **Critical**: This must match both the host and container ports in your port mapping (e.g., `6060:6060`). Changing this requires updating all three values. Example: For port `7070`, use `BOOKLORE_PORT=7070` and `7070:7070`. |
| `SWAGGER_ENABLED` | `false` | Controls access to Swagger UI for API documentation and testing. Set to `true` to enable at `/swagger-ui.html` (useful for development/testing). Keep `false` in production for security. |
| `FORCE_DISABLE_OIDC` | `false` | Forces local username/password authentication only. Set to `true` to completely disable OIDC/OAuth2 providers (Authentik, Pocket ID, etc.). Useful for troubleshooting authentication issues or temporarily bypassing external identity providers. |
### MariaDB Container
| Key | Default Value | Description |
|-----------------------|---------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `PUID` | `1000` | Process User ID for the LinuxServer.io MariaDB container. Set this to match your host user's UID for proper file permissions. Use `id -u` on Linux to find your UID. |
| `PGID` | `1000` | Process Group ID for the LinuxServer.io MariaDB container. Set this to match your host user's GID for proper file permissions. Use `id -g` on Linux to find your GID. |
| `TZ` | `Etc/UTC` | Timezone for the MariaDB container. Should match the BookLore container's timezone for consistency in timestamps. |
| `MYSQL_ROOT_PASSWORD` | - | Root password for the MariaDB database. **Required**. Use a strong, unique password different from `MYSQL_PASSWORD`. This provides administrative access to the database server. Never expose or commit to VCS. |
| `MYSQL_DATABASE` | `booklore` | Name of the database to create on first run. This database will be used by BookLore to store all application data. Should not be changed after initial setup. |
| `MYSQL_USER` | `booklore` | Username for the application database user. Must match `DATABASE_USERNAME` in the BookLore container configuration. This user will have full access to the `MYSQL_DATABASE`. |
| `MYSQL_PASSWORD` | - | Password for the application database user. **Required**. Use a strong, unique password. Must match `DATABASE_PASSWORD` in the BookLore container configuration. Store securely and never commit to VCS. |
## 📥 Bookdrop Folder: Auto-Import Files
BookLore now supports a **Bookdrop folder**, a special directory where you can drop your book files (`.pdf`, `.epub`, `.cbz`, etc.), and BookLore will automatically detect, process, and prepare them for import. This makes it easy to bulk add new books without manually uploading each one.
@@ -214,9 +199,9 @@ services:
booklore:
...
volumes:
- /your/local/path/to/booklore/data:/app/data
- /your/local/path/to/booklore/books:/books
- /your/local/path/to/booklore/bookdrop:/bookdrop # 👈 Bookdrop directory
- ./data:/app/data
- ./books:/books
- ./bookdrop:/bookdrop # 👈 Bookdrop directory
```
## 🔑 OIDC/OAuth2 Authentication (Authentik, Pocket ID, etc.)
@@ -2,9 +2,12 @@ package com.adityachandel.booklore.config;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import io.swagger.v3.oas.models.servers.Server;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -16,7 +19,18 @@ public class OpenApiConfig {
final String securitySchemeName = "bearerAuth";
return new OpenAPI()
.info(new Info().title("Booklore API").version("1.0"))
.info(new Info()
.title("Booklore API")
.version("1.0")
.description("Booklore is a personal library management system. This API allows you to manage books, libraries, users, shelves, and more.")
.contact(new Contact()
.name("Booklore")
.url("https://github.com/booklore-app/booklore"))
.license(new License()
.name("GNU General Public License v3.0")
.url("https://www.gnu.org/licenses/gpl-3.0.html"))
)
.addServersItem(new Server().url("/").description("Current server"))
.addSecurityItem(new SecurityRequirement().addList(securitySchemeName))
.components(new Components().addSecuritySchemes(securitySchemeName,
new SecurityScheme()
@@ -0,0 +1,24 @@
package com.adityachandel.booklore.config;
import com.adityachandel.booklore.service.task.TaskService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.EnableScheduling;
@Configuration
@EnableScheduling
@AllArgsConstructor
@Slf4j
public class TaskSchedulerConfig {
private final TaskService taskService;
@EventListener(ApplicationReadyEvent.class)
public void initializeScheduledTasks() {
log.info("Application ready, initializing scheduled tasks");
taskService.initializeScheduledTasks();
}
}
@@ -4,20 +4,21 @@ import com.adityachandel.booklore.config.security.filter.ImageCachingFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
@Configuration
public class ImageCacheConfig {
@Bean
public FilterRegistrationBean<ImageCachingFilter> imageCachingFilterRegistration(ImageCachingFilter filter) {
public FilterRegistrationBean<ImageCachingFilter> imageCachingFilterRegistration() {
FilterRegistrationBean<ImageCachingFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(filter);
registrationBean.setFilter(new ImageCachingFilter());
registrationBean.addUrlPatterns(
"/api/v1/media/book/*/cover",
"/api/v1/media/book/*/thumbnail",
"/api/v1/media/book/*/backup-cover"
);
registrationBean.setOrder(1);
registrationBean.setOrder(Ordered.LOWEST_PRECEDENCE);
return registrationBean;
}
}
@@ -17,6 +17,7 @@ import org.springframework.security.config.annotation.authentication.builders.Au
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@@ -42,9 +43,9 @@ public class SecurityConfig {
private final AppProperties appProperties;
private static final String[] SWAGGER_ENDPOINTS = {
"/swagger-ui.html",
"/swagger-ui/**",
"/v3/api-docs/**"
"/api/v1/swagger-ui.html",
"/api/v1/swagger-ui/**",
"/api/v1/api-docs/**"
};
private static final String[] COMMON_PUBLIC_ENDPOINTS = {
@@ -120,6 +121,9 @@ public class SecurityConfig {
.securityMatcher("/api/v1/media/**")
.csrf(AbstractHttpConfigurer::disable)
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.headers(headers -> headers
.cacheControl(HeadersConfigurer.CacheControlConfig::disable)
)
.authorizeHttpRequests(auth -> auth
.anyRequest().permitAll()
)
@@ -148,7 +152,6 @@ public class SecurityConfig {
return http.build();
}
@Bean
public AuthenticationManager authenticationManager(HttpSecurity http) throws Exception {
return http.getSharedObject(AuthenticationManagerBuilder.class)
@@ -41,21 +41,24 @@ public class CoverJwtFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
String token = request.getParameter("token");
if (token != null) {
try {
if (jwtUtils.validateToken(token)) {
authenticateLocalUser(token, request);
} else if (appSettingService.getAppSettings().isOidcEnabled()) {
authenticateOidcUser(token, request);
} else {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Missing or invalid token");
return;
}
} catch (Exception ex) {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication failed: " + ex.getMessage());
if (token == null || token.isEmpty()) {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Missing authentication token");
return;
}
try {
if (jwtUtils.validateToken(token)) {
authenticateLocalUser(token, request);
} else if (appSettingService.getAppSettings().isOidcEnabled()) {
authenticateOidcUser(token, request);
} else {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid token");
return;
}
} catch (Exception ex) {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication failed: " + ex.getMessage());
return;
}
chain.doFilter(request, response);
}
@@ -8,6 +8,7 @@ import com.adityachandel.booklore.model.dto.BookLoreUser;
import com.adityachandel.booklore.model.dto.request.UserLoginRequest;
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
import com.adityachandel.booklore.model.entity.RefreshTokenEntity;
import com.adityachandel.booklore.model.enums.ProvisioningMethod;
import com.adityachandel.booklore.repository.RefreshTokenRepository;
import com.adityachandel.booklore.repository.UserRepository;
import com.adityachandel.booklore.service.user.DefaultSettingInitializer;
@@ -21,6 +22,7 @@ import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -39,14 +41,48 @@ public class AuthenticationService {
public BookLoreUser getAuthenticatedUser() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null) {
return null;
}
Object principal = authentication.getPrincipal();
if (principal instanceof BookLoreUser) {
defaultSettingInitializer.ensureDefaultSettings((BookLoreUser) principal);
return (BookLoreUser) principal;
if (principal instanceof BookLoreUser user) {
if (user.getId() != null && user.getId() != -1L) {
defaultSettingInitializer.ensureDefaultSettings(user);
}
return user;
}
throw new IllegalStateException("Authenticated principal is not of type BookLoreUser");
}
public BookLoreUser getSystemUser() {
return createSystemUser();
}
private BookLoreUser createSystemUser() {
BookLoreUser.UserPermissions permissions = new BookLoreUser.UserPermissions();
permissions.setAdmin(true);
permissions.setCanUpload(true);
permissions.setCanDownload(true);
permissions.setCanEditMetadata(true);
permissions.setCanManipulateLibrary(true);
permissions.setCanSyncKoReader(true);
permissions.setCanSyncKobo(true);
permissions.setCanEmailBook(true);
permissions.setCanDeleteBook(true);
permissions.setCanAccessOpds(true);
return BookLoreUser.builder()
.id(-1L)
.username("system")
.name("System User")
.email("system@booklore.internal")
.provisioningMethod(ProvisioningMethod.LOCAL)
.isDefaultPassword(false)
.permissions(permissions)
.assignedLibraries(List.of())
.userSettings(new BookLoreUser.UserSettings())
.build();
}
public OpdsUserDetails getOpdsUser() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
@@ -3,7 +3,7 @@ package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.config.security.annotation.CheckBookAccess;
import com.adityachandel.booklore.model.dto.AdditionalFile;
import com.adityachandel.booklore.model.enums.AdditionalFileType;
import com.adityachandel.booklore.service.AdditionalFileService;
import com.adityachandel.booklore.service.file.AdditionalFileService;
import com.adityachandel.booklore.service.upload.FileUploadService;
import lombok.AllArgsConstructor;
import org.springframework.core.io.Resource;
@@ -5,11 +5,17 @@ import com.adityachandel.booklore.model.dto.settings.AppSettings;
import com.adityachandel.booklore.model.dto.settings.SettingRequest;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import com.fasterxml.jackson.core.JsonProcessingException;
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 io.swagger.v3.oas.annotations.responses.ApiResponses;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Tag(name = "App Settings", description = "Endpoints for retrieving and updating application settings")
@AllArgsConstructor
@RestController
@RequestMapping("/api/v1/settings")
@@ -17,13 +23,21 @@ public class AppSettingController {
private final AppSettingService appSettingService;
@Operation(summary = "Get application settings", description = "Retrieve all application settings.")
@ApiResponse(responseCode = "200", description = "Application settings returned successfully")
@GetMapping
public AppSettings getAppSettings() {
return appSettingService.getAppSettings();
}
@Operation(summary = "Update application settings", description = "Update one or more application settings.")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Settings updated successfully"),
@ApiResponse(responseCode = "400", description = "Invalid request")
})
@PutMapping
public void updateSettings(@RequestBody List<SettingRequest> settingRequests) throws JsonProcessingException {
public void updateSettings(
@Parameter(description = "List of settings to update") @RequestBody List<SettingRequest> settingRequests) throws JsonProcessingException {
for (SettingRequest settingRequest : settingRequests) {
AppSettingKey key = AppSettingKey.valueOf(settingRequest.getName());
appSettingService.updateSetting(key, settingRequest.getValue());
@@ -6,7 +6,14 @@ import com.adityachandel.booklore.exception.ApiError;
import com.adityachandel.booklore.model.dto.UserCreateRequest;
import com.adityachandel.booklore.model.dto.request.RefreshTokenRequest;
import com.adityachandel.booklore.model.dto.request.UserLoginRequest;
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
import com.adityachandel.booklore.repository.UserRepository;
import com.adityachandel.booklore.service.user.UserProvisioningService;
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 io.swagger.v3.oas.annotations.responses.ApiResponses;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@@ -16,7 +23,9 @@ import org.springframework.web.bind.annotation.*;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
@Tag(name = "Authentication", description = "Endpoints for user authentication, registration, and token management")
@Slf4j
@AllArgsConstructor
@RestController
@@ -26,26 +35,45 @@ public class AuthenticationController {
private final AppProperties appProperties;
private final UserProvisioningService userProvisioningService;
private final AuthenticationService authenticationService;
private final UserRepository userRepository;
@Operation(summary = "Register a new user", description = "Register a new user. Only admins can register users.")
@ApiResponses({
@ApiResponse(responseCode = "204", description = "User registered successfully"),
@ApiResponse(responseCode = "403", description = "Forbidden")
})
@PostMapping("/register")
@PreAuthorize("@securityUtil.isAdmin()")
public ResponseEntity<?> registerUser(@RequestBody @Valid UserCreateRequest userCreateRequest) {
public ResponseEntity<?> registerUser(
@Parameter(description = "User registration request") @RequestBody @Valid UserCreateRequest userCreateRequest) {
userProvisioningService.provisionInternalUser(userCreateRequest);
return ResponseEntity.noContent().build();
}
@Operation(summary = "Login user", description = "Authenticate a user and return JWT tokens.")
@ApiResponse(responseCode = "200", description = "User authenticated successfully")
@PostMapping("/login")
public ResponseEntity<Map<String, String>> loginUser(@RequestBody @Valid UserLoginRequest loginRequest) {
public ResponseEntity<Map<String, String>> loginUser(
@Parameter(description = "User login request") @RequestBody @Valid UserLoginRequest loginRequest) {
return authenticationService.loginUser(loginRequest);
}
@Operation(summary = "Refresh JWT token", description = "Refresh the JWT token using a valid refresh token.")
@ApiResponse(responseCode = "200", description = "Token refreshed successfully")
@PostMapping("/refresh")
public ResponseEntity<Map<String, String>> refreshToken(@Valid @RequestBody RefreshTokenRequest request) {
public ResponseEntity<Map<String, String>> refreshToken(
@Parameter(description = "Refresh token request") @Valid @RequestBody RefreshTokenRequest request) {
return authenticationService.refreshToken(request.getRefreshToken());
}
@Operation(summary = "Remote login", description = "Authenticate a user using remote authentication headers.")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "User authenticated successfully"),
@ApiResponse(responseCode = "403", description = "Remote authentication is disabled")
})
@GetMapping("/remote")
public ResponseEntity<Map<String, String>> loginRemote(@RequestHeader Map<String, String> headers) {
public ResponseEntity<Map<String, String>> loginRemote(
@Parameter(description = "Authentication headers") @RequestHeader Map<String, String> headers) {
if (!appProperties.getRemoteAuth().isEnabled()) {
throw ApiError.REMOTE_AUTH_DISABLED.createException();
}
@@ -57,6 +85,15 @@ public class AuthenticationController {
log.debug("Remote-Auth: retrieved values from headers: name: {}, username: {}, email: {}, groups: {}", name, username, email, groups);
log.debug("Remote-Auth: remote auth settings: {}", appProperties.getRemoteAuth());
if ((username == null || username.isEmpty()) && (email != null && !email.isEmpty())) {
log.debug("Remote-Auth: username is empty, trying to find user by email: {}", email);
Optional<BookLoreUserEntity> user = userRepository.findByEmail(email);
if (user.isPresent()) {
username = user.get().getUsername();
log.debug("Remote-Auth: found user by email, username: {}", username);
}
}
return authenticationService.loginRemote(name, username, email, groups);
}
}
@@ -1,12 +1,17 @@
package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.service.AuthorService;
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 lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Tag(name = "Authors", description = "Endpoints for retrieving authors related to books")
@RequestMapping("/api/v1/authors")
@RestController
@AllArgsConstructor
@@ -14,8 +19,11 @@ public class AuthorController {
private final AuthorService authorService;
@Operation(summary = "Get authors by book ID", description = "Retrieve a list of authors for a specific book.")
@ApiResponse(responseCode = "200", description = "Authors returned successfully")
@GetMapping("/book/{bookId}")
public ResponseEntity<List<String>> getAuthorsByBookId(@PathVariable long bookId) {
public ResponseEntity<List<String>> getAuthorsByBookId(
@Parameter(description = "ID of the book") @PathVariable long bookId) {
return ResponseEntity.ok(authorService.getAuthorsByBookId(bookId));
}
}
@@ -4,14 +4,17 @@ import com.adityachandel.booklore.config.security.service.AuthenticationService;
import com.adityachandel.booklore.model.dto.BookLoreUser;
import com.adityachandel.booklore.model.dto.UploadResponse;
import com.adityachandel.booklore.model.dto.UrlRequest;
import com.adityachandel.booklore.service.BackgroundUploadService;
import com.adityachandel.booklore.service.file.BackgroundUploadService;
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 lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.Map;
@Tag(name = "Background Upload", description = "Endpoints for uploading and managing background images")
@RestController
@RequestMapping("/api/v1/background")
@RequiredArgsConstructor
@@ -20,8 +23,11 @@ public class BackgroundUploadController {
private final BackgroundUploadService backgroundUploadService;
private final AuthenticationService authenticationService;
@Operation(summary = "Upload background image file", description = "Upload a new background image file for the authenticated user.")
@ApiResponse(responseCode = "200", description = "Background image uploaded successfully")
@PostMapping("/upload")
public ResponseEntity<UploadResponse> uploadFile(@RequestParam("file") MultipartFile file) {
public ResponseEntity<UploadResponse> uploadFile(
@Parameter(description = "Background image file") @RequestParam("file") MultipartFile file) {
try {
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
UploadResponse response = backgroundUploadService.uploadBackgroundFile(file, authenticatedUser.getId());
@@ -31,8 +37,11 @@ public class BackgroundUploadController {
}
}
@Operation(summary = "Upload background image from URL", description = "Upload a new background image from a URL for the authenticated user.")
@ApiResponse(responseCode = "200", description = "Background image uploaded successfully")
@PostMapping("/url")
public ResponseEntity<UploadResponse> uploadUrl(@RequestBody UrlRequest request) {
public ResponseEntity<UploadResponse> uploadUrl(
@Parameter(description = "URL request containing the image URL") @RequestBody UrlRequest request) {
try {
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
UploadResponse response = backgroundUploadService.uploadBackgroundFromUrl(request.getUrl(), authenticatedUser.getId());
@@ -42,6 +51,8 @@ public class BackgroundUploadController {
}
}
@Operation(summary = "Reset background to default", description = "Reset the background image to the default for the authenticated user.")
@ApiResponse(responseCode = "200", description = "Background reset to default successfully")
@DeleteMapping
public ResponseEntity<Void> resetToDefault() {
try {
@@ -10,9 +10,14 @@ import com.adityachandel.booklore.model.dto.request.ReadStatusUpdateRequest;
import com.adityachandel.booklore.model.dto.request.ShelvesAssignmentRequest;
import com.adityachandel.booklore.model.dto.response.BookDeletionResponse;
import com.adityachandel.booklore.model.enums.ResetProgressType;
import com.adityachandel.booklore.service.BookService;
import com.adityachandel.booklore.service.book.BookService;
import com.adityachandel.booklore.service.metadata.BookMetadataService;
import com.adityachandel.booklore.service.recommender.BookRecommendationService;
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 io.swagger.v3.oas.annotations.responses.ApiResponses;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
@@ -27,6 +32,7 @@ import java.io.IOException;
import java.util.List;
import java.util.Set;
@Tag(name = "Books", description = "Endpoints for managing books, their metadata, progress, and recommendations")
@RequestMapping("/api/v1/books")
@RestController
@AllArgsConstructor
@@ -36,89 +42,148 @@ public class BookController {
private final BookRecommendationService bookRecommendationService;
private final BookMetadataService bookMetadataService;
@Operation(summary = "Get all books", description = "Retrieve a list of all books. Optionally include descriptions.")
@ApiResponse(responseCode = "200", description = "List of books returned successfully")
@GetMapping
public ResponseEntity<List<Book>> getBooks(@RequestParam(required = false, defaultValue = "false") boolean withDescription) {
public ResponseEntity<List<Book>> getBooks(
@Parameter(description = "Include book descriptions in the response")
@RequestParam(required = false, defaultValue = "false") boolean withDescription) {
return ResponseEntity.ok(bookService.getBookDTOs(withDescription));
}
@Operation(summary = "Get a book by ID", description = "Retrieve details of a specific book by its ID.")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Book details returned successfully"),
@ApiResponse(responseCode = "404", description = "Book not found")
})
@GetMapping("/{bookId}")
@CheckBookAccess(bookIdParam = "bookId")
public ResponseEntity<Book> getBook(@PathVariable long bookId, @RequestParam(required = false, defaultValue = "false") boolean withDescription) {
public ResponseEntity<Book> getBook(
@Parameter(description = "ID of the book to retrieve") @PathVariable long bookId,
@Parameter(description = "Include book description in the response") @RequestParam(required = false, defaultValue = "false") boolean withDescription) {
return ResponseEntity.ok(bookService.getBook(bookId, withDescription));
}
@Operation(summary = "Delete books", description = "Delete one or more books by their IDs. Requires admin or delete permission.")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Books deleted successfully"),
@ApiResponse(responseCode = "403", description = "Forbidden")
})
@PreAuthorize("@securityUtil.canDeleteBook() or @securityUtil.isAdmin()")
@DeleteMapping
public ResponseEntity<BookDeletionResponse> deleteBooks(@RequestParam Set<Long> ids) {
public ResponseEntity<BookDeletionResponse> deleteBooks(
@Parameter(description = "Set of book IDs to delete") @RequestParam Set<Long> ids) {
return bookService.deleteBooks(ids);
}
@Operation(summary = "Get books by IDs", description = "Retrieve multiple books by their IDs. Optionally include descriptions.")
@ApiResponse(responseCode = "200", description = "Books returned successfully")
@GetMapping("/batch")
public ResponseEntity<List<Book>> getBooksByIds(@RequestParam Set<Long> ids, @RequestParam(required = false, defaultValue = "false") boolean withDescription) {
public ResponseEntity<List<Book>> getBooksByIds(
@Parameter(description = "Set of book IDs to retrieve") @RequestParam Set<Long> ids,
@Parameter(description = "Include book descriptions in the response") @RequestParam(required = false, defaultValue = "false") boolean withDescription) {
return ResponseEntity.ok(bookService.getBooksByIds(ids, withDescription));
}
@Operation(summary = "Get ComicInfo metadata", description = "Retrieve ComicInfo metadata for a specific book.")
@ApiResponse(responseCode = "200", description = "ComicInfo metadata returned successfully")
@GetMapping("/{bookId}/cbx/metadata/comicinfo")
public ResponseEntity<?> getComicInfoMetadata(@PathVariable long bookId) {
public ResponseEntity<?> getComicInfoMetadata(
@Parameter(description = "ID of the book") @PathVariable long bookId) {
return ResponseEntity.ok(bookMetadataService.getComicInfoMetadata(bookId));
}
@Operation(summary = "Get book content", description = "Retrieve the binary content of a book for reading.")
@ApiResponse(responseCode = "200", description = "Book content returned successfully")
@GetMapping("/{bookId}/content")
@CheckBookAccess(bookIdParam = "bookId")
public ResponseEntity<ByteArrayResource> getBookContent(@PathVariable long bookId) throws IOException {
public ResponseEntity<ByteArrayResource> getBookContent(
@Parameter(description = "ID of the book") @PathVariable long bookId) throws IOException {
return bookService.getBookContent(bookId);
}
@Operation(summary = "Download book", description = "Download the book file. Requires download permission or admin.")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Book downloaded successfully"),
@ApiResponse(responseCode = "403", description = "Forbidden")
})
@GetMapping("/{bookId}/download")
@PreAuthorize("@securityUtil.canDownload() or @securityUtil.isAdmin()")
@CheckBookAccess(bookIdParam = "bookId")
public ResponseEntity<Resource> downloadBook(@PathVariable("bookId") Long bookId) {
public ResponseEntity<Resource> downloadBook(
@Parameter(description = "ID of the book to download") @PathVariable("bookId") Long bookId) {
return bookService.downloadBook(bookId);
}
@Operation(summary = "Get viewer settings", description = "Retrieve viewer settings for a specific book.")
@ApiResponse(responseCode = "200", description = "Viewer settings returned successfully")
@GetMapping("/{bookId}/viewer-setting")
@CheckBookAccess(bookIdParam = "bookId")
public ResponseEntity<BookViewerSettings> getBookViewerSettings(@PathVariable long bookId) {
public ResponseEntity<BookViewerSettings> getBookViewerSettings(
@Parameter(description = "ID of the book") @PathVariable long bookId) {
return ResponseEntity.ok(bookService.getBookViewerSetting(bookId));
}
@Operation(summary = "Update viewer settings", description = "Update viewer settings for a specific book.")
@ApiResponse(responseCode = "204", description = "Viewer settings updated successfully")
@PutMapping("/{bookId}/viewer-setting")
@CheckBookAccess(bookIdParam = "bookId")
public ResponseEntity<Void> updateBookViewerSettings(@RequestBody BookViewerSettings bookViewerSettings, @PathVariable long bookId) {
public ResponseEntity<Void> updateBookViewerSettings(
@Parameter(description = "Viewer settings to update") @RequestBody BookViewerSettings bookViewerSettings,
@Parameter(description = "ID of the book") @PathVariable long bookId) {
bookService.updateBookViewerSetting(bookId, bookViewerSettings);
return ResponseEntity.noContent().build();
}
@Operation(summary = "Assign books to shelves", description = "Assign or unassign books to/from shelves.")
@ApiResponse(responseCode = "200", description = "Books assigned/unassigned to shelves successfully")
@PostMapping("/shelves")
public ResponseEntity<List<Book>> addBookToShelf(@RequestBody @Valid ShelvesAssignmentRequest request) {
public ResponseEntity<List<Book>> addBookToShelf(
@Parameter(description = "Shelves assignment request") @RequestBody @Valid ShelvesAssignmentRequest request) {
return ResponseEntity.ok(bookService.assignShelvesToBooks(request.getBookIds(), request.getShelvesToAssign(), request.getShelvesToUnassign()));
}
@Operation(summary = "Update read progress", description = "Update the read progress for a book.")
@ApiResponse(responseCode = "204", description = "Read progress updated successfully")
@PostMapping("/progress")
public ResponseEntity<Void> addBookToProgress(@RequestBody @Valid ReadProgressRequest request) {
public ResponseEntity<Void> addBookToProgress(
@Parameter(description = "Read progress request") @RequestBody @Valid ReadProgressRequest request) {
bookService.updateReadProgress(request);
return ResponseEntity.noContent().build();
}
@Operation(summary = "Get book recommendations", description = "Get recommended books based on a specific book.")
@ApiResponse(responseCode = "200", description = "Recommendations returned successfully")
@GetMapping("/{id}/recommendations")
@CheckBookAccess(bookIdParam = "id")
public ResponseEntity<List<BookRecommendation>> getRecommendations(@PathVariable Long id, @RequestParam(defaultValue = "25") @Max(25) @Min(1) int limit) {
public ResponseEntity<List<BookRecommendation>> getRecommendations(
@Parameter(description = "ID of the book for recommendations") @PathVariable Long id,
@Parameter(description = "Maximum number of recommendations to return (max 25)") @RequestParam(defaultValue = "25") @Max(25) @Min(1) int limit) {
return ResponseEntity.ok(bookRecommendationService.getRecommendations(id, limit));
}
@Operation(summary = "Update read status", description = "Update the read status for one or more books.")
@ApiResponse(responseCode = "200", description = "Read status updated successfully")
@PutMapping("/read-status")
public ResponseEntity<List<Book>> updateReadStatus(@RequestBody @Valid ReadStatusUpdateRequest request) {
public ResponseEntity<List<Book>> updateReadStatus(
@Parameter(description = "Read status update request") @RequestBody @Valid ReadStatusUpdateRequest request) {
List<Book> updatedBooks = bookService.updateReadStatus(request.ids(), request.status());
return ResponseEntity.ok(updatedBooks);
}
@Operation(summary = "Reset reading progress", description = "Reset the reading progress for one or more books.")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Progress reset successfully"),
@ApiResponse(responseCode = "400", description = "No book IDs provided")
})
@PostMapping("/reset-progress")
public ResponseEntity<List<Book>> resetProgress(@RequestBody List<Long> bookIds, @RequestParam ResetProgressType type) {
public ResponseEntity<List<Book>> resetProgress(
@Parameter(description = "List of book IDs to reset progress for") @RequestBody List<Long> bookIds,
@Parameter(description = "Type of progress reset") @RequestParam ResetProgressType type) {
if (bookIds == null || bookIds.isEmpty()) {
throw ApiError.GENERIC_BAD_REQUEST.createException("No book IDs provided");
}
List<Book> updatedBooks = bookService.resetProgress(bookIds, type);
return ResponseEntity.ok(updatedBooks);
}
}
}
@@ -1,14 +1,17 @@
package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.config.security.service.AuthenticationService;
import com.adityachandel.booklore.service.BookService;
import com.adityachandel.booklore.service.book.BookService;
import com.adityachandel.booklore.service.bookdrop.BookDropService;
import com.adityachandel.booklore.service.metadata.BookMetadataService;
import com.adityachandel.booklore.service.reader.CbxReaderService;
import com.adityachandel.booklore.service.reader.PdfReaderService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.springframework.core.io.Resource;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
@@ -18,7 +21,9 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
@Tag(name = "Book Media", description = "Endpoints for retrieving book media such as covers, thumbnails, and pages")
@AllArgsConstructor
@RestController
@RequestMapping("/api/v1/media")
@@ -29,39 +34,64 @@ public class BookMediaController {
private final CbxReaderService cbxReaderService;
private final BookDropService bookDropService;
@Operation(summary = "Get book thumbnail", description = "Retrieve the thumbnail image for a specific book.")
@ApiResponse(responseCode = "200", description = "Book thumbnail returned successfully")
@GetMapping("/book/{bookId}/thumbnail")
public ResponseEntity<Resource> getBookThumbnail(@PathVariable long bookId) {
public ResponseEntity<Resource> getBookThumbnail(
@Parameter(description = "ID of the book") @PathVariable long bookId) {
return ResponseEntity.ok(bookService.getBookThumbnail(bookId));
}
@Operation(summary = "Get book cover", description = "Retrieve the cover image for a specific book.")
@ApiResponse(responseCode = "200", description = "Book cover returned successfully")
@GetMapping("/book/{bookId}/cover")
public ResponseEntity<Resource> getBookCover(@PathVariable long bookId) {
public ResponseEntity<Resource> getBookCover(
@Parameter(description = "ID of the book") @PathVariable long bookId) {
return ResponseEntity.ok(bookService.getBookCover(bookId));
}
@Operation(summary = "Get PDF page as image", description = "Retrieve a specific page from a PDF book as an image.")
@ApiResponse(responseCode = "200", description = "PDF page image returned successfully")
@GetMapping("/book/{bookId}/pdf/pages/{pageNumber}")
public void getPdfPage(@PathVariable Long bookId, @PathVariable int pageNumber, HttpServletResponse response) throws IOException {
public void getPdfPage(
@Parameter(description = "ID of the book") @PathVariable Long bookId,
@Parameter(description = "Page number to retrieve") @PathVariable int pageNumber,
HttpServletResponse response) throws IOException {
response.setContentType(MediaType.IMAGE_JPEG_VALUE);
pdfReaderService.streamPageImage(bookId, pageNumber, response.getOutputStream());
}
@Operation(summary = "Get CBX page as image", description = "Retrieve a specific page from a CBX book as an image.")
@ApiResponse(responseCode = "200", description = "CBX page image returned successfully")
@GetMapping("/book/{bookId}/cbx/pages/{pageNumber}")
public void getCbxPage(@PathVariable Long bookId, @PathVariable int pageNumber, HttpServletResponse response) throws IOException {
public void getCbxPage(
@Parameter(description = "ID of the book") @PathVariable Long bookId,
@Parameter(description = "Page number to retrieve") @PathVariable int pageNumber,
HttpServletResponse response) throws IOException {
response.setContentType(MediaType.IMAGE_JPEG_VALUE);
cbxReaderService.streamPageImage(bookId, pageNumber, response.getOutputStream());
}
@Operation(summary = "Get bookdrop cover", description = "Retrieve the cover image for a specific bookdrop file.")
@ApiResponse(responseCode = "200", description = "Bookdrop cover returned successfully")
@GetMapping("/bookdrop/{bookdropId}/cover")
public ResponseEntity<Resource> getBookdropCover(@PathVariable long bookdropId) {
public ResponseEntity<Resource> getBookdropCover(
@Parameter(description = "ID of the bookdrop file") @PathVariable long bookdropId) {
Resource file = bookDropService.getBookdropCover(bookdropId);
String contentDisposition = ContentDisposition.builder("inline")
.filename("cover.jpg", StandardCharsets.UTF_8)
.build()
.toString();
return (file != null)
? ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=cover.jpg")
.header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition)
.contentType(MediaType.IMAGE_JPEG)
.body(file)
: ResponseEntity.noContent().build();
}
@Operation(summary = "Get background image", description = "Retrieve the current background image for the authenticated user.")
@ApiResponse(responseCode = "200", description = "Background image returned successfully")
@GetMapping("/background")
public ResponseEntity<Resource> getBackgroundImage() {
try {
@@ -75,8 +105,13 @@ public class BookMediaController {
? MediaType.IMAGE_PNG
: MediaType.IMAGE_JPEG;
String contentDisposition = ContentDisposition.builder("inline")
.filename(filename, StandardCharsets.UTF_8)
.build()
.toString();
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=" + filename)
.header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition)
.contentType(mediaType)
.body(file);
} catch (Exception e) {
@@ -2,7 +2,11 @@ package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.model.dto.BookNote;
import com.adityachandel.booklore.model.dto.CreateBookNoteRequest;
import com.adityachandel.booklore.service.BookNoteService;
import com.adityachandel.booklore.service.book.BookNoteService;
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;
@@ -13,23 +17,32 @@ import java.util.List;
@RestController
@RequestMapping("/api/v1/book-notes")
@AllArgsConstructor
@Tag(name = "Book Notes", description = "Endpoints for managing notes attached to books")
public class BookNoteController {
private final BookNoteService bookNoteService;
@Operation(summary = "Get notes for a book", description = "Retrieve all notes for a specific book.")
@ApiResponse(responseCode = "200", description = "Notes returned successfully")
@GetMapping("/book/{bookId}")
public List<BookNote> getNotesForBook(@PathVariable Long bookId) {
public List<BookNote> getNotesForBook(
@Parameter(description = "ID of the book") @PathVariable Long bookId) {
return bookNoteService.getNotesForBook(bookId);
}
@Operation(summary = "Create or update a note", description = "Create a new note or update an existing note for a book.")
@ApiResponse(responseCode = "200", description = "Note created/updated successfully")
@PostMapping
public BookNote createNote(@Valid @RequestBody CreateBookNoteRequest request) {
public BookNote createNote(
@Parameter(description = "Note creation request") @Valid @RequestBody CreateBookNoteRequest request) {
return bookNoteService.createOrUpdateNote(request);
}
@Operation(summary = "Delete a note", description = "Delete a specific note by its ID.")
@ApiResponse(responseCode = "204", description = "Note deleted successfully")
@DeleteMapping("/{noteId}")
public ResponseEntity<Void> deleteNote(@PathVariable Long noteId) {
public ResponseEntity<Void> deleteNote(
@Parameter(description = "ID of the note to delete") @PathVariable Long noteId) {
bookNoteService.deleteNote(noteId);
return ResponseEntity.noContent().build();
}
@@ -1,25 +1,36 @@
package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.model.dto.BookReview;
import com.adityachandel.booklore.service.BookReviewService;
import com.adityachandel.booklore.service.book.BookReviewService;
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.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.constraints.Positive;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/v1/reviews")
@AllArgsConstructor
@Tag(name = "Book Reviews", description = "Endpoints for managing book reviews")
public class BookReviewController {
private final BookReviewService bookReviewService;
@Operation(summary = "List reviews for a book", description = "Retrieve all reviews for a specific book.")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Reviews returned successfully"),
@ApiResponse(responseCode = "204", description = "No reviews found")
})
@GetMapping("/book/{bookId}")
public ResponseEntity<List<BookReview>> listByBook(@PathVariable @Positive(message = "Book ID must be positive") Long bookId) {
public ResponseEntity<List<BookReview>> listByBook(
@Parameter(description = "ID of the book") @PathVariable @Positive(message = "Book ID must be positive") Long bookId) {
List<BookReview> reviews = bookReviewService.getByBookId(bookId);
if (reviews.isEmpty()) {
return ResponseEntity.noContent().build();
@@ -27,22 +38,31 @@ public class BookReviewController {
return ResponseEntity.ok(reviews);
}
@Operation(summary = "Refresh reviews for a book", description = "Refresh and retrieve reviews for a specific book. Requires metadata edit permission or admin.")
@ApiResponse(responseCode = "200", description = "Reviews refreshed successfully")
@PostMapping("/book/{bookId}/refresh")
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
public List<BookReview> refreshReviews(@PathVariable Long bookId) {
public List<BookReview> refreshReviews(
@Parameter(description = "ID of the book") @PathVariable Long bookId) {
return bookReviewService.refreshReviews(bookId);
}
@Operation(summary = "Delete a review", description = "Delete a specific review by its ID. Requires metadata edit permission or admin.")
@ApiResponse(responseCode = "204", description = "Review deleted successfully")
@DeleteMapping("/{id}")
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
public ResponseEntity<Void> delete(@PathVariable Long id) {
public ResponseEntity<Void> delete(
@Parameter(description = "ID of the review to delete") @PathVariable Long id) {
bookReviewService.delete(id);
return ResponseEntity.noContent().build();
}
@Operation(summary = "Delete all reviews for a book", description = "Delete all reviews for a specific book. Requires metadata edit permission or admin.")
@ApiResponse(responseCode = "204", description = "All reviews deleted successfully")
@DeleteMapping("/book/{bookId}")
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
public ResponseEntity<Void> deleteAllByBookId(@PathVariable Long bookId) {
public ResponseEntity<Void> deleteAllByBookId(
@Parameter(description = "ID of the book") @PathVariable Long bookId) {
bookReviewService.deleteAllByBookId(bookId);
return ResponseEntity.noContent().build();
}
@@ -8,12 +8,17 @@ import com.adityachandel.booklore.model.dto.response.BookdropFinalizeResult;
import com.adityachandel.booklore.service.bookdrop.BookDropService;
import com.adityachandel.booklore.service.bookdrop.BookdropMonitoringService;
import com.adityachandel.booklore.service.monitoring.MonitoringService;
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 lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@Tag(name = "Bookdrop", description = "Endpoints for managing bookdrop files and imports")
@AllArgsConstructor
@RestController
@RequestMapping("/api/v1/bookdrop")
@@ -22,28 +27,42 @@ public class BookdropFileController {
private final BookDropService bookDropService;
private final BookdropMonitoringService monitoringService;
@Operation(summary = "Get bookdrop notification summary", description = "Retrieve a summary of bookdrop file notifications.")
@ApiResponse(responseCode = "200", description = "Notification summary returned successfully")
@GetMapping("/notification")
public BookdropFileNotification getSummary() {
return bookDropService.getFileNotificationSummary();
}
@Operation(summary = "Get bookdrop files by status", description = "Retrieve a paginated list of bookdrop files filtered by status.")
@ApiResponse(responseCode = "200", description = "Bookdrop files returned successfully")
@GetMapping("/files")
public Page<BookdropFile> getFilesByStatus(@RequestParam(required = false) String status, Pageable pageable) {
public Page<BookdropFile> getFilesByStatus(
@Parameter(description = "Status to filter files by") @RequestParam(required = false) String status,
Pageable pageable) {
return bookDropService.getFilesByStatus(status, pageable);
}
@Operation(summary = "Discard selected bookdrop files", description = "Discard selected bookdrop files based on selection criteria.")
@ApiResponse(responseCode = "200", description = "Files discarded successfully")
@PostMapping("/files/discard")
public ResponseEntity<Void> discardSelectedFiles(@RequestBody BookdropSelectionRequest request) {
public ResponseEntity<Void> discardSelectedFiles(
@Parameter(description = "Selection request for files to discard") @RequestBody BookdropSelectionRequest request) {
bookDropService.discardSelectedFiles(request.isSelectAll(), request.getExcludedIds(), request.getSelectedIds());
return ResponseEntity.ok().build();
}
@Operation(summary = "Finalize bookdrop import", description = "Finalize the import of selected bookdrop files.")
@ApiResponse(responseCode = "200", description = "Import finalized successfully")
@PostMapping("/imports/finalize")
public ResponseEntity<BookdropFinalizeResult> finalizeImport(@RequestBody BookdropFinalizeRequest request) {
public ResponseEntity<BookdropFinalizeResult> finalizeImport(
@Parameter(description = "Finalize import request") @RequestBody BookdropFinalizeRequest request) {
BookdropFinalizeResult result = bookDropService.finalizeImport(request);
return ResponseEntity.ok(result);
}
@Operation(summary = "Rescan bookdrop folder", description = "Trigger a rescan of the bookdrop folder for new files.")
@ApiResponse(responseCode = "200", description = "Bookdrop folder rescanned successfully")
@PostMapping("/rescan")
public ResponseEntity<Void> rescanBookdrop() {
monitoringService.rescanBookdropFolder();
@@ -1,6 +1,10 @@
package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.service.reader.CbxReaderService;
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 lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@@ -12,12 +16,16 @@ import java.util.List;
@RestController
@RequestMapping("/api/v1/cbx")
@RequiredArgsConstructor
@Tag(name = "CBX Reader", description = "Endpoints for reading CBX format books")
public class CbxReaderController {
private final CbxReaderService cbxReaderService;
@Operation(summary = "List pages in a CBX book", description = "Retrieve a list of available page numbers for a CBX book.")
@ApiResponse(responseCode = "200", description = "Page numbers returned successfully")
@GetMapping("/{bookId}/pages")
public List<Integer> listPages(@PathVariable Long bookId) {
public List<Integer> listPages(
@Parameter(description = "ID of the book") @PathVariable Long bookId) {
return cbxReaderService.getAvailablePages(bookId);
}
}
@@ -3,6 +3,10 @@ package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.model.dto.EmailProviderV2;
import com.adityachandel.booklore.model.dto.request.CreateEmailProviderRequest;
import com.adityachandel.booklore.service.email.EmailProviderV2Service;
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 lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
@@ -13,44 +17,63 @@ import java.util.List;
@AllArgsConstructor
@RestController
@RequestMapping("/api/v2/email/providers")
@Tag(name = "Email Providers", description = "Endpoints for managing email providers for book delivery")
public class EmailProviderV2Controller {
private final EmailProviderV2Service service;
@Operation(summary = "Get all email providers", description = "Retrieve a list of all configured email providers.")
@ApiResponse(responseCode = "200", description = "Email providers returned successfully")
@PreAuthorize("@securityUtil.isAdmin() or @securityUtil.canEmailBook()")
@GetMapping
public ResponseEntity<List<EmailProviderV2>> getEmailProviders() {
return ResponseEntity.ok(service.getEmailProviders());
}
@Operation(summary = "Get an email provider by ID", description = "Retrieve details of a specific email provider.")
@ApiResponse(responseCode = "200", description = "Email provider returned successfully")
@PreAuthorize("@securityUtil.isAdmin() or @securityUtil.canEmailBook()")
@GetMapping("/{id}")
public ResponseEntity<EmailProviderV2> getEmailProvider(@PathVariable Long id) {
public ResponseEntity<EmailProviderV2> getEmailProvider(
@Parameter(description = "ID of the email provider") @PathVariable Long id) {
return ResponseEntity.ok(service.getEmailProvider(id));
}
@Operation(summary = "Create an email provider", description = "Create a new email provider configuration.")
@ApiResponse(responseCode = "200", description = "Email provider created successfully")
@PreAuthorize("@securityUtil.isAdmin() or @securityUtil.canEmailBook()")
@PostMapping
public ResponseEntity<EmailProviderV2> createEmailProvider(@RequestBody CreateEmailProviderRequest createEmailProviderRequest) {
public ResponseEntity<EmailProviderV2> createEmailProvider(
@Parameter(description = "Email provider creation request") @RequestBody CreateEmailProviderRequest createEmailProviderRequest) {
return ResponseEntity.ok(service.createEmailProvider(createEmailProviderRequest));
}
@Operation(summary = "Update an email provider", description = "Update an existing email provider configuration.")
@ApiResponse(responseCode = "200", description = "Email provider updated successfully")
@PreAuthorize("@securityUtil.isAdmin() or @securityUtil.canEmailBook()")
@PutMapping("/{id}")
public ResponseEntity<EmailProviderV2> updateEmailProvider(@PathVariable Long id, @RequestBody CreateEmailProviderRequest updateRequest) {
public ResponseEntity<EmailProviderV2> updateEmailProvider(
@Parameter(description = "ID of the email provider") @PathVariable Long id,
@Parameter(description = "Email provider update request") @RequestBody CreateEmailProviderRequest updateRequest) {
return ResponseEntity.ok(service.updateEmailProvider(id, updateRequest));
}
@Operation(summary = "Set default email provider", description = "Set a specific email provider as the default.")
@ApiResponse(responseCode = "204", description = "Default email provider set successfully")
@PreAuthorize("@securityUtil.isAdmin() or @securityUtil.canEmailBook()")
@PatchMapping("/{id}/set-default")
public ResponseEntity<Void> setDefaultEmailProvider(@PathVariable Long id) {
public ResponseEntity<Void> setDefaultEmailProvider(
@Parameter(description = "ID of the email provider") @PathVariable Long id) {
service.setDefaultEmailProvider(id);
return ResponseEntity.noContent().build();
}
@Operation(summary = "Delete an email provider", description = "Delete a specific email provider configuration.")
@ApiResponse(responseCode = "204", description = "Email provider deleted successfully")
@PreAuthorize("@securityUtil.isAdmin() or @securityUtil.canEmailBook()")
@DeleteMapping("/{id}")
public ResponseEntity<?> deleteEmailProvider(@PathVariable Long id) {
public ResponseEntity<?> deleteEmailProvider(
@Parameter(description = "ID of the email provider") @PathVariable Long id) {
service.deleteEmailProvider(id);
return ResponseEntity.noContent().build();
}
@@ -3,6 +3,10 @@ package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.model.dto.EmailRecipientV2;
import com.adityachandel.booklore.model.dto.request.CreateEmailRecipientRequest;
import com.adityachandel.booklore.service.email.EmailRecipientV2Service;
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 lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
@@ -13,44 +17,63 @@ import java.util.List;
@AllArgsConstructor
@RestController
@RequestMapping("/api/v2/email/recipients")
@Tag(name = "Email Recipients", description = "Endpoints for managing email recipients for book delivery")
public class EmailRecipientV2Controller {
private final EmailRecipientV2Service service;
@Operation(summary = "Get all email recipients", description = "Retrieve a list of all configured email recipients.")
@ApiResponse(responseCode = "200", description = "Email recipients returned successfully")
@PreAuthorize("@securityUtil.isAdmin() or @securityUtil.canEmailBook()")
@GetMapping
public ResponseEntity<List<EmailRecipientV2>> getEmailRecipients() {
return ResponseEntity.ok(service.getEmailRecipients());
}
@Operation(summary = "Get an email recipient by ID", description = "Retrieve details of a specific email recipient.")
@ApiResponse(responseCode = "200", description = "Email recipient returned successfully")
@PreAuthorize("@securityUtil.isAdmin() or @securityUtil.canEmailBook()")
@GetMapping("/{id}")
public ResponseEntity<EmailRecipientV2> getEmailRecipient(@PathVariable Long id) {
public ResponseEntity<EmailRecipientV2> getEmailRecipient(
@Parameter(description = "ID of the email recipient") @PathVariable Long id) {
return ResponseEntity.ok(service.getEmailRecipient(id));
}
@Operation(summary = "Create an email recipient", description = "Create a new email recipient configuration.")
@ApiResponse(responseCode = "200", description = "Email recipient created successfully")
@PreAuthorize("@securityUtil.isAdmin() or @securityUtil.canEmailBook()")
@PostMapping
public ResponseEntity<EmailRecipientV2> createEmailRecipient(@RequestBody CreateEmailRecipientRequest createEmailRecipientRequest) {
public ResponseEntity<EmailRecipientV2> createEmailRecipient(
@Parameter(description = "Email recipient creation request") @RequestBody CreateEmailRecipientRequest createEmailRecipientRequest) {
return ResponseEntity.ok(service.createEmailRecipient(createEmailRecipientRequest));
}
@Operation(summary = "Update an email recipient", description = "Update an existing email recipient configuration.")
@ApiResponse(responseCode = "200", description = "Email recipient updated successfully")
@PreAuthorize("@securityUtil.isAdmin() or @securityUtil.canEmailBook()")
@PutMapping("/{id}")
public ResponseEntity<EmailRecipientV2> updateEmailRecipient(@PathVariable Long id, @RequestBody CreateEmailRecipientRequest updateRequest) {
public ResponseEntity<EmailRecipientV2> updateEmailRecipient(
@Parameter(description = "ID of the email recipient") @PathVariable Long id,
@Parameter(description = "Email recipient update request") @RequestBody CreateEmailRecipientRequest updateRequest) {
return ResponseEntity.ok(service.updateEmailRecipient(id, updateRequest));
}
@Operation(summary = "Set default email recipient", description = "Set a specific email recipient as the default.")
@ApiResponse(responseCode = "204", description = "Default email recipient set successfully")
@PreAuthorize("@securityUtil.isAdmin() or @securityUtil.canEmailBook()")
@PatchMapping("/{id}/set-default")
public ResponseEntity<Void> setDefaultEmailRecipient(@PathVariable Long id) {
public ResponseEntity<Void> setDefaultEmailRecipient(
@Parameter(description = "ID of the email recipient") @PathVariable Long id) {
service.setDefaultRecipient(id);
return ResponseEntity.noContent().build();
}
@Operation(summary = "Delete an email recipient", description = "Delete a specific email recipient configuration.")
@ApiResponse(responseCode = "204", description = "Email recipient deleted successfully")
@PreAuthorize("@securityUtil.isAdmin() or @securityUtil.canEmailBook()")
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteEmailRecipient(@PathVariable Long id) {
public ResponseEntity<Void> deleteEmailRecipient(
@Parameter(description = "ID of the email recipient") @PathVariable Long id) {
service.deleteEmailRecipient(id);
return ResponseEntity.noContent().build();
}
@@ -2,6 +2,10 @@ package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.model.dto.request.FileMoveRequest;
import com.adityachandel.booklore.service.file.FileMoveService;
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 lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
@@ -12,13 +16,17 @@ import org.springframework.web.bind.annotation.RestController;
@AllArgsConstructor
@RestController
@RequestMapping("/api/v1/files")
@Tag(name = "File Move", description = "Endpoints for moving files within the library")
public class FileMoveController {
private final FileMoveService fileMoveService;
@Operation(summary = "Move files", description = "Bulk move files to a different location within the library.")
@ApiResponse(responseCode = "200", description = "Files moved successfully")
@PostMapping("/move")
public ResponseEntity<?> moveFiles(@RequestBody FileMoveRequest request) {
fileMoveService.moveFiles(request);
public ResponseEntity<?> moveFiles(
@Parameter(description = "File move request") @RequestBody FileMoveRequest request) {
fileMoveService.bulkMoveFiles(request);
return ResponseEntity.ok().build();
}
}
@@ -11,18 +11,29 @@ import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.Parameter;
import java.io.IOException;
@AllArgsConstructor
@RestController
@RequestMapping("/api/v1/files")
@Tag(name = "File Upload", description = "Endpoints for uploading files and books")
public class FileUploadController {
private final FileUploadService fileUploadService;
@Operation(summary = "Upload a file", description = "Upload a file to a specific library and path. Requires upload permission or admin.")
@ApiResponse(responseCode = "204", description = "File uploaded successfully")
@PreAuthorize("@securityUtil.isAdmin() or @securityUtil.canUpload()")
@PostMapping(value = "/upload", consumes = "multipart/form-data")
public ResponseEntity<?> uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("libraryId") long libraryId, @RequestParam("pathId") long pathId) throws IOException {
public ResponseEntity<?> uploadFile(
@Parameter(description = "File to upload") @RequestParam("file") MultipartFile file,
@Parameter(description = "Library ID") @RequestParam("libraryId") long libraryId,
@Parameter(description = "Path ID") @RequestParam("pathId") long pathId) throws IOException {
if (file.isEmpty()) {
throw new IllegalArgumentException("Uploaded file is missing.");
}
@@ -30,9 +41,12 @@ public class FileUploadController {
return ResponseEntity.noContent().build();
}
@Operation(summary = "Upload a book via BookDrop", description = "Upload a book using BookDrop. Requires upload permission or admin.")
@ApiResponse(responseCode = "200", description = "Book uploaded successfully")
@PreAuthorize("@securityUtil.isAdmin() or @securityUtil.canUpload()")
@PostMapping(value = "/upload/bookdrop", consumes = "multipart/form-data")
public ResponseEntity<Book> uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
public ResponseEntity<Book> uploadFile(
@Parameter(description = "Book file to upload") @RequestParam("file") MultipartFile file) throws IOException {
if (file.isEmpty()) {
throw new IllegalArgumentException("Uploaded file is missing.");
}
@@ -7,9 +7,15 @@ import com.adityachandel.booklore.model.dto.kobo.KoboReadingStateWrapper;
import com.adityachandel.booklore.model.dto.kobo.KoboResources;
import com.adityachandel.booklore.model.dto.kobo.KoboTestResponse;
import com.adityachandel.booklore.service.*;
import com.adityachandel.booklore.service.book.BookDownloadService;
import com.adityachandel.booklore.service.book.BookService;
import com.adityachandel.booklore.service.kobo.*;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
@@ -22,8 +28,6 @@ import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.List;
import java.util.Set;
@@ -31,6 +35,7 @@ import java.util.Set;
@RequiredArgsConstructor
@RestController
@RequestMapping(value = "/api/kobo/{token}")
@Tag(name = "Kobo Integration", description = "Endpoints for Kobo device and library integration")
public class KoboController {
private String token;
@@ -50,21 +55,27 @@ public class KoboController {
this.token = token;
}
@Operation(summary = "Initialize Kobo resources", description = "Initialize Kobo resources for the device.")
@ApiResponse(responseCode = "200", description = "Initialization successful")
@GetMapping("/v1/initialization")
public ResponseEntity<KoboResources> initialization() throws JsonProcessingException {
return koboInitializationService.initialize(token);
}
@Operation(summary = "Sync Kobo library", description = "Sync the user's Kobo library.")
@ApiResponse(responseCode = "200", description = "Library synced successfully")
@GetMapping("/v1/library/sync")
public ResponseEntity<?> syncLibrary(@AuthenticationPrincipal BookLoreUser user) {
return koboLibrarySyncService.syncLibrary(user, token);
}
@Operation(summary = "Get book thumbnail", description = "Retrieve the thumbnail image for a book.")
@ApiResponse(responseCode = "200", description = "Thumbnail returned successfully")
@GetMapping("/v1/books/{imageId}/thumbnail/{width}/{height}/false/image.jpg")
public ResponseEntity<Resource> getThumbnail(
@PathVariable String imageId,
@PathVariable int width,
@PathVariable int height) {
@Parameter(description = "Image ID") @PathVariable String imageId,
@Parameter(description = "Width of the thumbnail") @PathVariable int width,
@Parameter(description = "Height of the thumbnail") @PathVariable int height) {
if (StringUtils.isNumeric(imageId)) {
return koboThumbnailService.getThumbnail(Long.valueOf(imageId));
@@ -74,13 +85,15 @@ public class KoboController {
}
}
@Operation(summary = "Get greyscale book thumbnail", description = "Retrieve a greyscale thumbnail image for a book.")
@ApiResponse(responseCode = "200", description = "Greyscale thumbnail returned successfully")
@GetMapping("/v1/books/{bookId}/thumbnail/{width}/{height}/{quality}/{isGreyscale}/image.jpg")
public ResponseEntity<Resource> getGreyThumbnail(
@PathVariable String bookId,
@PathVariable int width,
@PathVariable int height,
@PathVariable int quality,
@PathVariable boolean isGreyscale) {
@Parameter(description = "Book ID") @PathVariable String bookId,
@Parameter(description = "Width of the thumbnail") @PathVariable int width,
@Parameter(description = "Height of the thumbnail") @PathVariable int height,
@Parameter(description = "Quality of the thumbnail") @PathVariable int quality,
@Parameter(description = "Is greyscale") @PathVariable boolean isGreyscale) {
if (StringUtils.isNumeric(bookId)) {
return koboThumbnailService.getThumbnail(Long.valueOf(bookId));
@@ -90,13 +103,19 @@ public class KoboController {
}
}
@Operation(summary = "Authenticate Kobo device", description = "Authenticate a Kobo device.")
@ApiResponse(responseCode = "200", description = "Device authenticated successfully")
@PostMapping("/v1/auth/device")
public ResponseEntity<KoboAuthentication> authenticateDevice(@RequestBody JsonNode body) {
public ResponseEntity<KoboAuthentication> authenticateDevice(
@Parameter(description = "Authentication request body") @RequestBody JsonNode body) {
return koboDeviceAuthService.authenticateDevice(body);
}
@Operation(summary = "Get book metadata", description = "Retrieve metadata for a book in the Kobo library.")
@ApiResponse(responseCode = "200", description = "Metadata returned successfully")
@GetMapping("/v1/library/{bookId}/metadata")
public ResponseEntity<?> getBookMetadata(@PathVariable String bookId) {
public ResponseEntity<?> getBookMetadata(
@Parameter(description = "Book ID") @PathVariable String bookId) {
if (StringUtils.isNumeric(bookId)) {
return ResponseEntity.ok(List.of(koboEntitlementService.getMetadataForBook(Long.parseLong(bookId), token)));
} else {
@@ -104,8 +123,11 @@ public class KoboController {
}
}
@Operation(summary = "Get reading state", description = "Retrieve the reading state for a book.")
@ApiResponse(responseCode = "200", description = "Reading state returned successfully")
@GetMapping("/v1/library/{bookId}/state")
public ResponseEntity<?> getState(@PathVariable String bookId) {
public ResponseEntity<?> getState(
@Parameter(description = "Book ID") @PathVariable String bookId) {
if (StringUtils.isNumeric(bookId)) {
return ResponseEntity.ok(koboReadingStateService.getReadingState(bookId));
} else {
@@ -113,8 +135,12 @@ public class KoboController {
}
}
@Operation(summary = "Update reading state", description = "Update the reading state for a book.")
@ApiResponse(responseCode = "200", description = "Reading state updated successfully")
@PutMapping("/v1/library/{bookId}/state")
public ResponseEntity<?> updateState(@PathVariable String bookId, @RequestBody KoboReadingStateWrapper body) {
public ResponseEntity<?> updateState(
@Parameter(description = "Book ID") @PathVariable String bookId,
@Parameter(description = "Reading state update body") @RequestBody KoboReadingStateWrapper body) {
if (StringUtils.isNumeric(bookId)) {
return ResponseEntity.ok(koboReadingStateService.saveReadingState(body.getReadingStates()));
} else {
@@ -122,16 +148,22 @@ public class KoboController {
}
}
@Operation(summary = "Get Kobo test analytics", description = "Get test analytics for Kobo.")
@ApiResponse(responseCode = "200", description = "Test analytics returned successfully")
@PostMapping("/v1/analytics/gettests")
public ResponseEntity<?> getTests(@RequestBody Object body) {
public ResponseEntity<?> getTests(
@Parameter(description = "Test analytics request body") @RequestBody Object body) {
return ResponseEntity.ok(KoboTestResponse.builder()
.result("Success")
.testKey(RandomStringUtils.secure().nextAlphanumeric(24))
.build());
}
@Operation(summary = "Download Kobo book", description = "Download a book from the Kobo library.")
@ApiResponse(responseCode = "200", description = "Book downloaded successfully")
@GetMapping("/v1/books/{bookId}/download")
public void downloadBook(@PathVariable String bookId, HttpServletResponse response) throws IOException {
public void downloadBook(
@Parameter(description = "Book ID") @PathVariable String bookId, HttpServletResponse response) throws IOException {
if (StringUtils.isNumeric(bookId)) {
bookDownloadService.downloadKoboBook(Long.parseLong(bookId), response);
} else {
@@ -139,8 +171,11 @@ public class KoboController {
}
}
@Operation(summary = "Delete book from Kobo library", description = "Delete a book from the user's Kobo library.")
@ApiResponse(responseCode = "200", description = "Book deleted successfully")
@DeleteMapping("/v1/library/{bookId}")
public ResponseEntity<?> deleteBookFromLibrary(@PathVariable String bookId) {
public ResponseEntity<?> deleteBookFromLibrary(
@Parameter(description = "Book ID") @PathVariable String bookId) {
if (StringUtils.isNumeric(bookId)) {
Shelf userKoboShelf = shelfService.getUserKoboShelf();
if (userKoboShelf != null) {
@@ -152,6 +187,8 @@ public class KoboController {
}
}
@Operation(summary = "Catch-all for Kobo API", description = "Catch-all endpoint for unhandled Kobo API requests.")
@ApiResponse(responseCode = "200", description = "Request proxied successfully")
@RequestMapping(value = "/**", method = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE, RequestMethod.PATCH})
public ResponseEntity<JsonNode> catchAll(HttpServletRequest request, @RequestBody(required = false) Object body) {
String path = request.getRequestURI();
@@ -1,7 +1,11 @@
package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.model.dto.KoboSyncSettings;
import com.adityachandel.booklore.service.KoboSettingsService;
import com.adityachandel.booklore.service.kobo.KoboSettingsService;
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 lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
@@ -12,16 +16,21 @@ import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/v1/kobo-settings")
@RequiredArgsConstructor
@Tag(name = "Kobo Settings", description = "Endpoints for managing Kobo sync settings")
public class KoboSettingsController {
private final KoboSettingsService koboService;
@Operation(summary = "Get Kobo sync settings", description = "Retrieve the current user's Kobo sync settings.")
@ApiResponse(responseCode = "200", description = "Settings returned successfully")
@GetMapping
public ResponseEntity<KoboSyncSettings> getSettings() {
KoboSyncSettings settings = koboService.getCurrentUserSettings();
return ResponseEntity.ok(settings);
}
@Operation(summary = "Create or update Kobo token", description = "Create or update the Kobo sync token for the current user. Requires sync permission or admin.")
@ApiResponse(responseCode = "200", description = "Token created/updated successfully")
@PutMapping
@PreAuthorize("@securityUtil.canSyncKobo() or @securityUtil.isAdmin()")
public ResponseEntity<KoboSyncSettings> createOrUpdateToken() {
@@ -29,9 +38,12 @@ public class KoboSettingsController {
return ResponseEntity.ok(updated);
}
@Operation(summary = "Toggle Kobo sync", description = "Enable or disable Kobo sync for the current user. Requires sync permission or admin.")
@ApiResponse(responseCode = "204", description = "Sync toggled successfully")
@PutMapping("/sync")
@PreAuthorize("@securityUtil.canSyncKobo() or @securityUtil.isAdmin()")
public ResponseEntity<Void> toggleSync(@RequestParam boolean enabled) {
public ResponseEntity<Void> toggleSync(
@Parameter(description = "Enable or disable sync") @RequestParam boolean enabled) {
koboService.setSyncEnabled(enabled);
return ResponseEntity.noContent().build();
}
@@ -1,7 +1,11 @@
package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.model.dto.progress.KoreaderProgress;
import com.adityachandel.booklore.service.KoreaderService;
import com.adityachandel.booklore.service.koreader.KoreaderService;
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 lombok.extern.slf4j.Slf4j;
@@ -16,32 +20,44 @@ import java.util.Map;
@RestController
@AllArgsConstructor
@RequestMapping("/api/koreader")
@Tag(name = "KoReader", description = "Endpoints for KoReader device integration and progress sync")
public class KoreaderController {
private final KoreaderService koreaderService;
@Operation(summary = "Authorize KoReader user", description = "Authorize a user for KoReader sync.")
@ApiResponse(responseCode = "200", description = "User authorized successfully")
@GetMapping("/users/auth")
public ResponseEntity<Map<String, String>> authorizeUser() {
return koreaderService
.authorizeUser();
}
@Operation(summary = "Create KoReader user (disabled)", description = "Attempt to register a user via KoReader (always forbidden).")
@ApiResponse(responseCode = "403", description = "User registration forbidden")
@PostMapping("/users/create")
public ResponseEntity<?> createUser(@RequestBody Map<String, Object> userData) {
public ResponseEntity<?> createUser(
@Parameter(description = "User data") @RequestBody Map<String, Object> userData) {
log.warn("Attempt to register user via Koreader blocked: {}", userData);
return ResponseEntity.status(HttpStatus.FORBIDDEN).body(Map.of("error", "User registration via Koreader is disabled"));
}
@Operation(summary = "Get KoReader progress", description = "Retrieve reading progress for a book by its hash.")
@ApiResponse(responseCode = "200", description = "Progress returned successfully")
@GetMapping("/syncs/progress/{bookHash}")
public ResponseEntity<KoreaderProgress> getProgress(@PathVariable String bookHash) {
public ResponseEntity<KoreaderProgress> getProgress(
@Parameter(description = "Book hash") @PathVariable String bookHash) {
KoreaderProgress progress = koreaderService.getProgress(bookHash);
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_JSON)
.body(progress);
}
@Operation(summary = "Update KoReader progress", description = "Update reading progress for a book.")
@ApiResponse(responseCode = "200", description = "Progress updated successfully")
@PutMapping("/syncs/progress")
public ResponseEntity<?> updateProgress(@Valid @RequestBody KoreaderProgress koreaderProgress) {
public ResponseEntity<?> updateProgress(
@Parameter(description = "KoReader progress object") @Valid @RequestBody KoreaderProgress koreaderProgress) {
koreaderService.saveProgress(koreaderProgress.getDocument(), koreaderProgress);
return ResponseEntity.ok(Map.of("status", "progress updated"));
}
@@ -1,7 +1,11 @@
package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.model.dto.KoreaderUser;
import com.adityachandel.booklore.service.KoreaderUserService;
import com.adityachandel.booklore.service.koreader.KoreaderUserService;
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 lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
@@ -14,26 +18,35 @@ import java.util.Map;
@RestController
@RequestMapping("/api/v1/koreader-users")
@RequiredArgsConstructor
@Tag(name = "KoReader Users", description = "Endpoints for managing KoReader user accounts and sync settings")
public class KoreaderUserController {
private final KoreaderUserService koreaderUserService;
@Operation(summary = "Get current KoReader user", description = "Retrieve the current KoReader user profile.")
@ApiResponse(responseCode = "200", description = "User profile returned successfully")
@GetMapping("/me")
@PreAuthorize("@securityUtil.canSyncKoReader() or @securityUtil.isAdmin()")
public ResponseEntity<KoreaderUser> getCurrentUser() {
return ResponseEntity.ok(koreaderUserService.getUser());
}
@Operation(summary = "Upsert current KoReader user", description = "Create or update the current KoReader user profile.")
@ApiResponse(responseCode = "200", description = "User profile upserted successfully")
@PutMapping("/me")
@PreAuthorize("@securityUtil.canSyncKoReader() or @securityUtil.isAdmin()")
public ResponseEntity<KoreaderUser> upsertCurrentUser(@RequestBody Map<String, String> userData) {
public ResponseEntity<KoreaderUser> upsertCurrentUser(
@Parameter(description = "User data map") @RequestBody Map<String, String> userData) {
KoreaderUser user = koreaderUserService.upsertUser(userData.get("username"), userData.get("password"));
return ResponseEntity.ok(user);
}
@Operation(summary = "Toggle KoReader sync", description = "Enable or disable KoReader sync for the current user.")
@ApiResponse(responseCode = "204", description = "Sync toggled successfully")
@PatchMapping("/me/sync")
@PreAuthorize("@securityUtil.canSyncKoReader() or @securityUtil.isAdmin()")
public ResponseEntity<Void> updateSyncEnabled(@RequestParam boolean enabled) {
public ResponseEntity<Void> updateSyncEnabled(
@Parameter(description = "Enable or disable sync") @RequestParam boolean enabled) {
koreaderUserService.toggleSync(enabled);
return ResponseEntity.noContent().build();
}
@@ -5,6 +5,11 @@ import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.dto.Library;
import com.adityachandel.booklore.model.dto.request.CreateLibraryRequest;
import com.adityachandel.booklore.service.library.LibraryService;
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.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
@@ -16,68 +21,100 @@ import java.util.Map;
@RestController
@RequestMapping("/api/v1/libraries")
@AllArgsConstructor
@Tag(name = "Libraries", description = "Endpoints for managing libraries and their books")
public class LibraryController {
private final LibraryService libraryService;
@Operation(summary = "Get all libraries", description = "Retrieve a list of all libraries.")
@ApiResponse(responseCode = "200", description = "Libraries returned successfully")
@GetMapping
public ResponseEntity<List<Library>> getLibraries() {
return ResponseEntity.ok(libraryService.getLibraries());
}
@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"),
@ApiResponse(responseCode = "404", description = "Library not found")
})
@GetMapping("/{libraryId}")
@CheckLibraryAccess(libraryIdParam = "libraryId")
public ResponseEntity<Library> getLibrary(@PathVariable long libraryId) {
public ResponseEntity<Library> getLibrary(
@Parameter(description = "ID of the library") @PathVariable long libraryId) {
return ResponseEntity.ok(libraryService.getLibrary(libraryId));
}
@Operation(summary = "Create a library", description = "Create a new library. Requires admin or manipulation permission.")
@ApiResponse(responseCode = "200", description = "Library created successfully")
@PostMapping
@PreAuthorize("@securityUtil.canManipulateLibrary() or @securityUtil.isAdmin()")
public ResponseEntity<Library> createLibrary(@RequestBody CreateLibraryRequest request) {
public ResponseEntity<Library> createLibrary(
@Parameter(description = "Library creation request") @RequestBody CreateLibraryRequest request) {
return ResponseEntity.ok(libraryService.createLibrary(request));
}
@Operation(summary = "Update a library", description = "Update an existing library. Requires admin or manipulation permission.")
@ApiResponse(responseCode = "200", description = "Library updated successfully")
@PutMapping("/{libraryId}")
@CheckLibraryAccess(libraryIdParam = "libraryId")
@PreAuthorize("@securityUtil.canManipulateLibrary() or @securityUtil.isAdmin()")
public ResponseEntity<Library> updateLibrary(@RequestBody CreateLibraryRequest request, @PathVariable Long libraryId) {
public ResponseEntity<Library> updateLibrary(
@Parameter(description = "Library update request") @RequestBody CreateLibraryRequest request,
@Parameter(description = "ID of the library") @PathVariable Long libraryId) {
return ResponseEntity.ok(libraryService.updateLibrary(request, libraryId));
}
@Operation(summary = "Delete a library", description = "Delete a library by its ID. Requires admin or manipulation permission.")
@ApiResponse(responseCode = "204", description = "Library deleted successfully")
@DeleteMapping("/{libraryId}")
@CheckLibraryAccess(libraryIdParam = "libraryId")
@PreAuthorize("@securityUtil.canManipulateLibrary() or @securityUtil.isAdmin()")
public ResponseEntity<?> deleteLibrary(@PathVariable long libraryId) {
public ResponseEntity<?> deleteLibrary(
@Parameter(description = "ID of the library") @PathVariable long libraryId) {
libraryService.deleteLibrary(libraryId);
return ResponseEntity.noContent().build();
}
@Operation(summary = "Get a book from a library", description = "Retrieve a specific book from a library by its ID.")
@ApiResponse(responseCode = "200", description = "Book returned successfully")
@GetMapping("/{libraryId}/book/{bookId}")
@CheckLibraryAccess(libraryIdParam = "libraryId")
public ResponseEntity<Book> getBook(@PathVariable long libraryId, @PathVariable long bookId) {
public ResponseEntity<Book> getBook(
@Parameter(description = "ID of the library") @PathVariable long libraryId,
@Parameter(description = "ID of the book") @PathVariable long bookId) {
return ResponseEntity.ok(libraryService.getBook(libraryId, bookId));
}
@Operation(summary = "Get all books from a library", description = "Retrieve all books from a specific library.")
@ApiResponse(responseCode = "200", description = "Books returned successfully")
@GetMapping("/{libraryId}/book")
@CheckLibraryAccess(libraryIdParam = "libraryId")
public ResponseEntity<List<Book>> getBooks(@PathVariable long libraryId) {
public ResponseEntity<List<Book>> getBooks(
@Parameter(description = "ID of the library") @PathVariable long libraryId) {
List<Book> books = libraryService.getBooks(libraryId);
return ResponseEntity.ok(books);
}
@Operation(summary = "Rescan a library", description = "Rescan a library to refresh its contents. Requires admin or manipulation permission.")
@ApiResponse(responseCode = "204", description = "Library rescanned successfully")
@PutMapping("/{libraryId}/refresh")
@CheckLibraryAccess(libraryIdParam = "libraryId")
@PreAuthorize("@securityUtil.canManipulateLibrary() or @securityUtil.isAdmin()")
public ResponseEntity<?> rescanLibrary(@PathVariable long libraryId) {
public ResponseEntity<?> rescanLibrary(
@Parameter(description = "ID of the library") @PathVariable long libraryId) {
libraryService.rescanLibrary(libraryId);
return ResponseEntity.noContent().build();
}
@Operation(summary = "Set file naming pattern", description = "Set the file naming pattern for a library. Requires admin or manipulation permission.")
@ApiResponse(responseCode = "200", description = "File naming pattern updated successfully")
@PatchMapping("/{libraryId}/file-naming-pattern")
@CheckLibraryAccess(libraryIdParam = "libraryId")
@PreAuthorize("@securityUtil.canManipulateLibrary() or @securityUtil.isAdmin()")
public ResponseEntity<Library> setFileNamingPattern(@PathVariable long libraryId, @RequestBody Map<String, String> body) {
public ResponseEntity<Library> setFileNamingPattern(
@Parameter(description = "ID of the library") @PathVariable long libraryId,
@Parameter(description = "File naming pattern body") @RequestBody Map<String, String> body) {
String pattern = body.get("fileNamingPattern");
Library updated = libraryService.setFileNamingPattern(libraryId, pattern);
return ResponseEntity.ok(updated);
@@ -2,6 +2,10 @@ package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.model.dto.MagicShelf;
import com.adityachandel.booklore.service.MagicShelfService;
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 org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@@ -10,6 +14,7 @@ import java.util.List;
@RestController
@RequestMapping("/api/magic-shelves")
@Tag(name = "Magic Shelves", description = "Endpoints for managing user-defined magic shelves")
public class MagicShelfController {
private final MagicShelfService magicShelfService;
@@ -18,23 +23,34 @@ public class MagicShelfController {
this.magicShelfService = magicShelfService;
}
@Operation(summary = "Get all magic shelves for user", description = "Retrieve all magic shelves for the current user.")
@ApiResponse(responseCode = "200", description = "Magic shelves returned successfully")
@GetMapping
public ResponseEntity<List<MagicShelf>> getAllForUser() {
return ResponseEntity.ok(magicShelfService.getUserShelves());
}
@Operation(summary = "Get a magic shelf by ID", description = "Retrieve a specific magic shelf by its ID.")
@ApiResponse(responseCode = "200", description = "Magic shelf returned successfully")
@GetMapping("/{id}")
public ResponseEntity<MagicShelf> getShelf(@PathVariable Long id) {
public ResponseEntity<MagicShelf> getShelf(
@Parameter(description = "ID of the magic shelf") @PathVariable Long id) {
return ResponseEntity.ok(magicShelfService.getShelf(id));
}
@Operation(summary = "Create or update a magic shelf", description = "Create or update a magic shelf for the user.")
@ApiResponse(responseCode = "200", description = "Magic shelf created/updated successfully")
@PostMapping
public ResponseEntity<MagicShelf> createUpdateShelf(@Valid @RequestBody MagicShelf shelf) {
public ResponseEntity<MagicShelf> createUpdateShelf(
@Parameter(description = "Magic shelf object") @Valid @RequestBody MagicShelf shelf) {
return ResponseEntity.ok(magicShelfService.createOrUpdateShelf(shelf));
}
@Operation(summary = "Delete a magic shelf", description = "Delete a specific magic shelf by its ID.")
@ApiResponse(responseCode = "204", description = "Magic shelf deleted successfully")
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteShelf(@PathVariable Long id) {
public ResponseEntity<Void> deleteShelf(
@Parameter(description = "ID of the magic shelf") @PathVariable Long id) {
magicShelfService.deleteShelf(id);
return ResponseEntity.noContent().build();
}
@@ -20,12 +20,19 @@ import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.Parameter;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/api/v1/books")
@AllArgsConstructor
@Tag(name = "Book Metadata", description = "Endpoints for managing book metadata, covers, and metadata operations")
public class MetadataController {
private final BookMetadataService bookMetadataService;
@@ -37,17 +44,26 @@ public class MetadataController {
private final BookRepository bookRepository;
private final MetadataManagementService metadataManagementService;
@Operation(summary = "Get prospective metadata for a book", description = "Fetch prospective metadata for a book by its ID. Requires metadata edit permission or admin.")
@ApiResponse(responseCode = "200", description = "Prospective metadata returned successfully")
@PostMapping("/{bookId}/metadata/prospective")
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
@CheckBookAccess(bookIdParam = "bookId")
public ResponseEntity<List<BookMetadata>> getMetadataList(@RequestBody(required = false) FetchMetadataRequest fetchMetadataRequest, @PathVariable Long bookId) {
public ResponseEntity<List<BookMetadata>> getMetadataList(
@Parameter(description = "Fetch metadata request") @RequestBody(required = false) FetchMetadataRequest fetchMetadataRequest,
@Parameter(description = "ID of the book") @PathVariable Long bookId) {
return ResponseEntity.ok(bookMetadataService.getProspectiveMetadataListForBookId(bookId, fetchMetadataRequest));
}
@Operation(summary = "Update book metadata", description = "Update metadata for a book. Requires metadata edit permission or admin.")
@ApiResponse(responseCode = "200", description = "Metadata updated successfully")
@PutMapping("/{bookId}/metadata")
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
@CheckBookAccess(bookIdParam = "bookId")
public ResponseEntity<BookMetadata> updateMetadata(@RequestBody MetadataUpdateWrapper metadataUpdateWrapper, @PathVariable long bookId, @RequestParam(defaultValue = "true") boolean mergeCategories) {
public ResponseEntity<BookMetadata> updateMetadata(
@Parameter(description = "Metadata update wrapper") @RequestBody MetadataUpdateWrapper metadataUpdateWrapper,
@Parameter(description = "ID of the book") @PathVariable long bookId,
@Parameter(description = "Merge categories") @RequestParam(defaultValue = "true") boolean mergeCategories) {
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
MetadataUpdateContext context = MetadataUpdateContext.builder()
@@ -64,54 +80,82 @@ public class MetadataController {
return ResponseEntity.ok(bookMetadata);
}
@Operation(summary = "Bulk edit book metadata", description = "Bulk update metadata for multiple books. Requires metadata edit permission or admin.")
@ApiResponse(responseCode = "204", description = "Bulk metadata updated successfully")
@PutMapping("/bulk-edit-metadata")
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
public ResponseEntity<List<BookMetadata>> bulkEditMetadata(@RequestBody BulkMetadataUpdateRequest bulkMetadataUpdateRequest, @RequestParam boolean mergeCategories) {
return ResponseEntity.ok(bookMetadataService.bulkUpdateMetadata(bulkMetadataUpdateRequest, mergeCategories));
public ResponseEntity<Void> bulkEditMetadata(
@Parameter(description = "Bulk metadata update request") @RequestBody BulkMetadataUpdateRequest bulkMetadataUpdateRequest) {
boolean mergeCategories = bulkMetadataUpdateRequest.isMergeCategories();
boolean mergeMoods = bulkMetadataUpdateRequest.isMergeMoods();
boolean mergeTags = bulkMetadataUpdateRequest.isMergeTags();
bookMetadataService.bulkUpdateMetadata(bulkMetadataUpdateRequest, mergeCategories, mergeMoods, mergeTags);
return ResponseEntity.noContent().build();
}
@Operation(summary = "Upload cover image from file", description = "Upload a cover image for a book from a file. Requires metadata edit permission or admin.")
@ApiResponse(responseCode = "200", description = "Cover image uploaded successfully")
@PostMapping("/{bookId}/metadata/cover/upload")
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
@CheckBookAccess(bookIdParam = "bookId")
public ResponseEntity<BookMetadata> uploadCoverFromFile(@PathVariable Long bookId, @RequestParam("file") MultipartFile file) {
public ResponseEntity<BookMetadata> uploadCoverFromFile(
@Parameter(description = "ID of the book") @PathVariable Long bookId,
@Parameter(description = "Cover image file") @RequestParam("file") MultipartFile file) {
BookMetadata updated = bookMetadataService.updateCoverImageFromFile(bookId, file);
return ResponseEntity.ok(updated);
}
@Operation(summary = "Upload cover image from URL", description = "Upload a cover image for a book from a URL. Requires metadata edit permission or admin.")
@ApiResponse(responseCode = "200", description = "Cover image uploaded successfully")
@PostMapping("/{bookId}/metadata/cover/from-url")
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
@CheckBookAccess(bookIdParam = "bookId")
public ResponseEntity<BookMetadata> uploadCoverFromUrl(@PathVariable Long bookId, @RequestBody Map<String, String> body) {
public ResponseEntity<BookMetadata> uploadCoverFromUrl(
@Parameter(description = "ID of the book") @PathVariable Long bookId,
@Parameter(description = "URL body") @RequestBody Map<String, String> body) {
BookMetadata updated = bookMetadataService.updateCoverImageFromUrl(bookId, body.get("url"));
return ResponseEntity.ok(updated);
}
@Operation(summary = "Toggle all metadata locks", description = "Toggle all metadata locks for books. Requires metadata edit permission or admin.")
@ApiResponse(responseCode = "200", description = "Metadata locks toggled successfully")
@PutMapping("/metadata/toggle-all-lock")
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
public ResponseEntity<List<BookMetadata>> toggleAllMetadata(@RequestBody ToggleAllLockRequest request) {
public ResponseEntity<List<BookMetadata>> toggleAllMetadata(
@Parameter(description = "Toggle all lock request") @RequestBody ToggleAllLockRequest request) {
return ResponseEntity.ok(bookMetadataService.toggleAllLock(request));
}
@Operation(summary = "Toggle field locks for metadata", description = "Toggle field locks for book metadata. Requires metadata edit permission or admin.")
@ApiResponse(responseCode = "200", description = "Field locks toggled successfully")
@PutMapping("/metadata/toggle-field-locks")
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
public ResponseEntity<List<BookMetadata>> toggleFieldLocks(@RequestBody ToggleFieldLocksRequest request) {
public ResponseEntity<List<BookMetadata>> toggleFieldLocks(
@Parameter(description = "Toggle field locks request") @RequestBody ToggleFieldLocksRequest request) {
bookMetadataService.toggleFieldLocks(request.getBookIds(), request.getFieldActions());
return ResponseEntity.ok().build();
}
@Operation(summary = "Regenerate all covers", description = "Regenerate covers for all books. Requires metadata edit permission or admin.")
@ApiResponse(responseCode = "204", description = "Covers regenerated successfully")
@PostMapping("/regenerate-covers")
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
public void regenerateCovers() {
bookMetadataService.regenerateCovers();
}
@Operation(summary = "Regenerate cover for a book", description = "Regenerate cover for a specific book. Requires metadata edit permission or admin.")
@ApiResponse(responseCode = "204", description = "Cover regenerated successfully")
@PostMapping("/{bookId}/regenerate-cover")
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
@CheckBookAccess(bookIdParam = "bookId")
public void regenerateCovers(@PathVariable Long bookId) {
public void regenerateCovers(
@Parameter(description = "ID of the book") @PathVariable Long bookId) {
bookMetadataService.regenerateCover(bookId);
}
@Operation(summary = "Recalculate metadata match scores", description = "Recalculate match scores for all metadata. Requires admin.")
@ApiResponse(responseCode = "204", description = "Match scores recalculated successfully")
@PostMapping("/metadata/recalculate-match-scores")
@PreAuthorize("@securityUtil.isAdmin()")
public ResponseEntity<Void> recalculateMatchScores() {
@@ -119,21 +163,30 @@ public class MetadataController {
return ResponseEntity.noContent().build();
}
@Operation(summary = "Get cover images for a book", description = "Fetch cover images for a book.")
@ApiResponse(responseCode = "200", description = "Cover images returned successfully")
@PostMapping("/{bookId}/metadata/covers")
public ResponseEntity<List<CoverImage>> getImages(@RequestBody CoverFetchRequest request) {
public ResponseEntity<List<CoverImage>> getImages(
@Parameter(description = "Cover fetch request") @RequestBody CoverFetchRequest request) {
return ResponseEntity.ok(duckDuckGoCoverService.getCovers(request));
}
@Operation(summary = "Consolidate metadata", description = "Merge metadata values. Requires metadata edit permission or admin.")
@ApiResponse(responseCode = "204", description = "Metadata consolidated successfully")
@PostMapping("/metadata/manage/consolidate")
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
public ResponseEntity<Void> mergeMetadata(@Validated @RequestBody MergeMetadataRequest request) {
public ResponseEntity<Void> mergeMetadata(
@Parameter(description = "Merge metadata request") @Validated @RequestBody MergeMetadataRequest request) {
metadataManagementService.consolidateMetadata(request.getMetadataType(), request.getTargetValues(), request.getValuesToMerge());
return ResponseEntity.noContent().build();
}
@Operation(summary = "Delete metadata values", description = "Delete metadata values. Requires metadata edit permission or admin.")
@ApiResponse(responseCode = "204", description = "Metadata deleted successfully")
@PostMapping("/metadata/manage/delete")
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
public ResponseEntity<Void> deleteMetadata(@Validated @RequestBody DeleteMetadataRequest request) {
public ResponseEntity<Void> deleteMetadata(
@Parameter(description = "Delete metadata request") @Validated @RequestBody DeleteMetadataRequest request) {
metadataManagementService.deleteMetadata(request.getMetadataType(), request.getValuesToDelete());
return ResponseEntity.noContent().build();
}
@@ -2,7 +2,11 @@ package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.model.dto.MetadataBatchProgressNotification;
import com.adityachandel.booklore.model.dto.response.MetadataTaskDetailsResponse;
import com.adityachandel.booklore.service.MetadataTaskService;
import com.adityachandel.booklore.service.metadata.MetadataTaskService;
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 lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
@@ -13,34 +17,48 @@ import java.util.List;
@RestController
@RequestMapping("/api/metadata/tasks")
@RequiredArgsConstructor
@Tag(name = "Metadata Tasks", description = "Endpoints for managing metadata batch tasks and proposals")
public class MetadataTaskController {
private final MetadataTaskService metadataTaskService;
@Operation(summary = "Get metadata task with proposals", description = "Retrieve a metadata task and its proposals by task ID. Requires metadata edit permission or admin.")
@ApiResponse(responseCode = "200", description = "Task details returned successfully")
@GetMapping("/{taskId}")
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
public ResponseEntity<MetadataTaskDetailsResponse> getTaskWithProposals(@PathVariable String taskId) {
public ResponseEntity<MetadataTaskDetailsResponse> getTaskWithProposals(
@Parameter(description = "Task ID") @PathVariable String taskId) {
return metadataTaskService.getTaskWithProposals(taskId)
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}
@Operation(summary = "Get active metadata tasks", description = "Retrieve all active metadata batch tasks. Requires metadata edit permission or admin.")
@ApiResponse(responseCode = "200", description = "Active tasks returned successfully")
@GetMapping("/active")
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
public ResponseEntity<List<MetadataBatchProgressNotification>> getActiveTasks() {
return ResponseEntity.ok(metadataTaskService.getActiveTasks());
}
@Operation(summary = "Delete a metadata task", description = "Delete a metadata task and its proposals by task ID. Requires metadata edit permission or admin.")
@ApiResponse(responseCode = "204", description = "Task deleted successfully")
@DeleteMapping("/{taskId}")
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
public ResponseEntity<Void> deleteTask(@PathVariable String taskId) {
public ResponseEntity<Void> deleteTask(
@Parameter(description = "Task ID") @PathVariable String taskId) {
boolean deleted = metadataTaskService.deleteTaskAndProposals(taskId);
return deleted ? ResponseEntity.noContent().build() : ResponseEntity.notFound().build();
}
@Operation(summary = "Update proposal status", description = "Update the status of a proposal for a metadata task. Requires metadata edit permission or admin.")
@ApiResponse(responseCode = "200", description = "Proposal status updated successfully")
@PostMapping("/{taskId}/proposals/{proposalId}/status")
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
public ResponseEntity<Void> updateProposalStatus(@PathVariable String taskId, @PathVariable Long proposalId, @RequestParam String status) {
public ResponseEntity<Void> updateProposalStatus(
@Parameter(description = "Task ID") @PathVariable String taskId,
@Parameter(description = "Proposal ID") @PathVariable Long proposalId,
@Parameter(description = "New status") @RequestParam String status) {
boolean updated = metadataTaskService.updateProposalStatus(taskId, proposalId, status);
return updated ? ResponseEntity.ok().build() : ResponseEntity.notFound().build();
}
@@ -1,7 +1,12 @@
package com.adityachandel.booklore.controller.opds;
package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.service.BookService;
import com.adityachandel.booklore.service.book.BookService;
import com.adityachandel.booklore.service.opds.OpdsFeedService;
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 io.swagger.v3.oas.annotations.responses.ApiResponses;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@@ -14,6 +19,7 @@ import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Tag(name = "OPDS", description = "Endpoints for OPDS catalog feeds, book downloads, covers, and search description")
@Slf4j
@RestController
@RequestMapping("/api/v1/opds")
@@ -26,13 +32,25 @@ public class OpdsController {
private final OpdsFeedService opdsFeedService;
private final BookService bookService;
@Operation(summary = "Download book file", description = "Download the book file by its ID.")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Book file downloaded successfully"),
@ApiResponse(responseCode = "404", description = "Book not found")
})
@GetMapping("/{bookId}/download")
public ResponseEntity<Resource> downloadBook(@PathVariable("bookId") Long bookId) {
public ResponseEntity<Resource> downloadBook(
@Parameter(description = "ID of the book to download") @PathVariable("bookId") Long bookId) {
return bookService.downloadBook(bookId);
}
@Operation(summary = "Get book cover image", description = "Retrieve the cover image for a book by its ID.")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Cover image returned successfully"),
@ApiResponse(responseCode = "404", description = "Book or cover not found")
})
@GetMapping("/{bookId}/cover")
public ResponseEntity<Resource> getBookCover(@PathVariable long bookId) {
public ResponseEntity<Resource> getBookCover(
@Parameter(description = "ID of the book") @PathVariable long bookId) {
Resource coverImage = bookService.getBookThumbnail(bookId);
String contentType = "image/jpeg";
return ResponseEntity.ok()
@@ -41,54 +59,74 @@ public class OpdsController {
.body(coverImage);
}
@Operation(summary = "Get OPDS root catalog", description = "Retrieve the OPDS root navigation feed.")
@ApiResponse(responseCode = "200", description = "Root OPDS catalog returned successfully")
@GetMapping(produces = OPDS_CATALOG_MEDIA_TYPE)
public ResponseEntity<String> getRootCatalog(HttpServletRequest request) {
public ResponseEntity<String> getRootCatalog(
@Parameter(hidden = true) HttpServletRequest request) {
String feed = opdsFeedService.generateRootNavigation(request);
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType(OPDS_CATALOG_MEDIA_TYPE))
.body(feed);
}
@Operation(summary = "Get OPDS libraries navigation", description = "Retrieve the OPDS libraries navigation feed.")
@ApiResponse(responseCode = "200", description = "Libraries navigation feed returned successfully")
@GetMapping(value = "/libraries", produces = OPDS_CATALOG_MEDIA_TYPE)
public ResponseEntity<String> getLibrariesNavigation(HttpServletRequest request) {
public ResponseEntity<String> getLibrariesNavigation(
@Parameter(hidden = true) HttpServletRequest request) {
String feed = opdsFeedService.generateLibrariesNavigation(request);
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType(OPDS_CATALOG_MEDIA_TYPE))
.body(feed);
}
@Operation(summary = "Get OPDS shelves navigation", description = "Retrieve the OPDS shelves navigation feed.")
@ApiResponse(responseCode = "200", description = "Shelves navigation feed returned successfully")
@GetMapping(value = "/shelves", produces = OPDS_CATALOG_MEDIA_TYPE)
public ResponseEntity<String> getShelvesNavigation(HttpServletRequest request) {
public ResponseEntity<String> getShelvesNavigation(
@Parameter(hidden = true) HttpServletRequest request) {
String feed = opdsFeedService.generateShelvesNavigation(request);
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType(OPDS_CATALOG_MEDIA_TYPE))
.body(feed);
}
@Operation(summary = "Get OPDS catalog feed", description = "Retrieve the OPDS acquisition catalog feed.")
@ApiResponse(responseCode = "200", description = "Catalog feed returned successfully")
@GetMapping(value = "/catalog", produces = OPDS_ACQUISITION_MEDIA_TYPE)
public ResponseEntity<String> getCatalog(HttpServletRequest request) {
public ResponseEntity<String> getCatalog(
@Parameter(hidden = true) HttpServletRequest request) {
String feed = opdsFeedService.generateCatalogFeed(request);
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType(OPDS_ACQUISITION_MEDIA_TYPE))
.body(feed);
}
@Operation(summary = "Get recent books feed", description = "Retrieve the OPDS feed for recently added books.")
@ApiResponse(responseCode = "200", description = "Recent books feed returned successfully")
@GetMapping(value = "/recent", produces = OPDS_ACQUISITION_MEDIA_TYPE)
public ResponseEntity<String> getRecentBooks(HttpServletRequest request) {
public ResponseEntity<String> getRecentBooks(
@Parameter(hidden = true) HttpServletRequest request) {
String feed = opdsFeedService.generateRecentFeed(request);
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType(OPDS_ACQUISITION_MEDIA_TYPE))
.body(feed);
}
@Operation(summary = "Get surprise feed", description = "Retrieve the OPDS feed for surprise/random books.")
@ApiResponse(responseCode = "200", description = "Surprise feed returned successfully")
@GetMapping(value = "/surprise", produces = OPDS_ACQUISITION_MEDIA_TYPE)
public ResponseEntity<String> getSurpriseFeed(HttpServletRequest request) {
public ResponseEntity<String> getSurpriseFeed(
@Parameter(hidden = true) HttpServletRequest request) {
String feed = opdsFeedService.generateSurpriseFeed(request);
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType(OPDS_ACQUISITION_MEDIA_TYPE))
.body(feed);
}
@Operation(summary = "Get OPDS search description", description = "Retrieve the OpenSearch description document for OPDS search.")
@ApiResponse(responseCode = "200", description = "OpenSearch description returned successfully")
@GetMapping(value = "/search.opds", produces = {
"application/opensearchdescription+xml",
"application/atom+xml",
@@ -1,9 +1,12 @@
package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.model.dto.OpdsUserV2;
import com.adityachandel.booklore.model.dto.request.OpdsUserV2CreateRequest;
import com.adityachandel.booklore.service.OpdsUserV2Service;
import com.adityachandel.booklore.service.opds.OpdsUserV2Service;
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 lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
@@ -13,25 +16,34 @@ import java.util.List;
@RestController
@RequestMapping("/api/v2/opds-users")
@RequiredArgsConstructor
@Tag(name = "OPDS Users", description = "Endpoints for managing OPDS users")
public class OpdsUserV2Controller {
private final OpdsUserV2Service service;
@Operation(summary = "Get all OPDS users", description = "Retrieve a list of all OPDS users.")
@ApiResponse(responseCode = "200", description = "List of OPDS users returned successfully")
@GetMapping
@PreAuthorize("@securityUtil.isAdmin() or @securityUtil.canAccessOpds()")
public List<OpdsUserV2> getUsers() {
return service.getOpdsUsers();
}
@Operation(summary = "Create OPDS user", description = "Create a new OPDS user.")
@ApiResponse(responseCode = "200", description = "OPDS user created successfully")
@PostMapping
@PreAuthorize("@securityUtil.isAdmin() or @securityUtil.canAccessOpds()")
public OpdsUserV2 createUser(@RequestBody OpdsUserV2CreateRequest createRequest) {
public OpdsUserV2 createUser(
@Parameter(description = "OPDS user creation request") @RequestBody OpdsUserV2CreateRequest createRequest) {
return service.createOpdsUser(createRequest);
}
@Operation(summary = "Delete OPDS user", description = "Delete an OPDS user by ID.")
@ApiResponse(responseCode = "204", description = "OPDS user deleted successfully")
@DeleteMapping("/{id}")
@PreAuthorize("@securityUtil.isAdmin() or @securityUtil.canAccessOpds()")
public void deleteUser(@PathVariable Long id) {
public void deleteUser(
@Parameter(description = "ID of the OPDS user to delete") @PathVariable Long id) {
service.deleteOpdsUser(id);
}
}
@@ -8,18 +8,27 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.Parameter;
import java.util.List;
@RestController
@RequestMapping("/api/v1/path")
@AllArgsConstructor
@Tag(name = "Library Paths", description = "Endpoints for retrieving folder paths within libraries")
public class PathController {
private final PathService pathService;
@Operation(summary = "Get folders at a path", description = "Retrieve a list of folders at a given path. Requires admin or library manipulation permission.")
@ApiResponse(responseCode = "200", description = "Folders returned successfully")
@GetMapping
@PreAuthorize("@securityUtil.canManipulateLibrary() or @securityUtil.isAdmin()")
public List<String> getFolders(@RequestParam String path) {
public List<String> getFolders(
@Parameter(description = "Path to list folders at") @RequestParam String path) {
return pathService.getFoldersAtPath(path);
}
}
@@ -1,6 +1,10 @@
package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.service.reader.PdfReaderService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
@@ -15,12 +19,16 @@ import java.util.List;
@RestController
@RequestMapping("/api/v1/pdf")
@RequiredArgsConstructor
@Tag(name = "PDF Reader", description = "Endpoints for reading PDF format books")
public class PdfReaderController {
private final PdfReaderService pdfReaderService;
@Operation(summary = "List pages in a PDF book", description = "Retrieve a list of available page numbers for a PDF book.")
@ApiResponse(responseCode = "200", description = "Page numbers returned successfully")
@GetMapping("/{bookId}/pages")
public List<Integer> listPages(@PathVariable Long bookId) throws IOException {
public List<Integer> listPages(
@Parameter(description = "ID of the book") @PathVariable Long bookId) throws IOException {
return pdfReaderService.getAvailablePages(bookId);
}
}
@@ -2,6 +2,9 @@ package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.model.dto.settings.PublicAppSetting;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@@ -12,10 +15,13 @@ import java.util.List;
@RestController
@RequestMapping("/api/v1/public-settings")
@RequiredArgsConstructor
@Tag(name = "Public App Settings", description = "Endpoints for retrieving public application settings")
public class PublicAppSettingController {
private final AppSettingService appSettingService;
@Operation(summary = "Get public app settings", description = "Retrieve public application settings.")
@ApiResponse(responseCode = "200", description = "Settings returned successfully")
@GetMapping
public PublicAppSetting getPublicSettings() {
return appSettingService.getPublicSettings();
@@ -2,6 +2,10 @@ package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.model.dto.request.SendBookByEmailRequest;
import com.adityachandel.booklore.service.email.SendEmailV2Service;
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 lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
@@ -11,20 +15,27 @@ import org.springframework.web.bind.annotation.*;
@AllArgsConstructor
@RestController
@RequestMapping("/api/v2/email")
@Tag(name = "Send Email", description = "Endpoints for sending books via email")
public class SendEmailV2Controller {
private final SendEmailV2Service service;
@Operation(summary = "Send book by email", description = "Send a book to a recipient via email. Requires email permission or admin.")
@ApiResponse(responseCode = "204", description = "Book sent successfully")
@PreAuthorize("@securityUtil.canEmailBook() or @securityUtil.isAdmin()")
@PostMapping("/book")
public ResponseEntity<?> sendEmail(@Validated @RequestBody SendBookByEmailRequest request) {
public ResponseEntity<?> sendEmail(
@Parameter(description = "Send book by email request") @Validated @RequestBody SendBookByEmailRequest request) {
service.emailBook(request);
return ResponseEntity.noContent().build();
}
@Operation(summary = "Quick send book by email", description = "Quickly send a book by its ID via email. Requires email permission or admin.")
@ApiResponse(responseCode = "204", description = "Book sent successfully")
@PreAuthorize("@securityUtil.canEmailBook() or @securityUtil.isAdmin()")
@PostMapping("/book/{bookId}")
public ResponseEntity<?> emailBookQuick(@PathVariable Long bookId) {
public ResponseEntity<?> emailBookQuick(
@Parameter(description = "ID of the book to send") @PathVariable Long bookId) {
service.emailBookQuick(bookId);
return ResponseEntity.noContent().build();
}
@@ -4,6 +4,10 @@ import com.adityachandel.booklore.exception.ErrorResponse;
import com.adityachandel.booklore.model.dto.request.InitialUserRequest;
import com.adityachandel.booklore.model.dto.response.SuccessResponse;
import com.adityachandel.booklore.service.user.UserProvisioningService;
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 lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@@ -11,10 +15,13 @@ import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/v1/setup")
@RequiredArgsConstructor
@Tag(name = "Setup", description = "Endpoints for initial application setup and user provisioning")
public class SetupController {
private final UserProvisioningService userProvisioningService;
@Operation(summary = "Get setup status", description = "Check if initial setup has been completed.")
@ApiResponse(responseCode = "200", description = "Setup status returned successfully")
@GetMapping("/status")
public ResponseEntity<?> getSetupStatus() {
boolean isCompleted = userProvisioningService.isInitialUserAlreadyProvisioned();
@@ -24,8 +31,11 @@ public class SetupController {
return ResponseEntity.ok(new SuccessResponse<>(200, message, isCompleted));
}
@Operation(summary = "Setup first user", description = "Provision the initial admin user during setup.")
@ApiResponse(responseCode = "200", description = "Admin user created successfully")
@PostMapping
public ResponseEntity<?> setupFirstUser(@RequestBody InitialUserRequest request) {
public ResponseEntity<?> setupFirstUser(
@Parameter(description = "Initial user request") @RequestBody InitialUserRequest request) {
if (userProvisioningService.isInitialUserAlreadyProvisioned()) {
return ResponseEntity.status(403).body(new ErrorResponse(403, "Setup is disabled after the first user is created."));
}
@@ -4,6 +4,11 @@ import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.dto.Shelf;
import com.adityachandel.booklore.model.dto.request.ShelfCreateRequest;
import com.adityachandel.booklore.service.ShelfService;
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.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpStatus;
@@ -16,42 +21,64 @@ import java.util.List;
@AllArgsConstructor
@RestController
@RequestMapping(("/api/v1/shelves"))
@Tag(name = "Shelves", description = "Endpoints for managing shelves and their books")
public class ShelfController {
private final ShelfService shelfService;
@Operation(summary = "Get all shelves", description = "Retrieve a list of all shelves.")
@ApiResponse(responseCode = "200", description = "Shelves returned successfully")
@GetMapping
public ResponseEntity<List<Shelf>> getAllShelves() {
return ResponseEntity.ok(shelfService.getShelves());
}
@Operation(summary = "Get a shelf by ID", description = "Retrieve details of a specific shelf by its ID.")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Shelf details returned successfully"),
@ApiResponse(responseCode = "403", description = "Forbidden")
})
@GetMapping("/{shelfId}")
@PreAuthorize("@securityUtil.isShelfOwner(#shelfId)")
public ResponseEntity<Shelf> getShelf(@PathVariable Long shelfId) {
public ResponseEntity<Shelf> getShelf(
@Parameter(description = "ID of the shelf") @PathVariable Long shelfId) {
return ResponseEntity.ok(shelfService.getShelf(shelfId));
}
@Operation(summary = "Create a shelf", description = "Create a new shelf.")
@ApiResponse(responseCode = "201", description = "Shelf created successfully")
@PostMapping
public ResponseEntity<Shelf> createShelf(@Valid @RequestBody ShelfCreateRequest request) {
public ResponseEntity<Shelf> createShelf(
@Parameter(description = "Shelf creation request") @Valid @RequestBody ShelfCreateRequest request) {
return ResponseEntity.status(HttpStatus.CREATED).body(shelfService.createShelf(request));
}
@Operation(summary = "Update a shelf", description = "Update an existing shelf by its ID.")
@ApiResponse(responseCode = "200", description = "Shelf updated successfully")
@PutMapping("/{shelfId}")
@PreAuthorize("@securityUtil.isShelfOwner(#shelfId)")
public ResponseEntity<Shelf> updateShelf(@Valid @RequestBody ShelfCreateRequest request, @PathVariable Long shelfId) {
public ResponseEntity<Shelf> updateShelf(
@Parameter(description = "Shelf update request") @Valid @RequestBody ShelfCreateRequest request,
@Parameter(description = "ID of the shelf") @PathVariable Long shelfId) {
return ResponseEntity.ok(shelfService.updateShelf(shelfId, request));
}
@Operation(summary = "Delete a shelf", description = "Delete a shelf by its ID.")
@ApiResponse(responseCode = "204", description = "Shelf deleted successfully")
@DeleteMapping("/{shelfId}")
@PreAuthorize("@securityUtil.isShelfOwner(#shelfId)")
public ResponseEntity<Void> deleteShelf(@PathVariable Long shelfId) {
public ResponseEntity<Void> deleteShelf(
@Parameter(description = "ID of the shelf") @PathVariable Long shelfId) {
shelfService.deleteShelf(shelfId);
return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
}
@Operation(summary = "Get books on a shelf", description = "Retrieve all books assigned to a specific shelf.")
@ApiResponse(responseCode = "200", description = "Books returned successfully")
@GetMapping("/{shelfId}/books")
@PreAuthorize("@securityUtil.isShelfOwner(#shelfId)")
public ResponseEntity<List<Book>> getShelfBooks(@PathVariable Long shelfId) {
public ResponseEntity<List<Book>> getShelfBooks(
@Parameter(description = "ID of the shelf") @PathVariable Long shelfId) {
return ResponseEntity.ok(shelfService.getShelfBooks(shelfId));
}
}
@@ -0,0 +1,70 @@
package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.model.dto.TaskInfo;
import com.adityachandel.booklore.model.dto.request.TaskCreateRequest;
import com.adityachandel.booklore.model.dto.request.TaskCronConfigRequest;
import com.adityachandel.booklore.model.dto.response.CronConfig;
import com.adityachandel.booklore.model.dto.response.TaskCancelResponse;
import com.adityachandel.booklore.model.dto.response.TaskCreateResponse;
import com.adityachandel.booklore.model.dto.response.TasksHistoryResponse;
import com.adityachandel.booklore.model.enums.TaskType;
import com.adityachandel.booklore.service.task.TaskCronService;
import com.adityachandel.booklore.service.task.TaskHistoryService;
import com.adityachandel.booklore.service.task.TaskService;
import com.adityachandel.booklore.task.TaskStatus;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@AllArgsConstructor
@RestController
@RequestMapping("/api/v1/tasks")
public class TaskController {
private final TaskService service;
private final TaskHistoryService taskHistoryService;
private final TaskCronService taskCronService;
@GetMapping
@PreAuthorize("@securityUtil.isAdmin()")
public ResponseEntity<List<TaskInfo>> getAvailableTasks() {
List<TaskInfo> taskInfos = service.getAvailableTasks();
return ResponseEntity.ok(taskInfos);
}
@PostMapping("/start")
@PreAuthorize("@securityUtil.isAdmin()")
public ResponseEntity<TaskCreateResponse> startTask(@RequestBody TaskCreateRequest request) {
TaskCreateResponse response = service.runAsUser(request);
if (response.getStatus() == TaskStatus.ACCEPTED) {
return ResponseEntity.status(HttpStatus.ACCEPTED).body(response);
}
return ResponseEntity.ok(response);
}
@DeleteMapping("/{taskId}/cancel")
@PreAuthorize("@securityUtil.isAdmin()")
public ResponseEntity<TaskCancelResponse> cancelTask(@PathVariable String taskId) {
TaskCancelResponse response = service.cancelTask(taskId);
return ResponseEntity.ok(response);
}
@GetMapping("/last")
@PreAuthorize("@securityUtil.isAdmin()")
public ResponseEntity<TasksHistoryResponse> getLatestTasksForEachType() {
TasksHistoryResponse response = taskHistoryService.getLatestTasksForEachType();
return ResponseEntity.ok(response);
}
@PatchMapping("/{taskType}/cron")
@PreAuthorize("@securityUtil.isAdmin()")
public ResponseEntity<CronConfig> patchCronConfig(@PathVariable TaskType taskType, @RequestBody TaskCronConfigRequest request) {
CronConfig response = taskCronService.patchCronConfig(taskType, request);
service.rescheduleTask(taskType);
return ResponseEntity.ok(response);
}
}
@@ -1,47 +0,0 @@
package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.model.dto.request.TaskCreateRequest;
import com.adityachandel.booklore.model.dto.response.TaskCancelResponse;
import com.adityachandel.booklore.model.dto.response.TaskCreateResponse;
import com.adityachandel.booklore.model.dto.response.TaskStatusResponse;
import com.adityachandel.booklore.service.TaskHistoryService;
import com.adityachandel.booklore.service.TaskService;
import com.adityachandel.booklore.task.*;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
@AllArgsConstructor
@RestController
@RequestMapping("/api/v2/tasks")
public class TaskV2Controller {
private final TaskService service;
private final TaskHistoryService taskHistoryService;
@PostMapping
@PreAuthorize("@securityUtil.isAdmin()")
public ResponseEntity<TaskCreateResponse> startTask(@RequestBody TaskCreateRequest request) {
TaskCreateResponse response = service.run(request);
if (response.getStatus() == TaskStatus.ACCEPTED) {
return ResponseEntity.status(HttpStatus.ACCEPTED).body(response);
}
return ResponseEntity.ok(response);
}
@DeleteMapping("/{taskId}")
@PreAuthorize("@securityUtil.isAdmin()")
public ResponseEntity<TaskCancelResponse> cancelTask(@PathVariable String taskId) {
TaskCancelResponse response = service.cancelTask(taskId);
return ResponseEntity.ok(response);
}
@GetMapping("/latest")
@PreAuthorize("@securityUtil.isAdmin()")
public ResponseEntity<TaskStatusResponse> getLatestTasksForEachType() {
TaskStatusResponse response = taskHistoryService.getLatestTasksForEachType();
return ResponseEntity.ok(response);
}
}
@@ -6,6 +6,11 @@ import com.adityachandel.booklore.model.dto.request.UpdateUserSettingRequest;
import com.adityachandel.booklore.model.dto.BookLoreUser;
import com.adityachandel.booklore.model.dto.request.UserUpdateRequest;
import com.adityachandel.booklore.service.user.UserService;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.Parameter;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
@@ -17,56 +22,84 @@ import java.util.List;
@AllArgsConstructor
@RestController
@RequestMapping("/api/v1/users")
@Tag(name = "Users", description = "Endpoints for managing users and their settings")
public class UserController {
private final UserService userService;
@Operation(summary = "Get current user", description = "Retrieve the profile of the currently authenticated user.")
@ApiResponse(responseCode = "200", description = "User profile returned successfully")
@GetMapping("/me")
public ResponseEntity<BookLoreUser> getMyself() {
return ResponseEntity.ok(userService.getMyself());
}
@Operation(summary = "Get user by ID", description = "Retrieve a user's profile by their ID.")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "User profile returned successfully"),
@ApiResponse(responseCode = "403", description = "Forbidden")
})
@GetMapping("/{id}")
@PreAuthorize("@securityUtil.canViewUserProfile(#id)")
public ResponseEntity<BookLoreUser> getUser(@PathVariable Long id) {
public ResponseEntity<BookLoreUser> getUser(
@Parameter(description = "ID of the user") @PathVariable Long id) {
return ResponseEntity.ok(userService.getBookLoreUser(id));
}
@Operation(summary = "Get all users", description = "Retrieve a list of all users. Requires admin.")
@ApiResponse(responseCode = "200", description = "Users returned successfully")
@GetMapping
@PreAuthorize("@securityUtil.isAdmin()")
public ResponseEntity<List<BookLoreUser>> getAllUsers() {
return ResponseEntity.ok(userService.getBookLoreUsers());
}
@Operation(summary = "Update user", description = "Update a user's profile by their ID. Requires admin.")
@ApiResponse(responseCode = "200", description = "User updated successfully")
@PutMapping("/{id}")
@PreAuthorize("@securityUtil.isAdmin()")
public ResponseEntity<BookLoreUser> updateUser(@PathVariable Long id, @Valid @RequestBody UserUpdateRequest updateRequest) {
public ResponseEntity<BookLoreUser> updateUser(
@Parameter(description = "ID of the user") @PathVariable Long id,
@Parameter(description = "User update request") @Valid @RequestBody UserUpdateRequest updateRequest) {
BookLoreUser updatedUser = userService.updateUser(id, updateRequest);
return ResponseEntity.ok(updatedUser);
}
@Operation(summary = "Delete user", description = "Delete a user by their ID. Requires admin.")
@ApiResponse(responseCode = "204", description = "User deleted successfully")
@DeleteMapping("/{id}")
@PreAuthorize("@securityUtil.isAdmin()")
public void deleteUser(@PathVariable Long id) {
public void deleteUser(
@Parameter(description = "ID of the user") @PathVariable Long id) {
userService.deleteUser(id);
}
@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(@RequestBody ChangePasswordRequest request) {
public ResponseEntity<?> changePassword(
@Parameter(description = "Change password request") @RequestBody ChangePasswordRequest request) {
userService.changePassword(request);
return ResponseEntity.ok().build();
}
@Operation(summary = "Change another user's password", description = "Change the password for another user. Requires admin.")
@ApiResponse(responseCode = "200", description = "Password changed successfully")
@PutMapping("/change-user-password")
@PreAuthorize("@securityUtil.isAdmin()")
public ResponseEntity<?> changeUserPassword(@RequestBody ChangeUserPasswordRequest request) {
public ResponseEntity<?> changeUserPassword(
@Parameter(description = "Change user password request") @RequestBody ChangeUserPasswordRequest request) {
userService.changeUserPassword(request);
return ResponseEntity.ok().build();
}
@Operation(summary = "Update user settings", description = "Update settings for the current user.")
@ApiResponse(responseCode = "204", description = "User settings updated successfully")
@PutMapping("/{id}/settings")
@PreAuthorize("@securityUtil.isSelf(#id)")
public void updateUserSetting(@PathVariable Long id, @RequestBody UpdateUserSettingRequest request) {
public void updateUserSetting(
@Parameter(description = "ID of the user") @PathVariable Long id,
@Parameter(description = "Update user setting request") @RequestBody UpdateUserSettingRequest request) {
userService.updateUserSetting(id, request);
}
}
@@ -3,6 +3,9 @@ package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.model.dto.ReleaseNote;
import com.adityachandel.booklore.model.dto.VersionInfo;
import com.adityachandel.booklore.service.VersionService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
@@ -14,15 +17,20 @@ import java.util.List;
@AllArgsConstructor
@RestController
@RequestMapping("/api/v1/version")
@Tag(name = "Version", description = "Endpoints for retrieving application version and changelog")
public class VersionController {
private final VersionService versionService;
@Operation(summary = "Get application version", description = "Retrieve the current application version.")
@ApiResponse(responseCode = "200", description = "Version info returned successfully")
@GetMapping
public ResponseEntity<VersionInfo> getVersionInfo() {
return ResponseEntity.ok(versionService.getVersionInfo());
}
@Operation(summary = "Get changelog since current version", description = "Retrieve the changelog since the current version.")
@ApiResponse(responseCode = "200", description = "Changelog returned successfully")
@GetMapping("/changelog")
public ResponseEntity<List<ReleaseNote>> getChangelogSinceCurrent() {
return ResponseEntity.ok(versionService.getChangelogSinceCurrentVersion());
@@ -51,7 +51,9 @@ public enum ApiError {
UNSUPPORTED_FILE_TYPE(HttpStatus.UNSUPPORTED_MEDIA_TYPE, "%s"),
CONFLICT(HttpStatus.CONFLICT, "%s"),
FILE_NOT_FOUND(HttpStatus.NOT_FOUND, "File not found: %s"),
SHELF_CANNOT_BE_DELETED(HttpStatus.FORBIDDEN, "'%s' shelf can't be deleted" ),;
SHELF_CANNOT_BE_DELETED(HttpStatus.FORBIDDEN, "'%s' shelf can't be deleted" ),
TASK_NOT_FOUND(HttpStatus.NOT_FOUND, "Scheduled task not found: %s"),
TASK_ALREADY_RUNNING(HttpStatus.CONFLICT, "Task is already running: %s"),;
private final HttpStatus status;
private final String message;
@@ -12,5 +12,7 @@ public class MetadataUpdateContext {
private MetadataUpdateWrapper metadataUpdateWrapper;
private boolean updateThumbnail;
private boolean mergeCategories;
private boolean mergeMoods;
private boolean mergeTags;
private MetadataReplaceMode replaceMode;
}
@@ -10,6 +10,9 @@ import lombok.NoArgsConstructor;
import java.util.List;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class BookLoreUser {
private Long id;
private String username;
@@ -0,0 +1,12 @@
package com.adityachandel.booklore.model.dto;
import lombok.Builder;
import lombok.Data;
@Builder
@Data
public class FileMoveResult {
private boolean moved;
private String newFileName;
private String newFileSubPath;
}
@@ -0,0 +1,36 @@
package com.adityachandel.booklore.model.dto;
import com.adityachandel.booklore.model.dto.response.CronConfig;
import com.adityachandel.booklore.model.enums.TaskType;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class TaskInfo {
private TaskType taskType;
private String name;
private String description;
private boolean parallel;
private boolean async;
private boolean cronSupported;
private CronConfig cronConfig;
private String metadata;
public static TaskInfo fromTaskType(TaskType taskType) {
return TaskInfo.builder()
.taskType(taskType)
.name(taskType.getName())
.description(taskType.getDescription())
.parallel(taskType.isParallel())
.async(taskType.isAsync())
.cronSupported(taskType.isCronSupported())
.build();
}
}
@@ -35,4 +35,8 @@ public class BulkMetadataUpdateRequest {
private Set<String> tags;
private boolean clearTags;
private boolean mergeCategories;
private boolean mergeMoods;
private boolean mergeTags;
}
@@ -14,5 +14,6 @@ public class FileMoveRequest {
public static class Move {
private Long bookId;
private Long targetLibraryId;
private Long targetLibraryPathId;
}
}
@@ -1,9 +1,7 @@
package com.adityachandel.booklore.model.dto.request;
import com.adityachandel.booklore.model.enums.TaskType;
import com.adityachandel.booklore.task.tasks.options.ClearCbxCacheOptions;
import com.adityachandel.booklore.task.tasks.options.ClearPdfCacheOptions;
import com.adityachandel.booklore.task.tasks.options.LibraryRescanOptions;
import com.adityachandel.booklore.task.options.LibraryRescanOptions;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
@@ -22,10 +20,8 @@ public class TaskCreateRequest {
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "taskType", include = JsonTypeInfo.As.EXTERNAL_PROPERTY)
@JsonSubTypes({
@JsonSubTypes.Type(value = ClearCbxCacheOptions.class, name = "CLEAR_CBX_CACHE"),
@JsonSubTypes.Type(value = ClearPdfCacheOptions.class, name = "CLEAR_PDF_CACHE"),
@JsonSubTypes.Type(value = LibraryRescanOptions.class, name = "RE_SCAN_LIBRARY"),
@JsonSubTypes.Type(value = MetadataRefreshRequest.class, name = "REFRESH_METADATA"),
@JsonSubTypes.Type(value = LibraryRescanOptions.class, name = "REFRESH_LIBRARY_METADATA"),
@JsonSubTypes.Type(value = MetadataRefreshRequest.class, name = "REFRESH_METADATA_MANUAL"),
})
private Object options;
@@ -0,0 +1,16 @@
package com.adityachandel.booklore.model.dto.request;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class TaskCronConfigRequest {
private String cronExpression;
private Boolean enabled;
}
@@ -0,0 +1,23 @@
package com.adityachandel.booklore.model.dto.response;
import com.adityachandel.booklore.model.enums.TaskType;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDateTime;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class CronConfig {
private Long id;
private TaskType taskType;
private String cronExpression;
private Boolean enabled;
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
}
@@ -9,20 +9,19 @@ import lombok.NoArgsConstructor;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class TaskStatusResponse {
private List<TaskInfo> tasks;
public class TasksHistoryResponse {
private List<TaskHistory> taskHistories;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public static class TaskInfo {
public static class TaskHistory {
private String id;
private TaskType type;
private TaskStatus status;
@@ -31,6 +30,5 @@ public class TaskStatusResponse {
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
private LocalDateTime completedAt;
private Map<String, Object> metadata;
}
}
@@ -8,5 +8,6 @@ import lombok.*;
@NoArgsConstructor
public class PublicAppSetting {
private boolean oidcEnabled;
private boolean remoteAuthEnabled;
private OidcProviderDetails oidcProviderDetails;
}
@@ -27,7 +27,7 @@ public class LibraryEntity {
@Convert(converter = SortConverter.class)
private Sort sort;
@OneToMany(mappedBy = "library", cascade = CascadeType.MERGE, orphanRemoval = true)
@OneToMany(mappedBy = "library", orphanRemoval = true)
private List<BookEntity> bookEntities;
@OneToMany(mappedBy = "library", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER)
@@ -0,0 +1,53 @@
package com.adityachandel.booklore.model.entity;
import com.adityachandel.booklore.model.enums.TaskType;
import jakarta.persistence.*;
import lombok.*;
import java.time.LocalDateTime;
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@Entity
@Table(name = "task_cron_configuration")
public class TaskCronConfigurationEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Enumerated(EnumType.STRING)
@Column(name = "task_type", nullable = false, unique = true)
private TaskType taskType;
@Column(name = "cron_expression", nullable = false)
private String cronExpression;
@Column(name = "enabled", nullable = false)
private Boolean enabled;
@Column(name = "created_by", nullable = false)
private Long createdBy;
@Column(name = "created_at", nullable = false, updatable = false)
private LocalDateTime createdAt;
@Column(name = "updated_at", nullable = false)
private LocalDateTime updatedAt;
@PrePersist
protected void onCreate() {
createdAt = LocalDateTime.now();
updatedAt = LocalDateTime.now();
}
@PreUpdate
protected void onUpdate() {
updatedAt = LocalDateTime.now();
}
}
@@ -16,7 +16,7 @@ import java.util.Map;
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class TaskEntity {
public class TaskHistoryEntity {
@Id
@Column(length = 36)
@@ -54,14 +54,4 @@ public class TaskEntity {
@Convert(converter = JpaJsonConverter.class)
@Column(name = "task_options", columnDefinition = "TEXT")
private Map<String, Object> taskOptions;
@Override
public boolean equals(Object o) {
return this == o || (o instanceof TaskEntity other && id != null && id.equals(other.id));
}
@Override
public int hashCode() {
return id != null ? id.hashCode() : System.identityHashCode(this);
}
}
@@ -4,10 +4,70 @@ import lombok.Getter;
public enum TaskType {
CLEAR_CBX_CACHE(false, false),
CLEAR_PDF_CACHE(false, false),
RE_SCAN_LIBRARY(false, true),
REFRESH_METADATA(false, true);
CLEAR_CBX_CACHE(
false,
false,
true,
false,
"Clear CBX Cache",
"Clears temporarily extracted comic book files used by the reader."
),
CLEAR_PDF_CACHE(
false,
false,
true,
false,
"Clear PDF Cache",
"Clears temporarily generated images used by the streaming PDF reader."
),
REFRESH_LIBRARY_METADATA(
false,
true,
false,
false,
"Refresh Metadata",
"Re-reads book information (title, author, cover, etc.) from your files and updates the Booklore database."
),
UPDATE_BOOK_RECOMMENDATIONS(
false,
true,
true,
false,
"Update Book Recommendations",
"Analyzes your library to generate personalized book recommendations based on the books you own."
),
CLEANUP_DELETED_BOOKS(
false,
false,
true,
false,
"Cleanup Deleted Books",
"Permanently removes database entries for books you previously deleted from your libraries."
),
SYNC_LIBRARY_FILES(
false,
false,
true,
false,
"Sync Library Files",
"Scans your library folders to detect new books and removes entries for files that no longer exist."
),
CLEANUP_TEMP_METADATA(
false,
false,
true,
false,
"Cleanup Temporary Metadata",
"Removes temporary metadata files created during the bookdrop and manual metadata review processes."
),
REFRESH_METADATA_MANUAL(
false,
true,
false,
true,
"Refresh Metadata",
"Updates metadata information for your selected books."
);
@Getter
private final boolean parallel;
@@ -15,8 +75,24 @@ public enum TaskType {
@Getter
private final boolean async;
TaskType(boolean parallel, boolean async) {
@Getter
private final boolean cronSupported;
@Getter
private final boolean hiddenFromUI;
@Getter
private final String name;
@Getter
private final String description;
TaskType(boolean parallel, boolean async, boolean cronSupported, boolean hiddenFromUI, String name, String description) {
this.parallel = parallel;
this.async = async;
this.cronSupported = cronSupported;
this.hiddenFromUI = hiddenFromUI;
this.name = name;
this.description = description;
}
}
@@ -7,6 +7,7 @@ import lombok.Getter;
@AllArgsConstructor
public enum Topic {
BOOK_ADD("/queue/book-add"),
BOOK_UPDATE("/queue/book-update"),
BOOKS_REMOVE("/queue/books-remove"),
BOOK_METADATA_UPDATE("/queue/book-metadata-update"),
BOOK_METADATA_BATCH_UPDATE("/queue/book-metadata-batch-update"),
@@ -1,11 +1,13 @@
package com.adityachandel.booklore.repository;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
import jakarta.transaction.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.*;
import org.springframework.data.repository.query.Param;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Repository;
import java.time.Instant;
@@ -61,19 +63,10 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpec
@Query("SELECT b FROM BookEntity b WHERE b.library.id IN :libraryIds AND (b.deleted IS NULL OR b.deleted = false)")
List<BookEntity> findAllWithMetadataByLibraryIds(@Param("libraryIds") Collection<Long> libraryIds);
@EntityGraph(attributePaths = {"metadata", "shelves", "libraryPath"})
@Query(value = "SELECT b FROM BookEntity b WHERE b.library.id IN :libraryIds AND (b.deleted IS NULL OR b.deleted = false)")
Page<BookEntity> findAllWithMetadataByLibraryIds(@Param("libraryIds") Collection<Long> libraryIds, Pageable pageable);
@EntityGraph(attributePaths = {"metadata", "shelves", "libraryPath"})
@Query("SELECT DISTINCT b FROM BookEntity b JOIN b.shelves s WHERE s.id = :shelfId AND (b.deleted IS NULL OR b.deleted = false)")
List<BookEntity> findAllWithMetadataByShelfId(@Param("shelfId") Long shelfId);
@EntityGraph(attributePaths = {"metadata", "shelves", "libraryPath"})
@Query(value = "SELECT DISTINCT b FROM BookEntity b JOIN b.shelves s WHERE s.id = :shelfId AND (b.deleted IS NULL OR b.deleted = false)",
countQuery = "SELECT COUNT(DISTINCT b.id) FROM BookEntity b JOIN b.shelves s WHERE s.id = :shelfId AND (b.deleted IS NULL OR b.deleted = false)")
Page<BookEntity> findAllWithMetadataByShelfId(@Param("shelfId") Long shelfId, Pageable pageable);
@EntityGraph(attributePaths = {"metadata", "shelves", "libraryPath"})
@Query("SELECT b FROM BookEntity b WHERE b.fileSizeKb IS NULL AND (b.deleted IS NULL OR b.deleted = false)")
List<BookEntity> findAllWithMetadataByFileSizeKbIsNull();
@@ -112,39 +105,27 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpec
""")
Page<BookEntity> searchByMetadata(@Param("text") String text, Pageable pageable);
@Query(value = """
SELECT DISTINCT b FROM BookEntity b
LEFT JOIN b.metadata m
LEFT JOIN m.authors a
WHERE (b.deleted IS NULL OR b.deleted = false)
AND b.library.id IN :libraryIds
AND (
LOWER(m.title) LIKE LOWER(CONCAT('%', :text, '%'))
OR LOWER(m.seriesName) LIKE LOWER(CONCAT('%', :text, '%'))
OR LOWER(a.name) LIKE LOWER(CONCAT('%', :text, '%'))
)
""",
countQuery = """
SELECT COUNT(DISTINCT b.id) FROM BookEntity b
LEFT JOIN b.metadata m
LEFT JOIN m.authors a
WHERE (b.deleted IS NULL OR b.deleted = false)
AND b.library.id IN :libraryIds
AND (
LOWER(m.title) LIKE LOWER(CONCAT('%', :text, '%'))
OR LOWER(m.seriesName) LIKE LOWER(CONCAT('%', :text, '%'))
OR LOWER(a.name) LIKE LOWER(CONCAT('%', :text, '%'))
)
""")
Page<BookEntity> searchByMetadataAndLibraryIds(@Param("text") String text, @Param("libraryIds") Collection<Long> libraryIds, Pageable pageable);
@Modifying
@Transactional
@Query("DELETE FROM BookEntity b WHERE b.deletedAt IS NOT NULL AND b.deletedAt < :cutoff")
int deleteAllByDeletedAtBefore(Instant cutoff);
@Query("DELETE FROM BookEntity b WHERE b.deleted IS TRUE")
int deleteAllSoftDeleted();
@Query("SELECT COUNT(b) FROM BookEntity b WHERE b.deleted = TRUE")
long countAllSoftDeleted();
@Modifying
@Transactional
@Query("UPDATE BookEntity b SET b.library.id = :libraryId WHERE b.id = :bookId")
void updateLibraryId(@Param("bookId") Long bookId, @Param("libraryId") Long libraryId);
@Query("""
UPDATE BookEntity b
SET b.fileSubPath = :fileSubPath,
b.fileName = :fileName,
b.library.id = :libraryId,
b.libraryPath = :libraryPath
WHERE b.id = :bookId
""")
void updateFileAndLibrary(
@Param("bookId") Long bookId,
@Param("fileSubPath") String fileSubPath,
@Param("fileName") String fileName,
@Param("libraryId") Long libraryId,
@Param("libraryPath") LibraryPathEntity libraryPath);
}
@@ -13,6 +13,9 @@ public interface MetadataFetchJobRepository extends JpaRepository<MetadataFetchJ
int deleteAllByCompletedAtBefore(Instant cutoff);
@Query("SELECT COUNT(m) FROM MetadataFetchJobEntity m")
long countAll();
@Query("SELECT DISTINCT t FROM MetadataFetchJobEntity t LEFT JOIN FETCH t.proposals")
List<MetadataFetchJobEntity> findAllWithProposals();
}
@@ -0,0 +1,18 @@
package com.adityachandel.booklore.repository;
import com.adityachandel.booklore.model.entity.TaskCronConfigurationEntity;
import com.adityachandel.booklore.model.enums.TaskType;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
@Repository
public interface TaskCronConfigurationRepository extends JpaRepository<TaskCronConfigurationEntity, Long> {
Optional<TaskCronConfigurationEntity> findByTaskType(TaskType taskType);
List<TaskCronConfigurationEntity> findByEnabledTrue();
}
@@ -0,0 +1,17 @@
package com.adityachandel.booklore.repository;
import com.adityachandel.booklore.model.entity.TaskHistoryEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface TaskHistoryRepository extends JpaRepository<TaskHistoryEntity, String> {
@Query("SELECT t FROM TaskHistoryEntity t WHERE t.createdAt = " +
"(SELECT MAX(t2.createdAt) FROM TaskHistoryEntity t2 WHERE t2.type = t.type) " +
"ORDER BY t.createdAt DESC")
List<TaskHistoryEntity> findLatestTaskForEachType();
}
@@ -1,17 +0,0 @@
package com.adityachandel.booklore.repository;
import com.adityachandel.booklore.model.entity.TaskEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface TaskRepository extends JpaRepository<TaskEntity, String> {
@Query("SELECT t FROM TaskEntity t WHERE t.createdAt = " +
"(SELECT MAX(t2.createdAt) FROM TaskEntity t2 WHERE t2.type = t.type) " +
"ORDER BY t.createdAt DESC")
List<TaskEntity> findLatestTaskForEachType();
}
@@ -12,6 +12,8 @@ public interface UserRepository extends JpaRepository<BookLoreUserEntity, Long>
Optional<BookLoreUserEntity> findByUsername(String username);
Optional<BookLoreUserEntity> findByEmail(String email);
Optional<BookLoreUserEntity> findById(Long id);
List<BookLoreUserEntity> findAllByLibraries_Id(Long libraryId);
@@ -1,88 +0,0 @@
package com.adityachandel.booklore.service;
import com.adityachandel.booklore.model.enums.TaskType;
import com.adityachandel.booklore.util.FileService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;
@Service
@RequiredArgsConstructor
@Slf4j
public class TaskMetadataService {
private final FileService fileService;
public Map<String, Object> getMetadataForTaskType(TaskType taskType) {
Map<String, Object> metadata = new HashMap<>();
switch (taskType) {
case CLEAR_CBX_CACHE:
metadata.putAll(getCacheMetadata(fileService.getCbxCachePath(), "CBX"));
break;
case CLEAR_PDF_CACHE:
metadata.putAll(getCacheMetadata(fileService.getPdfCachePath(), "PDF"));
break;
default:
break;
}
return metadata;
}
private Map<String, Object> getCacheMetadata(String cachePathStr, String cacheType) {
Map<String, Object> metadata = new HashMap<>();
try {
Path cachePath = Paths.get(cachePathStr);
if (Files.exists(cachePath) && Files.isDirectory(cachePath)) {
long sizeInBytes = calculateDirectorySize(cachePath);
String formattedSize = formatBytes(sizeInBytes);
metadata.put("currentCacheSize", formattedSize);
metadata.put("currentCacheSizeBytes", sizeInBytes);
} else {
metadata.put("currentCacheSize", "0 B");
metadata.put("currentCacheSizeBytes", 0L);
}
} catch (Exception e) {
log.error("Error calculating {} cache size", cacheType, e);
metadata.put("currentCacheSize", "Unknown");
metadata.put("currentCacheSizeBytes", -1L);
}
return metadata;
}
private long calculateDirectorySize(Path path) throws IOException {
try (Stream<Path> walk = Files.walk(path)) {
return walk
.filter(Files::isRegularFile)
.mapToLong(p -> {
try {
return Files.size(p);
} catch (IOException e) {
log.warn("Could not get size of file: {}", p, e);
return 0L;
}
})
.sum();
}
}
private String formatBytes(long bytes) {
if (bytes < 1024) return bytes + " B";
int exp = (int) (Math.log(bytes) / Math.log(1024));
String pre = "KMGTPE".charAt(exp - 1) + "";
return String.format("%.1f %sB", bytes / Math.pow(1024, exp), pre);
}
}
@@ -73,6 +73,7 @@ public class AppSettingService {
PublicAppSetting.PublicAppSettingBuilder builder = PublicAppSetting.builder();
builder.oidcEnabled(Boolean.parseBoolean(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.OIDC_ENABLED, "false")));
builder.remoteAuthEnabled(appProperties.getRemoteAuth().isEnabled());
builder.oidcProviderDetails(settingPersistenceHelper.getJsonSetting(settingsMap, AppSettingKey.OIDC_PROVIDER_DETAILS, OidcProviderDetails.class, null, false));
return builder.build();
@@ -111,4 +112,4 @@ public class AppSettingService {
return builder.build();
}
}
}
@@ -1,4 +1,4 @@
package com.adityachandel.booklore.service;
package com.adityachandel.booklore.service.book;
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
import com.adityachandel.booklore.model.entity.*;
@@ -9,8 +9,6 @@ import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.nio.file.Files;
import java.time.Instant;
import java.util.*;
@@ -1,4 +1,4 @@
package com.adityachandel.booklore.service;
package com.adityachandel.booklore.service.book;
import com.adityachandel.booklore.exception.ApiError;
import com.adityachandel.booklore.model.dto.settings.KoboSettings;
@@ -13,6 +13,7 @@ import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
@@ -23,6 +24,7 @@ import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@@ -51,10 +53,15 @@ public class BookDownloadService {
InputStream inputStream = new FileInputStream(bookFile);
InputStreamResource resource = new InputStreamResource(inputStream);
String contentDisposition = ContentDisposition.builder("attachment")
.filename(file.getFileName().toString(), StandardCharsets.UTF_8)
.build()
.toString();
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.contentLength(bookFile.length())
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFileName() + "\"")
.header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition)
.header(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate")
.header(HttpHeaders.PRAGMA, "no-cache")
.header(HttpHeaders.EXPIRES, "0")
@@ -106,7 +113,11 @@ public class BookDownloadService {
private void setResponseHeaders(HttpServletResponse response, File file) {
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
response.setContentLengthLong(file.length());
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getName() + "\"");
String contentDisposition = ContentDisposition.builder("attachment")
.filename(file.getName(), StandardCharsets.UTF_8)
.build()
.toString();
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, contentDisposition);
}
private void streamFileToResponse(File file, HttpServletResponse response) throws IOException {
@@ -1,4 +1,4 @@
package com.adityachandel.booklore.service;
package com.adityachandel.booklore.service.book;
import com.adityachandel.booklore.config.security.service.AuthenticationService;
import com.adityachandel.booklore.exception.ApiError;
@@ -1,4 +1,4 @@
package com.adityachandel.booklore.service;
package com.adityachandel.booklore.service.book;
import com.adityachandel.booklore.mapper.v2.BookMapperV2;
import com.adityachandel.booklore.model.dto.Book;
@@ -24,12 +24,6 @@ public class BookQueryService {
return mapBooksToDto(books, includeDescription, null);
}
public Page<Book> getAllBooksPage(boolean includeDescription, int page, int size) {
Pageable pageable = PageRequest.of(Math.max(page - 1, 0), size);
Page<BookEntity> books = bookRepository.findAllWithMetadata(pageable);
return createPageFromBooks(books, pageable, includeDescription, null);
}
public List<Book> getAllBooksByLibraryIds(Set<Long> libraryIds, boolean includeDescription, Long userId) {
List<BookEntity> books = bookRepository.findAllWithMetadataByLibraryIds(libraryIds);
return mapBooksToDto(books, includeDescription, userId);
@@ -48,27 +42,10 @@ public class BookQueryService {
return bookRepository.findAllFullBooks();
}
public Page<Book> searchBooksByMetadataPage(String text, int page, int size) {
Pageable pageable = PageRequest.of(Math.max(page - 1, 0), size);
Page<BookEntity> books = bookRepository.searchByMetadata(text, pageable);
List<Book> mapped = books.getContent().stream()
.map(bookMapperV2::toDTO)
.collect(Collectors.toList());
return new PageImpl<>(mapped, pageable, books.getTotalElements());
}
public void saveAll(List<BookEntity> books) {
bookRepository.saveAll(books);
}
public List<Book> searchBooksByMetadata(String text) {
Pageable pageable = PageRequest.of(0, Integer.MAX_VALUE);
Page<BookEntity> books = bookRepository.searchByMetadata(text, pageable);
return books.getContent().stream()
.map(bookMapperV2::toDTO)
.collect(Collectors.toList());
}
private List<Book> mapBooksToDto(List<BookEntity> books, boolean includeDescription, Long userId) {
return books.stream()
.map(book -> mapBookToDto(book, includeDescription, userId))
@@ -90,9 +67,4 @@ public class BookQueryService {
return dto;
}
private Page<Book> createPageFromBooks(Page<BookEntity> books, Pageable pageable, boolean includeDescription, Long userId) {
List<Book> mapped = mapBooksToDto(books.getContent(), includeDescription, userId);
return new PageImpl<>(mapped, pageable, books.getTotalElements());
}
}
@@ -1,4 +1,4 @@
package com.adityachandel.booklore.service;
package com.adityachandel.booklore.service.book;
import com.adityachandel.booklore.config.security.service.AuthenticationService;
import com.adityachandel.booklore.exception.ApiError;
@@ -1,4 +1,4 @@
package com.adityachandel.booklore.service;
package com.adityachandel.booklore.service.book;
import com.adityachandel.booklore.config.security.service.AuthenticationService;
import com.adityachandel.booklore.exception.ApiError;
@@ -15,6 +15,7 @@ import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.model.enums.ReadStatus;
import com.adityachandel.booklore.model.enums.ResetProgressType;
import com.adityachandel.booklore.repository.*;
import com.adityachandel.booklore.service.user.UserProgressService;
import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService;
import com.adityachandel.booklore.util.FileService;
import com.adityachandel.booklore.util.FileUtils;
@@ -1,4 +1,4 @@
package com.adityachandel.booklore.service;
package com.adityachandel.booklore.service.file;
import com.adityachandel.booklore.mapper.AdditionalFileMapper;
import com.adityachandel.booklore.model.dto.AdditionalFile;
@@ -10,6 +10,7 @@ import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
@@ -17,6 +18,7 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
@@ -78,9 +80,14 @@ public class AdditionalFileService {
Resource resource = new UrlResource(filePath.toUri());
String contentDisposition = ContentDisposition.builder("attachment")
.filename(file.getFileName(), StandardCharsets.UTF_8)
.build()
.toString();
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFileName() + "\"")
.header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition)
.body(resource);
}
}
@@ -1,4 +1,4 @@
package com.adityachandel.booklore.service;
package com.adityachandel.booklore.service.file;
import com.adityachandel.booklore.model.dto.UploadResponse;
import com.adityachandel.booklore.util.FileService;
@@ -1,4 +1,4 @@
package com.adityachandel.booklore.service;
package com.adityachandel.booklore.service.file;
import java.io.IOException;
import java.io.RandomAccessFile;
@@ -0,0 +1,145 @@
package com.adityachandel.booklore.service.file;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.LibraryEntity;
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService;
import com.adityachandel.booklore.util.PathPatternResolver;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.HashSet;
import java.util.Set;
@Slf4j
@Component
@AllArgsConstructor
public class FileMoveHelper {
private final MonitoringRegistrationService monitoringRegistrationService;
private final AppSettingService appSettingService;
public void moveFile(Path source, Path target) throws IOException {
if (target.getParent() != null) {
Files.createDirectories(target.getParent());
}
log.info("Moving file from {} to {}", source, target);
Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);
}
public String extractSubPath(Path filePath, LibraryPathEntity libraryPathEntity) {
Path libraryRoot = Paths.get(libraryPathEntity.getPath()).toAbsolutePath().normalize();
Path parentDir = filePath.getParent().toAbsolutePath().normalize();
Path relativeSubPath = libraryRoot.relativize(parentDir);
return relativeSubPath.toString().replace('\\', '/');
}
public void unregisterLibrary(Long libraryId) {
monitoringRegistrationService.unregisterLibrary(libraryId);
}
public void registerLibraryPaths(Long libraryId, Path libraryRoot) {
monitoringRegistrationService.registerLibraryPaths(libraryId, libraryRoot);
}
public String getFileNamingPattern(LibraryEntity library) {
String pattern = library.getFileNamingPattern();
if (pattern == null || pattern.trim().isEmpty()) {
try {
pattern = appSettingService.getAppSettings().getUploadPattern();
log.debug("Using default pattern for library {} as no custom pattern is set", library.getName());
} catch (Exception e) {
log.warn("Failed to get default upload pattern for library {}: {}", library.getName(), e.getMessage());
}
}
if (pattern == null || pattern.trim().isEmpty()) {
pattern = "{currentFilename}";
log.info("No file naming pattern available for library {}. Using fallback pattern: {currentFilename}", library.getName());
}
if (pattern.endsWith("/") || pattern.endsWith("\\")) {
pattern += "{currentFilename}";
}
return pattern;
}
public Path generateNewFilePath(BookEntity book, LibraryPathEntity libraryPathEntity, String pattern) {
String newRelativePathStr = PathPatternResolver.resolvePattern(book, pattern);
if (newRelativePathStr.startsWith("/") || newRelativePathStr.startsWith("\\")) {
newRelativePathStr = newRelativePathStr.substring(1);
}
String path = libraryPathEntity.getPath();
return Paths.get(path, newRelativePathStr);
}
public void deleteEmptyParentDirsUpToLibraryFolders(Path currentDir, Set<Path> libraryRoots) throws IOException {
Set<String> ignoredFilenames = Set.of(".DS_Store", "Thumbs.db");
currentDir = currentDir.toAbsolutePath().normalize();
Set<Path> normalizedRoots = new HashSet<>();
for (Path root : libraryRoots) {
normalizedRoots.add(root.toAbsolutePath().normalize());
}
while (currentDir != null) {
if (isLibraryRoot(currentDir, normalizedRoots)) {
break;
}
File[] files = currentDir.toFile().listFiles();
if (files == null) {
log.warn("Cannot read directory: {}. Stopping cleanup.", currentDir);
break;
}
if (hasOnlyIgnoredFiles(files, ignoredFilenames)) {
deleteIgnoredFilesAndDirectory(files, currentDir);
currentDir = currentDir.getParent();
} else {
break;
}
}
}
private boolean isLibraryRoot(Path currentDir, Set<Path> normalizedRoots) {
for (Path root : normalizedRoots) {
try {
if (Files.isSameFile(root, currentDir)) {
return true;
}
} catch (IOException e) {
log.warn("Failed to compare paths: {} and {}", root, currentDir);
}
}
return false;
}
private boolean hasOnlyIgnoredFiles(File[] files, Set<String> ignoredFilenames) {
for (File file : files) {
if (!ignoredFilenames.contains(file.getName())) {
return false;
}
}
return true;
}
private void deleteIgnoredFilesAndDirectory(File[] files, Path currentDir) {
for (File file : files) {
try {
Files.delete(file.toPath());
log.info("Deleted ignored file: {}", file.getAbsolutePath());
} catch (IOException e) {
log.warn("Failed to delete ignored file: {}", file.getAbsolutePath());
}
}
try {
Files.delete(currentDir);
log.info("Deleted empty directory: {}", currentDir);
} catch (IOException e) {
log.warn("Failed to delete directory: {}", currentDir, e);
}
}
}
@@ -1,182 +1,155 @@
package com.adityachandel.booklore.service.file;
import com.adityachandel.booklore.mapper.BookMapper;
import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.mapper.LibraryMapper;
import com.adityachandel.booklore.model.dto.FileMoveResult;
import com.adityachandel.booklore.model.dto.request.FileMoveRequest;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.LibraryEntity;
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
import com.adityachandel.booklore.model.websocket.Topic;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.service.BookQueryService;
import com.adityachandel.booklore.repository.LibraryRepository;
import com.adityachandel.booklore.service.NotificationService;
import com.adityachandel.booklore.util.PathPatternResolver;
import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService;
import jakarta.persistence.EntityManager;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;
import static com.adityachandel.booklore.model.enums.PermissionType.ADMIN;
import static com.adityachandel.booklore.model.enums.PermissionType.MANIPULATE_LIBRARY;
@Slf4j
@Service
@AllArgsConstructor
@Service
@Slf4j
public class FileMoveService {
private static final int BATCH_SIZE = 100;
private final BookQueryService bookQueryService;
private final BookRepository bookRepository;
private final LibraryRepository libraryRepository;
private final FileMoveHelper fileMoveHelper;
private final MonitoringRegistrationService monitoringRegistrationService;
private final LibraryMapper libraryMapper;
private final BookMapper bookMapper;
private final NotificationService notificationService;
private final UnifiedFileMoveService unifiedFileMoveService;
private final EntityManager entityManager;
@Transactional
public void moveFiles(FileMoveRequest request) {
List<Long> bookIds = request.getBookIds().stream().toList();
List<FileMoveRequest.Move> moves = request.getMoves() != null ? request.getMoves() : List.of();
public void bulkMoveFiles(FileMoveRequest request) {
List<FileMoveRequest.Move> moves = request.getMoves();
Set<Long> targetLibraryIds = moves.stream().map(FileMoveRequest.Move::getTargetLibraryId).collect(Collectors.toSet());
Set<Long> sourceLibraryIds = new HashSet<>();
monitoringRegistrationService.unregisterLibraries(targetLibraryIds);
log.info("Moving {} books with {} specific moves in batches of {}", bookIds.size(), moves.size(), BATCH_SIZE);
for (FileMoveRequest.Move move : moves) {
Long bookId = move.getBookId();
Long targetLibraryId = move.getTargetLibraryId();
Long targetLibraryPathId = move.getTargetLibraryPathId();
Map<Long, Long> bookToTargetLibraryMap = moves.stream()
.collect(Collectors.toMap(
FileMoveRequest.Move::getBookId,
FileMoveRequest.Move::getTargetLibraryId
));
Map<Long, List<Book>> libraryRemovals = new HashMap<>();
Map<Long, List<Book>> libraryAdditions = new HashMap<>();
List<Book> allUpdatedBooks = new ArrayList<>();
int totalProcessed = 0;
int offset = 0;
while (offset < bookIds.size()) {
log.info("Processing batch {}/{}", (offset / BATCH_SIZE) + 1, (bookIds.size() + BATCH_SIZE - 1) / BATCH_SIZE);
List<Long> batchBookIds = bookIds.subList(offset, Math.min(offset + BATCH_SIZE, bookIds.size()));
Set<Long> batchBookIdSet = new HashSet<>(batchBookIds);
List<BookEntity> batchBooks = bookQueryService.findWithMetadataByIdsWithPagination(batchBookIdSet, offset, BATCH_SIZE);
if (batchBooks.isEmpty()) {
log.info("No more books at offset {}", offset);
break;
}
List<Book> batchUpdatedBooks = processBookChunk(batchBooks, bookToTargetLibraryMap, libraryRemovals, libraryAdditions);
allUpdatedBooks.addAll(batchUpdatedBooks);
totalProcessed += batchBooks.size();
offset += BATCH_SIZE;
log.info("Processed {}/{} books", totalProcessed, bookIds.size());
}
log.info("Move completed: {} books processed, {} updated", totalProcessed, allUpdatedBooks.size());
sendUpdateNotifications(allUpdatedBooks);
sendCrossLibraryMoveNotifications(libraryRemovals, libraryAdditions);
}
public String generatePathFromPattern(BookEntity book, String pattern) {
return PathPatternResolver.resolvePattern(book, pattern);
}
private List<Book> processBookChunk(List<BookEntity> books, Map<Long, Long> bookToTargetLibraryMap, Map<Long, List<Book>> libraryRemovals, Map<Long, List<Book>> libraryAdditions) {
List<Book> updatedBooks = new ArrayList<>();
Map<Long, Long> originalLibraryIds = new HashMap<>();
for (BookEntity book : books) {
if (book.getLibraryPath() != null && book.getLibraryPath().getLibrary() != null) {
originalLibraryIds.put(book.getId(), book.getLibraryPath().getLibrary().getId());
}
}
unifiedFileMoveService.moveBatchBookFiles(books, bookToTargetLibraryMap, new UnifiedFileMoveService.BatchMoveCallback() {
@Override
public void onBookMoved(BookEntity book) {
Long targetLibraryId = bookToTargetLibraryMap.get(book.getId());
Long originalSourceLibraryId = originalLibraryIds.get(book.getId());
log.debug("Processing moved book {}: targetLibraryId={}, originalSourceLibraryId={}", book.getId(), targetLibraryId, originalSourceLibraryId);
if (targetLibraryId != null && originalSourceLibraryId != null && !targetLibraryId.equals(originalSourceLibraryId)) {
log.info("Cross-library move detected for book {}: {} -> {}", book.getId(), originalSourceLibraryId, targetLibraryId);
Book bookDtoForRemoval = bookMapper.toBookWithDescription(book, false);
bookDtoForRemoval.setLibraryId(originalSourceLibraryId);
libraryRemovals.computeIfAbsent(originalSourceLibraryId, k -> new ArrayList<>()).add(bookDtoForRemoval);
log.debug("Added book {} to removal list for library {}", book.getId(), originalSourceLibraryId);
bookRepository.updateLibraryId(book.getId(), targetLibraryId);
log.debug("Updated library_id for book {} to {}", book.getId(), targetLibraryId);
BookEntity savedBook = bookRepository.saveAndFlush(book);
Book updatedBookDto = bookMapper.toBookWithDescription(savedBook, false);
updatedBookDto.setLibraryId(targetLibraryId);
libraryAdditions.computeIfAbsent(targetLibraryId, k -> new ArrayList<>()).add(updatedBookDto);
log.debug("Added book {} to addition list for library {} with libraryId {}", book.getId(), targetLibraryId, updatedBookDto.getLibraryId());
updatedBooks.add(updatedBookDto);
} else {
log.debug("Same library move for book {} or no target specified. Target: {}, Original: {}", book.getId(), targetLibraryId, originalSourceLibraryId);
BookEntity savedBook = bookRepository.save(book);
updatedBooks.add(bookMapper.toBook(savedBook));
}
}
@Override
public void onBookMoveFailed(BookEntity book, Exception error) {
log.error("Move failed for book {}: {}", book.getId(), error.getMessage(), error);
throw new RuntimeException("File move failed for book id " + book.getId(), error);
}
});
log.info("Processed {} books, {} library removals tracked, {} library additions tracked", updatedBooks.size(), libraryRemovals.size(), libraryAdditions.size());
return updatedBooks;
}
private void sendUpdateNotifications(List<Book> updatedBooks) {
if (!updatedBooks.isEmpty()) {
notificationService.sendMessage(Topic.BOOK_METADATA_BATCH_UPDATE, updatedBooks);
}
}
private void sendCrossLibraryMoveNotifications(Map<Long, List<Book>> libraryRemovals, Map<Long, List<Book>> libraryAdditions) {
log.info("Sending cross-library move notifications: {} removals, {} additions",
libraryRemovals.size(), libraryAdditions.size());
for (Map.Entry<Long, List<Book>> entry : libraryRemovals.entrySet()) {
List<Long> removedBookIds = entry.getValue().stream()
.map(Book::getId)
.collect(Collectors.toList());
log.info("Notifying removal of {} books from library {}: {}", removedBookIds.size(), entry.getKey(), removedBookIds);
try {
notificationService.sendMessageToPermissions(Topic.BOOKS_REMOVE, removedBookIds, Set.of(ADMIN, MANIPULATE_LIBRARY));
log.info("Successfully sent removal notification for library {}", entry.getKey());
} catch (Exception e) {
log.error("Failed to send removal notification for library {}: {}", entry.getKey(), e.getMessage(), e);
}
}
for (Map.Entry<Long, List<Book>> entry : libraryAdditions.entrySet()) {
List<Book> addedBooks = entry.getValue();
log.info("Notifying addition of {} books to library {}", addedBooks.size(), entry.getKey());
try {
for (Book book : addedBooks) {
log.debug("Sending BOOK_ADD notification for book {} to library {}", book.getId(), entry.getKey());
notificationService.sendMessageToPermissions(Topic.BOOK_ADD, book, Set.of(ADMIN, MANIPULATE_LIBRARY));
Optional<BookEntity> optionalBook = bookRepository.findById(bookId);
Optional<LibraryEntity> optionalLibrary = libraryRepository.findById(targetLibraryId);
if (optionalBook.isEmpty() || optionalLibrary.isEmpty()) {
continue;
}
log.info("Successfully sent {} addition notifications for library {}", addedBooks.size(), entry.getKey());
BookEntity bookEntity = optionalBook.get();
LibraryEntity targetLibrary = optionalLibrary.get();
Optional<LibraryPathEntity> optionalLibraryPathEntity = targetLibrary.getLibraryPaths().stream().filter(l -> Objects.equals(l.getId(), targetLibraryPathId)).findFirst();
if (optionalLibraryPathEntity.isEmpty()) {
continue;
}
LibraryPathEntity libraryPathEntity = optionalLibraryPathEntity.get();
LibraryEntity sourceLibrary = bookEntity.getLibrary();
if (sourceLibrary.getId().equals(targetLibrary.getId())) {
continue;
}
if (!sourceLibraryIds.contains(sourceLibrary.getId())) {
monitoringRegistrationService.unregisterLibraries(Collections.singleton(sourceLibrary.getId()));
sourceLibraryIds.add(sourceLibrary.getId());
}
Path currentFilePath = bookEntity.getFullFilePath();
String pattern = fileMoveHelper.getFileNamingPattern(targetLibrary);
Path newFilePath = fileMoveHelper.generateNewFilePath(bookEntity, libraryPathEntity, pattern);
if (currentFilePath.equals(newFilePath)) {
continue;
}
fileMoveHelper.moveFile(currentFilePath, newFilePath);
String newFileName = newFilePath.getFileName().toString();
String newFileSubPath = fileMoveHelper.extractSubPath(newFilePath, libraryPathEntity);
bookRepository.updateFileAndLibrary(bookEntity.getId(), newFileSubPath, newFileName, targetLibrary.getId(), libraryPathEntity);
Path libraryRoot = Paths.get(bookEntity.getLibraryPath().getPath()).toAbsolutePath().normalize();
fileMoveHelper.deleteEmptyParentDirsUpToLibraryFolders(currentFilePath.getParent(), Set.of(libraryRoot));
entityManager.clear();
BookEntity fresh = bookRepository.findById(bookId).orElseThrow();
notificationService.sendMessage(Topic.BOOK_UPDATE, bookMapper.toBookWithDescription(fresh, false));
} catch (Exception e) {
log.error("Failed to send addition notifications for library {}: {}", entry.getKey(), e.getMessage(), e);
log.error("Error moving file for book ID {}: {}", bookId, e.getMessage(), e);
}
}
for (Long libraryId : targetLibraryIds) {
Optional<LibraryEntity> optionalLibrary = libraryRepository.findById(libraryId);
optionalLibrary.ifPresent(library -> {
monitoringRegistrationService.registerLibrary(libraryMapper.toLibrary(library));
});
}
for (Long libraryId : sourceLibraryIds) {
Optional<LibraryEntity> optionalLibrary = libraryRepository.findById(libraryId);
optionalLibrary.ifPresent(library -> {
monitoringRegistrationService.registerLibrary(libraryMapper.toLibrary(library));
});
}
}
@Transactional
public FileMoveResult moveSingleFile(BookEntity bookEntity) {
Long libraryId = bookEntity.getLibraryPath().getLibrary().getId();
Path libraryRoot = Paths.get(bookEntity.getLibraryPath().getPath()).toAbsolutePath().normalize();
try {
String pattern = fileMoveHelper.getFileNamingPattern(bookEntity.getLibraryPath().getLibrary());
Path currentFilePath = bookEntity.getFullFilePath();
Path expectedFilePath = fileMoveHelper.generateNewFilePath(bookEntity, bookEntity.getLibraryPath(), pattern);
if (currentFilePath.equals(expectedFilePath)) {
return FileMoveResult.builder().moved(false).build();
}
log.info("File for book ID {} needs to be moved from {} to {} to match library pattern", bookEntity.getId(), currentFilePath, expectedFilePath);
fileMoveHelper.unregisterLibrary(libraryId);
fileMoveHelper.moveFile(currentFilePath, expectedFilePath);
fileMoveHelper.deleteEmptyParentDirsUpToLibraryFolders(currentFilePath.getParent(), Set.of(libraryRoot));
String newFileName = expectedFilePath.getFileName().toString();
String newFileSubPath = fileMoveHelper.extractSubPath(expectedFilePath, bookEntity.getLibraryPath());
return FileMoveResult.builder()
.moved(true)
.newFileName(newFileName)
.newFileSubPath(newFileSubPath)
.build();
} catch (Exception e) {
log.error("Failed to move file for book ID {}: {}", bookEntity.getId(), e.getMessage(), e);
} finally {
fileMoveHelper.registerLibraryPaths(libraryId, libraryRoot);
}
return FileMoveResult.builder().moved(false).build();
}
}
@@ -1,12 +1,7 @@
package com.adityachandel.booklore.service.file;
import com.adityachandel.booklore.model.dto.BookMetadata;
import com.adityachandel.booklore.model.entity.BookAdditionalFileEntity;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.LibraryEntity;
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
import com.adityachandel.booklore.repository.LibraryPathRepository;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import com.adityachandel.booklore.util.PathPatternResolver;
import lombok.AllArgsConstructor;
@@ -14,51 +9,17 @@ import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
@Slf4j
@Component
@AllArgsConstructor
public class FileMovingHelper {
private final BookAdditionalFileRepository bookAdditionalFileRepository;
private final AppSettingService appSettingService;
private final LibraryPathRepository libraryPathRepository;
/**
* Generates the new file path based on the library's file naming pattern
*/
public Path generateNewFilePath(BookEntity book, String pattern) {
String newRelativePathStr = PathPatternResolver.resolvePattern(book, pattern);
if (newRelativePathStr.startsWith("/") || newRelativePathStr.startsWith("\\")) {
newRelativePathStr = newRelativePathStr.substring(1);
}
Path libraryRoot = Paths.get(book.getLibraryPath().getPath()).toAbsolutePath().normalize();
return libraryRoot.resolve(newRelativePathStr).normalize();
}
/**
* Generates the new file path based on metadata and file naming pattern
*/
public Path generateNewFilePath(String libraryRootPath, BookMetadata metadata, String pattern, String fileName) {
String relativePath = PathPatternResolver.resolvePattern(metadata, pattern, FilenameUtils.getName(fileName));
return Paths.get(libraryRootPath, relativePath);
}
/**
* Gets the file naming pattern for a library, falling back to default if not set,
* and finally to {currentFilename} if no patterns are available
*/
public String getFileNamingPattern(LibraryEntity library) {
String pattern = library.getFileNamingPattern();
if (pattern == null || pattern.trim().isEmpty()) {
@@ -73,340 +34,14 @@ public class FileMovingHelper {
pattern = "{currentFilename}";
log.info("No file naming pattern available for library {}. Using fallback pattern: {currentFilename}", library.getName());
}
// Ensure pattern ends with filename placeholder if it ends with separator
if (pattern.endsWith("/") || pattern.endsWith("\\")) {
pattern += "{currentFilename}";
}
return pattern;
}
/**
* Checks if a book has all required path components for file operations
*/
public boolean hasRequiredPathComponents(BookEntity book) {
if (book.getLibraryPath() == null || book.getLibraryPath().getPath() == null ||
book.getFileSubPath() == null || book.getFileName() == null) {
log.error("Missing required path components for book id {}. Skipping.", book.getId());
return false;
}
return true;
}
/**
* Moves a book file if the current path differs from the expected pattern
*/
public boolean moveBookFileIfNeeded(BookEntity book, String pattern) throws IOException {
Path oldFilePath = book.getFullFilePath();
Path newFilePath = generateNewFilePath(book, pattern);
if (oldFilePath.equals(newFilePath)) {
log.debug("Source and destination paths are identical for book id {}. Skipping.", book.getId());
return false;
}
moveBookFileAndUpdatePaths(book, oldFilePath, newFilePath);
return true;
}
/**
* Moves a file from source to target path, creating directories as needed
*/
public void moveFile(Path source, Path target) throws IOException {
if (target.getParent() != null) {
Files.createDirectories(target.getParent());
}
log.info("Moving file from {} to {}", source, target);
Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);
}
/**
* Updates book entity paths after a file move
*/
public void updateBookPaths(BookEntity book, Path newFilePath) {
String newFileName = newFilePath.getFileName().toString();
Path libraryRoot = Paths.get(book.getLibraryPath().getPath()).toAbsolutePath().normalize();
Path newRelativeSubPath = libraryRoot.relativize(newFilePath.getParent());
String newFileSubPath = newRelativeSubPath.toString().replace('\\', '/');
book.setFileSubPath(newFileSubPath);
book.setFileName(newFileName);
}
/**
* Moves additional files for a book based on the file naming pattern
*/
public void moveAdditionalFiles(BookEntity book, String pattern) throws IOException {
Map<String, Integer> fileNameCounter = new HashMap<>();
for (BookAdditionalFileEntity additionalFile : book.getAdditionalFiles()) {
moveAdditionalFile(book, additionalFile, pattern, fileNameCounter);
}
}
/**
* Deletes empty parent directories up to library roots
*/
public void deleteEmptyParentDirsUpToLibraryFolders(Path currentDir, Set<Path> libraryRoots) throws IOException {
Set<String> ignoredFilenames = Set.of(".DS_Store", "Thumbs.db");
currentDir = currentDir.toAbsolutePath().normalize();
Set<Path> normalizedRoots = new HashSet<>();
for (Path root : libraryRoots) {
normalizedRoots.add(root.toAbsolutePath().normalize());
}
while (currentDir != null) {
if (isLibraryRoot(currentDir, normalizedRoots)) {
log.debug("Reached library root: {}. Stopping cleanup.", currentDir);
break;
}
File[] files = currentDir.toFile().listFiles();
if (files == null) {
log.warn("Cannot read directory: {}. Stopping cleanup.", currentDir);
break;
}
if (hasOnlyIgnoredFiles(files, ignoredFilenames)) {
deleteIgnoredFilesAndDirectory(files, currentDir);
currentDir = currentDir.getParent();
} else {
log.debug("Directory {} contains important files. Stopping cleanup.", currentDir);
break;
}
}
}
/**
* Moves a book file to a different library with the target library's naming pattern
*/
public boolean moveBookFileToLibrary(BookEntity book, LibraryEntity targetLibrary) throws IOException {
if (!hasRequiredPathComponents(book)) {
log.error("Missing required path components for book id {}. Cannot move to different library.", book.getId());
return false;
}
Path oldFilePath = book.getFullFilePath();
String pattern = getFileNamingPattern(targetLibrary);
// Generate new file path in target library
Path newFilePath = generateNewFilePathForLibrary(book, targetLibrary, pattern);
if (oldFilePath.equals(newFilePath)) {
log.debug("Source and destination paths are identical for book id {}. Skipping cross-library move.", book.getId());
return false;
}
moveBookFileAndUpdatePathsForLibrary(book, oldFilePath, newFilePath, targetLibrary);
return true;
}
/**
* Generates the new file path for a book in a different library
*/
public Path generateNewFilePathForLibrary(BookEntity book, LibraryEntity targetLibrary, String pattern) {
String newRelativePathStr = PathPatternResolver.resolvePattern(book, pattern);
if (newRelativePathStr.startsWith("/") || newRelativePathStr.startsWith("\\")) {
newRelativePathStr = newRelativePathStr.substring(1);
}
Path targetLibraryRoot = getLibraryRootPath(targetLibrary);
return targetLibraryRoot.resolve(newRelativePathStr).normalize();
}
/**
* Gets the root path for a library (uses the first library path)
*/
private Path getLibraryRootPath(LibraryEntity library) {
if (library.getLibraryPaths() == null || library.getLibraryPaths().isEmpty()) {
throw new RuntimeException("Library " + library.getName() + " has no paths configured");
}
return Paths.get(library.getLibraryPaths().getFirst().getPath()).toAbsolutePath().normalize();
}
private void moveBookFileAndUpdatePaths(BookEntity book, Path oldFilePath, Path newFilePath) throws IOException {
moveFile(oldFilePath, newFilePath);
updateBookPaths(book, newFilePath);
// Clean up empty directories
try {
Path libraryRoot = Paths.get(book.getLibraryPath().getPath()).toAbsolutePath().normalize();
deleteEmptyParentDirsUpToLibraryFolders(oldFilePath.getParent(), Set.of(libraryRoot));
} catch (IOException e) {
log.warn("Failed to clean up empty directories after moving book ID {}: {}", book.getId(), e.getMessage());
}
}
private void moveBookFileAndUpdatePathsForLibrary(BookEntity book, Path oldFilePath, Path newFilePath, LibraryEntity targetLibrary) throws IOException {
moveFile(oldFilePath, newFilePath);
updateBookPathsForLibrary(book, newFilePath, targetLibrary);
// Clean up empty directories in source library
// IMPORTANT: We need to collect ALL library roots to avoid deleting any library root directory
try {
Set<Path> allLibraryRoots = getAllLibraryRoots();
deleteEmptyParentDirsUpToLibraryFolders(oldFilePath.getParent(), allLibraryRoots);
} catch (IOException e) {
log.warn("Failed to clean up empty directories after moving book ID {}: {}", book.getId(), e.getMessage());
}
}
/**
* Gets all library root paths from all libraries to ensure we never delete any library root
*/
private Set<Path> getAllLibraryRoots() {
Set<Path> allRoots = new HashSet<>();
try {
// Get all libraries and collect their root paths
libraryPathRepository.findAll().forEach(libraryPath -> {
try {
Path rootPath = Paths.get(libraryPath.getPath()).toAbsolutePath().normalize();
allRoots.add(rootPath);
log.debug("Added library root to protection list: {}", rootPath);
} catch (Exception e) {
log.warn("Failed to process library path {}: {}", libraryPath.getPath(), e.getMessage());
}
});
} catch (Exception e) {
log.error("Failed to collect all library roots: {}", e.getMessage());
}
return allRoots;
}
private void updateBookPathsForLibrary(BookEntity book, Path newFilePath, LibraryEntity targetLibrary) {
String newFileName = newFilePath.getFileName().toString();
Path targetLibraryRoot = getLibraryRootPath(targetLibrary);
Path newRelativeSubPath = targetLibraryRoot.relativize(newFilePath.getParent());
String newFileSubPath = newRelativeSubPath.toString().replace('\\', '/');
// Find or create the appropriate LibraryPathEntity for the target library
String targetLibraryPath = targetLibrary.getLibraryPaths().getFirst().getPath();
LibraryPathEntity targetLibraryPathEntity = libraryPathRepository
.findByLibraryIdAndPath(targetLibrary.getId(), targetLibraryPath)
.orElseThrow(() -> new RuntimeException("LibraryPath not found for library " + targetLibrary.getId() + " and path " + targetLibraryPath));
// Update only the path-related fields, avoid touching library entity relationships
// that might trigger cascade operations
book.setLibraryPath(targetLibraryPathEntity); // This should update library_path_id
book.setFileSubPath(newFileSubPath);
book.setFileName(newFileName);
// DO NOT set book.setLibrary(targetLibrary) to avoid cascade issues
log.debug("Updated book {} path references: libraryPathId={}, newPath={}",
book.getId(), targetLibraryPathEntity.getId(), newFilePath);
}
private void moveAdditionalFile(BookEntity book, BookAdditionalFileEntity additionalFile, String pattern, Map<String, Integer> fileNameCounter) throws IOException {
Path oldAdditionalFilePath = additionalFile.getFullFilePath();
if (!Files.exists(oldAdditionalFilePath)) {
log.warn("Additional file does not exist for book id {}: {}", book.getId(), oldAdditionalFilePath);
return;
}
Path newAdditionalFilePath = generateAdditionalFilePath(book, additionalFile, pattern);
newAdditionalFilePath = ensureUniqueFilePath(newAdditionalFilePath, fileNameCounter);
if (oldAdditionalFilePath.equals(newAdditionalFilePath)) {
log.debug("Source and destination paths are identical for additional file id {}. Skipping.", additionalFile.getId());
return;
}
moveFile(oldAdditionalFilePath, newAdditionalFilePath);
Path libraryRoot = Paths.get(book.getLibraryPath().getPath()).toAbsolutePath().normalize();
updateAdditionalFilePaths(additionalFile, newAdditionalFilePath, libraryRoot);
bookAdditionalFileRepository.save(additionalFile);
log.info("Updated additional file id {} with new path", additionalFile.getId());
}
private Path generateAdditionalFilePath(BookEntity book, BookAdditionalFileEntity additionalFile, String pattern) {
String newRelativePathStr = PathPatternResolver.resolvePattern(book.getMetadata(), pattern, additionalFile.getFileName());
// Fall back to the filename when resolver returns null/empty to avoid NPEs in callers/tests
if (newRelativePathStr == null || newRelativePathStr.trim().isEmpty()) {
newRelativePathStr = additionalFile.getFileName() != null ? additionalFile.getFileName() : "";
}
if (!newRelativePathStr.isEmpty() && (newRelativePathStr.startsWith("/") || newRelativePathStr.startsWith("\\"))) {
newRelativePathStr = newRelativePathStr.substring(1);
}
Path libraryRoot = Paths.get(book.getLibraryPath().getPath()).toAbsolutePath().normalize();
return libraryRoot.resolve(newRelativePathStr).normalize();
}
private Path ensureUniqueFilePath(Path filePath, Map<String, Integer> fileNameCounter) {
String fileName = filePath.getFileName().toString();
String baseName = fileName;
String extension = "";
int lastDot = fileName.lastIndexOf(".");
if (lastDot >= 0 && lastDot < fileName.length() - 1) {
baseName = fileName.substring(0, lastDot);
extension = fileName.substring(lastDot);
}
String fileKey = filePath.toString().toLowerCase();
Integer count = fileNameCounter.get(fileKey);
if (count == null) {
fileNameCounter.put(fileKey, 1);
return filePath;
} else {
count++;
fileNameCounter.put(fileKey, count);
String newFileName = baseName + "_" + count + extension;
return filePath.getParent().resolve(newFileName);
}
}
private void updateAdditionalFilePaths(BookAdditionalFileEntity additionalFile, Path newFilePath, Path libraryRoot) {
String newFileName = newFilePath.getFileName().toString();
Path newRelativeSubPath = libraryRoot.relativize(newFilePath.getParent());
String newFileSubPath = newRelativeSubPath.toString().replace('\\', '/');
additionalFile.setFileSubPath(newFileSubPath);
additionalFile.setFileName(newFileName);
}
private boolean isLibraryRoot(Path currentDir, Set<Path> normalizedRoots) {
for (Path root : normalizedRoots) {
try {
if (Files.isSameFile(root, currentDir)) {
return true;
}
} catch (IOException e) {
log.warn("Failed to compare paths: {} and {}", root, currentDir);
}
}
return false;
}
private boolean hasOnlyIgnoredFiles(File[] files, Set<String> ignoredFilenames) {
for (File file : files) {
if (!ignoredFilenames.contains(file.getName())) {
return false;
}
}
return true;
}
private void deleteIgnoredFilesAndDirectory(File[] files, Path currentDir) {
for (File file : files) {
try {
Files.delete(file.toPath());
log.info("Deleted ignored file: {}", file.getAbsolutePath());
} catch (IOException e) {
log.warn("Failed to delete ignored file: {}", file.getAbsolutePath());
}
}
try {
Files.delete(currentDir);
log.info("Deleted empty directory: {}", currentDir);
} catch (IOException e) {
log.warn("Failed to delete directory: {}", currentDir, e);
}
public Path generateNewFilePath(String libraryRootPath, BookMetadata metadata, String pattern, String fileName) {
String relativePath = PathPatternResolver.resolvePattern(metadata, pattern, FilenameUtils.getName(fileName));
return Paths.get(libraryRootPath, relativePath);
}
}
@@ -1,147 +0,0 @@
package com.adityachandel.booklore.service.file;
import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Supplier;
import java.util.stream.Stream;
/**
* Service responsible for executing file operations while temporarily disabling monitoring
* on specific paths to prevent event loops and race conditions during file system operations.
*
* This service provides targeted path protection by unregistering only the directories
* involved in the operation rather than pausing all monitoring, ensuring minimal
* disruption to the monitoring system.
*/
@Slf4j
@Component
@AllArgsConstructor
public class MonitoredFileOperationService {
private final MonitoringRegistrationService monitoringRegistrationService;
/**
* Executes a file operation with targeted path protection to prevent monitoring conflicts.
*
* This method temporarily unregisters monitoring for only the specific directories involved
* in the operation (source and target) rather than pausing all monitoring. This approach
* minimizes the impact on the monitoring system while preventing event loops that could
* occur when the monitoring service detects changes from our own file operations.
*
* The process follows these steps:
* 1. Identify source and target directories
* 2. Temporarily unregister monitoring for these specific paths
* 3. Execute the file operation
* 4. Wait for filesystem operations to settle
* 5. Re-register paths and scan for new directory structures
*
* @param sourcePath the source file path for the operation
* @param targetPath the target file path for the operation
* @param libraryId the library ID used for re-registration of monitoring
* @param operation the file operation to execute (supplied as a lambda)
* @param <T> the return type of the operation
*/
public <T> void executeWithMonitoringSuspended(Path sourcePath, Path targetPath, Long libraryId, Supplier<T> operation) {
// Extract parent directories since we monitor directories, not individual files
Path sourceDir = sourcePath.getParent();
Path targetDir = targetPath.getParent();
// Track which paths we unregister so we can restore them later
Set<Path> unregisteredPaths = new HashSet<>();
try {
// Unregister source directory to prevent detection of file removal events
if (monitoringRegistrationService.isPathMonitored(sourceDir)) {
monitoringRegistrationService.unregisterSpecificPath(sourceDir);
unregisteredPaths.add(sourceDir);
log.debug("Temporarily unregistered source directory to prevent monitoring conflicts: {}", sourceDir);
}
// Unregister target directory if it's different from source and already exists
// This prevents detection of file creation events during the operation
if (!sourceDir.equals(targetDir) && Files.exists(targetDir) && monitoringRegistrationService.isPathMonitored(targetDir)) {
monitoringRegistrationService.unregisterSpecificPath(targetDir);
unregisteredPaths.add(targetDir);
log.debug("Temporarily unregistered target directory to prevent monitoring conflicts: {}", targetDir);
}
log.debug("Protected {} directory paths from monitoring during file operation", unregisteredPaths.size());
// Execute the actual file operation (move, copy, delete, etc.)
T result = operation.get();
// Allow filesystem operations to complete and settle before re-enabling monitoring
// This prevents race conditions where monitoring might restart before the operation is fully complete
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.warn("Thread interrupted while waiting for filesystem operations to settle");
}
} finally {
// Always restore monitoring, even if the operation failed
reregisterPathsAfterMove(unregisteredPaths, libraryId, targetDir);
}
}
/**
* Restores monitoring registration for paths after a file operation and discovers new directories.
*
* This method handles the cleanup phase by:
* 1. Re-registering previously monitored paths that still exist
* 2. Registering new directory structures created by the operation
* 3. Ensuring comprehensive monitoring coverage after the operation
*
* @param unregisteredPaths the set of paths that were temporarily unregistered
* @param libraryId the library ID to use for new registrations
* @param targetDir the target directory where new structures might have been created
*/
private void reregisterPathsAfterMove(Set<Path> unregisteredPaths, Long libraryId, Path targetDir) {
// Restore monitoring for original paths that still exist after the operation
for (Path path : unregisteredPaths) {
if (Files.exists(path) && Files.isDirectory(path)) {
monitoringRegistrationService.registerSpecificPath(path, libraryId);
log.debug("Restored monitoring for existing path: {}", path);
} else {
log.info("Path no longer exists after operation, skipping re-registration: {}", path);
}
}
// Register monitoring for new directory structures created at the target location
if (Files.exists(targetDir) && Files.isDirectory(targetDir)) {
// Register the target directory itself if it wasn't previously monitored
if (!monitoringRegistrationService.isPathMonitored(targetDir)) {
monitoringRegistrationService.registerSpecificPath(targetDir, libraryId);
log.debug("Registered new target directory for monitoring: {}", targetDir);
}
// Discover and register any new subdirectories created during the operation
// This ensures complete monitoring coverage for complex directory structures
try (Stream<Path> stream = Files.walk(targetDir)) {
stream.filter(Files::isDirectory)
.filter(Files::exists)
.filter(path -> !path.equals(targetDir)) // Skip the parent directory itself
.forEach(path -> {
if (!monitoringRegistrationService.isPathMonitored(path)) {
monitoringRegistrationService.registerSpecificPath(path, libraryId);
log.info("Registered new subdirectory for monitoring: {}", path);
}
});
} catch (IOException e) {
log.warn("Failed to scan and register new subdirectories at: {}", targetDir, e);
}
}
log.debug("Completed restoration of monitoring after file operation");
}
}
@@ -1,264 +0,0 @@
package com.adityachandel.booklore.service.file;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.LibraryEntity;
import com.adityachandel.booklore.repository.LibraryRepository;
import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
@Slf4j
@Service
@AllArgsConstructor
public class UnifiedFileMoveService {
private final FileMovingHelper fileMovingHelper;
private final MonitoredFileOperationService monitoredFileOperationService;
private final MonitoringRegistrationService monitoringRegistrationService;
private final LibraryRepository libraryRepository;
/**
* Moves a single book file to match the library's file naming pattern.
* Used for metadata updates where one file needs to be moved.
*/
public void moveSingleBookFile(BookEntity bookEntity) {
if (bookEntity.getLibraryPath() == null || bookEntity.getLibraryPath().getLibrary() == null) {
log.debug("Book ID {} has no library associated. Skipping file move.", bookEntity.getId());
return;
}
String pattern = fileMovingHelper.getFileNamingPattern(bookEntity.getLibraryPath().getLibrary());
if (!fileMovingHelper.hasRequiredPathComponents(bookEntity)) {
log.debug("Missing required path components for book ID {}. Skipping file move.", bookEntity.getId());
return;
}
Path currentFilePath = bookEntity.getFullFilePath();
Path expectedFilePath = fileMovingHelper.generateNewFilePath(bookEntity, pattern);
// Check if current path differs from expected pattern
if (currentFilePath.equals(expectedFilePath)) {
log.debug("File for book ID {} is already in the correct location according to library pattern. No move needed.", bookEntity.getId());
return;
}
log.info("File for book ID {} needs to be moved from {} to {} to match library pattern",
bookEntity.getId(), currentFilePath, expectedFilePath);
Long libraryId = bookEntity.getLibraryPath().getLibrary().getId();
Path libraryRoot = Paths.get(bookEntity.getLibraryPath().getPath())
.toAbsolutePath().normalize();
// unregister the entire library to suppress all watch events during the move
monitoringRegistrationService.unregisterLibrary(libraryId);
try {
monitoredFileOperationService.executeWithMonitoringSuspended(
currentFilePath, expectedFilePath, libraryId, () -> {
try {
boolean moved = fileMovingHelper.moveBookFileIfNeeded(bookEntity, pattern);
if (moved) {
log.info("Successfully moved file for book ID {} from {} to {}",
bookEntity.getId(), currentFilePath, bookEntity.getFullFilePath());
}
return moved;
} catch (IOException e) {
log.error("Failed to move file for book ID {}: {}", bookEntity.getId(), e.getMessage(), e);
throw new RuntimeException("File move failed", e);
}
}
);
} finally {
// re-register all folders under the library after the move
monitoringRegistrationService.registerLibraryPaths(libraryId, libraryRoot);
}
}
/**
* Moves multiple book files in batches with cross-library support and library-level monitoring protection.
* Used for bulk file operations where many files need to be moved, potentially across libraries.
*/
public void moveBatchBookFiles(List<BookEntity> books, Map<Long, Long> bookToTargetLibraryMap, BatchMoveCallback callback) {
if (books.isEmpty()) {
log.debug("No books to move");
return;
}
Set<Long> allLibraryIds = new HashSet<>();
Map<Long, Set<Path>> libraryToRootsMap = new HashMap<>();
// Collect library information for monitoring protection
for (BookEntity book : books) {
if (book.getMetadata() == null) continue;
if (!fileMovingHelper.hasRequiredPathComponents(book)) continue;
Path oldFilePath = book.getFullFilePath();
if (!Files.exists(oldFilePath)) continue;
// Source library
Long sourceLibraryId = book.getLibraryPath().getLibrary().getId();
Path sourceLibraryRoot = Paths.get(book.getLibraryPath().getPath()).toAbsolutePath().normalize();
libraryToRootsMap.computeIfAbsent(sourceLibraryId, k -> new HashSet<>()).add(sourceLibraryRoot);
allLibraryIds.add(sourceLibraryId);
// Target library (if different)
Long targetLibraryId = bookToTargetLibraryMap.get(book.getId());
if (targetLibraryId != null && !targetLibraryId.equals(sourceLibraryId)) {
LibraryEntity targetLibrary = libraryRepository.findById(targetLibraryId).orElse(null);
if (targetLibrary != null && targetLibrary.getLibraryPaths() != null && !targetLibrary.getLibraryPaths().isEmpty()) {
Path targetLibraryRoot = Paths.get(targetLibrary.getLibraryPaths().getFirst().getPath()).toAbsolutePath().normalize();
libraryToRootsMap.computeIfAbsent(targetLibraryId, k -> new HashSet<>()).add(targetLibraryRoot);
allLibraryIds.add(targetLibraryId);
}
}
}
// Unregister all affected libraries for batch operation
unregisterLibrariesBatch(libraryToRootsMap);
try {
// Small delay to let any pending file watcher events settle
try {
Thread.sleep(500);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.warn("Interrupted during pre-move delay");
}
// Process each book
for (BookEntity book : books) {
if (book.getMetadata() == null) continue;
if (!fileMovingHelper.hasRequiredPathComponents(book)) continue;
Path oldFilePath = book.getFullFilePath();
if (!Files.exists(oldFilePath)) {
log.warn("File not found for book {}: {}", book.getId(), oldFilePath);
continue;
}
log.debug("Moving book {}: '{}'", book.getId(), book.getMetadata().getTitle());
try {
Long targetLibraryId = bookToTargetLibraryMap.get(book.getId());
boolean moved = false;
if (targetLibraryId != null && !targetLibraryId.equals(book.getLibraryPath().getLibrary().getId())) {
// Cross-library move
LibraryEntity targetLibrary = libraryRepository.findById(targetLibraryId).orElse(null);
if (targetLibrary != null) {
moved = fileMovingHelper.moveBookFileToLibrary(book, targetLibrary);
if (moved) {
log.debug("Book {} moved to library {} successfully", book.getId(), targetLibraryId);
}
} else {
log.error("Target library {} not found for book {}", targetLibraryId, book.getId());
callback.onBookMoveFailed(book, new RuntimeException("Target library not found"));
continue;
}
} else {
// Same library move (existing functionality)
String pattern = fileMovingHelper.getFileNamingPattern(book.getLibraryPath().getLibrary());
moved = fileMovingHelper.moveBookFileIfNeeded(book, pattern);
if (moved) {
log.debug("Book {} moved within library successfully", book.getId());
}
}
if (moved) {
callback.onBookMoved(book);
// Move additional files if any
if (book.getAdditionalFiles() != null && !book.getAdditionalFiles().isEmpty()) {
String pattern = fileMovingHelper.getFileNamingPattern(book.getLibraryPath().getLibrary());
fileMovingHelper.moveAdditionalFiles(book, pattern);
}
}
} catch (IOException e) {
log.error("Move failed for book {}: {}", book.getId(), e.getMessage(), e);
callback.onBookMoveFailed(book, e);
}
}
// Longer delay to let filesystem operations settle before re-registering monitoring
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.warn("Interrupted during batch move delay");
}
} finally {
// Re-register all affected libraries
registerLibrariesBatch(libraryToRootsMap);
}
}
// Overloaded method for backward compatibility with same-library moves
public void moveBatchBookFiles(List<BookEntity> books, BatchMoveCallback callback) {
moveBatchBookFiles(books, new HashMap<>(), callback);
}
private void unregisterLibrariesBatch(Map<Long, Set<Path>> libraryToRootsMap) {
log.debug("Unregistering {} libraries for batch move", libraryToRootsMap.size());
for (Map.Entry<Long, Set<Path>> entry : libraryToRootsMap.entrySet()) {
Long libraryId = entry.getKey();
try {
monitoringRegistrationService.unregisterLibrary(libraryId);
log.debug("Unregistered library {}", libraryId);
} catch (Exception e) {
log.warn("Failed to unregister library {}: {}", libraryId, e.getMessage());
}
}
}
private void registerLibrariesBatch(Map<Long, Set<Path>> libraryToRootsMap) {
log.debug("Re-registering {} libraries after batch move", libraryToRootsMap.size());
for (Map.Entry<Long, Set<Path>> entry : libraryToRootsMap.entrySet()) {
Long libraryId = entry.getKey();
Set<Path> libraryRoots = entry.getValue();
// Verify library still exists before re-registering
try {
LibraryEntity library = libraryRepository.findById(libraryId).orElse(null);
if (library == null) {
log.warn("Library {} no longer exists, skipping re-registration", libraryId);
continue;
}
for (Path libraryRoot : libraryRoots) {
if (Files.exists(libraryRoot) && Files.isDirectory(libraryRoot)) {
try {
monitoringRegistrationService.registerLibraryPaths(libraryId, libraryRoot);
log.debug("Re-registered library {} at {}", libraryId, libraryRoot);
} catch (Exception e) {
log.warn("Failed to re-register library {} at {}: {}", libraryId, libraryRoot, e.getMessage());
}
} else {
log.debug("Library root {} no longer exists or is not a directory, skipping re-registration", libraryRoot);
}
}
} catch (Exception e) {
log.error("Error verifying library {} during re-registration: {}", libraryId, e.getMessage());
}
}
}
/**
* Callback interface for batch move operations
*/
public interface BatchMoveCallback {
void onBookMoved(BookEntity book);
void onBookMoveFailed(BookEntity book, Exception error);
}
}
@@ -9,8 +9,8 @@ import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.enums.FileProcessStatus;
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.service.BookCreatorService;
import com.adityachandel.booklore.service.FileFingerprint;
import com.adityachandel.booklore.service.book.BookCreatorService;
import com.adityachandel.booklore.service.file.FileFingerprint;
import com.adityachandel.booklore.service.metadata.MetadataMatchService;
import com.adityachandel.booklore.util.FileService;
import jakarta.persistence.EntityManager;
@@ -9,7 +9,7 @@ import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
import com.adityachandel.booklore.repository.BookMetadataRepository;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.service.BookCreatorService;
import com.adityachandel.booklore.service.book.BookCreatorService;
import com.adityachandel.booklore.service.metadata.extractor.CbxMetadataExtractor;
import com.adityachandel.booklore.service.metadata.MetadataMatchService;
import com.adityachandel.booklore.util.FileService;
@@ -9,7 +9,7 @@ import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
import com.adityachandel.booklore.repository.BookMetadataRepository;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.service.BookCreatorService;
import com.adityachandel.booklore.service.book.BookCreatorService;
import com.adityachandel.booklore.service.metadata.MetadataMatchService;
import com.adityachandel.booklore.service.metadata.extractor.EpubMetadataExtractor;
import com.adityachandel.booklore.util.FileService;
@@ -8,7 +8,7 @@ import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
import com.adityachandel.booklore.repository.BookMetadataRepository;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.service.BookCreatorService;
import com.adityachandel.booklore.service.book.BookCreatorService;
import com.adityachandel.booklore.service.metadata.MetadataMatchService;
import com.adityachandel.booklore.service.metadata.extractor.PdfMetadataExtractor;
import com.adityachandel.booklore.util.FileService;
@@ -1,4 +1,4 @@
package com.adityachandel.booklore.service;
package com.adityachandel.booklore.service.kobo;
import com.adityachandel.booklore.model.dto.kobo.*;
import com.adityachandel.booklore.model.dto.settings.KoboSettings;
@@ -9,6 +9,7 @@ import com.adityachandel.booklore.model.entity.CategoryEntity;
import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.model.enums.KoboBookFormat;
import com.adityachandel.booklore.model.enums.KoboReadStatus;
import com.adityachandel.booklore.service.book.BookQueryService;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import com.adityachandel.booklore.util.kobo.KoboUrlBuilder;
import lombok.AllArgsConstructor;
@@ -1,4 +1,4 @@
package com.adityachandel.booklore.service;
package com.adityachandel.booklore.service.kobo;
import com.adityachandel.booklore.mapper.BookEntityToKoboSnapshotBookMapper;
import com.adityachandel.booklore.model.entity.KoboDeletedBookProgressEntity;
@@ -7,8 +7,6 @@ import com.adityachandel.booklore.model.dto.kobo.*;
import com.adityachandel.booklore.model.entity.KoboSnapshotBookEntity;
import com.adityachandel.booklore.model.entity.KoboLibrarySnapshotEntity;
import com.adityachandel.booklore.repository.KoboDeletedBookProgressRepository;
import com.adityachandel.booklore.service.KoboEntitlementService;
import com.adityachandel.booklore.service.KoboLibrarySnapshotService;
import com.adityachandel.booklore.util.RequestUtils;
import com.adityachandel.booklore.util.kobo.BookloreSyncTokenGenerator;
import com.fasterxml.jackson.databind.JsonNode;
@@ -1,4 +1,4 @@
package com.adityachandel.booklore.service;
package com.adityachandel.booklore.service.kobo;
import com.adityachandel.booklore.mapper.KoboReadingStateMapper;
import com.adityachandel.booklore.model.dto.kobo.KoboReadingState;
@@ -1,4 +1,4 @@
package com.adityachandel.booklore.service;
package com.adityachandel.booklore.service.kobo;
import com.adityachandel.booklore.config.security.service.AuthenticationService;
import com.adityachandel.booklore.model.dto.BookLoreUser;
@@ -9,6 +9,7 @@ import com.adityachandel.booklore.model.entity.KoboUserSettingsEntity;
import com.adityachandel.booklore.model.entity.ShelfEntity;
import com.adityachandel.booklore.model.enums.ShelfType;
import com.adityachandel.booklore.repository.KoboUserSettingsRepository;
import com.adityachandel.booklore.service.ShelfService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@@ -1,6 +1,6 @@
package com.adityachandel.booklore.service.kobo;
import com.adityachandel.booklore.service.BookService;
import com.adityachandel.booklore.service.book.BookService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.Resource;
@@ -1,8 +1,7 @@
package com.adityachandel.booklore.service;
package com.adityachandel.booklore.service.koreader;
import java.time.Instant;
import java.util.Map;
import java.util.Optional;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
@@ -1,4 +1,4 @@
package com.adityachandel.booklore.service;
package com.adityachandel.booklore.service.koreader;
import com.adityachandel.booklore.config.security.service.AuthenticationService;
import com.adityachandel.booklore.exception.ApiError;
@@ -12,7 +12,7 @@ import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.model.enums.LibraryScanMode;
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.service.FileFingerprint;
import com.adityachandel.booklore.service.file.FileFingerprint;
import com.adityachandel.booklore.service.event.AdminEventBroadcaster;
import com.adityachandel.booklore.service.event.BookEventBroadcaster;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor;
@@ -10,7 +10,7 @@ import com.adityachandel.booklore.model.websocket.Topic;
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
import com.adityachandel.booklore.repository.LibraryRepository;
import com.adityachandel.booklore.service.NotificationService;
import com.adityachandel.booklore.task.RescanLibraryContext;
import com.adityachandel.booklore.task.options.RescanLibraryContext;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import lombok.AllArgsConstructor;
@@ -23,8 +23,6 @@ import java.nio.file.Path;
import java.util.*;
import java.util.stream.Collectors;
import static com.adityachandel.booklore.model.websocket.LogNotification.createLogNotification;
@AllArgsConstructor
@Service
@Slf4j
@@ -12,7 +12,7 @@ import com.adityachandel.booklore.repository.LibraryRepository;
import com.adityachandel.booklore.service.NotificationService;
import com.adityachandel.booklore.service.metadata.BookMetadataUpdater;
import com.adityachandel.booklore.service.metadata.extractor.MetadataExtractorFactory;
import com.adityachandel.booklore.task.RescanLibraryContext;
import com.adityachandel.booklore.task.options.RescanLibraryContext;
import com.adityachandel.booklore.task.TaskCancellationManager;
import com.adityachandel.booklore.task.TaskStatus;
import com.adityachandel.booklore.model.enums.TaskType;
@@ -110,7 +110,7 @@ public class LibraryRescanHelper {
try {
TaskProgressPayload payload = TaskProgressPayload.builder()
.taskId(taskId)
.taskType(TaskType.RE_SCAN_LIBRARY)
.taskType(TaskType.REFRESH_LIBRARY_METADATA)
.message(message)
.progress(progress)
.taskStatus(taskStatus)
@@ -21,7 +21,7 @@ import com.adityachandel.booklore.repository.LibraryRepository;
import com.adityachandel.booklore.repository.UserRepository;
import com.adityachandel.booklore.service.NotificationService;
import com.adityachandel.booklore.service.monitoring.MonitoringService;
import com.adityachandel.booklore.task.RescanLibraryContext;
import com.adityachandel.booklore.task.options.RescanLibraryContext;
import com.adityachandel.booklore.util.FileService;
import com.adityachandel.booklore.util.SecurityContextVirtualThread;
import jakarta.annotation.PostConstruct;
@@ -22,9 +22,10 @@ import com.adityachandel.booklore.model.websocket.LogNotification;
import com.adityachandel.booklore.model.websocket.Topic;
import com.adityachandel.booklore.repository.BookMetadataRepository;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.service.BookQueryService;
import com.adityachandel.booklore.service.book.BookQueryService;
import com.adityachandel.booklore.service.NotificationService;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import com.adityachandel.booklore.service.file.FileFingerprint;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry;
import com.adityachandel.booklore.service.metadata.extractor.CbxMetadataExtractor;
@@ -51,8 +52,6 @@ import java.util.concurrent.CompletableFuture;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;
import static com.adityachandel.booklore.model.websocket.LogNotification.createLogNotification;
@Slf4j
@Service
@AllArgsConstructor
@@ -172,8 +171,13 @@ public class BookMetadataService {
boolean convertCbrCb7ToCbz = settings.isConvertCbrCb7ToCbz();
if (saveToOriginalFile && (bookEntity.getBookType() != BookFileType.CBX || convertCbrCb7ToCbz)) {
metadataWriterFactory.getWriter(bookEntity.getBookType())
.ifPresent(writer -> writerAction.accept(writer, bookEntity));
.ifPresent(writer -> {
writerAction.accept(writer, bookEntity);
String newHash = FileFingerprint.generateHash(bookEntity.getFullFilePath());
bookEntity.setCurrentHash(newHash);
});
}
bookRepository.save(bookEntity);
return bookMetadataMapper.toBookMetadata(bookEntity.getMetadata(), true);
}
@@ -235,7 +239,7 @@ public class BookMetadataService {
}
@Transactional
public List<BookMetadata> bulkUpdateMetadata(BulkMetadataUpdateRequest request, boolean mergeCategories) {
public void bulkUpdateMetadata(BulkMetadataUpdateRequest request, boolean mergeCategories, boolean mergeMoods, boolean mergeTags) {
List<BookEntity> books = bookRepository.findAllWithMetadataByIds(request.getBookIds());
MetadataClearFlags clearFlags = metadataClearFlagsMapper.toClearFlags(request);
@@ -261,14 +265,12 @@ public class BookMetadataService {
.build())
.updateThumbnail(false)
.mergeCategories(mergeCategories)
.mergeMoods(mergeMoods)
.mergeTags(mergeTags)
.build();
bookMetadataUpdater.setBookMetadata(context);
notificationService.sendMessage(Topic.BOOK_UPDATE, bookMapper.toBook(book));
}
return books.stream()
.map(BookEntity::getMetadata)
.map(m -> bookMetadataMapper.toBookMetadata(m, false))
.toList();
}
}
@@ -4,6 +4,7 @@ import com.adityachandel.booklore.model.MetadataClearFlags;
import com.adityachandel.booklore.model.MetadataUpdateContext;
import com.adityachandel.booklore.model.MetadataUpdateWrapper;
import com.adityachandel.booklore.model.dto.BookMetadata;
import com.adityachandel.booklore.model.dto.FileMoveResult;
import com.adityachandel.booklore.model.dto.settings.MetadataPersistenceSettings;
import com.adityachandel.booklore.model.entity.*;
import com.adityachandel.booklore.model.enums.BookFileType;
@@ -13,9 +14,9 @@ import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.repository.CategoryRepository;
import com.adityachandel.booklore.repository.MoodRepository;
import com.adityachandel.booklore.repository.TagRepository;
import com.adityachandel.booklore.service.FileFingerprint;
import com.adityachandel.booklore.service.file.FileFingerprint;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import com.adityachandel.booklore.service.file.UnifiedFileMoveService;
import com.adityachandel.booklore.service.file.FileMoveService;
import com.adityachandel.booklore.service.metadata.writer.MetadataWriterFactory;
import com.adityachandel.booklore.util.FileService;
import com.adityachandel.booklore.util.MetadataChangeDetector;
@@ -30,9 +31,7 @@ import java.io.File;
import java.net.InetAddress;
import java.net.URL;
import java.time.Instant;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.stream.Collectors;
@@ -52,13 +51,15 @@ public class BookMetadataUpdater {
private final AppSettingService appSettingService;
private final MetadataWriterFactory metadataWriterFactory;
private final BookReviewUpdateService bookReviewUpdateService;
private final UnifiedFileMoveService unifiedFileMoveService;
private final FileMoveService fileMoveService;
@Transactional
public void setBookMetadata(MetadataUpdateContext context) {
BookEntity bookEntity = context.getBookEntity();
MetadataUpdateWrapper wrapper = context.getMetadataUpdateWrapper();
boolean mergeCategories = context.isMergeCategories();
boolean mergeMoods = context.isMergeMoods();
boolean mergeTags = context.isMergeTags();
boolean updateThumbnail = context.isUpdateThumbnail();
MetadataReplaceMode replaceMode = context.getReplaceMode();
@@ -96,8 +97,8 @@ public class BookMetadataUpdater {
updateBasicFields(newMetadata, metadata, clearFlags, replaceMode);
updateAuthorsIfNeeded(newMetadata, metadata, clearFlags, mergeCategories, replaceMode);
updateCategoriesIfNeeded(newMetadata, metadata, clearFlags, mergeCategories, replaceMode);
updateMoodsIfNeeded(newMetadata, metadata, clearFlags, mergeCategories, replaceMode);
updateTagsIfNeeded(newMetadata, metadata, clearFlags, mergeCategories, replaceMode);
updateMoodsIfNeeded(newMetadata, metadata, clearFlags, mergeMoods, replaceMode);
updateTagsIfNeeded(newMetadata, metadata, clearFlags, mergeTags, replaceMode);
bookReviewUpdateService.updateBookReviews(newMetadata, metadata, clearFlags, mergeCategories);
updateThumbnailIfNeeded(bookId, newMetadata, metadata, updateThumbnail);
@@ -110,60 +111,40 @@ public class BookMetadataUpdater {
log.warn("Failed to calculate metadata match score for book ID {}: {}", bookId, e.getMessage());
}
if ((writeToFile && hasValueChanges) || thumbnailRequiresUpdate) {
if (bookType == BookFileType.CBX && !convertCbrCb7ToCbz) {
log.info("CBX metadata writing disabled for book ID {}", bookId);
} else {
metadataWriterFactory.getWriter(bookType).ifPresent(writer -> {
try {
String thumbnailUrl = updateThumbnail ? newMetadata.getThumbnailUrl() : null;
if ((StringUtils.hasText(thumbnailUrl) && isLocalOrPrivateUrl(thumbnailUrl) || Boolean.TRUE.equals(metadata.getCoverLocked()))) {
log.debug("Blocked local/private thumbnail URL: {}", thumbnailUrl);
thumbnailUrl = null;
}
File file = new File(bookEntity.getFullFilePath().toUri());
writer.writeMetadataToFile(file, metadata, thumbnailUrl, clearFlags);
String newHash;
// Special handling: If original file was .cbr or .cb7 and now .cbz exists, update to .cbz
File resultingFile = file;
if (!file.exists()) {
// Replace last extension .cbr or .cb7 (case-insensitive) with .cbz
String cbzName = file.getName().replaceFirst("(?i)\\.(cbr|cb7)$", ".cbz");
File cbzFile = new File(file.getParentFile(), cbzName);
if (cbzFile.exists()) {
bookEntity.setFileName(cbzName);
resultingFile = cbzFile;
}
bookEntity.setFileSizeKb(resultingFile.length() / 1024);
log.info("Converted to CBZ: {} -> {}", file.getAbsolutePath(), resultingFile.getAbsolutePath());
newHash = FileFingerprint.generateHash(resultingFile.toPath());
} else {
newHash = FileFingerprint.generateHash(bookEntity.getFullFilePath());
}
bookEntity.setCurrentHash(newHash);
} catch (Exception e) {
log.warn("Failed to write metadata for book ID {}: {}", bookId, e.getMessage());
boolean hasValueChangesForFileWrite = MetadataChangeDetector.hasValueChangesForFileWrite(newMetadata, metadata, clearFlags);
if ((writeToFile && hasValueChangesForFileWrite) || thumbnailRequiresUpdate) {
metadataWriterFactory.getWriter(bookType).ifPresent(writer -> {
try {
String thumbnailUrl = updateThumbnail ? newMetadata.getThumbnailUrl() : null;
if ((StringUtils.hasText(thumbnailUrl) && isLocalOrPrivateUrl(thumbnailUrl) || Boolean.TRUE.equals(metadata.getCoverLocked()))) {
log.debug("Blocked local/private thumbnail URL: {}", thumbnailUrl);
thumbnailUrl = null;
}
});
}
File file = new File(bookEntity.getFullFilePath().toUri());
writer.writeMetadataToFile(file, metadata, thumbnailUrl, clearFlags);
String newHash = FileFingerprint.generateHash(bookEntity.getFullFilePath());
bookEntity.setCurrentHash(newHash);
} catch (Exception e) {
log.warn("Failed to write metadata for book ID {}: {}", bookId, e.getMessage());
}
});
}
boolean moveFilesToLibraryPattern = settings.isMoveFilesToLibraryPattern();
if (moveFilesToLibraryPattern) {
try {
unifiedFileMoveService.moveSingleBookFile(bookEntity);
BookEntity book = metadata.getBook();
FileMoveResult result = fileMoveService.moveSingleFile(book);
if (result.isMoved()) {
book.setFileName(result.getNewFileName());
book.setFileSubPath(result.getNewFileSubPath());
}
} catch (Exception e) {
log.warn("Failed to move files for book ID {} after metadata update: {}", bookId, e.getMessage());
}
}
}
private void updateBasicFields(BookMetadata m, BookMetadataEntity e, MetadataClearFlags clear, MetadataReplaceMode replaceMode) {
handleFieldUpdate(e.getTitleLocked(), clear.isTitle(), m.getTitle(), v -> e.setTitle(nullIfBlank(v)), e::getTitle, replaceMode);
handleFieldUpdate(e.getSubtitleLocked(), clear.isSubtitle(), m.getSubtitle(), v -> e.setSubtitle(nullIfBlank(v)), e::getSubtitle, replaceMode);
@@ -191,18 +172,20 @@ public class BookMetadataUpdater {
handleFieldUpdate(e.getHardcoverReviewCountLocked(), clear.isHardcoverReviewCount(), m.getHardcoverReviewCount(), e::setHardcoverReviewCount, e::getHardcoverReviewCount, replaceMode);
}
private <T> void handleFieldUpdate(Boolean locked, boolean shouldClear, T newValue, Consumer<T> setter, Supplier<T> getter, MetadataReplaceMode replaceMode) {
private <T> void handleFieldUpdate(Boolean locked, boolean shouldClear, T newValue, Consumer<T> setter, Supplier<T> getter, MetadataReplaceMode mode) {
if (Boolean.TRUE.equals(locked)) return;
if (shouldClear) {
setter.accept(null);
return;
} else if (replaceMode == MetadataReplaceMode.REPLACE_ALL) {
}
if (mode == null) {
if (newValue != null) setter.accept(newValue);
return;
}
if (mode == MetadataReplaceMode.REPLACE_ALL) {
setter.accept(newValue);
} else if (mode == MetadataReplaceMode.REPLACE_MISSING && isValueMissing(getter.get())) {
setter.accept(newValue);
} else if (replaceMode == MetadataReplaceMode.REPLACE_MISSING) {
T currentValue = getter.get();
if (isValueMissing(currentValue)) {
setter.accept(newValue);
}
}
}
@@ -213,153 +196,154 @@ public class BookMetadataUpdater {
}
private void updateAuthorsIfNeeded(BookMetadata m, BookMetadataEntity e, MetadataClearFlags clear, boolean merge, MetadataReplaceMode replaceMode) {
if (Boolean.TRUE.equals(e.getAuthorsLocked())) {
return;
}
if (e.getAuthors() == null) {
e.setAuthors(new HashSet<>());
}
if (Boolean.TRUE.equals(e.getAuthorsLocked())) return;
e.setAuthors(Optional.ofNullable(e.getAuthors()).orElseGet(HashSet::new));
if (clear.isAuthors()) {
e.getAuthors().clear();
return;
}
if (m.getAuthors() == null) {
if (replaceMode == MetadataReplaceMode.REPLACE_ALL) {
e.getAuthors().clear();
}
Set<String> authorNames = Optional.ofNullable(m.getAuthors()).orElse(Collections.emptySet());
if (authorNames.isEmpty()) {
if (replaceMode == MetadataReplaceMode.REPLACE_ALL) e.getAuthors().clear();
return;
}
Set<AuthorEntity> newAuthors = m.getAuthors().stream()
.filter(a -> a != null && !a.isBlank())
Set<AuthorEntity> newAuthors = authorNames.stream()
.filter(name -> name != null && !name.isBlank())
.map(name -> authorRepository.findByName(name)
.orElseGet(() -> authorRepository.save(AuthorEntity.builder().name(name).build())))
.collect(Collectors.toSet());
if (replaceMode == MetadataReplaceMode.REPLACE_ALL) {
if (merge) {
e.getAuthors().addAll(newAuthors);
} else {
e.getAuthors().clear();
e.getAuthors().addAll(newAuthors);
}
} else if (replaceMode == MetadataReplaceMode.REPLACE_MISSING) {
if (e.getAuthors().isEmpty()) {
e.getAuthors().addAll(newAuthors);
}
if (newAuthors.isEmpty()) return;
boolean replaceAll = replaceMode == MetadataReplaceMode.REPLACE_ALL;
boolean replaceMissing = replaceMode == MetadataReplaceMode.REPLACE_MISSING;
if (replaceAll) {
if (!merge) e.getAuthors().clear();
e.getAuthors().addAll(newAuthors);
} else if (replaceMissing && e.getAuthors().isEmpty()) {
e.getAuthors().addAll(newAuthors);
} else if (replaceMode == null) {
if (!merge) e.getAuthors().clear();
e.getAuthors().addAll(newAuthors);
}
}
private void updateCategoriesIfNeeded(BookMetadata m, BookMetadataEntity e, MetadataClearFlags clear, boolean merge, MetadataReplaceMode replaceMode) {
if (Boolean.TRUE.equals(e.getCategoriesLocked())) {
return;
}
if (e.getCategories() == null) {
e.setCategories(new HashSet<>());
}
if (Boolean.TRUE.equals(e.getCategoriesLocked())) return;
e.setCategories(Optional.ofNullable(e.getCategories()).orElseGet(HashSet::new));
if (clear.isCategories()) {
e.getCategories().clear();
return;
}
if (m.getCategories() == null) {
if (replaceMode == MetadataReplaceMode.REPLACE_ALL) {
e.getCategories().clear();
}
Set<String> categoryNames = Optional.ofNullable(m.getCategories()).orElse(Collections.emptySet());
if (categoryNames.isEmpty()) {
if (replaceMode == MetadataReplaceMode.REPLACE_ALL) e.getCategories().clear();
return;
}
Set<CategoryEntity> newCategories = m.getCategories().stream()
.filter(n -> n != null && !n.isBlank())
Set<CategoryEntity> newCategories = categoryNames.stream()
.filter(name -> name != null && !name.isBlank())
.map(name -> categoryRepository.findByName(name)
.orElseGet(() -> categoryRepository.save(CategoryEntity.builder().name(name).build())))
.collect(Collectors.toSet());
if (replaceMode == MetadataReplaceMode.REPLACE_ALL) {
if (merge) {
e.getCategories().addAll(newCategories);
} else {
e.getCategories().clear();
e.getCategories().addAll(newCategories);
}
} else if (replaceMode == MetadataReplaceMode.REPLACE_MISSING) {
if (e.getCategories().isEmpty()) {
e.getCategories().addAll(newCategories);
}
if (newCategories.isEmpty()) return;
boolean replaceAll = replaceMode == MetadataReplaceMode.REPLACE_ALL;
boolean replaceMissing = replaceMode == MetadataReplaceMode.REPLACE_MISSING;
if (replaceAll) {
if (!merge) e.getCategories().clear();
e.getCategories().addAll(newCategories);
} else if (replaceMissing && e.getCategories().isEmpty()) {
e.getCategories().addAll(newCategories);
} else if (replaceMode == null) {
if (!merge) e.getCategories().clear();
e.getCategories().addAll(newCategories);
}
}
private void updateMoodsIfNeeded(BookMetadata m, BookMetadataEntity e, MetadataClearFlags clear, boolean merge, MetadataReplaceMode replaceMode) {
if (Boolean.TRUE.equals(e.getMoodsLocked())) {
return;
}
if (e.getMoods() == null) {
e.setMoods(new HashSet<>());
}
if (Boolean.TRUE.equals(e.getMoodsLocked())) return;
e.setMoods(Optional.ofNullable(e.getMoods()).orElseGet(HashSet::new));
if (clear.isMoods()) {
e.getMoods().clear();
return;
}
if (m.getMoods() == null) {
if (replaceMode == MetadataReplaceMode.REPLACE_ALL) {
e.getMoods().clear();
}
Set<String> moodNames = Optional.ofNullable(m.getMoods()).orElse(Collections.emptySet());
if (moodNames.isEmpty()) {
if (replaceMode == MetadataReplaceMode.REPLACE_ALL) e.getMoods().clear();
return;
}
Set<MoodEntity> newMoods = m.getMoods().stream()
.filter(n -> n != null && !n.isBlank())
Set<MoodEntity> newMoods = moodNames.stream()
.filter(name -> name != null && !name.isBlank())
.map(name -> moodRepository.findByName(name)
.orElseGet(() -> moodRepository.save(MoodEntity.builder().name(name).build())))
.collect(Collectors.toSet());
if (replaceMode == MetadataReplaceMode.REPLACE_ALL) {
if (merge) {
e.getMoods().addAll(newMoods);
} else {
e.getMoods().clear();
e.getMoods().addAll(newMoods);
}
} else if (replaceMode == MetadataReplaceMode.REPLACE_MISSING) {
if (e.getMoods().isEmpty()) {
e.getMoods().addAll(newMoods);
}
if (newMoods.isEmpty()) return;
boolean replaceAll = replaceMode == MetadataReplaceMode.REPLACE_ALL;
boolean replaceMissing = replaceMode == MetadataReplaceMode.REPLACE_MISSING;
if (replaceAll) {
if (!merge) e.getMoods().clear();
e.getMoods().addAll(newMoods);
} else if (replaceMissing && e.getMoods().isEmpty()) {
e.getMoods().addAll(newMoods);
} else if (replaceMode == null) {
if (!merge) e.getMoods().clear();
e.getMoods().addAll(newMoods);
}
}
private void updateTagsIfNeeded(BookMetadata m, BookMetadataEntity e, MetadataClearFlags clear, boolean merge, MetadataReplaceMode replaceMode) {
if (Boolean.TRUE.equals(e.getTagsLocked())) {
return;
}
if (e.getTags() == null) {
e.setTags(new HashSet<>());
}
if (Boolean.TRUE.equals(e.getTagsLocked())) return;
e.setTags(Optional.ofNullable(e.getTags()).orElseGet(HashSet::new));
if (clear.isTags()) {
e.getTags().clear();
return;
}
if (m.getTags() == null) {
if (replaceMode == MetadataReplaceMode.REPLACE_ALL) {
e.getTags().clear();
}
Set<String> tagNames = Optional.ofNullable(m.getTags()).orElse(Collections.emptySet());
if (tagNames.isEmpty()) {
if (replaceMode == MetadataReplaceMode.REPLACE_ALL) e.getTags().clear();
return;
}
Set<TagEntity> newTags = m.getTags().stream()
.filter(n -> n != null && !n.isBlank())
Set<TagEntity> newTags = tagNames.stream()
.filter(name -> name != null && !name.isBlank())
.map(name -> tagRepository.findByName(name)
.orElseGet(() -> tagRepository.save(TagEntity.builder().name(name).build())))
.collect(Collectors.toSet());
if (replaceMode == MetadataReplaceMode.REPLACE_ALL) {
if (merge) {
e.getTags().addAll(newTags);
} else {
e.getTags().clear();
e.getTags().addAll(newTags);
}
} else if (replaceMode == MetadataReplaceMode.REPLACE_MISSING) {
if (e.getTags().isEmpty()) {
e.getTags().addAll(newTags);
}
if (newTags.isEmpty()) return;
boolean replaceAll = replaceMode == MetadataReplaceMode.REPLACE_ALL;
boolean replaceMissing = replaceMode == MetadataReplaceMode.REPLACE_MISSING;
if (replaceAll) {
if (!merge) e.getTags().clear();
e.getTags().addAll(newTags);
} else if (replaceMissing && e.getTags().isEmpty()) {
e.getTags().addAll(newTags);
} else if (replaceMode == null) {
if (!merge) e.getTags().clear();
e.getTags().addAll(newTags);
}
}

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