Merge pull request #480 from adityachandelgit/develop
Merge Develop into Master for Release
This commit is contained in:
@@ -52,6 +52,7 @@ services:
|
||||
- DATABASE_URL=jdbc:mariadb://mariadb:3306/booklore # Only modify this if you're familiar with JDBC and your database setup
|
||||
- DATABASE_USERNAME=booklore # Must match MYSQL_USER defined in the mariadb container
|
||||
- DATABASE_PASSWORD=your_secure_password # Use a strong password; must match MYSQL_PASSWORD defined in the mariadb container
|
||||
- SWAGGER_ENABLED=false # Enable or disable Swagger UI (API docs). Set to 'true' to allow access; 'false' to block access (recommended for production).
|
||||
depends_on:
|
||||
mariadb:
|
||||
condition: service_healthy
|
||||
|
||||
@@ -12,8 +12,8 @@ import org.springframework.stereotype.Component;
|
||||
public class AppProperties {
|
||||
private String pathConfig;
|
||||
private String version;
|
||||
|
||||
private RemoteAuth remoteAuth;
|
||||
private Swagger swagger = new Swagger();
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@@ -26,4 +26,10 @@ public class AppProperties {
|
||||
private String headerGroups;
|
||||
private String adminGroup;
|
||||
}
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public static class Swagger {
|
||||
private boolean enabled = true;
|
||||
}
|
||||
}
|
||||
|
||||
+1
-3
@@ -18,9 +18,7 @@ public class CustomOpdsUserDetailsService implements UserDetailsService {
|
||||
|
||||
@Override
|
||||
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
|
||||
OpdsUserEntity user = opdsUserRepository.findByUsername(username)
|
||||
.orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(username));
|
||||
|
||||
OpdsUserEntity user = opdsUserRepository.findByUsername(username).orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(username));
|
||||
return User.builder()
|
||||
.username(user.getUsername())
|
||||
.password(user.getPassword())
|
||||
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.adityachandel.booklore.config.security;
|
||||
|
||||
import org.springframework.boot.web.servlet.FilterRegistrationBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
public class ImageCacheConfig {
|
||||
|
||||
@Bean
|
||||
public FilterRegistrationBean<ImageCachingFilter> imageCachingFilterRegistration() {
|
||||
FilterRegistrationBean<ImageCachingFilter> registrationBean = new FilterRegistrationBean<>();
|
||||
registrationBean.setFilter(new ImageCachingFilter());
|
||||
registrationBean.addUrlPatterns("/api/v1/books/*/cover");
|
||||
return registrationBean;
|
||||
}
|
||||
}
|
||||
-2
@@ -15,12 +15,10 @@ public class ImageCachingFilter extends OncePerRequestFilter {
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
|
||||
|
||||
if (request.getRequestURI().startsWith("/api/v1/books") && request.getRequestURI().contains("/cover")) {
|
||||
response.setHeader(HttpHeaders.CACHE_CONTROL, "public, max-age=3600");
|
||||
response.setHeader(HttpHeaders.EXPIRES, String.valueOf(System.currentTimeMillis() + 3600000));
|
||||
}
|
||||
|
||||
filterChain.doFilter(request, response);
|
||||
}
|
||||
}
|
||||
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
package com.adityachandel.booklore.config.security;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.settings.OidcProviderDetails;
|
||||
import com.adityachandel.booklore.service.appsettings.AppSettingService;
|
||||
import com.nimbusds.jose.JWSAlgorithm;
|
||||
import com.nimbusds.jose.jwk.source.JWKSource;
|
||||
import com.nimbusds.jose.jwk.source.RemoteJWKSet;
|
||||
import com.nimbusds.jose.proc.JWSKeySelector;
|
||||
import com.nimbusds.jose.proc.JWSVerificationKeySelector;
|
||||
import com.nimbusds.jose.proc.SecurityContext;
|
||||
import com.nimbusds.jose.util.DefaultResourceRetriever;
|
||||
import com.nimbusds.jwt.JWTClaimsSet;
|
||||
import com.nimbusds.jwt.proc.ConfigurableJWTProcessor;
|
||||
import com.nimbusds.jwt.proc.DefaultJWTProcessor;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.URL;
|
||||
import java.util.Collections;
|
||||
import java.util.Date;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class OidcTokenValidator {
|
||||
|
||||
private final AppSettingService appSettingService;
|
||||
|
||||
public Authentication validate(String token) {
|
||||
if (!appSettingService.getAppSettings().isOidcEnabled()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
OidcProviderDetails providerDetails = appSettingService.getAppSettings().getOidcProviderDetails();
|
||||
String jwksUrl = providerDetails.getJwksUrl();
|
||||
if (jwksUrl == null || jwksUrl.isEmpty()) {
|
||||
log.error("JWKS URL is not configured");
|
||||
return null;
|
||||
}
|
||||
|
||||
URL jwksURL = new URI(jwksUrl).toURL();
|
||||
DefaultResourceRetriever resourceRetriever = new DefaultResourceRetriever(2000, 2000);
|
||||
JWKSource<SecurityContext> jwkSource = new RemoteJWKSet<>(jwksURL, resourceRetriever);
|
||||
ConfigurableJWTProcessor<SecurityContext> jwtProcessor = new DefaultJWTProcessor<>();
|
||||
JWSKeySelector<SecurityContext> keySelector = new JWSVerificationKeySelector<>(JWSAlgorithm.RS256, jwkSource);
|
||||
jwtProcessor.setJWSKeySelector(keySelector);
|
||||
|
||||
JWTClaimsSet claimsSet = jwtProcessor.process(token, null);
|
||||
Date expirationTime = claimsSet.getExpirationTime();
|
||||
if (expirationTime == null || expirationTime.before(new Date())) {
|
||||
log.warn("OIDC token is expired or missing exp claim");
|
||||
return null;
|
||||
}
|
||||
return new UsernamePasswordAuthenticationToken("oidc-user", null, Collections.emptyList());
|
||||
} catch (Exception e) {
|
||||
log.error("OIDC token validation failed", e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package com.adityachandel.booklore.config.security;
|
||||
|
||||
import io.swagger.v3.oas.models.Components;
|
||||
import io.swagger.v3.oas.models.OpenAPI;
|
||||
import io.swagger.v3.oas.models.info.Info;
|
||||
import io.swagger.v3.oas.models.security.SecurityRequirement;
|
||||
import io.swagger.v3.oas.models.security.SecurityScheme;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
public class OpenApiConfig {
|
||||
|
||||
@Bean
|
||||
public OpenAPI customOpenAPI() {
|
||||
final String securitySchemeName = "bearerAuth";
|
||||
|
||||
return new OpenAPI()
|
||||
.info(new Info().title("Booklore API").version("1.0"))
|
||||
.addSecurityItem(new SecurityRequirement().addList(securitySchemeName))
|
||||
.components(new Components().addSecuritySchemes(securitySchemeName,
|
||||
new SecurityScheme()
|
||||
.name(securitySchemeName)
|
||||
.type(SecurityScheme.Type.HTTP)
|
||||
.scheme("bearer")
|
||||
.bearerFormat("JWT")));
|
||||
}
|
||||
}
|
||||
+54
-25
@@ -1,9 +1,12 @@
|
||||
package com.adityachandel.booklore.config.security;
|
||||
|
||||
import com.adityachandel.booklore.config.AppProperties;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.web.servlet.FilterRegistrationBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.authentication.AuthenticationProvider;
|
||||
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
|
||||
@@ -20,8 +23,12 @@ import org.springframework.web.cors.CorsConfiguration;
|
||||
import org.springframework.web.cors.CorsConfigurationSource;
|
||||
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
|
||||
@AllArgsConstructor
|
||||
@EnableMethodSecurity
|
||||
@Configuration
|
||||
@@ -29,6 +36,24 @@ public class SecurityConfig {
|
||||
|
||||
private final CustomOpdsUserDetailsService customOpdsUserDetailsService;
|
||||
private final DualJwtAuthenticationFilter dualJwtAuthenticationFilter;
|
||||
private final AppProperties appProperties;
|
||||
|
||||
private static final String[] SWAGGER_ENDPOINTS = {
|
||||
"/swagger-ui.html",
|
||||
"/swagger-ui/**",
|
||||
"/v3/api-docs/**"
|
||||
};
|
||||
|
||||
private static final String[] COMMON_PUBLIC_ENDPOINTS = {
|
||||
"/ws/**",
|
||||
"/api/v1/auth/**",
|
||||
"/api/v1/settings",
|
||||
"/api/v1/setup/**",
|
||||
"/api/v1/books/*/cover",
|
||||
"/api/v1/opds/*/cover.jpg",
|
||||
"/api/v1/cbx/*/pages/*",
|
||||
"/api/v1/pdf/*/pages/*"
|
||||
};
|
||||
|
||||
@Bean
|
||||
public PasswordEncoder passwordEncoder() {
|
||||
@@ -36,33 +61,44 @@ public class SecurityConfig {
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
|
||||
@Order(1)
|
||||
public SecurityFilterChain opdsBasicAuthSecurityChain(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.securityMatcher("/api/v1/opds/**")
|
||||
.csrf(AbstractHttpConfigurer::disable)
|
||||
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
|
||||
.httpBasic(basic -> basic
|
||||
.realmName("Booklore OPDS")
|
||||
.authenticationEntryPoint((request, response, authException) -> {
|
||||
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
response.setHeader("WWW-Authenticate", "Basic realm=\"Booklore OPDS\"");
|
||||
response.getWriter().write("HTTP Status 401 - " + authException.getMessage());
|
||||
})
|
||||
);
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Order(2)
|
||||
public SecurityFilterChain jwtApiSecurityChain(HttpSecurity http) throws Exception {
|
||||
List<String> publicEndpoints = new ArrayList<>(Arrays.asList(COMMON_PUBLIC_ENDPOINTS));
|
||||
if (appProperties.getSwagger().isEnabled()) {
|
||||
publicEndpoints.addAll(Arrays.asList(SWAGGER_ENDPOINTS));
|
||||
}
|
||||
http
|
||||
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
|
||||
.csrf(AbstractHttpConfigurer::disable)
|
||||
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.requestMatchers(
|
||||
"/api/v1/auth/**",
|
||||
"/swagger-ui/**",
|
||||
"/v3/api-docs/**",
|
||||
"/ws/**",
|
||||
"/api/v1/books/*/cover",
|
||||
"/api/v1/settings",
|
||||
"/api/v1/setup",
|
||||
"/api/v1/setup/**",
|
||||
"/api/v1/opds/*/cover.jpg",
|
||||
"/api/v1/cbx/*/pages/*",
|
||||
"/api/v1/pdf/*/pages/*"
|
||||
).permitAll()
|
||||
.requestMatchers(publicEndpoints.toArray(new String[0])).permitAll()
|
||||
.anyRequest().authenticated()
|
||||
)
|
||||
.httpBasic(customizer -> customizer.realmName("Booklore OPDS"))
|
||||
.addFilterBefore(dualJwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
|
||||
return http.build();
|
||||
}
|
||||
|
||||
|
||||
@Bean
|
||||
public AuthenticationManager authenticationManager(HttpSecurity http) throws Exception {
|
||||
return http.getSharedObject(AuthenticationManagerBuilder.class)
|
||||
@@ -86,17 +122,10 @@ public class SecurityConfig {
|
||||
configuration.setAllowedHeaders(List.of("Authorization", "Cache-Control", "Content-Type"));
|
||||
configuration.setExposedHeaders(List.of("Content-Disposition"));
|
||||
configuration.setAllowCredentials(true);
|
||||
|
||||
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
|
||||
source.registerCorsConfiguration("/**", configuration);
|
||||
|
||||
return source;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public FilterRegistrationBean<ImageCachingFilter> loggingFilter() {
|
||||
FilterRegistrationBean<ImageCachingFilter> registrationBean = new FilterRegistrationBean<>();
|
||||
registrationBean.setFilter(new ImageCachingFilter());
|
||||
registrationBean.addUrlPatterns("/api/v1/books/*/cover");
|
||||
return registrationBean;
|
||||
}
|
||||
|
||||
}
|
||||
+22
-35
@@ -12,65 +12,52 @@ public class SecurityUtil {
|
||||
|
||||
private final ShelfRepository shelfRepository;
|
||||
|
||||
public boolean isAdmin() {
|
||||
private BookLoreUser getCurrentUser() {
|
||||
var authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (authentication != null && authentication.getPrincipal() instanceof BookLoreUser user) {
|
||||
return user.getPermissions().isAdmin();
|
||||
return user;
|
||||
}
|
||||
return false;
|
||||
return null;
|
||||
}
|
||||
|
||||
public boolean isAdmin() {
|
||||
var user = getCurrentUser();
|
||||
return user != null && user.getPermissions().isAdmin();
|
||||
}
|
||||
|
||||
public boolean isSelf(Long userId) {
|
||||
var authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (authentication != null && authentication.getPrincipal() instanceof BookLoreUser user) {
|
||||
return user.getId().equals(userId);
|
||||
}
|
||||
return false;
|
||||
var user = getCurrentUser();
|
||||
return user != null && user.getId().equals(userId);
|
||||
}
|
||||
|
||||
public boolean canUpload() {
|
||||
var authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (authentication != null && authentication.getPrincipal() instanceof BookLoreUser user) {
|
||||
return user.getPermissions().isCanUpload();
|
||||
}
|
||||
return false;
|
||||
var user = getCurrentUser();
|
||||
return user != null && user.getPermissions().isCanUpload();
|
||||
}
|
||||
|
||||
public boolean canManipulateLibrary() {
|
||||
var authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (authentication != null && authentication.getPrincipal() instanceof BookLoreUser user) {
|
||||
return user.getPermissions().isCanManipulateLibrary();
|
||||
}
|
||||
return false;
|
||||
var user = getCurrentUser();
|
||||
return user != null && user.getPermissions().isCanManipulateLibrary();
|
||||
}
|
||||
|
||||
public boolean canEditMetadata() {
|
||||
var authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (authentication != null && authentication.getPrincipal() instanceof BookLoreUser user) {
|
||||
return user.getPermissions().isCanEditMetadata();
|
||||
}
|
||||
return false;
|
||||
var user = getCurrentUser();
|
||||
return user != null && user.getPermissions().isCanEditMetadata();
|
||||
}
|
||||
|
||||
public boolean canEmailBook() {
|
||||
var authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (authentication != null && authentication.getPrincipal() instanceof BookLoreUser user) {
|
||||
return user.getPermissions().isCanEmailBook();
|
||||
}
|
||||
return false;
|
||||
var user = getCurrentUser();
|
||||
return user != null && user.getPermissions().isCanEmailBook();
|
||||
}
|
||||
|
||||
public boolean canViewUserProfile(Long userId) {
|
||||
var authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (authentication != null && authentication.getPrincipal() instanceof BookLoreUser user) {
|
||||
return user.getPermissions().isAdmin() || user.getId().equals(userId);
|
||||
}
|
||||
return false;
|
||||
var user = getCurrentUser();
|
||||
return user != null && (user.getPermissions().isAdmin() || user.getId().equals(userId));
|
||||
}
|
||||
|
||||
public boolean isShelfOwner(Long shelfId) {
|
||||
var authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (authentication != null && authentication.getPrincipal() instanceof BookLoreUser user) {
|
||||
var user = getCurrentUser();
|
||||
if (user != null) {
|
||||
return shelfRepository.findById(shelfId)
|
||||
.map(shelf -> shelf.getUser().getId().equals(user.getId()))
|
||||
.orElse(false);
|
||||
|
||||
+10
-52
@@ -1,17 +1,6 @@
|
||||
package com.adityachandel.booklore.config.security;
|
||||
|
||||
import com.adityachandel.booklore.service.appsettings.AppSettingService;
|
||||
import com.nimbusds.jose.JWSAlgorithm;
|
||||
import com.nimbusds.jose.jwk.source.JWKSource;
|
||||
import com.nimbusds.jose.jwk.source.RemoteJWKSet;
|
||||
import com.nimbusds.jose.proc.JWSKeySelector;
|
||||
import com.nimbusds.jose.proc.JWSVerificationKeySelector;
|
||||
import com.nimbusds.jose.proc.SecurityContext;
|
||||
import com.nimbusds.jose.util.DefaultResourceRetriever;
|
||||
import com.nimbusds.jwt.JWTClaimsSet;
|
||||
import com.nimbusds.jwt.proc.ConfigurableJWTProcessor;
|
||||
import com.nimbusds.jwt.proc.DefaultJWTProcessor;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.core.annotation.Order;
|
||||
@@ -26,20 +15,17 @@ import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.URL;
|
||||
import java.util.Collections;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
@Order(Ordered.HIGHEST_PRECEDENCE + 99)
|
||||
@AllArgsConstructor
|
||||
@RequiredArgsConstructor
|
||||
public class WebSocketAuthInterceptor implements ChannelInterceptor {
|
||||
|
||||
private final JwtUtils jwtUtils;
|
||||
private final AppSettingService appSettingService;
|
||||
private final OidcTokenValidator oidcTokenValidator;
|
||||
|
||||
@Override
|
||||
public Message<?> preSend(Message<?> message, MessageChannel channel) {
|
||||
@@ -53,7 +39,7 @@ public class WebSocketAuthInterceptor implements ChannelInterceptor {
|
||||
throw new IllegalArgumentException("Missing Authorization header");
|
||||
}
|
||||
|
||||
String token = authHeaders.get(0).replace("Bearer ", "");
|
||||
String token = authHeaders.getFirst().replace("Bearer ", "");
|
||||
Authentication auth = authenticateToken(token);
|
||||
|
||||
if (auth == null) {
|
||||
@@ -71,41 +57,13 @@ public class WebSocketAuthInterceptor implements ChannelInterceptor {
|
||||
private Authentication authenticateToken(String token) {
|
||||
if (jwtUtils.validateToken(token)) {
|
||||
String username = jwtUtils.extractUsername(token);
|
||||
List<SimpleGrantedAuthority> authorities = Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"));
|
||||
return new UsernamePasswordAuthenticationToken(username, null, authorities);
|
||||
return new UsernamePasswordAuthenticationToken(
|
||||
username,
|
||||
null,
|
||||
Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"))
|
||||
);
|
||||
}
|
||||
|
||||
if (appSettingService.getAppSettings().isOidcEnabled()) {
|
||||
try {
|
||||
var providerDetails = appSettingService.getAppSettings().getOidcProviderDetails();
|
||||
String jwksUrl = providerDetails.getJwksUrl();
|
||||
if (jwksUrl == null || jwksUrl.isEmpty()) {
|
||||
log.error("JWKS URL is not configured");
|
||||
return null;
|
||||
}
|
||||
|
||||
URL jwksURL = new URI(jwksUrl).toURL();
|
||||
DefaultResourceRetriever resourceRetriever = new DefaultResourceRetriever(2000, 2000);
|
||||
JWKSource<SecurityContext> jwkSource = new RemoteJWKSet<>(jwksURL, resourceRetriever);
|
||||
ConfigurableJWTProcessor<SecurityContext> jwtProcessor = new DefaultJWTProcessor<>();
|
||||
JWSKeySelector<SecurityContext> keySelector = new JWSVerificationKeySelector<>(JWSAlgorithm.RS256, jwkSource);
|
||||
jwtProcessor.setJWSKeySelector(keySelector);
|
||||
|
||||
JWTClaimsSet claimsSet = jwtProcessor.process(token, null);
|
||||
Date expirationTime = claimsSet.getExpirationTime();
|
||||
if (expirationTime == null || expirationTime.before(new Date())) {
|
||||
log.warn("OIDC token is expired or missing exp claim");
|
||||
return null;
|
||||
}
|
||||
return new UsernamePasswordAuthenticationToken("oidc-user", null, Collections.emptyList());
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("OIDC token validation failed", e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// If not OIDC-enabled, return null (or could throw an error depending on the requirement)
|
||||
return null;
|
||||
return oidcTokenValidator.validate(token);
|
||||
}
|
||||
}
|
||||
+11
-11
@@ -6,7 +6,7 @@ import com.adityachandel.booklore.model.dto.BookViewerSettings;
|
||||
import com.adityachandel.booklore.model.dto.request.ReadProgressRequest;
|
||||
import com.adityachandel.booklore.model.dto.request.ShelvesAssignmentRequest;
|
||||
import com.adityachandel.booklore.service.recommender.BookRecommendationService;
|
||||
import com.adityachandel.booklore.service.BooksService;
|
||||
import com.adityachandel.booklore.service.BookService;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.Max;
|
||||
import jakarta.validation.constraints.Min;
|
||||
@@ -24,53 +24,53 @@ import java.util.List;
|
||||
@AllArgsConstructor
|
||||
public class BookController {
|
||||
|
||||
private final BooksService booksService;
|
||||
private final BookService bookService;
|
||||
private final BookRecommendationService bookRecommendationService;
|
||||
|
||||
@GetMapping
|
||||
public ResponseEntity<List<Book>> getBooks(@RequestParam(required = false, defaultValue = "false") boolean withDescription) {
|
||||
return ResponseEntity.ok(booksService.getBooks(withDescription));
|
||||
return ResponseEntity.ok(bookService.getBookDTOs(withDescription));
|
||||
}
|
||||
|
||||
@GetMapping("/{bookId}")
|
||||
public ResponseEntity<Book> getBook(@PathVariable long bookId, @RequestParam(required = false, defaultValue = "false") boolean withDescription) {
|
||||
return ResponseEntity.ok(booksService.getBook(bookId, withDescription));
|
||||
return ResponseEntity.ok(bookService.getBook(bookId, withDescription));
|
||||
}
|
||||
|
||||
@GetMapping("/{bookId}/cover")
|
||||
public ResponseEntity<Resource> getBookCover(@PathVariable long bookId) {
|
||||
return ResponseEntity.ok(booksService.getBookCover(bookId));
|
||||
return ResponseEntity.ok(bookService.getBookCover(bookId));
|
||||
}
|
||||
|
||||
@GetMapping("/{bookId}/content")
|
||||
public ResponseEntity<ByteArrayResource> getBookContent(@PathVariable long bookId) throws IOException {
|
||||
return booksService.getBookContent(bookId);
|
||||
return bookService.getBookContent(bookId);
|
||||
}
|
||||
|
||||
@GetMapping("/{bookId}/download")
|
||||
public ResponseEntity<Resource> downloadBook(@PathVariable("bookId") Long bookId) {
|
||||
return booksService.downloadBook(bookId);
|
||||
return bookService.downloadBook(bookId);
|
||||
}
|
||||
|
||||
@GetMapping("/{bookId}/viewer-setting")
|
||||
public ResponseEntity<BookViewerSettings> getBookViewerSettings(@PathVariable long bookId) {
|
||||
return ResponseEntity.ok(booksService.getBookViewerSetting(bookId));
|
||||
return ResponseEntity.ok(bookService.getBookViewerSetting(bookId));
|
||||
}
|
||||
|
||||
@PutMapping("/{bookId}/viewer-setting")
|
||||
public ResponseEntity<Void> updateBookViewerSettings(@RequestBody BookViewerSettings bookViewerSettings, @PathVariable long bookId) {
|
||||
booksService.updateBookViewerSetting(bookId, bookViewerSettings);
|
||||
bookService.updateBookViewerSetting(bookId, bookViewerSettings);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
@PostMapping("/shelves")
|
||||
public ResponseEntity<List<Book>> addBookToShelf(@RequestBody @Valid ShelvesAssignmentRequest request) {
|
||||
return ResponseEntity.ok(booksService.assignShelvesToBooks(request.getBookIds(), request.getShelvesToAssign(), request.getShelvesToUnassign()));
|
||||
return ResponseEntity.ok(bookService.assignShelvesToBooks(request.getBookIds(), request.getShelvesToAssign(), request.getShelvesToUnassign()));
|
||||
}
|
||||
|
||||
@PostMapping("/progress")
|
||||
public ResponseEntity<Void> addBookToProgress(@RequestBody @Valid ReadProgressRequest request) {
|
||||
booksService.updateReadProgress(request);
|
||||
bookService.updateReadProgress(request);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
|
||||
+2
-11
@@ -55,15 +55,6 @@ public class MetadataController {
|
||||
return ResponseEntity.ok(updatedMetadata);
|
||||
}
|
||||
|
||||
@PutMapping("/{bookId}/metadata/toggle-field-lock")
|
||||
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<BookMetadata> updateFieldLockState(@RequestBody FieldLockRequest request) {
|
||||
long bookId = request.getBookId();
|
||||
String field = request.getField();
|
||||
boolean isLocked = request.getIsLocked();
|
||||
return ResponseEntity.ok(bookMetadataService.updateFieldLockState(bookId, field, isLocked));
|
||||
}
|
||||
|
||||
@PutMapping("/metadata/toggle-all-lock")
|
||||
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<List<BookMetadata>> toggleAllMetadata(@RequestBody ToggleAllLockRequest request) {
|
||||
@@ -73,8 +64,8 @@ public class MetadataController {
|
||||
@PutMapping("/metadata/toggle-field-locks")
|
||||
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<List<BookMetadata>> toggleFieldLocks(@RequestBody ToggleFieldLocksRequest request) {
|
||||
List<BookMetadata> updated = bookMetadataService.toggleFieldLocks(request.getBookIds(), request.getFieldActions());
|
||||
return ResponseEntity.ok(updated);
|
||||
bookMetadataService.toggleFieldLocks(request.getBookIds(), request.getFieldActions());
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
|
||||
@PostMapping("/regenerate-covers")
|
||||
|
||||
+4
-4
@@ -1,6 +1,6 @@
|
||||
package com.adityachandel.booklore.controller;
|
||||
|
||||
import com.adityachandel.booklore.service.BooksService;
|
||||
import com.adityachandel.booklore.service.BookService;
|
||||
import com.adityachandel.booklore.service.opds.OpdsService;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -19,7 +19,7 @@ import org.springframework.web.bind.annotation.RestController;
|
||||
public class OpdsController {
|
||||
|
||||
private final OpdsService opdsService;
|
||||
private final BooksService booksService;
|
||||
private final BookService bookService;
|
||||
|
||||
@GetMapping(value = "/catalog", produces = "application/atom+xml;profile=opds-catalog")
|
||||
public ResponseEntity<String> getCatalogFeed(HttpServletRequest request) {
|
||||
@@ -31,12 +31,12 @@ public class OpdsController {
|
||||
|
||||
@GetMapping("/{bookId}/download")
|
||||
public ResponseEntity<Resource> downloadBook(@PathVariable("bookId") Long bookId) {
|
||||
return booksService.downloadBook(bookId);
|
||||
return bookService.downloadBook(bookId);
|
||||
}
|
||||
|
||||
@GetMapping("/{bookId}/cover.jpg")
|
||||
public ResponseEntity<Resource> getBookCover(@PathVariable long bookId) {
|
||||
Resource coverImage = booksService.getBookCover(bookId);
|
||||
Resource coverImage = bookService.getBookCover(bookId);
|
||||
String contentType = "image/jpeg";
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.parseMediaType(contentType))
|
||||
|
||||
@@ -3,7 +3,6 @@ package com.adityachandel.booklore.controller;
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.dto.Shelf;
|
||||
import com.adityachandel.booklore.model.dto.request.ShelfCreateRequest;
|
||||
import com.adityachandel.booklore.model.dto.Sort;
|
||||
import com.adityachandel.booklore.service.ShelfService;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.AllArgsConstructor;
|
||||
|
||||
+6
-5
@@ -9,9 +9,10 @@ import jakarta.persistence.AttributeConverter;
|
||||
import jakarta.persistence.Converter;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
@Converter
|
||||
public class BookRecommendationIdsListConverter implements AttributeConverter<List<BookRecommendationLite>, String> {
|
||||
public class BookRecommendationIdsListConverter implements AttributeConverter<Set<BookRecommendationLite>, String> {
|
||||
|
||||
private static final ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
@@ -20,7 +21,7 @@ public class BookRecommendationIdsListConverter implements AttributeConverter<Li
|
||||
}
|
||||
|
||||
@Override
|
||||
public String convertToDatabaseColumn(List<BookRecommendationLite> recommendations) {
|
||||
public String convertToDatabaseColumn(Set<BookRecommendationLite> recommendations) {
|
||||
try {
|
||||
return objectMapper.writeValueAsString(recommendations);
|
||||
} catch (JsonProcessingException e) {
|
||||
@@ -29,12 +30,12 @@ public class BookRecommendationIdsListConverter implements AttributeConverter<Li
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<BookRecommendationLite> convertToEntityAttribute(String json) {
|
||||
public Set<BookRecommendationLite> convertToEntityAttribute(String json) {
|
||||
if (json == null || json.trim().isEmpty()) {
|
||||
return List.of();
|
||||
return Set.of();
|
||||
}
|
||||
try {
|
||||
return objectMapper.readValue(json, new TypeReference<List<BookRecommendationLite>>() {
|
||||
return objectMapper.readValue(json, new TypeReference<Set<BookRecommendationLite>>() {
|
||||
});
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Error converting JSON to BookRecommendation list", e);
|
||||
|
||||
@@ -8,7 +8,7 @@ import org.mapstruct.Context;
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.Mapping;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Mapper(componentModel = "spring", uses = {BookMetadataMapper.class, ShelfMapper.class})
|
||||
@@ -29,21 +29,21 @@ public interface BookMapper {
|
||||
@Mapping(target = "shelves", ignore = true)
|
||||
Book toBookWithoutMetadataAndShelves(BookEntity bookEntity);
|
||||
|
||||
default List<String> mapAuthors(List<AuthorEntity> authors) {
|
||||
default Set<String> mapAuthors(Set<AuthorEntity> authors) {
|
||||
if (authors == null) {
|
||||
return null;
|
||||
}
|
||||
return authors.stream()
|
||||
.map(AuthorEntity::getName)
|
||||
.collect(Collectors.toList());
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
default List<String> mapCategories(List<CategoryEntity> categories) {
|
||||
default Set<String> mapCategories(Set<CategoryEntity> categories) {
|
||||
if (categories == null) {
|
||||
return null;
|
||||
}
|
||||
return categories.stream()
|
||||
.map(CategoryEntity::getName)
|
||||
.collect(Collectors.toList());
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.adityachandel.booklore.mapperv2;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||
import com.adityachandel.booklore.model.entity.AuthorEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
|
||||
import com.adityachandel.booklore.model.entity.CategoryEntity;
|
||||
import org.mapstruct.*;
|
||||
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Mapper(componentModel = "spring")
|
||||
public interface BookMapperV2 {
|
||||
|
||||
@Mapping(source = "library.id", target = "libraryId")
|
||||
@Mapping(target = "metadata", qualifiedByName = "mapMetadata")
|
||||
Book toDTO(BookEntity bookEntity);
|
||||
|
||||
@Named("mapMetadata")
|
||||
@Mapping(target = "authors", source = "authors", qualifiedByName = "mapAuthors")
|
||||
@Mapping(target = "categories", source = "categories", qualifiedByName = "mapCategories")
|
||||
BookMetadata mapMetadata(BookMetadataEntity metadataEntity);
|
||||
|
||||
@Named("mapAuthors")
|
||||
default Set<String> mapAuthors(Set<AuthorEntity> authors) {
|
||||
return authors == null ? Set.of() :
|
||||
authors.stream().map(AuthorEntity::getName).collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
@Named("mapCategories")
|
||||
default Set<String> mapCategories(Set<CategoryEntity> categories) {
|
||||
return categories == null ? Set.of() :
|
||||
categories.stream().map(CategoryEntity::getName).collect(Collectors.toSet());
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@ import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
@Builder
|
||||
@Data
|
||||
@@ -25,5 +25,5 @@ public class Book {
|
||||
private PdfProgress pdfProgress;
|
||||
private EpubProgress epubProgress;
|
||||
private CbxProgress cbxProgress;
|
||||
private List<Shelf> shelves;
|
||||
private Set<Shelf> shelves;
|
||||
}
|
||||
|
||||
@@ -60,6 +60,7 @@ public class BookLoreUser {
|
||||
private String sortDir;
|
||||
private String view;
|
||||
private Float coverSize;
|
||||
private Boolean seriesCollapsed;
|
||||
}
|
||||
|
||||
@Data
|
||||
@@ -80,6 +81,7 @@ public class BookLoreUser {
|
||||
private String sortKey;
|
||||
private String sortDir;
|
||||
private String view;
|
||||
private Boolean seriesCollapse;
|
||||
}
|
||||
|
||||
@Data
|
||||
|
||||
@@ -7,6 +7,7 @@ import lombok.*;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@@ -45,8 +46,8 @@ public class BookMetadata {
|
||||
private String googleId;
|
||||
|
||||
private Instant coverUpdatedOn;
|
||||
private List<String> authors;
|
||||
private List<String> categories;
|
||||
private Set<String> authors;
|
||||
private Set<String> categories;
|
||||
|
||||
private MetadataProvider provider;
|
||||
private String thumbnailUrl;
|
||||
@@ -68,8 +69,6 @@ public class BookMetadata {
|
||||
private Boolean googleIdLocked;
|
||||
private Boolean pageCountLocked;
|
||||
private Boolean languageLocked;
|
||||
private Boolean ratingLocked;
|
||||
private Boolean reviewCountLocked;
|
||||
private Boolean amazonRatingLocked;
|
||||
private Boolean amazonReviewCountLocked;
|
||||
private Boolean goodreadsRatingLocked;
|
||||
|
||||
+3
-2
@@ -3,6 +3,7 @@ package com.adityachandel.booklore.model.dto.response;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import lombok.Data;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
@Data
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
@@ -18,7 +19,7 @@ public class GoogleBooksApiResponse {
|
||||
public static class VolumeInfo {
|
||||
private String title;
|
||||
private String subtitle;
|
||||
private List<String> authors;
|
||||
private Set<String> authors;
|
||||
private String publisher;
|
||||
private String publishedDate;
|
||||
private String description;
|
||||
@@ -26,7 +27,7 @@ public class GoogleBooksApiResponse {
|
||||
private Integer pageCount;
|
||||
private ImageLinks imageLinks;
|
||||
private String language;
|
||||
private List<String> categories;
|
||||
private Set<String> categories;
|
||||
}
|
||||
|
||||
@Data
|
||||
|
||||
@@ -10,6 +10,7 @@ import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
@Entity
|
||||
@Getter
|
||||
@@ -56,11 +57,11 @@ public class BookEntity {
|
||||
joinColumns = @JoinColumn(name = "book_id"),
|
||||
inverseJoinColumns = @JoinColumn(name = "shelf_id")
|
||||
)
|
||||
private List<ShelfEntity> shelves;
|
||||
private Set<ShelfEntity> shelves;
|
||||
|
||||
@Convert(converter = BookRecommendationIdsListConverter.class)
|
||||
@Column(name = "similar_books_json", columnDefinition = "TEXT")
|
||||
private List<BookRecommendationLite> similarBooksJson;
|
||||
private Set<BookRecommendationLite> similarBooksJson;
|
||||
|
||||
public Path getFullFilePath() {
|
||||
if (libraryPath == null || libraryPath.getPath() == null || fileSubPath == null || fileName == null) {
|
||||
|
||||
+7
-10
@@ -3,10 +3,13 @@ package com.adityachandel.booklore.model.entity;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
import org.hibernate.annotations.Fetch;
|
||||
import org.hibernate.annotations.FetchMode;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
@Entity
|
||||
@Getter
|
||||
@@ -134,12 +137,6 @@ public class BookMetadataEntity {
|
||||
@Column(name = "language_locked")
|
||||
private Boolean languageLocked = Boolean.FALSE;
|
||||
|
||||
@Column(name = "rating_locked")
|
||||
private Boolean ratingLocked = Boolean.FALSE;
|
||||
|
||||
@Column(name = "review_count_locked")
|
||||
private Boolean reviewCountLocked = Boolean.FALSE;
|
||||
|
||||
@Column(name = "amazon_rating_locked")
|
||||
private Boolean amazonRatingLocked = Boolean.FALSE;
|
||||
|
||||
@@ -196,7 +193,8 @@ public class BookMetadataEntity {
|
||||
name = "book_metadata_author_mapping",
|
||||
joinColumns = @JoinColumn(name = "book_id"),
|
||||
inverseJoinColumns = @JoinColumn(name = "author_id"))
|
||||
private List<AuthorEntity> authors;
|
||||
@Fetch(FetchMode.SUBSELECT)
|
||||
private Set<AuthorEntity> authors;
|
||||
|
||||
@ManyToMany(fetch = FetchType.LAZY)
|
||||
@JoinTable(
|
||||
@@ -204,7 +202,8 @@ public class BookMetadataEntity {
|
||||
joinColumns = @JoinColumn(name = "book_id"),
|
||||
inverseJoinColumns = @JoinColumn(name = "category_id")
|
||||
)
|
||||
private List<CategoryEntity> categories;
|
||||
@Fetch(FetchMode.SUBSELECT)
|
||||
private Set<CategoryEntity> categories;
|
||||
|
||||
public void applyLockToAllFields(boolean lock) {
|
||||
this.titleLocked = lock;
|
||||
@@ -218,8 +217,6 @@ public class BookMetadataEntity {
|
||||
this.pageCountLocked = lock;
|
||||
this.thumbnailLocked = lock;
|
||||
this.languageLocked = lock;
|
||||
this.ratingLocked = lock;
|
||||
this.reviewCountLocked = lock;
|
||||
this.coverLocked = lock;
|
||||
this.seriesNameLocked = lock;
|
||||
this.seriesNumberLocked = lock;
|
||||
|
||||
-1
@@ -1,6 +1,5 @@
|
||||
package com.adityachandel.booklore.model.websocket;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
+12
@@ -1,6 +1,7 @@
|
||||
package com.adityachandel.booklore.repository;
|
||||
|
||||
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
|
||||
import org.springframework.data.jpa.repository.EntityGraph;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
@@ -10,6 +11,17 @@ import java.util.Set;
|
||||
|
||||
public interface BookMetadataRepository extends JpaRepository<BookMetadataEntity, Long> {
|
||||
|
||||
|
||||
@Query("SELECT m FROM BookMetadataEntity m WHERE m.bookId IN :bookIds")
|
||||
List<BookMetadataEntity> findAllByBookIds(@Param("bookIds") Set<Long> bookIds);
|
||||
|
||||
@Query("SELECT m FROM BookMetadataEntity m WHERE m.bookId IN :bookIds")
|
||||
List<BookMetadataEntity> getMetadataForBookIds(@Param("bookIds") Set<Long> bookIds);
|
||||
|
||||
@Query("SELECT m FROM BookMetadataEntity m WHERE m.bookId IN :bookIds")
|
||||
List<BookMetadataEntity> getMetadataForBookIds(@Param("bookIds") List<Long> bookIds);
|
||||
|
||||
|
||||
@EntityGraph(attributePaths = {"authors", "categories"})
|
||||
List<BookMetadataEntity> findAllByBookIdIn(Set<Long> bookIds);
|
||||
}
|
||||
|
||||
+28
-17
@@ -1,10 +1,7 @@
|
||||
package com.adityachandel.booklore.repository;
|
||||
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
|
||||
import org.springframework.data.jpa.repository.Modifying;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.jpa.repository.*;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@@ -16,16 +13,6 @@ import java.util.Set;
|
||||
@Repository
|
||||
public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpecificationExecutor<BookEntity> {
|
||||
|
||||
@Query("SELECT b FROM BookEntity b")
|
||||
List<BookEntity> getAllBooks();
|
||||
|
||||
@Query("SELECT b FROM BookEntity b WHERE b.library.id IN :libraryIds")
|
||||
List<BookEntity> getAllByLibraryIds(@Param("libraryIds") Set<Long> libraryIds);
|
||||
|
||||
List<BookEntity> findAllByIdIn(Collection<Long> ids);
|
||||
|
||||
List<BookEntity> findBooksByLibraryId(Long libraryId);
|
||||
|
||||
@Query("SELECT b.id FROM BookEntity b WHERE b.libraryPath.id IN :libraryPathIds")
|
||||
List<Long> findAllBookIdsByLibraryPathIdIn(@Param("libraryPathIds") Collection<Long> libraryPathIds);
|
||||
|
||||
@@ -33,13 +20,37 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpec
|
||||
|
||||
Optional<BookEntity> findBookByFileNameAndLibraryId(String fileName, long libraryId);
|
||||
|
||||
@Query("SELECT b FROM BookEntity b JOIN b.shelves s WHERE s.id = :shelfId")
|
||||
List<BookEntity> findByShelfId(@Param("shelfId") Long shelfId);
|
||||
@EntityGraph(attributePaths = {"metadata", "shelves"})
|
||||
@Query("SELECT DISTINCT b FROM BookEntity b JOIN b.shelves s WHERE s.id = :shelfId")
|
||||
List<BookEntity> findAllWithMetadataByShelfId(@Param("shelfId") Long shelfId);
|
||||
|
||||
@Modifying
|
||||
@Query("DELETE FROM BookEntity b WHERE b.id IN (:ids)")
|
||||
void deleteByIdIn(Collection<Long> ids);
|
||||
|
||||
List<BookEntity> findByFileSizeKbIsNull();
|
||||
@EntityGraph(attributePaths = {"metadata", "shelves"})
|
||||
@Query("SELECT b FROM BookEntity b WHERE b.fileSizeKb IS NULL")
|
||||
List<BookEntity> findAllWithMetadataByFileSizeKbIsNull();
|
||||
|
||||
@EntityGraph(attributePaths = {"metadata", "shelves"})
|
||||
@Query("SELECT b FROM BookEntity b")
|
||||
List<BookEntity> findAllWithMetadata();
|
||||
|
||||
@EntityGraph(attributePaths = {"metadata", "shelves"})
|
||||
@Query("SELECT b FROM BookEntity b WHERE b.id IN :bookIds")
|
||||
List<BookEntity> findAllWithMetadataByIds(@Param("bookIds") Set<Long> bookIds);
|
||||
|
||||
@EntityGraph(attributePaths = {"metadata", "shelves"})
|
||||
@Query("SELECT b FROM BookEntity b WHERE b.library.id = :libraryId")
|
||||
List<BookEntity> findAllWithMetadataByLibraryId(@Param("libraryId") Long libraryId);
|
||||
|
||||
@Query("""
|
||||
SELECT DISTINCT b FROM BookEntity b
|
||||
LEFT JOIN FETCH b.metadata m
|
||||
LEFT JOIN FETCH m.authors
|
||||
LEFT JOIN FETCH m.categories
|
||||
LEFT JOIN FETCH b.shelves
|
||||
""")
|
||||
List<BookEntity> findAllFullBooks();
|
||||
}
|
||||
|
||||
|
||||
+18
-46
@@ -12,10 +12,7 @@ import org.springframework.stereotype.Service;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.*;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@@ -29,6 +26,7 @@ public class BookCreatorService {
|
||||
|
||||
public BookEntity createShellBook(LibraryFile libraryFile, BookFileType bookFileType) {
|
||||
long fileSizeKb = FileUtils.getFileSizeInKb(libraryFile.getFullPath());
|
||||
BookMetadataEntity metadata = BookMetadataEntity.builder().build();
|
||||
BookEntity bookEntity = BookEntity.builder()
|
||||
.library(libraryFile.getLibraryEntity())
|
||||
.libraryPath(libraryFile.getLibraryPathEntity())
|
||||
@@ -37,58 +35,32 @@ public class BookCreatorService {
|
||||
.bookType(bookFileType)
|
||||
.fileSizeKb(fileSizeKb)
|
||||
.addedOn(Instant.now())
|
||||
.metadata(metadata)
|
||||
.build();
|
||||
BookMetadataEntity bookMetadataEntity = BookMetadataEntity.builder().build();
|
||||
bookEntity.setMetadata(bookMetadataEntity);
|
||||
return bookRepository.saveAndFlush(bookEntity);
|
||||
}
|
||||
|
||||
public void addCategoriesToBook(List<String> categories, BookEntity bookEntity) {
|
||||
for (String category : categories) {
|
||||
// Truncate category name to fit in VARCHAR(255)
|
||||
String truncatedCategory = truncate(category, 255);
|
||||
Optional<CategoryEntity> catOpt = categoryRepository.findByName(truncatedCategory);
|
||||
CategoryEntity categoryEntity;
|
||||
if (catOpt.isPresent()) {
|
||||
categoryEntity = catOpt.get();
|
||||
} else {
|
||||
categoryEntity = CategoryEntity.builder()
|
||||
.name(truncatedCategory)
|
||||
.build();
|
||||
categoryEntity = categoryRepository.save(categoryEntity);
|
||||
}
|
||||
if (bookEntity.getMetadata().getCategories() == null) {
|
||||
bookEntity.getMetadata().setCategories(new ArrayList<>());
|
||||
}
|
||||
bookEntity.getMetadata().getCategories().add(categoryEntity);
|
||||
if (bookEntity.getMetadata().getCategories() == null) {
|
||||
bookEntity.getMetadata().setCategories(new HashSet<>());
|
||||
}
|
||||
categories.stream()
|
||||
.map(cat -> truncate(cat, 255))
|
||||
.map(truncated -> categoryRepository.findByName(truncated)
|
||||
.orElseGet(() -> categoryRepository.save(CategoryEntity.builder().name(truncated).build())))
|
||||
.forEach(catEntity -> bookEntity.getMetadata().getCategories().add(catEntity));
|
||||
}
|
||||
|
||||
public void addAuthorsToBook(Set<String> authors, BookEntity bookEntity) {
|
||||
for (String authorStr : authors) {
|
||||
Optional<AuthorEntity> authorOptional = authorRepository.findByName(authorStr);
|
||||
AuthorEntity authorEntity;
|
||||
if (authorOptional.isPresent()) {
|
||||
authorEntity = authorOptional.get();
|
||||
} else {
|
||||
authorEntity = AuthorEntity.builder()
|
||||
.name(authorStr)
|
||||
.build();
|
||||
authorEntity = authorRepository.save(authorEntity);
|
||||
}
|
||||
if (bookEntity.getMetadata().getAuthors() == null) {
|
||||
bookEntity.getMetadata().setAuthors(new ArrayList<>());
|
||||
}
|
||||
bookEntity.getMetadata().getAuthors().add(authorEntity);
|
||||
if (bookEntity.getMetadata().getAuthors() == null) {
|
||||
bookEntity.getMetadata().setAuthors(new HashSet<>());
|
||||
}
|
||||
authors.stream()
|
||||
.map(authorName -> authorRepository.findByName(authorName)
|
||||
.orElseGet(() -> authorRepository.save(AuthorEntity.builder().name(authorName).build())))
|
||||
.forEach(authorEntity -> bookEntity.getMetadata().getAuthors().add(authorEntity));
|
||||
}
|
||||
|
||||
/**
|
||||
* Truncates a string to the specified maximum length
|
||||
* @param input The input string
|
||||
* @param maxLength The maximum length
|
||||
* @return The truncated string, or null if input is null
|
||||
*/
|
||||
|
||||
private String truncate(String input, int maxLength) {
|
||||
if (input == null) return null;
|
||||
return input.length() <= maxLength ? input : input.substring(0, maxLength);
|
||||
@@ -101,4 +73,4 @@ public class BookCreatorService {
|
||||
bookRepository.save(bookEntity);
|
||||
bookMetadataRepository.save(bookEntity.getMetadata());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.mapperv2.BookMapperV2;
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@RequiredArgsConstructor
|
||||
@Service
|
||||
public class BookQueryService {
|
||||
|
||||
private final BookRepository bookRepository;
|
||||
private final BookMapperV2 bookMapperV2;
|
||||
|
||||
public List<Book> getAllBooks(boolean includeDescription) {
|
||||
List<BookEntity> books = bookRepository.findAllWithMetadata();
|
||||
return books.stream()
|
||||
.map(book -> {
|
||||
Book dto = bookMapperV2.toDTO(book);
|
||||
if (!includeDescription && dto.getMetadata() != null) {
|
||||
dto.getMetadata().setDescription(null);
|
||||
}
|
||||
return dto;
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public List<BookEntity> findAllWithMetadataByIds(Set<Long> bookIds) {
|
||||
return bookRepository.findAllWithMetadataByIds(bookIds);
|
||||
}
|
||||
|
||||
public List<BookEntity> getAllFullBookEntities() {
|
||||
return bookRepository.findAllFullBooks();
|
||||
}
|
||||
|
||||
public void saveAll(List<BookEntity> books) {
|
||||
bookRepository.saveAll(books);
|
||||
}
|
||||
}
|
||||
+36
-138
@@ -2,7 +2,7 @@ package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.config.security.AuthenticationService;
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.mapper.*;
|
||||
import com.adityachandel.booklore.mapper.BookMapper;
|
||||
import com.adityachandel.booklore.model.dto.*;
|
||||
import com.adityachandel.booklore.model.dto.request.ReadProgressRequest;
|
||||
import com.adityachandel.booklore.model.entity.*;
|
||||
@@ -35,10 +35,9 @@ import java.util.stream.Collectors;
|
||||
@Slf4j
|
||||
@AllArgsConstructor
|
||||
@Service
|
||||
public class BooksService {
|
||||
public class BookService {
|
||||
|
||||
private final BookRepository bookRepository;
|
||||
private final BookMetadataRepository bookMetadataRepository;
|
||||
private final PdfViewerPreferencesRepository pdfViewerPreferencesRepository;
|
||||
private final EpubViewerPreferencesRepository epubViewerPreferencesRepository;
|
||||
private final CbxViewerPreferencesRepository cbxViewerPreferencesRepository;
|
||||
@@ -49,15 +48,39 @@ public class BooksService {
|
||||
private final UserRepository userRepository;
|
||||
private final UserBookProgressRepository userBookProgressRepository;
|
||||
private final AuthenticationService authenticationService;
|
||||
private final AuthorRepository authorRepository;
|
||||
private final CategoryRepository categoryRepository;
|
||||
private final BookMetadataAuthorMappingRepository bookMetadataAuthorMappingRepository;
|
||||
private final BookMetadataCategoryMappingRepository bookMetadataCategoryMappingRepository;
|
||||
private final BookShelfMappingRepository bookShelfMappingRepository;
|
||||
private final BookMetadataMapper bookMetadataMapper;
|
||||
private final AuthorMapper authorMapper;
|
||||
private final CategoryMapper categoryMapper;
|
||||
private final ShelfMapper shelfMapper;
|
||||
private final BookQueryService bookQueryService;
|
||||
private final UserProgressService userProgressService;
|
||||
|
||||
public List<Book> getBookDTOs(boolean includeDescription) {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
List<Book> books = bookQueryService.getAllBooks(includeDescription);
|
||||
Map<Long, UserBookProgressEntity> progressMap = userProgressService.fetchUserProgress(user.getId(), books.stream().map(Book::getId).collect(Collectors.toSet()));
|
||||
books.forEach(book -> {
|
||||
UserBookProgressEntity progress = progressMap.get(book.getId());
|
||||
if (progress != null) {
|
||||
setBookProgress(book, progress);
|
||||
book.setLastReadTime(progress.getLastReadTime());
|
||||
}
|
||||
});
|
||||
return books;
|
||||
}
|
||||
|
||||
private void setBookProgress(Book book, UserBookProgressEntity progress) {
|
||||
switch (book.getBookType()) {
|
||||
case EPUB -> book.setEpubProgress(EpubProgress.builder()
|
||||
.cfi(progress.getEpubProgress())
|
||||
.percentage(progress.getEpubProgressPercent())
|
||||
.build());
|
||||
case PDF -> book.setPdfProgress(PdfProgress.builder()
|
||||
.page(progress.getPdfProgress())
|
||||
.percentage(progress.getPdfProgressPercent())
|
||||
.build());
|
||||
case CBX -> book.setCbxProgress(CbxProgress.builder()
|
||||
.page(progress.getCbxProgress())
|
||||
.percentage(progress.getCbxProgressPercent())
|
||||
.build());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public BookViewerSettings getBookViewerSetting(long bookId) {
|
||||
@@ -208,131 +231,6 @@ public class BooksService {
|
||||
return book;
|
||||
}
|
||||
|
||||
public List<Book> getBooks(boolean withDescription) {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
|
||||
Set<Long> bookIds;
|
||||
List<BookEntity> bookEntities = user.getPermissions().isAdmin()
|
||||
? bookRepository.getAllBooks()
|
||||
: bookRepository.getAllByLibraryIds(
|
||||
user.getAssignedLibraries().stream()
|
||||
.map(Library::getId)
|
||||
.collect(Collectors.toSet())
|
||||
);
|
||||
|
||||
List<Book> books = bookEntities.stream()
|
||||
.map(bookMapper::toBookWithoutMetadataAndShelves)
|
||||
.toList();
|
||||
|
||||
bookIds = bookEntities.stream()
|
||||
.map(BookEntity::getId)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
Map<Long, BookMetadata> metadataByBookId = fetchMetadata(bookIds, withDescription);
|
||||
Map<Long, List<String>> authorsByBookId = fetchAuthors(bookIds);
|
||||
Map<Long, List<String>> categoriesByBookId = fetchCategories(bookIds);
|
||||
Map<Long, List<Shelf>> shelvesByBookId = fetchShelves(bookIds);
|
||||
Map<Long, UserBookProgressEntity> progressByBookId = fetchUserProgress(user.getId(), bookIds);
|
||||
|
||||
for (Book book : books) {
|
||||
Long bookId = book.getId();
|
||||
|
||||
var metadata = metadataByBookId.get(bookId);
|
||||
if (metadata != null) {
|
||||
metadata.setAuthors(authorsByBookId.getOrDefault(bookId, List.of()));
|
||||
metadata.setCategories(categoriesByBookId.getOrDefault(bookId, List.of()));
|
||||
book.setMetadata(metadata);
|
||||
}
|
||||
|
||||
book.setShelves(shelvesByBookId.getOrDefault(bookId, List.of()));
|
||||
|
||||
var progress = progressByBookId.get(bookId);
|
||||
if (progress != null) {
|
||||
book.setLastReadTime(progress.getLastReadTime());
|
||||
setBookProgress(book, progress);
|
||||
}
|
||||
}
|
||||
|
||||
return books;
|
||||
}
|
||||
|
||||
private Map<Long, BookMetadata> fetchMetadata(Set<Long> bookIds, boolean withDescription) {
|
||||
var metadataList = bookMetadataRepository.getMetadataForBookIds(bookIds);
|
||||
return metadataList.stream()
|
||||
.map(m -> bookMetadataMapper.toBookMetadataWithoutRelations(m, withDescription))
|
||||
.collect(Collectors.toMap(BookMetadata::getBookId, m -> m));
|
||||
}
|
||||
|
||||
private Map<Long, List<String>> fetchAuthors(Set<Long> bookIds) {
|
||||
var mappings = bookMetadataAuthorMappingRepository.findAllByBookIdIn(bookIds);
|
||||
var authorIds = mappings.stream()
|
||||
.map(BookMetadataAuthorMapping::getAuthorId)
|
||||
.collect(Collectors.toSet());
|
||||
var authors = authorRepository.findAllByIdIn(authorIds);
|
||||
var authorNamesById = authors.stream()
|
||||
.collect(Collectors.toMap(AuthorEntity::getId, authorMapper::toAuthorEntityName));
|
||||
|
||||
return mappings.stream()
|
||||
.collect(Collectors.groupingBy(
|
||||
BookMetadataAuthorMapping::getBookId,
|
||||
Collectors.mapping(m -> authorNamesById.get(m.getAuthorId()), Collectors.toList())
|
||||
));
|
||||
}
|
||||
|
||||
private Map<Long, List<String>> fetchCategories(Set<Long> bookIds) {
|
||||
var mappings = bookMetadataCategoryMappingRepository.findAllByBookIdIn(bookIds);
|
||||
var categoryIds = mappings.stream()
|
||||
.map(BookMetadataCategoryMapping::getCategoryId)
|
||||
.collect(Collectors.toSet());
|
||||
var categories = categoryRepository.findAllByIdIn(categoryIds);
|
||||
var categoryNamesById = categories.stream()
|
||||
.collect(Collectors.toMap(CategoryEntity::getId, categoryMapper::toCategoryName));
|
||||
|
||||
return mappings.stream()
|
||||
.collect(Collectors.groupingBy(
|
||||
BookMetadataCategoryMapping::getBookId,
|
||||
Collectors.mapping(m -> categoryNamesById.get(m.getCategoryId()), Collectors.toList())
|
||||
));
|
||||
}
|
||||
|
||||
private Map<Long, List<Shelf>> fetchShelves(Set<Long> bookIds) {
|
||||
var shelfMappings = bookShelfMappingRepository.findAllByBookIdIn(bookIds);
|
||||
var shelfIds = shelfMappings.stream()
|
||||
.map(BookShelfMapping::getShelfId)
|
||||
.collect(Collectors.toSet());
|
||||
var shelves = shelfRepository.findAllByIdIn(shelfIds);
|
||||
var shelfById = shelves.stream()
|
||||
.collect(Collectors.toMap(ShelfEntity::getId, shelfMapper::toShelf));
|
||||
|
||||
return shelfMappings.stream()
|
||||
.collect(Collectors.groupingBy(
|
||||
BookShelfMapping::getBookId,
|
||||
Collectors.mapping(m -> shelfById.get(m.getShelfId()), Collectors.toList())
|
||||
));
|
||||
}
|
||||
|
||||
private Map<Long, UserBookProgressEntity> fetchUserProgress(Long userId, Set<Long> bookIds) {
|
||||
return userBookProgressRepository.findByUserIdAndBookIdIn(userId, bookIds).stream()
|
||||
.collect(Collectors.toMap(p -> p.getBook().getId(), p -> p));
|
||||
}
|
||||
|
||||
private void setBookProgress(Book book, UserBookProgressEntity progress) {
|
||||
switch (book.getBookType()) {
|
||||
case EPUB -> book.setEpubProgress(EpubProgress.builder()
|
||||
.cfi(progress.getEpubProgress())
|
||||
.percentage(progress.getEpubProgressPercent())
|
||||
.build());
|
||||
case PDF -> book.setPdfProgress(PdfProgress.builder()
|
||||
.page(progress.getPdfProgress())
|
||||
.percentage(progress.getPdfProgressPercent())
|
||||
.build());
|
||||
case CBX -> book.setCbxProgress(CbxProgress.builder()
|
||||
.page(progress.getCbxProgress())
|
||||
.percentage(progress.getCbxProgressPercent())
|
||||
.build());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Transactional
|
||||
public List<Book> assignShelvesToBooks(Set<Long> bookIds, Set<Long> shelfIdsToAssign, Set<Long> shelfIdsToUnassign) {
|
||||
@@ -350,7 +248,7 @@ public class BooksService {
|
||||
throw ApiError.UNAUTHORIZED.createException("Cannot unassign shelves that do not belong to the user.");
|
||||
}
|
||||
|
||||
List<BookEntity> bookEntities = bookRepository.findAllById(bookIds);
|
||||
List<BookEntity> bookEntities = bookQueryService.findAllWithMetadataByIds(bookIds);
|
||||
List<ShelfEntity> shelvesToAssign = shelfRepository.findAllById(shelfIdsToAssign);
|
||||
for (BookEntity bookEntity : bookEntities) {
|
||||
bookEntity.getShelves().removeIf(shelf -> shelfIdsToUnassign.contains(shelf.getId()));
|
||||
@@ -8,7 +8,6 @@ import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||
import com.adityachandel.booklore.model.dto.Shelf;
|
||||
import com.adityachandel.booklore.model.dto.request.ShelfCreateRequest;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||
import com.adityachandel.booklore.model.entity.ShelfEntity;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
@@ -32,49 +31,60 @@ public class ShelfService {
|
||||
private final UserRepository userRepository;
|
||||
|
||||
public Shelf createShelf(ShelfCreateRequest request) {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
BookLoreUserEntity userEntity = userRepository.findById(user.getId()).orElseThrow(() -> new UsernameNotFoundException("User not found"));
|
||||
boolean exists = shelfRepository.existsByUserIdAndName(user.getId(), request.getName());
|
||||
if (exists) {
|
||||
Long userId = getAuthenticatedUserId();
|
||||
if (shelfRepository.existsByUserIdAndName(userId, request.getName())) {
|
||||
throw ApiError.SHELF_ALREADY_EXISTS.createException(request.getName());
|
||||
}
|
||||
ShelfEntity shelfEntity = ShelfEntity.builder()
|
||||
.icon(request.getIcon())
|
||||
.name(request.getName())
|
||||
.user(userEntity)
|
||||
.user(fetchUserEntityById(userId))
|
||||
.build();
|
||||
return shelfMapper.toShelf(shelfRepository.save(shelfEntity));
|
||||
}
|
||||
|
||||
public Shelf updateShelf(Long id, ShelfCreateRequest request) {
|
||||
ShelfEntity shelfEntity = shelfRepository.findById(id).orElseThrow(() -> ApiError.SHELF_NOT_FOUND.createException(id));
|
||||
ShelfEntity shelfEntity = findShelfByIdOrThrow(id);
|
||||
shelfEntity.setName(request.getName());
|
||||
shelfEntity.setIcon(request.getIcon());
|
||||
return shelfMapper.toShelf(shelfRepository.save(shelfEntity));
|
||||
}
|
||||
|
||||
public List<Shelf> getShelves() {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
return shelfRepository.findByUserId(user.getId()).stream()
|
||||
Long userId = getAuthenticatedUserId();
|
||||
return shelfRepository.findByUserId(userId).stream()
|
||||
.map(shelfMapper::toShelf)
|
||||
.toList();
|
||||
}
|
||||
|
||||
public Shelf getShelf(Long shelfId) {
|
||||
ShelfEntity shelfEntity = shelfRepository.findById(shelfId).orElseThrow(() -> ApiError.SHELF_NOT_FOUND.createException(shelfId));
|
||||
return shelfMapper.toShelf(shelfEntity);
|
||||
return shelfMapper.toShelf(findShelfByIdOrThrow(shelfId));
|
||||
}
|
||||
|
||||
public void deleteShelf(Long shelfId) {
|
||||
shelfRepository.findById(shelfId).orElseThrow(() -> ApiError.SHELF_NOT_FOUND.createException(shelfId));
|
||||
findShelfByIdOrThrow(shelfId);
|
||||
shelfRepository.deleteById(shelfId);
|
||||
}
|
||||
|
||||
public List<Book> getShelfBooks(Long shelfId) {
|
||||
shelfRepository.findById(shelfId).orElseThrow(() -> ApiError.SHELF_NOT_FOUND.createException(shelfId));
|
||||
List<BookEntity> bookEntities = bookRepository.findByShelfId(shelfId);
|
||||
return bookEntities.stream()
|
||||
findShelfByIdOrThrow(shelfId);
|
||||
return bookRepository.findAllWithMetadataByShelfId(shelfId).stream()
|
||||
.map(bookMapper::toBook)
|
||||
.toList();
|
||||
}
|
||||
|
||||
private Long getAuthenticatedUserId() {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
return user.getId();
|
||||
}
|
||||
|
||||
private BookLoreUserEntity fetchUserEntityById(Long userId) {
|
||||
return userRepository.findById(userId)
|
||||
.orElseThrow(() -> new UsernameNotFoundException("User not found with ID " + userId));
|
||||
}
|
||||
|
||||
private ShelfEntity findShelfByIdOrThrow(Long shelfId) {
|
||||
return shelfRepository.findById(shelfId)
|
||||
.orElseThrow(() -> ApiError.SHELF_NOT_FOUND.createException(shelfId));
|
||||
}
|
||||
}
|
||||
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.model.entity.UserBookProgressEntity;
|
||||
import com.adityachandel.booklore.repository.UserBookProgressRepository;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@RequiredArgsConstructor
|
||||
@Service
|
||||
public class UserProgressService {
|
||||
|
||||
private final UserBookProgressRepository userBookProgressRepository;
|
||||
|
||||
public Map<Long, UserBookProgressEntity> fetchUserProgress(Long userId, Set<Long> bookIds) {
|
||||
return userBookProgressRepository.findByUserIdAndBookIdIn(userId, bookIds).stream()
|
||||
.collect(Collectors.toMap(p -> p.getBook().getId(), p -> p));
|
||||
}
|
||||
}
|
||||
+4
-4
@@ -12,7 +12,7 @@ import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@@ -50,6 +50,7 @@ public class EmailProviderService {
|
||||
emailProviderRepository.save(emailProvider);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void deleteEmailProvider(Long id) {
|
||||
EmailProviderEntity emailProviderToDelete = emailProviderRepository.findById(id).orElseThrow(() -> ApiError.EMAIL_PROVIDER_NOT_FOUND.createException(id));
|
||||
boolean isDefaultProvider = emailProviderToDelete.isDefaultProvider();
|
||||
@@ -57,8 +58,7 @@ public class EmailProviderService {
|
||||
List<EmailProviderEntity> allProviders = emailProviderRepository.findAll();
|
||||
if (allProviders.size() > 1) {
|
||||
allProviders.remove(emailProviderToDelete);
|
||||
int randomIndex = (int) (Math.random() * allProviders.size());
|
||||
EmailProviderEntity newDefaultProvider = allProviders.get(randomIndex);
|
||||
EmailProviderEntity newDefaultProvider = allProviders.get(ThreadLocalRandom.current().nextInt(allProviders.size()));
|
||||
newDefaultProvider.setDefaultProvider(true);
|
||||
emailProviderRepository.save(newDefaultProvider);
|
||||
}
|
||||
@@ -67,6 +67,6 @@ public class EmailProviderService {
|
||||
}
|
||||
|
||||
public List<EmailProvider> getEmailProviders() {
|
||||
return emailProviderRepository.findAll().stream().map(emailProviderMapper::toDTO).collect(Collectors.toList());
|
||||
return emailProviderRepository.findAll().stream().map(emailProviderMapper::toDTO).toList();
|
||||
}
|
||||
}
|
||||
+6
-3
@@ -12,7 +12,7 @@ import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@@ -27,6 +27,7 @@ public class EmailRecipientService {
|
||||
return emailRecipientMapper.toDTO(emailRecipient);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public EmailRecipient createEmailRecipient(CreateEmailRecipientRequest request) {
|
||||
boolean isFirstRecipient = emailRecipientRepository.count() == 0;
|
||||
if (request.isDefaultRecipient() || isFirstRecipient) {
|
||||
@@ -38,6 +39,7 @@ public class EmailRecipientService {
|
||||
return emailRecipientMapper.toDTO(savedEntity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public EmailRecipient updateEmailRecipient(Long id, CreateEmailRecipientRequest request) {
|
||||
EmailRecipientEntity existingRecipient = emailRecipientRepository.findById(id).orElseThrow(() -> ApiError.EMAIL_RECIPIENT_NOT_FOUND.createException(id));
|
||||
if (request.isDefaultRecipient()) {
|
||||
@@ -56,6 +58,7 @@ public class EmailRecipientService {
|
||||
emailRecipientRepository.save(emailRecipient);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void deleteEmailRecipient(Long id) {
|
||||
EmailRecipientEntity emailRecipientToDelete = emailRecipientRepository.findById(id).orElseThrow(() -> ApiError.EMAIL_RECIPIENT_NOT_FOUND.createException(id));
|
||||
boolean isDefaultRecipient = emailRecipientToDelete.isDefaultRecipient();
|
||||
@@ -63,7 +66,7 @@ public class EmailRecipientService {
|
||||
List<EmailRecipientEntity> allRecipients = emailRecipientRepository.findAll();
|
||||
if (allRecipients.size() > 1) {
|
||||
allRecipients.remove(emailRecipientToDelete);
|
||||
int randomIndex = (int) (Math.random() * allRecipients.size());
|
||||
int randomIndex = ThreadLocalRandom.current().nextInt(allRecipients.size());
|
||||
EmailRecipientEntity newDefaultRecipient = allRecipients.get(randomIndex);
|
||||
newDefaultRecipient.setDefaultRecipient(true);
|
||||
emailRecipientRepository.save(newDefaultRecipient);
|
||||
@@ -75,6 +78,6 @@ public class EmailRecipientService {
|
||||
public List<EmailRecipient> getEmailRecipients() {
|
||||
return emailRecipientRepository.findAll().stream()
|
||||
.map(emailRecipientMapper::toDTO)
|
||||
.collect(Collectors.toList());
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
-1
@@ -26,7 +26,6 @@ import java.awt.image.BufferedImage;
|
||||
import java.io.*;
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
|
||||
+1
-1
@@ -22,6 +22,7 @@ import javax.xml.XMLConstants;
|
||||
import javax.xml.parsers.DocumentBuilder;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Propagation;
|
||||
@@ -31,7 +32,6 @@ import org.w3c.dom.Element;
|
||||
import org.w3c.dom.NodeList;
|
||||
|
||||
import com.adityachandel.booklore.mapper.BookMapper;
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
package com.adityachandel.booklore.service.fileprocessor;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
|
||||
|
||||
public interface FileProcessor {
|
||||
Book processFile(LibraryFile libraryFile, boolean forceProcess);
|
||||
|
||||
+1
-1
@@ -1,8 +1,8 @@
|
||||
package com.adityachandel.booklore.service.library;
|
||||
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
|
||||
|
||||
+4
-4
@@ -127,7 +127,7 @@ public class LibraryService {
|
||||
try {
|
||||
libraryProcessingService.processLibrary(libraryId);
|
||||
} catch (InvalidDataAccessApiUsageException e) {
|
||||
log.warn("InvalidDataAccessApiUsageException - Library id: {}", libraryId);
|
||||
log.debug("InvalidDataAccessApiUsageException - Library id: {}", libraryId);
|
||||
} catch (IOException e) {
|
||||
log.error("Error while parsing library books", e);
|
||||
}
|
||||
@@ -166,7 +166,7 @@ public class LibraryService {
|
||||
try {
|
||||
libraryProcessingService.processLibrary(libraryId);
|
||||
} catch (InvalidDataAccessApiUsageException e) {
|
||||
log.warn("InvalidDataAccessApiUsageException - Library id: {}", libraryId);
|
||||
log.debug("InvalidDataAccessApiUsageException - Library id: {}", libraryId);
|
||||
} catch (IOException e) {
|
||||
log.error("Error while parsing library books", e);
|
||||
}
|
||||
@@ -182,7 +182,7 @@ public class LibraryService {
|
||||
try {
|
||||
libraryProcessingService.rescanLibrary(libraryId);
|
||||
} catch (InvalidDataAccessApiUsageException e) {
|
||||
log.warn("InvalidDataAccessApiUsageException - Library id: {}", libraryId);
|
||||
log.debug("InvalidDataAccessApiUsageException - Library id: {}", libraryId);
|
||||
} catch (IOException e) {
|
||||
log.error("Error while parsing library books", e);
|
||||
}
|
||||
@@ -228,7 +228,7 @@ public class LibraryService {
|
||||
|
||||
public List<Book> getBooks(long libraryId) {
|
||||
libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
|
||||
List<BookEntity> bookEntities = bookRepository.findBooksByLibraryId(libraryId);
|
||||
List<BookEntity> bookEntities = bookRepository.findAllWithMetadataByLibraryId(libraryId);
|
||||
return bookEntities.stream().map(bookMapper::toBook).toList();
|
||||
}
|
||||
}
|
||||
+36
-105
@@ -25,6 +25,7 @@ import com.adityachandel.booklore.service.fileprocessor.CbxProcessor;
|
||||
import com.adityachandel.booklore.service.fileprocessor.EpubProcessor;
|
||||
import com.adityachandel.booklore.service.fileprocessor.PdfProcessor;
|
||||
import com.adityachandel.booklore.service.metadata.parser.BookParser;
|
||||
import com.adityachandel.booklore.service.BookQueryService;
|
||||
import com.adityachandel.booklore.util.FileService;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -59,6 +60,7 @@ public class BookMetadataService {
|
||||
private final PdfProcessor pdfProcessor;
|
||||
private final EpubProcessor epubProcessor;
|
||||
private final CbxProcessor cbxProcessor;
|
||||
private final BookQueryService bookQueryService;
|
||||
private final Map<MetadataProvider, BookParser> parserMap;
|
||||
|
||||
public List<BookMetadata> getProspectiveMetadataListForBookId(long bookId, FetchMetadataRequest request) {
|
||||
@@ -262,58 +264,58 @@ public class BookMetadataService {
|
||||
return value;
|
||||
}
|
||||
|
||||
List<String> getAllCategories(Map<MetadataProvider, BookMetadata> metadataMap, MetadataRefreshOptions.FieldProvider fieldProvider, FieldValueExtractorList fieldValueExtractor) {
|
||||
Set<String> getAllCategories(Map<MetadataProvider, BookMetadata> metadataMap, MetadataRefreshOptions.FieldProvider fieldProvider, FieldValueExtractorList fieldValueExtractor) {
|
||||
Set<String> uniqueCategories = new HashSet<>();
|
||||
if (fieldProvider.getP4() != null && metadataMap.containsKey(fieldProvider.getP4())) {
|
||||
List<String> extracted = fieldValueExtractor.extract(metadataMap.get(fieldProvider.getP4()));
|
||||
Set<String> extracted = fieldValueExtractor.extract(metadataMap.get(fieldProvider.getP4()));
|
||||
if (extracted != null) {
|
||||
uniqueCategories.addAll(extracted);
|
||||
}
|
||||
}
|
||||
if (fieldProvider.getP3() != null && metadataMap.containsKey(fieldProvider.getP3())) {
|
||||
List<String> extracted = fieldValueExtractor.extract(metadataMap.get(fieldProvider.getP3()));
|
||||
Set<String> extracted = fieldValueExtractor.extract(metadataMap.get(fieldProvider.getP3()));
|
||||
if (extracted != null) {
|
||||
uniqueCategories.addAll(extracted);
|
||||
}
|
||||
}
|
||||
if (fieldProvider.getP2() != null && metadataMap.containsKey(fieldProvider.getP2())) {
|
||||
List<String> extracted = fieldValueExtractor.extract(metadataMap.get(fieldProvider.getP2()));
|
||||
Set<String> extracted = fieldValueExtractor.extract(metadataMap.get(fieldProvider.getP2()));
|
||||
if (extracted != null) {
|
||||
uniqueCategories.addAll(extracted);
|
||||
}
|
||||
}
|
||||
if (fieldProvider.getP1() != null && metadataMap.containsKey(fieldProvider.getP1())) {
|
||||
List<String> extracted = fieldValueExtractor.extract(metadataMap.get(fieldProvider.getP1()));
|
||||
Set<String> extracted = fieldValueExtractor.extract(metadataMap.get(fieldProvider.getP1()));
|
||||
if (extracted != null) {
|
||||
uniqueCategories.addAll(extracted);
|
||||
}
|
||||
}
|
||||
return new ArrayList<>(uniqueCategories);
|
||||
return new HashSet<>(uniqueCategories);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
protected List<String> resolveFieldAsList(Map<MetadataProvider, BookMetadata> metadataMap, MetadataRefreshOptions.FieldProvider fieldProvider, FieldValueExtractorList fieldValueExtractor) {
|
||||
List<String> values = new ArrayList<>();
|
||||
protected Set<String> resolveFieldAsList(Map<MetadataProvider, BookMetadata> metadataMap, MetadataRefreshOptions.FieldProvider fieldProvider, FieldValueExtractorList fieldValueExtractor) {
|
||||
Set<String> values = new HashSet<>();
|
||||
if (fieldProvider.getP4() != null && metadataMap.containsKey(fieldProvider.getP4())) {
|
||||
List<String> newValues = fieldValueExtractor.extract(metadataMap.get(fieldProvider.getP4()));
|
||||
Set<String> newValues = fieldValueExtractor.extract(metadataMap.get(fieldProvider.getP4()));
|
||||
if (newValues != null && !newValues.isEmpty()) {
|
||||
values = newValues;
|
||||
}
|
||||
}
|
||||
if (fieldProvider.getP3() != null && metadataMap.containsKey(fieldProvider.getP3())) {
|
||||
List<String> newValues = fieldValueExtractor.extract(metadataMap.get(fieldProvider.getP3()));
|
||||
Set<String> newValues = fieldValueExtractor.extract(metadataMap.get(fieldProvider.getP3()));
|
||||
if (newValues != null && !newValues.isEmpty()) {
|
||||
values = newValues;
|
||||
}
|
||||
}
|
||||
if (values.isEmpty() && fieldProvider.getP2() != null && metadataMap.containsKey(fieldProvider.getP2())) {
|
||||
List<String> newValues = fieldValueExtractor.extract(metadataMap.get(fieldProvider.getP2()));
|
||||
Set<String> newValues = fieldValueExtractor.extract(metadataMap.get(fieldProvider.getP2()));
|
||||
if (newValues != null && !newValues.isEmpty()) {
|
||||
values = newValues;
|
||||
}
|
||||
}
|
||||
if (values.isEmpty() && fieldProvider.getP1() != null && metadataMap.containsKey(fieldProvider.getP1())) {
|
||||
List<String> newValues = fieldValueExtractor.extract(metadataMap.get(fieldProvider.getP1()));
|
||||
Set<String> newValues = fieldValueExtractor.extract(metadataMap.get(fieldProvider.getP1()));
|
||||
if (newValues != null && !newValues.isEmpty()) {
|
||||
values = newValues;
|
||||
}
|
||||
@@ -332,7 +334,7 @@ public class BookMetadataService {
|
||||
LibraryEntity libraryEntity = libraryRepository.findById(request.getLibraryId()).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(request.getLibraryId()));
|
||||
yield libraryEntity.getBookEntities();
|
||||
}
|
||||
case BOOKS -> bookRepository.findAllByIdIn(request.getBookIds());
|
||||
case BOOKS -> bookQueryService.findAllWithMetadataByIds(request.getBookIds());
|
||||
};
|
||||
books.sort(Comparator.comparing(BookEntity::getFileName, Comparator.nullsLast(String::compareTo)));
|
||||
return books;
|
||||
@@ -390,97 +392,37 @@ public class BookMetadataService {
|
||||
return parser;
|
||||
}
|
||||
|
||||
public BookMetadata updateFieldLockState(long bookId, String field, boolean isLocked) {
|
||||
BookMetadataEntity existingMetadata = bookMetadataRepository.findById(bookId).orElseThrow(() -> new RuntimeException("Book metadata not found"));
|
||||
switch (field) {
|
||||
case "title":
|
||||
existingMetadata.setTitleLocked(isLocked);
|
||||
break;
|
||||
case "subtitle":
|
||||
existingMetadata.setSubtitleLocked(isLocked);
|
||||
break;
|
||||
case "authors":
|
||||
existingMetadata.setAuthorsLocked(isLocked);
|
||||
break;
|
||||
case "categories":
|
||||
existingMetadata.setCategoriesLocked(isLocked);
|
||||
break;
|
||||
case "publisher":
|
||||
existingMetadata.setPublisherLocked(isLocked);
|
||||
break;
|
||||
case "publishedDate":
|
||||
existingMetadata.setPublishedDateLocked(isLocked);
|
||||
break;
|
||||
case "isbn10":
|
||||
existingMetadata.setIsbn10Locked(isLocked);
|
||||
break;
|
||||
case "isbn13":
|
||||
existingMetadata.setIsbn13Locked(isLocked);
|
||||
break;
|
||||
case "description":
|
||||
existingMetadata.setDescriptionLocked(isLocked);
|
||||
break;
|
||||
case "pageCount":
|
||||
existingMetadata.setPageCountLocked(isLocked);
|
||||
break;
|
||||
case "language":
|
||||
existingMetadata.setLanguageLocked(isLocked);
|
||||
break;
|
||||
case "asin":
|
||||
existingMetadata.setAsinLocked(isLocked);
|
||||
break;
|
||||
case "amazonRating":
|
||||
existingMetadata.setAmazonRatingLocked(isLocked);
|
||||
break;
|
||||
case "amazonReviewCount":
|
||||
existingMetadata.setAmazonReviewCountLocked(isLocked);
|
||||
break;
|
||||
case "goodreadsId":
|
||||
existingMetadata.setGoodreadsIdLocked(isLocked);
|
||||
break;
|
||||
case "goodreadsRating":
|
||||
existingMetadata.setGoodreadsRatingLocked(isLocked);
|
||||
break;
|
||||
case "goodreadsReviewCount":
|
||||
existingMetadata.setGoodreadsReviewCountLocked(isLocked);
|
||||
break;
|
||||
case "hardcoverId":
|
||||
existingMetadata.setHardcoverIdLocked(isLocked);
|
||||
break;
|
||||
case "hardcoverRating":
|
||||
existingMetadata.setHardcoverRatingLocked(isLocked);
|
||||
break;
|
||||
case "hardcoverReviewCount":
|
||||
existingMetadata.setHardcoverReviewCountLocked(isLocked);
|
||||
break;
|
||||
case "googleId":
|
||||
existingMetadata.setGoogleIdLocked(isLocked);
|
||||
break;
|
||||
default:
|
||||
throw new IllegalArgumentException("Invalid field name: " + field);
|
||||
}
|
||||
return bookMetadataMapper.toBookMetadata(bookMetadataRepository.save(existingMetadata), true);
|
||||
}
|
||||
public void toggleFieldLocks(List<Long> bookIds, Map<String, String> fieldActions) {
|
||||
List<BookMetadataEntity> metadataEntities = bookMetadataRepository
|
||||
.getMetadataForBookIds(bookIds)
|
||||
.stream()
|
||||
.distinct()
|
||||
.toList();
|
||||
|
||||
public List<BookMetadata> toggleFieldLocks(List<Long> bookIds, Map<String, String> fieldActions) {
|
||||
List<BookMetadataEntity> entitiesToUpdate = new ArrayList<>();
|
||||
for (Long bookId : bookIds) {
|
||||
BookMetadataEntity metadataEntity = bookMetadataRepository.findById(bookId).orElseThrow(() -> new IllegalArgumentException("Book metadata not found for bookId: " + bookId));
|
||||
for (BookMetadataEntity metadataEntity : metadataEntities) {
|
||||
fieldActions.forEach((field, action) -> {
|
||||
try {
|
||||
String setterName = "set" + Character.toUpperCase(field.charAt(0)) + field.substring(1);
|
||||
Method setter = BookMetadataEntity.class.getMethod(setterName, Boolean.class);
|
||||
setter.invoke(metadataEntity, "LOCK".equalsIgnoreCase(action));
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Failed to invoke setter for field: " + field + " on bookId: " + bookId, e);
|
||||
throw new RuntimeException("Failed to invoke setter for field: " + field + " on bookId: " + metadataEntity.getBookId(), e);
|
||||
}
|
||||
});
|
||||
entitiesToUpdate.add(metadataEntity);
|
||||
}
|
||||
List<BookMetadataEntity> savedEntities = bookMetadataRepository.saveAll(entitiesToUpdate);
|
||||
return savedEntities.stream()
|
||||
.map(entity -> bookMetadataMapper.toBookMetadata(entity, true))
|
||||
|
||||
bookMetadataRepository.saveAll(metadataEntities);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public List<BookMetadata> toggleAllLock(ToggleAllLockRequest request) {
|
||||
boolean lock = request.getLock() == Lock.LOCK;
|
||||
List<BookEntity> books = bookQueryService.findAllWithMetadataByIds(request.getBookIds())
|
||||
.stream()
|
||||
.peek(book -> book.getMetadata().applyLockToAllFields(lock))
|
||||
.toList();
|
||||
bookRepository.saveAll(books);
|
||||
return books.stream().map(b -> bookMetadataMapper.toBookMetadata(b.getMetadata(), false)).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public BookMetadata handleCoverUpload(Long bookId, MultipartFile file) {
|
||||
@@ -502,7 +444,7 @@ public class BookMetadataService {
|
||||
|
||||
public void regenerateCovers() {
|
||||
Thread.startVirtualThread(() -> {
|
||||
List<BookEntity> books = bookRepository.findAll().stream()
|
||||
List<BookEntity> books = bookQueryService.getAllFullBookEntities().stream()
|
||||
.filter(book -> book.getMetadata().getCoverLocked() == null || !book.getMetadata().getCoverLocked())
|
||||
.toList();
|
||||
int total = books.size();
|
||||
@@ -533,15 +475,4 @@ public class BookMetadataService {
|
||||
}
|
||||
log.info("{}Successfully regenerated cover for book ID {} ({})", progress, book.getId(), title);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public List<BookMetadata> toggleAllLock(ToggleAllLockRequest request) {
|
||||
boolean lock = request.getLock() == Lock.LOCK;
|
||||
List<BookEntity> books = bookRepository.findAllByIdIn(request.getBookIds())
|
||||
.stream()
|
||||
.peek(book -> book.getMetadata().applyLockToAllFields(lock))
|
||||
.toList();
|
||||
bookRepository.saveAll(books);
|
||||
return books.stream().map(b -> bookMetadataMapper.toBookMetadata(b.getMetadata(), false)).collect(Collectors.toList());
|
||||
}
|
||||
}
|
||||
+112
-178
@@ -7,16 +7,19 @@ import com.adityachandel.booklore.repository.*;
|
||||
import com.adityachandel.booklore.util.FileService;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Propagation;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.Objects;
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Slf4j
|
||||
@@ -42,107 +45,74 @@ public class BookMetadataUpdater {
|
||||
return metadata;
|
||||
}
|
||||
|
||||
if ((metadata.getGoodreadsIdLocked() == null || !metadata.getGoodreadsIdLocked()) && newMetadata.getGoodreadsId() != null) {
|
||||
metadata.setGoodreadsId(newMetadata.getGoodreadsId().isBlank() ? null : newMetadata.getGoodreadsId());
|
||||
}
|
||||
if ((metadata.getHardcoverIdLocked() == null || !metadata.getHardcoverIdLocked()) && newMetadata.getHardcoverId() != null) {
|
||||
metadata.setHardcoverId(newMetadata.getHardcoverId().isBlank() ? null : newMetadata.getHardcoverId());
|
||||
}
|
||||
if ((metadata.getGoogleIdLocked() == null || !metadata.getGoogleIdLocked()) && newMetadata.getGoogleId() != null) {
|
||||
metadata.setGoogleId(newMetadata.getGoogleId().isBlank() ? null : newMetadata.getGoogleId());
|
||||
}
|
||||
if ((metadata.getTitleLocked() == null || !metadata.getTitleLocked()) && newMetadata.getTitle() != null) {
|
||||
metadata.setTitle(newMetadata.getTitle().isEmpty() ? null : newMetadata.getTitle());
|
||||
}
|
||||
if ((metadata.getSubtitleLocked() == null || !metadata.getSubtitleLocked()) && newMetadata.getSubtitle() != null) {
|
||||
metadata.setSubtitle(newMetadata.getSubtitle().isBlank() ? null : newMetadata.getSubtitle());
|
||||
}
|
||||
if ((metadata.getPublisherLocked() == null || !metadata.getPublisherLocked()) && newMetadata.getPublisher() != null) {
|
||||
metadata.setPublisher(newMetadata.getPublisher().isBlank() ? null : newMetadata.getPublisher());
|
||||
}
|
||||
if ((metadata.getPublishedDateLocked() == null || !metadata.getPublishedDateLocked()) && newMetadata.getPublishedDate() != null) {
|
||||
metadata.setPublishedDate(newMetadata.getPublishedDate());
|
||||
}
|
||||
if ((metadata.getLanguageLocked() == null || !metadata.getLanguageLocked()) && newMetadata.getLanguage() != null) {
|
||||
metadata.setLanguage(newMetadata.getLanguage().isBlank() ? null : newMetadata.getLanguage());
|
||||
}
|
||||
if ((metadata.getIsbn10Locked() == null || !metadata.getIsbn10Locked()) && newMetadata.getIsbn10() != null) {
|
||||
metadata.setIsbn10(newMetadata.getIsbn10().isBlank() ? null : newMetadata.getIsbn10());
|
||||
}
|
||||
if ((metadata.getIsbn13Locked() == null || !metadata.getIsbn13Locked()) && newMetadata.getIsbn13() != null) {
|
||||
metadata.setIsbn13(newMetadata.getIsbn13().isBlank() ? null : newMetadata.getIsbn13());
|
||||
}
|
||||
if ((metadata.getAsinLocked() == null || !metadata.getAsinLocked()) && newMetadata.getAsin() != null) {
|
||||
metadata.setAsin(newMetadata.getAsin().isBlank() ? null : newMetadata.getAsin());
|
||||
}
|
||||
if ((metadata.getDescriptionLocked() == null || !metadata.getDescriptionLocked()) && newMetadata.getDescription() != null) {
|
||||
metadata.setDescription(newMetadata.getDescription().isBlank() ? null : newMetadata.getDescription());
|
||||
}
|
||||
if ((metadata.getPageCountLocked() == null || !metadata.getPageCountLocked()) && newMetadata.getPageCount() != null) {
|
||||
metadata.setPageCount(newMetadata.getPageCount());
|
||||
}
|
||||
if ((metadata.getAmazonRatingLocked() == null || !metadata.getAmazonRatingLocked()) && newMetadata.getAmazonRating() != null) {
|
||||
metadata.setAmazonRating(newMetadata.getAmazonRating());
|
||||
}
|
||||
if ((metadata.getAmazonReviewCountLocked() == null || !metadata.getAmazonReviewCountLocked()) && newMetadata.getAmazonReviewCount() != null) {
|
||||
metadata.setAmazonReviewCount(newMetadata.getAmazonReviewCount());
|
||||
}
|
||||
if ((metadata.getGoodreadsRatingLocked() == null || !metadata.getGoodreadsRatingLocked()) && newMetadata.getGoodreadsRating() != null) {
|
||||
metadata.setGoodreadsRating(newMetadata.getGoodreadsRating());
|
||||
}
|
||||
if ((metadata.getGoodreadsReviewCountLocked() == null || !metadata.getGoodreadsReviewCountLocked()) && newMetadata.getGoodreadsReviewCount() != null) {
|
||||
metadata.setGoodreadsReviewCount(newMetadata.getGoodreadsReviewCount());
|
||||
}
|
||||
if ((metadata.getHardcoverRatingLocked() == null || !metadata.getHardcoverRatingLocked()) && newMetadata.getHardcoverRating() != null) {
|
||||
metadata.setHardcoverRating(newMetadata.getHardcoverRating());
|
||||
}
|
||||
if ((metadata.getHardcoverReviewCountLocked() == null || !metadata.getHardcoverReviewCountLocked()) && newMetadata.getHardcoverReviewCount() != null) {
|
||||
metadata.setHardcoverReviewCount(newMetadata.getHardcoverReviewCount());
|
||||
}
|
||||
if ((metadata.getSeriesNameLocked() == null || !metadata.getSeriesNameLocked()) && newMetadata.getSeriesName() != null) {
|
||||
metadata.setSeriesName(newMetadata.getSeriesName());
|
||||
}
|
||||
if ((metadata.getSeriesNumberLocked() == null || !metadata.getSeriesNumberLocked()) && newMetadata.getSeriesNumber() != null) {
|
||||
metadata.setSeriesNumber(newMetadata.getSeriesNumber());
|
||||
}
|
||||
if ((metadata.getSeriesTotalLocked() == null || !metadata.getSeriesTotalLocked()) && newMetadata.getSeriesTotal() != null) {
|
||||
metadata.setSeriesTotal(newMetadata.getSeriesTotal());
|
||||
}
|
||||
updateBasicFields(newMetadata, metadata);
|
||||
updateAuthorsIfNeeded(newMetadata, metadata);
|
||||
updateCategoriesIfNeeded(newMetadata, metadata, mergeCategories);
|
||||
updateThumbnailIfNeeded(bookId, newMetadata, metadata, setThumbnail);
|
||||
|
||||
if ((metadata.getAuthorsLocked() == null || !metadata.getAuthorsLocked()) && newMetadata.getAuthors() != null && !newMetadata.getAuthors().isEmpty()) {
|
||||
metadata.setAuthors(newMetadata.getAuthors()
|
||||
.stream()
|
||||
.filter(a -> a != null && !a.isBlank())
|
||||
.map(authorName -> authorRepository.findByName(authorName)
|
||||
.orElseGet(() -> authorRepository.save(AuthorEntity.builder().name(authorName).build())))
|
||||
.collect(Collectors.toList()));
|
||||
}
|
||||
bookMetadataRepository.save(metadata);
|
||||
return metadata;
|
||||
}
|
||||
|
||||
if (mergeCategories) {
|
||||
if ((metadata.getCategoriesLocked() == null || !metadata.getCategoriesLocked()) && newMetadata.getCategories() != null) {
|
||||
private void updateBasicFields(BookMetadata newMetadata, BookMetadataEntity metadata) {
|
||||
updateFieldIfUnlocked(metadata::getGoodreadsIdLocked, newMetadata.getGoodreadsId(), v -> metadata.setGoodreadsId(nullIfBlank(v)));
|
||||
updateFieldIfUnlocked(metadata::getHardcoverIdLocked, newMetadata.getHardcoverId(), v -> metadata.setHardcoverId(nullIfBlank(v)));
|
||||
updateFieldIfUnlocked(metadata::getGoogleIdLocked, newMetadata.getGoogleId(), v -> metadata.setGoogleId(nullIfBlank(v)));
|
||||
updateFieldIfUnlocked(metadata::getTitleLocked, newMetadata.getTitle(), v -> metadata.setTitle(nullIfBlank(v)));
|
||||
updateFieldIfUnlocked(metadata::getSubtitleLocked, newMetadata.getSubtitle(), v -> metadata.setSubtitle(nullIfBlank(v)));
|
||||
updateFieldIfUnlocked(metadata::getPublisherLocked, newMetadata.getPublisher(), v -> metadata.setPublisher(nullIfBlank(v)));
|
||||
updateFieldIfUnlocked(metadata::getPublishedDateLocked, newMetadata.getPublishedDate(), metadata::setPublishedDate);
|
||||
updateFieldIfUnlocked(metadata::getLanguageLocked, newMetadata.getLanguage(), v -> metadata.setLanguage(nullIfBlank(v)));
|
||||
updateFieldIfUnlocked(metadata::getIsbn10Locked, newMetadata.getIsbn10(), v -> metadata.setIsbn10(nullIfBlank(v)));
|
||||
updateFieldIfUnlocked(metadata::getIsbn13Locked, newMetadata.getIsbn13(), v -> metadata.setIsbn13(nullIfBlank(v)));
|
||||
updateFieldIfUnlocked(metadata::getAsinLocked, newMetadata.getAsin(), v -> metadata.setAsin(nullIfBlank(v)));
|
||||
updateFieldIfUnlocked(metadata::getDescriptionLocked, newMetadata.getDescription(), v -> metadata.setDescription(nullIfBlank(v)));
|
||||
updateFieldIfUnlocked(metadata::getPageCountLocked, newMetadata.getPageCount(), metadata::setPageCount);
|
||||
updateFieldIfUnlocked(metadata::getAmazonRatingLocked, newMetadata.getAmazonRating(), metadata::setAmazonRating);
|
||||
updateFieldIfUnlocked(metadata::getAmazonReviewCountLocked, newMetadata.getAmazonReviewCount(), metadata::setAmazonReviewCount);
|
||||
updateFieldIfUnlocked(metadata::getGoodreadsRatingLocked, newMetadata.getGoodreadsRating(), metadata::setGoodreadsRating);
|
||||
updateFieldIfUnlocked(metadata::getGoodreadsReviewCountLocked, newMetadata.getGoodreadsReviewCount(), metadata::setGoodreadsReviewCount);
|
||||
updateFieldIfUnlocked(metadata::getHardcoverRatingLocked, newMetadata.getHardcoverRating(), metadata::setHardcoverRating);
|
||||
updateFieldIfUnlocked(metadata::getHardcoverReviewCountLocked, newMetadata.getHardcoverReviewCount(), metadata::setHardcoverReviewCount);
|
||||
updateFieldIfUnlocked(metadata::getSeriesNameLocked, newMetadata.getSeriesName(), metadata::setSeriesName);
|
||||
updateFieldIfUnlocked(metadata::getSeriesNumberLocked, newMetadata.getSeriesNumber(), metadata::setSeriesNumber);
|
||||
updateFieldIfUnlocked(metadata::getSeriesTotalLocked, newMetadata.getSeriesTotal(), metadata::setSeriesTotal);
|
||||
}
|
||||
|
||||
private void updateAuthorsIfNeeded(BookMetadata newMetadata, BookMetadataEntity metadata) {
|
||||
if (shouldUpdateField(metadata.getAuthorsLocked(), newMetadata.getAuthors()) && newMetadata.getAuthors() != null && !newMetadata.getAuthors().isEmpty()) {
|
||||
metadata.setAuthors(newMetadata.getAuthors().stream()
|
||||
.filter(a -> a != null && !a.isBlank())
|
||||
.map(authorName -> authorRepository.findByName(authorName)
|
||||
.orElseGet(() -> authorRepository.save(AuthorEntity.builder().name(authorName).build())))
|
||||
.collect(Collectors.toSet()));
|
||||
}
|
||||
}
|
||||
|
||||
private void updateCategoriesIfNeeded(BookMetadata newMetadata, BookMetadataEntity metadata, boolean mergeCategories) {
|
||||
if (shouldUpdateField(metadata.getCategoriesLocked(), newMetadata.getCategories()) && newMetadata.getCategories() != null) {
|
||||
if (mergeCategories) {
|
||||
HashSet<CategoryEntity> existingCategories = new HashSet<>(metadata.getCategories());
|
||||
newMetadata.getCategories()
|
||||
.stream()
|
||||
.filter(c -> c != null && !c.isBlank())
|
||||
.forEach(categoryName -> {
|
||||
CategoryEntity categoryEntity = categoryRepository.findByName(categoryName)
|
||||
.orElseGet(() -> categoryRepository.save(CategoryEntity.builder().name(categoryName).build()));
|
||||
existingCategories.add(categoryEntity);
|
||||
});
|
||||
metadata.setCategories(new ArrayList<>(existingCategories));
|
||||
}
|
||||
} else {
|
||||
if ((metadata.getCategoriesLocked() == null || !metadata.getCategoriesLocked()) && newMetadata.getCategories() != null && !newMetadata.getCategories().isEmpty()) {
|
||||
metadata.setCategories(newMetadata.getCategories()
|
||||
.stream()
|
||||
.filter(c -> c != null && !c.isBlank())
|
||||
.map(categoryName -> categoryRepository.findByName(categoryName)
|
||||
.orElseGet(() -> categoryRepository.save(CategoryEntity.builder().name(categoryName).build())))
|
||||
.collect(Collectors.toList()));
|
||||
newMetadata.getCategories().stream()
|
||||
.filter(c -> c != null && !c.isBlank())
|
||||
.forEach(categoryName -> {
|
||||
CategoryEntity categoryEntity = categoryRepository.findByName(categoryName)
|
||||
.orElseGet(() -> categoryRepository.save(CategoryEntity.builder().name(categoryName).build()));
|
||||
existingCategories.add(categoryEntity);
|
||||
});
|
||||
metadata.setCategories(new HashSet<>(existingCategories));
|
||||
} else if (!newMetadata.getCategories().isEmpty()) {
|
||||
metadata.setCategories(newMetadata.getCategories().stream()
|
||||
.filter(c -> c != null && !c.isBlank())
|
||||
.map(categoryName -> categoryRepository.findByName(categoryName)
|
||||
.orElseGet(() -> categoryRepository.save(CategoryEntity.builder().name(categoryName).build())))
|
||||
.collect(Collectors.toSet()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (setThumbnail && (metadata.getThumbnailLocked() == null || !metadata.getThumbnailLocked()) && newMetadata.getThumbnailUrl() != null && !newMetadata.getThumbnailUrl().isEmpty()) {
|
||||
private void updateThumbnailIfNeeded(long bookId, BookMetadata newMetadata, BookMetadataEntity metadata, boolean setThumbnail) {
|
||||
if (setThumbnail && shouldUpdateField(metadata.getThumbnailLocked(), newMetadata.getThumbnailUrl()) && !newMetadata.getThumbnailUrl().isEmpty()) {
|
||||
String thumbnailPath = null;
|
||||
try {
|
||||
thumbnailPath = fileService.createThumbnail(bookId, newMetadata.getThumbnailUrl());
|
||||
@@ -152,92 +122,56 @@ public class BookMetadataUpdater {
|
||||
}
|
||||
metadata.setThumbnail(thumbnailPath);
|
||||
}
|
||||
}
|
||||
|
||||
if (!metadata.getAuthors().isEmpty()) {
|
||||
authorRepository.saveAll(metadata.getAuthors());
|
||||
private boolean shouldUpdateField(Boolean locked, Object newValue) {
|
||||
return (locked == null || !locked) && newValue != null;
|
||||
}
|
||||
|
||||
private String nullIfBlank(String value) {
|
||||
return StringUtils.hasText(value) ? value : null;
|
||||
}
|
||||
|
||||
private <T> void updateFieldIfUnlocked(Supplier<Boolean> lockSupplier, T newValue, Consumer<T> setter) {
|
||||
if (shouldUpdateField(lockSupplier.get(), newValue)) {
|
||||
setter.accept(newValue);
|
||||
}
|
||||
if (!metadata.getCategories().isEmpty()) {
|
||||
categoryRepository.saveAll(metadata.getCategories());
|
||||
}
|
||||
bookMetadataRepository.save(metadata);
|
||||
return metadata;
|
||||
}
|
||||
|
||||
private void updateLocks(BookMetadata newMetadata, BookMetadataEntity metadata) {
|
||||
if (newMetadata.getTitleLocked() != null) {
|
||||
metadata.setTitleLocked(newMetadata.getTitleLocked());
|
||||
}
|
||||
if (newMetadata.getSubtitleLocked() != null) {
|
||||
metadata.setSubtitleLocked(newMetadata.getSubtitleLocked());
|
||||
}
|
||||
if (newMetadata.getPublisherLocked() != null) {
|
||||
metadata.setPublisherLocked(newMetadata.getPublisherLocked());
|
||||
}
|
||||
if (newMetadata.getPublishedDateLocked() != null) {
|
||||
metadata.setPublishedDateLocked(newMetadata.getPublishedDateLocked());
|
||||
}
|
||||
if (newMetadata.getDescriptionLocked() != null) {
|
||||
metadata.setDescriptionLocked(newMetadata.getDescriptionLocked());
|
||||
}
|
||||
if (newMetadata.getIsbn13Locked() != null) {
|
||||
metadata.setIsbn13Locked(newMetadata.getIsbn13Locked());
|
||||
}
|
||||
if (newMetadata.getIsbn10Locked() != null) {
|
||||
metadata.setIsbn10Locked(newMetadata.getIsbn10Locked());
|
||||
}
|
||||
if (newMetadata.getAsinLocked() != null) {
|
||||
metadata.setAsinLocked(newMetadata.getAsinLocked());
|
||||
}
|
||||
if (newMetadata.getGoodreadsIdLocked() != null) {
|
||||
metadata.setGoodreadsIdLocked(newMetadata.getGoodreadsIdLocked());
|
||||
}
|
||||
if (newMetadata.getHardcoverIdLocked() != null) {
|
||||
metadata.setHardcoverIdLocked(newMetadata.getHardcoverIdLocked());
|
||||
}
|
||||
if (newMetadata.getGoogleIdLocked() != null) {
|
||||
metadata.setGoogleIdLocked(newMetadata.getGoogleIdLocked());
|
||||
}
|
||||
if (newMetadata.getPageCountLocked() != null) {
|
||||
metadata.setPageCountLocked(newMetadata.getPageCountLocked());
|
||||
}
|
||||
if (newMetadata.getLanguageLocked() != null) {
|
||||
metadata.setLanguageLocked(newMetadata.getLanguageLocked());
|
||||
}
|
||||
if (newMetadata.getAmazonRatingLocked() != null) {
|
||||
metadata.setAmazonRatingLocked(newMetadata.getAmazonRatingLocked());
|
||||
}
|
||||
if (newMetadata.getAmazonReviewCountLocked() != null) {
|
||||
metadata.setAmazonReviewCountLocked(newMetadata.getAmazonReviewCountLocked());
|
||||
}
|
||||
if (newMetadata.getGoodreadsRatingLocked() != null) {
|
||||
metadata.setGoodreadsRatingLocked(newMetadata.getGoodreadsRatingLocked());
|
||||
}
|
||||
if (newMetadata.getGoodreadsReviewCountLocked() != null) {
|
||||
metadata.setGoodreadsReviewCountLocked(newMetadata.getGoodreadsReviewCountLocked());
|
||||
}
|
||||
if (newMetadata.getHardcoverRatingLocked() != null) {
|
||||
metadata.setHardcoverRatingLocked(newMetadata.getHardcoverRatingLocked());
|
||||
}
|
||||
if (newMetadata.getHardcoverReviewCountLocked() != null) {
|
||||
metadata.setHardcoverReviewCountLocked(newMetadata.getHardcoverReviewCountLocked());
|
||||
}
|
||||
if (newMetadata.getSeriesNameLocked() != null) {
|
||||
metadata.setSeriesNameLocked(newMetadata.getSeriesNameLocked());
|
||||
}
|
||||
if (newMetadata.getSeriesNumberLocked() != null) {
|
||||
metadata.setSeriesNumberLocked(newMetadata.getSeriesNumberLocked());
|
||||
}
|
||||
if (newMetadata.getSeriesTotalLocked() != null) {
|
||||
metadata.setSeriesTotalLocked(newMetadata.getSeriesTotalLocked());
|
||||
}
|
||||
if (newMetadata.getAuthorsLocked() != null) {
|
||||
metadata.setAuthorsLocked(newMetadata.getAuthorsLocked());
|
||||
}
|
||||
if (newMetadata.getCategoriesLocked() != null) {
|
||||
metadata.setCategoriesLocked(newMetadata.getCategoriesLocked());
|
||||
}
|
||||
if (newMetadata.getCoverLocked() != null) {
|
||||
metadata.setCoverLocked(newMetadata.getCoverLocked());
|
||||
List<Pair<Boolean, Consumer<Boolean>>> lockMappings = List.of(
|
||||
Pair.of(newMetadata.getTitleLocked(), metadata::setTitleLocked),
|
||||
Pair.of(newMetadata.getSubtitleLocked(), metadata::setSubtitleLocked),
|
||||
Pair.of(newMetadata.getPublisherLocked(), metadata::setPublisherLocked),
|
||||
Pair.of(newMetadata.getPublishedDateLocked(), metadata::setPublishedDateLocked),
|
||||
Pair.of(newMetadata.getDescriptionLocked(), metadata::setDescriptionLocked),
|
||||
Pair.of(newMetadata.getIsbn13Locked(), metadata::setIsbn13Locked),
|
||||
Pair.of(newMetadata.getIsbn10Locked(), metadata::setIsbn10Locked),
|
||||
Pair.of(newMetadata.getAsinLocked(), metadata::setAsinLocked),
|
||||
Pair.of(newMetadata.getGoodreadsIdLocked(), metadata::setGoodreadsIdLocked),
|
||||
Pair.of(newMetadata.getHardcoverIdLocked(), metadata::setHardcoverIdLocked),
|
||||
Pair.of(newMetadata.getGoogleIdLocked(), metadata::setGoogleIdLocked),
|
||||
Pair.of(newMetadata.getPageCountLocked(), metadata::setPageCountLocked),
|
||||
Pair.of(newMetadata.getLanguageLocked(), metadata::setLanguageLocked),
|
||||
Pair.of(newMetadata.getAmazonRatingLocked(), metadata::setAmazonRatingLocked),
|
||||
Pair.of(newMetadata.getAmazonReviewCountLocked(), metadata::setAmazonReviewCountLocked),
|
||||
Pair.of(newMetadata.getGoodreadsRatingLocked(), metadata::setGoodreadsRatingLocked),
|
||||
Pair.of(newMetadata.getGoodreadsReviewCountLocked(), metadata::setGoodreadsReviewCountLocked),
|
||||
Pair.of(newMetadata.getHardcoverRatingLocked(), metadata::setHardcoverRatingLocked),
|
||||
Pair.of(newMetadata.getHardcoverReviewCountLocked(), metadata::setHardcoverReviewCountLocked),
|
||||
Pair.of(newMetadata.getSeriesNameLocked(), metadata::setSeriesNameLocked),
|
||||
Pair.of(newMetadata.getSeriesNumberLocked(), metadata::setSeriesNumberLocked),
|
||||
Pair.of(newMetadata.getSeriesTotalLocked(), metadata::setSeriesTotalLocked),
|
||||
Pair.of(newMetadata.getAuthorsLocked(), metadata::setAuthorsLocked),
|
||||
Pair.of(newMetadata.getCategoriesLocked(), metadata::setCategoriesLocked),
|
||||
Pair.of(newMetadata.getCoverLocked(), metadata::setCoverLocked)
|
||||
);
|
||||
lockMappings.forEach(pair -> applyLock(pair.getLeft(), pair.getRight()));
|
||||
}
|
||||
|
||||
private void applyLock(Boolean newLockValue, Consumer<Boolean> setter) {
|
||||
if (newLockValue != null) {
|
||||
setter.accept(newLockValue);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+2
-1
@@ -3,8 +3,9 @@ package com.adityachandel.booklore.service.metadata;
|
||||
import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
@FunctionalInterface
|
||||
interface FieldValueExtractorList {
|
||||
List<String> extract(BookMetadata metadata);
|
||||
Set<String> extract(BookMetadata metadata);
|
||||
}
|
||||
|
||||
-1
@@ -1,7 +1,6 @@
|
||||
package com.adityachandel.booklore.service.metadata.extractor;
|
||||
|
||||
import com.adityachandel.booklore.model.UploadedFileMetadata;
|
||||
import com.adityachandel.booklore.service.upload.UploadedFileMetadataExtractor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.io.FilenameUtils;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
-1
@@ -1,7 +1,6 @@
|
||||
package com.adityachandel.booklore.service.metadata.extractor;
|
||||
|
||||
import com.adityachandel.booklore.model.UploadedFileMetadata;
|
||||
import com.adityachandel.booklore.service.upload.UploadedFileMetadataExtractor;
|
||||
import io.documentnode.epub4j.domain.Author;
|
||||
import io.documentnode.epub4j.domain.Book;
|
||||
import io.documentnode.epub4j.epub.EpubReader;
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.adityachandel.booklore.service.upload;
|
||||
package com.adityachandel.booklore.service.metadata.extractor;
|
||||
|
||||
import com.adityachandel.booklore.model.UploadedFileMetadata;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.adityachandel.booklore.service.upload;
|
||||
package com.adityachandel.booklore.service.metadata.extractor;
|
||||
|
||||
import com.adityachandel.booklore.model.UploadedFileMetadata;
|
||||
|
||||
+11
-4
@@ -51,9 +51,16 @@ public class AmazonBookParser implements BookParser {
|
||||
}
|
||||
List<BookMetadata> fetchedBookMetadata = new ArrayList<>();
|
||||
for (String amazonBookId : amazonBookIds) {
|
||||
if (amazonBookId == null || amazonBookId.isBlank()) {
|
||||
log.debug("Skipping null or blank Amazon book ID.");
|
||||
continue;
|
||||
}
|
||||
BookMetadata metadata = getBookMetadata(amazonBookId);
|
||||
if (metadata.getTitle() == null || metadata.getTitle().isBlank() ||
|
||||
metadata.getAuthors() == null || metadata.getAuthors().isEmpty()) {
|
||||
if (metadata == null) {
|
||||
log.debug("Skipping null metadata for ID: {}", amazonBookId);
|
||||
continue;
|
||||
}
|
||||
if (metadata.getTitle() == null || metadata.getTitle().isBlank() || metadata.getAuthors() == null || metadata.getAuthors().isEmpty()) {
|
||||
log.debug("Skipping metadata with missing title or author for ID: {}", amazonBookId);
|
||||
continue;
|
||||
}
|
||||
@@ -145,8 +152,8 @@ public class AmazonBookParser implements BookParser {
|
||||
.provider(MetadataProvider.Amazon)
|
||||
.title(getTitle(doc))
|
||||
.subtitle(getSubtitle(doc))
|
||||
.authors(getAuthors(doc).stream().toList())
|
||||
.categories(getBestSellerCategories(doc).stream().toList())
|
||||
.authors(new HashSet<>(getAuthors(doc)))
|
||||
.categories(new HashSet<>(getBestSellerCategories(doc)))
|
||||
.description(cleanDescriptionHtml(getDescription(doc)))
|
||||
.seriesName(getSeriesName(doc))
|
||||
.seriesNumber(getSeriesNumber(doc))
|
||||
|
||||
+6
-6
@@ -99,7 +99,7 @@ public class GoodReadsParser implements BookParser {
|
||||
if (contributorKey != null) {
|
||||
String contributorName = getContributorName(apolloStateJson, contributorKey);
|
||||
if (contributorName != null) {
|
||||
builder.authors(List.of(contributorName));
|
||||
builder.authors(Set.of(contributorName));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -255,9 +255,9 @@ public class GoodReadsParser implements BookParser {
|
||||
return null;
|
||||
}
|
||||
|
||||
private List<String> extractGenres(JSONObject bookJson) {
|
||||
private Set<String> extractGenres(JSONObject bookJson) {
|
||||
try {
|
||||
List<String> genres = new ArrayList<>();
|
||||
Set<String> genres = new HashSet<>();
|
||||
JSONArray bookGenresJsonArray = bookJson.getJSONArray("bookGenres");
|
||||
for (int i = 0; i < bookGenresJsonArray.length(); i++) {
|
||||
JSONObject genreJson = bookGenresJsonArray.getJSONObject(i).getJSONObject("genre");
|
||||
@@ -314,7 +314,7 @@ public class GoodReadsParser implements BookParser {
|
||||
FuzzyScore fuzzyScore = new FuzzyScore(Locale.ENGLISH);
|
||||
String queryAuthor = request.getAuthor();
|
||||
for (Element previewBook : previewBooks) {
|
||||
List<String> authors = extractAuthorsPreview(previewBook);
|
||||
Set<String> authors = extractAuthorsPreview(previewBook);
|
||||
if (queryAuthor != null && !queryAuthor.isBlank()) {
|
||||
List<String> queryAuthorTokens = List.of(queryAuthor.toLowerCase().split("\\s+"));
|
||||
boolean matches = authors.stream().flatMap(a -> Arrays.stream(a.toLowerCase().split("\\s+"))).anyMatch(actual -> {
|
||||
@@ -371,8 +371,8 @@ public class GoodReadsParser implements BookParser {
|
||||
return null;
|
||||
}
|
||||
|
||||
private List<String> extractAuthorsPreview(Element book) {
|
||||
List<String> authors = new ArrayList<>();
|
||||
private Set<String> extractAuthorsPreview(Element book) {
|
||||
Set<String> authors = new HashSet<>();
|
||||
try {
|
||||
Elements authorsElement = book.select("a.authorName");
|
||||
for (Element authorElement : authorsElement) {
|
||||
|
||||
+3
-2
@@ -22,6 +22,7 @@ import java.time.format.DateTimeFormatter;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Slf4j
|
||||
@@ -94,8 +95,8 @@ public class GoogleParser implements BookParser {
|
||||
.publisher(volumeInfo.getPublisher())
|
||||
.publishedDate(parseDate(volumeInfo.getPublishedDate()))
|
||||
.description(volumeInfo.getDescription())
|
||||
.authors(Optional.ofNullable(volumeInfo.getAuthors()).orElse(List.of()))
|
||||
.categories(Optional.ofNullable(volumeInfo.getCategories()).orElse(List.of()))
|
||||
.authors(Optional.ofNullable(volumeInfo.getAuthors()).orElse(Set.of()))
|
||||
.categories(Optional.ofNullable(volumeInfo.getCategories()).orElse(Set.of()))
|
||||
.isbn13(isbns.get("ISBN_13"))
|
||||
.isbn10(isbns.get("ISBN_10"))
|
||||
.pageCount(volumeInfo.getPageCount())
|
||||
|
||||
+3
-2
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
@Data
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
@@ -43,7 +44,7 @@ public class GraphQLResponse {
|
||||
private String title;
|
||||
|
||||
@JsonProperty("author_names")
|
||||
private List<String> authorNames;
|
||||
private Set<String> authorNames;
|
||||
|
||||
private String description;
|
||||
private List<String> isbns;
|
||||
@@ -57,7 +58,7 @@ public class GraphQLResponse {
|
||||
@JsonProperty("release_date")
|
||||
private String releaseDate;
|
||||
|
||||
private List<String> genres;
|
||||
private Set<String> genres;
|
||||
|
||||
@JsonProperty("featured_series")
|
||||
private FeaturedSeries featuredSeries;
|
||||
|
||||
+1
-1
@@ -35,7 +35,7 @@ public class AppMigrationService {
|
||||
return;
|
||||
}
|
||||
|
||||
List<BookEntity> books = bookRepository.findByFileSizeKbIsNull();
|
||||
List<BookEntity> books = bookRepository.findAllWithMetadataByFileSizeKbIsNull();
|
||||
for (BookEntity book : books) {
|
||||
Long sizeInKb = FileUtils.getFileSizeInKb(book);
|
||||
if (sizeInKb != null) {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package com.adityachandel.booklore.service.opds;
|
||||
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.service.BookQueryService;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -15,10 +15,10 @@ import java.util.List;
|
||||
@RequiredArgsConstructor
|
||||
public class OpdsService {
|
||||
|
||||
private final BookRepository bookRepository;
|
||||
private final BookQueryService bookQueryService;
|
||||
|
||||
public String generateCatalogFeed(HttpServletRequest request) {
|
||||
var books = bookRepository.findAll();
|
||||
var books = bookQueryService.getAllFullBookEntities();
|
||||
var feedVersion = extractVersionFromAcceptHeader(request);
|
||||
|
||||
return switch (feedVersion) {
|
||||
|
||||
+6
-5
@@ -2,8 +2,8 @@ package com.adityachandel.booklore.service.recommender;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.BookRecommendationLite;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.service.appsettings.AppSettingService;
|
||||
import com.adityachandel.booklore.service.BookQueryService;
|
||||
import jakarta.transaction.Transactional;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -11,13 +11,14 @@ import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class BookRecommendationScheduler {
|
||||
|
||||
private final BookRepository bookRepository;
|
||||
private final BookQueryService bookQueryService;
|
||||
private final BookRecommendationService recommendationService;
|
||||
private final AppSettingService appSettingService;
|
||||
|
||||
@@ -33,17 +34,17 @@ public class BookRecommendationScheduler {
|
||||
long startTime = System.currentTimeMillis();
|
||||
log.info("Scheduled task 'updateAllSimilarBooks' started at: {}. Current timestamp: {}", startTime, startTime);
|
||||
|
||||
List<BookEntity> allBooks = bookRepository.findAll();
|
||||
List<BookEntity> allBooks = bookQueryService.getAllFullBookEntities();
|
||||
|
||||
for (BookEntity book : allBooks) {
|
||||
try {
|
||||
List<BookRecommendationLite> recommendations = recommendationService.findSimilarBookIds(book.getId(), RECOMMENDATION_LIMIT);
|
||||
Set<BookRecommendationLite> recommendations = recommendationService.findSimilarBookIds(book.getId(), RECOMMENDATION_LIMIT);
|
||||
book.setSimilarBooksJson(recommendations);
|
||||
} catch (Exception e) {
|
||||
log.error("Error updating similar books for book ID {}: {}", book.getId(), e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
bookRepository.saveAll(allBooks);
|
||||
bookQueryService.saveAll(allBooks);
|
||||
|
||||
long endTime = System.currentTimeMillis();
|
||||
log.info("Completed scheduled task 'updateAllSimilarBooks' at: {}. Duration: {} ms", endTime, endTime - startTime);
|
||||
|
||||
+26
-16
@@ -8,7 +8,7 @@ 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.repository.BookRepository;
|
||||
import com.adityachandel.booklore.service.user.UserService;
|
||||
import com.adityachandel.booklore.service.BookQueryService;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
@@ -25,16 +25,16 @@ public class BookRecommendationService {
|
||||
|
||||
private final BookSimilarityService similarityService;
|
||||
private final BookRepository bookRepository;
|
||||
private final BookQueryService bookQueryService;
|
||||
private final BookMapper bookMapper;
|
||||
private final AuthenticationService authenticationService;
|
||||
|
||||
private static final int MAX_BOOKS_PER_AUTHOR = 3;
|
||||
|
||||
public List<BookRecommendation> getRecommendations(Long bookId, int limit) {
|
||||
BookEntity book = bookRepository.findById(bookId)
|
||||
.orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||
BookEntity book = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||
|
||||
List<BookRecommendationLite> recommendations = book.getSimilarBooksJson();
|
||||
Set<BookRecommendationLite> recommendations = book.getSimilarBooksJson();
|
||||
if (recommendations == null || recommendations.isEmpty()) {
|
||||
log.info("Recommendations for book ID {} are missing or empty. Computing similarity...", bookId);
|
||||
recommendations = findSimilarBookIds(bookId, limit);
|
||||
@@ -42,17 +42,27 @@ public class BookRecommendationService {
|
||||
bookRepository.save(book);
|
||||
}
|
||||
|
||||
List<Long> recommendedBookIds = recommendations.stream()
|
||||
Set<Long> recommendedBookIds = recommendations.stream()
|
||||
.map(BookRecommendationLite::getB)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
Set<Long> accessibleLibraryIds = user.getAssignedLibraries().stream()
|
||||
.map(Library::getId)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
Map<Long, BookEntity> recommendedBooksMap = bookRepository.findAllById(recommendedBookIds).stream()
|
||||
.filter(b -> b.getLibrary() != null && accessibleLibraryIds.contains(b.getLibrary().getId()))
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
Set<Long> accessibleLibraryIds;
|
||||
if (user.getPermissions().isAdmin()) {
|
||||
accessibleLibraryIds = null;
|
||||
} else {
|
||||
accessibleLibraryIds = user.getAssignedLibraries().stream()
|
||||
.map(Library::getId)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
Map<Long, BookEntity> recommendedBooksMap = bookQueryService.findAllWithMetadataByIds(recommendedBookIds).stream()
|
||||
.filter(b -> {
|
||||
if (accessibleLibraryIds == null) {
|
||||
return true;
|
||||
}
|
||||
return b.getLibrary() != null && accessibleLibraryIds.contains(b.getLibrary().getId());
|
||||
})
|
||||
.collect(Collectors.toMap(BookEntity::getId, Function.identity()));
|
||||
|
||||
return recommendations.stream()
|
||||
@@ -66,20 +76,20 @@ public class BookRecommendationService {
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
protected List<BookRecommendationLite> findSimilarBookIds(Long bookId, int limit) {
|
||||
protected Set<BookRecommendationLite> findSimilarBookIds(Long bookId, int limit) {
|
||||
List<BookRecommendation> similarBooks = findSimilarBooks(bookId, limit);
|
||||
if (similarBooks == null || similarBooks.isEmpty()) {
|
||||
return Collections.emptyList();
|
||||
return Collections.emptySet();
|
||||
}
|
||||
return similarBooks.stream()
|
||||
.map(b -> new BookRecommendationLite(b.getBook().getId(), b.getSimilarityScore()))
|
||||
.collect(Collectors.toList());
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
protected List<BookRecommendation> findSimilarBooks(Long bookId, int limit) {
|
||||
BookEntity target = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||
|
||||
List<BookEntity> candidates = bookRepository.findAll();
|
||||
List<BookEntity> candidates = bookQueryService.getAllFullBookEntities();
|
||||
|
||||
String targetSeriesName = Optional.ofNullable(target.getMetadata())
|
||||
.map(BookMetadataEntity::getSeriesName)
|
||||
|
||||
+4
-4
@@ -58,9 +58,9 @@ public class BookSimilarityService {
|
||||
return round(score, 5);
|
||||
}
|
||||
|
||||
private List<String> extractNames(List<?> entities) {
|
||||
if (entities == null) return Collections.emptyList();
|
||||
List<String> names = new ArrayList<>();
|
||||
private Set<String> extractNames(Set<?> entities) {
|
||||
if (entities == null) return Collections.emptySet();
|
||||
Set<String> names = new HashSet<>();
|
||||
for (Object obj : entities) {
|
||||
if (obj instanceof AuthorEntity author && author.getName() != null) {
|
||||
names.add(author.getName().toLowerCase());
|
||||
@@ -75,7 +75,7 @@ public class BookSimilarityService {
|
||||
return s1 != null && s2 != null && s1.equalsIgnoreCase(s2);
|
||||
}
|
||||
|
||||
private double jaccardSimilarity(List<String> a, List<String> b) {
|
||||
private double jaccardSimilarity(Set<String> a, Set<String> b) {
|
||||
if (a.isEmpty() || b.isEmpty()) return 0.0;
|
||||
Set<String> setA = new HashSet<>(a);
|
||||
Set<String> setB = new HashSet<>(b);
|
||||
|
||||
+1
@@ -15,6 +15,7 @@ import com.adityachandel.booklore.service.fileprocessor.CbxProcessor;
|
||||
import com.adityachandel.booklore.service.fileprocessor.EpubProcessor;
|
||||
import com.adityachandel.booklore.service.fileprocessor.PdfProcessor;
|
||||
import com.adityachandel.booklore.service.metadata.extractor.EpubMetadataExtractor;
|
||||
import com.adityachandel.booklore.service.metadata.extractor.PdfMetadataExtractor;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
+1
@@ -96,6 +96,7 @@ public class DefaultUserSettingsProvider {
|
||||
.sortDir("ASC")
|
||||
.view("GRID")
|
||||
.coverSize(1.0F)
|
||||
.seriesCollapsed(false)
|
||||
.build())
|
||||
.overrides(null)
|
||||
.build();
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
app:
|
||||
path-config: '/app/data'
|
||||
version: 'v0.0.40'
|
||||
|
||||
swagger:
|
||||
enabled: ${SWAGGER_ENABLED:false}
|
||||
remote-auth:
|
||||
enabled: ${REMOTE_AUTH_ENABLED:false}
|
||||
create-new-users: ${REMOTE_AUTH_CREATE_NEW_USERS:true}
|
||||
@@ -45,6 +46,10 @@ spring:
|
||||
enabled: true
|
||||
locations: classpath:db/migration
|
||||
|
||||
springdoc:
|
||||
swagger-ui:
|
||||
persist-authorization: true
|
||||
|
||||
logging:
|
||||
level:
|
||||
root: ${ROOT_LOG_LEVEL:INFO}
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {DialogService, DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||
import {ShelfAssignerComponent} from '../shelf-assigner/shelf-assigner.component';
|
||||
import {LockUnlockMetadataDialogComponent} from './lock-unlock-metadata-dialog/lock-unlock-metadata-dialog.component';
|
||||
import {MetadataFetchOptionsComponent} from '../../metadata/metadata-options-dialog/metadata-fetch-options/metadata-fetch-options.component';
|
||||
import {MetadataRefreshType} from '../../metadata/model/request/metadata-refresh-type.enum';
|
||||
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class BookDialogHelperService {
|
||||
|
||||
private dialogService = inject(DialogService);
|
||||
|
||||
openShelfAssigner(bookIds: Set<number>): DynamicDialogRef {
|
||||
return this.dialogService.open(ShelfAssignerComponent, {
|
||||
header: `Update Books' Shelves`,
|
||||
modal: true,
|
||||
closable: true,
|
||||
contentStyle: {overflow: 'auto'},
|
||||
baseZIndex: 10,
|
||||
style: {
|
||||
position: 'absolute',
|
||||
top: '15%',
|
||||
},
|
||||
data: {
|
||||
isMultiBooks: true,
|
||||
bookIds,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
openLockUnlockMetadataDialog(bookIds: Set<number>): DynamicDialogRef {
|
||||
const count = bookIds.size;
|
||||
return this.dialogService.open(LockUnlockMetadataDialogComponent, {
|
||||
header: `Lock or Unlock Metadata for ${count} Selected Book${count > 1 ? 's' : ''}`,
|
||||
modal: true,
|
||||
closable: true,
|
||||
data: {
|
||||
bookIds: Array.from(bookIds),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
openMetadataRefreshDialog(bookIds: Set<number>): DynamicDialogRef {
|
||||
return this.dialogService.open(MetadataFetchOptionsComponent, {
|
||||
header: 'Metadata Refresh Options',
|
||||
modal: true,
|
||||
closable: true,
|
||||
data: {
|
||||
bookIds: Array.from(bookIds),
|
||||
metadataRefreshType: MetadataRefreshType.BOOKS,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import {Subject} from 'rxjs';
|
||||
import {debounceTime} from 'rxjs/operators';
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {UserService} from '../../../settings/user-management/user.service';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class CoverScaleManager {
|
||||
private readonly baseWidth = 135;
|
||||
private readonly baseHeight = 220;
|
||||
|
||||
private readonly messageService = inject(MessageService);
|
||||
private readonly userService = inject(UserService);
|
||||
|
||||
private readonly scaleChangeSubject = new Subject<number>();
|
||||
readonly scaleChange$ = this.scaleChangeSubject.asObservable();
|
||||
|
||||
scaleFactor = 1.0;
|
||||
|
||||
constructor() {
|
||||
this.scaleChange$
|
||||
.pipe(debounceTime(1000))
|
||||
.subscribe(scale => this.persistScale(scale));
|
||||
}
|
||||
|
||||
setScale(scale: number): void {
|
||||
this.scaleFactor = scale;
|
||||
this.scaleChangeSubject.next(scale);
|
||||
}
|
||||
|
||||
get currentCardSize(): { width: number; height: number } {
|
||||
return {
|
||||
width: Math.round(this.baseWidth * this.scaleFactor),
|
||||
height: Math.round(this.baseHeight * this.scaleFactor),
|
||||
};
|
||||
}
|
||||
|
||||
get gridColumnMinWidth(): string {
|
||||
return `${this.currentCardSize.width}px`;
|
||||
}
|
||||
|
||||
private persistScale(scale: number): void {
|
||||
const user = this.userService.getCurrentUser();
|
||||
const entityViewPreferences = user?.userSettings?.entityViewPreferences;
|
||||
if (!user || !entityViewPreferences) {
|
||||
return;
|
||||
}
|
||||
entityViewPreferences.global = entityViewPreferences.global ?? {};
|
||||
entityViewPreferences.global.coverSize = scale;
|
||||
this.userService.updateUserSetting(user.id, 'entityViewPreferences', entityViewPreferences);
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'Cover Size Saved',
|
||||
detail: `Cover size set to ${scale.toFixed(2)}x.`
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -32,7 +32,6 @@
|
||||
</div>
|
||||
|
||||
<div class="flex items-center gap-8">
|
||||
|
||||
<div class="flex flex-row items-center gap-6">
|
||||
@if (isFilterActive) {
|
||||
<a class="topbar-items topbar-item" (click)="clearFilter()">
|
||||
@@ -43,7 +42,28 @@
|
||||
</i>
|
||||
</a>
|
||||
}
|
||||
|
||||
<div>
|
||||
<a
|
||||
class="topbar-items topbar-item"
|
||||
(click)="seriesCollapseOverlay.toggle($event)"
|
||||
pTooltip="Series collapse settings"
|
||||
tooltipPosition="top">
|
||||
<i class="pi pi-cog"></i>
|
||||
</a>
|
||||
<p-popover #seriesCollapseOverlay [dismissable]="true" appendTo="body">
|
||||
<div class="w-[220px] p-2">
|
||||
<div class="flex items-center gap-2">
|
||||
<p-checkbox
|
||||
[binary]="true"
|
||||
[ngModel]="seriesCollapseFilter.isSeriesCollapsed"
|
||||
(onChange)="onSeriesCollapseCheckboxChange($event.checked)"
|
||||
inputId="collapse-series-checkbox">
|
||||
</p-checkbox>
|
||||
<label for="collapse-series-checkbox">Collapse series</label>
|
||||
</div>
|
||||
</div>
|
||||
</p-popover>
|
||||
</div>
|
||||
<div>
|
||||
<a
|
||||
class="topbar-items topbar-item"
|
||||
@@ -52,11 +72,10 @@
|
||||
tooltipPosition="top">
|
||||
<i class="pi pi-th-large"></i>
|
||||
</a>
|
||||
|
||||
<p-popover #sizeOverlay [dismissable]="true" appendTo="body">
|
||||
<div style="width: 220px; padding: 8px;">
|
||||
<p-slider
|
||||
[(ngModel)]="scaleFactor"
|
||||
[(ngModel)]="coverScaleManager.scaleFactor"
|
||||
[min]="0.5"
|
||||
[max]="1.5"
|
||||
[step]="0.01"
|
||||
@@ -64,7 +83,7 @@
|
||||
(onChange)="updateScale()"
|
||||
></p-slider>
|
||||
<div style="text-align: center; margin-top: 8px;">
|
||||
{{ scaleFactor.toFixed(2) }}x
|
||||
{{ coverScaleManager.scaleFactor.toFixed(2) }}x
|
||||
</div>
|
||||
</div>
|
||||
</p-popover>
|
||||
@@ -78,9 +97,9 @@
|
||||
tooltipPosition="top">
|
||||
</i>
|
||||
</a>
|
||||
<p-menu #sortMenu [popup]="true" [model]="sortOptions" appendTo="body">
|
||||
<p-menu #sortMenu [popup]="true" [model]="this.bookSorter.sortOptions" appendTo="body">
|
||||
<ng-template pTemplate="item" let-item>
|
||||
<div class="flex justify-between items-center px-4 py-2 cursor-pointer" (click)="sortBooks(item.field)">
|
||||
<div class="flex justify-between items-center px-4 py-2 cursor-pointer" (click)="this.bookSorter.sortBooks(item.field)">
|
||||
<span>{{ item.label }}</span>
|
||||
@if (item.icon) {
|
||||
<i [class]="item.icon"></i>
|
||||
@@ -108,7 +127,8 @@
|
||||
placeholder="Title, Series or Author..."
|
||||
[(ngModel)]="bookTitle"
|
||||
(ngModelChange)="onSearchTermChange($event)"
|
||||
class="search-input"/>
|
||||
class="search-input"
|
||||
/>
|
||||
@if (bookTitle) {
|
||||
<p-button
|
||||
icon="pi pi-times"
|
||||
@@ -130,7 +150,8 @@
|
||||
[rounded]="true"
|
||||
(click)="toggleFilterSidebar()"
|
||||
pTooltip="Toggle filter sidebar"
|
||||
tooltipPosition="top"/>
|
||||
tooltipPosition="top"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -159,8 +180,11 @@
|
||||
@if (bookState?.books; as books) {
|
||||
<div class="book-card-container">
|
||||
@if (currentViewMode === 'table' && books.length > 0) {
|
||||
<app-book-table [books]="books" (selectedBooksChange)="onSelectedBooksChange($event)"
|
||||
[sortOption]="selectedSort!"></app-book-table>
|
||||
<app-book-table
|
||||
[books]="books"
|
||||
(selectedBooksChange)="onSelectedBooksChange($event)"
|
||||
[sortOption]="this.bookSorter.selectedSort!"
|
||||
></app-book-table>
|
||||
}
|
||||
@if (currentViewMode === 'grid') {
|
||||
<virtual-scroller class="virtual-scroller" #scroll [items]="books">
|
||||
@@ -170,12 +194,13 @@
|
||||
[ngStyle]="{'grid-template-columns': 'repeat(auto-fill, minmax(' + gridColumnMinWidth + ', 1fr))'}">
|
||||
@for (book of scroll.viewPortItems; track book) {
|
||||
<div
|
||||
class="virtual-scroller-item"
|
||||
class="virtual-scroller-item relative"
|
||||
[ngStyle]="{width: currentCardSize.width + 'px', height: currentCardSize.height + 'px'}">
|
||||
<app-book-card
|
||||
[book]="book"
|
||||
[isCheckboxEnabled]="true"
|
||||
[onBookSelect]="handleBookSelect.bind(this)"
|
||||
[isSeriesCollapsed]="seriesCollapseFilter.isSeriesCollapsed"
|
||||
[isSelected]="selectedBooks.has(book.id)">
|
||||
</app-book-card>
|
||||
</div>
|
||||
@@ -249,5 +274,4 @@
|
||||
</div>
|
||||
|
||||
<app-book-filter [entity$]="entity$" [entityType$]="entityType$" [resetFilter$]="resetFilterSubject"></app-book-filter>
|
||||
|
||||
</div>
|
||||
|
||||
@@ -6,8 +6,7 @@ import {BookService} from '../../service/book.service';
|
||||
import {debounceTime, filter, map, switchMap, take} from 'rxjs/operators';
|
||||
import {BehaviorSubject, combineLatest, Observable, of, Subject} from 'rxjs';
|
||||
import {ShelfService} from '../../service/shelf.service';
|
||||
import {ShelfAssignerComponent} from '../shelf-assigner/shelf-assigner.component';
|
||||
import {DialogService, DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||
import {DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||
import {Library} from '../../model/library.model';
|
||||
import {Shelf} from '../../model/shelf.model';
|
||||
import {SortService} from '../../service/sort.service';
|
||||
@@ -17,8 +16,6 @@ import {Book} from '../../model/book.model';
|
||||
import {LibraryShelfMenuService} from '../../service/library-shelf-menu.service';
|
||||
import {BookTableComponent} from './book-table/book-table.component';
|
||||
import {animate, state, style, transition, trigger} from '@angular/animations';
|
||||
import {MetadataFetchOptionsComponent} from '../../metadata/metadata-options-dialog/metadata-fetch-options/metadata-fetch-options.component';
|
||||
import {MetadataRefreshType} from '../../metadata/model/request/metadata-refresh-type.enum';
|
||||
import {Button} from 'primeng/button';
|
||||
import {AsyncPipe, NgClass, NgStyle} from '@angular/common';
|
||||
import {VirtualScrollerModule} from '@iharbeck/ngx-virtual-scroller';
|
||||
@@ -27,14 +24,20 @@ import {ProgressSpinner} from 'primeng/progressspinner';
|
||||
import {Menu} from 'primeng/menu';
|
||||
import {InputText} from 'primeng/inputtext';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {BookFilterComponent, isFileSizeInRange, isPageCountInRange, isRatingInRange} from './book-filter/book-filter.component';
|
||||
import {BookFilterComponent} from './book-filter/book-filter.component';
|
||||
import {Tooltip} from 'primeng/tooltip';
|
||||
import {Fluid} from 'primeng/fluid';
|
||||
import {EntityViewPreferences, UserService} from '../../../settings/user-management/user.service';
|
||||
import {LockUnlockMetadataDialogComponent} from './lock-unlock-metadata-dialog/lock-unlock-metadata-dialog.component';
|
||||
import {OverlayPanelModule} from 'primeng/overlaypanel';
|
||||
import {Slider} from 'primeng/slider';
|
||||
import {Popover} from 'primeng/popover';
|
||||
import {SeriesCollapseFilter} from './filters/SeriesCollapseFilter';
|
||||
import {SideBarFilter} from './filters/SidebarFilter';
|
||||
import {HeaderFilter} from './filters/HeaderFilter';
|
||||
import {CoverScaleManager} from './CoverScaleManager';
|
||||
import {BookSorter} from './sorting/BookSorter';
|
||||
import {BookDialogHelperService} from './BookDialogHelperService';
|
||||
import {Checkbox} from 'primeng/checkbox';
|
||||
|
||||
export enum EntityType {
|
||||
LIBRARY = 'Library',
|
||||
@@ -48,7 +51,8 @@ const QUERY_PARAMS = {
|
||||
SORT: 'sort',
|
||||
DIRECTION: 'direction',
|
||||
FILTER: 'filter',
|
||||
SIDEBAR: 'sidebar'
|
||||
SIDEBAR: 'sidebar',
|
||||
FROM: 'from',
|
||||
};
|
||||
|
||||
const VIEW_MODES = {
|
||||
@@ -66,7 +70,8 @@ const SORT_DIRECTION = {
|
||||
standalone: true,
|
||||
templateUrl: './book-browser.component.html',
|
||||
styleUrls: ['./book-browser.component.scss'],
|
||||
imports: [Button, VirtualScrollerModule, BookCardComponent, AsyncPipe, ProgressSpinner, Menu, InputText, FormsModule, BookTableComponent, BookFilterComponent, Tooltip, NgClass, Fluid, PrimeTemplate, NgStyle, OverlayPanelModule, Slider, Popover],
|
||||
imports: [Button, VirtualScrollerModule, BookCardComponent, AsyncPipe, ProgressSpinner, Menu, InputText, FormsModule, BookTableComponent, BookFilterComponent, Tooltip, NgClass, Fluid, PrimeTemplate, NgStyle, OverlayPanelModule, Slider, Popover, Checkbox],
|
||||
providers: [SeriesCollapseFilter],
|
||||
animations: [
|
||||
trigger('slideInOut', [
|
||||
state('void', style({
|
||||
@@ -109,117 +114,71 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
|
||||
selectedFilterMode = new BehaviorSubject<'and' | 'or'>('and');
|
||||
protected resetFilterSubject = new Subject<void>();
|
||||
|
||||
entityViewPreferences!: EntityViewPreferences;
|
||||
|
||||
protected userService = inject(UserService);
|
||||
protected coverScaleManager = inject(CoverScaleManager);
|
||||
|
||||
private activatedRoute = inject(ActivatedRoute);
|
||||
private messageService = inject(MessageService);
|
||||
private libraryService = inject(LibraryService);
|
||||
private bookService = inject(BookService);
|
||||
private shelfService = inject(ShelfService);
|
||||
private dialogService = inject(DialogService);
|
||||
private dialogHelperService = inject(BookDialogHelperService);
|
||||
private sortService = inject(SortService);
|
||||
private router = inject(Router);
|
||||
private cdr = inject(ChangeDetectorRef);
|
||||
private changeDetectorRef = inject(ChangeDetectorRef);
|
||||
private libraryShelfMenuService = inject(LibraryShelfMenuService);
|
||||
|
||||
sortOptions: any[] = [
|
||||
{label: 'Title', icon: '', field: 'title', command: () => this.sortBooks('title')},
|
||||
{label: 'Title + Series', icon: '', field: 'titleSeries', command: () => this.sortBooks('titleSeries')},
|
||||
{label: 'Author', icon: '', field: 'author', command: () => this.sortBooks('author')},
|
||||
{label: 'Last Read', field: 'lastReadTime', command: () => this.sortBooks('lastReadTime')},
|
||||
{label: 'Added On', field: 'addedOn', command: () => this.sortBooks('addedOn')},
|
||||
{label: 'File Size', icon: '', field: 'fileSizeKb', command: () => this.sortBooks('fileSizeKb')},
|
||||
{label: 'Locked', icon: '', field: 'locked', command: () => this.sortBooks('locked')},
|
||||
{label: 'Publisher', icon: '', field: 'publisher', command: () => this.sortBooks('publisher')},
|
||||
{label: 'Published Date', icon: '', field: 'publishedDate', command: () => this.sortBooks('publishedDate')},
|
||||
{label: 'Amazon Rating', icon: '', field: 'amazonRating', command: () => this.sortBooks('amazonRating')},
|
||||
{label: 'Amazon #', icon: '', field: 'amazonReviewCount', command: () => this.sortBooks('amazonReviewCount')},
|
||||
{label: 'Goodreads Rating', icon: '', field: 'goodreadsRating', command: () => this.sortBooks('goodreadsRating')},
|
||||
{label: 'Goodreads #', icon: '', field: 'goodreadsReviewCount', command: () => this.sortBooks('goodreadsReviewCount')},
|
||||
{label: 'Hardcover Rating', icon: '', field: 'hardcoverRating', command: () => this.sortBooks('hardcoverRating')},
|
||||
{label: 'Hardcover #', icon: '', field: 'hardcoverReviewCount', command: () => this.sortBooks('hardcoverReviewCount')},
|
||||
{label: 'Pages', icon: '', field: 'pageCount', command: () => this.sortBooks('pageCount')}
|
||||
];
|
||||
protected seriesCollapseFilter = new SeriesCollapseFilter();
|
||||
private sideBarFilter = new SideBarFilter(this.selectedFilter, this.selectedFilterMode);
|
||||
private headerFilter = new HeaderFilter(this.searchTerm$);
|
||||
protected bookSorter = new BookSorter((selectedSort) => this.applySortOption(selectedSort));
|
||||
|
||||
selectedSort: SortOption | undefined = undefined;
|
||||
currentViewMode: string | undefined = undefined;
|
||||
lastAppliedSort: SortOption | null = null;
|
||||
filterVisibility = true;
|
||||
|
||||
prefs!: EntityViewPreferences;
|
||||
|
||||
baseWidth = 135;
|
||||
baseHeight = 220;
|
||||
scaleFactor = 1.0;
|
||||
private settingFiltersFromUrl = false;
|
||||
|
||||
get currentCardSize() {
|
||||
return {
|
||||
width: Math.round(this.baseWidth * this.scaleFactor),
|
||||
height: Math.round(this.baseHeight * this.scaleFactor)
|
||||
};
|
||||
return this.coverScaleManager.currentCardSize;
|
||||
}
|
||||
|
||||
get gridColumnMinWidth(): string {
|
||||
return `${this.currentCardSize.width}px`;
|
||||
return this.coverScaleManager.gridColumnMinWidth;
|
||||
}
|
||||
|
||||
updateScale(): void {
|
||||
this.scaleChange$.next(this.scaleFactor);
|
||||
this.coverScaleManager.setScale(this.coverScaleManager.scaleFactor);
|
||||
}
|
||||
|
||||
private scaleChange$ = new Subject<number>();
|
||||
|
||||
ngOnInit(): void {
|
||||
|
||||
this.scaleChange$.pipe(debounceTime(1000)).subscribe(scale => {
|
||||
const user = this.userService.getCurrentUser();
|
||||
if (!user || !this.prefs) return;
|
||||
this.prefs.global = this.prefs.global ?? {};
|
||||
this.prefs.global.coverSize = scale;
|
||||
this.userService.updateUserSetting(user.id, 'entityViewPreferences', this.prefs);
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'Cover Size Saved',
|
||||
detail: `Cover size set to ${scale.toFixed(2)}x.`
|
||||
});
|
||||
});
|
||||
this.coverScaleManager.scaleChange$.pipe(debounceTime(1000)).subscribe();
|
||||
|
||||
this.bookService.loadBooks();
|
||||
|
||||
const currentPath = this.activatedRoute.snapshot.routeConfig?.path;
|
||||
|
||||
if (currentPath === 'all-books') {
|
||||
this.entityType = EntityType.ALL_BOOKS;
|
||||
this.entityType$ = of(EntityType.ALL_BOOKS);
|
||||
if (currentPath === 'all-books' || currentPath === 'unshelved-books') {
|
||||
const entityType = currentPath === 'all-books' ? EntityType.ALL_BOOKS : EntityType.UNSHELVED;
|
||||
this.entityType = entityType;
|
||||
this.entityType$ = of(entityType);
|
||||
this.entity$ = of(null);
|
||||
|
||||
} else if (currentPath === 'unshelved-books') {
|
||||
this.entityType = EntityType.UNSHELVED;
|
||||
this.entityType$ = of(EntityType.UNSHELVED);
|
||||
this.entity$ = of(null);
|
||||
|
||||
} else {
|
||||
const routeEntityInfo$ = this.getEntityInfoFromRoute();
|
||||
|
||||
this.entityType$ = routeEntityInfo$.pipe(map(info => info.entityType));
|
||||
this.entity$ = routeEntityInfo$.pipe(
|
||||
switchMap(({entityId, entityType}) => this.fetchEntity(entityId, entityType))
|
||||
);
|
||||
|
||||
this.entityType$ = routeEntityInfo$.pipe(
|
||||
map(({entityType}) => entityType)
|
||||
);
|
||||
|
||||
this.entity$?.subscribe((entity) => {
|
||||
if (!entity) {
|
||||
this.entityOptions = [];
|
||||
return;
|
||||
}
|
||||
if (this.isLibrary(entity)) {
|
||||
this.entity = entity;
|
||||
this.entityOptions = this.libraryShelfMenuService.initializeLibraryMenuItems(entity);
|
||||
} else {
|
||||
this.entity = entity;
|
||||
this.entityOptions = this.libraryShelfMenuService.initializeShelfMenuItems(entity);
|
||||
}
|
||||
this.entity$.subscribe(entity => {
|
||||
this.entity = entity ?? null;
|
||||
this.entityOptions = entity
|
||||
? this.isLibrary(entity)
|
||||
? this.libraryShelfMenuService.initializeLibraryMenuItems(entity)
|
||||
: this.libraryShelfMenuService.initializeShelfMenuItems(entity)
|
||||
: [];
|
||||
});
|
||||
}
|
||||
|
||||
@@ -231,17 +190,150 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
|
||||
});
|
||||
}
|
||||
|
||||
private isLibrary(entity: Library | Shelf): entity is Library {
|
||||
return (entity as Library).paths !== undefined;
|
||||
ngAfterViewInit() {
|
||||
combineLatest({
|
||||
paramMap: this.activatedRoute.queryParamMap,
|
||||
user: this.userService.userState$.pipe(
|
||||
filter((user): user is NonNullable<typeof user> => !!user),
|
||||
take(1)
|
||||
)
|
||||
}).subscribe(({paramMap, user}) => {
|
||||
|
||||
const viewParam = paramMap.get(QUERY_PARAMS.VIEW);
|
||||
const sortParam = paramMap.get(QUERY_PARAMS.SORT);
|
||||
const directionParam = paramMap.get(QUERY_PARAMS.DIRECTION);
|
||||
const sidebarParam = paramMap.get(QUERY_PARAMS.SIDEBAR);
|
||||
const filterParams = paramMap.get(QUERY_PARAMS.FILTER);
|
||||
|
||||
const parsedFilters: Record<string, string[]> = {};
|
||||
|
||||
if (filterParams) {
|
||||
this.settingFiltersFromUrl = true;
|
||||
|
||||
filterParams.split(',').forEach(pair => {
|
||||
const [key, ...valueParts] = pair.split(':');
|
||||
const value = valueParts.join(':');
|
||||
if (key && value) {
|
||||
parsedFilters[key] = value.split('|').map(v => v.trim()).filter(Boolean);
|
||||
}
|
||||
});
|
||||
|
||||
this.selectedFilter.next(parsedFilters);
|
||||
this.bookFilterComponent.setFilters?.(parsedFilters);
|
||||
this.bookFilterComponent.onFiltersChanged?.();
|
||||
|
||||
const firstFilter = filterParams.split(',')[0];
|
||||
const [key, ...values] = firstFilter.split(':');
|
||||
const firstValue = values.join(':').split('|')[0];
|
||||
if (key && firstValue) {
|
||||
this.currentFilterLabel = this.capitalize(key) + ': ' + firstValue;
|
||||
} else {
|
||||
this.currentFilterLabel = 'All Books';
|
||||
}
|
||||
|
||||
this.rawFilterParamFromUrl = filterParams;
|
||||
this.settingFiltersFromUrl = false;
|
||||
} else {
|
||||
this.rawFilterParamFromUrl = null;
|
||||
this.currentFilterLabel = 'All Books';
|
||||
}
|
||||
|
||||
|
||||
this.entityViewPreferences = user.userSettings?.entityViewPreferences;
|
||||
const globalPrefs = this.entityViewPreferences?.global;
|
||||
const currentEntityTypeStr = this.entityType ? this.entityType.toString().toUpperCase() : undefined;
|
||||
this.coverScaleManager.scaleFactor = user.userSettings.entityViewPreferences?.global?.coverSize ?? 1.0;
|
||||
|
||||
const override = this.entityViewPreferences?.overrides?.find(o =>
|
||||
o.entityType?.toUpperCase() === currentEntityTypeStr &&
|
||||
o.entityId === this.entity?.id
|
||||
);
|
||||
|
||||
const effectivePrefs = override?.preferences ?? globalPrefs ?? {
|
||||
sortKey: 'addedOn',
|
||||
sortDir: 'ASC',
|
||||
view: 'GRID'
|
||||
};
|
||||
|
||||
const userSortKey = effectivePrefs.sortKey;
|
||||
const userSortDir = effectivePrefs.sortDir?.toUpperCase() === 'DESC'
|
||||
? SortDirection.DESCENDING
|
||||
: SortDirection.ASCENDING;
|
||||
|
||||
const matchedSort = this.bookSorter.sortOptions.find(opt => opt.field === userSortKey) || this.bookSorter.sortOptions.find(opt => opt.field === sortParam);
|
||||
|
||||
this.bookSorter.selectedSort = matchedSort ? {
|
||||
label: matchedSort.label,
|
||||
field: matchedSort.field,
|
||||
direction: userSortDir ?? (
|
||||
directionParam?.toUpperCase() === SORT_DIRECTION.DESCENDING
|
||||
? SortDirection.DESCENDING
|
||||
: SortDirection.ASCENDING
|
||||
)
|
||||
} : {
|
||||
label: 'Added On',
|
||||
field: 'addedOn',
|
||||
direction: SortDirection.DESCENDING
|
||||
};
|
||||
|
||||
const fromParam = paramMap.get(QUERY_PARAMS.FROM);
|
||||
this.currentViewMode = fromParam === 'toggle'
|
||||
? (viewParam === VIEW_MODES.TABLE || viewParam === VIEW_MODES.GRID
|
||||
? viewParam
|
||||
: VIEW_MODES.GRID)
|
||||
: (effectivePrefs.view?.toLowerCase() ?? VIEW_MODES.GRID);
|
||||
|
||||
this.bookFilterComponent.showFilters = sidebarParam === 'true' || (sidebarParam === null && this.filterVisibility);
|
||||
|
||||
this.bookSorter.updateSortOptions();
|
||||
|
||||
if (this.lastAppliedSort?.field !== this.bookSorter.selectedSort.field || this.lastAppliedSort?.direction !== this.bookSorter.selectedSort.direction) {
|
||||
this.lastAppliedSort = {...this.bookSorter.selectedSort};
|
||||
this.applySortOption(this.bookSorter.selectedSort);
|
||||
}
|
||||
|
||||
const queryParams: any = {
|
||||
[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,
|
||||
[QUERY_PARAMS.SIDEBAR]: this.bookFilterComponent.showFilters.toString(),
|
||||
[QUERY_PARAMS.FILTER]: Object.entries(parsedFilters).map(([k, v]) => `${k}:${v.join('|')}`).join(',')
|
||||
};
|
||||
|
||||
const currentParams = this.activatedRoute.snapshot.queryParams;
|
||||
const changed = Object.keys(queryParams).some(k => currentParams[k] !== queryParams[k]);
|
||||
|
||||
if (changed) {
|
||||
this.router.navigate([], {
|
||||
queryParams,
|
||||
replaceUrl: true
|
||||
});
|
||||
}
|
||||
|
||||
this.changeDetectorRef.detectChanges();
|
||||
});
|
||||
|
||||
this.bookFilterComponent.filterSelected.subscribe((filters: Record<string, any> | null) => {
|
||||
if (this.settingFiltersFromUrl) return;
|
||||
|
||||
this.selectedFilter.next(filters);
|
||||
this.rawFilterParamFromUrl = null;
|
||||
|
||||
const hasSidebarFilters = !!filters && Object.keys(filters).length > 0;
|
||||
this.currentFilterLabel = hasSidebarFilters ? 'All Books (Filtered)' : 'All Books';
|
||||
});
|
||||
|
||||
this.bookFilterComponent.filterModeChanged.subscribe((mode: 'and' | 'or') => {
|
||||
this.selectedFilterMode.next(mode);
|
||||
});
|
||||
|
||||
this.searchTerm$.subscribe(term => {
|
||||
this.hasSearchTerm = !!term && term.trim().length > 0;
|
||||
});
|
||||
}
|
||||
|
||||
toggleTableGrid(): void {
|
||||
this.currentViewMode = this.currentViewMode === VIEW_MODES.GRID ? VIEW_MODES.TABLE : VIEW_MODES.GRID;
|
||||
this.router.navigate([], {
|
||||
queryParams: {view: this.currentViewMode},
|
||||
queryParamsHandling: 'merge',
|
||||
replaceUrl: true
|
||||
});
|
||||
private isLibrary(entity: Library | Shelf): entity is Library {
|
||||
return (entity as Library).paths !== undefined;
|
||||
}
|
||||
|
||||
get viewIcon(): string {
|
||||
@@ -253,6 +345,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
|
||||
map(params => {
|
||||
const libraryId = Number(params.get('libraryId') || NaN);
|
||||
const shelfId = Number(params.get('shelfId') || NaN);
|
||||
|
||||
if (!isNaN(libraryId)) {
|
||||
this.entityType = EntityType.LIBRARY;
|
||||
return {entityId: libraryId, entityType: EntityType.LIBRARY};
|
||||
@@ -260,6 +353,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
|
||||
this.entityType = EntityType.SHELF;
|
||||
return {entityId: shelfId, entityType: EntityType.SHELF};
|
||||
} else {
|
||||
this.entityType = EntityType.ALL_BOOKS;
|
||||
return {entityId: NaN, entityType: EntityType.ALL_BOOKS};
|
||||
}
|
||||
})
|
||||
@@ -267,129 +361,45 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
|
||||
}
|
||||
|
||||
private fetchEntity(entityId: number, entityType: EntityType): Observable<Library | Shelf | null> {
|
||||
if (entityType == EntityType.LIBRARY) {
|
||||
return this.fetchLibrary(entityId);
|
||||
} else if (EntityType.SHELF) {
|
||||
return this.fetchShelf(entityId);
|
||||
switch (entityType) {
|
||||
case EntityType.LIBRARY:
|
||||
return this.fetchLibrary(entityId);
|
||||
case EntityType.SHELF:
|
||||
return this.fetchShelf(entityId);
|
||||
default:
|
||||
return of(null);
|
||||
}
|
||||
return of(null);
|
||||
}
|
||||
|
||||
private fetchBooksByEntity(entityId: number, entityType: EntityType): Observable<BookState> {
|
||||
if (entityType == EntityType.LIBRARY) {
|
||||
return this.fetchBooksByLibrary(entityId);
|
||||
} else if (entityType == EntityType.SHELF) {
|
||||
return this.fetchBooksByShelf(entityId);
|
||||
} else {
|
||||
return this.fetchAllBooks();
|
||||
switch (entityType) {
|
||||
case EntityType.LIBRARY:
|
||||
return this.fetchBooks(book => book.libraryId === entityId);
|
||||
case EntityType.SHELF:
|
||||
return this.fetchBooks(book =>
|
||||
book.shelves?.some(shelf => shelf.id === entityId) ?? false
|
||||
);
|
||||
case EntityType.ALL_BOOKS:
|
||||
default:
|
||||
return this.fetchAllBooks();
|
||||
}
|
||||
}
|
||||
|
||||
private fetchBooksByLibrary(libraryId: number): Observable<BookState> {
|
||||
return this.fetchBooks(book => book.libraryId === libraryId);
|
||||
}
|
||||
|
||||
private fetchBooksByShelf(shelfId: number): Observable<BookState> {
|
||||
return this.fetchBooks(book => {
|
||||
return book.shelves?.some(shelf => shelf.id === shelfId) ?? false;
|
||||
});
|
||||
}
|
||||
|
||||
private fetchAllBooks(): Observable<BookState> {
|
||||
return this.bookService.bookState$.pipe(
|
||||
map(bookState => this.processBookState(bookState)),
|
||||
switchMap(bookState => this.headerFilter(bookState)),
|
||||
switchMap(bookState => this.sideBarFilter(bookState))
|
||||
switchMap(bookState => this.applyBookFilters(bookState))
|
||||
);
|
||||
}
|
||||
|
||||
private fetchUnshelvedBooks(): Observable<BookState> {
|
||||
return this.bookService.bookState$.pipe(
|
||||
map(bookState => {
|
||||
const unshelvedBooks = (bookState.books || []).filter(book =>
|
||||
!book.shelves || book.shelves.length === 0
|
||||
);
|
||||
return {
|
||||
...bookState,
|
||||
books: unshelvedBooks
|
||||
};
|
||||
}),
|
||||
map(bookState => ({
|
||||
...bookState,
|
||||
books: (bookState.books || []).filter(book => !book.shelves || book.shelves.length === 0)
|
||||
})),
|
||||
map(bookState => this.processBookState(bookState)),
|
||||
switchMap(bookState => this.headerFilter(bookState)),
|
||||
switchMap(bookState => this.sideBarFilter(bookState))
|
||||
);
|
||||
}
|
||||
|
||||
private sideBarFilter(bookState: BookState): Observable<BookState> {
|
||||
return combineLatest([this.selectedFilter, this.selectedFilterMode]).pipe(
|
||||
map(([activeFilters, mode]) => {
|
||||
if (!activeFilters) return bookState;
|
||||
const filteredBooks = (bookState.books || []).filter(book => {
|
||||
const matches = Object.entries(activeFilters).map(([filterType, filterValues]) => {
|
||||
if (!Array.isArray(filterValues) || filterValues.length === 0) {
|
||||
return mode === 'or';
|
||||
}
|
||||
switch (filterType) {
|
||||
case 'author':
|
||||
return mode === 'and'
|
||||
? filterValues.every(val => book.metadata?.authors?.includes(val))
|
||||
: filterValues.some(val => book.metadata?.authors?.includes(val));
|
||||
case 'category':
|
||||
return mode === 'and'
|
||||
? filterValues.every(val => book.metadata?.categories?.includes(val))
|
||||
: filterValues.some(val => book.metadata?.categories?.includes(val));
|
||||
case 'publisher':
|
||||
return mode === 'and'
|
||||
? filterValues.every(val => book.metadata?.publisher === val)
|
||||
: filterValues.some(val => book.metadata?.publisher === val);
|
||||
case 'series':
|
||||
return mode === 'and'
|
||||
? filterValues.every(val => book.metadata?.seriesName === val)
|
||||
: filterValues.some(val => book.metadata?.seriesName === val);
|
||||
case 'amazonRating':
|
||||
return filterValues.some(range => isRatingInRange(book.metadata?.amazonRating, range));
|
||||
case 'goodreadsRating':
|
||||
return filterValues.some(range => isRatingInRange(book.metadata?.goodreadsRating, range));
|
||||
case 'hardcoverRating':
|
||||
return filterValues.some(range => isRatingInRange(book.metadata?.hardcoverRating, range));
|
||||
case 'publishedDate':
|
||||
return filterValues.includes(new Date(book.metadata?.publishedDate || '').getFullYear());
|
||||
case 'fileSize':
|
||||
return filterValues.some(range => isFileSizeInRange(book.fileSizeKb, range));
|
||||
case 'shelfStatus':
|
||||
const shelved = book.shelves && book.shelves.length > 0 ? 'shelved' : 'unshelved';
|
||||
return filterValues.includes(shelved);
|
||||
case 'pageCount':
|
||||
return filterValues.some(range => isPageCountInRange(book.metadata?.pageCount!, range));
|
||||
case 'language':
|
||||
return filterValues.includes(book.metadata?.language);
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
});
|
||||
return mode === 'and' ? matches.every(m => m) : matches.some(m => m);
|
||||
});
|
||||
return {...bookState, books: filteredBooks};
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
private headerFilter(bookState: BookState): Observable<BookState> {
|
||||
return this.searchTerm$.pipe(
|
||||
map(term => {
|
||||
if (term && term.trim() !== '') {
|
||||
const filteredBooks = bookState.books?.filter(book => {
|
||||
const matchesTitle = book.metadata?.title?.toLowerCase().includes(term.toLowerCase());
|
||||
const matchesSeries = book.metadata?.seriesName?.toLowerCase().includes(term.toLowerCase());
|
||||
const matchesAuthor = book.metadata?.authors.some(author =>
|
||||
author.toLowerCase().includes(term.toLowerCase())
|
||||
);
|
||||
return matchesTitle || matchesSeries || matchesAuthor;
|
||||
}) || null;
|
||||
return {...bookState, books: filteredBooks};
|
||||
}
|
||||
return bookState;
|
||||
})
|
||||
switchMap(bookState => this.applyBookFilters(bookState))
|
||||
);
|
||||
}
|
||||
|
||||
@@ -398,19 +408,25 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
|
||||
map(bookState => {
|
||||
if (bookState.loaded && !bookState.error) {
|
||||
const filteredBooks = bookState.books?.filter(bookFilter) || [];
|
||||
const sortedBooks = this.sortService.applySort(filteredBooks, this.selectedSort!);
|
||||
const sortedBooks = this.sortService.applySort(filteredBooks, this.bookSorter.selectedSort!);
|
||||
return {...bookState, books: sortedBooks};
|
||||
}
|
||||
return bookState;
|
||||
}),
|
||||
switchMap(bookState => this.headerFilter(bookState)),
|
||||
switchMap(bookState => this.sideBarFilter(bookState))
|
||||
switchMap(bookState => this.applyBookFilters(bookState))
|
||||
);
|
||||
}
|
||||
|
||||
private applyBookFilters(bookState: BookState): Observable<BookState> {
|
||||
return this.headerFilter.filter(bookState).pipe(
|
||||
switchMap(filtered => this.sideBarFilter.filter(filtered)),
|
||||
switchMap(filtered => this.seriesCollapseFilter.filter(filtered))
|
||||
);
|
||||
}
|
||||
|
||||
private processBookState(bookState: BookState): BookState {
|
||||
if (bookState.loaded && !bookState.error) {
|
||||
const sortedBooks = this.sortService.applySort(bookState.books || [], this.selectedSort!);
|
||||
const sortedBooks = this.sortService.applySort(bookState.books || [], this.bookSorter.selectedSort!);
|
||||
return {...bookState, books: sortedBooks};
|
||||
}
|
||||
return bookState;
|
||||
@@ -461,20 +477,8 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
|
||||
}
|
||||
}
|
||||
|
||||
unshelfBooks() {
|
||||
if (this.entity) {
|
||||
this.bookService.updateBookShelves(this.selectedBooks, new Set(), new Set([this.entity.id])).subscribe(
|
||||
{
|
||||
next: () => {
|
||||
this.messageService.add({severity: 'info', summary: 'Success', detail: 'Books shelves updated'});
|
||||
this.selectedBooks = new Set<number>();
|
||||
},
|
||||
error: () => {
|
||||
this.messageService.add({severity: 'error', summary: 'Error', detail: 'Failed to update books shelves'});
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
onSeriesCollapseCheckboxChange(value: boolean): void {
|
||||
this.seriesCollapseFilter.setCollapsed(value);
|
||||
}
|
||||
|
||||
applySortOption(sortOption: SortOption): void {
|
||||
@@ -504,46 +508,8 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
|
||||
this.resetFilterSubject.next();
|
||||
}
|
||||
|
||||
openShelfAssigner() {
|
||||
this.dynamicDialogRef = this.dialogService.open(ShelfAssignerComponent, {
|
||||
header: `Update Books' Shelves`,
|
||||
modal: true,
|
||||
closable: true,
|
||||
contentStyle: {overflow: 'auto'},
|
||||
baseZIndex: 10,
|
||||
style: {
|
||||
position: 'absolute',
|
||||
top: '15%',
|
||||
},
|
||||
data: {
|
||||
isMultiBooks: true,
|
||||
bookIds: this.selectedBooks
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
updateMetadata() {
|
||||
this.dialogService.open(MetadataFetchOptionsComponent, {
|
||||
header: 'Metadata Refresh Options',
|
||||
modal: true,
|
||||
closable: true,
|
||||
data: {
|
||||
bookIds: Array.from(this.selectedBooks),
|
||||
metadataRefreshType: MetadataRefreshType.BOOKS
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
toggleFilterSidebar() {
|
||||
this.bookFilterComponent.showFilters = !this.bookFilterComponent.showFilters;
|
||||
|
||||
this.router.navigate([], {
|
||||
queryParams: {
|
||||
[QUERY_PARAMS.SIDEBAR]: this.bookFilterComponent.showFilters.toString()
|
||||
},
|
||||
queryParamsHandling: 'merge',
|
||||
replaceUrl: true
|
||||
});
|
||||
get hasSidebarFilters(): boolean {
|
||||
return this.selectedFilter && Object.keys(this.selectedFilter.getValue() || {}).length > 0;
|
||||
}
|
||||
|
||||
get isFilterActive(): boolean {
|
||||
@@ -557,212 +523,55 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
|
||||
this.clearSearch();
|
||||
}
|
||||
|
||||
sortBooks(field: string): void {
|
||||
const existingSort = this.sortOptions.find(opt => opt.field === field);
|
||||
if (!existingSort) return;
|
||||
|
||||
if (this.selectedSort?.field === field) {
|
||||
this.selectedSort = {
|
||||
...this.selectedSort,
|
||||
direction: this.selectedSort.direction === SortDirection.ASCENDING
|
||||
? SortDirection.DESCENDING
|
||||
: SortDirection.ASCENDING
|
||||
};
|
||||
} else {
|
||||
this.selectedSort = {
|
||||
label: existingSort.label,
|
||||
field: existingSort.field,
|
||||
direction: SortDirection.ASCENDING
|
||||
};
|
||||
}
|
||||
|
||||
this.updateSortOptions();
|
||||
this.applySortOption(this.selectedSort);
|
||||
|
||||
/*this.router.navigate([], {
|
||||
queryParams: {
|
||||
sort: this.selectedSort.field,
|
||||
direction: this.selectedSort.direction === SortDirection.ASCENDING
|
||||
? SORT_DIRECTION.ASCENDING
|
||||
: SORT_DIRECTION.DESCENDING
|
||||
},
|
||||
queryParamsHandling: 'merge',
|
||||
replaceUrl: true
|
||||
});*/
|
||||
}
|
||||
|
||||
updateSortOptions() {
|
||||
const directionIcon = this.selectedSort!.direction === SortDirection.ASCENDING ? 'pi pi-arrow-up' : 'pi pi-arrow-down';
|
||||
this.sortOptions = this.sortOptions.map((option) => ({
|
||||
...option,
|
||||
icon: option.field === this.selectedSort!.field ? directionIcon : '',
|
||||
}));
|
||||
}
|
||||
|
||||
private settingFiltersFromUrl = false;
|
||||
|
||||
ngAfterViewInit() {
|
||||
this.bookFilterComponent.filterSelected.subscribe((filters: Record<string, any> | null) => {
|
||||
if (this.settingFiltersFromUrl) return;
|
||||
|
||||
this.selectedFilter.next(filters);
|
||||
this.rawFilterParamFromUrl = null;
|
||||
|
||||
const hasSidebarFilters = !!filters && Object.keys(filters).length > 0;
|
||||
this.currentFilterLabel = hasSidebarFilters ? 'All Books (Filtered)' : 'All Books';
|
||||
});
|
||||
|
||||
this.bookFilterComponent.filterModeChanged.subscribe((mode: 'and' | 'or') => {
|
||||
this.selectedFilterMode.next(mode);
|
||||
});
|
||||
|
||||
this.searchTerm$.subscribe(term => {
|
||||
this.hasSearchTerm = !!term && term.trim().length > 0;
|
||||
});
|
||||
|
||||
this.activatedRoute.queryParamMap.subscribe(paramMap => {
|
||||
const viewParam = paramMap.get(QUERY_PARAMS.VIEW);
|
||||
const sortParam = paramMap.get(QUERY_PARAMS.SORT);
|
||||
const directionParam = paramMap.get(QUERY_PARAMS.DIRECTION);
|
||||
const sidebarParam = paramMap.get(QUERY_PARAMS.SIDEBAR);
|
||||
const rawFilterParam = paramMap.get(QUERY_PARAMS.FILTER);
|
||||
|
||||
const parsedFilters: Record<string, string[]> = {};
|
||||
|
||||
if (rawFilterParam) {
|
||||
this.settingFiltersFromUrl = true;
|
||||
|
||||
rawFilterParam.split(',').forEach(pair => {
|
||||
const [key, ...valueParts] = pair.split(':');
|
||||
const value = valueParts.join(':');
|
||||
if (key && value) {
|
||||
parsedFilters[key] = value.split('|').map(v => v.trim()).filter(Boolean);
|
||||
}
|
||||
});
|
||||
|
||||
this.selectedFilter.next(parsedFilters);
|
||||
this.bookFilterComponent.setFilters?.(parsedFilters);
|
||||
|
||||
const firstFilter = rawFilterParam.split(',')[0];
|
||||
const [key, ...values] = firstFilter.split(':');
|
||||
const firstValue = values.join(':').split('|')[0];
|
||||
if (key && firstValue) {
|
||||
this.currentFilterLabel = this.capitalize(key) + ': ' + firstValue;
|
||||
} else {
|
||||
this.currentFilterLabel = 'All Books';
|
||||
}
|
||||
|
||||
this.rawFilterParamFromUrl = rawFilterParam;
|
||||
this.settingFiltersFromUrl = false;
|
||||
} else {
|
||||
this.rawFilterParamFromUrl = null;
|
||||
this.currentFilterLabel = 'All Books';
|
||||
}
|
||||
|
||||
this.userService.userState$
|
||||
.pipe(
|
||||
filter((user): user is NonNullable<typeof user> => !!user),
|
||||
take(1)
|
||||
)
|
||||
.subscribe(user => {
|
||||
this.prefs = user.userSettings?.entityViewPreferences;
|
||||
const globalPrefs = this.prefs?.global;
|
||||
const currentEntityTypeStr = this.entityType ? this.entityType.toString().toUpperCase() : undefined;
|
||||
this.scaleFactor = user.userSettings.entityViewPreferences?.global?.coverSize ?? 1.0;
|
||||
|
||||
const override = this.prefs?.overrides?.find(o =>
|
||||
o.entityType?.toUpperCase() === currentEntityTypeStr &&
|
||||
o.entityId === this.entity?.id
|
||||
);
|
||||
|
||||
const effectivePrefs = override?.preferences ?? globalPrefs ?? {
|
||||
sortKey: 'addedOn',
|
||||
sortDir: 'ASC',
|
||||
view: 'GRID'
|
||||
};
|
||||
|
||||
const userSortKey = effectivePrefs.sortKey;
|
||||
const userSortDir = effectivePrefs.sortDir?.toUpperCase() === 'DESC'
|
||||
? SortDirection.DESCENDING
|
||||
: SortDirection.ASCENDING;
|
||||
|
||||
const matchedSort = this.sortOptions.find(opt => opt.field === sortParam)
|
||||
|| this.sortOptions.find(opt => opt.field === userSortKey);
|
||||
|
||||
this.selectedSort = matchedSort ? {
|
||||
label: matchedSort.label,
|
||||
field: matchedSort.field,
|
||||
direction: directionParam?.toUpperCase() === SORT_DIRECTION.DESCENDING
|
||||
? SortDirection.DESCENDING
|
||||
: SortDirection.ASCENDING
|
||||
} : {
|
||||
label: 'Added On',
|
||||
field: 'addedOn',
|
||||
direction: SortDirection.DESCENDING
|
||||
};
|
||||
|
||||
this.currentViewMode = (viewParam === VIEW_MODES.TABLE || viewParam === VIEW_MODES.GRID)
|
||||
? viewParam
|
||||
: effectivePrefs.view?.toLowerCase() ?? VIEW_MODES.GRID;
|
||||
|
||||
this.bookFilterComponent.showFilters = sidebarParam === 'true'
|
||||
|| (sidebarParam === null && this.filterVisibility);
|
||||
|
||||
this.updateSortOptions();
|
||||
|
||||
if (
|
||||
this.lastAppliedSort?.field !== this.selectedSort.field ||
|
||||
this.lastAppliedSort?.direction !== this.selectedSort.direction
|
||||
) {
|
||||
this.lastAppliedSort = { ...this.selectedSort };
|
||||
this.applySortOption(this.selectedSort);
|
||||
}
|
||||
|
||||
const queryParams: any = {
|
||||
[QUERY_PARAMS.VIEW]: this.currentViewMode,
|
||||
[QUERY_PARAMS.SORT]: this.selectedSort.field,
|
||||
[QUERY_PARAMS.DIRECTION]: this.selectedSort.direction === SortDirection.ASCENDING
|
||||
? SORT_DIRECTION.ASCENDING
|
||||
: SORT_DIRECTION.DESCENDING,
|
||||
[QUERY_PARAMS.SIDEBAR]: this.bookFilterComponent.showFilters.toString(),
|
||||
[QUERY_PARAMS.FILTER]: Object.entries(parsedFilters)
|
||||
.map(([k, v]) => `${k}:${v.join('|')}`)
|
||||
.join(',')
|
||||
};
|
||||
|
||||
const currentParams = this.activatedRoute.snapshot.queryParams;
|
||||
const changed = Object.keys(queryParams).some(k => currentParams[k] !== queryParams[k]);
|
||||
|
||||
if (changed) {
|
||||
this.router.navigate([], {
|
||||
queryParams,
|
||||
replaceUrl: true
|
||||
});
|
||||
}
|
||||
|
||||
this.cdr.detectChanges();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
capitalize(str: string): string {
|
||||
private capitalize(str: string): string {
|
||||
return str.charAt(0).toUpperCase() + str.slice(1);
|
||||
}
|
||||
|
||||
|
||||
get hasSidebarFilters(): boolean {
|
||||
return this.selectedFilter && Object.keys(this.selectedFilter.getValue() || {}).length > 0;
|
||||
toggleFilterSidebar() {
|
||||
this.bookFilterComponent.showFilters = !this.bookFilterComponent.showFilters;
|
||||
this.router.navigate([], {
|
||||
queryParams: {
|
||||
[QUERY_PARAMS.SIDEBAR]: this.bookFilterComponent.showFilters.toString()
|
||||
},
|
||||
queryParamsHandling: 'merge',
|
||||
replaceUrl: true
|
||||
});
|
||||
}
|
||||
|
||||
lockUnlockMetadata() {
|
||||
const count = this.selectedBooks.size;
|
||||
this.dynamicDialogRef = this.dialogService.open(LockUnlockMetadataDialogComponent, {
|
||||
header: `Lock or Unlock Metadata for ${count} Selected Book${count > 1 ? 's' : ''}`,
|
||||
modal: true,
|
||||
closable: true,
|
||||
data: {
|
||||
bookIds: Array.from(this.selectedBooks)
|
||||
toggleTableGrid(): void {
|
||||
this.currentViewMode = this.currentViewMode === VIEW_MODES.GRID ? VIEW_MODES.TABLE : VIEW_MODES.GRID;
|
||||
this.router.navigate([], {
|
||||
queryParams: {
|
||||
view: this.currentViewMode,
|
||||
[QUERY_PARAMS.FROM]: 'toggle'
|
||||
},
|
||||
queryParamsHandling: 'merge',
|
||||
replaceUrl: true
|
||||
});
|
||||
}
|
||||
|
||||
unshelfBooks() {
|
||||
if (!this.entity) return;
|
||||
this.bookService.updateBookShelves(this.selectedBooks, new Set(), new Set([this.entity.id])).subscribe({
|
||||
next: () => {
|
||||
this.messageService.add({severity: 'info', summary: 'Success', detail: 'Books shelves updated'});
|
||||
this.selectedBooks.clear();
|
||||
},
|
||||
error: () => {
|
||||
this.messageService.add({severity: 'error', summary: 'Error', detail: 'Failed to update books shelves'});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
openShelfAssigner(): void {
|
||||
this.dynamicDialogRef = this.dialogHelperService.openShelfAssigner(this.selectedBooks);
|
||||
}
|
||||
|
||||
lockUnlockMetadata(): void {
|
||||
this.dynamicDialogRef = this.dialogHelperService.openLockUnlockMetadataDialog(this.selectedBooks);
|
||||
}
|
||||
|
||||
updateMetadata(): void {
|
||||
this.dialogHelperService.openMetadataRefreshDialog(this.selectedBooks);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,6 +12,18 @@
|
||||
loading="lazy"
|
||||
(load)="onImageLoad()"/>
|
||||
|
||||
@if (book.metadata?.seriesNumber != null) {
|
||||
<div class="series-number-overlay">
|
||||
#{{ book.metadata?.seriesNumber }}
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (book.seriesCount != null && book.seriesCount! > 1) {
|
||||
<div class="series-count-overlay">
|
||||
{{ book.seriesCount }}
|
||||
</div>
|
||||
}
|
||||
|
||||
<p-button [rounded]="true" icon="pi pi-info" class="info-btn" (click)="openBookInfo(book)"></p-button>
|
||||
<p-button [hidden]="readButtonHidden" [rounded]="true" icon="pi pi-book" class="read-btn" (click)="readBook(book)"></p-button>
|
||||
|
||||
|
||||
@@ -136,6 +136,35 @@
|
||||
opacity: 0.8;
|
||||
}
|
||||
|
||||
.series-number-overlay {
|
||||
position: absolute;
|
||||
top: 4px;
|
||||
left: 4px;
|
||||
background-color: rgba(0, 0, 0, 0.7);
|
||||
color: white;
|
||||
font-size: 0.75rem;
|
||||
padding: 1px 3px;
|
||||
border-radius: 3px;
|
||||
z-index: 3;
|
||||
}
|
||||
|
||||
.series-count-overlay {
|
||||
position: absolute;
|
||||
top: 4px;
|
||||
right: 4px;
|
||||
background-color: var(--primary-color);
|
||||
color: var(--primary-text-color-dark);
|
||||
font-size: 0.75rem;
|
||||
padding: 1px 6px;
|
||||
border-radius: 3px;
|
||||
z-index: 3;
|
||||
white-space: nowrap;
|
||||
user-select: none;
|
||||
font-weight: 600;
|
||||
text-align: center;
|
||||
box-shadow: 0 0 4px rgba(0, 0, 0, 0.15);
|
||||
}
|
||||
|
||||
::ng-deep .progress-incomplete .p-progressbar-value {
|
||||
background-color: #3b82f6;
|
||||
}
|
||||
|
||||
@@ -35,6 +35,7 @@ export class BookCardComponent implements OnInit {
|
||||
@Input() isSelected: boolean = false;
|
||||
@Input() bottomBarHidden: boolean = false;
|
||||
@Input() readButtonHidden: boolean = false;
|
||||
@Input() isSeriesCollapsed: boolean = false;
|
||||
|
||||
items: MenuItem[] | undefined;
|
||||
isHovered: boolean = false;
|
||||
|
||||
+6
-6
@@ -9,9 +9,9 @@
|
||||
optionValue="value"
|
||||
class="text-sm"
|
||||
allowEmpty="false"
|
||||
styleClass="h-8"></p-selectButton>
|
||||
styleClass="h-8"></p-selectButton>
|
||||
</div>
|
||||
<p-accordion [value]="0">
|
||||
<p-accordion [value]="expandedPanels">
|
||||
@for (filterType of filterTypes; track filterType; let i = $index) {
|
||||
<p-accordion-panel [value]="i">
|
||||
<p-accordion-header>
|
||||
@@ -31,10 +31,10 @@
|
||||
<div>
|
||||
<div
|
||||
class="cursor-pointer transition-colors duration-200 ease-in-out pb-1 flex items-center gap-2"
|
||||
[ngClass]="{
|
||||
'text-[var(--primary-color)]':
|
||||
activeFilters[filterType]?.includes(filter.value?.id || filter.value)
|
||||
}"
|
||||
[ngClass]="{
|
||||
'text-[var(--primary-color)]':
|
||||
activeFilters[filterType]?.includes(filter.value?.id || filter.value)
|
||||
}"
|
||||
(click)="handleFilterClick(filterType, filter.value?.id || filter.value)">
|
||||
<p-badge [value]="filter.bookCount"></p-badge>
|
||||
@if (filterType === 'amazonRating') {
|
||||
|
||||
+20
-29
@@ -7,7 +7,7 @@ import {Shelf} from '../../../model/shelf.model';
|
||||
import {EntityType} from '../book-browser.component';
|
||||
import {Book} from '../../../model/book.model';
|
||||
import {Accordion, AccordionContent, AccordionHeader, AccordionPanel} from 'primeng/accordion';
|
||||
import { AsyncPipe, NgClass, TitleCasePipe } from '@angular/common';
|
||||
import {AsyncPipe, NgClass, TitleCasePipe} from '@angular/common';
|
||||
import {Badge} from 'primeng/badge';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {SelectButton} from 'primeng/selectbutton';
|
||||
@@ -44,27 +44,6 @@ export const pageCountRanges = [
|
||||
{id: '1000plus', label: '1000+ pages', min: 1000, max: Infinity}
|
||||
];
|
||||
|
||||
export function isRatingInRange(rating: number | undefined | null, rangeId: string): boolean {
|
||||
if (rating == null) return false;
|
||||
const range = ratingRanges.find(r => r.id === rangeId);
|
||||
if (!range) return false;
|
||||
return rating >= range.min && rating < range.max;
|
||||
}
|
||||
|
||||
export function isFileSizeInRange(fileSizeKb: number | undefined, rangeId: string): boolean {
|
||||
if (fileSizeKb == null) return false;
|
||||
const range = fileSizeRanges.find(r => r.id === rangeId);
|
||||
if (!range) return false;
|
||||
return fileSizeKb >= range.min && fileSizeKb < range.max;
|
||||
}
|
||||
|
||||
export function isPageCountInRange(pageCount: number | undefined, rangeId: string): boolean {
|
||||
if (pageCount == null) return false;
|
||||
const range = pageCountRanges.find(r => r.id === rangeId);
|
||||
if (!range) return false;
|
||||
return pageCount >= range.min && pageCount < range.max;
|
||||
}
|
||||
|
||||
const getLanguageFilter = (book: Book) => {
|
||||
const lang = book.metadata?.language;
|
||||
return lang ? [{id: lang, name: lang}] : [];
|
||||
@@ -116,7 +95,7 @@ function getPageCountRangeFilters(pageCount?: number) {
|
||||
TitleCasePipe,
|
||||
FormsModule,
|
||||
SelectButton
|
||||
]
|
||||
]
|
||||
})
|
||||
export class BookFilterComponent implements OnInit {
|
||||
@Output() filterSelected = new EventEmitter<Record<string, any> | null>();
|
||||
@@ -131,11 +110,11 @@ export class BookFilterComponent implements OnInit {
|
||||
filterStreams: Record<string, Observable<Filter<any>[]>> = {};
|
||||
filterTypes: string[] = [];
|
||||
filterModeOptions = [
|
||||
{ label: 'AND', value: 'and' },
|
||||
{ label: 'OR', value: 'or' }
|
||||
{label: 'AND', value: 'and'},
|
||||
{label: 'OR', value: 'or'}
|
||||
];
|
||||
private _selectedFilterMode: 'and' | 'or' = 'and';
|
||||
|
||||
expandedPanels: number = 0;
|
||||
readonly filterLabels: Record<string, string> = {
|
||||
author: 'Author',
|
||||
category: 'Category',
|
||||
@@ -175,6 +154,8 @@ export class BookFilterComponent implements OnInit {
|
||||
if (this.resetFilter$) {
|
||||
this.resetFilter$.subscribe(() => this.clearActiveFilter());
|
||||
}
|
||||
|
||||
this.setExpandedPanels();
|
||||
}
|
||||
|
||||
private getFilterStream<T>(
|
||||
@@ -241,7 +222,7 @@ export class BookFilterComponent implements OnInit {
|
||||
if (Object.keys(this.activeFilters).length === 0) {
|
||||
this.filterSelected.emit(null);
|
||||
} else {
|
||||
this.filterSelected.emit({ ...this.activeFilters });
|
||||
this.filterSelected.emit({...this.activeFilters});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -255,12 +236,22 @@ export class BookFilterComponent implements OnInit {
|
||||
this.activeFilters[key] = [value];
|
||||
}
|
||||
}
|
||||
|
||||
this.filterSelected.emit({ ...this.activeFilters });
|
||||
this.filterSelected.emit({...this.activeFilters});
|
||||
}
|
||||
|
||||
clearActiveFilter() {
|
||||
this.activeFilters = {};
|
||||
this.filterSelected.emit(null);
|
||||
}
|
||||
|
||||
setExpandedPanels(): void {
|
||||
const firstActiveIndex = this.filterTypes.findIndex(
|
||||
type => this.activeFilters[type]?.length
|
||||
);
|
||||
this.expandedPanels = firstActiveIndex !== -1 ? firstActiveIndex : 0;
|
||||
}
|
||||
|
||||
onFiltersChanged(): void {
|
||||
this.setExpandedPanels();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
import {BookState} from '../../../model/state/book-state.model';
|
||||
import {Observable} from 'rxjs';
|
||||
|
||||
export interface BookFilter {
|
||||
filter(bookState: BookState): Observable<BookState>;
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import {BookFilter} from './BookFilter';
|
||||
import {BookState} from '../../../model/state/book-state.model';
|
||||
import {Observable} from 'rxjs';
|
||||
import {map} from 'rxjs/operators';
|
||||
|
||||
export class HeaderFilter implements BookFilter {
|
||||
|
||||
constructor(private searchTerm$: Observable<any>) {
|
||||
}
|
||||
|
||||
filter(bookState: BookState): Observable<BookState> {
|
||||
return this.searchTerm$.pipe(
|
||||
map(term => {
|
||||
if (term && term.trim() !== '') {
|
||||
const filteredBooks = bookState.books?.filter(book => {
|
||||
const matchesTitle = book.metadata?.title?.toLowerCase().includes(term.toLowerCase());
|
||||
const matchesSeries = book.metadata?.seriesName?.toLowerCase().includes(term.toLowerCase());
|
||||
const matchesAuthor = book.metadata?.authors.some(author =>
|
||||
author.toLowerCase().includes(term.toLowerCase())
|
||||
);
|
||||
return matchesTitle || matchesSeries || matchesAuthor;
|
||||
}) || null;
|
||||
return {...bookState, books: filteredBooks};
|
||||
}
|
||||
return bookState;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import { BookFilter } from './BookFilter';
|
||||
import { Observable, BehaviorSubject } from 'rxjs';
|
||||
import { BookState } from '../../../model/state/book-state.model';
|
||||
import { map, debounceTime, filter, take } from 'rxjs/operators';
|
||||
import { Book } from '../../../model/book.model';
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { MessageService } from 'primeng/api';
|
||||
import { UserService } from '../../../../settings/user-management/user.service';
|
||||
|
||||
@Injectable()
|
||||
export class SeriesCollapseFilter implements BookFilter {
|
||||
private readonly userService = inject(UserService);
|
||||
private readonly messageService = inject(MessageService);
|
||||
|
||||
private readonly seriesCollapseSubject = new BehaviorSubject<boolean>(false);
|
||||
readonly seriesCollapse$ = this.seriesCollapseSubject.asObservable();
|
||||
|
||||
private hasUserToggled = false;
|
||||
|
||||
constructor() {
|
||||
this.userService.userState$
|
||||
.pipe(filter(user => !!user), take(1))
|
||||
.subscribe(user => {
|
||||
const prefs = user.userSettings?.entityViewPreferences;
|
||||
const initialCollapsed = prefs?.global?.seriesCollapsed ?? false;
|
||||
this.seriesCollapseSubject.next(initialCollapsed);
|
||||
});
|
||||
|
||||
this.seriesCollapse$
|
||||
.pipe(debounceTime(500))
|
||||
.subscribe(isCollapsed => {
|
||||
if (this.hasUserToggled) {
|
||||
this.persistCollapsePreference(isCollapsed);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
get isSeriesCollapsed(): boolean {
|
||||
return this.seriesCollapseSubject.value;
|
||||
}
|
||||
|
||||
setCollapsed(value: boolean): void {
|
||||
this.hasUserToggled = true;
|
||||
this.seriesCollapseSubject.next(value);
|
||||
}
|
||||
|
||||
filter(bookState: BookState): Observable<BookState> {
|
||||
return this.seriesCollapse$.pipe(
|
||||
map(isCollapsed => {
|
||||
if (!isCollapsed || !bookState.books) return bookState;
|
||||
|
||||
const seenSeries = new Set<string>();
|
||||
const collapsedBooks: Book[] = [];
|
||||
|
||||
for (const book of bookState.books) {
|
||||
const name = book.metadata?.seriesName?.trim();
|
||||
if (name && !seenSeries.has(name)) {
|
||||
const count = bookState.books.filter(b => b.metadata?.seriesName?.trim() === name).length;
|
||||
collapsedBooks.push({
|
||||
...book,
|
||||
seriesCount: count,
|
||||
});
|
||||
seenSeries.add(name);
|
||||
} else if (!name) {
|
||||
collapsedBooks.push(book);
|
||||
}
|
||||
}
|
||||
|
||||
return { ...bookState, books: collapsedBooks };
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
private persistCollapsePreference(isCollapsed: boolean): void {
|
||||
const user = this.userService.getCurrentUser();
|
||||
const prefs = user?.userSettings?.entityViewPreferences;
|
||||
if (!user || !prefs) return;
|
||||
|
||||
prefs.global = prefs.global ?? {};
|
||||
prefs.global.seriesCollapsed = isCollapsed;
|
||||
|
||||
this.userService.updateUserSetting(user.id, 'entityViewPreferences', prefs);
|
||||
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'Preference Saved',
|
||||
detail: `Series collapse set to ${isCollapsed ? 'enabled' : 'disabled'}.`
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import {Observable, combineLatest, of} from 'rxjs';
|
||||
import {map} from 'rxjs/operators';
|
||||
import {BookFilter} from './BookFilter';
|
||||
import {BookState} from '../../../model/state/book-state.model';
|
||||
import {fileSizeRanges, pageCountRanges, ratingRanges} from '../book-filter/book-filter.component';
|
||||
|
||||
export function isRatingInRange(rating: number | undefined | null, rangeId: string): boolean {
|
||||
if (rating == null) return false;
|
||||
const range = ratingRanges.find(r => r.id === rangeId);
|
||||
if (!range) return false;
|
||||
return rating >= range.min && rating < range.max;
|
||||
}
|
||||
|
||||
export function isFileSizeInRange(fileSizeKb: number | undefined, rangeId: string): boolean {
|
||||
if (fileSizeKb == null) return false;
|
||||
const range = fileSizeRanges.find(r => r.id === rangeId);
|
||||
if (!range) return false;
|
||||
return fileSizeKb >= range.min && fileSizeKb < range.max;
|
||||
}
|
||||
|
||||
export function isPageCountInRange(pageCount: number | undefined, rangeId: string): boolean {
|
||||
if (pageCount == null) return false;
|
||||
const range = pageCountRanges.find(r => r.id === rangeId);
|
||||
if (!range) return false;
|
||||
return pageCount >= range.min && pageCount < range.max;
|
||||
}
|
||||
|
||||
export class SideBarFilter implements BookFilter {
|
||||
|
||||
constructor(private selectedFilter$: Observable<any>, private selectedFilterMode$: Observable<'and' | 'or'>) {
|
||||
}
|
||||
|
||||
filter(bookState: BookState): Observable<BookState> {
|
||||
return combineLatest([this.selectedFilter$, this.selectedFilterMode$]).pipe(
|
||||
map(([activeFilters, mode]) => {
|
||||
if (!activeFilters) return bookState;
|
||||
const filteredBooks = (bookState.books || []).filter(book => {
|
||||
const matches = Object.entries(activeFilters).map(([filterType, filterValues]) => {
|
||||
if (!Array.isArray(filterValues) || filterValues.length === 0) {
|
||||
return mode === 'or';
|
||||
}
|
||||
switch (filterType) {
|
||||
case 'author':
|
||||
return mode === 'and'
|
||||
? filterValues.every(val => book.metadata?.authors?.includes(val))
|
||||
: filterValues.some(val => book.metadata?.authors?.includes(val));
|
||||
case 'category':
|
||||
return mode === 'and'
|
||||
? filterValues.every(val => book.metadata?.categories?.includes(val))
|
||||
: filterValues.some(val => book.metadata?.categories?.includes(val));
|
||||
case 'publisher':
|
||||
return mode === 'and'
|
||||
? filterValues.every(val => book.metadata?.publisher === val)
|
||||
: filterValues.some(val => book.metadata?.publisher === val);
|
||||
case 'series':
|
||||
return mode === 'and'
|
||||
? filterValues.every(val => book.metadata?.seriesName === val)
|
||||
: filterValues.some(val => book.metadata?.seriesName === val);
|
||||
case 'amazonRating':
|
||||
return filterValues.some(range => isRatingInRange(book.metadata?.amazonRating, range));
|
||||
case 'goodreadsRating':
|
||||
return filterValues.some(range => isRatingInRange(book.metadata?.goodreadsRating, range));
|
||||
case 'hardcoverRating':
|
||||
return filterValues.some(range => isRatingInRange(book.metadata?.hardcoverRating, range));
|
||||
case 'publishedDate':
|
||||
return filterValues.includes(new Date(book.metadata?.publishedDate || '').getFullYear());
|
||||
case 'fileSize':
|
||||
return filterValues.some(range => isFileSizeInRange(book.fileSizeKb, range));
|
||||
case 'shelfStatus':
|
||||
const shelved = book.shelves && book.shelves.length > 0 ? 'shelved' : 'unshelved';
|
||||
return filterValues.includes(shelved);
|
||||
case 'pageCount':
|
||||
return filterValues.some(range => isPageCountInRange(book.metadata?.pageCount!, range));
|
||||
case 'language':
|
||||
return filterValues.includes(book.metadata?.language);
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
});
|
||||
return mode === 'and' ? matches.every(m => m) : matches.some(m => m);
|
||||
});
|
||||
return {...bookState, books: filteredBooks};
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import {SortDirection, SortOption} from '../../../model/sort.model';
|
||||
|
||||
|
||||
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: 'Author', field: 'author', direction: SortDirection.ASCENDING },
|
||||
{ label: 'Last Read', field: 'lastReadTime', 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 },
|
||||
];
|
||||
|
||||
constructor(private applySortOption: (sort: SortOption) => void) {}
|
||||
|
||||
sortBooks(field: string): void {
|
||||
const existingSort = this.sortOptions.find(opt => opt.field === field);
|
||||
if (!existingSort) return;
|
||||
|
||||
if (this.selectedSort?.field === field) {
|
||||
this.selectedSort = {
|
||||
...this.selectedSort,
|
||||
direction: this.selectedSort.direction === SortDirection.ASCENDING
|
||||
? SortDirection.DESCENDING
|
||||
: SortDirection.ASCENDING
|
||||
};
|
||||
} else {
|
||||
this.selectedSort = {
|
||||
label: existingSort.label,
|
||||
field: existingSort.field,
|
||||
direction: SortDirection.ASCENDING
|
||||
};
|
||||
}
|
||||
|
||||
this.updateSortOptions();
|
||||
this.applySortOption(this.selectedSort);
|
||||
|
||||
/*this.router.navigate([], {
|
||||
queryParams: {
|
||||
sort: this.selectedSort.field,
|
||||
direction: this.selectedSort.direction === SortDirection.ASCENDING
|
||||
? SORT_DIRECTION.ASCENDING
|
||||
: SORT_DIRECTION.DESCENDING
|
||||
},
|
||||
queryParamsHandling: 'merge',
|
||||
replaceUrl: true
|
||||
});*/
|
||||
}
|
||||
|
||||
updateSortOptions() {
|
||||
const directionIcon = this.selectedSort!.direction === SortDirection.ASCENDING ? 'pi pi-arrow-up' : 'pi pi-arrow-down';
|
||||
this.sortOptions = this.sortOptions.map((option) => ({
|
||||
...option,
|
||||
icon: option.field === this.selectedSort!.field ? directionIcon : '',
|
||||
}));
|
||||
}
|
||||
}
|
||||
@@ -113,7 +113,6 @@ export class PdfViewerComponent implements OnInit, OnDestroy {
|
||||
|
||||
onPdfPagesLoaded(event: any): void {
|
||||
this.totalPages = event.pagesCount;
|
||||
console.log('Total pages loaded:', this.totalPages);
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
|
||||
-6
@@ -98,8 +98,6 @@ export class MetadataEditorComponent implements OnInit {
|
||||
descriptionLocked: new FormControl(false),
|
||||
pageCountLocked: new FormControl(false),
|
||||
languageLocked: new FormControl(false),
|
||||
ratingLocked: new FormControl(false),
|
||||
reviewCountLocked: new FormControl(false),
|
||||
asinLocked: new FormControl(false),
|
||||
amazonRatingLocked: new FormControl(false),
|
||||
amazonReviewCountLocked: new FormControl(false),
|
||||
@@ -166,8 +164,6 @@ export class MetadataEditorComponent implements OnInit {
|
||||
descriptionLocked: metadata.descriptionLocked || false,
|
||||
pageCountLocked: metadata.pageCountLocked || false,
|
||||
languageLocked: metadata.languageLocked || false,
|
||||
ratingLocked: metadata.ratingLocked || false,
|
||||
reviewCountLocked: metadata.reviewCountLocked || false,
|
||||
asinLocked: metadata.asinLocked || false,
|
||||
amazonRatingLocked: metadata.amazonRatingLocked || false,
|
||||
amazonReviewCountLocked: metadata.amazonReviewCountLocked || false,
|
||||
@@ -340,9 +336,7 @@ export class MetadataEditorComponent implements OnInit {
|
||||
descriptionLocked: this.metadataForm.get('descriptionLocked')?.value,
|
||||
pageCountLocked: this.metadataForm.get('pageCountLocked')?.value,
|
||||
languageLocked: this.metadataForm.get('languageLocked')?.value,
|
||||
ratingLocked: this.metadataForm.get('ratingLocked')?.value,
|
||||
asinLocked: this.metadataForm.get('asinLocked')?.value,
|
||||
reviewCountLocked: this.metadataForm.get('reviewCountLocked')?.value,
|
||||
amazonRatingLocked: this.metadataForm.get('amazonRatingLocked')?.value,
|
||||
amazonReviewCountLocked: this.metadataForm.get('amazonReviewCountLocked')?.value,
|
||||
goodreadsIdLocked: this.metadataForm.get('goodreadsIdLocked')?.value,
|
||||
|
||||
+50
-39
@@ -10,7 +10,12 @@
|
||||
loading="lazy"
|
||||
width="225"
|
||||
style="min-width: 225px;"
|
||||
/>
|
||||
/>
|
||||
@if (metadata?.seriesNumber != null) {
|
||||
<div class="series-number-overlay">
|
||||
#{{ metadata?.seriesNumber }}
|
||||
</div>
|
||||
}
|
||||
@if (getProgressPercent() !== null) {
|
||||
<p-progressBar
|
||||
[value]="getProgressPercent()"
|
||||
@@ -51,7 +56,9 @@
|
||||
filter: 'author:' + author
|
||||
}"
|
||||
>{{ author }}</a>
|
||||
@if (!isLast) {<span>, </span>}
|
||||
@if (!isLast) {
|
||||
<span>, </span>
|
||||
}
|
||||
}
|
||||
</p>
|
||||
</div>
|
||||
@@ -61,17 +68,18 @@
|
||||
@if (metadata.amazonRating) {
|
||||
@if (metadata.asin) {
|
||||
<a class="flex items-center gap-1" [href]="'https://www.amazon.com/dp/' + metadata.asin" target="_blank" rel="noopener noreferrer">
|
||||
<img src="https://www.amazon.com/favicon.ico" alt="Amazon" class="w-5 h-5 object-contain transform transition duration-200 hover:scale-125 hover:drop-shadow-lg" />
|
||||
<img src="https://www.amazon.com/favicon.ico" alt="Amazon"
|
||||
class="w-5 h-5 object-contain transform transition duration-200 hover:scale-125 hover:drop-shadow-lg"/>
|
||||
<p class="font-semibold">{{ metadata.amazonRating }}</p>
|
||||
</a>
|
||||
} @else {
|
||||
<span class="flex items-center gap-1">
|
||||
<img src="https://www.amazon.com/favicon.ico" alt="Amazon" class="w-5 h-5 object-contain" />
|
||||
<img src="https://www.amazon.com/favicon.ico" alt="Amazon" class="w-5 h-5 object-contain"/>
|
||||
<p class="font-semibold">{{ metadata.amazonRating }}</p>
|
||||
</span>
|
||||
}
|
||||
<p-rating [ngModel]="metadata.amazonRating" readonly stars="5"
|
||||
[style.--p-rating-icon-active-color]="getStarColor(metadata.amazonRating)">
|
||||
[style.--p-rating-icon-active-color]="getStarColor(metadata.amazonRating)">
|
||||
</p-rating>
|
||||
<p class="font-semibold">({{ metadata.amazonReviewCount | number:'1.0-0' }})</p>
|
||||
@if (metadata.goodreadsRating || metadata.hardcoverRating) {
|
||||
@@ -81,17 +89,18 @@
|
||||
@if (metadata.goodreadsRating) {
|
||||
@if (metadata.goodreadsId) {
|
||||
<a class="flex items-center gap-1" [href]="'https://www.goodreads.com/book/show/' + metadata.goodreadsId" target="_blank" rel="noopener noreferrer">
|
||||
<img src="https://www.goodreads.com/favicon.ico" alt="Goodreads" class="w-5 h-5 object-contain transform transition duration-200 hover:scale-125 hover:drop-shadow-lg" />
|
||||
<img src="https://www.goodreads.com/favicon.ico" alt="Goodreads"
|
||||
class="w-5 h-5 object-contain transform transition duration-200 hover:scale-125 hover:drop-shadow-lg"/>
|
||||
<p class="font-semibold">{{ metadata.goodreadsRating }}</p>
|
||||
</a>
|
||||
} @else {
|
||||
<span class="flex items-center gap-1">
|
||||
<img src="https://www.goodreads.com/favicon.ico" alt="Goodreads" class="w-5 h-5 object-contain" />
|
||||
<img src="https://www.goodreads.com/favicon.ico" alt="Goodreads" class="w-5 h-5 object-contain"/>
|
||||
<p class="font-semibold">{{ metadata.goodreadsRating }}</p>
|
||||
</span>
|
||||
}
|
||||
<p-rating [ngModel]="metadata.goodreadsRating" readonly stars="5"
|
||||
[style.--p-rating-icon-active-color]="getStarColor(metadata.goodreadsRating)">
|
||||
[style.--p-rating-icon-active-color]="getStarColor(metadata.goodreadsRating)">
|
||||
</p-rating>
|
||||
<p class="font-semibold">({{ metadata.goodreadsReviewCount | number:'1.0-0' }})</p>
|
||||
@if (metadata.hardcoverRating) {
|
||||
@@ -101,17 +110,18 @@
|
||||
@if (metadata.hardcoverRating) {
|
||||
@if (metadata.hardcoverId) {
|
||||
<a class="flex items-center gap-1" [href]="'https://hardcover.app/books/' + metadata.hardcoverId" target="_blank" rel="noopener noreferrer">
|
||||
<img src="https://assets.hardcover.app/static/favicon.ico" alt="Hardcover" class="w-5 h-5 object-contain transform transition duration-200 hover:scale-125 hover:drop-shadow-lg" />
|
||||
<img src="https://assets.hardcover.app/static/favicon.ico" alt="Hardcover"
|
||||
class="w-5 h-5 object-contain transform transition duration-200 hover:scale-125 hover:drop-shadow-lg"/>
|
||||
<p class="font-semibold">{{ metadata.hardcoverRating }}</p>
|
||||
</a>
|
||||
} @else {
|
||||
<span class="flex items-center gap-1">
|
||||
<img src="https://assets.hardcover.app/static/favicon.ico" alt="Hardcover" class="w-5 h-5 object-contain" />
|
||||
<img src="https://assets.hardcover.app/static/favicon.ico" alt="Hardcover" class="w-5 h-5 object-contain"/>
|
||||
<p class="font-semibold">{{ metadata.hardcoverRating }}</p>
|
||||
</span>
|
||||
}
|
||||
<p-rating [ngModel]="metadata.hardcoverRating" readonly stars="5"
|
||||
[style.--p-rating-icon-active-color]="getStarColor(metadata.hardcoverRating)">
|
||||
[style.--p-rating-icon-active-color]="getStarColor(metadata.hardcoverRating)">
|
||||
</p-rating>
|
||||
<p class="font-semibold">({{ metadata.hardcoverReviewCount | number:'1.0-0' }})</p>
|
||||
@if ((metadata.amazonRating || metadata.goodreadsRating || metadata.hardcoverRating) && metadata.googleId) {
|
||||
@@ -119,22 +129,23 @@
|
||||
}
|
||||
}
|
||||
@if (metadata.googleId) {
|
||||
<a class="flex items-center gap-1" [href]="'https://books.google.com/books?id=' + metadata.googleId" target="_blank" rel="noopener noreferrer">
|
||||
<img src="https://books.google.com/favicon.ico" alt="Google Books" class="w-5 h-5 object-contain transform transition duration-200 hover:scale-125 hover:drop-shadow-lg" />
|
||||
</a>
|
||||
<a class="flex items-center gap-1" [href]="'https://books.google.com/books?id=' + metadata.googleId" target="_blank" rel="noopener noreferrer">
|
||||
<img src="https://books.google.com/favicon.ico" alt="Google Books"
|
||||
class="w-5 h-5 object-contain transform transition duration-200 hover:scale-125 hover:drop-shadow-lg"/>
|
||||
</a>
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
} @else {
|
||||
} @else {
|
||||
|
||||
<p-rating
|
||||
[(ngModel)]="metadata.rating"
|
||||
readonly
|
||||
stars="5"
|
||||
[style.--p-rating-icon-active-color]="getStarColor(metadata.rating)">
|
||||
</p-rating>
|
||||
<p class="font-semibold">
|
||||
{{ metadata?.reviewCount ? '(' + (metadata?.reviewCount | number:'1.0-0') + ' Ratings)' : 'No Ratings' }}
|
||||
<p-rating
|
||||
[(ngModel)]="metadata.rating"
|
||||
readonly
|
||||
stars="5"
|
||||
[style.--p-rating-icon-active-color]="getStarColor(metadata.rating)">
|
||||
</p-rating>
|
||||
<p class="font-semibold">
|
||||
{{ metadata?.reviewCount ? '(' + (metadata?.reviewCount | number:'1.0-0') + ' Ratings)' : 'No Ratings' }}
|
||||
</p>
|
||||
}
|
||||
</div>
|
||||
@@ -182,7 +193,7 @@
|
||||
onLabel=""
|
||||
offLabel=""
|
||||
size="small"
|
||||
class="flex-shrink-0"></p-toggleButton>
|
||||
class="flex-shrink-0"></p-toggleButton>
|
||||
@if (showFilePath) {
|
||||
<div
|
||||
class="flex items-center gap-4 flex-grow"
|
||||
@@ -271,12 +282,12 @@
|
||||
@if (metadata.description && metadata.description.length > 100) {
|
||||
<div class="text-left">
|
||||
<button pButton
|
||||
type="button"
|
||||
[label]="isExpanded ? 'Show less' : 'Show more'"
|
||||
[icon]="isExpanded ? 'pi pi-chevron-up' : 'pi pi-chevron-down'"
|
||||
iconPos="right"
|
||||
class="p-button-text p-button-sm"
|
||||
(click)="toggleExpand()">
|
||||
type="button"
|
||||
[label]="isExpanded ? 'Show less' : 'Show more'"
|
||||
[icon]="isExpanded ? 'pi pi-chevron-up' : 'pi pi-chevron-down'"
|
||||
iconPos="right"
|
||||
class="p-button-text p-button-sm"
|
||||
(click)="toggleExpand()">
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
@@ -285,10 +296,10 @@
|
||||
<div>
|
||||
<h3 class="text-xl font-semibold pt-2">More in the Series</h3>
|
||||
<div class="dashboard-scroller-infinite"
|
||||
infiniteScroll
|
||||
[infiniteScrollDistance]="2"
|
||||
[infiniteScrollThrottle]="50"
|
||||
[horizontal]="true">
|
||||
infiniteScroll
|
||||
[infiniteScrollDistance]="2"
|
||||
[infiniteScrollThrottle]="50"
|
||||
[horizontal]="true">
|
||||
@for (book of bookInSeries; track book) {
|
||||
<div class="dashboard-scroller-card">
|
||||
<app-book-card
|
||||
@@ -307,10 +318,10 @@
|
||||
<div>
|
||||
<h3 class="text-xl font-semibold">Similar Books</h3>
|
||||
<div class="dashboard-scroller-infinite"
|
||||
infiniteScroll
|
||||
[infiniteScrollDistance]="2"
|
||||
[infiniteScrollThrottle]="50"
|
||||
[horizontal]="true">
|
||||
infiniteScroll
|
||||
[infiniteScrollDistance]="2"
|
||||
[infiniteScrollThrottle]="50"
|
||||
[horizontal]="true">
|
||||
@for (book of recommendedBooks; track book) {
|
||||
<div class="dashboard-scroller-card">
|
||||
<app-book-card
|
||||
|
||||
+12
@@ -63,3 +63,15 @@
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
.series-number-overlay {
|
||||
position: absolute;
|
||||
top: 6px;
|
||||
right: 6px;
|
||||
background-color: rgba(0, 0, 0, 0.7);
|
||||
color: white;
|
||||
font-size: 0.8rem;
|
||||
padding: 1px 3px;
|
||||
border-radius: 3px;
|
||||
z-index: 3;
|
||||
}
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ export interface Book {
|
||||
cbxProgress?: CbxProgress;
|
||||
filePath?: string;
|
||||
fileSizeKb?: number;
|
||||
seriesCount?: number | null;
|
||||
}
|
||||
|
||||
export interface EpubProgress {
|
||||
@@ -82,8 +83,6 @@ export interface BookMetadata {
|
||||
googleIdLocked?: boolean;
|
||||
pageCountLocked?: boolean;
|
||||
languageLocked?: boolean;
|
||||
ratingLocked?: boolean;
|
||||
reviewCountLocked?: boolean;
|
||||
amazonRatingLocked?: boolean;
|
||||
amazonReviewCountLocked?: boolean;
|
||||
goodreadsRatingLocked?: boolean;
|
||||
|
||||
@@ -372,22 +372,37 @@ export class BookService {
|
||||
this.bookStateSubject.next({...currentState, books: updatedBooks})
|
||||
}
|
||||
|
||||
toggleFieldLocks(bookIds: Set<number>, fieldActions: Record<string, 'LOCK' | 'UNLOCK'>): Observable<void> {
|
||||
toggleFieldLocks(bookIds: number[] | Set<number>, fieldActions: Record<string, 'LOCK' | 'UNLOCK'>): Observable<void> {
|
||||
const bookIdSet = bookIds instanceof Set ? bookIds : new Set(bookIds);
|
||||
|
||||
const requestBody = {
|
||||
bookIds: Array.from(bookIds),
|
||||
fieldActions: fieldActions
|
||||
bookIds: Array.from(bookIdSet),
|
||||
fieldActions
|
||||
};
|
||||
return this.http.put<BookMetadata[]>(`${this.url}/metadata/toggle-field-locks`, requestBody).pipe(
|
||||
tap((updatedMetadataList) => {
|
||||
|
||||
return this.http.put<void>(`${this.url}/metadata/toggle-field-locks`, requestBody).pipe(
|
||||
tap(() => {
|
||||
const currentState = this.bookStateSubject.value;
|
||||
const updatedBooks = (currentState.books || []).map(book => {
|
||||
const updatedMetadata = updatedMetadataList.find(meta => meta.bookId === book.id);
|
||||
return updatedMetadata ? {...book, metadata: updatedMetadata} : book;
|
||||
if (!bookIdSet.has(book.id)) return book;
|
||||
const updatedMetadata = {...book.metadata};
|
||||
for (const [field, action] of Object.entries(fieldActions)) {
|
||||
const lockField = field.endsWith('Locked') ? field : `${field}Locked`;
|
||||
if (lockField in updatedMetadata) {
|
||||
(updatedMetadata as any)[lockField] = action === 'LOCK';
|
||||
}
|
||||
}
|
||||
return {
|
||||
...book,
|
||||
metadata: updatedMetadata
|
||||
};
|
||||
});
|
||||
this.bookStateSubject.next({
|
||||
...currentState,
|
||||
books: updatedBooks as Book[]
|
||||
});
|
||||
this.bookStateSubject.next({...currentState, books: updatedBooks});
|
||||
}),
|
||||
map(() => void 0),
|
||||
catchError((error) => {
|
||||
catchError(error => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Field Lock Update Failed',
|
||||
@@ -397,4 +412,5 @@ export class BookService {
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -16,7 +16,8 @@ export interface EntityViewPreference {
|
||||
sortKey: string;
|
||||
sortDir: 'ASC' | 'DESC';
|
||||
view: 'GRID' | 'TABLE';
|
||||
coverSize: number
|
||||
coverSize: number;
|
||||
seriesCollapsed: boolean;
|
||||
}
|
||||
|
||||
export interface EntityViewPreferenceOverride {
|
||||
|
||||
+28
-13
@@ -23,7 +23,7 @@ import {filter, take} from 'rxjs/operators';
|
||||
Button,
|
||||
TableModule,
|
||||
ToastModule
|
||||
],
|
||||
],
|
||||
templateUrl: './view-preferences.component.html',
|
||||
styleUrl: './view-preferences.component.scss'
|
||||
})
|
||||
@@ -154,24 +154,39 @@ export class ViewPreferencesComponent implements OnInit {
|
||||
saveSettings(): void {
|
||||
if (!this.user) return;
|
||||
|
||||
const payload = {
|
||||
global: {
|
||||
sortKey: this.selectedSort,
|
||||
sortDir: this.selectedSortDir,
|
||||
view: this.selectedView
|
||||
},
|
||||
overrides: this.overrides.map(o => ({
|
||||
const prefs = structuredClone(this.user.userSettings.entityViewPreferences ?? {});
|
||||
|
||||
prefs.global = {
|
||||
...prefs.global,
|
||||
sortKey: this.selectedSort,
|
||||
sortDir: this.selectedSortDir,
|
||||
view: this.selectedView
|
||||
};
|
||||
|
||||
prefs.overrides = this.overrides.map(o => {
|
||||
const existing = prefs.overrides?.find(p =>
|
||||
p.entityId === o.library && p.entityType === o.entityType
|
||||
)?.preferences;
|
||||
|
||||
return {
|
||||
entityType: o.entityType,
|
||||
entityId: o.library,
|
||||
preferences: {
|
||||
sortKey: o.sort,
|
||||
sortDir: o.sortDir,
|
||||
view: o.view
|
||||
view: o.view,
|
||||
coverSize: existing?.coverSize ?? 1.0,
|
||||
seriesCollapsed: existing?.seriesCollapsed ?? false
|
||||
}
|
||||
}))
|
||||
};
|
||||
};
|
||||
});
|
||||
|
||||
this.userService.updateUserSetting(this.user.id, 'entityViewPreferences', payload);
|
||||
this.messageService.add({severity: 'success', summary: 'Preferences Saved', detail: 'Your sorting and view preferences were saved successfully.'});
|
||||
this.userService.updateUserSetting(this.user.id, 'entityViewPreferences', prefs);
|
||||
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'Preferences Saved',
|
||||
detail: 'Your sorting and view preferences were saved successfully.'
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
:root[class="p-dark"] {
|
||||
--primary-text-color: var(--p-primary-400);
|
||||
--primary-text-color-dark: var(--p-primary-900);
|
||||
--primary-color: var(--p-primary-color);
|
||||
--primary-contrast-color: var(--p-primary-contrast-color);
|
||||
--primary-hover-color: var(--p-primary-hover-color);
|
||||
--text-color: var(--p-surface-0);
|
||||
--text-secondary-color: var(--p-surface-400);
|
||||
--glow-image: url(https://www.primefaces.org/cdn/primevue/images/layout/pattern.png), radial-gradient(50% 50% at center -25px, var(--p-primary-color) 0%, #000000 100%);
|
||||
--glow-blend: hard-light, color-dodge;
|
||||
--topbar-sticky-background: rgba(0, 0, 0, .3);
|
||||
--mobile-menu-background: rgba(0, 0, 0, .3);
|
||||
--card-border: 1px solid transparent;
|
||||
|
||||
Reference in New Issue
Block a user