Feature/999 add high resolution cover support upload storage and search (#1006)
* Add high-resolution cover support: upload, storage, and search * Disable tests until fixed
This commit is contained in:
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.adityachandel.booklore.config.security;
|
||||
package com.adityachandel.booklore.config;
|
||||
|
||||
import io.swagger.v3.oas.models.Components;
|
||||
import io.swagger.v3.oas.models.OpenAPI;
|
||||
@@ -1,6 +1,6 @@
|
||||
package com.adityachandel.booklore.config;
|
||||
|
||||
import com.adityachandel.booklore.config.security.WebSocketAuthInterceptor;
|
||||
import com.adityachandel.booklore.config.security.interceptor.WebSocketAuthInterceptor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.messaging.simp.config.ChannelRegistration;
|
||||
|
||||
+9
-3
@@ -1,5 +1,6 @@
|
||||
package com.adityachandel.booklore.config.security;
|
||||
|
||||
import com.adityachandel.booklore.config.security.filter.ImageCachingFilter;
|
||||
import org.springframework.boot.web.servlet.FilterRegistrationBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
@@ -8,10 +9,15 @@ import org.springframework.context.annotation.Configuration;
|
||||
public class ImageCacheConfig {
|
||||
|
||||
@Bean
|
||||
public FilterRegistrationBean<ImageCachingFilter> imageCachingFilterRegistration() {
|
||||
public FilterRegistrationBean<ImageCachingFilter> imageCachingFilterRegistration(ImageCachingFilter filter) {
|
||||
FilterRegistrationBean<ImageCachingFilter> registrationBean = new FilterRegistrationBean<>();
|
||||
registrationBean.setFilter(new ImageCachingFilter());
|
||||
registrationBean.addUrlPatterns("/api/v1/books/*/cover");
|
||||
registrationBean.setFilter(filter);
|
||||
registrationBean.addUrlPatterns(
|
||||
"/api/v1/media/book/*/cover",
|
||||
"/api/v1/media/book/*/thumbnail",
|
||||
"/api/v1/media/book/*/backup-cover"
|
||||
);
|
||||
registrationBean.setOrder(1);
|
||||
return registrationBean;
|
||||
}
|
||||
}
|
||||
|
||||
+26
-15
@@ -1,9 +1,12 @@
|
||||
package com.adityachandel.booklore.config.security;
|
||||
|
||||
import com.adityachandel.booklore.config.AppProperties;
|
||||
import com.adityachandel.booklore.config.security.filter.CoverJwtFilter;
|
||||
import com.adityachandel.booklore.config.security.filter.DualJwtAuthenticationFilter;
|
||||
import com.adityachandel.booklore.config.security.filter.KoboAuthFilter;
|
||||
import com.adityachandel.booklore.config.security.filter.KoreaderAuthFilter;
|
||||
import com.adityachandel.booklore.config.security.service.CustomOpdsUserDetailsService;
|
||||
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;
|
||||
@@ -36,7 +39,6 @@ public class SecurityConfig {
|
||||
|
||||
private final CustomOpdsUserDetailsService customOpdsUserDetailsService;
|
||||
private final DualJwtAuthenticationFilter dualJwtAuthenticationFilter;
|
||||
private final KoboAuthFilter koboAuthFilter;
|
||||
private final AppProperties appProperties;
|
||||
|
||||
private static final String[] SWAGGER_ENDPOINTS = {
|
||||
@@ -46,17 +48,11 @@ public class SecurityConfig {
|
||||
};
|
||||
|
||||
private static final String[] COMMON_PUBLIC_ENDPOINTS = {
|
||||
"/ws/**",
|
||||
"/kobo/**",
|
||||
"/api/v1/auth/**",
|
||||
"/api/v1/public-settings",
|
||||
"/api/v1/setup/**",
|
||||
"/api/v1/books/*/cover",
|
||||
"/api/v1/books/*/backup-cover",
|
||||
"/api/v1/opds/*/cover.jpg",
|
||||
"/api/v1/cbx/*/pages/*",
|
||||
"/api/v1/pdf/*/pages/*",
|
||||
"/api/bookdrop/*/cover"
|
||||
"/ws/**", // WebSocket connections (auth handled in WebSocketAuthInterceptor)
|
||||
"/kobo/**", // Kobo API requests (auth handled in KoboAuthFilter)
|
||||
"/api/v1/auth/**", // Login and token refresh endpoints (must remain public)
|
||||
"/api/v1/public-settings", // Public endpoint for checking OIDC or other app settings
|
||||
"/api/v1/setup/**" // Setup wizard endpoints (must remain accessible before initial setup)
|
||||
};
|
||||
|
||||
private static final String[] COMMON_UNAUTHENTICATED_ENDPOINTS = {
|
||||
@@ -71,7 +67,6 @@ public class SecurityConfig {
|
||||
@Bean
|
||||
@Order(1)
|
||||
public SecurityFilterChain opdsBasicAuthSecurityChain(HttpSecurity http) throws Exception {
|
||||
|
||||
List<String> unauthenticatedEndpoints = new ArrayList<>(Arrays.asList(COMMON_UNAUTHENTICATED_ENDPOINTS));
|
||||
http
|
||||
.securityMatcher("/api/v1/opds/**")
|
||||
@@ -118,6 +113,22 @@ public class SecurityConfig {
|
||||
|
||||
@Bean
|
||||
@Order(4)
|
||||
public SecurityFilterChain coverJwtApiSecurityChain(HttpSecurity http, CoverJwtFilter coverJwtFilter) throws Exception {
|
||||
http
|
||||
.securityMatcher("/api/v1/media/**")
|
||||
.csrf(AbstractHttpConfigurer::disable)
|
||||
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.anyRequest().permitAll()
|
||||
)
|
||||
.addFilterBefore(coverJwtFilter, UsernamePasswordAuthenticationFilter.class)
|
||||
.addFilterBefore(dualJwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Order(5)
|
||||
public SecurityFilterChain jwtApiSecurityChain(HttpSecurity http) throws Exception {
|
||||
List<String> publicEndpoints = new ArrayList<>(Arrays.asList(COMMON_PUBLIC_ENDPOINTS));
|
||||
if (appProperties.getSwagger().isEnabled()) {
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
package com.adityachandel.booklore.config.security.aspect;
|
||||
|
||||
import com.adityachandel.booklore.config.security.AuthenticationService;
|
||||
import com.adityachandel.booklore.config.security.service.AuthenticationService;
|
||||
import com.adityachandel.booklore.config.security.annotation.CheckBookAccess;
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
package com.adityachandel.booklore.config.security.aspect;
|
||||
|
||||
import com.adityachandel.booklore.config.security.AuthenticationService;
|
||||
import com.adityachandel.booklore.config.security.service.AuthenticationService;
|
||||
import com.adityachandel.booklore.config.security.annotation.CheckLibraryAccess;
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
package com.adityachandel.booklore.config.security.filter;
|
||||
|
||||
import com.adityachandel.booklore.config.security.JwtUtils;
|
||||
import com.adityachandel.booklore.config.security.userdetails.UserAuthenticationDetails;
|
||||
import com.adityachandel.booklore.mapper.custom.BookLoreUserTransformer;
|
||||
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||
import com.adityachandel.booklore.repository.UserRepository;
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
@AllArgsConstructor
|
||||
@Component
|
||||
public class CoverJwtFilter extends OncePerRequestFilter {
|
||||
|
||||
private final JwtUtils jwtUtils;
|
||||
private final UserRepository userRepository;
|
||||
private final BookLoreUserTransformer bookLoreUserTransformer;
|
||||
|
||||
@Override
|
||||
protected boolean shouldNotFilter(HttpServletRequest request) {
|
||||
String path = request.getRequestURI();
|
||||
return !path.startsWith("/api/v1/media/");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
|
||||
String token = request.getParameter("token");
|
||||
if (token != null && jwtUtils.validateToken(token)) {
|
||||
Long userId = jwtUtils.extractUserId(token);
|
||||
BookLoreUserEntity bookLoreUserEntity = userRepository.findById(userId).orElseThrow(() -> new UsernameNotFoundException("User not found"));
|
||||
BookLoreUser bookLoreUser = bookLoreUserTransformer.toDTO(bookLoreUserEntity);
|
||||
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(bookLoreUser, null, null);
|
||||
authentication.setDetails(new UserAuthenticationDetails(request, bookLoreUser.getId()));
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
chain.doFilter(request, response);
|
||||
} else {
|
||||
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Missing or invalid token");
|
||||
}
|
||||
}
|
||||
}
|
||||
+4
-1
@@ -1,5 +1,8 @@
|
||||
package com.adityachandel.booklore.config.security;
|
||||
package com.adityachandel.booklore.config.security.filter;
|
||||
|
||||
import com.adityachandel.booklore.config.security.service.DynamicOidcJwtProcessor;
|
||||
import com.adityachandel.booklore.config.security.JwtUtils;
|
||||
import com.adityachandel.booklore.config.security.userdetails.UserAuthenticationDetails;
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.mapper.custom.BookLoreUserTransformer;
|
||||
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||
+4
-3
@@ -1,4 +1,4 @@
|
||||
package com.adityachandel.booklore.config.security;
|
||||
package com.adityachandel.booklore.config.security.filter;
|
||||
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
@@ -15,9 +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")) {
|
||||
String uri = request.getRequestURI();
|
||||
if (uri.startsWith("/api/v1/media/book/") && (uri.contains("/cover") || uri.contains("/thumbnail") || uri.contains("/backup-cover"))) {
|
||||
response.setHeader(HttpHeaders.CACHE_CONTROL, "public, max-age=3600");
|
||||
response.setHeader(HttpHeaders.EXPIRES, String.valueOf(System.currentTimeMillis() + 3600000));
|
||||
response.setHeader(HttpHeaders.EXPIRES, String.valueOf(System.currentTimeMillis() + 3600_000));
|
||||
}
|
||||
filterChain.doFilter(request, response);
|
||||
}
|
||||
+3
-1
@@ -1,5 +1,7 @@
|
||||
package com.adityachandel.booklore.config.security;
|
||||
package com.adityachandel.booklore.config.security.filter;
|
||||
|
||||
import com.adityachandel.booklore.config.security.JwtUtils;
|
||||
import com.adityachandel.booklore.config.security.userdetails.UserAuthenticationDetails;
|
||||
import com.adityachandel.booklore.mapper.custom.BookLoreUserTransformer;
|
||||
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
package com.adityachandel.booklore.config.security;
|
||||
package com.adityachandel.booklore.config.security.filter;
|
||||
|
||||
import com.adityachandel.booklore.config.security.userdetails.UserAuthenticationDetails;
|
||||
import com.adityachandel.booklore.mapper.custom.BookLoreUserTransformer;
|
||||
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||
import com.adityachandel.booklore.model.entity.UserPermissionsEntity;
|
||||
+2
-2
@@ -1,5 +1,6 @@
|
||||
package com.adityachandel.booklore.config.security;
|
||||
package com.adityachandel.booklore.config.security.filter;
|
||||
|
||||
import com.adityachandel.booklore.config.security.userdetails.KoreaderUserDetails;
|
||||
import com.adityachandel.booklore.repository.KoreaderUserRepository;
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
@@ -10,7 +11,6 @@ import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.User;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
+3
-1
@@ -1,5 +1,7 @@
|
||||
package com.adityachandel.booklore.config.security;
|
||||
package com.adityachandel.booklore.config.security.interceptor;
|
||||
|
||||
import com.adityachandel.booklore.config.security.JwtUtils;
|
||||
import com.adityachandel.booklore.config.security.service.DynamicOidcJwtProcessor;
|
||||
import com.nimbusds.jwt.JWTClaimsSet;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
+2
-1
@@ -1,6 +1,7 @@
|
||||
package com.adityachandel.booklore.config.security;
|
||||
package com.adityachandel.booklore.config.security.service;
|
||||
|
||||
import com.adityachandel.booklore.config.AppProperties;
|
||||
import com.adityachandel.booklore.config.security.JwtUtils;
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||
import com.adityachandel.booklore.model.dto.request.UserLoginRequest;
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.adityachandel.booklore.config.security;
|
||||
package com.adityachandel.booklore.config.security.service;
|
||||
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.model.entity.OpdsUserEntity;
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.adityachandel.booklore.config.security;
|
||||
package com.adityachandel.booklore.config.security.service;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.settings.OidcProviderDetails;
|
||||
import com.adityachandel.booklore.service.appsettings.AppSettingService;
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.adityachandel.booklore.config.security;
|
||||
package com.adityachandel.booklore.config.security.userdetails;
|
||||
|
||||
import lombok.Getter;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.adityachandel.booklore.config.security;
|
||||
package com.adityachandel.booklore.config.security.userdetails;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.Getter;
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
package com.adityachandel.booklore.controller;
|
||||
|
||||
import com.adityachandel.booklore.config.AppProperties;
|
||||
import com.adityachandel.booklore.config.security.AuthenticationService;
|
||||
import com.adityachandel.booklore.config.security.service.AuthenticationService;
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.model.dto.UserCreateRequest;
|
||||
import com.adityachandel.booklore.model.dto.request.RefreshTokenRequest;
|
||||
|
||||
@@ -60,23 +60,6 @@ public class BookController {
|
||||
return ResponseEntity.ok(bookService.getBooksByIds(ids, withDescription));
|
||||
}
|
||||
|
||||
@GetMapping("/{bookId}/cover")
|
||||
public ResponseEntity<Resource> getBookCover(@PathVariable long bookId) {
|
||||
return ResponseEntity.ok(bookService.getBookCover(bookId));
|
||||
}
|
||||
|
||||
@GetMapping("/{bookId}/backup-cover")
|
||||
public ResponseEntity<Resource> getBackupBookCover(@PathVariable long bookId) {
|
||||
Resource file = bookMetadataService.getBackupCoverForBook(bookId);
|
||||
if (file == null) {
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
return ResponseEntity.ok()
|
||||
.header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=cover.jpg")
|
||||
.contentType(MediaType.IMAGE_JPEG)
|
||||
.body(file);
|
||||
}
|
||||
|
||||
@GetMapping("/{bookId}/content")
|
||||
@CheckBookAccess(bookIdParam = "bookId")
|
||||
public ResponseEntity<ByteArrayResource> getBookContent(@PathVariable long bookId) throws IOException {
|
||||
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
package com.adityachandel.booklore.controller;
|
||||
|
||||
import com.adityachandel.booklore.service.BookService;
|
||||
import com.adityachandel.booklore.service.bookdrop.BookDropService;
|
||||
import com.adityachandel.booklore.service.metadata.BookMetadataService;
|
||||
import com.adityachandel.booklore.service.reader.CbxReaderService;
|
||||
import com.adityachandel.booklore.service.reader.PdfReaderService;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
@AllArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/media")
|
||||
public class BookMediaController {
|
||||
|
||||
private final BookService bookService;
|
||||
private final BookMetadataService bookMetadataService;
|
||||
private final PdfReaderService pdfReaderService;
|
||||
private final CbxReaderService cbxReaderService;
|
||||
private final BookDropService bookDropService;
|
||||
|
||||
@GetMapping("/book/{bookId}/thumbnail")
|
||||
public ResponseEntity<Resource> getBookThumbnail(@PathVariable long bookId) {
|
||||
return ResponseEntity.ok(bookService.getBookThumbnail(bookId));
|
||||
}
|
||||
|
||||
@GetMapping("/book/{bookId}/cover")
|
||||
public ResponseEntity<Resource> getBookCover(@PathVariable long bookId) {
|
||||
return ResponseEntity.ok(bookService.getBookCover(bookId));
|
||||
}
|
||||
|
||||
@GetMapping("/book/{bookId}/backup-cover")
|
||||
public ResponseEntity<Resource> getBackupBookCover(@PathVariable long bookId) {
|
||||
Resource file = bookMetadataService.getBackupCoverForBook(bookId);
|
||||
if (file == null) {
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
return ResponseEntity.ok()
|
||||
.header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=cover.jpg")
|
||||
.contentType(MediaType.IMAGE_JPEG)
|
||||
.body(file);
|
||||
}
|
||||
|
||||
@GetMapping("/book/{bookId}/pdf/pages/{pageNumber}")
|
||||
public void getPdfPage(@PathVariable Long bookId, @PathVariable int pageNumber, HttpServletResponse response) throws IOException {
|
||||
response.setContentType(MediaType.IMAGE_JPEG_VALUE);
|
||||
pdfReaderService.streamPageImage(bookId, pageNumber, response.getOutputStream());
|
||||
}
|
||||
|
||||
@GetMapping("/book/{bookId}/cbx/pages/{pageNumber}")
|
||||
public void getCbxPage(@PathVariable Long bookId, @PathVariable int pageNumber, HttpServletResponse response) throws IOException {
|
||||
response.setContentType(MediaType.IMAGE_JPEG_VALUE);
|
||||
cbxReaderService.streamPageImage(bookId, pageNumber, response.getOutputStream());
|
||||
}
|
||||
|
||||
@GetMapping("/bookdrop/{bookdropId}/cover")
|
||||
public ResponseEntity<Resource> getBookdropCover(@PathVariable long bookdropId) {
|
||||
Resource file = bookDropService.getBookdropCover(bookdropId);
|
||||
return (file != null)
|
||||
? ResponseEntity.ok()
|
||||
.header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=cover.jpg")
|
||||
.contentType(MediaType.IMAGE_JPEG)
|
||||
.body(file)
|
||||
: ResponseEntity.noContent().build();
|
||||
}
|
||||
}
|
||||
+1
-15
@@ -7,17 +7,14 @@ import com.adityachandel.booklore.model.dto.request.BookdropSelectionRequest;
|
||||
import com.adityachandel.booklore.model.dto.response.BookdropFinalizeResult;
|
||||
import com.adityachandel.booklore.service.bookdrop.BookDropService;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@AllArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/api/bookdrop")
|
||||
@RequestMapping("/api/v1/bookdrop")
|
||||
public class BookdropFileController {
|
||||
|
||||
private final BookDropService bookDropService;
|
||||
@@ -43,15 +40,4 @@ public class BookdropFileController {
|
||||
BookdropFinalizeResult result = bookDropService.finalizeImport(request);
|
||||
return ResponseEntity.ok(result);
|
||||
}
|
||||
|
||||
@GetMapping("/{bookdropId}/cover")
|
||||
public ResponseEntity<Resource> getBookdropCover(@PathVariable long bookdropId) {
|
||||
Resource file = bookDropService.getBookdropCover(bookdropId);
|
||||
return (file != null)
|
||||
? ResponseEntity.ok()
|
||||
.header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=cover.jpg")
|
||||
.contentType(MediaType.IMAGE_JPEG)
|
||||
.body(file)
|
||||
: ResponseEntity.noContent().build();
|
||||
}
|
||||
}
|
||||
+4
-12
@@ -1,13 +1,12 @@
|
||||
package com.adityachandel.booklore.controller;
|
||||
|
||||
import com.adityachandel.booklore.config.security.annotation.CheckBookAccess;
|
||||
import com.adityachandel.booklore.service.reader.CbxReaderService;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@@ -17,15 +16,8 @@ public class CbxReaderController {
|
||||
|
||||
private final CbxReaderService cbxReaderService;
|
||||
|
||||
|
||||
@GetMapping("/{bookId}/pages")
|
||||
public List<Integer> listPages(@PathVariable Long bookId) {
|
||||
return cbxReaderService.getAvailablePages(bookId);
|
||||
}
|
||||
|
||||
@GetMapping("/{bookId}/pages/{pageNumber}")
|
||||
public void getPage(@PathVariable Long bookId, @PathVariable int pageNumber, HttpServletResponse response) throws IOException {
|
||||
response.setContentType(MediaType.IMAGE_JPEG_VALUE);
|
||||
cbxReaderService.streamPageImage(bookId, pageNumber, response.getOutputStream());
|
||||
}
|
||||
}
|
||||
+9
-7
@@ -1,24 +1,20 @@
|
||||
package com.adityachandel.booklore.controller;
|
||||
|
||||
import com.adityachandel.booklore.config.security.AuthenticationService;
|
||||
import com.adityachandel.booklore.config.security.service.AuthenticationService;
|
||||
import com.adityachandel.booklore.config.security.annotation.CheckBookAccess;
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.mapper.BookMetadataMapper;
|
||||
import com.adityachandel.booklore.model.MetadataUpdateWrapper;
|
||||
import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||
import com.adityachandel.booklore.model.dto.EpubMetadata;
|
||||
import com.adityachandel.booklore.model.dto.CoverImage;
|
||||
import com.adityachandel.booklore.model.dto.request.*;
|
||||
import com.adityachandel.booklore.model.dto.settings.MetadataMatchWeights;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.quartz.JobSchedulerService;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.service.metadata.BookMetadataService;
|
||||
import com.adityachandel.booklore.service.metadata.BookMetadataUpdater;
|
||||
import com.adityachandel.booklore.service.metadata.MetadataMatchService;
|
||||
import com.adityachandel.booklore.service.metadata.*;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
@@ -37,6 +33,7 @@ public class MetadataController {
|
||||
private final AuthenticationService authenticationService;
|
||||
private final BookMetadataMapper bookMetadataMapper;
|
||||
private final MetadataMatchService metadataMatchService;
|
||||
private final DuckDuckGoCoverService duckDuckGoCoverService;
|
||||
private final BookRepository bookRepository;
|
||||
|
||||
@PostMapping("/{bookId}/metadata/prospective")
|
||||
@@ -127,4 +124,9 @@ public class MetadataController {
|
||||
BookMetadata restoredMetadata = bookMetadataService.restoreMetadataFromBackup(bookId);
|
||||
return ResponseEntity.ok(restoredMetadata);
|
||||
}
|
||||
|
||||
@PostMapping("/{bookId}/metadata/covers")
|
||||
public ResponseEntity<List<CoverImage>> getImages(@RequestBody CoverFetchRequest request) {
|
||||
return ResponseEntity.ok(duckDuckGoCoverService.getCovers(request));
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -50,9 +50,9 @@ public class OpdsController {
|
||||
return bookService.downloadBook(bookId);
|
||||
}
|
||||
|
||||
@GetMapping("/{bookId}/cover.jpg")
|
||||
@GetMapping("/{bookId}/cover")
|
||||
public ResponseEntity<Resource> getBookCover(@PathVariable long bookId) {
|
||||
Resource coverImage = bookService.getBookCover(bookId);
|
||||
Resource coverImage = bookService.getBookThumbnail(bookId);
|
||||
String contentType = "image/jpeg";
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.parseMediaType(contentType))
|
||||
|
||||
-7
@@ -1,6 +1,5 @@
|
||||
package com.adityachandel.booklore.controller;
|
||||
|
||||
import com.adityachandel.booklore.config.security.annotation.CheckBookAccess;
|
||||
import com.adityachandel.booklore.service.reader.PdfReaderService;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -24,10 +23,4 @@ public class PdfReaderController {
|
||||
public List<Integer> listPages(@PathVariable Long bookId) throws IOException {
|
||||
return pdfReaderService.getAvailablePages(bookId);
|
||||
}
|
||||
|
||||
@GetMapping("/{bookId}/pages/{pageNumber}")
|
||||
public void getPage(@PathVariable Long bookId, @PathVariable int pageNumber, HttpServletResponse response) throws IOException {
|
||||
response.setContentType(MediaType.IMAGE_JPEG_VALUE);
|
||||
pdfReaderService.streamPageImage(bookId, pageNumber, response.getOutputStream());
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -73,7 +73,7 @@ public class BookLoreUserTransformer {
|
||||
}
|
||||
}
|
||||
} catch (IllegalArgumentException e) {
|
||||
log.warn("Unknown setting key encountered: {}", key);
|
||||
log.debug("Unknown setting key encountered: {}", key);
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to deserialize setting '{}': {}", key, e.getMessage(), e);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.adityachandel.booklore.model.dto;
|
||||
|
||||
import lombok.Value;
|
||||
|
||||
@Value
|
||||
public class CoverImage {
|
||||
String url;
|
||||
int width;
|
||||
int height;
|
||||
int index;
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package com.adityachandel.booklore.model.dto.request;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
@Builder
|
||||
@Data
|
||||
public class CoverFetchRequest {
|
||||
private String isbn;
|
||||
private String title;
|
||||
private String author;
|
||||
}
|
||||
-1
@@ -11,7 +11,6 @@ import lombok.NoArgsConstructor;
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class AppSettings {
|
||||
private String coverResolution;
|
||||
private MetadataRefreshOptions metadataRefreshOptions;
|
||||
private boolean autoBookSearch;
|
||||
private boolean similarBookRecommendation;
|
||||
|
||||
-3
@@ -57,9 +57,6 @@ public class BookMetadataEntity {
|
||||
@Column(name = "page_count")
|
||||
private Integer pageCount;
|
||||
|
||||
@Column(name = "thumbnail", length = 1000)
|
||||
private String thumbnail;
|
||||
|
||||
@Column(name = "language", length = 10)
|
||||
private String language;
|
||||
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
package com.adityachandel.booklore.quartz;
|
||||
|
||||
import com.adityachandel.booklore.config.security.AuthenticationService;
|
||||
import com.adityachandel.booklore.config.security.service.AuthenticationService;
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||
import com.adityachandel.booklore.model.dto.request.MetadataRefreshRequest;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.config.security.AuthenticationService;
|
||||
import com.adityachandel.booklore.config.security.service.AuthenticationService;
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.mapper.BookNoteMapper;
|
||||
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.config.security.AuthenticationService;
|
||||
import com.adityachandel.booklore.config.security.service.AuthenticationService;
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.mapper.BookReviewMapper;
|
||||
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.config.security.AuthenticationService;
|
||||
import com.adityachandel.booklore.config.security.service.AuthenticationService;
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.mapper.BookMapper;
|
||||
import com.adityachandel.booklore.model.dto.*;
|
||||
@@ -20,10 +20,7 @@ import com.adityachandel.booklore.util.FileUtils;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.EnumUtils;
|
||||
import org.springframework.core.io.ByteArrayResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.core.io.UrlResource;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.core.io.*;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
@@ -34,6 +31,7 @@ import org.springframework.transaction.annotation.Transactional;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.MalformedURLException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
@@ -448,9 +446,32 @@ public class BookService {
|
||||
}).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public Resource getBookThumbnail(long bookId) {
|
||||
Path thumbnailPath = Paths.get(fileService.getThumbnailFile(bookId));
|
||||
try {
|
||||
if (Files.exists(thumbnailPath)) {
|
||||
return new UrlResource(thumbnailPath.toUri());
|
||||
} else {
|
||||
Path defaultCover = Paths.get("static/images/missing-cover.jpg");
|
||||
return new UrlResource(defaultCover.toUri());
|
||||
}
|
||||
} catch (MalformedURLException e) {
|
||||
throw new RuntimeException("Failed to load book cover for bookId=" + bookId, e);
|
||||
}
|
||||
}
|
||||
|
||||
public Resource getBookCover(long bookId) {
|
||||
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||
return fileService.getBookCover(bookEntity.getMetadata().getThumbnail());
|
||||
Path coverPath = Paths.get(fileService.getCoverFile(bookId));
|
||||
try {
|
||||
if (Files.exists(coverPath)) {
|
||||
return new UrlResource(coverPath.toUri());
|
||||
} else {
|
||||
Path defaultCover = Paths.get("static/images/missing-cover.jpg");
|
||||
return new UrlResource(defaultCover.toUri());
|
||||
}
|
||||
} catch (MalformedURLException e) {
|
||||
throw new RuntimeException("Failed to load book cover for bookId=" + bookId, e);
|
||||
}
|
||||
}
|
||||
|
||||
public ResponseEntity<Resource> downloadBook(Long bookId) {
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.config.security.AuthenticationService;
|
||||
import com.adityachandel.booklore.config.security.service.AuthenticationService;
|
||||
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||
import com.adityachandel.booklore.model.dto.KoboSyncSettings;
|
||||
import com.adityachandel.booklore.model.dto.request.ShelfCreateRequest;
|
||||
|
||||
@@ -4,7 +4,6 @@ import java.time.Instant;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Service;
|
||||
@@ -12,7 +11,7 @@ import org.springframework.stereotype.Service;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import com.adityachandel.booklore.config.security.KoreaderUserDetails;
|
||||
import com.adityachandel.booklore.config.security.userdetails.KoreaderUserDetails;
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.model.dto.progress.KoreaderProgress;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.config.security.AuthenticationService;
|
||||
import com.adityachandel.booklore.config.security.service.AuthenticationService;
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.mapper.KoreaderUserMapper;
|
||||
import com.adityachandel.booklore.model.dto.KoreaderUser;
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.config.security.AuthenticationService;
|
||||
import com.adityachandel.booklore.config.security.service.AuthenticationService;
|
||||
import com.adityachandel.booklore.model.dto.MagicShelf;
|
||||
import com.adityachandel.booklore.model.entity.MagicShelfEntity;
|
||||
import com.adityachandel.booklore.repository.MagicShelfRepository;
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.config.security.AuthenticationService;
|
||||
import com.adityachandel.booklore.config.security.service.AuthenticationService;
|
||||
import com.adityachandel.booklore.mapper.FetchedProposalMapper;
|
||||
import com.adityachandel.booklore.model.dto.FetchedProposal;
|
||||
import com.adityachandel.booklore.model.dto.MetadataBatchProgressNotification;
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.config.security.AuthenticationService;
|
||||
import com.adityachandel.booklore.config.security.service.AuthenticationService;
|
||||
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||
import com.adityachandel.booklore.model.entity.UserPermissionsEntity;
|
||||
import com.adityachandel.booklore.model.enums.PermissionType;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.config.security.AuthenticationService;
|
||||
import com.adityachandel.booklore.config.security.service.AuthenticationService;
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.mapper.BookMapper;
|
||||
import com.adityachandel.booklore.mapper.ShelfMapper;
|
||||
|
||||
-1
@@ -91,7 +91,6 @@ public class AppSettingService {
|
||||
builder.metadataPublicReviewsSettings(settingPersistenceHelper.getJsonSetting(settingsMap, AppSettingKey.METADATA_PUBLIC_REVIEWS_SETTINGS, MetadataPublicReviewsSettings.class, settingPersistenceHelper.getDefaultMetadataPublicReviewsSettings(), true));
|
||||
builder.koboSettings(settingPersistenceHelper.getJsonSetting(settingsMap, AppSettingKey.KOBO_SETTINGS, KoboSettings.class, settingPersistenceHelper.getDefaultKoboSettings(), true));
|
||||
|
||||
builder.coverResolution(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.COVER_IMAGE_RESOLUTION, "250x350"));
|
||||
builder.autoBookSearch(Boolean.parseBoolean(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.AUTO_BOOK_SEARCH, "true")));
|
||||
builder.uploadPattern(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.UPLOAD_FILE_PATTERN, "{authors}/<{series}/><{seriesIndex}. >{title}< - {authors}>< ({year})>"));
|
||||
builder.similarBookRecommendation(Boolean.parseBoolean(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.SIMILAR_BOOK_RECOMMENDATION, "true")));
|
||||
|
||||
+1
-3
@@ -15,7 +15,6 @@ import com.adityachandel.booklore.service.metadata.extractor.CbxMetadataExtracto
|
||||
import com.adityachandel.booklore.service.metadata.extractor.EpubMetadataExtractor;
|
||||
import com.adityachandel.booklore.service.metadata.extractor.PdfMetadataExtractor;
|
||||
import com.adityachandel.booklore.util.FileService;
|
||||
import com.adityachandel.booklore.util.ImageUtils;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import lombok.AllArgsConstructor;
|
||||
@@ -44,7 +43,6 @@ public class BookdropMetadataService {
|
||||
private final PdfMetadataExtractor pdfMetadataExtractor;
|
||||
private final CbxMetadataExtractor cbxMetadataExtractor;
|
||||
private final MetadataRefreshService metadataRefreshService;
|
||||
private final ImageUtils imageUtils;
|
||||
private final FileService fileService;
|
||||
|
||||
@Transactional
|
||||
@@ -119,7 +117,7 @@ public class BookdropMetadataService {
|
||||
};
|
||||
if (coverBytes != null) {
|
||||
try {
|
||||
imageUtils.saveImage(coverBytes, fileService.getTempBookdropCoverImagePath(entity.getId()), 250, 350);
|
||||
fileService.saveImage(coverBytes, fileService.getTempBookdropCoverImagePath(entity.getId()));
|
||||
} catch (IOException e) {
|
||||
log.warn("Failed to save extracted cover for file: {}", entity.getFilePath(), e);
|
||||
}
|
||||
|
||||
+5
-7
@@ -5,12 +5,11 @@ 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.repository.BookAdditionalFileRepository;
|
||||
import com.adityachandel.booklore.repository.BookMetadataRepository;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.service.BookCreatorService;
|
||||
import com.adityachandel.booklore.service.FileFingerprint;
|
||||
import com.adityachandel.booklore.service.metadata.MetadataMatchService;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
import com.adityachandel.booklore.util.FileService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.transaction.annotation.Propagation;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
@@ -25,16 +24,16 @@ public abstract class AbstractFileProcessor implements BookFileProcessor {
|
||||
protected final BookAdditionalFileRepository bookAdditionalFileRepository;
|
||||
protected final BookCreatorService bookCreatorService;
|
||||
protected final BookMapper bookMapper;
|
||||
protected final FileProcessingUtils fileProcessingUtils;
|
||||
protected final MetadataMatchService metadataMatchService;
|
||||
protected final FileService fileService;
|
||||
|
||||
protected AbstractFileProcessor(BookRepository bookRepository, BookAdditionalFileRepository bookAdditionalFileRepository, BookCreatorService bookCreatorService, BookMapper bookMapper, FileProcessingUtils fileProcessingUtils, MetadataMatchService metadataMatchService) {
|
||||
protected AbstractFileProcessor(BookRepository bookRepository, BookAdditionalFileRepository bookAdditionalFileRepository, BookCreatorService bookCreatorService, BookMapper bookMapper, FileService fileService, MetadataMatchService metadataMatchService) {
|
||||
this.bookRepository = bookRepository;
|
||||
this.bookAdditionalFileRepository = bookAdditionalFileRepository;
|
||||
this.bookCreatorService = bookCreatorService;
|
||||
this.bookMapper = bookMapper;
|
||||
this.fileProcessingUtils = fileProcessingUtils;
|
||||
this.metadataMatchService = metadataMatchService;
|
||||
this.fileService = fileService;
|
||||
}
|
||||
|
||||
@Transactional(propagation = Propagation.REQUIRES_NEW)
|
||||
@@ -43,8 +42,7 @@ public abstract class AbstractFileProcessor implements BookFileProcessor {
|
||||
Path path = libraryFile.getFullPath();
|
||||
String fileName = path.getFileName().toString();
|
||||
String hash = FileFingerprint.generateHash(path);
|
||||
|
||||
Optional<Book> duplicate = fileProcessingUtils.checkForDuplicateAndUpdateMetadataIfNeeded(libraryFile, hash, bookRepository, bookAdditionalFileRepository, bookMapper);
|
||||
Optional<Book> duplicate = fileService.checkForDuplicateAndUpdateMetadataIfNeeded(libraryFile, hash, bookRepository, bookAdditionalFileRepository, bookMapper);
|
||||
if (duplicate.isPresent()) {
|
||||
return handleDuplicate(duplicate.get(), libraryFile);
|
||||
}
|
||||
|
||||
+8
-5
@@ -9,6 +9,7 @@ import com.adityachandel.booklore.repository.BookMetadataRepository;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.service.BookCreatorService;
|
||||
import com.adityachandel.booklore.service.metadata.MetadataMatchService;
|
||||
import com.adityachandel.booklore.util.FileService;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
import com.github.junrar.Archive;
|
||||
import com.github.junrar.rarfile.FileHeader;
|
||||
@@ -25,6 +26,8 @@ import java.io.*;
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
|
||||
import static com.adityachandel.booklore.util.FileService.truncate;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
public class CbxProcessor extends AbstractFileProcessor implements BookFileProcessor {
|
||||
@@ -35,10 +38,10 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce
|
||||
BookAdditionalFileRepository bookAdditionalFileRepository,
|
||||
BookCreatorService bookCreatorService,
|
||||
BookMapper bookMapper,
|
||||
FileProcessingUtils fileProcessingUtils,
|
||||
FileService fileService,
|
||||
BookMetadataRepository bookMetadataRepository,
|
||||
MetadataMatchService metadataMatchService) {
|
||||
super(bookRepository, bookAdditionalFileRepository, bookCreatorService, bookMapper, fileProcessingUtils, metadataMatchService);
|
||||
super(bookRepository, bookAdditionalFileRepository, bookCreatorService, bookMapper, fileService, metadataMatchService);
|
||||
this.bookMetadataRepository = bookMetadataRepository;
|
||||
}
|
||||
|
||||
@@ -46,7 +49,7 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce
|
||||
public BookEntity processNewFile(LibraryFile libraryFile) {
|
||||
BookEntity bookEntity = bookCreatorService.createShellBook(libraryFile, BookFileType.CBX);
|
||||
if (generateCover(bookEntity)) {
|
||||
fileProcessingUtils.setBookCoverPath(bookEntity.getId(), bookEntity.getMetadata());
|
||||
fileService.setBookCoverPath(bookEntity.getMetadata());
|
||||
}
|
||||
setMetadata(bookEntity);
|
||||
return bookEntity;
|
||||
@@ -58,7 +61,7 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce
|
||||
try {
|
||||
Optional<BufferedImage> imageOptional = extractImagesFromArchive(file);
|
||||
if (imageOptional.isPresent()) {
|
||||
boolean saved = fileProcessingUtils.saveCoverImage(imageOptional.get(), bookEntity.getId());
|
||||
boolean saved = fileService.saveCoverImages(imageOptional.get(), bookEntity.getId());
|
||||
if (saved) {
|
||||
bookEntity.getMetadata().setCoverUpdatedOn(Instant.now());
|
||||
bookMetadataRepository.save(bookEntity.getMetadata());
|
||||
@@ -170,6 +173,6 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce
|
||||
.replaceAll("(?i)\\.cb[rz7]$", "")
|
||||
.replaceAll("[_\\-]", " ")
|
||||
.trim();
|
||||
bookEntity.getMetadata().setTitle(FileProcessingUtils.truncate(title, 1000));
|
||||
bookEntity.getMetadata().setTitle(truncate(title, 1000));
|
||||
}
|
||||
}
|
||||
+6
-5
@@ -12,6 +12,7 @@ import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.service.BookCreatorService;
|
||||
import com.adityachandel.booklore.service.metadata.MetadataMatchService;
|
||||
import com.adityachandel.booklore.service.metadata.extractor.EpubMetadataExtractor;
|
||||
import com.adityachandel.booklore.util.FileService;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
import io.documentnode.epub4j.domain.Resource;
|
||||
import io.documentnode.epub4j.epub.EpubReader;
|
||||
@@ -26,7 +27,7 @@ import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static com.adityachandel.booklore.service.fileprocessor.FileProcessingUtils.truncate;
|
||||
import static com.adityachandel.booklore.util.FileService.truncate;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@@ -39,11 +40,11 @@ public class EpubProcessor extends AbstractFileProcessor implements BookFileProc
|
||||
BookAdditionalFileRepository bookAdditionalFileRepository,
|
||||
BookCreatorService bookCreatorService,
|
||||
BookMapper bookMapper,
|
||||
FileProcessingUtils fileProcessingUtils,
|
||||
FileService fileService,
|
||||
BookMetadataRepository bookMetadataRepository,
|
||||
MetadataMatchService metadataMatchService,
|
||||
EpubMetadataExtractor epubMetadataExtractor) {
|
||||
super(bookRepository, bookAdditionalFileRepository, bookCreatorService, bookMapper, fileProcessingUtils, metadataMatchService);
|
||||
super(bookRepository, bookAdditionalFileRepository, bookCreatorService, bookMapper, fileService, metadataMatchService);
|
||||
this.epubMetadataExtractor = epubMetadataExtractor;
|
||||
this.bookMetadataRepository = bookMetadataRepository;
|
||||
}
|
||||
@@ -53,7 +54,7 @@ public class EpubProcessor extends AbstractFileProcessor implements BookFileProc
|
||||
BookEntity bookEntity = bookCreatorService.createShellBook(libraryFile, BookFileType.EPUB);
|
||||
setBookMetadata(bookEntity);
|
||||
if (generateCover(bookEntity)) {
|
||||
fileProcessingUtils.setBookCoverPath(bookEntity.getId(), bookEntity.getMetadata());
|
||||
fileService.setBookCoverPath(bookEntity.getMetadata());
|
||||
}
|
||||
return bookEntity;
|
||||
}
|
||||
@@ -147,6 +148,6 @@ public class EpubProcessor extends AbstractFileProcessor implements BookFileProc
|
||||
|
||||
private boolean saveCoverImage(Resource coverImage, long bookId) throws IOException {
|
||||
BufferedImage originalImage = ImageIO.read(new ByteArrayInputStream(coverImage.getData()));
|
||||
return fileProcessingUtils.saveCoverImage(originalImage, bookId);
|
||||
return fileService.saveCoverImages(originalImage, bookId);
|
||||
}
|
||||
}
|
||||
-133
@@ -1,133 +0,0 @@
|
||||
package com.adityachandel.booklore.service.fileprocessor;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
|
||||
import com.adityachandel.booklore.model.entity.BookAdditionalFileEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
|
||||
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.service.appsettings.AppSettingService;
|
||||
import com.adityachandel.booklore.util.FileService;
|
||||
import com.adityachandel.booklore.mapper.BookMapper;
|
||||
import jakarta.transaction.Transactional;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import java.awt.*;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.time.Instant;
|
||||
import java.util.Comparator;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
@AllArgsConstructor
|
||||
@Service
|
||||
@Slf4j
|
||||
public class FileProcessingUtils {
|
||||
|
||||
private final FileService fileService;
|
||||
private final AppSettingService appSettingService;
|
||||
|
||||
public void setBookCoverPath(long bookId, BookMetadataEntity bookMetadataEntity) {
|
||||
bookMetadataEntity.setThumbnail(fileService.getThumbnailPath(bookId) + "/f.jpg");
|
||||
bookMetadataEntity.setCoverUpdatedOn(Instant.now());
|
||||
}
|
||||
|
||||
public boolean saveCoverImage(BufferedImage coverImage, long bookId) throws IOException {
|
||||
String resolution = appSettingService.getAppSettings().getCoverResolution();
|
||||
String[] split = resolution.split("x");
|
||||
int x = Integer.parseInt(split[0]);
|
||||
int y = Integer.parseInt(split[1]);
|
||||
|
||||
BufferedImage resizedImage = resizeImage(coverImage, x, y);
|
||||
File bookDirectory = new File(fileService.getThumbnailPath(bookId));
|
||||
if (!bookDirectory.exists()) {
|
||||
if (!bookDirectory.mkdirs()) {
|
||||
throw new IOException("Failed to create directory: " + bookDirectory.getAbsolutePath());
|
||||
}
|
||||
}
|
||||
String coverImageName = "f.jpg";
|
||||
File coverImageFile = new File(bookDirectory, coverImageName);
|
||||
return ImageIO.write(resizedImage, "JPEG", coverImageFile);
|
||||
}
|
||||
|
||||
public BufferedImage resizeImage(BufferedImage originalImage, int width, int height) {
|
||||
Image tmp = originalImage.getScaledInstance(width, height, Image.SCALE_SMOOTH);
|
||||
BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
|
||||
Graphics2D g2d = resizedImage.createGraphics();
|
||||
g2d.drawImage(tmp, 0, 0, null);
|
||||
g2d.dispose();
|
||||
return resizedImage;
|
||||
}
|
||||
|
||||
public void deleteBookCovers(Set<Long> bookIds) {
|
||||
for (Long bookId : bookIds) {
|
||||
String bookCoverFolder = fileService.getThumbnailPath(bookId);
|
||||
Path folderPath = Paths.get(bookCoverFolder);
|
||||
try {
|
||||
if (Files.exists(folderPath) && Files.isDirectory(folderPath)) {
|
||||
try (Stream<Path> walk = Files.walk(folderPath)) {
|
||||
walk.sorted(Comparator.reverseOrder())
|
||||
.forEach(path -> {
|
||||
try {
|
||||
Files.delete(path);
|
||||
} catch (IOException e) {
|
||||
log.error("Failed to delete file: {} - {}", path, e.getMessage());
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.error("Error processing folder: {} - {}", folderPath, e.getMessage());
|
||||
}
|
||||
}
|
||||
log.info("Deleted {} book covers", bookIds.size());
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Optional<Book> checkForDuplicateAndUpdateMetadataIfNeeded(LibraryFile libraryFile, String hash, BookRepository bookRepository, BookAdditionalFileRepository bookAdditionalFileRepository, BookMapper bookMapper) {
|
||||
if (StringUtils.isBlank(hash)) {
|
||||
log.warn("Skipping file due to missing hash: {}", libraryFile.getFullPath());
|
||||
return Optional.empty();
|
||||
}
|
||||
Optional<BookEntity> existingByHash = bookRepository.findByCurrentHash(hash);
|
||||
if (existingByHash.isPresent()) {
|
||||
BookEntity book = existingByHash.get();
|
||||
String fileName = libraryFile.getFullPath().getFileName().toString();
|
||||
if (!book.getFileName().equals(fileName)) {
|
||||
book.setFileName(fileName);
|
||||
}
|
||||
if (!Objects.equals(book.getLibraryPath().getId(), libraryFile.getLibraryPathEntity().getId())) {
|
||||
book.setLibraryPath(libraryFile.getLibraryPathEntity());
|
||||
book.setFileSubPath(libraryFile.getFileSubPath());
|
||||
}
|
||||
return Optional.of(bookMapper.toBook(book));
|
||||
}
|
||||
Optional<BookAdditionalFileEntity> existingAdditionalFile = bookAdditionalFileRepository.findByAltFormatCurrentHash(hash);
|
||||
if (existingAdditionalFile.isPresent()) {
|
||||
BookAdditionalFileEntity additionalFile = existingAdditionalFile.get();
|
||||
BookEntity book = additionalFile.getBook();
|
||||
|
||||
// Additional file might have a different name or path, so there is no need
|
||||
// to update the file name or library path here
|
||||
return Optional.of(bookMapper.toBook(book));
|
||||
}
|
||||
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
public static String truncate(String input, int maxLength) {
|
||||
return input == null ? null : (input.length() <= maxLength ? input : input.substring(0, maxLength));
|
||||
}
|
||||
}
|
||||
+6
-5
@@ -11,6 +11,7 @@ import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.service.BookCreatorService;
|
||||
import com.adityachandel.booklore.service.metadata.MetadataMatchService;
|
||||
import com.adityachandel.booklore.service.metadata.extractor.PdfMetadataExtractor;
|
||||
import com.adityachandel.booklore.util.FileService;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
@@ -26,7 +27,7 @@ import java.io.IOException;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
import static com.adityachandel.booklore.service.fileprocessor.FileProcessingUtils.truncate;
|
||||
import static com.adityachandel.booklore.util.FileService.truncate;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@@ -39,11 +40,11 @@ public class PdfProcessor extends AbstractFileProcessor implements BookFileProce
|
||||
BookAdditionalFileRepository bookAdditionalFileRepository,
|
||||
BookCreatorService bookCreatorService,
|
||||
BookMapper bookMapper,
|
||||
FileProcessingUtils fileProcessingUtils,
|
||||
FileService fileService,
|
||||
BookMetadataRepository bookMetadataRepository,
|
||||
MetadataMatchService metadataMatchService,
|
||||
PdfMetadataExtractor pdfMetadataExtractor) {
|
||||
super(bookRepository, bookAdditionalFileRepository, bookCreatorService, bookMapper, fileProcessingUtils, metadataMatchService);
|
||||
super(bookRepository, bookAdditionalFileRepository, bookCreatorService, bookMapper, fileService, metadataMatchService);
|
||||
this.pdfMetadataExtractor = pdfMetadataExtractor;
|
||||
this.bookMetadataRepository = bookMetadataRepository;
|
||||
}
|
||||
@@ -52,7 +53,7 @@ public class PdfProcessor extends AbstractFileProcessor implements BookFileProce
|
||||
public BookEntity processNewFile(LibraryFile libraryFile) {
|
||||
BookEntity bookEntity = bookCreatorService.createShellBook(libraryFile, BookFileType.PDF);
|
||||
if (generateCover(bookEntity)) {
|
||||
fileProcessingUtils.setBookCoverPath(bookEntity.getId(), bookEntity.getMetadata());
|
||||
fileService.setBookCoverPath(bookEntity.getMetadata());
|
||||
}
|
||||
extractAndSetMetadata(bookEntity);
|
||||
return bookEntity;
|
||||
@@ -139,6 +140,6 @@ public class PdfProcessor extends AbstractFileProcessor implements BookFileProce
|
||||
|
||||
private boolean generateCoverImageAndSave(Long bookId, PDDocument document) throws IOException {
|
||||
BufferedImage coverImage = new PDFRenderer(document).renderImageWithDPI(0, 300, ImageType.RGB);
|
||||
return fileProcessingUtils.saveCoverImage(coverImage, bookId);
|
||||
return fileService.saveCoverImages(coverImage, bookId);
|
||||
}
|
||||
}
|
||||
+1
-4
@@ -18,7 +18,6 @@ import com.adityachandel.booklore.util.FileService;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@@ -243,9 +242,7 @@ public class LibraryProcessingService {
|
||||
List<BookEntity> books = bookRepository.findAllById(bookIds);
|
||||
for (BookEntity book : books) {
|
||||
try {
|
||||
if (book.getMetadata() != null && StringUtils.isNotBlank(book.getMetadata().getThumbnail())) {
|
||||
deleteDirectoryRecursively(Path.of(fileService.getThumbnailPath(book.getId())));
|
||||
}
|
||||
deleteDirectoryRecursively(Path.of(fileService.getImagesFolder(book.getId())));
|
||||
Path backupDir = Path.of(fileService.getBookMetadataBackupPath(book.getId()));
|
||||
if (Files.exists(backupDir)) {
|
||||
deleteDirectoryRecursively(backupDir);
|
||||
|
||||
+5
-7
@@ -1,6 +1,6 @@
|
||||
package com.adityachandel.booklore.service.library;
|
||||
|
||||
import com.adityachandel.booklore.config.security.AuthenticationService;
|
||||
import com.adityachandel.booklore.config.security.service.AuthenticationService;
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.mapper.BookMapper;
|
||||
import com.adityachandel.booklore.mapper.LibraryMapper;
|
||||
@@ -20,16 +20,14 @@ import com.adityachandel.booklore.repository.LibraryPathRepository;
|
||||
import com.adityachandel.booklore.repository.LibraryRepository;
|
||||
import com.adityachandel.booklore.repository.UserRepository;
|
||||
import com.adityachandel.booklore.service.NotificationService;
|
||||
import com.adityachandel.booklore.util.SecurityContextVirtualThread;
|
||||
import com.adityachandel.booklore.service.fileprocessor.FileProcessingUtils;
|
||||
import com.adityachandel.booklore.service.monitoring.MonitoringService;
|
||||
import com.adityachandel.booklore.util.FileService;
|
||||
import com.adityachandel.booklore.util.SecurityContextVirtualThread;
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import jakarta.transaction.Transactional;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.dao.InvalidDataAccessApiUsageException;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@@ -53,7 +51,7 @@ public class LibraryService {
|
||||
private final BookMapper bookMapper;
|
||||
private final LibraryMapper libraryMapper;
|
||||
private final NotificationService notificationService;
|
||||
private final FileProcessingUtils fileProcessingUtils;
|
||||
private final FileService fileService;
|
||||
private final MonitoringService monitoringService;
|
||||
private final AuthenticationService authenticationService;
|
||||
private final UserRepository userRepository;
|
||||
@@ -227,7 +225,7 @@ public class LibraryService {
|
||||
monitoringService.unregisterLibrary(id);
|
||||
});
|
||||
Set<Long> bookIds = library.getBookEntities().stream().map(BookEntity::getId).collect(Collectors.toSet());
|
||||
fileProcessingUtils.deleteBookCovers(bookIds);
|
||||
fileService.deleteBookCovers(bookIds);
|
||||
libraryRepository.deleteById(id);
|
||||
log.info("Library deleted successfully: {}", id);
|
||||
}
|
||||
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
package com.adityachandel.booklore.service.metadata;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.CoverImage;
|
||||
import com.adityachandel.booklore.model.dto.request.CoverFetchRequest;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface BookCoverProvider {
|
||||
List<CoverImage> getCovers(CoverFetchRequest request);
|
||||
}
|
||||
|
||||
+2
-8
@@ -216,14 +216,8 @@ public class BookMetadataUpdater {
|
||||
}
|
||||
if (!set) return;
|
||||
if (!StringUtils.hasText(m.getThumbnailUrl()) || isLocalOrPrivateUrl(m.getThumbnailUrl())) return;
|
||||
|
||||
try {
|
||||
String path = fileService.createThumbnail(bookId, m.getThumbnailUrl());
|
||||
e.setThumbnail(path);
|
||||
e.setCoverUpdatedOn(Instant.now());
|
||||
} catch (IOException ex) {
|
||||
log.warn("Thumbnail generation failed for book {}: {}", bookId, ex.getMessage());
|
||||
}
|
||||
fileService.createThumbnailFromUrl(bookId, m.getThumbnailUrl());
|
||||
e.setCoverUpdatedOn(Instant.now());
|
||||
}
|
||||
|
||||
private void updateLocks(BookMetadata m, BookMetadataEntity e) {
|
||||
|
||||
+155
@@ -0,0 +1,155 @@
|
||||
package com.adityachandel.booklore.service.metadata;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.CoverImage;
|
||||
import com.adityachandel.booklore.model.dto.request.CoverFetchRequest;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.jsoup.Connection;
|
||||
import org.jsoup.Jsoup;
|
||||
import org.jsoup.nodes.Document;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.*;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@AllArgsConstructor
|
||||
public class DuckDuckGoCoverService implements BookCoverProvider {
|
||||
|
||||
private static final String SEARCH_BASE_URL = "https://duckduckgo.com/?q=";
|
||||
private static final String JSON_BASE_URL = "https://duckduckgo.com/i.js?o=json&q=";
|
||||
private static final String SITE_FILTER = "+(site%3Aamazon.com+OR+site%3Agoodreads.com)";
|
||||
private static final String SEARCH_PARAMS = "&iar=images&iaf=size%3ALarge%2Clayout%3ATall";
|
||||
private static final String JSON_PARAMS = "&iar=images&iaf=size%3ALarge%2Clayout%3ATall";
|
||||
|
||||
private static final String USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36";
|
||||
private static final String REFERRER = "https://duckduckgo.com/";
|
||||
private static final Map<String, String> DEFAULT_HEADERS = Map.ofEntries(
|
||||
Map.entry("accept", "text/html, application/json"),
|
||||
Map.entry("content-type", "application/json"),
|
||||
Map.entry("user-agent", USER_AGENT)
|
||||
);
|
||||
|
||||
private final ObjectMapper mapper;
|
||||
|
||||
public List<CoverImage> getCovers(CoverFetchRequest request) {
|
||||
String title = request.getTitle();
|
||||
String author = request.getAuthor();
|
||||
String searchTerm = (author != null && !author.isEmpty())
|
||||
? title + " " + author + " book"
|
||||
: title + " book";
|
||||
|
||||
String encodedSiteQuery = URLEncoder.encode(searchTerm, StandardCharsets.UTF_8);
|
||||
String siteUrl = SEARCH_BASE_URL + encodedSiteQuery + SITE_FILTER + SEARCH_PARAMS;
|
||||
Document siteDoc = getDocument(siteUrl);
|
||||
Pattern tokenPattern = Pattern.compile("vqd=\"(\\d+-\\d+)\"");
|
||||
Matcher siteMatcher = tokenPattern.matcher(siteDoc.html());
|
||||
if (!siteMatcher.find()) {
|
||||
log.error("Could not find search token for site-filtered images!");
|
||||
return Collections.emptyList();
|
||||
}
|
||||
String siteSearchToken = siteMatcher.group(1);
|
||||
List<CoverImage> siteFilteredImages = fetchImagesFromApi(searchTerm + " (site:amazon.com OR site:goodreads.com)", siteSearchToken);
|
||||
siteFilteredImages.removeIf(dto -> dto.getWidth() < 350);
|
||||
siteFilteredImages.removeIf(dto -> dto.getWidth() >= dto.getHeight());
|
||||
if (siteFilteredImages.size() > 7) {
|
||||
siteFilteredImages = siteFilteredImages.subList(0, 7);
|
||||
}
|
||||
|
||||
String generalQuery = searchTerm;
|
||||
String encodedGeneralQuery = URLEncoder.encode(generalQuery, StandardCharsets.UTF_8);
|
||||
String generalUrl = SEARCH_BASE_URL + encodedGeneralQuery + SEARCH_PARAMS;
|
||||
Document generalDoc = getDocument(generalUrl);
|
||||
Matcher generalMatcher = tokenPattern.matcher(generalDoc.html());
|
||||
List<CoverImage> generalBookImages = new ArrayList<>();
|
||||
if (generalMatcher.find()) {
|
||||
String generalSearchToken = generalMatcher.group(1);
|
||||
generalBookImages = fetchImagesFromApi(generalQuery, generalSearchToken);
|
||||
generalBookImages.removeIf(dto -> dto.getWidth() < 350);
|
||||
generalBookImages.removeIf(dto -> dto.getWidth() >= dto.getHeight());
|
||||
Set<String> siteUrls = siteFilteredImages.stream().map(CoverImage::getUrl).collect(Collectors.toSet());
|
||||
generalBookImages.removeIf(dto -> siteUrls.contains(dto.getUrl()));
|
||||
if (generalBookImages.size() > 10) {
|
||||
generalBookImages = generalBookImages.subList(0, 10);
|
||||
}
|
||||
}
|
||||
|
||||
List<CoverImage> allImages = new ArrayList<>(siteFilteredImages);
|
||||
allImages.addAll(generalBookImages);
|
||||
|
||||
for (int i = 0; i < allImages.size(); i++) {
|
||||
CoverImage img = allImages.get(i);
|
||||
allImages.set(i, new CoverImage(
|
||||
img.getUrl(),
|
||||
img.getWidth(),
|
||||
img.getHeight(),
|
||||
i + 1
|
||||
));
|
||||
}
|
||||
|
||||
return allImages;
|
||||
}
|
||||
|
||||
private List<CoverImage> fetchImagesFromApi(String query, String searchToken) {
|
||||
List<CoverImage> priority = new ArrayList<>();
|
||||
List<CoverImage> others = new ArrayList<>();
|
||||
try {
|
||||
String url = JSON_BASE_URL
|
||||
+ URLEncoder.encode(query, StandardCharsets.UTF_8)
|
||||
+ JSON_PARAMS
|
||||
+ "&vqd=" + searchToken;
|
||||
|
||||
Connection.Response resp = Jsoup.connect(url)
|
||||
.ignoreContentType(true)
|
||||
.referrer(REFERRER)
|
||||
.followRedirects(true)
|
||||
.headers(DEFAULT_HEADERS)
|
||||
.method(Connection.Method.GET)
|
||||
.execute();
|
||||
|
||||
String json = resp.body();
|
||||
JsonNode results = mapper.readTree(json).path("results");
|
||||
if (results.isArray()) {
|
||||
for (JsonNode img : results) {
|
||||
String link = img.path("image").asText();
|
||||
int w = img.path("width").asInt();
|
||||
int h = img.path("height").asInt();
|
||||
CoverImage dto = new CoverImage(link, w, h, 0);
|
||||
if (link.contains("amazon") || link.contains("goodreads")) {
|
||||
priority.add(dto);
|
||||
} else {
|
||||
others.add(dto);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("Error fetching images from DuckDuckGo", e);
|
||||
}
|
||||
List<CoverImage> all = new ArrayList<>(priority);
|
||||
all.addAll(others);
|
||||
return all;
|
||||
}
|
||||
|
||||
private Document getDocument(String url) {
|
||||
try {
|
||||
Connection.Response response = Jsoup.connect(url)
|
||||
.referrer(REFERRER)
|
||||
.followRedirects(true)
|
||||
.headers(DEFAULT_HEADERS)
|
||||
.method(Connection.Method.GET)
|
||||
.execute();
|
||||
return response.parse();
|
||||
} catch (IOException e) {
|
||||
log.error("Error parsing url: {}", url, e);
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
-1
@@ -61,7 +61,6 @@ public class MetadataMatchService {
|
||||
if (isPositive(metadata.getGoodreadsReviewCount())) score += weights.getGoodreadsReviewCount();
|
||||
if (isPositive(metadata.getHardcoverRating())) score += weights.getHardcoverRating();
|
||||
if (isPositive(metadata.getHardcoverReviewCount())) score += weights.getHardcoverReviewCount();
|
||||
if (isPresent(metadata.getThumbnail())) score += weights.getCoverImage();
|
||||
|
||||
return (score / totalWeight) * 100f;
|
||||
}
|
||||
|
||||
+1
-6
@@ -8,16 +8,11 @@ import com.adityachandel.booklore.model.dto.request.FetchMetadataRequest;
|
||||
import com.adityachandel.booklore.model.dto.request.MetadataRefreshOptions;
|
||||
import com.adityachandel.booklore.model.dto.request.MetadataRefreshRequest;
|
||||
import com.adityachandel.booklore.model.dto.settings.AppSettings;
|
||||
import com.adityachandel.booklore.model.dto.settings.MetadataPublicReviewsSettings;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryEntity;
|
||||
import com.adityachandel.booklore.model.entity.MetadataFetchJobEntity;
|
||||
import com.adityachandel.booklore.model.entity.MetadataFetchProposalEntity;
|
||||
import com.adityachandel.booklore.model.enums.FetchedMetadataProposalStatus;
|
||||
import com.adityachandel.booklore.model.enums.MetadataFetchTaskStatus;
|
||||
import com.adityachandel.booklore.model.enums.MetadataProvider;
|
||||
import com.adityachandel.booklore.model.enums.EventTaskType;
|
||||
import com.adityachandel.booklore.model.enums.TaskStatus;
|
||||
import com.adityachandel.booklore.model.enums.*;
|
||||
import com.adityachandel.booklore.model.websocket.Topic;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.repository.LibraryRepository;
|
||||
|
||||
+4
-9
@@ -78,7 +78,7 @@ public class EpubMetadataBackupRestoreService extends AbstractMetadataBackupRest
|
||||
BookMetadata backupMetadata = readMetadata(metadataFile, bookEntity.getId());
|
||||
bookMetadataRestorer.restoreMetadata(bookEntity, backupMetadata, coverFile.toString());
|
||||
|
||||
updateThumbnailIfNeeded(bookEntity.getId(), coverFile, bookEntity.getMetadata());
|
||||
updateThumbnailIfNeeded(bookEntity.getMetadata(), coverFile, bookEntity.getId());
|
||||
|
||||
log.info("Successfully restored embedded metadata for EPUB book ID {}", bookEntity.getId());
|
||||
}
|
||||
@@ -102,13 +102,8 @@ public class EpubMetadataBackupRestoreService extends AbstractMetadataBackupRest
|
||||
return BookFileType.EPUB;
|
||||
}
|
||||
|
||||
private void updateThumbnailIfNeeded(long bookId, Path coverPath, BookMetadataEntity metadata) {
|
||||
try {
|
||||
String thumbnailPath = fileService.createThumbnail(bookId, coverPath.toString());
|
||||
metadata.setThumbnail(thumbnailPath);
|
||||
metadata.setCoverUpdatedOn(Instant.now());
|
||||
} catch (IOException e) {
|
||||
log.error("Failed to update thumbnail for book ID {}: {}", bookId, e.getMessage(), e);
|
||||
}
|
||||
private void updateThumbnailIfNeeded(BookMetadataEntity metadata, Path coverFile, long bookId) throws IOException {
|
||||
/*String thumbnailPath = fileService.createThumbnailFromFile(bookId, coverFile.toString());*/
|
||||
metadata.setCoverUpdatedOn(Instant.now());
|
||||
}
|
||||
}
|
||||
+81
@@ -1,5 +1,6 @@
|
||||
package com.adityachandel.booklore.service.migration;
|
||||
|
||||
import com.adityachandel.booklore.config.AppProperties;
|
||||
import com.adityachandel.booklore.model.entity.AppMigrationEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.repository.AppMigrationRepository;
|
||||
@@ -7,15 +8,23 @@ import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.service.BookQueryService;
|
||||
import com.adityachandel.booklore.service.FileFingerprint;
|
||||
import com.adityachandel.booklore.service.metadata.MetadataMatchService;
|
||||
import com.adityachandel.booklore.util.FileService;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
import jakarta.transaction.Transactional;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
|
||||
@Slf4j
|
||||
@@ -27,6 +36,8 @@ public class AppMigrationService {
|
||||
private BookRepository bookRepository;
|
||||
private BookQueryService bookQueryService;
|
||||
private MetadataMatchService metadataMatchService;
|
||||
private AppProperties appProperties;
|
||||
private FileService fileService;
|
||||
|
||||
@Transactional
|
||||
public void populateMissingFileSizesOnce() {
|
||||
@@ -102,4 +113,74 @@ public class AppMigrationService {
|
||||
"Calculate and store initialHash and currentHash for all books"
|
||||
));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void populateCoversAndResizeThumbnails() {
|
||||
if (migrationRepository.existsById("populateCoversAndResizeThumbnails")) return;
|
||||
|
||||
long start = System.nanoTime();
|
||||
log.info("Starting migration: populateCoversAndResizeThumbnails");
|
||||
|
||||
String dataFolder = appProperties.getPathConfig();
|
||||
Path thumbsDir = Paths.get(dataFolder, "thumbs");
|
||||
Path imagesDir = Paths.get(dataFolder, "images");
|
||||
|
||||
try {
|
||||
if (Files.exists(thumbsDir)) {
|
||||
Files.walk(thumbsDir)
|
||||
.filter(Files::isRegularFile)
|
||||
.forEach(path -> {
|
||||
try {
|
||||
// Load original image
|
||||
BufferedImage originalImage = ImageIO.read(path.toFile());
|
||||
if (originalImage == null) {
|
||||
log.warn("Skipping non-image file: {}", path);
|
||||
return;
|
||||
}
|
||||
|
||||
// Extract bookId from folder structure
|
||||
Path relative = thumbsDir.relativize(path); // e.g., "11/f.jpg"
|
||||
String bookId = relative.getParent().toString(); // "11"
|
||||
|
||||
Path bookDir = imagesDir.resolve(bookId);
|
||||
Files.createDirectories(bookDir);
|
||||
|
||||
// Copy original to cover.jpg
|
||||
Path coverFile = bookDir.resolve("cover.jpg");
|
||||
ImageIO.write(originalImage, "jpg", coverFile.toFile());
|
||||
|
||||
// Resize and save thumbnail.jpg
|
||||
BufferedImage resized = fileService.resizeImage(originalImage, 250, 350);
|
||||
Path thumbnailFile = bookDir.resolve("thumbnail.jpg");
|
||||
ImageIO.write(resized, "jpg", thumbnailFile.toFile());
|
||||
|
||||
log.debug("Processed book {}: cover={} thumbnail={}", bookId, coverFile, thumbnailFile);
|
||||
} catch (IOException e) {
|
||||
log.error("Error processing file {}", path, e);
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
});
|
||||
|
||||
// Delete old thumbs directory
|
||||
log.info("Deleting old thumbs directory: {}", thumbsDir);
|
||||
Files.walk(thumbsDir)
|
||||
.sorted(Comparator.reverseOrder())
|
||||
.map(Path::toFile)
|
||||
.forEach(File::delete);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.error("Error during migration populateCoversAndResizeThumbnails", e);
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
|
||||
migrationRepository.save(new AppMigrationEntity(
|
||||
"populateCoversAndResizeThumbnails",
|
||||
LocalDateTime.now(),
|
||||
"Copy thumbnails to images/{bookId}/cover.jpg and create resized 250x350 images as thumbnail.jpg"
|
||||
));
|
||||
|
||||
long elapsedMs = (System.nanoTime() - start) / 1_000_000;
|
||||
log.info("Completed migration: populateCoversAndResizeThumbnails in {} ms", elapsedMs);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+1
@@ -16,5 +16,6 @@ public class AppMigrationStartup {
|
||||
appMigrationService.populateMissingFileSizesOnce();
|
||||
appMigrationService.populateMetadataScoresOnce();
|
||||
appMigrationService.populateFileHashesOnce();
|
||||
appMigrationService.populateCoversAndResizeThumbnails();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -132,7 +132,7 @@ public class OpdsService {
|
||||
""".formatted(book.getId(), fileMimeType(book)));
|
||||
|
||||
if (book.getMetadata().getCoverUpdatedOn() != null) {
|
||||
String coverPath = "/api/v1/opds/" + book.getId() + "/cover.jpg?" + book.getMetadata().getCoverUpdatedOn();
|
||||
String coverPath = "/api/v1/opds/" + book.getId() + "/cover?" + book.getMetadata().getCoverUpdatedOn();
|
||||
feed.append("""
|
||||
<link rel="http://opds-spec.org/image" href="%s" type="image/jpeg"/>
|
||||
<link rel="http://opds-spec.org/image/thumbnail" href="%s" type="image/jpeg"/>
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
package com.adityachandel.booklore.service.recommender;
|
||||
|
||||
import com.adityachandel.booklore.config.security.AuthenticationService;
|
||||
import com.adityachandel.booklore.config.security.service.AuthenticationService;
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.mapper.BookMapper;
|
||||
import com.adityachandel.booklore.model.dto.*;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
package com.adityachandel.booklore.service.user;
|
||||
|
||||
import com.adityachandel.booklore.config.security.AuthenticationService;
|
||||
import com.adityachandel.booklore.config.security.service.AuthenticationService;
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.mapper.custom.BookLoreUserTransformer;
|
||||
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||
|
||||
@@ -2,24 +2,37 @@ package com.adityachandel.booklore.util;
|
||||
|
||||
import com.adityachandel.booklore.config.AppProperties;
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.service.appsettings.AppSettingService;
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
|
||||
import com.adityachandel.booklore.model.entity.BookAdditionalFileEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
|
||||
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.mapper.BookMapper;
|
||||
import jakarta.transaction.Transactional;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.core.io.UrlResource;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import java.awt.*;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.URL;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.time.Instant;
|
||||
import java.util.Comparator;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
@@ -27,109 +40,159 @@ import java.nio.file.Paths;
|
||||
public class FileService {
|
||||
|
||||
private final AppProperties appProperties;
|
||||
private final AppSettingService appSettingService;
|
||||
|
||||
// @formatter:off
|
||||
private static final String IMAGES_DIR = "images";
|
||||
private static final String THUMBNAIL_FILENAME = "thumbnail.jpg";
|
||||
private static final String COVER_FILENAME = "cover.jpg";
|
||||
private static final String JPEG_MIME_TYPE = "image/jpeg";
|
||||
private static final String PNG_MIME_TYPE = "image/png";
|
||||
private static final long MAX_FILE_SIZE_BYTES = 5L * 1024 * 1024;
|
||||
private static final int THUMBNAIL_WIDTH = 250;
|
||||
private static final int THUMBNAIL_HEIGHT = 350;
|
||||
private static final String IMAGE_FORMAT = "JPEG";
|
||||
// @formatter:on
|
||||
|
||||
public void createThumbnailFromFile(long bookId, MultipartFile file) {
|
||||
try {
|
||||
validateCoverFile(file);
|
||||
String outputFolder = getThumbnailPath(bookId);
|
||||
File folder = new File(outputFolder);
|
||||
if (!folder.exists() && !folder.mkdirs()) {
|
||||
throw ApiError.DIRECTORY_CREATION_FAILED.createException(folder.getAbsolutePath());
|
||||
}
|
||||
BufferedImage originalImage = ImageIO.read(file.getInputStream());
|
||||
if (originalImage == null) {
|
||||
throw ApiError.IMAGE_NOT_FOUND.createException();
|
||||
}
|
||||
BufferedImage resizedImage = resizeImage(originalImage);
|
||||
File outputFile = new File(folder, "f.jpg");
|
||||
ImageIO.write(resizedImage, "JPEG", outputFile);
|
||||
log.info("Thumbnail created and saved at: {}", outputFile.getAbsolutePath());
|
||||
boolean success = saveCoverImages(originalImage, bookId);
|
||||
if (!success) {
|
||||
throw ApiError.FILE_READ_ERROR.createException("Failed to save cover images");
|
||||
}
|
||||
log.info("Cover images created and saved for book ID: {}", bookId);
|
||||
} catch (Exception e) {
|
||||
log.error("An error occurred while creating the thumbnail: {}", e.getMessage(), e);
|
||||
throw ApiError.FILE_READ_ERROR.createException(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public boolean saveCoverImages(BufferedImage coverImage, long bookId) throws IOException {
|
||||
String folderPath = getImagesFolder(bookId);
|
||||
File folder = new File(folderPath);
|
||||
if (!folder.exists() && !folder.mkdirs()) {
|
||||
throw new IOException("Failed to create directory: " + folder.getAbsolutePath());
|
||||
}
|
||||
File originalFile = new File(folder, COVER_FILENAME);
|
||||
boolean originalSaved = ImageIO.write(coverImage, IMAGE_FORMAT, originalFile);
|
||||
BufferedImage thumb = resizeImage(coverImage, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT);
|
||||
File thumbnailFile = new File(folder, THUMBNAIL_FILENAME);
|
||||
boolean thumbnailSaved = ImageIO.write(thumb, IMAGE_FORMAT, thumbnailFile);
|
||||
return originalSaved && thumbnailSaved;
|
||||
}
|
||||
|
||||
public BufferedImage resizeImage(BufferedImage originalImage, int width, int height) {
|
||||
Image tmp = originalImage.getScaledInstance(width, height, Image.SCALE_SMOOTH);
|
||||
BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
|
||||
Graphics2D g2d = resizedImage.createGraphics();
|
||||
g2d.drawImage(tmp, 0, 0, null);
|
||||
g2d.dispose();
|
||||
return resizedImage;
|
||||
}
|
||||
|
||||
public void saveImage(byte[] imageData, String filePath) throws IOException {
|
||||
BufferedImage originalImage = ImageIO.read(new ByteArrayInputStream(imageData));
|
||||
File outputFile = new File(filePath);
|
||||
File parentDir = outputFile.getParentFile();
|
||||
if (!parentDir.exists() && !parentDir.mkdirs()) {
|
||||
throw new IOException("Failed to create directory: " + parentDir);
|
||||
}
|
||||
ImageIO.write(originalImage, IMAGE_FORMAT, outputFile);
|
||||
log.info("Image saved successfully to: {}", filePath);
|
||||
}
|
||||
|
||||
public void setBookCoverPath(BookMetadataEntity bookMetadataEntity) {
|
||||
bookMetadataEntity.setCoverUpdatedOn(Instant.now());
|
||||
}
|
||||
|
||||
public void deleteBookCovers(Set<Long> bookIds) {
|
||||
for (Long bookId : bookIds) {
|
||||
String bookCoverFolder = getImagesFolder(bookId);
|
||||
Path folderPath = Paths.get(bookCoverFolder);
|
||||
try {
|
||||
if (Files.exists(folderPath) && Files.isDirectory(folderPath)) {
|
||||
try (Stream<Path> walk = Files.walk(folderPath)) {
|
||||
walk.sorted(Comparator.reverseOrder())
|
||||
.forEach(path -> {
|
||||
try {
|
||||
Files.delete(path);
|
||||
} catch (IOException e) {
|
||||
log.error("Failed to delete file: {} - {}", path, e.getMessage());
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.error("Error processing folder: {} - {}", folderPath, e.getMessage());
|
||||
}
|
||||
}
|
||||
log.info("Deleted {} book covers", bookIds.size());
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Optional<Book> checkForDuplicateAndUpdateMetadataIfNeeded(LibraryFile libraryFile, String hash, BookRepository bookRepository, BookAdditionalFileRepository bookAdditionalFileRepository, BookMapper bookMapper) {
|
||||
if (StringUtils.isBlank(hash)) {
|
||||
log.warn("Skipping file due to missing hash: {}", libraryFile.getFullPath());
|
||||
return Optional.empty();
|
||||
}
|
||||
Optional<BookEntity> existingByHash = bookRepository.findByCurrentHash(hash);
|
||||
if (existingByHash.isPresent()) {
|
||||
BookEntity book = existingByHash.get();
|
||||
String fileName = libraryFile.getFullPath().getFileName().toString();
|
||||
if (!book.getFileName().equals(fileName)) {
|
||||
book.setFileName(fileName);
|
||||
}
|
||||
if (!Objects.equals(book.getLibraryPath().getId(), libraryFile.getLibraryPathEntity().getId())) {
|
||||
book.setLibraryPath(libraryFile.getLibraryPathEntity());
|
||||
book.setFileSubPath(libraryFile.getFileSubPath());
|
||||
}
|
||||
return Optional.of(bookMapper.toBook(book));
|
||||
}
|
||||
Optional<BookAdditionalFileEntity> existingAdditionalFile = bookAdditionalFileRepository.findByAltFormatCurrentHash(hash);
|
||||
if (existingAdditionalFile.isPresent()) {
|
||||
BookAdditionalFileEntity additionalFile = existingAdditionalFile.get();
|
||||
BookEntity book = additionalFile.getBook();
|
||||
|
||||
// Additional file might have a different name or path, so there is no need
|
||||
// to update the file name or library path here
|
||||
return Optional.of(bookMapper.toBook(book));
|
||||
}
|
||||
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
public static String truncate(String input, int maxLength) {
|
||||
return input == null ? null : (input.length() <= maxLength ? input : input.substring(0, maxLength));
|
||||
}
|
||||
|
||||
private void validateCoverFile(MultipartFile file) {
|
||||
if (file.isEmpty()) {
|
||||
throw new IllegalArgumentException("Uploaded file is empty");
|
||||
}
|
||||
String contentType = file.getContentType();
|
||||
if (!("image/jpeg".equalsIgnoreCase(contentType) || "image/png".equalsIgnoreCase(contentType))) {
|
||||
if (!(JPEG_MIME_TYPE.equalsIgnoreCase(contentType) || PNG_MIME_TYPE.equalsIgnoreCase(contentType))) {
|
||||
throw new IllegalArgumentException("Only JPEG and PNG files are allowed");
|
||||
}
|
||||
long maxFileSize = 5 * 1024 * 1024;
|
||||
if (file.getSize() > maxFileSize) {
|
||||
if (file.getSize() > MAX_FILE_SIZE_BYTES) {
|
||||
throw new IllegalArgumentException("File size must not exceed 5 MB");
|
||||
}
|
||||
}
|
||||
|
||||
public Resource getBookCover(String thumbnailPath) {
|
||||
Path thumbPath;
|
||||
if (thumbnailPath == null || thumbnailPath.isEmpty()) {
|
||||
thumbPath = Paths.get(getMissingThumbnailPath());
|
||||
} else {
|
||||
thumbPath = Paths.get(thumbnailPath);
|
||||
}
|
||||
try {
|
||||
Resource resource = new UrlResource(thumbPath.toUri());
|
||||
if (resource.exists() && resource.isReadable()) {
|
||||
return resource;
|
||||
} else {
|
||||
throw ApiError.IMAGE_NOT_FOUND.createException(thumbPath);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw ApiError.IMAGE_NOT_FOUND.createException(thumbPath);
|
||||
}
|
||||
|
||||
public String getImagesFolder(long bookId) {
|
||||
return appProperties.getPathConfig() + "/" + IMAGES_DIR + "/" + bookId + "/";
|
||||
}
|
||||
|
||||
public String createThumbnail(long bookId, String thumbnailUrl) throws IOException {
|
||||
String newFilename = "f.jpg";
|
||||
resizeAndSaveImage(thumbnailUrl, new File(getThumbnailPath(bookId)), newFilename);
|
||||
return getThumbnailPath(bookId) + newFilename;
|
||||
public String getThumbnailFile(long bookId) {
|
||||
return appProperties.getPathConfig() + "/" + IMAGES_DIR + "/" + bookId + "/" + THUMBNAIL_FILENAME;
|
||||
}
|
||||
|
||||
private void resizeAndSaveImage(String imageSource, File outputFolder, String outputFileName) throws IOException {
|
||||
BufferedImage originalImage;
|
||||
File file = new File(imageSource);
|
||||
if (file.exists()) {
|
||||
try (InputStream inputStream = new FileInputStream(file)) {
|
||||
originalImage = ImageIO.read(inputStream);
|
||||
}
|
||||
} else {
|
||||
try (InputStream inputStream = new URL(imageSource).openStream()) {
|
||||
originalImage = ImageIO.read(inputStream);
|
||||
}
|
||||
}
|
||||
if (originalImage == null) {
|
||||
throw new IOException("Failed to read image from: " + imageSource);
|
||||
}
|
||||
BufferedImage resizedImage = resizeImage(originalImage);
|
||||
if (!outputFolder.exists() && !outputFolder.mkdirs()) {
|
||||
throw new IOException("Failed to create output directory: " + outputFolder.getAbsolutePath());
|
||||
}
|
||||
File outputFile = new File(outputFolder, outputFileName);
|
||||
ImageIO.write(resizedImage, "JPEG", outputFile);
|
||||
log.info("Image saved to: {}", outputFile.getAbsolutePath());
|
||||
}
|
||||
|
||||
private BufferedImage resizeImage(BufferedImage originalImage) {
|
||||
String resolution = appSettingService.getAppSettings().getCoverResolution();
|
||||
String[] split = resolution.split("x");
|
||||
int x = Integer.parseInt(split[0]);
|
||||
int y = Integer.parseInt(split[1]);
|
||||
|
||||
BufferedImage resizedImage = new BufferedImage(x, y, BufferedImage.TYPE_INT_RGB);
|
||||
Graphics2D g2d = resizedImage.createGraphics();
|
||||
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
|
||||
g2d.drawImage(originalImage, 0, 0, x, y, null);
|
||||
g2d.dispose();
|
||||
return resizedImage;
|
||||
}
|
||||
|
||||
public String getThumbnailPath(long bookId) {
|
||||
return appProperties.getPathConfig() + "/thumbs/" + bookId + "/";
|
||||
public String getCoverFile(long bookId) {
|
||||
return appProperties.getPathConfig() + "/" + IMAGES_DIR + "/" + bookId + "/" + COVER_FILENAME;
|
||||
}
|
||||
|
||||
public String getMetadataBackupPath() {
|
||||
@@ -148,15 +211,35 @@ public class FileService {
|
||||
return appProperties.getPathConfig() + "/pdf_cache";
|
||||
}
|
||||
|
||||
public String getMissingThumbnailPath() {
|
||||
return appProperties.getPathConfig() + "/thumbs/missing/m.jpg";
|
||||
}
|
||||
|
||||
public String getTempBookdropCoverImagePath(long bookdropFileId) {
|
||||
return Paths.get(appProperties.getPathConfig(), "bookdrop_temp", bookdropFileId + ".jpg").toString();
|
||||
}
|
||||
|
||||
public String getBookdropPath() {
|
||||
return appProperties.getBookdropFolder();
|
||||
public void createThumbnailFromUrl(long bookId, String imageUrl) {
|
||||
try {
|
||||
BufferedImage originalImage = downloadImageFromUrl(imageUrl);
|
||||
boolean success = saveCoverImages(originalImage, bookId);
|
||||
if (!success) {
|
||||
throw ApiError.FILE_READ_ERROR.createException("Failed to save cover images");
|
||||
}
|
||||
log.info("Cover images created and saved from URL for book ID: {}", bookId);
|
||||
} catch (Exception e) {
|
||||
log.error("An error occurred while creating thumbnail from URL: {}", e.getMessage(), e);
|
||||
throw ApiError.FILE_READ_ERROR.createException(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private BufferedImage downloadImageFromUrl(String imageUrl) throws IOException {
|
||||
try {
|
||||
URL url = new URL(imageUrl);
|
||||
BufferedImage image = ImageIO.read(url);
|
||||
if (image == null) {
|
||||
throw new IOException("Unable to read image from URL: " + imageUrl);
|
||||
}
|
||||
return image;
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to download image from URL: {} - {}", imageUrl, e.getMessage());
|
||||
throw new IOException("Failed to download image from URL: " + imageUrl, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
package com.adityachandel.booklore.util;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import java.awt.*;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
|
||||
@Service
|
||||
public class ImageUtils {
|
||||
|
||||
public void saveImage(byte[] imageData, String filePath, Integer width, Integer height) throws IOException {
|
||||
BufferedImage originalImage = ImageIO.read(new ByteArrayInputStream(imageData));
|
||||
BufferedImage resizedImage = resizeImage(originalImage, width, height);
|
||||
|
||||
File outputFile = new File(filePath);
|
||||
File parentDir = outputFile.getParentFile();
|
||||
if (!parentDir.exists() && !parentDir.mkdirs()) {
|
||||
throw new IOException("Failed to create directory: " + parentDir);
|
||||
}
|
||||
|
||||
ImageIO.write(resizedImage, "JPEG", outputFile);
|
||||
}
|
||||
|
||||
private BufferedImage resizeImage(BufferedImage originalImage, int width, int height) {
|
||||
Image tmp = originalImage.getScaledInstance(width, height, Image.SCALE_SMOOTH);
|
||||
BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
|
||||
Graphics2D g2d = resizedImage.createGraphics();
|
||||
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
|
||||
g2d.drawImage(tmp, 0, 0, null);
|
||||
g2d.dispose();
|
||||
return resizedImage;
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 19 KiB |
Reference in New Issue
Block a user