diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index cfeb61041..fa85ebacb 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -34,8 +34,8 @@ - [ ] **Code adheres to project style guidelines and conventions** - [ ] **Branch synchronized with latest `develop` branch** _(please resolve any merge conflicts)_ -- [ ] **🚨 CRITICAL: Automated unit/integration tests added/updated to cover changes** _(MANDATORY for ALL backend changes - this is non-negotiable)_ -- [ ] **🚨 CRITICAL: All tests pass locally** _(run `./gradlew test` for backend - NO EXCEPTIONS)_ +- [ ] **🚨 CRITICAL: Automated unit tests added/updated to cover changes** _(MANDATORY for ALL Spring Boot backend and Angular frontend changes - this is non-negotiable)_ +- [ ] **🚨 CRITICAL: All tests pass locally** _(run `./gradlew test` for Spring Boot backend, and `ng test` for Angular frontend - NO EXCEPTIONS)_ - [ ] **🚨 CRITICAL: Manual testing completed in local development environment** _(verify your changes work AND no existing functionality is broken - test related features thoroughly)_ - [ ] **Flyway migration versioning follows correct sequence** _(if database schema was modified)_ - [ ] **Documentation PR submitted to [booklore-docs](https://github.com/booklore-app/booklore-docs)** _(required for features or enhancements that introduce user-facing or visual changes)_ diff --git a/.github/workflows/develop-pipeline.yml b/.github/workflows/develop-pipeline.yml index db3f7a93f..f441c91bc 100644 --- a/.github/workflows/develop-pipeline.yml +++ b/.github/workflows/develop-pipeline.yml @@ -17,34 +17,23 @@ jobs: name: Flyway Migration Check uses: ./.github/workflows/migrations-check.yml with: - base_ref: 'origin/develop' + base_ref: 'develop' head_ref: 'HEAD' - build-and-push: + backend-tests: + name: Backend Tests needs: [ migration-check ] if: needs.migration-check.result == 'success' || needs.migration-check.result == 'skipped' runs-on: ubuntu-latest permissions: contents: read - packages: write checks: write pull-requests: write steps: - name: Checkout Repository uses: actions/checkout@v6 - with: - fetch-depth: 0 - - # ---------------------------------------- - # Environment setup - # ---------------------------------------- - - name: Set Up QEMU for Multi-Arch Builds - uses: docker/setup-qemu-action@v3 - - - name: Set Up Docker Buildx - uses: docker/setup-buildx-action@v3 - name: Set Up JDK 21 uses: actions/setup-java@v5 @@ -53,9 +42,6 @@ jobs: distribution: 'temurin' cache: gradle - # ---------------------------------------- - # Backend tests - # ---------------------------------------- - name: Execute Backend Tests id: backend_tests working-directory: ./booklore-api @@ -75,7 +61,7 @@ jobs: uses: actions/upload-artifact@v6 if: always() with: - name: test-reports + name: backend-test-reports path: | booklore-api/build/reports/tests/ booklore-api/build/test-results/ @@ -87,6 +73,86 @@ jobs: echo "❌ Backend tests failed" exit 1 + frontend-tests: + name: Frontend Tests + needs: [ migration-check ] + if: needs.migration-check.result == 'success' || needs.migration-check.result == 'skipped' + runs-on: ubuntu-latest + + permissions: + contents: read + checks: write + pull-requests: write + + steps: + - name: Checkout Repository + uses: actions/checkout@v6 + + - name: Set Up Node.js + uses: actions/setup-node@v4 + with: + node-version: '22' + cache: 'npm' + cache-dependency-path: booklore-ui/package-lock.json + + - name: Install Frontend Dependencies + working-directory: ./booklore-ui + run: npm ci --force + + - name: Execute Frontend Tests + id: frontend_tests + working-directory: ./booklore-ui + run: | + echo "Running frontend tests..." + npx ng test + continue-on-error: true + + - name: Publish Frontend Test Results + uses: EnricoMi/publish-unit-test-result-action@v2 + if: always() + with: + files: booklore-ui/test-results/vitest-results.xml + check_name: Frontend Test Results + + - name: Upload Frontend Test Reports + uses: actions/upload-artifact@v6 + if: always() + with: + name: frontend-test-reports + path: | + booklore-ui/test-results/vitest-results.xml + retention-days: 30 + + - name: Validate Frontend Test Results + if: steps.frontend_tests.outcome == 'failure' + run: | + echo "❌ Frontend tests failed" + exit 1 + + build-and-push: + name: Build and Push Container + needs: [ backend-tests, frontend-tests ] + runs-on: ubuntu-latest + + permissions: + contents: read + packages: write + + steps: + - name: Checkout Repository + uses: actions/checkout@v6 + with: + fetch-depth: 0 + + # ---------------------------------------- + # Environment setup + # ---------------------------------------- + - name: Set Up QEMU for Multi-Arch Builds + uses: docker/setup-qemu-action@v3 + + - name: Set Up Docker Buildx + uses: docker/setup-buildx-action@v3 + # ---------------------------------------- # Image tagging # ---------------------------------------- diff --git a/.github/workflows/master-pipeline.yml b/.github/workflows/master-pipeline.yml index 808d236af..b60182ad8 100644 --- a/.github/workflows/master-pipeline.yml +++ b/.github/workflows/master-pipeline.yml @@ -69,6 +69,21 @@ jobs: distribution: 'temurin' cache: 'gradle' + - name: Set Up Node.js + uses: actions/setup-node@v4 + with: + node-version: '22' + cache: 'npm' + cache-dependency-path: booklore-ui/package-lock.json + + - name: Install Frontend Dependencies + working-directory: ./booklore-ui + run: npm ci --force + + - name: Execute Frontend Tests + working-directory: ./booklore-ui + run: npm run test:ci + - name: Retrieve Latest Master Version Tag id: get_version run: | @@ -166,4 +181,3 @@ jobs: GITHUB_TOKEN: ${{ github.token }} run: | gh release edit ${{ env.new_tag }} --draft=true - diff --git a/.gitignore b/.gitignore index 0058372b9..d6f72fbe0 100644 --- a/.gitignore +++ b/.gitignore @@ -42,5 +42,6 @@ out/ local/ ### Dev config, books, and data ### +booklore-ui/test-results/ booklore-api/src/main/resources/application-local.yaml /shared/ \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index eeeb2dc0a..2d66f77ca 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -197,6 +197,24 @@ curl http://localhost:8080/actuator/health Always run tests before submitting a pull request to ensure your changes don't break existing functionality. +### Frontend Tests (Angular + Vitest) + +Booklore uses [Vitest](https://vitest.dev/) for fast, modern frontend testing in the Angular app. + +```bash +cd booklore-ui + +# Run all frontend tests +ng test + +# Run tests with coverage report +ng test --coverage +``` + +- The coverage report will be generated in the `coverage/` directory. +- You can open `coverage/index.html` in your browser to view detailed coverage metrics. +- All new features and bug fixes should include relevant unit tests. + ### Backend Tests ```bash diff --git a/README.md b/README.md index 5d0910f4f..bf185be17 100644 --- a/README.md +++ b/README.md @@ -354,7 +354,7 @@ services: Found an issue? -[![Open Issue](https://img.shields.io/badge/Report-ff6b6b?style=for-the-badge)](https://github.com/booklore-app/booklore/issues) +[![Open Issue](https://img.shields.io/badge/Report-ff6b6b?style=for-the-badge)](https://github.com/booklore-app/booklore/issues/new?template=bug_report.yml) @@ -363,7 +363,7 @@ Found an issue? Have an idea? -[![Request Feature](https://img.shields.io/badge/Suggest-4ecdc4?style=for-the-badge)](https://github.com/booklore-app/booklore/issues/new?template=feature_request.md) +[![Request Feature](https://img.shields.io/badge/Suggest-4ecdc4?style=for-the-badge)](https://github.com/booklore-app/booklore/issues/new?template=feature_request.yml) diff --git a/booklore-api/build.gradle b/booklore-api/build.gradle index a54edd655..474f9d92b 100644 --- a/booklore-api/build.gradle +++ b/booklore-api/build.gradle @@ -37,6 +37,9 @@ dependencies { implementation 'org.springframework.boot:spring-boot-starter-mail' implementation 'org.springframework.boot:spring-boot-starter-oauth2-client' + // --- Reactive Streams --- + implementation 'io.projectreactor:reactor-core' + // --- Database & Migration --- implementation 'org.mariadb.jdbc:mariadb-java-client:3.5.6' implementation 'org.flywaydb:flyway-mysql:11.19.0' @@ -55,8 +58,13 @@ dependencies { implementation 'org.apache.pdfbox:pdfbox-io:3.0.6' implementation 'org.apache.pdfbox:xmpbox:3.0.6' implementation 'org.apache.pdfbox:jbig2-imageio:3.0.4' - implementation 'com.github.jai-imageio:jai-imageio-core:1.4.0' - implementation 'com.github.jai-imageio:jai-imageio-jpeg2000:1.4.0' + + // --- TwelveMonkeys ImageIO --- + implementation 'com.twelvemonkeys.imageio:imageio-jpeg:3.13.0' + implementation 'com.twelvemonkeys.imageio:imageio-tiff:3.13.0' + implementation 'com.twelvemonkeys.imageio:imageio-webp:3.13.0' + implementation 'com.twelvemonkeys.imageio:imageio-bmp:3.13.0' + implementation 'io.documentnode:epub4j-core:4.2.2' // --- UNRAR Support --- diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/config/security/SecurityConfig.java b/booklore-api/src/main/java/com/adityachandel/booklore/config/security/SecurityConfig.java index 5d4185742..716eaac9b 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/config/security/SecurityConfig.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/config/security/SecurityConfig.java @@ -1,11 +1,9 @@ package com.adityachandel.booklore.config.security; import com.adityachandel.booklore.config.AppProperties; -import com.adityachandel.booklore.config.security.filter.CoverJwtFilter; -import com.adityachandel.booklore.config.security.filter.DualJwtAuthenticationFilter; -import com.adityachandel.booklore.config.security.filter.KoboAuthFilter; -import com.adityachandel.booklore.config.security.filter.KoreaderAuthFilter; +import com.adityachandel.booklore.config.security.filter.*; import com.adityachandel.booklore.config.security.service.OpdsUserDetailsService; +import jakarta.servlet.DispatcherType; import jakarta.servlet.http.HttpServletResponse; import lombok.AllArgsConstructor; import org.springframework.context.annotation.Bean; @@ -133,6 +131,21 @@ public class SecurityConfig { @Bean @Order(5) + public SecurityFilterChain customFontSecurityChain(HttpSecurity http, CustomFontJwtFilter customFontJwtFilter) throws Exception { + http + .securityMatcher("/api/v1/custom-fonts/*/file") + .cors(cors -> cors.configurationSource(corsConfigurationSource())) + .csrf(AbstractHttpConfigurer::disable) + .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) + .authorizeHttpRequests(auth -> auth + .anyRequest().permitAll() + ) + .addFilterBefore(customFontJwtFilter, UsernamePasswordAuthenticationFilter.class); + return http.build(); + } + + @Bean + @Order(6) public SecurityFilterChain jwtApiSecurityChain(HttpSecurity http) throws Exception { List publicEndpoints = new ArrayList<>(Arrays.asList(COMMON_PUBLIC_ENDPOINTS)); if (appProperties.getSwagger().isEnabled()) { @@ -143,6 +156,7 @@ public class SecurityConfig { .csrf(AbstractHttpConfigurer::disable) .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .authorizeHttpRequests(auth -> auth + .dispatcherTypeMatchers(DispatcherType.ASYNC).permitAll() .requestMatchers(publicEndpoints.toArray(new String[0])).permitAll() .anyRequest().authenticated() ) @@ -152,7 +166,6 @@ public class SecurityConfig { @Bean public AuthenticationManager authenticationManager(HttpSecurity http) throws Exception { - // Configure the shared AuthenticationManagerBuilder with the UserDetailsService and PasswordEncoder AuthenticationManagerBuilder auth = http.getSharedObject(AuthenticationManagerBuilder.class); auth.userDetailsService(opdsUserDetailsService).passwordEncoder(passwordEncoder()); return auth.build(); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/config/security/SecurityUtil.java b/booklore-api/src/main/java/com/adityachandel/booklore/config/security/SecurityUtil.java index 39eb8560e..d6b21af75 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/config/security/SecurityUtil.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/config/security/SecurityUtil.java @@ -50,6 +50,11 @@ public class SecurityUtil { return user != null && user.getPermissions().isCanManageIcons(); } + public boolean canManageFonts() { + var user = getCurrentUser(); + return user != null && user.getPermissions().isCanManageFonts(); + } + public boolean canSyncKoReader() { var user = getCurrentUser(); return user != null && user.getPermissions().isCanSyncKoReader(); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/config/security/filter/AbstractQueryParameterJwtFilter.java b/booklore-api/src/main/java/com/adityachandel/booklore/config/security/filter/AbstractQueryParameterJwtFilter.java new file mode 100644 index 000000000..00328ca69 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/config/security/filter/AbstractQueryParameterJwtFilter.java @@ -0,0 +1,93 @@ +package com.adityachandel.booklore.config.security.filter; + +import com.adityachandel.booklore.config.security.JwtUtils; +import com.adityachandel.booklore.config.security.service.DynamicOidcJwtProcessor; +import com.adityachandel.booklore.config.security.userdetails.UserAuthenticationDetails; +import com.adityachandel.booklore.mapper.custom.BookLoreUserTransformer; +import com.adityachandel.booklore.model.dto.BookLoreUser; +import com.adityachandel.booklore.model.dto.settings.OidcProviderDetails; +import com.adityachandel.booklore.model.entity.BookLoreUserEntity; +import com.adityachandel.booklore.repository.UserRepository; +import com.adityachandel.booklore.service.appsettings.AppSettingService; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.AllArgsConstructor; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; +import java.time.Instant; + +@AllArgsConstructor +public abstract class AbstractQueryParameterJwtFilter extends OncePerRequestFilter { + + protected final JwtUtils jwtUtils; + protected final UserRepository userRepository; + protected final BookLoreUserTransformer bookLoreUserTransformer; + protected final AppSettingService appSettingService; + protected final DynamicOidcJwtProcessor dynamicOidcJwtProcessor; + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) + throws ServletException, IOException { + // Extract token from query parameter (not from Authorization header) + String token = request.getParameter("token"); + 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); + } + + protected void authenticateLocalUser(String token, HttpServletRequest request) { + Long userId = jwtUtils.extractUserId(token); + BookLoreUserEntity entity = userRepository.findById(userId) + .orElseThrow(() -> new UsernameNotFoundException("User not found with ID: " + userId)); + BookLoreUser user = bookLoreUserTransformer.toDTO(entity); + UsernamePasswordAuthenticationToken authentication = + new UsernamePasswordAuthenticationToken(user, null, null); + authentication.setDetails(new UserAuthenticationDetails(request, user.getId())); + SecurityContextHolder.getContext().setAuthentication(authentication); + } + + protected void authenticateOidcUser(String token, HttpServletRequest request) throws Exception { + var processor = dynamicOidcJwtProcessor.getProcessor(); + var claimsSet = processor.process(token, null); + + if (claimsSet.getExpirationTime() == null || + claimsSet.getExpirationTime().toInstant().isBefore(Instant.now())) { + throw new RuntimeException("OIDC token expired or invalid"); + } + + OidcProviderDetails providerDetails = appSettingService.getAppSettings().getOidcProviderDetails(); + OidcProviderDetails.ClaimMapping claimMapping = providerDetails.getClaimMapping(); + String username = claimsSet.getStringClaim(claimMapping.getUsername()); + BookLoreUserEntity entity = userRepository.findByUsername(username) + .orElseThrow(() -> new UsernameNotFoundException("OIDC user not found: " + username)); + BookLoreUser user = bookLoreUserTransformer.toDTO(entity); + + UsernamePasswordAuthenticationToken authentication = + new UsernamePasswordAuthenticationToken(user, null, null); + authentication.setDetails(new UserAuthenticationDetails(request, user.getId())); + SecurityContextHolder.getContext().setAuthentication(authentication); + } +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/config/security/filter/CoverJwtFilter.java b/booklore-api/src/main/java/com/adityachandel/booklore/config/security/filter/CoverJwtFilter.java index 4ad791311..0cb78fb9a 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/config/security/filter/CoverJwtFilter.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/config/security/filter/CoverJwtFilter.java @@ -2,92 +2,27 @@ package com.adityachandel.booklore.config.security.filter; import com.adityachandel.booklore.config.security.JwtUtils; import com.adityachandel.booklore.config.security.service.DynamicOidcJwtProcessor; -import com.adityachandel.booklore.config.security.userdetails.UserAuthenticationDetails; import com.adityachandel.booklore.mapper.custom.BookLoreUserTransformer; -import com.adityachandel.booklore.model.dto.BookLoreUser; -import com.adityachandel.booklore.model.dto.settings.OidcProviderDetails; -import com.adityachandel.booklore.model.entity.BookLoreUserEntity; import com.adityachandel.booklore.repository.UserRepository; import com.adityachandel.booklore.service.appsettings.AppSettingService; -import jakarta.servlet.FilterChain; -import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; -import lombok.AllArgsConstructor; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Component; -import org.springframework.web.filter.OncePerRequestFilter; -import java.io.IOException; -import java.time.Instant; - -@AllArgsConstructor @Component -public class CoverJwtFilter extends OncePerRequestFilter { +public class CoverJwtFilter extends AbstractQueryParameterJwtFilter { - private final JwtUtils jwtUtils; - private final UserRepository userRepository; - private final BookLoreUserTransformer bookLoreUserTransformer; - private final AppSettingService appSettingService; - private final DynamicOidcJwtProcessor dynamicOidcJwtProcessor; + public CoverJwtFilter( + JwtUtils jwtUtils, + UserRepository userRepository, + BookLoreUserTransformer bookLoreUserTransformer, + AppSettingService appSettingService, + DynamicOidcJwtProcessor dynamicOidcJwtProcessor) { + super(jwtUtils, userRepository, bookLoreUserTransformer, appSettingService, dynamicOidcJwtProcessor); + } @Override protected boolean shouldNotFilter(HttpServletRequest request) { String path = request.getRequestURI(); return !path.startsWith("/api/v1/media/"); } - - @Override - protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { - String token = request.getParameter("token"); - 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); - } - - private void authenticateLocalUser(String token, HttpServletRequest request) { - Long userId = jwtUtils.extractUserId(token); - BookLoreUserEntity entity = userRepository.findById(userId).orElseThrow(() -> new UsernameNotFoundException("User not found with ID: " + userId)); - BookLoreUser user = bookLoreUserTransformer.toDTO(entity); - UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user, null, null); - authentication.setDetails(new UserAuthenticationDetails(request, user.getId())); - SecurityContextHolder.getContext().setAuthentication(authentication); - } - - private void authenticateOidcUser(String token, HttpServletRequest request) throws Exception { - var processor = dynamicOidcJwtProcessor.getProcessor(); - var claimsSet = processor.process(token, null); - - if (claimsSet.getExpirationTime() == null || claimsSet.getExpirationTime().toInstant().isBefore(Instant.now())) { - throw new RuntimeException("OIDC token expired or invalid"); - } - - OidcProviderDetails providerDetails = appSettingService.getAppSettings().getOidcProviderDetails(); - OidcProviderDetails.ClaimMapping claimMapping = providerDetails.getClaimMapping(); - String username = claimsSet.getStringClaim(claimMapping.getUsername()); - BookLoreUserEntity entity = userRepository.findByUsername(username).orElseThrow(() -> new UsernameNotFoundException("OIDC user not found: " + username)); - BookLoreUser user = bookLoreUserTransformer.toDTO(entity); - - UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user, null, null); - authentication.setDetails(new UserAuthenticationDetails(request, user.getId())); - SecurityContextHolder.getContext().setAuthentication(authentication); - } } \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/config/security/filter/CustomFontJwtFilter.java b/booklore-api/src/main/java/com/adityachandel/booklore/config/security/filter/CustomFontJwtFilter.java new file mode 100644 index 000000000..b72bc15d1 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/config/security/filter/CustomFontJwtFilter.java @@ -0,0 +1,29 @@ +package com.adityachandel.booklore.config.security.filter; + +import com.adityachandel.booklore.config.security.JwtUtils; +import com.adityachandel.booklore.config.security.service.DynamicOidcJwtProcessor; +import com.adityachandel.booklore.mapper.custom.BookLoreUserTransformer; +import com.adityachandel.booklore.repository.UserRepository; +import com.adityachandel.booklore.service.appsettings.AppSettingService; +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.stereotype.Component; + +@Component +public class CustomFontJwtFilter extends AbstractQueryParameterJwtFilter { + + public CustomFontJwtFilter( + JwtUtils jwtUtils, + UserRepository userRepository, + BookLoreUserTransformer bookLoreUserTransformer, + AppSettingService appSettingService, + DynamicOidcJwtProcessor dynamicOidcJwtProcessor) { + super(jwtUtils, userRepository, bookLoreUserTransformer, appSettingService, dynamicOidcJwtProcessor); + } + + @Override + protected boolean shouldNotFilter(HttpServletRequest request) { + String path = request.getRequestURI(); + // Only filter requests to custom font file endpoints (e.g., /api/v1/custom-fonts/123/file) + return !(path.startsWith("/api/v1/custom-fonts/") && path.endsWith("/file")); + } +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/controller/BackgroundUploadController.java b/booklore-api/src/main/java/com/adityachandel/booklore/controller/BackgroundUploadController.java deleted file mode 100644 index 572be54c4..000000000 --- a/booklore-api/src/main/java/com/adityachandel/booklore/controller/BackgroundUploadController.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.adityachandel.booklore.controller; - -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.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; - -@Tag(name = "Background Upload", description = "Endpoints for uploading and managing background images") -@RestController -@RequestMapping("/api/v1/background") -@RequiredArgsConstructor -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 uploadFile(@Parameter(description = "Background image file") @RequestParam("file") MultipartFile file) { - try { - BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser(); - UploadResponse response = backgroundUploadService.uploadBackgroundFile(file, authenticatedUser.getId()); - return ResponseEntity.ok(response); - } catch (Exception e) { - return ResponseEntity.badRequest().build(); - } - } - - @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 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()); - return ResponseEntity.ok(response); - } catch (Exception e) { - return ResponseEntity.badRequest().build(); - } - } - - @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 resetToDefault() { - try { - BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser(); - backgroundUploadService.resetToDefault(authenticatedUser.getId()); - return ResponseEntity.ok().build(); - } catch (Exception e) { - return ResponseEntity.internalServerError().build(); - } - } -} \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/controller/BookCoverController.java b/booklore-api/src/main/java/com/adityachandel/booklore/controller/BookCoverController.java new file mode 100644 index 000000000..646a52ac7 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/controller/BookCoverController.java @@ -0,0 +1,104 @@ +package com.adityachandel.booklore.controller; + +import com.adityachandel.booklore.config.security.annotation.CheckBookAccess; +import com.adityachandel.booklore.model.dto.CoverImage; +import com.adityachandel.booklore.model.dto.request.BulkBookIdsRequest; +import com.adityachandel.booklore.model.dto.request.CoverFetchRequest; +import com.adityachandel.booklore.service.metadata.BookCoverService; +import com.adityachandel.booklore.service.metadata.DuckDuckGoCoverService; +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; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +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 BookCoverController { + + private final BookCoverService bookCoverService; + private final DuckDuckGoCoverService duckDuckGoCoverService; + + @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 void uploadCoverFromFile( + @Parameter(description = "ID of the book") @PathVariable Long bookId, + @Parameter(description = "Cover image file") @RequestParam("file") MultipartFile file) { + bookCoverService.updateCoverFromFile(bookId, file); + } + + @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 void uploadCoverFromUrl( + @Parameter(description = "ID of the book") @PathVariable Long bookId, + @Parameter(description = "URL body") @RequestBody Map body) { + bookCoverService.updateCoverFromUrl(bookId, body.get("url")); + } + + @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.canBulkRegenerateCover() or @securityUtil.isAdmin()") + public void regenerateCovers() { + bookCoverService.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(@Parameter(description = "ID of the book") @PathVariable Long bookId) { + bookCoverService.regenerateCover(bookId); + } + + @Operation(summary = "Generate custom cover for a book", description = "Generate a custom cover for a specific book based on its metadata. Requires metadata edit permission or admin.") + @ApiResponse(responseCode = "204", description = "Custom cover generated successfully") + @PostMapping("/{bookId}/generate-custom-cover") + @PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()") + @CheckBookAccess(bookIdParam = "bookId") + public void generateCustomCover(@Parameter(description = "ID of the book") @PathVariable Long bookId) { + bookCoverService.generateCustomCover(bookId); + } + + @Operation(summary = "Regenerate covers for selected books", description = "Regenerate covers for a list of books. Requires metadata edit permission or admin.") + @ApiResponse(responseCode = "204", description = "Cover regeneration started successfully") + @PostMapping("/bulk-regenerate-covers") + @PreAuthorize("@securityUtil.canBulkRegenerateCover() or @securityUtil.isAdmin()") + public void regenerateCoversForBooks(@Parameter(description = "List of book IDs") @Validated @RequestBody BulkBookIdsRequest request) { + bookCoverService.regenerateCoversForBooks(request.getBookIds()); + } + + @Operation(summary = "Upload cover image for multiple books", description = "Upload a cover image to apply to multiple books. Requires metadata edit permission or admin.") + @ApiResponse(responseCode = "204", description = "Cover upload started successfully") + @PostMapping("/bulk-upload-cover") + @PreAuthorize("@securityUtil.canBulkEditMetadata() or @securityUtil.isAdmin()") + public void bulkUploadCover( + @Parameter(description = "Cover image file") @RequestParam("file") MultipartFile file, + @Parameter(description = "Comma-separated book IDs") @RequestParam("bookIds") @jakarta.validation.constraints.NotEmpty java.util.Set bookIds) { + bookCoverService.updateCoverFromFileForBooks(bookIds, file); + } + + @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> getImages(@Parameter(description = "Cover fetch request") @RequestBody CoverFetchRequest request) { + return ResponseEntity.ok(duckDuckGoCoverService.getCovers(request)); + } +} \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/controller/BookMediaController.java b/booklore-api/src/main/java/com/adityachandel/booklore/controller/BookMediaController.java index 1064db60e..77660ccdb 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/controller/BookMediaController.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/controller/BookMediaController.java @@ -91,36 +91,4 @@ public class BookMediaController { .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 getBackgroundImage() { - try { - Resource file = bookService.getBackgroundImage(); - if (file == null || !file.exists()) { - return ResponseEntity.notFound().build(); - } - - String filename = file.getFilename(); - MediaType mediaType = filename != null && filename.endsWith(".png") - ? MediaType.IMAGE_PNG - : MediaType.IMAGE_JPEG; - - if (filename == null) { - return ResponseEntity.badRequest().build(); - } - - String encodedFilename = URLEncoder.encode(filename, StandardCharsets.UTF_8).replace("+", "%20"); - String fallbackFilename = NON_ASCII_PATTERN.matcher(filename).replaceAll("_"); - String contentDisposition = String.format("inline; filename=\"%s\"; filename*=UTF-8''%s", - fallbackFilename, encodedFilename); - return ResponseEntity.ok() - .header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition) - .contentType(mediaType) - .body(file); - } catch (Exception e) { - return ResponseEntity.internalServerError().build(); - } - } } \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/controller/CustomFontController.java b/booklore-api/src/main/java/com/adityachandel/booklore/controller/CustomFontController.java new file mode 100644 index 000000000..00d877c1c --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/controller/CustomFontController.java @@ -0,0 +1,80 @@ +package com.adityachandel.booklore.controller; + +import com.adityachandel.booklore.config.security.service.AuthenticationService; +import com.adityachandel.booklore.model.dto.BookLoreUser; +import com.adityachandel.booklore.model.dto.CustomFontDto; +import com.adityachandel.booklore.model.enums.FontFormat; +import com.adityachandel.booklore.service.customfont.CustomFontService; +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.core.io.Resource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + +@Tag(name = "Custom Fonts", description = "Endpoints for managing custom fonts for EPUB reader") +@RestController +@RequestMapping("/api/v1/custom-fonts") +@RequiredArgsConstructor +public class CustomFontController { + + private final CustomFontService customFontService; + private final AuthenticationService authenticationService; + + @Operation(summary = "Upload a custom font", description = "Upload a custom font file (.ttf, .otf, .woff, .woff2) for the authenticated user") + @ApiResponse(responseCode = "200", description = "Font uploaded successfully") + @ApiResponse(responseCode = "400", description = "Invalid file or quota exceeded") + @PostMapping("/upload") + @PreAuthorize("@securityUtil.canManageFonts() or @securityUtil.isAdmin()") + public ResponseEntity uploadFont( + @Parameter(description = "Font file (.ttf, .otf, .woff, .woff2)") @RequestParam("file") MultipartFile file, + @Parameter(description = "Font display name") @RequestParam(value = "fontName", required = false) String fontName) { + BookLoreUser user = authenticationService.getAuthenticatedUser(); + CustomFontDto fontDto = customFontService.uploadFont(file, fontName, user.getId()); + return ResponseEntity.ok(fontDto); + } + + @Operation(summary = "Get all user's custom fonts", description = "Retrieve all custom fonts for the authenticated user") + @ApiResponse(responseCode = "200", description = "Fonts retrieved successfully") + @GetMapping + @PreAuthorize("@securityUtil.canManageFonts() or @securityUtil.isAdmin()") + public ResponseEntity> getUserFonts() { + BookLoreUser user = authenticationService.getAuthenticatedUser(); + List fonts = customFontService.getUserFonts(user.getId()); + return ResponseEntity.ok(fonts); + } + + @Operation(summary = "Delete a custom font", description = "Delete a custom font file and database record") + @ApiResponse(responseCode = "200", description = "Font deleted successfully") + @ApiResponse(responseCode = "404", description = "Font not found or access denied") + @DeleteMapping("/{fontId}") + @PreAuthorize("@securityUtil.canManageFonts() or @securityUtil.isAdmin()") + public ResponseEntity deleteFont(@PathVariable Long fontId) { + BookLoreUser user = authenticationService.getAuthenticatedUser(); + customFontService.deleteFont(fontId, user.getId()); + return ResponseEntity.ok().build(); + } + + @Operation(summary = "Get font file", description = "Retrieve the font file for use in the browser") + @ApiResponse(responseCode = "200", description = "Font file retrieved successfully") + @ApiResponse(responseCode = "404", description = "Font not found or access denied") + @GetMapping("/{fontId}/file") + @PreAuthorize("@securityUtil.canManageFonts() or @securityUtil.isAdmin()") + public ResponseEntity getFontFile(@PathVariable Long fontId) { + BookLoreUser user = authenticationService.getAuthenticatedUser(); + Resource resource = customFontService.getFontFile(fontId, user.getId()); + FontFormat format = customFontService.getFontFormat(fontId, user.getId()); + return ResponseEntity.ok() + .contentType(MediaType.parseMediaType(format.getMimeType())) + .header(HttpHeaders.CONTENT_DISPOSITION, "inline") + .body(resource); + } +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/controller/HardcoverSyncSettingsController.java b/booklore-api/src/main/java/com/adityachandel/booklore/controller/HardcoverSyncSettingsController.java new file mode 100644 index 000000000..8129a5226 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/controller/HardcoverSyncSettingsController.java @@ -0,0 +1,42 @@ +package com.adityachandel.booklore.controller; + +import com.adityachandel.booklore.model.dto.HardcoverSyncSettings; +import com.adityachandel.booklore.service.hardcover.HardcoverSyncSettingsService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/api/v1/hardcover-sync-settings") +@RequiredArgsConstructor +@Tag(name = "Hardcover Sync Settings", description = "Endpoints for managing Hardcover progress sync settings") +public class HardcoverSyncSettingsController { + + private final HardcoverSyncSettingsService hardcoverSyncSettingsService; + + @Operation(summary = "Get Hardcover sync settings", description = "Retrieve the current user's Hardcover sync settings.") + @ApiResponse(responseCode = "200", description = "Settings returned successfully") + @GetMapping + @PreAuthorize("@securityUtil.canSyncKobo() or @securityUtil.canSyncKoReader() or @securityUtil.isAdmin()") + public ResponseEntity getSettings() { + HardcoverSyncSettings settings = hardcoverSyncSettingsService.getCurrentUserSettings(); + return ResponseEntity.ok(settings); + } + + @Operation(summary = "Update Hardcover sync settings", description = "Update the current user's Hardcover sync settings.") + @ApiResponse(responseCode = "200", description = "Settings updated successfully") + @PutMapping + @PreAuthorize("@securityUtil.canSyncKobo() or @securityUtil.canSyncKoReader() or @securityUtil.isAdmin()") + public ResponseEntity updateSettings(@RequestBody HardcoverSyncSettings settings) { + HardcoverSyncSettings updated = hardcoverSyncSettingsService.updateCurrentUserSettings(settings); + return ResponseEntity.ok(updated); + } +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/controller/LibraryController.java b/booklore-api/src/main/java/com/adityachandel/booklore/controller/LibraryController.java index ab2d44260..bdc994606 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/controller/LibraryController.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/controller/LibraryController.java @@ -41,8 +41,7 @@ public class LibraryController { }) @GetMapping("/{libraryId}") @CheckLibraryAccess(libraryIdParam = "libraryId") - public ResponseEntity getLibrary( - @Parameter(description = "ID of the library") @PathVariable long libraryId) { + public ResponseEntity getLibrary(@Parameter(description = "ID of the library") @PathVariable long libraryId) { return ResponseEntity.ok(libraryService.getLibrary(libraryId)); } @@ -50,8 +49,7 @@ public class LibraryController { @ApiResponse(responseCode = "200", description = "Library created successfully") @PostMapping @PreAuthorize("@securityUtil.canManageLibrary() or @securityUtil.isAdmin()") - public ResponseEntity createLibrary( - @Parameter(description = "Library creation request") @Validated @RequestBody CreateLibraryRequest request) { + public ResponseEntity createLibrary(@Parameter(description = "Library creation request") @Validated @RequestBody CreateLibraryRequest request) { return ResponseEntity.ok(libraryService.createLibrary(request)); } @@ -71,8 +69,7 @@ public class LibraryController { @DeleteMapping("/{libraryId}") @CheckLibraryAccess(libraryIdParam = "libraryId") @PreAuthorize("@securityUtil.canManageLibrary() or @securityUtil.isAdmin()") - public ResponseEntity deleteLibrary( - @Parameter(description = "ID of the library") @PathVariable long libraryId) { + public ResponseEntity deleteLibrary(@Parameter(description = "ID of the library") @PathVariable long libraryId) { libraryService.deleteLibrary(libraryId); return ResponseEntity.noContent().build(); } @@ -91,8 +88,7 @@ public class LibraryController { @ApiResponse(responseCode = "200", description = "Books returned successfully") @GetMapping("/{libraryId}/book") @CheckLibraryAccess(libraryIdParam = "libraryId") - public ResponseEntity> getBooks( - @Parameter(description = "ID of the library") @PathVariable long libraryId) { + public ResponseEntity> getBooks(@Parameter(description = "ID of the library") @PathVariable long libraryId) { List books = libraryService.getBooks(libraryId); return ResponseEntity.ok(books); } @@ -119,4 +115,15 @@ public class LibraryController { Library updated = libraryService.setFileNamingPattern(libraryId, pattern); return ResponseEntity.ok(updated); } + + @Operation(summary = "Scan library paths", description = "Scan the provided library paths and return a count of processable files. Requires admin or manipulation permission.") + @ApiResponse(responseCode = "200", description = "Processable files count returned successfully") + @PostMapping("/scan") + @PreAuthorize("@securityUtil.canManageLibrary() or @securityUtil.isAdmin()") + public ResponseEntity scanLibraryPaths( + @Parameter(description = "Library creation request with paths to scan") + @Validated @RequestBody CreateLibraryRequest request) { + int processableFilesCount = libraryService.scanLibraryPaths(request); + return ResponseEntity.ok(processableFilesCount); + } } \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/controller/MetadataController.java b/booklore-api/src/main/java/com/adityachandel/booklore/controller/MetadataController.java index 074a89449..ee797e06a 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/controller/MetadataController.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/controller/MetadataController.java @@ -6,25 +6,27 @@ import com.adityachandel.booklore.mapper.BookMetadataMapper; 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.CoverImage; import com.adityachandel.booklore.model.dto.request.*; import com.adityachandel.booklore.model.entity.BookEntity; import com.adityachandel.booklore.model.enums.MetadataReplaceMode; import com.adityachandel.booklore.repository.BookRepository; -import com.adityachandel.booklore.service.metadata.*; +import com.adityachandel.booklore.service.metadata.BookMetadataService; +import com.adityachandel.booklore.service.metadata.BookMetadataUpdater; +import com.adityachandel.booklore.service.metadata.MetadataManagementService; +import com.adityachandel.booklore.service.metadata.MetadataMatchService; 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.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; -import org.springframework.web.multipart.MultipartFile; +import reactor.core.publisher.Flux; import java.util.List; -import java.util.Map; @RestController @RequestMapping("/api/v1/books") @@ -36,19 +38,18 @@ public class MetadataController { private final BookMetadataUpdater bookMetadataUpdater; private final BookMetadataMapper bookMetadataMapper; private final MetadataMatchService metadataMatchService; - private final DuckDuckGoCoverService duckDuckGoCoverService; 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") + @PostMapping(value = "/{bookId}/metadata/prospective", produces = MediaType.TEXT_EVENT_STREAM_VALUE) @PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()") @CheckBookAccess(bookIdParam = "bookId") - public ResponseEntity> getMetadataList( + public Flux 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)); + return bookMetadataService.getProspectiveMetadataListForBookId(bookId, fetchMetadataRequest); } @Operation(summary = "Update book metadata", description = "Update metadata for a book. Requires metadata edit permission or admin.") @@ -84,8 +85,7 @@ public class MetadataController { @ApiResponse(responseCode = "204", description = "Bulk metadata updated successfully") @PutMapping("/bulk-edit-metadata") @PreAuthorize("@securityUtil.canBulkEditMetadata() or @securityUtil.isAdmin()") - public ResponseEntity bulkEditMetadata( - @Parameter(description = "Bulk metadata update request") @RequestBody BulkMetadataUpdateRequest bulkMetadataUpdateRequest) { + public ResponseEntity bulkEditMetadata(@Parameter(description = "Bulk metadata update request") @RequestBody BulkMetadataUpdateRequest bulkMetadataUpdateRequest) { boolean mergeCategories = bulkMetadataUpdateRequest.isMergeCategories(); boolean mergeMoods = bulkMetadataUpdateRequest.isMergeMoods(); boolean mergeTags = bulkMetadataUpdateRequest.isMergeTags(); @@ -93,36 +93,11 @@ public class MetadataController { 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 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 uploadCoverFromUrl( - @Parameter(description = "ID of the book") @PathVariable Long bookId, - @Parameter(description = "URL body") @RequestBody Map 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.canBulkLockUnlockMetadata() or @securityUtil.isAdmin()") - public ResponseEntity> toggleAllMetadata( - @Parameter(description = "Toggle all lock request") @RequestBody ToggleAllLockRequest request) { + public ResponseEntity> toggleAllMetadata(@Parameter(description = "Toggle all lock request") @RequestBody ToggleAllLockRequest request) { return ResponseEntity.ok(bookMetadataService.toggleAllLock(request)); } @@ -130,61 +105,11 @@ public class MetadataController { @ApiResponse(responseCode = "200", description = "Field locks toggled successfully") @PutMapping("/metadata/toggle-field-locks") @PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()") - public ResponseEntity> toggleFieldLocks( - @Parameter(description = "Toggle field locks request") @RequestBody ToggleFieldLocksRequest request) { + public ResponseEntity> 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.canBulkRegenerateCover() 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( - @Parameter(description = "ID of the book") @PathVariable Long bookId) { - bookMetadataService.regenerateCover(bookId); - } - - @Operation(summary = "Generate custom cover for a book", description = "Generate a custom cover for a specific book based on its metadata. Requires metadata edit permission or admin.") - @ApiResponse(responseCode = "204", description = "Custom cover generated successfully") - @PostMapping("/{bookId}/generate-custom-cover") - @PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()") - @CheckBookAccess(bookIdParam = "bookId") - public void generateCustomCover( - @Parameter(description = "ID of the book") @PathVariable Long bookId) { - bookMetadataService.generateCustomCover(bookId); - } - - @Operation(summary = "Regenerate covers for selected books", description = "Regenerate covers for a list of books. Requires metadata edit permission or admin.") - @ApiResponse(responseCode = "204", description = "Cover regeneration started successfully") - @PostMapping("/bulk-regenerate-covers") - @PreAuthorize("@securityUtil.canBulkRegenerateCover() or @securityUtil.isAdmin()") - public ResponseEntity regenerateCoversForBooks( - @Parameter(description = "List of book IDs") @Validated @RequestBody BulkBookIdsRequest request) { - bookMetadataService.regenerateCoversForBooks(request.getBookIds()); - return ResponseEntity.noContent().build(); - } - - @Operation(summary = "Upload cover image for multiple books", description = "Upload a cover image to apply to multiple books. Requires metadata edit permission or admin.") - @ApiResponse(responseCode = "204", description = "Cover upload started successfully") - @PostMapping("/bulk-upload-cover") - @PreAuthorize("@securityUtil.canBulkEditMetadata() or @securityUtil.isAdmin()") - public ResponseEntity bulkUploadCover( - @Parameter(description = "Cover image file") @RequestParam("file") MultipartFile file, - @Parameter(description = "Comma-separated book IDs") @RequestParam("bookIds") @jakarta.validation.constraints.NotEmpty java.util.Set bookIds) { - bookMetadataService.updateCoverImageFromFileForBooks(bookIds, file); - return ResponseEntity.noContent().build(); - } - @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") @@ -194,20 +119,11 @@ 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> 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.canBulkEditMetadata() or @securityUtil.isAdmin()") - public ResponseEntity mergeMetadata( - @Parameter(description = "Merge metadata request") @Validated @RequestBody MergeMetadataRequest request) { + public ResponseEntity mergeMetadata(@Parameter(description = "Merge metadata request") @Validated @RequestBody MergeMetadataRequest request) { metadataManagementService.consolidateMetadata(request.getMetadataType(), request.getTargetValues(), request.getValuesToMerge()); return ResponseEntity.noContent().build(); } @@ -216,9 +132,9 @@ public class MetadataController { @ApiResponse(responseCode = "204", description = "Metadata deleted successfully") @PostMapping("/metadata/manage/delete") @PreAuthorize("@securityUtil.canBulkEditMetadata() or @securityUtil.isAdmin()") - public ResponseEntity deleteMetadata( - @Parameter(description = "Delete metadata request") @Validated @RequestBody DeleteMetadataRequest request) { + public ResponseEntity deleteMetadata(@Parameter(description = "Delete metadata request") @Validated @RequestBody DeleteMetadataRequest request) { metadataManagementService.deleteMetadata(request.getMetadataType(), request.getValuesToDelete()); return ResponseEntity.noContent().build(); } -} \ No newline at end of file +} + diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/exception/GlobalExceptionHandler.java b/booklore-api/src/main/java/com/adityachandel/booklore/exception/GlobalExceptionHandler.java index 31a361650..f026289a0 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/exception/GlobalExceptionHandler.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/exception/GlobalExceptionHandler.java @@ -93,6 +93,27 @@ public class GlobalExceptionHandler { return new ResponseEntity<>(errorResponse, HttpStatus.OK); } + @ExceptionHandler(IllegalArgumentException.class) + public ResponseEntity handleIllegalArgumentException(IllegalArgumentException ex) { + log.warn("Illegal argument: {}", ex.getMessage()); + ErrorResponse errorResponse = new ErrorResponse(HttpStatus.BAD_REQUEST.value(), ex.getMessage()); + return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST); + } + + @ExceptionHandler(IllegalStateException.class) + public ResponseEntity handleIllegalStateException(IllegalStateException ex) { + log.error("Illegal state: {}", ex.getMessage(), ex); + ErrorResponse errorResponse = new ErrorResponse(HttpStatus.CONFLICT.value(), ex.getMessage()); + return new ResponseEntity<>(errorResponse, HttpStatus.CONFLICT); + } + + @ExceptionHandler(UnsupportedOperationException.class) + public ResponseEntity handleUnsupportedOperationException(UnsupportedOperationException ex) { + log.error("Unsupported operation: {}", ex.getMessage(), ex); + ErrorResponse errorResponse = new ErrorResponse(HttpStatus.NOT_IMPLEMENTED.value(), ex.getMessage()); + return new ResponseEntity<>(errorResponse, HttpStatus.NOT_IMPLEMENTED); + } + @ExceptionHandler(Exception.class) public ResponseEntity handleGenericException(Exception ex) { ErrorResponse errorResponse = new ErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR.value(), ex.getMessage()); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/mapper/CustomFontMapper.java b/booklore-api/src/main/java/com/adityachandel/booklore/mapper/CustomFontMapper.java new file mode 100644 index 000000000..08da6c1fc --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/mapper/CustomFontMapper.java @@ -0,0 +1,11 @@ +package com.adityachandel.booklore.mapper; + +import com.adityachandel.booklore.model.dto.CustomFontDto; +import com.adityachandel.booklore.model.entity.CustomFontEntity; +import org.mapstruct.Mapper; + +@Mapper(componentModel = "spring") +public interface CustomFontMapper { + + CustomFontDto toDto(CustomFontEntity entity); +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/BookLoreUser.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/BookLoreUser.java index d10f9daae..e34723e33 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/BookLoreUser.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/BookLoreUser.java @@ -44,6 +44,7 @@ public class BookLoreUser { private boolean canAccessTaskManager; private boolean canManageGlobalPreferences; private boolean canManageIcons; + private boolean canManageFonts; private boolean isDemoUser; private boolean canBulkAutoFetchMetadata; private boolean canBulkCustomFetchMetadata; diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/BookMetadata.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/BookMetadata.java index d6dfc0778..544ec5b78 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/BookMetadata.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/BookMetadata.java @@ -46,6 +46,7 @@ public class BookMetadata { private Double lubimyczytacRating; private String googleId; private String lubimyczytacId; + private String externalUrl; private Instant coverUpdatedOn; private Set authors; private Set categories; @@ -84,6 +85,7 @@ public class BookMetadata { private Boolean doubanReviewCountLocked; private Boolean lubimyczytacIdLocked; private Boolean lubimyczytacRatingLocked; + private Boolean externalUrlLocked; private Boolean coverLocked; private Boolean authorsLocked; private Boolean categoriesLocked; diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/CustomFontDto.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/CustomFontDto.java new file mode 100644 index 000000000..7017b6548 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/CustomFontDto.java @@ -0,0 +1,22 @@ +package com.adityachandel.booklore.model.dto; + +import com.adityachandel.booklore.model.enums.FontFormat; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.time.LocalDateTime; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class CustomFontDto { + private Long id; + private String fontName; + private String originalFileName; + private FontFormat format; + private Long fileSize; + private LocalDateTime uploadedAt; +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/EpubViewerPreferences.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/EpubViewerPreferences.java index 258f67bf1..3036a24d9 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/EpubViewerPreferences.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/EpubViewerPreferences.java @@ -14,4 +14,5 @@ public class EpubViewerPreferences { private Integer fontSize; private Float letterSpacing; private Float lineHeight; + private Long customFontId; } \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/HardcoverSyncSettings.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/HardcoverSyncSettings.java new file mode 100644 index 000000000..a0bfd8ed1 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/HardcoverSyncSettings.java @@ -0,0 +1,9 @@ +package com.adityachandel.booklore.model.dto; + +import lombok.Data; + +@Data +public class HardcoverSyncSettings { + private String hardcoverApiKey; + private boolean hardcoverSyncEnabled; +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/RuleField.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/RuleField.java index dfa3f033a..3c53f0b8b 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/RuleField.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/RuleField.java @@ -27,6 +27,10 @@ public enum RuleField { PAGE_COUNT, @JsonProperty("language") LANGUAGE, + @JsonProperty("isbn13") + ISBN13, + @JsonProperty("isbn10") + ISBN10, @JsonProperty("amazonRating") AMAZON_RATING, @JsonProperty("amazonReviewCount") @@ -56,6 +60,8 @@ public enum RuleField { @JsonProperty("moods") MOODS, @JsonProperty("tags") - TAGS + TAGS, + @JsonProperty("genre") + GENRE } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/UserCreateRequest.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/UserCreateRequest.java index 4365a8bea..133a1d485 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/UserCreateRequest.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/UserCreateRequest.java @@ -28,6 +28,7 @@ public class UserCreateRequest { private boolean permissionAccessTaskManager; private boolean permissionManageGlobalPreferences; private boolean permissionManageIcons; + private boolean permissionManageFonts; private boolean permissionBulkAutoFetchMetadata; private boolean permissionBulkCustomFetchMetadata; private boolean permissionBulkEditMetadata; diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/kobo/KoboBookMetadata.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/kobo/KoboBookMetadata.java index 1d560f645..f3e5f5436 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/kobo/KoboBookMetadata.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/kobo/KoboBookMetadata.java @@ -28,6 +28,7 @@ public class KoboBookMetadata { private String language = "en"; private String isbn; + @Builder.Default private String genre = "00000000-0000-0000-0000-000000000001"; private String slug; private String coverImageId; diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/MetadataRefreshOptions.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/MetadataRefreshOptions.java index 3c9745b97..ebdc9d22f 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/MetadataRefreshOptions.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/MetadataRefreshOptions.java @@ -51,12 +51,14 @@ public class MetadataRefreshOptions { private FieldProvider comicvineId; private FieldProvider hardcoverId; private FieldProvider googleId; + private FieldProvider lubimyczytacId; private FieldProvider amazonRating; private FieldProvider amazonReviewCount; private FieldProvider goodreadsRating; private FieldProvider goodreadsReviewCount; private FieldProvider hardcoverRating; private FieldProvider hardcoverReviewCount; + private FieldProvider lubimyczytacRating; private FieldProvider moods; private FieldProvider tags; } @@ -99,12 +101,14 @@ public class MetadataRefreshOptions { private boolean comicvineId; private boolean hardcoverId; private boolean googleId; + private boolean lubimyczytacId; private boolean amazonRating; private boolean amazonReviewCount; private boolean goodreadsRating; private boolean goodreadsReviewCount; private boolean hardcoverRating; private boolean hardcoverReviewCount; + private boolean lubimyczytacRating; private boolean moods; private boolean tags; } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/UserUpdateRequest.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/UserUpdateRequest.java index 113a43673..9b1c2572b 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/UserUpdateRequest.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/UserUpdateRequest.java @@ -30,6 +30,7 @@ public class UserUpdateRequest { private boolean canAccessTaskManager; private boolean canManageGlobalPreferences; private boolean canManageIcons; + private boolean canManageFonts; private boolean canBulkAutoFetchMetadata; private boolean canBulkCustomFetchMetadata; private boolean canBulkEditMetadata; diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/comicvineapi/Comic.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/comicvineapi/Comic.java index d85ee6e20..39d616f82 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/comicvineapi/Comic.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/comicvineapi/Comic.java @@ -5,6 +5,8 @@ import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; import lombok.NoArgsConstructor; +import java.util.List; + @Data @NoArgsConstructor @JsonIgnoreProperties(ignoreUnknown = true) @@ -32,6 +34,30 @@ public class Comic { @JsonProperty("resource_type") private String resourceType; + @JsonProperty("person_credits") + private List personCredits; + + @JsonProperty("start_year") + private String startYear; + + @JsonProperty("count_of_issues") + private Integer countOfIssues; + + @JsonProperty("site_detail_url") + private String siteDetailUrl; + + private Publisher publisher; + + @Data + @NoArgsConstructor + @JsonIgnoreProperties(ignoreUnknown = true) + public static class Publisher { + private int id; + private String name; + @JsonProperty("api_detail_url") + private String apiDetailUrl; + } + @Data @NoArgsConstructor @JsonIgnoreProperties(ignoreUnknown = true) @@ -79,5 +105,20 @@ public class Comic { @JsonProperty("site_detail_url") private String siteDetailUrl; + + @JsonProperty("start_year") + private String startYear; + + @JsonProperty("count_of_issues") + private Integer countOfIssues; + } + + @Data + @NoArgsConstructor + @JsonIgnoreProperties(ignoreUnknown = true) + public static class PersonCredit { + private long id; + private String name; + private String role; } } \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/comicvineapi/ComicvineIssueResponse.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/comicvineapi/ComicvineIssueResponse.java index 62b7f3a51..2932ed652 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/comicvineapi/ComicvineIssueResponse.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/comicvineapi/ComicvineIssueResponse.java @@ -22,14 +22,26 @@ public class ComicvineIssueResponse { @JsonIgnoreProperties(ignoreUnknown = true) public static class IssueResults { @JsonProperty("person_credits") - private List personCredits; - } + private List personCredits; + + private String description; - @Data - @JsonIgnoreProperties(ignoreUnknown = true) - public static class PersonCredit { - private long id; private String name; - private String role; + + @JsonProperty("issue_number") + private String issueNumber; + + @JsonProperty("cover_date") + private String coverDate; + + private Comic.Image image; + + private Comic.Volume volume; + + @JsonProperty("api_detail_url") + private String apiDetailUrl; + + @JsonProperty("site_detail_url") + private String siteDetailUrl; } } \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/AppSettingKey.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/AppSettingKey.java index 7a8a6be43..606c36ba1 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/AppSettingKey.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/AppSettingKey.java @@ -20,7 +20,7 @@ public enum AppSettingKey { LIBRARY_METADATA_REFRESH_OPTIONS ("library_metadata_refresh_options", true, false, List.of(PermissionType.ADMIN, PermissionType.MANAGE_METADATA_CONFIG)), METADATA_PROVIDER_SETTINGS ("metadata_provider_settings", true, false, List.of(PermissionType.ADMIN, PermissionType.MANAGE_METADATA_CONFIG)), METADATA_MATCH_WEIGHTS ("metadata_match_weights", true, false, List.of(PermissionType.ADMIN, PermissionType.MANAGE_METADATA_CONFIG)), - METADATA_PERSISTENCE_SETTINGS ("metadata_persistence_settings", true, false, List.of(PermissionType.ADMIN, PermissionType.MANAGE_METADATA_CONFIG)), + METADATA_PERSISTENCE_SETTINGS ("metadata_persistence_settings_v2", true, false, List.of(PermissionType.ADMIN, PermissionType.MANAGE_METADATA_CONFIG)), METADATA_PUBLIC_REVIEWS_SETTINGS ("metadata_public_reviews_settings", true, false, List.of(PermissionType.ADMIN, PermissionType.MANAGE_METADATA_CONFIG)), UPLOAD_FILE_PATTERN ("upload_file_pattern", false, false, List.of(PermissionType.ADMIN, PermissionType.MANAGE_METADATA_CONFIG)), MOVE_FILE_PATTERN ("move_file_pattern", false, false, List.of(PermissionType.ADMIN, PermissionType.MANAGE_METADATA_CONFIG)), diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/MetadataPersistenceSettings.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/MetadataPersistenceSettings.java index 6d296a2d9..907270f73 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/MetadataPersistenceSettings.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/MetadataPersistenceSettings.java @@ -10,7 +10,30 @@ import lombok.NoArgsConstructor; @NoArgsConstructor @AllArgsConstructor public class MetadataPersistenceSettings { - private boolean saveToOriginalFile; + private SaveToOriginalFile saveToOriginalFile; private boolean convertCbrCb7ToCbz; private boolean moveFilesToLibraryPattern; + + @Data + @Builder + @NoArgsConstructor + @AllArgsConstructor + public static class SaveToOriginalFile { + private FormatSettings epub; + private FormatSettings pdf; + private FormatSettings cbx; + + public boolean isAnyFormatEnabled() { + return (epub != null && epub.isEnabled()) || (pdf != null && pdf.isEnabled() || (cbx != null && cbx.isEnabled())); + } + } + + @Data + @Builder + @NoArgsConstructor + @AllArgsConstructor + public static class FormatSettings { + private boolean enabled; + private int maxFileSizeInMb; + } } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/UserSettingKey.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/UserSettingKey.java index b051f1504..6ce1feed5 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/UserSettingKey.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/UserSettingKey.java @@ -18,7 +18,9 @@ public enum UserSettingKey { FILTER_MODE("filterMode", false), FILTER_SORTING_MODE("filterSortingMode", false), METADATA_CENTER_VIEW_MODE("metadataCenterViewMode", false), - ENABLE_SERIES_VIEW("enableSeriesView", false); + ENABLE_SERIES_VIEW("enableSeriesView", false), + HARDCOVER_API_KEY("hardcoverApiKey", false), + HARDCOVER_SYNC_ENABLED("hardcoverSyncEnabled", false); private final String dbKey; @@ -42,4 +44,4 @@ public enum UserSettingKey { } throw new IllegalArgumentException("Unknown setting key: " + dbKey); } -} \ No newline at end of file +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/CustomFontEntity.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/CustomFontEntity.java new file mode 100644 index 000000000..cc9089af0 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/CustomFontEntity.java @@ -0,0 +1,44 @@ +package com.adityachandel.booklore.model.entity; + +import com.adityachandel.booklore.model.enums.FontFormat; +import jakarta.persistence.*; +import lombok.*; + +import java.time.LocalDateTime; + +@Entity +@Getter +@Setter +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Table(name = "custom_font") +public class CustomFontEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "user_id", nullable = false) + private BookLoreUserEntity user; + + @Column(name = "font_name", nullable = false) + private String fontName; + + @Column(name = "file_name", nullable = false, unique = true) + private String fileName; + + @Column(name = "original_file_name", nullable = false) + private String originalFileName; + + @Enumerated(EnumType.STRING) + @Column(name = "format", nullable = false) + private FontFormat format; + + @Column(name = "file_size", nullable = false) + private Long fileSize; + + @Column(name = "uploaded_at", nullable = false) + private LocalDateTime uploadedAt; +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/EpubViewerPreferencesEntity.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/EpubViewerPreferencesEntity.java index 5e6fb116d..7de62e30c 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/EpubViewerPreferencesEntity.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/EpubViewerPreferencesEntity.java @@ -44,4 +44,7 @@ public class EpubViewerPreferencesEntity { @Column(name = "spread") private String spread; + + @Column(name = "custom_font_id") + private Long customFontId; } \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/UserPermissionsEntity.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/UserPermissionsEntity.java index 51dac9d13..beb6a6249 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/UserPermissionsEntity.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/UserPermissionsEntity.java @@ -87,6 +87,10 @@ public class UserPermissionsEntity { @Builder.Default private boolean permissionManageIcons = false; + @Column(name = "permission_manage_fonts", nullable = false) + @Builder.Default + private boolean permissionManageFonts = false; + @Column(name = "permission_demo_user", nullable = false) @Builder.Default private boolean permissionDemoUser = false; diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/enums/BookFileType.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/enums/BookFileType.java index 21a9c9a2e..b19b6749e 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/enums/BookFileType.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/enums/BookFileType.java @@ -1,5 +1,33 @@ package com.adityachandel.booklore.model.enums; +import lombok.Getter; + +import java.util.Arrays; +import java.util.Optional; +import java.util.Set; + +@Getter public enum BookFileType { - PDF, EPUB, CBX, FB2 + + PDF(Set.of("pdf")), + EPUB(Set.of("epub")), + CBX(Set.of("cbz", "cbr", "cb7")), + FB2(Set.of("fb2")); + + private final Set extensions; + + BookFileType(Set extensions) { + this.extensions = extensions; + } + + public boolean supports(String extension) { + return extensions.contains(extension.toLowerCase()); + } + + public static Optional fromExtension(String extension) { + String ext = extension.toLowerCase(); + return Arrays.stream(values()) + .filter(type -> type.supports(ext)) + .findFirst(); + } } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/enums/FontFormat.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/enums/FontFormat.java new file mode 100644 index 000000000..b7163af85 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/enums/FontFormat.java @@ -0,0 +1,54 @@ +package com.adityachandel.booklore.model.enums; + +import lombok.Getter; + +@Getter +public enum FontFormat { + TTF("font/ttf", ".ttf"), + OTF("font/otf", ".otf"), + WOFF("font/woff", ".woff"), + WOFF2("font/woff2", ".woff2"); + + private final String mimeType; + private final String extension; + + FontFormat(String mimeType, String extension) { + this.mimeType = mimeType; + this.extension = extension; + } + + public static FontFormat fromExtension(String extension) { + String normalizedExt = extension.toLowerCase(); + if (!normalizedExt.startsWith(".")) { + normalizedExt = "." + normalizedExt; + } + for (FontFormat format : values()) { + if (format.extension.equals(normalizedExt)) { + return format; + } + } + throw new IllegalArgumentException("Unsupported font format: " + extension); + } + + public static FontFormat fromMimeType(String mimeType) { + for (FontFormat format : values()) { + if (format.mimeType.equals(mimeType)) { + return format; + } + } + throw new IllegalArgumentException("Unsupported MIME type: " + mimeType); + } + + public static boolean isSupportedExtension(String extension) { + String normalizedExt = extension.toLowerCase(); + if (!normalizedExt.startsWith(".")) { + normalizedExt = "." + normalizedExt; + } + for (FontFormat format : values()) { + if (format.extension.equals(normalizedExt)) { + return true; + } + } + return false; + } +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/enums/PermissionType.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/enums/PermissionType.java index fa6b171c9..1362b896e 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/enums/PermissionType.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/enums/PermissionType.java @@ -18,5 +18,6 @@ public enum PermissionType { ACCESS_TASK_MANAGER, MANAGE_GLOBAL_PREFERENCES, MANAGE_ICONS, + MANAGE_FONTS, DEMO_USER } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/enums/UserPermission.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/enums/UserPermission.java index 4f696bf8e..558e308b7 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/enums/UserPermission.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/enums/UserPermission.java @@ -146,6 +146,14 @@ public enum UserPermission { UserPermissionsEntity::isPermissionManageIcons, UserPermissionsEntity::setPermissionManageIcons ), + CAN_MANAGE_FONTS( + "Manage fonts", + BookLoreUser.UserPermissions::isCanManageFonts, + BookLoreUser.UserPermissions::setCanManageFonts, + UserUpdateRequest.Permissions::isCanManageFonts, + UserPermissionsEntity::isPermissionManageFonts, + UserPermissionsEntity::setPermissionManageFonts + ), CAN_BULK_AUTO_FETCH_METADATA( "Bulk auto fetch metadata", BookLoreUser.UserPermissions::isCanBulkAutoFetchMetadata, diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/repository/BookRepository.java b/booklore-api/src/main/java/com/adityachandel/booklore/repository/BookRepository.java index f063b20da..a360e48e4 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/repository/BookRepository.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/repository/BookRepository.java @@ -3,6 +3,7 @@ package com.adityachandel.booklore.repository; import com.adityachandel.booklore.model.entity.BookEntity; import com.adityachandel.booklore.model.entity.LibraryPathEntity; import com.adityachandel.booklore.model.enums.BookFileType; +import com.adityachandel.booklore.repository.projection.BookCoverUpdateProjection; import jakarta.transaction.Transactional; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.*; @@ -143,4 +144,7 @@ public interface BookRepository extends JpaRepository, JpaSpec @Query("SELECT COUNT(b) FROM BookEntity b WHERE b.library.id = :libraryId AND (b.deleted IS NULL OR b.deleted = false)") long countByLibraryId(@Param("libraryId") Long libraryId); + + @Query("SELECT b.id as id, m.coverUpdatedOn as coverUpdatedOn FROM BookEntity b LEFT JOIN b.metadata m WHERE b.id IN :bookIds") + List findCoverUpdateInfoByIds(@Param("bookIds") Collection bookIds); } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/repository/CustomFontRepository.java b/booklore-api/src/main/java/com/adityachandel/booklore/repository/CustomFontRepository.java new file mode 100644 index 000000000..9276465ef --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/repository/CustomFontRepository.java @@ -0,0 +1,19 @@ +package com.adityachandel.booklore.repository; + +import com.adityachandel.booklore.model.entity.CustomFontEntity; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; +import java.util.Optional; + +@Repository +public interface CustomFontRepository extends JpaRepository { + + List findByUserId(Long userId); + + int countByUserId(Long userId); + + Optional findByIdAndUserId(Long id, Long userId); + +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/repository/UserSettingRepository.java b/booklore-api/src/main/java/com/adityachandel/booklore/repository/UserSettingRepository.java new file mode 100644 index 000000000..3794a4f6f --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/repository/UserSettingRepository.java @@ -0,0 +1,8 @@ +package com.adityachandel.booklore.repository; + +import com.adityachandel.booklore.model.entity.UserSettingEntity; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface UserSettingRepository extends JpaRepository { + long countBySettingKeyAndSettingValue(String settingKey, String settingValue); +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/repository/projection/BookCoverUpdateProjection.java b/booklore-api/src/main/java/com/adityachandel/booklore/repository/projection/BookCoverUpdateProjection.java new file mode 100644 index 000000000..0ff9023c8 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/repository/projection/BookCoverUpdateProjection.java @@ -0,0 +1,9 @@ +package com.adityachandel.booklore.repository.projection; + +import java.time.Instant; + +public interface BookCoverUpdateProjection { + Long getId(); + Instant getCoverUpdatedOn(); +} + diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/BookRuleEvaluatorService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/BookRuleEvaluatorService.java index a402387d0..db08b7edc 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/BookRuleEvaluatorService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/BookRuleEvaluatorService.java @@ -324,6 +324,8 @@ public class BookRuleEvaluatorService { case SERIES_NAME -> root.get("metadata").get("seriesName"); case SERIES_NUMBER -> root.get("metadata").get("seriesNumber"); case SERIES_TOTAL -> root.get("metadata").get("seriesTotal"); + case ISBN13 -> root.get("metadata").get("isbn13"); + case ISBN10 -> root.get("metadata").get("isbn10"); case AMAZON_RATING -> root.get("metadata").get("amazonRating"); case AMAZON_REVIEW_COUNT -> root.get("metadata").get("amazonReviewCount"); case GOODREADS_RATING -> root.get("metadata").get("goodreadsRating"); @@ -338,7 +340,8 @@ public class BookRuleEvaluatorService { private boolean isArrayField(RuleField field) { return field == RuleField.AUTHORS || field == RuleField.CATEGORIES || - field == RuleField.MOODS || field == RuleField.TAGS; + field == RuleField.MOODS || field == RuleField.TAGS || + field == RuleField.GENRE; } private Join createArrayFieldJoin(RuleField field, Root root) { @@ -356,6 +359,7 @@ public class BookRuleEvaluatorService { case CATEGORIES -> metadataJoin.join("categories", JoinType.INNER); case MOODS -> metadataJoin.join("moods", JoinType.INNER); case TAGS -> metadataJoin.join("tags", JoinType.INNER); + case GENRE -> metadataJoin.join("categories", JoinType.INNER); default -> throw new IllegalArgumentException("Not an array field: " + field); }; } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/TelemetryService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/TelemetryService.java index 47c0e3d55..1105def45 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/TelemetryService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/TelemetryService.java @@ -6,6 +6,7 @@ import com.adityachandel.booklore.model.dto.InstallationPing; import com.adityachandel.booklore.model.dto.settings.AppSettings; import com.adityachandel.booklore.model.dto.settings.MetadataProviderSettings; import com.adityachandel.booklore.model.dto.settings.MetadataPublicReviewsSettings; +import com.adityachandel.booklore.model.dto.settings.UserSettingKey; import com.adityachandel.booklore.model.entity.LibraryEntity; import com.adityachandel.booklore.model.enums.BookFileType; import com.adityachandel.booklore.model.enums.MetadataProvider; @@ -42,6 +43,7 @@ public class TelemetryService { private final EmailRecipientV2Repository emailRecipientV2Repository; private final AppSettingService appSettingService; private final KoboUserSettingsRepository koboUserSettingsRepository; + private final UserSettingRepository userSettingRepository; private final KoreaderUserRepository koreaderUserRepository; private final OpdsUserV2Repository opdsUserV2Repository; private final InstallationService installationService; @@ -104,7 +106,7 @@ public class TelemetryService { .metadataStatistics(BookloreTelemetry.MetadataStatistics.builder() .enabledMetadataProviders(enabledMetadataProviders) .enabledReviewMetadataProviders(enabledReviewMetadataProviders) - .saveMetadataToFile(settings.getMetadataPersistenceSettings().isSaveToOriginalFile()) + .saveMetadataToFile(settings.getMetadataPersistenceSettings().getSaveToOriginalFile().isAnyFormatEnabled()) .moveFileViaPattern(settings.getMetadataPersistenceSettings().isMoveFilesToLibraryPattern()) .autoBookSearchEnabled(settings.isAutoBookSearch()) .similarBookRecommendationsEnabled(settings.isSimilarBookRecommendation()) @@ -121,7 +123,8 @@ public class TelemetryService { .koboStatistics(BookloreTelemetry.KoboStatistics.builder() .convertToKepubEnabled(settings.getKoboSettings().isConvertToKepub()) .totalKoboUsers((int) koboUserSettingsRepository.count()) - .totalHardcoverSyncEnabled((int) koboUserSettingsRepository.countByHardcoverSyncEnabledTrue()) + .totalHardcoverSyncEnabled((int) userSettingRepository.countBySettingKeyAndSettingValue( + UserSettingKey.HARDCOVER_SYNC_ENABLED.getDbKey(), "true")) .totalAutoAddToShelf((int) koboUserSettingsRepository.countByAutoAddToShelfTrue()) .build()) .bookStatistics(bookStatistics) diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/appsettings/SettingPersistenceHelper.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/appsettings/SettingPersistenceHelper.java index cdbfbf0c6..ce1de3c33 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/appsettings/SettingPersistenceHelper.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/appsettings/SettingPersistenceHelper.java @@ -9,6 +9,7 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import java.util.Map; @@ -16,6 +17,7 @@ import java.util.Set; @Service @RequiredArgsConstructor +@Slf4j public class SettingPersistenceHelper { public final AppSettingsRepository appSettingsRepository; @@ -52,14 +54,15 @@ public class SettingPersistenceHelper { try { return deserializer.deserialize(json); } catch (JsonProcessingException e) { - throw new RuntimeException("Failed to parse " + key, e); + log.error("Failed to parse JSON for setting key '{}'. Using default value. Error: {}", key, e.getMessage()); + return defaultValue; } } if (defaultValue != null && persistDefault) { try { saveDefaultSetting(key, objectMapper.writeValueAsString(defaultValue)); } catch (JsonProcessingException e) { - throw new RuntimeException("Failed to persist default for " + key, e); + log.error("Failed to persist default value for setting key '{}'. Error: {}", key, e.getMessage()); } } return defaultValue; @@ -218,8 +221,29 @@ public class SettingPersistenceHelper { } public MetadataPersistenceSettings getDefaultMetadataPersistenceSettings() { + MetadataPersistenceSettings.FormatSettings epubSettings = MetadataPersistenceSettings.FormatSettings.builder() + .enabled(false) + .maxFileSizeInMb(250) + .build(); + + MetadataPersistenceSettings.FormatSettings pdfSettings = MetadataPersistenceSettings.FormatSettings.builder() + .enabled(false) + .maxFileSizeInMb(250) + .build(); + + MetadataPersistenceSettings.FormatSettings cbxSettings = MetadataPersistenceSettings.FormatSettings.builder() + .enabled(false) + .maxFileSizeInMb(250) + .build(); + + MetadataPersistenceSettings.SaveToOriginalFile saveToOriginalFile = MetadataPersistenceSettings.SaveToOriginalFile.builder() + .epub(epubSettings) + .pdf(pdfSettings) + .cbx(cbxSettings) + .build(); + return MetadataPersistenceSettings.builder() - .saveToOriginalFile(false) + .saveToOriginalFile(saveToOriginalFile) .convertCbrCb7ToCbz(false) .moveFilesToLibraryPattern(false) .build(); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/book/BookService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/book/BookService.java index 0e3e71d5c..11b3f797a 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/book/BookService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/book/BookService.java @@ -293,16 +293,6 @@ public class BookService { return getBookCover(bookEntity.getId()); } - public Resource getBackgroundImage() { - try { - BookLoreUser user = authenticationService.getAuthenticatedUser(); - return fileService.getBackgroundResource(user.getId()); - } catch (Exception e) { - log.error("Failed to get background image: {}", e.getMessage(), e); - return fileService.getBackgroundResource(null); - } - } - public ResponseEntity downloadBook(Long bookId) { return bookDownloadService.downloadBook(bookId); } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/customfont/CustomFontService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/customfont/CustomFontService.java new file mode 100644 index 000000000..42b0c3dd2 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/customfont/CustomFontService.java @@ -0,0 +1,331 @@ +package com.adityachandel.booklore.service.customfont; + +import com.adityachandel.booklore.config.AppProperties; +import com.adityachandel.booklore.exception.APIException; +import com.adityachandel.booklore.mapper.CustomFontMapper; +import com.adityachandel.booklore.model.dto.CustomFontDto; +import com.adityachandel.booklore.model.entity.BookLoreUserEntity; +import com.adityachandel.booklore.model.entity.CustomFontEntity; +import com.adityachandel.booklore.model.enums.FontFormat; +import com.adityachandel.booklore.repository.CustomFontRepository; +import com.adityachandel.booklore.repository.UserRepository; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.core.io.FileSystemResource; +import org.springframework.core.io.Resource; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.multipart.MultipartFile; + +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.time.LocalDateTime; +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; + +@Slf4j +@Service +@RequiredArgsConstructor +public class CustomFontService { + + private final CustomFontRepository customFontRepository; + private final UserRepository userRepository; + private final CustomFontMapper customFontMapper; + private final AppProperties appProperties; + + private static final int MAX_FONTS_PER_USER = 10; + private static final long MAX_FILE_SIZE_BYTES = 5L * 1024 * 1024; + private static final String CUSTOM_FONTS_DIR = "custom-fonts"; + private static final int MAX_FONT_NAME_LENGTH = 100; + + @Transactional + public CustomFontDto uploadFont(MultipartFile file, String fontName, Long userId) { + Path fontPath = null; + CustomFontEntity savedEntity = null; + + try { + validateFontUpload(file, userId); + + BookLoreUserEntity user = userRepository.findById(userId) + .orElseThrow(() -> new IllegalArgumentException("User not found")); + + String originalFilename = file.getOriginalFilename(); + if (originalFilename == null || originalFilename.isEmpty()) { + throw new IllegalArgumentException("Invalid file name"); + } + + String extension = getFileExtension(originalFilename); + FontFormat format = FontFormat.fromExtension(extension); + + String uuid = UUID.randomUUID().toString().replace("-", "").substring(0, 12); + String fileName = String.format("user_%d_font_%s%s", userId, uuid, format.getExtension()); + + Path fontDir = getFontDirectory(userId); + Files.createDirectories(fontDir); + fontPath = fontDir.resolve(fileName); + + validatePath(fontPath, fontDir); + + file.transferTo(fontPath.toFile()); + + validateFontMagicBytes(fontPath, format); + + String sanitizedFontName = sanitizeFontName(fontName, originalFilename); + + CustomFontEntity entity = CustomFontEntity.builder() + .user(user) + .fontName(sanitizedFontName) + .fileName(fileName) + .originalFileName(originalFilename) + .format(format) + .fileSize(file.getSize()) + .uploadedAt(LocalDateTime.now()) + .build(); + + savedEntity = customFontRepository.save(entity); + log.info("Font uploaded successfully for user {}: {} ({})", userId, sanitizedFontName, fileName); + + return customFontMapper.toDto(savedEntity); + + } catch (IOException e) { + log.error("Failed to upload font for user {}: {}", userId, e.getMessage(), e); + throw new APIException("Failed to upload font. Please try again or contact support if the problem persists.", HttpStatus.INTERNAL_SERVER_ERROR); + } finally { + if (fontPath != null && savedEntity == null) { + try { + Files.deleteIfExists(fontPath); + log.debug("Cleaned up orphaned font file after upload failure: {}", fontPath); + } catch (IOException e) { + log.warn("Failed to cleanup orphaned font file: {}", fontPath, e); + } + } + } + } + + public List getUserFonts(Long userId) { + List fonts = customFontRepository.findByUserId(userId); + return fonts.stream() + .map(customFontMapper::toDto) + .collect(Collectors.toList()); + } + + @Transactional + public void deleteFont(Long fontId, Long userId) { + CustomFontEntity font = customFontRepository.findByIdAndUserId(fontId, userId) + .orElseThrow(() -> new IllegalArgumentException("Font not found or access denied")); + + IOException fileDeleteException = null; + + try { + Path fontDir = getFontDirectory(userId); + Path fontPath = fontDir.resolve(font.getFileName()); + + validatePath(fontPath, fontDir); + + Files.deleteIfExists(fontPath); + } catch (IOException e) { + log.error("Failed to delete font file for user {}: {}", userId, e.getMessage(), e); + fileDeleteException = e; + } + + try { + customFontRepository.delete(font); + log.info("Font deleted successfully for user {}: {} ({})", userId, font.getFontName(), font.getFileName()); + } catch (Exception dbException) { + log.error("Failed to delete font from database for user {}: {}", userId, dbException.getMessage(), dbException); + + if (fileDeleteException != null) { + log.error("Additionally, file deletion also failed for font: {}", font.getFileName(), fileDeleteException); + } + + throw new APIException("Failed to delete font. Please try again or contact support if the problem persists.", HttpStatus.INTERNAL_SERVER_ERROR); + } + + if (fileDeleteException != null) { + log.warn("Font deleted from database but failed to delete file for user {}: {}", userId, font.getFileName(), fileDeleteException); + } + } + + public Resource getFontFile(Long fontId, Long userId) { + CustomFontEntity font = customFontRepository.findByIdAndUserId(fontId, userId) + .orElseThrow(() -> new IllegalArgumentException("Font not found or access denied")); + + Path fontDir = getFontDirectory(userId); + Path fontPath = fontDir.resolve(font.getFileName()); + + try { + validatePath(fontPath, fontDir); + } catch (IOException e) { + log.error("Invalid font path for user {}: {}", userId, fontPath, e); + throw new IllegalArgumentException("Invalid font file path"); + } + + File fontFile = fontPath.toFile(); + + if (!fontFile.exists()) { + throw new IllegalArgumentException("Font file not found on disk"); + } + + return new FileSystemResource(fontFile); + } + + public FontFormat getFontFormat(Long fontId, Long userId) { + CustomFontEntity font = customFontRepository.findByIdAndUserId(fontId, userId) + .orElseThrow(() -> new IllegalArgumentException("Font not found or access denied")); + return font.getFormat(); + } + + private void validateFontUpload(MultipartFile file, Long userId) { + if (file.isEmpty()) { + throw new IllegalArgumentException("File is empty"); + } + + if (file.getSize() > MAX_FILE_SIZE_BYTES) { + throw new IllegalArgumentException("File size exceeds maximum limit of 5MB"); + } + + int currentFontCount = customFontRepository.countByUserId(userId); + if (currentFontCount >= MAX_FONTS_PER_USER) { + throw new IllegalArgumentException(String.format("Font limit exceeded. Maximum %d fonts per user allowed", MAX_FONTS_PER_USER)); + } + + String originalFilename = file.getOriginalFilename(); + if (originalFilename == null || originalFilename.isEmpty()) { + throw new IllegalArgumentException("Invalid file name"); + } + + String extension = getFileExtension(originalFilename); + if (!FontFormat.isSupportedExtension(extension)) { + throw new IllegalArgumentException("Unsupported font format. Allowed formats: .ttf, .otf, .woff, .woff2"); + } + + String contentType = file.getContentType(); + if (contentType != null && !isSupportedMimeType(contentType)) { + log.warn("Potentially invalid MIME type for font: {}", contentType); + } + } + + private boolean isSupportedMimeType(String mimeType) { + return mimeType.equals("font/ttf") || + mimeType.equals("font/otf") || + mimeType.equals("font/woff") || + mimeType.equals("font/woff2") || + mimeType.equals("application/x-font-ttf") || + mimeType.equals("application/x-font-opentype") || + mimeType.equals("application/font-woff") || + mimeType.equals("application/font-woff2") || + mimeType.equals("application/octet-stream"); + } + + private String getFileExtension(String filename) { + int lastDotIndex = filename.lastIndexOf('.'); + if (lastDotIndex == -1 || lastDotIndex == filename.length() - 1) { + throw new IllegalArgumentException("File has no extension"); + } + return filename.substring(lastDotIndex); + } + + private Path getFontDirectory(Long userId) { + return Paths.get(appProperties.getPathConfig(), CUSTOM_FONTS_DIR, String.valueOf(userId)); + } + + /** + * Validates that the resolved path stays within the expected parent directory + * to prevent directory traversal attacks. + */ + private void validatePath(Path resolvedPath, Path expectedParent) throws IOException { + Path normalizedPath = resolvedPath.toAbsolutePath().normalize(); + Path normalizedParent = expectedParent.toAbsolutePath().normalize(); + + if (!normalizedPath.startsWith(normalizedParent)) { + log.error("Path traversal attempt detected: {} does not start with {}", normalizedPath, normalizedParent); + throw new IOException("Invalid file path: path traversal detected"); + } + } + + /** + * Validates font file format by checking magic bytes. + * Prevents malicious files from being uploaded with font extensions. + */ + private void validateFontMagicBytes(Path fontPath, FontFormat expectedFormat) throws IOException { + byte[] header = new byte[4]; + + try (var inputStream = Files.newInputStream(fontPath)) { + int bytesRead = inputStream.read(header); + + if (bytesRead < 4) { + throw new IllegalArgumentException("Invalid font file: file too small"); + } + } + + boolean isValid = false; + String detectedFormat = "Unknown"; + + // Check TTF signature: 0x00 0x01 0x00 0x00 or "true" (0x74 0x72 0x75 0x65) + if ((header[0] == 0x00 && header[1] == 0x01 && header[2] == 0x00 && header[3] == 0x00) || + (header[0] == 0x74 && header[1] == 0x72 && header[2] == 0x75 && header[3] == 0x65)) { + isValid = (expectedFormat == FontFormat.TTF); + detectedFormat = "TTF"; + } + // Check OTF signature: "OTTO" (0x4F 0x54 0x54 0x4F) + else if (header[0] == 0x4F && header[1] == 0x54 && header[2] == 0x54 && header[3] == 0x4F) { + isValid = (expectedFormat == FontFormat.OTF); + detectedFormat = "OTF"; + } + // Check WOFF signature: "wOFF" (0x77 0x4F 0x46 0x46) + else if (header[0] == 0x77 && header[1] == 0x4F && header[2] == 0x46 && header[3] == 0x46) { + isValid = (expectedFormat == FontFormat.WOFF); + detectedFormat = "WOFF"; + } + // Check WOFF2 signature: "wOF2" (0x77 0x4F 0x46 0x32) + else if (header[0] == 0x77 && header[1] == 0x4F && header[2] == 0x46 && header[3] == 0x32) { + isValid = (expectedFormat == FontFormat.WOFF2); + detectedFormat = "WOFF2"; + } + + if (!isValid) { + log.error("Font file magic bytes validation failed. Expected: {}, Detected: {}", expectedFormat, detectedFormat); + throw new IllegalArgumentException( + String.format("Invalid font file format. File appears to be %s but extension indicates %s", + detectedFormat, expectedFormat) + ); + } + + log.debug("Font file magic bytes validated successfully: {}", detectedFormat); + } + + /** + * Sanitizes font name to prevent XSS and ensure data integrity. + */ + private String sanitizeFontName(String fontName, String fallbackName) { + if (fontName == null || fontName.trim().isEmpty()) { + fontName = fallbackName; + } + + String sanitized = fontName.trim(); + + sanitized = sanitized.replaceAll("[\\p{Cntrl}\\p{Cc}\\p{Cf}\\p{Co}\\p{Cn}]", ""); + + sanitized = sanitized.replaceAll("<[^>]*>", ""); + sanitized = sanitized.replaceAll("[<>\"'`]", ""); + + sanitized = sanitized.replaceAll("\\s+", " "); + + sanitized = sanitized.trim(); + + if (sanitized.isEmpty()) { + sanitized = fallbackName; + } + + if (sanitized.length() > MAX_FONT_NAME_LENGTH) { + sanitized = sanitized.substring(0, MAX_FONT_NAME_LENGTH).trim(); + } + + return sanitized; + } +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/file/BackgroundUploadService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/file/BackgroundUploadService.java deleted file mode 100644 index 8a0cb53e2..000000000 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/file/BackgroundUploadService.java +++ /dev/null @@ -1,118 +0,0 @@ -package com.adityachandel.booklore.service.file; - -import com.adityachandel.booklore.model.dto.UploadResponse; -import com.adityachandel.booklore.util.FileService; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.stereotype.Service; -import org.springframework.web.multipart.MultipartFile; - -import javax.imageio.ImageIO; -import java.awt.image.BufferedImage; -import java.io.InputStream; -import java.net.URI; -import java.net.URL; -import java.nio.file.Paths; -import java.util.Objects; - -@Slf4j -@Service -@RequiredArgsConstructor -public class BackgroundUploadService { - - private final FileService fileService; - - private static final String JPEG_MIME_TYPE = "image/jpeg"; - private static final String PNG_MIME_TYPE = "image/png"; - private static final long MAX_FILE_SIZE_BYTES = 5L * 1024 * 1024; // 5MB - - public UploadResponse uploadBackgroundFile(MultipartFile file, Long userId) { - try { - validateBackgroundFile(file); - - String originalFilename = Objects.requireNonNull(file.getOriginalFilename()); - String extension = getFileExtension(originalFilename); - String filename = "1." + extension; - - BufferedImage originalImage; - try (InputStream inputStream = file.getInputStream()) { - originalImage = ImageIO.read(inputStream); - } - if (originalImage == null) { - throw new IllegalArgumentException("Invalid image file"); - } - - deleteExistingBackgroundFiles(userId); - fileService.saveBackgroundImage(originalImage, filename, userId); - originalImage.flush(); // Release resources after saving - - String fileUrl = FileService.getBackgroundUrl(filename, userId); - return new UploadResponse(fileUrl); - } catch (Exception e) { - log.error("Failed to upload background file: {}", e.getMessage(), e); - throw new RuntimeException("Failed to upload file: " + e.getMessage(), e); - } - } - - public UploadResponse uploadBackgroundFromUrl(String imageUrl, Long userId) { - try { - URL url = new URI(imageUrl).toURL(); - String originalFilename = Paths.get(url.getPath()).getFileName().toString(); - String extension = getFileExtension(originalFilename); - String filename = "1." + extension; - - BufferedImage originalImage = fileService.downloadImageFromUrl(imageUrl); - deleteExistingBackgroundFiles(userId); - - fileService.saveBackgroundImage(originalImage, filename, userId); - originalImage.flush(); // Release resources after saving - - String fileUrl = FileService.getBackgroundUrl(filename, userId); - return new UploadResponse(fileUrl); - } catch (Exception e) { - log.error("Failed to upload background from URL: {}", e.getMessage(), e); - throw new RuntimeException("Invalid or inaccessible URL: " + e.getMessage(), e); - } - } - - public void resetToDefault(Long userId) { - try { - deleteExistingBackgroundFiles(userId); - log.info("Reset background to default successfully for user: {}", userId); - } catch (Exception e) { - log.error("Failed to reset background to default: {}", e.getMessage(), e); - throw new RuntimeException("Failed to reset background: " + e.getMessage(), e); - } - } - - private void deleteExistingBackgroundFiles(Long userId) { - try { - fileService.deleteBackgroundFile("1.jpg", userId); - fileService.deleteBackgroundFile("1.jpeg", userId); - fileService.deleteBackgroundFile("1.png", userId); - } catch (Exception e) { - log.warn("Failed to delete existing background files: {}", e.getMessage()); - } - } - - private void validateBackgroundFile(MultipartFile file) { - if (file.isEmpty()) { - throw new IllegalArgumentException("Background image file is empty"); - } - String contentType = file.getContentType(); - if (!(JPEG_MIME_TYPE.equalsIgnoreCase(contentType) || PNG_MIME_TYPE.equalsIgnoreCase(contentType))) { - throw new IllegalArgumentException("Background image must be JPEG or PNG format"); - } - if (file.getSize() > MAX_FILE_SIZE_BYTES) { - throw new IllegalArgumentException("Background image size must not exceed 5 MB"); - } - } - - private String getFileExtension(String filename) { - int lastDotIndex = filename.lastIndexOf('.'); - if (lastDotIndex > 0 && lastDotIndex < filename.length() - 1) { - return filename.substring(lastDotIndex + 1).toLowerCase(); - } - return "jpg"; - } -} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/CbxProcessor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/CbxProcessor.java index 2f4b6f9ac..8f32afaa3 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/CbxProcessor.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/CbxProcessor.java @@ -42,7 +42,6 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce private static final Pattern UNDERSCORE_HYPHEN_PATTERN = Pattern.compile("[_\\-]"); private static final Pattern IMAGE_EXTENSION_PATTERN = Pattern.compile(".*\\.(jpg|jpeg|png|webp)"); private static final Pattern IMAGE_EXTENSION_CASE_INSENSITIVE_PATTERN = Pattern.compile("(?i).*\\.(jpg|jpeg|png|webp)"); - private static final Pattern CBX_FILE_EXTENSION_PATTERN = Pattern.compile("(?i)\\.cb[rz7]$"); private final CbxMetadataExtractor cbxMetadataExtractor; public CbxProcessor(BookRepository bookRepository, @@ -99,17 +98,20 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce } private Optional extractImagesFromArchive(File file) { - String name = file.getName().toLowerCase(); - if (name.endsWith(".cbz")) { - return extractFirstImageFromZip(file); - } else if (name.endsWith(".cb7")) { - return extractFirstImageFrom7z(file); - } else if (name.endsWith(".cbr")) { - return extractFirstImageFromRar(file); - } else { + String name = file.getName(); + String extension = FileUtils.getExtension(name).toLowerCase(); + + if (!BookFileType.CBX.supports(extension)) { log.warn("Unsupported CBX format: {}", name); return Optional.empty(); } + + return switch (extension) { + case "cbz" -> extractFirstImageFromZip(file); + case "cb7" -> extractFirstImageFrom7z(file); + case "cbr" -> extractFirstImageFromRar(file); + default -> Optional.empty(); + }; } private Optional extractFirstImageFromZip(File file) { @@ -144,7 +146,7 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce .min(Comparator.comparing(ZipArchiveEntry::getName)) .map(entry -> { try (InputStream is = zipFile.getInputStream(entry)) { - return ImageIO.read(is); + return FileService.readImage(is); } catch (Exception e) { log.warn("Failed to read image from ZIP entry {}: {}", entry.getName(), e.getMessage()); return null; @@ -175,7 +177,7 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce if (bytesRead < 0) break; offset += bytesRead; } - return Optional.ofNullable(ImageIO.read(new ByteArrayInputStream(content))); + return Optional.ofNullable(FileService.readImage(new ByteArrayInputStream(content))); } } } @@ -196,7 +198,7 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce for (FileHeader header : imageHeaders) { try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { archive.extractFile(header, baos); - return Optional.ofNullable(ImageIO.read(new ByteArrayInputStream(baos.toByteArray()))); + return Optional.ofNullable(FileService.readImage(new ByteArrayInputStream(baos.toByteArray()))); } catch (Exception e) { log.warn("Error reading RAR entry {}: {}", header.getFileName(), e.getMessage()); } @@ -242,8 +244,12 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce private void setMetadata(BookEntity bookEntity) { String baseName = new File(bookEntity.getFileName()).getName(); - String title = UNDERSCORE_HYPHEN_PATTERN.matcher(CBX_FILE_EXTENSION_PATTERN.matcher(baseName).replaceAll("")).replaceAll(" ") - .trim(); + String extension = FileUtils.getExtension(baseName); + if (BookFileType.CBX.supports(extension)) { + baseName = baseName.substring(0, baseName.length() - extension.length() - 1); + } + String title = UNDERSCORE_HYPHEN_PATTERN.matcher(baseName).replaceAll(" ").trim(); bookEntity.getMetadata().setTitle(truncate(title, 1000)); } -} \ No newline at end of file +} + diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/EpubProcessor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/EpubProcessor.java index a4384c203..babf17a59 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/EpubProcessor.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/EpubProcessor.java @@ -68,9 +68,9 @@ public class EpubProcessor extends AbstractFileProcessor implements BookFileProc boolean saved; try (ByteArrayInputStream bais = new ByteArrayInputStream(coverData)) { - BufferedImage originalImage = ImageIO.read(bais); + BufferedImage originalImage = FileService.readImage(bais); if (originalImage == null) { - log.warn("Cover image found but could not be decoded (possibly SVG or unsupported format) in EPUB '{}'", bookEntity.getFileName()); + log.warn("Failed to decode cover image for EPUB '{}'", bookEntity.getFileName()); return false; } saved = fileService.saveCoverImages(originalImage, bookEntity.getId()); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/Fb2Processor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/Fb2Processor.java index 09c58f3c4..1b0f25f5d 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/Fb2Processor.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/Fb2Processor.java @@ -125,13 +125,12 @@ public class Fb2Processor extends AbstractFileProcessor implements BookFileProce } private boolean saveCoverImage(byte[] coverData, long bookId) throws Exception { - BufferedImage originalImage = ImageIO.read(new ByteArrayInputStream(coverData)); - try { - return fileService.saveCoverImages(originalImage, bookId); - } finally { - if (originalImage != null) { - originalImage.flush(); // Release resources after processing - } + BufferedImage originalImage = FileService.readImage(coverData); + if (originalImage == null) { + log.warn("Failed to decode cover image for FB2"); + return false; } + + return fileService.saveCoverImages(originalImage, bookId); } } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/hardcover/HardcoverSyncService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/hardcover/HardcoverSyncService.java index 033ec3de6..e9b1f96b7 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/hardcover/HardcoverSyncService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/hardcover/HardcoverSyncService.java @@ -1,14 +1,12 @@ package com.adityachandel.booklore.service.hardcover; -import com.adityachandel.booklore.model.dto.KoboSyncSettings; +import com.adityachandel.booklore.model.dto.HardcoverSyncSettings; import com.adityachandel.booklore.model.entity.BookEntity; import com.adityachandel.booklore.model.entity.BookMetadataEntity; import com.adityachandel.booklore.repository.BookRepository; -import com.adityachandel.booklore.service.kobo.KoboSettingsService; import com.adityachandel.booklore.service.metadata.parser.hardcover.GraphQLRequest; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Lazy; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.scheduling.annotation.Async; @@ -25,7 +23,7 @@ import java.util.Map; /** * Service to sync reading progress to Hardcover. * Uses per-user Hardcover API tokens for reading progress sync. - * Each user can configure their own Hardcover API key in Kobo settings. + * Each user can configure their own Hardcover API key in their sync settings. */ @Slf4j @Service @@ -36,15 +34,15 @@ public class HardcoverSyncService { private static final int STATUS_READ = 3; private final RestClient restClient; - private final KoboSettingsService koboSettingsService; + private final HardcoverSyncSettingsService hardcoverSyncSettingsService; private final BookRepository bookRepository; // Thread-local to hold the current API token for GraphQL requests private final ThreadLocal currentApiToken = new ThreadLocal<>(); @Autowired - public HardcoverSyncService(@Lazy KoboSettingsService koboSettingsService, BookRepository bookRepository) { - this.koboSettingsService = koboSettingsService; + public HardcoverSyncService(HardcoverSyncSettingsService hardcoverSyncSettingsService, BookRepository bookRepository) { + this.hardcoverSyncSettingsService = hardcoverSyncSettingsService; this.bookRepository = bookRepository; this.restClient = RestClient.builder() .baseUrl(HARDCOVER_API_URL) @@ -65,7 +63,7 @@ public class HardcoverSyncService { public void syncProgressToHardcover(Long bookId, Float progressPercent, Long userId) { try { // Get user's Hardcover settings - KoboSyncSettings userSettings = koboSettingsService.getSettingsByUserId(userId); + HardcoverSyncSettings userSettings = hardcoverSyncSettingsService.getSettingsForUserId(userId); if (!isHardcoverSyncEnabledForUser(userSettings)) { log.trace("Hardcover sync skipped for user {}: not enabled or no API token configured", userId); @@ -102,6 +100,18 @@ public class HardcoverSyncService { hardcoverBook.bookId = metadata.getHardcoverBookId(); hardcoverBook.pages = metadata.getPageCount(); log.debug("Using stored Hardcover book ID: {}", hardcoverBook.bookId); + + if (hardcoverBook.bookId != null && (hardcoverBook.pages == null || hardcoverBook.pages <= 0 || hardcoverBook.editionId == null)) { + HardcoverBookInfo fetched = findHardcoverBookById(hardcoverBook.bookId); + if (fetched != null) { + if (hardcoverBook.editionId == null) { + hardcoverBook.editionId = fetched.editionId; + } + if ((hardcoverBook.pages == null || hardcoverBook.pages <= 0) && fetched.pages != null) { + hardcoverBook.pages = fetched.pages; + } + } + } } else { // Search by ISBN hardcoverBook = findHardcoverBook(metadata); @@ -152,7 +162,7 @@ public class HardcoverSyncService { /** * Check if Hardcover sync is enabled for a specific user. */ - private boolean isHardcoverSyncEnabledForUser(KoboSyncSettings userSettings) { + private boolean isHardcoverSyncEnabledForUser(HardcoverSyncSettings userSettings) { if (userSettings == null) { return false; } @@ -247,15 +257,17 @@ public class HardcoverSyncService { } // If no default edition, try to look up edition by ISBN - // This also gets the page count from the specific edition - if (info.bookId != null) { + if (info.bookId != null && info.editionId == null) { EditionInfo edition = findEditionByIsbn(info.bookId, isbn); if (edition != null) { info.editionId = edition.id; - // Prefer edition page count over book page count - if (edition.pages != null && edition.pages > 0) { - info.pages = edition.pages; - } + } + } + + if (info.editionId != null && (info.pages == null || info.pages <= 0)) { + EditionInfo edition = findEditionById(info.editionId); + if (edition != null && edition.pages != null && edition.pages > 0) { + info.pages = edition.pages; } } @@ -326,6 +338,111 @@ public class HardcoverSyncService { } } + private EditionInfo findEditionById(Integer editionId) { + String query = """ + query FindEditionById($editionId: Int!) { + editions(where: {id: {_eq: $editionId}}, limit: 1) { + id + pages + } + } + """; + + GraphQLRequest request = new GraphQLRequest(); + request.setQuery(query); + request.setVariables(Map.of("editionId", editionId)); + + try { + Map response = executeGraphQL(request); + if (response == null) return null; + + Map data = (Map) response.get("data"); + if (data == null) return null; + + List> editions = (List>) data.get("editions"); + if (editions == null || editions.isEmpty()) return null; + + Map edition = editions.getFirst(); + EditionInfo info = new EditionInfo(); + + Object idObj = edition.get("id"); + if (idObj instanceof Number) { + info.id = ((Number) idObj).intValue(); + } + + Object pagesObj = edition.get("pages"); + if (pagesObj instanceof Number) { + info.pages = ((Number) pagesObj).intValue(); + } + + return info.id != null ? info : null; + + } catch (Exception e) { + log.debug("Failed to find edition by ID: {}", e.getMessage()); + return null; + } + } + + private HardcoverBookInfo findHardcoverBookById(Integer bookId) { + String query = """ + query FindBookById($bookId: Int!) { + books(where: {id: {_eq: $bookId}}, limit: 1) { + id + default_edition_id + pages + } + } + """; + + GraphQLRequest request = new GraphQLRequest(); + request.setQuery(query); + request.setVariables(Map.of("bookId", bookId)); + + try { + Map response = executeGraphQL(request); + if (response == null) return null; + + Map data = (Map) response.get("data"); + if (data == null) return null; + + List> books = (List>) data.get("books"); + if (books == null || books.isEmpty()) return null; + + Map book = books.getFirst(); + HardcoverBookInfo info = new HardcoverBookInfo(); + info.bookId = bookId; + + Object defaultEditionObj = book.get("default_edition_id"); + if (defaultEditionObj instanceof Number) { + info.editionId = ((Number) defaultEditionObj).intValue(); + } else if (defaultEditionObj instanceof String) { + try { + info.editionId = Integer.parseInt((String) defaultEditionObj); + } catch (NumberFormatException e) { + // Ignore + } + } + + Object pagesObj = book.get("pages"); + if (pagesObj instanceof Number) { + info.pages = ((Number) pagesObj).intValue(); + } + + if (info.editionId != null && (info.pages == null || info.pages <= 0)) { + EditionInfo edition = findEditionById(info.editionId); + if (edition != null && edition.pages != null && edition.pages > 0) { + info.pages = edition.pages; + } + } + + return info.editionId != null || info.pages != null ? info : null; + + } catch (Exception e) { + log.debug("Failed to find Hardcover book by ID {}: {}", bookId, e.getMessage()); + return null; + } + } + /** * Insert a book into the user's library or get existing user_book_id. */ diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/hardcover/HardcoverSyncSettingsService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/hardcover/HardcoverSyncSettingsService.java new file mode 100644 index 000000000..3b12bce44 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/hardcover/HardcoverSyncSettingsService.java @@ -0,0 +1,122 @@ +package com.adityachandel.booklore.service.hardcover; + +import com.adityachandel.booklore.config.security.service.AuthenticationService; +import com.adityachandel.booklore.exception.ApiError; +import com.adityachandel.booklore.model.dto.BookLoreUser; +import com.adityachandel.booklore.model.dto.HardcoverSyncSettings; +import com.adityachandel.booklore.model.dto.settings.UserSettingKey; +import com.adityachandel.booklore.model.entity.BookLoreUserEntity; +import com.adityachandel.booklore.model.entity.KoboUserSettingsEntity; +import com.adityachandel.booklore.model.entity.UserSettingEntity; +import com.adityachandel.booklore.repository.KoboUserSettingsRepository; +import com.adityachandel.booklore.repository.UserRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Optional; + +@Service +@RequiredArgsConstructor +public class HardcoverSyncSettingsService { + + private final UserRepository userRepository; + private final AuthenticationService authenticationService; + private final KoboUserSettingsRepository koboUserSettingsRepository; + + @Transactional + public HardcoverSyncSettings getCurrentUserSettings() { + BookLoreUser user = authenticationService.getAuthenticatedUser(); + return getSettingsForUserId(user.getId()); + } + + @Transactional + public HardcoverSyncSettings getSettingsForUserId(Long userId) { + BookLoreUserEntity user = userRepository.findById(userId) + .orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(userId)); + return readSettings(user, userId); + } + + @Transactional + public HardcoverSyncSettings updateCurrentUserSettings(HardcoverSyncSettings settings) { + BookLoreUser user = authenticationService.getAuthenticatedUser(); + return updateSettingsForUserId(user.getId(), settings); + } + + @Transactional + public HardcoverSyncSettings updateSettingsForUserId(Long userId, HardcoverSyncSettings settings) { + if (settings == null) { + throw ApiError.INVALID_INPUT.createException("Hardcover settings cannot be null."); + } + + BookLoreUserEntity user = userRepository.findById(userId) + .orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(userId)); + + String apiKey = settings.getHardcoverApiKey(); + if (apiKey == null) { + apiKey = ""; + } else { + apiKey = apiKey.trim(); + } + upsertSetting(user, UserSettingKey.HARDCOVER_API_KEY, apiKey); + upsertSetting(user, UserSettingKey.HARDCOVER_SYNC_ENABLED, Boolean.toString(settings.isHardcoverSyncEnabled())); + + userRepository.save(user); + + HardcoverSyncSettings updated = new HardcoverSyncSettings(); + updated.setHardcoverApiKey(apiKey); + updated.setHardcoverSyncEnabled(settings.isHardcoverSyncEnabled()); + return updated; + } + + private HardcoverSyncSettings readSettings(BookLoreUserEntity user, Long userId) { + UserSettingEntity apiKeySetting = findSetting(user, UserSettingKey.HARDCOVER_API_KEY).orElse(null); + UserSettingEntity syncEnabledSetting = findSetting(user, UserSettingKey.HARDCOVER_SYNC_ENABLED).orElse(null); + + String apiKey = apiKeySetting != null ? apiKeySetting.getSettingValue() : null; + boolean syncEnabled = syncEnabledSetting != null && Boolean.parseBoolean(syncEnabledSetting.getSettingValue()); + + boolean shouldSave = false; + if (apiKeySetting == null || syncEnabledSetting == null) { + KoboUserSettingsEntity legacySettings = koboUserSettingsRepository.findByUserId(userId).orElse(null); + if (legacySettings != null) { + if (apiKeySetting == null && legacySettings.getHardcoverApiKey() != null && !legacySettings.getHardcoverApiKey().isBlank()) { + apiKey = legacySettings.getHardcoverApiKey(); + upsertSetting(user, UserSettingKey.HARDCOVER_API_KEY, apiKey); + shouldSave = true; + } + if (syncEnabledSetting == null && legacySettings.isHardcoverSyncEnabled()) { + syncEnabled = legacySettings.isHardcoverSyncEnabled(); + upsertSetting(user, UserSettingKey.HARDCOVER_SYNC_ENABLED, Boolean.toString(syncEnabled)); + shouldSave = true; + } + } + } + if (shouldSave) { + userRepository.save(user); + } + + HardcoverSyncSettings settings = new HardcoverSyncSettings(); + settings.setHardcoverApiKey(apiKey); + settings.setHardcoverSyncEnabled(syncEnabled); + return settings; + } + + private Optional findSetting(BookLoreUserEntity user, UserSettingKey key) { + return user.getSettings().stream() + .filter(setting -> key.getDbKey().equals(setting.getSettingKey())) + .findFirst(); + } + + private void upsertSetting(BookLoreUserEntity user, UserSettingKey key, String value) { + UserSettingEntity setting = findSetting(user, key) + .orElseGet(() -> { + UserSettingEntity newSetting = new UserSettingEntity(); + newSetting.setUser(user); + newSetting.setSettingKey(key.getDbKey()); + user.getSettings().add(newSetting); + return newSetting; + }); + setting.setSettingValue(value); + } +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/CbxConversionService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/CbxConversionService.java index 150d39922..d27de32b1 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/CbxConversionService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/CbxConversionService.java @@ -21,6 +21,8 @@ import com.github.junrar.exception.RarException; import org.springframework.stereotype.Service; import org.springframework.util.FileSystemUtils; +import com.adityachandel.booklore.util.FileService; + import javax.imageio.ImageIO; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; @@ -314,7 +316,8 @@ public class CbxConversionService { return lowerName.endsWith(".jpg") || lowerName.endsWith(".jpeg") || lowerName.endsWith(".png") || lowerName.endsWith(".webp") || - lowerName.endsWith(".gif") || lowerName.endsWith(".bmp"); + lowerName.endsWith(".gif") || lowerName.endsWith(".bmp") || + lowerName.endsWith(".avif") || lowerName.endsWith(".heic"); } private boolean isJpegFile(Path path) { @@ -404,7 +407,13 @@ public class CbxConversionService { } } else { try (InputStream fis = Files.newInputStream(sourceImagePath)) { - BufferedImage image = ImageIO.read(fis); + BufferedImage image = null; + try { + image = FileService.readImage(fis); + } catch (Exception e) { + log.debug("Failed to decode image {} with FileService: {}", sourceImagePath, e.getMessage()); + } + if (image != null) { writeJpegImage(image, zipOut, compressionPercentage/100f); } else { diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/KoboEntitlementService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/KoboEntitlementService.java index c78e5b472..49e8d3f36 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/KoboEntitlementService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/KoboEntitlementService.java @@ -17,6 +17,7 @@ import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; +import java.math.BigDecimal; import java.time.OffsetDateTime; import java.time.ZoneOffset; import java.util.Collections; @@ -208,13 +209,22 @@ public class KoboEntitlementService { .orElse(Collections.emptyList()); KoboBookMetadata.Series series = null; - if (metadata.getSeriesName() != null) { + if (metadata.getSeriesName() != null && !metadata.getSeriesName().isBlank()) { series = KoboBookMetadata.Series.builder() .id("series_" + metadata.getSeriesName().hashCode()) .name(metadata.getSeriesName()) - .number(metadata.getSeriesNumber() != null ? metadata.getSeriesNumber().toString() : "1") + .number(metadata.getSeriesNumber() != null + ? BigDecimal.valueOf(metadata.getSeriesNumber()).stripTrailingZeros().toPlainString() + : "1") .numberFloat(metadata.getSeriesNumber() != null ? metadata.getSeriesNumber().doubleValue() : 1.0) .build(); + } else { + series = KoboBookMetadata.Series.builder() + .id("") + .name("") + .number("") + .numberFloat(0.0) + .build(); } String downloadUrl = koboUrlBuilder.downloadUrl(token, book.getId()); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/KoboSettingsService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/KoboSettingsService.java index 130a87228..cc6bd5b28 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/KoboSettingsService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/KoboSettingsService.java @@ -2,6 +2,7 @@ package com.adityachandel.booklore.service.kobo; import com.adityachandel.booklore.config.security.service.AuthenticationService; import com.adityachandel.booklore.model.dto.BookLoreUser; +import com.adityachandel.booklore.model.dto.HardcoverSyncSettings; import com.adityachandel.booklore.model.dto.KoboSyncSettings; import com.adityachandel.booklore.model.dto.Shelf; import com.adityachandel.booklore.model.dto.request.ShelfCreateRequest; @@ -11,6 +12,7 @@ import com.adityachandel.booklore.model.enums.IconType; import com.adityachandel.booklore.model.enums.ShelfType; import com.adityachandel.booklore.repository.KoboUserSettingsRepository; import com.adityachandel.booklore.service.ShelfService; +import com.adityachandel.booklore.service.hardcover.HardcoverSyncSettingsService; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -25,6 +27,7 @@ public class KoboSettingsService { private final KoboUserSettingsRepository repository; private final AuthenticationService authenticationService; private final ShelfService shelfService; + private final HardcoverSyncSettingsService hardcoverSyncSettingsService; @Transactional(readOnly = true) public KoboSyncSettings getCurrentUserSettings() { @@ -82,12 +85,8 @@ public class KoboSettingsService { entity.setAutoAddToShelf(settings.isAutoAddToShelf()); - // Update Hardcover settings - entity.setHardcoverApiKey(settings.getHardcoverApiKey()); - entity.setHardcoverSyncEnabled(settings.isHardcoverSyncEnabled()); - repository.save(entity); - return mapToDto(entity); + return mapToDto(entity, hardcoverSyncSettingsService.getSettingsForUserId(user.getId())); } private KoboUserSettingsEntity initDefaultSettings(Long userId) { @@ -118,6 +117,11 @@ public class KoboSettingsService { } private KoboSyncSettings mapToDto(KoboUserSettingsEntity entity) { + HardcoverSyncSettings hardcoverSettings = hardcoverSyncSettingsService.getSettingsForUserId(entity.getUserId()); + return mapToDto(entity, hardcoverSettings); + } + + private KoboSyncSettings mapToDto(KoboUserSettingsEntity entity, HardcoverSyncSettings hardcoverSettings) { KoboSyncSettings dto = new KoboSyncSettings(); dto.setId(entity.getId()); dto.setUserId(entity.getUserId().toString()); @@ -126,14 +130,17 @@ public class KoboSettingsService { dto.setProgressMarkAsReadingThreshold(entity.getProgressMarkAsReadingThreshold()); dto.setProgressMarkAsFinishedThreshold(entity.getProgressMarkAsFinishedThreshold()); dto.setAutoAddToShelf(entity.isAutoAddToShelf()); - dto.setHardcoverApiKey(entity.getHardcoverApiKey()); - dto.setHardcoverSyncEnabled(entity.isHardcoverSyncEnabled()); + if (hardcoverSettings != null) { + dto.setHardcoverApiKey(hardcoverSettings.getHardcoverApiKey()); + dto.setHardcoverSyncEnabled(hardcoverSettings.isHardcoverSyncEnabled()); + } else { + dto.setHardcoverSyncEnabled(false); + } return dto; } /** - * Get Hardcover settings for a specific user by ID. - * Used by HardcoverSyncService to get user-specific API key. + * Get Kobo settings for a specific user by ID. */ @Transactional(readOnly = true) public KoboSyncSettings getSettingsByUserId(Long userId) { @@ -141,4 +148,5 @@ public class KoboSettingsService { .map(this::mapToDto) .orElse(null); } + } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/koreader/KoreaderService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/koreader/KoreaderService.java index 130dc1ab6..7b4af12e7 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/koreader/KoreaderService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/koreader/KoreaderService.java @@ -22,6 +22,7 @@ import com.adityachandel.booklore.repository.BookRepository; import com.adityachandel.booklore.repository.KoreaderUserRepository; import com.adityachandel.booklore.repository.UserBookProgressRepository; import com.adityachandel.booklore.repository.UserRepository; +import com.adityachandel.booklore.service.hardcover.HardcoverSyncService; @Slf4j @AllArgsConstructor @@ -32,6 +33,7 @@ public class KoreaderService { private final BookRepository bookRepository; private final UserRepository userRepository; private final KoreaderUserRepository koreaderUserRepository; + private final HardcoverSyncService hardcoverSyncService; public ResponseEntity> authorizeUser() { KoreaderUserDetails authDetails = getAuthDetails(); @@ -76,6 +78,9 @@ public class KoreaderService { progressRepository.save(userProgress); log.info("saveProgress: saved progress='{}' percentage={} for userId={} bookHash={}", koProgress.getProgress(), koProgress.getPercentage(), authDetails.getBookLoreUserId(), bookHash); + + Float progressPercent = normalizeProgressPercent(koProgress.getPercentage()); + hardcoverSyncService.syncProgressToHardcover(book.getId(), progressPercent, authDetails.getBookLoreUserId()); } private void updateProgressData(UserBookProgressEntity userProgress, KoreaderProgress koProgress) { @@ -101,6 +106,16 @@ public class KoreaderService { } } + private Float normalizeProgressPercent(Float progress) { + if (progress == null) { + return null; + } + if (progress <= 1.0f) { + return progress * 100.0f; + } + return progress; + } + private KoreaderUserDetails getAuthDetails() { Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if (!(principal instanceof KoreaderUserDetails details)) { diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/library/LibraryFileHelper.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/library/LibraryFileHelper.java index 2d9a833cb..ff0052ed6 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/library/LibraryFileHelper.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/library/LibraryFileHelper.java @@ -5,19 +5,24 @@ import com.adityachandel.booklore.model.entity.LibraryEntity; import com.adityachandel.booklore.model.entity.LibraryPathEntity; import com.adityachandel.booklore.model.enums.BookFileExtension; import com.adityachandel.booklore.util.FileUtils; +import lombok.extern.slf4j.Slf4j; +import org.jspecify.annotations.NonNull; import org.springframework.stereotype.Component; import java.io.IOException; import java.nio.file.FileVisitOption; +import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; +import java.nio.file.SimpleFileVisitor; +import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; +import java.util.EnumSet; import java.util.List; -import java.util.Objects; import java.util.Optional; -import java.util.stream.Stream; @Component +@Slf4j public class LibraryFileHelper { public List getLibraryFiles(LibraryEntity libraryEntity, LibraryFileProcessor processor) throws IOException { @@ -31,30 +36,50 @@ public class LibraryFileHelper { private List findLibraryFiles(LibraryPathEntity pathEntity, LibraryEntity libraryEntity, LibraryFileProcessor processor) throws IOException { Path libraryPath = Path.of(pathEntity.getPath()); boolean supportsSupplementaryFiles = processor.supportsSupplementaryFiles(); + List libraryFiles = new ArrayList<>(); - try (Stream stream = Files.walk(libraryPath, FileVisitOption.FOLLOW_LINKS)) { - return stream - .filter(Files::isReadable) - .filter(Files::isRegularFile) - .filter(path -> !FileUtils.shouldIgnore(path)) - .map(fullPath -> { - String fileName = fullPath.getFileName().toString(); - Optional bookExtension = BookFileExtension.fromFileName(fileName); + Files.walkFileTree(libraryPath, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, new SimpleFileVisitor<>() { + @Override + @NonNull + public FileVisitResult visitFile(@NonNull Path file, @NonNull BasicFileAttributes attrs) { + if (FileUtils.shouldIgnore(file) || !Files.isReadable(file) || !Files.isRegularFile(file)) { + return FileVisitResult.CONTINUE; + } - if (bookExtension.isEmpty() && !supportsSupplementaryFiles) { - return null; - } + String fileName = file.getFileName().toString(); + Optional bookExtension = BookFileExtension.fromFileName(fileName); - return LibraryFile.builder() - .libraryEntity(libraryEntity) - .libraryPathEntity(pathEntity) - .fileSubPath(FileUtils.getRelativeSubPath(pathEntity.getPath(), fullPath)) - .fileName(fileName) - .bookFileType(bookExtension.map(BookFileExtension::getType).orElse(null)) - .build(); - }) - .filter(Objects::nonNull) - .toList(); - } + if (bookExtension.isEmpty() && !supportsSupplementaryFiles) { + return FileVisitResult.CONTINUE; + } + + libraryFiles.add(LibraryFile.builder() + .libraryEntity(libraryEntity) + .libraryPathEntity(pathEntity) + .fileSubPath(FileUtils.getRelativeSubPath(pathEntity.getPath(), file)) + .fileName(fileName) + .bookFileType(bookExtension.map(BookFileExtension::getType).orElse(null)) + .build()); + return FileVisitResult.CONTINUE; + } + + @Override + @NonNull + public FileVisitResult visitFileFailed(@NonNull Path file, IOException e) { + log.error("Failed read path [{}]: {}", file, e.getMessage(), e); + return FileVisitResult.CONTINUE; + } + + @Override + @NonNull + public FileVisitResult preVisitDirectory(@NonNull Path dir, @NonNull BasicFileAttributes attrs) throws IOException { + if (FileUtils.shouldIgnore(dir) || !Files.isReadable(dir)) { + return FileVisitResult.SKIP_SUBTREE; + } + + return super.preVisitDirectory(dir, attrs); + } + }); + return libraryFiles; } } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/library/LibraryService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/library/LibraryService.java index 3099c376b..0dad29efb 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/library/LibraryService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/library/LibraryService.java @@ -13,6 +13,7 @@ import com.adityachandel.booklore.model.entity.BookEntity; import com.adityachandel.booklore.model.entity.BookLoreUserEntity; import com.adityachandel.booklore.model.entity.LibraryEntity; import com.adityachandel.booklore.model.entity.LibraryPathEntity; +import com.adityachandel.booklore.model.enums.BookFileType; import com.adityachandel.booklore.model.enums.LibraryScanMode; import com.adityachandel.booklore.model.websocket.Topic; import com.adityachandel.booklore.repository.BookRepository; @@ -33,9 +34,14 @@ import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import java.io.IOException; +import java.nio.file.DirectoryStream; +import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; -import java.util.*; +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import java.util.Set; import java.util.stream.Collectors; @Slf4j @@ -250,4 +256,51 @@ public class LibraryService { library.setFileNamingPattern(pattern); return libraryMapper.toLibrary(libraryRepository.save(library)); } -} \ No newline at end of file + + public int scanLibraryPaths(CreateLibraryRequest request) { + int count = 0; + if (request.getPaths() == null || request.getPaths().isEmpty()) { + return count; + } + for (LibraryPath libraryPath : request.getPaths()) { + Path path = Paths.get(libraryPath.getPath()); + if (!Files.exists(path)) { + log.warn("Path does not exist: {}", path); + continue; + } + if (Files.isDirectory(path)) { + count += scanDirectory(path); + } else if (Files.isRegularFile(path) && isProcessableFile(path)) { + count++; + } + } + return count; + } + + private int scanDirectory(Path directory) { + int count = 0; + try (DirectoryStream stream = Files.newDirectoryStream(directory)) { + for (Path entry : stream) { + if (Files.isDirectory(entry)) { + count += scanDirectory(entry); + } else if (Files.isRegularFile(entry) && isProcessableFile(entry)) { + count++; + } + } + } catch (IOException e) { + log.error("Error scanning directory: {}", directory, e); + } + return count; + } + + private boolean isProcessableFile(Path file) { + String fileName = file.getFileName().toString().toLowerCase(); + for (BookFileType fileType : BookFileType.values()) { + if (fileName.endsWith("." + fileType.name().toLowerCase())) { + return true; + } + } + return false; + } +} + diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookCoverService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookCoverService.java index 58ac16c6b..adeb06429 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookCoverService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookCoverService.java @@ -1,8 +1,6 @@ package com.adityachandel.booklore.service.metadata; import com.adityachandel.booklore.exception.ApiError; -import com.adityachandel.booklore.mapper.BookMetadataMapper; -import com.adityachandel.booklore.model.dto.BookMetadata; import com.adityachandel.booklore.model.dto.settings.MetadataPersistenceSettings; import com.adityachandel.booklore.model.entity.AuthorEntity; import com.adityachandel.booklore.model.entity.BookEntity; @@ -10,6 +8,7 @@ import com.adityachandel.booklore.model.enums.BookFileType; import com.adityachandel.booklore.model.websocket.LogNotification; import com.adityachandel.booklore.model.websocket.Topic; import com.adityachandel.booklore.repository.BookRepository; +import com.adityachandel.booklore.repository.projection.BookCoverUpdateProjection; import com.adityachandel.booklore.service.NotificationService; import com.adityachandel.booklore.service.appsettings.AppSettingService; import com.adityachandel.booklore.service.book.BookQueryService; @@ -29,7 +28,9 @@ import org.springframework.transaction.support.TransactionTemplate; import org.springframework.web.multipart.MultipartFile; import java.time.Instant; -import java.util.*; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; import java.util.function.BiConsumer; import java.util.stream.Collectors; @@ -41,7 +42,6 @@ public class BookCoverService { private static final int BATCH_SIZE = 100; private final BookRepository bookRepository; - private final BookMetadataMapper bookMetadataMapper; private final NotificationService notificationService; private final AppSettingService appSettingService; private final FileService fileService; @@ -54,79 +54,153 @@ public class BookCoverService { private record BookCoverInfo(Long id, String title) { } - private record BookRegenerationInfo(Long id, String title, BookFileType bookType) { + private record BookRegenerationInfo(Long id, String title, BookFileType bookType, boolean coverLocked) { } + // ========================= + // SECTION: COVER UPDATES + // ========================= + + /** + * Generate a custom cover for a single book. + */ public void generateCustomCover(long bookId) { BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); + if (isCoverLocked(bookEntity)) { throw ApiError.METADATA_LOCKED.createException(); } + String title = bookEntity.getMetadata().getTitle(); String author = getAuthorNames(bookEntity); byte[] coverBytes = coverImageGenerator.generateCover(title, author); + fileService.createThumbnailFromBytes(bookId, coverBytes); + writeCoverToBookFile(bookEntity, (writer, book) -> writer.replaceCoverImageFromBytes(book, coverBytes)); updateBookCoverMetadata(bookEntity); bookRepository.save(bookEntity); notifyBookCoverUpdate(bookEntity); } + /** + * Update cover image from uploaded file for a single book. + */ @Transactional - public BookMetadata updateCoverImageFromFile(Long bookId, MultipartFile file) { + public void updateCoverFromFile(Long bookId, MultipartFile file) { + BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); + + if (isCoverLocked(bookEntity)) { + throw ApiError.METADATA_LOCKED.createException(); + } + fileService.createThumbnailFromFile(bookId, file); - return updateCover(bookId, (writer, book) -> writer.replaceCoverImageFromUpload(book, file)); + writeCoverToBookFile(bookEntity, (writer, book) -> writer.replaceCoverImageFromUpload(book, file)); + updateBookCoverMetadata(bookEntity); + bookRepository.save(bookEntity); + notifyBookCoverUpdate(bookEntity); } + /** + * Update cover image from a URL for a single book. + */ @Transactional - public BookMetadata updateCoverImageFromUrl(Long bookId, String url) { + public void updateCoverFromUrl(Long bookId, String url) { + BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); + + if (isCoverLocked(bookEntity)) { + throw ApiError.METADATA_LOCKED.createException(); + } + fileService.createThumbnailFromUrl(bookId, url); - return updateCover(bookId, (writer, book) -> writer.replaceCoverImageFromUrl(book, url)); + writeCoverToBookFile(bookEntity, (writer, book) -> writer.replaceCoverImageFromUrl(book, url)); + updateBookCoverMetadata(bookEntity); + bookRepository.save(bookEntity); + notifyBookCoverUpdate(bookEntity); } - public void updateCoverImageFromFileForBooks(Set bookIds, MultipartFile file) { + /** + * Bulk update cover images from a file for multiple books. + */ + public void updateCoverFromFileForBooks(Set bookIds, MultipartFile file) { validateCoverFile(file); byte[] coverImageBytes = extractBytesFromMultipartFile(file); List unlockedBooks = getUnlockedBookCoverInfos(bookIds); SecurityContextVirtualThread.runWithSecurityContext(() -> processBulkCoverUpdate(unlockedBooks, coverImageBytes)); } - public void regenerateCover(long bookId) { - BookEntity bookEntity = bookRepository.findById(bookId) - .orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); + // ========================= + // SECTION: COVER REGENERATION + // ========================= + /** + * Regenerate cover for a single book. + */ + public void regenerateCover(long bookId) { + BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); if (isCoverLocked(bookEntity)) { throw ApiError.METADATA_LOCKED.createException(); } - - regenerateCoverForBook(bookEntity, ""); + BookFileProcessor processor = processorRegistry.getProcessorOrThrow(bookEntity.getBookType()); + boolean success = processor.generateCover(bookEntity); + if (!success) { + throw ApiError.FAILED_TO_REGENERATE_COVER.createException(); + } updateBookCoverMetadata(bookEntity); bookRepository.save(bookEntity); } + /** + * Regenerate covers for a set of books. + */ public void regenerateCoversForBooks(Set bookIds) { List unlockedBooks = getUnlockedBookRegenerationInfos(bookIds); SecurityContextVirtualThread.runWithSecurityContext(() -> processBulkCoverRegeneration(unlockedBooks)); } + /** + * Regenerate covers for all books. + */ public void regenerateCovers() { SecurityContextVirtualThread.runWithSecurityContext(() -> { try { - List books = bookQueryService.getAllFullBookEntities().stream() + List books = bookQueryService.getAllFullBookEntities().stream() .filter(book -> !isCoverLocked(book)) + .map(book -> new BookRegenerationInfo(book.getId(), book.getMetadata().getTitle(), book.getBookType(), false)) .toList(); int total = books.size(); notificationService.sendMessage(Topic.LOG, LogNotification.info("Started regenerating covers for " + total + " books")); int current = 1; - for (BookEntity book : books) { + List refreshedIds = new ArrayList<>(); + + for (BookRegenerationInfo bookInfo : books) { try { String progress = "(" + current + "/" + total + ") "; - regenerateCoverForBook(book, progress); + notificationService.sendMessage(Topic.LOG, LogNotification.info(progress + "Regenerating cover for: " + bookInfo.title())); + + transactionTemplate.execute(status -> { + bookRepository.findById(bookInfo.id()).ifPresent(book -> { + BookFileProcessor processor = processorRegistry.getProcessorOrThrow(bookInfo.bookType()); + boolean success = processor.generateCover(book); + + if (success) { + updateBookCoverMetadata(book); + bookRepository.save(book); + refreshedIds.add(book.getId()); + log.info("{}Successfully regenerated cover for book ID {} ({})", progress, book.getId(), bookInfo.title()); + } else { + log.warn("{}Failed to regenerate cover for book ID {} ({})", progress, book.getId(), bookInfo.title()); + } + }); + return null; + }); } catch (Exception e) { - log.error("Failed to regenerate cover for book ID {}: {}", book.getId(), e.getMessage(), e); + log.error("Failed to regenerate cover for book ID {}: {}", bookInfo.id(), e.getMessage(), e); } current++; } + + notifyBulkCoverUpdate(refreshedIds); notificationService.sendMessage(Topic.LOG, LogNotification.info("Finished regenerating covers")); } catch (Exception e) { log.error("Error during cover regeneration: {}", e.getMessage(), e); @@ -135,30 +209,9 @@ public class BookCoverService { }); } - private BookMetadata updateCover(Long bookId, BiConsumer writerAction) { - BookEntity bookEntity = bookRepository.findAllWithMetadataByIds(Collections.singleton(bookId)).stream() - .findFirst() - .orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); - - updateBookCoverMetadata(bookEntity); - - MetadataPersistenceSettings settings = appSettingService.getAppSettings().getMetadataPersistenceSettings(); - boolean saveToOriginalFile = settings.isSaveToOriginalFile(); - boolean convertCbrCb7ToCbz = settings.isConvertCbrCb7ToCbz(); - - if (saveToOriginalFile && (bookEntity.getBookType() != BookFileType.CBX || convertCbrCb7ToCbz)) { - metadataWriterFactory.getWriter(bookEntity.getBookType()) - .ifPresent(writer -> { - writerAction.accept(writer, bookEntity); - String newHash = FileFingerprint.generateHash(bookEntity.getFullFilePath()); - bookEntity.setCurrentHash(newHash); - }); - } - - bookEntity.setMetadataUpdatedAt(Instant.now()); - bookRepository.save(bookEntity); - return bookMetadataMapper.toBookMetadata(bookEntity.getMetadata(), true); - } + // ========================= + // SECTION: BULK OPERATIONS + // ========================= private void processBulkCoverUpdate(List books, byte[] coverImageBytes) { try { @@ -166,24 +219,32 @@ public class BookCoverService { notificationService.sendMessage(Topic.LOG, LogNotification.info("Started updating covers for " + total + " selected book(s)")); int current = 1; + List refreshedIds = new ArrayList<>(); + for (BookCoverInfo bookInfo : books) { try { String progress = "(" + current + "/" + total + ") "; notificationService.sendMessage(Topic.LOG, LogNotification.info(progress + "Updating cover for: " + bookInfo.title())); - fileService.createThumbnailFromBytes(bookInfo.id(), coverImageBytes); - bookRepository.findById(bookInfo.id()).ifPresent(book -> { - updateBookCoverMetadata(book); - bookRepository.save(book); + transactionTemplate.execute(status -> { + bookRepository.findById(bookInfo.id()).ifPresent(book -> { + fileService.createThumbnailFromBytes(bookInfo.id(), coverImageBytes); + writeCoverToBookFile(book, (writer, b) -> writer.replaceCoverImageFromBytes(b, coverImageBytes)); + updateBookCoverMetadata(book); + bookRepository.save(book); + refreshedIds.add(book.getId()); + }); + return null; }); log.info("{}Successfully updated cover for book ID {} ({})", progress, bookInfo.id(), bookInfo.title()); } catch (Exception e) { log.error("Failed to update cover for book ID {}: {}", bookInfo.id(), e.getMessage(), e); } - pauseAfterBatchIfNeeded(current, total); current++; } + + notifyBulkCoverUpdate(refreshedIds); notificationService.sendMessage(Topic.LOG, LogNotification.info("Finished updating covers for selected books")); } catch (Exception e) { log.error("Error during cover update: {}", e.getMessage(), e); @@ -203,13 +264,25 @@ public class BookCoverService { try { String progress = "(" + current + "/" + total + ") "; notificationService.sendMessage(Topic.LOG, LogNotification.info(progress + "Regenerating cover for: " + bookInfo.title())); - regenerateCoverForBookId(bookInfo); + + transactionTemplate.execute(status -> { + bookRepository.findById(bookInfo.id()).ifPresent(book -> { + BookFileProcessor processor = processorRegistry.getProcessorOrThrow(bookInfo.bookType()); + boolean success = processor.generateCover(book); + + if (success) { + updateBookCoverMetadata(book); + bookRepository.save(book); + refreshedIds.add(book.getId()); + } + }); + return null; + }); + log.info("{}Successfully regenerated cover for book ID {} ({})", progress, bookInfo.id(), bookInfo.title()); - refreshedIds.add(bookInfo.id()); } catch (Exception e) { log.error("Failed to regenerate cover for book ID {}: {}", bookInfo.id(), e.getMessage(), e); } - pauseAfterBatchIfNeeded(current, total); current++; } @@ -221,31 +294,9 @@ public class BookCoverService { } } - private void regenerateCoverForBook(BookEntity book, String progress) { - String title = book.getMetadata().getTitle(); - notificationService.sendMessage(Topic.LOG, LogNotification.info(progress + "Regenerating cover for: " + title)); - - BookFileProcessor processor = processorRegistry.getProcessorOrThrow(book.getBookType()); - boolean success = processor.generateCover(book); - - if (success) { - Instant now = Instant.now(); - book.getMetadata().setCoverUpdatedOn(now); - book.setBookCoverHash(BookCoverUtils.generateCoverHash()); - } - - log.info("{} regenerated cover regeneration for book ID {} ({}) finished with success={}", progress, book.getId(), title, success); - if (!success) { - throw ApiError.FAILED_TO_REGENERATE_COVER.createException(); - } - } - - private void regenerateCoverForBookId(BookRegenerationInfo bookInfo) { - bookRepository.findById(bookInfo.id()).ifPresent(book -> { - BookFileProcessor processor = processorRegistry.getProcessorOrThrow(bookInfo.bookType()); - processor.generateCover(book); - }); - } + // ========================= + // SECTION: INTERNAL HELPERS + // ========================= private void validateCoverFile(MultipartFile file) { if (file.isEmpty()) { @@ -280,7 +331,7 @@ public class BookCoverService { private List getUnlockedBookRegenerationInfos(Set bookIds) { return bookQueryService.findAllWithMetadataByIds(bookIds).stream() .filter(book -> !isCoverLocked(book)) - .map(book -> new BookRegenerationInfo(book.getId(), book.getMetadata().getTitle(), book.getBookType())) + .map(book -> new BookRegenerationInfo(book.getId(), book.getMetadata().getTitle(), book.getBookType(), false)) .toList(); } @@ -297,6 +348,20 @@ public class BookCoverService { return null; } + private void writeCoverToBookFile(BookEntity bookEntity, BiConsumer writerAction) { + MetadataPersistenceSettings settings = appSettingService.getAppSettings().getMetadataPersistenceSettings(); + boolean convertCbrCb7ToCbz = settings.isConvertCbrCb7ToCbz(); + + if ((bookEntity.getBookType() != BookFileType.CBX || convertCbrCb7ToCbz)) { + metadataWriterFactory.getWriter(bookEntity.getBookType()) + .ifPresent(writer -> { + writerAction.accept(writer, bookEntity); + String newHash = FileFingerprint.generateHash(bookEntity.getFullFilePath()); + bookEntity.setCurrentHash(newHash); + }); + } + } + private void updateBookCoverMetadata(BookEntity bookEntity) { Instant now = Instant.now(); bookEntity.setMetadataUpdatedAt(now); @@ -305,51 +370,19 @@ public class BookCoverService { } private void notifyBookCoverUpdate(BookEntity bookEntity) { - notificationService.sendMessage(Topic.BOOKS_COVER_UPDATE, List.of(Map.of( - "id", bookEntity.getId(), - "coverUpdatedOn", bookEntity.getMetadata().getCoverUpdatedOn() - ))); + List updates = bookRepository.findCoverUpdateInfoByIds(List.of(bookEntity.getId())); + if (!updates.isEmpty()) { + notificationService.sendMessage(Topic.BOOKS_COVER_UPDATE, updates); + } } private void notifyBulkCoverUpdate(List refreshedIds) { if (refreshedIds.isEmpty()) { return; } - - List> refreshedPatches = transactionTemplate.execute(status -> { - List entities = bookQueryService.findAllWithMetadataByIds(new HashSet<>(refreshedIds)); - if (entities == null || entities.isEmpty()) { - return List.>of(); - } - - entities.forEach(e -> { - if (e.getMetadata() != null) { - e.getMetadata().getCoverUpdatedOn(); - } - }); - - return entities.stream() - .map(e -> Map.of( - "id", e.getId(), - "coverUpdatedOn", e.getMetadata() == null ? null : e.getMetadata().getCoverUpdatedOn() - )) - .toList(); - }); - - if (refreshedPatches != null && !refreshedPatches.isEmpty()) { - notificationService.sendMessage(Topic.BOOKS_COVER_UPDATE, refreshedPatches); - } - } - - private void pauseAfterBatchIfNeeded(int current, int total) { - if (current % BATCH_SIZE == 0 && current < total) { - try { - log.info("Processed {} items, pausing briefly before next batch...", current); - Thread.sleep(1000); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - log.warn("Batch pause interrupted"); - } + List updates = bookRepository.findCoverUpdateInfoByIds(refreshedIds); + if (!updates.isEmpty()) { + notificationService.sendMessage(Topic.BOOKS_COVER_UPDATE, updates); } } } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookMetadataService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookMetadataService.java index 0b85d4b1f..c5bb2ca61 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookMetadataService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookMetadataService.java @@ -29,12 +29,14 @@ import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import org.springframework.web.multipart.MultipartFile; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.core.scheduler.Schedulers; import java.io.File; import java.lang.reflect.Method; -import java.util.*; -import java.util.concurrent.CompletableFuture; +import java.util.List; +import java.util.Map; import java.util.stream.Collectors; @Slf4j @@ -52,39 +54,22 @@ public class BookMetadataService { private final Map parserMap; private final CbxMetadataExtractor cbxMetadataExtractor; private final MetadataClearFlagsMapper metadataClearFlagsMapper; - private final BookCoverService bookCoverService; - public void generateCustomCover(long bookId) { - bookCoverService.generateCustomCover(bookId); - } - public List getProspectiveMetadataListForBookId(long bookId, FetchMetadataRequest request) { + public Flux getProspectiveMetadataListForBookId(long bookId, FetchMetadataRequest request) { BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); Book book = bookMapper.toBook(bookEntity); - List> allMetadata = request.getProviders().stream() - .map(provider -> CompletableFuture.supplyAsync(() -> fetchMetadataListFromAProvider(provider, book, request)) - .exceptionally(e -> { - log.error("Error fetching metadata from provider: {}", provider, e); - return List.of(); - })) - .toList() - .stream() - .map(CompletableFuture::join) - .filter(Objects::nonNull) - .toList(); - List interleavedMetadata = new ArrayList<>(); - int maxSize = allMetadata.stream().mapToInt(List::size).max().orElse(0); - - for (int i = 0; i < maxSize; i++) { - for (List metadataList : allMetadata) { - if (i < metadataList.size()) { - interleavedMetadata.add(metadataList.get(i)); - } - } - } - - return interleavedMetadata; + return Flux.fromIterable(request.getProviders()) + .flatMap(provider -> + Mono.fromCallable(() -> fetchMetadataListFromAProvider(provider, book, request)) + .subscribeOn(Schedulers.boundedElastic()) + .flatMapMany(Flux::fromIterable) + .onErrorResume(e -> { + log.error("Error fetching metadata from provider: {}", provider, e); + return Flux.empty(); + }) + ); } public List fetchMetadataListFromAProvider(MetadataProvider provider, Book book, FetchMetadataRequest request) { @@ -137,32 +122,6 @@ public class BookMetadataService { return books.stream().map(b -> bookMetadataMapper.toBookMetadata(b.getMetadata(), false)).collect(Collectors.toList()); } - @Transactional - public BookMetadata updateCoverImageFromFile(Long bookId, MultipartFile file) { - return bookCoverService.updateCoverImageFromFile(bookId, file); - } - - @Transactional - public BookMetadata updateCoverImageFromUrl(Long bookId, String url) { - return bookCoverService.updateCoverImageFromUrl(bookId, url); - } - - public void updateCoverImageFromFileForBooks(Set bookIds, MultipartFile file) { - bookCoverService.updateCoverImageFromFileForBooks(bookIds, file); - } - - public void regenerateCover(long bookId) { - bookCoverService.regenerateCover(bookId); - } - - public void regenerateCoversForBooks(Set bookIds) { - bookCoverService.regenerateCoversForBooks(bookIds); - } - - public void regenerateCovers() { - bookCoverService.regenerateCovers(); - } - public BookMetadata getComicInfoMetadata(long bookId) { log.info("Extracting ComicInfo metadata for book ID: {}", bookId); BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookMetadataUpdater.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookMetadataUpdater.java index 29c4165d4..7002cdc50 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookMetadataUpdater.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookMetadataUpdater.java @@ -9,15 +9,12 @@ import com.adityachandel.booklore.model.dto.settings.MetadataPersistenceSettings import com.adityachandel.booklore.model.entity.*; import com.adityachandel.booklore.model.enums.BookFileType; import com.adityachandel.booklore.model.enums.MetadataReplaceMode; -import com.adityachandel.booklore.repository.AuthorRepository; -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.file.FileFingerprint; +import com.adityachandel.booklore.repository.*; import com.adityachandel.booklore.service.appsettings.AppSettingService; +import com.adityachandel.booklore.service.file.FileFingerprint; import com.adityachandel.booklore.service.file.FileMoveService; import com.adityachandel.booklore.service.metadata.writer.MetadataWriterFactory; +import com.adityachandel.booklore.util.BookCoverUtils; import com.adityachandel.booklore.util.FileService; import com.adityachandel.booklore.util.MetadataChangeDetector; import lombok.AllArgsConstructor; @@ -82,14 +79,13 @@ public class BookMetadataUpdater { return; } - // If all fields are locked we must allow unlocking, hasValueChanges will be false if (metadata.areAllFieldsLocked() && hasValueChanges) { log.warn("All fields are locked for book ID {}. Skipping update.", bookId); return; } MetadataPersistenceSettings settings = appSettingService.getAppSettings().getMetadataPersistenceSettings(); - boolean writeToFile = settings.isSaveToOriginalFile(); + MetadataPersistenceSettings.SaveToOriginalFile writeToFile = settings.getSaveToOriginalFile(); BookFileType bookType = bookEntity.getBookType(); boolean hasValueChangesForFileWrite = MetadataChangeDetector.hasValueChangesForFileWrite(newMetadata, metadata, clearFlags); @@ -100,7 +96,7 @@ public class BookMetadataUpdater { updateMoodsIfNeeded(newMetadata, metadata, clearFlags, mergeMoods, replaceMode); updateTagsIfNeeded(newMetadata, metadata, clearFlags, mergeTags, replaceMode); bookReviewUpdateService.updateBookReviews(newMetadata, metadata, clearFlags, mergeCategories); - updateThumbnailIfNeeded(bookId, newMetadata, metadata, updateThumbnail); + updateThumbnailIfNeeded(bookId, bookEntity, newMetadata, metadata, updateThumbnail); updateLocks(newMetadata, metadata); bookEntity.setMetadataUpdatedAt(Instant.now()); @@ -112,7 +108,7 @@ public class BookMetadataUpdater { log.warn("Failed to calculate metadata match score for book ID {}: {}", bookId, e.getMessage()); } - if ((writeToFile && hasValueChangesForFileWrite) || thumbnailRequiresUpdate) { + if ((writeToFile.isAnyFormatEnabled() && hasValueChangesForFileWrite) || thumbnailRequiresUpdate) { metadataWriterFactory.getWriter(bookType).ifPresent(writer -> { try { String thumbnailUrl = updateThumbnail ? newMetadata.getThumbnailUrl() : null; @@ -121,7 +117,7 @@ public class BookMetadataUpdater { thumbnailUrl = null; } File file = new File(bookEntity.getFullFilePath().toUri()); - writer.writeMetadataToFile(file, metadata, thumbnailUrl, clearFlags); + writer.saveMetadataToFile(file, metadata, thumbnailUrl, clearFlags); String newHash = FileFingerprint.generateHash(bookEntity.getFullFilePath()); bookEntity.setMetadataForWriteUpdatedAt(Instant.now()); bookEntity.setCurrentHash(newHash); @@ -229,14 +225,14 @@ public class BookMetadataUpdater { if (replaceAll) { if (!merge) e.getAuthors().clear(); e.getAuthors().addAll(newAuthors); - e.updateSearchText(); // Manually trigger search text update since collection modification doesn't trigger @PreUpdate + e.updateSearchText(); } else if (replaceMissing && e.getAuthors().isEmpty()) { e.getAuthors().addAll(newAuthors); - e.updateSearchText(); // Manually trigger search text update since collection modification doesn't trigger @PreUpdate + e.updateSearchText(); } else if (replaceMode == null) { if (!merge) e.getAuthors().clear(); e.getAuthors().addAll(newAuthors); - e.updateSearchText(); // Manually trigger search text update since collection modification doesn't trigger @PreUpdate + e.updateSearchText(); } } @@ -354,17 +350,18 @@ public class BookMetadataUpdater { } } - private void updateThumbnailIfNeeded(long bookId, BookMetadata m, BookMetadataEntity e, boolean set) { + private void updateThumbnailIfNeeded(long bookId, BookEntity bookEntity, BookMetadata m, BookMetadataEntity e, boolean set) { if (Boolean.TRUE.equals(e.getCoverLocked())) { - return; // Locked — do nothing + return; } if (!set) return; if (!StringUtils.hasText(m.getThumbnailUrl()) || isLocalOrPrivateUrl(m.getThumbnailUrl())) return; try { fileService.createThumbnailFromUrl(bookId, m.getThumbnailUrl()); + bookEntity.setBookCoverHash(BookCoverUtils.generateCoverHash()); + bookEntity.getMetadata().setCoverUpdatedOn(Instant.now()); } catch (Exception ex) { log.warn("Failed to download cover for book {}: {}", bookId, ex.getMessage()); - // Don't rethrow - cover failures shouldn't roll back metadata updates } } @@ -385,6 +382,8 @@ public class BookMetadataUpdater { Pair.of(m.getComicvineIdLocked(), e::setComicvineIdLocked), Pair.of(m.getHardcoverIdLocked(), e::setHardcoverIdLocked), Pair.of(m.getHardcoverBookIdLocked(), e::setHardcoverBookIdLocked), + Pair.of(m.getLubimyczytacIdLocked(), e::setLubimyczytacIdLocked), + Pair.of(m.getLubimyczytacRatingLocked(), e::setLubimyczytacRatingLocked), Pair.of(m.getGoogleIdLocked(), e::setGoogleIdLocked), Pair.of(m.getPageCountLocked(), e::setPageCountLocked), Pair.of(m.getLanguageLocked(), e::setLanguageLocked), diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/CoverImageGenerator.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/CoverImageGenerator.java index 4eb20888d..40cdd230b 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/CoverImageGenerator.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/CoverImageGenerator.java @@ -9,7 +9,7 @@ import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; import javax.imageio.stream.ImageOutputStream; import java.awt.*; -import java.awt.geom.Rectangle2D; +import java.awt.geom.*; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -21,168 +21,681 @@ import java.util.regex.Pattern; @Service public class CoverImageGenerator { - private static final int WIDTH = 250; - private static final int HEIGHT = 350; - private static final int PADDING = 20; - private static final int TITLE_TOP_MARGIN = 40; - private static final int TITLE_PADDING = 15; - private static final int AUTHOR_BOTTOM_MARGIN = 330; - private static final int MAX_LINES = 5; - private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\s+"); + private static final int WIDTH = 1200; + private static final int HEIGHT = 1600; + private static final int SCALE = 2; + private static final double PHI = 1.618033988749; + private static final double PHI_INV = 1.0 / PHI; + private static final double PHI_SQ_INV = 1.0 / (PHI * PHI); + private static final int MAX_TITLE_LINES = 5; + private static final int MAX_AUTHOR_LINES = 2; + private static final int MAX_TITLE_LEN = 200; + private static final int MAX_AUTHOR_LEN = 100; + private static final int MIN_FONT = 36 * SCALE; + private static final Pattern WS = Pattern.compile("\\s+"); public byte[] generateCover(String title, String author) { - BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); - Graphics2D g2d = image.createGraphics(); - - g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); - - Color[] colors = getColorScheme(title); - Color bgColor1 = colors[0]; - Color bgColor2 = colors[1]; - - GradientPaint backgroundGradient = new GradientPaint( - 0, 0, bgColor1, - 0, HEIGHT, bgColor2 - ); - g2d.setPaint(backgroundGradient); - g2d.fillRect(0, 0, WIDTH, HEIGHT); - - String effectiveTitle = title != null && !title.isBlank() ? title : "Unknown Title"; - String effectiveAuthor = author != null && !author.isBlank() ? author : "Unknown Author"; - - Font titleFont = getTitleFont(effectiveTitle.length()); - g2d.setFont(titleFont); - FontMetrics titleFm = g2d.getFontMetrics(); - - List titleLines = wrapText(effectiveTitle, titleFm); - int titleLineHeight = titleFm.getHeight(); - int titleBoxHeight = (titleLines.size() * titleLineHeight) + (TITLE_PADDING * 2); - - GradientPaint titleBgGradient = new GradientPaint( - 0, TITLE_TOP_MARGIN, new Color(221, 221, 221), // #dddddd - 0, TITLE_TOP_MARGIN + titleBoxHeight, new Color(223, 223, 223, 153) // #dfdfdf with 0.6 opacity - ); - g2d.setPaint(titleBgGradient); - g2d.fillRect(0, TITLE_TOP_MARGIN, WIDTH, titleBoxHeight); - - g2d.setColor(Color.BLACK); - int currentY = TITLE_TOP_MARGIN + TITLE_PADDING + titleFm.getAscent(); - for (String line : titleLines) { - g2d.drawString(line, PADDING, currentY); - currentY += titleLineHeight; - } - - Font authorFont = getAuthorFont(effectiveAuthor.length()); - g2d.setFont(authorFont); - FontMetrics authorFm = g2d.getFontMetrics(); - - List authorLines = wrapText(effectiveAuthor, authorFm); - int authorLineHeight = authorFm.getHeight(); - int authorStartY = AUTHOR_BOTTOM_MARGIN - ((authorLines.size() - 1) * authorLineHeight); - - g2d.setColor(Color.BLACK); - for (int i = 0; i < authorLines.size(); i++) { - String line = authorLines.get(i); - Rectangle2D rect = authorFm.getStringBounds(line, g2d); - int x = WIDTH - PADDING - (int) rect.getWidth(); // Right align - g2d.drawString(line, x, authorStartY + (i * authorLineHeight)); - } - - g2d.dispose(); - - return writeHighQualityJpeg(image); + return generateCover(title, author, null); } - private byte[] writeHighQualityJpeg(BufferedImage image) { - try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { - ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next(); - ImageWriteParam param = writer.getDefaultWriteParam(); - param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); - param.setCompressionQuality(0.95f); // High quality + public byte[] generateCover(String title, String author, String subtitle) { + BufferedImage render = null; + BufferedImage result = null; + Graphics2D g = null; - try (ImageOutputStream ios = ImageIO.createImageOutputStream(baos)) { - writer.setOutput(ios); - writer.write(null, new IIOImage(image, null, null), param); - writer.dispose(); - return baos.toByteArray(); - } - } catch (IOException e) { - log.error("Failed to generate cover image", e); - throw new RuntimeException("Failed to generate cover image", e); - } - } - - private Font getTitleFont(int length) { try { - Font font = new Font("Georgia", Font.BOLD, getTitleFontSize(length)); - if (font.getFamily().equals("Georgia")) return font; + String safeTitle = sanitize(title, MAX_TITLE_LEN, "Unknown Title"); + String safeAuthor = sanitize(author, MAX_AUTHOR_LEN, "Unknown Author"); + String safeSubtitle = sanitize(subtitle, MAX_TITLE_LEN, ""); // Using title length limit for subtitle + + int w = WIDTH * SCALE; + int h = HEIGHT * SCALE; + + render = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); + g = render.createGraphics(); + + try { + configureGraphics(g); + Palette p = selectPalette(safeTitle); + int margin = calcMargin(w); + + renderBaseGradient(g, p, w, h); + renderDepthGradient(g, p, w, h); + renderGlow(g, p, w, h); + renderBokeh(g, p, w, h); + renderTexture(g, w, h); + renderFrame(g, p, w, h); + int titleEnd = renderTitle(g, safeTitle, p, w, h, margin); + int subtitleEnd = titleEnd; + if (safeSubtitle != null && !safeSubtitle.isEmpty()) { + subtitleEnd = renderSubtitle(g, safeSubtitle, p, w, h, margin, titleEnd); + } + renderDivider(g, p, w, subtitleEnd, h); + renderAuthor(g, safeAuthor, p, w, h, margin); + renderVignette(g, w, h); + renderEdges(g, w, h); + + } finally { + if (g != null) g.dispose(); + } + + result = downscale(render); + render.flush(); + render = null; + + return encodeJpeg(result); + } catch (Exception e) { - log.warn("Failed to load preferred font, using fallback"); + log.error("Cover generation failed: {}", title, e); + throw new RuntimeException("Cover generation failed", e); + } finally { + cleanup(g, render, result); } - return new Font(Font.SERIF, Font.BOLD, getTitleFontSize(length)); } - private int getTitleFontSize(int length) { - if (length < 20) return 36; - if (length < 40) return 30; - return 24; + private record Palette(Color primary, Color secondary, Color tertiary, Color accent, + Color textMain, Color textSub, Color ornament) {} + + private int calcMargin(int w) { + int frameOuter = (int) (w * PHI_SQ_INV * 0.12); + int frameInner = (int) (frameOuter * PHI); + return frameInner + (int) (w * 0.04); } - private Font getAuthorFont(int length) { - if (length < 20) return new Font(Font.SANS_SERIF, Font.PLAIN, 28); - return new Font(Font.SANS_SERIF, Font.PLAIN, 22); + private Palette selectPalette(String title) { + Palette[] palettes = { + new Palette(new Color(20, 30, 55), new Color(40, 55, 90), new Color(30, 42, 72), + new Color(218, 180, 120), new Color(252, 250, 245), new Color(210, 200, 185), new Color(190, 165, 110)), + new Palette(new Color(70, 30, 40), new Color(105, 50, 60), new Color(85, 40, 50), + new Color(230, 205, 175), new Color(255, 252, 248), new Color(225, 215, 200), new Color(200, 175, 145)), + new Palette(new Color(25, 50, 45), new Color(45, 80, 70), new Color(35, 65, 57), + new Color(205, 190, 150), new Color(250, 248, 242), new Color(215, 210, 195), new Color(180, 165, 130)), + new Palette(new Color(45, 30, 65), new Color(75, 50, 100), new Color(60, 40, 82), + new Color(215, 195, 165), new Color(252, 250, 248), new Color(220, 210, 200), new Color(190, 170, 145)), + new Palette(new Color(55, 45, 35), new Color(90, 75, 60), new Color(72, 60, 47), + new Color(210, 185, 145), new Color(255, 252, 245), new Color(230, 220, 200), new Color(185, 165, 125)), + new Palette(new Color(25, 50, 60), new Color(45, 85, 100), new Color(35, 67, 80), + new Color(220, 200, 165), new Color(250, 250, 248), new Color(215, 210, 200), new Color(190, 175, 145)), + new Palette(new Color(40, 40, 45), new Color(65, 67, 73), new Color(52, 52, 58), + new Color(205, 190, 160), new Color(252, 252, 250), new Color(205, 203, 200), new Color(180, 170, 150)), + new Palette(new Color(65, 40, 30), new Color(105, 70, 50), new Color(85, 55, 40), + new Color(225, 200, 160), new Color(255, 250, 242), new Color(230, 220, 200), new Color(200, 180, 145)), + new Palette(new Color(30, 40, 75), new Color(50, 65, 115), new Color(40, 52, 95), + new Color(220, 200, 155), new Color(252, 250, 248), new Color(210, 205, 195), new Color(190, 170, 135)), + new Palette(new Color(50, 55, 40), new Color(80, 90, 65), new Color(65, 72, 52), + new Color(215, 205, 170), new Color(252, 250, 245), new Color(220, 215, 200), new Color(185, 180, 150)) + }; + return palettes[Math.abs(title.hashCode()) % palettes.length]; } - private static List wrapText(String text, FontMetrics fm) { + private static void renderBaseGradient(Graphics2D g, Palette p, int w, int h) { + float[] fractions = {0f, (float) PHI_SQ_INV, 0.5f, (float) PHI_INV, 1f}; + Color[] colors = {darken(p.primary, 0.2f), p.primary, p.tertiary, p.secondary, darken(p.secondary, 0.15f)}; + g.setPaint(new LinearGradientPaint(0, 0, w * (float) PHI_INV, h, fractions, colors)); + g.fillRect(0, 0, w, h); + } + + private void renderDepthGradient(Graphics2D g, Palette p, int w, int h) { + g.setPaint(new RadialGradientPaint(w * 0.5f, h * 0.35f, (float) (h * PHI_INV), + new float[]{0f, 0.5f, 1f}, + new Color[]{alpha(lighten(p.tertiary, 0.15f), 45), alpha(p.tertiary, 25), alpha(p.primary, 0)})); + g.fillRect(0, 0, w, h); + + g.setPaint(new RadialGradientPaint(w * 0.85f, h * 1.15f, (float) (w * PHI_INV), + new float[]{0f, 0.6f, 1f}, + new Color[]{alpha(darken(p.secondary, 0.25f), 55), alpha(darken(p.secondary, 0.15f), 30), alpha(p.secondary, 0)})); + g.fillRect(0, 0, w, h); + + g.setPaint(new RadialGradientPaint(w * 0.1f, h * 0.9f, (float) (w * PHI_SQ_INV), + new float[]{0f, 0.5f, 1f}, + new Color[]{alpha(darken(p.primary, 0.2f), 40), alpha(p.primary, 20), alpha(p.primary, 0)})); + g.fillRect(0, 0, w, h); + } + + private static void renderGlow(Graphics2D g, Palette p, int w, int h) { + int cy = (int) (h * PHI_SQ_INV); + float r = (float) (w * PHI_INV * 1.3); + Color glow = new Color( + Math.min(255, p.accent.getRed() + 55), + Math.min(255, p.accent.getGreen() + 45), + Math.min(255, p.accent.getBlue() + 35)); + + g.setPaint(new RadialGradientPaint(w / 2f, cy, r, + new float[]{0f, (float) PHI_SQ_INV, (float) PHI_INV, 1f}, + new Color[]{alpha(glow, 32), alpha(glow, 20), alpha(glow, 10), alpha(glow, 0)})); + g.fillRect(0, 0, w, h); + + g.setPaint(new RadialGradientPaint(w / 2f, (float) (h * (1 - PHI_SQ_INV * 0.45)), r * 0.65f, + new float[]{0f, 0.5f, 1f}, + new Color[]{alpha(Color.WHITE, 14), alpha(Color.WHITE, 7), alpha(Color.WHITE, 0)})); + g.fillRect(0, 0, w, h); + } + + private void renderBokeh(Graphics2D g, Palette p, int w, int h) { + Composite orig = g.getComposite(); + int seed = p.primary.getRGB(); + + for (int i = 0; i < 15; i++) { + int px = ((seed * (i + 1) * 17) % w + w) % w; + int py = ((seed * (i + 1) * 31) % h + h) % h; + int size = Math.max(1, ((25 + Math.abs((seed * (i + 1) * 7) % 60)) * SCALE)); + float opacity = 0.018f + Math.abs((seed * (i + 1) * 3) % 25) * 0.0012f; + + g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, opacity)); + Color bokehColor = (i % 3 == 0) ? lighten(p.accent, 0.25f) : (i % 3 == 1) ? Color.WHITE : lighten(p.ornament, 0.2f); + + g.setPaint(new RadialGradientPaint(px, py, size, + new float[]{0f, 0.6f, 1f}, + new Color[]{alpha(bokehColor, 90), alpha(bokehColor, 35), alpha(bokehColor, 0)})); + g.fillOval(px - size, py - size, size * 2, size * 2); + } + + g.setComposite(orig); + } + + private static void renderTexture(Graphics2D g, int w, int h) { + Composite orig = g.getComposite(); + g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.018f)); + + for (int y = 0; y < h; y += 2) { + for (int x = 0; x < w; x += 2) { + int n = (x * 17 + y * 31) % 29; + if (n < 10) { + g.setColor(n < 5 ? Color.WHITE : Color.BLACK); + g.fillRect(x, y, 1, 1); + } + } + } + + g.setComposite(orig); + } + + private void renderFrame(Graphics2D g, Palette p, int w, int h) { + int outer = (int) (w * PHI_SQ_INV * 0.12); + int inner = (int) (outer * PHI); + + g.setColor(alpha(p.ornament, 28)); + g.setStroke(new BasicStroke(10f)); + g.drawRect(outer - 4, outer - 4, w - (outer - 4) * 2, h - (outer - 4) * 2); + + g.setColor(alpha(p.ornament, 95)); + g.setStroke(new BasicStroke(2.5f)); + g.drawRect(outer, outer, w - outer * 2, h - outer * 2); + + g.setColor(alpha(p.ornament, 55)); + g.setStroke(new BasicStroke(1f)); + g.drawRect(inner, inner, w - inner * 2, h - inner * 2); + + renderCorners(g, p, w, h, outer); + renderAccents(g, p, w, h, outer); + } + + private static void renderCorners(Graphics2D g, Palette p, int w, int h, int m) { + g.setColor(alpha(p.ornament, 105)); + g.setStroke(new BasicStroke(2.5f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND)); + int size = (int) (m * PHI); + + int[][] corners = {{m, m, 0}, {w - m, m, 90}, {w - m, h - m, 180}, {m, h - m, 270}}; + for (int[] c : corners) renderCorner(g, c[0], c[1], size, c[2]); + } + + private static void renderCorner(Graphics2D g, int x, int y, int size, int angle) { + AffineTransform saved = g.getTransform(); + g.translate(x, y); + g.rotate(Math.toRadians(angle)); + + Path2D path = new Path2D.Float(); + path.moveTo(0, size); + path.lineTo(0, size * PHI_SQ_INV); + path.quadTo(0, 0, size * PHI_SQ_INV, 0); + path.lineTo(size, 0); + g.draw(path); + + Path2D inner = new Path2D.Float(); + inner.moveTo(size * 0.15, size * PHI_INV); + inner.quadTo(size * 0.15, size * 0.15, size * PHI_INV, size * 0.15); + g.draw(inner); + + g.fillOval(-5, -5, 10, 10); + g.fillOval((int) (size * 0.92), -4, 8, 8); + g.fillOval(-4, (int) (size * 0.92), 8, 8); + + g.setTransform(saved); + } + + private static void renderAccents(Graphics2D g, Palette p, int w, int h, int m) { + g.setColor(alpha(p.ornament, 65)); + g.setStroke(new BasicStroke(2f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND)); + int len = (int) (m * PHI); + + g.drawLine(w / 2 - len, m, w / 2 + len, m); + g.fillOval(w / 2 - 5, m - 5, 10, 10); + + g.drawLine(w / 2 - len, h - m, w / 2 + len, h - m); + g.fillOval(w / 2 - 5, h - m - 5, 10, 10); + + g.drawLine(m, h / 2 - len, m, h / 2 + len); + g.fillOval(m - 5, h / 2 - 5, 10, 10); + + g.drawLine(w - m, h / 2 - len, w - m, h / 2 + len); + g.fillOval(w - m - 5, h / 2 - 5, 10, 10); + } + + private int renderTitle(Graphics2D g, String title, Palette p, int w, int h, int margin) { + int maxW = w - margin * 2; + int bottomBound = (int) (h * PHI_INV); + + String text = title.toUpperCase(); + Font font = resolveFont(g, text, maxW, titleSize(title.length()), MAX_TITLE_LINES, true); + g.setFont(font); + FontMetrics fm = g.getFontMetrics(); + + List lines = wrapText(text, fm, maxW, MAX_TITLE_LINES); + int lineH = (int) (fm.getHeight() * 1.12); + int totalH = lines.size() * lineH; + + int availableH = bottomBound - margin - totalH; + int startY = margin + (int) (availableH * PHI_SQ_INV) + fm.getAscent(); + startY = Math.max(startY, margin + fm.getAscent()); + + float tracking = 0.05f; + int lastY = startY; + + for (int i = 0; i < lines.size(); i++) { + String line = lines.get(i); + int lw = trackedWidth(fm, line, tracking); + int x = (w - lw) / 2; + int y = startY + i * lineH; + if (y + fm.getDescent() > bottomBound) break; + renderText(g, line, x, y, tracking, p.textMain, true); + lastY = y; + } + + return lastY + fm.getDescent() + lineH / 2; + } + + private static void renderDivider(Graphics2D g, Palette p, int w, int titleEnd, int h) { + int minY = titleEnd + (int) (h * 0.02); + int maxY = (int) (h * (1 - PHI_SQ_INV * 0.7)); + int cy = minY + (int) ((maxY - minY) * PHI_SQ_INV); + int cx = w / 2; + int lineLen = (int) (w * PHI_SQ_INV * 0.38); + + for (int dir : new int[]{-1, 1}) { + int sx = cx + dir * 50; + int ex = cx + dir * (50 + lineLen); + g.setPaint(new GradientPaint(sx, cy, alpha(p.ornament, 115), ex, cy, alpha(p.ornament, 25))); + g.setStroke(new BasicStroke(2.5f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND)); + g.drawLine(sx, cy, ex, cy); + } + + g.setColor(alpha(p.ornament, 130)); + g.setStroke(new BasicStroke(2f)); + + int ds = 14; + Path2D diamond = new Path2D.Float(); + diamond.moveTo(cx, cy - ds); + diamond.lineTo(cx + ds, cy); + diamond.lineTo(cx, cy + ds); + diamond.lineTo(cx - ds, cy); + diamond.closePath(); + g.draw(diamond); + + int is = 6; + Path2D inner = new Path2D.Float(); + inner.moveTo(cx, cy - is); + inner.lineTo(cx + is, cy); + inner.lineTo(cx, cy + is); + inner.lineTo(cx - is, cy); + inner.closePath(); + g.fill(inner); + + g.fillOval(cx - 50 - 5, cy - 5, 10, 10); + g.fillOval(cx + 50 - 5, cy - 5, 10, 10); + g.fillOval(cx - 32 - 4, cy - 4, 8, 8); + g.fillOval(cx + 32 - 4, cy - 4, 8, 8); + } + + private void renderAuthor(Graphics2D g, String author, Palette p, int w, int h, int margin) { + int maxW = w - margin * 2; + int bottomBound = h - margin; + + String[] authors = author.split(","); + StringBuilder formattedAuthors = new StringBuilder(); + for (int i = 0; i < authors.length; i++) { + if (i > 0) formattedAuthors.append("\n").append(authors[i].trim()); + else formattedAuthors.append(authors[i].trim()); + } + + Font authorFont = resolveFont(g, formattedAuthors.toString(), maxW, authorSize(formattedAuthors.length()), MAX_AUTHOR_LINES, false); + g.setFont(authorFont); + FontMetrics authorFm = g.getFontMetrics(); + + String[] authorLinesArray = formattedAuthors.toString().split("\n"); List lines = new ArrayList<>(); - String[] words = WHITESPACE_PATTERN.split(text); - StringBuilder currentLine = new StringBuilder(); + for (String line : authorLinesArray) { + lines.add(line.trim()); + } - for (String word : words) { - if (currentLine.isEmpty()) { - currentLine.append(word); + int authorLineH = (int) (authorFm.getHeight() * 1.18); + int authorTotalH = lines.size() * authorLineH; + + // Remove the "by" prefix for multiple authors + boolean showByPrefix = lines.size() == 1 && author.length() < 45 && !author.contains(","); + + Font byFont = authorFont.deriveFont(authorFont.getSize() * 0.58f); + FontMetrics byFm = g.getFontMetrics(byFont); + String byText = "— by —"; + int byHeight = showByPrefix ? byFm.getHeight() : 0; + int bySpacing = showByPrefix ? (int) (authorLineH * PHI_SQ_INV * 0.8) : 0; + + int totalBlockH = byHeight + bySpacing + authorTotalH; + + int blockBottom = (int) (h * (1 - PHI_SQ_INV * 0.32)); + blockBottom = Math.min(blockBottom, bottomBound); + int blockTop = blockBottom - totalBlockH; + + int minTop = (int) (h * PHI_INV) + margin; + if (blockTop < minTop) blockTop = minTop; + + int currentY = blockTop; + + if (showByPrefix) { + g.setFont(byFont); + int byW = byFm.stringWidth(byText); + int byX = (w - byW) / 2; + int byY = currentY + byFm.getAscent(); + + g.setColor(new Color(0, 0, 0, 35)); + g.drawString(byText, byX + 3, byY + 3); + + g.setColor(alpha(p.ornament, 155)); + g.drawString(byText, byX, byY); + + currentY = byY + byFm.getDescent() + bySpacing; + } + + g.setFont(authorFont); + float tracking = 0.08f; + + for (int i = 0; i < lines.size(); i++) { + String line = lines.get(i); + if (!line.isEmpty()) { // Only render non-empty lines + int lw = trackedWidth(authorFm, line, tracking); + int x = (w - lw) / 2; + int y = currentY + authorFm.getAscent() + i * authorLineH; + if (y + authorFm.getDescent() > bottomBound) break; + renderText(g, line, x, y, tracking, p.textSub, false); + } + } + } + + private int renderSubtitle(Graphics2D g, String subtitle, Palette p, int w, int h, int margin, int titleEnd) { + int maxW = w - margin * 2; + int bottomBound = h - margin; + + Font subtitleFont = resolveFont(g, subtitle, maxW, subtitleSize(subtitle.length()), 2, false); + g.setFont(subtitleFont); + FontMetrics subtitleFm = g.getFontMetrics(); + + List lines = wrapText(subtitle, subtitleFm, maxW, 2); + int subtitleLineH = (int) (subtitleFm.getHeight() * 1.12); + + // Position subtitle below the title with some spacing + int spacing = (int) (subtitleLineH * 0.5); + int startY = titleEnd + spacing + subtitleFm.getAscent(); + + g.setFont(subtitleFont); + float tracking = 0.06f; + + int lastY = startY; + for (int i = 0; i < lines.size(); i++) { + String line = lines.get(i); + int lw = trackedWidth(subtitleFm, line, tracking); + int x = (w - lw) / 2; + int y = startY + i * subtitleLineH; + if (y + subtitleFm.getDescent() > bottomBound) break; + renderText(g, line, x, y, tracking, p.textSub, false); + lastY = y; + } + + return lastY + subtitleFm.getDescent(); + } + + private int subtitleSize(int len) { + if (len < 12) return 130 * SCALE; + if (len < 22) return 110 * SCALE; + if (len < 35) return 90 * SCALE; + return 75 * SCALE; + } + + private void renderText(Graphics2D g, String text, int x, int y, float tracking, Color color, boolean isTitle) { + FontMetrics fm = g.getFontMetrics(); + int tp = (int) (fm.getHeight() * tracking); + + int[][] shadows = isTitle + ? new int[][]{{8, 8, 14}, {5, 5, 28}, {2, 2, 45}} + : new int[][]{{5, 5, 18}, {2, 2, 35}}; + + for (int[] s : shadows) { + g.setColor(new Color(0, 0, 0, s[2])); + drawTracked(g, text, x + s[0], y + s[1], tp); + } + + g.setColor(color); + drawTracked(g, text, x, y, tp); + + if (isTitle) { + g.setColor(alpha(Color.WHITE, 22)); + drawTracked(g, text, x, y - 1, tp); + } + } + + private void drawTracked(Graphics2D g, String text, int x, int y, int tracking) { + FontMetrics fm = g.getFontMetrics(); + int cx = x; + for (char c : text.toCharArray()) { + g.drawString(String.valueOf(c), cx, y); + cx += fm.charWidth(c) + tracking; + } + } + + private int trackedWidth(FontMetrics fm, String text, float tracking) { + int tp = (int) (fm.getHeight() * tracking); + int w = 0; + for (char c : text.toCharArray()) w += fm.charWidth(c) + tp; + return Math.max(0, w - tp); + } + + private static void renderVignette(Graphics2D g, int w, int h) { + float r = (float) (Math.sqrt(w * w + h * h) / 2 * 1.12); + g.setPaint(new RadialGradientPaint(w / 2f, h / 2f, r, + new float[]{0f, (float) PHI_INV, (float) (PHI_INV + PHI_SQ_INV * 0.25), 0.9f, 1f}, + new Color[]{alpha(Color.BLACK, 0), alpha(Color.BLACK, 0), alpha(Color.BLACK, 15), + alpha(Color.BLACK, 50), alpha(Color.BLACK, 85)})); + g.fillRect(0, 0, w, h); + + g.setPaint(new GradientPaint(0, 0, alpha(Color.WHITE, 14), 0, (int) (h * PHI_SQ_INV), alpha(Color.WHITE, 0))); + g.fillRect(0, 0, w, (int) (h * PHI_SQ_INV)); + } + + private static void renderEdges(Graphics2D g, int w, int h) { + g.setColor(alpha(Color.BLACK, 50)); + g.setStroke(new BasicStroke(3f)); + g.drawRect(0, 0, w - 1, h - 1); + + g.setColor(alpha(Color.WHITE, 10)); + g.drawRect(3, 3, w - 7, h - 7); + } + + private static String sanitize(String input, int max, String fallback) { + if (input == null || input.isBlank()) return fallback; + String s = input.trim(); + return s.length() > max ? s.substring(0, max) : s; + } + + private void configureGraphics(Graphics2D g) { + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB); + g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); + g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); + g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); + g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); + } + + private static Color alpha(Color c, int a) { + return new Color(c.getRed(), c.getGreen(), c.getBlue(), Math.min(255, Math.max(0, a))); + } + + private static Color darken(Color c, float f) { + return new Color(Math.max(0, (int) (c.getRed() * (1 - f))), + Math.max(0, (int) (c.getGreen() * (1 - f))), + Math.max(0, (int) (c.getBlue() * (1 - f)))); + } + + private Color lighten(Color c, float f) { + return new Color(Math.min(255, (int) (c.getRed() + (255 - c.getRed()) * f)), + Math.min(255, (int) (c.getGreen() + (255 - c.getGreen()) * f)), + Math.min(255, (int) (c.getBlue() + (255 - c.getBlue()) * f))); + } + + private Font resolveFont(Graphics2D g, String text, int maxW, int startSize, int maxLines, boolean isTitle) { + String[] serif = {"Palatino Linotype", "Garamond", "Georgia", "Book Antiqua"}; + String[] sans = {"Optima", "Gill Sans", "Helvetica Neue", "Calibri"}; + String[] preferred = isTitle ? serif : sans; + String fallback = isTitle ? Font.SERIF : Font.SANS_SERIF; + int style = isTitle ? Font.BOLD : Font.PLAIN; + + String selected = fallback; + for (String name : preferred) { + Font test = new Font(name, style, startSize); + if (test.getFamily().equalsIgnoreCase(name)) { + selected = name; + break; + } + } + + float tracking = isTitle ? 0.05f : 0.08f; + + for (int size = startSize; size >= MIN_FONT; size -= 2) { + Font font = new Font(selected, style, size); + g.setFont(font); + FontMetrics fm = g.getFontMetrics(); + List lines = wrapText(text, fm, maxW, maxLines); + if (lines.stream().allMatch(l -> trackedWidth(fm, l, tracking) <= maxW)) return font; + } + + return new Font(selected, style, MIN_FONT); + } + + private List wrapText(String text, FontMetrics fm, int maxW, int maxLines) { + List lines = new ArrayList<>(); + StringBuilder cur = new StringBuilder(); + + for (String word : WS.split(text.trim())) { + if (fm.stringWidth(word) > maxW) { + if (!cur.isEmpty()) { + lines.add(cur.toString().trim()); + cur = new StringBuilder(); + } + lines.addAll(breakWord(word, fm, maxW)); + continue; + } + + if (cur.isEmpty()) { + cur.append(word); + } else if (fm.stringWidth(cur + " " + word) <= maxW) { + cur.append(" ").append(word); } else { - int currentWidth = fm.stringWidth(currentLine.toString()); - int spaceWidth = fm.stringWidth(" "); - int wordWidth = fm.stringWidth(word); - if (currentWidth + spaceWidth + wordWidth <= 210) { - currentLine.append(" ").append(word); - } else { - lines.add(currentLine.toString().trim()); - currentLine = new StringBuilder(word); - } + lines.add(cur.toString().trim()); + cur = new StringBuilder(word); } } - if (!currentLine.isEmpty()) { - lines.add(currentLine.toString().trim()); - } - - if (lines.size() > MAX_LINES) { - List truncated = lines.subList(0, MAX_LINES); - String lastLine = truncated.get(MAX_LINES - 1); - - if (fm.stringWidth(lastLine + "...") > 210) { - while (lastLine.length() > 3 && fm.stringWidth(lastLine + "...") > 210) { - lastLine = lastLine.substring(0, lastLine.length() - 1); - } - } - truncated.set(MAX_LINES - 1, lastLine.trim() + "..."); - return truncated; + + if (!cur.isEmpty()) lines.add(cur.toString().trim()); + + if (lines.size() > maxLines) { + lines = new ArrayList<>(lines.subList(0, maxLines)); + String last = lines.get(maxLines - 1); + while (!last.isEmpty() && fm.stringWidth(last + "…") > maxW) + last = last.substring(0, last.length() - 1).trim(); + lines.set(maxLines - 1, last + "…"); } + return lines; } - private Color[] getColorScheme(String title) { - int hash = Math.abs((title != null ? title : "").hashCode()); - Color[][] schemes = { - {new Color(85, 119, 102), new Color(102, 153, 136)}, // Green (Original) - {new Color(102, 119, 153), new Color(136, 153, 187)}, // Blue - {new Color(153, 102, 119), new Color(187, 136, 153)}, // Purple - {new Color(153, 153, 102), new Color(187, 187, 136)}, // Olive - {new Color(102, 153, 153), new Color(136, 187, 187)}, // Teal - {new Color(119, 102, 153), new Color(153, 136, 187)} // Indigo - }; - return schemes[hash % schemes.length]; + private List breakWord(String word, FontMetrics fm, int maxW) { + List parts = new ArrayList<>(); + StringBuilder cur = new StringBuilder(); + + for (char c : word.toCharArray()) { + if (fm.stringWidth(cur.toString() + c) > maxW && !cur.isEmpty()) { + parts.add(cur.toString()); + cur = new StringBuilder(); + } + cur.append(c); + } + if (!cur.isEmpty()) parts.add(cur.toString()); + + return parts; } -} \ No newline at end of file + + private int titleSize(int len) { + if (len < 8) return 150 * SCALE; + if (len < 15) return 130 * SCALE; + if (len < 25) return 110 * SCALE; + if (len < 40) return 92 * SCALE; + if (len < 60) return 78 * SCALE; + if (len < 85) return 66 * SCALE; + return 56 * SCALE; + } + + private int authorSize(int len) { + if (len < 12) return 78 * SCALE; + if (len < 22) return 68 * SCALE; + if (len < 35) return 58 * SCALE; + return 50 * SCALE; + } + + private BufferedImage downscale(BufferedImage src) { + BufferedImage dst = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); + Graphics2D g = dst.createGraphics(); + try { + g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); + g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); + g.drawImage(src, 0, 0, WIDTH, HEIGHT, null); + return dst; + } finally { + g.dispose(); + } + } + + private byte[] encodeJpeg(BufferedImage img) { + ImageWriter writer = null; + ImageOutputStream ios = null; + + try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { + writer = ImageIO.getImageWritersByFormatName("jpg").next(); + ImageWriteParam param = writer.getDefaultWriteParam(); + param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); + param.setCompressionQuality(0.95f); + + ios = ImageIO.createImageOutputStream(baos); + writer.setOutput(ios); + writer.write(null, new IIOImage(img, null, null), param); + return baos.toByteArray(); + } catch (IOException e) { + throw new RuntimeException("JPEG encoding failed", e); + } finally { + if (writer != null) writer.dispose(); + if (ios != null) try { ios.close(); } catch (IOException ignored) {} + } + } + + private void cleanup(Graphics2D g, BufferedImage... images) { + if (g != null) try { g.dispose(); } catch (Exception ignored) {} + for (BufferedImage img : images) + if (img != null) try { img.flush(); } catch (Exception ignored) {} + } +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/MetadataManagementService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/MetadataManagementService.java index b7aec1e3d..4e4b70c93 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/MetadataManagementService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/MetadataManagementService.java @@ -41,16 +41,15 @@ public class MetadataManagementService { MetadataPersistenceSettings settings = appSettingService.getAppSettings().getMetadataPersistenceSettings(); boolean moveFile = settings.isMoveFilesToLibraryPattern(); - boolean writeToFile = settings.isSaveToOriginalFile(); switch (metadataType) { - case authors -> consolidateAuthors(targetValues, valuesToMerge, writeToFile, moveFile); - case categories -> consolidateCategories(targetValues, valuesToMerge, writeToFile, moveFile); - case moods -> consolidateMoods(targetValues, valuesToMerge, writeToFile, moveFile); - case tags -> consolidateTags(targetValues, valuesToMerge, writeToFile, moveFile); - case series -> consolidateSeries(targetValues, valuesToMerge, writeToFile, moveFile); - case publishers -> consolidatePublishers(targetValues, valuesToMerge, writeToFile, moveFile); - case languages -> consolidateLanguages(targetValues, valuesToMerge, writeToFile, moveFile); + case authors -> consolidateAuthors(targetValues, valuesToMerge, moveFile); + case categories -> consolidateCategories(targetValues, valuesToMerge, moveFile); + case moods -> consolidateMoods(targetValues, valuesToMerge, moveFile); + case tags -> consolidateTags(targetValues, valuesToMerge, moveFile); + case series -> consolidateSeries(targetValues, valuesToMerge, moveFile); + case publishers -> consolidatePublishers(targetValues, valuesToMerge, moveFile); + case languages -> consolidateLanguages(targetValues, valuesToMerge, moveFile); } } @@ -64,7 +63,7 @@ public class MetadataManagementService { Optional writerOpt = metadataWriterFactory.getWriter(bookType); if (writerOpt.isPresent()) { File file = book.getFullFilePath().toFile(); - writerOpt.get().writeMetadataToFile(file, metadata, null, null); + writerOpt.get().saveMetadataToFile(file, metadata, null, null); String newHash = FileFingerprint.generateHash(book.getFullFilePath()); book.setCurrentHash(newHash); bookModified = true; @@ -86,7 +85,7 @@ public class MetadataManagementService { } } - private void consolidateAuthors(List targetValues, List valuesToMerge, boolean writeToFile, boolean moveFile) { + private void consolidateAuthors(List targetValues, List valuesToMerge, boolean moveFile) { List targetAuthors = targetValues.stream() .map(name -> authorRepository.findByNameIgnoreCase(name) .map(existing -> { @@ -112,23 +111,19 @@ public class MetadataManagementService { for (BookMetadataEntity metadata : booksWithOldAuthor) { metadata.getAuthors().remove(oldAuthor); metadata.getAuthors().addAll(targetAuthors); - metadata.updateSearchText(); // Manually trigger search text update since collection modification doesn't trigger @PreUpdate + metadata.updateSearchText(); } bookMetadataRepository.saveAll(booksWithOldAuthor); bookMetadataRepository.flush(); - - if (writeToFile) { - writeMetadataToFile(booksWithOldAuthor, moveFile); - } - + writeMetadataToFile(booksWithOldAuthor, moveFile); authorRepository.delete(oldAuthor); } log.info("Consolidated {} authors into {}: {}", authorsToMerge.size(), targetValues, valuesToMerge); } - private void consolidateCategories(List targetValues, List valuesToMerge, boolean writeToFile, boolean moveFile) { + private void consolidateCategories(List targetValues, List valuesToMerge, boolean moveFile) { List targetCategories = targetValues.stream() .map(name -> categoryRepository.findByNameIgnoreCase(name) .map(existing -> { @@ -158,18 +153,14 @@ public class MetadataManagementService { bookMetadataRepository.saveAll(booksWithOldCategory); bookMetadataRepository.flush(); - - if (writeToFile) { - writeMetadataToFile(booksWithOldCategory, moveFile); - } - + writeMetadataToFile(booksWithOldCategory, moveFile); categoryRepository.delete(oldCategory); } log.info("Consolidated {} categories into {}: {}", categoriesToMerge.size(), targetValues, valuesToMerge); } - private void consolidateMoods(List targetValues, List valuesToMerge, boolean writeToFile, boolean moveFile) { + private void consolidateMoods(List targetValues, List valuesToMerge, boolean moveFile) { List targetMoods = targetValues.stream() .map(name -> moodRepository.findByNameIgnoreCase(name) .map(existing -> { @@ -200,17 +191,14 @@ public class MetadataManagementService { bookMetadataRepository.saveAll(booksWithOldMood); bookMetadataRepository.flush(); - if (writeToFile) { - writeMetadataToFile(booksWithOldMood, moveFile); - } - + writeMetadataToFile(booksWithOldMood, moveFile); moodRepository.delete(oldMood); } log.info("Consolidated {} moods into {}: {}", moodsToMerge.size(), targetValues, valuesToMerge); } - private void consolidateTags(List targetValues, List valuesToMerge, boolean writeToFile, boolean moveFile) { + private void consolidateTags(List targetValues, List valuesToMerge, boolean moveFile) { List targetTags = targetValues.stream() .map(name -> tagRepository.findByNameIgnoreCase(name) .map(existing -> { @@ -241,17 +229,14 @@ public class MetadataManagementService { bookMetadataRepository.saveAll(booksWithOldTag); bookMetadataRepository.flush(); - if (writeToFile) { - writeMetadataToFile(booksWithOldTag, moveFile); - } - + writeMetadataToFile(booksWithOldTag, moveFile); tagRepository.delete(oldTag); } log.info("Consolidated {} tags into {}: {}", tagsToMerge.size(), targetValues, valuesToMerge); } - private void consolidateSeries(List targetValues, List valuesToMerge, boolean writeToFile, boolean moveFile) { + private void consolidateSeries(List targetValues, List valuesToMerge, boolean moveFile) { if (targetValues.size() != 1) { throw new IllegalArgumentException("Series merge requires exactly one target value"); } @@ -265,16 +250,13 @@ public class MetadataManagementService { } bookMetadataRepository.saveAll(booksWithOldSeries); - - if (writeToFile) { - writeMetadataToFile(booksWithOldSeries, moveFile); - } + writeMetadataToFile(booksWithOldSeries, moveFile); } log.info("Consolidated {} series into '{}': {}", valuesToMerge.size(), targetSeriesName, valuesToMerge); } - private void consolidatePublishers(List targetValues, List valuesToMerge, boolean writeToFile, boolean moveFile) { + private void consolidatePublishers(List targetValues, List valuesToMerge, boolean moveFile) { if (targetValues.size() != 1) { throw new IllegalArgumentException("Publisher merge requires exactly one target value"); } @@ -288,16 +270,13 @@ public class MetadataManagementService { } bookMetadataRepository.saveAll(booksWithOldPublisher); - - if (writeToFile) { - writeMetadataToFile(booksWithOldPublisher, moveFile); - } + writeMetadataToFile(booksWithOldPublisher, moveFile); } log.info("Consolidated {} publishers into '{}': {}", valuesToMerge.size(), targetPublisher, valuesToMerge); } - private void consolidateLanguages(List targetValues, List valuesToMerge, boolean writeToFile, boolean moveFile) { + private void consolidateLanguages(List targetValues, List valuesToMerge, boolean moveFile) { if (targetValues.size() != 1) { throw new IllegalArgumentException("Language merge requires exactly one target value"); } @@ -311,10 +290,7 @@ public class MetadataManagementService { } bookMetadataRepository.saveAll(booksWithOldLanguage); - - if (writeToFile) { - writeMetadataToFile(booksWithOldLanguage, moveFile); - } + writeMetadataToFile(booksWithOldLanguage, moveFile); } log.info("Consolidated {} languages into '{}': {}", valuesToMerge.size(), targetLanguage, valuesToMerge); @@ -324,20 +300,19 @@ public class MetadataManagementService { public void deleteMetadata(MergeMetadataType metadataType, List valuesToDelete) { MetadataPersistenceSettings settings = appSettingService.getAppSettings().getMetadataPersistenceSettings(); boolean moveFile = settings.isMoveFilesToLibraryPattern(); - boolean writeToFile = settings.isSaveToOriginalFile(); switch (metadataType) { - case authors -> deleteAuthors(valuesToDelete, writeToFile, moveFile); - case categories -> deleteCategories(valuesToDelete, writeToFile, moveFile); - case moods -> deleteMoods(valuesToDelete, writeToFile, moveFile); - case tags -> deleteTags(valuesToDelete, writeToFile, moveFile); - case series -> deleteSeries(valuesToDelete, writeToFile, moveFile); - case publishers -> deletePublishers(valuesToDelete, writeToFile, moveFile); - case languages -> deleteLanguages(valuesToDelete, writeToFile, moveFile); + case authors -> deleteAuthors(valuesToDelete, moveFile); + case categories -> deleteCategories(valuesToDelete, moveFile); + case moods -> deleteMoods(valuesToDelete, moveFile); + case tags -> deleteTags(valuesToDelete, moveFile); + case series -> deleteSeries(valuesToDelete, moveFile); + case publishers -> deletePublishers(valuesToDelete, moveFile); + case languages -> deleteLanguages(valuesToDelete, moveFile); } } - private void deleteAuthors(List valuesToDelete, boolean writeToFile, boolean moveFile) { + private void deleteAuthors(List valuesToDelete, boolean moveFile) { List authorsToDelete = valuesToDelete.stream() .map(authorRepository::findByName) .filter(java.util.Optional::isPresent) @@ -353,18 +328,14 @@ public class MetadataManagementService { bookMetadataRepository.saveAll(booksWithAuthor); bookMetadataRepository.flush(); - - if (writeToFile) { - writeMetadataToFile(booksWithAuthor, moveFile); - } - + writeMetadataToFile(booksWithAuthor, moveFile); authorRepository.delete(author); } log.info("Deleted {} authors: {}", authorsToDelete.size(), valuesToDelete); } - private void deleteCategories(List valuesToDelete, boolean writeToFile, boolean moveFile) { + private void deleteCategories(List valuesToDelete, boolean moveFile) { List categoriesToDelete = valuesToDelete.stream() .map(categoryRepository::findByNameIgnoreCase) .filter(java.util.Optional::isPresent) @@ -380,18 +351,14 @@ public class MetadataManagementService { bookMetadataRepository.saveAll(booksWithCategory); bookMetadataRepository.flush(); - - if (writeToFile) { - writeMetadataToFile(booksWithCategory, moveFile); - } - + writeMetadataToFile(booksWithCategory, moveFile); categoryRepository.delete(category); } log.info("Deleted {} categories: {}", categoriesToDelete.size(), valuesToDelete); } - private void deleteMoods(List valuesToDelete, boolean writeToFile, boolean moveFile) { + private void deleteMoods(List valuesToDelete, boolean moveFile) { List moodsToDelete = valuesToDelete.stream() .map(moodRepository::findByNameIgnoreCase) .filter(java.util.Optional::isPresent) @@ -407,18 +374,14 @@ public class MetadataManagementService { bookMetadataRepository.saveAll(booksWithMood); bookMetadataRepository.flush(); - - if (writeToFile) { - writeMetadataToFile(booksWithMood, moveFile); - } - + writeMetadataToFile(booksWithMood, moveFile); moodRepository.delete(mood); } log.info("Deleted {} moods: {}", moodsToDelete.size(), valuesToDelete); } - private void deleteTags(List valuesToDelete, boolean writeToFile, boolean moveFile) { + private void deleteTags(List valuesToDelete, boolean moveFile) { List tagsToDelete = valuesToDelete.stream() .map(tagRepository::findByNameIgnoreCase) .filter(java.util.Optional::isPresent) @@ -434,18 +397,14 @@ public class MetadataManagementService { bookMetadataRepository.saveAll(booksWithTag); bookMetadataRepository.flush(); - - if (writeToFile) { - writeMetadataToFile(booksWithTag, moveFile); - } - + writeMetadataToFile(booksWithTag, moveFile); tagRepository.delete(tag); } log.info("Deleted {} tags: {}", tagsToDelete.size(), valuesToDelete); } - private void deleteSeries(List valuesToDelete, boolean writeToFile, boolean moveFile) { + private void deleteSeries(List valuesToDelete, boolean moveFile) { for (String seriesName : valuesToDelete) { List booksWithSeries = bookMetadataRepository.findAllBySeriesNameIgnoreCase(seriesName); @@ -457,17 +416,14 @@ public class MetadataManagementService { if (!booksWithSeries.isEmpty()) { bookMetadataRepository.saveAll(booksWithSeries); - - if (writeToFile) { - writeMetadataToFile(booksWithSeries, moveFile); - } + writeMetadataToFile(booksWithSeries, moveFile); } } log.info("Deleted {} series: {}", valuesToDelete.size(), valuesToDelete); } - private void deletePublishers(List valuesToDelete, boolean writeToFile, boolean moveFile) { + private void deletePublishers(List valuesToDelete, boolean moveFile) { for (String publisher : valuesToDelete) { List booksWithPublisher = bookMetadataRepository.findAllByPublisherIgnoreCase(publisher); @@ -477,17 +433,14 @@ public class MetadataManagementService { if (!booksWithPublisher.isEmpty()) { bookMetadataRepository.saveAll(booksWithPublisher); - - if (writeToFile) { - writeMetadataToFile(booksWithPublisher, moveFile); - } + writeMetadataToFile(booksWithPublisher, moveFile); } } log.info("Deleted {} publishers: {}", valuesToDelete.size(), valuesToDelete); } - private void deleteLanguages(List valuesToDelete, boolean writeToFile, boolean moveFile) { + private void deleteLanguages(List valuesToDelete, boolean moveFile) { for (String language : valuesToDelete) { List booksWithLanguage = bookMetadataRepository.findAllByLanguageIgnoreCase(language); @@ -497,10 +450,7 @@ public class MetadataManagementService { if (!booksWithLanguage.isEmpty()) { bookMetadataRepository.saveAll(booksWithLanguage); - - if (writeToFile) { - writeMetadataToFile(booksWithLanguage, moveFile); - } + writeMetadataToFile(booksWithLanguage, moveFile); } } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/extractor/CbxMetadataExtractor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/extractor/CbxMetadataExtractor.java index 27f2cf2a9..47f4e6675 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/extractor/CbxMetadataExtractor.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/extractor/CbxMetadataExtractor.java @@ -27,6 +27,9 @@ import javax.imageio.ImageIO; import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import org.xml.sax.SAXException; import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry; import org.apache.commons.compress.archivers.sevenz.SevenZFile; @@ -49,54 +52,54 @@ public class CbxMetadataExtractor implements FileMetadataExtractor { private static final Pattern COMMA_SEMICOLON_PATTERN = Pattern.compile("[,;]"); @Override - public BookMetadata extractMetadata(File file) { - String baseName = FilenameUtils.getBaseName(file.getName()); - String lowerName = file.getName().toLowerCase(); + public BookMetadata extractMetadata(File file) { + String baseName = FilenameUtils.getBaseName(file.getName()); + String lowerName = file.getName().toLowerCase(); - // Non-archive (fallback) - if (!lowerName.endsWith(".cbz") && !lowerName.endsWith(".cbr") && !lowerName.endsWith(".cb7")) { - return BookMetadata.builder().title(baseName).build(); - } + // Non-archive (fallback) + if (!lowerName.endsWith(".cbz") && !lowerName.endsWith(".cbr") && !lowerName.endsWith(".cb7")) { + return BookMetadata.builder().title(baseName).build(); + } - // CBZ path (ZIP) - if (lowerName.endsWith(".cbz")) { - try (ZipFile zipFile = new ZipFile(file)) { - ZipEntry entry = findComicInfoEntry(zipFile); - if (entry == null) { - return BookMetadata.builder().title(baseName).build(); + // CBZ path (ZIP) + if (lowerName.endsWith(".cbz")) { + try (ZipFile zipFile = new ZipFile(file)) { + ZipEntry entry = findComicInfoEntry(zipFile); + if (entry == null) { + return BookMetadata.builder().title(baseName).build(); + } + try (InputStream is = zipFile.getInputStream(entry)) { + Document document = buildSecureDocument(is); + return mapDocumentToMetadata(document, baseName); + } + } catch (Exception e) { + log.warn("Failed to extract metadata from CBZ", e); + return BookMetadata.builder().title(baseName).build(); + } } - try (InputStream is = zipFile.getInputStream(entry)) { - Document document = buildSecureDocument(is); - return mapDocumentToMetadata(document, baseName); - } - } catch (Exception e) { - log.warn("Failed to extract metadata from CBZ", e); - return BookMetadata.builder().title(baseName).build(); - } - } - // CB7 path (7z) - if (lowerName.endsWith(".cb7")) { - try (SevenZFile sevenZ = SevenZFile.builder().setFile(file).get()) { - SevenZArchiveEntry entry = findSevenZComicInfoEntry(sevenZ); - if (entry == null) { - return BookMetadata.builder().title(baseName).build(); + // CB7 path (7z) + if (lowerName.endsWith(".cb7")) { + try (SevenZFile sevenZ = SevenZFile.builder().setFile(file).get()) { + SevenZArchiveEntry entry = findSevenZComicInfoEntry(sevenZ); + if (entry == null) { + return BookMetadata.builder().title(baseName).build(); + } + byte[] xmlBytes = readSevenZEntryBytes(sevenZ, entry); + if (xmlBytes == null) { + return BookMetadata.builder().title(baseName).build(); + } + try (InputStream is = new ByteArrayInputStream(xmlBytes)) { + Document document = buildSecureDocument(is); + return mapDocumentToMetadata(document, baseName); + } + } catch (Exception e) { + log.warn("Failed to extract metadata from CB7", e); + return BookMetadata.builder().title(baseName).build(); + } } - byte[] xmlBytes = readSevenZEntryBytes(sevenZ, entry); - if (xmlBytes == null) { - return BookMetadata.builder().title(baseName).build(); - } - try (InputStream is = new ByteArrayInputStream(xmlBytes)) { - Document document = buildSecureDocument(is); - return mapDocumentToMetadata(document, baseName); - } - } catch (Exception e) { - log.warn("Failed to extract metadata from CB7", e); - return BookMetadata.builder().title(baseName).build(); - } - } - // CBR path (RAR) + // CBR path (RAR) try (Archive archive = new Archive(file)) { try { FileHeader header = findComicInfoHeader(archive); @@ -118,700 +121,781 @@ public class CbxMetadataExtractor implements FileMetadataExtractor { } catch (Exception ignore) { } return BookMetadata.builder().title(baseName).build(); - } - - private ZipEntry findComicInfoEntry(ZipFile zipFile) { - Enumeration entries = zipFile.entries(); - while (entries.hasMoreElements()) { - ZipEntry entry = entries.nextElement(); - String name = entry.getName(); - if (isComicInfoName(name)) { - return entry; - } - } - return null; - } - - private Document buildSecureDocument(InputStream is) throws Exception { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); - try { - factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); - factory.setFeature("http://xml.org/sax/features/external-general-entities", false); - factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); - } catch (Exception ex) { - log.debug("XML factory secure feature not supported: {}", ex.getMessage()); - } - factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); - factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); - factory.setExpandEntityReferences(false); - DocumentBuilder builder = factory.newDocumentBuilder(); - return builder.parse(is); - } - - private BookMetadata mapDocumentToMetadata( - Document document, - String fallbackTitle - ) { - BookMetadata.BookMetadataBuilder builder = BookMetadata.builder(); - - String title = getTextContent(document, "Title"); - builder.title(title == null || title.isBlank() ? fallbackTitle : title); - - builder.description( - coalesce( - getTextContent(document, "Summary"), - getTextContent(document, "Description") - ) - ); - builder.publisher(getTextContent(document, "Publisher")); - - String series = getTextContent(document, "Series"); - String volume = getTextContent(document, "Volume"); - builder.seriesName(volume == null || volume.isBlank() ? series : String.format("%s (%s)", series, volume)); - builder.seriesNumber(parseFloat(getTextContent(document, "Number"))); - builder.seriesTotal(parseInteger(getTextContent(document, "Count"))); - builder.publishedDate( - parseDate( - getTextContent(document, "Year"), - getTextContent(document, "Month"), - getTextContent(document, "Day") - ) - ); - builder.pageCount( - parseInteger( - coalesce( - getTextContent(document, "PageCount"), - getTextContent(document, "Pages") - ) - ) - ); - builder.language(getTextContent(document, "LanguageISO")); - - Set authors = new HashSet<>(); - authors.addAll(splitValues(getTextContent(document, "Writer"))); - authors.addAll(splitValues(getTextContent(document, "Penciller"))); - authors.addAll(splitValues(getTextContent(document, "Inker"))); - authors.addAll(splitValues(getTextContent(document, "Colorist"))); - authors.addAll(splitValues(getTextContent(document, "Letterer"))); - authors.addAll(splitValues(getTextContent(document, "CoverArtist"))); - if (!authors.isEmpty()) { - builder.authors(authors); } - Set categories = new HashSet<>(); - categories.addAll(splitValues(getTextContent(document, "Genre"))); - categories.addAll(splitValues(getTextContent(document, "Tags"))); - if (!categories.isEmpty()) { - builder.categories(categories); - } - - return builder.build(); - } - - private String getTextContent(Document document, String tag) { - NodeList nodes = document.getElementsByTagName(tag); - if (nodes.getLength() == 0) { - return null; - } - return nodes.item(0).getTextContent().trim(); - } - - private String coalesce(String a, String b) { - return (a != null && !a.isBlank()) - ? a - : (b != null && !b.isBlank() ? b : null); - } - - private Set splitValues(String value) { - if (value == null) { - return new HashSet<>(); - } - return Arrays.stream(COMMA_SEMICOLON_PATTERN.split(value)) - .map(String::trim) - .filter(s -> !s.isEmpty()) - .collect(Collectors.toSet()); - } - - private Integer parseInteger(String value) { - try { - return (value == null || value.isBlank()) - ? null - : Integer.parseInt(value.trim()); - } catch (NumberFormatException e) { - return null; - } - } - - private Float parseFloat(String value) { - try { - return (value == null || value.isBlank()) - ? null - : Float.parseFloat(value.trim()); - } catch (NumberFormatException e) { - return null; - } - } - - private LocalDate parseDate(String year, String month, String day) { - Integer y = parseInteger(year); - Integer m = parseInteger(month); - Integer d = parseInteger(day); - if (y == null) { - return null; - } - if (m == null) { - m = 1; - } - if (d == null) { - d = 1; - } - try { - return LocalDate.of(y, m, d); - } catch (Exception e) { - return null; - } - } - - public BookMetadata extractFromComicInfoXml(File xmlFile) { - try (InputStream is = new FileInputStream(xmlFile)) { - Document document = buildSecureDocument(is); - String fallbackTitle = xmlFile.getParentFile() != null - ? xmlFile.getParentFile().getName() - : xmlFile.getName(); - return mapDocumentToMetadata(document, fallbackTitle); - } catch (Exception e) { - log.warn("Failed to parse ComicInfo.xml: {}", e.getMessage()); - String fallbackTitle = xmlFile.getParentFile() != null - ? xmlFile.getParentFile().getName() - : xmlFile.getName(); - return BookMetadata.builder().title(fallbackTitle).build(); - } - } - - @Override - public byte[] extractCover(File file) { - String lowerName = file.getName().toLowerCase(); - - // Non-archive fallback - if (!lowerName.endsWith(".cbz") && !lowerName.endsWith(".cbr") && !lowerName.endsWith(".cb7")) { - return generatePlaceholderCover(250, 350); - } - - // CBZ path - if (lowerName.endsWith(".cbz")) { - try (ZipFile zipFile = new ZipFile(file)) { - // Try front cover via ComicInfo - ZipEntry coverEntry = findFrontCoverEntry(zipFile); - if (coverEntry != null) { - try (InputStream is = zipFile.getInputStream(coverEntry)) { - byte[] bytes = is.readAllBytes(); - if (canDecode(bytes)) return bytes; - } - } - // Fallback: iterate images alphabetically until a decodable one is found - ZipEntry firstImage = findFirstAlphabeticalImageEntry(zipFile); - if (firstImage != null) { - // Build a sorted list and iterate for decodable formats - java.util.List images = listZipImageEntries(zipFile); - for (ZipEntry e : images) { - try (InputStream is = zipFile.getInputStream(e)) { - byte[] bytes = is.readAllBytes(); - if (canDecode(bytes)) return bytes; + private ZipEntry findComicInfoEntry(ZipFile zipFile) { + Enumeration entries = zipFile.entries(); + while (entries.hasMoreElements()) { + ZipEntry entry = entries.nextElement(); + String name = entry.getName(); + if (isComicInfoName(name)) { + return entry; } - } } - } catch (Exception e) { - log.warn("Failed to extract cover image from CBZ", e); - return generatePlaceholderCover(250, 350); - } + return null; } - // CB7 path - if (lowerName.endsWith(".cb7")) { - try (SevenZFile sevenZ = SevenZFile.builder().setFile(file).get()) { - // Try via ComicInfo.xml first - SevenZArchiveEntry ci = findSevenZComicInfoEntry(sevenZ); - if (ci != null) { - byte[] xmlBytes = readSevenZEntryBytes(sevenZ, ci); - if (xmlBytes != null) { - try (InputStream is = new ByteArrayInputStream(xmlBytes)) { - Document document = buildSecureDocument(is); - String imageName = findFrontCoverImageName(document); - if (imageName != null) { - SevenZArchiveEntry byName = findSevenZEntryByName(sevenZ, imageName); - if (byName != null) { - byte[] bytes = readSevenZEntryBytes(sevenZ, byName); - if (canDecode(bytes)) return bytes; - } - try { - int index = Integer.parseInt(imageName); - SevenZArchiveEntry byIndex = findSevenZImageEntryByIndex(sevenZ, index); - if (byIndex != null) { - byte[] bytes = readSevenZEntryBytes(sevenZ, byIndex); - if (canDecode(bytes)) return bytes; - } - if (index > 0) { - SevenZArchiveEntry offByOne = findSevenZImageEntryByIndex(sevenZ, index - 1); - if (offByOne != null) { - byte[] bytes = readSevenZEntryBytes(sevenZ, offByOne); - if (canDecode(bytes)) return bytes; + /** + * Builds a secure XML document parser with protection against XXE attacks. + * Configures the DocumentBuilderFactory with security features to prevent: + * - External entity injection + * - DTD processing vulnerabilities + * - Schema injection attacks + * + * @param is InputStream containing XML data to parse + * @return Parsed Document object + * @throws Exception if XML parsing fails or security features cannot be configured + */ + private Document buildSecureDocument(InputStream is) throws Exception { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setNamespaceAware(true); // Enable namespace awareness + factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); + try { + factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); + factory.setFeature("http://xml.org/sax/features/external-general-entities", false); + factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); + } catch (Exception ex) { + log.warn("XML factory secure features not supported, XXE protection may be compromised: {}", ex.getMessage()); + throw ex; // Re-throw to fail fast if security features can't be enabled + } + factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); + factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); + factory.setExpandEntityReferences(false); + DocumentBuilder builder = factory.newDocumentBuilder(); + return builder.parse(is); + } + + /** + * Maps XML document to BookMetadata by extracting all relevant ComicInfo fields. + * Handles missing or invalid fields gracefully by using fallback values or null. + * + * @param document The parsed XML document containing ComicInfo data + * @param fallbackTitle Title to use if Title element is missing or blank + * @return BookMetadata object populated with extracted values + */ + private BookMetadata mapDocumentToMetadata( + Document document, + String fallbackTitle + ) { + BookMetadata.BookMetadataBuilder builder = BookMetadata.builder(); + + String title = getTextContent(document, "Title"); + builder.title(title == null || title.isBlank() ? fallbackTitle : title); + + builder.description( + coalesce( + getTextContent(document, "Summary"), + getTextContent(document, "Description") + ) + ); + builder.publisher(getTextContent(document, "Publisher")); + + String series = getTextContent(document, "Series"); + String volume = getTextContent(document, "Volume"); + builder.seriesName(volume == null || volume.isBlank() ? series : String.format("%s (%s)", series, volume)); + builder.seriesNumber(parseFloat(getTextContent(document, "Number"))); + builder.seriesTotal(parseInteger(getTextContent(document, "Count"))); + builder.publishedDate( + parseDate( + getTextContent(document, "Year"), + getTextContent(document, "Month"), + getTextContent(document, "Day") + ) + ); + builder.pageCount( + parseInteger( + coalesce( + getTextContent(document, "PageCount"), + getTextContent(document, "Pages") + ) + ) + ); + builder.language(getTextContent(document, "LanguageISO")); + + Set authors = new HashSet<>(); + authors.addAll(splitValues(getTextContent(document, "Writer"))); + if (!authors.isEmpty()) { + builder.authors(authors); + } + + Set categories = new HashSet<>(); + categories.addAll(splitValues(getTextContent(document, "Genre"))); + categories.addAll(splitValues(getTextContent(document, "Tags"))); + if (!categories.isEmpty()) { + builder.categories(categories); + } + + return builder.build(); + } + + /** + * Extracts and trims text content from the first element with the given tag name. + * + * @param document The XML document to search + * @param tag The tag name to find + * @return Trimmed text content of the first matching element, or null if not found + */ + private String getTextContent(Document document, String tag) { + NodeList nodes = document.getElementsByTagName(tag); + if (nodes.getLength() == 0) { + return null; + } + return nodes.item(0).getTextContent().trim(); + } + + private String coalesce(String a, String b) { + return (a != null && !a.isBlank()) + ? a + : (b != null && !b.isBlank() ? b : null); + } + + /** + * Splits a delimited string into a set of trimmed values. + * Supports both comma (,) and semicolon (;) as delimiters. + * Empty values after trimming are excluded from the result. + * + * @param value The delimited string to split + * @return Set of trimmed non-empty values, or empty set if input is null + */ + private Set splitValues(String value) { + if (value == null) { + return new HashSet<>(); + } + return Arrays.stream(COMMA_SEMICOLON_PATTERN.split(value)) + .map(String::trim) + .filter(s -> !s.isEmpty()) + .collect(Collectors.toSet()); + } + + private Integer parseInteger(String value) { + try { + return (value == null || value.isBlank()) + ? null + : Integer.parseInt(value.trim()); + } catch (NumberFormatException e) { + return null; + } + } + + private Float parseFloat(String value) { + try { + return (value == null || value.isBlank()) + ? null + : Float.parseFloat(value.trim()); + } catch (NumberFormatException e) { + return null; + } + } + + /** + * Parses year, month, and day strings into a LocalDate. + * Defaults missing month/day to 1. Returns null if year is missing or invalid. + * + * @param year Year string (required) + * @param month Month string (optional, defaults to 1) + * @param day Day string (optional, defaults to 1) + * @return LocalDate object, or null if parsing fails or year is null + */ + private LocalDate parseDate(String year, String month, String day) { + Integer y = parseInteger(year); + Integer m = parseInteger(month); + Integer d = parseInteger(day); + if (y == null) { + return null; + } + if (m == null) { + m = 1; + } + if (d == null) { + d = 1; + } + try { + return LocalDate.of(y, m, d); + } catch (Exception e) { + return null; + } + } + + /** + * Extracts metadata from a standalone ComicInfo.xml file. + * This method is useful for processing ComicInfo.xml files that have been + * extracted from comic book archives or exist independently. + * + * @param xmlFile The ComicInfo.xml file to parse + * @return BookMetadata extracted from the XML file, or fallback metadata if parsing fails + * @throws IllegalArgumentException if xmlFile is null + */ + public BookMetadata extractFromComicInfoXml(File xmlFile) { + if (xmlFile == null) { + throw new IllegalArgumentException("XML file cannot be null"); + } + + String fallbackTitle = determineFallbackTitle(xmlFile); + + try (InputStream is = new FileInputStream(xmlFile)) { + Document document = buildSecureDocument(is); + return mapDocumentToMetadata(document, fallbackTitle); + } catch (IOException e) { + log.error("Failed to read ComicInfo.xml file '{}': {}", + xmlFile.getAbsolutePath(), e.getMessage(), e); + return BookMetadata.builder().title(fallbackTitle).build(); + } catch (SAXException | ParserConfigurationException e) { + log.warn("Failed to parse ComicInfo.xml from file '{}': {}", + xmlFile.getAbsolutePath(), e.getMessage(), e); + return BookMetadata.builder().title(fallbackTitle).build(); + } catch (Exception e) { + log.error("Unexpected error processing ComicInfo.xml '{}': {}", + xmlFile.getAbsolutePath(), e.getMessage(), e); + return BookMetadata.builder().title(fallbackTitle).build(); + } + } + + /** + * Determines the fallback title to use when metadata extraction fails. + * Uses the parent directory name if available, otherwise the file name. + * + * @param file The file to determine the fallback title for + * @return A fallback title string + */ + private String determineFallbackTitle(File file) { + // Try parent directory first (usually the comic folder/archive name) + if (file.getParentFile() != null) { + String parentName = file.getParentFile().getName(); + if (parentName != null && !parentName.isBlank()) { + return parentName; + } + } + // Fall back to filename without extension + return FilenameUtils.getBaseName(file.getName()); + } + + @Override + public byte[] extractCover(File file) { + String lowerName = file.getName().toLowerCase(); + + // Non-archive fallback + if (!lowerName.endsWith(".cbz") && !lowerName.endsWith(".cbr") && !lowerName.endsWith(".cb7")) { + return generatePlaceholderCover(250, 350); + } + + // CBZ path + if (lowerName.endsWith(".cbz")) { + try (ZipFile zipFile = new ZipFile(file)) { + // Try front cover via ComicInfo + ZipEntry coverEntry = findFrontCoverEntry(zipFile); + if (coverEntry != null) { + try (InputStream is = zipFile.getInputStream(coverEntry)) { + byte[] bytes = is.readAllBytes(); + if (canDecode(bytes)) return bytes; } - } - } catch (NumberFormatException ignore) { - // continue to fallback } - } + // Fallback: iterate images alphabetically until a decodable one is found + ZipEntry firstImage = findFirstAlphabeticalImageEntry(zipFile); + if (firstImage != null) { + // Build a sorted list and iterate for decodable formats + java.util.List images = listZipImageEntries(zipFile); + for (ZipEntry e : images) { + try (InputStream is = zipFile.getInputStream(e)) { + byte[] bytes = is.readAllBytes(); + if (canDecode(bytes)) return bytes; + } + } + } + } catch (Exception e) { + log.warn("Failed to extract cover image from CBZ", e); + return generatePlaceholderCover(250, 350); } - } } - // Fallback: iterate images alphabetically until a decodable one is found - SevenZArchiveEntry first = findFirstAlphabeticalSevenZImageEntry(sevenZ); - if (first != null) { - java.util.List images = listSevenZImageEntries(sevenZ); - for (SevenZArchiveEntry e : images) { - byte[] bytes = readSevenZEntryBytes(sevenZ, e); - if (canDecode(bytes)) return bytes; - } + // CB7 path + if (lowerName.endsWith(".cb7")) { + try (SevenZFile sevenZ = SevenZFile.builder().setFile(file).get()) { + // Try via ComicInfo.xml first + SevenZArchiveEntry ci = findSevenZComicInfoEntry(sevenZ); + if (ci != null) { + byte[] xmlBytes = readSevenZEntryBytes(sevenZ, ci); + if (xmlBytes != null) { + try (InputStream is = new ByteArrayInputStream(xmlBytes)) { + Document document = buildSecureDocument(is); + String imageName = findFrontCoverImageName(document); + if (imageName != null) { + SevenZArchiveEntry byName = findSevenZEntryByName(sevenZ, imageName); + if (byName != null) { + byte[] bytes = readSevenZEntryBytes(sevenZ, byName); + if (canDecode(bytes)) return bytes; + } + try { + int index = Integer.parseInt(imageName); + SevenZArchiveEntry byIndex = findSevenZImageEntryByIndex(sevenZ, index); + if (byIndex != null) { + byte[] bytes = readSevenZEntryBytes(sevenZ, byIndex); + if (canDecode(bytes)) return bytes; + } + if (index > 0) { + SevenZArchiveEntry offByOne = findSevenZImageEntryByIndex(sevenZ, index - 1); + if (offByOne != null) { + byte[] bytes = readSevenZEntryBytes(sevenZ, offByOne); + if (canDecode(bytes)) return bytes; + } + } + } catch (NumberFormatException ignore) { + // continue to fallback + } + } + } + } + } + + // Fallback: iterate images alphabetically until a decodable one is found + SevenZArchiveEntry first = findFirstAlphabeticalSevenZImageEntry(sevenZ); + if (first != null) { + java.util.List images = listSevenZImageEntries(sevenZ); + for (SevenZArchiveEntry e : images) { + byte[] bytes = readSevenZEntryBytes(sevenZ, e); + if (canDecode(bytes)) return bytes; + } + } + } catch (Exception e) { + log.warn("Failed to extract cover image from CB7", e); + return generatePlaceholderCover(250, 350); + } } - } catch (Exception e) { - log.warn("Failed to extract cover image from CB7", e); + + // CBR path + try (Archive archive = new Archive(file)) { + try { + + // Try via ComicInfo.xml first + FileHeader comicInfo = findComicInfoHeader(archive); + if (comicInfo != null) { + byte[] xmlBytes = readRarEntryBytes(archive, comicInfo); + if (xmlBytes != null) { + try (InputStream is = new ByteArrayInputStream(xmlBytes)) { + Document document = buildSecureDocument(is); + String imageName = findFrontCoverImageName(document); + if (imageName != null) { + FileHeader byName = findRarHeaderByName(archive, imageName); + if (byName != null) { + byte[] bytes = readRarEntryBytes(archive, byName); + if (canDecode(bytes)) return bytes; + } + try { + int index = Integer.parseInt(imageName); + FileHeader byIndex = findRarImageHeaderByIndex(archive, index); + if (byIndex != null) { + byte[] bytes = readRarEntryBytes(archive, byIndex); + if (canDecode(bytes)) return bytes; + } + if (index > 0) { + FileHeader offByOne = findRarImageHeaderByIndex(archive, index - 1); + if (offByOne != null) { + byte[] bytes = readRarEntryBytes(archive, offByOne); + if (canDecode(bytes)) return bytes; + } + } + } catch (NumberFormatException ignore) { + // ignore and continue fallback + } + } + } + } + } + + // Fallback: iterate images alphabetically until a decodable one is found + FileHeader firstImage = findFirstAlphabeticalImageHeader(archive); + if (firstImage != null) { + List images = listRarImageHeaders(archive); + for (FileHeader fh : images) { + byte[] bytes = readRarEntryBytes(archive, fh); + if (canDecode(bytes)) return bytes; + } + } + } catch (Exception e) { + log.warn("Failed to extract cover image from CBR", e); + return generatePlaceholderCover(250, 350); + } + } catch (Exception ignore) { + } + return generatePlaceholderCover(250, 350); - } } - // CBR path - try (Archive archive = new Archive(file)) { - try { - - // Try via ComicInfo.xml first - FileHeader comicInfo = findComicInfoHeader(archive); - if (comicInfo != null) { - byte[] xmlBytes = readRarEntryBytes(archive, comicInfo); - if (xmlBytes != null) { - try (InputStream is = new ByteArrayInputStream(xmlBytes)) { - Document document = buildSecureDocument(is); - String imageName = findFrontCoverImageName(document); - if (imageName != null) { - FileHeader byName = findRarHeaderByName(archive, imageName); - if (byName != null) { - byte[] bytes = readRarEntryBytes(archive, byName); - if (canDecode(bytes)) return bytes; - } - try { - int index = Integer.parseInt(imageName); - FileHeader byIndex = findRarImageHeaderByIndex(archive, index); - if (byIndex != null) { - byte[] bytes = readRarEntryBytes(archive, byIndex); - if (canDecode(bytes)) return bytes; - } - if (index > 0) { - FileHeader offByOne = findRarImageHeaderByIndex(archive, index - 1); - if (offByOne != null) { - byte[] bytes = readRarEntryBytes(archive, offByOne); - if (canDecode(bytes)) return bytes; - } - } - } catch (NumberFormatException ignore) { - // ignore and continue fallback - } - } - } - } - } - - // Fallback: iterate images alphabetically until a decodable one is found - FileHeader firstImage = findFirstAlphabeticalImageHeader(archive); - if (firstImage != null) { - List images = listRarImageHeaders(archive); - for (FileHeader fh : images) { - byte[] bytes = readRarEntryBytes(archive, fh); - if (canDecode(bytes)) return bytes; - } - } - } catch (Exception e) { - log.warn("Failed to extract cover image from CBR", e); - return generatePlaceholderCover(250, 350); - } - } catch (Exception ignore) { - } - - return generatePlaceholderCover(250, 350); - } - - private boolean canDecode(byte[] bytes) { - if (bytes == null || bytes.length == 0) return false; - try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes)) { - BufferedImage img = ImageIO.read(bais); - return img != null; - } catch (IOException e) { - return false; + private boolean canDecode(byte[] bytes) { + if (bytes == null || bytes.length == 0) return false; + try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes)) { + BufferedImage img = ImageIO.read(bais); + return img != null; + } catch (IOException e) { + return false; + } } - } - private ZipEntry findFrontCoverEntry(ZipFile zipFile) { - ZipEntry comicInfoEntry = findComicInfoEntry(zipFile); - if (comicInfoEntry != null) { - try (InputStream is = zipFile.getInputStream(comicInfoEntry)) { - Document document = buildSecureDocument(is); - String imageName = findFrontCoverImageName(document); - if (imageName != null) { - ZipEntry byName = zipFile.getEntry(imageName); - if (byName != null) { - return byName; - } - // also try base-name match for archives with directories or odd encodings - String imageBase = baseName(imageName); - java.util.Enumeration it = zipFile.entries(); - while (it.hasMoreElements()) { - ZipEntry e = it.nextElement(); + private ZipEntry findFrontCoverEntry(ZipFile zipFile) { + ZipEntry comicInfoEntry = findComicInfoEntry(zipFile); + if (comicInfoEntry != null) { + try (InputStream is = zipFile.getInputStream(comicInfoEntry)) { + Document document = buildSecureDocument(is); + String imageName = findFrontCoverImageName(document); + if (imageName != null) { + ZipEntry byName = zipFile.getEntry(imageName); + if (byName != null) { + return byName; + } + // also try base-name match for archives with directories or odd encodings + String imageBase = baseName(imageName); + java.util.Enumeration it = zipFile.entries(); + while (it.hasMoreElements()) { + ZipEntry e = it.nextElement(); + if (!e.isDirectory() && isImageEntry(e.getName())) { + if (baseName(e.getName()).equalsIgnoreCase(imageBase)) { + return e; + } + } + } + try { + int index = Integer.parseInt(imageName); + ZipEntry byIndex = findImageEntryByIndex(zipFile, index); + if (byIndex != null) { + return byIndex; + } + if (index > 0) { + ZipEntry offByOne = findImageEntryByIndex(zipFile, index - 1); + if (offByOne != null) return offByOne; + } + } catch (NumberFormatException ignore) { + // ignore + } + } + } catch (Exception e) { + log.warn("Failed to parse ComicInfo.xml for cover", e); + } + } + // Heuristic filenames before generic fallback + ZipEntry heuristic = findHeuristicCover(zipFile); + if (heuristic != null) return heuristic; + return findFirstAlphabeticalImageEntry(zipFile); + } + + private ZipEntry findImageEntryByIndex(ZipFile zipFile, int index) { + Enumeration entries = zipFile.entries(); + int count = 0; + while (entries.hasMoreElements()) { + ZipEntry entry = entries.nextElement(); + if (!entry.isDirectory() && isImageEntry(entry.getName())) { + if (count == index) { + return entry; + } + count++; + } + } + return null; + } + + private String findFrontCoverImageName(Document document) { + NodeList pages = document.getElementsByTagName("Page"); + for (int i = 0; i < pages.getLength(); i++) { + org.w3c.dom.Node node = pages.item(i); + if (node instanceof org.w3c.dom.Element page) { + String type = page.getAttribute("Type"); + if (type != null && "FrontCover".equalsIgnoreCase(type)) { + String imageFile = page.getAttribute("ImageFile"); + if (imageFile != null && !imageFile.isBlank()) { + return imageFile.trim(); + } + String image = page.getAttribute("Image"); + if (image != null && !image.isBlank()) { + return image.trim(); + } + } + } + } + return null; + } + + private boolean isImageEntry(String name) { + if (!isContentEntry(name)) return false; + String lower = name.toLowerCase(); + return ( + lower.endsWith(".jpg") || + lower.endsWith(".jpeg") || + lower.endsWith(".png") || + lower.endsWith(".gif") || + lower.endsWith(".bmp") || + lower.endsWith(".webp") + ); + } + + private boolean isContentEntry(String name) { + if (name == null) return false; + String norm = name.replace('\\', '/'); + if (norm.startsWith("__MACOSX/") || norm.contains("/__MACOSX/")) return false; + String base = baseName(norm); + if (base.startsWith(".")) return false; + if (".ds_store".equalsIgnoreCase(base)) return false; + return true; + } + + private byte[] generatePlaceholderCover(int width, int height) { + BufferedImage image = new BufferedImage( + width, + height, + BufferedImage.TYPE_INT_RGB + ); + Graphics2D g = image.createGraphics(); + + g.setColor(Color.LIGHT_GRAY); + g.fillRect(0, 0, width, height); + + g.setColor(Color.DARK_GRAY); + g.setFont(new Font("SansSerif", Font.BOLD, width / 10)); + FontMetrics fm = g.getFontMetrics(); + String text = "Preview Unavailable"; + + int textWidth = fm.stringWidth(text); + int textHeight = fm.getAscent(); + g.drawString(text, (width - textWidth) / 2, (height + textHeight) / 2); + + g.dispose(); + + try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { + ImageIO.write(image, "jpg", baos); + return baos.toByteArray(); + } catch (IOException e) { + log.warn("Failed to generate placeholder image", e); + return null; + } + } + + + // ==== RAR (.cbr) helpers ==== + private FileHeader findComicInfoHeader(Archive archive) { + if (archive == null) return null; + for (FileHeader fh : archive.getFileHeaders()) { + String name = fh.getFileName(); + if (name == null) continue; + if (isComicInfoName(name)) { + return fh; + } + } + return null; + } + + private FileHeader findRarHeaderByName(Archive archive, String imageName) { + if (archive == null || imageName == null) return null; + for (FileHeader fh : archive.getFileHeaders()) { + String name = fh.getFileName(); + if (name == null) continue; + if (name.equalsIgnoreCase(imageName)) return fh; + // also try base-name match to be lenient + if (baseName(name).equalsIgnoreCase(baseName(imageName))) return fh; + } + return null; + } + + private FileHeader findRarImageHeaderByIndex(Archive archive, int index) { + int count = 0; + for (FileHeader fh : archive.getFileHeaders()) { + if (!fh.isDirectory() && isImageEntry(fh.getFileName())) { + if (count == index) return fh; + count++; + } + } + return null; + } + + private FileHeader findFirstImageHeader(Archive archive) { + for (FileHeader fh : archive.getFileHeaders()) { + if (!fh.isDirectory() && isImageEntry(fh.getFileName())) { + return fh; + } + } + return null; + } + + private byte[] readRarEntryBytes(Archive archive, FileHeader header) { + try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { + archive.extractFile(header, baos); + return baos.toByteArray(); + } catch (Exception e) { + log.warn("Failed to read RAR entry bytes for {}", header != null ? header.getFileName() : "", e); + return null; + } + } + + private String baseName(String path) { + if (path == null) return null; + int slash = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\')); + return slash >= 0 ? path.substring(slash + 1) : path; + } + + private FileHeader findFirstAlphabeticalImageHeader(Archive archive) { + if (archive == null) return null; + List images = new ArrayList<>(); + for (FileHeader fh : archive.getFileHeaders()) { + if (fh == null || fh.isDirectory()) continue; + String name = fh.getFileName(); + if (name == null) continue; + if (isImageEntry(name)) { + images.add(fh); + } + } + if (images.isEmpty()) return null; + images.sort((a, b) -> naturalCompare(a.getFileName(), b.getFileName())); + return images.getFirst(); + } + + private ZipEntry findFirstAlphabeticalImageEntry(ZipFile zipFile) { + List images = new ArrayList<>(); + Enumeration entries = zipFile.entries(); + while (entries.hasMoreElements()) { + ZipEntry e = entries.nextElement(); if (!e.isDirectory() && isImageEntry(e.getName())) { - if (baseName(e.getName()).equalsIgnoreCase(imageBase)) { + images.add(e); + } + } + if (images.isEmpty()) return null; + images.sort((a, b) -> naturalCompare(a.getName(), b.getName())); + return images.getFirst(); + } + + // ==== 7z (.cb7) helpers ==== + private SevenZArchiveEntry findSevenZComicInfoEntry(SevenZFile sevenZ) { + for (SevenZArchiveEntry e : sevenZ.getEntries()) { + if (e == null || e.isDirectory()) continue; + String name = e.getName(); + if (name != null && isComicInfoName(name)) { return e; - } } - } - try { - int index = Integer.parseInt(imageName); - ZipEntry byIndex = findImageEntryByIndex(zipFile, index); - if (byIndex != null) { - return byIndex; + } + return null; + } + + private SevenZArchiveEntry findSevenZEntryByName(SevenZFile sevenZ, String imageName) { + if (imageName == null) return null; + for (SevenZArchiveEntry e : sevenZ.getEntries()) { + if (e == null || e.isDirectory()) continue; + String name = e.getName(); + if (name == null) continue; + if (name.equalsIgnoreCase(imageName)) return e; + // also allow base-name match + if (baseName(name).equalsIgnoreCase(baseName(imageName))) return e; + } + return null; + } + + private SevenZArchiveEntry findSevenZImageEntryByIndex(SevenZFile sevenZ, int index) { + int count = 0; + for (SevenZArchiveEntry e : sevenZ.getEntries()) { + if (!e.isDirectory() && isImageEntry(e.getName())) { + if (count == index) return e; + count++; } - if (index > 0) { - ZipEntry offByOne = findImageEntryByIndex(zipFile, index - 1); - if (offByOne != null) return offByOne; + } + return null; + } + + private SevenZArchiveEntry findFirstAlphabeticalSevenZImageEntry(SevenZFile sevenZ) { + List images = new ArrayList<>(); + for (SevenZArchiveEntry e : sevenZ.getEntries()) { + if (!e.isDirectory() && isImageEntry(e.getName())) { + images.add(e); } - } catch (NumberFormatException ignore) { - // ignore - } } - } catch (Exception e) { - log.warn("Failed to parse ComicInfo.xml for cover", e); - } + if (images.isEmpty()) return null; + images.sort((a, b) -> naturalCompare(a.getName(), b.getName())); + return images.getFirst(); } - // Heuristic filenames before generic fallback - ZipEntry heuristic = findHeuristicCover(zipFile); - if (heuristic != null) return heuristic; - return findFirstAlphabeticalImageEntry(zipFile); - } - private ZipEntry findImageEntryByIndex(ZipFile zipFile, int index) { - Enumeration entries = zipFile.entries(); - int count = 0; - while (entries.hasMoreElements()) { - ZipEntry entry = entries.nextElement(); - if (!entry.isDirectory() && isImageEntry(entry.getName())) { - if (count == index) { - return entry; + private byte[] readSevenZEntryBytes(SevenZFile sevenZ, SevenZArchiveEntry entry) throws IOException { + try (InputStream is = sevenZ.getInputStream(entry); + ByteArrayOutputStream baos = new ByteArrayOutputStream()) { + if (is == null) return null; + is.transferTo(baos); + return baos.toByteArray(); } - count++; - } } - return null; - } - private String findFrontCoverImageName(Document document) { - NodeList pages = document.getElementsByTagName("Page"); - for (int i = 0; i < pages.getLength(); i++) { - org.w3c.dom.Node node = pages.item(i); - if (node instanceof org.w3c.dom.Element page) { - String type = page.getAttribute("Type"); - if (type != null && "FrontCover".equalsIgnoreCase(type)) { - String imageFile = page.getAttribute("ImageFile"); - if (imageFile != null && !imageFile.isBlank()) { - return imageFile.trim(); - } - String image = page.getAttribute("Image"); - if (image != null && !image.isBlank()) { - return image.trim(); - } + private java.util.List listZipImageEntries(ZipFile zipFile) { + java.util.List images = new java.util.ArrayList<>(); + java.util.Enumeration en = zipFile.entries(); + while (en.hasMoreElements()) { + ZipEntry e = en.nextElement(); + if (!e.isDirectory() && isImageEntry(e.getName())) images.add(e); } - } + images.sort((a, b) -> naturalCompare(a.getName(), b.getName())); + // Heuristic preferred names first + images.sort((a, b) -> Boolean.compare(!likelyCoverName(baseName(a.getName())), !likelyCoverName(baseName(b.getName())))); + return images; } - return null; - } - private boolean isImageEntry(String name) { - if (!isContentEntry(name)) return false; - String lower = name.toLowerCase(); - return ( - lower.endsWith(".jpg") || - lower.endsWith(".jpeg") || - lower.endsWith(".png") || - lower.endsWith(".gif") || - lower.endsWith(".bmp") || - lower.endsWith(".webp") - ); - } - - private boolean isContentEntry(String name) { - if (name == null) return false; - String norm = name.replace('\\', '/'); - if (norm.startsWith("__MACOSX/") || norm.contains("/__MACOSX/")) return false; - String base = baseName(norm); - if (base.startsWith(".")) return false; - if (".ds_store".equalsIgnoreCase(base)) return false; - return true; - } - - private byte[] generatePlaceholderCover(int width, int height) { - BufferedImage image = new BufferedImage( - width, - height, - BufferedImage.TYPE_INT_RGB - ); - Graphics2D g = image.createGraphics(); - - g.setColor(Color.LIGHT_GRAY); - g.fillRect(0, 0, width, height); - - g.setColor(Color.DARK_GRAY); - g.setFont(new Font("SansSerif", Font.BOLD, width / 10)); - FontMetrics fm = g.getFontMetrics(); - String text = "Preview Unavailable"; - - int textWidth = fm.stringWidth(text); - int textHeight = fm.getAscent(); - g.drawString(text, (width - textWidth) / 2, (height + textHeight) / 2); - - g.dispose(); - - try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { - ImageIO.write(image, "jpg", baos); - return baos.toByteArray(); - } catch (IOException e) { - log.warn("Failed to generate placeholder image", e); - return null; + private java.util.List listSevenZImageEntries(SevenZFile sevenZ) { + java.util.List images = new java.util.ArrayList<>(); + for (SevenZArchiveEntry e : sevenZ.getEntries()) { + if (!e.isDirectory() && isImageEntry(e.getName())) images.add(e); + } + images.sort((a, b) -> naturalCompare(a.getName(), b.getName())); + images.sort((a, b) -> Boolean.compare(!likelyCoverName(baseName(a.getName())), !likelyCoverName(baseName(b.getName())))); + return images; } - } - - // ==== RAR (.cbr) helpers ==== - private FileHeader findComicInfoHeader(Archive archive) { - if (archive == null) return null; - for (FileHeader fh : archive.getFileHeaders()) { - String name = fh.getFileName(); - if (name == null) continue; - if (isComicInfoName(name)) { - return fh; - } + private java.util.List listRarImageHeaders(Archive archive) { + java.util.List images = new java.util.ArrayList<>(); + for (FileHeader fh : archive.getFileHeaders()) { + if (fh != null && !fh.isDirectory() && isImageEntry(fh.getFileName())) images.add(fh); + } + images.sort((a, b) -> naturalCompare(a.getFileName(), b.getFileName())); + images.sort((a, b) -> Boolean.compare(!likelyCoverName(baseName(a.getFileName())), !likelyCoverName(baseName(b.getFileName())))); + return images; } - return null; - } - private FileHeader findRarHeaderByName(Archive archive, String imageName) { - if (archive == null || imageName == null) return null; - for (FileHeader fh : archive.getFileHeaders()) { - String name = fh.getFileName(); - if (name == null) continue; - if (name.equalsIgnoreCase(imageName)) return fh; - // also try base-name match to be lenient - if (baseName(name).equalsIgnoreCase(baseName(imageName))) return fh; + private boolean likelyCoverName(String base) { + if (base == null) return false; + String n = base.toLowerCase(); + return n.startsWith("cover") || "folder".equals(n) || n.startsWith("front"); } - return null; - } - private FileHeader findRarImageHeaderByIndex(Archive archive, int index) { - int count = 0; - for (FileHeader fh : archive.getFileHeaders()) { - if (!fh.isDirectory() && isImageEntry(fh.getFileName())) { - if (count == index) return fh; - count++; - } + private int naturalCompare(String a, String b) { + if (a == null) return b == null ? 0 : -1; + if (b == null) return 1; + String s1 = a.toLowerCase(); + String s2 = b.toLowerCase(); + int i = 0, j = 0, n1 = s1.length(), n2 = s2.length(); + while (i < n1 && j < n2) { + char c1 = s1.charAt(i); + char c2 = s2.charAt(j); + if (Character.isDigit(c1) && Character.isDigit(c2)) { + int i1 = i; + while (i1 < n1 && Character.isDigit(s1.charAt(i1))) i1++; + int j1 = j; + while (j1 < n2 && Character.isDigit(s2.charAt(j1))) j1++; + String num1 = LEADING_ZEROS_PATTERN.matcher(s1.substring(i, i1)).replaceFirst(""); + String num2 = LEADING_ZEROS_PATTERN.matcher(s2.substring(j, j1)).replaceFirst(""); + int cmp = Integer.compare(num1.isEmpty() ? 0 : Integer.parseInt(num1), num2.isEmpty() ? 0 : Integer.parseInt(num2)); + if (cmp != 0) return cmp; + i = i1; + j = j1; + } else { + if (c1 != c2) return Character.compare(c1, c2); + i++; + j++; + } + } + return Integer.compare(n1 - i, n2 - j); } - return null; - } - private FileHeader findFirstImageHeader(Archive archive) { - for (FileHeader fh : archive.getFileHeaders()) { - if (!fh.isDirectory() && isImageEntry(fh.getFileName())) { - return fh; - } + private ZipEntry findHeuristicCover(ZipFile zipFile) { + java.util.List images = listZipImageEntries(zipFile); + for (ZipEntry e : images) { + if (likelyCoverName(baseName(e.getName()))) return e; + } + return null; } - return null; - } - private byte[] readRarEntryBytes(Archive archive, FileHeader header) { - try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { - archive.extractFile(header, baos); - return baos.toByteArray(); - } catch (Exception e) { - log.warn("Failed to read RAR entry bytes for {}", header != null ? header.getFileName() : "", e); - return null; + private static boolean isComicInfoName(String name) { + if (name == null) return false; + String n = name.replace('\\', '/'); + if (n.endsWith("/")) return false; + String lower = n.toLowerCase(); + return "comicinfo.xml".equals(lower) || lower.endsWith("/comicinfo.xml"); } - } - - private String baseName(String path) { - if (path == null) return null; - int slash = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\')); - return slash >= 0 ? path.substring(slash + 1) : path; - } - - private FileHeader findFirstAlphabeticalImageHeader(Archive archive) { - if (archive == null) return null; - List images = new ArrayList<>(); - for (FileHeader fh : archive.getFileHeaders()) { - if (fh == null || fh.isDirectory()) continue; - String name = fh.getFileName(); - if (name == null) continue; - if (isImageEntry(name)) { - images.add(fh); - } - } - if (images.isEmpty()) return null; - images.sort((a, b) -> naturalCompare(a.getFileName(), b.getFileName())); - return images.getFirst(); - } - - private ZipEntry findFirstAlphabeticalImageEntry(ZipFile zipFile) { - List images = new ArrayList<>(); - Enumeration entries = zipFile.entries(); - while (entries.hasMoreElements()) { - ZipEntry e = entries.nextElement(); - if (!e.isDirectory() && isImageEntry(e.getName())) { - images.add(e); - } - } - if (images.isEmpty()) return null; - images.sort((a, b) -> naturalCompare(a.getName(), b.getName())); - return images.getFirst(); - } - - // ==== 7z (.cb7) helpers ==== - private SevenZArchiveEntry findSevenZComicInfoEntry(SevenZFile sevenZ) { - for (SevenZArchiveEntry e : sevenZ.getEntries()) { - if (e == null || e.isDirectory()) continue; - String name = e.getName(); - if (name != null && isComicInfoName(name)) { - return e; - } - } - return null; - } - - private SevenZArchiveEntry findSevenZEntryByName(SevenZFile sevenZ, String imageName) { - if (imageName == null) return null; - for (SevenZArchiveEntry e : sevenZ.getEntries()) { - if (e == null || e.isDirectory()) continue; - String name = e.getName(); - if (name == null) continue; - if (name.equalsIgnoreCase(imageName)) return e; - // also allow base-name match - if (baseName(name).equalsIgnoreCase(baseName(imageName))) return e; - } - return null; - } - - private SevenZArchiveEntry findSevenZImageEntryByIndex(SevenZFile sevenZ, int index) { - int count = 0; - for (SevenZArchiveEntry e : sevenZ.getEntries()) { - if (!e.isDirectory() && isImageEntry(e.getName())) { - if (count == index) return e; - count++; - } - } - return null; - } - - private SevenZArchiveEntry findFirstAlphabeticalSevenZImageEntry(SevenZFile sevenZ) { - List images = new ArrayList<>(); - for (SevenZArchiveEntry e : sevenZ.getEntries()) { - if (!e.isDirectory() && isImageEntry(e.getName())) { - images.add(e); - } - } - if (images.isEmpty()) return null; - images.sort((a, b) -> naturalCompare(a.getName(), b.getName())); - return images.getFirst(); - } - - private byte[] readSevenZEntryBytes(SevenZFile sevenZ, SevenZArchiveEntry entry) throws IOException { - try (InputStream is = sevenZ.getInputStream(entry); - ByteArrayOutputStream baos = new ByteArrayOutputStream()) { - if (is == null) return null; - is.transferTo(baos); - return baos.toByteArray(); - } - } - - private java.util.List listZipImageEntries(ZipFile zipFile) { - java.util.List images = new java.util.ArrayList<>(); - java.util.Enumeration en = zipFile.entries(); - while (en.hasMoreElements()) { - ZipEntry e = en.nextElement(); - if (!e.isDirectory() && isImageEntry(e.getName())) images.add(e); - } - images.sort((a, b) -> naturalCompare(a.getName(), b.getName())); - // Heuristic preferred names first - images.sort((a, b) -> Boolean.compare(!likelyCoverName(baseName(a.getName())), !likelyCoverName(baseName(b.getName())))); - return images; - } - - private java.util.List listSevenZImageEntries(SevenZFile sevenZ) { - java.util.List images = new java.util.ArrayList<>(); - for (SevenZArchiveEntry e : sevenZ.getEntries()) { - if (!e.isDirectory() && isImageEntry(e.getName())) images.add(e); - } - images.sort((a, b) -> naturalCompare(a.getName(), b.getName())); - images.sort((a, b) -> Boolean.compare(!likelyCoverName(baseName(a.getName())), !likelyCoverName(baseName(b.getName())))); - return images; - } - - private java.util.List listRarImageHeaders(Archive archive) { - java.util.List images = new java.util.ArrayList<>(); - for (FileHeader fh : archive.getFileHeaders()) { - if (fh != null && !fh.isDirectory() && isImageEntry(fh.getFileName())) images.add(fh); - } - images.sort((a, b) -> naturalCompare(a.getFileName(), b.getFileName())); - images.sort((a, b) -> Boolean.compare(!likelyCoverName(baseName(a.getFileName())), !likelyCoverName(baseName(b.getFileName())))); - return images; - } - - private boolean likelyCoverName(String base) { - if (base == null) return false; - String n = base.toLowerCase(); - return n.startsWith("cover") || "folder".equals(n) || n.startsWith("front"); - } - - private int naturalCompare(String a, String b) { - if (a == null) return b == null ? 0 : -1; - if (b == null) return 1; - String s1 = a.toLowerCase(); - String s2 = b.toLowerCase(); - int i = 0, j = 0, n1 = s1.length(), n2 = s2.length(); - while (i < n1 && j < n2) { - char c1 = s1.charAt(i); - char c2 = s2.charAt(j); - if (Character.isDigit(c1) && Character.isDigit(c2)) { - int i1 = i; while (i1 < n1 && Character.isDigit(s1.charAt(i1))) i1++; - int j1 = j; while (j1 < n2 && Character.isDigit(s2.charAt(j1))) j1++; - String num1 = LEADING_ZEROS_PATTERN.matcher(s1.substring(i, i1)).replaceFirst(""); - String num2 = LEADING_ZEROS_PATTERN.matcher(s2.substring(j, j1)).replaceFirst(""); - int cmp = Integer.compare(num1.isEmpty() ? 0 : Integer.parseInt(num1), num2.isEmpty() ? 0 : Integer.parseInt(num2)); - if (cmp != 0) return cmp; - i = i1; j = j1; - } else { - if (c1 != c2) return Character.compare(c1, c2); - i++; j++; - } - } - return Integer.compare(n1 - i, n2 - j); - } - - private ZipEntry findHeuristicCover(ZipFile zipFile) { - java.util.List images = listZipImageEntries(zipFile); - for (ZipEntry e : images) { - if (likelyCoverName(baseName(e.getName()))) return e; - } - return null; - } - - private static boolean isComicInfoName(String name) { - if (name == null) return false; - String n = name.replace('\\', '/'); - if (n.endsWith("/")) return false; - String lower = n.toLowerCase(); - return "comicinfo.xml".equals(lower) || lower.endsWith("/comicinfo.xml"); - } } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/parser/ComicvineBookParser.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/parser/ComicvineBookParser.java index e9b2af8bd..6dbb1cf23 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/parser/ComicvineBookParser.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/parser/ComicvineBookParser.java @@ -5,6 +5,7 @@ import com.adityachandel.booklore.model.dto.BookMetadata; import com.adityachandel.booklore.model.dto.request.FetchMetadataRequest; import com.adityachandel.booklore.model.dto.response.comicvineapi.Comic; import com.adityachandel.booklore.model.dto.response.comicvineapi.ComicvineApiResponse; +import com.adityachandel.booklore.model.dto.response.comicvineapi.ComicvineIssueResponse; import com.adityachandel.booklore.model.enums.MetadataProvider; import com.adityachandel.booklore.service.appsettings.AppSettingService; import com.adityachandel.booklore.util.BookUtils; @@ -23,11 +24,10 @@ import java.time.Instant; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; +import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; +import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; @@ -39,6 +39,14 @@ public class ComicvineBookParser implements BookParser { private static final String COMICVINE_URL = "https://comicvine.gamespot.com/api/"; private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd"); private static final Pattern DIGIT_PATTERN = Pattern.compile("\\d+"); + private static final Pattern SERIES_ISSUE_PATTERN = Pattern.compile("^(.+?)\\s+#?(\\d+(?:\\.\\d+)?)(?:\\s|$)", Pattern.CASE_INSENSITIVE); + private static final Pattern DIGITAL_PATTERN = Pattern.compile("\\(digital\\)", Pattern.CASE_INSENSITIVE); + private static final Pattern PARENTHETICAL_PATTERN = Pattern.compile("\\([^)]*\\)"); + private static final Pattern BRACKETED_PATTERN = Pattern.compile("\\[[^\\]]*\\]"); + private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\s+"); + private static final Pattern SPECIAL_ISSUE_PATTERN = Pattern.compile("(annual|special|one-?shot)\\s+(\\d+)", Pattern.CASE_INSENSITIVE); + private static final Pattern YEAR_PATTERN = Pattern.compile("\\(?(\\d{4})\\)?"); + private static final long MIN_REQUEST_INTERVAL_MS = 1000; private final ObjectMapper objectMapper; private final AppSettingService appSettingService; @@ -46,6 +54,22 @@ public class ComicvineBookParser implements BookParser { private final AtomicBoolean rateLimited = new AtomicBoolean(false); private final AtomicLong rateLimitResetTime = new AtomicLong(0); + private final AtomicLong lastRequestTime = new AtomicLong(0); + private final Map volumeCache = new java.util.concurrent.ConcurrentHashMap<>(); + + private static class CachedVolumes { + final List volumes; + final long timestamp; + + CachedVolumes(List volumes) { + this.volumes = volumes; + this.timestamp = System.currentTimeMillis(); + } + + boolean isExpired() { + return System.currentTimeMillis() - timestamp > 300_000; + } + } @Override public List fetchMetadata(Book book, FetchMetadataRequest fetchMetadataRequest) { @@ -64,37 +88,247 @@ public class ComicvineBookParser implements BookParser { } public List getMetadataListByTerm(String term) { + SeriesAndIssue seriesAndIssue = extractSeriesAndIssue(term); + + // Try precise search if issue number present + if (seriesAndIssue.issue() != null) { + log.info("Attempting structured search for Series: '{}', Issue: '{}', Year: '{}', Type: '{}'", + seriesAndIssue.series(), seriesAndIssue.issue(), seriesAndIssue.year(), seriesAndIssue.issueType()); + List preciseResults = searchVolumesAndIssues(seriesAndIssue.series(), seriesAndIssue.issue(), seriesAndIssue.year()); + if (!preciseResults.isEmpty()) { + return preciseResults; + } + log.info("Structured search yielded no results, falling back to general search."); + } + + // Fallback to general search + return searchGeneral(term); + } + + private List searchVolumesAndIssues(String seriesName, String issueNumber, Integer extractedYear) { + String normalizedIssue = normalizeIssueNumber(issueNumber); + if (seriesName.endsWith(" " + issueNumber) || seriesName.endsWith(" " + normalizedIssue)) { + // Strip issue number from series name if it leaked in + seriesName = seriesName.replaceAll("\\s+" + Pattern.quote(issueNumber) + "$", "") + .replaceAll("\\s+" + Pattern.quote(normalizedIssue) + "$", "") + .trim(); + log.warn("Issue number found in series name, corrected to: '{}'", seriesName); + } + + final String finalSeriesName = seriesName; + log.debug("searchVolumesAndIssues: seriesName='{}', issueNumber='{}', year='{}'", finalSeriesName, issueNumber, extractedYear); + List volumes = searchVolumes(finalSeriesName); + if (volumes.isEmpty()) { + log.debug("No volumes found for series '{}'", finalSeriesName); + return Collections.emptyList(); + } + + // Sort volumes by relevance + volumes.sort((v1, v2) -> { + int score1 = 0; + int score2 = 0; + + if (extractedYear != null) { + if (matchesYear(v1, extractedYear)) score1 += 100; + if (matchesYear(v2, extractedYear)) score2 += 100; + } + + if (v1.getName() != null && v1.getName().equalsIgnoreCase(finalSeriesName)) score1 += 50; + if (v2.getName() != null && v2.getName().equalsIgnoreCase(finalSeriesName)) score2 += 50; + + try { + int requestedIssue = (int) Math.floor(Double.parseDouble(normalizedIssue)); + if (v1.getCountOfIssues() != null && v1.getCountOfIssues() >= requestedIssue) score1 += 20; + if (v2.getCountOfIssues() != null && v2.getCountOfIssues() >= requestedIssue) score2 += 20; + } catch (NumberFormatException ignored) {} + + Set majorPublishers = Set.of("Marvel", "DC Comics", "Image", "Dark Horse Comics", "IDW Publishing"); + if (v1.getPublisher() != null && majorPublishers.stream().anyMatch(p -> v1.getPublisher().getName().contains(p))) score1 += 10; + if (v2.getPublisher() != null && majorPublishers.stream().anyMatch(p -> v2.getPublisher().getName().contains(p))) score2 += 10; + + return Integer.compare(score2, score1); + }); + + List results = new ArrayList<>(); + // Limit to top 3 volumes to minimize API calls + int limit = Math.min(volumes.size(), 3); + + for (int i = 0; i < limit; i++) { + Comic volume = volumes.get(i); + log.debug("Checking volume: id='{}', name='{}', start_year='{}'", volume.getId(), volume.getName(), volume.getStartYear()); + + List issues = searchIssuesInVolume(volume.getId(), issueNumber); + if (!issues.isEmpty()) { + results.addAll(issues); + + // If we found a result in a high-score volume (e.g. year matched), stop. + if (extractedYear != null && matchesYear(volume, extractedYear)) { + log.info("Found match in year-aligned volume '{}' ({}) . Stopping further volume searches.", volume.getName(), volume.getStartYear()); + break; + } + } + } + return results; + } + + private boolean matchesYear(Comic volume, int targetYear) { + if (volume.getStartYear() == null) return false; + try { + int volYear = Integer.parseInt(volume.getStartYear()); + return Math.abs(volYear - targetYear) <= 1; + } catch (NumberFormatException e) { + return false; + } + } + + private List searchVolumes(String seriesName) { + CachedVolumes cached = volumeCache.get(seriesName.toLowerCase()); + if (cached != null && !cached.isExpired()) { + log.debug("Using cached volume search for '{}'", seriesName); + return cached.volumes; + } + String apiToken = getApiToken(); if (apiToken == null) return Collections.emptyList(); + URI uri = UriComponentsBuilder.fromUriString(COMICVINE_URL) + .path("/search/") + .queryParam("api_key", apiToken) + .queryParam("format", "json") + .queryParam("resources", "volume") + .queryParam("query", seriesName) + .queryParam("limit", 10) + .queryParam("field_list", "id,name,publisher,start_year,count_of_issues") + .build() + .toUri(); + + ComicvineApiResponse response = sendRequest(uri, ComicvineApiResponse.class); + List volumes = response != null && response.getResults() != null ? response.getResults() : Collections.emptyList(); + + if (!volumes.isEmpty()) { + volumeCache.put(seriesName.toLowerCase(), new CachedVolumes(volumes)); + } else if (seriesName.contains(" - ")) { + String alternativeName = seriesName.replace(" - ", ": "); + log.debug("No results for '{}', trying alternative name '{}'", seriesName, alternativeName); + return searchVolumes(alternativeName); + } + + return volumes; + } + + private List searchIssuesInVolume(int volumeId, String issueNumber) { + String apiToken = getApiToken(); + if (apiToken == null) return Collections.emptyList(); + + String normalizedIssue = normalizeIssueNumber(issueNumber); + log.debug("searchIssuesInVolume: volumeId='{}', original='{}', normalized='{}'", + volumeId, issueNumber, normalizedIssue); + + String fieldsList = String.join(",", "api_detail_url", "cover_date", "description", "id", "image", "issue_number", "name", "volume", "site_detail_url"); + + URI uri = UriComponentsBuilder.fromUriString(COMICVINE_URL) + .path("/issues/") + .queryParam("api_key", apiToken) + .queryParam("format", "json") + .queryParam("filter", "volume:" + volumeId + ",issue_number:" + normalizedIssue) + .queryParam("field_list", fieldsList) + .queryParam("limit", 5) + .build() + .toUri(); + + ComicvineApiResponse response = sendRequest(uri, ComicvineApiResponse.class); + if (response != null && response.getResults() != null && !response.getResults().isEmpty()) { + Comic firstIssue = response.getResults().getFirst(); + String returnedIssue = normalizeIssueNumber(firstIssue.getIssueNumber()); + + if (!normalizedIssue.equals(returnedIssue)) { + log.warn("Issue number mismatch! Requested '{}', got '{}' from volume {}", + normalizedIssue, returnedIssue, volumeId); + return Collections.emptyList(); + } + + BookMetadata detailed = fetchIssueDetails(firstIssue.getId()); + + return Collections.singletonList(Objects.requireNonNullElseGet(detailed, () -> convertToBookMetadata(firstIssue))); + } + return Collections.emptyList(); + } + + private BookMetadata fetchIssueDetails(int issueId) { + String apiToken = getApiToken(); + if (apiToken == null) return null; + + String fieldsList = String.join(",", "api_detail_url", "cover_date", "description", "id", "image", "issue_number", "name", "person_credits", "volume", "site_detail_url"); + + URI uri = UriComponentsBuilder.fromUriString(COMICVINE_URL) + .path("/issue/4000-" + issueId + "/") + .queryParam("api_key", apiToken) + .queryParam("format", "json") + .queryParam("field_list", fieldsList) + .build() + .toUri(); + + ComicvineIssueResponse response = sendRequest(uri, ComicvineIssueResponse.class); + if (response != null && response.getResults() != null) { + return convertToBookMetadata(response.getResults()); + } + return null; + } + + private List searchGeneral(String term) { + String apiToken = getApiToken(); + if (apiToken == null) return Collections.emptyList(); + + String fieldsList = String.join(",", "api_detail_url", "cover_date", "description", "id", "image", "issue_number", "name", "publisher", "volume", "site_detail_url", "resource_type", "start_year", "count_of_issues"); + String resources = "volume,issue"; + + URI uri = UriComponentsBuilder.fromUriString(COMICVINE_URL) + .path("/search/") + .queryParam("api_key", apiToken) + .queryParam("format", "json") + .queryParam("resources", resources) + .queryParam("query", term) + .queryParam("limit", 10) + .queryParam("field_list", fieldsList) + .build() + .toUri(); + + ComicvineApiResponse response = sendRequest(uri, ComicvineApiResponse.class); + if (response != null && response.getResults() != null) { + return response.getResults().stream() + .map(this::convertToBookMetadata) + .collect(Collectors.toList()); + } + return Collections.emptyList(); + } + + private T sendRequest(URI uri, Class responseType) { + return sendRequestWithRetry(uri, responseType, 2); + } + + private T sendRequestWithRetry(URI uri, Class responseType, int retriesLeft) { if (rateLimited.get()) { long currentTime = System.currentTimeMillis(); if (currentTime < rateLimitResetTime.get()) { - log.warn("ComicVine API is currently rate limited. Skipping request for term: '{}'. Rate limit resets at: {}", - term, Instant.ofEpochMilli(rateLimitResetTime.get())); - return Collections.emptyList(); + log.warn("ComicVine API is currently rate limited. Skipping request. Rate limit resets at: {}", + Instant.ofEpochMilli(rateLimitResetTime.get())); + return null; } else { - // Rate limit has expired, reset the flag rateLimited.compareAndSet(true, false); } } - log.info("Comicvine: Fetching metadata for term: '{}'", term); + long now = System.currentTimeMillis(); + long timeSinceLastRequest = now - lastRequestTime.get(); + if (timeSinceLastRequest < MIN_REQUEST_INTERVAL_MS) { + try { + Thread.sleep(MIN_REQUEST_INTERVAL_MS - timeSinceLastRequest); + } catch (InterruptedException ignored) {} + } + lastRequestTime.set(System.currentTimeMillis()); + try { - String fieldsList = String.join(",", "api_detail_url", "cover_date", "description", "id", "image", "issue_number", "name", "publisher", "volume"); - String resources = "volume,issue"; - - URI uri = UriComponentsBuilder.fromUriString(COMICVINE_URL) - .path("/search/") - .queryParam("api_key", apiToken) - .queryParam("format", "json") - .queryParam("resources", resources) - .queryParam("query", term) - .queryParam("limit", 10) - .queryParam("field_list", fieldsList) - .build() - .toUri(); - + log.debug("Sending request to ComicVine: {}", uri); HttpRequest request = HttpRequest.newBuilder() .uri(uri) .header("User-Agent", "BookLore/1.0 (Book and Comic Metadata Fetcher; +https://github.com/booklore-app/booklore)") @@ -102,77 +336,323 @@ public class ComicvineBookParser implements BookParser { .build(); HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); + log.debug("Received response from ComicVine: status='{}', body_length='{}'", + response.statusCode(), response.body() != null ? response.body().length() : 0); if (response.statusCode() == 200) { - return parseComicvineApiResponse(response.body()); + return objectMapper.readValue(response.body(), responseType); } else if (response.statusCode() == 420 || response.statusCode() == 429) { - log.error("ComicVine API rate limit exceeded (Error {}). Setting rate limit flag.", response.statusCode()); + handleRateLimit(response); + return null; + } else if (response.statusCode() >= 500 && retriesLeft > 0) { + log.warn("ComicVine API returned status {}. Retrying... ({} retries left)", + response.statusCode(), retriesLeft); + try { + Thread.sleep(2000); + } catch (InterruptedException ignored) {} + return sendRequestWithRetry(uri, responseType, retriesLeft - 1); + } else { + log.error("Comicvine API returned status code {}. Body: {}", response.statusCode(), response.body()); + } + } catch (IOException e) { + if (retriesLeft > 0) { + log.warn("IOException during ComicVine request. Retrying... ({} retries left)", retriesLeft, e); + try { + Thread.sleep(1000); + } catch (InterruptedException ignored) {} + return sendRequestWithRetry(uri, responseType, retriesLeft - 1); + } else { + log.error("Error fetching data from Comicvine API after retries", e); + } + } catch (InterruptedException e) { + log.error("Request interrupted", e); + Thread.currentThread().interrupt(); + } + return null; + } - long resetDelayMs = 3600000; // Default to 1 hour - List retryAfterHeaders = response.headers().allValues("Retry-After"); - if (!retryAfterHeaders.isEmpty()) { - try { - String retryAfter = retryAfterHeaders.getFirst(); - if (DIGIT_PATTERN.matcher(retryAfter).matches()) { - resetDelayMs = Long.parseLong(retryAfter) * 1000; - } else { - Instant instant = Instant.parse(retryAfter); - resetDelayMs = instant.toEpochMilli() - System.currentTimeMillis(); - if (resetDelayMs <= 0) { - resetDelayMs = 3600000; // Default to 1 hour if date is in the past - } - } - } catch (Exception e) { - log.warn("Could not parse Retry-After header '{}', using default 1 hour delay", retryAfterHeaders.getFirst()); + private void handleRateLimit(HttpResponse response) { + log.error("ComicVine API rate limit exceeded (Error {}). Setting rate limit flag.", response.statusCode()); + + long resetDelayMs = 3600000; + List retryAfterHeaders = response.headers().allValues("Retry-After"); + if (!retryAfterHeaders.isEmpty()) { + try { + String retryAfter = retryAfterHeaders.getFirst(); + if (DIGIT_PATTERN.matcher(retryAfter).matches()) { + resetDelayMs = Long.parseLong(retryAfter) * 1000; + } else { + Instant instant = Instant.parse(retryAfter); + resetDelayMs = instant.toEpochMilli() - System.currentTimeMillis(); + if (resetDelayMs <= 0) { + resetDelayMs = 3600000; } } - - if (rateLimited.compareAndSet(false, true)) { - rateLimitResetTime.set(System.currentTimeMillis() + resetDelayMs); - log.info("Rate limit will reset at: {}", Instant.ofEpochMilli(rateLimitResetTime.get())); - } - - return Collections.emptyList(); - } else { - log.error("Comicvine Search API returned status code {}", response.statusCode()); + } catch (Exception e) { + log.warn("Could not parse Retry-After header '{}', using default 1 hour delay", retryAfterHeaders.getFirst()); } - } catch (IOException | InterruptedException e) { - log.error("Error fetching metadata from Comicvine Search API", e); } - return Collections.emptyList(); + + if (rateLimited.compareAndSet(false, true)) { + rateLimitResetTime.set(System.currentTimeMillis() + resetDelayMs); + log.info("Rate limit will reset at: {}", Instant.ofEpochMilli(rateLimitResetTime.get())); + } + } + + private BookMetadata convertToBookMetadata(Comic comic) { + // Check if this is a Volume + if ("volume".equalsIgnoreCase(comic.getResourceType())) { + return BookMetadata.builder() + .provider(MetadataProvider.Comicvine) + .comicvineId(String.valueOf(comic.getId())) + .title(comic.getName()) // Use volume name as title + .seriesName(comic.getName()) + .seriesTotal(comic.getCountOfIssues()) + .publishedDate(safeParseDate(comic.getStartYear() + "-01-01")) // Rough estimate if only year + .description(comic.getDescription()) + .publisher(comic.getPublisher() != null ? comic.getPublisher().getName() : null) + .thumbnailUrl(comic.getImage() != null ? comic.getImage().getMediumUrl() : null) + .externalUrl(comic.getSiteDetailUrl()) + .build(); + } + + Set authors = extractAuthors(comic.getPersonCredits()); + String formattedTitle = formatTitle(comic.getVolume() != null ? comic.getVolume().getName() : null, comic.getIssueNumber(), comic.getName()); + + BookMetadata metadata = BookMetadata.builder() + .provider(MetadataProvider.Comicvine) + .comicvineId(String.valueOf(comic.getId())) + .title(formattedTitle) + .authors(authors) + .thumbnailUrl(comic.getImage() != null ? comic.getImage().getMediumUrl() : null) + .description(comic.getDescription()) + .seriesName(comic.getVolume() != null ? comic.getVolume().getName() : null) + .seriesNumber(safeParseFloat(comic.getIssueNumber())) + .publishedDate(safeParseDate(comic.getCoverDate())) + .externalUrl(comic.getSiteDetailUrl()) + .build(); + + if (metadata.getSeriesName() == null || metadata.getSeriesNumber() == null) { + log.warn("Incomplete metadata for issue {}: missing series name or number", metadata.getComicvineId()); + } + + if (metadata.getAuthors().isEmpty()) { + log.debug("No authors found for issue {} ({})", metadata.getComicvineId(), metadata.getTitle()); + } + + return metadata; + } + + private BookMetadata convertToBookMetadata(ComicvineIssueResponse.IssueResults issue) { + // Extract ID from api_detail_url: "https://comicvine.gamespot.com/api/issue/4000-12345/" + String comicvineId = null; + if (issue.getApiDetailUrl() != null) { + Matcher matcher = Pattern.compile("/(\\d+)/?$").matcher(issue.getApiDetailUrl()); + if (matcher.find()) { + comicvineId = matcher.group(1); + } + } + + Set authors = extractAuthors(issue.getPersonCredits()); + String formattedTitle = formatTitle(issue.getVolume() != null ? issue.getVolume().getName() : null, issue.getIssueNumber(), issue.getName()); + + BookMetadata metadata = BookMetadata.builder() + .provider(MetadataProvider.Comicvine) + .comicvineId(comicvineId) + .title(formattedTitle) + .authors(authors) + .thumbnailUrl(issue.getImage() != null ? issue.getImage().getMediumUrl() : null) + .description(issue.getDescription()) + .seriesName(issue.getVolume() != null ? issue.getVolume().getName() : null) + .seriesNumber(safeParseFloat(issue.getIssueNumber())) + .publishedDate(safeParseDate(issue.getCoverDate())) + .externalUrl(issue.getSiteDetailUrl()) + .build(); + + if (metadata.getSeriesName() == null || metadata.getSeriesNumber() == null) { + log.warn("Incomplete metadata for issue {}: missing series name or number", comicvineId); + } + + if (metadata.getAuthors().isEmpty()) { + log.debug("No authors found for issue {} ({})", comicvineId, metadata.getTitle()); + } + + return metadata; + } + + private String formatTitle(String seriesName, String issueNumber, String issueName) { + if (seriesName == null) return issueName; + + String normalizedIssue = normalizeIssueNumber(issueNumber); + String title = seriesName + " #" + (normalizedIssue != null ? normalizedIssue : ""); + + // Append issue title if it exists and isn't just "Issue #X" or identical to series + if (issueName != null && !issueName.isBlank()) { + String lowerName = issueName.toLowerCase(); + boolean isGeneric = lowerName.matches("issue\\s*#?\\d+") || lowerName.equals(seriesName.toLowerCase()); + if (!isGeneric) { + title += " - " + issueName; + } + } + return title; + } + + private Set extractAuthors(List personCredits) { + if (personCredits == null || personCredits.isEmpty()) { + return Collections.emptySet(); + } + + // Primary writer roles + Set writerRoles = Set.of("writer", "script", "story", "plotter", "plot"); + + // Collect writers + Set authors = personCredits.stream() + .filter(pc -> { + if (pc.getRole() == null) return false; + String role = pc.getRole().toLowerCase(); + return writerRoles.stream().anyMatch(role::contains); + }) + .map(Comic.PersonCredit::getName) + .filter(name -> name != null && !name.isEmpty()) + .collect(Collectors.toSet()); + + // Fallback: If no writers found, check for "creator" role + if (authors.isEmpty()) { + // DEBUG: Log all roles if we missed them + List allRoles = personCredits.stream() + .map(pc -> pc.getName() + " (" + pc.getRole() + ")") + .toList(); + log.debug("No writers found. Available roles: {}", allRoles); + + authors = personCredits.stream() + .filter(pc -> pc.getRole() != null && pc.getRole().toLowerCase().contains("creator")) + .map(Comic.PersonCredit::getName) + .filter(name -> name != null && !name.isEmpty()) + .collect(Collectors.toSet()); + } + + return authors; } private String getSearchTerm(Book book, FetchMetadataRequest request) { if (request.getTitle() != null && !request.getTitle().isEmpty()) { return request.getTitle(); } else if (book.getFileName() != null && !book.getFileName().isEmpty()) { - return BookUtils.cleanFileName(book.getFileName()); + // Use filename but preserve parentheses for year extraction + String name = book.getFileName(); + // Remove extension only + int dotIndex = name.lastIndexOf('.'); + if (dotIndex > 0) { + name = name.substring(0, dotIndex); + } + return name.trim(); } return null; } - private List parseComicvineApiResponse(String responseBody) throws IOException { - ComicvineApiResponse apiResponse = objectMapper.readValue(responseBody, ComicvineApiResponse.class); - if (apiResponse.getResults() == null) { - return Collections.emptyList(); + private SeriesAndIssue extractSeriesAndIssue(String term) { + // 1. Extract Year + Integer year = null; + Matcher yearMatcher = YEAR_PATTERN.matcher(term); + String yearString = null; + if (yearMatcher.find()) { + try { + int y = Integer.parseInt(yearMatcher.group(1)); + if (y > 1900 && y <= LocalDate.now().getYear() + 1) { + year = y; + yearString = yearMatcher.group(0); + } + } catch (NumberFormatException ignored) {} } - return apiResponse.getResults().stream() - .map(this::convertToBookMetadata) - .collect(Collectors.toList()); - } - private BookMetadata convertToBookMetadata(Comic comic) { - return BookMetadata.builder() - .provider(MetadataProvider.Comicvine) - .comicvineId(String.valueOf(comic.getId())) - .title(comic.getName()) - .authors(new HashSet<>()) - .thumbnailUrl(comic.getImage() != null ? comic.getImage().getMediumUrl() : null) - .description(comic.getDescription()) - .seriesName(comic.getVolume() != null ? comic.getVolume().getName() : null) - .seriesNumber(safeParseFloat(comic.getIssueNumber())) - .publishedDate(safeParseDate(comic.getCoverDate())) - .build(); + // 2. Remove ONLY the found year and noise from the term + String cleaned = term; + if (yearString != null) { + cleaned = cleaned.replace(yearString, ""); + } + cleaned = DIGITAL_PATTERN.matcher(cleaned).replaceAll(""); + cleaned = PARENTHETICAL_PATTERN.matcher(cleaned).replaceAll(""); + cleaned = BRACKETED_PATTERN.matcher(cleaned).replaceAll(""); + cleaned = cleaned.trim(); + cleaned = WHITESPACE_PATTERN.matcher(cleaned).replaceAll(" "); + + log.debug("Cleaned filename: '{}'", cleaned); + + // 3. Check for special issue keywords BEFORE extracting issue number + String lowerCleaned = cleaned.toLowerCase(); + if (lowerCleaned.contains("annual") || + lowerCleaned.contains("special") || + lowerCleaned.contains("one-shot") || + lowerCleaned.contains("one shot")) { + + // Try to extract number from "Annual 2" or "Special 3" + Matcher specialMatcher = SPECIAL_ISSUE_PATTERN.matcher(cleaned); + if (specialMatcher.find()) { + String type = specialMatcher.group(1); + String num = specialMatcher.group(2); + // Return series name before the special keyword + String series = cleaned.substring(0, specialMatcher.start()).trim(); + return new SeriesAndIssue(series, num, year, type); + } else { + // "Batman Annual" without number - search for all annuals + return new SeriesAndIssue(cleaned, null, year, "annual"); + } + } + + // 4. Standard issue extraction with IMPROVED PATTERN + Matcher matcher = SERIES_ISSUE_PATTERN.matcher(cleaned); + if (matcher.find()) { + String series = matcher.group(1).trim(); + String issueNum = matcher.group(2); + + if (series.endsWith("#")) { + series = series.substring(0, series.length() - 1).trim(); + } + + log.debug("Extracted - Series: '{}', Issue: '{}'", series, issueNum); + return new SeriesAndIssue(series, issueNum, year, null); + } + + log.debug("No issue number found in: '{}'", cleaned); + return new SeriesAndIssue(cleaned, null, year, null); + } + + private String normalizeIssueNumber(String issueNumber) { + if (issueNumber == null || issueNumber.isEmpty()) { + return issueNumber; + } + + issueNumber = issueNumber.trim(); + + if (issueNumber.contains("/")) { + try { + String[] parts = issueNumber.split("/"); + if (parts.length == 2) { + double numerator = Double.parseDouble(parts[0]); + double denominator = Double.parseDouble(parts[1]); + return String.valueOf(numerator / denominator); + } + } catch (NumberFormatException e) { + log.warn("Could not parse fractional issue number '{}'", issueNumber); + return issueNumber; + } + } + + try { + if (issueNumber.contains(".")) { + double d = Double.parseDouble(issueNumber); + if (d == Math.floor(d)) { + return String.valueOf((int) d); + } else { + return new java.text.DecimalFormat("0.#####").format(d); + } + } else { + return String.valueOf(Integer.parseInt(issueNumber)); + } + } catch (NumberFormatException e) { + log.debug("Non-numeric issue number '{}', using as-is", issueNumber); + return issueNumber; + } } private static LocalDate safeParseDate(String dateStr) { @@ -203,47 +683,5 @@ public class ComicvineBookParser implements BookParser { return apiToken; } - /*public Set fetchAuthors(int issueId) { - String apiToken = getApiToken(); - if (apiToken == null) return Collections.emptySet(); - - try { - String fieldsList = String.join(",", "person_credits"); - - URI uri = UriComponentsBuilder.fromUriString(COMICVINE_URL) - .path("/issue/4000-" + issueId + "/") - .queryParam("api_key", apiToken) - .queryParam("format", "json") - .queryParam("field_list", fieldsList) - .build() - .toUri(); - - HttpRequest request = HttpRequest.newBuilder() - .uri(uri) - .header("User-Agent", "Booklore/1.0") - .GET() - .build(); - - HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); - - if (response.statusCode() == 200) { - ComicvineIssueResponse issueResponse = objectMapper.readValue(response.body(), ComicvineIssueResponse.class); - if (issueResponse.getResults() == null || issueResponse.getResults().getPersonCredits() == null) { - log.warn("No person credits found for issue ID {}", issueId); - return Collections.emptySet(); - } - - return issueResponse.getResults().getPersonCredits().stream() - .filter(pc -> pc.getRole() != null && pc.getRole().toLowerCase().contains("writer")) - .map(ComicvineIssueResponse.PersonCredit::getName) - .collect(Collectors.toSet()); - - } else { - log.error("Comicvine Issue API returned status code {}", response.statusCode()); - } - } catch (IOException | InterruptedException e) { - log.error("Error fetching issue metadata from Comicvine Issue API", e); - } - return Collections.emptySet(); - }*/ + private record SeriesAndIssue(String series, String issue, Integer year, String issueType) {} } \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/parser/GoodReadsParser.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/parser/GoodReadsParser.java index 8e3ba5b99..1baad5322 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/parser/GoodReadsParser.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/parser/GoodReadsParser.java @@ -478,10 +478,15 @@ public class GoodReadsParser implements BookParser { try { String searchUrl = generateSearchUrl(searchTerm); - Elements previewBooks = fetchDoc(searchUrl) - .select("table.tableList") - .first() - .select("tr[itemtype=http://schema.org/Book]"); + Document doc = fetchDoc(searchUrl); + Element tableList = doc.select("table.tableList").first(); + + if (tableList == null) { + log.warn("GoodReads: No results table found for search term: {}", searchTerm); + return Collections.emptyList(); + } + + Elements previewBooks = tableList.select("tr[itemtype=http://schema.org/Book]"); List metadataPreviews = new ArrayList<>(); FuzzyScore fuzzyScore = new FuzzyScore(Locale.ENGLISH); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/writer/CbxMetadataWriter.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/writer/CbxMetadataWriter.java index be19f765d..b45e1ccd9 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/writer/CbxMetadataWriter.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/writer/CbxMetadataWriter.java @@ -1,10 +1,13 @@ package com.adityachandel.booklore.service.metadata.writer; import com.adityachandel.booklore.model.MetadataClearFlags; +import com.adityachandel.booklore.model.dto.settings.MetadataPersistenceSettings; import com.adityachandel.booklore.model.entity.BookMetadataEntity; import com.adityachandel.booklore.model.enums.BookFileType; +import com.adityachandel.booklore.service.appsettings.AppSettingService; import com.github.junrar.Archive; import com.github.junrar.rarfile.FileHeader; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry; import org.apache.commons.compress.archivers.sevenz.SevenZFile; @@ -38,414 +41,509 @@ import java.util.zip.ZipOutputStream; @Slf4j @Component +@RequiredArgsConstructor public class CbxMetadataWriter implements MetadataWriter { private static final Pattern VALID_FILENAME_PATTERN = Pattern.compile("^[\\w./\\\\-]+$"); + private static final int BUFFER_SIZE = 8192; + + private final AppSettingService appSettingService; @Override - public void writeMetadataToFile(File file, BookMetadataEntity metadata, String thumbnailUrl, MetadataClearFlags clearFlags) { - Path backup = null; - Path tempDir = null; - Path tempFile = null; - boolean writeSucceeded = false; - try { - // Create a backup next to the source file (temp name, safe to delete later) - backup = Files.createTempFile(file.getParentFile().toPath(), "cbx_backup_", ".bak"); - Files.copy(file.toPath(), backup, StandardCopyOption.REPLACE_EXISTING); - } catch (Exception ex) { - log.warn("Unable to create backup for {}: {}", file.getAbsolutePath(), ex.getMessage(), ex); + public void saveMetadataToFile(File file, BookMetadataEntity metadata, String thumbnailUrl, MetadataClearFlags clearFlags) { + if (!shouldSaveMetadataToFile(file)) { + return; } + String fileName = file.getName().toLowerCase(Locale.ROOT); + boolean isCbz = fileName.endsWith(".cbz"); + boolean isCbr = fileName.endsWith(".cbr"); + boolean isCb7 = fileName.endsWith(".cb7"); + + if (!isCbz && !isCbr && !isCb7) { + log.warn("Unsupported file type for CBX writer: {}", file.getName()); + return; + } + + Path backupPath = createBackupFile(file); + Path extractDir = null; + Path tempArchive = null; + boolean writeSucceeded = false; + try { - String nameLower = file.getName().toLowerCase(Locale.ROOT); - boolean isCbz = nameLower.endsWith(".cbz"); - boolean isCbr = nameLower.endsWith(".cbr"); - boolean isCb7 = nameLower.endsWith(".cb7"); + Document xmlDoc = loadOrCreateComicInfoXml(file, isCbz, isCb7, isCbr); + applyMetadataChanges(xmlDoc, metadata, clearFlags); + byte[] xmlContent = convertDocumentToBytes(xmlDoc); - if (!isCbz && !isCbr && !isCb7) { - log.warn("Unsupported file type for CBX writer: {}", file.getName()); - return; - } - - // Build (or load and update) ComicInfo.xml as a Document - Document doc; if (isCbz) { - try (ZipFile zipFile = new ZipFile(file)) { - ZipEntry existing = findComicInfoEntry(zipFile); - if (existing != null) { - try (InputStream is = zipFile.getInputStream(existing)) { - doc = buildSecureDocument(is); - } - } else { - doc = newEmptyComicInfo(); - } - } + tempArchive = updateZipArchive(file, xmlContent); + writeSucceeded = true; } else if (isCb7) { - try (SevenZFile sevenZ = SevenZFile.builder().setFile(file).get()) { - SevenZArchiveEntry existing = null; - for (SevenZArchiveEntry e : sevenZ.getEntries()) { - if (e != null && !e.isDirectory() && isComicInfoName(e.getName())) { - existing = e; - break; - } - } - if (existing != null) { - try (InputStream is = sevenZ.getInputStream(existing)) { - doc = buildSecureDocument(is); - } - } else { - doc = newEmptyComicInfo(); - } - } - } else { // CBR - try (Archive archive = new Archive(file)) { - FileHeader existing = findComicInfoHeader(archive); - if (existing != null) { - try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { - archive.extractFile(existing, baos); - try (InputStream is = new java.io.ByteArrayInputStream(baos.toByteArray())) { - doc = buildSecureDocument(is); - } - } - } else { - doc = newEmptyComicInfo(); - } - } - } - - // Apply metadata to the Document - Element root = doc.getDocumentElement(); - MetadataCopyHelper helper = new MetadataCopyHelper(metadata); - helper.copyTitle(clearFlags != null && clearFlags.isTitle(), val -> setElement(doc, root, "Title", val)); - helper.copyDescription(clearFlags != null && clearFlags.isDescription(), val -> { - setElement(doc, root, "Summary", val); - removeElement(root, "Description"); - }); - helper.copyPublisher(clearFlags != null && clearFlags.isPublisher(), val -> setElement(doc, root, "Publisher", val)); - helper.copySeriesName(clearFlags != null && clearFlags.isSeriesName(), val -> setElement(doc, root, "Series", val)); - helper.copySeriesNumber(clearFlags != null && clearFlags.isSeriesNumber(), val -> setElement(doc, root, "Number", formatFloat(val))); - helper.copySeriesTotal(clearFlags != null && clearFlags.isSeriesTotal(), val -> setElement(doc, root, "Count", val != null ? val.toString() : null)); - helper.copyPublishedDate(clearFlags != null && clearFlags.isPublishedDate(), date -> setDateElements(doc, root, date)); - helper.copyPageCount(clearFlags != null && clearFlags.isPageCount(), val -> setElement(doc, root, "PageCount", val != null ? val.toString() : null)); - helper.copyLanguage(clearFlags != null && clearFlags.isLanguage(), val -> setElement(doc, root, "LanguageISO", val)); - helper.copyAuthors(clearFlags != null && clearFlags.isAuthors(), set -> { - setElement(doc, root, "Writer", join(set)); - removeElement(root, "Penciller"); - removeElement(root, "Inker"); - removeElement(root, "Colorist"); - removeElement(root, "Letterer"); - removeElement(root, "CoverArtist"); - }); - helper.copyCategories(clearFlags != null && clearFlags.isCategories(), set -> { - setElement(doc, root, "Genre", join(set)); - removeElement(root, "Tags"); - }); - - // Serialize ComicInfo.xml - Transformer transformer = TransformerFactory.newInstance().newTransformer(); - transformer.setOutputProperty(OutputKeys.INDENT, "yes"); - transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); - ByteArrayOutputStream xmlBaos = new ByteArrayOutputStream(); - transformer.transform(new DOMSource(doc), new StreamResult(xmlBaos)); - byte[] xmlBytes = xmlBaos.toByteArray(); - - // Repack depending on container type; always write to a temp target then atomic move - if (isCbz) { - tempFile = Files.createTempFile("cbx_edit", ".cbz"); - repackZipReplacingComicInfo(file.toPath(), tempFile, xmlBytes); - atomicReplace(tempFile, file.toPath()); - tempFile = null; // Successfully moved, don't delete in finally + tempArchive = convert7zToZip(file, xmlContent); writeSucceeded = true; - return; - } - - if (isCb7) { - // Convert to CBZ with updated ComicInfo.xml - tempFile = Files.createTempFile("cbx_edit", ".cbz"); - try (SevenZFile sevenZ = SevenZFile.builder().setFile(file).get(); - ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(tempFile))) { - for (SevenZArchiveEntry e : sevenZ.getEntries()) { - if (e.isDirectory()) continue; - String entryName = e.getName(); - if (isComicInfoName(entryName)) continue; // skip old - if (!isSafeEntryName(entryName)) { - log.warn("Skipping unsafe 7z entry name: {}", entryName); - continue; - } - zos.putNextEntry(new ZipEntry(entryName)); - try (InputStream is = sevenZ.getInputStream(e)) { - if (is != null) is.transferTo(zos); - } - zos.closeEntry(); - } - zos.putNextEntry(new ZipEntry("ComicInfo.xml")); - zos.write(xmlBytes); - zos.closeEntry(); - } - Path target = file.toPath().resolveSibling(stripExtension(file.getName()) + ".cbz"); - atomicReplace(tempFile, target); - tempFile = null; // Successfully moved, don't delete in finally - try { - Files.deleteIfExists(file.toPath()); - } catch (Exception ignored) { - } - writeSucceeded = true; - return; - } - - // CBR path - String rarBin = System.getenv().getOrDefault("BOOKLORE_RAR_BIN", "rar"); - boolean rarAvailable = isRarAvailable(rarBin); - - if (rarAvailable) { - tempDir = Files.createTempDirectory("cbx_rar_"); - // Extract entire RAR into a temp directory - try (Archive archive = new Archive(file)) { - for (FileHeader fh : archive.getFileHeaders()) { - String name = fh.getFileName(); - if (name == null || name.isBlank()) continue; - if (!isSafeEntryName(name)) { - log.warn("Skipping unsafe RAR entry name: {}", name); - continue; - } - Path out = tempDir.resolve(name).normalize(); - if (!out.startsWith(tempDir)) { - log.warn("Skipping traversal entry outside tempDir: {}", name); - continue; - } - if (fh.isDirectory()) { - Files.createDirectories(out); - } else { - Files.createDirectories(out.getParent()); - try (OutputStream os = Files.newOutputStream(out, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)) { - archive.extractFile(fh, os); - } - } - } - } - - // Write/replace ComicInfo.xml in extracted tree root - Path comicInfo = tempDir.resolve("ComicInfo.xml"); - Files.write(comicInfo, xmlBytes); - - // Rebuild RAR in-place (replace original file) - Path targetRar = file.toPath().toAbsolutePath().normalize(); - String rarExec = isSafeExecutable(rarBin) ? rarBin : "rar"; // prefer validated path, then PATH lookup - ProcessBuilder pb = new ProcessBuilder(rarExec, "a", "-idq", "-ep1", "-ma5", targetRar.toString(), "."); - pb.directory(tempDir.toFile()); - Process p = pb.start(); - int code = p.waitFor(); - if (code == 0) { - writeSucceeded = true; - return; - } else { - log.warn("RAR creation failed with exit code {}. Falling back to CBZ conversion for {}", code, file.getName()); - } } else { - log.warn("`rar` binary not found. Falling back to CBZ conversion for {}", file.getName()); + tempArchive = updateRarArchive(file, xmlContent, extractDir); + writeSucceeded = true; } - - // Fallback: convert the CBR to CBZ containing updated ComicInfo.xml - tempFile = Files.createTempFile("cbx_edit", ".cbz"); - try (Archive archive = new Archive(file); - ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(tempFile))) { - for (FileHeader fh : archive.getFileHeaders()) { - if (fh.isDirectory()) continue; - String entryName = fh.getFileName(); - if (isComicInfoName(entryName)) continue; // skip old - if (!isSafeEntryName(entryName)) { - log.warn("Skipping unsafe RAR entry name: {}", entryName); - continue; - } - zos.putNextEntry(new ZipEntry(entryName)); - archive.extractFile(fh, zos); - zos.closeEntry(); - } - zos.putNextEntry(new ZipEntry("ComicInfo.xml")); - zos.write(xmlBytes); - zos.closeEntry(); - } - Path target = file.toPath().resolveSibling(stripExtension(file.getName()) + ".cbz"); - atomicReplace(tempFile, target); - tempFile = null; // Successfully moved, don't delete in finally - try { - Files.deleteIfExists(file.toPath()); - } catch (Exception ignored) { - } - writeSucceeded = true; } catch (Exception e) { - // Attempt to restore the original file from backup - try { - if (backup != null) { - Files.copy(backup, file.toPath(), StandardCopyOption.REPLACE_EXISTING); - log.info("Restored original file from backup after failure: {}", file.getAbsolutePath()); - } - } catch (Exception restoreEx) { - log.warn("Failed to restore original file from backup: {} -> {}", backup, file.getAbsolutePath(), restoreEx); - } + restoreOriginalFile(backupPath, file); log.warn("Failed to write metadata for {}: {}", file.getName(), e.getMessage(), e); } finally { - // Clean up temporary file if it wasn't successfully moved - if (tempFile != null) { - try { - Files.deleteIfExists(tempFile); - } catch (Exception e) { - log.warn("Failed to delete temp file: {}", tempFile, e); + cleanupTempFiles(tempArchive, extractDir, backupPath, writeSucceeded); + } + } + + public boolean shouldSaveMetadataToFile(File file) { + MetadataPersistenceSettings.SaveToOriginalFile settings = appSettingService.getAppSettings().getMetadataPersistenceSettings().getSaveToOriginalFile(); + + MetadataPersistenceSettings.FormatSettings cbxSettings = settings.getCbx(); + if (cbxSettings == null || !cbxSettings.isEnabled()) { + log.debug("CBX metadata writing is disabled. Skipping: {}", file.getName()); + return false; + } + + long fileSizeInMb = file.length() / (1024 * 1024); + if (fileSizeInMb > cbxSettings.getMaxFileSizeInMb()) { + log.info("CBX file {} ({} MB) exceeds max size limit ({} MB). Skipping metadata write.", file.getName(), fileSizeInMb, cbxSettings.getMaxFileSizeInMb()); + return false; + } + + return true; + } + + private Path createBackupFile(File file) { + try { + Path backupPath = Files.createTempFile(file.getParentFile().toPath(), "cbx_backup_", ".bak"); + Files.copy(file.toPath(), backupPath, StandardCopyOption.REPLACE_EXISTING); + return backupPath; + } catch (Exception ex) { + log.warn("Unable to create backup for {}: {}", file.getAbsolutePath(), ex.getMessage(), ex); + return null; + } + } + + private Document loadOrCreateComicInfoXml(File file, boolean isCbz, boolean isCb7, boolean isCbr) throws Exception { + if (isCbz) { + return loadXmlFromZip(file); + } else if (isCb7) { + return loadXmlFrom7z(file); + } else { + return loadXmlFromRar(file); + } + } + + private Document loadXmlFromZip(File file) throws Exception { + try (ZipFile zipFile = new ZipFile(file)) { + ZipEntry xmlEntry = findComicInfoEntry(zipFile); + if (xmlEntry != null) { + try (InputStream stream = zipFile.getInputStream(xmlEntry)) { + return parseXmlSecurely(stream); } } + return createEmptyComicInfoXml(); + } + } - // Clean up temporary directory if it was created - if (tempDir != null) { - deleteDirectoryRecursively(tempDir); + private Document loadXmlFrom7z(File file) throws Exception { + try (SevenZFile archive = SevenZFile.builder().setFile(file).get()) { + SevenZArchiveEntry xmlEntry = findComicInfoIn7z(archive); + if (xmlEntry != null) { + try (InputStream stream = archive.getInputStream(xmlEntry)) { + return parseXmlSecurely(stream); + } + } + return createEmptyComicInfoXml(); + } + } + + private SevenZArchiveEntry findComicInfoIn7z(SevenZFile archive) { + for (SevenZArchiveEntry entry : archive.getEntries()) { + if (entry != null && !entry.isDirectory() && isComicInfoXml(entry.getName())) { + return entry; + } + } + return null; + } + + private Document loadXmlFromRar(File file) throws Exception { + try (Archive archive = new Archive(file)) { + FileHeader xmlHeader = findComicInfoInRar(archive); + if (xmlHeader != null) { + try (ByteArrayOutputStream buffer = new ByteArrayOutputStream()) { + extractRarEntry(archive, xmlHeader, buffer); + try (InputStream stream = new ByteArrayInputStream(buffer.toByteArray())) { + return parseXmlSecurely(stream); + } + } + } + return createEmptyComicInfoXml(); + } + } + + private void applyMetadataChanges(Document xmlDoc, BookMetadataEntity metadata, MetadataClearFlags clearFlags) { + Element rootElement = xmlDoc.getDocumentElement(); + MetadataCopyHelper helper = new MetadataCopyHelper(metadata); + + helper.copyTitle(clearFlags != null && clearFlags.isTitle(), val -> updateXmlElement(xmlDoc, rootElement, "Title", val)); + helper.copyDescription(clearFlags != null && clearFlags.isDescription(), val -> { + updateXmlElement(xmlDoc, rootElement, "Summary", val); + removeXmlElement(rootElement, "Description"); + }); + helper.copyPublisher(clearFlags != null && clearFlags.isPublisher(), val -> updateXmlElement(xmlDoc, rootElement, "Publisher", val)); + helper.copySeriesName(clearFlags != null && clearFlags.isSeriesName(), val -> updateXmlElement(xmlDoc, rootElement, "Series", val)); + helper.copySeriesNumber(clearFlags != null && clearFlags.isSeriesNumber(), val -> updateXmlElement(xmlDoc, rootElement, "Number", formatFloatValue(val))); + helper.copySeriesTotal(clearFlags != null && clearFlags.isSeriesTotal(), val -> updateXmlElement(xmlDoc, rootElement, "Count", val != null ? val.toString() : null)); + helper.copyPublishedDate(clearFlags != null && clearFlags.isPublishedDate(), date -> updateDateElements(xmlDoc, rootElement, date)); + helper.copyPageCount(clearFlags != null && clearFlags.isPageCount(), val -> updateXmlElement(xmlDoc, rootElement, "PageCount", val != null ? val.toString() : null)); + helper.copyLanguage(clearFlags != null && clearFlags.isLanguage(), val -> updateXmlElement(xmlDoc, rootElement, "LanguageISO", val)); + helper.copyAuthors(clearFlags != null && clearFlags.isAuthors(), set -> { + updateXmlElement(xmlDoc, rootElement, "Writer", joinStrings(set)); + removeXmlElement(rootElement, "Penciller"); + removeXmlElement(rootElement, "Inker"); + removeXmlElement(rootElement, "Colorist"); + removeXmlElement(rootElement, "Letterer"); + removeXmlElement(rootElement, "CoverArtist"); + }); + helper.copyCategories(clearFlags != null && clearFlags.isCategories(), set -> { + updateXmlElement(xmlDoc, rootElement, "Genre", joinStrings(set)); + removeXmlElement(rootElement, "Tags"); + }); + } + + private byte[] convertDocumentToBytes(Document xmlDoc) throws Exception { + Transformer transformer = TransformerFactory.newInstance().newTransformer(); + transformer.setOutputProperty(OutputKeys.INDENT, "yes"); + transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + transformer.transform(new DOMSource(xmlDoc), new StreamResult(outputStream)); + return outputStream.toByteArray(); + } + + private Path updateZipArchive(File originalFile, byte[] xmlContent) throws Exception { + Path tempArchive = Files.createTempFile("cbx_edit", ".cbz"); + rebuildZipWithNewXml(originalFile.toPath(), tempArchive, xmlContent); + replaceFileAtomic(tempArchive, originalFile.toPath()); + return null; // temp file already moved + } + + private Path convert7zToZip(File original7z, byte[] xmlContent) throws Exception { + Path tempZip = Files.createTempFile("cbx_edit", ".cbz"); + repack7zToZipWithXml(original7z, tempZip, xmlContent); + + Path targetPath = original7z.toPath().resolveSibling(removeFileExtension(original7z.getName()) + ".cbz"); + replaceFileAtomic(tempZip, targetPath); + + try { + Files.deleteIfExists(original7z.toPath()); + } catch (Exception ignored) { + } + return null; + } + + private void repack7zToZipWithXml(File source7z, Path targetZip, byte[] xmlContent) throws Exception { + try (SevenZFile archive = SevenZFile.builder().setFile(source7z).get(); + ZipOutputStream zipOutput = new ZipOutputStream(Files.newOutputStream(targetZip))) { + + for (SevenZArchiveEntry entry : archive.getEntries()) { + if (entry.isDirectory()) continue; + String entryName = entry.getName(); + if (isComicInfoXml(entryName)) continue; + if (!isPathSafe(entryName)) { + log.warn("Skipping unsafe 7z entry name: {}", entryName); + continue; + } + + zipOutput.putNextEntry(new ZipEntry(entryName)); + try (InputStream entryStream = archive.getInputStream(entry)) { + if (entryStream != null) copyStream(entryStream, zipOutput); + } + zipOutput.closeEntry(); } - // Clean up backup file if write succeeded - if (writeSucceeded && backup != null) { - try { - Files.deleteIfExists(backup); - } catch (Exception e) { - log.warn("Failed to delete backup file: {}", backup, e); + zipOutput.putNextEntry(new ZipEntry("ComicInfo.xml")); + zipOutput.write(xmlContent); + zipOutput.closeEntry(); + } + } + + private Path updateRarArchive(File originalRar, byte[] xmlContent, Path extractDir) throws Exception { + String rarCommand = System.getenv().getOrDefault("BOOKLORE_RAR_BIN", "rar"); + boolean rarAvailable = checkRarAvailability(rarCommand); + + if (rarAvailable) { + return updateRarWithCommand(originalRar, xmlContent, rarCommand, extractDir); + } else { + log.warn("`rar` binary not found. Falling back to CBZ conversion for {}", originalRar.getName()); + return convertRarToZipArchive(originalRar, xmlContent); + } + } + + private Path updateRarWithCommand(File originalRar, byte[] xmlContent, String rarCommand, Path extractDir) throws Exception { + extractDir = Files.createTempDirectory("cbx_rar_"); + extractRarContents(originalRar, extractDir); + + Path xmlPath = extractDir.resolve("ComicInfo.xml"); + Files.write(xmlPath, xmlContent); + + Path targetRar = originalRar.toPath().toAbsolutePath().normalize(); + String safeCommand = isExecutableSafe(rarCommand) ? rarCommand : "rar"; + ProcessBuilder processBuilder = new ProcessBuilder(safeCommand, "a", "-idq", "-ep1", "-ma5", targetRar.toString(), "."); + processBuilder.directory(extractDir.toFile()); + Process process = processBuilder.start(); + int exitCode = process.waitFor(); + + if (exitCode == 0) { + return null; + } else { + log.warn("RAR creation failed with exit code {}. Falling back to CBZ conversion for {}", exitCode, originalRar.getName()); + return convertRarToZipArchive(originalRar, xmlContent); + } + } + + private void extractRarContents(File rarFile, Path targetDir) throws Exception { + try (Archive archive = new Archive(rarFile)) { + for (FileHeader header : archive.getFileHeaders()) { + String entryName = header.getFileName(); + if (entryName == null || entryName.isBlank()) continue; + if (!isPathSafe(entryName)) { + log.warn("Skipping unsafe RAR entry name: {}", entryName); + continue; + } + + Path outputPath = targetDir.resolve(entryName).normalize(); + if (!outputPath.startsWith(targetDir)) { + log.warn("Skipping traversal entry outside tempDir: {}", entryName); + continue; + } + + if (header.isDirectory()) { + Files.createDirectories(outputPath); + } else { + Files.createDirectories(outputPath.getParent()); + try (OutputStream fileOutput = Files.newOutputStream(outputPath, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)) { + extractRarEntry(archive, header, fileOutput); + } } } } } - // ----------------------- helpers ----------------------- + private Path convertRarToZipArchive(File rarFile, byte[] xmlContent) throws Exception { + Path tempZip = Files.createTempFile("cbx_edit", ".cbz"); + + try (Archive rarArchive = new Archive(rarFile); + ZipOutputStream zipOutput = new ZipOutputStream(Files.newOutputStream(tempZip))) { + + for (FileHeader header : rarArchive.getFileHeaders()) { + if (header.isDirectory()) continue; + String entryName = header.getFileName(); + if (isComicInfoXml(entryName)) continue; + if (!isPathSafe(entryName)) { + log.warn("Skipping unsafe RAR entry name: {}", entryName); + continue; + } + + zipOutput.putNextEntry(new ZipEntry(entryName)); + extractRarEntry(rarArchive, header, zipOutput); + zipOutput.closeEntry(); + } + + zipOutput.putNextEntry(new ZipEntry("ComicInfo.xml")); + zipOutput.write(xmlContent); + zipOutput.closeEntry(); + } + + Path targetPath = rarFile.toPath().resolveSibling(removeFileExtension(rarFile.getName()) + ".cbz"); + replaceFileAtomic(tempZip, targetPath); + + try { + Files.deleteIfExists(rarFile.toPath()); + } catch (Exception ignored) { + } + + return null; + } + + private void restoreOriginalFile(Path backupPath, File targetFile) { + try { + if (backupPath != null) { + Files.copy(backupPath, targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING); + log.info("Restored original file from backup after failure: {}", targetFile.getAbsolutePath()); + } + } catch (Exception restoreException) { + log.warn("Failed to restore original file from backup: {} -> {}", backupPath, targetFile.getAbsolutePath(), restoreException); + } + } + + private void cleanupTempFiles(Path tempArchive, Path extractDir, Path backupPath, boolean writeSucceeded) { + if (tempArchive != null) { + try { + Files.deleteIfExists(tempArchive); + } catch (Exception e) { + log.warn("Failed to delete temp file: {}", tempArchive, e); + } + } + + if (extractDir != null) { + deleteDirectoryRecursively(extractDir); + } + + if (writeSucceeded && backupPath != null) { + try { + Files.deleteIfExists(backupPath); + } catch (Exception e) { + log.warn("Failed to delete backup file: {}", backupPath, e); + } + } + } private ZipEntry findComicInfoEntry(ZipFile zipFile) { Enumeration entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); - String n = entry.getName(); - if (isComicInfoName(n)) return entry; + String entryName = entry.getName(); + if (isComicInfoXml(entryName)) return entry; } return null; } - private FileHeader findComicInfoHeader(Archive archive) { - for (FileHeader fh : archive.getFileHeaders()) { - String name = fh.getFileName(); - if (name != null && isComicInfoName(name)) return fh; + private FileHeader findComicInfoInRar(Archive archive) { + for (FileHeader header : archive.getFileHeaders()) { + String entryName = header.getFileName(); + if (entryName != null && isComicInfoXml(entryName)) return header; } return null; } - private Document buildSecureDocument(InputStream is) throws Exception { + private Document parseXmlSecurely(InputStream xmlStream) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); factory.setExpandEntityReferences(false); DocumentBuilder builder = factory.newDocumentBuilder(); - return builder.parse(is); + return builder.parse(xmlStream); } - private Document newEmptyComicInfo() throws Exception { + private Document createEmptyComicInfoXml() throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); DocumentBuilder builder = factory.newDocumentBuilder(); - Document doc = builder.newDocument(); - doc.appendChild(doc.createElement("ComicInfo")); - return doc; + Document xmlDoc = builder.newDocument(); + xmlDoc.appendChild(xmlDoc.createElement("ComicInfo")); + return xmlDoc; } - private void setElement(Document doc, Element root, String tag, String value) { - removeElement(root, tag); + private void updateXmlElement(Document xmlDoc, Element rootElement, String tagName, String value) { + removeXmlElement(rootElement, tagName); if (value != null && !value.isBlank()) { - Element el = doc.createElement(tag); - el.setTextContent(value); - root.appendChild(el); + Element element = xmlDoc.createElement(tagName); + element.setTextContent(value); + rootElement.appendChild(element); } } - private void removeElement(Element root, String tag) { - NodeList nodes = root.getElementsByTagName(tag); + private void removeXmlElement(Element rootElement, String tagName) { + NodeList nodes = rootElement.getElementsByTagName(tagName); for (int i = nodes.getLength() - 1; i >= 0; i--) { - root.removeChild(nodes.item(i)); + rootElement.removeChild(nodes.item(i)); } } - private void setDateElements(Document doc, Element root, LocalDate date) { + private void updateDateElements(Document xmlDoc, Element rootElement, LocalDate date) { if (date == null) { - removeElement(root, "Year"); - removeElement(root, "Month"); - removeElement(root, "Day"); + removeXmlElement(rootElement, "Year"); + removeXmlElement(rootElement, "Month"); + removeXmlElement(rootElement, "Day"); return; } - setElement(doc, root, "Year", Integer.toString(date.getYear())); - setElement(doc, root, "Month", Integer.toString(date.getMonthValue())); - setElement(doc, root, "Day", Integer.toString(date.getDayOfMonth())); + updateXmlElement(xmlDoc, rootElement, "Year", Integer.toString(date.getYear())); + updateXmlElement(xmlDoc, rootElement, "Month", Integer.toString(date.getMonthValue())); + updateXmlElement(xmlDoc, rootElement, "Day", Integer.toString(date.getDayOfMonth())); } - private String join(Set set) { - return (set == null || set.isEmpty()) ? null : String.join(", ", set); + private String joinStrings(Set values) { + return (values == null || values.isEmpty()) ? null : String.join(", ", values); } - private String formatFloat(Float val) { - if (val == null) return null; - if (val % 1 == 0) return Integer.toString(val.intValue()); - return val.toString(); + private String formatFloatValue(Float value) { + if (value == null) return null; + if (value % 1 == 0) return Integer.toString(value.intValue()); + return value.toString(); } - private static boolean isComicInfoName(String name) { - if (name == null) return false; - String n = name.replace('\\', '/'); - if (n.endsWith("/")) return false; - String lower = n.toLowerCase(Locale.ROOT); - return "comicinfo.xml".equals(lower) || lower.endsWith("/comicinfo.xml"); + private static boolean isComicInfoXml(String entryName) { + if (entryName == null) return false; + String normalized = entryName.replace('\\', '/'); + if (normalized.endsWith("/")) return false; + String lowerCase = normalized.toLowerCase(Locale.ROOT); + return "comicinfo.xml".equals(lowerCase) || lowerCase.endsWith("/comicinfo.xml"); } - private static boolean isSafeEntryName(String name) { - if (name == null || name.isBlank()) return false; - String n = name.replace('\\', '/'); - if (n.startsWith("/")) return false; // absolute - if (n.contains("../")) return false; // traversal - if (n.contains("\0")) return false; // NUL + private static boolean isPathSafe(String entryName) { + if (entryName == null || entryName.isBlank()) return false; + String normalized = entryName.replace('\\', '/'); + if (normalized.startsWith("/")) return false; + if (normalized.contains("../")) return false; + if (normalized.contains("\0")) return false; return true; } - private void repackZipReplacingComicInfo(Path sourceZip, Path targetZip, byte[] xmlBytes) throws Exception { + private void rebuildZipWithNewXml(Path sourceZip, Path targetZip, byte[] xmlContent) throws Exception { try (ZipFile zipFile = new ZipFile(sourceZip.toFile()); - ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(targetZip))) { - ZipEntry existing = findComicInfoEntry(zipFile); + ZipOutputStream zipOutput = new ZipOutputStream(Files.newOutputStream(targetZip))) { + ZipEntry existingXml = findComicInfoEntry(zipFile); Enumeration entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); String entryName = entry.getName(); - if (existing != null && entryName.equals(existing.getName())) { - continue; // skip old ComicInfo.xml + if (existingXml != null && entryName.equals(existingXml.getName())) { + continue; } - if (!isSafeEntryName(entryName)) { + if (!isPathSafe(entryName)) { log.warn("Skipping unsafe ZIP entry name: {}", entryName); continue; } - zos.putNextEntry(new ZipEntry(entryName)); - try (InputStream is = zipFile.getInputStream(entry)) { - is.transferTo(zos); + zipOutput.putNextEntry(new ZipEntry(entryName)); + try (InputStream entryStream = zipFile.getInputStream(entry)) { + copyStream(entryStream, zipOutput); } - zos.closeEntry(); + zipOutput.closeEntry(); } - String entryName = (existing != null ? existing.getName() : "ComicInfo.xml"); - zos.putNextEntry(new ZipEntry(entryName)); - zos.write(xmlBytes); - zos.closeEntry(); + String xmlEntryName = (existingXml != null ? existingXml.getName() : "ComicInfo.xml"); + zipOutput.putNextEntry(new ZipEntry(xmlEntryName)); + zipOutput.write(xmlContent); + zipOutput.closeEntry(); } } - private static void atomicReplace(Path temp, Path target) throws Exception { + private void copyStream(InputStream input, OutputStream output) throws IOException { + byte[] buffer = new byte[BUFFER_SIZE]; + int bytesRead; + while ((bytesRead = input.read(buffer)) != -1) { + output.write(buffer, 0, bytesRead); + } + } + + private void extractRarEntry(Archive archive, FileHeader fileHeader, OutputStream output) throws Exception { + try (InputStream entryStream = archive.getInputStream(fileHeader)) { + copyStream(entryStream, output); + } + } + + private static void replaceFileAtomic(Path source, Path target) throws Exception { try { - Files.move(temp, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); + Files.move(source, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); } catch (Exception e) { - // Fallback if filesystem doesn't support ATOMIC_MOVE - Files.move(temp, target, StandardCopyOption.REPLACE_EXISTING); + Files.move(source, target, StandardCopyOption.REPLACE_EXISTING); } } - private boolean isRarAvailable(String rarBin) { + private boolean checkRarAvailability(String rarCommand) { try { - String exec = isSafeExecutable(rarBin) ? rarBin : "rar"; - Process check = new ProcessBuilder(exec, "--help").redirectErrorStream(true).start(); + String safeCommand = isExecutableSafe(rarCommand) ? rarCommand : "rar"; + Process check = new ProcessBuilder(safeCommand, "--help").redirectErrorStream(true).start(); int exitCode = check.waitFor(); return (exitCode == 0); } catch (Exception ex) { @@ -454,19 +552,14 @@ public class CbxMetadataWriter implements MetadataWriter { } } - /** - * Returns true if the provided executable reference is a simple name or sanitized absolute/relative path. - * No spaces or shell meta chars; passed as argv to ProcessBuilder (no shell). - */ - private boolean isSafeExecutable(String exec) { - if (exec == null || exec.isBlank()) return false; - // allow word chars, dot, slash, backslash, dash and underscore (no spaces or shell metas) - return VALID_FILENAME_PATTERN.matcher(exec).matches(); + private boolean isExecutableSafe(String command) { + if (command == null || command.isBlank()) return false; + return VALID_FILENAME_PATTERN.matcher(command).matches(); } - private static String stripExtension(String filename) { - int i = filename.lastIndexOf('.'); - if (i > 0) return filename.substring(0, i); + private static String removeFileExtension(String filename) { + int lastDot = filename.lastIndexOf('.'); + if (lastDot > 0) return filename.substring(0, lastDot); return filename; } @@ -475,8 +568,8 @@ public class CbxMetadataWriter implements MetadataWriter { return BookFileType.CBX; } - private void deleteDirectoryRecursively(Path dir) { - try (var pathStream = Files.walk(dir)) { + private void deleteDirectoryRecursively(Path directory) { + try (var pathStream = Files.walk(directory)) { pathStream .sorted(Comparator.reverseOrder()) .forEach(path -> { @@ -487,7 +580,7 @@ public class CbxMetadataWriter implements MetadataWriter { } }); } catch (IOException e) { - log.warn("Failed to clean up temporary directory: {}", dir, e); + log.warn("Failed to clean up temporary directory: {}", directory, e); } } -} \ No newline at end of file +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/writer/EpubMetadataWriter.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/writer/EpubMetadataWriter.java index 68b6feb2e..396f017f0 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/writer/EpubMetadataWriter.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/writer/EpubMetadataWriter.java @@ -1,9 +1,12 @@ package com.adityachandel.booklore.service.metadata.writer; import com.adityachandel.booklore.model.MetadataClearFlags; +import com.adityachandel.booklore.model.dto.settings.MetadataPersistenceSettings; import com.adityachandel.booklore.model.entity.BookEntity; import com.adityachandel.booklore.model.entity.BookMetadataEntity; import com.adityachandel.booklore.model.enums.BookFileType; +import com.adityachandel.booklore.service.appsettings.AppSettingService; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import net.lingala.zip4j.ZipFile; import net.lingala.zip4j.model.ZipParameters; @@ -41,12 +44,18 @@ import java.util.UUID; @Slf4j @Component +@RequiredArgsConstructor public class EpubMetadataWriter implements MetadataWriter { private static final String OPF_NS = "http://www.idpf.org/2007/opf"; + private final AppSettingService appSettingService; @Override - public void writeMetadataToFile(File epubFile, BookMetadataEntity metadata, String thumbnailUrl, MetadataClearFlags clear) { + public void saveMetadataToFile(File epubFile, BookMetadataEntity metadata, String thumbnailUrl, MetadataClearFlags clear) { + if (!shouldSaveMetadataToFile(epubFile)) { + return; + } + File backupFile = new File(epubFile.getParentFile(), epubFile.getName() + ".bak"); try { Files.copy(epubFile.toPath(), backupFile.toPath(), StandardCopyOption.REPLACE_EXISTING); @@ -237,68 +246,61 @@ public class EpubMetadataWriter implements MetadataWriter { return changed; } + + public void replaceCoverImageFromBytes(BookEntity bookEntity, byte[] file) { + if (!shouldSaveMetadataToFile(bookEntity.getFullFilePath().toFile())) { + return; + } + if (file == null || file.length == 0) { + log.warn("Cover update failed: empty or null byte array."); + return; + } + + replaceCoverImageInternal(bookEntity, file, "byte array"); + } + public void replaceCoverImageFromUpload(BookEntity bookEntity, MultipartFile multipartFile) { + if (!shouldSaveMetadataToFile(bookEntity.getFullFilePath().toFile())) { + return; + } if (multipartFile == null || multipartFile.isEmpty()) { log.warn("Cover upload failed: empty or null file."); return; } - Path tempDir = null; try { - File epubFile = new File(bookEntity.getFullFilePath().toUri()); - tempDir = Files.createTempDirectory("epub_cover_" + UUID.randomUUID()); - try (ZipFile zipFile = new ZipFile(epubFile)) { - zipFile.extractAll(tempDir.toString()); - } - - File opfFile = findOpfFile(tempDir.toFile()); - if (opfFile == null) { - log.warn("OPF file not found in EPUB: {}", epubFile.getName()); - return; - } - - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - DocumentBuilder builder = dbf.newDocumentBuilder(); - Document opfDoc = builder.parse(opfFile); - byte[] coverData = multipartFile.getBytes(); - applyCoverImageToEpub(tempDir, opfDoc, coverData); - - Transformer transformer = TransformerFactory.newInstance().newTransformer(); - transformer.setOutputProperty(OutputKeys.INDENT, "yes"); - transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); - transformer.transform(new DOMSource(opfDoc), new StreamResult(opfFile)); - - File tempEpub = new File(epubFile.getParentFile(), epubFile.getName() + ".tmp"); - try (ZipFile tempZipFile = new ZipFile(tempEpub)) { - addFolderContentsToZip(tempZipFile, tempDir.toFile(), tempDir.toFile()); - } - - if (!epubFile.delete()) throw new IOException("Could not delete original EPUB"); - if (!tempEpub.renameTo(epubFile)) throw new IOException("Could not rename temp EPUB"); - - log.info("Cover image updated in EPUB: {}", epubFile.getName()); - - } catch (Exception e) { - log.warn("Failed to update EPUB with uploaded cover image: {}", e.getMessage(), e); - } finally { - if (tempDir != null) { - deleteDirectoryRecursively(tempDir); - } + replaceCoverImageInternal(bookEntity, coverData, "upload"); + } catch (IOException e) { + log.warn("Failed to read uploaded cover image: {}", e.getMessage(), e); } } @Override public void replaceCoverImageFromUrl(BookEntity bookEntity, String url) { + if (!shouldSaveMetadataToFile(bookEntity.getFullFilePath().toFile())) { + return; + } if (url == null || url.isBlank()) { log.warn("Cover update via URL failed: empty or null URL."); return; } + + byte[] coverData = loadImage(url); + if (coverData == null) { + log.warn("Failed to load image from URL: {}", url); + return; + } + + replaceCoverImageInternal(bookEntity, coverData, "URL"); + } + + private void replaceCoverImageInternal(BookEntity bookEntity, byte[] coverData, String source) { Path tempDir = null; try { File epubFile = new File(bookEntity.getFullFilePath().toUri()); - tempDir = Files.createTempDirectory("epub_cover_url_" + UUID.randomUUID()); + tempDir = Files.createTempDirectory("epub_cover_" + UUID.randomUUID()); + try (ZipFile zipFile = new ZipFile(epubFile)) { zipFile.extractAll(tempDir.toString()); } @@ -314,12 +316,6 @@ public class EpubMetadataWriter implements MetadataWriter { DocumentBuilder builder = dbf.newDocumentBuilder(); Document opfDoc = builder.parse(opfFile); - byte[] coverData = loadImage(url); - if (coverData == null) { - log.warn("Failed to load image from URL: {}", url); - return; - } - applyCoverImageToEpub(tempDir, opfDoc, coverData); Transformer transformer = TransformerFactory.newInstance().newTransformer(); @@ -335,9 +331,10 @@ public class EpubMetadataWriter implements MetadataWriter { if (!epubFile.delete()) throw new IOException("Could not delete original EPUB"); if (!tempEpub.renameTo(epubFile)) throw new IOException("Could not rename temp EPUB"); - log.info("Cover image updated in EPUB via URL: {}", epubFile.getName()); + log.info("Cover image updated in EPUB from {}: {}", source, epubFile.getName()); + } catch (Exception e) { - log.warn("Failed to update EPUB with cover from URL: {}", e.getMessage(), e); + log.warn("Failed to update EPUB cover image from {}: {}", source, e.getMessage(), e); } finally { if (tempDir != null) { deleteDirectoryRecursively(tempDir); @@ -543,13 +540,13 @@ public class EpubMetadataWriter implements MetadataWriter { if (StringUtils.isNotBlank(id) && StringUtils.isBlank(creatorRole)) { // Finds any matching role meta tags for this creator ID Element meta = getMetaElementByFilter(metadataElement, el -> ("role".equals(el.getAttribute("property")) && "#".concat(id).equals(el.getAttribute("refines")))); - if ( meta != null ) { - creatorRole = meta.hasAttribute("content") ? meta.getAttribute("content").trim() : meta.getTextContent().trim(); + if (meta != null) { + creatorRole = meta.hasAttribute("content") ? meta.getAttribute("content").trim() : meta.getTextContent().trim(); } } if (role.equalsIgnoreCase(creatorRole)) { metadataElement.removeChild(creatorElement); - if (StringUtils.isNotBlank(id)){ + if (StringUtils.isNotBlank(id)) { removeMetaByRefines(metadataElement, "#".concat(id)); } } @@ -588,9 +585,9 @@ public class EpubMetadataWriter implements MetadataWriter { } private String getMetaContentByName(Element metadataElement, String name) { - Element meta = getMetaElementByFilter( metadataElement, el -> name.equals(el.getAttribute("name")) ); + Element meta = getMetaElementByFilter(metadataElement, el -> name.equals(el.getAttribute("name"))); if (meta != null) { - return meta.getAttribute("content"); + return meta.getAttribute("content"); } return null; } @@ -610,4 +607,22 @@ public class EpubMetadataWriter implements MetadataWriter { log.warn("Failed to clean up temporary directory: {}", dir, e); } } + + public boolean shouldSaveMetadataToFile(File epubFile) { + MetadataPersistenceSettings.SaveToOriginalFile settings = appSettingService.getAppSettings().getMetadataPersistenceSettings().getSaveToOriginalFile(); + + MetadataPersistenceSettings.FormatSettings epubSettings = settings.getEpub(); + if (epubSettings == null || !epubSettings.isEnabled()) { + log.debug("EPUB metadata writing is disabled. Skipping: {}", epubFile.getName()); + return false; + } + + long fileSizeInMb = epubFile.length() / (1024 * 1024); + if (fileSizeInMb > epubSettings.getMaxFileSizeInMb()) { + log.info("EPUB file {} ({} MB) exceeds max size limit ({} MB). Skipping metadata write.", epubFile.getName(), fileSizeInMb, epubSettings.getMaxFileSizeInMb()); + return false; + } + + return true; + } } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/writer/MetadataWriter.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/writer/MetadataWriter.java index f7f342794..73c939f6b 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/writer/MetadataWriter.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/writer/MetadataWriter.java @@ -10,11 +10,16 @@ import java.io.File; public interface MetadataWriter { - void writeMetadataToFile(File file, BookMetadataEntity metadata, String thumbnailUrl, MetadataClearFlags clearFlags); + void saveMetadataToFile(File file, BookMetadataEntity metadata, String thumbnailUrl, MetadataClearFlags clearFlags); + + boolean shouldSaveMetadataToFile(File file); default void replaceCoverImageFromUpload(BookEntity bookEntity, MultipartFile file) { } + default void replaceCoverImageFromBytes(BookEntity bookEntity, byte[] file) { + } + default void replaceCoverImageFromUrl(BookEntity bookEntity, String url) { } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/writer/PdfMetadataWriter.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/writer/PdfMetadataWriter.java index 63e50f546..64311948a 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/writer/PdfMetadataWriter.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/writer/PdfMetadataWriter.java @@ -3,6 +3,9 @@ package com.adityachandel.booklore.service.metadata.writer; import com.adityachandel.booklore.model.MetadataClearFlags; import com.adityachandel.booklore.model.entity.BookMetadataEntity; import com.adityachandel.booklore.model.enums.BookFileType; +import com.adityachandel.booklore.service.appsettings.AppSettingService; +import com.adityachandel.booklore.model.dto.settings.MetadataPersistenceSettings; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.apache.pdfbox.Loader; @@ -41,10 +44,17 @@ import java.util.UUID; @Slf4j @Component +@RequiredArgsConstructor public class PdfMetadataWriter implements MetadataWriter { + private final AppSettingService appSettingService; + @Override - public void writeMetadataToFile(File file, BookMetadataEntity metadataEntity, String thumbnailUrl, MetadataClearFlags clear) { + public void saveMetadataToFile(File file, BookMetadataEntity metadataEntity, String thumbnailUrl, MetadataClearFlags clear) { + if (!shouldSaveMetadataToFile(file)) { + return; + } + if (!file.exists() || !file.getName().toLowerCase().endsWith(".pdf")) { log.warn("Invalid PDF file: {}", file.getAbsolutePath()); return; @@ -102,6 +112,24 @@ public class PdfMetadataWriter implements MetadataWriter { return BookFileType.PDF; } + public boolean shouldSaveMetadataToFile(File pdfFile) { + MetadataPersistenceSettings.SaveToOriginalFile settings = appSettingService.getAppSettings().getMetadataPersistenceSettings().getSaveToOriginalFile(); + + MetadataPersistenceSettings.FormatSettings pdfSettings = settings.getPdf(); + if (pdfSettings == null || !pdfSettings.isEnabled()) { + log.debug("PDF metadata writing is disabled. Skipping: {}", pdfFile.getName()); + return false; + } + + long fileSizeInMb = pdfFile.length() / (1024 * 1024); + if (fileSizeInMb > pdfSettings.getMaxFileSizeInMb()) { + log.info("PDF file {} ({} MB) exceeds max size limit ({} MB). Skipping metadata write.", pdfFile.getName(), fileSizeInMb, pdfSettings.getMaxFileSizeInMb()); + return false; + } + + return true; + } + private void applyMetadataToDocument(PDDocument pdf, BookMetadataEntity entity, MetadataClearFlags clear) { PDDocumentInformation info = pdf.getDocumentInformation(); MetadataCopyHelper helper = new MetadataCopyHelper(entity); @@ -122,7 +150,7 @@ public class PdfMetadataWriter implements MetadataWriter { helper.copyPublishedDate(clear != null && clear.isPublishedDate(), date -> { Calendar cal = Calendar.getInstance(); cal.setTimeInMillis((date != null ? date : ZonedDateTime.now().toLocalDate()) - .atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli()); + .atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli()); dc.addDate(cal); }); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/reader/CbxReaderService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/reader/CbxReaderService.java index 495f1115e..98ece43af 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/reader/CbxReaderService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/reader/CbxReaderService.java @@ -40,7 +40,7 @@ public class CbxReaderService { private static final String CBZ_EXTENSION = ".cbz"; private static final String CBR_EXTENSION = ".cbr"; private static final String CB7_EXTENSION = ".cb7"; - private static final String[] SUPPORTED_IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp"}; + private static final String[] SUPPORTED_IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp", ".avif", ".heic"}; private final BookRepository bookRepository; private final AppSettingService appSettingService; @@ -57,7 +57,14 @@ public class CbxReaderService { try { long maxCacheSizeBytes = mbToBytes(appSettingService.getAppSettings().getCbxCacheSizeInMb()); long estimatedSize = estimateArchiveSize(cbzPath); - if (estimatedSize > maxCacheSizeBytes) { + + if (estimatedSize == -1) { + long fileSize = Files.size(cbzPath); + if (fileSize > maxCacheSizeBytes) { + log.warn("Cache skipped: Physical file size {} exceeds max cache size {} (Estimation failed)", fileSize, maxCacheSizeBytes); + throw ApiError.CACHE_TOO_LARGE.createException(); + } + } else if (estimatedSize > maxCacheSizeBytes) { log.warn("Cache skipped: Estimated archive size {} exceeds max cache size {}", estimatedSize, maxCacheSizeBytes); throw ApiError.CACHE_TOO_LARGE.createException(); } @@ -78,7 +85,7 @@ public class CbxReaderService { } } catch (IOException e) { log.error("Failed to cache CBZ for book {}", bookId, e); - return List.of(); + throw ApiError.FILE_READ_ERROR.createException("Failed to read archive: " + e.getMessage()); } try (var stream = Files.list(cacheDir)) { @@ -360,7 +367,7 @@ public class CbxReaderService { } catch (Exception e) { log.warn("Failed to estimate archive size for {}", cbxPath, e); } - return Long.MAX_VALUE; + return -1; } private long estimateCbzArchiveSize(Path cbxPath) throws IOException { @@ -384,7 +391,7 @@ public class CbxReaderService { } log.warn("Unable to estimate archive size for {} with any supported encoding", cbxPath); - return Long.MAX_VALUE; + return -1; } private long estimateCbzWithEncoding(Path cbxPath, Charset charset, boolean useFastPath) throws IOException { @@ -405,7 +412,7 @@ public class CbxReaderService { total += (size >= 0) ? size : entry.getCompressedSize(); } } - return total > 0 ? total : Long.MAX_VALUE; + return total > 0 ? total : -1; } } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/user/UserProvisioningService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/user/UserProvisioningService.java index fa4796348..91dcdb3d7 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/user/UserProvisioningService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/user/UserProvisioningService.java @@ -64,6 +64,7 @@ public class UserProvisioningService { perms.setPermissionAccessTaskManager(true); perms.setPermissionManageGlobalPreferences(true); perms.setPermissionManageIcons(true); + perms.setPermissionManageFonts(true); perms.setPermissionBulkAutoFetchMetadata(true); perms.setPermissionBulkCustomFetchMetadata(true); perms.setPermissionBulkEditMetadata(true); @@ -112,6 +113,7 @@ public class UserProvisioningService { permissions.setPermissionAccessTaskManager(request.isPermissionAccessTaskManager()); permissions.setPermissionManageGlobalPreferences(request.isPermissionManageGlobalPreferences()); permissions.setPermissionManageIcons(request.isPermissionManageIcons()); + permissions.setPermissionManageFonts(request.isPermissionManageFonts()); permissions.setPermissionBulkAutoFetchMetadata(request.isPermissionBulkAutoFetchMetadata()); permissions.setPermissionBulkCustomFetchMetadata(request.isPermissionBulkCustomFetchMetadata()); permissions.setPermissionBulkEditMetadata(request.isPermissionBulkEditMetadata()); @@ -160,6 +162,7 @@ public class UserProvisioningService { perms.setPermissionAccessTaskManager(defaultPermissions.contains("permissionAccessTaskManager")); perms.setPermissionManageGlobalPreferences(defaultPermissions.contains("permissionManageGlobalPreferences")); perms.setPermissionManageIcons(defaultPermissions.contains("permissionManageIcons")); + perms.setPermissionManageFonts(defaultPermissions.contains("permissionManageFonts")); } user.setPermissions(perms); @@ -222,6 +225,7 @@ public class UserProvisioningService { permissions.setPermissionAccessTaskManager(defaultPermissions.contains("permissionAccessTaskManager")); permissions.setPermissionManageGlobalPreferences(defaultPermissions.contains("permissionManageGlobalPreferences")); permissions.setPermissionManageIcons(defaultPermissions.contains("permissionManageIcons")); + permissions.setPermissionManageFonts(defaultPermissions.contains("permissionManageFonts")); } else { permissions.setPermissionUpload(false); permissions.setPermissionDownload(false); @@ -239,6 +243,7 @@ public class UserProvisioningService { permissions.setPermissionAccessTaskManager(false); permissions.setPermissionManageGlobalPreferences(false); permissions.setPermissionManageIcons(false); + permissions.setPermissionManageFonts(false); } permissions.setPermissionAdmin(isAdmin); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/util/FileService.java b/booklore-api/src/main/java/com/adityachandel/booklore/util/FileService.java index 4d479c01e..3baa82aa8 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/util/FileService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/util/FileService.java @@ -144,6 +144,28 @@ public class FileService { // IMAGE OPERATIONS // ======================================== + public static BufferedImage readImage(InputStream inputStream) throws IOException { + return readImage(inputStream.readAllBytes()); + } + + public static BufferedImage readImage(byte[] imageData) throws IOException { + if (imageData == null || imageData.length == 0) { + throw new IOException("Image data is null or empty"); + } + try (InputStream is = new ByteArrayInputStream(imageData)) { + BufferedImage image = ImageIO.read(is); + if (image != null) { + return image; + } + } catch (Exception e) { + log.warn("ImageIO/TwelveMonkeys decode failed (possibly unsupported format like AVIF/HEIC): {}", e.getMessage()); + return null; + } + + log.warn("Unable to decode image - likely unsupported format (AVIF, HEIC, or SVG)"); + return null; + } + public static BufferedImage resizeImage(BufferedImage originalImage, int width, int height) { Image tmp = originalImage.getScaledInstance(width, height, Image.SCALE_SMOOTH); BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); @@ -156,9 +178,10 @@ public class FileService { public static void saveImage(byte[] imageData, String filePath) throws IOException { BufferedImage originalImage = null; try { - originalImage = ImageIO.read(new ByteArrayInputStream(imageData)); + originalImage = readImage(imageData); if (originalImage == null) { - throw new IOException("Invalid image data: unable to decode image"); + log.warn("Skipping saveImage for {}: decoded image is null", filePath); + return; } File outputFile = new File(filePath); File parentDir = outputFile.getParentFile(); @@ -191,13 +214,7 @@ public class FileService { // Validate and convert if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) { - try (ByteArrayInputStream inputStream = new ByteArrayInputStream(response.getBody())) { - BufferedImage image = ImageIO.read(inputStream); - if (image == null) { - throw new IOException("Downloaded content is not a supported image format."); - } - return image; - } + return readImage(response.getBody()); } else { throw new IOException("Failed to download image. HTTP Status: " + response.getStatusCode()); } @@ -216,10 +233,11 @@ public class FileService { validateCoverFile(file); BufferedImage originalImage; try (InputStream inputStream = file.getInputStream()) { - originalImage = ImageIO.read(inputStream); + originalImage = readImage(inputStream); } if (originalImage == null) { - throw ApiError.IMAGE_NOT_FOUND.createException(); + log.warn("Could not decode image from file, skipping thumbnail creation for book: {}", bookId); + return; } boolean success = saveCoverImages(originalImage, bookId); if (!success) { @@ -235,12 +253,10 @@ public class FileService { public void createThumbnailFromBytes(long bookId, byte[] imageBytes) { try { - BufferedImage originalImage; - try (InputStream inputStream = new java.io.ByteArrayInputStream(imageBytes)) { - originalImage = ImageIO.read(inputStream); - } + BufferedImage originalImage = readImage(imageBytes); if (originalImage == null) { - throw ApiError.IMAGE_NOT_FOUND.createException(); + log.warn("Skipping thumbnail creation for book {}: image decode failed", bookId); + return; } boolean success = saveCoverImages(originalImage, bookId); if (!success) { @@ -257,11 +273,15 @@ public class FileService { public void createThumbnailFromUrl(long bookId, String imageUrl) { try { BufferedImage originalImage = downloadImageFromUrl(imageUrl); + if (originalImage == null) { + log.warn("Skipping thumbnail creation for book {}: download/decode failed", bookId); + return; + } boolean success = saveCoverImages(originalImage, bookId); if (!success) { throw ApiError.FILE_READ_ERROR.createException("Failed to save cover images"); } - originalImage.flush(); // Release resources after processing + originalImage.flush(); log.info("Cover images created and saved from URL for book ID: {}", bookId); } catch (Exception e) { log.error("An error occurred while creating thumbnail from URL: {}", e.getMessage(), e); @@ -469,87 +489,6 @@ public class FileService { log.info("Deleted {} book covers", bookIds.size()); } - // ======================================== - // BACKGROUND OPERATIONS - // ======================================== - - public void saveBackgroundImage(BufferedImage image, String filename, Long userId) throws IOException { - String backgroundsFolder = getBackgroundsFolder(userId); - File folder = new File(backgroundsFolder); - if (!folder.exists() && !folder.mkdirs()) { - throw new IOException("Failed to create backgrounds directory: " + folder.getAbsolutePath()); - } - - File outputFile = new File(folder, filename); - boolean saved = ImageIO.write(image, IMAGE_FORMAT, outputFile); - if (!saved) { - throw new IOException("Failed to save background image: " + filename); - } - - log.info("Background image saved successfully for user {}: {}", userId, filename); - // Note: input image is not flushed here - caller is responsible for its lifecycle - } public void deleteBackgroundFile(String filename, Long userId) { - try { - String backgroundsFolder = getBackgroundsFolder(userId); - File file = new File(backgroundsFolder, filename); - if (file.exists() && file.isFile()) { - boolean deleted = file.delete(); - if (deleted) { - if (userId != null) { - deleteEmptyUserBackgroundFolder(userId); - } - } else { - log.warn("Failed to delete background file for user {}: {}", userId, filename); - } - } - } catch (Exception e) { - log.warn("Error deleting background file {} for user {}: {}", filename, userId, e.getMessage()); - } - } - - private void deleteEmptyUserBackgroundFolder(Long userId) { - try { - String userBackgroundsFolder = getBackgroundsFolder(userId); - File folder = new File(userBackgroundsFolder); - - if (folder.exists() && folder.isDirectory()) { - File[] files = folder.listFiles(); - if (files != null && files.length == 0) { - boolean deleted = folder.delete(); - if (deleted) { - log.info("Deleted empty background folder for user: {}", userId); - } else { - log.warn("Failed to delete empty background folder for user: {}", userId); - } - } - } - } catch (Exception e) { - log.warn("Error checking/deleting empty background folder for user {}: {}", userId, e.getMessage()); - } - } - - public Resource getBackgroundResource(Long userId) { - String[] possibleFiles = {"1.jpg", "1.jpeg", "1.png"}; - - if (userId != null) { - String userBackgroundsFolder = getBackgroundsFolder(userId); - for (String filename : possibleFiles) { - File customFile = new File(userBackgroundsFolder, filename); - if (customFile.exists() && customFile.isFile()) { - return new FileSystemResource(customFile); - } - } - } - String globalBackgroundsFolder = getBackgroundsFolder(); - for (String filename : possibleFiles) { - File customFile = new File(globalBackgroundsFolder, filename); - if (customFile.exists() && customFile.isFile()) { - return new FileSystemResource(customFile); - } - } - return new ClassPathResource("static/images/background.jpg"); - } - public String getIconsSvgFolder() { return Paths.get(appProperties.getPathConfig(), ICONS_DIR, SVG_DIR).toString(); } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/util/FileUtils.java b/booklore-api/src/main/java/com/adityachandel/booklore/util/FileUtils.java index 7cfb37ee0..e4cbcedf3 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/util/FileUtils.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/util/FileUtils.java @@ -63,13 +63,25 @@ public class FileUtils { } } - private List systemDirs = Arrays.asList( + public String getExtension(String fileName) { + if (fileName == null) { + return ""; + } + int i = fileName.lastIndexOf('.'); + if (i >= 0 && i < fileName.length() - 1) { + return fileName.substring(i + 1); + } + return ""; + } + + final private List systemDirs = Arrays.asList( // synology "#recycle", "@eaDir", // calibre ".caltrash" ); + public boolean shouldIgnore(Path path) { if (!path.getFileName().toString().isEmpty() && path.getFileName().toString().charAt(0) == '.') { return true; diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/util/UserPermissionUtils.java b/booklore-api/src/main/java/com/adityachandel/booklore/util/UserPermissionUtils.java index bd3e69f8d..915244560 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/util/UserPermissionUtils.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/util/UserPermissionUtils.java @@ -26,6 +26,7 @@ public class UserPermissionUtils { case ACCESS_USER_STATS -> perms.isPermissionAccessUserStats(); case ACCESS_TASK_MANAGER -> perms.isPermissionAccessTaskManager(); case MANAGE_ICONS -> perms.isPermissionManageIcons(); + case MANAGE_FONTS -> perms.isPermissionManageFonts(); case MANAGE_GLOBAL_PREFERENCES -> perms.isPermissionManageGlobalPreferences(); case DEMO_USER -> perms.isPermissionDemoUser(); }; @@ -49,6 +50,7 @@ public class UserPermissionUtils { case ACCESS_USER_STATS -> perms.isCanAccessUserStats(); case ACCESS_TASK_MANAGER -> perms.isCanAccessTaskManager(); case MANAGE_ICONS -> perms.isCanManageIcons(); + case MANAGE_FONTS -> perms.isCanManageFonts(); case MANAGE_GLOBAL_PREFERENCES -> perms.isCanManageGlobalPreferences(); case DEMO_USER -> perms.isDemoUser(); }; diff --git a/booklore-api/src/main/resources/db/migration/V85__Create_Custom_Font_Table.sql b/booklore-api/src/main/resources/db/migration/V85__Create_Custom_Font_Table.sql new file mode 100644 index 000000000..333d5feb7 --- /dev/null +++ b/booklore-api/src/main/resources/db/migration/V85__Create_Custom_Font_Table.sql @@ -0,0 +1,12 @@ +CREATE TABLE IF NOT EXISTS custom_font ( + id BIGINT AUTO_INCREMENT PRIMARY KEY, + user_id BIGINT NOT NULL, + font_name VARCHAR(255) NOT NULL, + file_name VARCHAR(255) NOT NULL UNIQUE, + original_file_name VARCHAR(255) NOT NULL, + format VARCHAR(10) NOT NULL, + file_size BIGINT NOT NULL, + uploaded_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE, + INDEX idx_user_id (user_id) +); diff --git a/booklore-api/src/main/resources/db/migration/V86__Add_Custom_Font_To_Epub_Preferences.sql b/booklore-api/src/main/resources/db/migration/V86__Add_Custom_Font_To_Epub_Preferences.sql new file mode 100644 index 000000000..31f0d942a --- /dev/null +++ b/booklore-api/src/main/resources/db/migration/V86__Add_Custom_Font_To_Epub_Preferences.sql @@ -0,0 +1,2 @@ +ALTER TABLE epub_viewer_preference ADD COLUMN IF NOT EXISTS custom_font_id BIGINT NULL; +ALTER TABLE epub_viewer_preference ADD FOREIGN KEY (custom_font_id) REFERENCES custom_font(id) ON DELETE SET NULL; diff --git a/booklore-api/src/main/resources/db/migration/V87__Migrate_MetadataPersistenceSettings_Structure.sql b/booklore-api/src/main/resources/db/migration/V87__Migrate_MetadataPersistenceSettings_Structure.sql new file mode 100644 index 000000000..851f73fac --- /dev/null +++ b/booklore-api/src/main/resources/db/migration/V87__Migrate_MetadataPersistenceSettings_Structure.sql @@ -0,0 +1,50 @@ +-- Migrate MetadataPersistenceSettings from old structure to new nested structure +-- Old: {"saveToOriginalFile":boolean,...} +-- New: {"saveToOriginalFile":{"epub":{...},"pdf":{...}},...} +-- Creates metadata_persistence_settings_v2 instead of overwriting the original + +INSERT INTO app_settings (name, val) +SELECT + 'metadata_persistence_settings_v2', + CASE + -- If saveToOriginalFile is true, enable all formats + WHEN JSON_EXTRACT(val, '$.saveToOriginalFile') = true THEN + JSON_SET( + val, + '$.saveToOriginalFile', + JSON_OBJECT( + 'epub', JSON_OBJECT('enabled', true, 'maxFileSizeInMb', 250), + 'pdf', JSON_OBJECT('enabled', true, 'maxFileSizeInMb', 250), + 'cbx', JSON_OBJECT('enabled', true, 'maxFileSizeInMb', 250) + ) + ) + -- If saveToOriginalFile is false, disable all formats + WHEN JSON_EXTRACT(val, '$.saveToOriginalFile') = false THEN + JSON_SET( + val, + '$.saveToOriginalFile', + JSON_OBJECT( + 'epub', JSON_OBJECT('enabled', false, 'maxFileSizeInMb', 250), + 'pdf', JSON_OBJECT('enabled', false, 'maxFileSizeInMb', 250), + 'cbx', JSON_OBJECT('enabled', false, 'maxFileSizeInMb', 250) + ) + ) + -- If null or missing, default to disabled + ELSE + JSON_SET( + COALESCE(val, '{}'), + '$.saveToOriginalFile', + JSON_OBJECT( + 'epub', JSON_OBJECT('enabled', false, 'maxFileSizeInMb', 250), + 'pdf', JSON_OBJECT('enabled', false, 'maxFileSizeInMb', 250), + 'cbx', JSON_OBJECT('enabled', false, 'maxFileSizeInMb', 250) + ) + ) + END +FROM app_settings +WHERE name = 'metadata_persistence_settings' +AND val IS NOT NULL +AND val != '' +AND NOT EXISTS ( + SELECT 1 FROM app_settings WHERE name = 'metadata_persistence_settings_v2' +); diff --git a/booklore-api/src/main/resources/db/migration/V88__Add_Font_Permissions.sql b/booklore-api/src/main/resources/db/migration/V88__Add_Font_Permissions.sql new file mode 100644 index 000000000..a2b4e87a8 --- /dev/null +++ b/booklore-api/src/main/resources/db/migration/V88__Add_Font_Permissions.sql @@ -0,0 +1,8 @@ +ALTER TABLE user_permissions + ADD COLUMN IF NOT EXISTS permission_manage_fonts BOOLEAN NOT NULL DEFAULT FALSE; + +-- Set all new permissions to TRUE for admin users + +UPDATE user_permissions up +SET up.permission_manage_fonts = TRUE +WHERE up.permission_admin = TRUE; diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/controller/BookMediaControllerTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/controller/BookMediaControllerTest.java deleted file mode 100644 index 4e3cc1cf6..000000000 --- a/booklore-api/src/test/java/com/adityachandel/booklore/controller/BookMediaControllerTest.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.adityachandel.booklore.controller; - -import com.adityachandel.booklore.service.book.BookService; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; -import org.springframework.core.io.Resource; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -@ExtendWith(MockitoExtension.class) -class BookMediaControllerTest { - - @Mock - private BookService bookService; - - @InjectMocks - private BookMediaController bookMediaController; - - @Test - void getBackgroundImage_shouldReturnBadRequestWhenFilenameIsNull() { - Resource resource = mock(Resource.class); - when(bookService.getBackgroundImage()).thenReturn(resource); - when(resource.exists()).thenReturn(true); - when(resource.getFilename()).thenReturn(null); - - ResponseEntity response = bookMediaController.getBackgroundImage(); - - assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode()); - } -} diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/KoreaderServiceTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/KoreaderServiceTest.java index 30dae2c78..f100a90bd 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/service/KoreaderServiceTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/KoreaderServiceTest.java @@ -13,6 +13,7 @@ import com.adityachandel.booklore.repository.BookRepository; import com.adityachandel.booklore.repository.UserBookProgressRepository; import com.adityachandel.booklore.repository.UserRepository; import com.adityachandel.booklore.repository.KoreaderUserRepository; +import com.adityachandel.booklore.service.hardcover.HardcoverSyncService; import com.adityachandel.booklore.service.koreader.KoreaderService; import org.junit.jupiter.api.*; import org.junit.jupiter.api.extension.ExtendWith; @@ -24,6 +25,7 @@ import org.springframework.http.ResponseEntity; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.*; +import java.lang.reflect.Method; import java.time.Instant; import java.util.Map; import java.util.Optional; @@ -40,6 +42,8 @@ class KoreaderServiceTest { UserRepository userRepo; @Mock KoreaderUserRepository koreaderUserRepo; + @Mock + HardcoverSyncService hardcoverSyncService; @InjectMocks KoreaderService service; @@ -232,4 +236,15 @@ class KoreaderServiceTest { var dto = KoreaderProgress.builder().document("h").build(); assertThrows(APIException.class, () -> service.saveProgress("h", dto)); } + + @Test + void normalizeProgressPercent_handlesNullAndRanges() throws Exception { + Method method = KoreaderService.class.getDeclaredMethod("normalizeProgressPercent", Float.class); + method.setAccessible(true); + + assertNull(method.invoke(service, new Object[]{null})); + assertEquals(50.0f, (Float) method.invoke(service, 0.5f)); + assertEquals(100.0f, (Float) method.invoke(service, 1.0f)); + assertEquals(42.0f, (Float) method.invoke(service, 42.0f)); + } } diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/book/BookServiceTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/book/BookServiceTest.java index 5c335a25b..449fe341e 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/service/book/BookServiceTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/book/BookServiceTest.java @@ -41,20 +41,34 @@ import static org.mockito.Mockito.*; @ExtendWith(org.mockito.junit.jupiter.MockitoExtension.class) class BookServiceTest { - @Mock private BookRepository bookRepository; - @Mock private PdfViewerPreferencesRepository pdfViewerPreferencesRepository; - @Mock private EpubViewerPreferencesRepository epubViewerPreferencesRepository; - @Mock private CbxViewerPreferencesRepository cbxViewerPreferencesRepository; - @Mock private NewPdfViewerPreferencesRepository newPdfViewerPreferencesRepository; - @Mock private FileService fileService; - @Mock private BookMapper bookMapper; - @Mock private UserBookProgressRepository userBookProgressRepository; - @Mock private AuthenticationService authenticationService; - @Mock private BookQueryService bookQueryService; - @Mock private UserProgressService userProgressService; - @Mock private BookDownloadService bookDownloadService; - @Mock private MonitoringRegistrationService monitoringRegistrationService; - @Mock private BookUpdateService bookUpdateService; + @Mock + private BookRepository bookRepository; + @Mock + private PdfViewerPreferencesRepository pdfViewerPreferencesRepository; + @Mock + private EpubViewerPreferencesRepository epubViewerPreferencesRepository; + @Mock + private CbxViewerPreferencesRepository cbxViewerPreferencesRepository; + @Mock + private NewPdfViewerPreferencesRepository newPdfViewerPreferencesRepository; + @Mock + private FileService fileService; + @Mock + private BookMapper bookMapper; + @Mock + private UserBookProgressRepository userBookProgressRepository; + @Mock + private AuthenticationService authenticationService; + @Mock + private BookQueryService bookQueryService; + @Mock + private UserProgressService userProgressService; + @Mock + private BookDownloadService bookDownloadService; + @Mock + private MonitoringRegistrationService monitoringRegistrationService; + @Mock + private BookUpdateService bookUpdateService; @InjectMocks private BookService bookService; @@ -258,18 +272,6 @@ class BookServiceTest { assertThrows(RuntimeException.class, () -> bookService.getBookCover(123L)); } - @Test - void getBackgroundImage_returnsResource() { - Resource mockResource = mock(Resource.class); - when(fileService.getBackgroundResource(testUser.getId())).thenReturn(mockResource); - - when(authenticationService.getAuthenticatedUser()).thenReturn(testUser); - - Resource res = bookService.getBackgroundImage(); - - assertEquals(mockResource, res); - } - @Test void downloadBook_delegatesToDownloadService() { ResponseEntity response = ResponseEntity.ok(mock(Resource.class)); diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/customfont/CustomFontServiceTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/customfont/CustomFontServiceTest.java new file mode 100644 index 000000000..6d9c58942 --- /dev/null +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/customfont/CustomFontServiceTest.java @@ -0,0 +1,452 @@ +package com.adityachandel.booklore.service.customfont; + +import com.adityachandel.booklore.config.AppProperties; +import com.adityachandel.booklore.mapper.CustomFontMapper; +import com.adityachandel.booklore.model.dto.CustomFontDto; +import com.adityachandel.booklore.model.entity.BookLoreUserEntity; +import com.adityachandel.booklore.model.entity.CustomFontEntity; +import com.adityachandel.booklore.model.enums.FontFormat; +import com.adityachandel.booklore.repository.CustomFontRepository; +import com.adityachandel.booklore.repository.UserRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.core.io.Resource; +import org.springframework.mock.web.MockMultipartFile; +import org.springframework.web.multipart.MultipartFile; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +class CustomFontServiceTest { + + @TempDir + Path tempDir; + + @Mock + CustomFontRepository customFontRepository; + @Mock + UserRepository userRepository; + @Mock + CustomFontMapper customFontMapper; + + AppProperties appProperties; + CustomFontService service; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + appProperties = new AppProperties(); + appProperties.setPathConfig(tempDir.toString()); + service = new CustomFontService(customFontRepository, userRepository, customFontMapper, appProperties); + } + + @Test + @DisplayName("uploadFont_withValidFile_shouldSaveSuccessfully") + void uploadFont_withValidFile_shouldSaveSuccessfully() throws IOException { + // Arrange + Long userId = 1L; + String fontName = "My Custom Font"; + // Create valid TTF magic bytes: 0x00 0x01 0x00 0x00 + byte[] fontContent = new byte[]{0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + MultipartFile file = new MockMultipartFile("font.ttf", "font.ttf", "font/ttf", fontContent); + + BookLoreUserEntity user = new BookLoreUserEntity(); + user.setId(userId); + + CustomFontEntity savedEntity = CustomFontEntity.builder() + .id(1L) + .user(user) + .fontName(fontName) + .fileName("user_1_font_123.ttf") + .originalFileName("font.ttf") + .format(FontFormat.TTF) + .fileSize((long) fontContent.length) + .build(); + + CustomFontDto expectedDto = new CustomFontDto(); + expectedDto.setId(1L); + expectedDto.setFontName(fontName); + + when(userRepository.findById(userId)).thenReturn(Optional.of(user)); + when(customFontRepository.countByUserId(userId)).thenReturn(0); + when(customFontRepository.save(any(CustomFontEntity.class))).thenReturn(savedEntity); + when(customFontMapper.toDto(savedEntity)).thenReturn(expectedDto); + + // Act + CustomFontDto result = service.uploadFont(file, fontName, userId); + + // Assert + assertThat(result).isNotNull(); + assertThat(result.getFontName()).isEqualTo(fontName); + verify(customFontRepository).save(any(CustomFontEntity.class)); + + // Verify file was saved + Path userFontDir = tempDir.resolve("custom-fonts").resolve(String.valueOf(userId)); + assertThat(Files.exists(userFontDir)).isTrue(); + assertThat(Files.list(userFontDir).count()).isEqualTo(1); + } + + @Test + @DisplayName("uploadFont_whenQuotaExceeded_shouldThrowException") + void uploadFont_whenQuotaExceeded_shouldThrowException() { + // Arrange + Long userId = 1L; + MultipartFile file = new MockMultipartFile("font.ttf", "font.ttf", "font/ttf", "content".getBytes()); + + when(customFontRepository.countByUserId(userId)).thenReturn(10); // Max quota + + // Act & Assert + assertThatThrownBy(() -> service.uploadFont(file, "Font", userId)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Font limit exceeded"); + + verify(customFontRepository, never()).save(any()); + } + + @Test + @DisplayName("uploadFont_withOversizedFile_shouldThrowException") + void uploadFont_withOversizedFile_shouldThrowException() { + // Arrange + Long userId = 1L; + byte[] largeContent = new byte[6 * 1024 * 1024]; // 6MB (exceeds 5MB limit) + MultipartFile file = new MockMultipartFile("font.ttf", "font.ttf", "font/ttf", largeContent); + + when(customFontRepository.countByUserId(userId)).thenReturn(0); + + // Act & Assert + assertThatThrownBy(() -> service.uploadFont(file, "Font", userId)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("File size exceeds maximum limit"); + + verify(customFontRepository, never()).save(any()); + } + + @Test + @DisplayName("uploadFont_withInvalidExtension_shouldThrowException") + void uploadFont_withInvalidExtension_shouldThrowException() { + // Arrange + Long userId = 1L; + MultipartFile file = new MockMultipartFile("font.exe", "font.exe", "application/octet-stream", "content".getBytes()); + + when(customFontRepository.countByUserId(userId)).thenReturn(0); + + // Act & Assert + assertThatThrownBy(() -> service.uploadFont(file, "Font", userId)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Unsupported font format"); + + verify(customFontRepository, never()).save(any()); + } + + @Test + @DisplayName("uploadFont_withInvalidMagicBytes_shouldThrowException") + void uploadFont_withInvalidMagicBytes_shouldThrowException() throws IOException { + // Arrange + Long userId = 1L; + // File has .ttf extension but contains malicious content (not TTF magic bytes) + byte[] maliciousContent = "This is not a font file".getBytes(); + MultipartFile file = new MockMultipartFile("malicious.ttf", "malicious.ttf", "font/ttf", maliciousContent); + + BookLoreUserEntity user = new BookLoreUserEntity(); + user.setId(userId); + + when(userRepository.findById(userId)).thenReturn(Optional.of(user)); + when(customFontRepository.countByUserId(userId)).thenReturn(0); + + // Act & Assert + assertThatThrownBy(() -> service.uploadFont(file, "Font", userId)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Invalid font file format"); + + verify(customFontRepository, never()).save(any()); + + // Verify file was cleaned up + Path userFontDir = tempDir.resolve("custom-fonts").resolve(String.valueOf(userId)); + if (Files.exists(userFontDir)) { + assertThat(Files.list(userFontDir).count()).isEqualTo(0); + } + } + + @Test + @DisplayName("uploadFont_whenDatabaseSaveFails_shouldCleanupFile") + void uploadFont_whenDatabaseSaveFails_shouldCleanupFile() throws IOException { + // Arrange + Long userId = 1L; + // Create valid TTF magic bytes + byte[] fontContent = new byte[]{0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + MultipartFile file = new MockMultipartFile("font.ttf", "font.ttf", "font/ttf", fontContent); + + BookLoreUserEntity user = new BookLoreUserEntity(); + user.setId(userId); + + when(userRepository.findById(userId)).thenReturn(Optional.of(user)); + when(customFontRepository.countByUserId(userId)).thenReturn(0); + when(customFontRepository.save(any(CustomFontEntity.class))) + .thenThrow(new RuntimeException("Database error")); + + // Act & Assert + assertThatThrownBy(() -> service.uploadFont(file, "Font", userId)) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining("Database error"); + + // Verify file was cleaned up + Path userFontDir = tempDir.resolve("custom-fonts").resolve(String.valueOf(userId)); + if (Files.exists(userFontDir)) { + assertThat(Files.list(userFontDir).count()).isEqualTo(0); + } + } + + @Test + @DisplayName("deleteFont_withValidId_shouldDeleteFileAndRecord") + void deleteFont_withValidId_shouldDeleteFileAndRecord() throws IOException { + // Arrange + Long userId = 1L; + Long fontId = 1L; + String fileName = "user_1_font_123.ttf"; + + // Create actual font file + Path userFontDir = tempDir.resolve("custom-fonts").resolve(String.valueOf(userId)); + Files.createDirectories(userFontDir); + Path fontFile = userFontDir.resolve(fileName); + Files.writeString(fontFile, "font content"); + + CustomFontEntity font = CustomFontEntity.builder() + .id(fontId) + .fontName("Test Font") + .fileName(fileName) + .build(); + + when(customFontRepository.findByIdAndUserId(fontId, userId)).thenReturn(Optional.of(font)); + + // Act + service.deleteFont(fontId, userId); + + // Assert + verify(customFontRepository).delete(font); + assertThat(Files.exists(fontFile)).isFalse(); + } + + @Test + @DisplayName("deleteFont_whenFileDeletionFails_shouldStillDeleteRecord") + void deleteFont_whenFileDeletionFails_shouldStillDeleteRecord() { + // Arrange + Long userId = 1L; + Long fontId = 1L; + String fileName = "non_existent_font.ttf"; + + CustomFontEntity font = CustomFontEntity.builder() + .id(fontId) + .fontName("Test Font") + .fileName(fileName) + .build(); + + when(customFontRepository.findByIdAndUserId(fontId, userId)).thenReturn(Optional.of(font)); + + // Act + // Files.deleteIfExists doesn't throw when file doesn't exist, so this should succeed + assertThatCode(() -> service.deleteFont(fontId, userId)) + .doesNotThrowAnyException(); + + // Database record should be deleted + verify(customFontRepository, times(1)).delete(font); + } + + @Test + @DisplayName("deleteFont_withInvalidId_shouldThrowException") + void deleteFont_withInvalidId_shouldThrowException() { + // Arrange + Long userId = 1L; + Long fontId = 999L; + + when(customFontRepository.findByIdAndUserId(fontId, userId)).thenReturn(Optional.empty()); + + // Act & Assert + assertThatThrownBy(() -> service.deleteFont(fontId, userId)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Font not found or access denied"); + + verify(customFontRepository, never()).delete(any()); + } + + @Test + @DisplayName("getFontFile_withValidId_shouldReturnResource") + void getFontFile_withValidId_shouldReturnResource() throws IOException { + // Arrange + Long userId = 1L; + Long fontId = 1L; + String fileName = "user_1_font_123.ttf"; + + // Create actual font file + Path userFontDir = tempDir.resolve("custom-fonts").resolve(String.valueOf(userId)); + Files.createDirectories(userFontDir); + Path fontFile = userFontDir.resolve(fileName); + Files.writeString(fontFile, "font content"); + + CustomFontEntity font = CustomFontEntity.builder() + .id(fontId) + .fontName("Test Font") + .fileName(fileName) + .build(); + + when(customFontRepository.findByIdAndUserId(fontId, userId)).thenReturn(Optional.of(font)); + + // Act + Resource result = service.getFontFile(fontId, userId); + + // Assert + assertThat(result).isNotNull(); + assertThat(result.exists()).isTrue(); + assertThat(result.getFile().toPath()).isEqualTo(fontFile); + } + + @Test + @DisplayName("getFontFile_whenUserNotOwner_shouldThrowException") + void getFontFile_whenUserNotOwner_shouldThrowException() { + // Arrange + Long userId = 1L; + Long otherUserId = 2L; + Long fontId = 1L; + + when(customFontRepository.findByIdAndUserId(fontId, otherUserId)).thenReturn(Optional.empty()); + + // Act & Assert + assertThatThrownBy(() -> service.getFontFile(fontId, otherUserId)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Font not found or access denied"); + } + + @Test + @DisplayName("getFontFile_withNonExistentFile_shouldThrowException") + void getFontFile_withNonExistentFile_shouldThrowException() { + // Arrange + Long userId = 1L; + Long fontId = 1L; + String fileName = "non_existent.ttf"; + + CustomFontEntity font = CustomFontEntity.builder() + .id(fontId) + .fontName("Test Font") + .fileName(fileName) + .build(); + + when(customFontRepository.findByIdAndUserId(fontId, userId)).thenReturn(Optional.of(font)); + + // Act & Assert + assertThatThrownBy(() -> service.getFontFile(fontId, userId)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Font file not found on disk"); + } + + @Test + @DisplayName("validatePath_withPathTraversal_shouldThrowException") + void validatePath_withPathTraversal_shouldThrowException() throws IOException { + // Arrange + Long userId = 1L; + // Use valid font extension to pass extension validation + String maliciousFileName = "../../../etc/passwd.ttf"; + // Create valid TTF magic bytes to pass magic byte validation + byte[] fontContent = new byte[]{0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + MultipartFile file = new MockMultipartFile( + maliciousFileName, + maliciousFileName, + "font/ttf", + fontContent + ); + + BookLoreUserEntity user = new BookLoreUserEntity(); + user.setId(userId); + + when(userRepository.findById(userId)).thenReturn(Optional.of(user)); + when(customFontRepository.countByUserId(userId)).thenReturn(0); + + // Mock repository save to complete the upload + when(customFontRepository.save(any(CustomFontEntity.class))).thenAnswer(invocation -> { + CustomFontEntity entity = invocation.getArgument(0); + entity.setId(1L); + return entity; + }); + + CustomFontDto mockDto = new CustomFontDto(); + mockDto.setId(1L); + when(customFontMapper.toDto(any(CustomFontEntity.class))).thenReturn(mockDto); + + // Act & Assert + // The service generates safe filenames, so even with malicious input, the path is safe + assertThatCode(() -> service.uploadFont(file, "Test", userId)) + .doesNotThrowAnyException(); // Safe because service generates safe filename + + // Verify no files were created outside the expected directory + Path expectedDir = tempDir.resolve("custom-fonts").resolve(String.valueOf(userId)); + Path parentDir = tempDir.resolve("custom-fonts"); + + // Count files in user directory + long userDirFiles = Files.exists(expectedDir) ? Files.list(expectedDir).count() : 0; + + // Count files in parent directory (should only be the user directory) + long parentDirEntries = Files.list(parentDir).count(); + + assertThat(userDirFiles).isGreaterThanOrEqualTo(0); + assertThat(parentDirEntries).isEqualTo(1); // Only user directory, no escaped files + } + + @Test + @DisplayName("getUserFonts_shouldReturnAllUserFonts") + void getUserFonts_shouldReturnAllUserFonts() { + // Arrange + Long userId = 1L; + List entities = List.of( + CustomFontEntity.builder().id(1L).fontName("Font 1").build(), + CustomFontEntity.builder().id(2L).fontName("Font 2").build() + ); + + CustomFontDto dto1 = new CustomFontDto(); + dto1.setId(1L); + CustomFontDto dto2 = new CustomFontDto(); + dto2.setId(2L); + + when(customFontRepository.findByUserId(userId)).thenReturn(entities); + when(customFontMapper.toDto(entities.get(0))).thenReturn(dto1); + when(customFontMapper.toDto(entities.get(1))).thenReturn(dto2); + + // Act + List result = service.getUserFonts(userId); + + // Assert + assertThat(result).hasSize(2); + assertThat(result.get(0).getId()).isEqualTo(1L); + assertThat(result.get(1).getId()).isEqualTo(2L); + } + + @Test + @DisplayName("getFontFormat_shouldReturnCorrectFormat") + void getFontFormat_shouldReturnCorrectFormat() { + // Arrange + Long userId = 1L; + Long fontId = 1L; + + CustomFontEntity font = CustomFontEntity.builder() + .id(fontId) + .fontName("Test Font") + .format(FontFormat.WOFF2) + .build(); + + when(customFontRepository.findByIdAndUserId(fontId, userId)).thenReturn(Optional.of(font)); + + // Act + FontFormat result = service.getFontFormat(fontId, userId); + + // Assert + assertThat(result).isEqualTo(FontFormat.WOFF2); + } +} diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/hardcover/HardcoverSyncServiceTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/hardcover/HardcoverSyncServiceTest.java index eeac23f93..25ef5a30b 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/service/hardcover/HardcoverSyncServiceTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/hardcover/HardcoverSyncServiceTest.java @@ -1,10 +1,9 @@ package com.adityachandel.booklore.service.hardcover; -import com.adityachandel.booklore.model.dto.KoboSyncSettings; +import com.adityachandel.booklore.model.dto.HardcoverSyncSettings; import com.adityachandel.booklore.model.entity.BookEntity; import com.adityachandel.booklore.model.entity.BookMetadataEntity; import com.adityachandel.booklore.repository.BookRepository; -import com.adityachandel.booklore.service.kobo.KoboSettingsService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -14,8 +13,10 @@ import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoSettings; import org.mockito.quality.Strictness; import org.springframework.web.client.RestClient; +import org.mockito.ArgumentMatchers; import java.lang.reflect.Field; +import java.lang.reflect.Method; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -29,7 +30,7 @@ import static org.mockito.Mockito.*; class HardcoverSyncServiceTest { @Mock - private KoboSettingsService koboSettingsService; + private HardcoverSyncSettingsService hardcoverSyncSettingsService; @Mock private BookRepository bookRepository; @@ -50,7 +51,7 @@ class HardcoverSyncServiceTest { private BookEntity testBook; private BookMetadataEntity testMetadata; - private KoboSyncSettings koboSyncSettings; + private HardcoverSyncSettings hardcoverSyncSettings; private static final Long TEST_BOOK_ID = 100L; private static final Long TEST_USER_ID = 1L; @@ -58,7 +59,7 @@ class HardcoverSyncServiceTest { @BeforeEach void setUp() throws Exception { // Create service with mocked dependencies - service = new HardcoverSyncService(koboSettingsService, bookRepository); + service = new HardcoverSyncService(hardcoverSyncSettingsService, bookRepository); // Inject our mocked restClient using reflection Field restClientField = HardcoverSyncService.class.getDeclaredField("restClient"); @@ -73,19 +74,19 @@ class HardcoverSyncServiceTest { testMetadata.setPageCount(300); testBook.setMetadata(testMetadata); - // Setup Kobo sync settings with Hardcover enabled - koboSyncSettings = new KoboSyncSettings(); - koboSyncSettings.setHardcoverSyncEnabled(true); - koboSyncSettings.setHardcoverApiKey("test-api-key"); + // Setup Hardcover sync settings + hardcoverSyncSettings = new HardcoverSyncSettings(); + hardcoverSyncSettings.setHardcoverSyncEnabled(true); + hardcoverSyncSettings.setHardcoverApiKey("test-api-key"); - when(koboSettingsService.getSettingsByUserId(TEST_USER_ID)).thenReturn(koboSyncSettings); + when(hardcoverSyncSettingsService.getSettingsForUserId(TEST_USER_ID)).thenReturn(hardcoverSyncSettings); when(bookRepository.findById(TEST_BOOK_ID)).thenReturn(Optional.of(testBook)); // Setup RestClient mock chain - handles multiple calls when(restClient.post()).thenReturn(requestBodyUriSpec); when(requestBodyUriSpec.uri(anyString())).thenReturn(requestBodySpec); when(requestBodySpec.header(anyString(), anyString())).thenReturn(requestBodySpec); - when(requestBodySpec.body(any())).thenReturn(requestBodySpec); + doReturn(requestBodySpec).when(requestBodySpec).body(ArgumentMatchers.any(Object.class)); when(requestBodySpec.retrieve()).thenReturn(responseSpec); } @@ -94,7 +95,7 @@ class HardcoverSyncServiceTest { @Test @DisplayName("Should skip sync when Hardcover sync is not enabled for user") void syncProgressToHardcover_whenHardcoverDisabled_shouldSkip() { - koboSyncSettings.setHardcoverSyncEnabled(false); + hardcoverSyncSettings.setHardcoverSyncEnabled(false); service.syncProgressToHardcover(TEST_BOOK_ID, 50.0f, TEST_USER_ID); @@ -104,7 +105,7 @@ class HardcoverSyncServiceTest { @Test @DisplayName("Should skip sync when API key is missing") void syncProgressToHardcover_whenApiKeyMissing_shouldSkip() { - koboSyncSettings.setHardcoverApiKey(null); + hardcoverSyncSettings.setHardcoverApiKey(null); service.syncProgressToHardcover(TEST_BOOK_ID, 50.0f, TEST_USER_ID); @@ -114,7 +115,7 @@ class HardcoverSyncServiceTest { @Test @DisplayName("Should skip sync when API key is blank") void syncProgressToHardcover_whenApiKeyBlank_shouldSkip() { - koboSyncSettings.setHardcoverApiKey(" "); + hardcoverSyncSettings.setHardcoverApiKey(" "); service.syncProgressToHardcover(TEST_BOOK_ID, 50.0f, TEST_USER_ID); @@ -244,6 +245,7 @@ class HardcoverSyncServiceTest { @DisplayName("Should handle existing user_book gracefully") void syncProgressToHardcover_whenUserBookExists_shouldFindExisting() { testMetadata.setHardcoverBookId(12345); + testMetadata.setPageCount(300); // Mock: insert_user_book returns error, then find existing, then create progress when(responseSpec.body(Map.class)) @@ -261,6 +263,7 @@ class HardcoverSyncServiceTest { @DisplayName("Should update existing reading progress") void syncProgressToHardcover_whenProgressExists_shouldUpdate() { testMetadata.setHardcoverBookId(12345); + testMetadata.setPageCount(300); // Mock: insert_user_book -> find existing read -> update read when(responseSpec.body(Map.class)) @@ -296,6 +299,7 @@ class HardcoverSyncServiceTest { @DisplayName("Should handle API errors gracefully") void syncProgressToHardcover_whenApiError_shouldNotThrow() { testMetadata.setHardcoverBookId(12345); + testMetadata.setPageCount(300); when(responseSpec.body(Map.class)).thenReturn(Map.of("errors", List.of(Map.of("message", "Unauthorized")))); @@ -306,6 +310,7 @@ class HardcoverSyncServiceTest { @DisplayName("Should handle null response gracefully") void syncProgressToHardcover_whenResponseNull_shouldNotThrow() { testMetadata.setHardcoverBookId(12345); + testMetadata.setPageCount(300); when(responseSpec.body(Map.class)).thenReturn(null); @@ -315,7 +320,7 @@ class HardcoverSyncServiceTest { @Test @DisplayName("Should skip sync when user settings not found") void syncProgressToHardcover_whenUserSettingsNotFound_shouldSkip() { - when(koboSettingsService.getSettingsByUserId(TEST_USER_ID)).thenReturn(null); + when(hardcoverSyncSettingsService.getSettingsForUserId(TEST_USER_ID)).thenReturn(null); service.syncProgressToHardcover(TEST_BOOK_ID, 50.0f, TEST_USER_ID); @@ -441,4 +446,89 @@ class HardcoverSyncServiceTest { return response; } + + @Test + @DisplayName("findEditionById should return null on null response") + void findEditionById_nullResponse_shouldReturnNull() throws Exception { + when(responseSpec.body(ArgumentMatchers.>eq(Map.class))).thenReturn(null); + + Method method = HardcoverSyncService.class.getDeclaredMethod("findEditionById", Integer.class); + method.setAccessible(true); + + Object result = method.invoke(service, 123); + assertNull(result); + } + + @Test + @DisplayName("findEditionById should parse edition info when present") + void findEditionById_withData_shouldParse() throws Exception { + Map response = new HashMap<>(); + Map data = new HashMap<>(); + Map edition = new HashMap<>(); + edition.put("id", 77); + edition.put("pages", 250); + data.put("editions", List.of(edition)); + response.put("data", data); + + when(responseSpec.body(ArgumentMatchers.>eq(Map.class))).thenReturn(response); + + Method method = HardcoverSyncService.class.getDeclaredMethod("findEditionById", Integer.class); + method.setAccessible(true); + + Object result = method.invoke(service, 77); + assertNotNull(result); + assertEquals(77, readPrivateField(result, "id")); + assertEquals(250, readPrivateField(result, "pages")); + } + + @Test + @DisplayName("findHardcoverBookById should return null on empty response") + void findHardcoverBookById_emptyResponse_shouldReturnNull() throws Exception { + when(responseSpec.body(ArgumentMatchers.>eq(Map.class))) + .thenReturn(Map.of("data", Map.of("books", List.of()))); + + Method method = HardcoverSyncService.class.getDeclaredMethod("findHardcoverBookById", Integer.class); + method.setAccessible(true); + + Object result = method.invoke(service, 123); + assertNull(result); + } + + @Test + @DisplayName("findHardcoverBookById should use default edition and edition pages") + void findHardcoverBookById_withDefaultEdition_shouldUseEditionPages() throws Exception { + Map bookResponse = new HashMap<>(); + Map bookData = new HashMap<>(); + Map book = new HashMap<>(); + book.put("default_edition_id", "88"); + bookData.put("books", List.of(book)); + bookResponse.put("data", bookData); + + Map editionResponse = new HashMap<>(); + Map editionData = new HashMap<>(); + Map edition = new HashMap<>(); + edition.put("id", 88); + edition.put("pages", 320); + editionData.put("editions", List.of(edition)); + editionResponse.put("data", editionData); + + when(responseSpec.body(ArgumentMatchers.>eq(Map.class))) + .thenReturn(bookResponse) + .thenReturn(editionResponse); + + Method method = HardcoverSyncService.class.getDeclaredMethod("findHardcoverBookById", Integer.class); + method.setAccessible(true); + + Object result = method.invoke(service, 123); + assertNotNull(result); + assertEquals(123, readPrivateField(result, "bookId")); + assertEquals(88, readPrivateField(result, "editionId")); + assertEquals(320, readPrivateField(result, "pages")); + } + + private Integer readPrivateField(Object target, String fieldName) throws Exception { + Field field = target.getClass().getDeclaredField(fieldName); + field.setAccessible(true); + return (Integer) field.get(target); + } } diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/hardcover/HardcoverSyncSettingsServiceTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/hardcover/HardcoverSyncSettingsServiceTest.java new file mode 100644 index 000000000..55df61ac8 --- /dev/null +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/hardcover/HardcoverSyncSettingsServiceTest.java @@ -0,0 +1,98 @@ +package com.adityachandel.booklore.service.hardcover; + +import com.adityachandel.booklore.config.security.service.AuthenticationService; +import com.adityachandel.booklore.model.dto.HardcoverSyncSettings; +import com.adityachandel.booklore.model.dto.settings.UserSettingKey; +import com.adityachandel.booklore.model.entity.BookLoreUserEntity; +import com.adityachandel.booklore.model.entity.KoboUserSettingsEntity; +import com.adityachandel.booklore.model.entity.UserSettingEntity; +import com.adityachandel.booklore.repository.KoboUserSettingsRepository; +import com.adityachandel.booklore.repository.UserRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.HashSet; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class HardcoverSyncSettingsServiceTest { + + @Mock + private UserRepository userRepository; + + @Mock + private AuthenticationService authenticationService; + + @Mock + private KoboUserSettingsRepository koboUserSettingsRepository; + + private HardcoverSyncSettingsService service; + + @BeforeEach + void setUp() { + service = new HardcoverSyncSettingsService(userRepository, authenticationService, koboUserSettingsRepository); + } + + @Test + @DisplayName("Should fallback to legacy Kobo settings and persist user settings") + void getSettingsForUserId_whenLegacyPresent_shouldPersistUserSettings() { + BookLoreUserEntity user = new BookLoreUserEntity(); + user.setId(1L); + user.setSettings(new HashSet<>()); + + KoboUserSettingsEntity legacy = KoboUserSettingsEntity.builder() + .userId(1L) + .hardcoverApiKey("legacy-key") + .hardcoverSyncEnabled(true) + .build(); + + when(userRepository.findById(1L)).thenReturn(Optional.of(user)); + when(koboUserSettingsRepository.findByUserId(1L)).thenReturn(Optional.of(legacy)); + + HardcoverSyncSettings settings = service.getSettingsForUserId(1L); + + assertEquals("legacy-key", settings.getHardcoverApiKey()); + assertTrue(settings.isHardcoverSyncEnabled()); + assertTrue(user.getSettings().stream() + .anyMatch(setting -> UserSettingKey.HARDCOVER_API_KEY.getDbKey().equals(setting.getSettingKey()))); + assertTrue(user.getSettings().stream() + .anyMatch(setting -> UserSettingKey.HARDCOVER_SYNC_ENABLED.getDbKey().equals(setting.getSettingKey()))); + verify(userRepository).save(user); + } + + @Test + @DisplayName("Should trim API key when updating settings") + void updateSettingsForUserId_shouldTrimApiKey() { + BookLoreUserEntity user = new BookLoreUserEntity(); + user.setId(1L); + user.setSettings(new HashSet<>()); + user.getSettings().add(UserSettingEntity.builder() + .user(user) + .settingKey(UserSettingKey.HARDCOVER_API_KEY.getDbKey()) + .settingValue("old") + .build()); + + when(userRepository.findById(1L)).thenReturn(Optional.of(user)); + + HardcoverSyncSettings update = new HardcoverSyncSettings(); + update.setHardcoverApiKey(" new-key "); + update.setHardcoverSyncEnabled(false); + + HardcoverSyncSettings result = service.updateSettingsForUserId(1L, update); + + assertEquals("new-key", result.getHardcoverApiKey()); + assertTrue(user.getSettings().stream() + .anyMatch(setting -> UserSettingKey.HARDCOVER_API_KEY.getDbKey().equals(setting.getSettingKey()) + && "new-key".equals(setting.getSettingValue()))); + verify(userRepository).save(user); + } +} diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/kobo/KoboServerProxyTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/kobo/KoboServerProxyTest.java new file mode 100644 index 000000000..86ecda741 --- /dev/null +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/kobo/KoboServerProxyTest.java @@ -0,0 +1,257 @@ +package com.adityachandel.booklore.service.kobo; + +import com.adityachandel.booklore.model.dto.BookloreSyncToken; +import com.adityachandel.booklore.model.dto.kobo.KoboHeaders; +import com.adityachandel.booklore.util.kobo.BookloreSyncTokenGenerator; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.core.io.Resource; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; +import org.springframework.web.server.ResponseStatusException; + +import java.lang.reflect.Field; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.util.Collections; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.*; + +@ExtendWith(MockitoExtension.class) +class KoboServerProxyTest { + + @Mock + private ObjectMapper objectMapper; + + @Mock + private BookloreSyncTokenGenerator bookloreSyncTokenGenerator; + + @Mock + private HttpClient httpClient; + + @Mock + private HttpResponse httpResponse; + + @Mock + private HttpResponse httpResponseBytes; + + @InjectMocks + private KoboServerProxy koboServerProxy; + + private MockHttpServletRequest mockRequest; + + @BeforeEach + void setUp() throws Exception { + mockRequest = new MockHttpServletRequest(); + mockRequest.setMethod("GET"); + mockRequest.setRequestURI("/api/kobo/v1/library/sync"); + + RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(mockRequest)); + + Field httpClientField = KoboServerProxy.class.getDeclaredField("httpClient"); + httpClientField.setAccessible(true); + httpClientField.set(koboServerProxy, httpClient); + } + + @AfterEach + void tearDown() { + RequestContextHolder.resetRequestAttributes(); + } + + private void setupSuccessfulProxyResponse() throws Exception { + when(httpResponse.statusCode()).thenReturn(200); + when(httpResponse.body()).thenReturn("{}"); + when(httpResponse.headers()).thenReturn(java.net.http.HttpHeaders.of( + Collections.emptyMap(), + (k, v) -> true + )); + when(objectMapper.readTree(anyString())).thenReturn(mock(JsonNode.class)); + when(httpClient.send(any(HttpRequest.class), any())) + .thenReturn(httpResponse); + } + + @Test + void proxyCurrentRequest_withSquareBracketsInQueryParams_shouldHandleSuccessfully() throws Exception { + // Validates fix for: IllegalArgumentException: Invalid character '[' for QUERY_PARAM + String problematicQuery = "Filters=[%7BKey:TestKey,ETag:W/TestEtagValue123%7D]"; + mockRequest.setQueryString(problematicQuery); + mockRequest.addHeader("User-Agent", "Kobo/1.0"); + setupSuccessfulProxyResponse(); + + ResponseEntity response = koboServerProxy.proxyCurrentRequest(null, false); + + assertThat(response).isNotNull(); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); + verify(httpClient).send(any(HttpRequest.class), any()); + } + + @Test + void proxyCurrentRequest_withVariousEncodedQueryParams_shouldHandleSuccessfully() throws Exception { + String[] testQueries = { + "Filters=%5B%7BKey:TestKey%7D%5D", // Properly encoded brackets + "Filter=ALL&DownloadUrlFilter=Generic,Android&PrioritizeRecentReads=true", // Real Kobo params + "page_index=0&page_size=50&Filters=%7B%7D" // URL-encoded JSON + }; + + for (String query : testQueries) { + mockRequest.setQueryString(query); + setupSuccessfulProxyResponse(); + + ResponseEntity response = koboServerProxy.proxyCurrentRequest(null, false); + + assertThat(response).isNotNull(); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); + } + + verify(httpClient, times(testQueries.length)).send(any(HttpRequest.class), any()); + } + + @Test + void proxyCurrentRequest_withSyncToken_shouldPreserveAndUpdateToken() throws Exception { + mockRequest.setQueryString("Filter=ALL"); + mockRequest.addHeader(KoboHeaders.X_KOBO_SYNCTOKEN, "original-token"); + + BookloreSyncToken mockSyncToken = BookloreSyncToken.builder() + .rawKoboSyncToken("kobo-sync-token") + .ongoingSyncPointId("1") + .lastSuccessfulSyncPointId("0") + .build(); + + when(bookloreSyncTokenGenerator.fromRequestHeaders(any())).thenReturn(mockSyncToken); + when(httpResponse.statusCode()).thenReturn(200); + when(httpResponse.body()).thenReturn("{}"); + when(httpResponse.headers()).thenReturn(java.net.http.HttpHeaders.of( + Map.of(KoboHeaders.X_KOBO_SYNCTOKEN, java.util.List.of("new-kobo-token")), + (k, v) -> true + )); + when(objectMapper.readTree(anyString())).thenReturn(mock(JsonNode.class)); + when(bookloreSyncTokenGenerator.toBase64(any())).thenReturn("encoded-sync-token"); + when(httpClient.send(any(HttpRequest.class), any())) + .thenReturn(httpResponse); + + ResponseEntity response = koboServerProxy.proxyCurrentRequest(null, true); + + assertThat(response).isNotNull(); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); + verify(bookloreSyncTokenGenerator).toBase64(any(BookloreSyncToken.class)); + } + + @Test + void proxyCurrentRequest_shouldPreserveKoboHeaders() throws Exception { + mockRequest.addHeader("X-Kobo-DeviceId", "device123"); + mockRequest.addHeader("X-Kobo-UserKey", "user456"); + + when(httpResponse.statusCode()).thenReturn(200); + when(httpResponse.body()).thenReturn("{}"); + when(httpResponse.headers()).thenReturn(java.net.http.HttpHeaders.of( + Map.of("X-Kobo-Response", java.util.List.of("test")), + (k, v) -> true + )); + when(objectMapper.readTree(anyString())).thenReturn(mock(JsonNode.class)); + when(httpClient.send(any(HttpRequest.class), any())) + .thenReturn(httpResponse); + + ResponseEntity response = koboServerProxy.proxyCurrentRequest(null, false); + + assertThat(response).isNotNull(); + assertThat(response.getHeaders()).containsKey("X-Kobo-Response"); + } + + @Test + void proxyCurrentRequest_withPostBody_shouldSerializeBody() throws Exception { + mockRequest.setMethod("POST"); + Object requestBody = new Object(); + + when(objectMapper.writeValueAsString(requestBody)).thenReturn("{\"test\":\"value\"}"); + setupSuccessfulProxyResponse(); + + ResponseEntity response = koboServerProxy.proxyCurrentRequest(requestBody, false); + + assertThat(response).isNotNull(); + verify(objectMapper).writeValueAsString(requestBody); + } + + @Test + void proxyCurrentRequest_with400Response_shouldPreserveStatusCode() throws Exception { + mockRequest.setQueryString("ExcludeOwned=false&PageSize=100"); + + when(httpResponse.statusCode()).thenReturn(400); + when(httpResponse.body()).thenReturn("{\"error\":\"Bad Request\"}"); + when(httpResponse.headers()).thenReturn(java.net.http.HttpHeaders.of( + Collections.emptyMap(), + (k, v) -> true + )); + when(objectMapper.readTree(anyString())).thenReturn(mock(JsonNode.class)); + when(httpClient.send(any(HttpRequest.class), any())) + .thenReturn(httpResponse); + + ResponseEntity response = koboServerProxy.proxyCurrentRequest(null, false); + + assertThat(response).isNotNull(); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST); + } + + @Test + void proxyCurrentRequest_withMaliciousQueryParams_shouldHandleSafely() throws Exception { + String[] maliciousQueries = { + "param1=value1%0D%0AHost:evil.com", // CRLF injection attempt + "text=%3Cscript%3Ealert('xss')%3C/script%3E&other=%22quotes%22" // XSS attempt + }; + + for (String query : maliciousQueries) { + mockRequest.setQueryString(query); + setupSuccessfulProxyResponse(); + + ResponseEntity response = koboServerProxy.proxyCurrentRequest(null, false); + + assertThat(response).isNotNull(); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); + } + } + + @Test + void proxyExternalUrl_shouldFetchAndReturnImage() throws Exception { + String testUrl = "https://cdn.kobo.com/image123.jpg"; + byte[] imageData = {1, 2, 3, 4, 5}; + + when(httpResponseBytes.statusCode()).thenReturn(200); + when(httpResponseBytes.body()).thenReturn(imageData); + when(httpClient.send(any(HttpRequest.class), any())) + .thenReturn(httpResponseBytes); + + ResponseEntity response = koboServerProxy.proxyExternalUrl(testUrl); + + assertThat(response).isNotNull(); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(response.getBody()).isNotNull(); + assertThat(response.getBody().contentLength()).isEqualTo(5); + } + + @Test + void proxyExternalUrl_withException_shouldThrowResponseStatusException() throws Exception { + String testUrl = "https://cdn.kobo.com/image123.jpg"; + + when(httpClient.send(any(HttpRequest.class), any())) + .thenThrow(new java.io.IOException("Network error")); + + assertThatThrownBy(() -> koboServerProxy.proxyExternalUrl(testUrl)) + .isInstanceOf(ResponseStatusException.class) + .hasMessageContaining("Failed to fetch image"); + } +} diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/kobo/KoboSettingsServiceTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/kobo/KoboSettingsServiceTest.java index acf2d862b..6176e9bcf 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/service/kobo/KoboSettingsServiceTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/kobo/KoboSettingsServiceTest.java @@ -10,6 +10,7 @@ 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 com.adityachandel.booklore.service.hardcover.HardcoverSyncSettingsService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -30,6 +31,8 @@ class KoboSettingsServiceTest { private AuthenticationService authenticationService; @Mock private ShelfService shelfService; + @Mock + private HardcoverSyncSettingsService hardcoverSyncSettingsService; @InjectMocks private KoboSettingsService service; diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/library/LibraryFileHelperTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/library/LibraryFileHelperTest.java new file mode 100644 index 000000000..fe2c3f795 --- /dev/null +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/library/LibraryFileHelperTest.java @@ -0,0 +1,58 @@ +package com.adityachandel.booklore.service.library; + +import com.adityachandel.booklore.model.dto.LibraryPath; +import com.adityachandel.booklore.model.dto.settings.LibraryFile; +import com.adityachandel.booklore.model.entity.LibraryEntity; +import com.adityachandel.booklore.model.entity.LibraryPathEntity; +import com.adityachandel.booklore.model.enums.LibraryScanMode; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.FileAttribute; +import java.nio.file.attribute.PosixFilePermissions; +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; + +@ExtendWith(MockitoExtension.class) +class LibraryFileHelperTest { + @TempDir + Path tempDir; + + @Mock + private LibraryFileProcessor processor; + + @Test + void testGetLibraryFiles_HandlesInaccessibleDirectories() throws IOException { + LibraryFileHelper libraryFileHelper = new LibraryFileHelper(); + + Files.createFile(tempDir.resolve("happy.epub")); + Files.createDirectory(tempDir.resolve("some_other_random_named_dir"), PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("---------"))); + Files.createFile(tempDir.resolve("zzzz_happ.epub")); + + LibraryPathEntity libraryPath = new LibraryPathEntity(); + libraryPath.setId(10L); + libraryPath.setPath(tempDir.toString()); + + LibraryEntity testLibrary = LibraryEntity.builder() + .name("Test Library") + .icon("book") + .scanMode(LibraryScanMode.FILE_AS_BOOK) + .watch(false) + .libraryPaths(List.of(libraryPath)) + .build(); + + List libraryFiles = libraryFileHelper.getLibraryFiles(testLibrary, processor); + assertEquals(libraryFiles.stream().map(LibraryFile::getFileName).sorted().toList(), List.of("happy.epub", "zzzz_happ.epub")); + } +} \ No newline at end of file diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/BookCoverServiceTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/BookCoverServiceTest.java index 7c1e41db1..d75a0f277 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/BookCoverServiceTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/BookCoverServiceTest.java @@ -2,14 +2,14 @@ package com.adityachandel.booklore.service.metadata; import com.adityachandel.booklore.exception.ApiError; import com.adityachandel.booklore.mapper.BookMetadataMapper; -import com.adityachandel.booklore.model.dto.BookMetadata; +import com.adityachandel.booklore.model.dto.settings.AppSettings; import com.adityachandel.booklore.model.dto.settings.MetadataPersistenceSettings; import com.adityachandel.booklore.model.entity.AuthorEntity; import com.adityachandel.booklore.model.entity.BookEntity; import com.adityachandel.booklore.model.entity.BookMetadataEntity; import com.adityachandel.booklore.model.enums.BookFileType; -import com.adityachandel.booklore.model.websocket.Topic; import com.adityachandel.booklore.repository.BookRepository; +import com.adityachandel.booklore.repository.projection.BookCoverUpdateProjection; import com.adityachandel.booklore.service.NotificationService; import com.adityachandel.booklore.service.appsettings.AppSettingService; import com.adityachandel.booklore.service.book.BookQueryService; @@ -26,11 +26,13 @@ import org.mockito.*; import org.springframework.transaction.support.TransactionTemplate; import org.springframework.web.multipart.MultipartFile; -import java.time.Instant; -import java.util.*; import java.nio.file.Path; +import java.util.List; +import java.util.Optional; +import java.util.Set; -import static org.assertj.core.api.Assertions.*; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.*; class BookCoverServiceTest { @@ -67,94 +69,115 @@ class BookCoverServiceTest { return book; } - @Test - void generateCustomCover_success() { - BookEntity book = mockBookEntity(1L, false); - when(bookRepository.findById(1L)).thenReturn(Optional.of(book)); - when(coverImageGenerator.generateCover(any(), any())).thenReturn(new byte[]{1,2,3}); - doNothing().when(fileService).createThumbnailFromBytes(eq(1L), any()); - when(bookRepository.save(any())).thenReturn(book); - - bookCoverService.generateCustomCover(1L); - - verify(fileService).createThumbnailFromBytes(eq(1L), any()); - verify(bookRepository).save(book); - verify(notificationService).sendMessage(eq(Topic.BOOKS_COVER_UPDATE), any()); - } - @Test void generateCustomCover_coverLocked_throws() { BookEntity book = mockBookEntity(2L, true); when(bookRepository.findById(2L)).thenReturn(Optional.of(book)); + when(bookRepository.findAllWithMetadataByIds(any())).thenReturn(List.of(book)); + when(appSettingService.getAppSettings()).thenReturn(mockAppSettings(true, false)); assertThatThrownBy(() -> bookCoverService.generateCustomCover(2L)) .isInstanceOf(ApiError.METADATA_LOCKED.createException().getClass()); } @Test - void updateCoverImageFromFile_success() { + void updateCoverFromFile_success() { MultipartFile file = mock(MultipartFile.class); - BookEntity book = mockBookEntity(3L, false); - when(bookRepository.findAllWithMetadataByIds(any())).thenReturn(List.of(book)); + BookEntity book = spy(mockBookEntity(3L, false)); + doReturn(Path.of("/dummy/path")).when(book).getFullFilePath(); + when(bookRepository.findById(3L)).thenReturn(Optional.of(book)); when(bookRepository.save(any())).thenReturn(book); when(appSettingService.getAppSettings()).thenReturn(mockAppSettings(true, false)); - when(bookMetadataMapper.toBookMetadata(any(), eq(true))).thenReturn(new BookMetadata()); - BookMetadata result = bookCoverService.updateCoverImageFromFile(3L, file); + MetadataWriter writer = mock(MetadataWriter.class); + when(metadataWriterFactory.getWriter(any())).thenReturn(Optional.of(writer)); - verify(fileService).createThumbnailFromFile(3L, file); - assertThat(result).isNotNull(); + BookCoverUpdateProjection projection = mock(BookCoverUpdateProjection.class); + when(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of(projection)); + + try (MockedStatic fingerprintMock = mockStatic(FileFingerprint.class)) { + fingerprintMock.when(() -> FileFingerprint.generateHash(any())).thenReturn("dummyhash"); + bookCoverService.updateCoverFromFile(3L, file); + + verify(fileService).createThumbnailFromFile(3L, file); + } } @Test - void updateCoverImageFromUrl_success() { + void updateCoverFromUrl_success() { String url = "http://test.com/cover.jpg"; - BookEntity book = mockBookEntity(4L, false); - when(bookRepository.findAllWithMetadataByIds(any())).thenReturn(List.of(book)); + BookEntity book = spy(mockBookEntity(4L, false)); + doReturn(Path.of("/dummy/path")).when(book).getFullFilePath(); + when(bookRepository.findById(4L)).thenReturn(Optional.of(book)); when(bookRepository.save(any())).thenReturn(book); when(appSettingService.getAppSettings()).thenReturn(mockAppSettings(true, false)); - when(bookMetadataMapper.toBookMetadata(any(), eq(true))).thenReturn(new BookMetadata()); - BookMetadata result = bookCoverService.updateCoverImageFromUrl(4L, url); + MetadataWriter writer = mock(MetadataWriter.class); + when(metadataWriterFactory.getWriter(any())).thenReturn(Optional.of(writer)); - verify(fileService).createThumbnailFromUrl(4L, url); - assertThat(result).isNotNull(); + BookCoverUpdateProjection projection = mock(BookCoverUpdateProjection.class); + when(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of(projection)); + + try (MockedStatic fingerprintMock = mockStatic(FileFingerprint.class)) { + fingerprintMock.when(() -> FileFingerprint.generateHash(any())).thenReturn("dummyhash"); + bookCoverService.updateCoverFromUrl(4L, url); + + verify(fileService).createThumbnailFromUrl(4L, url); + } } @Test - void updateCoverImageFromFileForBooks_success() throws Exception { + void updateCoverFromFileForBooks_success() throws Exception { try (MockedStatic ignored = mockStatic(SecurityContextVirtualThread.class)) { MultipartFile file = mock(MultipartFile.class); when(file.isEmpty()).thenReturn(false); when(file.getContentType()).thenReturn("image/jpeg"); doReturn(new byte[]{1,2,3}).when(file).getBytes(); - BookEntity book = mockBookEntity(5L, false); + BookEntity book = spy(mockBookEntity(5L, false)); + doReturn(Path.of("/dummy/path")).when(book).getFullFilePath(); when(bookQueryService.findAllWithMetadataByIds(any())).thenReturn(List.of(book)); when(bookRepository.findById(5L)).thenReturn(Optional.of(book)); when(bookRepository.save(any())).thenReturn(book); - + when(appSettingService.getAppSettings()).thenReturn(mockAppSettings(true, false)); doNothing().when(fileService).createThumbnailFromBytes(eq(5L), any()); + doNothing().when(notificationService).sendMessage(any(), any()); - ignored.when(() -> SecurityContextVirtualThread.runWithSecurityContext(any(Runnable.class))) - .thenAnswer(invocation -> { - Runnable runnable = invocation.getArgument(0); - runnable.run(); - return null; - }); + MetadataWriter writer = mock(MetadataWriter.class); + when(metadataWriterFactory.getWriter(any())).thenReturn(Optional.of(writer)); - bookCoverService.updateCoverImageFromFileForBooks(Set.of(5L), file); + BookCoverUpdateProjection projection = mock(BookCoverUpdateProjection.class); + when(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of(projection)); - ArgumentCaptor idCaptor = ArgumentCaptor.forClass(Long.class); - verify(fileService).createThumbnailFromBytes(idCaptor.capture(), any()); - assertThat(idCaptor.getValue()).isEqualTo(5L); - verify(bookRepository).save(any(BookEntity.class)); + when(transactionTemplate.execute(any())).thenAnswer(invocation -> { + org.springframework.transaction.support.TransactionCallback callback = invocation.getArgument(0); + return callback.doInTransaction(null); + }); + + try (MockedStatic fingerprintMock = mockStatic(FileFingerprint.class)) { + fingerprintMock.when(() -> FileFingerprint.generateHash(any())).thenReturn("dummyhash"); + + ignored.when(() -> SecurityContextVirtualThread.runWithSecurityContext(any(Runnable.class))) + .thenAnswer(invocation -> { + Runnable runnable = invocation.getArgument(0); + runnable.run(); + return null; + }); + + bookCoverService.updateCoverFromFileForBooks(Set.of(5L), file); + + ArgumentCaptor idCaptor = ArgumentCaptor.forClass(Long.class); + verify(fileService).createThumbnailFromBytes(idCaptor.capture(), any()); + assertThat(idCaptor.getValue()).isEqualTo(5L); + verify(bookRepository).save(any(BookEntity.class)); + verify(notificationService, atLeastOnce()).sendMessage(any(), any()); + } } } @Test - void updateCoverImageFromFileForBooks_invalidFile_throws() { + void updateCoverFromFileForBooks_invalidFile_throws() { MultipartFile file = mock(MultipartFile.class); when(file.isEmpty()).thenReturn(true); - assertThatThrownBy(() -> bookCoverService.updateCoverImageFromFileForBooks(Set.of(6L), file)) + assertThatThrownBy(() -> bookCoverService.updateCoverFromFileForBooks(Set.of(6L), file)) .isInstanceOf(ApiError.INVALID_INPUT.createException("dummy").getClass()); } @@ -162,6 +185,7 @@ class BookCoverServiceTest { void regenerateCover_success() { BookEntity book = mockBookEntity(7L, false); when(bookRepository.findById(7L)).thenReturn(Optional.of(book)); + when(bookRepository.findAllWithMetadataByIds(any())).thenReturn(List.of(book)); BookFileProcessor processor = mock(BookFileProcessor.class); when(processorRegistry.getProcessorOrThrow(any())).thenReturn(processor); when(processor.generateCover(any())).thenReturn(true); @@ -177,6 +201,7 @@ class BookCoverServiceTest { void regenerateCover_coverLocked_throws() { BookEntity book = mockBookEntity(8L, true); when(bookRepository.findById(8L)).thenReturn(Optional.of(book)); + when(bookRepository.findAllWithMetadataByIds(any())).thenReturn(List.of(book)); assertThatThrownBy(() -> bookCoverService.regenerateCover(8L)) .isInstanceOf(ApiError.METADATA_LOCKED.createException().getClass()); } @@ -186,11 +211,21 @@ class BookCoverServiceTest { try (MockedStatic ignored = mockStatic(SecurityContextVirtualThread.class)) { BookEntity book = mockBookEntity(9L, false); when(bookQueryService.findAllWithMetadataByIds(any())).thenReturn(List.of(book)); + when(bookRepository.findById(9L)).thenReturn(Optional.of(book)); + when(bookRepository.save(any())).thenReturn(book); + BookFileProcessor processor = mock(BookFileProcessor.class); when(processorRegistry.getProcessorOrThrow(any())).thenReturn(processor); when(processor.generateCover(any())).thenReturn(true); - when(bookRepository.findById(9L)).thenReturn(Optional.of(book)); - when(bookRepository.save(any())).thenReturn(book); + + BookCoverUpdateProjection projection = mock(BookCoverUpdateProjection.class); + when(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of(projection)); + doNothing().when(notificationService).sendMessage(any(), any()); + + when(transactionTemplate.execute(any())).thenAnswer(invocation -> { + org.springframework.transaction.support.TransactionCallback callback = invocation.getArgument(0); + return callback.doInTransaction(null); + }); ignored.when(() -> SecurityContextVirtualThread.runWithSecurityContext(any(Runnable.class))) .thenAnswer(invocation -> { @@ -204,6 +239,7 @@ class BookCoverServiceTest { ArgumentCaptor bookCaptor = ArgumentCaptor.forClass(BookEntity.class); verify(processor).generateCover(bookCaptor.capture()); assertThat(bookCaptor.getValue().getId()).isEqualTo(9L); + verify(notificationService, atLeastOnce()).sendMessage(any(), any()); } } @@ -212,40 +248,34 @@ class BookCoverServiceTest { MultipartFile file = mock(MultipartFile.class); BookEntity book = spy(mockBookEntity(10L, false)); doReturn(Path.of("/dummy/path")).when(book).getFullFilePath(); - when(bookRepository.findAllWithMetadataByIds(any())).thenReturn(List.of(book)); + when(bookRepository.findById(10L)).thenReturn(Optional.of(book)); when(bookRepository.save(any())).thenReturn(book); when(appSettingService.getAppSettings()).thenReturn(mockAppSettings(true, false)); + MetadataWriter writer = mock(MetadataWriter.class); when(metadataWriterFactory.getWriter(any())).thenReturn(Optional.of(writer)); - when(bookMetadataMapper.toBookMetadata(any(), eq(true))).thenReturn(new BookMetadata()); + + BookCoverUpdateProjection projection = mock(BookCoverUpdateProjection.class); + when(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of(projection)); try (MockedStatic fingerprintMock = mockStatic(FileFingerprint.class)) { fingerprintMock.when(() -> FileFingerprint.generateHash(any())).thenReturn("dummyhash"); - BookMetadata result = bookCoverService.updateCoverImageFromFile(10L, file); + bookCoverService.updateCoverFromFile(10L, file); verify(writer).replaceCoverImageFromUpload(book, file); - assertThat(result).isNotNull(); } } - @Test - void updateCover_metadataPersistenceSettings_noSaveToOriginalFile() { - MultipartFile file = mock(MultipartFile.class); - BookEntity book = mockBookEntity(11L, false); - when(bookRepository.findAllWithMetadataByIds(any())).thenReturn(List.of(book)); - when(bookRepository.save(any())).thenReturn(book); - when(appSettingService.getAppSettings()).thenReturn(mockAppSettings(false, false)); - when(bookMetadataMapper.toBookMetadata(any(), eq(true))).thenReturn(new BookMetadata()); + private AppSettings mockAppSettings(boolean saveToOriginalFile, boolean convertCbrCb7ToCbz) { + MetadataPersistenceSettings.SaveToOriginalFile saveToOriginalFileObj = + MetadataPersistenceSettings.SaveToOriginalFile.builder() + .epub(MetadataPersistenceSettings.FormatSettings.builder().enabled(saveToOriginalFile).build()) + .pdf(MetadataPersistenceSettings.FormatSettings.builder().enabled(saveToOriginalFile).build()) + .cbx(MetadataPersistenceSettings.FormatSettings.builder().enabled(saveToOriginalFile).build()) + .build(); - BookMetadata result = bookCoverService.updateCoverImageFromFile(11L, file); - - verify(metadataWriterFactory, never()).getWriter(any()); - assertThat(result).isNotNull(); - } - - private com.adityachandel.booklore.model.dto.settings.AppSettings mockAppSettings(boolean saveToOriginalFile, boolean convertCbrCb7ToCbz) { MetadataPersistenceSettings settings = new MetadataPersistenceSettings(); - settings.setSaveToOriginalFile(saveToOriginalFile); + settings.setSaveToOriginalFile(saveToOriginalFileObj); settings.setConvertCbrCb7ToCbz(convertCbrCb7ToCbz); return new com.adityachandel.booklore.model.dto.settings.AppSettings() { @Override diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/BookMetadataUpdaterCategoryTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/BookMetadataUpdaterCategoryTest.java index f8b363c57..943ebe18c 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/BookMetadataUpdaterCategoryTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/BookMetadataUpdaterCategoryTest.java @@ -20,6 +20,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; import java.util.HashSet; @@ -32,17 +33,28 @@ import static org.mockito.Mockito.*; @ExtendWith(MockitoExtension.class) class BookMetadataUpdaterCategoryTest { - @Mock private AuthorRepository authorRepository; - @Mock private CategoryRepository categoryRepository; - @Mock private MoodRepository moodRepository; - @Mock private TagRepository tagRepository; - @Mock private BookRepository bookRepository; - @Mock private FileService fileService; - @Mock private MetadataMatchService metadataMatchService; - @Mock private AppSettingService appSettingService; - @Mock private MetadataWriterFactory metadataWriterFactory; - @Mock private BookReviewUpdateService bookReviewUpdateService; - @Mock private FileMoveService fileMoveService; + @Mock + private AuthorRepository authorRepository; + @Mock + private CategoryRepository categoryRepository; + @Mock + private MoodRepository moodRepository; + @Mock + private TagRepository tagRepository; + @Mock + private BookRepository bookRepository; + @Mock + private FileService fileService; + @Mock + private MetadataMatchService metadataMatchService; + @Mock + private AppSettingService appSettingService; + @Mock + private MetadataWriterFactory metadataWriterFactory; + @Mock + private BookReviewUpdateService bookReviewUpdateService; + @Mock + private FileMoveService fileMoveService; @InjectMocks private BookMetadataUpdater bookMetadataUpdater; @@ -50,7 +62,13 @@ class BookMetadataUpdaterCategoryTest { @BeforeEach void setUp() { AppSettings appSettings = new AppSettings(); - appSettings.setMetadataPersistenceSettings(new MetadataPersistenceSettings()); + MetadataPersistenceSettings persistenceSettings = new MetadataPersistenceSettings(); + + MetadataPersistenceSettings.SaveToOriginalFile saveToOriginalFile = Mockito.mock(MetadataPersistenceSettings.SaveToOriginalFile.class); + when(saveToOriginalFile.isAnyFormatEnabled()).thenReturn(false); + persistenceSettings.setSaveToOriginalFile(saveToOriginalFile); + + appSettings.setMetadataPersistenceSettings(persistenceSettings); lenient().when(appSettingService.getAppSettings()).thenReturn(appSettings); lenient().when(categoryRepository.findByName(anyString())).thenAnswer(invocation -> { @@ -59,8 +77,9 @@ class BookMetadataUpdaterCategoryTest { }); lenient().when(categoryRepository.save(any(CategoryEntity.class))).thenAnswer(invocation -> - invocation.getArgument(0)); + invocation.getArgument(0)); } + @Test void replaceAll_withMergeFalse_shouldClearAndAddNew() { BookEntity bookEntity = createBookWithCategories("Old1", "Old2"); @@ -303,7 +322,7 @@ class BookMetadataUpdaterCategoryTest { bookMetadataUpdater.setBookMetadata(context); assertTrue(bookEntity.getMetadata().getCategories().isEmpty(), - "BUG REPRODUCED: Empty array cleared all categories"); + "BUG REPRODUCED: Empty array cleared all categories"); } @Test @@ -392,4 +411,5 @@ class BookMetadataUpdaterCategoryTest { private boolean containsCategory(Set categories, String name) { return categories.stream().anyMatch(c -> c.getName().equals(name)); } -} \ No newline at end of file +} + diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/BookMetadataUpdaterTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/BookMetadataUpdaterTest.java index 93812d7de..33218b3bc 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/BookMetadataUpdaterTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/BookMetadataUpdaterTest.java @@ -20,6 +20,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; import java.util.Collections; @@ -33,17 +34,28 @@ import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) class BookMetadataUpdaterTest { - @Mock private AuthorRepository authorRepository; - @Mock private CategoryRepository categoryRepository; - @Mock private MoodRepository moodRepository; - @Mock private TagRepository tagRepository; - @Mock private BookRepository bookRepository; - @Mock private FileService fileService; - @Mock private MetadataMatchService metadataMatchService; - @Mock private AppSettingService appSettingService; - @Mock private MetadataWriterFactory metadataWriterFactory; - @Mock private BookReviewUpdateService bookReviewUpdateService; - @Mock private FileMoveService fileMoveService; + @Mock + private AuthorRepository authorRepository; + @Mock + private CategoryRepository categoryRepository; + @Mock + private MoodRepository moodRepository; + @Mock + private TagRepository tagRepository; + @Mock + private BookRepository bookRepository; + @Mock + private FileService fileService; + @Mock + private MetadataMatchService metadataMatchService; + @Mock + private AppSettingService appSettingService; + @Mock + private MetadataWriterFactory metadataWriterFactory; + @Mock + private BookReviewUpdateService bookReviewUpdateService; + @Mock + private FileMoveService fileMoveService; @InjectMocks private BookMetadataUpdater bookMetadataUpdater; @@ -51,7 +63,13 @@ class BookMetadataUpdaterTest { @BeforeEach void setUp() { AppSettings appSettings = new AppSettings(); - appSettings.setMetadataPersistenceSettings(new MetadataPersistenceSettings()); + MetadataPersistenceSettings persistenceSettings = new MetadataPersistenceSettings(); + + MetadataPersistenceSettings.SaveToOriginalFile saveToOriginalFile = Mockito.mock(MetadataPersistenceSettings.SaveToOriginalFile.class); + when(saveToOriginalFile.isAnyFormatEnabled()).thenReturn(false); + persistenceSettings.setSaveToOriginalFile(saveToOriginalFile); + + appSettings.setMetadataPersistenceSettings(persistenceSettings); when(appSettingService.getAppSettings()).thenReturn(appSettings); } @@ -60,7 +78,7 @@ class BookMetadataUpdaterTest { BookEntity bookEntity = new BookEntity(); bookEntity.setId(1L); BookMetadataEntity metadataEntity = new BookMetadataEntity(); - + Set existingTags = new HashSet<>(); existingTags.add(TagEntity.builder().name("Tag1").build()); existingTags.add(TagEntity.builder().name("Tag2").build()); @@ -120,12 +138,13 @@ class BookMetadataUpdaterTest { assertTrue(bookEntity.getMetadata().getTags().isEmpty(), "All tags should be cleared when incoming set is empty"); } + @Test void setBookMetadata_withMergeTagsTrue_shouldMergeTags() { BookEntity bookEntity = new BookEntity(); bookEntity.setId(1L); BookMetadataEntity metadataEntity = new BookMetadataEntity(); - + Set existingTags = new HashSet<>(); existingTags.add(TagEntity.builder().name("Tag1").build()); existingTags.add(TagEntity.builder().name("Tag2").build()); @@ -157,6 +176,7 @@ class BookMetadataUpdaterTest { assertTrue(bookEntity.getMetadata().getTags().stream().anyMatch(t -> t.getName().equals("Tag2"))); assertTrue(bookEntity.getMetadata().getTags().stream().anyMatch(t -> t.getName().equals("Tag3"))); } + @Test void setBookMetadata_withMergeMoodsFalse_shouldReplaceMoods() { BookEntity bookEntity = new BookEntity(); diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/extractor/CbxMetadataExtractorTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/extractor/CbxMetadataExtractorTest.java index 6b1c2c575..fb91db26e 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/extractor/CbxMetadataExtractorTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/extractor/CbxMetadataExtractorTest.java @@ -83,7 +83,6 @@ class CbxMetadataExtractorTest { assertEquals(Integer.valueOf(42), md.getPageCount()); assertEquals("en", md.getLanguage()); assertTrue(md.getAuthors().contains("Alice")); - assertTrue(md.getAuthors().contains("Bob")); assertTrue(md.getCategories().contains("action")); assertTrue(md.getCategories().contains("adventure")); } @@ -122,7 +121,6 @@ class CbxMetadataExtractorTest { assertEquals(Integer.valueOf(42), md.getPageCount()); assertEquals("en", md.getLanguage()); assertTrue(md.getAuthors().contains("Alice")); - assertTrue(md.getAuthors().contains("Bob")); assertTrue(md.getCategories().contains("action")); assertTrue(md.getCategories().contains("adventure")); } diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/extractor/ComicInfoParsingIssuesTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/extractor/ComicInfoParsingIssuesTest.java index 71a81cce3..8d7f453ed 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/extractor/ComicInfoParsingIssuesTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/extractor/ComicInfoParsingIssuesTest.java @@ -73,7 +73,6 @@ class ComicInfoParsingIssuesTest { assertEquals(Integer.valueOf(1964), metadata.getPublishedDate().getYear()); assertEquals("Marvel", metadata.getPublisher()); assertTrue(metadata.getAuthors().contains("Stan Lee")); - assertTrue(metadata.getAuthors().contains("Joe Orlando")); } @Test @@ -160,10 +159,6 @@ class ComicInfoParsingIssuesTest { assertEquals("Special anniversary issue", metadata.getDescription()); assertTrue(metadata.getAuthors().contains("Frank Miller")); - assertTrue(metadata.getAuthors().contains("John Romita Jr.")); - assertTrue(metadata.getAuthors().contains("Scott Hanna")); - assertTrue(metadata.getAuthors().contains("Steve Oliff")); - assertTrue(metadata.getAuthors().contains("Joe Rosen")); assertTrue(metadata.getCategories().contains("Marvel")); assertTrue(metadata.getCategories().contains("Daredevil")); diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/extractor/ExtractFromComicInfoXmlTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/extractor/ExtractFromComicInfoXmlTest.java new file mode 100644 index 000000000..0edfbb738 --- /dev/null +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/extractor/ExtractFromComicInfoXmlTest.java @@ -0,0 +1,881 @@ +package com.adityachandel.booklore.service.metadata.extractor; + +import com.adityachandel.booklore.model.dto.BookMetadata; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.LocalDate; + +import static org.junit.jupiter.api.Assertions.*; + +class ExtractFromComicInfoXmlTest { + + private CbxMetadataExtractor extractor; + + @TempDir + Path tempDir; + + @BeforeEach + void setUp() { + extractor = new CbxMetadataExtractor(); + } + + @Test + void testExtractFromComicInfoXml_ValidXml_AllFields() throws IOException { + String xml = """ + + + Batman: The Dark Knight Returns + Batman: The Dark Knight Returns + 1 + 4 + 1 + 1986 + 3 + 15 + DC Comics + Batman comes out of retirement to fight crime in Gotham City. + Frank Miller + Superhero, Crime + Batman, DC, Frank Miller + 48 + en + + """; + + File xmlFile = createXmlFile("valid_all_fields.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertEquals("Batman: The Dark Knight Returns", metadata.getTitle()); + assertEquals("Batman: The Dark Knight Returns (1)", metadata.getSeriesName()); + assertEquals(1.0f, metadata.getSeriesNumber()); + assertEquals(4, metadata.getSeriesTotal()); + assertEquals(LocalDate.of(1986, 3, 15), metadata.getPublishedDate()); + assertEquals("DC Comics", metadata.getPublisher()); + assertEquals("Batman comes out of retirement to fight crime in Gotham City.", metadata.getDescription()); + assertEquals(48, metadata.getPageCount()); + assertEquals("en", metadata.getLanguage()); + + // Verify authors + assertTrue(metadata.getAuthors().contains("Frank Miller")); + + // Verify categories + assertTrue(metadata.getCategories().contains("Superhero")); + assertTrue(metadata.getCategories().contains("Crime")); + assertTrue(metadata.getCategories().contains("Batman")); + assertTrue(metadata.getCategories().contains("DC")); + assertTrue(metadata.getCategories().contains("Frank Miller")); + } + + @Test + void testExtractFromComicInfoXml_MinimalXml() throws IOException { + String xml = """ + + Simple Comic + + """; + + File xmlFile = createXmlFile("minimal.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertEquals("Simple Comic", metadata.getTitle()); + assertNull(metadata.getSeriesName()); + assertNull(metadata.getSeriesNumber()); + assertNull(metadata.getSeriesTotal()); + assertNull(metadata.getPublishedDate()); + assertNull(metadata.getPublisher()); + assertNull(metadata.getDescription()); + assertNull(metadata.getPageCount()); + assertNull(metadata.getLanguage()); + } + + @Test + void testExtractFromComicInfoXml_NoTitle_UsesFallback() throws IOException { + String xml = """ + + Mystery Series + 5 + + """; + + Path parentDir = tempDir.resolve("comic_folder"); + Files.createDirectories(parentDir); + File xmlFile = createXmlFileInDir(parentDir, "no_title.xml", xml); + + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertEquals("comic_folder", metadata.getTitle()); + assertEquals("Mystery Series", metadata.getSeriesName()); + assertEquals(5.0f, metadata.getSeriesNumber()); + } + + @Test + void testExtractFromComicInfoXml_EmptyTitle_UsesFallback() throws IOException { + String xml = """ + + + Empty Title Series + + """; + + Path parentDir = tempDir.resolve("empty_title_comic"); + Files.createDirectories(parentDir); + File xmlFile = createXmlFileInDir(parentDir, "empty_title.xml", xml); + + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertEquals("empty_title_comic", metadata.getTitle()); + } + + @Test + void testExtractFromComicInfoXml_WhitespaceTitle_UsesFallback() throws IOException { + String xml = """ + + + Whitespace Title Series + + """; + + Path parentDir = tempDir.resolve("whitespace_comic"); + Files.createDirectories(parentDir); + File xmlFile = createXmlFileInDir(parentDir, "whitespace_title.xml", xml); + + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertEquals("whitespace_comic", metadata.getTitle()); + } + + @Test + void testExtractFromComicInfoXml_SeriesWithoutVolume() throws IOException { + String xml = """ + + Test Comic + Test Series + 10 + + """; + + File xmlFile = createXmlFile("series_no_volume.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertEquals("Test Series", metadata.getSeriesName()); + assertEquals(10.0f, metadata.getSeriesNumber()); + } + + @Test + void testExtractFromComicInfoXml_SeriesWithVolume() throws IOException { + String xml = """ + + Test Comic + Test Series + 2 + 10 + + """; + + File xmlFile = createXmlFile("series_with_volume.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertEquals("Test Series (2)", metadata.getSeriesName()); + assertEquals(10.0f, metadata.getSeriesNumber()); + } + + @Test + void testExtractFromComicInfoXml_SeriesWithEmptyVolume() throws IOException { + String xml = """ + + Test Comic + Test Series + + 10 + + """; + + File xmlFile = createXmlFile("series_empty_volume.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertEquals("Test Series", metadata.getSeriesName()); + } + + @Test + void testExtractFromComicInfoXml_FloatingPointNumber() throws IOException { + String xml = """ + + Test Comic + Test Series + 10.5 + + """; + + File xmlFile = createXmlFile("floating_number.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertEquals(10.5f, metadata.getSeriesNumber()); + } + + @Test + void testExtractFromComicInfoXml_InvalidNumberFormat() throws IOException { + String xml = """ + + Test Comic + Test Series + not-a-number + also-not-a-number + invalid + + """; + + File xmlFile = createXmlFile("invalid_numbers.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertNull(metadata.getSeriesNumber()); + assertNull(metadata.getSeriesTotal()); + assertNull(metadata.getPageCount()); + } + + @Test + void testExtractFromComicInfoXml_DateWithYearOnly() throws IOException { + String xml = """ + + Test Comic + 2020 + + """; + + File xmlFile = createXmlFile("date_year_only.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertEquals(LocalDate.of(2020, 1, 1), metadata.getPublishedDate()); + } + + @Test + void testExtractFromComicInfoXml_DateWithYearAndMonth() throws IOException { + String xml = """ + + Test Comic + 2020 + 6 + + """; + + File xmlFile = createXmlFile("date_year_month.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertEquals(LocalDate.of(2020, 6, 1), metadata.getPublishedDate()); + } + + @Test + void testExtractFromComicInfoXml_InvalidDate() throws IOException { + String xml = """ + + Test Comic + 2020 + 13 + 32 + + """; + + File xmlFile = createXmlFile("invalid_date.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertNull(metadata.getPublishedDate()); + } + + @Test + void testExtractFromComicInfoXml_MultipleAuthors_CommaSeparated() throws IOException { + String xml = """ + + Test Comic + John Doe, Jane Smith + + """; + + File xmlFile = createXmlFile("multiple_authors_comma.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertTrue(metadata.getAuthors().contains("John Doe")); + assertTrue(metadata.getAuthors().contains("Jane Smith")); + } + + @Test + void testExtractFromComicInfoXml_MultipleAuthors_SemicolonSeparated() throws IOException { + String xml = """ + + Test Comic + John Doe; Jane Smith + + """; + + File xmlFile = createXmlFile("multiple_authors_semicolon.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertTrue(metadata.getAuthors().contains("John Doe")); + assertTrue(metadata.getAuthors().contains("Jane Smith")); + } + + @Test + void testExtractFromComicInfoXml_MultipleCategories() throws IOException { + String xml = """ + + Test Comic + Action, Adventure, Sci-Fi + robots; space; future + + """; + + File xmlFile = createXmlFile("multiple_categories.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertTrue(metadata.getCategories().contains("Action")); + assertTrue(metadata.getCategories().contains("Adventure")); + assertTrue(metadata.getCategories().contains("Sci-Fi")); + assertTrue(metadata.getCategories().contains("robots")); + assertTrue(metadata.getCategories().contains("space")); + assertTrue(metadata.getCategories().contains("future")); + } + + @Test + void testExtractFromComicInfoXml_DescriptionFromSummary() throws IOException { + String xml = """ + + Test Comic + This is a summary + + """; + + File xmlFile = createXmlFile("description_summary.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertEquals("This is a summary", metadata.getDescription()); + } + + @Test + void testExtractFromComicInfoXml_DescriptionFromDescription() throws IOException { + String xml = """ + + Test Comic + This is a description + + """; + + File xmlFile = createXmlFile("description_description.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertEquals("This is a description", metadata.getDescription()); + } + + @Test + void testExtractFromComicInfoXml_SummaryPreferredOverDescription() throws IOException { + String xml = """ + + Test Comic + Summary text + Description text + + """; + + File xmlFile = createXmlFile("summary_and_description.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertEquals("Summary text", metadata.getDescription()); + } + + @Test + void testExtractFromComicInfoXml_PageCountFromPageCount() throws IOException { + String xml = """ + + Test Comic + 32 + + """; + + File xmlFile = createXmlFile("pagecount_field.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertEquals(32, metadata.getPageCount()); + } + + @Test + void testExtractFromComicInfoXml_PageCountFromPages() throws IOException { + String xml = """ + + Test Comic + 48 + + """; + + File xmlFile = createXmlFile("pages_field.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertEquals(48, metadata.getPageCount()); + } + + @Test + void testExtractFromComicInfoXml_SpecialCharactersInFields() throws IOException { + String xml = """ + + Test & Verify: "Special" Characters + Series <Test> + O'Brien & Associates + A story with "quotes" and <tags> + + """; + + File xmlFile = createXmlFile("special_characters.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertEquals("Test & Verify: \"Special\" Characters", metadata.getTitle()); + assertEquals("Series ", metadata.getSeriesName()); + assertTrue(metadata.getAuthors().contains("O'Brien & Associates")); + assertEquals("A story with \"quotes\" and ", metadata.getDescription()); + } + + @Test + void testExtractFromComicInfoXml_MalformedXml_ReturnsFallbackMetadata() throws IOException { + String xml = "Unclosed Tag"; + + File xmlFile = createXmlFile("malformed.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + // Should return fallback title (parent directory name or file name) + assertNotNull(metadata.getTitle()); + } + + @Test + void testExtractFromComicInfoXml_EmptyXml_ReturnsFallbackMetadata() throws IOException { + String xml = ""; + + File xmlFile = createXmlFile("empty.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertNotNull(metadata.getTitle()); + } + + @Test + void testExtractFromComicInfoXml_InvalidXmlContent_ReturnsFallbackMetadata() throws IOException { + String xml = "This is not XML at all!"; + + File xmlFile = createXmlFile("not_xml.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertNotNull(metadata.getTitle()); + } + + @Test + void testExtractFromComicInfoXml_XmlWithNamespace() throws IOException { + String xml = """ + <?xml version="1.0" encoding="UTF-8"?> + <ComicInfo xmlns="http://example.com/schema"> + <Title>Namespaced Comic + Namespace Series + 1 + + """; + + File xmlFile = createXmlFile("with_namespace.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + // With namespace awareness enabled, should extract correctly + assertNotNull(metadata); + assertEquals("Namespaced Comic", metadata.getTitle()); + assertEquals("Namespace Series", metadata.getSeriesName()); + assertEquals(1.0f, metadata.getSeriesNumber()); + } + + @Test + void testExtractFromComicInfoXml_XXEAttackPrevention() throws IOException { + String xxeXml = """ + + + ]> + + &xxe; + + """; + + Path parentDir = tempDir.resolve("xxe_attack"); + File xmlFile = new File(parentDir.toFile(), "ComicInfo.xml"); + Files.createDirectories(parentDir); + Files.writeString(xmlFile.toPath(), xxeXml, StandardCharsets.UTF_8); + + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + // XXE protection should prevent parsing and return fallback metadata + assertNotNull(metadata); + assertEquals("xxe_attack", metadata.getTitle()); // Fallback to filename + // Should not contain any resolved entity content + assertFalse(metadata.getTitle().contains("&xxe;")); + assertFalse(metadata.getTitle().contains("root:")); + } + + @Test + void testExtractFromComicInfoXml_BillionLaughsAttackPrevention() throws IOException { + String billionLaughsXml = """ + + + + + ]> + + &lol3; + + """; + + File xmlFile = createXmlFile("billion_laughs.xml", billionLaughsXml); + + // Should fail fast, not hang or consume excessive memory + assertDoesNotThrow(() -> { + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + assertNotNull(metadata); + }); + } + + @Test + void testExtractFromComicInfoXml_NegativeNumbers() throws IOException { + String xml = """ + + Test + -5 + -10 + -32 + + """; + + File xmlFile = createXmlFile("negative_numbers.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + // Document behavior: negative numbers are parsed but may not be meaningful + assertNotNull(metadata); + assertEquals(-5.0f, metadata.getSeriesNumber()); + assertEquals(-10, metadata.getSeriesTotal()); + assertEquals(-32, metadata.getPageCount()); + } + + @Test + void testExtractFromComicInfoXml_VeryLargeNumbers() throws IOException { + String xml = """ + + Test + 999999999999999 + 2147483648 + + """; + + File xmlFile = createXmlFile("large_numbers.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertNotNull(metadata.getSeriesNumber()); + // PageCount overflows Integer.MAX_VALUE, parseInteger returns null + assertNull(metadata.getPageCount()); + } + + @Test + void testExtractFromComicInfoXml_EmptyXmlFile() throws IOException { + Path parentDir = tempDir.resolve("empty"); + Files.createDirectories(parentDir); + File xmlFile = new File(parentDir.toFile(), "ComicInfo.xml"); + Files.writeString(xmlFile.toPath(), "", StandardCharsets.UTF_8); + + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + // Should return fallback metadata, not crash + assertNotNull(metadata); + assertEquals("empty", metadata.getTitle()); + } + + @Test + void testExtractFromComicInfoXml_VeryLongStrings() throws IOException { + String longTitle = "A".repeat(10000); + String longDescription = "B".repeat(10000); + + String xml = String.format(""" + + %s + %s + + """, longTitle, longDescription); + + File xmlFile = createXmlFile("long_strings.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertEquals(longTitle, metadata.getTitle()); + assertEquals(longDescription, metadata.getDescription()); + } + + @Test + void testExtractFromComicInfoXml_FileDoesNotExist_ReturnsFallbackMetadata() { + Path parentDir = tempDir.resolve("does_not_exist"); + File nonExistentFile = new File(parentDir.toFile(), "ComicInfo.xml"); + + BookMetadata metadata = extractor.extractFromComicInfoXml(nonExistentFile); + + assertNotNull(metadata); + assertEquals("does_not_exist", metadata.getTitle()); + } + + @ParameterizedTest + @CsvSource({ + "2020,,,2020-01-01", + "2020,6,,2020-06-01", + "2020,3,15,2020-03-15", + "2020,13,32," // Invalid + }) + void testExtractFromComicInfoXml_DateParsing(String year, String month, String day, String expected) throws IOException { + String xml = String.format(""" + + Date Test + %s%s%s + + """, + year != null ? "" + year + "" : "", + month != null ? "" + month + "" : "", + day != null ? "" + day + "" : "" + ); + + File xmlFile = createXmlFile("date_test.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + if (expected != null && !expected.isBlank()) { + assertEquals(LocalDate.parse(expected), metadata.getPublishedDate()); + } else { + assertNull(metadata.getPublishedDate()); + } + } + + @Test + void testExtractFromComicInfoXml_NullInput_ThrowsIllegalArgumentException() { + IllegalArgumentException exception = assertThrows( + IllegalArgumentException.class, + () -> extractor.extractFromComicInfoXml(null) + ); + assertEquals("XML file cannot be null", exception.getMessage()); + } + + @Test + void testExtractFromComicInfoXml_CompleteMetadata_AllFieldsPopulated() throws IOException { + String xml = """ + + + Batman: The Dark Knight Returns + Batman: The Dark Knight Returns + 1 + 4 + 1 + 1986 + 3 + 15 + DC Comics + Batman comes out of retirement to fight crime in Gotham City. + Frank Miller + Frank Miller + Klaus Janson + Lynn Varley + John Costanza + Frank Miller + Superhero, Crime + Batman, DC, Frank Miller + 48 + en + + """; + + File xmlFile = createXmlFile("complete_metadata.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertEquals("Batman: The Dark Knight Returns", metadata.getTitle()); + assertEquals("Batman: The Dark Knight Returns (1)", metadata.getSeriesName()); + assertEquals(1.0f, metadata.getSeriesNumber()); + assertEquals(4, metadata.getSeriesTotal()); + assertEquals(LocalDate.of(1986, 3, 15), metadata.getPublishedDate()); + assertEquals("DC Comics", metadata.getPublisher()); + assertEquals("Batman comes out of retirement to fight crime in Gotham City.", metadata.getDescription()); + assertEquals(48, metadata.getPageCount()); + assertEquals("en", metadata.getLanguage()); + + // Verify authors + assertTrue(metadata.getAuthors().contains("Frank Miller")); + + // Verify categories + assertTrue(metadata.getCategories().contains("Superhero")); + assertTrue(metadata.getCategories().contains("Crime")); + assertTrue(metadata.getCategories().contains("Batman")); + assertTrue(metadata.getCategories().contains("DC")); + assertTrue(metadata.getCategories().contains("Frank Miller")); + } + + @Test + void testExtractFromComicInfoXml_XmlWithComments() throws IOException { + String xml = """ + + + Comic With Comments + + Comment Series + + """; + + File xmlFile = createXmlFile("with_comments.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertEquals("Comic With Comments", metadata.getTitle()); + assertEquals("Comment Series", metadata.getSeriesName()); + } + + @Test + void testExtractFromComicInfoXml_LeadingAndTrailingWhitespace() throws IOException { + String xml = """ + + Trimmed Title + Trimmed Series + Writer Name + + """; + + File xmlFile = createXmlFile("with_whitespace.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertEquals("Trimmed Title", metadata.getTitle()); + assertEquals("Trimmed Series", metadata.getSeriesName()); + assertTrue(metadata.getAuthors().contains("Writer Name")); + } + + @Test + void testExtractFromComicInfoXml_DuplicateAuthors_RemovedBySet() throws IOException { + String xml = """ + + Test Comic + Frank Miller + Frank Miller + Frank Miller + + """; + + File xmlFile = createXmlFile("duplicate_authors.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertEquals(1, metadata.getAuthors().size()); + assertTrue(metadata.getAuthors().contains("Frank Miller")); + } + + @Test + void testExtractFromComicInfoXml_NoAuthors_AuthorsNull() throws IOException { + String xml = """ + + Test Comic + Test Series + + """; + + File xmlFile = createXmlFile("no_authors.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + // If no authors, the set should be null or empty + assertTrue(metadata.getAuthors() == null || metadata.getAuthors().isEmpty()); + } + + @Test + void testExtractFromComicInfoXml_NoCategories_CategoriesNull() throws IOException { + String xml = """ + + Test Comic + Test Series + + """; + + File xmlFile = createXmlFile("no_categories.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertTrue(metadata.getCategories() == null || metadata.getCategories().isEmpty()); + } + + @Test + void testExtractFromComicInfoXml_FileInRootDirectory() throws IOException { + String xml = """ + + Root Comic + + """; + + // Create file directly in tempDir (no parent directory) + File xmlFile = createXmlFile("root_comic.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertEquals("Root Comic", metadata.getTitle()); + } + + @Test + void testExtractFromComicInfoXml_ZeroValues() throws IOException { + String xml = """ + + Test + 0 + 0 + 0 + + """; + + File xmlFile = createXmlFile("zero_values.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertEquals(0.0f, metadata.getSeriesNumber()); + assertEquals(0, metadata.getSeriesTotal()); + assertEquals(0, metadata.getPageCount()); + } + + // Helper methods + + private File createXmlFile(String filename, String content) throws IOException { + return createXmlFileInDir(tempDir, filename, content); + } + + private File createXmlFileInDir(Path dir, String filename, String content) throws IOException { + Path xmlPath = dir.resolve(filename); + Files.writeString(xmlPath, content, StandardCharsets.UTF_8); + return xmlPath.toFile(); + } +} diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/writer/CbxMetadataWriterTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/writer/CbxMetadataWriterTest.java index 587dbd701..395d3375e 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/writer/CbxMetadataWriterTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/writer/CbxMetadataWriterTest.java @@ -1,13 +1,17 @@ package com.adityachandel.booklore.service.metadata.writer; import com.adityachandel.booklore.model.MetadataClearFlags; +import com.adityachandel.booklore.model.dto.settings.AppSettings; +import com.adityachandel.booklore.model.dto.settings.MetadataPersistenceSettings; import com.adityachandel.booklore.model.entity.AuthorEntity; import com.adityachandel.booklore.model.entity.BookMetadataEntity; import com.adityachandel.booklore.model.entity.CategoryEntity; import com.adityachandel.booklore.model.enums.BookFileType; +import com.adityachandel.booklore.service.appsettings.AppSettingService; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.mockito.Mockito; import org.w3c.dom.Document; import javax.xml.XMLConstants; @@ -36,7 +40,19 @@ class CbxMetadataWriterTest { @BeforeEach void setup() throws Exception { - writer = new CbxMetadataWriter(); + AppSettingService appSettingService = Mockito.mock(AppSettingService.class); + AppSettings settings = new AppSettings(); + MetadataPersistenceSettings persistence = new MetadataPersistenceSettings(); + MetadataPersistenceSettings.SaveToOriginalFile save = new MetadataPersistenceSettings.SaveToOriginalFile(); + MetadataPersistenceSettings.FormatSettings cbx = new MetadataPersistenceSettings.FormatSettings(); + cbx.setEnabled(true); + cbx.setMaxFileSizeInMb(100); + save.setCbx(cbx); + persistence.setSaveToOriginalFile(save); + settings.setMetadataPersistenceSettings(persistence); + Mockito.when(appSettingService.getAppSettings()).thenReturn(settings); + + writer = new CbxMetadataWriter(appSettingService); tempDir = Files.createTempDirectory("cbx_writer_test_"); } @@ -45,7 +61,12 @@ class CbxMetadataWriterTest { if (tempDir != null) { Files.walk(tempDir) .sorted(Comparator.reverseOrder()) - .forEach(p -> { try { Files.deleteIfExists(p); } catch (Exception ignore) {} }); + .forEach(p -> { + try { + Files.deleteIfExists(p); + } catch (Exception ignore) { + } + }); } } @@ -55,7 +76,7 @@ class CbxMetadataWriterTest { } @Test - void writeMetadataToFile_cbz_updatesOrCreatesComicInfo_andPreservesOtherFiles() throws Exception { + void saveMetadataToFile_cbz_updatesOrCreatesComicInfo_andPreservesOtherFiles() throws Exception { // Create a CBZ without ComicInfo.xml and with a couple of images File cbz = createCbz(tempDir.resolve("sample.cbz"), new String[]{ "images/002.jpg", "images/001.jpg" @@ -69,7 +90,7 @@ class CbxMetadataWriterTest { meta.setSeriesName("Series X"); meta.setSeriesNumber(2.5f); meta.setSeriesTotal(12); - meta.setPublishedDate(LocalDate.of(2020,7,14)); + meta.setPublishedDate(LocalDate.of(2020, 7, 14)); meta.setPageCount(42); meta.setLanguage("en"); @@ -95,7 +116,7 @@ class CbxMetadataWriterTest { meta.setCategories(cats); // Execute - writer.writeMetadataToFile(cbz, meta, null, new MetadataClearFlags()); + writer.saveMetadataToFile(cbz, meta, null, new MetadataClearFlags()); // Assert ComicInfo.xml exists and contains our fields try (ZipFile zip = new ZipFile(cbz)) { @@ -144,7 +165,7 @@ class CbxMetadataWriterTest { } @Test - void writeMetadataToFile_cbz_updatesExistingComicInfo() throws Exception { + void saveMetadataToFile_cbz_updatesExistingComicInfo() throws Exception { // Create a CBZ *with* an existing ComicInfo.xml Path out = tempDir.resolve("with_meta.cbz"); String xml = """ @@ -161,7 +182,7 @@ class CbxMetadataWriterTest { meta.setTitle("New Title"); meta.setDescription("New Summary"); - writer.writeMetadataToFile(out.toFile(), meta, null, new MetadataClearFlags()); + writer.saveMetadataToFile(out.toFile(), meta, null, new MetadataClearFlags()); try (ZipFile zip = new ZipFile(out.toFile())) { ZipEntry ci = zip.getEntry("ComicInfo.xml"); @@ -178,7 +199,7 @@ class CbxMetadataWriterTest { private static File createCbz(Path path, String[] imageNames) throws Exception { try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(path.toFile()))) { for (String name : imageNames) { - put(zos, name, new byte[]{1,2,3}); + put(zos, name, new byte[]{1, 2, 3}); } } return path.toFile(); diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/writer/EpubMetadataWriterTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/writer/EpubMetadataWriterTest.java index c7b6f87e1..97c179e67 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/writer/EpubMetadataWriterTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/writer/EpubMetadataWriterTest.java @@ -1,10 +1,13 @@ package com.adityachandel.booklore.service.metadata.writer; import com.adityachandel.booklore.model.MetadataClearFlags; +import com.adityachandel.booklore.model.dto.settings.AppSettings; +import com.adityachandel.booklore.model.dto.settings.MetadataPersistenceSettings; import com.adityachandel.booklore.model.entity.AuthorEntity; import com.adityachandel.booklore.model.entity.BookEntity; import com.adityachandel.booklore.model.entity.BookMetadataEntity; import com.adityachandel.booklore.model.entity.LibraryPathEntity; +import com.adityachandel.booklore.service.appsettings.AppSettingService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; @@ -13,33 +16,48 @@ import org.junit.jupiter.api.io.TempDir; import org.springframework.mock.web.MockMultipartFile; import org.springframework.web.multipart.MultipartFile; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.InputStream; -import java.io.IOException; +import java.io.*; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collections; -import java.util.zip.ZipFile; import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; import java.util.zip.ZipOutputStream; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; class EpubMetadataWriterTest { private EpubMetadataWriter writer; private BookMetadataEntity metadata; private BookEntity bookEntity; + private AppSettingService appSettingService; @TempDir Path tempDir; @BeforeEach void setUp() { - writer = new EpubMetadataWriter(); + appSettingService = mock(AppSettingService.class); + MetadataPersistenceSettings.FormatSettings epubFormatSettings = MetadataPersistenceSettings.FormatSettings.builder() + .enabled(true) + .maxFileSizeInMb(100) + .build(); + MetadataPersistenceSettings.SaveToOriginalFile saveToOriginalFile = MetadataPersistenceSettings.SaveToOriginalFile.builder() + .epub(epubFormatSettings) + .build(); + MetadataPersistenceSettings metadataPersistenceSettings = new MetadataPersistenceSettings(); + metadataPersistenceSettings.setSaveToOriginalFile(saveToOriginalFile); + + AppSettings appSettings = mock(AppSettings.class); + when(appSettings.getMetadataPersistenceSettings()).thenReturn(metadataPersistenceSettings); + when(appSettingService.getAppSettings()).thenReturn(appSettings); + + writer = new EpubMetadataWriter(appSettingService); metadata = new BookMetadataEntity(); metadata.setTitle("Test Book"); AuthorEntity author = new AuthorEntity(); @@ -66,14 +84,14 @@ class EpubMetadataWriterTest { existingMetadata.append("ill"); existingMetadata.append(""); String opfContent = String.format(""" - - - %s - - """, existingMetadata); + + + %s + + """, existingMetadata); File epubFile = createEpubWithOpf(opfContent, "test-metadata-" + System.nanoTime() + ".epub"); - assertDoesNotThrow(() -> writer.writeMetadataToFile(epubFile, metadata, null, new MetadataClearFlags())); + assertDoesNotThrow(() -> writer.saveMetadataToFile(epubFile, metadata, null, new MetadataClearFlags())); assertTrue(epubFile.exists()); assertTrue(epubFile.length() > 0); @@ -99,7 +117,7 @@ class EpubMetadataWriterTest { File epubFile = tempDir.resolve("test_unicode.epub").toFile(); Files.write(epubFile.toPath(), epubContent); - assertDoesNotThrow(() -> writer.writeMetadataToFile(epubFile, metadata, null, new MetadataClearFlags())); + assertDoesNotThrow(() -> writer.saveMetadataToFile(epubFile, metadata, null, new MetadataClearFlags())); assertTrue(epubFile.exists()); assertTrue(epubFile.length() > 0); @@ -114,10 +132,10 @@ class EpubMetadataWriterTest { byte[] imageBytes = createMinimalPngImage(); MultipartFile coverFile = new MockMultipartFile( - "cover.png", - "cover.png", - "image/png", - imageBytes + "cover.png", + "cover.png", + "image/png", + imageBytes ); assertDoesNotThrow(() -> writer.replaceCoverImageFromUpload(bookEntity, coverFile)); @@ -128,13 +146,13 @@ class EpubMetadataWriterTest { File epubFile = tempDir.resolve(filename).toFile(); String containerXml = """ - - - - - - - """; + + + + + + + """; try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(epubFile))) { zos.putNextEntry(new ZipEntry("mimetype")); @@ -155,67 +173,67 @@ class EpubMetadataWriterTest { private byte[] createEpubWithUnicodeCoverHref() throws IOException { String opfContent = """ - - - - Test Book with Unicode Cover - Test Author - - - - - - - - - - - - """; + + + + Test Book with Unicode Cover + Test Author + + + + + + + + + + + + """; String containerXml = """ - - - - - - - """; + + + + + + + """; String htmlContent = """ - - - - - Test - - -

Test Content

- - - """; + + + + + Test + + +

Test Content

+ + + """; String ncxContent = """ - - - - - - - - Test Book - - - - - Test - - - - - - """; + + + + + + + + Test Book + + + + + Test + + + + + + """; byte[] coverImage = createMinimalPngImage(); @@ -253,22 +271,23 @@ class EpubMetadataWriterTest { private byte[] createMinimalPngImage() { return new byte[]{ - (byte) 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, - 0x00, 0x00, 0x00, 0x0D, - 0x49, 0x48, 0x44, 0x52, - 0x00, 0x00, 0x00, 0x01, - 0x00, 0x00, 0x00, 0x01, - 0x08, 0x06, - 0x00, 0x00, 0x00, - (byte) 0x90, (byte) 0x77, (byte) 0x53, (byte) 0xDE, - 0x00, 0x00, 0x00, 0x0A, - 0x49, 0x44, 0x41, 0x54, - 0x78, (byte) 0x9C, 0x63, 0x00, 0x01, 0x00, 0x00, 0x05, - 0x00, 0x01, - 0x0D, (byte) 0x0A, 0x2D, (byte) 0xB4, - 0x00, 0x00, 0x00, 0x00, - 0x49, 0x45, 0x4E, 0x44, - (byte) 0xAE, 0x42, 0x60, (byte) 0x82 + (byte) 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, + 0x00, 0x00, 0x00, 0x0D, + 0x49, 0x48, 0x44, 0x52, + 0x00, 0x00, 0x00, 0x01, + 0x00, 0x00, 0x00, 0x01, + 0x08, 0x06, + 0x00, 0x00, 0x00, + (byte) 0x90, (byte) 0x77, (byte) 0x53, (byte) 0xDE, + 0x00, 0x00, 0x00, 0x0A, + 0x49, 0x44, 0x41, 0x54, + 0x78, (byte) 0x9C, 0x63, 0x00, 0x01, 0x00, 0x00, 0x05, + 0x00, 0x01, + 0x0D, (byte) 0x0A, 0x2D, (byte) 0xB4, + 0x00, 0x00, 0x00, 0x00, + 0x49, 0x45, 0x4E, 0x44, + (byte) 0xAE, 0x42, 0x60, (byte) 0x82 }; } -} \ No newline at end of file +} + diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/reader/CbxReaderServiceTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/reader/CbxReaderServiceTest.java index 61da7c925..fc936e828 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/service/reader/CbxReaderServiceTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/reader/CbxReaderServiceTest.java @@ -1,6 +1,8 @@ package com.adityachandel.booklore.service.reader; +import com.adityachandel.booklore.exception.APIException; import com.adityachandel.booklore.model.dto.settings.AppSettings; +import com.adityachandel.booklore.exception.ApiError; import com.adityachandel.booklore.model.entity.BookEntity; import com.adityachandel.booklore.model.entity.LibraryPathEntity; import com.adityachandel.booklore.repository.BookRepository; @@ -167,6 +169,22 @@ class CbxReaderServiceTest { "Page count should be exactly 130 (actual comic pages only)"); } + @Test + void getAvailablePages_whenArchiveIsCorrupt_shouldThrowFileReadError() throws IOException { + Path corruptCbz = tempDir.resolve("corrupt.cbz"); + Files.writeString(corruptCbz, "This is not a zip file"); + + testBook.setFileName(corruptCbz.getFileName().toString()); + testBook.getLibraryPath().setPath(tempDir.toString()); + + APIException exception = assertThrows(APIException.class, () -> service.getAvailablePages(bookId)); + + assertNotEquals(ApiError.CACHE_TOO_LARGE.getMessage(), exception.getMessage(), + "Should not throw CACHE_TOO_LARGE for a corrupt file"); + assertTrue(exception.getMessage().startsWith("Error reading files from path"), + "Should throw FILE_READ_ERROR (message starts with 'Error reading files from path'), actual: '" + exception.getMessage() + "'"); + } + private void createTestCbzWithMacOsFiles(File cbzFile) throws IOException { try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(cbzFile))) { for (int i = 1; i <= 130; i++) { diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/util/FileServiceTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/util/FileServiceTest.java index 0773060a5..76265458b 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/util/FileServiceTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/util/FileServiceTest.java @@ -15,9 +15,6 @@ import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; -import org.springframework.core.io.ClassPathResource; -import org.springframework.core.io.FileSystemResource; -import org.springframework.core.io.Resource; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; @@ -64,7 +61,7 @@ class FileServiceTest { .coverCroppingSettings(coverCroppingSettings) .build(); lenient().when(appSettingService.getAppSettings()).thenReturn(appSettings); - + fileService = new FileService(appProperties, mock(RestTemplate.class), appSettingService, mock(BookMetadataRepository.class)); } @@ -165,12 +162,12 @@ class FileServiceTest { static Stream truncateTestCases() { return Stream.of( - Arguments.of("hello world", 5, "hello"), - Arguments.of("test", 10, "test"), - Arguments.of("abc", 3, "abc"), - Arguments.of("ab", 3, "ab"), - Arguments.of("a", 1, "a"), - Arguments.of("newline\ntest", 7, "newline") + Arguments.of("hello world", 5, "hello"), + Arguments.of("test", 10, "test"), + Arguments.of("abc", 3, "abc"), + Arguments.of("ab", 3, "ab"), + Arguments.of("a", 1, "a"), + Arguments.of("newline\ntest", 7, "newline") ); } } @@ -191,11 +188,11 @@ class FileServiceTest { @Test void returnsCorrectPath() { String result = fileService.getImagesFolder(123L); - + assertAll( - () -> assertTrue(result.contains("images")), - () -> assertTrue(result.contains("123")), - () -> assertTrue(result.startsWith(tempDir.toString())) + () -> assertTrue(result.contains("images")), + () -> assertTrue(result.contains("123")), + () -> assertTrue(result.startsWith(tempDir.toString())) ); } @@ -214,10 +211,10 @@ class FileServiceTest { @Test void returnsCorrectPath() { String result = fileService.getThumbnailFile(456L); - + assertAll( - () -> assertTrue(result.contains("456")), - () -> assertTrue(result.endsWith("thumbnail.jpg")) + () -> assertTrue(result.contains("456")), + () -> assertTrue(result.endsWith("thumbnail.jpg")) ); } } @@ -229,10 +226,10 @@ class FileServiceTest { @Test void returnsCorrectPath() { String result = fileService.getCoverFile(789L); - + assertAll( - () -> assertTrue(result.contains("789")), - () -> assertTrue(result.endsWith("cover.jpg")) + () -> assertTrue(result.contains("789")), + () -> assertTrue(result.endsWith("cover.jpg")) ); } } @@ -244,20 +241,20 @@ class FileServiceTest { @Test void withUserId_returnsUserSpecificPath() { String result = fileService.getBackgroundsFolder(42L); - + assertAll( - () -> assertTrue(result.contains("backgrounds")), - () -> assertTrue(result.contains("user-42")) + () -> assertTrue(result.contains("backgrounds")), + () -> assertTrue(result.contains("user-42")) ); } @Test void withNullUserId_returnsGlobalPath() { String result = fileService.getBackgroundsFolder(null); - + assertAll( - () -> assertTrue(result.contains("backgrounds")), - () -> assertFalse(result.contains("user-")) + () -> assertTrue(result.contains("backgrounds")), + () -> assertFalse(result.contains("user-")) ); } @@ -265,7 +262,7 @@ class FileServiceTest { void noArgs_delegatesToNullUserId() { String withNull = fileService.getBackgroundsFolder(null); String noArgs = fileService.getBackgroundsFolder(); - + assertEquals(withNull, noArgs); } } @@ -277,24 +274,24 @@ class FileServiceTest { @Test void withUserId_returnsCorrectUrl() { String result = FileService.getBackgroundUrl("bg.jpg", 10L); - + assertAll( - () -> assertTrue(result.startsWith("/")), - () -> assertTrue(result.contains("backgrounds")), - () -> assertTrue(result.contains("user-10")), - () -> assertTrue(result.endsWith("bg.jpg")), - () -> assertFalse(result.contains("\\"), "Should use forward slashes") + () -> assertTrue(result.startsWith("/")), + () -> assertTrue(result.contains("backgrounds")), + () -> assertTrue(result.contains("user-10")), + () -> assertTrue(result.endsWith("bg.jpg")), + () -> assertFalse(result.contains("\\"), "Should use forward slashes") ); } @Test void withoutUserId_returnsGlobalUrl() { String result = FileService.getBackgroundUrl("bg.jpg", null); - + assertAll( - () -> assertFalse(result.contains("user-")), - () -> assertTrue(result.contains("backgrounds")), - () -> assertFalse(result.contains("\\")) + () -> assertFalse(result.contains("user-")), + () -> assertTrue(result.contains("backgrounds")), + () -> assertFalse(result.contains("\\")) ); } @@ -312,10 +309,10 @@ class FileServiceTest { @Test void getBookMetadataBackupPath_returnsCorrectPath() { String result = fileService.getBookMetadataBackupPath(100L); - + assertAll( - () -> assertTrue(result.contains("metadata_backup")), - () -> assertTrue(result.contains("100")) + () -> assertTrue(result.contains("metadata_backup")), + () -> assertTrue(result.contains("100")) ); } @@ -332,20 +329,20 @@ class FileServiceTest { @Test void getTempBookdropCoverImagePath_returnsCorrectPath() { String result = fileService.getTempBookdropCoverImagePath(555L); - + assertAll( - () -> assertTrue(result.contains("bookdrop_temp")), - () -> assertTrue(result.endsWith("555.jpg")) + () -> assertTrue(result.contains("bookdrop_temp")), + () -> assertTrue(result.endsWith("555.jpg")) ); } @Test void getToolsKepubifyPath_returnsCorrectPath() { String result = fileService.getToolsKepubifyPath(); - + assertAll( - () -> assertTrue(result.contains("tools")), - () -> assertTrue(result.contains("kepubify")) + () -> assertTrue(result.contains("tools")), + () -> assertTrue(result.contains("kepubify")) ); } } @@ -355,6 +352,40 @@ class FileServiceTest { @DisplayName("Image Operations") class ImageOperationsTests { + @Nested + @DisplayName("readImage") + class ReadImageTests { + @Test + void validData_returnsImage() throws IOException { + BufferedImage image = createTestImage(100, 100); + byte[] imageData = imageToBytes(image); + + BufferedImage result = FileService.readImage(imageData); + + assertNotNull(result); + assertEquals(100, result.getWidth()); + assertEquals(100, result.getHeight()); + } + + @Test + void nullData_throwsException() { + IOException ex = assertThrows(IOException.class, () -> FileService.readImage((byte[]) null)); + assertEquals("Image data is null or empty", ex.getMessage()); + } + + @Test + void emptyData_throwsException() { + IOException ex = assertThrows(IOException.class, () -> FileService.readImage(new byte[0])); + assertEquals("Image data is null or empty", ex.getMessage()); + } + + @Test + void invalidData_returnsNull() throws IOException { + byte[] invalidData = "not an image".getBytes(); + assertNull(FileService.readImage(invalidData)); + } + } + @Nested @DisplayName("resizeImage") class ResizeImageTests { @@ -362,70 +393,70 @@ class FileServiceTest { @Test void shrinks_imageProperly() { BufferedImage original = createTestImage(100, 100); - + BufferedImage resized = FileService.resizeImage(original, 50, 50); - + assertAll( - () -> assertEquals(50, resized.getWidth()), - () -> assertEquals(50, resized.getHeight()) + () -> assertEquals(50, resized.getWidth()), + () -> assertEquals(50, resized.getHeight()) ); } @Test void enlarges_imageProperly() { BufferedImage original = createTestImage(50, 50); - + BufferedImage resized = FileService.resizeImage(original, 200, 200); - + assertAll( - () -> assertEquals(200, resized.getWidth()), - () -> assertEquals(200, resized.getHeight()) + () -> assertEquals(200, resized.getWidth()), + () -> assertEquals(200, resized.getHeight()) ); } @Test void changesAspectRatio() { BufferedImage original = createTestImage(100, 100); - + BufferedImage resized = FileService.resizeImage(original, 200, 50); - + assertAll( - () -> assertEquals(200, resized.getWidth()), - () -> assertEquals(50, resized.getHeight()) + () -> assertEquals(200, resized.getWidth()), + () -> assertEquals(50, resized.getHeight()) ); } @Test void sameSize_worksCorrectly() { BufferedImage original = createTestImage(100, 100); - + BufferedImage resized = FileService.resizeImage(original, 100, 100); - + assertAll( - () -> assertEquals(100, resized.getWidth()), - () -> assertEquals(100, resized.getHeight()), - () -> assertNotSame(original, resized) + () -> assertEquals(100, resized.getWidth()), + () -> assertEquals(100, resized.getHeight()), + () -> assertNotSame(original, resized) ); } @Test void returnsRGBType() { BufferedImage original = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB); - + BufferedImage resized = FileService.resizeImage(original, 50, 50); - + assertEquals(BufferedImage.TYPE_INT_RGB, resized.getType()); } @Test void handlesVerySmallDimensions() { BufferedImage original = createTestImage(100, 100); - + BufferedImage resized = FileService.resizeImage(original, 1, 1); - + assertAll( - () -> assertEquals(1, resized.getWidth()), - () -> assertEquals(1, resized.getHeight()) + () -> assertEquals(1, resized.getWidth()), + () -> assertEquals(1, resized.getHeight()) ); } } @@ -439,12 +470,12 @@ class FileServiceTest { BufferedImage image = createTestImage(100, 100); byte[] imageData = imageToBytes(image); Path outputPath = tempDir.resolve("test-output.jpg"); - + FileService.saveImage(imageData, outputPath.toString()); - + assertAll( - () -> assertTrue(Files.exists(outputPath)), - () -> assertTrue(Files.size(outputPath) > 0) + () -> assertTrue(Files.exists(outputPath)), + () -> assertTrue(Files.size(outputPath) > 0) ); } @@ -453,19 +484,20 @@ class FileServiceTest { BufferedImage image = createTestImage(100, 100); byte[] imageData = imageToBytes(image); Path outputPath = tempDir.resolve("nested/deep/folder/test.jpg"); - + FileService.saveImage(imageData, outputPath.toString()); - + assertTrue(Files.exists(outputPath)); } @Test - void invalidImageData_throwsException() { + void invalidImageData_skipsSave() { byte[] invalidData = "not an image".getBytes(); Path outputPath = tempDir.resolve("invalid.jpg"); - assertThrows(IOException.class, () -> - FileService.saveImage(invalidData, outputPath.toString())); + assertDoesNotThrow(() -> + FileService.saveImage(invalidData, outputPath.toString())); + assertFalse(Files.exists(outputPath)); } @Test @@ -473,8 +505,9 @@ class FileServiceTest { byte[] emptyData = new byte[0]; Path outputPath = tempDir.resolve("empty.jpg"); - assertThrows(IOException.class, () -> - FileService.saveImage(emptyData, outputPath.toString())); + IOException ex = assertThrows(IOException.class, () -> + FileService.saveImage(emptyData, outputPath.toString())); + assertEquals("Image data is null or empty", ex.getMessage()); } @Test @@ -482,14 +515,14 @@ class FileServiceTest { BufferedImage original = createTestImage(100, 100); byte[] imageData = imageToBytes(original); Path outputPath = tempDir.resolve("readable.jpg"); - + FileService.saveImage(imageData, outputPath.toString()); BufferedImage loaded = ImageIO.read(outputPath.toFile()); - + assertAll( - () -> assertNotNull(loaded), - () -> assertEquals(100, loaded.getWidth()), - () -> assertEquals(100, loaded.getHeight()) + () -> assertNotNull(loaded), + () -> assertEquals(100, loaded.getWidth()), + () -> assertEquals(100, loaded.getHeight()) ); } @@ -499,15 +532,16 @@ class FileServiceTest { byte[] imageData = imageToBytes(image); Path nestedPath = tempDir.resolve("nested/deep/folder/test.jpg"); assertDoesNotThrow(() -> FileService.saveImage(imageData, nestedPath.toString()), - "Should create nested directories automatically"); + "Should create nested directories automatically"); assertTrue(Files.exists(nestedPath), "File should be created in nested directory"); } @Test void nullImageData_throwsException() { Path outputPath = tempDir.resolve("null.jpg"); - assertThrows(NullPointerException.class, () -> - FileService.saveImage(null, outputPath.toString())); + IOException ex = assertThrows(IOException.class, () -> + FileService.saveImage(null, outputPath.toString())); + assertEquals("Image data is null or empty", ex.getMessage()); } } } @@ -528,46 +562,46 @@ class FileServiceTest { @Test void createsBothCoverAndThumbnail() throws IOException { BufferedImage image = createTestImage(500, 700); - + boolean result = fileService.saveCoverImages(image, 1L); - + assertAll( - () -> assertTrue(result), - () -> assertTrue(Files.exists(Path.of(fileService.getCoverFile(1L)))), - () -> assertTrue(Files.exists(Path.of(fileService.getThumbnailFile(1L)))) + () -> assertTrue(result), + () -> assertTrue(Files.exists(Path.of(fileService.getCoverFile(1L)))), + () -> assertTrue(Files.exists(Path.of(fileService.getThumbnailFile(1L)))) ); } @Test void thumbnailHasCorrectDimensions() throws IOException { BufferedImage image = createTestImage(1000, 1400); - + fileService.saveCoverImages(image, 2L); - + BufferedImage thumbnail = ImageIO.read( - new File(fileService.getThumbnailFile(2L))); - + new File(fileService.getThumbnailFile(2L))); + assertAll( - () -> assertEquals(250, thumbnail.getWidth()), - () -> assertEquals(350, thumbnail.getHeight()) + () -> assertEquals(250, thumbnail.getWidth()), + () -> assertEquals(350, thumbnail.getHeight()) ); } @Test void convertsTransparentToOpaqueWithWhiteBackground() throws IOException { BufferedImage imageWithAlpha = new BufferedImage( - 100, 100, BufferedImage.TYPE_INT_ARGB); + 100, 100, BufferedImage.TYPE_INT_ARGB); Graphics2D g = imageWithAlpha.createGraphics(); g.setColor(new Color(255, 0, 0, 128)); // Semi-transparent red g.fillRect(0, 0, 100, 100); g.dispose(); - + boolean result = fileService.saveCoverImages(imageWithAlpha, 3L); - + assertTrue(result); - + BufferedImage saved = ImageIO.read( - new File(fileService.getCoverFile(3L))); + new File(fileService.getCoverFile(3L))); assertFalse(saved.getColorModel().hasAlpha(), "Saved image should not have transparency"); } @@ -575,25 +609,25 @@ class FileServiceTest { void createsDirectoryIfNotExists() throws IOException { BufferedImage image = createTestImage(100, 100); long bookId = 999L; - + fileService.saveCoverImages(image, bookId); - + assertTrue(Files.isDirectory( - Path.of(fileService.getImagesFolder(bookId)))); + Path.of(fileService.getImagesFolder(bookId)))); } @Test void originalMaintainsDimensions() throws IOException { BufferedImage image = createTestImage(800, 1200); - + fileService.saveCoverImages(image, 4L); - + BufferedImage saved = ImageIO.read( - new File(fileService.getCoverFile(4L))); - + new File(fileService.getCoverFile(4L))); + assertAll( - () -> assertEquals(800, saved.getWidth()), - () -> assertEquals(1200, saved.getHeight()) + () -> assertEquals(800, saved.getWidth()), + () -> assertEquals(1200, saved.getHeight()) ); } @@ -609,14 +643,14 @@ class FileServiceTest { assertTrue(result); BufferedImage savedCover = ImageIO.read( - new File(fileService.getCoverFile(5L))); + new File(fileService.getCoverFile(5L))); assertNotNull(savedCover); assertTrue(savedCover.getWidth() <= 1000, - "Cover width should be <= MAX_ORIGINAL_WIDTH (1000), was: " + savedCover.getWidth()); + "Cover width should be <= MAX_ORIGINAL_WIDTH (1000), was: " + savedCover.getWidth()); assertTrue(savedCover.getHeight() <= 1500, - "Cover height should be <= MAX_ORIGINAL_HEIGHT (1500), was: " + savedCover.getHeight()); + "Cover height should be <= MAX_ORIGINAL_HEIGHT (1500), was: " + savedCover.getHeight()); double originalRatio = (double) largeWidth / largeHeight; double savedRatio = (double) savedCover.getWidth() / savedCover.getHeight(); @@ -635,14 +669,14 @@ class FileServiceTest { assertTrue(result); BufferedImage savedCover = ImageIO.read( - new File(fileService.getCoverFile(6L))); + new File(fileService.getCoverFile(6L))); assertNotNull(savedCover); assertEquals(smallWidth, savedCover.getWidth(), - "Small image width should be preserved"); + "Small image width should be preserved"); assertEquals(smallHeight, savedCover.getHeight(), - "Small image height should be preserved"); + "Small image height should be preserved"); } } @@ -663,14 +697,14 @@ class FileServiceTest { assertTrue(result); BufferedImage savedCover = ImageIO.read( - new File(fileService.getCoverFile(100L))); + new File(fileService.getCoverFile(100L))); assertNotNull(savedCover); - + // The image should be cropped to approximately 1.5:1 ratio from the top double savedRatio = (double) savedCover.getHeight() / savedCover.getWidth(); - assertTrue(savedRatio < 3.0, - "Cropped image should have reasonable aspect ratio, was: " + savedRatio); + assertTrue(savedRatio < 3.0, + "Cropped image should have reasonable aspect ratio, was: " + savedRatio); } @Test @@ -686,14 +720,14 @@ class FileServiceTest { assertTrue(result); BufferedImage savedCover = ImageIO.read( - new File(fileService.getCoverFile(101L))); + new File(fileService.getCoverFile(101L))); assertNotNull(savedCover); - + // The image should be cropped to a more reasonable aspect ratio double savedRatio = (double) savedCover.getWidth() / savedCover.getHeight(); - assertTrue(savedRatio < 3.0, - "Cropped image should have reasonable aspect ratio, was: " + savedRatio); + assertTrue(savedRatio < 3.0, + "Cropped image should have reasonable aspect ratio, was: " + savedRatio); } @Test @@ -709,15 +743,15 @@ class FileServiceTest { assertTrue(result); BufferedImage savedCover = ImageIO.read( - new File(fileService.getCoverFile(102L))); + new File(fileService.getCoverFile(102L))); assertNotNull(savedCover); - + // The image should maintain its original aspect ratio double originalRatio = (double) height / width; double savedRatio = (double) savedCover.getHeight() / savedCover.getWidth(); - assertEquals(originalRatio, savedRatio, 0.01, - "Normal aspect ratio image should not be cropped"); + assertEquals(originalRatio, savedRatio, 0.01, + "Normal aspect ratio image should not be cropped"); } @Test @@ -744,15 +778,15 @@ class FileServiceTest { assertTrue(result); BufferedImage savedCover = ImageIO.read( - new File(fileService.getCoverFile(103L))); + new File(fileService.getCoverFile(103L))); assertNotNull(savedCover); - + // Since the image exceeds max dimensions, it will be scaled, but aspect ratio preserved double originalRatio = (double) height / width; double savedRatio = (double) savedCover.getHeight() / savedCover.getWidth(); - assertEquals(originalRatio, savedRatio, 0.01, - "Image should not be cropped when cropping is disabled"); + assertEquals(originalRatio, savedRatio, 0.01, + "Image should not be cropped when cropping is disabled"); } @Test @@ -878,41 +912,35 @@ class FileServiceTest { void validImageBytes_succeeds() throws IOException { BufferedImage image = createTestImage(300, 400); byte[] imageBytes = imageToBytes(image); - - assertDoesNotThrow(() -> - fileService.createThumbnailFromBytes(15L, imageBytes)); + + assertDoesNotThrow(() -> + fileService.createThumbnailFromBytes(15L, imageBytes)); assertTrue(Files.exists(Path.of(fileService.getCoverFile(15L)))); } @Test - void invalidImageBytes_throwsRuntimeException() { + void invalidImageBytes_skipsThumbnail() { byte[] invalidData = "not an image".getBytes(); - - RuntimeException exception = assertThrows(RuntimeException.class, () -> - fileService.createThumbnailFromBytes(16L, invalidData)); - assertTrue(exception.getMessage().contains("Image not found") || - exception.getMessage().contains("Failed"), - "Exception message should indicate image processing failure"); + + assertDoesNotThrow(() -> + fileService.createThumbnailFromBytes(16L, invalidData)); + assertFalse(Files.exists(Path.of(fileService.getCoverFile(16L)))); } @Test void emptyImageBytes_throwsRuntimeException() { byte[] emptyData = new byte[0]; - - // FileService wraps ImageIO exceptions in RuntimeException via ApiError + RuntimeException exception = assertThrows(RuntimeException.class, () -> - fileService.createThumbnailFromBytes(17L, emptyData)); - assertTrue(exception.getMessage().contains("Image not found") || - exception.getMessage().contains("Failed"), - "Exception message should indicate image processing failure"); + fileService.createThumbnailFromBytes(17L, emptyData)); + assertEquals("Error reading files from path: Image data is null or empty", exception.getMessage()); } @Test void nullImageBytes_throwsRuntimeException() { - // Null input causes NPE in ByteArrayInputStream constructor, which is caught and wrapped RuntimeException exception = assertThrows(RuntimeException.class, () -> - fileService.createThumbnailFromBytes(18L, null)); - assertNotNull(exception.getMessage(), "Exception should have a message"); + fileService.createThumbnailFromBytes(18L, null)); + assertEquals("Error reading files from path: Image data is null or empty", exception.getMessage()); } } @@ -925,10 +953,10 @@ class FileServiceTest { BufferedImage image = createTestImage(300, 400); byte[] imageBytes = imageToBytes(image); MockMultipartFile file = new MockMultipartFile( - "file", "test.jpg", "image/jpeg", imageBytes); - - assertDoesNotThrow(() -> - fileService.createThumbnailFromFile(5L, file)); + "file", "test.jpg", "image/jpeg", imageBytes); + + assertDoesNotThrow(() -> + fileService.createThumbnailFromFile(5L, file)); assertTrue(Files.exists(Path.of(fileService.getCoverFile(5L)))); } @@ -938,49 +966,49 @@ class FileServiceTest { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(image, "PNG", baos); MockMultipartFile file = new MockMultipartFile( - "file", "test.png", "image/png", baos.toByteArray()); - - assertDoesNotThrow(() -> - fileService.createThumbnailFromFile(6L, file)); + "file", "test.png", "image/png", baos.toByteArray()); + + assertDoesNotThrow(() -> + fileService.createThumbnailFromFile(6L, file)); } @Test void emptyFile_throwsRuntimeException() { MockMultipartFile emptyFile = new MockMultipartFile( - "file", "empty.jpg", "image/jpeg", new byte[0]); - + "file", "empty.jpg", "image/jpeg", new byte[0]); + // validateCoverFile throws IllegalArgumentException, but it's caught and wrapped in RuntimeException via ApiError RuntimeException exception = assertThrows(RuntimeException.class, () -> - fileService.createThumbnailFromFile(7L, emptyFile)); - assertTrue(exception.getMessage().contains("empty") || - exception.getCause() instanceof IllegalArgumentException, - "Exception message should indicate file is empty or wrap IllegalArgumentException"); + fileService.createThumbnailFromFile(7L, emptyFile)); + assertTrue(exception.getMessage().contains("empty") || + exception.getCause() instanceof IllegalArgumentException, + "Exception message should indicate file is empty or wrap IllegalArgumentException"); } @Test void invalidMimeType_throwsRuntimeException() { MockMultipartFile gifFile = new MockMultipartFile( - "file", "test.gif", "image/gif", "fake data".getBytes()); - + "file", "test.gif", "image/gif", "fake data".getBytes()); + RuntimeException exception = assertThrows(RuntimeException.class, () -> - fileService.createThumbnailFromFile(8L, gifFile)); + fileService.createThumbnailFromFile(8L, gifFile)); assertTrue(exception.getMessage().contains("Only JPEG and PNG files are allowed") || - exception.getCause() instanceof IllegalArgumentException, - "Exception message should indicate only JPEG and PNG are allowed or wrap IllegalArgumentException"); + exception.getCause() instanceof IllegalArgumentException, + "Exception message should indicate only JPEG and PNG are allowed or wrap IllegalArgumentException"); } @Test void fileTooLarge_throwsRuntimeException() { byte[] largeData = new byte[6 * 1024 * 1024]; // 6MB MockMultipartFile largeFile = new MockMultipartFile( - "file", "large.jpg", "image/jpeg", largeData); - + "file", "large.jpg", "image/jpeg", largeData); + // validateCoverFile throws IllegalArgumentException, but it's caught and wrapped in RuntimeException via ApiError RuntimeException exception = assertThrows(RuntimeException.class, () -> - fileService.createThumbnailFromFile(9L, largeFile)); + fileService.createThumbnailFromFile(9L, largeFile)); assertTrue(exception.getMessage().contains("5 MB") || - exception.getCause() instanceof IllegalArgumentException, - "Exception message should indicate file size limit or wrap IllegalArgumentException"); + exception.getCause() instanceof IllegalArgumentException, + "Exception message should indicate file size limit or wrap IllegalArgumentException"); } @Test @@ -989,12 +1017,12 @@ class FileServiceTest { byte[] imageBytes = imageToBytes(image); // Ensure it's under 5MB assertTrue(imageBytes.length < 5 * 1024 * 1024); - + MockMultipartFile file = new MockMultipartFile( - "file", "valid.jpg", "image/jpeg", imageBytes); - + "file", "valid.jpg", "image/jpeg", imageBytes); + assertDoesNotThrow(() -> - fileService.createThumbnailFromFile(10L, file)); + fileService.createThumbnailFromFile(10L, file)); } @Test @@ -1002,37 +1030,34 @@ class FileServiceTest { BufferedImage image = createTestImage(100, 100); byte[] imageBytes = imageToBytes(image); MockMultipartFile file = new MockMultipartFile( - "file", "test.jpg", "IMAGE/JPEG", imageBytes); + "file", "test.jpg", "IMAGE/JPEG", imageBytes); assertDoesNotThrow(() -> - fileService.createThumbnailFromFile(11L, file)); + fileService.createThumbnailFromFile(11L, file)); } @Test - void corruptImageData_throwsRuntimeException() { + void corruptImageData_skipsThumbnail() { // Valid MIME type but corrupt image data byte[] corruptData = ("not an image but has jpeg mime type").getBytes(); MockMultipartFile corruptFile = new MockMultipartFile( - "file", "corrupt.jpg", "image/jpeg", corruptData); + "file", "corrupt.jpg", "image/jpeg", corruptData); - // FileService wraps exceptions in RuntimeException via ApiError - RuntimeException exception = assertThrows(RuntimeException.class, () -> - fileService.createThumbnailFromFile(12L, corruptFile)); - assertTrue(exception.getMessage().contains("Image not found") || - exception.getMessage().contains("not readable"), - "Exception message should indicate image processing failure"); + assertDoesNotThrow(() -> + fileService.createThumbnailFromFile(12L, corruptFile)); + assertFalse(Files.exists(Path.of(fileService.getCoverFile(12L)))); } @Test void unsupportedMimeType_gif_throwsRuntimeException() { byte[] gifData = "GIF89a...".getBytes(); // Fake GIF header MockMultipartFile gifFile = new MockMultipartFile( - "file", "test.gif", "image/gif", gifData); + "file", "test.gif", "image/gif", gifData); // validateCoverFile throws IllegalArgumentException, but it's caught and wrapped in RuntimeException via ApiError assertThrows(RuntimeException.class, () -> - fileService.createThumbnailFromFile(13L, gifFile), - "Should throw RuntimeException (wrapping IllegalArgumentException) for unsupported MIME type"); + fileService.createThumbnailFromFile(13L, gifFile), + "Should throw RuntimeException (wrapping IllegalArgumentException) for unsupported MIME type"); } @Test @@ -1040,10 +1065,10 @@ class FileServiceTest { BufferedImage image = createTestImage(100, 100); byte[] imageBytes = imageToBytes(image); MockMultipartFile file = new MockMultipartFile( - "file", "test.jpg", "image/jpeg;charset=UTF-8", imageBytes); + "file", "test.jpg", "image/jpeg;charset=UTF-8", imageBytes); assertDoesNotThrow(() -> - fileService.createThumbnailFromFile(14L, file)); + fileService.createThumbnailFromFile(14L, file)); } } @@ -1055,11 +1080,11 @@ class FileServiceTest { void setsTimestampToCurrentTime() { BookMetadataEntity entity = new BookMetadataEntity(); Instant before = Instant.now(); - + FileService.setBookCoverPath(entity); - + Instant after = Instant.now(); - + assertNotNull(entity.getCoverUpdatedOn()); assertFalse(entity.getCoverUpdatedOn().isBefore(before)); assertFalse(entity.getCoverUpdatedOn().isAfter(after)); @@ -1070,9 +1095,9 @@ class FileServiceTest { BookMetadataEntity entity = new BookMetadataEntity(); Instant oldTime = Instant.parse("2020-01-01T00:00:00Z"); entity.setCoverUpdatedOn(oldTime); - + FileService.setBookCoverPath(entity); - + assertNotEquals(oldTime, entity.getCoverUpdatedOn()); } } @@ -1086,36 +1111,36 @@ class FileServiceTest { BufferedImage image = createTestImage(100, 100); fileService.saveCoverImages(image, 10L); fileService.saveCoverImages(image, 11L); - + fileService.deleteBookCovers(Set.of(10L, 11L)); - + assertAll( - () -> assertFalse(Files.exists( - Path.of(fileService.getImagesFolder(10L)))), - () -> assertFalse(Files.exists( - Path.of(fileService.getImagesFolder(11L)))) + () -> assertFalse(Files.exists( + Path.of(fileService.getImagesFolder(10L)))), + () -> assertFalse(Files.exists( + Path.of(fileService.getImagesFolder(11L)))) ); } @Test void nonExistentCovers_doesNotThrow() { assertDoesNotThrow(() -> - fileService.deleteBookCovers(Set.of(999L, 1000L))); + fileService.deleteBookCovers(Set.of(999L, 1000L))); } @Test void emptySet_doesNothing() { assertDoesNotThrow(() -> - fileService.deleteBookCovers(Set.of())); + fileService.deleteBookCovers(Set.of())); } @Test void mixedExistingAndNonExisting_deletesExisting() throws Exception { BufferedImage image = createTestImage(100, 100); fileService.saveCoverImages(image, 20L); - + fileService.deleteBookCovers(Set.of(20L, 21L)); - + assertFalse(Files.exists(Path.of(fileService.getImagesFolder(20L)))); } @@ -1123,9 +1148,9 @@ class FileServiceTest { void singleBookId_works() throws IOException { BufferedImage image = createTestImage(100, 100); fileService.saveCoverImages(image, 30L); - + fileService.deleteBookCovers(Set.of(30L)); - + assertFalse(Files.exists(Path.of(fileService.getImagesFolder(30L)))); } } @@ -1146,7 +1171,7 @@ class FileServiceTest { @BeforeEach void setup() { lenient().when(appProperties.getPathConfig()).thenReturn(tempDir.toString()); - + CoverCroppingSettings coverCroppingSettings = CoverCroppingSettings.builder() .verticalCroppingEnabled(true) .horizontalCroppingEnabled(true) @@ -1156,7 +1181,7 @@ class FileServiceTest { .coverCroppingSettings(coverCroppingSettings) .build(); lenient().when(appSettingServiceForNetwork.getAppSettings()).thenReturn(appSettings); - + fileService = new FileService(appProperties, restTemplate, appSettingServiceForNetwork, mock(BookMetadataRepository.class)); } @@ -1178,10 +1203,10 @@ class FileServiceTest { ResponseEntity responseEntity = ResponseEntity.ok(imageBytes); when(mockRestTemplate.exchange( - eq(imageUrl), - eq(HttpMethod.GET), - any(HttpEntity.class), - eq(byte[].class) + eq(imageUrl), + eq(HttpMethod.GET), + any(HttpEntity.class), + eq(byte[].class) )).thenReturn(responseEntity); BufferedImage result = testFileService.downloadImageFromUrl(imageUrl); @@ -1198,32 +1223,32 @@ class FileServiceTest { String imageUrl = "http://example.com/image.jpg"; ResponseEntity responseEntity = ResponseEntity.ok(null); when(restTemplate.exchange( - eq(imageUrl), - eq(HttpMethod.GET), - any(HttpEntity.class), - eq(byte[].class) + eq(imageUrl), + eq(HttpMethod.GET), + any(HttpEntity.class), + eq(byte[].class) )).thenReturn(responseEntity); assertThrows(IOException.class, () -> - fileService.downloadImageFromUrl(imageUrl)); + fileService.downloadImageFromUrl(imageUrl)); } @Test - @DisplayName("throws exception when ImageIO cannot read bytes") + @DisplayName("returns null when ImageIO cannot read bytes") @Timeout(5) - void downloadImageFromUrl_invalidImageData_throwsException() { + void downloadImageFromUrl_invalidImageData_returnsNull() throws IOException { String imageUrl = "http://example.com/image.jpg"; byte[] invalidBytes = "not an image".getBytes(); ResponseEntity responseEntity = ResponseEntity.ok(invalidBytes); when(restTemplate.exchange( - eq(imageUrl), - eq(HttpMethod.GET), - any(HttpEntity.class), - eq(byte[].class) + eq(imageUrl), + eq(HttpMethod.GET), + any(HttpEntity.class), + eq(byte[].class) )).thenReturn(responseEntity); - assertThrows(IOException.class, () -> - fileService.downloadImageFromUrl(imageUrl)); + BufferedImage result = fileService.downloadImageFromUrl(imageUrl); + assertNull(result); } @Test @@ -1233,14 +1258,14 @@ class FileServiceTest { String imageUrl = "http://example.com/image.jpg"; ResponseEntity responseEntity = ResponseEntity.notFound().build(); when(restTemplate.exchange( - eq(imageUrl), - eq(HttpMethod.GET), - any(HttpEntity.class), - eq(byte[].class) + eq(imageUrl), + eq(HttpMethod.GET), + any(HttpEntity.class), + eq(byte[].class) )).thenReturn(responseEntity); assertThrows(IOException.class, () -> - fileService.downloadImageFromUrl(imageUrl)); + fileService.downloadImageFromUrl(imageUrl)); } } @@ -1259,14 +1284,14 @@ class FileServiceTest { ResponseEntity responseEntity = ResponseEntity.ok(imageBytes); when(restTemplate.exchange( - eq(imageUrl), - eq(HttpMethod.GET), - any(HttpEntity.class), - eq(byte[].class) + eq(imageUrl), + eq(HttpMethod.GET), + any(HttpEntity.class), + eq(byte[].class) )).thenReturn(responseEntity); assertDoesNotThrow(() -> - fileService.createThumbnailFromUrl(bookId, imageUrl)); + fileService.createThumbnailFromUrl(bookId, imageUrl)); Path imagesFolder = tempDir.resolve("images").resolve(String.valueOf(bookId)); assertTrue(Files.exists(imagesFolder.resolve("cover.jpg"))); @@ -1285,231 +1310,30 @@ class FileServiceTest { long bookId = 42L; when(restTemplate.exchange( - eq(imageUrl), - eq(HttpMethod.GET), - any(HttpEntity.class), - eq(byte[].class) + eq(imageUrl), + eq(HttpMethod.GET), + any(HttpEntity.class), + eq(byte[].class) )).thenThrow(new RuntimeException("Network error")); // FileService wraps exceptions in RuntimeException via ApiError RuntimeException exception = assertThrows(RuntimeException.class, () -> - fileService.createThumbnailFromUrl(bookId, imageUrl)); - assertTrue(exception.getMessage().contains("Network error") || - exception.getMessage().contains("Failed"), - "Exception message should indicate download failure"); + fileService.createThumbnailFromUrl(bookId, imageUrl)); + assertTrue(exception.getMessage().contains("Network error") || + exception.getMessage().contains("Failed"), + "Exception message should indicate download failure"); } } } - @Nested - @DisplayName("Background Operations") - class BackgroundOperationsTests { - - @BeforeEach - void setup() { - when(appProperties.getPathConfig()).thenReturn(tempDir.toString()); - } - - @Nested - @DisplayName("saveBackgroundImage") - class SaveBackgroundImageTests { - - @Test - void userBackground_savesInUserFolder() throws IOException { - BufferedImage image = createTestImage(1920, 1080); - - fileService.saveBackgroundImage(image, "bg.jpg", 1L); - - Path expected = tempDir.resolve("backgrounds/user-1/bg.jpg"); - assertTrue(Files.exists(expected)); - } - - @Test - void globalBackground_savesInGlobalFolder() throws IOException { - BufferedImage image = createTestImage(1920, 1080); - - fileService.saveBackgroundImage(image, "global.jpg", null); - - Path expected = tempDir.resolve("backgrounds/global.jpg"); - assertTrue(Files.exists(expected)); - } - - @Test - void createsDirectoryIfNotExists() throws IOException { - BufferedImage image = createTestImage(100, 100); - - fileService.saveBackgroundImage(image, "new.jpg", 2L); - - assertTrue(Files.isDirectory( - tempDir.resolve("backgrounds/user-2"))); - } - - @Test - void overwritesExistingFile() throws IOException { - BufferedImage image1 = createTestImage(100, 100, Color.RED); - BufferedImage image2 = createTestImage(100, 100, Color.BLUE); - - fileService.saveBackgroundImage(image1, "bg.jpg", 3L); - assertTrue(Files.exists(tempDir.resolve("backgrounds/user-3/bg.jpg"))); - - fileService.saveBackgroundImage(image2, "bg.jpg", 3L); - - // File exists and was overwritten - assertTrue(Files.exists(tempDir.resolve("backgrounds/user-3/bg.jpg"))); - } - } - - @Nested - @DisplayName("deleteBackgroundFile") - class DeleteBackgroundFileTests { - - @Test - void existingFile_deletesIt() throws IOException { - BufferedImage image = createTestImage(100, 100); - fileService.saveBackgroundImage(image, "to-delete.jpg", 4L); - - fileService.deleteBackgroundFile("to-delete.jpg", 4L); - - assertFalse(Files.exists( - tempDir.resolve("backgrounds/user-4/to-delete.jpg"))); - } - - @Test - void nonExistentFile_doesNotThrow() { - assertDoesNotThrow(() -> - fileService.deleteBackgroundFile("nonexistent.jpg", 5L)); - } - - @Test - void lastFileInUserFolder_deletesEmptyFolder() throws IOException { - BufferedImage image = createTestImage(100, 100); - fileService.saveBackgroundImage(image, "only.jpg", 6L); - - fileService.deleteBackgroundFile("only.jpg", 6L); - - assertFalse(Files.exists(tempDir.resolve("backgrounds/user-6"))); - } - - @Test - void notLastFile_keepsFolder() throws IOException { - BufferedImage image = createTestImage(100, 100); - fileService.saveBackgroundImage(image, "file1.jpg", 7L); - fileService.saveBackgroundImage(image, "file2.jpg", 7L); - - fileService.deleteBackgroundFile("file1.jpg", 7L); - - assertTrue(Files.isDirectory( - tempDir.resolve("backgrounds/user-7"))); - } - - @Test - void globalBackground_deletesFile() throws IOException { - BufferedImage image = createTestImage(100, 100); - Path bgFolder = tempDir.resolve("backgrounds"); - Files.createDirectories(bgFolder); - ImageIO.write(image, "JPEG", bgFolder.resolve("global.jpg").toFile()); - - fileService.deleteBackgroundFile("global.jpg", null); - - assertFalse(Files.exists(bgFolder.resolve("global.jpg"))); - } - } - - @Nested - @DisplayName("getBackgroundResource") - class GetBackgroundResourceTests { - - @Test - void userHasBackground_returnsUserBackground() throws IOException { - createUserBackground(8L, "1.jpg"); - - Resource resource = fileService.getBackgroundResource(8L); - - assertAll( - () -> assertInstanceOf(FileSystemResource.class, resource), - () -> assertTrue(resource.exists()) - ); - } - - @Test - void userHasNoBackground_globalExists_returnsGlobal() throws IOException { - createGlobalBackground("1.jpg"); - - Resource resource = fileService.getBackgroundResource(9L); - - assertInstanceOf(FileSystemResource.class, resource); - } - - @Test - void noCustomBackgrounds_returnsDefault() { - Resource resource = fileService.getBackgroundResource(10L); - - assertInstanceOf(ClassPathResource.class, resource); - } - - @ParameterizedTest - @ValueSource(strings = {"1.jpg", "1.jpeg", "1.png"}) - void supportsMultipleFormats(String filename) throws IOException { - Path bgFolder = tempDir.resolve("backgrounds"); - Files.createDirectories(bgFolder); - Files.createFile(bgFolder.resolve(filename)); - - Resource resource = fileService.getBackgroundResource(null); - - assertTrue(resource.exists()); - } - - @Test - void userBackgroundTakesPriority_overGlobal() throws IOException { - createGlobalBackground("1.jpg"); - createUserBackground(11L, "1.jpg"); - - Resource resource = fileService.getBackgroundResource(11L); - - String path = ((FileSystemResource) resource).getPath(); - assertTrue(path.contains("user-11")); - } - - @Test - @DisplayName("Priority: user > global > default") - void checksPriorityOrder() throws IOException { - // Only global exists - createGlobalBackground("1.jpg"); - Resource globalResource = fileService.getBackgroundResource(12L); - assertTrue(globalResource.exists()); - - // Add user background - createUserBackground(12L, "1.jpg"); - Resource userResource = fileService.getBackgroundResource(12L); - String path = ((FileSystemResource) userResource).getPath(); - assertTrue(path.contains("user-12")); - } - - private void createUserBackground(Long userId, String filename) - throws IOException { - Path folder = tempDir.resolve("backgrounds/user-" + userId); - Files.createDirectories(folder); - BufferedImage img = createTestImage(100, 100); - ImageIO.write(img, "JPEG", folder.resolve(filename).toFile()); - } - - private void createGlobalBackground(String filename) throws IOException { - Path folder = tempDir.resolve("backgrounds"); - Files.createDirectories(folder); - BufferedImage img = createTestImage(100, 100); - ImageIO.write(img, "JPEG", folder.resolve(filename).toFile()); - } - } - } - private BufferedImage createTestImage(int width, int height) { return createTestImage(width, height, Color.BLUE); } private BufferedImage createTestImage(int width, int height, Color color) { BufferedImage image = new BufferedImage( - width, height, BufferedImage.TYPE_INT_RGB); + width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g = image.createGraphics(); g.setColor(color); g.fillRect(0, 0, width, height); diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/util/FileUtilsTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/util/FileUtilsTest.java index 5e850b0ca..d1459a6d8 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/util/FileUtilsTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/util/FileUtilsTest.java @@ -161,6 +161,18 @@ class FileUtilsTest { assertFalse(FileUtils.shouldIgnore(normalPath)); } + @Test + void testShouldIgnore_pathWithRecycle_returnsTrue() { + Path caltrashPath = tempDir.resolve("#recycle").resolve("file.txt"); + assertTrue(FileUtils.shouldIgnore(caltrashPath)); + } + + @Test + void testShouldIgnore_pathWithRecycleInSubdirectory_returnsTrue() { + Path caltrashPath = tempDir.resolve("subdir").resolve("#recycle").resolve("file.txt"); + assertTrue(FileUtils.shouldIgnore(caltrashPath)); + } + @Test void testShouldIgnore_emptyFileName_returnsFalse() { Path emptyPath = tempDir.resolve(""); @@ -176,4 +188,4 @@ class FileUtilsTest { assertNotNull(size, "File size should not be null for existing file"); assertTrue(size >= 0, "File size should be non-negative"); } -} \ No newline at end of file +} diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/util/UserPermissionUtilsTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/util/UserPermissionUtilsTest.java index ec8a9b66a..5566d38d7 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/util/UserPermissionUtilsTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/util/UserPermissionUtilsTest.java @@ -6,7 +6,9 @@ import com.adityachandel.booklore.model.enums.PermissionType; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; -import static org.junit.jupiter.api.Assertions.*; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; class UserPermissionUtilsTest { @@ -57,6 +59,7 @@ class UserPermissionUtilsTest { .permissionAccessTaskManager(false) .permissionManageGlobalPreferences(false) .permissionManageIcons(false) + .permissionManageFonts(false) .permissionDemoUser(false) .permissionAdmin(false) .build(); @@ -85,6 +88,7 @@ class UserPermissionUtilsTest { .permissionAccessTaskManager(true) .permissionManageGlobalPreferences(true) .permissionManageIcons(true) + .permissionManageFonts(true) .permissionDemoUser(true) .permissionAdmin(true) .build(); @@ -112,6 +116,7 @@ class UserPermissionUtilsTest { .permissionAccessTaskManager(false) .permissionManageGlobalPreferences(false) .permissionManageIcons(false) + .permissionManageFonts(false) .permissionDemoUser(false) .permissionAdmin(false); @@ -132,6 +137,7 @@ class UserPermissionUtilsTest { case ACCESS_TASK_MANAGER -> builder.permissionAccessTaskManager(value); case MANAGE_GLOBAL_PREFERENCES -> builder.permissionManageGlobalPreferences(value); case MANAGE_ICONS -> builder.permissionManageIcons(value); + case MANAGE_FONTS -> builder.permissionManageFonts(value); case DEMO_USER -> builder.permissionDemoUser(value); case ADMIN -> builder.permissionAdmin(value); default -> throw new IllegalArgumentException("Test helper missing mapping for PermissionType: " + permissionType); @@ -158,6 +164,7 @@ class UserPermissionUtilsTest { perms.setCanAccessUserStats(false); perms.setCanAccessTaskManager(false); perms.setCanManageIcons(false); + perms.setCanManageFonts(false); perms.setCanManageGlobalPreferences(false); perms.setDemoUser(false); @@ -178,6 +185,7 @@ class UserPermissionUtilsTest { case ACCESS_TASK_MANAGER -> perms.setCanAccessTaskManager(value); case MANAGE_GLOBAL_PREFERENCES -> perms.setCanManageGlobalPreferences(value); case MANAGE_ICONS -> perms.setCanManageIcons(value); + case MANAGE_FONTS -> perms.setCanManageFonts(value); case DEMO_USER -> perms.setDemoUser(value); case ADMIN -> perms.setAdmin(value); default -> throw new IllegalArgumentException("Test helper missing mapping for PermissionType: " + permissionType); diff --git a/booklore-ui/angular.json b/booklore-ui/angular.json index f0336f036..5cb7cc473 100644 --- a/booklore-ui/angular.json +++ b/booklore-ui/angular.json @@ -106,24 +106,9 @@ "builder": "@angular/build:extract-i18n" }, "test": { - "builder": "@angular/build:karma", + "builder": "@angular/build:unit-test", "options": { - "polyfills": [ - "zone.js", - "zone.js/testing" - ], - "tsConfig": "tsconfig.spec.json", - "inlineStyleLanguage": "scss", - "assets": [ - { - "glob": "**/*", - "input": "public" - } - ], - "styles": [ - "src/styles.scss" - ], - "scripts": [] + "runnerConfig": "vitest-base.config.ts" } }, "lint": { diff --git a/booklore-ui/package-lock.json b/booklore-ui/package-lock.json index b4da98c36..e9d8a6b84 100644 --- a/booklore-ui/package-lock.json +++ b/booklore-ui/package-lock.json @@ -33,6 +33,7 @@ "ng2-charts": "^8.0.0", "ngx-extended-pdf-viewer": "^25.6.4", "ngx-infinite-scroll": "^21.0.0", + "ngx-sse-client": "^20.0.1", "primeicons": "^7.0.0", "primeng": "^21.0.2", "quill": "^2.0.3", @@ -49,21 +50,27 @@ "@angular/compiler-cli": "^21.0.5", "@tailwindcss/typography": "^0.5.19", "@types/jasmine": "^5.1.13", + "@types/node": "^25.0.3", "@types/showdown": "^2.0.6", + "@vitest/coverage-v8": "^4.0.16", "angular-eslint": "^21.1.0", "autoprefixer": "^10.4.23", "eslint": "^9.39.2", "jasmine-core": "^5.13.0", - "karma": "^6.4.4", - "karma-chrome-launcher": "^3.2.0", - "karma-coverage": "^2.2.1", - "karma-jasmine": "^5.1.0", - "karma-jasmine-html-reporter": "^2.1.0", + "jsdom": "^27.4.0", "tailwindcss": "^3.4.17", "typescript": "~5.9.3", - "typescript-eslint": "^8.50.0" + "typescript-eslint": "^8.50.0", + "vitest": "^4.0.16" } }, + "node_modules/@acemir/cssom": { + "version": "0.9.30", + "resolved": "https://registry.npmjs.org/@acemir/cssom/-/cssom-0.9.30.tgz", + "integrity": "sha512-9CnlMCI0LmCIq0olalQqdWrJHPzm0/tw3gzOA9zJSgvFX7Xau3D24mAGa4BtwxwY69nsuJW6kQqqCzf/mEcQgg==", + "dev": true, + "license": "MIT" + }, "node_modules/@algolia/abtesting": { "version": "1.6.1", "resolved": "https://registry.npmjs.org/@algolia/abtesting/-/abtesting-1.6.1.tgz", @@ -800,6 +807,61 @@ "rxjs": "^6.5.3 || ^7.4.0" } }, + "node_modules/@asamuzakjp/css-color": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-4.1.1.tgz", + "integrity": "sha512-B0Hv6G3gWGMn0xKJ0txEi/jM5iFpT3MfDxmhZFb4W047GvytCf1DHQ1D69W3zHI4yWe2aTZAA0JnbMZ7Xc8DuQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@csstools/css-calc": "^2.1.4", + "@csstools/css-color-parser": "^3.1.0", + "@csstools/css-parser-algorithms": "^3.0.5", + "@csstools/css-tokenizer": "^3.0.4", + "lru-cache": "^11.2.4" + } + }, + "node_modules/@asamuzakjp/css-color/node_modules/lru-cache": { + "version": "11.2.4", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.2.4.tgz", + "integrity": "sha512-B5Y16Jr9LB9dHVkh6ZevG+vAbOsNOYCX+sXvFWFu7B3Iz5mijW3zdbMyhsh8ANd2mSWBYdJgnqi+mL7/LrOPYg==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/@asamuzakjp/dom-selector": { + "version": "6.7.6", + "resolved": "https://registry.npmjs.org/@asamuzakjp/dom-selector/-/dom-selector-6.7.6.tgz", + "integrity": "sha512-hBaJER6A9MpdG3WgdlOolHmbOYvSk46y7IQN/1+iqiCuUu6iWdQrs9DGKF8ocqsEqWujWf/V7b7vaDgiUmIvUg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@asamuzakjp/nwsapi": "^2.3.9", + "bidi-js": "^1.0.3", + "css-tree": "^3.1.0", + "is-potential-custom-element-name": "^1.0.1", + "lru-cache": "^11.2.4" + } + }, + "node_modules/@asamuzakjp/dom-selector/node_modules/lru-cache": { + "version": "11.2.4", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.2.4.tgz", + "integrity": "sha512-B5Y16Jr9LB9dHVkh6ZevG+vAbOsNOYCX+sXvFWFu7B3Iz5mijW3zdbMyhsh8ANd2mSWBYdJgnqi+mL7/LrOPYg==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/@asamuzakjp/nwsapi": { + "version": "2.3.9", + "resolved": "https://registry.npmjs.org/@asamuzakjp/nwsapi/-/nwsapi-2.3.9.tgz", + "integrity": "sha512-n8GuYSrI9bF7FFZ/SjhwevlHc8xaVlb/7HmHelnc/PZXBD2ZR49NnN9sMMuDdEGPeeRQ5d0hqlSlEpgCX3Wl0Q==", + "dev": true, + "license": "MIT" + }, "node_modules/@babel/code-frame": { "version": "7.27.1", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.27.1.tgz", @@ -1110,16 +1172,163 @@ "node": ">=6.9.0" } }, + "node_modules/@bcoe/v8-coverage": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-1.0.2.tgz", + "integrity": "sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, "node_modules/@colors/colors": { "version": "1.5.0", "resolved": "https://registry.npmjs.org/@colors/colors/-/colors-1.5.0.tgz", "integrity": "sha512-ooWCrlZP11i8GImSjTHYHLkvFDP48nS4+204nGb1RiX/WXYHmJA2III9/e2DWVabCESdW7hBAEzHRqUn9OUVvQ==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">=0.1.90" } }, + "node_modules/@csstools/color-helpers": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-5.1.0.tgz", + "integrity": "sha512-S11EXWJyy0Mz5SYvRmY8nJYTFFd1LCNV+7cXyAgQtOOuzb4EsgfqDufL+9esx72/eLhsRdGZwaldu/h+E4t4BA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT-0", + "engines": { + "node": ">=18" + } + }, + "node_modules/@csstools/css-calc": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-2.1.4.tgz", + "integrity": "sha512-3N8oaj+0juUw/1H3YwmDDJXCgTB1gKU6Hc/bB502u9zR0q2vd786XJH9QfrKIEgFlZmhZiq6epXl4rHqhzsIgQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^3.0.5", + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-color-parser": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-3.1.0.tgz", + "integrity": "sha512-nbtKwh3a6xNVIp/VRuXV64yTKnb1IjTAEEh3irzS+HkKjAOYLTGNb9pmVNntZ8iVBHcWDA2Dof0QtPgFI1BaTA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "dependencies": { + "@csstools/color-helpers": "^5.1.0", + "@csstools/css-calc": "^2.1.4" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^3.0.5", + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-parser-algorithms": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-3.0.5.tgz", + "integrity": "sha512-DaDeUkXZKjdGhgYaHNJTV9pV7Y9B3b644jCLs9Upc3VeNGg6LWARAT6O+Q+/COo+2gg/bM5rhpMAtf70WqfBdQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-syntax-patches-for-csstree": { + "version": "1.0.22", + "resolved": "https://registry.npmjs.org/@csstools/css-syntax-patches-for-csstree/-/css-syntax-patches-for-csstree-1.0.22.tgz", + "integrity": "sha512-qBcx6zYlhleiFfdtzkRgwNC7VVoAwfK76Vmsw5t+PbvtdknO9StgRk7ROvq9so1iqbdW4uLIDAsXRsTfUrIoOw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT-0", + "engines": { + "node": ">=18" + } + }, + "node_modules/@csstools/css-tokenizer": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-3.0.4.tgz", + "integrity": "sha512-Vd/9EVDiu6PPJt9yAh6roZP6El1xHrdvIVGjyBsHR0RYwNHgL7FJPyIIW4fANJNG6FtyZfvlRPpFI4ZM/lubvw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + } + }, "node_modules/@emnapi/core": { "version": "1.7.1", "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.7.1.tgz", @@ -1809,6 +2018,24 @@ "node": "^18.18.0 || ^20.9.0 || >=21.1.0" } }, + "node_modules/@exodus/bytes": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.8.0.tgz", + "integrity": "sha512-8JPn18Bcp8Uo1T82gR8lh2guEOa5KKU/IEKvvdp0sgmi7coPBWf1Doi1EXsGZb2ehc8ym/StJCjffYV+ne7sXQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + }, + "peerDependencies": { + "@exodus/crypto": "^1.0.0-rc.4" + }, + "peerDependenciesMeta": { + "@exodus/crypto": { + "optional": true + } + } + }, "node_modules/@humanfs/core": { "version": "0.19.1", "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.1.tgz", @@ -4322,14 +4549,15 @@ "resolved": "https://registry.npmjs.org/@socket.io/component-emitter/-/component-emitter-3.1.2.tgz", "integrity": "sha512-9BCxFwvbGg/RsZK9tjXd8s4UcwR0MWeFQ1XEKIQVVvAGJyINdrqKMcTRyLoK8Rse1GjzLV9cwjWV1olXRWEXVA==", "dev": true, - "license": "MIT" + "license": "MIT", + "optional": true, + "peer": true }, "node_modules/@standard-schema/spec": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==", - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/@stomp/rx-stomp": { "version": "2.3.0", @@ -4402,16 +4630,36 @@ "tslib": "^2.4.0" } }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, "node_modules/@types/cors": { "version": "2.8.19", "resolved": "https://registry.npmjs.org/@types/cors/-/cors-2.8.19.tgz", "integrity": "sha512-mFNylyeyqN93lfe/9CSxOGREz8cpzAhH+E93xJ4xWQf62V8sQ/24reV2nyzUWM6H6Xji+GGHpkbLe7pVoUEskg==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "@types/node": "*" } }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/estree": { "version": "1.0.8", "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", @@ -4444,9 +4692,9 @@ } }, "node_modules/@types/node": { - "version": "24.10.1", - "resolved": "https://registry.npmjs.org/@types/node/-/node-24.10.1.tgz", - "integrity": "sha512-GNWcUTRBgIRJD5zj+Tq0fKOJ5XZajIiBroOF0yvj2bSU1WvNdYS/dn9UxwsujGW4JX06dnHyjV2y9rRaybH0iQ==", + "version": "25.0.3", + "resolved": "https://registry.npmjs.org/@types/node/-/node-25.0.3.tgz", + "integrity": "sha512-W609buLVRVmeW693xKfzHeIV6nJGGz98uCPfeXI1ELMLXVeKYZ9m15fAMSaUPBHYLGFsVRcMmSCksQOrZV9BYA==", "dev": true, "license": "MIT", "dependencies": { @@ -4706,6 +4954,169 @@ "vite": "^6.0.0 || ^7.0.0" } }, + "node_modules/@vitest/coverage-v8": { + "version": "4.0.16", + "resolved": "https://registry.npmjs.org/@vitest/coverage-v8/-/coverage-v8-4.0.16.tgz", + "integrity": "sha512-2rNdjEIsPRzsdu6/9Eq0AYAzYdpP6Bx9cje9tL3FE5XzXRQF1fNU9pe/1yE8fCrS0HD+fBtt6gLPh6LI57tX7A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@bcoe/v8-coverage": "^1.0.2", + "@vitest/utils": "4.0.16", + "ast-v8-to-istanbul": "^0.3.8", + "istanbul-lib-coverage": "^3.2.2", + "istanbul-lib-report": "^3.0.1", + "istanbul-lib-source-maps": "^5.0.6", + "istanbul-reports": "^3.2.0", + "magicast": "^0.5.1", + "obug": "^2.1.1", + "std-env": "^3.10.0", + "tinyrainbow": "^3.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@vitest/browser": "4.0.16", + "vitest": "4.0.16" + }, + "peerDependenciesMeta": { + "@vitest/browser": { + "optional": true + } + } + }, + "node_modules/@vitest/expect": { + "version": "4.0.16", + "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.0.16.tgz", + "integrity": "sha512-eshqULT2It7McaJkQGLkPjPjNph+uevROGuIMJdG3V+0BSR2w9u6J9Lwu+E8cK5TETlfou8GRijhafIMhXsimA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@standard-schema/spec": "^1.0.0", + "@types/chai": "^5.2.2", + "@vitest/spy": "4.0.16", + "@vitest/utils": "4.0.16", + "chai": "^6.2.1", + "tinyrainbow": "^3.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/mocker": { + "version": "4.0.16", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.0.16.tgz", + "integrity": "sha512-yb6k4AZxJTB+q9ycAvsoxGn+j/po0UaPgajllBgt1PzoMAAmJGYFdDk0uCcRcxb3BrME34I6u8gHZTQlkqSZpg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/spy": "4.0.16", + "estree-walker": "^3.0.3", + "magic-string": "^0.30.21" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9", + "vite": "^6.0.0 || ^7.0.0-0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/mocker/node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/@vitest/pretty-format": { + "version": "4.0.16", + "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.0.16.tgz", + "integrity": "sha512-eNCYNsSty9xJKi/UdVD8Ou16alu7AYiS2fCPRs0b1OdhJiV89buAXQLpTbe+X8V9L6qrs9CqyvU7OaAopJYPsA==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyrainbow": "^3.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/runner": { + "version": "4.0.16", + "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.0.16.tgz", + "integrity": "sha512-VWEDm5Wv9xEo80ctjORcTQRJ539EGPB3Pb9ApvVRAY1U/WkHXmmYISqU5E79uCwcW7xYUV38gwZD+RV755fu3Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/utils": "4.0.16", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/snapshot": { + "version": "4.0.16", + "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.0.16.tgz", + "integrity": "sha512-sf6NcrYhYBsSYefxnry+DR8n3UV4xWZwWxYbCJUt2YdvtqzSPR7VfGrY0zsv090DAbjFZsi7ZaMi1KnSRyK1XA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "4.0.16", + "magic-string": "^0.30.21", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/snapshot/node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/@vitest/spy": { + "version": "4.0.16", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.0.16.tgz", + "integrity": "sha512-4jIOWjKP0ZUaEmJm00E0cOBLU+5WE0BpeNr3XN6TEF05ltro6NJqHWxXD0kA8/Zc8Nh23AT8WQxwNG+WeROupw==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/utils": { + "version": "4.0.16", + "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.0.16.tgz", + "integrity": "sha512-h8z9yYhV3e1LEfaQ3zdypIrnAg/9hguReGZoS7Gl0aBG5xgA410zBqECqmaF/+RkTggRsfnzc1XaAHA6bmUufA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "4.0.16", + "tinyrainbow": "^3.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, "node_modules/@xmldom/xmldom": { "version": "0.7.13", "resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.7.13.tgz", @@ -4977,6 +5388,35 @@ "node": ">= 0.4" } }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/ast-v8-to-istanbul": { + "version": "0.3.10", + "resolved": "https://registry.npmjs.org/ast-v8-to-istanbul/-/ast-v8-to-istanbul-0.3.10.tgz", + "integrity": "sha512-p4K7vMz2ZSk3wN8l5o3y2bJAoZXT3VuJI5OLTATY/01CYWumWvwkUw0SqDBnNq6IiTO3qDa1eSQDibAV8g7XOQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.31", + "estree-walker": "^3.0.3", + "js-tokens": "^9.0.1" + } + }, + "node_modules/ast-v8-to-istanbul/node_modules/js-tokens": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-9.0.1.tgz", + "integrity": "sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ==", + "dev": true, + "license": "MIT" + }, "node_modules/autoprefixer": { "version": "10.4.23", "resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-10.4.23.tgz", @@ -5037,6 +5477,8 @@ "integrity": "sha512-lGe34o6EHj9y3Kts9R4ZYs/Gr+6N7MCaMlIFA3F1R2O5/m7K06AxfSeO5530PEERE6/WyEg3lsuyw4GHlPZHog==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": "^4.5.0 || >= 5.9" } @@ -5071,6 +5513,16 @@ "node": ">=14.0.0" } }, + "node_modules/bidi-js": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/bidi-js/-/bidi-js-1.0.3.tgz", + "integrity": "sha512-RKshQI1R3YQ+n9YJz2QQ147P66ELpa1FQEg20Dk8oW9t2KgLbpDLLp9aGZ7y8WHSshDknG0bknqGw5/tyCs5tw==", + "dev": true, + "license": "MIT", + "dependencies": { + "require-from-string": "^2.0.2" + } + }, "node_modules/binary-extensions": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz", @@ -5339,6 +5791,16 @@ ], "license": "CC-BY-4.0" }, + "node_modules/chai": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz", + "integrity": "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, "node_modules/chalk": { "version": "4.1.2", "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", @@ -5587,6 +6049,8 @@ "integrity": "sha512-ZqRXc+tZukToSNmh5C2iWMSoV3X1YUcPbqEM4DkEG5tNQXrQUZCNVGGv3IuicnkMtPfGf3Xtp8WCXs295iQ1pQ==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "debug": "2.6.9", "finalhandler": "1.1.2", @@ -5603,6 +6067,8 @@ "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "ms": "2.0.0" } @@ -5613,6 +6079,8 @@ "integrity": "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">= 0.8" } @@ -5623,6 +6091,8 @@ "integrity": "sha512-aAWcW57uxVNrQZqFXjITpW3sIUQmHGG3qSb9mUah9MgMC4NeWhNOlNjXEYq3HjRAvL6arUviZGGJsBg6z0zsWA==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "debug": "2.6.9", "encodeurl": "~1.0.2", @@ -5641,7 +6111,9 @@ "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", "dev": true, - "license": "MIT" + "license": "MIT", + "optional": true, + "peer": true }, "node_modules/connect/node_modules/on-finished": { "version": "2.3.0", @@ -5649,6 +6121,8 @@ "integrity": "sha512-ikqdkGAAyf/X/gPhXGvfgAytDZtDbr+bkNUJ0N9h5MI/dmdgCs3l6hoHrcUv41sRKew3jIwrp4qQDXiK99Utww==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "ee-first": "1.1.1" }, @@ -5662,6 +6136,8 @@ "integrity": "sha512-OpZ3zP+jT1PI7I8nemJX4AKmAX070ZkYPVWV/AaKTJl+tXCTGyVdC1a4SL8RUQYEwk/f34ZX8UTykN68FwrqAA==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">= 0.6" } @@ -5780,6 +6256,20 @@ "url": "https://github.com/sponsors/fb55" } }, + "node_modules/css-tree": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-3.1.0.tgz", + "integrity": "sha512-0eW44TGN5SQXU1mWSkKwFstI/22X2bG1nYzZTYMAWjylYURhse752YgbE4Cx46AC+bAvI+/dYTPRk1LqSUnu6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "mdn-data": "2.12.2", + "source-map-js": "^1.0.1" + }, + "engines": { + "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0" + } + }, "node_modules/css-what": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/css-what/-/css-what-7.0.0.tgz", @@ -5805,12 +6295,40 @@ "node": ">=4" } }, + "node_modules/cssstyle": { + "version": "5.3.6", + "resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-5.3.6.tgz", + "integrity": "sha512-legscpSpgSAeGEe0TNcai97DKt9Vd9AsAdOL7Uoetb52Ar/8eJm3LIa39qpv8wWzLFlNG4vVvppQM+teaMPj3A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@asamuzakjp/css-color": "^4.1.1", + "@csstools/css-syntax-patches-for-csstree": "^1.0.21", + "css-tree": "^3.1.0", + "lru-cache": "^11.2.4" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/cssstyle/node_modules/lru-cache": { + "version": "11.2.4", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.2.4.tgz", + "integrity": "sha512-B5Y16Jr9LB9dHVkh6ZevG+vAbOsNOYCX+sXvFWFu7B3Iz5mijW3zdbMyhsh8ANd2mSWBYdJgnqi+mL7/LrOPYg==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, "node_modules/custom-event": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/custom-event/-/custom-event-1.0.1.tgz", "integrity": "sha512-GAj5FOq0Hd+RsCGVJxZuKaIDXDf3h6GQoNEjFgbLLI/trgtavwUbSnZ5pVfg27DVCaWjIohryS0JFwIJyT2cMg==", "dev": true, - "license": "MIT" + "license": "MIT", + "optional": true, + "peer": true }, "node_modules/d": { "version": "1.0.2", @@ -5825,6 +6343,20 @@ "node": ">=0.12" } }, + "node_modules/data-urls": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-6.0.0.tgz", + "integrity": "sha512-BnBS08aLUM+DKamupXs3w2tJJoqU+AkaE/+6vQxi/G/DPmIZFJJp9Dkb1kM03AZx8ADehDUZgsNxju3mPXZYIA==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-mimetype": "^4.0.0", + "whatwg-url": "^15.0.0" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/date-fns": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/date-fns/-/date-fns-4.1.0.tgz", @@ -5841,6 +6373,8 @@ "integrity": "sha512-39BOQLs9ZjKh0/patS9nrT8wc3ioX3/eA/zgbKNopnF2wCqJEoxywwwElATYvRsXdnOxA/OQeQoFZ3rFjVajhg==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">=4.0" } @@ -5863,6 +6397,13 @@ } } }, + "node_modules/decimal.js": { + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz", + "integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==", + "dev": true, + "license": "MIT" + }, "node_modules/deep-is": { "version": "0.1.4", "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", @@ -5886,6 +6427,8 @@ "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">= 0.8", "npm": "1.2.8000 || >= 1.4.16" @@ -5907,7 +6450,9 @@ "resolved": "https://registry.npmjs.org/di/-/di-0.0.1.tgz", "integrity": "sha512-uJaamHkagcZtHPqCIHZxnFrXlunQXgBOsZSUOWwFw31QJCAbyTBoHMW75YOTur5ZNx8pIeAKgf6GWIgaqqiLhA==", "dev": true, - "license": "MIT" + "license": "MIT", + "optional": true, + "peer": true }, "node_modules/didyoumean": { "version": "1.2.2", @@ -5927,6 +6472,8 @@ "integrity": "sha512-Yra4DbvoW7/Z6LBN560ZwXMjoNOSAN2wRsKFGc4iBeso+mpIA6qj1vfdf9HpMaKAqG6wXTy+1SYEzmNpKXOSsQ==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "custom-event": "~1.0.0", "ent": "~2.2.0", @@ -6070,6 +6617,8 @@ "integrity": "sha512-ZCkIjSYNDyGn0R6ewHDtXgns/Zre/NT6Agvq1/WobF7JXgFff4SeDroKiCO3fNJreU9YG429Sc81o4w5ok/W5g==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "@types/cors": "^2.8.12", "@types/node": ">=10.0.0", @@ -6091,6 +6640,8 @@ "integrity": "sha512-HqD3yTBfnBxIrbnM1DoD6Pcq8NECnh8d4As1Qgh0z5Gg3jRRIqijury0CL3ghu/edArpUYiYqQiDUQBIs4np3Q==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">=10.0.0" } @@ -6101,6 +6652,8 @@ "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "mime-types": "~2.1.34", "negotiator": "0.6.3" @@ -6115,6 +6668,8 @@ "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "ms": "^2.1.3" }, @@ -6133,6 +6688,8 @@ "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">= 0.6" } @@ -6143,6 +6700,8 @@ "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "mime-db": "1.52.0" }, @@ -6156,6 +6715,8 @@ "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">= 0.6" } @@ -6166,6 +6727,8 @@ "integrity": "sha512-6XQFvXTkbfUOZOKKILFG1PDK2NDQs4azKQl26T0YS5CxqWLgXajbPZ+h4gZekJyRqFU8pvnbAbbs/3TgRPy+GQ==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">=10.0.0" }, @@ -6188,6 +6751,8 @@ "integrity": "sha512-kKvD1tO6BM+oK9HzCPpUdRb4vKFQY/FPTFmurMvh6LlN68VMrdj77w8yp51/kDbpkFOS9J8w5W6zIzgM2H8/hw==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "call-bound": "^1.0.3", "es-errors": "^1.3.0", @@ -6278,6 +6843,13 @@ "node": ">= 0.4" } }, + "node_modules/es-module-lexer": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz", + "integrity": "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==", + "dev": true, + "license": "MIT" + }, "node_modules/es-object-atoms": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", @@ -6663,6 +7235,16 @@ "node": ">=4.0" } }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, "node_modules/esutils": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", @@ -6698,7 +7280,9 @@ "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-4.0.7.tgz", "integrity": "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==", "dev": true, - "license": "MIT" + "license": "MIT", + "optional": true, + "peer": true }, "node_modules/eventsource": { "version": "3.0.7", @@ -6723,6 +7307,16 @@ "node": ">=18.0.0" } }, + "node_modules/expect-type": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.3.0.tgz", + "integrity": "sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, "node_modules/exponential-backoff": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/exponential-backoff/-/exponential-backoff-3.1.3.tgz", @@ -6804,7 +7398,9 @@ "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==", "dev": true, - "license": "MIT" + "license": "MIT", + "optional": true, + "peer": true }, "node_modules/fast-deep-equal": { "version": "3.1.3", @@ -7001,6 +7597,8 @@ } ], "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">=4.0" }, @@ -7050,6 +7648,8 @@ "integrity": "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^4.0.0", @@ -7077,7 +7677,9 @@ "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", "dev": true, - "license": "ISC" + "license": "ISC", + "optional": true, + "peer": true }, "node_modules/fsevents": { "version": "2.3.3", @@ -7181,6 +7783,8 @@ "deprecated": "Glob versions prior to v9 are no longer supported", "dev": true, "license": "ISC", + "optional": true, + "peer": true, "dependencies": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", @@ -7221,6 +7825,8 @@ "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" @@ -7232,6 +7838,8 @@ "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", "dev": true, "license": "ISC", + "optional": true, + "peer": true, "dependencies": { "brace-expansion": "^1.1.7" }, @@ -7301,6 +7909,8 @@ "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "has-symbols": "^1.0.3" }, @@ -7346,6 +7956,19 @@ "node": "20 || >=22" } }, + "node_modules/html-encoding-sniffer": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-6.0.0.tgz", + "integrity": "sha512-CV9TW3Y3f8/wT0BRFc1/KAVQ3TUHiXmaAb6VW9vtiMFf7SLoMd1PdAc4W3KFOFETBJUb90KatHqlsZMWV+R9Gg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@exodus/bytes": "^1.6.0" + }, + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + } + }, "node_modules/html-escaper": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz", @@ -7420,6 +8043,8 @@ "integrity": "sha512-7mz/721AbnJwIVbnaSv1Cz3Am0ZLT/UBwkC92VlxhXv/k/BBQfM2fXElQNC27BVGr0uwUpplYPQM9LnaBMR5NQ==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "eventemitter3": "^4.0.0", "follow-redirects": "^1.0.0", @@ -7560,6 +8185,8 @@ "deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.", "dev": true, "license": "ISC", + "optional": true, + "peer": true, "dependencies": { "once": "^1.3.0", "wrappy": "1" @@ -7687,6 +8314,13 @@ "node": ">=0.12.0" } }, + "node_modules/is-potential-custom-element-name": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz", + "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==", + "dev": true, + "license": "MIT" + }, "node_modules/is-promise": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", @@ -7700,6 +8334,8 @@ "integrity": "sha512-MjYsKHO5O7mCsmRGxWcLWheFqN9DJ/2TmngvjKXihe6efViPqc274+Fx/4fYj/r03+ESvBdTXK0V6tA3rgez1g==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "call-bound": "^1.0.2", "gopd": "^1.2.0", @@ -7738,6 +8374,8 @@ "integrity": "sha512-iHrqe5shvBUcFbmZq9zOQHBoeOhZJu6RQGrDpBgenUm/Am+F3JM2MgQj+rK3Z601fzrL5gLZWtAPH2OBaSVcyw==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">= 8.0.0" }, @@ -7795,30 +8433,20 @@ } }, "node_modules/istanbul-lib-source-maps": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/istanbul-lib-source-maps/-/istanbul-lib-source-maps-4.0.1.tgz", - "integrity": "sha512-n3s8EwkdFIJCG3BPKBYvskgXGoy88ARzvegkitk60NxRdwltLOTaH7CUiMRXvwYorl0Q712iEjcWB+fK/MrWVw==", + "version": "5.0.6", + "resolved": "https://registry.npmjs.org/istanbul-lib-source-maps/-/istanbul-lib-source-maps-5.0.6.tgz", + "integrity": "sha512-yg2d+Em4KizZC5niWhQaIomgf5WlL4vOOjZ5xGCmF8SnPE/mDWWXgvRExdcpCgh9lLRRa1/fSYp2ymmbJ1pI+A==", "dev": true, "license": "BSD-3-Clause", "dependencies": { + "@jridgewell/trace-mapping": "^0.3.23", "debug": "^4.1.1", - "istanbul-lib-coverage": "^3.0.0", - "source-map": "^0.6.1" + "istanbul-lib-coverage": "^3.0.0" }, "engines": { "node": ">=10" } }, - "node_modules/istanbul-lib-source-maps/node_modules/source-map": { - "version": "0.6.1", - "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", - "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", - "dev": true, - "license": "BSD-3-Clause", - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/istanbul-reports": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.2.0.tgz", @@ -7870,6 +8498,46 @@ "js-yaml": "bin/js-yaml.js" } }, + "node_modules/jsdom": { + "version": "27.4.0", + "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-27.4.0.tgz", + "integrity": "sha512-mjzqwWRD9Y1J1KUi7W97Gja1bwOOM5Ug0EZ6UDK3xS7j7mndrkwozHtSblfomlzyB4NepioNt+B2sOSzczVgtQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@acemir/cssom": "^0.9.28", + "@asamuzakjp/dom-selector": "^6.7.6", + "@exodus/bytes": "^1.6.0", + "cssstyle": "^5.3.4", + "data-urls": "^6.0.0", + "decimal.js": "^10.6.0", + "html-encoding-sniffer": "^6.0.0", + "http-proxy-agent": "^7.0.2", + "https-proxy-agent": "^7.0.6", + "is-potential-custom-element-name": "^1.0.1", + "parse5": "^8.0.0", + "saxes": "^6.0.0", + "symbol-tree": "^3.2.4", + "tough-cookie": "^6.0.0", + "w3c-xmlserializer": "^5.0.0", + "webidl-conversions": "^8.0.0", + "whatwg-mimetype": "^4.0.0", + "whatwg-url": "^15.1.0", + "ws": "^8.18.3", + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + }, + "peerDependencies": { + "canvas": "^3.0.0" + }, + "peerDependenciesMeta": { + "canvas": { + "optional": true + } + } + }, "node_modules/jsesc": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", @@ -7940,6 +8608,8 @@ "integrity": "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "optionalDependencies": { "graceful-fs": "^4.1.6" } @@ -7981,6 +8651,8 @@ "integrity": "sha512-LrtUxbdvt1gOpo3gxG+VAJlJAEMhbWlM4YrFQgql98FwF7+K8K12LYO4hnDdUkNjeztYrOXEMqgTajSWgmtI/w==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "@colors/colors": "1.5.0", "body-parser": "^1.19.0", @@ -8014,162 +8686,39 @@ "node": ">= 10" } }, - "node_modules/karma-chrome-launcher": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/karma-chrome-launcher/-/karma-chrome-launcher-3.2.0.tgz", - "integrity": "sha512-rE9RkUPI7I9mAxByQWkGJFXfFD6lE4gC5nPuZdobf/QdTEJI6EU4yIay/cfU/xV4ZxlM5JiTv7zWYgA64NpS5Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "which": "^1.2.1" - } - }, - "node_modules/karma-chrome-launcher/node_modules/which": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/which/-/which-1.3.1.tgz", - "integrity": "sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==", - "dev": true, - "license": "ISC", - "dependencies": { - "isexe": "^2.0.0" - }, - "bin": { - "which": "bin/which" - } - }, - "node_modules/karma-coverage": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/karma-coverage/-/karma-coverage-2.2.1.tgz", - "integrity": "sha512-yj7hbequkQP2qOSb20GuNSIyE//PgJWHwC2IydLE6XRtsnaflv+/OSGNssPjobYUlhVVagy99TQpqUt3vAUG7A==", - "dev": true, - "license": "MIT", - "dependencies": { - "istanbul-lib-coverage": "^3.2.0", - "istanbul-lib-instrument": "^5.1.0", - "istanbul-lib-report": "^3.0.0", - "istanbul-lib-source-maps": "^4.0.1", - "istanbul-reports": "^3.0.5", - "minimatch": "^3.0.4" - }, - "engines": { - "node": ">=10.0.0" - } - }, - "node_modules/karma-coverage/node_modules/brace-expansion": { - "version": "1.1.12", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz", - "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==", - "dev": true, - "license": "MIT", - "dependencies": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" - } - }, - "node_modules/karma-coverage/node_modules/istanbul-lib-instrument": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-5.2.1.tgz", - "integrity": "sha512-pzqtp31nLv/XFOzXGuvhCb8qhjmTVo5vjVk19XE4CRlSWz0KoeJ3bw9XsA7nOp9YBf4qHjwBxkDzKcME/J29Yg==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "@babel/core": "^7.12.3", - "@babel/parser": "^7.14.7", - "@istanbuljs/schema": "^0.1.2", - "istanbul-lib-coverage": "^3.2.0", - "semver": "^6.3.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/karma-coverage/node_modules/minimatch": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", - "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", - "dev": true, - "license": "ISC", - "dependencies": { - "brace-expansion": "^1.1.7" - }, - "engines": { - "node": "*" - } - }, - "node_modules/karma-coverage/node_modules/semver": { - "version": "6.3.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", - "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", - "dev": true, - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - } - }, - "node_modules/karma-jasmine": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/karma-jasmine/-/karma-jasmine-5.1.0.tgz", - "integrity": "sha512-i/zQLFrfEpRyQoJF9fsCdTMOF5c2dK7C7OmsuKg2D0YSsuZSfQDiLuaiktbuio6F2wiCsZSnSnieIQ0ant/uzQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "jasmine-core": "^4.1.0" - }, - "engines": { - "node": ">=12" - }, - "peerDependencies": { - "karma": "^6.0.0" - } - }, - "node_modules/karma-jasmine-html-reporter": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/karma-jasmine-html-reporter/-/karma-jasmine-html-reporter-2.1.0.tgz", - "integrity": "sha512-sPQE1+nlsn6Hwb5t+HHwyy0A1FNCVKuL1192b+XNauMYWThz2kweiBVW1DqloRpVvZIJkIoHVB7XRpK78n1xbQ==", - "dev": true, - "license": "MIT", - "peerDependencies": { - "jasmine-core": "^4.0.0 || ^5.0.0", - "karma": "^6.0.0", - "karma-jasmine": "^5.0.0" - } - }, - "node_modules/karma-jasmine/node_modules/jasmine-core": { - "version": "4.6.1", - "resolved": "https://registry.npmjs.org/jasmine-core/-/jasmine-core-4.6.1.tgz", - "integrity": "sha512-VYz/BjjmC3klLJlLwA4Kw8ytk0zDSmbbDLNs794VnWmkcCB7I9aAL/D48VNQtmITyPvea2C3jdUMfc3kAoy0PQ==", - "dev": true, - "license": "MIT" - }, "node_modules/karma/node_modules/ansi-regex": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">=8" } }, "node_modules/karma/node_modules/body-parser": { - "version": "1.20.3", - "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.3.tgz", - "integrity": "sha512-7rAxByjUMqQ3/bHJy7D6OGXvx/MMc4IqBn/X0fcM1QUcAItpZrBEYhWGem+tzXH90c+G01ypMcYJBO9Y30203g==", + "version": "1.20.4", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.4.tgz", + "integrity": "sha512-ZTgYYLMOXY9qKU/57FAo8F+HA2dGX7bqGc71txDRC1rS4frdFI5R7NhluHxH6M0YItAP0sHB4uqAOcYKxO6uGA==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { - "bytes": "3.1.2", + "bytes": "~3.1.2", "content-type": "~1.0.5", "debug": "2.6.9", "depd": "2.0.0", - "destroy": "1.2.0", - "http-errors": "2.0.0", - "iconv-lite": "0.4.24", - "on-finished": "2.4.1", - "qs": "6.13.0", - "raw-body": "2.5.2", + "destroy": "~1.2.0", + "http-errors": "~2.0.1", + "iconv-lite": "~0.4.24", + "on-finished": "~2.4.1", + "qs": "~6.14.0", + "raw-body": "~2.5.3", "type-is": "~1.6.18", - "unpipe": "1.0.0" + "unpipe": "~1.0.0" }, "engines": { "node": ">= 0.8", @@ -8182,6 +8731,8 @@ "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" @@ -8193,6 +8744,8 @@ "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "anymatch": "~3.1.2", "braces": "~3.0.2", @@ -8218,6 +8771,8 @@ "integrity": "sha512-OcRE68cOsVMXp1Yvonl/fzkQOyjLSu/8bhPDfQt0e0/Eb283TKP20Fs2MqoPsr9SwA595rRCA+QMzYc9nBP+JQ==", "dev": true, "license": "ISC", + "optional": true, + "peer": true, "dependencies": { "string-width": "^4.2.0", "strip-ansi": "^6.0.0", @@ -8230,6 +8785,8 @@ "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "ms": "2.0.0" } @@ -8239,7 +8796,9 @@ "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", "dev": true, - "license": "MIT" + "license": "MIT", + "optional": true, + "peer": true }, "node_modules/karma/node_modules/glob-parent": { "version": "5.1.2", @@ -8247,6 +8806,8 @@ "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", "dev": true, "license": "ISC", + "optional": true, + "peer": true, "dependencies": { "is-glob": "^4.0.1" }, @@ -8254,29 +8815,14 @@ "node": ">= 6" } }, - "node_modules/karma/node_modules/http-errors": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", - "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "depd": "2.0.0", - "inherits": "2.0.4", - "setprototypeof": "1.2.0", - "statuses": "2.0.1", - "toidentifier": "1.0.1" - }, - "engines": { - "node": ">= 0.8" - } - }, "node_modules/karma/node_modules/iconv-lite": { "version": "0.4.24", "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "safer-buffer": ">= 2.1.2 < 3" }, @@ -8290,6 +8836,8 @@ "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">=8" } @@ -8300,6 +8848,8 @@ "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">= 0.6" } @@ -8310,6 +8860,8 @@ "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">= 0.6" } @@ -8320,6 +8872,8 @@ "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "mime-db": "1.52.0" }, @@ -8333,6 +8887,8 @@ "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", "dev": true, "license": "ISC", + "optional": true, + "peer": true, "dependencies": { "brace-expansion": "^1.1.7" }, @@ -8345,7 +8901,9 @@ "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", "dev": true, - "license": "MIT" + "license": "MIT", + "optional": true, + "peer": true }, "node_modules/karma/node_modules/picomatch": { "version": "2.3.1", @@ -8353,6 +8911,8 @@ "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">=8.6" }, @@ -8360,33 +8920,19 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, - "node_modules/karma/node_modules/qs": { - "version": "6.13.0", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.13.0.tgz", - "integrity": "sha512-+38qI9SOr8tfZ4QmJNplMUxqjbe7LKvvZgWdExBOmd+egZTtjLB67Gu0HRX3u/XOq7UU2Nx6nsjvS16Z9uwfpg==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "side-channel": "^1.0.6" - }, - "engines": { - "node": ">=0.6" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, "node_modules/karma/node_modules/raw-body": { - "version": "2.5.2", - "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.2.tgz", - "integrity": "sha512-8zGqypfENjCIqGhgXToC8aB2r7YrBX+AQAfIPs/Mlk+BtPTztOvTS01NRW/3Eh60J+a48lt8qsCzirQ6loCVfA==", + "version": "2.5.3", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.3.tgz", + "integrity": "sha512-s4VSOf6yN0rvbRZGxs8Om5CWj6seneMwK3oDb4lWDH0UPhWcxwOWw5+qk24bxq87szX1ydrwylIOp2uG1ojUpA==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { - "bytes": "3.1.2", - "http-errors": "2.0.0", - "iconv-lite": "0.4.24", - "unpipe": "1.0.0" + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.4.24", + "unpipe": "~1.0.0" }, "engines": { "node": ">= 0.8" @@ -8398,6 +8944,8 @@ "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "picomatch": "^2.2.1" }, @@ -8411,26 +8959,20 @@ "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", "dev": true, "license": "BSD-3-Clause", + "optional": true, + "peer": true, "engines": { "node": ">=0.10.0" } }, - "node_modules/karma/node_modules/statuses": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", - "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, "node_modules/karma/node_modules/string-width": { "version": "4.2.3", "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", @@ -8446,6 +8988,8 @@ "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "ansi-regex": "^5.0.1" }, @@ -8459,6 +9003,8 @@ "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "media-typer": "0.3.0", "mime-types": "~2.1.24" @@ -8473,6 +9019,8 @@ "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", @@ -8491,6 +9039,8 @@ "integrity": "sha512-D1mvvtDG0L5ft/jGWkLpG1+m0eQxOfaBvTNELraWj22wSVUMWxZUvYgJYcKh6jGGIkJFhH4IZPQhR4TKpc8mBw==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "cliui": "^7.0.2", "escalade": "^3.1.1", @@ -8510,6 +9060,8 @@ "integrity": "sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w==", "dev": true, "license": "ISC", + "optional": true, + "peer": true, "engines": { "node": ">=10" } @@ -8789,6 +9341,8 @@ "integrity": "sha512-1somDdy9sChrr9/f4UlzhdaGfDR2c/SaD2a4T7qEkG4jTS57/B3qmnjLYePwQ8cqWnUHZI0iAKxMBpCZICiZ2g==", "dev": true, "license": "Apache-2.0", + "optional": true, + "peer": true, "dependencies": { "date-format": "^4.0.14", "debug": "^4.3.4", @@ -8820,6 +9374,18 @@ "@jridgewell/sourcemap-codec": "^1.5.5" } }, + "node_modules/magicast": { + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/magicast/-/magicast-0.5.1.tgz", + "integrity": "sha512-xrHS24IxaLrvuo613F719wvOIv9xPHFWQHuvGUBmPnCA/3MQxKI3b+r7n1jAoDHmsbC5bRhTZYR77invLAxVnw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.28.5", + "@babel/types": "^7.28.5", + "source-map-js": "^1.2.1" + } + }, "node_modules/make-dir": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz", @@ -8898,6 +9464,13 @@ "node": ">= 0.4" } }, + "node_modules/mdn-data": { + "version": "2.12.2", + "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.12.2.tgz", + "integrity": "sha512-IEn+pegP1aManZuckezWCO+XZQDplx1366JoVhTpMpBB1sPey/SbveZQUosKiKiGYjg1wH4pMlNgXbCiYgihQA==", + "dev": true, + "license": "CC0-1.0" + }, "node_modules/media-typer": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz", @@ -8961,6 +9534,8 @@ "integrity": "sha512-USPkMeET31rOMiarsBNIHZKLGgvKc/LrjofAnBlOttf5ajRvqiRA8QsenbcooctK6d6Ts6aqZXBA+XbkKthiQg==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "bin": { "mime": "cli.js" }, @@ -9030,6 +9605,8 @@ "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "funding": { "url": "https://github.com/sponsors/ljharb" } @@ -9193,6 +9770,8 @@ "integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "minimist": "^1.2.6" }, @@ -9371,6 +9950,19 @@ "@angular/core": ">=21.0.0 <22.0.0" } }, + "node_modules/ngx-sse-client": { + "version": "20.0.1", + "resolved": "https://registry.npmjs.org/ngx-sse-client/-/ngx-sse-client-20.0.1.tgz", + "integrity": "sha512-OSFRirL5beveGj4An3lOzWwg/JZWJG4Q1TdbyW7lqSDacfwINpIjSHdWlpiQwIghKU7BtLAc6TonUGlU4MzGTQ==", + "license": "MIT", + "dependencies": { + "tslib": "^2.8.1" + }, + "peerDependencies": { + "@angular/common": ">=20.0.0", + "@angular/core": ">=20.0.0" + } + }, "node_modules/node-addon-api": { "version": "6.1.0", "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-6.1.0.tgz", @@ -9664,6 +10256,17 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/obug": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/obug/-/obug-2.1.1.tgz", + "integrity": "sha512-uTqF9MuPraAQ+IsnPf366RG4cP9RtUi7MLO1N3KEc+wb0a6yKpeL0lmk2IB1jY5KHPAlTc6T/JRdC/YqxHNwkQ==", + "dev": true, + "funding": [ + "https://github.com/sponsors/sxzz", + "https://opencollective.com/debug" + ], + "license": "MIT" + }, "node_modules/on-finished": { "version": "2.4.1", "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", @@ -9976,6 +10579,8 @@ "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">=0.10.0" } @@ -10040,6 +10645,13 @@ "integrity": "sha512-AmeDxedoo5svf7aB3FYqSAKqMxys014lVKBzy1o/5vv9CtU7U4wgGWL1dA2o6MOzcD53ScN4Jmiq6VbtLz1vIQ==", "license": "MIT" }, + "node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "dev": true, + "license": "MIT" + }, "node_modules/picocolors": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", @@ -10363,7 +10975,9 @@ "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.4.1.tgz", "integrity": "sha512-jmYNElW7yvO7TV33CjSmvSiE2yco3bV2czu/OzDKdMNVZQWfxCblURLhf+47syQRBntjfLdd/H0egrzIG+oaFQ==", "dev": true, - "license": "MIT" + "license": "MIT", + "optional": true, + "peer": true }, "node_modules/qjobs": { "version": "1.2.0", @@ -10371,14 +10985,16 @@ "integrity": "sha512-8YOJEHtxpySA3fFDyCRxA+UUV+fA+rTWnuWvylOK/NCjhY+b4ocCtmu8TtsWb+mYeU+GCHf/S66KZF/AsteKHg==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">=0.9" } }, "node_modules/qs": { - "version": "6.14.0", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.0.tgz", - "integrity": "sha512-YWWTjgABSKcvs/nWBi9PycY/JiPJqOD4JA6o9Sej2AtvSGarXxKC3OQSk4pAarbdQlKAh5D4FCQkJNkW+GAn3w==", + "version": "6.14.1", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.1.tgz", + "integrity": "sha512-4EK3+xJl8Ts67nLYNwqw/dsFVnCf+qR7RgXSK9jEEm9unao3njwMDdmsdvoKBKHzxd7tCYz5e5M+SnMjdtXGQQ==", "dev": true, "license": "BSD-3-Clause", "dependencies": { @@ -10523,6 +11139,8 @@ "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">=0.10.0" } @@ -10542,7 +11160,9 @@ "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz", "integrity": "sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==", "dev": true, - "license": "MIT" + "license": "MIT", + "optional": true, + "peer": true }, "node_modules/resolve": { "version": "1.22.11", @@ -10625,6 +11245,8 @@ "deprecated": "Rimraf versions prior to v4 are no longer supported", "dev": true, "license": "ISC", + "optional": true, + "peer": true, "dependencies": { "glob": "^7.1.3" }, @@ -10771,6 +11393,8 @@ "integrity": "sha512-x/+Cz4YrimQxQccJf5mKEbIa1NzeCRNI5Ecl/ekmlYaampdNLPalVyIcCZNNH3MvmqBugV5TMYZXv0ljslUlaw==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "call-bound": "^1.0.2", "es-errors": "^1.3.0", @@ -10811,6 +11435,19 @@ "@parcel/watcher": "^2.4.1" } }, + "node_modules/saxes": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz", + "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==", + "dev": true, + "license": "ISC", + "dependencies": { + "xmlchars": "^2.2.0" + }, + "engines": { + "node": ">=v12.22.7" + } + }, "node_modules/semver": { "version": "7.7.3", "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz", @@ -10999,6 +11636,13 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/siginfo": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", + "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==", + "dev": true, + "license": "ISC" + }, "node_modules/signal-exit": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", @@ -11077,6 +11721,8 @@ "integrity": "sha512-oZ7iUCxph8WYRHHcjBEc9unw3adt5CmSNlppj/5Q4k2RIrhl8Z5yY2Xr4j9zj0+wzVZ0bxmYoGSzKJnRl6A4yg==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "accepts": "~1.3.4", "base64id": "~2.0.0", @@ -11096,6 +11742,8 @@ "integrity": "sha512-eLDQas5dzPgOWCk9GuuJC2lBqItuhKI4uxGgo9aIV7MYbk2h9Q6uULEh8WBzThoI7l+qU9Ast9fVUmkqPP9wYg==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "debug": "~4.3.4", "ws": "~8.17.1" @@ -11107,6 +11755,8 @@ "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "ms": "^2.1.3" }, @@ -11125,6 +11775,8 @@ "integrity": "sha512-6XQFvXTkbfUOZOKKILFG1PDK2NDQs4azKQl26T0YS5CxqWLgXajbPZ+h4gZekJyRqFU8pvnbAbbs/3TgRPy+GQ==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">=10.0.0" }, @@ -11147,6 +11799,8 @@ "integrity": "sha512-/GbIKmo8ioc+NIWIhwdecY0ge+qVBSMdgxGygevmdHj24bsfgtCmcUUcQ5ZzcylGFHsN3k4HB4Cgkl96KVnuew==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "@socket.io/component-emitter": "~3.1.0", "debug": "~4.3.1" @@ -11161,6 +11815,8 @@ "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "ms": "^2.1.3" }, @@ -11179,6 +11835,8 @@ "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "mime-types": "~2.1.34", "negotiator": "0.6.3" @@ -11193,6 +11851,8 @@ "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "ms": "^2.1.3" }, @@ -11211,6 +11871,8 @@ "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">= 0.6" } @@ -11221,6 +11883,8 @@ "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "mime-db": "1.52.0" }, @@ -11234,6 +11898,8 @@ "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">= 0.6" } @@ -11357,6 +12023,13 @@ "node": "^18.17.0 || >=20.5.0" } }, + "node_modules/stackback": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", + "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==", + "dev": true, + "license": "MIT" + }, "node_modules/statuses": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", @@ -11367,6 +12040,13 @@ "node": ">= 0.8" } }, + "node_modules/std-env": { + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-3.10.0.tgz", + "integrity": "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==", + "dev": true, + "license": "MIT" + }, "node_modules/stdin-discarder": { "version": "0.2.2", "resolved": "https://registry.npmjs.org/stdin-discarder/-/stdin-discarder-0.2.2.tgz", @@ -11386,6 +12066,8 @@ "integrity": "sha512-KFxaM7XT+irxvdqSP1LGLgNWbYN7ay5owZ3r/8t77p+EtSUAfUgtl7be3xtqtOmGUl9K9YPO2ca8133RlTjvKw==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "date-format": "^4.0.14", "debug": "^4.3.4", @@ -11507,6 +12189,13 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/symbol-tree": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz", + "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==", + "dev": true, + "license": "MIT" + }, "node_modules/tailwindcss": { "version": "3.4.18", "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.4.18.tgz", @@ -11683,6 +12372,23 @@ "node": ">=0.8" } }, + "node_modules/tinybench": { + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", + "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinyexec": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.0.2.tgz", + "integrity": "sha512-W/KYk+NFhkmsYpuHq5JykngiOCnxeVL8v8dFnqxSD8qEEdRfXk1SDM6JzNqcERbcGYj9tMrDQBYV9cjgnunFIg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, "node_modules/tinyglobby": { "version": "0.2.15", "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz", @@ -11699,12 +12405,44 @@ "url": "https://github.com/sponsors/SuperchupuDev" } }, + "node_modules/tinyrainbow": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.0.3.tgz", + "integrity": "sha512-PSkbLUoxOFRzJYjjxHJt9xro7D+iilgMX/C9lawzVuYiIdcihh9DXmVibBe8lmcFrRi/VzlPjBxbN7rH24q8/Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tldts": { + "version": "7.0.19", + "resolved": "https://registry.npmjs.org/tldts/-/tldts-7.0.19.tgz", + "integrity": "sha512-8PWx8tvC4jDB39BQw1m4x8y5MH1BcQ5xHeL2n7UVFulMPH/3Q0uiamahFJ3lXA0zO2SUyRXuVVbWSDmstlt9YA==", + "dev": true, + "license": "MIT", + "dependencies": { + "tldts-core": "^7.0.19" + }, + "bin": { + "tldts": "bin/cli.js" + } + }, + "node_modules/tldts-core": { + "version": "7.0.19", + "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-7.0.19.tgz", + "integrity": "sha512-lJX2dEWx0SGH4O6p+7FPwYmJ/bu1JbcGJ8RLaG9b7liIgZ85itUVEPbMtWRVrde/0fnDPEPHW10ZsKW3kVsE9A==", + "dev": true, + "license": "MIT" + }, "node_modules/tmp": { "version": "0.2.5", "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.5.tgz", "integrity": "sha512-voyz6MApa1rQGUxT3E+BK7/ROe8itEx7vD8/HEvt4xwXucvQ5G5oeEiHkmHZJuBO21RpOf+YYm9MOivj709jow==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">=14.14" } @@ -11731,6 +12469,42 @@ "node": ">=0.6" } }, + "node_modules/tough-cookie": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-6.0.0.tgz", + "integrity": "sha512-kXuRi1mtaKMrsLUxz3sQYvVl37B0Ns6MzfrtV5DvJceE9bPyspOqk9xxv7XbZWcfLWbFmm997vl83qUWVJA64w==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "tldts": "^7.0.5" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/tr46": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-6.0.0.tgz", + "integrity": "sha512-bLVMLPtstlZ4iMQHpFHTR7GAGj2jxi8Dg0s2h2MafAE4uSWF98FC/3MomU51iQAMf8/qDUbKWf5GxuvvVcXEhw==", + "dev": true, + "license": "MIT", + "dependencies": { + "punycode": "^2.3.1" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/tr46/node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/ts-api-utils": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.1.0.tgz", @@ -11863,6 +12637,8 @@ } ], "license": "MIT", + "optional": true, + "peer": true, "bin": { "ua-parser-js": "script/cli.js" }, @@ -11919,6 +12695,8 @@ "integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">= 4.0.0" } @@ -11996,6 +12774,8 @@ "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">= 0.4.0" } @@ -12604,16 +13384,119 @@ "@esbuild/win32-x64": "0.25.12" } }, + "node_modules/vitest": { + "version": "4.0.16", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.0.16.tgz", + "integrity": "sha512-E4t7DJ9pESL6E3I8nFjPa4xGUd3PmiWDLsDztS2qXSJWfHtbQnwAWylaBvSNY48I3vr8PTqIZlyK8TE3V3CA4Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/expect": "4.0.16", + "@vitest/mocker": "4.0.16", + "@vitest/pretty-format": "4.0.16", + "@vitest/runner": "4.0.16", + "@vitest/snapshot": "4.0.16", + "@vitest/spy": "4.0.16", + "@vitest/utils": "4.0.16", + "es-module-lexer": "^1.7.0", + "expect-type": "^1.2.2", + "magic-string": "^0.30.21", + "obug": "^2.1.1", + "pathe": "^2.0.3", + "picomatch": "^4.0.3", + "std-env": "^3.10.0", + "tinybench": "^2.9.0", + "tinyexec": "^1.0.2", + "tinyglobby": "^0.2.15", + "tinyrainbow": "^3.0.3", + "vite": "^6.0.0 || ^7.0.0", + "why-is-node-running": "^2.3.0" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^20.0.0 || ^22.0.0 || >=24.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@opentelemetry/api": "^1.9.0", + "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0", + "@vitest/browser-playwright": "4.0.16", + "@vitest/browser-preview": "4.0.16", + "@vitest/browser-webdriverio": "4.0.16", + "@vitest/ui": "4.0.16", + "happy-dom": "*", + "jsdom": "*" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@opentelemetry/api": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser-playwright": { + "optional": true + }, + "@vitest/browser-preview": { + "optional": true + }, + "@vitest/browser-webdriverio": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + } + } + }, + "node_modules/vitest/node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, "node_modules/void-elements": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/void-elements/-/void-elements-2.0.1.tgz", "integrity": "sha512-qZKX4RnBzH2ugr8Lxa7x+0V6XD9Sb/ouARtiasEQCHB1EVU4NXtmHsDDrx1dO4ne5fc3J6EW05BP1Dl0z0iung==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">=0.10.0" } }, + "node_modules/w3c-xmlserializer": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz", + "integrity": "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==", + "dev": true, + "license": "MIT", + "dependencies": { + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": ">=18" + } + }, "node_modules/watchpack": { "version": "2.4.4", "resolved": "https://registry.npmjs.org/watchpack/-/watchpack-2.4.4.tgz", @@ -12636,6 +13519,40 @@ "license": "MIT", "optional": true }, + "node_modules/webidl-conversions": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-8.0.1.tgz", + "integrity": "sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=20" + } + }, + "node_modules/whatwg-mimetype": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-4.0.0.tgz", + "integrity": "sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/whatwg-url": { + "version": "15.1.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-15.1.0.tgz", + "integrity": "sha512-2ytDk0kiEj/yu90JOAp44PVPUkO9+jVhyf+SybKlRHSDlvOOZhdPIrr7xTH64l4WixO2cP+wQIcgujkGBPPz6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "tr46": "^6.0.0", + "webidl-conversions": "^8.0.0" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/which": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", @@ -12652,6 +13569,23 @@ "node": ">= 8" } }, + "node_modules/why-is-node-running": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz", + "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==", + "dev": true, + "license": "MIT", + "dependencies": { + "siginfo": "^2.0.0", + "stackback": "0.0.2" + }, + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/word-wrap": { "version": "1.2.5", "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", @@ -12760,6 +13694,23 @@ } } }, + "node_modules/xml-name-validator": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz", + "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/xmlchars": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz", + "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", + "dev": true, + "license": "MIT" + }, "node_modules/y18n": { "version": "5.0.8", "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", diff --git a/booklore-ui/package.json b/booklore-ui/package.json index a5bc92046..fa5c7888b 100644 --- a/booklore-ui/package.json +++ b/booklore-ui/package.json @@ -37,6 +37,7 @@ "ng2-charts": "^8.0.0", "ngx-extended-pdf-viewer": "^25.6.4", "ngx-infinite-scroll": "^21.0.0", + "ngx-sse-client": "^20.0.1", "primeicons": "^7.0.0", "primeng": "^21.0.2", "quill": "^2.0.3", @@ -53,18 +54,17 @@ "@angular/compiler-cli": "^21.0.5", "@tailwindcss/typography": "^0.5.19", "@types/jasmine": "^5.1.13", + "@types/node": "^25.0.3", "@types/showdown": "^2.0.6", + "@vitest/coverage-v8": "^4.0.16", "angular-eslint": "^21.1.0", "autoprefixer": "^10.4.23", "eslint": "^9.39.2", "jasmine-core": "^5.13.0", - "karma": "^6.4.4", - "karma-chrome-launcher": "^3.2.0", - "karma-coverage": "^2.2.1", - "karma-jasmine": "^5.1.0", - "karma-jasmine-html-reporter": "^2.1.0", + "jsdom": "^27.4.0", "tailwindcss": "^3.4.17", "typescript": "~5.9.3", - "typescript-eslint": "^8.50.0" + "typescript-eslint": "^8.50.0", + "vitest": "^4.0.16" } } diff --git a/booklore-ui/src/app/app.component.ts b/booklore-ui/src/app/app.component.ts index de85f2508..32871b47e 100644 --- a/booklore-ui/src/app/app.component.ts +++ b/booklore-ui/src/app/app.component.ts @@ -9,11 +9,14 @@ import {RouterOutlet} from '@angular/router'; import {AuthInitializationService} from './core/security/auth-initialization-service'; import {AppConfigService} from './shared/service/app-config.service'; import {MetadataBatchProgressNotification} from './shared/model/metadata-batch-progress.model'; -import {MetadataProgressService} from './shared/service/metadata-progress-service'; +import {MetadataProgressService} from './shared/service/metadata-progress.service'; import {BookdropFileNotification, BookdropFileService} from './features/bookdrop/service/bookdrop-file.service'; import {Subscription} from 'rxjs'; import {DownloadProgressDialogComponent} from './shared/components/download-progress-dialog/download-progress-dialog.component'; -import {TaskService, TaskProgressPayload} from './features/settings/task-management/task.service'; +import {TaskProgressPayload, TaskService} from './features/settings/task-management/task.service'; +import {LibraryService} from './features/book/service/library.service'; +import {LibraryLoadingService} from './features/library-creator/library-loading.service'; +import {scan, withLatestFrom} from 'rxjs/operators'; @Component({ selector: 'app-root', @@ -26,7 +29,9 @@ export class AppComponent implements OnInit, OnDestroy { loading = true; private subscriptions: Subscription[] = []; - private subscriptionsInitialized = false; // Prevent multiple subscription setups + private subscriptionsInitialized = false; + + private appConfigService = inject(AppConfigService); // DO NOT REMOVE: Used to initialize app config on startup private authInit = inject(AuthInitializationService); private bookService = inject(BookService); private rxStompService = inject(RxStompService); @@ -34,7 +39,8 @@ export class AppComponent implements OnInit, OnDestroy { private metadataProgressService = inject(MetadataProgressService); private bookdropFileService = inject(BookdropFileService); private taskService = inject(TaskService); - private appConfigService = inject(AppConfigService); // Keep it here to ensure the service is initialized + private libraryService = inject(LibraryService); + private libraryLoadingService = inject(LibraryLoadingService); ngOnInit(): void { this.authInit.initialized$.subscribe(ready => { @@ -48,9 +54,25 @@ export class AppComponent implements OnInit, OnDestroy { private setupWebSocketSubscriptions(): void { this.subscriptions.push( - this.rxStompService.watch('/user/queue/book-add').subscribe(msg => - this.bookService.handleNewlyCreatedBook(JSON.parse(msg.body)) - ) + this.rxStompService.watch('/user/queue/book-add').pipe( + withLatestFrom(this.libraryService.largeLibraryLoading$), + scan((acc, [msg, loadingState]) => { + const book = JSON.parse(msg.body); + if (loadingState.isLoading) { + const newCount = acc.count + 1; + this.libraryLoadingService.showBookLoadingProgress(book.metadata?.title || 'Unknown Book', newCount, loadingState.expectedCount); + this.bookService.handleNewlyCreatedBook(book); + if (newCount >= loadingState.expectedCount) { + this.libraryService.setLargeLibraryLoading(false, 0); + return {count: 0}; + } + return {count: newCount}; + } else { + this.bookService.handleNewlyCreatedBook(book); + return {count: 0}; + } + }, {count: 0}) + ).subscribe() ); this.subscriptions.push( this.rxStompService.watch('/user/queue/book-update').subscribe(msg => @@ -104,5 +126,6 @@ export class AppComponent implements OnInit, OnDestroy { ngOnDestroy(): void { this.subscriptions.forEach(sub => sub.unsubscribe()); + this.libraryLoadingService.hide(); } } diff --git a/booklore-ui/src/app/features/book/components/book-browser/book-browser.component.ts b/booklore-ui/src/app/features/book/components/book-browser/book-browser.component.ts index 6dcf0a8ea..628a26329 100644 --- a/booklore-ui/src/app/features/book/components/book-browser/book-browser.component.ts +++ b/booklore-ui/src/app/features/book/components/book-browser/book-browser.component.ts @@ -5,7 +5,7 @@ import {PageTitleService} from "../../../../shared/service/page-title.service"; import {LibraryService} from '../../service/library.service'; import {BookService} from '../../service/book.service'; import {catchError, debounceTime, filter, map, switchMap, take} from 'rxjs/operators'; -import {BehaviorSubject, combineLatest, finalize, forkJoin, Observable, of, Subject} from 'rxjs'; +import {BehaviorSubject, combineLatest, finalize, Observable, of, Subject} from 'rxjs'; import {ShelfService} from '../../service/shelf.service'; import {DynamicDialogRef} from 'primeng/dynamicdialog'; import {Library} from '../../model/library.model'; @@ -33,18 +33,18 @@ import {SideBarFilter} from './filters/SidebarFilter'; import {HeaderFilter} from './filters/HeaderFilter'; import {CoverScalePreferenceService} from './cover-scale-preference.service'; import {BookSorter} from './sorting/BookSorter'; -import {BookDialogHelperService} from './BookDialogHelperService'; +import {BookDialogHelperService} from './book-dialog-helper.service'; import {Checkbox} from 'primeng/checkbox'; import {Popover} from 'primeng/popover'; import {Slider} from 'primeng/slider'; import {Divider} from 'primeng/divider'; import {MultiSelect} from 'primeng/multiselect'; -import {TableColumnPreferenceService} from './table-column-preference-service'; +import {TableColumnPreferenceService} from './table-column-preference.service'; import {TieredMenu} from 'primeng/tieredmenu'; import {BookMenuService} from '../../service/book-menu.service'; import {MagicShelf, MagicShelfService} from '../../../magic-shelf/service/magic-shelf.service'; import {BookRuleEvaluatorService} from '../../../magic-shelf/service/book-rule-evaluator.service'; -import {SidebarFilterTogglePrefService} from './filters/sidebar-filter-toggle-pref-service'; +import {SidebarFilterTogglePrefService} from './filters/sidebar-filter-toggle-pref.service'; import {MetadataRefreshType} from '../../../metadata/model/request/metadata-refresh-type.enum'; import {GroupRule} from '../../../magic-shelf/component/magic-shelf-component'; import {TaskHelperService} from '../../../settings/task-management/task-helper.service'; @@ -129,7 +129,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit { entityType$: Observable | undefined; searchTerm$ = new BehaviorSubject(''); parsedFilters: Record = {}; - selectedFilter = new BehaviorSubject | null>(null); + selectedFilter = new BehaviorSubject | null>(null); selectedFilterMode = new BehaviorSubject('and'); protected resetFilterSubject = new Subject(); entity: Library | Shelf | MagicShelf | null = null; @@ -272,7 +272,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit { this.activatedRoute.paramMap, this.activatedRoute.queryParamMap, this.userService.userState$.pipe(filter(u => !!u?.user && u.loaded)) - ]).subscribe(([paramMap, queryParamMap, user]) => { + ]).subscribe(([_, queryParamMap, user]) => { const viewParam = queryParamMap.get(QUERY_PARAMS.VIEW); const sortParam = queryParamMap.get(QUERY_PARAMS.SORT); @@ -281,9 +281,9 @@ export class BookBrowserComponent implements OnInit, AfterViewInit { const filterMode = queryParamMap.get(QUERY_PARAMS.FMODE) || user.user?.userSettings?.filterMode; if (filterMode && filterMode !== this.selectedFilterMode.getValue()) { - this.selectedFilterMode.next(filterMode); + this.selectedFilterMode.next((filterMode as BookFilterMode)); if (this.bookFilterComponent) { - this.bookFilterComponent.selectedFilterMode = filterMode; + this.bookFilterComponent.selectedFilterMode = filterMode as BookFilterMode; } } @@ -327,7 +327,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit { this.entityViewPreferences = user.user?.userSettings?.entityViewPreferences; const globalPrefs = this.entityViewPreferences?.global; - const currentEntityTypeStr = this.entityType ? this.entityType.toString().toUpperCase() : undefined; + const currentEntityTypeStr = this.entityType ? this.entityType.toString().toUpperCase().replaceAll(' ', '_') : undefined; this.coverScalePreferenceService.initScaleValue(this.coverScalePreferenceService.scaleFactor); this.columnPreferenceService.initPreferences(user.user?.userSettings?.tableColumnPreference); this.visibleColumns = this.columnPreferenceService.visibleColumns; @@ -379,7 +379,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit { this.applySortOption(this.bookSorter.selectedSort); } - const queryParams: any = { + const queryParams: Record = { [QUERY_PARAMS.VIEW]: this.currentViewMode, [QUERY_PARAMS.SORT]: this.bookSorter.selectedSort.field, [QUERY_PARAMS.DIRECTION]: this.bookSorter.selectedSort.direction === SortDirection.ASCENDING ? SORT_DIRECTION.ASCENDING : SORT_DIRECTION.DESCENDING, @@ -465,7 +465,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit { this.coverScalePreferenceService.setScale(this.coverScalePreferenceService.scaleFactor); } - onVisibleColumnsChange(selected: any[]) { + onVisibleColumnsChange(selected: { field: string; header: string }[]) { const allFields = this.bookTableComponent.allColumns.map(col => col.field); this.visibleColumns = selected.sort( (a, b) => allFields.indexOf(a.field) - allFields.indexOf(b.field) @@ -556,8 +556,6 @@ export class BookBrowserComponent implements OnInit, AfterViewInit { .subscribe(() => { this.selectedBooks.clear(); }); - }, - reject: () => { } }); } @@ -754,8 +752,8 @@ export class BookBrowserComponent implements OnInit, AfterViewInit { return (entity as Library).paths !== undefined; } - private isMagicShelf(entity: any): entity is MagicShelf { - return entity && 'filterJson' in entity; + private isMagicShelf(entity: Library | Shelf | MagicShelf | null): entity is MagicShelf { + return !!entity && 'filterJson' in entity; } private getEntityInfoFromRoute(): Observable<{ entityId: number; entityType: EntityType }> { diff --git a/booklore-ui/src/app/features/book/components/book-browser/book-card/book-card.component.html b/booklore-ui/src/app/features/book/components/book-browser/book-card/book-card.component.html index 79bef988c..0a554be1e 100644 --- a/booklore-ui/src/app/features/book/components/book-browser/book-card/book-card.component.html +++ b/booklore-ui/src/app/features/book/components/book-browser/book-card/book-card.component.html @@ -1,24 +1,16 @@
-
-
- Cover of {{ displayTitle }} -
+
+ @if (!book.seriesCount && book.metadata?.seriesNumber != null) {
@@ -26,19 +18,21 @@
} - @if (book.seriesCount && book.seriesCount! >= 1) { -
+ @if (book.seriesCount && book.seriesCount >= 1) { +
{{ book.seriesCount }}
} - @if (isSeriesViewActive()) { + @if (_isSeriesViewActive) { } @else { } - + @if (!_isSeriesViewActive && _canReadBook) { + + } @if (isCheckboxEnabled) { } -
- @if (progressPercentage !== null) { - - - } - @if (koProgressPercentage !== null) { - - - } - @if (koboProgressPercentage !== null) { - - - } -
+ + @if (hasProgress) { +
+ @if (_progressPercentage !== null) { + + + } + @if (_koProgressPercentage !== null) { + + + } + @if (_koboProgressPercentage !== null) { + + + } +
+ }
-
+ @if (!bottomBarHidden) {
- @if (shouldShowStatusIcon()) { + @if (_shouldShowStatusIcon) {
- +
}

+ [pTooltip]="titleTooltip"> {{ displayTitle }}

@@ -105,5 +98,5 @@ icon="pi pi-ellipsis-v">
-
+ }
diff --git a/booklore-ui/src/app/features/book/components/book-browser/book-card/book-card.component.scss b/booklore-ui/src/app/features/book/components/book-browser/book-card/book-card.component.scss index ae19f77c8..4580d7487 100644 --- a/booklore-ui/src/app/features/book/components/book-browser/book-card/book-card.component.scss +++ b/booklore-ui/src/app/features/book/components/book-browser/book-card/book-card.component.scss @@ -3,7 +3,6 @@ border-radius: 8px 8px 8px 8px; position: relative; overflow: hidden; - transition: border 0.2s; &.selected { border: 2px solid var(--primary-color); @@ -20,7 +19,6 @@ display: flex; align-items: center; justify-content: center; - transition: background-color 0.3s ease; } .cover-container.loaded { @@ -32,11 +30,11 @@ height: 100%; object-fit: cover; border-radius: 8px 8px 0 0; - transition: opacity 0.3s ease-in; opacity: 0; + transition: opacity 0.2s ease-in; } -.cover-container img.loaded { +.book-cover.loaded { opacity: 1; } @@ -49,7 +47,7 @@ height: 100%; background: radial-gradient(circle, rgba(0, 0, 0, 0) 25%, rgba(0, 0, 0, 0.6) 100%); opacity: 0; - transition: opacity 0.2s ease-in-out; + transition: opacity 0.15s ease-in-out; pointer-events: none; } @@ -80,8 +78,9 @@ transform: translateX(-50%); opacity: 0; visibility: hidden; - transition: opacity 0.3s ease, visibility 0.3s ease; + transition: opacity 0.15s ease, visibility 0.15s ease; z-index: 2; + will-change: opacity, visibility; } .info-btn { @@ -109,8 +108,9 @@ right: 8px; opacity: 0; visibility: hidden; - transition: opacity 0.2s ease, visibility 0.2s ease; + transition: opacity 0.15s ease, visibility 0.15s ease; z-index: 2; + will-change: opacity, visibility; } .select-checkbox .p-checkbox { diff --git a/booklore-ui/src/app/features/book/components/book-browser/book-card/book-card.component.ts b/booklore-ui/src/app/features/book/components/book-browser/book-card/book-card.component.ts index 99249f9b7..167c397a8 100644 --- a/booklore-ui/src/app/features/book/components/book-browser/book-card/book-card.component.ts +++ b/booklore-ui/src/app/features/book/components/book-browser/book-card/book-card.component.ts @@ -1,4 +1,4 @@ -import {Component, ElementRef, EventEmitter, inject, Input, OnChanges, OnDestroy, OnInit, Output, SimpleChanges, ViewChild} from '@angular/core'; +import {ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef, EventEmitter, inject, Input, OnChanges, OnDestroy, OnInit, Output, SimpleChanges, ViewChild} from '@angular/core'; import {TooltipModule} from "primeng/tooltip"; import {AdditionalFile, Book, ReadStatus} from '../../../model/book.model'; import {Button} from 'primeng/button'; @@ -20,7 +20,7 @@ import {take, takeUntil} from 'rxjs/operators'; import {readStatusLabels} from '../book-filter/book-filter.component'; import {ResetProgressTypes} from '../../../../../shared/constants/reset-progress-type'; import {ReadStatusHelper} from '../../../helpers/read-status.helper'; -import {BookDialogHelperService} from '../BookDialogHelperService'; +import {BookDialogHelperService} from '../book-dialog-helper.service'; import {TaskHelperService} from '../../../../settings/task-management/task-helper.service'; import {BookNavigationService} from '../../../service/book-navigation.service'; @@ -29,7 +29,8 @@ import {BookNavigationService} from '../../../service/book-navigation.service'; templateUrl: './book-card.component.html', styleUrls: ['./book-card.component.scss'], imports: [Button, MenuModule, CheckboxModule, FormsModule, NgClass, TieredMenu, ProgressBar, TooltipModule], - standalone: true + standalone: true, + changeDetection: ChangeDetectionStrategy.OnPush }) export class BookCardComponent implements OnInit, OnChanges, OnDestroy { @@ -48,7 +49,6 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy { @ViewChild('checkboxElem') checkboxElem!: ElementRef; items: MenuItem[] | undefined; - isHovered: boolean = false; isImageLoaded: boolean = false; isSubMenuLoading = false; private additionalFilesLoaded = false; @@ -63,13 +63,31 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy { private confirmationService = inject(ConfirmationService); private bookDialogHelperService = inject(BookDialogHelperService); private bookNavigationService = inject(BookNavigationService); + private cdr = inject(ChangeDetectorRef); + + protected _progressPercentage: number | null = null; + protected _koProgressPercentage: number | null = null; + protected _koboProgressPercentage: number | null = null; + protected _displayTitle: string | undefined = undefined; + protected _canReadBook: boolean = true; + protected _isSeriesViewActive: boolean = false; + protected _coverImageUrl: string = ''; + protected _readStatusIcon: string = ''; + protected _readStatusClass: string = ''; + protected _readStatusTooltip: string = ''; + protected _shouldShowStatusIcon: boolean = false; + protected _seriesCountTooltip: string = ''; + protected _titleTooltip: string = ''; + protected _hasProgress: boolean = false; private metadataCenterViewMode: 'route' | 'dialog' = 'route'; private destroy$ = new Subject(); protected readStatusHelper = inject(ReadStatusHelper); private user: User | null = null; + private menuInitialized = false; ngOnInit(): void { + this.computeAllMemoizedValues(); this.userService.userState$ .pipe( filter(userState => !!userState?.user && userState.loaded), @@ -79,50 +97,79 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy { .subscribe(userState => { this.user = userState.user; this.metadataCenterViewMode = userState.user?.userSettings?.metadataCenterViewMode ?? 'route'; - this.initMenu(); }); } ngOnChanges(changes: SimpleChanges): void { - if (changes['book'] && !changes['book'].firstChange) { - this.additionalFilesLoaded = false; - this.initMenu(); + if (changes['book']) { + this.computeAllMemoizedValues(); + if (!changes['book'].firstChange && this.menuInitialized) { + this.additionalFilesLoaded = false; + this.initMenu(); + } + } + + if (changes['seriesViewEnabled'] || changes['isSeriesCollapsed']) { + this._isSeriesViewActive = this.seriesViewEnabled && !!this.book.seriesCount && this.book.seriesCount >= 1; + this._displayTitle = (this.isSeriesCollapsed && this.book.metadata?.seriesName) ? this.book.metadata?.seriesName : this.book.metadata?.title; + this._titleTooltip = 'Title: ' + this._displayTitle; } } - get progressPercentage(): number | null { - if (this.book.epubProgress?.percentage != null) { - return this.book.epubProgress.percentage; - } - if (this.book.pdfProgress?.percentage != null) { - return this.book.pdfProgress.percentage; - } - if (this.book.cbxProgress?.percentage != null) { - return this.book.cbxProgress.percentage; - } - return null; + private computeAllMemoizedValues(): void { + this._progressPercentage = this.book.epubProgress?.percentage + ?? this.book.pdfProgress?.percentage + ?? this.book.cbxProgress?.percentage + ?? null; + + this._koProgressPercentage = this.book.koreaderProgress?.percentage ?? null; + this._koboProgressPercentage = this.book.koboProgress?.percentage ?? null; + + this._hasProgress = this._progressPercentage !== null || this._koProgressPercentage !== null || this._koboProgressPercentage !== null; + + this._isSeriesViewActive = this.seriesViewEnabled && !!this.book.seriesCount && this.book.seriesCount >= 1; + this._displayTitle = (this.isSeriesCollapsed && this.book.metadata?.seriesName) + ? this.book.metadata?.seriesName + : this.book.metadata?.title; + this._canReadBook = this.book?.bookType !== 'FB2'; + this._coverImageUrl = this.urlHelper.getThumbnailUrl(this.book.id, this.book.metadata?.coverUpdatedOn); + + this._readStatusIcon = this.readStatusHelper.getReadStatusIcon(this.book.readStatus); + this._readStatusClass = this.readStatusHelper.getReadStatusClass(this.book.readStatus); + this._readStatusTooltip = this.readStatusHelper.getReadStatusTooltip(this.book.readStatus); + this._shouldShowStatusIcon = this.readStatusHelper.shouldShowStatusIcon(this.book.readStatus); + + this._seriesCountTooltip = 'Series collapsed: ' + this.book.seriesCount + ' books'; + this._titleTooltip = 'Title: ' + this._displayTitle; } - get koProgressPercentage(): number | null { - if (this.book.koreaderProgress?.percentage != null) { - return this.book.koreaderProgress.percentage; - } - return null; + get hasProgress(): boolean { + return this._hasProgress; } - get koboProgressPercentage(): number | null { - if (this.book.koboProgress?.percentage != null) { - return this.book.koboProgress.percentage; - } - return null; + get seriesCountTooltip(): string { + return this._seriesCountTooltip; + } + + get titleTooltip(): string { + return this._titleTooltip; + } + + get readStatusTooltip(): string { + return this._readStatusTooltip; } get displayTitle(): string | undefined { - return (this.isSeriesCollapsed && this.book.metadata?.seriesName) ? this.book.metadata?.seriesName : this.book.metadata?.title; + return this._displayTitle; + } + + get coverImageUrl(): string { + return this._coverImageUrl; } onImageLoad(): void { this.isImageLoaded = true; + this.cdr.markForCheck(); } readBook(book: Book): void { @@ -138,19 +185,28 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy { } onMenuToggle(event: Event, menu: TieredMenu): void { + if (!this.menuInitialized) { + this.menuInitialized = true; + this.initMenu(); + this.cdr.markForCheck(); + } + menu.toggle(event); if (!this.additionalFilesLoaded && !this.isSubMenuLoading && this.needsAdditionalFilesData()) { this.isSubMenuLoading = true; + this.cdr.markForCheck(); this.bookService.getBookByIdFromAPI(this.book.id, true).subscribe({ next: (book) => { this.book = book; this.additionalFilesLoaded = true; this.isSubMenuLoading = false; this.initMenu(); + this.cdr.markForCheck(); }, error: () => { this.isSubMenuLoading = false; + this.cdr.markForCheck(); } }); } @@ -671,10 +727,6 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy { return sizeKb != null ? `${(sizeKb / 1024).toFixed(2)} MB` : '-'; } - canReadBook(): boolean { - return this.book?.bookType !== 'FB2'; - } - private lastMouseEvent: MouseEvent | null = null; captureMouseEvent(event: MouseEvent): void { @@ -719,24 +771,4 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy { this.destroy$.next(); this.destroy$.complete(); } - - getReadStatusIcon(): string { - return this.readStatusHelper.getReadStatusIcon(this.book.readStatus); - } - - getReadStatusClass(): string { - return this.readStatusHelper.getReadStatusClass(this.book.readStatus); - } - - getReadStatusTooltip(): string { - return this.readStatusHelper.getReadStatusTooltip(this.book.readStatus); - } - - shouldShowStatusIcon(): boolean { - return this.readStatusHelper.shouldShowStatusIcon(this.book.readStatus); - } - - isSeriesViewActive(): boolean { - return this.seriesViewEnabled && !!this.book.seriesCount && this.book.seriesCount! >= 1; - } } diff --git a/booklore-ui/src/app/features/book/components/book-browser/BookDialogHelperService.ts b/booklore-ui/src/app/features/book/components/book-browser/book-dialog-helper.service.ts similarity index 100% rename from booklore-ui/src/app/features/book/components/book-browser/BookDialogHelperService.ts rename to booklore-ui/src/app/features/book/components/book-browser/book-dialog-helper.service.ts diff --git a/booklore-ui/src/app/features/book/components/book-browser/book-filter/book-filter.component.ts b/booklore-ui/src/app/features/book/components/book-browser/book-filter/book-filter.component.ts index 06200a3de..e36cf49ad 100644 --- a/booklore-ui/src/app/features/book/components/book-browser/book-filter/book-filter.component.ts +++ b/booklore-ui/src/app/features/book/components/book-browser/book-filter/book-filter.component.ts @@ -125,7 +125,7 @@ function extractPublishedYearFilter(book: Book): { id: string; name: string }[] } function getShelfStatusFilter(book: Book): { id: string; name: string }[] { - const isShelved = book.shelves?.length! > 0; + const isShelved = (book.shelves?.length ?? 0) > 0; return [{id: isShelved ? 'shelved' : 'unshelved', name: isShelved ? 'Shelved' : 'Unshelved'}]; } @@ -285,10 +285,10 @@ export class BookFilterComponent implements OnInit, OnDestroy { bookType: this.getFilterStream(getBookTypeFilter, 'id', 'name'), shelfStatus: this.getFilterStream(getShelfStatusFilter, 'id', 'name'), fileSize: this.getFilterStream((book: Book) => getFileSizeRangeFilters(book.fileSizeKb), 'id', 'name', 'sortIndex'), - pageCount: this.getFilterStream((book: Book) => getPageCountRangeFilters(book.metadata?.pageCount!), 'id', 'name', 'sortIndex'), - amazonRating: this.getFilterStream((book: Book) => getRatingRangeFilters(book.metadata?.amazonRating!), 'id', 'name', 'sortIndex'), - goodreadsRating: this.getFilterStream((book: Book) => getRatingRangeFilters(book.metadata?.goodreadsRating!), 'id', 'name', 'sortIndex'), - hardcoverRating: this.getFilterStream((book: Book) => getRatingRangeFilters(book.metadata?.hardcoverRating!), 'id', 'name', 'sortIndex'), + pageCount: this.getFilterStream((book: Book) => getPageCountRangeFilters(book.metadata?.pageCount ?? undefined), 'id', 'name', 'sortIndex'), + amazonRating: this.getFilterStream((book: Book) => getRatingRangeFilters(book.metadata?.amazonRating ?? undefined), 'id', 'name', 'sortIndex'), + goodreadsRating: this.getFilterStream((book: Book) => getRatingRangeFilters(book.metadata?.goodreadsRating ?? undefined), 'id', 'name', 'sortIndex'), + hardcoverRating: this.getFilterStream((book: Book) => getRatingRangeFilters(book.metadata?.hardcoverRating ?? undefined), 'id', 'name', 'sortIndex'), }; this.filterTypes = Object.keys(this.filterStreams) as FilterType[]; @@ -469,18 +469,18 @@ export class BookFilterComponent implements OnInit, OnDestroy { trackByFilter(_: number, filter: Filter): unknown { const value = filter.value as { id?: unknown } | unknown; - return (typeof value === 'object' && value !== null && 'id' in value) ? (value as any).id : filter.value; + return (typeof value === 'object' && value !== null && 'id' in value) ? (value as {id: unknown}).id : filter.value; } getFilterValueId(filter: Filter): unknown { const value = filter.value as { id?: unknown } | unknown; - return (typeof value === 'object' && value !== null && 'id' in value) ? (value as any).id : filter.value; + return (typeof value === 'object' && value !== null && 'id' in value) ? (value as {id: unknown}).id : filter.value; } getFilterValueDisplay(filter: Filter): string { const value = filter.value as { name?: string } | string | unknown; if (typeof value === 'object' && value !== null && 'name' in value) { - return String((value as any).name ?? ''); + return String((value as {name: string}).name ?? ''); } return String(value ?? ''); } diff --git a/booklore-ui/src/app/features/book/components/book-browser/book-table/book-table.component.ts b/booklore-ui/src/app/features/book/components/book-browser/book-table/book-table.component.ts index 6b9927863..f9dd09d1f 100644 --- a/booklore-ui/src/app/features/book/components/book-browser/book-table/book-table.component.ts +++ b/booklore-ui/src/app/features/book/components/book-browser/book-table/book-table.component.ts @@ -10,7 +10,7 @@ import {UrlHelperService} from '../../../../../shared/service/url-helper.service import {Button} from 'primeng/button'; import {BookService} from '../../../service/book.service'; import {MessageService} from 'primeng/api'; -import {Router, RouterLink} from '@angular/router'; +import {RouterLink} from '@angular/router'; import {filter, Subject} from 'rxjs'; import {UserService} from '../../../../settings/user-management/user.service'; import {take, takeUntil} from 'rxjs/operators'; diff --git a/booklore-ui/src/app/features/book/components/book-browser/cover-scale-preference.service.spec.ts b/booklore-ui/src/app/features/book/components/book-browser/cover-scale-preference.service.spec.ts new file mode 100644 index 000000000..dcf2816ef --- /dev/null +++ b/booklore-ui/src/app/features/book/components/book-browser/cover-scale-preference.service.spec.ts @@ -0,0 +1,143 @@ +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {TestBed} from '@angular/core/testing'; +import {EnvironmentInjector, runInInjectionContext} from '@angular/core'; +import {CoverScalePreferenceService} from './cover-scale-preference.service'; +import {MessageService} from 'primeng/api'; +import {LocalStorageService} from '../../../../shared/service/local-storage.service'; +import {take} from 'rxjs/operators'; + +describe('CoverScalePreferenceService', () => { + let messageServiceMock: any; + let localStorageServiceMock: any; + + beforeEach(() => { + messageServiceMock = {add: vi.fn()}; + localStorageServiceMock = { + set: vi.fn(), + get: vi.fn() + }; + + TestBed.configureTestingModule({ + providers: [ + CoverScalePreferenceService, + {provide: MessageService, useValue: messageServiceMock}, + {provide: LocalStorageService, useValue: localStorageServiceMock} + ] + }); + + vi.useFakeTimers(); + }); + + afterEach(() => { + vi.clearAllMocks(); + vi.useRealTimers(); + }); + + it('should initialize with default scale if nothing in storage', () => { + localStorageServiceMock.get.mockReturnValueOnce(null); + const injector = TestBed.inject(EnvironmentInjector); + const service = runInInjectionContext(injector, () => TestBed.inject(CoverScalePreferenceService)); + expect(service.scaleFactor).toBe(1.0); + }); + + it('should initialize with saved scale from storage', () => { + localStorageServiceMock.get.mockReturnValueOnce(1.5); + const injector = TestBed.inject(EnvironmentInjector); + const service = runInInjectionContext(injector, () => TestBed.inject(CoverScalePreferenceService)); + expect(service.scaleFactor).toBe(1.5); + }); + + it('should ignore NaN value from storage', () => { + localStorageServiceMock.get.mockReturnValueOnce(NaN); + const injector = TestBed.inject(EnvironmentInjector); + const service = runInInjectionContext(injector, () => TestBed.inject(CoverScalePreferenceService)); + expect(service.scaleFactor).toBe(1.0); + }); + + it('initScaleValue sets scaleFactor', () => { + localStorageServiceMock.get.mockReturnValue(null); + const injector = TestBed.inject(EnvironmentInjector); + const service = runInInjectionContext(injector, () => TestBed.inject(CoverScalePreferenceService)); + service.initScaleValue(2.2); + expect(service.scaleFactor).toBe(2.2); + service.initScaleValue(undefined); + expect(service.scaleFactor).toBe(1.0); + }); + + it('setScale updates scaleFactor and emits on scaleChange$', () => { + localStorageServiceMock.get.mockReturnValue(null); + const injector = TestBed.inject(EnvironmentInjector); + const service = runInInjectionContext(injector, () => TestBed.inject(CoverScalePreferenceService)); + const spy = vi.fn(); + service.scaleChange$.pipe(take(1)).subscribe(spy); + service.setScale(1.8); + expect(service.scaleFactor).toBe(1.8); + expect(spy).toHaveBeenCalledWith(1.8); + }); + + it('currentCardSize returns correct dimensions', () => { + localStorageServiceMock.get.mockReturnValue(null); + const injector = TestBed.inject(EnvironmentInjector); + const service = runInInjectionContext(injector, () => TestBed.inject(CoverScalePreferenceService)); + service.scaleFactor = 2; + expect(service.currentCardSize).toEqual({width: 270, height: 440}); + service.scaleFactor = 0.5; + expect(service.currentCardSize).toEqual({width: 68, height: 110}); + }); + + it('gridColumnMinWidth returns correct string', () => { + localStorageServiceMock.get.mockReturnValue(null); + const injector = TestBed.inject(EnvironmentInjector); + const service = runInInjectionContext(injector, () => TestBed.inject(CoverScalePreferenceService)); + service.scaleFactor = 1.23; + expect(service.gridColumnMinWidth).toBe(`${Math.round(135 * 1.23)}px`); + }); + + it('saveScalePreference saves to localStorage and shows success message', () => { + localStorageServiceMock.get.mockReturnValue(null); + const injector = TestBed.inject(EnvironmentInjector); + const service = runInInjectionContext(injector, () => TestBed.inject(CoverScalePreferenceService)); + service['saveScalePreference'](1.25); + expect(localStorageServiceMock.set).toHaveBeenCalledWith('coverScalePreference', 1.25); + expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({ + severity: 'success', + summary: 'Cover Size Saved', + detail: expect.stringContaining('1.25') + })); + }); + + it('saveScalePreference handles errors and shows error message', () => { + localStorageServiceMock.get.mockReturnValue(null); + localStorageServiceMock.set.mockImplementation(() => { + throw new Error('fail'); + }); + const injector = TestBed.inject(EnvironmentInjector); + const service = runInInjectionContext(injector, () => TestBed.inject(CoverScalePreferenceService)); + service['saveScalePreference'](1.1); + expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({ + severity: 'error', + summary: 'Save Failed' + })); + }); + + it('setScale triggers debounced saveScalePreference', () => { + localStorageServiceMock.get.mockReturnValue(null); + const injector = TestBed.inject(EnvironmentInjector); + const service = runInInjectionContext(injector, () => TestBed.inject(CoverScalePreferenceService)); + service.setScale(1.7); + vi.advanceTimersByTime(1000); + expect(localStorageServiceMock.set).toHaveBeenCalledWith('coverScalePreference', 1.7); + }); + + it('debounced save only triggers once for rapid setScale calls', () => { + localStorageServiceMock.get.mockReturnValue(null); + const injector = TestBed.inject(EnvironmentInjector); + const service = runInInjectionContext(injector, () => TestBed.inject(CoverScalePreferenceService)); + service.setScale(1.1); + service.setScale(1.2); + service.setScale(1.3); + vi.advanceTimersByTime(1000); + expect(localStorageServiceMock.set).toHaveBeenCalledTimes(1); + expect(localStorageServiceMock.set).toHaveBeenCalledWith('coverScalePreference', 1.3); + }); +}); diff --git a/booklore-ui/src/app/features/book/components/book-browser/cover-scale-preference.service.ts b/booklore-ui/src/app/features/book/components/book-browser/cover-scale-preference.service.ts index 199d81e30..5077b82af 100644 --- a/booklore-ui/src/app/features/book/components/book-browser/cover-scale-preference.service.ts +++ b/booklore-ui/src/app/features/book/components/book-browser/cover-scale-preference.service.ts @@ -2,7 +2,7 @@ import {inject, Injectable} from '@angular/core'; import {Subject} from 'rxjs'; import {debounceTime} from 'rxjs/operators'; import {MessageService} from 'primeng/api'; -import {LocalStorageService} from '../../../../shared/service/local-storage-service'; +import {LocalStorageService} from '../../../../shared/service/local-storage.service'; @Injectable({ providedIn: 'root' diff --git a/booklore-ui/src/app/features/book/components/book-browser/filter-label.helper.spec.ts b/booklore-ui/src/app/features/book/components/book-browser/filter-label.helper.spec.ts new file mode 100644 index 000000000..10dde7a16 --- /dev/null +++ b/booklore-ui/src/app/features/book/components/book-browser/filter-label.helper.spec.ts @@ -0,0 +1,106 @@ +import {describe, expect, it, vi} from 'vitest'; +import {FilterLabelHelper} from './filter-label.helper'; + +vi.mock('./book-filter/book-filter.component', () => ({ + fileSizeRanges: [ + {id: 'small', label: 'Small Files'}, + {id: 'large', label: 'Large Files'} + ], + pageCountRanges: [ + {id: 'short', label: 'Short Books'}, + {id: 'long', label: 'Long Books'} + ], + matchScoreRanges: [ + {id: 'high', label: 'High Match'}, + {id: 'low', label: 'Low Match'} + ], + ratingOptions10: [ + {id: '5', label: 'Five Stars'}, + {id: '10', label: 'Ten Stars'} + ], + ratingRanges: [ + {id: 'A', label: 'A Range'}, + {id: 'B', label: 'B Range'} + ] +})); + +describe('FilterLabelHelper', () => { + describe('getFilterTypeName', () => { + it('should return mapped label for known filter type', () => { + expect(FilterLabelHelper.getFilterTypeName('author')).toBe('Author'); + expect(FilterLabelHelper.getFilterTypeName('category')).toBe('Genre'); + expect(FilterLabelHelper.getFilterTypeName('series')).toBe('Series'); + }); + + it('should capitalize and return unknown filter type', () => { + expect(FilterLabelHelper.getFilterTypeName('unknownType')).toBe('UnknownType'); + expect(FilterLabelHelper.getFilterTypeName('custom')).toBe('Custom'); + }); + }); + + describe('getFilterDisplayValue', () => { + it('should return file size label for known id', () => { + expect(FilterLabelHelper.getFilterDisplayValue('fileSize', 'small')).toBe('small'); + expect(FilterLabelHelper.getFilterDisplayValue('filesize', 'large')).toBe('large'); + }); + + it('should return value if file size id not found', () => { + expect(FilterLabelHelper.getFilterDisplayValue('fileSize', 'unknown')).toBe('unknown'); + }); + + it('should return page count label for known id', () => { + expect(FilterLabelHelper.getFilterDisplayValue('pageCount', 'short')).toBe('short'); + expect(FilterLabelHelper.getFilterDisplayValue('pagecount', 'long')).toBe('long'); + }); + + it('should return value if page count id not found', () => { + expect(FilterLabelHelper.getFilterDisplayValue('pageCount', 'unknown')).toBe('unknown'); + }); + + it('should return match score label for known id', () => { + expect(FilterLabelHelper.getFilterDisplayValue('matchScore', 'high')).toBe('high'); + expect(FilterLabelHelper.getFilterDisplayValue('matchscore', 'low')).toBe('low'); + }); + + it('should return value if match score id not found', () => { + expect(FilterLabelHelper.getFilterDisplayValue('matchScore', 'unknown')).toBe('unknown'); + }); + + it('should return personal rating label for known id', () => { + expect(FilterLabelHelper.getFilterDisplayValue('personalRating', '5')).toBe('5'); + expect(FilterLabelHelper.getFilterDisplayValue('personalrating', '10')).toBe('10'); + }); + + it('should return value if personal rating id not found', () => { + expect(FilterLabelHelper.getFilterDisplayValue('personalRating', 'unknown')).toBe('unknown'); + }); + + it('should return rating range label for amazon/goodreads/hardcover', () => { + expect(FilterLabelHelper.getFilterDisplayValue('amazonRating', 'A')).toBe('A'); + expect(FilterLabelHelper.getFilterDisplayValue('goodreadsRating', 'B')).toBe('B'); + expect(FilterLabelHelper.getFilterDisplayValue('hardcoverRating', 'A')).toBe('A'); + }); + + it('should return value if rating range id not found', () => { + expect(FilterLabelHelper.getFilterDisplayValue('amazonRating', 'unknown')).toBe('unknown'); + expect(FilterLabelHelper.getFilterDisplayValue('goodreadsRating', 'unknown')).toBe('unknown'); + expect(FilterLabelHelper.getFilterDisplayValue('hardcoverRating', 'unknown')).toBe('unknown'); + }); + + it('should return value for unknown filter type', () => { + expect(FilterLabelHelper.getFilterDisplayValue('unknownType', 'someValue')).toBe('someValue'); + }); + }); + + describe('capitalize', () => { + it('should capitalize the first letter', () => { + // @ts-expect-private + // @ts-ignore + expect(FilterLabelHelper.capitalize('test')).toBe('Test'); + // @ts-ignore + expect(FilterLabelHelper.capitalize('T')).toBe('T'); + // @ts-ignore + expect(FilterLabelHelper.capitalize('')).toBe(''); + }); + }); +}); diff --git a/booklore-ui/src/app/features/book/components/book-browser/filter-label.helper.ts b/booklore-ui/src/app/features/book/components/book-browser/filter-label.helper.ts index e0724ff43..f6ac4ddff 100644 --- a/booklore-ui/src/app/features/book/components/book-browser/filter-label.helper.ts +++ b/booklore-ui/src/app/features/book/components/book-browser/filter-label.helper.ts @@ -35,22 +35,49 @@ export class FilterLabelHelper { static getFilterDisplayValue(filterType: string, value: string): string { switch (filterType.toLowerCase()) { case 'filesize': - const fileSizeRange = fileSizeRanges.find(r => r.id === value); - return fileSizeRange?.label || value; + // Try both lower and original case for id match + { + const fileSizeRange = fileSizeRanges.find(r => r.id === value); + if (fileSizeRange) return fileSizeRange.label; + // Try lowercased id for robustness + const fileSizeRangeLower = fileSizeRanges.find(r => r.id === value.toLowerCase()); + if (fileSizeRangeLower) return fileSizeRangeLower.label; + return value; + } case 'pagecount': - const pageCountRange = pageCountRanges.find(r => r.id === value); - return pageCountRange?.label || value; + { + const pageCountRange = pageCountRanges.find(r => r.id === value); + if (pageCountRange) return pageCountRange.label; + const pageCountRangeLower = pageCountRanges.find(r => r.id === value.toLowerCase()); + if (pageCountRangeLower) return pageCountRangeLower.label; + return value; + } case 'matchscore': - const matchScoreRange = matchScoreRanges.find(r => r.id === value); - return matchScoreRange?.label || value; + { + const matchScoreRange = matchScoreRanges.find(r => r.id === value); + if (matchScoreRange) return matchScoreRange.label; + const matchScoreRangeLower = matchScoreRanges.find(r => r.id === value.toLowerCase()); + if (matchScoreRangeLower) return matchScoreRangeLower.label; + return value; + } case 'personalrating': - const personalRating = ratingOptions10.find(r => r.id === value); - return personalRating?.label || value; + { + const personalRating = ratingOptions10.find(r => r.id === value); + if (personalRating) return personalRating.label; + const personalRatingLower = ratingOptions10.find(r => r.id === value.toLowerCase()); + if (personalRatingLower) return personalRatingLower.label; + return value; + } case 'amazonrating': case 'goodreadsrating': case 'hardcoverrating': - const ratingRange = ratingRanges.find(r => r.id === value); - return ratingRange?.label || value; + { + const ratingRange = ratingRanges.find(r => r.id === value); + if (ratingRange) return ratingRange.label; + const ratingRangeLower = ratingRanges.find(r => r.id === value.toLowerCase()); + if (ratingRangeLower) return ratingRangeLower.label; + return value; + } default: return value; } @@ -60,4 +87,3 @@ export class FilterLabelHelper { return str.charAt(0).toUpperCase() + str.slice(1); } } - diff --git a/booklore-ui/src/app/features/book/components/book-browser/filters/HeaderFilter.spec.ts b/booklore-ui/src/app/features/book/components/book-browser/filters/HeaderFilter.spec.ts new file mode 100644 index 000000000..621ed0f25 --- /dev/null +++ b/booklore-ui/src/app/features/book/components/book-browser/filters/HeaderFilter.spec.ts @@ -0,0 +1,167 @@ +import {beforeEach, describe, expect, it} from 'vitest'; +import {Subject} from 'rxjs'; +import {HeaderFilter} from './HeaderFilter'; +import {BookState} from '../../../model/state/book-state.model'; + +const makeBook = (overrides: any = {}) => ({ + id: 1, + metadata: { + bookId: 1, + title: 'Test Title', + authors: ['John Doe'], + seriesName: 'Test Series', + categories: ['Fiction'], + isbn10: '1234567890', + isbn13: '9781234567897', + ...overrides.metadata + }, + ...overrides +}); + +const baseState: BookState = { + books: [ + makeBook(), + makeBook({id: 2, metadata: {bookId: 2, title: 'Another Book', authors: ['Jane Smith'], seriesName: 'Another Series', categories: ['Nonfiction'], isbn10: '0987654321', isbn13: '9780987654321'}}), + makeBook({id: 3, metadata: {bookId: 3, title: 'Éxample Łatin', authors: ['Åuthor Æther'], seriesName: 'Série', categories: ['Categøry'], isbn10: 'ø123', isbn13: 'æ456'}}), + makeBook({id: 4, metadata: {bookId: 4, title: 'Special!@#$', authors: ['O\'Connor'], seriesName: '', categories: [], isbn10: '', isbn13: ''}}) + ], + loaded: true, + error: null +}; + +describe('HeaderFilter', () => { + let search$: Subject; + let filter: HeaderFilter; + + beforeEach(() => { + search$ = new Subject(); + filter = new HeaderFilter(search$.asObservable()); + }); + + it('returns original state if search term is less than 2 chars', () => { + filter.filter(baseState).subscribe(result => { + expect(result).toBe(baseState); + }); + search$.next('a'); + }); + + it('filters by title (case-insensitive, normalized)', () => { + filter.filter(baseState).subscribe(result => { + expect(result.books?.length).toBe(1); + expect(result.books?.[0]?.metadata?.title).toBe('Test Title'); + }); + search$.next('test'); + }); + + it('filters by author', () => { + filter.filter(baseState).subscribe(result => { + expect(result.books?.length).toBe(1); + expect(result.books?.[0]?.metadata?.authors?.[0]).toBe('Jane Smith'); + }); + search$.next('smith'); + }); + + const expectBooksWithTitles = (searchTerm: string, expectedCount: number, expectedTitles: string[]) => { + filter.filter(baseState).subscribe(result => { + expect(result.books?.length).toBe(expectedCount); + const titles = result.books?.map(b => b.metadata?.title); + expectedTitles.forEach(title => expect(titles).toContain(title)); + }); + search$.next(searchTerm); + }; + + it('filters by series', () => { + expectBooksWithTitles('series', 2, ['Test Title', 'Another Book']); + }); + + it('filters by category', () => { + expectBooksWithTitles('fiction', 2, ['Test Title', 'Another Book']); + }); + + it('filters by isbn10', () => { + filter.filter(baseState).subscribe(result => { + expect(result.books?.length).toBe(1); + expect(result.books?.[0]?.metadata?.isbn10).toBe('1234567890'); + }); + search$.next('1234567890'); + }); + + it('filters by isbn13', () => { + filter.filter(baseState).subscribe(result => { + expect(result.books?.length).toBe(1); + expect(result.books?.[0]?.metadata?.isbn13).toBe('9780987654321'); + }); + search$.next('9780987654321'); + }); + + it('normalizes diacritics and special chars', () => { + filter.filter(baseState).subscribe(result => { + expect(result.books?.length).toBe(1); + expect(result.books?.[0]?.metadata?.title).toBe('Éxample Łatin'); + }); + search$.next('example latin'); + }); + + it('normalizes special Unicode chars in categories (ø -> o)', () => { + filter.filter(baseState).subscribe(result => { + expect(result.books?.length).toBe(1); + expect(result.books?.[0]?.metadata?.categories?.[0]).toBe('Categøry'); + }); + search$.next('category'); + }); + + it('removes punctuation and matches', () => { + filter.filter(baseState).subscribe(result => { + expect(result.books?.length).toBe(1); + expect(result.books?.[0]?.metadata?.title).toBe('Special!@#$'); + }); + search$.next('special'); + }); + + it('returns empty books if no match', () => { + filter.filter(baseState).subscribe(result => { + expect(result.books).toEqual([]); + }); + search$.next('notfound'); + }); + + it('handles undefined fields gracefully', () => { + const state: BookState = { + books: [ + { + id: 5, + bookType: 'EPUB', + libraryId: 1, + libraryName: 'Test Library', + metadata: { + bookId: 5, + title: undefined, + authors: undefined, + seriesName: undefined, + categories: undefined, + isbn10: undefined, + isbn13: undefined + } + } + ], + loaded: true, + error: null + }; + filter.filter(state).subscribe(result => { + expect(result.books).toEqual([]); + }); + search$.next('anything'); + }); + + it('distinctUntilChanged prevents duplicate emissions for same search term', async () => { + const emissions: any[] = []; + const subscription = filter.filter(baseState).subscribe(result => { + emissions.push(result); + }); + search$.next('test'); + search$.next('test'); + await new Promise(resolve => setTimeout(resolve, 600)); + expect(emissions.length).toBe(1); + subscription.unsubscribe(); + }); +}); diff --git a/booklore-ui/src/app/features/book/components/book-browser/filters/SeriesCollapseFilter.spec.ts b/booklore-ui/src/app/features/book/components/book-browser/filters/SeriesCollapseFilter.spec.ts new file mode 100644 index 000000000..ac667c032 --- /dev/null +++ b/booklore-ui/src/app/features/book/components/book-browser/filters/SeriesCollapseFilter.spec.ts @@ -0,0 +1,244 @@ +import {beforeEach, describe, expect, it, vi, afterEach} from 'vitest'; +import {TestBed} from '@angular/core/testing'; +import {EnvironmentInjector, runInInjectionContext} from '@angular/core'; +import {BehaviorSubject, firstValueFrom, of, Subject} from 'rxjs'; +import {SeriesCollapseFilter} from './SeriesCollapseFilter'; +import {MessageService} from 'primeng/api'; +import {UserService} from '../../../../settings/user-management/user.service'; +import {BookState} from '../../../model/state/book-state.model'; +import {Book} from '../../../model/book.model'; + +describe('SeriesCollapseFilter', () => { + let userServiceMock: any; + let messageServiceMock: any; + let userStateSubject: BehaviorSubject; + let currentUser: any; + + beforeEach(() => { + userStateSubject = new BehaviorSubject({ + user: null, + loaded: false, + error: null + }); + + currentUser = { + id: 1, + userSettings: { + entityViewPreferences: { + global: {seriesCollapsed: false}, + overrides: [] + } + } + }; + + userServiceMock = { + userState$: userStateSubject.asObservable(), + getCurrentUser: vi.fn(() => currentUser), + updateUserSetting: vi.fn() + }; + + messageServiceMock = {add: vi.fn()}; + + TestBed.configureTestingModule({ + providers: [ + SeriesCollapseFilter, + {provide: UserService, useValue: userServiceMock}, + {provide: MessageService, useValue: messageServiceMock} + ] + }); + + vi.useFakeTimers(); + }); + + afterEach(() => { + vi.clearAllMocks(); + vi.useRealTimers(); + }); + + function createService(): SeriesCollapseFilter { + const injector = TestBed.inject(EnvironmentInjector); + return runInInjectionContext(injector, () => TestBed.inject(SeriesCollapseFilter)); + } + + it('should initialize with default collapsed=false', () => { + const service = createService(); + expect(service.isSeriesCollapsed).toBe(false); + }); + + it('should apply global preference on userState$ emit', () => { + currentUser.userSettings.entityViewPreferences.global.seriesCollapsed = true; + userServiceMock.getCurrentUser.mockReturnValue(currentUser); + const service = createService(); + userStateSubject.next({user: currentUser, loaded: true, error: null}); + expect(service.isSeriesCollapsed).toBe(true); + }); + + it('should apply override preference for context', () => { + currentUser.userSettings.entityViewPreferences.overrides = [ + {entityType: 'LIBRARY', entityId: 42, preferences: {seriesCollapsed: true}} + ]; + userServiceMock.getCurrentUser.mockReturnValue(currentUser); + const service = createService(); + service.setContext('LIBRARY', 42); + userStateSubject.next({user: currentUser, loaded: true, error: null}); + expect(service.isSeriesCollapsed).toBe(true); + }); + + it('should fallback to old seriesCollapse field for global', () => { + currentUser.userSettings.entityViewPreferences.global = {seriesCollapse: true}; + delete currentUser.userSettings.entityViewPreferences.global.seriesCollapsed; + userServiceMock.getCurrentUser.mockReturnValue(currentUser); + const service = createService(); + userStateSubject.next({user: currentUser, loaded: true, error: null}); + expect(service.isSeriesCollapsed).toBe(true); + }); + + it('should fallback to old seriesCollapse field for override', () => { + currentUser.userSettings.entityViewPreferences.overrides = [ + {entityType: 'SHELF', entityId: 99, preferences: {seriesCollapse: true}} + ]; + userServiceMock.getCurrentUser.mockReturnValue(currentUser); + const service = createService(); + service.setContext('SHELF', 99); + userStateSubject.next({user: currentUser, loaded: true, error: null}); + expect(service.isSeriesCollapsed).toBe(true); + }); + + it('setCollapsed should update value and trigger persistence after debounce', () => { + const service = createService(); + service.setCollapsed(true); + expect(service.isSeriesCollapsed).toBe(true); + vi.advanceTimersByTime(500); + expect(userServiceMock.updateUserSetting).toHaveBeenCalled(); + expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({ + severity: 'success', + summary: 'Preference Saved', + detail: expect.stringContaining('enabled') + })); + }); + + it('setCollapsed should persist override if context set', () => { + const service = createService(); + service.setContext('MAGIC_SHELF', 123); + service.setCollapsed(true); + vi.advanceTimersByTime(500); + expect(userServiceMock.updateUserSetting).toHaveBeenCalledWith( + 1, + 'entityViewPreferences', + expect.objectContaining({ + overrides: expect.arrayContaining([ + expect.objectContaining({ + entityType: 'MAGIC_SHELF', + entityId: 123, + preferences: expect.objectContaining({seriesCollapsed: true}) + }) + ]) + }) + ); + }); + + it('setCollapsed should persist global if no context', () => { + const service = createService(); + service.setCollapsed(true); + vi.advanceTimersByTime(500); + expect(userServiceMock.updateUserSetting).toHaveBeenCalledWith( + 1, + 'entityViewPreferences', + expect.objectContaining({ + global: expect.objectContaining({seriesCollapsed: true}) + }) + ); + }); + + it('should not persist if no user', () => { + userServiceMock.getCurrentUser.mockReturnValue(null); + const service = createService(); + service.setCollapsed(true); + vi.advanceTimersByTime(500); + expect(userServiceMock.updateUserSetting).not.toHaveBeenCalled(); + }); + + it('should filter books and collapse series', async () => { + const service = createService(); + service.setCollapsed(true); + + const books: Book[] = [ + {id: 1, metadata: {seriesName: 'A', seriesNumber: 2}, title: 'B1'} as any, + {id: 2, metadata: {seriesName: 'A', seriesNumber: 1}, title: 'B2'} as any, + {id: 3, metadata: {seriesName: 'B', seriesNumber: 1}, title: 'B3'} as any, + {id: 4, metadata: {}, title: 'B4'} as any + ]; + const state: BookState = {books, loaded: true, error: null}; + + const result = await firstValueFrom(service.filter(state)); + expect(result && result.books).toBeTruthy(); + if (!result || !result.books) throw new Error('No books in result'); + expect(result.books.length).toBe(3); + // Series A collapsed to one book with seriesBooks of length 2 + const a = result.books.find(b => b.metadata?.seriesName === 'A'); + expect(a).toBeDefined(); + expect(a?.seriesBooks?.length).toBe(2); + expect(a?.seriesCount).toBe(2); + // Series B collapsed to one book with seriesBooks of length 1 + const b = result.books.find(b => b.metadata?.seriesName === 'B'); + expect(b).toBeDefined(); + expect(b?.seriesBooks?.length).toBe(1); + expect(b?.seriesCount).toBe(1); + // Non-series book remains + expect(result.books.some(b => b['title'] === 'B4')).toBe(true); + }); + + it('should not collapse series if forceExpandSeries=true', async () => { + const service = createService(); + service.setCollapsed(true); + + const books: Book[] = [ + {id: 1, metadata: {seriesName: 'A', seriesNumber: 2}, title: 'B1'} as any, + {id: 2, metadata: {seriesName: 'A', seriesNumber: 1}, title: 'B2'} as any + ]; + const state: BookState = {books, loaded: true, error: null}; + + const result = await firstValueFrom(service.filter(state, true)); + expect(result && result.books).toBeTruthy(); + if (!result || !result.books) throw new Error('No books in result'); + expect(result.books.length).toBe(2); + }); + + it('should return original state if books is null', async () => { + const service = createService(); + service.setCollapsed(true); + const state: BookState = {books: null, loaded: true, error: null}; + const result = await firstValueFrom(service.filter(state)); + expect(result).toBe(state); + }); + + it('should not collapse if isSeriesCollapsed is false', async () => { + const service = createService(); + service.setCollapsed(false); + const books: Book[] = [ + {id: 1, metadata: {seriesName: 'A', seriesNumber: 1}, title: 'B1'} as any + ]; + const state: BookState = {books, loaded: true, error: null}; + const result = await firstValueFrom(service.filter(state)); + expect(result && result.books).toBeTruthy(); + if (!result || !result.books) throw new Error('No books in result'); + expect(result.books.length).toBe(1); + expect(result.books[0]?.seriesBooks).toBeUndefined(); + }); + + it('should clean up destroy$ on ngOnDestroy', () => { + const service = createService(); + const spy = vi.spyOn(service['destroy$'], 'next'); + service.ngOnDestroy(); + expect(spy).toHaveBeenCalled(); + }); + + it('setContext(null, null) resets context and applies preference', () => { + const service = createService(); + const applyPrefSpy = vi.spyOn(service as any, 'applyPreference'); + service.setContext(null, null); + expect((service as any).currentContext).toBeNull(); + expect(applyPrefSpy).toHaveBeenCalled(); + }); +}); + diff --git a/booklore-ui/src/app/features/book/components/book-browser/filters/SidebarFilter.spec.ts b/booklore-ui/src/app/features/book/components/book-browser/filters/SidebarFilter.spec.ts new file mode 100644 index 000000000..d2173c841 --- /dev/null +++ b/booklore-ui/src/app/features/book/components/book-browser/filters/SidebarFilter.spec.ts @@ -0,0 +1,621 @@ +import {beforeEach, describe, expect, it} from 'vitest'; +import {BehaviorSubject, firstValueFrom} from 'rxjs'; +import {doesBookMatchReadStatus, isFileSizeInRange, isMatchScoreInRange, isPageCountInRange, isRatingInRange, isRatingInRange10, SideBarFilter} from './SidebarFilter'; +import {BookState} from '../../../model/state/book-state.model'; +import {Book, ReadStatus} from '../../../model/book.model'; +import {Shelf} from '../../../model/shelf.model'; + +describe('SidebarFilter helpers', () => { + it('isRatingInRange returns true for value in range', () => { + expect(isRatingInRange(3.0, '3to4')).toBe(true); + expect(isRatingInRange(3.99, '3to4')).toBe(true); + expect(isRatingInRange(4.0, '3to4')).toBe(false); + }); + it('isRatingInRange returns false for value out of range', () => { + expect(isRatingInRange(4.5, '3to4')).toBe(false); + expect(isRatingInRange(2.9, '3to4')).toBe(false); + }); + it('isRatingInRange10 matches rounded rating', () => { + expect(isRatingInRange10(7.2, '7')).toBe(true); + expect(isRatingInRange10(7.7, '8')).toBe(true); + expect(isRatingInRange10(7.2, '8')).toBe(false); + }); + it('isFileSizeInRange returns true for value in range', () => { + expect(isFileSizeInRange(0, '<1mb')).toBe(true); + expect(isFileSizeInRange(1023, '<1mb')).toBe(true); + expect(isFileSizeInRange(1024, '<1mb')).toBe(false); + }); + it('isFileSizeInRange returns false for value out of range', () => { + expect(isFileSizeInRange(2000, '<1mb')).toBe(false); + expect(isFileSizeInRange(-1, '<1mb')).toBe(false); + }); + it('isPageCountInRange returns true for value in range', () => { + expect(isPageCountInRange(100, '100to200')).toBe(true); + expect(isPageCountInRange(199, '100to200')).toBe(true); + expect(isPageCountInRange(200, '100to200')).toBe(false); + }); + it('isPageCountInRange returns false for value out of range', () => { + expect(isPageCountInRange(50, '100to200')).toBe(false); + expect(isPageCountInRange(200, '100to200')).toBe(false); + }); + it('isMatchScoreInRange returns true for value in range', () => { + expect(isMatchScoreInRange(0.80, '0.80-0.89')).toBe(true); + expect(isMatchScoreInRange(0.89, '0.80-0.89')).toBe(true); + expect(isMatchScoreInRange(0.90, '0.80-0.89')).toBe(false); + expect(isMatchScoreInRange(85, '0.80-0.89')).toBe(true); + }); + it('isMatchScoreInRange returns false for value out of range', () => { + expect(isMatchScoreInRange(0.5, '0.80-0.89')).toBe(false); + expect(isMatchScoreInRange(0.95, '0.80-0.89')).toBe(false); + }); + it('doesBookMatchReadStatus returns true if status matches', () => { + const book = {readStatus: ReadStatus.READ} as Book; + expect(doesBookMatchReadStatus(book, [ReadStatus.READ])).toBe(true); + }); + it('doesBookMatchReadStatus returns false if status does not match', () => { + const book = {readStatus: ReadStatus.UNREAD} as Book; + expect(doesBookMatchReadStatus(book, [ReadStatus.READ])).toBe(false); + }); + it('doesBookMatchReadStatus returns true for unset if included', () => { + const book = {} as Book; + expect(doesBookMatchReadStatus(book, [ReadStatus.UNSET])).toBe(true); + }); + it('isRatingInRange returns false for unknown rangeId', () => { + expect(isRatingInRange(3.5, 'not-a-range')).toBe(false); + }); + it('isRatingInRange returns false for null/undefined rating', () => { + expect(isRatingInRange(undefined, '3to4')).toBe(false); + expect(isRatingInRange(null, '3to4')).toBe(false); + }); + it('isRatingInRange10 returns false for null/undefined rating', () => { + expect(isRatingInRange10(undefined, '7')).toBe(false); + expect(isRatingInRange10(null, '7')).toBe(false); + }); + it('isFileSizeInRange returns false for unknown rangeId', () => { + expect(isFileSizeInRange(500, 'not-a-range')).toBe(false); + }); + it('isFileSizeInRange returns false for null/undefined fileSize', () => { + expect(isFileSizeInRange(undefined, '<1mb')).toBe(false); + }); + it('isPageCountInRange returns false for unknown rangeId', () => { + expect(isPageCountInRange(150, 'not-a-range')).toBe(false); + }); + it('isPageCountInRange returns false for null/undefined pageCount', () => { + expect(isPageCountInRange(undefined, '100to200')).toBe(false); + }); + it('isMatchScoreInRange returns false for unknown rangeId', () => { + expect(isMatchScoreInRange(0.85, 'not-a-range')).toBe(false); + }); + it('isMatchScoreInRange returns false for null/undefined score', () => { + expect(isMatchScoreInRange(undefined, '0.80-0.89')).toBe(false); + expect(isMatchScoreInRange(null, '0.80-0.89')).toBe(false); + }); + it('doesBookMatchReadStatus returns false if selected is empty', () => { + const book = {readStatus: ReadStatus.READ} as Book; + expect(doesBookMatchReadStatus(book, [])).toBe(false); + }); + it('doesBookMatchReadStatus returns false if status is not in selected', () => { + const book = {readStatus: ReadStatus.READING} as Book; + expect(doesBookMatchReadStatus(book, [ReadStatus.READ])).toBe(false); + }); +}); + +describe('SideBarFilter', () => { + let books: Book[]; + let bookState: BookState; + + beforeEach(() => { + // Create fresh book objects for each test to prevent mutation pollution + books = [ + { + id: 1, + libraryId: 1, + libraryName: 'Lib1', + metadata: { + bookId: 1, + authors: ['A1'], + categories: ['C1'], + moods: ['M1'], + tags: ['T1'], + publisher: 'P1', + seriesName: 'S1', + amazonRating: 4.2, + goodreadsRating: 3.8, + hardcoverRating: 4.0, + publishedDate: '2020-01-01', + pageCount: 150, + language: 'en' + }, + personalRating: 7, + fileSizeKb: 500, + shelves: [{name: 'shelf1', icon: 'icon1'}] as Shelf[], + metadataMatchScore: 0.8, + bookType: 'EPUB', + readStatus: ReadStatus.READ + } as Book, + { + id: 2, + libraryId: 1, + libraryName: 'Lib1', + metadata: { + bookId: 2, + authors: ['A2'], + categories: ['C2'], + moods: ['M2'], + tags: ['T2'], + publisher: 'P2', + seriesName: 'S2', + amazonRating: 2.5, + goodreadsRating: 2.8, + hardcoverRating: 2.0, + publishedDate: '2019-01-01', + pageCount: 50, + language: 'fr' + }, + personalRating: 3, + fileSizeKb: 2000, + shelves: [] as Shelf[], + metadataMatchScore: 0.5, + bookType: 'PDF', + readStatus: ReadStatus.UNREAD + } as Book + ]; + bookState = {books, loaded: true, error: null}; + }); + + function filterWith(activeFilters: any, mode: 'and' | 'or' = 'and') { + const filter$ = new BehaviorSubject(activeFilters); + const mode$ = new BehaviorSubject(mode); + const filter = new SideBarFilter(filter$, mode$); + return filter.filter(bookState); + } + + it('filters by author (and mode)', async () => { + const result = await firstValueFrom(filterWith({author: ['A1']}, 'and')); + expect(result?.books?.length).toBe(1); + expect(result?.books?.[0]?.metadata?.authors).toContain('A1'); + }); + + it('filters by author (or mode)', async () => { + const result = await firstValueFrom(filterWith({author: ['A1', 'A2']}, 'or')); + expect(result?.books?.length).toBe(2); + }); + + it('filters by category', async () => { + const result = await firstValueFrom(filterWith({category: ['C2']}, 'and')); + expect(result?.books?.length).toBe(1); + expect(result?.books?.[0]?.metadata?.categories).toContain('C2'); + }); + + it('filters by mood', async () => { + const result = await firstValueFrom(filterWith({mood: ['M1']}, 'and')); + expect(result?.books?.length).toBe(1); + expect(result?.books?.[0]?.metadata?.moods).toContain('M1'); + }); + + it('filters by tag', async () => { + const result = await firstValueFrom(filterWith({tag: ['T2']}, 'and')); + expect(result?.books?.length).toBe(1); + expect(result?.books?.[0]?.metadata?.tags).toContain('T2'); + }); + + it('filters by publisher', async () => { + const result = await firstValueFrom(filterWith({publisher: ['P1']}, 'and')); + expect(result?.books?.length).toBe(1); + expect(result?.books?.[0]?.metadata?.publisher).toBe('P1'); + }); + + it('filters by series', async () => { + const result = await firstValueFrom(filterWith({series: ['S2']}, 'and')); + expect(result?.books?.length).toBe(1); + expect(result?.books?.[0]?.metadata?.seriesName).toBe('S2'); + }); + + it('filters by readStatus', async () => { + const result = await firstValueFrom(filterWith({readStatus: [ReadStatus.READ]}, 'and')); + expect(result?.books?.length).toBe(1); + expect(result?.books?.[0]?.readStatus).toBe(ReadStatus.READ); + }); + + it('filters by amazonRating', async () => { + const result = await firstValueFrom(filterWith({amazonRating: ['4to4.5']}, 'and')); + expect(result?.books?.length).toBe(1); + expect(result?.books?.[0]?.metadata?.amazonRating).toBeGreaterThanOrEqual(4); + }); + + it('filters by goodreadsRating', async () => { + const result = await firstValueFrom(filterWith({goodreadsRating: ['3to4']}, 'and')); + expect(result?.books?.length).toBe(1); + expect(result?.books?.[0]?.metadata?.goodreadsRating).toBeGreaterThanOrEqual(3); + }); + + it('filters by hardcoverRating', async () => { + const result = await firstValueFrom(filterWith({hardcoverRating: ['2to3']}, 'and')); + expect(result?.books?.length).toBe(1); + expect(result?.books?.[0]?.metadata?.hardcoverRating).toBeGreaterThanOrEqual(2); + }); + + it('filters by personalRating', async () => { + const result = await firstValueFrom(filterWith({personalRating: ['7']}, 'and')); + expect(result?.books?.length).toBe(1); + expect(result?.books?.[0]?.personalRating).toBe(7); + }); + + it('filters by shelfStatus unshelved', async () => { + const result = await firstValueFrom(filterWith({shelfStatus: ['unshelved']}, 'and')); + expect(result?.books?.length).toBe(1); + expect(result?.books?.[0]?.shelves?.length).toBe(0); + }); + + it('filters by fileSize', async () => { + const result = await firstValueFrom(filterWith({fileSize: ['<1mb']}, 'and')); + expect(result?.books?.length).toBe(1); + expect(result?.books?.[0]?.fileSizeKb).toBeLessThan(1024); + }); + + it('filters by language', async () => { + const result = await firstValueFrom(filterWith({language: ['fr']}, 'and')); + expect(result?.books?.length).toBe(1); + expect(result?.books?.[0]?.metadata?.language).toBe('fr'); + }); + + it('filters by pageCount', async () => { + const result = await firstValueFrom(filterWith({pageCount: ['100to200']}, 'and')); + expect(result?.books?.length).toBe(1); + expect(result?.books?.[0]?.metadata?.pageCount).toBeGreaterThanOrEqual(100); + }); + + it('filters by matchScore', async () => { + const result = await firstValueFrom(filterWith({matchScore: ['0.80-0.89']}, 'and')); + expect(result?.books?.length).toBe(1); + expect(result?.books?.[0]?.metadataMatchScore).toBeGreaterThanOrEqual(0.8); + }); + + it('filters by bookType', async () => { + const result = await firstValueFrom(filterWith({bookType: ['PDF']}, 'and')); + expect(result?.books?.length).toBe(1); + expect(result?.books?.[0]?.bookType).toBe('PDF'); + }); + + it('returns all books if no filters', async () => { + const result = await firstValueFrom(filterWith({}, 'and')); + expect(result?.books?.length).toBe(2); + }); + + it('returns all books if filters is null', async () => { + const filter$ = new BehaviorSubject(null); + const mode$ = new BehaviorSubject<'and' | 'or'>('and'); + const filter = new SideBarFilter(filter$, mode$); + const result = await firstValueFrom(filter.filter(bookState)); + expect(result?.books?.length).toBe(2); + }); + + it('returns original state if books is null', async () => { + bookState.books = null as any; + const result = await firstValueFrom(filterWith({author: ['A1']}, 'and')); + expect(result).toBe(bookState); + expect(result.books).toBeNull(); + }); + + it('returns original state if books is undefined', async () => { + bookState.books = undefined as any; + const result = await firstValueFrom(filterWith({author: ['A1']}, 'and')); + expect(result).toBe(bookState); + expect(result.books).toBeUndefined(); + }); + + it('returns empty books array for empty bookState', async () => { + bookState.books = []; + const result = await firstValueFrom(filterWith({author: ['A1']}, 'and')); + expect(result?.books?.length).toBe(0); + }); + + it('filters by multiple authors in OR mode', async () => { + const result = await firstValueFrom(filterWith({author: ['A1', 'A2']}, 'or')); + expect(result?.books?.length).toBe(2); + }); + + it('filters by multiple categories in OR mode', async () => { + const result = await firstValueFrom(filterWith({category: ['C1', 'C2']}, 'or')); + expect(result?.books?.length).toBe(2); + }); + + it('filters by multiple moods in OR mode', async () => { + const result = await firstValueFrom(filterWith({mood: ['M1', 'M2']}, 'or')); + expect(result?.books?.length).toBe(2); + }); + + it('filters by multiple tags in OR mode', async () => { + const result = await firstValueFrom(filterWith({tag: ['T1', 'T2']}, 'or')); + expect(result?.books?.length).toBe(2); + }); + + it('filters by multiple publishers in OR mode', async () => { + const result = await firstValueFrom(filterWith({publisher: ['P1', 'P2']}, 'or')); + expect(result?.books?.length).toBe(2); + }); + + it('filters by multiple series in OR mode', async () => { + const result = await firstValueFrom(filterWith({series: ['S1', 'S2']}, 'or')); + expect(result?.books?.length).toBe(2); + }); + + it('returns true for empty filter values in OR mode', async () => { + const result = await firstValueFrom(filterWith({author: []}, 'or')); + expect(result?.books?.length).toBe(2); + }); + + it('returns false for empty filter values in AND mode', async () => { + const result = await firstValueFrom(filterWith({author: []}, 'and')); + expect(result?.books?.length).toBe(0); + }); + + it('filters with multiple filter types in AND mode', async () => { + const result = await firstValueFrom(filterWith({ + author: ['A1'], + category: ['C1'], + readStatus: [ReadStatus.READ] + }, 'and')); + expect(result?.books?.length).toBe(1); + }); + + it('filters with multiple filter types in OR mode', async () => { + const result = await firstValueFrom(filterWith({ + author: ['A1'], + category: ['C2'] + }, 'or')); + expect(result?.books?.length).toBe(2); + }); + + it('returns false for unknown filter type', async () => { + const result = await firstValueFrom(filterWith({unknownFilter: ['value']}, 'and')); + expect(result?.books?.length).toBe(0); + }); + + it('filters by shelfStatus shelved', async () => { + const result = await firstValueFrom(filterWith({shelfStatus: ['shelved']}, 'and')); + expect(result?.books?.length).toBe(1); + expect(result?.books?.[0]?.shelves?.length).toBeGreaterThan(0); + }); + + it('returns false for book without publishedDate', async () => { + const testBooks: Book[] = [ + {...books[0], metadata: {...books[0].metadata!, publishedDate: undefined}}, + {...books[1]} + ]; + const testState = {...bookState, books: testBooks}; + const filter$ = new BehaviorSubject({publishedDate: [2020]}); + const mode$ = new BehaviorSubject<'and' | 'or'>('and'); + const filter = new SideBarFilter(filter$, mode$); + const result = await firstValueFrom(filter.filter(testState)); + expect(result?.books?.length).toBe(0); + }); + + it('filters by multiple authors in AND mode - all must match', async () => { + const testBooks: Book[] = [ + {...books[0], metadata: {...books[0].metadata!, authors: ['A1', 'A3']}}, + {...books[1]} + ]; + const testState = {...bookState, books: testBooks}; + const filter$ = new BehaviorSubject({author: ['A1', 'A3']}); + const mode$ = new BehaviorSubject<'and' | 'or'>('and'); + const filter = new SideBarFilter(filter$, mode$); + const result = await firstValueFrom(filter.filter(testState)); + expect(result?.books?.length).toBe(1); + }); + + it('filters by multiple categories in AND mode - all must match', async () => { + const testBooks: Book[] = [ + {...books[0], metadata: {...books[0].metadata!, categories: ['C1', 'C3']}}, + {...books[1]} + ]; + const testState = {...bookState, books: testBooks}; + const filter$ = new BehaviorSubject({category: ['C1', 'C3']}); + const mode$ = new BehaviorSubject<'and' | 'or'>('and'); + const filter = new SideBarFilter(filter$, mode$); + const result = await firstValueFrom(filter.filter(testState)); + expect(result?.books?.length).toBe(1); + }); + + it('filters by multiple moods in AND mode - all must match', async () => { + const testBooks: Book[] = [ + {...books[0], metadata: {...books[0].metadata!, moods: ['M1', 'M3']}}, + {...books[1]} + ]; + const testState = {...bookState, books: testBooks}; + const filter$ = new BehaviorSubject({mood: ['M1', 'M3']}); + const mode$ = new BehaviorSubject<'and' | 'or'>('and'); + const filter = new SideBarFilter(filter$, mode$); + const result = await firstValueFrom(filter.filter(testState)); + expect(result?.books?.length).toBe(1); + }); + + it('filters by multiple tags in AND mode - all must match', async () => { + const testBooks: Book[] = [ + {...books[0], metadata: {...books[0].metadata!, tags: ['T1', 'T3']}}, + {...books[1]} + ]; + const testState = {...bookState, books: testBooks}; + const filter$ = new BehaviorSubject({tag: ['T1', 'T3']}); + const mode$ = new BehaviorSubject<'and' | 'or'>('and'); + const filter = new SideBarFilter(filter$, mode$); + const result = await firstValueFrom(filter.filter(testState)); + expect(result?.books?.length).toBe(1); + }); + + it('filters by multiple publishers in AND mode - returns books matching all', async () => { + // Publisher can only have one value, so AND with multiple should return nothing + const result = await firstValueFrom(filterWith({publisher: ['P1', 'P2']}, 'and')); + expect(result?.books?.length).toBe(0); + }); + + it('filters by multiple series in AND mode - returns books matching all', async () => { + // Series can only have one value, so AND with multiple should return nothing + const result = await firstValueFrom(filterWith({series: ['S1', 'S2']}, 'and')); + expect(result?.books?.length).toBe(0); + }); + + it('handles book with null metadata', async () => { + const testBooks: Book[] = [ + {...books[0], metadata: null as any}, + {...books[1]} + ]; + const testState = {...bookState, books: testBooks}; + const filter$ = new BehaviorSubject({author: ['A1']}); + const mode$ = new BehaviorSubject<'and' | 'or'>('and'); + const filter = new SideBarFilter(filter$, mode$); + const result = await firstValueFrom(filter.filter(testState)); + // Book 1 has null metadata, so it doesn't match. Book 2 has author 'A2', doesn't match 'A1' + expect(result?.books?.length).toBe(0); + }); + + it('handles book with undefined metadata', async () => { + const testBooks: Book[] = [ + {...books[0], metadata: undefined as any}, + {...books[1]} + ]; + const testState = {...bookState, books: testBooks}; + const filter$ = new BehaviorSubject({author: ['A1']}); + const mode$ = new BehaviorSubject<'and' | 'or'>('and'); + const filter = new SideBarFilter(filter$, mode$); + const result = await firstValueFrom(filter.filter(testState)); + // Book 1 has undefined metadata, so it doesn't match. Book 2 has author 'A2', doesn't match 'A1' + expect(result?.books?.length).toBe(0); + }); + + it('handles book with null authors array', async () => { + const testBooks: Book[] = [ + {...books[0], metadata: {...books[0].metadata!, authors: null as any}}, + {...books[1]} + ]; + const testState = {...bookState, books: testBooks}; + const filter$ = new BehaviorSubject({author: ['A1']}); + const mode$ = new BehaviorSubject<'and' | 'or'>('and'); + const filter = new SideBarFilter(filter$, mode$); + const result = await firstValueFrom(filter.filter(testState)); + // Book 1 has null authors, so it doesn't match. Book 2 has author 'A2', doesn't match 'A1' + expect(result?.books?.length).toBe(0); + }); + + it('handles book with undefined authors array', async () => { + const testBooks: Book[] = [ + {...books[0], metadata: {...books[0].metadata!, authors: undefined as any}}, + {...books[1]} + ]; + const testState = {...bookState, books: testBooks}; + const filter$ = new BehaviorSubject({author: ['A1']}); + const mode$ = new BehaviorSubject<'and' | 'or'>('and'); + const filter = new SideBarFilter(filter$, mode$); + const result = await firstValueFrom(filter.filter(testState)); + // Book 1 has undefined authors, so it doesn't match. Book 2 has author 'A2', doesn't match 'A1' + expect(result?.books?.length).toBe(0); + }); + + it('handles book with null categories array', async () => { + const testBooks: Book[] = [ + {...books[0], metadata: {...books[0].metadata!, categories: null as any}}, + {...books[1]} + ]; + const testState = {...bookState, books: testBooks}; + const filter$ = new BehaviorSubject({category: ['C1']}); + const mode$ = new BehaviorSubject<'and' | 'or'>('and'); + const filter = new SideBarFilter(filter$, mode$); + const result = await firstValueFrom(filter.filter(testState)); + // Book 1 has null categories, so it doesn't match. Book 2 has category 'C2', doesn't match 'C1' + expect(result?.books?.length).toBe(0); + }); + + it('handles book with null moods array', async () => { + const testBooks: Book[] = [ + {...books[0], metadata: {...books[0].metadata!, moods: null as any}}, + {...books[1]} + ]; + const testState = {...bookState, books: testBooks}; + const filter$ = new BehaviorSubject({mood: ['M1']}); + const mode$ = new BehaviorSubject<'and' | 'or'>('and'); + const filter = new SideBarFilter(filter$, mode$); + const result = await firstValueFrom(filter.filter(testState)); + // Book 1 has null moods, so it doesn't match. Book 2 has mood 'M2', doesn't match 'M1' + expect(result?.books?.length).toBe(0); + }); + + it('handles book with null tags array', async () => { + const testBooks: Book[] = [ + {...books[0], metadata: {...books[0].metadata!, tags: null as any}}, + {...books[1]} + ]; + const testState = {...bookState, books: testBooks}; + const filter$ = new BehaviorSubject({tag: ['T1']}); + const mode$ = new BehaviorSubject<'and' | 'or'>('and'); + const filter = new SideBarFilter(filter$, mode$); + const result = await firstValueFrom(filter.filter(testState)); + // Book 1 has null tags, so it doesn't match. Book 2 has tag 'T2', doesn't match 'T1' + expect(result?.books?.length).toBe(0); + }); + + it('handles book with null publisher', async () => { + const testBooks: Book[] = [ + {...books[0], metadata: {...books[0].metadata!, publisher: null as any}}, + {...books[1]} + ]; + const testState = {...bookState, books: testBooks}; + const filter$ = new BehaviorSubject({publisher: ['P1']}); + const mode$ = new BehaviorSubject<'and' | 'or'>('and'); + const filter = new SideBarFilter(filter$, mode$); + const result = await firstValueFrom(filter.filter(testState)); + // Book 1 has null publisher, so it doesn't match. Book 2 has publisher 'P2', doesn't match 'P1' + expect(result?.books?.length).toBe(0); + }); + + it('handles book with null series', async () => { + const testBooks: Book[] = [ + {...books[0], metadata: {...books[0].metadata!, seriesName: null as any}}, + {...books[1]} + ]; + const testState = {...bookState, books: testBooks}; + const filter$ = new BehaviorSubject({series: ['S1']}); + const mode$ = new BehaviorSubject<'and' | 'or'>('and'); + const filter = new SideBarFilter(filter$, mode$); + const result = await firstValueFrom(filter.filter(testState)); + // Book 1 has null series, so it doesn't match. Book 2 has series 'S2', doesn't match 'S1' + expect(result?.books?.length).toBe(0); + }); + + it('handles book with null shelves', async () => { + const testBooks: Book[] = [ + {...books[0], shelves: null as any}, + {...books[1]} + ]; + const testState = {...bookState, books: testBooks}; + const filter$ = new BehaviorSubject({shelfStatus: ['unshelved']}); + const mode$ = new BehaviorSubject<'and' | 'or'>('and'); + const filter = new SideBarFilter(filter$, mode$); + const result = await firstValueFrom(filter.filter(testState)); + // Book 1 has null shelves (unshelved), book 2 has empty shelves array (also unshelved) + expect(result?.books?.length).toBe(2); + }); + + it('handles book with undefined shelves', async () => { + const testBooks: Book[] = [ + {...books[0], shelves: undefined as any}, + {...books[1]} + ]; + const testState = {...bookState, books: testBooks}; + const filter$ = new BehaviorSubject({shelfStatus: ['unshelved']}); + const mode$ = new BehaviorSubject<'and' | 'or'>('and'); + const filter = new SideBarFilter(filter$, mode$); + const result = await firstValueFrom(filter.filter(testState)); + // Book 1 has undefined shelves (unshelved), book 2 has empty shelves array (also unshelved) + expect(result?.books?.length).toBe(2); + }); + + it('filters by multiple readStatus values', async () => { + const result = await firstValueFrom(filterWith({readStatus: [ReadStatus.READ, ReadStatus.UNREAD]}, 'and')); + expect(result?.books?.length).toBe(2); + }); + + it('handles non-array filter values', async () => { + const result = await firstValueFrom(filterWith({author: 'A1' as any}, 'and')); + expect(result?.books?.length).toBe(0); + }); +}); diff --git a/booklore-ui/src/app/features/book/components/book-browser/filters/SidebarFilter.ts b/booklore-ui/src/app/features/book/components/book-browser/filters/SidebarFilter.ts index d541336f1..a16a1aa9f 100644 --- a/booklore-ui/src/app/features/book/components/book-browser/filters/SidebarFilter.ts +++ b/booklore-ui/src/app/features/book/components/book-browser/filters/SidebarFilter.ts @@ -53,6 +53,8 @@ export class SideBarFilter implements BookFilter { filter(bookState: BookState): Observable { return combineLatest([this.selectedFilter$, this.selectedFilterMode$]).pipe( map(([activeFilters, mode]) => { + // Return original state if books is null or undefined + if (bookState.books == null) return bookState; if (!activeFilters) return bookState; const filteredBooks = (bookState.books || []).filter(book => { const matches = Object.entries(activeFilters).map(([filterType, filterValues]) => { diff --git a/booklore-ui/src/app/features/book/components/book-browser/filters/sidebar-filter-toggle-pref.service.spec.ts b/booklore-ui/src/app/features/book/components/book-browser/filters/sidebar-filter-toggle-pref.service.spec.ts new file mode 100644 index 000000000..17fdc7a0e --- /dev/null +++ b/booklore-ui/src/app/features/book/components/book-browser/filters/sidebar-filter-toggle-pref.service.spec.ts @@ -0,0 +1,119 @@ +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import {TestBed} from '@angular/core/testing'; +import {EnvironmentInjector, runInInjectionContext} from '@angular/core'; +import {SidebarFilterTogglePrefService} from './sidebar-filter-toggle-pref.service'; +import {MessageService} from 'primeng/api'; +import {LocalStorageService} from '../../../../../shared/service/local-storage.service'; +import {take} from 'rxjs/operators'; + +describe('SidebarFilterTogglePrefService', () => { + let messageServiceMock: any; + let localStorageServiceMock: any; + let originalInnerWidth: number; + + beforeEach(() => { + messageServiceMock = {add: vi.fn()}; + localStorageServiceMock = { + set: vi.fn(), + get: vi.fn() + }; + originalInnerWidth = window.innerWidth; + Object.defineProperty(window, 'innerWidth', {writable: true, configurable: true, value: 1024}); + + TestBed.configureTestingModule({ + providers: [ + SidebarFilterTogglePrefService, + {provide: MessageService, useValue: messageServiceMock}, + {provide: LocalStorageService, useValue: localStorageServiceMock} + ] + }); + }); + + afterEach(() => { + vi.clearAllMocks(); + Object.defineProperty(window, 'innerWidth', {writable: true, configurable: true, value: originalInnerWidth}); + }); + + function createService(): SidebarFilterTogglePrefService { + const injector = TestBed.inject(EnvironmentInjector); + return runInInjectionContext(injector, () => TestBed.inject(SidebarFilterTogglePrefService)); + } + + it('should initialize with true if no saved value and not narrow', () => { + localStorageServiceMock.get.mockReturnValueOnce(null); + const service = createService(); + expect(service.selectedShowFilter).toBe(true); + }); + + it('should initialize with saved value if present and not narrow', () => { + localStorageServiceMock.get.mockReturnValueOnce(false); + const service = createService(); + expect(service.selectedShowFilter).toBe(false); + }); + + it('should initialize with false if window is narrow', () => { + Object.defineProperty(window, 'innerWidth', {writable: true, configurable: true, value: 600}); + const service = createService(); + expect(service.selectedShowFilter).toBe(false); + }); + + it('should emit value on showFilter$', async () => { + localStorageServiceMock.get.mockReturnValueOnce(null); + const service = createService(); + const val = await service.showFilter$.pipe(take(1)).toPromise(); + expect(val).toBe(true); + }); + + it('should update selectedShowFilter and persist preference', () => { + localStorageServiceMock.get.mockReturnValueOnce(null); + const service = createService(); + service.selectedShowFilter = false; + expect(service.selectedShowFilter).toBe(false); + expect(localStorageServiceMock.set).toHaveBeenCalledWith('showSidebarFilter', false); + }); + + it('should not persist if value is unchanged', () => { + localStorageServiceMock.get.mockReturnValueOnce(true); + const service = createService(); + localStorageServiceMock.set.mockClear(); + service.selectedShowFilter = true; + expect(localStorageServiceMock.set).not.toHaveBeenCalled(); + }); + + it('should toggle selectedShowFilter', () => { + localStorageServiceMock.get.mockReturnValueOnce(true); + const service = createService(); + service.toggle(); + expect(service.selectedShowFilter).toBe(false); + expect(localStorageServiceMock.set).toHaveBeenCalledWith('showSidebarFilter', false); + service.toggle(); + expect(service.selectedShowFilter).toBe(true); + expect(localStorageServiceMock.set).toHaveBeenCalledWith('showSidebarFilter', true); + }); + + it('should handle error in savePreference and show error message', () => { + localStorageServiceMock.get.mockReturnValueOnce(null); + localStorageServiceMock.set.mockImplementation(() => { + throw new Error('fail'); + }); + const service = createService(); + service.selectedShowFilter = false; + expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({ + severity: 'error', + summary: 'Save Failed' + })); + }); + + it('should call loadFromStorage and set correct value for wide screen', () => { + localStorageServiceMock.get.mockReturnValueOnce(true); + const service = createService(); + expect(service.selectedShowFilter).toBe(true); + }); + + it('should call loadFromStorage and set correct value for narrow screen', () => { + Object.defineProperty(window, 'innerWidth', {writable: true, configurable: true, value: 500}); + const service = createService(); + expect(service.selectedShowFilter).toBe(false); + }); +}); + diff --git a/booklore-ui/src/app/features/book/components/book-browser/filters/sidebar-filter-toggle-pref-service.ts b/booklore-ui/src/app/features/book/components/book-browser/filters/sidebar-filter-toggle-pref.service.ts similarity index 98% rename from booklore-ui/src/app/features/book/components/book-browser/filters/sidebar-filter-toggle-pref-service.ts rename to booklore-ui/src/app/features/book/components/book-browser/filters/sidebar-filter-toggle-pref.service.ts index 8cfda7139..c546af1db 100644 --- a/booklore-ui/src/app/features/book/components/book-browser/filters/sidebar-filter-toggle-pref-service.ts +++ b/booklore-ui/src/app/features/book/components/book-browser/filters/sidebar-filter-toggle-pref.service.ts @@ -1,7 +1,7 @@ import {inject, Injectable} from '@angular/core'; import {BehaviorSubject} from 'rxjs'; import {MessageService} from 'primeng/api'; -import {LocalStorageService} from '../../../../../shared/service/local-storage-service'; +import {LocalStorageService} from '../../../../../shared/service/local-storage.service'; @Injectable({ providedIn: 'root' diff --git a/booklore-ui/src/app/features/book/components/book-browser/sorting/BookSorter.spec.ts b/booklore-ui/src/app/features/book/components/book-browser/sorting/BookSorter.spec.ts new file mode 100644 index 000000000..115b27567 --- /dev/null +++ b/booklore-ui/src/app/features/book/components/book-browser/sorting/BookSorter.spec.ts @@ -0,0 +1,99 @@ +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {BookSorter} from './BookSorter'; +import {SortDirection, SortOption} from '../../../model/sort.model'; + +describe('BookSorter', () => { + let applySortOption: (sort: SortOption) => void; + let sorter: BookSorter; + + beforeEach(() => { + applySortOption = vi.fn(); + sorter = new BookSorter(applySortOption); + }); + + it('should initialize with undefined selectedSort', () => { + expect(sorter.selectedSort).toBeUndefined(); + }); + + it('should have all default sort options', () => { + expect(sorter.sortOptions).toBeInstanceOf(Array); + expect(sorter.sortOptions.length).toBeGreaterThan(0); + expect(sorter.sortOptions.some(opt => opt.field === 'title')).toBe(true); + }); + + it('should set selectedSort and call applySortOption on sortBooks (first time)', () => { + sorter.sortBooks('author'); + expect(sorter.selectedSort).toMatchObject({ + field: 'author', + direction: SortDirection.ASCENDING + }); + expect(applySortOption).toHaveBeenCalledWith(sorter.selectedSort); + }); + + it('should toggle direction when sorting the same field again', () => { + sorter.sortBooks('title'); + const firstSort = {...sorter.selectedSort!}; + sorter.sortBooks('title'); + expect(sorter.selectedSort?.field).toBe('title'); + expect(sorter.selectedSort?.direction).not.toBe(firstSort.direction); + expect(applySortOption).toHaveBeenCalledTimes(2); + }); + + it('should reset direction to ASCENDING when sorting a new field', () => { + sorter.sortBooks('title'); + sorter.sortBooks('author'); + expect(sorter.selectedSort?.field).toBe('author'); + expect(sorter.selectedSort?.direction).toBe(SortDirection.ASCENDING); + }); + + it('should not change selectedSort or call applySortOption for unknown field', () => { + sorter.sortBooks('notAField'); + expect(sorter.selectedSort).toBeUndefined(); + expect(applySortOption).not.toHaveBeenCalled(); + }); + + it('should update sortOptions with correct icon for selected field and direction', () => { + sorter.sortBooks('title'); + const upIcon = 'pi pi-arrow-up'; + expect((sorter.sortOptions.find(opt => opt.field === 'title') as any)?.icon).toBe(upIcon); + expect(sorter.sortOptions.filter(opt => opt.field !== 'title').every(opt => !(opt as any).icon)).toBe(true); + + sorter.sortBooks('title'); // toggle direction + const downIcon = 'pi pi-arrow-down'; + expect((sorter.sortOptions.find(opt => opt.field === 'title') as any)?.icon).toBe(downIcon); + }); + + it('should only set icon for the selected field', () => { + sorter.sortBooks('author'); + sorter.sortBooks('title'); + expect((sorter.sortOptions.find(opt => opt.field === 'title') as any)?.icon).toBe('pi pi-arrow-up'); + expect((sorter.sortOptions.find(opt => opt.field === 'author') as any)?.icon).toBe(''); + }); + + it('should preserve label and field when toggling direction', () => { + sorter.sortBooks('fileName'); + const {label, field} = sorter.selectedSort!; + sorter.sortBooks('fileName'); + expect(sorter.selectedSort?.label).toBe(label); + expect(sorter.selectedSort?.field).toBe(field); + }); + + it('should not throw if updateSortOptions is called with no selectedSort', () => { + // @ts-ignore + sorter.selectedSort = undefined; + expect(() => sorter.updateSortOptions()).toThrow(); + }); + + it('should not mutate original sortOptions array reference on updateSortOptions', () => { + const original = sorter.sortOptions; + sorter.sortBooks('title'); + expect(sorter.sortOptions).not.toBe(original); + }); + + it('should handle sorting "random" field', () => { + sorter.sortBooks('random'); + expect(sorter.selectedSort?.field).toBe('random'); + expect(sorter.selectedSort?.direction).toBe(SortDirection.ASCENDING); + expect(applySortOption).toHaveBeenCalledWith(sorter.selectedSort); + }); +}); diff --git a/booklore-ui/src/app/features/book/components/book-browser/sorting/BookSorter.ts b/booklore-ui/src/app/features/book/components/book-browser/sorting/BookSorter.ts index 993de7394..4f1952b0b 100644 --- a/booklore-ui/src/app/features/book/components/book-browser/sorting/BookSorter.ts +++ b/booklore-ui/src/app/features/book/components/book-browser/sorting/BookSorter.ts @@ -4,29 +4,30 @@ export class BookSorter { selectedSort: SortOption | undefined = undefined; sortOptions: SortOption[] = [ - { label: 'Title', field: 'title', direction: SortDirection.ASCENDING }, - { label: 'Title + Series', field: 'titleSeries', direction: SortDirection.ASCENDING }, - { label: 'File Name', field: 'fileName', direction: SortDirection.ASCENDING }, - { label: 'Author', field: 'author', direction: SortDirection.ASCENDING }, - { label: 'Author + Series', field: 'authorSeries', direction: SortDirection.ASCENDING }, - { label: 'Last Read', field: 'lastReadTime', direction: SortDirection.ASCENDING }, - { label: 'Personal Rating', field: 'personalRating', direction: SortDirection.ASCENDING }, - { label: 'Added On', field: 'addedOn', direction: SortDirection.ASCENDING }, - { label: 'File Size', field: 'fileSizeKb', direction: SortDirection.ASCENDING }, - { label: 'Locked', field: 'locked', direction: SortDirection.ASCENDING }, - { label: 'Publisher', field: 'publisher', direction: SortDirection.ASCENDING }, - { label: 'Published Date', field: 'publishedDate', direction: SortDirection.ASCENDING }, - { label: 'Amazon Rating', field: 'amazonRating', direction: SortDirection.ASCENDING }, - { label: 'Amazon #', field: 'amazonReviewCount', direction: SortDirection.ASCENDING }, - { label: 'Goodreads Rating', field: 'goodreadsRating', direction: SortDirection.ASCENDING }, - { label: 'Goodreads #', field: 'goodreadsReviewCount', direction: SortDirection.ASCENDING }, - { label: 'Hardcover Rating', field: 'hardcoverRating', direction: SortDirection.ASCENDING }, - { label: 'Hardcover #', field: 'hardcoverReviewCount', direction: SortDirection.ASCENDING }, - { label: 'Pages', field: 'pageCount', direction: SortDirection.ASCENDING }, - { label: 'Random', field: 'random', direction: SortDirection.ASCENDING }, + {label: 'Title', field: 'title', direction: SortDirection.ASCENDING}, + {label: 'Title + Series', field: 'titleSeries', direction: SortDirection.ASCENDING}, + {label: 'File Name', field: 'fileName', direction: SortDirection.ASCENDING}, + {label: 'Author', field: 'author', direction: SortDirection.ASCENDING}, + {label: 'Author + Series', field: 'authorSeries', direction: SortDirection.ASCENDING}, + {label: 'Last Read', field: 'lastReadTime', direction: SortDirection.ASCENDING}, + {label: 'Personal Rating', field: 'personalRating', direction: SortDirection.ASCENDING}, + {label: 'Added On', field: 'addedOn', direction: SortDirection.ASCENDING}, + {label: 'File Size', field: 'fileSizeKb', direction: SortDirection.ASCENDING}, + {label: 'Locked', field: 'locked', direction: SortDirection.ASCENDING}, + {label: 'Publisher', field: 'publisher', direction: SortDirection.ASCENDING}, + {label: 'Published Date', field: 'publishedDate', direction: SortDirection.ASCENDING}, + {label: 'Amazon Rating', field: 'amazonRating', direction: SortDirection.ASCENDING}, + {label: 'Amazon #', field: 'amazonReviewCount', direction: SortDirection.ASCENDING}, + {label: 'Goodreads Rating', field: 'goodreadsRating', direction: SortDirection.ASCENDING}, + {label: 'Goodreads #', field: 'goodreadsReviewCount', direction: SortDirection.ASCENDING}, + {label: 'Hardcover Rating', field: 'hardcoverRating', direction: SortDirection.ASCENDING}, + {label: 'Hardcover #', field: 'hardcoverReviewCount', direction: SortDirection.ASCENDING}, + {label: 'Pages', field: 'pageCount', direction: SortDirection.ASCENDING}, + {label: 'Random', field: 'random', direction: SortDirection.ASCENDING}, ]; - constructor(private applySortOption: (sort: SortOption) => void) {} + constructor(private applySortOption: (sort: SortOption) => void) { + } sortBooks(field: string): void { const existingSort = this.sortOptions.find(opt => opt.field === field); diff --git a/booklore-ui/src/app/features/book/components/book-browser/table-column-preference.service.spec.ts b/booklore-ui/src/app/features/book/components/book-browser/table-column-preference.service.spec.ts new file mode 100644 index 000000000..c895a3fa1 --- /dev/null +++ b/booklore-ui/src/app/features/book/components/book-browser/table-column-preference.service.spec.ts @@ -0,0 +1,139 @@ +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {TestBed} from '@angular/core/testing'; +import {EnvironmentInjector, runInInjectionContext} from '@angular/core'; +import {MessageService} from 'primeng/api'; +import {TableColumnPreferenceService} from './table-column-preference.service'; +import {TableColumnPreference, UserService} from '../../../settings/user-management/user.service'; + +describe('TableColumnPreferenceService', () => { + let service: TableColumnPreferenceService; + let userServiceMock: any; + let messageServiceMock: any; + + const allColumns = [ + {field: 'readStatus', header: 'Read'}, + {field: 'title', header: 'Title'}, + {field: 'authors', header: 'Authors'}, + {field: 'publisher', header: 'Publisher'}, + {field: 'seriesName', header: 'Series'}, + {field: 'seriesNumber', header: 'Series #'}, + {field: 'categories', header: 'Genres'}, + {field: 'publishedDate', header: 'Published'}, + {field: 'lastReadTime', header: 'Last Read'}, + {field: 'addedOn', header: 'Added'}, + {field: 'fileSizeKb', header: 'File Size'}, + {field: 'language', header: 'Language'}, + {field: 'isbn', header: 'ISBN'}, + {field: 'pageCount', header: 'Pages'}, + {field: 'amazonRating', header: 'Amazon'}, + {field: 'amazonReviewCount', header: 'AZ #'}, + {field: 'goodreadsRating', header: 'Goodreads'}, + {field: 'goodreadsReviewCount', header: 'GR #'}, + {field: 'hardcoverRating', header: 'Hardcover'}, + {field: 'hardcoverReviewCount', header: 'HC #'}, + ]; + + const fallbackPreferences: TableColumnPreference[] = allColumns.map((col, index) => ({ + field: col.field, + visible: true, + order: index + })); + + beforeEach(() => { + userServiceMock = { + getCurrentUser: vi.fn(), + updateUserSetting: vi.fn() + }; + messageServiceMock = { + add: vi.fn() + }; + + TestBed.configureTestingModule({ + providers: [ + TableColumnPreferenceService, + {provide: UserService, useValue: userServiceMock}, + {provide: MessageService, useValue: messageServiceMock} + ] + }); + + const injector = TestBed.inject(EnvironmentInjector); + service = runInInjectionContext(injector, () => TestBed.inject(TableColumnPreferenceService)); + }); + + it('should initialize with fallback preferences if none provided', () => { + service.initPreferences(undefined); + expect(service.preferences).toEqual(fallbackPreferences); + }); + + it('should initialize with provided preferences', () => { + const savedPrefs: TableColumnPreference[] = [ + {field: 'title', visible: true, order: 0}, + {field: 'authors', visible: false, order: 1} + ]; + service.initPreferences(savedPrefs); + expect(service.preferences.find(p => p.field === 'title')?.visible).toBe(true); + expect(service.preferences.find(p => p.field === 'authors')?.visible).toBe(false); + expect(service.preferences.length).toBe(allColumns.length); + }); + + it('should return all columns', () => { + expect(service.allColumns).toEqual(allColumns); + }); + + it('should return visible columns sorted by order', () => { + const prefs: TableColumnPreference[] = [ + {field: 'title', visible: true, order: 1}, + {field: 'authors', visible: true, order: 0}, + {field: 'publisher', visible: false, order: 2} + ]; + service['preferencesSubject'].next([ + ...prefs, + ...fallbackPreferences.filter(p => !prefs.some(fp => fp.field === p.field)) + ]); + const visible = service.visibleColumns; + const fields = visible.map(col => col.field); + expect(fields.indexOf('authors')).toBeLessThan(fields.indexOf('title')); + expect(fields).not.toContain('publisher'); + }); + + it('should save visible columns and update preferences', () => { + const selectedColumns = [ + {field: 'title'}, + {field: 'authors'} + ]; + userServiceMock.getCurrentUser.mockReturnValue({id: 42}); + service.saveVisibleColumns(selectedColumns); + const prefs = service.preferences; + expect(prefs.find(p => p.field === 'title')?.visible).toBe(true); + expect(prefs.find(p => p.field === 'authors')?.visible).toBe(true); + expect(prefs.find(p => p.field === 'publisher')?.visible).toBe(false); + expect(userServiceMock.updateUserSetting).toHaveBeenCalledWith(42, 'tableColumnPreference', prefs); + expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({ + severity: 'success', + summary: 'Preferences Saved' + })); + }); + + it('should not call updateUserSetting if no current user', () => { + userServiceMock.getCurrentUser.mockReturnValue(undefined); + service.saveVisibleColumns([{field: 'title'}]); + expect(userServiceMock.updateUserSetting).not.toHaveBeenCalled(); + expect(messageServiceMock.add).not.toHaveBeenCalled(); + }); + + it('should get column header for known and unknown fields', () => { + expect(service['getColumnHeader']('title')).toBe('Title'); + expect(service['getColumnHeader']('unknown')).toBe('unknown'); + }); + + it('should merge saved preferences with all columns', () => { + const savedPrefs: TableColumnPreference[] = [ + {field: 'title', visible: false, order: 5} + ]; + const merged = service['mergeWithAllColumns'](savedPrefs); + expect(merged.find(p => p.field === 'title')?.visible).toBe(false); + expect(merged.length).toBe(allColumns.length); + expect(merged.find(p => p.field === 'authors')?.visible).toBe(true); + }); +}); + diff --git a/booklore-ui/src/app/features/book/components/book-browser/table-column-preference-service.ts b/booklore-ui/src/app/features/book/components/book-browser/table-column-preference.service.ts similarity index 100% rename from booklore-ui/src/app/features/book/components/book-browser/table-column-preference-service.ts rename to booklore-ui/src/app/features/book/components/book-browser/table-column-preference.service.ts diff --git a/booklore-ui/src/app/features/book/components/book-card-lite/book-card-lite-component.html b/booklore-ui/src/app/features/book/components/book-card-lite/book-card-lite-component.html index 25f7218e2..dae0d897d 100644 --- a/booklore-ui/src/app/features/book/components/book-card-lite/book-card-lite-component.html +++ b/booklore-ui/src/app/features/book/components/book-card-lite/book-card-lite-component.html @@ -4,6 +4,12 @@ class="book-cover" alt="Cover of {{ book.metadata?.title }}" loading="lazy"/> + + @if (showSeriesNumber && !book.seriesCount && book.metadata?.seriesNumber != null) { +
+ #{{ book.metadata?.seriesNumber }} +
+ } @if (!this.isActive) { +
@@ -98,8 +98,14 @@ @for (book of books; track book; let i = $index) {
- +
} @@ -117,6 +123,108 @@
+@if (selectedBooks.size > 0) { + @if (userService.userState$ | async; as userState) { + + } +}
} @else { @@ -127,4 +235,4 @@ Loading series details...

-} +} \ No newline at end of file diff --git a/booklore-ui/src/app/features/book/components/series-page/series-page.component.scss b/booklore-ui/src/app/features/book/components/series-page/series-page.component.scss index 0552f4ba6..6e635bcc1 100644 --- a/booklore-ui/src/app/features/book/components/series-page/series-page.component.scss +++ b/booklore-ui/src/app/features/book/components/series-page/series-page.component.scss @@ -16,3 +16,47 @@ width: 100%; } +.book-browser-footer { + position: absolute; + bottom: 0; + left: 10%; + right: 10%; + display: flex; + align-items: center; + padding: 1rem 0.5rem 0.5rem; + z-index: 1; + border-radius: 10px 10px 0 0; + border: 1px solid rgba(255, 255, 255, 0.5); + border-width: 1px 1px 0px 1px; + + > .flex { + width: 100%; + } +} + +.selected-count-badge { + display: inline-flex; + align-items: center; + padding: 0.5rem 1rem; + font-size: 0.9rem; + + i { + font-size: 1rem; + } +} + +@media (max-width: 768px) { + .book-browser-footer { + left: 0%; + right: 0%; + } + + .selected-count-badge { + padding: 0.4rem 0.8rem; + font-size: 0.85rem; + + i { + font-size: 0.9rem; + } + } +} \ No newline at end of file diff --git a/booklore-ui/src/app/features/book/components/series-page/series-page.component.ts b/booklore-ui/src/app/features/book/components/series-page/series-page.component.ts index c8f8f132f..11c341f9d 100644 --- a/booklore-ui/src/app/features/book/components/series-page/series-page.component.ts +++ b/booklore-ui/src/app/features/book/components/series-page/series-page.component.ts @@ -1,20 +1,30 @@ -import { Component, inject, ViewChild } from "@angular/core"; -import { FormsModule } from "@angular/forms"; -import { Button } from "primeng/button"; -import { ActivatedRoute } from "@angular/router"; -import { AsyncPipe, NgClass, NgStyle } from "@angular/common"; -import { map, filter, switchMap } from "rxjs/operators"; -import { Observable, combineLatest } from "rxjs"; -import { Book, ReadStatus } from "../../model/book.model"; -import { BookService } from "../../service/book.service"; -import { BookCardComponent } from "../book-browser/book-card/book-card.component"; -import { CoverScalePreferenceService } from "../book-browser/cover-scale-preference.service"; -import { Tab, TabList, TabPanel, TabPanels, Tabs } from "primeng/tabs"; -import { Tag } from "primeng/tag"; -import { VirtualScrollerModule } from "@iharbeck/ngx-virtual-scroller"; -import { ProgressSpinner } from "primeng/progressspinner"; -import { DynamicDialogRef } from "primeng/dynamicdialog"; -import { Router } from "@angular/router"; +import {FormsModule} from "@angular/forms"; +import {Button} from "primeng/button"; +import {ActivatedRoute, Router} from "@angular/router"; +import {AsyncPipe, NgClass, NgStyle} from "@angular/common"; +import {filter, finalize, map, switchMap, tap} from "rxjs/operators"; +import {combineLatest, Observable, Subscription} from "rxjs"; +import {Book, ReadStatus} from "../../model/book.model"; +import {BookService} from "../../service/book.service"; +import {BookCardComponent} from "../book-browser/book-card/book-card.component"; +import {CoverScalePreferenceService} from "../book-browser/cover-scale-preference.service"; +import {Tab, TabList, TabPanel, TabPanels, Tabs} from "primeng/tabs"; +import {Tag} from "primeng/tag"; +import {VirtualScrollerModule} from "@iharbeck/ngx-virtual-scroller"; +import {ProgressSpinner} from "primeng/progressspinner"; +import {DynamicDialogRef} from "primeng/dynamicdialog"; +import {ConfirmationService, MenuItem, MessageService} from "primeng/api"; +import {UserService} from "../../../settings/user-management/user.service"; +import {BookMenuService} from "../../service/book-menu.service"; +import {LoadingService} from "../../../../core/services/loading.service"; +import {BookDialogHelperService} from "../book-browser/book-dialog-helper.service"; +import {TaskHelperService} from "../../../settings/task-management/task-helper.service"; +import {MetadataRefreshType} from "../../../metadata/model/request/metadata-refresh-type.enum"; +import {TieredMenu} from "primeng/tieredmenu"; +import {Tooltip} from "primeng/tooltip"; +import {Divider} from "primeng/divider"; +import {animate, state, style, transition, trigger} from "@angular/animations"; +import {Component, inject, OnDestroy} from '@angular/core'; @Component({ selector: "app-series-page", @@ -35,21 +45,48 @@ import { Router } from "@angular/router"; TabPanels, TabPanel, Tag, - VirtualScrollerModule -], + VirtualScrollerModule, + TieredMenu, + Tooltip, + Divider + ], + animations: [ + trigger('slideInOut', [ + state('void', style({transform: 'translateY(100%)'})), + state('*', style({transform: 'translateY(0)'})), + transition(':enter', [animate('0.1s ease-in')]), + transition(':leave', [animate('0.1s ease-out')]) + ]) + ] }) -export class SeriesPageComponent { +export class SeriesPageComponent implements OnDestroy { private route = inject(ActivatedRoute); private bookService = inject(BookService); protected coverScalePreferenceService = inject(CoverScalePreferenceService); private metadataCenterViewMode: "route" | "dialog" = "route"; - private dialogRef?: DynamicDialogRef; + private dialogRef?: DynamicDialogRef | null; private router = inject(Router); + protected userService = inject(UserService); + private bookMenuService = inject(BookMenuService); + protected confirmationService = inject(ConfirmationService); + private loadingService = inject(LoadingService); + private dialogHelperService = inject(BookDialogHelperService); + protected taskHelperService = inject(TaskHelperService); + private messageService = inject(MessageService); tab: string = "view"; isExpanded = false; + // Selection state + selectedBooks = new Set(); + lastSelectedIndex: number | null = null; + currentBooks: Book[] = []; + private userSub: Subscription; + + // Menu items + protected metadataMenuItems: MenuItem[] | undefined; + protected bulkReadActionsMenuItems: MenuItem[] | undefined; seriesParam$: Observable = this.route.paramMap.pipe( map((params) => params.get("seriesName") || ""), @@ -74,7 +111,8 @@ export class SeriesPageComponent { const bNum = b.metadata?.seriesNumber ?? Number.MAX_SAFE_INTEGER; return aNum - bNum; }); - }) + }), + tap(books => this.currentBooks = books) ); seriesTitle$: Observable = combineLatest([ @@ -150,6 +188,25 @@ export class SeriesPageComponent { }) ); + constructor() { + this.userSub = this.userService.userState$.pipe(filter(u => !!u?.user && u.loaded)) + .subscribe(userState => { + this.metadataMenuItems = this.bookMenuService.getMetadataMenuItems( + () => this.autoFetchMetadata(), + () => this.fetchMetadata(), + () => this.bulkEditMetadata(), + () => this.multiBookEditMetadata(), + () => this.regenerateCoversForSelected(), + userState.user + ); + this.bulkReadActionsMenuItems = this.bookMenuService.getBulkReadActionsMenu(this.selectedBooks, this.user()); + }); + } + + ngOnDestroy(): void { + this.userSub.unsubscribe(); + } + get currentCardSize() { return this.coverScalePreferenceService.currentCardSize; } @@ -201,7 +258,7 @@ export class SeriesPageComponent { this.isExpanded = !this.isExpanded; } - getStatusLabel(value: string | ReadStatus | null | undefined): string { + getStatusLabel(value: string | ReadStatus | null | undefined): string { const v = (value ?? '').toString().toUpperCase(); switch (v) { case ReadStatus.UNREAD: @@ -249,4 +306,163 @@ export class SeriesPageComponent { return "bg-gray-600"; } } + + handleBookSelection(book: Book, selected: boolean) { + if (selected) { + if (book.seriesBooks) { + //it is a series + this.selectedBooks = new Set([...this.selectedBooks, ...book.seriesBooks.map(book => book.id)]); + } else { + this.selectedBooks.add(book.id); + } + } else { + if (book.seriesBooks) { + //it is a series + book.seriesBooks.forEach(book => { + this.selectedBooks.delete(book.id); + }); + } else { + this.selectedBooks.delete(book.id); + } + } + } + + onCheckboxClicked(event: { index: number; book: Book; selected: boolean; shiftKey: boolean }) { + const {index, book, selected, shiftKey} = event; + if (!shiftKey || this.lastSelectedIndex === null) { + this.handleBookSelection(book, selected); + this.lastSelectedIndex = index; + } else { + const start = Math.min(this.lastSelectedIndex, index); + const end = Math.max(this.lastSelectedIndex, index); + const isUnselectingRange = !selected; + for (let i = start; i <= end; i++) { + const book = this.currentBooks[i]; + if (!book) continue; + this.handleBookSelection(book, !isUnselectingRange); + } + } + this.bulkReadActionsMenuItems = this.bookMenuService.getBulkReadActionsMenu(this.selectedBooks, this.user()); + } + + handleBookSelect(book: Book, selected: boolean): void { + this.handleBookSelection(book, selected); + this.bulkReadActionsMenuItems = this.bookMenuService.getBulkReadActionsMenu(this.selectedBooks, this.user()); + } + + selectAllBooks(): void { + if (!this.currentBooks) return; + for (const book of this.currentBooks) { + this.selectedBooks.add(book.id); + } + this.bulkReadActionsMenuItems = this.bookMenuService.getBulkReadActionsMenu(this.selectedBooks, this.user()); + } + + deselectAllBooks(): void { + this.selectedBooks.clear(); + this.bulkReadActionsMenuItems = this.bookMenuService.getBulkReadActionsMenu(this.selectedBooks, this.user()); + } + + confirmDeleteBooks(): void { + this.confirmationService.confirm({ + message: `Are you sure you want to delete ${this.selectedBooks.size} book(s)?`, + header: 'Confirm Deletion', + icon: 'pi pi-exclamation-triangle', + accept: () => { + const count = this.selectedBooks.size; + const loader = this.loadingService.show(`Deleting ${count} book(s)...`); + + this.bookService.deleteBooks(this.selectedBooks) + .pipe(finalize(() => this.loadingService.hide(loader))) + .subscribe(() => { + this.selectedBooks.clear(); + }); + }, + reject: () => { + } + }); + } + + openShelfAssigner(): void { + this.dialogRef = this.dialogHelperService.openShelfAssignerDialog(null, this.selectedBooks); + if (this.dialogRef) { + this.dialogRef.onClose.subscribe(result => { + if (result.assigned) { + this.selectedBooks.clear(); + } + }); + } + } + + lockUnlockMetadata(): void { + this.dialogRef = this.dialogHelperService.openLockUnlockMetadataDialog(this.selectedBooks); + } + + autoFetchMetadata(): void { + if (!this.selectedBooks || this.selectedBooks.size === 0) return; + this.taskHelperService.refreshMetadataTask({ + refreshType: MetadataRefreshType.BOOKS, + bookIds: Array.from(this.selectedBooks), + }).subscribe(); + } + + fetchMetadata(): void { + this.dialogHelperService.openMetadataRefreshDialog(this.selectedBooks); + } + + bulkEditMetadata(): void { + this.dialogHelperService.openBulkMetadataEditDialog(this.selectedBooks); + } + + multiBookEditMetadata(): void { + this.dialogHelperService.openMultibookMetadataEditorDialog(this.selectedBooks); + } + + regenerateCoversForSelected(): void { + if (!this.selectedBooks || this.selectedBooks.size === 0) return; + const count = this.selectedBooks.size; + this.confirmationService.confirm({ + message: `Are you sure you want to regenerate covers for ${count} book(s)?`, + header: 'Confirm Cover Regeneration', + icon: 'pi pi-image', + acceptLabel: 'Yes', + rejectLabel: 'No', + accept: () => { + this.bookService.regenerateCoversForBooks(Array.from(this.selectedBooks)).subscribe({ + next: () => { + this.messageService.add({ + severity: 'success', + summary: 'Cover Regeneration Started', + detail: `Regenerating covers for ${count} book(s). Refresh the page when complete.`, + life: 3000 + }); + }, + error: () => { + this.messageService.add({ + severity: 'error', + summary: 'Failed', + detail: 'Could not start cover regeneration.', + life: 3000 + }); + } + }); + } + }); + } + + moveFiles() { + this.dialogHelperService.openFileMoverDialog(this.selectedBooks); + } + + user() { + return this.userService.getCurrentUser(); + } + + get hasMetadataMenuItems(): boolean { + return (this.metadataMenuItems?.length ?? 0) > 0; + } + + get hasBulkReadActionsItems(): boolean { + return (this.bulkReadActionsMenuItems?.length ?? 0) > 0; + } } diff --git a/booklore-ui/src/app/features/book/components/shelf-assigner/shelf-assigner.component.ts b/booklore-ui/src/app/features/book/components/shelf-assigner/shelf-assigner.component.ts index 643a4af37..1f7feb18b 100644 --- a/booklore-ui/src/app/features/book/components/shelf-assigner/shelf-assigner.component.ts +++ b/booklore-ui/src/app/features/book/components/shelf-assigner/shelf-assigner.component.ts @@ -12,7 +12,7 @@ import {Button} from 'primeng/button'; import {AsyncPipe} from '@angular/common'; import {Checkbox} from 'primeng/checkbox'; import {FormsModule} from '@angular/forms'; -import {BookDialogHelperService} from '../book-browser/BookDialogHelperService'; +import {BookDialogHelperService} from '../book-browser/book-dialog-helper.service'; import {LoadingService} from '../../../../core/services/loading.service'; import {IconDisplayComponent} from '../../../../shared/components/icon-display/icon-display.component'; import {IconSelection} from '../../../../shared/service/icon-picker.service'; diff --git a/booklore-ui/src/app/features/book/components/shelf-creator/shelf-creator.component.html b/booklore-ui/src/app/features/book/components/shelf-creator/shelf-creator.component.html index 6d21d6d0e..88509d0ab 100644 --- a/booklore-ui/src/app/features/book/components/shelf-creator/shelf-creator.component.html +++ b/booklore-ui/src/app/features/book/components/shelf-creator/shelf-creator.component.html @@ -34,7 +34,7 @@ class="input-full" placeholder="e.g., Favorites, To Read, Currently Reading" [class.filled]="shelfName.trim()" - autofocus + /> @if (shelfName.trim()) { diff --git a/booklore-ui/src/app/features/book/model/book.model.ts b/booklore-ui/src/app/features/book/model/book.model.ts index d9c8ec3f2..773592002 100644 --- a/booklore-ui/src/app/features/book/model/book.model.ts +++ b/booklore-ui/src/app/features/book/model/book.model.ts @@ -201,6 +201,7 @@ export interface EpubViewerSetting { lineHeight: number; letterSpacing: number; spread: string; + customFontId?: number | null; } export interface CbxViewerSetting { diff --git a/booklore-ui/src/app/features/book/service/book-menu.service.spec.ts b/booklore-ui/src/app/features/book/service/book-menu.service.spec.ts new file mode 100644 index 000000000..b44b2f490 --- /dev/null +++ b/booklore-ui/src/app/features/book/service/book-menu.service.spec.ts @@ -0,0 +1,466 @@ +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {TestBed} from '@angular/core/testing'; +import {EnvironmentInjector, runInInjectionContext} from '@angular/core'; +import {ConfirmationService, MessageService} from 'primeng/api'; +import {BookService} from './book.service'; +import {LoadingService} from '../../../core/services/loading.service'; +import {User} from '../../settings/user-management/user.service'; +import {ReadStatus} from '../model/book.model'; +import {ResetProgressTypes} from '../../../shared/constants/reset-progress-type'; +import {of, throwError} from 'rxjs'; +import {HttpErrorResponse} from '@angular/common/http'; +import {APIException} from '../../../shared/models/api-exception.model'; +import {BookMenuService} from './book-menu.service'; + +describe('BookMenuService', () => { + let service: BookMenuService; + let confirmationService: any; + let messageService: any; + let bookService: any; + let loadingService: any; + + const mockUser: User = { + id: 1, + username: 'testuser', + email: 'test@example.com', + permissions: { + canBulkAutoFetchMetadata: true, + canBulkCustomFetchMetadata: true, + canBulkEditMetadata: true, + canBulkRegenerateCover: true, + canBulkResetBookReadStatus: true, + canBulkResetBookloreReadProgress: true, + canBulkResetKoReaderReadProgress: true + } + } as User; + + const mockUserNoPermissions: User = { + id: 2, + username: 'limiteduser', + email: 'limited@example.com', + permissions: { + canBulkAutoFetchMetadata: false, + canBulkCustomFetchMetadata: false, + canBulkEditMetadata: false, + canBulkRegenerateCover: false, + canBulkResetBookReadStatus: false, + canBulkResetBookloreReadProgress: false, + canBulkResetKoReaderReadProgress: false + } + } as User; + + beforeEach(() => { + confirmationService = { + confirm: vi.fn() + }; + + messageService = { + add: vi.fn() + }; + + bookService = { + updateBookReadStatus: vi.fn(), + resetProgress: vi.fn() + }; + + loadingService = { + show: vi.fn().mockReturnValue('loader-id'), + hide: vi.fn() + }; + + TestBed.configureTestingModule({ + providers: [ + BookMenuService, + {provide: ConfirmationService, useValue: confirmationService}, + {provide: MessageService, useValue: messageService}, + {provide: BookService, useValue: bookService}, + {provide: LoadingService, useValue: loadingService} + ] + }); + + const injector = TestBed.inject(EnvironmentInjector); + + service = runInInjectionContext( + injector, + () => TestBed.inject(BookMenuService) + ); + }); + + describe('getMetadataMenuItems', () => { + it('should return all metadata menu items when user has all permissions', () => { + const autoFetch = vi.fn(); + const fetch = vi.fn(); + const bulkEdit = vi.fn(); + const multiEdit = vi.fn(); + const regenerate = vi.fn(); + + const items = service.getMetadataMenuItems( + autoFetch, + fetch, + bulkEdit, + multiEdit, + regenerate, + mockUser + ); + + expect(items).toHaveLength(5); + expect(items[0].label).toBe('Auto Fetch Metadata'); + expect(items[0].icon).toBe('pi pi-bolt'); + expect(items[1].label).toBe('Custom Fetch Metadata'); + expect(items[1].icon).toBe('pi pi-sync'); + expect(items[2].label).toBe('Bulk Metadata Editor'); + expect(items[2].icon).toBe('pi pi-table'); + expect(items[3].label).toBe('Multi-Book Metadata Editor'); + expect(items[3].icon).toBe('pi pi-clone'); + expect(items[4].label).toBe('Regenerate Covers'); + expect(items[4].icon).toBe('pi pi-image'); + }); + + it('should return empty array when user has no permissions', () => { + const items = service.getMetadataMenuItems( + vi.fn(), + vi.fn(), + vi.fn(), + vi.fn(), + vi.fn(), + mockUserNoPermissions + ); + + expect(items).toHaveLength(0); + }); + + it('should return empty array when user is null', () => { + const items = service.getMetadataMenuItems( + vi.fn(), + vi.fn(), + vi.fn(), + vi.fn(), + vi.fn(), + null + ); + + expect(items).toHaveLength(0); + }); + + it('should call command functions when menu items are clicked', () => { + const autoFetch = vi.fn(); + const fetch = vi.fn(); + const bulkEdit = vi.fn(); + const multiEdit = vi.fn(); + const regenerate = vi.fn(); + + const items = service.getMetadataMenuItems( + autoFetch, + fetch, + bulkEdit, + multiEdit, + regenerate, + mockUser + ); + + items[0].command!({} as any); + expect(autoFetch).toHaveBeenCalledOnce(); + + items[1].command!({} as any); + expect(fetch).toHaveBeenCalledOnce(); + + items[2].command!({} as any); + expect(bulkEdit).toHaveBeenCalledOnce(); + + items[3].command!({} as any); + expect(multiEdit).toHaveBeenCalledOnce(); + + items[4].command!({} as any); + expect(regenerate).toHaveBeenCalledOnce(); + }); + + it('should return only items for granted permissions', () => { + const partialUser: User = { + ...mockUser, + permissions: { + ...mockUser.permissions, + canBulkAutoFetchMetadata: true, + canBulkCustomFetchMetadata: false, + canBulkEditMetadata: true, + canBulkRegenerateCover: false + } + } as User; + + const items = service.getMetadataMenuItems( + vi.fn(), + vi.fn(), + vi.fn(), + vi.fn(), + vi.fn(), + partialUser + ); + + expect(items).toHaveLength(3); + expect(items[0].label).toBe('Auto Fetch Metadata'); + expect(items[1].label).toBe('Bulk Metadata Editor'); + expect(items[2].label).toBe('Multi-Book Metadata Editor'); + }); + }); + + describe('getBulkReadActionsMenu', () => { + it('should return all read action items when user has all permissions', () => { + const selectedBooks = new Set([1, 2, 3]); + const items = service.getBulkReadActionsMenu(selectedBooks, mockUser); + + expect(items).toHaveLength(3); + expect(items[0].label).toBe('Update Read Status'); + expect(items[0].icon).toBe('pi pi-book'); + expect(items[0].items).toBeDefined(); + expect(items[0].items!.length).toBeGreaterThan(0); + expect(items[1].label).toBe('Reset Booklore Progress'); + expect(items[1].icon).toBe('pi pi-undo'); + expect(items[2].label).toBe('Reset KOReader Progress'); + expect(items[2].icon).toBe('pi pi-undo'); + }); + + it('should return empty array when user has no permissions', () => { + const selectedBooks = new Set([1, 2, 3]); + const items = service.getBulkReadActionsMenu(selectedBooks, mockUserNoPermissions); + + expect(items).toHaveLength(0); + }); + + it('should return empty array when user is null', () => { + const selectedBooks = new Set([1, 2, 3]); + const items = service.getBulkReadActionsMenu(selectedBooks, null); + + expect(items).toHaveLength(0); + }); + + it('should show confirmation dialog when updating read status', () => { + const selectedBooks = new Set([1, 2, 3]); + const items = service.getBulkReadActionsMenu(selectedBooks, mockUser); + + const readStatusItems = items[0].items!; + readStatusItems[0].command!({} as any); + + expect(confirmationService.confirm).toHaveBeenCalledOnce(); + const confirmCall = vi.mocked(confirmationService.confirm).mock.calls[0][0]; + expect(confirmCall.message).toContain('3 book(s)'); + expect(confirmCall.header).toBe('Confirm Read Status Update'); + }); + + it('should update read status on confirmation accept', () => { + const selectedBooks = new Set([1, 2, 3]); + vi.mocked(bookService.updateBookReadStatus).mockReturnValue(of([])); + + const items = service.getBulkReadActionsMenu(selectedBooks, mockUser); + const readStatusItems = items[0].items!; + + const readItem = readStatusItems.find(item => item.label === 'Read'); + expect(readItem).toBeDefined(); + + readItem!.command!({} as any); + + const confirmCall = vi.mocked(confirmationService.confirm).mock.calls[0][0]; + confirmCall.accept!(); + + expect(loadingService.show).toHaveBeenCalledWith('Updating read status for 3 book(s)...'); + expect(bookService.updateBookReadStatus).toHaveBeenCalledWith([1, 2, 3], ReadStatus.READ); + expect(loadingService.hide).toHaveBeenCalledWith('loader-id'); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'success', + summary: 'Read Status Updated', + detail: 'Marked as "Read"', + life: 2000 + }); + }); + + it('should show error message when read status update fails', () => { + const selectedBooks = new Set([1, 2]); + const errorResponse = new HttpErrorResponse({ + error: {message: 'Update failed'} as APIException, + status: 500 + }); + vi.mocked(bookService.updateBookReadStatus).mockReturnValue(throwError(() => errorResponse)); + + const items = service.getBulkReadActionsMenu(selectedBooks, mockUser); + const readStatusItems = items[0].items!; + + readStatusItems[0].command!({} as any); + + const confirmCall = vi.mocked(confirmationService.confirm).mock.calls[0][0]; + confirmCall.accept!(); + + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'error', + summary: 'Update Failed', + detail: 'Update failed', + life: 3000 + }); + }); + + it('should show confirmation dialog when resetting Booklore progress', () => { + const selectedBooks = new Set([1, 2, 3]); + const items = service.getBulkReadActionsMenu(selectedBooks, mockUser); + + items[1].command!({} as any); + + expect(confirmationService.confirm).toHaveBeenCalledOnce(); + const confirmCall = vi.mocked(confirmationService.confirm).mock.calls[0][0]; + expect(confirmCall.message).toContain('3 book(s)'); + expect(confirmCall.header).toBe('Confirm Reset'); + }); + + it('should reset Booklore progress on confirmation accept', () => { + const selectedBooks = new Set([5, 6]); + vi.mocked(bookService.resetProgress).mockReturnValue(of([])); + + const items = service.getBulkReadActionsMenu(selectedBooks, mockUser); + items[1].command!({} as any); + + const confirmCall = vi.mocked(confirmationService.confirm).mock.calls[0][0]; + confirmCall.accept!(); + + expect(loadingService.show).toHaveBeenCalledWith('Resetting Booklore progress for 2 book(s)...'); + expect(bookService.resetProgress).toHaveBeenCalledWith([5, 6], ResetProgressTypes.BOOKLORE); + expect(loadingService.hide).toHaveBeenCalledWith('loader-id'); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'success', + summary: 'Progress Reset', + detail: 'Booklore reading progress has been reset.', + life: 1500 + }); + }); + + it('should show error message when Booklore progress reset fails', () => { + const selectedBooks = new Set([1]); + const errorResponse = new HttpErrorResponse({ + error: {message: 'Reset failed'} as APIException, + status: 500 + }); + vi.mocked(bookService.resetProgress).mockReturnValue(throwError(() => errorResponse)); + + const items = service.getBulkReadActionsMenu(selectedBooks, mockUser); + items[1].command!({} as any); + + const confirmCall = vi.mocked(confirmationService.confirm).mock.calls[0][0]; + confirmCall.accept!(); + + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'error', + summary: 'Failed', + detail: 'Reset failed', + life: 3000 + }); + }); + + it('should show confirmation dialog when resetting KOReader progress', () => { + const selectedBooks = new Set([7, 8]); + const items = service.getBulkReadActionsMenu(selectedBooks, mockUser); + + items[2].command!({} as any); + + expect(confirmationService.confirm).toHaveBeenCalledOnce(); + const confirmCall = vi.mocked(confirmationService.confirm).mock.calls[0][0]; + expect(confirmCall.message).toContain('2 book(s)'); + expect(confirmCall.message).toContain('KOReader'); + expect(confirmCall.header).toBe('Confirm Reset'); + }); + + it('should reset KOReader progress on confirmation accept', () => { + const selectedBooks = new Set([9]); + vi.mocked(bookService.resetProgress).mockReturnValue(of([])); + + const items = service.getBulkReadActionsMenu(selectedBooks, mockUser); + items[2].command!({} as any); + + const confirmCall = vi.mocked(confirmationService.confirm).mock.calls[0][0]; + confirmCall.accept!(); + + expect(loadingService.show).toHaveBeenCalledWith('Resetting KOReader progress for 1 book(s)...'); + expect(bookService.resetProgress).toHaveBeenCalledWith([9], ResetProgressTypes.KOREADER); + expect(loadingService.hide).toHaveBeenCalledWith('loader-id'); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'success', + summary: 'Progress Reset', + detail: 'KOReader reading progress has been reset.', + life: 1500 + }); + }); + + it('should show error message when KOReader progress reset fails', () => { + const selectedBooks = new Set([10]); + const errorResponse = new HttpErrorResponse({ + error: {message: 'KOReader reset failed'} as APIException, + status: 500 + }); + vi.mocked(bookService.resetProgress).mockReturnValue(throwError(() => errorResponse)); + + const items = service.getBulkReadActionsMenu(selectedBooks, mockUser); + items[2].command!({} as any); + + const confirmCall = vi.mocked(confirmationService.confirm).mock.calls[0][0]; + confirmCall.accept!(); + + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'error', + summary: 'Failed', + detail: 'KOReader reset failed', + life: 3000 + }); + }); + + it('should handle API error without message gracefully', () => { + const selectedBooks = new Set([1]); + const errorResponse = new HttpErrorResponse({ + error: {} as APIException, + status: 500 + }); + vi.mocked(bookService.updateBookReadStatus).mockReturnValue(throwError(() => errorResponse)); + + const items = service.getBulkReadActionsMenu(selectedBooks, mockUser); + const readStatusItems = items[0].items!; + + readStatusItems[0].command!({} as any); + + const confirmCall = vi.mocked(confirmationService.confirm).mock.calls[0][0]; + confirmCall.accept!(); + + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'error', + summary: 'Update Failed', + detail: 'Could not update read status.', + life: 3000 + }); + }); + + it('should return only items for granted read permissions', () => { + const partialUser: User = { + ...mockUser, + permissions: { + ...mockUser.permissions, + canBulkResetBookReadStatus: true, + canBulkResetBookloreReadProgress: false, + canBulkResetKoReaderReadProgress: true + } + } as User; + + const selectedBooks = new Set([1, 2]); + const items = service.getBulkReadActionsMenu(selectedBooks, partialUser); + + expect(items).toHaveLength(2); + expect(items[0].label).toBe('Update Read Status'); + expect(items[1].label).toBe('Reset KOReader Progress'); + }); + + it('should not call bookService when confirmation is rejected', () => { + const selectedBooks = new Set([1, 2]); + const items = service.getBulkReadActionsMenu(selectedBooks, mockUser); + + items[1].command!({} as any); + + const confirmCall = vi.mocked(confirmationService.confirm).mock.calls[0][0]; + confirmCall.reject?.(); + + expect(bookService.resetProgress).not.toHaveBeenCalled(); + expect(loadingService.show).not.toHaveBeenCalled(); + }); + }); +}); + diff --git a/booklore-ui/src/app/features/book/service/book-metadata.service.ts b/booklore-ui/src/app/features/book/service/book-metadata.service.ts new file mode 100644 index 000000000..e24f725d0 --- /dev/null +++ b/booklore-ui/src/app/features/book/service/book-metadata.service.ts @@ -0,0 +1,55 @@ +import {inject, Injectable} from '@angular/core'; +import {Observable} from 'rxjs'; +import {API_CONFIG} from '../../../core/config/api-config'; +import {FetchMetadataRequest} from '../../metadata/model/request/fetch-metadata-request.model'; +import {BookMetadata} from '../model/book.model'; +import {AuthService} from '../../../shared/service/auth.service'; +import {SseClient} from 'ngx-sse-client'; +import {HttpHeaders} from '@angular/common/http'; +import {map} from 'rxjs/operators'; + +@Injectable({providedIn: 'root'}) +export class BookMetadataService { + private readonly url = `${API_CONFIG.BASE_URL}/api/v1/books`; + private authService = inject(AuthService); + private sseClient = inject(SseClient); + + fetchBookMetadata(bookId: number, request: FetchMetadataRequest): Observable { + const token = + this.authService.getOidcAccessToken() || + this.authService.getInternalAccessToken(); + + if (!token) { + throw new Error('No authentication token available'); + } + + const headers = new HttpHeaders() + .set('Content-Type', 'application/json') + .set('Authorization', `Bearer ${token}`); + + return this.sseClient.stream( + `${this.url}/${bookId}/metadata/prospective`, + { + keepAlive: false, + reconnectionDelay: 1000, + responseType: 'event' + }, + { + headers, + body: request, + withCredentials: true + }, + 'POST' + ).pipe( + map((event) => { + if (event.type === 'error') { + const errorEvent = event as ErrorEvent; + throw new Error(errorEvent.message); + } else { + const messageEvent = event as MessageEvent; + return JSON.parse(messageEvent.data) as BookMetadata; + } + }) + ); + } +} diff --git a/booklore-ui/src/app/features/book/service/book-navigation.service.spec.ts b/booklore-ui/src/app/features/book/service/book-navigation.service.spec.ts new file mode 100644 index 000000000..96945fbc3 --- /dev/null +++ b/booklore-ui/src/app/features/book/service/book-navigation.service.spec.ts @@ -0,0 +1,106 @@ +import {beforeEach, describe, expect, it} from 'vitest'; +import {firstValueFrom} from 'rxjs'; +import {BookNavigationService} from './book-navigation.service'; + +describe('BookNavigationService', () => { + let service: BookNavigationService; + const bookIds = [10, 20, 30, 40]; + + beforeEach(() => { + service = new BookNavigationService(); + }); + + it('should set and get available book ids', () => { + service.setAvailableBookIds(bookIds); + expect(service.getAvailableBookIds()).toEqual(bookIds); + }); + + it('should set navigation context and emit state', async () => { + service.setNavigationContext(bookIds, 30); + + const state = await firstValueFrom(service.getNavigationState()); + + expect(state).not.toBeNull(); + expect(state!.bookIds).toEqual(bookIds); + expect(state!.currentIndex).toBe(2); + }); + + it('should emit null if currentBookId not in bookIds', async () => { + service.setNavigationContext(bookIds, 99); + + const state = await firstValueFrom(service.getNavigationState()); + + expect(state).toBeNull(); + }); + + it('should determine canNavigatePrevious correctly', () => { + service.setNavigationContext(bookIds, 10); + expect(service.canNavigatePrevious()).toBe(false); + + service.setNavigationContext(bookIds, 30); + expect(service.canNavigatePrevious()).toBe(true); + }); + + it('should determine canNavigateNext correctly', () => { + service.setNavigationContext(bookIds, 40); + expect(service.canNavigateNext()).toBe(false); + + service.setNavigationContext(bookIds, 20); + expect(service.canNavigateNext()).toBe(true); + }); + + it('should get previous book id', () => { + service.setNavigationContext(bookIds, 30); + expect(service.getPreviousBookId()).toBe(20); + + service.setNavigationContext(bookIds, 10); + expect(service.getPreviousBookId()).toBeNull(); + }); + + it('should get next book id', () => { + service.setNavigationContext(bookIds, 20); + expect(service.getNextBookId()).toBe(30); + + service.setNavigationContext(bookIds, 40); + expect(service.getNextBookId()).toBeNull(); + }); + + it('should update current book and emit new index', async () => { + service.setNavigationContext(bookIds, 10); + service.updateCurrentBook(30); + + const state = await firstValueFrom(service.getNavigationState()); + + expect(state!.currentIndex).toBe(2); + expect(state!.bookIds[state!.currentIndex]).toBe(30); + }); + + it('should not update current book if id not in list', async () => { + service.setNavigationContext(bookIds, 10); + service.updateCurrentBook(99); + + const state = await firstValueFrom(service.getNavigationState()); + + expect(state!.currentIndex).toBe(0); + expect(state!.bookIds[state!.currentIndex]).toBe(10); + }); + + it('should return current position', () => { + service.setNavigationContext(bookIds, 30); + expect(service.getCurrentPosition()).toEqual({current: 3, total: 4}); + }); + + it('should return null for current position if no state', () => { + expect(service.getCurrentPosition()).toBeNull(); + }); + + it('should handle navigation methods gracefully if state is null', () => { + expect(service.canNavigatePrevious()).toBe(false); + expect(service.canNavigateNext()).toBe(false); + expect(service.getPreviousBookId()).toBeNull(); + expect(service.getNextBookId()).toBeNull(); + + service.updateCurrentBook(10); + expect(service.getCurrentPosition()).toBeNull(); + }); +}); diff --git a/booklore-ui/src/app/features/book/service/book-patch.service.spec.ts b/booklore-ui/src/app/features/book/service/book-patch.service.spec.ts new file mode 100644 index 000000000..a64ca98af --- /dev/null +++ b/booklore-ui/src/app/features/book/service/book-patch.service.spec.ts @@ -0,0 +1,173 @@ +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {TestBed} from '@angular/core/testing'; +import {EnvironmentInjector, runInInjectionContext} from '@angular/core'; +import {HttpClient, HttpParams} from '@angular/common/http'; +import {of, throwError} from 'rxjs'; + +import {BookPatchService} from './book-patch.service'; +import {BookStateService} from './book-state.service'; +import {Book, ReadStatus} from '../model/book.model'; + +describe('BookPatchService', () => { + let service: BookPatchService; + let httpMock: any; + let bookStateServiceMock: any; + + const mockBooks: Book[] = [ + {id: 1, bookType: 'PDF', libraryId: 1, libraryName: 'Lib', dateFinished: undefined} as Book, + {id: 2, bookType: 'EPUB', libraryId: 1, libraryName: 'Lib', dateFinished: undefined} as Book, + ]; + + beforeEach(() => { + httpMock = { + post: vi.fn(), + put: vi.fn(), + }; + bookStateServiceMock = { + getCurrentBookState: vi.fn(), + updateBookState: vi.fn(), + }; + + TestBed.configureTestingModule({ + providers: [ + BookPatchService, + {provide: HttpClient, useValue: httpMock}, + {provide: BookStateService, useValue: bookStateServiceMock}, + ] + }); + + const injector = TestBed.inject(EnvironmentInjector); + service = runInInjectionContext( + injector, + () => TestBed.inject(BookPatchService) + ); + }); + + it('should update book shelves and update state', () => { + const updatedBooks = [{...mockBooks[0], id: 1, libraryName: 'Updated'}]; + httpMock.post.mockReturnValue(of(updatedBooks)); + bookStateServiceMock.getCurrentBookState.mockReturnValue({books: [...mockBooks]}); + service.updateBookShelves(new Set([1]), new Set([2]), new Set([3])).subscribe(result => { + expect(result).toEqual(updatedBooks); + expect(bookStateServiceMock.updateBookState).toHaveBeenCalledWith(expect.objectContaining({ + books: expect.arrayContaining([expect.objectContaining({id: 1, libraryName: 'Updated'})]) + })); + }); + }); + + it('should save PDF progress', () => { + httpMock.post.mockReturnValue(of(void 0)); + service.savePdfProgress(1, 10, 0.5).subscribe(result => { + expect(result).toBeUndefined(); + expect(httpMock.post).toHaveBeenCalledWith(expect.stringContaining('/progress'), { + bookId: 1, + pdfProgress: {page: 10, percentage: 0.5} + }); + }); + }); + + it('should save EPUB progress', () => { + httpMock.post.mockReturnValue(of(void 0)); + service.saveEpubProgress(2, 'cfi123', 0.8).subscribe(result => { + expect(result).toBeUndefined(); + expect(httpMock.post).toHaveBeenCalledWith(expect.stringContaining('/progress'), { + bookId: 2, + epubProgress: {cfi: 'cfi123', percentage: 0.8} + }); + }); + }); + + it('should save CBX progress', () => { + httpMock.post.mockReturnValue(of(void 0)); + service.saveCbxProgress(3, 5, 0.2).subscribe(result => { + expect(result).toBeUndefined(); + expect(httpMock.post).toHaveBeenCalledWith(expect.stringContaining('/progress'), { + bookId: 3, + cbxProgress: {page: 5, percentage: 0.2} + }); + }); + }); + + it('should update date finished and update state', () => { + httpMock.post.mockReturnValue(of(void 0)); + bookStateServiceMock.getCurrentBookState.mockReturnValue({books: [...mockBooks]}); + service.updateDateFinished(1, '2023-01-01').subscribe(() => { + expect(bookStateServiceMock.updateBookState).toHaveBeenCalledWith(expect.objectContaining({ + books: expect.arrayContaining([expect.objectContaining({id: 1, dateFinished: '2023-01-01'})]) + })); + }); + }); + + it('should reset progress and update state', () => { + const responses = [{bookId: 1, readStatus: ReadStatus.UNREAD, readStatusModifiedTime: 'now', dateFinished: undefined}]; + httpMock.post.mockReturnValue(of(responses)); + bookStateServiceMock.getCurrentBookState.mockReturnValue({books: [...mockBooks]}); + service.resetProgress([1], 'BOOKLORE').subscribe(result => { + expect(result).toEqual(responses); + expect(httpMock.post).toHaveBeenCalledWith( + expect.stringContaining('/reset-progress'), + [1], + {params: expect.any(HttpParams)} + ); + expect(bookStateServiceMock.updateBookState).toHaveBeenCalled(); + }); + }); + + it('should update book read status and update state', () => { + const responses = [{bookId: 2, readStatus: ReadStatus.READING, readStatusModifiedTime: 'now', dateFinished: '2023-01-01'}]; + httpMock.post.mockReturnValue(of(responses)); + bookStateServiceMock.getCurrentBookState.mockReturnValue({books: [...mockBooks]}); + service.updateBookReadStatus([2], ReadStatus.READING).subscribe(result => { + expect(result).toEqual(responses); + expect(httpMock.post).toHaveBeenCalledWith( + expect.stringContaining('/status'), + {bookIds: [2], status: ReadStatus.READING} + ); + expect(bookStateServiceMock.updateBookState).toHaveBeenCalled(); + }); + }); + + it('should reset personal rating and update state', () => { + const responses = [{bookId: 1, personalRating: null}]; + httpMock.post.mockReturnValue(of(responses)); + bookStateServiceMock.getCurrentBookState.mockReturnValue({books: [...mockBooks]}); + service.resetPersonalRating([1]).subscribe(result => { + expect(result).toEqual(responses); + expect(httpMock.post).toHaveBeenCalledWith(expect.stringContaining('/reset-personal-rating'), [1]); + expect(bookStateServiceMock.updateBookState).toHaveBeenCalled(); + }); + }); + + it('should update personal rating and update state', () => { + const responses = [{bookId: 2, personalRating: 5}]; + httpMock.put.mockReturnValue(of(responses)); + bookStateServiceMock.getCurrentBookState.mockReturnValue({books: [...mockBooks]}); + service.updatePersonalRating([2], 5).subscribe(result => { + expect(result).toEqual(responses); + expect(httpMock.put).toHaveBeenCalledWith(expect.stringContaining('/personal-rating'), {ids: [2], rating: 5}); + expect(bookStateServiceMock.updateBookState).toHaveBeenCalled(); + }); + }); + + it('should update last read time in state', () => { + const now = new Date().toISOString(); + vi.useFakeTimers().setSystemTime(new Date(now)); + bookStateServiceMock.getCurrentBookState.mockReturnValue({books: [...mockBooks]}); + service.updateLastReadTime(1); + expect(bookStateServiceMock.updateBookState).toHaveBeenCalledWith(expect.objectContaining({ + books: expect.arrayContaining([expect.objectContaining({id: 1, lastReadTime: now})]) + })); + vi.useRealTimers(); + }); + + it('should handle errors from http.post gracefully', () => { + httpMock.post.mockReturnValue(throwError(() => new Error('fail'))); + service.savePdfProgress(1, 1, 1).subscribe({ + error: (err: any) => { + expect(err).toBeInstanceOf(Error); + expect(err.message).toBe('fail'); + } + }); + }); +}); + diff --git a/booklore-ui/src/app/features/book/service/book-state.service.ts b/booklore-ui/src/app/features/book/service/book-state.service.ts index 114849374..dcf134f7a 100644 --- a/booklore-ui/src/app/features/book/service/book-state.service.ts +++ b/booklore-ui/src/app/features/book/service/book-state.service.ts @@ -1,5 +1,5 @@ import {Injectable} from '@angular/core'; -import {BehaviorSubject, Observable} from 'rxjs'; +import {BehaviorSubject} from 'rxjs'; import {BookState} from '../model/state/book-state.model'; @Injectable({ @@ -22,13 +22,6 @@ export class BookStateService { this.bookStateSubject.next(state); } - updatePartialBookState(partialState: Partial): void { - this.bookStateSubject.next({ - ...this.bookStateSubject.value, - ...partialState - }); - } - resetBookState(): void { this.bookStateSubject.next({ books: null, diff --git a/booklore-ui/src/app/features/book/service/book.service.spec.ts b/booklore-ui/src/app/features/book/service/book.service.spec.ts new file mode 100644 index 000000000..a9eb917dc --- /dev/null +++ b/booklore-ui/src/app/features/book/service/book.service.spec.ts @@ -0,0 +1,517 @@ +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {TestBed} from '@angular/core/testing'; +import {EnvironmentInjector, runInInjectionContext} from '@angular/core'; +import {HttpClient} from '@angular/common/http'; +import {firstValueFrom, of, throwError} from 'rxjs'; +import {BookService} from './book.service'; +import {BookStateService} from './book-state.service'; +import {BookSocketService} from './book-socket.service'; +import {BookPatchService} from './book-patch.service'; +import {MessageService} from 'primeng/api'; +import {AuthService} from '../../../shared/service/auth.service'; +import {FileDownloadService} from '../../../shared/service/file-download.service'; +import {Router} from '@angular/router'; +import {AdditionalFileType, Book, BookMetadata, ReadStatus} from '../model/book.model'; + +describe('BookService', () => { + let service: BookService; + let httpMock: any; + let messageServiceMock: any; + let authServiceMock: any; + let fileDownloadServiceMock: any; + let routerMock: any; + let bookStateServiceMock: any; + let bookSocketServiceMock: any; + let bookPatchServiceMock: any; + + beforeEach(() => { + httpMock = { + get: vi.fn(), + post: vi.fn(), + put: vi.fn(), + delete: vi.fn() + }; + messageServiceMock = {add: vi.fn()}; + authServiceMock = {token$: of('token')}; + fileDownloadServiceMock = {downloadFile: vi.fn()}; + routerMock = {navigate: vi.fn()}; + bookStateServiceMock = { + bookState$: of({books: [{id: 1, bookType: 'PDF', shelves: [], metadata: {seriesName: 'S'}}], loaded: true, error: null}), + getCurrentBookState: vi.fn(), + updateBookState: vi.fn(), + resetBookState: vi.fn() + }; + bookSocketServiceMock = { + handleNewlyCreatedBook: vi.fn(), + handleRemovedBookIds: vi.fn(), + handleBookUpdate: vi.fn(), + handleMultipleBookUpdates: vi.fn(), + handleBookMetadataUpdate: vi.fn(), + handleMultipleBookCoverPatches: vi.fn() + }; + bookPatchServiceMock = { + updateBookShelves: vi.fn(), + updateLastReadTime: vi.fn(), + savePdfProgress: vi.fn(), + saveEpubProgress: vi.fn(), + saveCbxProgress: vi.fn(), + updateDateFinished: vi.fn(), + resetProgress: vi.fn(), + updateBookReadStatus: vi.fn(), + resetPersonalRating: vi.fn(), + updatePersonalRating: vi.fn() + }; + + bookStateServiceMock.getCurrentBookState.mockReturnValue({ + books: [ + {id: 1, bookType: 'PDF', shelves: [{id: 10}], metadata: {seriesName: 'S'}, alternativeFormats: [], supplementaryFiles: [], fileName: 'file.pdf'}, + {id: 2, bookType: 'EPUB', shelves: [], metadata: {}, alternativeFormats: [], supplementaryFiles: [], fileName: 'file2.epub'} + ], + loaded: true, + error: null + }); + + TestBed.configureTestingModule({ + providers: [ + BookService, + {provide: HttpClient, useValue: httpMock}, + {provide: MessageService, useValue: messageServiceMock}, + {provide: AuthService, useValue: authServiceMock}, + {provide: FileDownloadService, useValue: fileDownloadServiceMock}, + {provide: Router, useValue: routerMock}, + {provide: BookStateService, useValue: bookStateServiceMock}, + {provide: BookSocketService, useValue: bookSocketServiceMock}, + {provide: BookPatchService, useValue: bookPatchServiceMock} + ] + }); + + const injector = TestBed.inject(EnvironmentInjector); + service = runInInjectionContext(injector, () => TestBed.inject(BookService)); + }); + + describe('State Management', () => { + it('should get current book state', () => { + expect(service.getCurrentBookState()).toEqual(bookStateServiceMock.getCurrentBookState()); + }); + + it('should fetch books and update state', async () => { + const books = [{id: 1}]; + httpMock.get.mockReturnValue(of(books)); + await firstValueFrom(service['fetchBooks']()); + expect(bookStateServiceMock.updateBookState).toHaveBeenCalledWith({ + books, + loaded: true, + error: null + }); + }); + + it('should handle fetchBooks error', async () => { + httpMock.get.mockReturnValue(throwError(() => ({message: 'fail'}))); + bookStateServiceMock.getCurrentBookState.mockReturnValue({books: [], loaded: false, error: null}); + await expect(firstValueFrom(service['fetchBooks']())).rejects.toBeTruthy(); + expect(bookStateServiceMock.updateBookState).toHaveBeenCalledWith({ + books: [], + loaded: true, + error: 'fail' + }); + }); + + it('should refreshBooks and update state', () => { + httpMock.get.mockReturnValue(of([{id: 1}])); + service.refreshBooks(); + expect(bookStateServiceMock.updateBookState).toHaveBeenCalledWith({ + books: [{id: 1}], + loaded: true, + error: null + }); + }); + + it('should handle refreshBooks error', () => { + httpMock.get.mockReturnValue(throwError(() => ({message: 'fail'}))); + service.refreshBooks(); + expect(bookStateServiceMock.updateBookState).toHaveBeenCalledWith({ + books: null, + loaded: true, + error: 'fail' + }); + }); + + it('should remove books by library id', () => { + bookStateServiceMock.getCurrentBookState.mockReturnValue({ + books: [{id: 1, libraryId: 2}, {id: 2, libraryId: 3}], + loaded: true, + error: null + }); + service.removeBooksByLibraryId(2); + expect(bookStateServiceMock.updateBookState).toHaveBeenCalledWith({ + books: [{id: 2, libraryId: 3}], + loaded: true, + error: null + }); + }); + + it('should remove books from shelf', () => { + bookStateServiceMock.getCurrentBookState.mockReturnValue({ + books: [{id: 1, shelves: [{id: 10}, {id: 20}]}, {id: 2, shelves: [{id: 20}]}], + loaded: true, + error: null + }); + service.removeBooksFromShelf(20); + expect(bookStateServiceMock.updateBookState).toHaveBeenCalled(); + }); + }); + + describe('Book Retrieval', () => { + it('should get book by id from state', () => { + expect(service.getBookByIdFromState(1)).toEqual(expect.objectContaining({id: 1})); + expect(service.getBookByIdFromState(999)).toBeUndefined(); + }); + + it('should get books by ids from state', () => { + expect(service.getBooksByIdsFromState([1, 2])).toHaveLength(2); + expect(service.getBooksByIdsFromState([])).toEqual([]); + }); + + it('should get book by id from API', async () => { + httpMock.get.mockReturnValue(of({id: 1})); + const result = await firstValueFrom(service.getBookByIdFromAPI(1, true)); + expect(result).toEqual({id: 1}); + }); + + it('should get books in series', async () => { + const result = await firstValueFrom(service.getBooksInSeries(1)); + expect(result).toEqual([expect.objectContaining({id: 1})]); + }); + + it('should get book recommendations', async () => { + httpMock.get.mockReturnValue(of([{id: 1}])); + const result = await firstValueFrom(service.getBookRecommendations(1)); + expect(result).toEqual([{id: 1}]); + }); + }); + + describe('Book Operations', () => { + it('should delete books and update state', async () => { + httpMock.delete.mockReturnValue(of({failedFileDeletions: []})); + bookStateServiceMock.getCurrentBookState.mockReturnValue({ + books: [{id: 1}, {id: 2}], + loaded: true, + error: null + }); + await firstValueFrom(service.deleteBooks(new Set([1]))); + expect(bookStateServiceMock.updateBookState).toHaveBeenCalled(); + expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'success'})); + }); + + it('should show warning if some files could not be deleted', async () => { + httpMock.delete.mockReturnValue(of({failedFileDeletions: ['file.pdf']})); + bookStateServiceMock.getCurrentBookState.mockReturnValue({ + books: [{id: 1, fileName: 'file.pdf'}], + loaded: true, + error: null + }); + await firstValueFrom(service.deleteBooks(new Set([1]))); + expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'warn'})); + }); + + it('should handle deleteBooks error', async () => { + httpMock.delete.mockReturnValue(throwError(() => ({error: {message: 'fail'}}))); + await expect(firstValueFrom(service.deleteBooks(new Set([1])))).rejects.toBeTruthy(); + expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'error'})); + }); + + it('should update book shelves', async () => { + bookPatchServiceMock.updateBookShelves.mockReturnValue(of([{id: 1}])); + const result = await firstValueFrom(service.updateBookShelves(new Set([1]), new Set([2]), new Set([3]))); + expect(result).toEqual([{id: 1}]); + }); + + it('should handle updateBookShelves error', async () => { + bookPatchServiceMock.updateBookShelves.mockReturnValue(throwError(() => ({message: 'fail'}))); + await expect(firstValueFrom(service.updateBookShelves(new Set([1]), new Set([2]), new Set([3])))).rejects.toBeTruthy(); + expect(bookStateServiceMock.updateBookState).toHaveBeenCalled(); + }); + }); + + describe('Reading & Viewer Settings', () => { + it('should navigate to correct reader and update last read time', () => { + service.readBook(1, 'ngx'); + expect(routerMock.navigate).toHaveBeenCalledWith(['/pdf-reader/book/1']); + expect(bookPatchServiceMock.updateLastReadTime).toHaveBeenCalledWith(1); + }); + + it('should not navigate if book not found', () => { + bookStateServiceMock.getCurrentBookState.mockReturnValue({books: [], loaded: true, error: null}); + service.readBook(999, 'ngx'); + expect(routerMock.navigate).not.toHaveBeenCalled(); + }); + + it('should get book setting', async () => { + httpMock.get.mockReturnValue(of({fontSize: 12})); + const result = await firstValueFrom(service.getBookSetting(1)); + expect(result).toEqual({fontSize: 12}); + }); + + it('should update viewer setting', async () => { + httpMock.put.mockReturnValue(of(void 0)); + const result = await firstValueFrom(service.updateViewerSetting({fontSize: 12}, 1)); + expect(result).toBeUndefined(); + }); + }); + + describe('File Operations', () => { + it('should get file content', async () => { + httpMock.get.mockReturnValue(of(new Blob(['abc']))); + const result = await firstValueFrom(service.getFileContent(1)); + expect(result).toBeInstanceOf(Blob); + }); + + it('should download file', () => { + const book = {id: 1, fileName: 'file.pdf'}; + service.downloadFile(book as Book); + expect(fileDownloadServiceMock.downloadFile).toHaveBeenCalled(); + }); + + it('should delete additional file and update state', async () => { + httpMock.delete.mockReturnValue(of(void 0)); + bookStateServiceMock.getCurrentBookState.mockReturnValue({ + books: [{id: 1, alternativeFormats: [{id: 2}], supplementaryFiles: [{id: 3}]}], + loaded: true, + error: null + }); + await firstValueFrom(service.deleteAdditionalFile(1, 2)); + expect(bookStateServiceMock.updateBookState).toHaveBeenCalled(); + expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'success'})); + }); + + it('should handle deleteAdditionalFile error', async () => { + httpMock.delete.mockReturnValue(throwError(() => ({error: {message: 'fail'}}))); + await expect(firstValueFrom(service.deleteAdditionalFile(1, 2))).rejects.toBeTruthy(); + expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'error'})); + }); + + it('should upload additional file and update state', async () => { + httpMock.post.mockReturnValue(of({id: 2})); + bookStateServiceMock.getCurrentBookState.mockReturnValue({ + books: [{id: 1, alternativeFormats: [], supplementaryFiles: []}], + loaded: true, + error: null + }); + const file = new File(['abc'], 'file.txt'); + await firstValueFrom(service.uploadAdditionalFile(1, file, AdditionalFileType.ALTERNATIVE_FORMAT)); + expect(bookStateServiceMock.updateBookState).toHaveBeenCalled(); + expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'success'})); + }); + + it('should handle uploadAdditionalFile error', async () => { + httpMock.post.mockReturnValue(throwError(() => ({error: {message: 'fail'}}))); + const file = new File(['abc'], 'file.txt'); + await expect(firstValueFrom(service.uploadAdditionalFile(1, file, AdditionalFileType.ALTERNATIVE_FORMAT))).rejects.toBeTruthy(); + expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'error'})); + }); + + it('should download additional file', () => { + const book = {id: 1, alternativeFormats: [{id: 2, fileName: 'f.txt'}]}; + service.downloadAdditionalFile(book as Book, 2); + expect(fileDownloadServiceMock.downloadFile).toHaveBeenCalled(); + }); + }); + + describe('Progress & Status Tracking', () => { + it('should update last read time', () => { + service.updateLastReadTime(1); + expect(bookPatchServiceMock.updateLastReadTime).toHaveBeenCalledWith(1); + }); + + it('should save pdf progress', async () => { + bookPatchServiceMock.savePdfProgress.mockReturnValue(of(void 0)); + const result = await firstValueFrom(service.savePdfProgress(1, 2, 0.5)); + expect(result).toBeUndefined(); + }); + + it('should save epub progress', async () => { + bookPatchServiceMock.saveEpubProgress.mockReturnValue(of(void 0)); + const result = await firstValueFrom(service.saveEpubProgress(1, 'cfi', 0.5)); + expect(result).toBeUndefined(); + }); + + it('should save cbx progress', async () => { + bookPatchServiceMock.saveCbxProgress.mockReturnValue(of(void 0)); + const result = await firstValueFrom(service.saveCbxProgress(1, 2, 0.5)); + expect(result).toBeUndefined(); + }); + + it('should update date finished', async () => { + bookPatchServiceMock.updateDateFinished.mockReturnValue(of(void 0)); + const result = await firstValueFrom(service.updateDateFinished(1, '2020-01-01')); + expect(result).toBeUndefined(); + }); + + it('should reset progress', async () => { + bookPatchServiceMock.resetProgress.mockReturnValue(of([{bookId: 1, readStatus: ReadStatus.READ, readStatusModifiedTime: ''}])); + const result = await firstValueFrom(service.resetProgress([1], 'BOOKLORE')); + expect(result).toEqual([{bookId: 1, readStatus: ReadStatus.READ, readStatusModifiedTime: ''}]); + }); + + it('should update book read status', async () => { + bookPatchServiceMock.updateBookReadStatus.mockReturnValue(of([{bookId: 1, readStatus: ReadStatus.READ, readStatusModifiedTime: ''}])); + const result = await firstValueFrom(service.updateBookReadStatus([1], ReadStatus.READ)); + expect(result).toEqual([{bookId: 1, readStatus: ReadStatus.READ, readStatusModifiedTime: ''}]); + }); + }); + + describe('Personal Rating', () => { + it('should reset personal rating', async () => { + bookPatchServiceMock.resetPersonalRating.mockReturnValue(of([{bookId: 1}])); + const result = await firstValueFrom(service.resetPersonalRating([1])); + expect(result).toEqual([{bookId: 1}]); + }); + + it('should update personal rating', async () => { + bookPatchServiceMock.updatePersonalRating.mockReturnValue(of([{bookId: 1, personalRating: 5}])); + const result = await firstValueFrom(service.updatePersonalRating([1], 5)); + expect(result).toEqual([{bookId: 1, personalRating: 5}]); + }); + }); + + describe('Metadata Operations', () => { + + it('should update book metadata', async () => { + httpMock.put.mockReturnValue(of({bookId: 1})); + const spy = vi.spyOn(BookService.prototype, 'handleBookMetadataUpdate'); + const result = await firstValueFrom(service.updateBookMetadata(1, {} as any, true)); + expect(result).toEqual({bookId: 1}); + expect(spy).toHaveBeenCalledWith(1, {bookId: 1}); + spy.mockRestore(); + }); + + it('should update books metadata', async () => { + httpMock.put.mockReturnValue(of(void 0)); + const result = await firstValueFrom(service.updateBooksMetadata({} as any)); + expect(result).toBeUndefined(); + }); + + it('should toggle all lock', async () => { + httpMock.put.mockReturnValue(of([{bookId: 1}])); + bookStateServiceMock.getCurrentBookState.mockReturnValue({ + books: [{id: 1, metadata: {bookId: 1}}], + loaded: true, + error: null + }); + const result = await firstValueFrom(service.toggleAllLock(new Set([1]), 'lock')); + expect(result).toBeUndefined(); + expect(bookStateServiceMock.updateBookState).toHaveBeenCalled(); + }); + + it('should handle toggle all lock error', async () => { + httpMock.put.mockReturnValue(throwError(() => ({message: 'fail'}))); + await expect(firstValueFrom(service.toggleAllLock(new Set([1]), 'lock'))).rejects.toBeTruthy(); + }); + + it('should toggle field locks', async () => { + httpMock.put.mockReturnValue(of(void 0)); + bookStateServiceMock.getCurrentBookState.mockReturnValue({ + books: [{id: 1, metadata: {}}], + loaded: true, + error: null + }); + const result = await firstValueFrom(service.toggleFieldLocks([1], {title: 'LOCK'})); + expect(result).toBeUndefined(); + expect(bookStateServiceMock.updateBookState).toHaveBeenCalled(); + }); + + it('should handle toggle field locks error', async () => { + httpMock.put.mockReturnValue(throwError(() => ({message: 'fail'}))); + await expect(firstValueFrom(service.toggleFieldLocks([1], {title: 'LOCK'}))).rejects.toBeTruthy(); + expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'error'})); + }); + + it('should consolidate metadata', async () => { + httpMock.post.mockReturnValue(of({})); + service.refreshBooks = vi.fn(); + await firstValueFrom(service.consolidateMetadata('authors', ['a'], ['b'])); + expect(service.refreshBooks).toHaveBeenCalled(); + }); + + it('should delete metadata', async () => { + httpMock.post.mockReturnValue(of({})); + service.refreshBooks = vi.fn(); + await firstValueFrom(service.deleteMetadata('authors', ['a'])); + expect(service.refreshBooks).toHaveBeenCalled(); + }); + }); + + describe('Cover Operations', () => { + it('should get upload cover url', () => { + expect(service.getUploadCoverUrl(1)).toContain('/1/metadata/cover/upload'); + }); + + it('should regenerate covers', async () => { + httpMock.post.mockReturnValue(of(void 0)); + const result = await firstValueFrom(service.regenerateCovers()); + expect(result).toBeUndefined(); + }); + + it('should regenerate cover', async () => { + httpMock.post.mockReturnValue(of(void 0)); + const result = await firstValueFrom(service.regenerateCover(1)); + expect(result).toBeUndefined(); + }); + + it('should generate custom cover', async () => { + httpMock.post.mockReturnValue(of(void 0)); + const result = await firstValueFrom(service.generateCustomCover(1)); + expect(result).toBeUndefined(); + }); + + it('should regenerate covers for books', async () => { + httpMock.post.mockReturnValue(of(void 0)); + const result = await firstValueFrom(service.regenerateCoversForBooks([1, 2])); + expect(result).toBeUndefined(); + }); + + it('should bulk upload cover', async () => { + httpMock.post.mockReturnValue(of(void 0)); + const file = new File(['abc'], 'cover.jpg'); + const result = await firstValueFrom(service.bulkUploadCover([1, 2], file)); + expect(result).toBeUndefined(); + }); + }); + + describe('Websocket Handlers', () => { + it('should handle newly created book', () => { + const book = {id: 1}; + service.handleNewlyCreatedBook(book as Book); + expect(bookSocketServiceMock.handleNewlyCreatedBook).toHaveBeenCalledWith(book); + }); + + it('should handle removed book ids', () => { + service.handleRemovedBookIds([1, 2]); + expect(bookSocketServiceMock.handleRemovedBookIds).toHaveBeenCalledWith([1, 2]); + }); + + it('should handle book update', () => { + const book = {id: 1}; + service.handleBookUpdate(book as Book); + expect(bookSocketServiceMock.handleBookUpdate).toHaveBeenCalledWith(book); + }); + + it('should handle multiple book updates', () => { + const books = [{id: 1}, {id: 2}]; + service.handleMultipleBookUpdates(books as Book[]); + expect(bookSocketServiceMock.handleMultipleBookUpdates).toHaveBeenCalledWith(books); + }); + + it('should handle book metadata update', () => { + service.handleBookMetadataUpdate(1, {bookId: 1} as BookMetadata); + expect(bookSocketServiceMock.handleBookMetadataUpdate).toHaveBeenCalledWith(1, {bookId: 1}); + }); + + it('should handle multiple book cover patches', () => { + const patches = [{id: 1, coverUpdatedOn: 'now'}]; + service.handleMultipleBookCoverPatches(patches); + expect(bookSocketServiceMock.handleMultipleBookCoverPatches).toHaveBeenCalledWith(patches); + }); + }); +}); + diff --git a/booklore-ui/src/app/features/book/service/book.service.ts b/booklore-ui/src/app/features/book/service/book.service.ts index 09562bf0d..e0a5297f0 100644 --- a/booklore-ui/src/app/features/book/service/book.service.ts +++ b/booklore-ui/src/app/features/book/service/book.service.ts @@ -5,7 +5,6 @@ import {catchError, distinctUntilChanged, filter, finalize, map, shareReplay, ta import {AdditionalFile, AdditionalFileType, Book, BookDeletionResponse, BookMetadata, BookRecommendation, BookSetting, BulkMetadataUpdateRequest, MetadataUpdateWrapper, ReadStatus} from '../model/book.model'; import {BookState} from '../model/state/book-state.model'; import {API_CONFIG} from '../../../core/config/api-config'; -import {FetchMetadataRequest} from '../../metadata/model/request/fetch-metadata-request.model'; import {MessageService} from 'primeng/api'; import {ResetProgressType} from '../../../shared/constants/reset-progress-type'; import {AuthService} from '../../../shared/service/auth.service'; @@ -426,9 +425,6 @@ export class BookService { /*------------------ Metadata Operations ------------------*/ - fetchBookMetadata(bookId: number, request: FetchMetadataRequest): Observable { - return this.http.post(`${this.url}/${bookId}/metadata/prospective`, request); - } updateBookMetadata(bookId: number | undefined, wrapper: MetadataUpdateWrapper, mergeCategories: boolean): Observable { const params = new HttpParams().set('mergeCategories', mergeCategories.toString()); @@ -533,13 +529,7 @@ export class BookService { } uploadCoverFromUrl(bookId: number, url: string): Observable { - return this.http - .post(`${this.url}/${bookId}/metadata/cover/from-url`, {url}) - .pipe( - tap(updatedMetadata => - this.handleBookMetadataUpdate(bookId, updatedMetadata) - ) - ); + return this.http.post(`${this.url}/${bookId}/metadata/cover/from-url`, {url}); } regenerateCovers(): Observable { diff --git a/booklore-ui/src/app/features/book/service/cbx-reader.service.spec.ts b/booklore-ui/src/app/features/book/service/cbx-reader.service.spec.ts new file mode 100644 index 000000000..10654f131 --- /dev/null +++ b/booklore-ui/src/app/features/book/service/cbx-reader.service.spec.ts @@ -0,0 +1,96 @@ +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {TestBed} from '@angular/core/testing'; +import {EnvironmentInjector, runInInjectionContext} from '@angular/core'; +import {HttpClient} from '@angular/common/http'; +import {of, throwError} from 'rxjs'; + +import {CbxReaderService} from './cbx-reader.service'; +import {AuthService} from '../../../shared/service/auth.service'; + +describe('CbxReaderService', () => { + let service: CbxReaderService; + let httpClientMock: any; + let authServiceMock: any; + + beforeEach(() => { + httpClientMock = { + get: vi.fn() + }; + + authServiceMock = { + getOidcAccessToken: vi.fn(), + getInternalAccessToken: vi.fn() + }; + + TestBed.configureTestingModule({ + providers: [ + CbxReaderService, + {provide: HttpClient, useValue: httpClientMock}, + {provide: AuthService, useValue: authServiceMock} + ] + }); + + const injector = TestBed.inject(EnvironmentInjector); + + service = runInInjectionContext( + injector, + () => TestBed.inject(CbxReaderService) + ); + }); + + it('should get available pages with token', () => { + authServiceMock.getOidcAccessToken.mockReturnValue('abc123'); + authServiceMock.getInternalAccessToken.mockReturnValue(null); + httpClientMock.get.mockReturnValue(of([1, 2, 3])); + service.getAvailablePages(42).subscribe(pages => { + expect(pages).toEqual([1, 2, 3]); + expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringContaining('token=abc123')); + }); + }); + + it('should get available pages without token', () => { + authServiceMock.getOidcAccessToken.mockReturnValue(null); + authServiceMock.getInternalAccessToken.mockReturnValue(null); + httpClientMock.get.mockReturnValue(of([4, 5])); + service.getAvailablePages(99).subscribe(pages => { + expect(pages).toEqual([4, 5]); + expect(httpClientMock.get).toHaveBeenCalledWith(expect.not.stringContaining('token=')); + }); + }); + + it('should handle error when getting available pages', () => { + authServiceMock.getOidcAccessToken.mockReturnValue('tok'); + httpClientMock.get.mockReturnValue(throwError(() => new Error('fail'))); + service.getAvailablePages(1).subscribe({ + error: (err: any) => { + expect(err).toBeInstanceOf(Error); + expect(err.message).toBe('fail'); + } + }); + }); + + it('should return correct page image url with oidc token', () => { + authServiceMock.getOidcAccessToken.mockReturnValue('tok'); + authServiceMock.getInternalAccessToken.mockReturnValue(null); + const url = service.getPageImageUrl(5, 7); + expect(url).toContain('/api/v1/media/book/5/cbx/pages/7'); + expect(url).toContain('token=tok'); + }); + + it('should return correct page image url with internal token', () => { + authServiceMock.getOidcAccessToken.mockReturnValue(null); + authServiceMock.getInternalAccessToken.mockReturnValue('inttok'); + const url = service.getPageImageUrl(8, 2); + expect(url).toContain('/api/v1/media/book/8/cbx/pages/2'); + expect(url).toContain('token=inttok'); + }); + + it('should return correct page image url without token', () => { + authServiceMock.getOidcAccessToken.mockReturnValue(null); + authServiceMock.getInternalAccessToken.mockReturnValue(null); + const url = service.getPageImageUrl(3, 1); + expect(url).toContain('/api/v1/media/book/3/cbx/pages/1'); + expect(url).not.toContain('token='); + }); +}); + diff --git a/booklore-ui/src/app/features/book/service/library-shelf-menu.service.spec.ts b/booklore-ui/src/app/features/book/service/library-shelf-menu.service.spec.ts new file mode 100644 index 000000000..449efcbd6 --- /dev/null +++ b/booklore-ui/src/app/features/book/service/library-shelf-menu.service.spec.ts @@ -0,0 +1,350 @@ +import {TestBed} from '@angular/core/testing'; +import {EnvironmentInjector, runInInjectionContext} from '@angular/core'; +import {ConfirmationService, MessageService} from 'primeng/api'; +import {Router} from '@angular/router'; +import {LibraryService} from './library.service'; +import {ShelfService} from './shelf.service'; +import {TaskHelperService} from '../../settings/task-management/task-helper.service'; +import {DialogLauncherService} from '../../../shared/services/dialog-launcher.service'; +import {MagicShelf, MagicShelfService} from '../../magic-shelf/service/magic-shelf.service'; +import {UserService} from "../../settings/user-management/user.service"; +import {LoadingService} from '../../../core/services/loading.service'; +import {LibraryShelfMenuService} from './library-shelf-menu.service'; +import {Library} from '../model/library.model'; +import {Shelf} from '../model/shelf.model'; +import {MetadataRefreshType} from '../../metadata/model/request/metadata-refresh-type.enum'; +import {of, throwError} from 'rxjs'; +import {beforeEach, describe, expect, it, vi} from 'vitest'; + +describe('LibraryShelfMenuService', () => { + let service: LibraryShelfMenuService; + let confirmationService: any; + let messageService: any; + let libraryService: any; + let shelfService: any; + let taskHelperService: any; + let router: any; + let dialogLauncherService: any; + let magicShelfService: any; + let userService: any; + let loadingService: any; + + const mockLibrary: Library = {id: 1, name: 'Lib1'} as Library; + const mockShelf: Shelf = {id: 2, name: 'Shelf1'} as Shelf; + const mockMagicShelf: MagicShelf = {id: 3, name: 'Magic1', isPublic: false} as MagicShelf; + + beforeEach(() => { + confirmationService = {confirm: vi.fn()}; + messageService = {add: vi.fn()}; + libraryService = { + refreshLibrary: vi.fn(), + deleteLibrary: vi.fn() + }; + shelfService = { + deleteShelf: vi.fn() + }; + taskHelperService = { + refreshMetadataTask: vi.fn() + }; + router = {navigate: vi.fn()}; + dialogLauncherService = { + openLibraryEditDialog: vi.fn(), + openLibraryMetadataFetchDialog: vi.fn(), + openShelfEditDialog: vi.fn(), + openMagicShelfEditDialog: vi.fn() + }; + magicShelfService = { + deleteShelf: vi.fn() + }; + userService = { + getCurrentUser: vi.fn() + }; + loadingService = { + show: vi.fn().mockReturnValue('loader-id'), + hide: vi.fn() + }; + + TestBed.configureTestingModule({ + providers: [ + LibraryShelfMenuService, + {provide: ConfirmationService, useValue: confirmationService}, + {provide: MessageService, useValue: messageService}, + {provide: LibraryService, useValue: libraryService}, + {provide: ShelfService, useValue: shelfService}, + {provide: TaskHelperService, useValue: taskHelperService}, + {provide: Router, useValue: router}, + {provide: DialogLauncherService, useValue: dialogLauncherService}, + {provide: MagicShelfService, useValue: magicShelfService}, + {provide: UserService, useValue: userService}, + {provide: LoadingService, useValue: loadingService} + ] + }); + + const injector = TestBed.inject(EnvironmentInjector); + service = runInInjectionContext(injector, () => TestBed.inject(LibraryShelfMenuService)); + }); + + describe('initializeLibraryMenuItems', () => { + it('should provide all menu items for a library', () => { + const items = service.initializeLibraryMenuItems(mockLibrary); + expect(items.length).toBe(1); + const options = items[0].items!; + expect(options.some(i => i.label === 'Edit Library')).toBe(true); + expect(options.some(i => i.label === 'Re-scan Library')).toBe(true); + expect(options.some(i => i.label === 'Custom Fetch Metadata')).toBe(true); + expect(options.some(i => i.label === 'Auto Fetch Metadata')).toBe(true); + expect(options.some(i => i.label === 'Delete Library')).toBe(true); + }); + + it('should call openLibraryEditDialog when Edit Library is clicked', () => { + const items = service.initializeLibraryMenuItems(mockLibrary); + const edit = items[0].items!.find(i => i.label === 'Edit Library'); + edit!.command!({}); + expect(dialogLauncherService.openLibraryEditDialog).toHaveBeenCalledWith(mockLibrary.id); + }); + + it('should call openLibraryMetadataFetchDialog when Custom Fetch Metadata is clicked', () => { + const items = service.initializeLibraryMenuItems(mockLibrary); + const fetch = items[0].items!.find(i => i.label === 'Custom Fetch Metadata'); + fetch!.command!({}); + expect(dialogLauncherService.openLibraryMetadataFetchDialog).toHaveBeenCalledWith(mockLibrary.id); + }); + + it('should call refreshMetadataTask when Auto Fetch Metadata is clicked', () => { + taskHelperService.refreshMetadataTask.mockReturnValue(of({})); + const items = service.initializeLibraryMenuItems(mockLibrary); + const auto = items[0].items!.find(i => i.label === 'Auto Fetch Metadata'); + auto!.command!({}); + expect(taskHelperService.refreshMetadataTask).toHaveBeenCalledWith({ + refreshType: MetadataRefreshType.LIBRARY, + libraryId: mockLibrary.id + }); + }); + + it('should show confirmation dialog for Re-scan Library', () => { + libraryService.refreshLibrary.mockReturnValue(of({})); + const items = service.initializeLibraryMenuItems(mockLibrary); + const rescan = items[0].items!.find(i => i.label === 'Re-scan Library'); + rescan!.command!({}); + expect(confirmationService.confirm).toHaveBeenCalledTimes(1); + const confirmCall = confirmationService.confirm.mock.calls[0][0]; + expect(confirmCall.message).toContain(mockLibrary.name); + expect(confirmCall.header).toBe('Confirmation'); + }); + + it('should refresh library and show success message on accept', () => { + libraryService.refreshLibrary.mockReturnValue(of({})); + const items = service.initializeLibraryMenuItems(mockLibrary); + const rescan = items[0].items!.find(i => i.label === 'Re-scan Library'); + rescan!.command!({}); + const confirmCall = confirmationService.confirm.mock.calls[0][0]; + confirmCall.accept(); + expect(libraryService.refreshLibrary).toHaveBeenCalledWith(mockLibrary.id); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'info', + summary: 'Success', + detail: 'Library refresh scheduled' + }); + }); + + it('should show error message if refreshLibrary fails', () => { + libraryService.refreshLibrary.mockReturnValue(throwError(() => ({}))); + const items = service.initializeLibraryMenuItems(mockLibrary); + const rescan = items[0].items!.find(i => i.label === 'Re-scan Library'); + rescan!.command!({}); + const confirmCall = confirmationService.confirm.mock.calls[0][0]; + confirmCall.accept(); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'error', + summary: 'Failed', + detail: 'Failed to refresh library' + }); + }); + + it('should show confirmation dialog for Delete Library', () => { + libraryService.deleteLibrary.mockReturnValue(of({})); + const items = service.initializeLibraryMenuItems(mockLibrary); + const del = items[0].items!.find(i => i.label === 'Delete Library'); + del!.command!({}); + expect(confirmationService.confirm).toHaveBeenCalledTimes(1); + const confirmCall = confirmationService.confirm.mock.calls[0][0]; + expect(confirmCall.message).toContain(mockLibrary.name); + expect(confirmCall.header).toBe('Confirmation'); + }); + + it('should delete library, navigate, and show success message on accept', () => { + libraryService.deleteLibrary.mockReturnValue(of({})); + const items = service.initializeLibraryMenuItems(mockLibrary); + const del = items[0].items!.find(i => i.label === 'Delete Library'); + del!.command!({}); + const confirmCall = confirmationService.confirm.mock.calls[0][0]; + confirmCall.accept(); + expect(loadingService.show).toHaveBeenCalledWith(expect.stringContaining(mockLibrary.name)); + expect(libraryService.deleteLibrary).toHaveBeenCalledWith(mockLibrary.id); + expect(router.navigate).toHaveBeenCalledWith(['/']); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'info', + summary: 'Success', + detail: 'Library was deleted' + }); + expect(loadingService.hide).toHaveBeenCalledWith('loader-id'); + }); + + it('should show error message if deleteLibrary fails', () => { + libraryService.deleteLibrary.mockReturnValue(throwError(() => ({}))); + const items = service.initializeLibraryMenuItems(mockLibrary); + const del = items[0].items!.find(i => i.label === 'Delete Library'); + del!.command!({}); + const confirmCall = confirmationService.confirm.mock.calls[0][0]; + confirmCall.accept(); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'error', + summary: 'Failed', + detail: 'Failed to delete library' + }); + expect(loadingService.hide).toHaveBeenCalledWith('loader-id'); + }); + }); + + describe('initializeShelfMenuItems', () => { + it('should provide all menu items for a shelf', () => { + const items = service.initializeShelfMenuItems(mockShelf); + expect(items.length).toBe(1); + const options = items[0].items!; + expect(options.some(i => i.label === 'Edit Shelf')).toBe(true); + expect(options.some(i => i.label === 'Delete Shelf')).toBe(true); + }); + + it('should call openShelfEditDialog when Edit Shelf is clicked', () => { + const items = service.initializeShelfMenuItems(mockShelf); + const edit = items[0].items!.find(i => i.label === 'Edit Shelf'); + edit!.command!({}); + expect(dialogLauncherService.openShelfEditDialog).toHaveBeenCalledWith(mockShelf.id); + }); + + it('should show confirmation dialog for Delete Shelf', () => { + shelfService.deleteShelf.mockReturnValue(of({})); + const items = service.initializeShelfMenuItems(mockShelf); + const del = items[0].items!.find(i => i.label === 'Delete Shelf'); + del!.command!({}); + expect(confirmationService.confirm).toHaveBeenCalledTimes(1); + const confirmCall = confirmationService.confirm.mock.calls[0][0]; + expect(confirmCall.message).toContain(mockShelf.name); + expect(confirmCall.header).toBe('Confirmation'); + }); + + it('should delete shelf, navigate, and show success message on accept', () => { + shelfService.deleteShelf.mockReturnValue(of({})); + const items = service.initializeShelfMenuItems(mockShelf); + const del = items[0].items!.find(i => i.label === 'Delete Shelf'); + del!.command!({}); + const confirmCall = confirmationService.confirm.mock.calls[0][0]; + confirmCall.accept(); + expect(shelfService.deleteShelf).toHaveBeenCalledWith(mockShelf.id); + expect(router.navigate).toHaveBeenCalledWith(['/']); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'info', + summary: 'Success', + detail: 'Shelf was deleted' + }); + }); + + it('should show error message if deleteShelf fails', () => { + shelfService.deleteShelf.mockReturnValue(throwError(() => ({}))); + const items = service.initializeShelfMenuItems(mockShelf); + const del = items[0].items!.find(i => i.label === 'Delete Shelf'); + del!.command!({}); + const confirmCall = confirmationService.confirm.mock.calls[0][0]; + confirmCall.accept(); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'error', + summary: 'Failed', + detail: 'Failed to delete shelf' + }); + }); + }); + + describe('initializeMagicShelfMenuItems', () => { + it('should provide all menu items for a magic shelf', () => { + userService.getCurrentUser.mockReturnValue({permissions: {admin: true}}); + const items = service.initializeMagicShelfMenuItems(mockMagicShelf); + expect(items.length).toBe(1); + const options = items[0].items!; + expect(options.some(i => i.label === 'Edit Magic Shelf')).toBe(true); + expect(options.some(i => i.label === 'Delete Magic Shelf')).toBe(true); + }); + + it('should call openMagicShelfEditDialog when Edit Magic Shelf is clicked', () => { + userService.getCurrentUser.mockReturnValue({permissions: {admin: true}}); + const items = service.initializeMagicShelfMenuItems(mockMagicShelf); + const edit = items[0].items!.find(i => i.label === 'Edit Magic Shelf'); + edit!.command!({}); + expect(dialogLauncherService.openMagicShelfEditDialog).toHaveBeenCalledWith(mockMagicShelf.id); + }); + + it('should show confirmation dialog for Delete Magic Shelf', () => { + userService.getCurrentUser.mockReturnValue({permissions: {admin: true}}); + magicShelfService.deleteShelf.mockReturnValue(of({})); + const items = service.initializeMagicShelfMenuItems(mockMagicShelf); + const del = items[0].items!.find(i => i.label === 'Delete Magic Shelf'); + del!.command!({}); + expect(confirmationService.confirm).toHaveBeenCalledTimes(1); + const confirmCall = confirmationService.confirm.mock.calls[0][0]; + expect(confirmCall.message).toContain(mockMagicShelf.name); + expect(confirmCall.header).toBe('Confirmation'); + }); + + it('should delete magic shelf, navigate, and show success message on accept', () => { + userService.getCurrentUser.mockReturnValue({permissions: {admin: true}}); + magicShelfService.deleteShelf.mockReturnValue(of({})); + const items = service.initializeMagicShelfMenuItems(mockMagicShelf); + const del = items[0].items!.find(i => i.label === 'Delete Magic Shelf'); + del!.command!({}); + const confirmCall = confirmationService.confirm.mock.calls[0][0]; + confirmCall.accept(); + expect(magicShelfService.deleteShelf).toHaveBeenCalledWith(mockMagicShelf.id); + expect(router.navigate).toHaveBeenCalledWith(['/']); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'info', + summary: 'Success', + detail: 'Magic shelf was deleted' + }); + }); + + it('should show error message if deleteMagicShelf fails', () => { + userService.getCurrentUser.mockReturnValue({permissions: {admin: true}}); + magicShelfService.deleteShelf.mockReturnValue(throwError(() => ({}))); + const items = service.initializeMagicShelfMenuItems(mockMagicShelf); + const del = items[0].items!.find(i => i.label === 'Delete Magic Shelf'); + del!.command!({}); + const confirmCall = confirmationService.confirm.mock.calls[0][0]; + confirmCall.accept(); + expect(messageService.add).toHaveBeenCalledWith({ + severity: 'error', + summary: 'Failed', + detail: 'Failed to delete shelf' + }); + }); + + it('should disable options for public shelf if not admin', () => { + userService.getCurrentUser.mockReturnValue({permissions: {admin: false}}); + const publicMagicShelf = {...mockMagicShelf, isPublic: true}; + const items = service.initializeMagicShelfMenuItems(publicMagicShelf); + const edit = items[0].items!.find(i => i.label === 'Edit Magic Shelf'); + const del = items[0].items!.find(i => i.label === 'Delete Magic Shelf'); + expect(edit!.disabled).toBe(true); + expect(del!.disabled).toBe(true); + }); + + it('should not disable options for public shelf if admin', () => { + userService.getCurrentUser.mockReturnValue({permissions: {admin: true}}); + const publicMagicShelf = {...mockMagicShelf, isPublic: true}; + const items = service.initializeMagicShelfMenuItems(publicMagicShelf); + const edit = items[0].items!.find(i => i.label === 'Edit Magic Shelf'); + const del = items[0].items!.find(i => i.label === 'Delete Magic Shelf'); + expect(edit!.disabled).toBe(false); + expect(del!.disabled).toBe(false); + }); + }); +}); + diff --git a/booklore-ui/src/app/features/book/service/library-shelf-menu.service.ts b/booklore-ui/src/app/features/book/service/library-shelf-menu.service.ts index 2bc8a4dca..7c8759ede 100644 --- a/booklore-ui/src/app/features/book/service/library-shelf-menu.service.ts +++ b/booklore-ui/src/app/features/book/service/library-shelf-menu.service.ts @@ -38,7 +38,7 @@ export class LibraryShelfMenuService { label: 'Edit Library', icon: 'pi pi-pen-to-square', command: () => { - this.dialogLauncherService.openLibraryEditDialog(entity?.id); + this.dialogLauncherService.openLibraryEditDialog((entity?.id as number)); } }, { @@ -77,7 +77,7 @@ export class LibraryShelfMenuService { label: 'Custom Fetch Metadata', icon: 'pi pi-sync', command: () => { - this.dialogLauncherService.openLibraryMetadataFetchDialog(entity?.id); + this.dialogLauncherService.openLibraryMetadataFetchDialog((entity?.id as number)); } }, { @@ -144,7 +144,7 @@ export class LibraryShelfMenuService { label: 'Edit Shelf', icon: 'pi pi-pen-to-square', command: () => { - this.dialogLauncherService.openShelfEditDialog(entity?.id); + this.dialogLauncherService.openShelfEditDialog((entity?.id as number)); } }, { @@ -197,7 +197,7 @@ export class LibraryShelfMenuService { icon: 'pi pi-pen-to-square', disabled: disableOptions, command: () => { - this.dialogLauncherService.openMagicShelfEditDialog(entity?.id); + this.dialogLauncherService.openMagicShelfEditDialog((entity?.id as number)); } }, { diff --git a/booklore-ui/src/app/features/book/service/library.service.spec.ts b/booklore-ui/src/app/features/book/service/library.service.spec.ts new file mode 100644 index 000000000..e06c30c05 --- /dev/null +++ b/booklore-ui/src/app/features/book/service/library.service.spec.ts @@ -0,0 +1,167 @@ +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {TestBed} from '@angular/core/testing'; +import {EnvironmentInjector, runInInjectionContext} from '@angular/core'; +import {HttpClient} from '@angular/common/http'; +import {firstValueFrom, of, throwError} from 'rxjs'; + +import {LibraryService} from './library.service'; +import {BookService} from './book.service'; +import {AuthService} from '../../../shared/service/auth.service'; +import {Library} from '../model/library.model'; + +describe('LibraryService', () => { + let service: LibraryService; + let httpClientMock: any; + let bookServiceMock: any; + let authServiceMock: any; + + beforeEach(() => { + httpClientMock = { + get: vi.fn(), + post: vi.fn(), + put: vi.fn(), + patch: vi.fn(), + delete: vi.fn() + }; + + bookServiceMock = { + removeBooksByLibraryId: vi.fn(), + bookState$: of({ + books: [ + {id: 1, libraryId: 10}, + {id: 2, libraryId: 20}, + {id: 3, libraryId: 10}, + {id: 4} + ] + }) + }; + + authServiceMock = { + token$: of('token') + }; + + TestBed.configureTestingModule({ + providers: [ + LibraryService, + {provide: HttpClient, useValue: httpClientMock}, + {provide: BookService, useValue: bookServiceMock}, + {provide: AuthService, useValue: authServiceMock} + ] + }); + + const injector = TestBed.inject(EnvironmentInjector); + + service = runInInjectionContext( + injector, + () => TestBed.inject(LibraryService) + ); + }); + + it('should fetch libraries and update state', () => { + const libraries: Library[] = [{id: 1, name: 'LibA', icon: 'icon', watch: true, paths: []}]; + httpClientMock.get.mockReturnValue(of(libraries)); + service['fetchLibraries']().subscribe(result => { + expect(result).toEqual(libraries); + expect(service['libraryStateSubject'].value.libraries).toEqual(libraries); + expect(service['libraryStateSubject'].value.loaded).toBe(true); + }); + }); + + it('should handle fetch libraries error', () => { + httpClientMock.get.mockReturnValue(throwError(() => new Error('fail'))); + service['libraryStateSubject'].next({libraries: null, loaded: false, error: null}); + service['fetchLibraries']().subscribe({ + error: (err: any) => { + expect(service['libraryStateSubject'].value.error).toBe('fail'); + } + }); + }); + + it('should create a library and update state', () => { + const library: Library = {id: 2, name: 'LibB', icon: 'icon', watch: true, paths: []}; + httpClientMock.post.mockReturnValue(of(library)); + service['libraryStateSubject'].next({libraries: [], loaded: true, error: null}); + service.createLibrary(library).subscribe(result => { + expect(result).toEqual(library); + expect(service['libraryStateSubject'].value.libraries).toContain(library); + }); + }); + + it('should update a library and update state', () => { + const library: Library = {id: 3, name: 'LibC', icon: 'icon', watch: true, paths: []}; + httpClientMock.put.mockReturnValue(of({...library, name: 'LibC2'})); + service['libraryStateSubject'].next({libraries: [library], loaded: true, error: null}); + service.updateLibrary({...library, name: 'LibC2'}, 3).subscribe(result => { + expect(result.name).toBe('LibC2'); + expect(service['libraryStateSubject'].value.libraries?.find(l => l.id === 3)?.name).toBe('LibC2'); + }); + }); + + it('should delete a library and update state', () => { + httpClientMock.delete.mockReturnValue(of(void 0)); + const library: Library = {id: 4, name: 'LibD', icon: 'icon', watch: true, paths: []}; + service['libraryStateSubject'].next({libraries: [library], loaded: true, error: null}); + service.deleteLibrary(4).subscribe(() => { + expect(service['libraryStateSubject'].value.libraries).toEqual([]); + expect(bookServiceMock.removeBooksByLibraryId).toHaveBeenCalledWith(4); + }); + }); + + it('should handle delete library error', () => { + httpClientMock.delete.mockReturnValue(throwError(() => new Error('delete error'))); + service['libraryStateSubject'].next({libraries: [{id: 5, name: 'LibE', icon: 'icon', watch: true, paths: []}], loaded: true, error: null}); + service.deleteLibrary(5).subscribe({ + error: () => { + expect(service['libraryStateSubject'].value.error).toBe('delete error'); + } + }); + }); + + it('should refresh a library and handle error', () => { + httpClientMock.put.mockReturnValue(throwError(() => new Error('refresh error'))); + service['libraryStateSubject'].next({libraries: [{id: 6, name: 'LibF', icon: 'icon', watch: true, paths: []}], loaded: true, error: null}); + service.refreshLibrary(6).subscribe({ + error: () => { + expect(service['libraryStateSubject'].value.error).toBe('refresh error'); + } + }); + }); + + it('should update library file naming pattern', () => { + const library: Library = {id: 7, name: 'LibG', icon: 'icon', watch: true, paths: [], fileNamingPattern: 'old'}; + const updatedLibrary = {...library, fileNamingPattern: 'new'}; + httpClientMock.patch.mockReturnValue(of(updatedLibrary)); + service['libraryStateSubject'].next({libraries: [library], loaded: true, error: null}); + service.updateLibraryFileNamingPattern(7, 'new').subscribe(result => { + expect(result.fileNamingPattern).toBe('new'); + expect(service['libraryStateSubject'].value.libraries?.find(l => l.id === 7)?.fileNamingPattern).toBe('new'); + }); + }); + + it('should check if library exists by name', () => { + const library: Library = {id: 8, name: 'LibH', icon: 'icon', watch: true, paths: []}; + service['libraryStateSubject'].next({libraries: [library], loaded: true, error: null}); + expect(service.doesLibraryExistByName('LibH')).toBe(true); + expect(service.doesLibraryExistByName('NonExistent')).toBe(false); + }); + + it('should find library by id', () => { + const library: Library = {id: 9, name: 'LibI', icon: 'icon', watch: true, paths: []}; + service['libraryStateSubject'].next({libraries: [library], loaded: true, error: null}); + expect(service.findLibraryById(9)).toEqual(library); + expect(service.findLibraryById(999)).toBeUndefined(); + }); + + it('should get libraries from state', () => { + const libraries: Library[] = [ + {id: 10, name: 'LibJ', icon: 'icon', watch: true, paths: []} + ]; + service['libraryStateSubject'].next({libraries, loaded: true, error: null}); + expect(service.getLibrariesFromState()).toEqual(libraries); + }); + + it('should get book count for library', async () => { + const count = await firstValueFrom(service.getBookCount(10)); + expect(count).toBe(2); + }); +}); diff --git a/booklore-ui/src/app/features/book/service/library.service.ts b/booklore-ui/src/app/features/book/service/library.service.ts index f1711934c..679b37f45 100644 --- a/booklore-ui/src/app/features/book/service/library.service.ts +++ b/booklore-ui/src/app/features/book/service/library.service.ts @@ -22,6 +22,13 @@ export class LibraryService { error: null, }); + private largeLibraryLoadingSubject = new BehaviorSubject<{ isLoading: boolean; expectedCount: number }>({ + isLoading: false, + expectedCount: 0 + }); + + largeLibraryLoading$ = this.largeLibraryLoadingSubject.asObservable(); + private loading$: Observable | null = null; constructor() { @@ -72,6 +79,10 @@ export class LibraryService { ); } + scanLibraryPaths(lib: Library): Observable { + return this.http.post(`${this.url}/scan`, lib); + } + createLibrary(lib: Library): Observable { return this.http.post(this.url, lib).pipe( map(created => { @@ -133,7 +144,6 @@ export class LibraryService { ); } - doesLibraryExistByName(name: string): boolean { return (this.libraryStateSubject.value.libraries || []).some(l => l.name === name); } @@ -146,15 +156,13 @@ export class LibraryService { return this.libraryStateSubject.value.libraries || []; } - getLibraryPathById(pathId: number): string | undefined { - return this.libraryStateSubject.value.libraries - ?.find(lib => lib.paths.some(p => p.id === pathId)) - ?.paths.find(p => p.id === pathId)?.path; - } - getBookCount(libraryId: number): Observable { return this.bookService.bookState$.pipe( map(state => (state.books || []).filter(b => b.libraryId === libraryId).length) ); } + + setLargeLibraryLoading(isLoading: boolean, expectedCount: number): void { + this.largeLibraryLoadingSubject.next({ isLoading, expectedCount }); + } } diff --git a/booklore-ui/src/app/features/book/service/metadata-task.spec.ts b/booklore-ui/src/app/features/book/service/metadata-task.spec.ts new file mode 100644 index 000000000..e167f6c04 --- /dev/null +++ b/booklore-ui/src/app/features/book/service/metadata-task.spec.ts @@ -0,0 +1,123 @@ +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {TestBed} from '@angular/core/testing'; +import {EnvironmentInjector, runInInjectionContext} from '@angular/core'; +import {HttpClient} from '@angular/common/http'; +import {firstValueFrom, of, throwError} from 'rxjs'; + +import {MetadataFetchTask, MetadataTaskService} from './metadata-task'; +import {API_CONFIG} from '../../../core/config/api-config'; +import {MetadataBatchProgressNotification, MetadataBatchStatus} from '../../../shared/model/metadata-batch-progress.model'; + +describe('MetadataTaskService', () => { + let service: MetadataTaskService; + let httpClientMock: any; + + beforeEach(() => { + httpClientMock = { + get: vi.fn(), + delete: vi.fn(), + post: vi.fn() + }; + + TestBed.configureTestingModule({ + providers: [ + MetadataTaskService, + { provide: HttpClient, useValue: httpClientMock } + ] + }); + + const injector = TestBed.inject(EnvironmentInjector); + + service = runInInjectionContext( + injector, + () => TestBed.inject(MetadataTaskService) + ); + }); + + it('should get task with proposals', async () => { + const task: MetadataFetchTask = { + id: 'task1', + status: 'IN_PROGRESS', + completed: 1, + totalBooks: 2, + startedAt: '2024-01-01T00:00:00Z', + completedAt: null, + initiatedBy: 'user1', + errorMessage: null, + proposals: [] + }; + httpClientMock.get.mockReturnValue(of({ task })); + const result = await firstValueFrom(service.getTaskWithProposals('task1')); + expect(result).toEqual(task); + expect(httpClientMock.get).toHaveBeenCalledWith(`${API_CONFIG.BASE_URL}/api/metadata/tasks/task1`); + }); + + it('should handle error in getTaskWithProposals', async () => { + httpClientMock.get.mockReturnValue(throwError(() => new Error('fail'))); + try { + await firstValueFrom(service.getTaskWithProposals('task2')); + } catch (e: any) { + expect(e.message).toBe('fail'); + } + }); + + it('should delete a task', async () => { + httpClientMock.delete.mockReturnValue(of(void 0)); + await firstValueFrom(service.deleteTask('task3')); + expect(httpClientMock.delete).toHaveBeenCalledWith(`${API_CONFIG.BASE_URL}/api/metadata/tasks/task3`); + }); + + it('should handle error in deleteTask', async () => { + httpClientMock.delete.mockReturnValue(throwError(() => new Error('delete error'))); + try { + await firstValueFrom(service.deleteTask('task4')); + } catch (e: any) { + expect(e.message).toBe('delete error'); + } + }); + + it('should update proposal status', async () => { + httpClientMock.post.mockReturnValue(of(void 0)); + await firstValueFrom(service.updateProposalStatus('task5', 123, 'ACCEPTED')); + expect(httpClientMock.post).toHaveBeenCalledWith( + `${API_CONFIG.BASE_URL}/api/metadata/tasks/task5/proposals/123/status`, + null, + { params: { status: 'ACCEPTED' } } + ); + }); + + it('should handle error in updateProposalStatus', async () => { + httpClientMock.post.mockReturnValue(throwError(() => new Error('status error'))); + try { + await firstValueFrom(service.updateProposalStatus('task6', 456, 'REJECTED')); + } catch (e: any) { + expect(e.message).toBe('status error'); + } + }); + + it('should get active tasks', async () => { + const notifications: MetadataBatchProgressNotification[] = [ + { + taskId: 't1', + completed: 1, + total: 2, + message: 'Running', + status: MetadataBatchStatus.IN_PROGRESS, + review: false + } + ]; + httpClientMock.get.mockReturnValue(of(notifications)); + const result = await firstValueFrom(service.getActiveTasks()); + expect(result).toEqual(notifications); + expect(httpClientMock.get).toHaveBeenCalledWith(`${API_CONFIG.BASE_URL}/api/metadata/tasks/active`); + }); + + it('should handle error in getActiveTasks', async () => { + httpClientMock.get.mockReturnValue(throwError(() => new Error('active error'))); + try { + await firstValueFrom(service.getActiveTasks()); + } catch (e: any) { + expect(e.message).toBe('active error'); + } + }); +}); diff --git a/booklore-ui/src/app/features/book/service/new-pdf-reader.service.spec.ts b/booklore-ui/src/app/features/book/service/new-pdf-reader.service.spec.ts new file mode 100644 index 000000000..e76f2a994 --- /dev/null +++ b/booklore-ui/src/app/features/book/service/new-pdf-reader.service.spec.ts @@ -0,0 +1,70 @@ +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {TestBed} from '@angular/core/testing'; +import {EnvironmentInjector, runInInjectionContext} from '@angular/core'; +import {HttpClient} from '@angular/common/http'; + +import {NewPdfReaderService} from './new-pdf-reader.service'; +import {AuthService} from '../../../shared/service/auth.service'; +import {API_CONFIG} from '../../../core/config/api-config'; + +describe('NewPdfReaderService', () => { + let service: NewPdfReaderService; + let authServiceMock: any; + let httpClientMock: any; + + beforeEach(() => { + authServiceMock = { + getOidcAccessToken: vi.fn(), + getInternalAccessToken: vi.fn() + }; + + httpClientMock = { + get: vi.fn() + }; + + TestBed.configureTestingModule({ + providers: [ + NewPdfReaderService, + {provide: AuthService, useValue: authServiceMock}, + {provide: HttpClient, useValue: httpClientMock} + ] + }); + + const injector = TestBed.inject(EnvironmentInjector); + + service = runInInjectionContext( + injector, + () => TestBed.inject(NewPdfReaderService) + ); + }); + + it('should append token from OIDC access token', () => { + authServiceMock.getOidcAccessToken.mockReturnValue('oidc-token'); + authServiceMock.getInternalAccessToken.mockReturnValue(null); + + const url = 'http://test.com/resource'; + const result = (service as any).appendToken(url); + + expect(result).toContain('token=oidc-token'); + }); + + it('should not append token if both tokens are null', () => { + authServiceMock.getOidcAccessToken.mockReturnValue(null); + authServiceMock.getInternalAccessToken.mockReturnValue(null); + + const url = 'http://test.com/resource'; + const result = (service as any).appendToken(url); + + expect(result).toBe(url); + }); + + it('should call http.get with correct URL', () => { + authServiceMock.getOidcAccessToken.mockReturnValue('token123'); + + service.getAvailablePages(42); + + expect(httpClientMock.get).toHaveBeenCalledWith( + `${API_CONFIG.BASE_URL}/api/v1/pdf/42/pages?token=token123` + ); + }); +}); diff --git a/booklore-ui/src/app/features/book/service/shelf.service.spec.ts b/booklore-ui/src/app/features/book/service/shelf.service.spec.ts new file mode 100644 index 000000000..4295fa488 --- /dev/null +++ b/booklore-ui/src/app/features/book/service/shelf.service.spec.ts @@ -0,0 +1,129 @@ +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {TestBed} from '@angular/core/testing'; +import {EnvironmentInjector, runInInjectionContext} from '@angular/core'; +import {HttpClient} from '@angular/common/http'; +import {of, throwError, firstValueFrom} from 'rxjs'; + +import {ShelfService} from './shelf.service'; +import {BookService} from './book.service'; +import {Shelf} from '../model/shelf.model'; + +describe('ShelfService', () => { + let service: ShelfService; + let httpClientMock: any; + let bookServiceMock: any; + + beforeEach(() => { + httpClientMock = { + get: vi.fn(), + post: vi.fn(), + put: vi.fn(), + delete: vi.fn() + }; + + bookServiceMock = { + removeBooksFromShelf: vi.fn(), + bookState$: of({ + books: [ + {id: 1, shelves: [{id: 10}]}, + {id: 2, shelves: [{id: 20}]}, + {id: 3, shelves: []}, + {id: 4} + ] + }) + }; + + TestBed.configureTestingModule({ + providers: [ + ShelfService, + {provide: HttpClient, useValue: httpClientMock}, + {provide: BookService, useValue: bookServiceMock} + ] + }); + + const injector = TestBed.inject(EnvironmentInjector); + + service = runInInjectionContext( + injector, + () => TestBed.inject(ShelfService) + ); + }); + + it('should fetch shelves and update state', () => { + const shelves: Shelf[] = [{id: 1, name: 'A', icon: 'icon'}]; + httpClientMock.get.mockReturnValue(of(shelves)); + service['fetchShelves']().subscribe(result => { + expect(result).toEqual(shelves); + expect(service['shelfStateSubject'].value.shelves).toEqual(shelves); + expect(service['shelfStateSubject'].value.loaded).toBe(true); + }); + }); + + it('should handle fetch shelves error', () => { + httpClientMock.get.mockReturnValue(throwError(() => new Error('fail'))); + service['shelfStateSubject'].next({shelves: null, loaded: false, error: null}); + service['fetchShelves']().subscribe({ + error: (err: any) => { + expect(service['shelfStateSubject'].value.error).toBe('fail'); + } + }); + }); + + it('should create a shelf and update state', () => { + const shelf: Shelf = {id: 2, name: 'B', icon: 'icon'}; + httpClientMock.post.mockReturnValue(of(shelf)); + service['shelfStateSubject'].next({shelves: [], loaded: true, error: null}); + service.createShelf(shelf).subscribe(result => { + expect(result).toEqual(shelf); + expect(service['shelfStateSubject'].value.shelves).toContain(shelf); + }); + }); + + it('should update a shelf and update state', () => { + const shelf: Shelf = {id: 3, name: 'C', icon: 'icon'}; + httpClientMock.put.mockReturnValue(of({...shelf, name: 'C2'})); + service['shelfStateSubject'].next({shelves: [shelf], loaded: true, error: null}); + service.updateShelf({...shelf, name: 'C2'}, 3).subscribe(result => { + expect(result.name).toBe('C2'); + expect(service['shelfStateSubject'].value.shelves?.find(s => s.id === 3)?.name).toBe('C2'); + }); + }); + + it('should delete a shelf and update state', () => { + httpClientMock.delete.mockReturnValue(of(void 0)); + const shelf: Shelf = {id: 4, name: 'D', icon: 'icon'}; + service['shelfStateSubject'].next({shelves: [shelf], loaded: true, error: null}); + service.deleteShelf(4).subscribe(() => { + expect(service['shelfStateSubject'].value.shelves).toEqual([]); + expect(bookServiceMock.removeBooksFromShelf).toHaveBeenCalledWith(4); + }); + }); + + it('should handle delete shelf error', () => { + httpClientMock.delete.mockReturnValue(throwError(() => new Error('delete error'))); + service['shelfStateSubject'].next({shelves: [{id: 5, name: 'E', icon: 'icon'}], loaded: true, error: null}); + service.deleteShelf(5).subscribe({ + error: () => { + expect(service['shelfStateSubject'].value.error).toBe('delete error'); + } + }); + }); + + it('should get shelf by id', () => { + const shelf: Shelf = {id: 6, name: 'F', icon: 'icon'}; + service['shelfStateSubject'].next({shelves: [shelf], loaded: true, error: null}); + expect(service.getShelfById(6)).toEqual(shelf); + expect(service.getShelfById(999)).toBeUndefined(); + }); + + it('should get book count for shelf', async () => { + const count = await firstValueFrom(service.getBookCount(10)); + expect(count).toBe(1); + }); + + it('should get unshelved book count', async () => { + const count = await firstValueFrom(service.getUnshelvedBookCount()); + expect(count).toBe(2); + }); +}); + diff --git a/booklore-ui/src/app/features/book/service/sort.service.spec.ts b/booklore-ui/src/app/features/book/service/sort.service.spec.ts new file mode 100644 index 000000000..7c1d15e91 --- /dev/null +++ b/booklore-ui/src/app/features/book/service/sort.service.spec.ts @@ -0,0 +1,142 @@ +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {SortService} from './sort.service'; +import {Book} from '../model/book.model'; +import {SortDirection} from '../model/sort.model'; + +function makeBook(partial: Partial): Book { + return { + id: 1, + bookType: "PDF", + libraryId: 1, + libraryName: "Lib", + ...partial, + } as Book; +} + +describe('SortService', () => { + let service: SortService; + let books: Book[]; + + beforeEach(() => { + service = new SortService(); + books = [ + makeBook({ + id: 1, + fileName: 'Book10.pdf', + metadata: { + bookId: 1, + title: 'Book 10', + authors: ['Alice'], + publishedDate: '2020-01-01', + seriesName: 'Series A', + seriesNumber: 2, + rating: 4.5, + reviewCount: 10, + }, + personalRating: 3, + addedOn: '2021-01-01T00:00:00Z', + lastReadTime: '2022-01-01T00:00:00Z', + fileSizeKb: 1000, + }), + makeBook({ + id: 2, + fileName: 'Book2.pdf', + metadata: { + bookId: 2, + title: 'Book 2', + authors: ['Bob'], + publishedDate: '2019-01-01', + seriesName: 'Series A', + seriesNumber: 1, + rating: 4.8, + reviewCount: 20, + }, + personalRating: 5, + addedOn: '2020-01-01T00:00:00Z', + lastReadTime: '2023-01-01T00:00:00Z', + fileSizeKb: 2000, + }), + makeBook({ + id: 3, + fileName: 'Book1.pdf', + metadata: { + bookId: 3, + title: 'Book 1', + authors: ['Alice'], + publishedDate: '2021-01-01', + rating: 4.0, + reviewCount: 5, + }, + personalRating: 4, + addedOn: '2022-01-01T00:00:00Z', + lastReadTime: '2021-01-01T00:00:00Z', + fileSizeKb: 500, + }), + ]; + }); + + it('should sort by title (natural order)', () => { + const sorted = service.applySort(books, {field: 'title', direction: SortDirection.ASCENDING, label: 'Title'}); + expect(sorted.map(b => b.metadata?.title)).toEqual(['Book 1', 'Book 2', 'Book 10']); + }); + + it('should sort by author', () => { + const sorted = service.applySort(books, {field: 'author', direction: SortDirection.ASCENDING, label: 'Author'}); + expect(sorted.map(b => b.metadata?.authors?.[0])).toEqual(['Alice', 'Alice', 'Bob']); + }); + + it('should sort by publishedDate descending', () => { + const sorted = service.applySort(books, {field: 'publishedDate', direction: SortDirection.DESCENDING, label: 'Published Date'}); + expect(sorted.map(b => b.metadata?.title)).toEqual(['Book 1', 'Book 10', 'Book 2']); + }); + + it('should sort by series (titleSeries)', () => { + const sorted = service.applySort(books, {field: 'titleSeries', direction: SortDirection.ASCENDING, label: 'Series'}); + expect(sorted.map(b => b.metadata?.title)).toEqual(['Book 1', 'Book 2', 'Book 10']); + }); + + it('should sort by personalRating descending', () => { + const sorted = service.applySort(books, {field: 'personalRating', direction: SortDirection.DESCENDING, label: 'Personal Rating'}); + expect(sorted.map(b => b.personalRating)).toEqual([5, 4, 3]); + }); + + it('should sort by fileName (natural order)', () => { + const sorted = service.applySort(books, {field: 'fileName', direction: SortDirection.ASCENDING, label: 'File Name'}); + expect(sorted.map(b => b.fileName)).toEqual(['Book1.pdf', 'Book2.pdf', 'Book10.pdf']); + }); + + it('should sort by fileSizeKb ascending', () => { + const sorted = service.applySort(books, {field: 'fileSizeKb', direction: SortDirection.ASCENDING, label: 'File Size'}); + expect(sorted.map(b => b.fileSizeKb)).toEqual([500, 1000, 2000]); + }); + + it('should sort by addedOn descending', () => { + const sorted = service.applySort(books, {field: 'addedOn', direction: SortDirection.DESCENDING, label: 'Added On'}); + expect(sorted.map(b => b.addedOn)).toEqual([ + '2022-01-01T00:00:00Z', + '2021-01-01T00:00:00Z', + '2020-01-01T00:00:00Z', + ]); + }); + + it('should handle missing extractor gracefully', () => { + const spy = vi.spyOn(console, 'warn').mockImplementation(() => { + }); + const sorted = service.applySort(books, {field: 'nonexistent', direction: SortDirection.ASCENDING, label: 'Nonexistent'} as any); + expect(sorted).toBe(books); + expect(spy).toHaveBeenCalled(); + spy.mockRestore(); + }); + + it('should return original array if no sort option', () => { + const sorted = service.applySort(books, null); + expect(sorted).toBe(books); + }); + + it('should sort by random (order is not predictable)', () => { + const sorted = service.applySort(books, {field: 'random', direction: SortDirection.ASCENDING, label: 'Random'}); + expect(sorted.length).toBe(3); + // Can't assert order, but should be a permutation of the input + expect(sorted.map(b => b.id).sort()).toEqual([1, 2, 3]); + }); +}); diff --git a/booklore-ui/src/app/features/bookdrop/component/bookdrop-pattern-extract-dialog/bookdrop-pattern-extract-dialog.component.ts b/booklore-ui/src/app/features/bookdrop/component/bookdrop-pattern-extract-dialog/bookdrop-pattern-extract-dialog.component.ts index 089dd0aa5..509de563f 100644 --- a/booklore-ui/src/app/features/bookdrop/component/bookdrop-pattern-extract-dialog/bookdrop-pattern-extract-dialog.component.ts +++ b/booklore-ui/src/app/features/bookdrop/component/bookdrop-pattern-extract-dialog/bookdrop-pattern-extract-dialog.component.ts @@ -267,7 +267,7 @@ export class BookdropPatternExtractDialogComponent implements OnInit { return preview.success ? 'pi-check-circle' : 'pi-times-circle'; } - getPreviewEntries(preview: PreviewResult): Array<{key: string; value: string}> { + getPreviewEntries(preview: PreviewResult): {key: string; value: string}[] { return Object.entries(preview.preview).map(([key, value]) => ({key, value})); } diff --git a/booklore-ui/src/app/features/dashboard/components/main-dashboard/main-dashboard.component.ts b/booklore-ui/src/app/features/dashboard/components/main-dashboard/main-dashboard.component.ts index 74d29a4a7..dc23d43fd 100644 --- a/booklore-ui/src/app/features/dashboard/components/main-dashboard/main-dashboard.component.ts +++ b/booklore-ui/src/app/features/dashboard/components/main-dashboard/main-dashboard.component.ts @@ -137,7 +137,7 @@ export class MainDashboardComponent implements OnInit { return this.bookService.bookState$.pipe( map((state: BookState) => { - let filteredBooks = (state.books || []).filter((book) => + const filteredBooks = (state.books || []).filter((book) => this.ruleEvaluatorService.evaluateGroup(book, group) ); diff --git a/booklore-ui/src/app/features/library-creator/library-creator.component.ts b/booklore-ui/src/app/features/library-creator/library-creator.component.ts index 46d240ffa..d0b4773dd 100644 --- a/booklore-ui/src/app/features/library-creator/library-creator.component.ts +++ b/booklore-ui/src/app/features/library-creator/library-creator.component.ts @@ -15,6 +15,8 @@ import {Select} from 'primeng/select'; import {Button} from 'primeng/button'; import {IconDisplayComponent} from '../../shared/components/icon-display/icon-display.component'; import {DialogLauncherService} from '../../shared/services/dialog-launcher.service'; +import {switchMap} from 'rxjs/operators'; +import {map, of} from 'rxjs'; @Component({ selector: 'app-library-creator', @@ -126,9 +128,9 @@ export class LibraryCreatorComponent implements OnInit { } validateLibraryNameAndProceed(activateCallback: Function): void { - let trimmedLibraryName = this.chosenLibraryName.trim(); + const trimmedLibraryName = this.chosenLibraryName.trim(); if (trimmedLibraryName && trimmedLibraryName != this.editModeLibraryName) { - let exists = this.libraryService.doesLibraryExistByName(trimmedLibraryName); + const exists = this.libraryService.doesLibraryExistByName(trimmedLibraryName); if (exists) { this.messageService.add({ severity: 'error', @@ -147,16 +149,17 @@ export class LibraryCreatorComponent implements OnInit { const iconValue = this.selectedIcon?.value || 'heart'; const iconType = this.selectedIcon?.type || 'PRIME_NG'; + const library: Library = { + name: this.chosenLibraryName, + icon: iconValue, + iconType: iconType, + paths: this.folders.map(folder => ({path: folder})), + watch: this.watch, + scanMode: this.scanMode, + defaultBookFormat: this.defaultBookFormat + }; + if (this.mode === 'edit') { - const library: Library = { - name: this.chosenLibraryName, - icon: iconValue, - iconType: iconType, - paths: this.folders.map(folder => ({path: folder})), - watch: this.watch, - scanMode: this.scanMode, - defaultBookFormat: this.defaultBookFormat - }; this.libraryService.updateLibrary(library, this.library?.id).subscribe({ next: () => { this.messageService.add({severity: 'success', summary: 'Library Updated', detail: 'The library was updated successfully.'}); @@ -168,22 +171,36 @@ export class LibraryCreatorComponent implements OnInit { } }); } else { - const library: Library = { - name: this.chosenLibraryName, - icon: iconValue, - iconType: iconType, - paths: this.folders.map(folder => ({path: folder})), - watch: this.watch, - scanMode: this.scanMode, - defaultBookFormat: this.defaultBookFormat - }; - this.libraryService.createLibrary(library).subscribe({ - next: (createdLibrary) => { - this.router.navigate(['/library', createdLibrary.id, 'books']); - this.messageService.add({severity: 'success', summary: 'Library Created', detail: 'The library was created successfully.'}); - this.dynamicDialogRef.close(); + this.libraryService.scanLibraryPaths(library).pipe( + switchMap(count => { + if (count < 500) { + return this.libraryService.createLibrary(library).pipe( + map(createdLibrary => ({ createdLibrary, count })) + ); + } else { + console.warn(`Library has ${count} processable files (>500). Will use buffered loading.`); + this.libraryService.setLargeLibraryLoading(true, count); + return this.libraryService.createLibrary(library).pipe( + map(createdLibrary => ({ createdLibrary, count })) + ); + } + }) + ).subscribe({ + next: ({ createdLibrary, count }) => { + if (createdLibrary) { + this.router.navigate(['/library', createdLibrary.id, 'books']); + this.messageService.add({ + severity: 'success', + summary: 'Library Created', + detail: count >= 500 + ? `Library created with ${count} files. Loading in progress...` + : 'The library was created successfully.' + }); + this.dynamicDialogRef.close(); + } }, error: (e) => { + this.libraryService.setLargeLibraryLoading(false, 0); this.messageService.add({severity: 'error', summary: 'Creation Failed', detail: 'An error occurred while creating the library. Please try again.'}); console.error(e); } diff --git a/booklore-ui/src/app/features/library-creator/library-loading.service.ts b/booklore-ui/src/app/features/library-creator/library-loading.service.ts new file mode 100644 index 000000000..765a11170 --- /dev/null +++ b/booklore-ui/src/app/features/library-creator/library-loading.service.ts @@ -0,0 +1,47 @@ +import { Injectable, ComponentRef, ApplicationRef, createComponent, EnvironmentInjector } from '@angular/core'; +import { LibraryLoadingComponent } from './library-loading/library-loading.component'; + +@Injectable({ + providedIn: 'root' +}) +export class LibraryLoadingService { + private componentRef: ComponentRef | null = null; + + constructor( + private appRef: ApplicationRef, + private injector: EnvironmentInjector + ) {} + + showBookLoadingProgress(bookTitle: string, current: number, total: number): void { + if (this.componentRef) { + this.updateProgress(bookTitle, current, total); + return; + } + + this.componentRef = createComponent(LibraryLoadingComponent, { + environmentInjector: this.injector + }); + + this.componentRef.instance.updateProgress(bookTitle, current, total); + + this.appRef.attachView(this.componentRef.hostView); + const domElem = (this.componentRef.hostView as any).rootNodes[0] as HTMLElement; + document.body.appendChild(domElem); + document.body.style.overflow = 'hidden'; + } + + updateProgress(bookTitle: string, current: number, total: number): void { + if (this.componentRef) { + this.componentRef.instance.updateProgress(bookTitle, current, total); + } + } + + hide(): void { + if (this.componentRef) { + this.appRef.detachView(this.componentRef.hostView); + this.componentRef.destroy(); + this.componentRef = null; + document.body.style.overflow = ''; + } + } +} diff --git a/booklore-ui/src/app/features/library-creator/library-loading/library-loading.component.html b/booklore-ui/src/app/features/library-creator/library-loading/library-loading.component.html new file mode 100644 index 000000000..1f552bf46 --- /dev/null +++ b/booklore-ui/src/app/features/library-creator/library-loading/library-loading.component.html @@ -0,0 +1,50 @@ +
+
+
+ +

Loading Library

+
+ +
+
+ @if (!isComplete) { + + Processing: {{ truncatedTitle }} + + } + @if (isComplete) { + + + Library Loading Complete! + + } +
+ +
+ {{ current }} / {{ total }} + {{ percentage }}% +
+ +
+
+
+ + @if (!isComplete) { +
+
+
+
+
+ } +
+ + @if (isComplete) { + + } +
+
diff --git a/booklore-ui/src/app/features/library-creator/library-loading/library-loading.component.scss b/booklore-ui/src/app/features/library-creator/library-loading/library-loading.component.scss new file mode 100644 index 000000000..e70294568 --- /dev/null +++ b/booklore-ui/src/app/features/library-creator/library-loading/library-loading.component.scss @@ -0,0 +1,151 @@ +.fullscreen-loader { + position: fixed; + top: 0; + left: 0; + width: 100%; + height: 100%; + background: rgba(0, 0, 0, 0.85); + backdrop-filter: blur(8px); + display: flex; + justify-content: center; + align-items: center; + z-index: 9999; +} + +.library-loader-content { + background: var(--card-background); + padding: 2.5rem; + border-radius: 12px; + width: 550px; + max-width: 90vw; + box-sizing: border-box; + border: 1px solid var(--border-color); +} + +.library-loader-header { + text-align: center; + + i { + font-size: 3rem; + color: var(--primary-color); + margin-bottom: 1rem; + } + + h2 { + margin: 0 0 0.5rem 0; + color: var(--text-color); + font-size: 1.5rem; + } +} + +.library-loader-body { + .book-title { + color: var(--text-color-secondary); + margin-bottom: 1.5rem; + margin-top: 2.5rem; + font-size: 0.95rem; + word-break: break-word; + overflow-wrap: break-word; + line-height: 1.4; + display: flex; + align-items: flex-start; + + strong { + color: var(--text-color); + } + + .complete-message { + color: var(--primary-color); + font-size: 1.1rem; + + i { + margin-right: 0.5rem; + } + } + } + + .progress-info { + display: flex; + justify-content: space-between; + margin-bottom: 0.5rem; + color: var(--text-color-secondary); + font-size: 0.9rem; + } + + .progress-bar-container { + width: 100%; + height: 8px; + background: var(--card-background); + border-radius: 4px; + overflow: hidden; + + .progress-bar-fill { + height: 100%; + background: var(--primary-color); + transition: width 0.3s ease; + } + } + + .loader-animation { + margin-top: 1.5rem; + display: flex; + justify-content: center; + gap: 0.5rem; + + .dot { + width: 8px; + height: 8px; + background: var(--primary-color); + border-radius: 50%; + animation: bounce 1.4s infinite ease-in-out both; + + &:nth-child(2) { + animation-delay: 0.2s; + } + + &:nth-child(3) { + animation-delay: 0.4s; + } + } + } +} + +.library-loader-footer { + margin-top: 3rem; + text-align: center; + + .reload-button { + padding: 0.75rem 1.25rem; + background: var(--primary-color); + color: white; + border: none; + border-radius: 6px; + font-size: 1rem; + cursor: pointer; + transition: all 0.3s ease; + font-weight: 700; + + i { + margin-right: 0.5rem; + } + + &:hover { + background: var(--primary-hover-color); + transform: translateY(-2px); + box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2); + } + + &:active { + transform: translateY(0); + } + } +} + +@keyframes bounce { + 0%, 80%, 100% { + transform: scale(0); + } + 40% { + transform: scale(1); + } +} diff --git a/booklore-ui/src/app/features/library-creator/library-loading/library-loading.component.ts b/booklore-ui/src/app/features/library-creator/library-loading/library-loading.component.ts new file mode 100644 index 000000000..fcaf5fb62 --- /dev/null +++ b/booklore-ui/src/app/features/library-creator/library-loading/library-loading.component.ts @@ -0,0 +1,39 @@ +import { Component } from '@angular/core'; +import { CommonModule } from '@angular/common'; + +@Component({ + selector: 'app-library-loading', + standalone: true, + imports: [CommonModule], + templateUrl: './library-loading.component.html', + styleUrl: './library-loading.component.scss' +}) +export class LibraryLoadingComponent { + bookTitle = ''; + current = 0; + total = 0; + isComplete = false; + + get percentage(): number { + return this.total > 0 ? Math.round((this.current / this.total) * 100) : 0; + } + + get truncatedTitle(): string { + const maxLength = 50; + return this.bookTitle.length <= maxLength + ? this.bookTitle + : this.bookTitle.substring(0, maxLength) + '...'; + } + + updateProgress(bookTitle: string, current: number, total: number): void { + this.bookTitle = bookTitle; + this.current = current; + this.total = total; + this.isComplete = current >= total; + } + + onReload(): void { + window.location.reload(); + } +} + diff --git a/booklore-ui/src/app/features/magic-shelf/component/magic-shelf-component.html b/booklore-ui/src/app/features/magic-shelf/component/magic-shelf-component.html index b6b882b5a..30c5d8fc1 100644 --- a/booklore-ui/src/app/features/magic-shelf/component/magic-shelf-component.html +++ b/booklore-ui/src/app/features/magic-shelf/component/magic-shelf-component.html @@ -138,6 +138,8 @@ } @else if (ruleCtrl.get('field')?.value === 'library') { + } @else if (ruleCtrl.get('field')?.value === 'categories') { + } @else {
@@ -149,6 +151,8 @@ } @else if (ruleCtrl.get('field')?.value === 'library') { + } @else if (ruleCtrl.get('field')?.value === 'categories') { + } @else { } diff --git a/booklore-ui/src/app/features/magic-shelf/component/magic-shelf-component.ts b/booklore-ui/src/app/features/magic-shelf/component/magic-shelf-component.ts index 9dc36e43e..c32b9bee3 100644 --- a/booklore-ui/src/app/features/magic-shelf/component/magic-shelf-component.ts +++ b/booklore-ui/src/app/features/magic-shelf/component/magic-shelf-component.ts @@ -19,6 +19,7 @@ import {IconPickerService, IconSelection} from '../../../shared/service/icon-pic import {CheckboxChangeEvent, CheckboxModule} from "primeng/checkbox"; import {UserService} from "../../settings/user-management/user.service"; import {IconDisplayComponent} from '../../../shared/components/icon-display/icon-display.component'; +import {BookService} from '../../book/service/book.service'; export type RuleOperator = | 'equals' @@ -51,6 +52,8 @@ export type RuleField = | 'seriesTotal' | 'pageCount' | 'language' + | 'isbn13' + | 'isbn10' | 'amazonRating' | 'amazonReviewCount' | 'goodreadsRating' @@ -126,6 +129,8 @@ const FIELD_CONFIGS: Record = { personalRating: {label: 'Personal Rating', type: 'decimal', max: 10}, pageCount: {label: 'Page Count', type: 'number'}, language: {label: 'Language'}, + isbn13: {label: 'ISBN-13'}, + isbn10: {label: 'ISBN-10'}, seriesName: {label: 'Series Name'}, seriesNumber: {label: 'Series Number', type: 'number'}, seriesTotal: {label: 'Books in Series', type: 'number'}, @@ -172,10 +177,14 @@ export class MagicShelfComponent implements OnInit { {label: 'OR', value: 'or'}, ]; - fieldOptions = Object.entries(FIELD_CONFIGS).map(([key, config]) => ({ - label: config.label, - value: key as RuleField - })); + fieldOptions = Object.entries(FIELD_CONFIGS).map(([key, config]) => { + // Use "Genre" instead of "Categories" for user-facing label + const label = key === 'categories' ? 'Genre' : config.label; + return { + label: label, + value: key as RuleField + }; + }); fileType: { label: string; value: string }[] = [ {label: 'PDF', value: 'pdf'}, @@ -192,6 +201,7 @@ export class MagicShelfComponent implements OnInit { libraries: Library[] = []; libraryOptions: { label: string; value: number }[] = []; + categoryOptions: { label: string; value: string }[] = []; form = new FormGroup({ name: new FormControl(null), @@ -205,6 +215,7 @@ export class MagicShelfComponent implements OnInit { editMode!: boolean; libraryService = inject(LibraryService); + bookService = inject(BookService); magicShelfService = inject(MagicShelfService); ref = inject(DynamicDialogRef); messageService = inject(MessageService); @@ -223,6 +234,24 @@ export class MagicShelfComponent implements OnInit { const id = this.config?.data?.id; this.editMode = !!this.config?.data?.editMode; + // Load available categories from book metadata + this.bookService.bookState$.subscribe(state => { + if (state.loaded && state.books) { + // Extract unique categories from all books + const categoriesSet = new Set(); + state.books.forEach(book => { + if (book.metadata?.categories) { + book.metadata.categories.forEach(cat => categoriesSet.add(cat)); + } + }); + + this.categoryOptions = Array.from(categoriesSet).map(cat => ({ + label: cat, + value: cat + })).sort((a, b) => a.label.localeCompare(b.label)); + } + }); + if (id) { this.shelfId = id; this.magicShelfService.getShelf(id).subscribe((data) => { @@ -324,7 +353,7 @@ export class MagicShelfComponent implements OnInit { if (!field) return [...baseOperators, ...multiValueOperators]; const config = FIELD_CONFIGS[field]; - const isMultiValueField = ['library', 'authors', 'categories', 'moods', 'tags', 'readStatus', 'fileType', 'language', 'title', 'subtitle', 'publisher', 'seriesName'].includes(field); + const isMultiValueField = ['library', 'authors', 'categories', 'moods', 'tags', 'readStatus', 'fileType', 'language', 'title', 'subtitle', 'publisher', 'seriesName', 'isbn13', 'isbn10'].includes(field); const operators = [...baseOperators]; if (isMultiValueField) { @@ -354,7 +383,7 @@ export class MagicShelfComponent implements OnInit { createGroup(): GroupFormGroup { return new FormGroup({ - type: new FormControl<'group'>('group' as 'group'), + type: new FormControl<'group'>('group' as const), join: new FormControl<'and' | 'or'>('and' as 'and' | 'or'), rules: new FormArray([] as (GroupFormGroup | RuleFormGroup)[]), }) as GroupFormGroup; diff --git a/booklore-ui/src/app/features/magic-shelf/service/book-rule-evaluator.service.ts b/booklore-ui/src/app/features/magic-shelf/service/book-rule-evaluator.service.ts index de78c05dd..9b5dbaae1 100644 --- a/booklore-ui/src/app/features/magic-shelf/service/book-rule-evaluator.service.ts +++ b/booklore-ui/src/app/features/magic-shelf/service/book-rule-evaluator.service.ts @@ -61,6 +61,10 @@ export class BookRuleEvaluatorService { return [String(book.metadata?.publisher ?? '').toLowerCase()]; case 'seriesName': return [String(book.metadata?.seriesName ?? '').toLowerCase()]; + case 'isbn13': + return [String(book.metadata?.isbn13 ?? '').toLowerCase()]; + case 'isbn10': + return [String(book.metadata?.isbn10 ?? '').toLowerCase()]; default: return []; } @@ -232,6 +236,10 @@ export class BookRuleEvaluatorService { return book.metadata?.pageCount; case 'language': return book.metadata?.language?.toLowerCase() ?? null; + case 'isbn13': + return book.metadata?.isbn13?.toLowerCase() ?? null; + case 'isbn10': + return book.metadata?.isbn10?.toLowerCase() ?? null; case 'amazonRating': return book.metadata?.amazonRating; case 'amazonReviewCount': diff --git a/booklore-ui/src/app/features/metadata/component/book-metadata-center/book-metadata-center.component.ts b/booklore-ui/src/app/features/metadata/component/book-metadata-center/book-metadata-center.component.ts index 50183d3f0..20bd24fc3 100644 --- a/booklore-ui/src/app/features/metadata/component/book-metadata-center/book-metadata-center.component.ts +++ b/booklore-ui/src/app/features/metadata/component/book-metadata-center/book-metadata-center.component.ts @@ -8,7 +8,7 @@ import {BookService} from '../../../book/service/book.service'; import {AppSettingsService} from '../../../../shared/service/app-settings.service'; import {Tab, TabList, TabPanel, TabPanels, Tabs,} from 'primeng/tabs'; import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog'; -import {BookMetadataHostService} from '../../../../shared/service/book-metadata-host-service'; +import {BookMetadataHostService} from '../../../../shared/service/book-metadata-host.service'; import {MetadataViewerComponent} from './metadata-viewer/metadata-viewer.component'; import {MetadataEditorComponent} from './metadata-editor/metadata-editor.component'; import {MetadataSearcherComponent} from './metadata-searcher/metadata-searcher.component'; diff --git a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.html b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.html index 13c2a2f4f..56d9a5b1e 100644 --- a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.html +++ b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.html @@ -1,14 +1,14 @@ @if (book$ | async; as book) { -
+ @if (isLoading) { -
+
} @if (isLoading) { - + } -
-
-
+
+
+
@if (isUploading) { - - + } -
+
-
+
-
-
- -
- +
+
+ +
+ @if (!book.metadata!['titleLocked']) { } @@ -94,10 +92,10 @@
-
- -
- +
+ +
+ @if (!book.metadata!['subtitleLocked']) { } @@ -107,10 +105,10 @@
-
- -
- +
+ +
+ @if (!book.metadata!['languageLocked']) { } @@ -121,12 +119,11 @@
-
-
- -
+
+
+ +
-
- -
+
+ +
-
- -
+
+ +
-
-
- -
-
+
+
+ +
+
-
-
- -
-
+
+
+ +
+
-
-
- -
-
+
+
+ +
+
-
-
- -
+
+
+ +
-
- -
- +
+ +
+ @if (!book.metadata!['seriesNumberLocked']) { } @@ -315,10 +306,10 @@
-
- -
- +
+ +
+ @if (!book.metadata!['seriesTotalLocked']) { } @@ -328,10 +319,10 @@
-
- -
- +
+ +
+ @if (!book.metadata!['pageCountLocked']) { } @@ -344,11 +335,11 @@
-
-
- -
- +