refactor(api, test): improve readability and code quality across services, and tests (#1494)
* refactor(tests): improve readability and consistency across services - Replace field declarations with local variables in test setup methods to simplify code. - Introduce constants for patterns and update regex logic in `BookMediaController`. - Improve assertions and use more precise methods like `getFirst()` in tests. - Utilize `EnumMap` and `EnumSet` for better performance and memory efficiency in metadata logic. - Concatenate XML strings using multi-line strings or simplify where applicable. - Deprecate and refactor user provisioning to ensure consistency and reuse of logic. - Add additional parameters such as `watch` in `Library` entities and set defaults in builders. - Replace manual comparator logic with core library features like `Comparator.reverseOrder`. - Update metadata merging methods to use `getFirst()` for target values. - Adjust mocked objects to include additional fields in validation methods. Signed-off-by: Balázs Szücs <bszucs1209@gmail.com> * refactor(service): remove deprecated user provisioning method - Remove `provisionRemoteUser` method marked as deprecated in `UserProvisioningService`. - Encourage use of `provisionRemoteUserFromHeaders` as the preferred entry point. Signed-off-by: Balázs Szücs <bszucs1209@gmail.com> --------- Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>
This commit is contained in:
@@ -26,9 +26,9 @@ public class JwtUtils {
|
|||||||
|
|
||||||
private final JwtSecretService jwtSecretService;
|
private final JwtSecretService jwtSecretService;
|
||||||
@Getter
|
@Getter
|
||||||
public final long accessTokenExpirationMs = 1000L * 60 * 60 * 10; // 10 hours
|
public static final long accessTokenExpirationMs = 1000L * 60 * 60 * 10; // 10 hours
|
||||||
@Getter
|
@Getter
|
||||||
public final long refreshTokenExpirationMs = 1000L * 60 * 60 * 24 * 30; // 30 days
|
public static final long refreshTokenExpirationMs = 1000L * 60 * 60 * 24 * 30; // 30 days
|
||||||
|
|
||||||
private SecretKey getSigningKey() {
|
private SecretKey getSigningKey() {
|
||||||
String secretKey = jwtSecretService.getSecret();
|
String secretKey = jwtSecretService.getSecret();
|
||||||
|
|||||||
+4
-13
@@ -11,8 +11,6 @@ import org.springframework.context.annotation.Bean;
|
|||||||
import org.springframework.context.annotation.Configuration;
|
import org.springframework.context.annotation.Configuration;
|
||||||
import org.springframework.core.annotation.Order;
|
import org.springframework.core.annotation.Order;
|
||||||
import org.springframework.security.authentication.AuthenticationManager;
|
import org.springframework.security.authentication.AuthenticationManager;
|
||||||
import org.springframework.security.authentication.AuthenticationProvider;
|
|
||||||
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
|
|
||||||
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
|
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
|
||||||
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
|
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
|
||||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||||
@@ -154,17 +152,10 @@ public class SecurityConfig {
|
|||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public AuthenticationManager authenticationManager(HttpSecurity http) throws Exception {
|
public AuthenticationManager authenticationManager(HttpSecurity http) throws Exception {
|
||||||
return http.getSharedObject(AuthenticationManagerBuilder.class)
|
// Configure the shared AuthenticationManagerBuilder with the UserDetailsService and PasswordEncoder
|
||||||
.authenticationProvider(authenticationProvider())
|
AuthenticationManagerBuilder auth = http.getSharedObject(AuthenticationManagerBuilder.class);
|
||||||
.build();
|
auth.userDetailsService(opdsUserDetailsService).passwordEncoder(passwordEncoder());
|
||||||
}
|
return auth.build();
|
||||||
|
|
||||||
@Bean
|
|
||||||
public AuthenticationProvider authenticationProvider() {
|
|
||||||
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
|
|
||||||
provider.setUserDetailsService(opdsUserDetailsService);
|
|
||||||
provider.setPasswordEncoder(passwordEncoder());
|
|
||||||
return provider;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
|
|||||||
+1
-1
@@ -109,7 +109,7 @@ public class AuthenticationService {
|
|||||||
|
|
||||||
Optional<BookLoreUserEntity> user = userRepository.findByUsername(username);
|
Optional<BookLoreUserEntity> user = userRepository.findByUsername(username);
|
||||||
if (user.isEmpty() && appProperties.getRemoteAuth().isCreateNewUsers()) {
|
if (user.isEmpty() && appProperties.getRemoteAuth().isCreateNewUsers()) {
|
||||||
user = Optional.of(userProvisioningService.provisionRemoteUser(name, username, email, groups));
|
user = Optional.of(userProvisioningService.provisionRemoteUserFromHeaders(name, username, email, groups));
|
||||||
}
|
}
|
||||||
|
|
||||||
if (user.isEmpty()) {
|
if (user.isEmpty()) {
|
||||||
|
|||||||
+4
-1
@@ -22,6 +22,7 @@ import org.springframework.web.bind.annotation.RestController;
|
|||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.net.URLEncoder;
|
import java.net.URLEncoder;
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
@Tag(name = "Book Media", description = "Endpoints for retrieving book media such as covers, thumbnails, and pages")
|
@Tag(name = "Book Media", description = "Endpoints for retrieving book media such as covers, thumbnails, and pages")
|
||||||
@AllArgsConstructor
|
@AllArgsConstructor
|
||||||
@@ -29,6 +30,8 @@ import java.nio.charset.StandardCharsets;
|
|||||||
@RequestMapping("/api/v1/media")
|
@RequestMapping("/api/v1/media")
|
||||||
public class BookMediaController {
|
public class BookMediaController {
|
||||||
|
|
||||||
|
private static final Pattern NON_ASCII_PATTERN = Pattern.compile("[^\\x00-\\x7F]");
|
||||||
|
|
||||||
private final BookService bookService;
|
private final BookService bookService;
|
||||||
private final PdfReaderService pdfReaderService;
|
private final PdfReaderService pdfReaderService;
|
||||||
private final CbxReaderService cbxReaderService;
|
private final CbxReaderService cbxReaderService;
|
||||||
@@ -103,7 +106,7 @@ public class BookMediaController {
|
|||||||
: MediaType.IMAGE_JPEG;
|
: MediaType.IMAGE_JPEG;
|
||||||
|
|
||||||
String encodedFilename = URLEncoder.encode(filename, StandardCharsets.UTF_8).replace("+", "%20");
|
String encodedFilename = URLEncoder.encode(filename, StandardCharsets.UTF_8).replace("+", "%20");
|
||||||
String fallbackFilename = filename.replaceAll("[^\\x00-\\x7F]", "_");
|
String fallbackFilename = NON_ASCII_PATTERN.matcher(filename).replaceAll("_");
|
||||||
String contentDisposition = String.format("inline; filename=\"%s\"; filename*=UTF-8''%s",
|
String contentDisposition = String.format("inline; filename=\"%s\"; filename*=UTF-8''%s",
|
||||||
fallbackFilename, encodedFilename);
|
fallbackFilename, encodedFilename);
|
||||||
return ResponseEntity.ok()
|
return ResponseEntity.ok()
|
||||||
|
|||||||
+2
@@ -72,6 +72,8 @@ public class MetadataController {
|
|||||||
.updateThumbnail(true)
|
.updateThumbnail(true)
|
||||||
.mergeCategories(mergeCategories)
|
.mergeCategories(mergeCategories)
|
||||||
.replaceMode(MetadataReplaceMode.REPLACE_ALL)
|
.replaceMode(MetadataReplaceMode.REPLACE_ALL)
|
||||||
|
.mergeMoods(true)
|
||||||
|
.mergeTags(true)
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
bookMetadataUpdater.setBookMetadata(context);
|
bookMetadataUpdater.setBookMetadata(context);
|
||||||
|
|||||||
+3
-3
@@ -10,12 +10,12 @@ import java.util.Map;
|
|||||||
|
|
||||||
@Converter
|
@Converter
|
||||||
@Slf4j
|
@Slf4j
|
||||||
public class JpaJsonConverter implements AttributeConverter<Map<String, Object>, String> {
|
public class JpaJsonConverter implements AttributeConverter<Map, String> {
|
||||||
|
|
||||||
private static final ObjectMapper objectMapper = new ObjectMapper();
|
private static final ObjectMapper objectMapper = new ObjectMapper();
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String convertToDatabaseColumn(Map<String, Object> attribute) {
|
public String convertToDatabaseColumn(Map attribute) {
|
||||||
if (attribute == null) {
|
if (attribute == null) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -28,7 +28,7 @@ public class JpaJsonConverter implements AttributeConverter<Map<String, Object>,
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Map<String, Object> convertToEntityAttribute(String dbData) {
|
public Map convertToEntityAttribute(String dbData) {
|
||||||
if (dbData == null || dbData.isEmpty()) {
|
if (dbData == null || dbData.isEmpty()) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|||||||
+3
-3
@@ -8,12 +8,12 @@ import java.io.IOException;
|
|||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
@Converter(autoApply = true)
|
@Converter(autoApply = true)
|
||||||
public class MapToStringConverter implements AttributeConverter<Map<String, String>, String> {
|
public class MapToStringConverter implements AttributeConverter<Map, String> {
|
||||||
|
|
||||||
private static final ObjectMapper objectMapper = new ObjectMapper();
|
private static final ObjectMapper objectMapper = new ObjectMapper();
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String convertToDatabaseColumn(Map<String, String> attribute) {
|
public String convertToDatabaseColumn(Map attribute) {
|
||||||
try {
|
try {
|
||||||
return objectMapper.writeValueAsString(attribute);
|
return objectMapper.writeValueAsString(attribute);
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
@@ -22,7 +22,7 @@ public class MapToStringConverter implements AttributeConverter<Map<String, Stri
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Map<String, String> convertToEntityAttribute(String dbData) {
|
public Map convertToEntityAttribute(String dbData) {
|
||||||
try {
|
try {
|
||||||
return objectMapper.readValue(dbData, Map.class);
|
return objectMapper.readValue(dbData, Map.class);
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
|
|||||||
+2
-2
@@ -13,7 +13,7 @@ import java.util.regex.Pattern;
|
|||||||
public interface KoboReadingStateMapper {
|
public interface KoboReadingStateMapper {
|
||||||
|
|
||||||
ObjectMapper objectMapper = new ObjectMapper();
|
ObjectMapper objectMapper = new ObjectMapper();
|
||||||
Pattern PATTERN = Pattern.compile("^\"|\"$");
|
Pattern SURROUNDING_DOUBLE_QUOTES_PATTERN = Pattern.compile("^\"|\"$");
|
||||||
|
|
||||||
@Mapping(target = "currentBookmarkJson", expression = "java(toJson(dto.getCurrentBookmark()))")
|
@Mapping(target = "currentBookmarkJson", expression = "java(toJson(dto.getCurrentBookmark()))")
|
||||||
@Mapping(target = "statisticsJson", expression = "java(toJson(dto.getStatistics()))")
|
@Mapping(target = "statisticsJson", expression = "java(toJson(dto.getStatistics()))")
|
||||||
@@ -51,6 +51,6 @@ public interface KoboReadingStateMapper {
|
|||||||
|
|
||||||
default String cleanString(String value) {
|
default String cleanString(String value) {
|
||||||
if (value == null) return null;
|
if (value == null) return null;
|
||||||
return PATTERN.matcher(value).replaceAll("");
|
return SURROUNDING_DOUBLE_QUOTES_PATTERN.matcher(value).replaceAll("");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+1
-2
@@ -19,8 +19,7 @@ public class BookMetadataCategoryKey implements Serializable {
|
|||||||
@Override
|
@Override
|
||||||
public boolean equals(Object o) {
|
public boolean equals(Object o) {
|
||||||
if (this == o) return true;
|
if (this == o) return true;
|
||||||
if (!(o instanceof BookMetadataCategoryKey)) return false;
|
if (!(o instanceof BookMetadataCategoryKey that)) return false;
|
||||||
BookMetadataCategoryKey that = (BookMetadataCategoryKey) o;
|
|
||||||
return Objects.equals(bookId, that.bookId) && Objects.equals(categoryId, that.categoryId);
|
return Objects.equals(bookId, that.bookId) && Objects.equals(categoryId, that.categoryId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+5
-2
@@ -28,12 +28,15 @@ import java.nio.charset.StandardCharsets;
|
|||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
import java.nio.file.Paths;
|
import java.nio.file.Paths;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@AllArgsConstructor
|
@AllArgsConstructor
|
||||||
@Service
|
@Service
|
||||||
public class BookDownloadService {
|
public class BookDownloadService {
|
||||||
|
|
||||||
|
private static final Pattern NON_ASCII_PATTERN = Pattern.compile("[^\\x00-\\x7F]");
|
||||||
|
|
||||||
private final BookRepository bookRepository;
|
private final BookRepository bookRepository;
|
||||||
private final KepubConversionService kepubConversionService;
|
private final KepubConversionService kepubConversionService;
|
||||||
private final AppSettingService appSettingService;
|
private final AppSettingService appSettingService;
|
||||||
@@ -55,7 +58,7 @@ public class BookDownloadService {
|
|||||||
|
|
||||||
String encodedFilename = URLEncoder.encode(file.getFileName().toString(), StandardCharsets.UTF_8)
|
String encodedFilename = URLEncoder.encode(file.getFileName().toString(), StandardCharsets.UTF_8)
|
||||||
.replace("+", "%20");
|
.replace("+", "%20");
|
||||||
String fallbackFilename = file.getFileName().toString().replaceAll("[^\\x00-\\x7F]", "_");
|
String fallbackFilename = NON_ASCII_PATTERN.matcher(file.getFileName().toString()).replaceAll("_");
|
||||||
String contentDisposition = String.format("attachment; filename=\"%s\"; filename*=UTF-8''%s",
|
String contentDisposition = String.format("attachment; filename=\"%s\"; filename*=UTF-8''%s",
|
||||||
fallbackFilename, encodedFilename);
|
fallbackFilename, encodedFilename);
|
||||||
return ResponseEntity.ok()
|
return ResponseEntity.ok()
|
||||||
@@ -114,7 +117,7 @@ public class BookDownloadService {
|
|||||||
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
|
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
|
||||||
response.setContentLengthLong(file.length());
|
response.setContentLengthLong(file.length());
|
||||||
String encodedFilename = URLEncoder.encode(file.getName(), StandardCharsets.UTF_8).replace("+", "%20");
|
String encodedFilename = URLEncoder.encode(file.getName(), StandardCharsets.UTF_8).replace("+", "%20");
|
||||||
String fallbackFilename = file.getName().replaceAll("[^\\x00-\\x7F]", "_");
|
String fallbackFilename = NON_ASCII_PATTERN.matcher(file.getName()).replaceAll("_");
|
||||||
String contentDisposition = String.format("attachment; filename=\"%s\"; filename*=UTF-8''%s",
|
String contentDisposition = String.format("attachment; filename=\"%s\"; filename*=UTF-8''%s",
|
||||||
fallbackFilename, encodedFilename);
|
fallbackFilename, encodedFilename);
|
||||||
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, contentDisposition);
|
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, contentDisposition);
|
||||||
|
|||||||
+13
-12
@@ -587,35 +587,36 @@ public class BookService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public void deleteEmptyParentDirsUpToLibraryFolders(Path currentDir, Set<Path> libraryRoots) throws IOException {
|
public void deleteEmptyParentDirsUpToLibraryFolders(Path currentDir, Set<Path> libraryRoots) throws IOException {
|
||||||
|
Path dir = currentDir;
|
||||||
Set<String> ignoredFilenames = Set.of(".DS_Store", "Thumbs.db");
|
Set<String> ignoredFilenames = Set.of(".DS_Store", "Thumbs.db");
|
||||||
currentDir = currentDir.toAbsolutePath().normalize();
|
dir = dir.toAbsolutePath().normalize();
|
||||||
|
|
||||||
Set<Path> normalizedRoots = new HashSet<>();
|
Set<Path> normalizedRoots = new HashSet<>();
|
||||||
for (Path root : libraryRoots) {
|
for (Path root : libraryRoots) {
|
||||||
normalizedRoots.add(root.toAbsolutePath().normalize());
|
normalizedRoots.add(root.toAbsolutePath().normalize());
|
||||||
}
|
}
|
||||||
|
|
||||||
while (currentDir != null) {
|
while (dir != null) {
|
||||||
boolean isLibraryRoot = false;
|
boolean isLibraryRoot = false;
|
||||||
for (Path root : normalizedRoots) {
|
for (Path root : normalizedRoots) {
|
||||||
try {
|
try {
|
||||||
if (Files.isSameFile(root, currentDir)) {
|
if (Files.isSameFile(root, dir)) {
|
||||||
isLibraryRoot = true;
|
isLibraryRoot = true;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
log.warn("Failed to compare paths: {} and {}", root, currentDir);
|
log.warn("Failed to compare paths: {} and {}", root, dir);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isLibraryRoot) {
|
if (isLibraryRoot) {
|
||||||
log.debug("Reached library root: {}. Stopping cleanup.", currentDir);
|
log.debug("Reached library root: {}. Stopping cleanup.", dir);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
File[] files = currentDir.toFile().listFiles();
|
File[] files = dir.toFile().listFiles();
|
||||||
if (files == null) {
|
if (files == null) {
|
||||||
log.warn("Cannot read directory: {}. Stopping cleanup.", currentDir);
|
log.warn("Cannot read directory: {}. Stopping cleanup.", dir);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -637,15 +638,15 @@ public class BookService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
Files.delete(currentDir);
|
Files.delete(dir);
|
||||||
log.info("Deleted empty directory: {}", currentDir);
|
log.info("Deleted empty directory: {}", dir);
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
log.warn("Failed to delete directory: {}", currentDir, e);
|
log.warn("Failed to delete directory: {}", dir, e);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
currentDir = currentDir.getParent();
|
dir = dir.getParent();
|
||||||
} else {
|
} else {
|
||||||
log.debug("Directory {} contains important files. Stopping cleanup.", currentDir);
|
log.debug("Directory {} contains important files. Stopping cleanup.", dir);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+3
@@ -144,6 +144,9 @@ public class BookDropService {
|
|||||||
private BookdropFinalizeResult processFinalizationRequest(BookdropFinalizeRequest request) {
|
private BookdropFinalizeResult processFinalizationRequest(BookdropFinalizeRequest request) {
|
||||||
BookdropFinalizeResult results = BookdropFinalizeResult.builder()
|
BookdropFinalizeResult results = BookdropFinalizeResult.builder()
|
||||||
.processedAt(Instant.now())
|
.processedAt(Instant.now())
|
||||||
|
.totalFiles(0)
|
||||||
|
.successfullyImported(0)
|
||||||
|
.failed(0)
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
Long defaultLibraryId = request.getDefaultLibraryId();
|
Long defaultLibraryId = request.getDefaultLibraryId();
|
||||||
|
|||||||
+2
-1
@@ -7,6 +7,7 @@ import com.adityachandel.booklore.model.dto.request.SendBookByEmailRequest;
|
|||||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||||
import com.adityachandel.booklore.model.entity.EmailProviderV2Entity;
|
import com.adityachandel.booklore.model.entity.EmailProviderV2Entity;
|
||||||
import com.adityachandel.booklore.model.entity.EmailRecipientV2Entity;
|
import com.adityachandel.booklore.model.entity.EmailRecipientV2Entity;
|
||||||
|
import com.adityachandel.booklore.model.entity.UserEmailProviderPreferenceEntity;
|
||||||
import com.adityachandel.booklore.model.websocket.LogNotification;
|
import com.adityachandel.booklore.model.websocket.LogNotification;
|
||||||
import com.adityachandel.booklore.model.websocket.Topic;
|
import com.adityachandel.booklore.model.websocket.Topic;
|
||||||
import com.adityachandel.booklore.repository.BookRepository;
|
import com.adityachandel.booklore.repository.BookRepository;
|
||||||
@@ -179,7 +180,7 @@ public class SendEmailV2Service {
|
|||||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||||
|
|
||||||
Long defaultProviderId = preferenceRepository.findByUserId(user.getId())
|
Long defaultProviderId = preferenceRepository.findByUserId(user.getId())
|
||||||
.map(pref -> pref.getDefaultProviderId())
|
.map(UserEmailProviderPreferenceEntity::getDefaultProviderId)
|
||||||
.orElseThrow(ApiError.DEFAULT_EMAIL_PROVIDER_NOT_FOUND::createException);
|
.orElseThrow(ApiError.DEFAULT_EMAIL_PROVIDER_NOT_FOUND::createException);
|
||||||
|
|
||||||
return emailProviderRepository.findAccessibleProvider(defaultProviderId, user.getId())
|
return emailProviderRepository.findAccessibleProvider(defaultProviderId, user.getId())
|
||||||
|
|||||||
+4
-1
@@ -23,12 +23,15 @@ import java.nio.file.Files;
|
|||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@AllArgsConstructor
|
@AllArgsConstructor
|
||||||
@Service
|
@Service
|
||||||
public class AdditionalFileService {
|
public class AdditionalFileService {
|
||||||
|
|
||||||
|
private static final Pattern NON_ASCII = Pattern.compile("[^\\x00-\\x7F]");
|
||||||
|
|
||||||
private final BookAdditionalFileRepository additionalFileRepository;
|
private final BookAdditionalFileRepository additionalFileRepository;
|
||||||
private final AdditionalFileMapper additionalFileMapper;
|
private final AdditionalFileMapper additionalFileMapper;
|
||||||
private final MonitoringRegistrationService monitoringRegistrationService;
|
private final MonitoringRegistrationService monitoringRegistrationService;
|
||||||
@@ -81,7 +84,7 @@ public class AdditionalFileService {
|
|||||||
Resource resource = new UrlResource(filePath.toUri());
|
Resource resource = new UrlResource(filePath.toUri());
|
||||||
|
|
||||||
String encodedFilename = URLEncoder.encode(file.getFileName(), StandardCharsets.UTF_8).replace("+", "%20");
|
String encodedFilename = URLEncoder.encode(file.getFileName(), StandardCharsets.UTF_8).replace("+", "%20");
|
||||||
String fallbackFilename = file.getFileName().replaceAll("[^\\x00-\\x7F]", "_");
|
String fallbackFilename = NON_ASCII.matcher(file.getFileName()).replaceAll("_");
|
||||||
String contentDisposition = String.format("attachment; filename=\"%s\"; filename*=UTF-8''%s",
|
String contentDisposition = String.format("attachment; filename=\"%s\"; filename*=UTF-8''%s",
|
||||||
fallbackFilename, encodedFilename);
|
fallbackFilename, encodedFilename);
|
||||||
return ResponseEntity.ok()
|
return ResponseEntity.ok()
|
||||||
|
|||||||
+8
-7
@@ -80,24 +80,25 @@ public class FileMoveHelper {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public void deleteEmptyParentDirsUpToLibraryFolders(Path currentDir, Set<Path> libraryRoots) throws IOException {
|
public void deleteEmptyParentDirsUpToLibraryFolders(Path currentDir, Set<Path> libraryRoots) throws IOException {
|
||||||
|
Path dir = currentDir;
|
||||||
Set<String> ignoredFilenames = Set.of(".DS_Store", "Thumbs.db");
|
Set<String> ignoredFilenames = Set.of(".DS_Store", "Thumbs.db");
|
||||||
currentDir = currentDir.toAbsolutePath().normalize();
|
dir = dir.toAbsolutePath().normalize();
|
||||||
Set<Path> normalizedRoots = new HashSet<>();
|
Set<Path> normalizedRoots = new HashSet<>();
|
||||||
for (Path root : libraryRoots) {
|
for (Path root : libraryRoots) {
|
||||||
normalizedRoots.add(root.toAbsolutePath().normalize());
|
normalizedRoots.add(root.toAbsolutePath().normalize());
|
||||||
}
|
}
|
||||||
while (currentDir != null) {
|
while (dir != null) {
|
||||||
if (isLibraryRoot(currentDir, normalizedRoots)) {
|
if (isLibraryRoot(dir, normalizedRoots)) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
File[] files = currentDir.toFile().listFiles();
|
File[] files = dir.toFile().listFiles();
|
||||||
if (files == null) {
|
if (files == null) {
|
||||||
log.warn("Cannot read directory: {}. Stopping cleanup.", currentDir);
|
log.warn("Cannot read directory: {}. Stopping cleanup.", dir);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
if (hasOnlyIgnoredFiles(files, ignoredFilenames)) {
|
if (hasOnlyIgnoredFiles(files, ignoredFilenames)) {
|
||||||
deleteIgnoredFilesAndDirectory(files, currentDir);
|
deleteIgnoredFilesAndDirectory(files, dir);
|
||||||
currentDir = currentDir.getParent();
|
dir = dir.getParent();
|
||||||
} else {
|
} else {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-6
@@ -101,15 +101,11 @@ public class FileMoveService {
|
|||||||
|
|
||||||
for (Long libraryId : targetLibraryIds) {
|
for (Long libraryId : targetLibraryIds) {
|
||||||
Optional<LibraryEntity> optionalLibrary = libraryRepository.findById(libraryId);
|
Optional<LibraryEntity> optionalLibrary = libraryRepository.findById(libraryId);
|
||||||
optionalLibrary.ifPresent(library -> {
|
optionalLibrary.ifPresent(library -> monitoringRegistrationService.registerLibrary(libraryMapper.toLibrary(library)));
|
||||||
monitoringRegistrationService.registerLibrary(libraryMapper.toLibrary(library));
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
for (Long libraryId : sourceLibraryIds) {
|
for (Long libraryId : sourceLibraryIds) {
|
||||||
Optional<LibraryEntity> optionalLibrary = libraryRepository.findById(libraryId);
|
Optional<LibraryEntity> optionalLibrary = libraryRepository.findById(libraryId);
|
||||||
optionalLibrary.ifPresent(library -> {
|
optionalLibrary.ifPresent(library -> monitoringRegistrationService.registerLibrary(libraryMapper.toLibrary(library)));
|
||||||
monitoringRegistrationService.registerLibrary(libraryMapper.toLibrary(library));
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -121,7 +121,7 @@ public class EpubProcessor extends AbstractFileProcessor implements BookFileProc
|
|||||||
metadata.setPageCount(epubMetadata.getPageCount());
|
metadata.setPageCount(epubMetadata.getPageCount());
|
||||||
|
|
||||||
String lang = epubMetadata.getLanguage();
|
String lang = epubMetadata.getLanguage();
|
||||||
metadata.setLanguage(truncate((lang == null || lang.equalsIgnoreCase("UND")) ? "en" : lang, 1000));
|
metadata.setLanguage(truncate((lang == null || "UND".equalsIgnoreCase(lang)) ? "en" : lang, 1000));
|
||||||
|
|
||||||
metadata.setAsin(truncate(epubMetadata.getAsin(), 20));
|
metadata.setAsin(truncate(epubMetadata.getAsin(), 20));
|
||||||
metadata.setPersonalRating(epubMetadata.getPersonalRating());
|
metadata.setPersonalRating(epubMetadata.getPersonalRating());
|
||||||
|
|||||||
+1
-2
@@ -47,13 +47,12 @@ public class KoboLibrarySyncService {
|
|||||||
|
|
||||||
if (prevSnapshot.isPresent()) {
|
if (prevSnapshot.isPresent()) {
|
||||||
int maxRemaining = 5;
|
int maxRemaining = 5;
|
||||||
List<KoboSnapshotBookEntity> addedAll = new ArrayList<>();
|
|
||||||
List<KoboSnapshotBookEntity> removedAll = new ArrayList<>();
|
List<KoboSnapshotBookEntity> removedAll = new ArrayList<>();
|
||||||
|
|
||||||
koboLibrarySnapshotService.updateSyncedStatusForExistingBooks(prevSnapshot.get().getId(), currSnapshot.getId());
|
koboLibrarySnapshotService.updateSyncedStatusForExistingBooks(prevSnapshot.get().getId(), currSnapshot.getId());
|
||||||
|
|
||||||
Page<KoboSnapshotBookEntity> addedPage = koboLibrarySnapshotService.getNewlyAddedBooks(prevSnapshot.get().getId(), currSnapshot.getId(), PageRequest.of(0, maxRemaining), user.getId());
|
Page<KoboSnapshotBookEntity> addedPage = koboLibrarySnapshotService.getNewlyAddedBooks(prevSnapshot.get().getId(), currSnapshot.getId(), PageRequest.of(0, maxRemaining), user.getId());
|
||||||
addedAll.addAll(addedPage.getContent());
|
List<KoboSnapshotBookEntity> addedAll = new ArrayList<>(addedPage.getContent());
|
||||||
maxRemaining -= addedPage.getNumberOfElements();
|
maxRemaining -= addedPage.getNumberOfElements();
|
||||||
shouldContinueSync = addedPage.hasNext();
|
shouldContinueSync = addedPage.hasNext();
|
||||||
|
|
||||||
|
|||||||
+2
@@ -90,6 +90,8 @@ public class LibraryRescanHelper {
|
|||||||
.replaceMode(context.getOptions().getMetadataReplaceMode())
|
.replaceMode(context.getOptions().getMetadataReplaceMode())
|
||||||
.updateThumbnail(false)
|
.updateThumbnail(false)
|
||||||
.mergeCategories(false)
|
.mergeCategories(false)
|
||||||
|
.mergeMoods(true)
|
||||||
|
.mergeTags(true)
|
||||||
.build();
|
.build();
|
||||||
bookMetadataUpdater.setBookMetadata(metadataUpdateContext);
|
bookMetadataUpdater.setBookMetadata(metadataUpdateContext);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
|
|||||||
+3
-3
@@ -266,7 +266,7 @@ public class MetadataManagementService {
|
|||||||
if (targetValues.size() != 1) {
|
if (targetValues.size() != 1) {
|
||||||
throw new IllegalArgumentException("Series merge requires exactly one target value");
|
throw new IllegalArgumentException("Series merge requires exactly one target value");
|
||||||
}
|
}
|
||||||
String targetSeriesName = targetValues.get(0);
|
String targetSeriesName = targetValues.getFirst();
|
||||||
|
|
||||||
for (String oldSeriesName : valuesToMerge) {
|
for (String oldSeriesName : valuesToMerge) {
|
||||||
List<BookMetadataEntity> booksWithOldSeries = bookMetadataRepository.findAllBySeriesNameIgnoreCase(oldSeriesName);
|
List<BookMetadataEntity> booksWithOldSeries = bookMetadataRepository.findAllBySeriesNameIgnoreCase(oldSeriesName);
|
||||||
@@ -289,7 +289,7 @@ public class MetadataManagementService {
|
|||||||
if (targetValues.size() != 1) {
|
if (targetValues.size() != 1) {
|
||||||
throw new IllegalArgumentException("Publisher merge requires exactly one target value");
|
throw new IllegalArgumentException("Publisher merge requires exactly one target value");
|
||||||
}
|
}
|
||||||
String targetPublisher = targetValues.get(0);
|
String targetPublisher = targetValues.getFirst();
|
||||||
|
|
||||||
for (String oldPublisher : valuesToMerge) {
|
for (String oldPublisher : valuesToMerge) {
|
||||||
List<BookMetadataEntity> booksWithOldPublisher = bookMetadataRepository.findAllByPublisherIgnoreCase(oldPublisher);
|
List<BookMetadataEntity> booksWithOldPublisher = bookMetadataRepository.findAllByPublisherIgnoreCase(oldPublisher);
|
||||||
@@ -312,7 +312,7 @@ public class MetadataManagementService {
|
|||||||
if (targetValues.size() != 1) {
|
if (targetValues.size() != 1) {
|
||||||
throw new IllegalArgumentException("Language merge requires exactly one target value");
|
throw new IllegalArgumentException("Language merge requires exactly one target value");
|
||||||
}
|
}
|
||||||
String targetLanguage = targetValues.get(0);
|
String targetLanguage = targetValues.getFirst();
|
||||||
|
|
||||||
for (String oldLanguage : valuesToMerge) {
|
for (String oldLanguage : valuesToMerge) {
|
||||||
List<BookMetadataEntity> booksWithOldLanguage = bookMetadataRepository.findAllByLanguageIgnoreCase(oldLanguage);
|
List<BookMetadataEntity> booksWithOldLanguage = bookMetadataRepository.findAllByLanguageIgnoreCase(oldLanguage);
|
||||||
|
|||||||
+8
-5
@@ -283,6 +283,8 @@ public class MetadataRefreshService {
|
|||||||
.updateThumbnail(replaceCover)
|
.updateThumbnail(replaceCover)
|
||||||
.mergeCategories(mergeCategories)
|
.mergeCategories(mergeCategories)
|
||||||
.replaceMode(MetadataReplaceMode.REPLACE_MISSING)
|
.replaceMode(MetadataReplaceMode.REPLACE_MISSING)
|
||||||
|
.mergeMoods(true)
|
||||||
|
.mergeTags(true)
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
bookMetadataUpdater.setBookMetadata(context);
|
bookMetadataUpdater.setBookMetadata(context);
|
||||||
@@ -293,13 +295,14 @@ public class MetadataRefreshService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public List<MetadataProvider> prepareProviders(MetadataRefreshOptions refreshOptions) {
|
public List<MetadataProvider> prepareProviders(MetadataRefreshOptions refreshOptions) {
|
||||||
Set<MetadataProvider> allProviders = new HashSet<>(getAllProvidersUsingIndividualFields(refreshOptions));
|
Set<MetadataProvider> allProviders = EnumSet.noneOf(MetadataProvider.class);
|
||||||
|
allProviders.addAll(getAllProvidersUsingIndividualFields(refreshOptions));
|
||||||
return new ArrayList<>(allProviders);
|
return new ArrayList<>(allProviders);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected Set<MetadataProvider> getAllProvidersUsingIndividualFields(MetadataRefreshOptions refreshOptions) {
|
protected Set<MetadataProvider> getAllProvidersUsingIndividualFields(MetadataRefreshOptions refreshOptions) {
|
||||||
MetadataRefreshOptions.FieldOptions fieldOptions = refreshOptions.getFieldOptions();
|
MetadataRefreshOptions.FieldOptions fieldOptions = refreshOptions.getFieldOptions();
|
||||||
Set<MetadataProvider> uniqueProviders = new HashSet<>();
|
Set<MetadataProvider> uniqueProviders = EnumSet.noneOf(MetadataProvider.class);
|
||||||
|
|
||||||
if (fieldOptions != null) {
|
if (fieldOptions != null) {
|
||||||
addProviderToSet(fieldOptions.getTitle(), uniqueProviders);
|
addProviderToSet(fieldOptions.getTitle(), uniqueProviders);
|
||||||
@@ -499,15 +502,15 @@ public class MetadataRefreshService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
protected <T> T resolveField(Map<MetadataProvider, BookMetadata> metadataMap, MetadataRefreshOptions.FieldProvider fieldProvider, Function<BookMetadata, T> extractor) {
|
protected <T> T resolveField(Map<MetadataProvider, BookMetadata> metadataMap, MetadataRefreshOptions.FieldProvider fieldProvider, Function<BookMetadata, T> extractor) {
|
||||||
return resolveFieldWithProviders(metadataMap, fieldProvider, extractor, (value) -> value != null);
|
return resolveFieldWithProviders(metadataMap, fieldProvider, extractor, Objects::nonNull);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected Integer resolveFieldAsInteger(Map<MetadataProvider, BookMetadata> metadataMap, MetadataRefreshOptions.FieldProvider fieldProvider, Function<BookMetadata, Integer> fieldValueExtractor) {
|
protected Integer resolveFieldAsInteger(Map<MetadataProvider, BookMetadata> metadataMap, MetadataRefreshOptions.FieldProvider fieldProvider, Function<BookMetadata, Integer> fieldValueExtractor) {
|
||||||
return resolveFieldWithProviders(metadataMap, fieldProvider, fieldValueExtractor, (value) -> value != null);
|
return resolveFieldWithProviders(metadataMap, fieldProvider, fieldValueExtractor, Objects::nonNull);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected String resolveFieldAsString(Map<MetadataProvider, BookMetadata> metadataMap, MetadataRefreshOptions.FieldProvider fieldProvider, FieldValueExtractor fieldValueExtractor) {
|
protected String resolveFieldAsString(Map<MetadataProvider, BookMetadata> metadataMap, MetadataRefreshOptions.FieldProvider fieldProvider, FieldValueExtractor fieldValueExtractor) {
|
||||||
return resolveFieldWithProviders(metadataMap, fieldProvider, fieldValueExtractor::extract, (value) -> value != null);
|
return resolveFieldWithProviders(metadataMap, fieldProvider, fieldValueExtractor::extract, Objects::nonNull);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected Set<String> resolveFieldAsList(Map<MetadataProvider, BookMetadata> metadataMap, MetadataRefreshOptions.FieldProvider fieldProvider, FieldValueExtractorList fieldValueExtractor) {
|
protected Set<String> resolveFieldAsList(Map<MetadataProvider, BookMetadata> metadataMap, MetadataRefreshOptions.FieldProvider fieldProvider, FieldValueExtractorList fieldValueExtractor) {
|
||||||
|
|||||||
+78
-80
@@ -92,27 +92,27 @@ public class CbxMetadataExtractor implements FileMetadataExtractor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// CBR path (RAR)
|
// CBR path (RAR)
|
||||||
Archive archive = null;
|
try (Archive archive = new Archive(file)) {
|
||||||
try {
|
try {
|
||||||
archive = new Archive(file);
|
FileHeader header = findComicInfoHeader(archive);
|
||||||
FileHeader header = findComicInfoHeader(archive);
|
if (header == null) {
|
||||||
if (header == null) {
|
return BookMetadata.builder().title(baseName).build();
|
||||||
|
}
|
||||||
|
byte[] xmlBytes = readRarEntryBytes(archive, header);
|
||||||
|
if (xmlBytes == null) {
|
||||||
|
return BookMetadata.builder().title(baseName).build();
|
||||||
|
}
|
||||||
|
try (InputStream is = new ByteArrayInputStream(xmlBytes)) {
|
||||||
|
Document document = buildSecureDocument(is);
|
||||||
|
return mapDocumentToMetadata(document, baseName);
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("Failed to extract metadata from CBR", e);
|
||||||
|
return BookMetadata.builder().title(baseName).build();
|
||||||
|
}
|
||||||
|
} catch (Exception ignore) {
|
||||||
|
}
|
||||||
return BookMetadata.builder().title(baseName).build();
|
return BookMetadata.builder().title(baseName).build();
|
||||||
}
|
|
||||||
byte[] xmlBytes = readRarEntryBytes(archive, header);
|
|
||||||
if (xmlBytes == null) {
|
|
||||||
return BookMetadata.builder().title(baseName).build();
|
|
||||||
}
|
|
||||||
try (InputStream is = new ByteArrayInputStream(xmlBytes)) {
|
|
||||||
Document document = buildSecureDocument(is);
|
|
||||||
return mapDocumentToMetadata(document, baseName);
|
|
||||||
}
|
|
||||||
} catch (Exception e) {
|
|
||||||
log.warn("Failed to extract metadata from CBR", e);
|
|
||||||
return BookMetadata.builder().title(baseName).build();
|
|
||||||
} finally {
|
|
||||||
try { if (archive != null) archive.close(); } catch (Exception ignore) {}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private ZipEntry findComicInfoEntry(ZipFile zipFile) {
|
private ZipEntry findComicInfoEntry(ZipFile zipFile) {
|
||||||
@@ -374,61 +374,60 @@ public class CbxMetadataExtractor implements FileMetadataExtractor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// CBR path
|
// CBR path
|
||||||
Archive archive = null;
|
try (Archive archive = new Archive(file)) {
|
||||||
try {
|
try {
|
||||||
archive = new Archive(file);
|
|
||||||
|
|
||||||
// Try via ComicInfo.xml first
|
// Try via ComicInfo.xml first
|
||||||
FileHeader comicInfo = findComicInfoHeader(archive);
|
FileHeader comicInfo = findComicInfoHeader(archive);
|
||||||
if (comicInfo != null) {
|
if (comicInfo != null) {
|
||||||
byte[] xmlBytes = readRarEntryBytes(archive, comicInfo);
|
byte[] xmlBytes = readRarEntryBytes(archive, comicInfo);
|
||||||
if (xmlBytes != null) {
|
if (xmlBytes != null) {
|
||||||
try (InputStream is = new ByteArrayInputStream(xmlBytes)) {
|
try (InputStream is = new ByteArrayInputStream(xmlBytes)) {
|
||||||
Document document = buildSecureDocument(is);
|
Document document = buildSecureDocument(is);
|
||||||
String imageName = findFrontCoverImageName(document);
|
String imageName = findFrontCoverImageName(document);
|
||||||
if (imageName != null) {
|
if (imageName != null) {
|
||||||
FileHeader byName = findRarHeaderByName(archive, imageName);
|
FileHeader byName = findRarHeaderByName(archive, imageName);
|
||||||
if (byName != null) {
|
if (byName != null) {
|
||||||
byte[] bytes = readRarEntryBytes(archive, byName);
|
byte[] bytes = readRarEntryBytes(archive, byName);
|
||||||
if (canDecode(bytes)) return bytes;
|
if (canDecode(bytes)) return bytes;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
int index = Integer.parseInt(imageName);
|
int index = Integer.parseInt(imageName);
|
||||||
FileHeader byIndex = findRarImageHeaderByIndex(archive, index);
|
FileHeader byIndex = findRarImageHeaderByIndex(archive, index);
|
||||||
if (byIndex != null) {
|
if (byIndex != null) {
|
||||||
byte[] bytes = readRarEntryBytes(archive, byIndex);
|
byte[] bytes = readRarEntryBytes(archive, byIndex);
|
||||||
if (canDecode(bytes)) return bytes;
|
if (canDecode(bytes)) return bytes;
|
||||||
}
|
}
|
||||||
if (index > 0) {
|
if (index > 0) {
|
||||||
FileHeader offByOne = findRarImageHeaderByIndex(archive, index - 1);
|
FileHeader offByOne = findRarImageHeaderByIndex(archive, index - 1);
|
||||||
if (offByOne != null) {
|
if (offByOne != null) {
|
||||||
byte[] bytes = readRarEntryBytes(archive, offByOne);
|
byte[] bytes = readRarEntryBytes(archive, offByOne);
|
||||||
if (canDecode(bytes)) return bytes;
|
if (canDecode(bytes)) return bytes;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (NumberFormatException ignore) {
|
||||||
|
// ignore and continue fallback
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
} catch (NumberFormatException ignore) {
|
|
||||||
// ignore and continue fallback
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fallback: iterate images alphabetically until a decodable one is found
|
// Fallback: iterate images alphabetically until a decodable one is found
|
||||||
FileHeader firstImage = findFirstAlphabeticalImageHeader(archive);
|
FileHeader firstImage = findFirstAlphabeticalImageHeader(archive);
|
||||||
if (firstImage != null) {
|
if (firstImage != null) {
|
||||||
java.util.List<FileHeader> images = listRarImageHeaders(archive);
|
List<FileHeader> images = listRarImageHeaders(archive);
|
||||||
for (FileHeader fh : images) {
|
for (FileHeader fh : images) {
|
||||||
byte[] bytes = readRarEntryBytes(archive, fh);
|
byte[] bytes = readRarEntryBytes(archive, fh);
|
||||||
if (canDecode(bytes)) return bytes;
|
if (canDecode(bytes)) return bytes;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("Failed to extract cover image from CBR", e);
|
||||||
|
return generatePlaceholderCover(250, 350);
|
||||||
|
}
|
||||||
|
} catch (Exception ignore) {
|
||||||
}
|
}
|
||||||
} catch (Exception e) {
|
|
||||||
log.warn("Failed to extract cover image from CBR", e);
|
|
||||||
return generatePlaceholderCover(250, 350);
|
|
||||||
} finally {
|
|
||||||
try { if (archive != null) archive.close(); } catch (Exception ignore) {}
|
|
||||||
}
|
|
||||||
|
|
||||||
return generatePlaceholderCover(250, 350);
|
return generatePlaceholderCover(250, 350);
|
||||||
}
|
}
|
||||||
@@ -508,10 +507,9 @@ public class CbxMetadataExtractor implements FileMetadataExtractor {
|
|||||||
NodeList pages = document.getElementsByTagName("Page");
|
NodeList pages = document.getElementsByTagName("Page");
|
||||||
for (int i = 0; i < pages.getLength(); i++) {
|
for (int i = 0; i < pages.getLength(); i++) {
|
||||||
org.w3c.dom.Node node = pages.item(i);
|
org.w3c.dom.Node node = pages.item(i);
|
||||||
if (node instanceof org.w3c.dom.Element) {
|
if (node instanceof org.w3c.dom.Element page) {
|
||||||
org.w3c.dom.Element page = (org.w3c.dom.Element) node;
|
String type = page.getAttribute("Type");
|
||||||
String type = page.getAttribute("Type");
|
if (type != null && "FrontCover".equalsIgnoreCase(type)) {
|
||||||
if (type != null && type.equalsIgnoreCase("FrontCover")) {
|
|
||||||
String imageFile = page.getAttribute("ImageFile");
|
String imageFile = page.getAttribute("ImageFile");
|
||||||
if (imageFile != null && !imageFile.isBlank()) {
|
if (imageFile != null && !imageFile.isBlank()) {
|
||||||
return imageFile.trim();
|
return imageFile.trim();
|
||||||
@@ -545,7 +543,7 @@ public class CbxMetadataExtractor implements FileMetadataExtractor {
|
|||||||
if (norm.startsWith("__MACOSX/") || norm.contains("/__MACOSX/")) return false;
|
if (norm.startsWith("__MACOSX/") || norm.contains("/__MACOSX/")) return false;
|
||||||
String base = baseName(norm);
|
String base = baseName(norm);
|
||||||
if (base.startsWith(".")) return false;
|
if (base.startsWith(".")) return false;
|
||||||
if (base.equalsIgnoreCase(".ds_store")) return false;
|
if (".ds_store".equalsIgnoreCase(base)) return false;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -656,7 +654,7 @@ public class CbxMetadataExtractor implements FileMetadataExtractor {
|
|||||||
}
|
}
|
||||||
if (images.isEmpty()) return null;
|
if (images.isEmpty()) return null;
|
||||||
images.sort((a, b) -> naturalCompare(a.getFileName(), b.getFileName()));
|
images.sort((a, b) -> naturalCompare(a.getFileName(), b.getFileName()));
|
||||||
return images.get(0);
|
return images.getFirst();
|
||||||
}
|
}
|
||||||
|
|
||||||
private ZipEntry findFirstAlphabeticalImageEntry(ZipFile zipFile) {
|
private ZipEntry findFirstAlphabeticalImageEntry(ZipFile zipFile) {
|
||||||
@@ -670,7 +668,7 @@ public class CbxMetadataExtractor implements FileMetadataExtractor {
|
|||||||
}
|
}
|
||||||
if (images.isEmpty()) return null;
|
if (images.isEmpty()) return null;
|
||||||
images.sort((a, b) -> naturalCompare(a.getName(), b.getName()));
|
images.sort((a, b) -> naturalCompare(a.getName(), b.getName()));
|
||||||
return images.get(0);
|
return images.getFirst();
|
||||||
}
|
}
|
||||||
|
|
||||||
// ==== 7z (.cb7) helpers ====
|
// ==== 7z (.cb7) helpers ====
|
||||||
@@ -678,7 +676,7 @@ public class CbxMetadataExtractor implements FileMetadataExtractor {
|
|||||||
for (SevenZArchiveEntry e : sevenZ.getEntries()) {
|
for (SevenZArchiveEntry e : sevenZ.getEntries()) {
|
||||||
if (e == null || e.isDirectory()) continue;
|
if (e == null || e.isDirectory()) continue;
|
||||||
String name = e.getName();
|
String name = e.getName();
|
||||||
if (name != null && name.equalsIgnoreCase("ComicInfo.xml")) {
|
if (name != null && "ComicInfo.xml".equalsIgnoreCase(name)) {
|
||||||
return e;
|
return e;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -718,7 +716,7 @@ public class CbxMetadataExtractor implements FileMetadataExtractor {
|
|||||||
}
|
}
|
||||||
if (images.isEmpty()) return null;
|
if (images.isEmpty()) return null;
|
||||||
images.sort((a, b) -> naturalCompare(a.getName(), b.getName()));
|
images.sort((a, b) -> naturalCompare(a.getName(), b.getName()));
|
||||||
return images.get(0);
|
return images.getFirst();
|
||||||
}
|
}
|
||||||
|
|
||||||
private byte[] readSevenZEntryBytes(SevenZFile sevenZ, SevenZArchiveEntry entry) throws IOException {
|
private byte[] readSevenZEntryBytes(SevenZFile sevenZ, SevenZArchiveEntry entry) throws IOException {
|
||||||
@@ -766,7 +764,7 @@ public class CbxMetadataExtractor implements FileMetadataExtractor {
|
|||||||
private boolean likelyCoverName(String base) {
|
private boolean likelyCoverName(String base) {
|
||||||
if (base == null) return false;
|
if (base == null) return false;
|
||||||
String n = base.toLowerCase();
|
String n = base.toLowerCase();
|
||||||
return n.startsWith("cover") || n.equals("folder") || n.startsWith("front");
|
return n.startsWith("cover") || "folder".equals(n) || n.startsWith("front");
|
||||||
}
|
}
|
||||||
|
|
||||||
private int naturalCompare(String a, String b) {
|
private int naturalCompare(String a, String b) {
|
||||||
|
|||||||
+4
-4
@@ -132,12 +132,12 @@ public class EpubMetadataExtractor implements FileMetadataExtractor {
|
|||||||
String content = el.hasAttribute("content") ? el.getAttribute("content").trim() : text;
|
String content = el.hasAttribute("content") ? el.getAttribute("content").trim() : text;
|
||||||
if (StringUtils.isBlank(content)) continue;
|
if (StringUtils.isBlank(content)) continue;
|
||||||
|
|
||||||
if (!seriesFound && (prop.equals("booklore:series") || name.equals("calibre:series") || prop.equals("calibre:series") || prop.equals("belongs-to-collection"))) {
|
if (!seriesFound && ("booklore:series".equals(prop) || "calibre:series".equals(name) || "calibre:series".equals(prop) || "belongs-to-collection".equals(prop))) {
|
||||||
builderMeta.seriesName(content);
|
builderMeta.seriesName(content);
|
||||||
seriesFound = true;
|
seriesFound = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!seriesIndexFound && (prop.equals("booklore:series_index") || name.equals("calibre:series_index") || prop.equals("calibre:series_index") || prop.equals("group-position"))) {
|
if (!seriesIndexFound && ("booklore:series_index".equals(prop) || "calibre:series_index".equals(name) || "calibre:series_index".equals(prop) || "group-position".equals(prop))) {
|
||||||
try {
|
try {
|
||||||
builderMeta.seriesNumber(Float.parseFloat(content));
|
builderMeta.seriesNumber(Float.parseFloat(content));
|
||||||
seriesIndexFound = true;
|
seriesIndexFound = true;
|
||||||
@@ -145,11 +145,11 @@ public class EpubMetadataExtractor implements FileMetadataExtractor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (name.equals("calibre:pages") || name.equals("pagecount") || prop.equals("schema:pagecount") || prop.equals("media:pagecount") || prop.equals("booklore:page_count")) {
|
if ("calibre:pages".equals(name) || "pagecount".equals(name) || "schema:pagecount".equals(prop) || "media:pagecount".equals(prop) || "booklore:page_count".equals(prop)) {
|
||||||
safeParseInt(content, builderMeta::pageCount);
|
safeParseInt(content, builderMeta::pageCount);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (name.equals("calibre:rating") || prop.equals("booklore:personal_rating")) {
|
if ("calibre:rating".equals(name) || "booklore:personal_rating".equals(prop)) {
|
||||||
safeParseDouble(content, builderMeta::personalRating);
|
safeParseDouble(content, builderMeta::personalRating);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+5
-3
@@ -40,6 +40,8 @@ public class AmazonBookParser implements BookParser {
|
|||||||
private static final Pattern PARENTHESES_WITH_WHITESPACE_PATTERN = Pattern.compile("\\s*\\(.*?\\)");
|
private static final Pattern PARENTHESES_WITH_WHITESPACE_PATTERN = Pattern.compile("\\s*\\(.*?\\)");
|
||||||
private static final Pattern NON_ALPHANUMERIC_PATTERN = Pattern.compile("[^a-zA-Z0-9]");
|
private static final Pattern NON_ALPHANUMERIC_PATTERN = Pattern.compile("[^a-zA-Z0-9]");
|
||||||
private static final Pattern DP_SEPARATOR_PATTERN = Pattern.compile("/dp/");
|
private static final Pattern DP_SEPARATOR_PATTERN = Pattern.compile("/dp/");
|
||||||
|
// Pattern to extract country and date from strings like "Reviewed in ... on ..."
|
||||||
|
private static final Pattern REVIEWED_IN_ON_PATTERN = Pattern.compile("Reviewed in (.+?) on (.+)");
|
||||||
|
|
||||||
private static final Map<String, LocaleInfo> DOMAIN_LOCALE_MAP = Map.ofEntries(
|
private static final Map<String, LocaleInfo> DOMAIN_LOCALE_MAP = Map.ofEntries(
|
||||||
Map.entry("com", new LocaleInfo("en-US,en;q=0.9", Locale.US)),
|
Map.entry("com", new LocaleInfo("en-US,en;q=0.9", Locale.US)),
|
||||||
@@ -510,6 +512,7 @@ public class AmazonBookParser implements BookParser {
|
|||||||
|
|
||||||
private List<BookReview> getReviews(Document doc, int maxReviews) {
|
private List<BookReview> getReviews(Document doc, int maxReviews) {
|
||||||
List<BookReview> reviews = new ArrayList<>();
|
List<BookReview> reviews = new ArrayList<>();
|
||||||
|
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
|
||||||
String domain = appSettingService.getAppSettings().getMetadataProviderSettings().getAmazon().getDomain();
|
String domain = appSettingService.getAppSettings().getMetadataProviderSettings().getAmazon().getDomain();
|
||||||
LocaleInfo localeInfo = getLocaleInfoForDomain(domain);
|
LocaleInfo localeInfo = getLocaleInfoForDomain(domain);
|
||||||
|
|
||||||
@@ -556,8 +559,7 @@ public class AmazonBookParser implements BookParser {
|
|||||||
|
|
||||||
if (!fullDateText.isEmpty()) {
|
if (!fullDateText.isEmpty()) {
|
||||||
try {
|
try {
|
||||||
Pattern pattern = Pattern.compile("Reviewed in (.+?) on (.+)");
|
Matcher matcher = REVIEWED_IN_ON_PATTERN.matcher(fullDateText);
|
||||||
Matcher matcher = pattern.matcher(fullDateText);
|
|
||||||
String datePart = fullDateText;
|
String datePart = fullDateText;
|
||||||
|
|
||||||
if (matcher.find() && matcher.groupCount() == 2) {
|
if (matcher.find() && matcher.groupCount() == 2) {
|
||||||
@@ -744,7 +746,7 @@ public class AmazonBookParser implements BookParser {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!localeInfo.locale.getLanguage().equals("en")) {
|
if (!"en".equals(localeInfo.locale.getLanguage())) {
|
||||||
for (String pattern : patterns) {
|
for (String pattern : patterns) {
|
||||||
try {
|
try {
|
||||||
return LocalDate.parse(trimmedDate, DateTimeFormatter.ofPattern(pattern, localeInfo.locale));
|
return LocalDate.parse(trimmedDate, DateTimeFormatter.ofPattern(pattern, localeInfo.locale));
|
||||||
|
|||||||
+33
-29
@@ -41,6 +41,14 @@ public class DoubanBookParser implements BookParser {
|
|||||||
private static final Pattern NON_DIGIT_PATTERN = Pattern.compile("[^\\d]");
|
private static final Pattern NON_DIGIT_PATTERN = Pattern.compile("[^\\d]");
|
||||||
private static final Pattern NON_ALPHANUMERIC_CJK_PATTERN = Pattern.compile("[^a-zA-Z0-9\\u4e00-\\u9fff]");
|
private static final Pattern NON_ALPHANUMERIC_CJK_PATTERN = Pattern.compile("[^a-zA-Z0-9\\u4e00-\\u9fff]");
|
||||||
private static final Pattern SLASH_SEPARATOR_PATTERN = Pattern.compile(" / ");
|
private static final Pattern SLASH_SEPARATOR_PATTERN = Pattern.compile(" / ");
|
||||||
|
// Regex to extract JSON assigned to window.__DATA__ in Douban pages (DOTALL to capture across lines)
|
||||||
|
private static final Pattern WINDOW_DATA_JSON_PATTERN = Pattern.compile("window\\.__DATA__\\s*=\\s*(\\{.*\\});", Pattern.DOTALL);
|
||||||
|
// Pattern to extract numeric Douban subject id from URLs like /subject/123456/
|
||||||
|
private static final Pattern SUBJECT_ID_PATTERN = Pattern.compile("/subject/(\\d+)/");
|
||||||
|
// Pattern to extract rating number from class names like 'rating40' -> 40
|
||||||
|
private static final Pattern RATING_NUMBER_PATTERN = Pattern.compile("rating(\\d+)");
|
||||||
|
// Pattern for yyyy-MM-dd (or yyyy/M/d) date formats
|
||||||
|
private static final Pattern DATE_YMD_PATTERN = Pattern.compile("(\\d{4})[-/](\\d{1,2})[-/](\\d{1,2})");
|
||||||
private final AppSettingService appSettingService;
|
private final AppSettingService appSettingService;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -49,7 +57,7 @@ public class DoubanBookParser implements BookParser {
|
|||||||
if (searchResults == null || searchResults.isEmpty()) {
|
if (searchResults == null || searchResults.isEmpty()) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
BookMetadata topResult = searchResults.get(0);
|
BookMetadata topResult = searchResults.getFirst();
|
||||||
|
|
||||||
// If Douban reviews are enabled, fetch detailed metadata including reviews
|
// If Douban reviews are enabled, fetch detailed metadata including reviews
|
||||||
if (topResult.getDoubanId() != null && areDoubanReviewsEnabled()) {
|
if (topResult.getDoubanId() != null && areDoubanReviewsEnabled()) {
|
||||||
@@ -123,12 +131,11 @@ public class DoubanBookParser implements BookParser {
|
|||||||
String jsonData = null;
|
String jsonData = null;
|
||||||
|
|
||||||
// Use regex to find the JSON object in window.__DATA__
|
// Use regex to find the JSON object in window.__DATA__
|
||||||
Pattern pattern = Pattern.compile("window\\.__DATA__\\s*=\\s*(\\{.*\\});", Pattern.DOTALL);
|
Matcher matcher = WINDOW_DATA_JSON_PATTERN.matcher(htmlContent);
|
||||||
Matcher matcher = pattern.matcher(htmlContent);
|
if (matcher.find()) {
|
||||||
if (matcher.find()) {
|
jsonData = matcher.group(1);
|
||||||
jsonData = matcher.group(1);
|
log.debug("Successfully extracted JSON data, length: {}", jsonData.length());
|
||||||
log.debug("Successfully extracted JSON data, length: {}", jsonData.length());
|
}
|
||||||
}
|
|
||||||
|
|
||||||
if (jsonData == null) {
|
if (jsonData == null) {
|
||||||
log.warn("No JSON data found in Douban search response");
|
log.warn("No JSON data found in Douban search response");
|
||||||
@@ -156,7 +163,7 @@ public class DoubanBookParser implements BookParser {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (itemsNode.size() == 0) {
|
if (itemsNode.isEmpty()) {
|
||||||
log.info("No books found for the search query");
|
log.info("No books found for the search query");
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -244,12 +251,11 @@ public class DoubanBookParser implements BookParser {
|
|||||||
if (url == null || url.isEmpty()) {
|
if (url == null || url.isEmpty()) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
Pattern pattern = Pattern.compile("/subject/(\\d+)/");
|
Matcher matcher = SUBJECT_ID_PATTERN.matcher(url);
|
||||||
Matcher matcher = pattern.matcher(url);
|
if (matcher.find()) {
|
||||||
if (matcher.find()) {
|
return matcher.group(1);
|
||||||
return matcher.group(1);
|
}
|
||||||
}
|
return null;
|
||||||
return null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private BookMetadata getBookMetadata(String doubanBookId) {
|
private BookMetadata getBookMetadata(String doubanBookId) {
|
||||||
@@ -580,11 +586,10 @@ public class DoubanBookParser implements BookParser {
|
|||||||
Float ratingValue = null;
|
Float ratingValue = null;
|
||||||
if (!ratingElements.isEmpty()) {
|
if (!ratingElements.isEmpty()) {
|
||||||
String ratingClass = ratingElements.first().className();
|
String ratingClass = ratingElements.first().className();
|
||||||
Pattern pattern = Pattern.compile("rating(\\d+)");
|
Matcher matcher = RATING_NUMBER_PATTERN.matcher(ratingClass);
|
||||||
Matcher matcher = pattern.matcher(ratingClass);
|
if (matcher.find()) {
|
||||||
if (matcher.find()) {
|
ratingValue = Float.parseFloat(matcher.group(1)) / 2.0f; // Convert 5-star scale to 10-star scale
|
||||||
ratingValue = Float.parseFloat(matcher.group(1)) / 2.0f; // Convert 5-star scale to 10-star scale
|
}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Elements dateElements = reviewElement.select(".comment-info .comment-time");
|
Elements dateElements = reviewElement.select(".comment-info .comment-time");
|
||||||
@@ -715,13 +720,12 @@ public class DoubanBookParser implements BookParser {
|
|||||||
if (dateString == null || dateString.trim().isEmpty()) {
|
if (dateString == null || dateString.trim().isEmpty()) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
dateString = dateString.trim();
|
String trim = dateString.trim();
|
||||||
|
|
||||||
// Try regex patterns first for more flexibility
|
// Try regex patterns first for more flexibility
|
||||||
try {
|
try {
|
||||||
// Pattern for yyyy-MM-dd or yyyy-M-d or yyyy-MM-d or yyyy-M-dd
|
// Pattern for yyyy-MM-dd or yyyy-M-d or yyyy-MM-d or yyyy-M-dd
|
||||||
Pattern pattern = Pattern.compile("(\\d{4})[-/](\\d{1,2})[-/](\\d{1,2})");
|
Matcher matcher = DATE_YMD_PATTERN.matcher(trim);
|
||||||
Matcher matcher = pattern.matcher(dateString);
|
|
||||||
if (matcher.matches()) {
|
if (matcher.matches()) {
|
||||||
int year = Integer.parseInt(matcher.group(1));
|
int year = Integer.parseInt(matcher.group(1));
|
||||||
int month = Integer.parseInt(matcher.group(2));
|
int month = Integer.parseInt(matcher.group(2));
|
||||||
@@ -730,8 +734,8 @@ public class DoubanBookParser implements BookParser {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Pattern for yyyy-MM or yyyy-M
|
// Pattern for yyyy-MM or yyyy-M
|
||||||
pattern = Pattern.compile("(\\d{4})[-/](\\d{1,2})");
|
Pattern pattern = Pattern.compile("(\\d{4})[-/](\\d{1,2})");
|
||||||
matcher = pattern.matcher(dateString);
|
matcher = pattern.matcher(trim);
|
||||||
if (matcher.matches()) {
|
if (matcher.matches()) {
|
||||||
int year = Integer.parseInt(matcher.group(1));
|
int year = Integer.parseInt(matcher.group(1));
|
||||||
int month = Integer.parseInt(matcher.group(2));
|
int month = Integer.parseInt(matcher.group(2));
|
||||||
@@ -740,7 +744,7 @@ public class DoubanBookParser implements BookParser {
|
|||||||
|
|
||||||
// Pattern for yyyy
|
// Pattern for yyyy
|
||||||
pattern = Pattern.compile("(\\d{4})");
|
pattern = Pattern.compile("(\\d{4})");
|
||||||
matcher = pattern.matcher(dateString);
|
matcher = pattern.matcher(trim);
|
||||||
if (matcher.matches()) {
|
if (matcher.matches()) {
|
||||||
int year = Integer.parseInt(matcher.group(1));
|
int year = Integer.parseInt(matcher.group(1));
|
||||||
return LocalDate.of(year, 1, 1);
|
return LocalDate.of(year, 1, 1);
|
||||||
@@ -749,7 +753,7 @@ public class DoubanBookParser implements BookParser {
|
|||||||
// Chinese patterns
|
// Chinese patterns
|
||||||
// Pattern for 年月日: 2011年1月10日
|
// Pattern for 年月日: 2011年1月10日
|
||||||
pattern = Pattern.compile("(\\d{4})年(\\d{1,2})月(\\d{1,2})日");
|
pattern = Pattern.compile("(\\d{4})年(\\d{1,2})月(\\d{1,2})日");
|
||||||
matcher = pattern.matcher(dateString);
|
matcher = pattern.matcher(trim);
|
||||||
if (matcher.matches()) {
|
if (matcher.matches()) {
|
||||||
int year = Integer.parseInt(matcher.group(1));
|
int year = Integer.parseInt(matcher.group(1));
|
||||||
int month = Integer.parseInt(matcher.group(2));
|
int month = Integer.parseInt(matcher.group(2));
|
||||||
@@ -759,7 +763,7 @@ public class DoubanBookParser implements BookParser {
|
|||||||
|
|
||||||
// Pattern for 年月: 2111年12月
|
// Pattern for 年月: 2111年12月
|
||||||
pattern = Pattern.compile("(\\d{4})年(\\d{1,2})月");
|
pattern = Pattern.compile("(\\d{4})年(\\d{1,2})月");
|
||||||
matcher = pattern.matcher(dateString);
|
matcher = pattern.matcher(trim);
|
||||||
if (matcher.matches()) {
|
if (matcher.matches()) {
|
||||||
int year = Integer.parseInt(matcher.group(1));
|
int year = Integer.parseInt(matcher.group(1));
|
||||||
int month = Integer.parseInt(matcher.group(2));
|
int month = Integer.parseInt(matcher.group(2));
|
||||||
@@ -768,14 +772,14 @@ public class DoubanBookParser implements BookParser {
|
|||||||
|
|
||||||
// Pattern for 年: 2011年
|
// Pattern for 年: 2011年
|
||||||
pattern = Pattern.compile("(\\d{4})年");
|
pattern = Pattern.compile("(\\d{4})年");
|
||||||
matcher = pattern.matcher(dateString);
|
matcher = pattern.matcher(trim);
|
||||||
if (matcher.matches()) {
|
if (matcher.matches()) {
|
||||||
int year = Integer.parseInt(matcher.group(1));
|
int year = Integer.parseInt(matcher.group(1));
|
||||||
return LocalDate.of(year, 1, 1);
|
return LocalDate.of(year, 1, 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.warn("Exception while parsing date '{}': {}", dateString, e.getMessage());
|
log.warn("Exception while parsing date '{}': {}", trim, e.getMessage());
|
||||||
}
|
}
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
|
|||||||
+8
-4
@@ -40,6 +40,8 @@ public class GoodReadsParser implements BookParser {
|
|||||||
private static final String BASE_ISBN_URL = "https://www.goodreads.com/book/isbn/";
|
private static final String BASE_ISBN_URL = "https://www.goodreads.com/book/isbn/";
|
||||||
private static final int COUNT_DETAILED_METADATA_TO_GET = 3;
|
private static final int COUNT_DETAILED_METADATA_TO_GET = 3;
|
||||||
private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\s+");
|
private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\s+");
|
||||||
|
// Pattern to extract numeric Goodreads id from book URL like /book/show/12345
|
||||||
|
private static final Pattern BOOK_SHOW_ID_PATTERN = Pattern.compile("/book/show/(\\d+)");
|
||||||
private final AppSettingService appSettingService;
|
private final AppSettingService appSettingService;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -63,7 +65,7 @@ public class GoodReadsParser implements BookParser {
|
|||||||
.orElse(null);
|
.orElse(null);
|
||||||
|
|
||||||
if (ogUrl != null && !ogUrl.isBlank()) {
|
if (ogUrl != null && !ogUrl.isBlank()) {
|
||||||
String goodreadsId = ogUrl.substring(ogUrl.lastIndexOf("/") + 1);
|
String goodreadsId = ogUrl.substring(ogUrl.lastIndexOf('/') + 1);
|
||||||
if (!goodreadsId.isBlank()) {
|
if (!goodreadsId.isBlank()) {
|
||||||
BookMetadata metadata = parseBookDetails(doc, goodreadsId);
|
BookMetadata metadata = parseBookDetails(doc, goodreadsId);
|
||||||
if (metadata != null) {
|
if (metadata != null) {
|
||||||
@@ -309,7 +311,7 @@ public class GoodReadsParser implements BookParser {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private String handleStringNull(String s) {
|
private String handleStringNull(String s) {
|
||||||
if (s != null && s.equals("null")) {
|
if (s != null && "null".equals(s)) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
return s;
|
return s;
|
||||||
@@ -495,9 +497,11 @@ public class GoodReadsParser implements BookParser {
|
|||||||
private Integer extractGoodReadsIdPreview(Element book) {
|
private Integer extractGoodReadsIdPreview(Element book) {
|
||||||
try {
|
try {
|
||||||
Element bookTitle = book.select("a.bookTitle").first();
|
Element bookTitle = book.select("a.bookTitle").first();
|
||||||
|
if (bookTitle == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
String href = bookTitle.attr("href");
|
String href = bookTitle.attr("href");
|
||||||
Pattern pattern = Pattern.compile("/book/show/(\\d+)");
|
Matcher matcher = BOOK_SHOW_ID_PATTERN.matcher(href);
|
||||||
Matcher matcher = pattern.matcher(href);
|
|
||||||
if (matcher.find()) {
|
if (matcher.find()) {
|
||||||
return Integer.valueOf(matcher.group(1));
|
return Integer.valueOf(matcher.group(1));
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
@@ -397,7 +397,7 @@ public class CbxMetadataWriter implements MetadataWriter {
|
|||||||
String n = name.replace('\\', '/');
|
String n = name.replace('\\', '/');
|
||||||
if (n.endsWith("/")) return false;
|
if (n.endsWith("/")) return false;
|
||||||
String lower = n.toLowerCase(Locale.ROOT);
|
String lower = n.toLowerCase(Locale.ROOT);
|
||||||
return lower.equals("comicinfo.xml") || lower.endsWith("/comicinfo.xml");
|
return "comicinfo.xml".equals(lower) || lower.endsWith("/comicinfo.xml");
|
||||||
}
|
}
|
||||||
|
|
||||||
private static boolean isSafeEntryName(String name) {
|
private static boolean isSafeEntryName(String name) {
|
||||||
|
|||||||
+7
-21
@@ -107,9 +107,7 @@ public class EpubMetadataWriter implements MetadataWriter {
|
|||||||
hasChanges[0] = true;
|
hasChanges[0] = true;
|
||||||
});
|
});
|
||||||
|
|
||||||
helper.copySeriesName(clear != null && clear.isSeriesName(), val -> {
|
helper.copySeriesName(clear != null && clear.isSeriesName(), val -> replaceMetaElement(metadataElement, opfDoc, "calibre:series", val, hasChanges));
|
||||||
replaceMetaElement(metadataElement, opfDoc, "calibre:series", val, hasChanges);
|
|
||||||
});
|
|
||||||
|
|
||||||
helper.copySeriesNumber(clear != null && clear.isSeriesNumber(), val -> {
|
helper.copySeriesNumber(clear != null && clear.isSeriesNumber(), val -> {
|
||||||
String formatted = val != null ? String.format("%.1f", val) : null;
|
String formatted = val != null ? String.format("%.1f", val) : null;
|
||||||
@@ -136,24 +134,12 @@ public class EpubMetadataWriter implements MetadataWriter {
|
|||||||
};
|
};
|
||||||
|
|
||||||
switch (scheme) {
|
switch (scheme) {
|
||||||
case "AMAZON" -> helper.copyAsin(clearFlag, idValue -> {
|
case "AMAZON" -> helper.copyAsin(clearFlag, idValue -> updateIdentifier(metadataElement, opfDoc, scheme, idValue, hasChanges));
|
||||||
updateIdentifier(metadataElement, opfDoc, scheme, idValue, hasChanges);
|
case "GOOGLE" -> helper.copyGoogleId(clearFlag, idValue -> updateIdentifier(metadataElement, opfDoc, scheme, idValue, hasChanges));
|
||||||
});
|
case "GOODREADS" -> helper.copyGoodreadsId(clearFlag, idValue -> updateIdentifier(metadataElement, opfDoc, scheme, idValue, hasChanges));
|
||||||
case "GOOGLE" -> helper.copyGoogleId(clearFlag, idValue -> {
|
case "COMICVINE" -> helper.copyComicvineId(clearFlag, idValue -> updateIdentifier(metadataElement, opfDoc, scheme, idValue, hasChanges));
|
||||||
updateIdentifier(metadataElement, opfDoc, scheme, idValue, hasChanges);
|
case "HARDCOVER" -> helper.copyHardcoverId(clearFlag, idValue -> updateIdentifier(metadataElement, opfDoc, scheme, idValue, hasChanges));
|
||||||
});
|
case "ISBN" -> helper.copyIsbn13(clearFlag, idValue -> updateIdentifier(metadataElement, opfDoc, scheme, idValue, hasChanges));
|
||||||
case "GOODREADS" -> helper.copyGoodreadsId(clearFlag, idValue -> {
|
|
||||||
updateIdentifier(metadataElement, opfDoc, scheme, idValue, hasChanges);
|
|
||||||
});
|
|
||||||
case "COMICVINE" -> helper.copyComicvineId(clearFlag, idValue -> {
|
|
||||||
updateIdentifier(metadataElement, opfDoc, scheme, idValue, hasChanges);
|
|
||||||
});
|
|
||||||
case "HARDCOVER" -> helper.copyHardcoverId(clearFlag, idValue -> {
|
|
||||||
updateIdentifier(metadataElement, opfDoc, scheme, idValue, hasChanges);
|
|
||||||
});
|
|
||||||
case "ISBN" -> helper.copyIsbn13(clearFlag, idValue -> {
|
|
||||||
updateIdentifier(metadataElement, opfDoc, scheme, idValue, hasChanges);
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+2
-6
@@ -123,13 +123,9 @@ public class PdfMetadataWriter implements MetadataWriter {
|
|||||||
dc.addDate(cal);
|
dc.addDate(cal);
|
||||||
});
|
});
|
||||||
|
|
||||||
helper.copyAuthors(clear != null && clear.isAuthors(), authors -> {
|
helper.copyAuthors(clear != null && clear.isAuthors(), authors -> (authors != null ? authors : List.of("")).forEach(dc::addCreator));
|
||||||
(authors != null ? authors : List.of("")).forEach(dc::addCreator);
|
|
||||||
});
|
|
||||||
|
|
||||||
helper.copyCategories(clear != null && clear.isCategories(), cats -> {
|
helper.copyCategories(clear != null && clear.isCategories(), cats -> (cats != null ? cats : List.of("")).forEach(dc::addSubject));
|
||||||
(cats != null ? cats : List.of("")).forEach(dc::addSubject);
|
|
||||||
});
|
|
||||||
|
|
||||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||||
new XmpSerializer().serialize(xmp, baos, true);
|
new XmpSerializer().serialize(xmp, baos, true);
|
||||||
|
|||||||
+2
-7
@@ -6,6 +6,7 @@ import com.adityachandel.booklore.model.entity.BookMetadataEntity;
|
|||||||
import com.adityachandel.booklore.model.entity.CategoryEntity;
|
import com.adityachandel.booklore.model.entity.CategoryEntity;
|
||||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import lombok.Getter;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
@@ -143,6 +144,7 @@ public class BookVectorService {
|
|||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Getter
|
||||||
public static class ScoredBook {
|
public static class ScoredBook {
|
||||||
private final Long bookId;
|
private final Long bookId;
|
||||||
private final double score;
|
private final double score;
|
||||||
@@ -152,13 +154,6 @@ public class BookVectorService {
|
|||||||
this.score = score;
|
this.score = score;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Long getBookId() {
|
|
||||||
return bookId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public double getScore() {
|
|
||||||
return score;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+10
-7
@@ -134,13 +134,16 @@ public class UserProvisioningService {
|
|||||||
return createUser(user);
|
return createUser(user);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Deprecated
|
/**
|
||||||
|
* Create and persist a remote-provisioned user based on incoming headers.
|
||||||
|
* This is the preferred (non-deprecated) entry point for remote provisioning.
|
||||||
|
*/
|
||||||
@Transactional
|
@Transactional
|
||||||
public BookLoreUserEntity provisionRemoteUser(String name, String username, String email, String groups) {
|
public BookLoreUserEntity provisionRemoteUserFromHeaders(String name, String username, String email, String groups) {
|
||||||
boolean isAdmin = false;
|
boolean isAdmin = false;
|
||||||
if (groups != null && appProperties.getRemoteAuth().getAdminGroup() != null) {
|
if (groups != null && appProperties.getRemoteAuth().getAdminGroup() != null) {
|
||||||
String groupsContent = groups.trim();
|
String groupsContent = groups.trim();
|
||||||
if (groupsContent.startsWith("[") && groupsContent.endsWith("]")) {
|
if (groupsContent.length() >= 2 && groupsContent.charAt(0) == '[' && groupsContent.charAt(groupsContent.length() - 1) == ']') {
|
||||||
groupsContent = groupsContent.substring(1, groupsContent.length() - 1);
|
groupsContent = groupsContent.substring(1, groupsContent.length() - 1);
|
||||||
}
|
}
|
||||||
List<String> groupsList = Arrays.asList(WHITESPACE_PATTERN.split(groupsContent));
|
List<String> groupsList = Arrays.asList(WHITESPACE_PATTERN.split(groupsContent));
|
||||||
@@ -199,9 +202,9 @@ public class UserProvisioningService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
protected BookLoreUserEntity createUser(BookLoreUserEntity user) {
|
protected BookLoreUserEntity createUser(BookLoreUserEntity user) {
|
||||||
user = userRepository.save(user);
|
BookLoreUserEntity save = userRepository.save(user);
|
||||||
userDefaultsService.addDefaultShelves(user);
|
userDefaultsService.addDefaultShelves(save);
|
||||||
userDefaultsService.addDefaultSettings(user);
|
userDefaultsService.addDefaultSettings(save);
|
||||||
return user;
|
return save;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,30 +9,32 @@ public class BookUtils {
|
|||||||
private static final Pattern PARENTHESES_WITH_OPTIONAL_SPACE_PATTERN = Pattern.compile("\\s?\\(.*?\\)");
|
private static final Pattern PARENTHESES_WITH_OPTIONAL_SPACE_PATTERN = Pattern.compile("\\s?\\(.*?\\)");
|
||||||
|
|
||||||
public static String cleanFileName(String fileName) {
|
public static String cleanFileName(String fileName) {
|
||||||
if (fileName == null) {
|
String name = fileName;
|
||||||
|
if (name == null) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
fileName = fileName.replace("(Z-Library)", "").trim();
|
name = name.replace("(Z-Library)", "").trim();
|
||||||
fileName = PARENTHESES_WITH_OPTIONAL_SPACE_PATTERN.matcher(fileName).replaceAll("").trim(); // Remove the author name inside parentheses (e.g. (Jon Yablonski))
|
name = PARENTHESES_WITH_OPTIONAL_SPACE_PATTERN.matcher(name).replaceAll("").trim(); // Remove the author name inside parentheses (e.g. (Jon Yablonski))
|
||||||
int dotIndex = fileName.lastIndexOf('.'); // Remove the file extension (e.g., .pdf, .docx)
|
int dotIndex = name.lastIndexOf('.'); // Remove the file extension (e.g., .pdf, .docx)
|
||||||
if (dotIndex > 0) {
|
if (dotIndex > 0) {
|
||||||
fileName = fileName.substring(0, dotIndex).trim();
|
name = name.substring(0, dotIndex).trim();
|
||||||
}
|
}
|
||||||
return fileName;
|
return name;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static String cleanAndTruncateSearchTerm(String term) {
|
public static String cleanAndTruncateSearchTerm(String term) {
|
||||||
term = SPECIAL_CHARACTERS_PATTERN.matcher(term).replaceAll("").trim();
|
String s = term;
|
||||||
if (term.length() > 60) {
|
s = SPECIAL_CHARACTERS_PATTERN.matcher(s).replaceAll("").trim();
|
||||||
String[] words = WHITESPACE_PATTERN.split(term);
|
if (s.length() > 60) {
|
||||||
|
String[] words = WHITESPACE_PATTERN.split(s);
|
||||||
StringBuilder truncated = new StringBuilder();
|
StringBuilder truncated = new StringBuilder();
|
||||||
for (String word : words) {
|
for (String word : words) {
|
||||||
if (truncated.length() + word.length() + 1 > 60) break;
|
if (truncated.length() + word.length() + 1 > 60) break;
|
||||||
if (!truncated.isEmpty()) truncated.append(" ");
|
if (!truncated.isEmpty()) truncated.append(" ");
|
||||||
truncated.append(word);
|
truncated.append(word);
|
||||||
}
|
}
|
||||||
term = truncated.toString();
|
s = truncated.toString();
|
||||||
}
|
}
|
||||||
return term;
|
return s;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ import java.awt.image.BufferedImage;
|
|||||||
import java.io.ByteArrayInputStream;
|
import java.io.ByteArrayInputStream;
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
import java.net.URI;
|
||||||
import java.net.URL;
|
import java.net.URL;
|
||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
@@ -154,7 +155,8 @@ public class FileService {
|
|||||||
|
|
||||||
public BufferedImage downloadImageFromUrl(String imageUrl) throws IOException {
|
public BufferedImage downloadImageFromUrl(String imageUrl) throws IOException {
|
||||||
try {
|
try {
|
||||||
URL url = new URL(imageUrl);
|
URI uri = URI.create(imageUrl);
|
||||||
|
URL url = uri.toURL();
|
||||||
BufferedImage image = ImageIO.read(url);
|
BufferedImage image = ImageIO.read(url);
|
||||||
if (image == null) {
|
if (image == null) {
|
||||||
throw new IOException("Unable to read image from URL: " + imageUrl);
|
throw new IOException("Unable to read image from URL: " + imageUrl);
|
||||||
|
|||||||
+6
-4
@@ -157,10 +157,12 @@ public class MetadataChangeDetector {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static boolean isEffectivelyEmpty(Object value) {
|
private static boolean isEffectivelyEmpty(Object value) {
|
||||||
if (value == null) return true;
|
return switch (value) {
|
||||||
if (value instanceof String s) return s.isBlank();
|
case null -> true;
|
||||||
if (value instanceof Collection<?> c) return c.isEmpty();
|
case String s -> s.isBlank();
|
||||||
return false;
|
case Collection<?> c -> c.isEmpty();
|
||||||
|
default -> false;
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
private static boolean differsLock(Boolean dtoLock, Boolean entityLock) {
|
private static boolean differsLock(Boolean dtoLock, Boolean entityLock) {
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ public class PathPatternResolver {
|
|||||||
private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\s+");
|
private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\s+");
|
||||||
private static final Pattern FILE_EXTENSION_PATTERN = Pattern.compile(".*\\.[a-zA-Z0-9]+$");
|
private static final Pattern FILE_EXTENSION_PATTERN = Pattern.compile(".*\\.[a-zA-Z0-9]+$");
|
||||||
private static final Pattern CONTROL_CHARACTER_PATTERN = Pattern.compile("[\\p{Cntrl}]");
|
private static final Pattern CONTROL_CHARACTER_PATTERN = Pattern.compile("[\\p{Cntrl}]");
|
||||||
|
private static final Pattern INVALID_CHARS_PATTERN = Pattern.compile("[\\\\/:*?\"<>|]");
|
||||||
|
|
||||||
public static String resolvePattern(BookEntity book, String pattern) {
|
public static String resolvePattern(BookEntity book, String pattern) {
|
||||||
String currentFilename = book.getFileName() != null ? book.getFileName().trim() : "";
|
String currentFilename = book.getFileName() != null ? book.getFileName().trim() : "";
|
||||||
@@ -90,7 +91,7 @@ public class PathPatternResolver {
|
|||||||
|
|
||||||
private static String resolvePatternWithValues(String pattern, Map<String, String> values, String currentFilename) {
|
private static String resolvePatternWithValues(String pattern, Map<String, String> values, String currentFilename) {
|
||||||
String extension = "";
|
String extension = "";
|
||||||
int lastDot = currentFilename.lastIndexOf(".");
|
int lastDot = currentFilename.lastIndexOf('.');
|
||||||
if (lastDot >= 0 && lastDot < currentFilename.length() - 1) {
|
if (lastDot >= 0 && lastDot < currentFilename.length() - 1) {
|
||||||
extension = sanitize(currentFilename.substring(lastDot + 1)); // e.g. "epub"
|
extension = sanitize(currentFilename.substring(lastDot + 1)); // e.g. "epub"
|
||||||
}
|
}
|
||||||
@@ -100,7 +101,7 @@ public class PathPatternResolver {
|
|||||||
// Handle optional blocks enclosed in <...>
|
// Handle optional blocks enclosed in <...>
|
||||||
Pattern optionalBlockPattern = Pattern.compile("<([^<>]*)>");
|
Pattern optionalBlockPattern = Pattern.compile("<([^<>]*)>");
|
||||||
Matcher matcher = optionalBlockPattern.matcher(pattern);
|
Matcher matcher = optionalBlockPattern.matcher(pattern);
|
||||||
StringBuffer resolved = new StringBuffer();
|
StringBuilder resolved = new StringBuilder();
|
||||||
|
|
||||||
while (matcher.find()) {
|
while (matcher.find()) {
|
||||||
String block = matcher.group(1);
|
String block = matcher.group(1);
|
||||||
@@ -134,7 +135,7 @@ public class PathPatternResolver {
|
|||||||
// Replace known placeholders with values, preserve unknown ones
|
// Replace known placeholders with values, preserve unknown ones
|
||||||
Pattern placeholderPattern = Pattern.compile("\\{(.*?)}");
|
Pattern placeholderPattern = Pattern.compile("\\{(.*?)}");
|
||||||
Matcher placeholderMatcher = placeholderPattern.matcher(result);
|
Matcher placeholderMatcher = placeholderPattern.matcher(result);
|
||||||
StringBuffer finalResult = new StringBuffer();
|
StringBuilder finalResult = new StringBuilder();
|
||||||
|
|
||||||
while (placeholderMatcher.find()) {
|
while (placeholderMatcher.find()) {
|
||||||
String key = placeholderMatcher.group(1);
|
String key = placeholderMatcher.group(1);
|
||||||
@@ -166,8 +167,7 @@ public class PathPatternResolver {
|
|||||||
|
|
||||||
private static String sanitize(String input) {
|
private static String sanitize(String input) {
|
||||||
if (input == null) return "";
|
if (input == null) return "";
|
||||||
return WHITESPACE_PATTERN.matcher(CONTROL_CHARACTER_PATTERN.matcher(input
|
return WHITESPACE_PATTERN.matcher(CONTROL_CHARACTER_PATTERN.matcher(INVALID_CHARS_PATTERN.matcher(input).replaceAll("")).replaceAll("")).replaceAll(" ")
|
||||||
.replaceAll("[\\\\/:*?\"<>|]", "")).replaceAll("")).replaceAll(" ")
|
|
||||||
.trim();
|
.trim();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+1
-2
@@ -55,14 +55,13 @@ class AdditionalFileServiceTest {
|
|||||||
private BookAdditionalFileEntity fileEntity;
|
private BookAdditionalFileEntity fileEntity;
|
||||||
private AdditionalFile additionalFile;
|
private AdditionalFile additionalFile;
|
||||||
private BookEntity bookEntity;
|
private BookEntity bookEntity;
|
||||||
private LibraryPathEntity libraryPathEntity;
|
|
||||||
|
|
||||||
@BeforeEach
|
@BeforeEach
|
||||||
void setUp() throws IOException {
|
void setUp() throws IOException {
|
||||||
Path testFile = tempDir.resolve("test-file.pdf");
|
Path testFile = tempDir.resolve("test-file.pdf");
|
||||||
Files.createFile(testFile);
|
Files.createFile(testFile);
|
||||||
|
|
||||||
libraryPathEntity = new LibraryPathEntity();
|
LibraryPathEntity libraryPathEntity = new LibraryPathEntity();
|
||||||
libraryPathEntity.setId(1L);
|
libraryPathEntity.setId(1L);
|
||||||
libraryPathEntity.setPath(tempDir.toString());
|
libraryPathEntity.setPath(tempDir.toString());
|
||||||
|
|
||||||
|
|||||||
+3
-3
@@ -73,7 +73,7 @@ class BookNoteServiceTest {
|
|||||||
.build();
|
.build();
|
||||||
|
|
||||||
BookEntity book = BookEntity.builder().id(bookId).build();
|
BookEntity book = BookEntity.builder().id(bookId).build();
|
||||||
BookLoreUserEntity userEntity = BookLoreUserEntity.builder().id(userId).build();
|
BookLoreUserEntity userEntity = BookLoreUserEntity.builder().id(userId).isDefaultPassword(false).build();
|
||||||
BookNoteEntity savedEntity = BookNoteEntity.builder().id(noteId).build();
|
BookNoteEntity savedEntity = BookNoteEntity.builder().id(noteId).build();
|
||||||
BookNote dto = BookNote.builder().id(noteId).build();
|
BookNote dto = BookNote.builder().id(noteId).build();
|
||||||
|
|
||||||
@@ -108,7 +108,7 @@ class BookNoteServiceTest {
|
|||||||
BookNote dto = BookNote.builder().id(noteId).title("new title").content("new content").build();
|
BookNote dto = BookNote.builder().id(noteId).title("new title").content("new content").build();
|
||||||
|
|
||||||
when(bookRepository.findById(bookId)).thenReturn(Optional.of(BookEntity.builder().id(bookId).build()));
|
when(bookRepository.findById(bookId)).thenReturn(Optional.of(BookEntity.builder().id(bookId).build()));
|
||||||
when(userRepository.findById(userId)).thenReturn(Optional.of(BookLoreUserEntity.builder().id(userId).build()));
|
when(userRepository.findById(userId)).thenReturn(Optional.of(BookLoreUserEntity.builder().id(userId).isDefaultPassword(false).build()));
|
||||||
when(bookNoteRepository.findByIdAndUserId(noteId, userId)).thenReturn(Optional.of(existing));
|
when(bookNoteRepository.findByIdAndUserId(noteId, userId)).thenReturn(Optional.of(existing));
|
||||||
when(bookNoteRepository.save(existing)).thenReturn(saved);
|
when(bookNoteRepository.save(existing)).thenReturn(saved);
|
||||||
when(mapper.toDto(saved)).thenReturn(dto);
|
when(mapper.toDto(saved)).thenReturn(dto);
|
||||||
@@ -162,7 +162,7 @@ class BookNoteServiceTest {
|
|||||||
.build();
|
.build();
|
||||||
|
|
||||||
when(bookRepository.findById(bookId)).thenReturn(Optional.of(BookEntity.builder().id(bookId).build()));
|
when(bookRepository.findById(bookId)).thenReturn(Optional.of(BookEntity.builder().id(bookId).build()));
|
||||||
when(userRepository.findById(userId)).thenReturn(Optional.of(BookLoreUserEntity.builder().id(userId).build()));
|
when(userRepository.findById(userId)).thenReturn(Optional.of(BookLoreUserEntity.builder().id(userId).isDefaultPassword(false).build()));
|
||||||
when(bookNoteRepository.findByIdAndUserId(noteId, userId)).thenReturn(Optional.empty());
|
when(bookNoteRepository.findByIdAndUserId(noteId, userId)).thenReturn(Optional.empty());
|
||||||
|
|
||||||
assertThrows(EntityNotFoundException.class, () -> service.createOrUpdateNote(req));
|
assertThrows(EntityNotFoundException.class, () -> service.createOrUpdateNote(req));
|
||||||
|
|||||||
+9
-9
@@ -100,10 +100,10 @@ class BookReviewServiceTest {
|
|||||||
Set<MetadataPublicReviewsSettings.ReviewProviderConfig> configs = new HashSet<>();
|
Set<MetadataPublicReviewsSettings.ReviewProviderConfig> configs = new HashSet<>();
|
||||||
for (MetadataProvider provider : providers) {
|
for (MetadataProvider provider : providers) {
|
||||||
MetadataPublicReviewsSettings.ReviewProviderConfig config =
|
MetadataPublicReviewsSettings.ReviewProviderConfig config =
|
||||||
MetadataPublicReviewsSettings.ReviewProviderConfig.builder()
|
MetadataPublicReviewsSettings.ReviewProviderConfig.builder()
|
||||||
.provider(provider)
|
.provider(provider)
|
||||||
.enabled(true)
|
.enabled(true)
|
||||||
.build();
|
.maxReviews(10).build();
|
||||||
configs.add(config);
|
configs.add(config);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -193,7 +193,7 @@ class BookReviewServiceTest {
|
|||||||
when(bookRepository.findById(bookId)).thenReturn(Optional.of(bookEntity));
|
when(bookRepository.findById(bookId)).thenReturn(Optional.of(bookEntity));
|
||||||
when(mapper.toDto(savedEntity)).thenReturn(freshReview);
|
when(mapper.toDto(savedEntity)).thenReturn(freshReview);
|
||||||
|
|
||||||
Map<MetadataProvider, BookMetadata> metadataMap = new HashMap<>();
|
Map<MetadataProvider, BookMetadata> metadataMap = new EnumMap<>(MetadataProvider.class);
|
||||||
metadataMap.put(MetadataProvider.Amazon, BookMetadata.builder()
|
metadataMap.put(MetadataProvider.Amazon, BookMetadata.builder()
|
||||||
.bookReviews(Collections.singletonList(freshReview))
|
.bookReviews(Collections.singletonList(freshReview))
|
||||||
.build());
|
.build());
|
||||||
@@ -204,7 +204,7 @@ class BookReviewServiceTest {
|
|||||||
List<BookReview> result = service.getByBookId(bookId);
|
List<BookReview> result = service.getByBookId(bookId);
|
||||||
|
|
||||||
assertEquals(1, result.size());
|
assertEquals(1, result.size());
|
||||||
assertEquals(freshReview, result.get(0));
|
assertEquals(freshReview, result.getFirst());
|
||||||
verify(bookReviewUpdateService).addReviewsToBook(
|
verify(bookReviewUpdateService).addReviewsToBook(
|
||||||
Collections.singletonList(freshReview), bookEntity.getMetadata());
|
Collections.singletonList(freshReview), bookEntity.getMetadata());
|
||||||
verify(bookRepository).save(bookEntity);
|
verify(bookRepository).save(bookEntity);
|
||||||
@@ -229,7 +229,7 @@ class BookReviewServiceTest {
|
|||||||
when(bookRepository.findById(bookId)).thenReturn(Optional.of(bookEntity));
|
when(bookRepository.findById(bookId)).thenReturn(Optional.of(bookEntity));
|
||||||
when(mapper.toDto(savedEntity)).thenReturn(freshReview);
|
when(mapper.toDto(savedEntity)).thenReturn(freshReview);
|
||||||
|
|
||||||
Map<MetadataProvider, BookMetadata> metadataMap = new HashMap<>();
|
Map<MetadataProvider, BookMetadata> metadataMap = new EnumMap<>(MetadataProvider.class);
|
||||||
metadataMap.put(MetadataProvider.GoodReads, BookMetadata.builder()
|
metadataMap.put(MetadataProvider.GoodReads, BookMetadata.builder()
|
||||||
.bookReviews(Collections.singletonList(freshReview))
|
.bookReviews(Collections.singletonList(freshReview))
|
||||||
.build());
|
.build());
|
||||||
@@ -305,7 +305,7 @@ class BookReviewServiceTest {
|
|||||||
BookReview amazonReview = createBookReview(MetadataProvider.Amazon);
|
BookReview amazonReview = createBookReview(MetadataProvider.Amazon);
|
||||||
BookReview goodreadsReview = createBookReview(MetadataProvider.GoodReads);
|
BookReview goodreadsReview = createBookReview(MetadataProvider.GoodReads);
|
||||||
|
|
||||||
Map<MetadataProvider, BookMetadata> metadataMap = new HashMap<>();
|
Map<MetadataProvider, BookMetadata> metadataMap = new EnumMap<>(MetadataProvider.class);
|
||||||
metadataMap.put(MetadataProvider.Amazon, BookMetadata.builder()
|
metadataMap.put(MetadataProvider.Amazon, BookMetadata.builder()
|
||||||
.bookReviews(Collections.singletonList(amazonReview))
|
.bookReviews(Collections.singletonList(amazonReview))
|
||||||
.build());
|
.build());
|
||||||
@@ -330,7 +330,7 @@ class BookReviewServiceTest {
|
|||||||
AppSettings appSettings = new AppSettings();
|
AppSettings appSettings = new AppSettings();
|
||||||
appSettings.setMetadataPublicReviewsSettings(createReviewSettings(true, MetadataProvider.Amazon));
|
appSettings.setMetadataPublicReviewsSettings(createReviewSettings(true, MetadataProvider.Amazon));
|
||||||
|
|
||||||
Map<MetadataProvider, BookMetadata> metadataMap = new HashMap<>();
|
Map<MetadataProvider, BookMetadata> metadataMap = new EnumMap<>(MetadataProvider.class);
|
||||||
metadataMap.put(MetadataProvider.Amazon, BookMetadata.builder()
|
metadataMap.put(MetadataProvider.Amazon, BookMetadata.builder()
|
||||||
.bookReviews(null)
|
.bookReviews(null)
|
||||||
.build());
|
.build());
|
||||||
|
|||||||
+1
-3
@@ -140,9 +140,7 @@ class BookdropMetadataServiceTest {
|
|||||||
|
|
||||||
when(bookdropFileRepository.findById(sampleFile.getId())).thenReturn(Optional.of(sampleFile));
|
when(bookdropFileRepository.findById(sampleFile.getId())).thenReturn(Optional.of(sampleFile));
|
||||||
|
|
||||||
assertThatThrownBy(() -> {
|
assertThatThrownBy(() -> bookdropMetadataService.attachInitialMetadata(sampleFile.getId())).isInstanceOf(APIException.class)
|
||||||
bookdropMetadataService.attachInitialMetadata(sampleFile.getId());
|
|
||||||
}).isInstanceOf(APIException.class)
|
|
||||||
.hasMessageContaining("Invalid file format");
|
.hasMessageContaining("Invalid file format");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+3
-5
@@ -46,8 +46,6 @@ class KoreaderServiceTest {
|
|||||||
KoreaderService service;
|
KoreaderService service;
|
||||||
|
|
||||||
private KoreaderUserDetails details;
|
private KoreaderUserDetails details;
|
||||||
private Authentication auth;
|
|
||||||
private SecurityContext context;
|
|
||||||
|
|
||||||
@BeforeEach
|
@BeforeEach
|
||||||
void setUpAuth() {
|
void setUpAuth() {
|
||||||
@@ -55,8 +53,8 @@ class KoreaderServiceTest {
|
|||||||
when(details.getUsername()).thenReturn("u");
|
when(details.getUsername()).thenReturn("u");
|
||||||
when(details.getPassword()).thenReturn("md5pwd");
|
when(details.getPassword()).thenReturn("md5pwd");
|
||||||
when(details.getBookLoreUserId()).thenReturn(42L);
|
when(details.getBookLoreUserId()).thenReturn(42L);
|
||||||
auth = mock(Authentication.class);
|
Authentication auth = mock(Authentication.class);
|
||||||
context = new SecurityContextImpl();
|
SecurityContext context = new SecurityContextImpl();
|
||||||
when(auth.getPrincipal()).thenReturn(details);
|
when(auth.getPrincipal()).thenReturn(details);
|
||||||
context.setAuthentication(auth);
|
context.setAuthentication(auth);
|
||||||
SecurityContextHolder.setContext(context);
|
SecurityContextHolder.setContext(context);
|
||||||
@@ -77,7 +75,7 @@ class KoreaderServiceTest {
|
|||||||
when(details.getPassword()).thenReturn("MD5PWD");
|
when(details.getPassword()).thenReturn("MD5PWD");
|
||||||
|
|
||||||
ResponseEntity<Map<String, String>> resp = service.authorizeUser();
|
ResponseEntity<Map<String, String>> resp = service.authorizeUser();
|
||||||
assertEquals(200, resp.getStatusCodeValue());
|
assertEquals(200, resp.getStatusCode().value());
|
||||||
assertEquals("u", resp.getBody().get("username"));
|
assertEquals("u", resp.getBody().get("username"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+1
-2
@@ -34,14 +34,13 @@ class KoreaderUserServiceTest {
|
|||||||
@InjectMocks
|
@InjectMocks
|
||||||
KoreaderUserService service;
|
KoreaderUserService service;
|
||||||
|
|
||||||
private BookLoreUser ownerDto;
|
|
||||||
private BookLoreUserEntity ownerEntity;
|
private BookLoreUserEntity ownerEntity;
|
||||||
private KoreaderUserEntity entity;
|
private KoreaderUserEntity entity;
|
||||||
private KoreaderUser dto;
|
private KoreaderUser dto;
|
||||||
|
|
||||||
@BeforeEach
|
@BeforeEach
|
||||||
void init() {
|
void init() {
|
||||||
ownerDto = mock(BookLoreUser.class);
|
BookLoreUser ownerDto = mock(BookLoreUser.class);
|
||||||
when(ownerDto.getId()).thenReturn(123L);
|
when(ownerDto.getId()).thenReturn(123L);
|
||||||
when(ownerDto.getUsername()).thenReturn("ownerName");
|
when(ownerDto.getUsername()).thenReturn("ownerName");
|
||||||
when(authService.getAuthenticatedUser()).thenReturn(ownerDto);
|
when(authService.getAuthenticatedUser()).thenReturn(ownerDto);
|
||||||
|
|||||||
+8
-8
@@ -77,7 +77,7 @@ class OpdsBookServiceTest {
|
|||||||
|
|
||||||
List<Library> libraries = new ArrayList<>();
|
List<Library> libraries = new ArrayList<>();
|
||||||
for (Long id : libraryIds) {
|
for (Long id : libraryIds) {
|
||||||
libraries.add(Library.builder().id(id).name("Lib" + id).build());
|
libraries.add(Library.builder().id(id).name("Lib" + id).watch(false).build());
|
||||||
}
|
}
|
||||||
when(user.getAssignedLibraries()).thenReturn(libraries);
|
when(user.getAssignedLibraries()).thenReturn(libraries);
|
||||||
|
|
||||||
@@ -86,7 +86,7 @@ class OpdsBookServiceTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void getAccessibleLibraries_returnsAllLibraries_whenNoUserDetails() {
|
void getAccessibleLibraries_returnsAllLibraries_whenNoUserDetails() {
|
||||||
List<Library> libraries = List.of(Library.builder().id(1L).name("Lib1").build());
|
List<Library> libraries = List.of(Library.builder().id(1L).name("Lib1").watch(false).build());
|
||||||
when(libraryService.getAllLibraries()).thenReturn(libraries);
|
when(libraryService.getAllLibraries()).thenReturn(libraries);
|
||||||
|
|
||||||
List<Library> result = opdsBookService.getAccessibleLibraries(null);
|
List<Library> result = opdsBookService.getAccessibleLibraries(null);
|
||||||
@@ -104,7 +104,7 @@ class OpdsBookServiceTest {
|
|||||||
BookLoreUser.UserPermissions perms = mock(BookLoreUser.UserPermissions.class);
|
BookLoreUser.UserPermissions perms = mock(BookLoreUser.UserPermissions.class);
|
||||||
when(user.getPermissions()).thenReturn(perms);
|
when(user.getPermissions()).thenReturn(perms);
|
||||||
when(perms.isAdmin()).thenReturn(false);
|
when(perms.isAdmin()).thenReturn(false);
|
||||||
List<Library> assigned = List.of(Library.builder().id(2L).build());
|
List<Library> assigned = List.of(Library.builder().id(2L).watch(false).build());
|
||||||
when(user.getAssignedLibraries()).thenReturn(assigned);
|
when(user.getAssignedLibraries()).thenReturn(assigned);
|
||||||
|
|
||||||
List<Library> result = opdsBookService.getAccessibleLibraries(details);
|
List<Library> result = opdsBookService.getAccessibleLibraries(details);
|
||||||
@@ -115,7 +115,7 @@ class OpdsBookServiceTest {
|
|||||||
@Test
|
@Test
|
||||||
void getAccessibleLibraries_returnsAllLibraries_forAdmin() {
|
void getAccessibleLibraries_returnsAllLibraries_forAdmin() {
|
||||||
OpdsUserDetails details = v2UserDetails(1L, true, Set.of(1L));
|
OpdsUserDetails details = v2UserDetails(1L, true, Set.of(1L));
|
||||||
List<Library> allLibs = List.of(Library.builder().id(1L).build());
|
List<Library> allLibs = List.of(Library.builder().id(1L).watch(false).build());
|
||||||
when(libraryService.getAllLibraries()).thenReturn(allLibs);
|
when(libraryService.getAllLibraries()).thenReturn(allLibs);
|
||||||
|
|
||||||
List<Library> result = opdsBookService.getAccessibleLibraries(details);
|
List<Library> result = opdsBookService.getAccessibleLibraries(details);
|
||||||
@@ -194,7 +194,7 @@ class OpdsBookServiceTest {
|
|||||||
BookLoreUser.UserPermissions perms = mock(BookLoreUser.UserPermissions.class);
|
BookLoreUser.UserPermissions perms = mock(BookLoreUser.UserPermissions.class);
|
||||||
when(user.getPermissions()).thenReturn(perms);
|
when(user.getPermissions()).thenReturn(perms);
|
||||||
when(perms.isAdmin()).thenReturn(false);
|
when(perms.isAdmin()).thenReturn(false);
|
||||||
List<Library> libs = List.of(Library.builder().id(1L).build());
|
List<Library> libs = List.of(Library.builder().id(1L).watch(false).build());
|
||||||
when(user.getAssignedLibraries()).thenReturn(libs);
|
when(user.getAssignedLibraries()).thenReturn(libs);
|
||||||
|
|
||||||
Book book = Book.builder().id(1L).shelves(Set.of(Shelf.builder().userId(2L).build())).build();
|
Book book = Book.builder().id(1L).shelves(Set.of(Shelf.builder().userId(2L).build())).build();
|
||||||
@@ -208,12 +208,12 @@ class OpdsBookServiceTest {
|
|||||||
Page<Book> result = opdsBookService.getRecentBooksPage(details, 0, 10);
|
Page<Book> result = opdsBookService.getRecentBooksPage(details, 0, 10);
|
||||||
|
|
||||||
assertThat(result.getContent()).hasSize(1);
|
assertThat(result.getContent()).hasSize(1);
|
||||||
assertThat(result.getContent().get(0).getShelves()).allMatch(shelf -> shelf.getUserId().equals(2L));
|
assertThat(result.getContent().getFirst().getShelves()).allMatch(shelf -> shelf.getUserId().equals(2L));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void getLibraryName_returnsName_whenFound() {
|
void getLibraryName_returnsName_whenFound() {
|
||||||
List<Library> libs = List.of(Library.builder().id(1L).name("Lib1").build());
|
List<Library> libs = List.of(Library.builder().id(1L).name("Lib1").watch(false).build());
|
||||||
when(libraryService.getAllLibraries()).thenReturn(libs);
|
when(libraryService.getAllLibraries()).thenReturn(libs);
|
||||||
|
|
||||||
String name = opdsBookService.getLibraryName(1L);
|
String name = opdsBookService.getLibraryName(1L);
|
||||||
@@ -264,7 +264,7 @@ class OpdsBookServiceTest {
|
|||||||
void getRandomBooks_returnsBooks_whenLibrariesAccessible() {
|
void getRandomBooks_returnsBooks_whenLibrariesAccessible() {
|
||||||
OpdsUserDetails details = v2UserDetails(1L, true, Set.of(1L));
|
OpdsUserDetails details = v2UserDetails(1L, true, Set.of(1L));
|
||||||
OpdsBookService spy = Mockito.spy(opdsBookService);
|
OpdsBookService spy = Mockito.spy(opdsBookService);
|
||||||
List<Library> libs = List.of(Library.builder().id(1L).build());
|
List<Library> libs = List.of(Library.builder().id(1L).watch(false).build());
|
||||||
doReturn(libs).when(spy).getAccessibleLibraries(details);
|
doReturn(libs).when(spy).getAccessibleLibraries(details);
|
||||||
|
|
||||||
when(bookOpdsRepository.findRandomBookIdsByLibraryIds(anyList())).thenReturn(List.of(1L, 2L));
|
when(bookOpdsRepository.findRandomBookIdsByLibraryIds(anyList())).thenReturn(List.of(1L, 2L));
|
||||||
|
|||||||
+2
-3
@@ -86,12 +86,11 @@ class BookDropServiceTest {
|
|||||||
|
|
||||||
private BookdropFileEntity bookdropFileEntity;
|
private BookdropFileEntity bookdropFileEntity;
|
||||||
private LibraryEntity libraryEntity;
|
private LibraryEntity libraryEntity;
|
||||||
private LibraryPathEntity libraryPathEntity;
|
|
||||||
private BookdropFile bookdropFile;
|
private BookdropFile bookdropFile;
|
||||||
|
|
||||||
@BeforeEach
|
@BeforeEach
|
||||||
void setUp() throws IOException {
|
void setUp() throws IOException {
|
||||||
libraryPathEntity = new LibraryPathEntity();
|
LibraryPathEntity libraryPathEntity = new LibraryPathEntity();
|
||||||
libraryPathEntity.setId(1L);
|
libraryPathEntity.setId(1L);
|
||||||
libraryPathEntity.setPath(tempDir.toString());
|
libraryPathEntity.setPath(tempDir.toString());
|
||||||
|
|
||||||
@@ -142,7 +141,7 @@ class BookDropServiceTest {
|
|||||||
Page<BookdropFile> result = bookDropService.getFilesByStatus("pending", pageable);
|
Page<BookdropFile> result = bookDropService.getFilesByStatus("pending", pageable);
|
||||||
|
|
||||||
assertEquals(1, result.getContent().size());
|
assertEquals(1, result.getContent().size());
|
||||||
assertEquals(bookdropFile, result.getContent().get(0));
|
assertEquals(bookdropFile, result.getContent().getFirst());
|
||||||
verify(bookdropFileRepository).findAllByStatus(BookdropFileEntity.Status.PENDING_REVIEW, pageable);
|
verify(bookdropFileRepository).findAllByStatus(BookdropFileEntity.Status.PENDING_REVIEW, pageable);
|
||||||
verify(mapper).toDto(bookdropFileEntity);
|
verify(mapper).toDto(bookdropFileEntity);
|
||||||
}
|
}
|
||||||
|
|||||||
+6
-6
@@ -215,7 +215,7 @@ class AbstractFileProcessorTest {
|
|||||||
@Test
|
@Test
|
||||||
void processFile_shouldReturnUpdated_whenDuplicateFoundWithDifferentLibraryPath() {
|
void processFile_shouldReturnUpdated_whenDuplicateFoundWithDifferentLibraryPath() {
|
||||||
// Given
|
// Given
|
||||||
LibraryEntity library = LibraryEntity.builder().id(2L).build();
|
LibraryEntity library = LibraryEntity.builder().id(2L).watch(false).build();
|
||||||
LibraryPathEntity newLibraryPath = LibraryPathEntity.builder()
|
LibraryPathEntity newLibraryPath = LibraryPathEntity.builder()
|
||||||
.id(2L)
|
.id(2L)
|
||||||
.library(library)
|
.library(library)
|
||||||
@@ -232,7 +232,7 @@ class AbstractFileProcessorTest {
|
|||||||
|
|
||||||
Book duplicateBook = createMockBook(1L, "file.pdf");
|
Book duplicateBook = createMockBook(1L, "file.pdf");
|
||||||
BookEntity existingEntity = createMockBookEntity(1L, "file.pdf", "hash1", "sub",
|
BookEntity existingEntity = createMockBookEntity(1L, "file.pdf", "hash1", "sub",
|
||||||
LibraryPathEntity.builder().id(1L).library(LibraryEntity.builder().id(1L).build()).path("/old-path").build());
|
LibraryPathEntity.builder().id(1L).library(LibraryEntity.builder().id(1L).watch(false).build()).path("/old-path").build());
|
||||||
Book updatedBook = createMockBook(1L, "file.pdf");
|
Book updatedBook = createMockBook(1L, "file.pdf");
|
||||||
|
|
||||||
try (MockedStatic<FileFingerprint> fingerprintMock = mockStatic(FileFingerprint.class)) {
|
try (MockedStatic<FileFingerprint> fingerprintMock = mockStatic(FileFingerprint.class)) {
|
||||||
@@ -331,7 +331,7 @@ class AbstractFileProcessorTest {
|
|||||||
@Test
|
@Test
|
||||||
void processFile_shouldHandleNullFileSubPath() {
|
void processFile_shouldHandleNullFileSubPath() {
|
||||||
// Given
|
// Given
|
||||||
LibraryEntity library = LibraryEntity.builder().id(1L).build();
|
LibraryEntity library = LibraryEntity.builder().id(1L).watch(false).build();
|
||||||
LibraryPathEntity libraryPath = LibraryPathEntity.builder()
|
LibraryPathEntity libraryPath = LibraryPathEntity.builder()
|
||||||
.id(1L)
|
.id(1L)
|
||||||
.library(library)
|
.library(library)
|
||||||
@@ -373,7 +373,7 @@ class AbstractFileProcessorTest {
|
|||||||
@Test
|
@Test
|
||||||
void processFile_shouldHandleMultipleMetadataChangesSimultaneously() {
|
void processFile_shouldHandleMultipleMetadataChangesSimultaneously() {
|
||||||
// Given
|
// Given
|
||||||
LibraryEntity newLibrary = LibraryEntity.builder().id(2L).build();
|
LibraryEntity newLibrary = LibraryEntity.builder().id(2L).watch(false).build();
|
||||||
LibraryPathEntity newLibraryPath = LibraryPathEntity.builder()
|
LibraryPathEntity newLibraryPath = LibraryPathEntity.builder()
|
||||||
.id(2L)
|
.id(2L)
|
||||||
.library(newLibrary)
|
.library(newLibrary)
|
||||||
@@ -390,7 +390,7 @@ class AbstractFileProcessorTest {
|
|||||||
|
|
||||||
Book duplicateBook = createMockBook(1L, "old-file.pdf");
|
Book duplicateBook = createMockBook(1L, "old-file.pdf");
|
||||||
BookEntity existingEntity = createMockBookEntity(1L, "old-file.pdf", "hash1", "old-sub",
|
BookEntity existingEntity = createMockBookEntity(1L, "old-file.pdf", "hash1", "old-sub",
|
||||||
LibraryPathEntity.builder().id(1L).library(LibraryEntity.builder().id(1L).build()).build());
|
LibraryPathEntity.builder().id(1L).library(LibraryEntity.builder().id(1L).watch(false).build()).build());
|
||||||
Book updatedBook = createMockBook(1L, "new-file.pdf");
|
Book updatedBook = createMockBook(1L, "new-file.pdf");
|
||||||
|
|
||||||
try (MockedStatic<FileFingerprint> fingerprintMock = mockStatic(FileFingerprint.class)) {
|
try (MockedStatic<FileFingerprint> fingerprintMock = mockStatic(FileFingerprint.class)) {
|
||||||
@@ -442,7 +442,7 @@ class AbstractFileProcessorTest {
|
|||||||
|
|
||||||
// Helper methods
|
// Helper methods
|
||||||
private LibraryFile createMockLibraryFile() {
|
private LibraryFile createMockLibraryFile() {
|
||||||
LibraryEntity library = LibraryEntity.builder().id(1L).build();
|
LibraryEntity library = LibraryEntity.builder().id(1L).watch(false).build();
|
||||||
LibraryPathEntity libraryPath = LibraryPathEntity.builder()
|
LibraryPathEntity libraryPath = LibraryPathEntity.builder()
|
||||||
.id(1L)
|
.id(1L)
|
||||||
.library(library)
|
.library(library)
|
||||||
|
|||||||
+2
-2
@@ -62,7 +62,7 @@ class LibraryRescanHelperTest {
|
|||||||
|
|
||||||
LibraryRescanOptions options = LibraryRescanOptions.builder()
|
LibraryRescanOptions options = LibraryRescanOptions.builder()
|
||||||
.metadataReplaceMode(MetadataReplaceMode.REPLACE_ALL)
|
.metadataReplaceMode(MetadataReplaceMode.REPLACE_ALL)
|
||||||
.build();
|
.updateMetadataFromFiles(true).build();
|
||||||
|
|
||||||
rescanContext = RescanLibraryContext.builder()
|
rescanContext = RescanLibraryContext.builder()
|
||||||
.libraryId(1L)
|
.libraryId(1L)
|
||||||
@@ -226,7 +226,7 @@ class LibraryRescanHelperTest {
|
|||||||
|
|
||||||
List<TaskProgressPayload> payloads = payloadCaptor.getAllValues();
|
List<TaskProgressPayload> payloads = payloadCaptor.getAllValues();
|
||||||
assertEquals(3, payloads.size());
|
assertEquals(3, payloads.size());
|
||||||
assertEquals(0, payloads.get(0).getProgress());
|
assertEquals(0, payloads.getFirst().getProgress());
|
||||||
assertEquals(TaskStatus.IN_PROGRESS, payloads.get(0).getTaskStatus());
|
assertEquals(TaskStatus.IN_PROGRESS, payloads.get(0).getTaskStatus());
|
||||||
assertEquals(TaskType.REFRESH_LIBRARY_METADATA, payloads.get(0).getTaskType());
|
assertEquals(TaskType.REFRESH_LIBRARY_METADATA, payloads.get(0).getTaskType());
|
||||||
assertEquals(TaskStatus.IN_PROGRESS, payloads.get(1).getTaskStatus());
|
assertEquals(TaskStatus.IN_PROGRESS, payloads.get(1).getTaskStatus());
|
||||||
|
|||||||
+5
-6
@@ -16,6 +16,7 @@ import java.nio.charset.StandardCharsets;
|
|||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
import java.time.LocalDate;
|
import java.time.LocalDate;
|
||||||
|
import java.util.Comparator;
|
||||||
import java.util.LinkedHashMap;
|
import java.util.LinkedHashMap;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.zip.ZipEntry;
|
import java.util.zip.ZipEntry;
|
||||||
@@ -42,15 +43,14 @@ class CbxMetadataExtractorTest {
|
|||||||
if (tempDir != null) {
|
if (tempDir != null) {
|
||||||
// best-effort cleanup
|
// best-effort cleanup
|
||||||
Files.walk(tempDir)
|
Files.walk(tempDir)
|
||||||
.sorted((a, b) -> b.compareTo(a))
|
.sorted(Comparator.reverseOrder())
|
||||||
.forEach(p -> { try { Files.deleteIfExists(p); } catch (Exception ignore) {} });
|
.forEach(p -> { try { Files.deleteIfExists(p); } catch (Exception ignore) {} });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void extractMetadata_fromCbz_withComicInfo_populatesFields() throws Exception {
|
void extractMetadata_fromCbz_withComicInfo_populatesFields() throws Exception {
|
||||||
String xml = "" +
|
String xml = "<ComicInfo>" +
|
||||||
"<ComicInfo>" +
|
|
||||||
" <Title>My Comic</Title>" +
|
" <Title>My Comic</Title>" +
|
||||||
" <Summary>A short summary</Summary>" +
|
" <Summary>A short summary</Summary>" +
|
||||||
" <Publisher>Indie</Publisher>" +
|
" <Publisher>Indie</Publisher>" +
|
||||||
@@ -88,8 +88,7 @@ class CbxMetadataExtractorTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void extractCover_fromCbz_usesComicInfoImageFile() throws Exception {
|
void extractCover_fromCbz_usesComicInfoImageFile() throws Exception {
|
||||||
String xml = "" +
|
String xml = "<ComicInfo>" +
|
||||||
"<ComicInfo>" +
|
|
||||||
" <Pages>" +
|
" <Pages>" +
|
||||||
" <Page Type=\"FrontCover\" ImageFile=\"images/002.jpg\"/>" +
|
" <Page Type=\"FrontCover\" ImageFile=\"images/002.jpg\"/>" +
|
||||||
" </Pages>" +
|
" </Pages>" +
|
||||||
@@ -130,7 +129,7 @@ class CbxMetadataExtractorTest {
|
|||||||
@Test
|
@Test
|
||||||
void extractMetadata_nonArchive_fallbackTitle() throws Exception {
|
void extractMetadata_nonArchive_fallbackTitle() throws Exception {
|
||||||
Path txt = tempDir.resolve("Some Book Title.txt");
|
Path txt = tempDir.resolve("Some Book Title.txt");
|
||||||
Files.write(txt, "hello".getBytes(StandardCharsets.UTF_8));
|
Files.writeString(txt, "hello");
|
||||||
BookMetadata md = extractor.extractMetadata(txt.toFile());
|
BookMetadata md = extractor.extractMetadata(txt.toFile());
|
||||||
assertEquals("Some Book Title", md.getTitle());
|
assertEquals("Some Book Title", md.getTitle());
|
||||||
}
|
}
|
||||||
|
|||||||
+7
-5
@@ -20,6 +20,7 @@ import java.nio.charset.StandardCharsets;
|
|||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
import java.time.LocalDate;
|
import java.time.LocalDate;
|
||||||
|
import java.util.Comparator;
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import java.util.zip.ZipEntry;
|
import java.util.zip.ZipEntry;
|
||||||
@@ -43,7 +44,7 @@ class CbxMetadataWriterTest {
|
|||||||
void cleanup() throws Exception {
|
void cleanup() throws Exception {
|
||||||
if (tempDir != null) {
|
if (tempDir != null) {
|
||||||
Files.walk(tempDir)
|
Files.walk(tempDir)
|
||||||
.sorted((a, b) -> b.compareTo(a))
|
.sorted(Comparator.reverseOrder())
|
||||||
.forEach(p -> { try { Files.deleteIfExists(p); } catch (Exception ignore) {} });
|
.forEach(p -> { try { Files.deleteIfExists(p); } catch (Exception ignore) {} });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -142,10 +143,11 @@ class CbxMetadataWriterTest {
|
|||||||
void writeMetadataToFile_cbz_updatesExistingComicInfo() throws Exception {
|
void writeMetadataToFile_cbz_updatesExistingComicInfo() throws Exception {
|
||||||
// Create a CBZ *with* an existing ComicInfo.xml
|
// Create a CBZ *with* an existing ComicInfo.xml
|
||||||
Path out = tempDir.resolve("with_meta.cbz");
|
Path out = tempDir.resolve("with_meta.cbz");
|
||||||
String xml = "<ComicInfo>\n" +
|
String xml = """
|
||||||
" <Title>Old Title</Title>\n" +
|
<ComicInfo>
|
||||||
" <Summary>Old Summary</Summary>\n" +
|
<Title>Old Title</Title>
|
||||||
"</ComicInfo>";
|
<Summary>Old Summary</Summary>
|
||||||
|
</ComicInfo>""";
|
||||||
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(out.toFile()))) {
|
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(out.toFile()))) {
|
||||||
put(zos, "ComicInfo.xml", xml.getBytes(StandardCharsets.UTF_8));
|
put(zos, "ComicInfo.xml", xml.getBytes(StandardCharsets.UTF_8));
|
||||||
put(zos, "a.jpg", new byte[]{1});
|
put(zos, "a.jpg", new byte[]{1});
|
||||||
|
|||||||
+1
-1
@@ -57,7 +57,7 @@ class OpdsFeedServiceTest {
|
|||||||
OpdsUserDetails userDetails = mock(OpdsUserDetails.class);
|
OpdsUserDetails userDetails = mock(OpdsUserDetails.class);
|
||||||
when(authenticationService.getOpdsUser()).thenReturn(userDetails);
|
when(authenticationService.getOpdsUser()).thenReturn(userDetails);
|
||||||
|
|
||||||
Library lib = Library.builder().id(1L).name("Test Library").build();
|
Library lib = Library.builder().id(1L).name("Test Library").watch(false).build();
|
||||||
when(opdsBookService.getAccessibleLibraries(userDetails)).thenReturn(List.of(lib));
|
when(opdsBookService.getAccessibleLibraries(userDetails)).thenReturn(List.of(lib));
|
||||||
|
|
||||||
String xml = opdsFeedService.generateLibrariesNavigation(request);
|
String xml = opdsFeedService.generateLibrariesNavigation(request);
|
||||||
|
|||||||
+4
-4
@@ -71,7 +71,7 @@ class TaskCronServiceTest {
|
|||||||
|
|
||||||
List<TaskCronConfigurationEntity> result = service.getAllEnabledCronConfigs();
|
List<TaskCronConfigurationEntity> result = service.getAllEnabledCronConfigs();
|
||||||
assertEquals(1, result.size());
|
assertEquals(1, result.size());
|
||||||
assertEquals(TaskType.CLEAR_CBX_CACHE, result.get(0).getTaskType());
|
assertEquals(TaskType.CLEAR_CBX_CACHE, result.getFirst().getTaskType());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -117,7 +117,7 @@ class TaskCronServiceTest {
|
|||||||
@Test
|
@Test
|
||||||
void testPatchCronConfig_updateExisting() {
|
void testPatchCronConfig_updateExisting() {
|
||||||
TaskType type = TaskType.CLEAR_CBX_CACHE;
|
TaskType type = TaskType.CLEAR_CBX_CACHE;
|
||||||
BookLoreUser user = BookLoreUser.builder().id(10L).build();
|
BookLoreUser user = BookLoreUser.builder().id(10L).isDefaultPassword(false).build();
|
||||||
TaskCronConfigurationEntity entity = buildEntity(type, "0 0 1 * * *", false);
|
TaskCronConfigurationEntity entity = buildEntity(type, "0 0 1 * * *", false);
|
||||||
|
|
||||||
when(authService.getAuthenticatedUser()).thenReturn(user);
|
when(authService.getAuthenticatedUser()).thenReturn(user);
|
||||||
@@ -136,7 +136,7 @@ class TaskCronServiceTest {
|
|||||||
@Test
|
@Test
|
||||||
void testPatchCronConfig_createNew() {
|
void testPatchCronConfig_createNew() {
|
||||||
TaskType type = TaskType.CLEAR_CBX_CACHE;
|
TaskType type = TaskType.CLEAR_CBX_CACHE;
|
||||||
BookLoreUser user = BookLoreUser.builder().id(10L).build();
|
BookLoreUser user = BookLoreUser.builder().id(10L).isDefaultPassword(false).build();
|
||||||
|
|
||||||
when(authService.getAuthenticatedUser()).thenReturn(user);
|
when(authService.getAuthenticatedUser()).thenReturn(user);
|
||||||
when(repository.findByTaskType(type)).thenReturn(Optional.empty());
|
when(repository.findByTaskType(type)).thenReturn(Optional.empty());
|
||||||
@@ -155,7 +155,7 @@ class TaskCronServiceTest {
|
|||||||
@Test
|
@Test
|
||||||
void testPatchCronConfig_invalidCronExpression_throws() {
|
void testPatchCronConfig_invalidCronExpression_throws() {
|
||||||
TaskType type = TaskType.CLEAR_CBX_CACHE;
|
TaskType type = TaskType.CLEAR_CBX_CACHE;
|
||||||
BookLoreUser user = BookLoreUser.builder().id(10L).build();
|
BookLoreUser user = BookLoreUser.builder().id(10L).isDefaultPassword(false).build();
|
||||||
|
|
||||||
when(authService.getAuthenticatedUser()).thenReturn(user);
|
when(authService.getAuthenticatedUser()).thenReturn(user);
|
||||||
when(repository.findByTaskType(type)).thenReturn(Optional.empty());
|
when(repository.findByTaskType(type)).thenReturn(Optional.empty());
|
||||||
|
|||||||
+12
-12
@@ -69,7 +69,7 @@ class TaskServiceTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testRunAsUserThrowsExceptionForNullTaskType() {
|
void testRunAsUserThrowsExceptionForNullTaskType() {
|
||||||
TaskCreateRequest req = TaskCreateRequest.builder().build();
|
TaskCreateRequest req = TaskCreateRequest.builder().triggeredByCron(false).build();
|
||||||
APIException ex = assertThrows(APIException.class, () -> taskService.runAsUser(req));
|
APIException ex = assertThrows(APIException.class, () -> taskService.runAsUser(req));
|
||||||
assertEquals(HttpStatus.BAD_REQUEST, ex.getStatus());
|
assertEquals(HttpStatus.BAD_REQUEST, ex.getStatus());
|
||||||
}
|
}
|
||||||
@@ -94,14 +94,14 @@ class TaskServiceTest {
|
|||||||
user.setUsername("user1");
|
user.setUsername("user1");
|
||||||
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
|
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
|
||||||
when(mockTask.execute(any())).thenReturn(TaskCreateResponse.builder().taskType(TaskType.CLEANUP_TEMP_METADATA).build());
|
when(mockTask.execute(any())).thenReturn(TaskCreateResponse.builder().taskType(TaskType.CLEANUP_TEMP_METADATA).build());
|
||||||
TaskCreateRequest req = TaskCreateRequest.builder().taskType(TaskType.CLEANUP_TEMP_METADATA).build();
|
TaskCreateRequest req = TaskCreateRequest.builder().taskType(TaskType.CLEANUP_TEMP_METADATA).triggeredByCron(false).build();
|
||||||
TaskCreateResponse resp = taskService.runAsUser(req);
|
TaskCreateResponse resp = taskService.runAsUser(req);
|
||||||
assertEquals(TaskType.CLEANUP_TEMP_METADATA, resp.getTaskType());
|
assertEquals(TaskType.CLEANUP_TEMP_METADATA, resp.getTaskType());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testExecuteTaskThrowsForUnknownTaskType() {
|
void testExecuteTaskThrowsForUnknownTaskType() {
|
||||||
TaskCreateRequest req = TaskCreateRequest.builder().taskType(TaskType.CLEAR_CBX_CACHE).build();
|
TaskCreateRequest req = TaskCreateRequest.builder().taskType(TaskType.CLEAR_CBX_CACHE).triggeredByCron(false).build();
|
||||||
BookLoreUser user = new BookLoreUser();
|
BookLoreUser user = new BookLoreUser();
|
||||||
user.setId(1L);
|
user.setId(1L);
|
||||||
user.setUsername("user1");
|
user.setUsername("user1");
|
||||||
@@ -119,8 +119,8 @@ class TaskServiceTest {
|
|||||||
user.setUsername("parallelUser");
|
user.setUsername("parallelUser");
|
||||||
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
|
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
|
||||||
|
|
||||||
TaskCreateRequest req1 = TaskCreateRequest.builder().taskType(parallelType).build();
|
TaskCreateRequest req1 = TaskCreateRequest.builder().taskType(parallelType).triggeredByCron(false).build();
|
||||||
TaskCreateRequest req2 = TaskCreateRequest.builder().taskType(parallelType).build();
|
TaskCreateRequest req2 = TaskCreateRequest.builder().taskType(parallelType).triggeredByCron(false).build();
|
||||||
|
|
||||||
TaskCreateResponse resp1 = taskService.runAsUser(req1);
|
TaskCreateResponse resp1 = taskService.runAsUser(req1);
|
||||||
TaskCreateResponse resp2 = taskService.runAsUser(req2);
|
TaskCreateResponse resp2 = taskService.runAsUser(req2);
|
||||||
@@ -152,7 +152,7 @@ class TaskServiceTest {
|
|||||||
user.setUsername("nonParallelUser");
|
user.setUsername("nonParallelUser");
|
||||||
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
|
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
|
||||||
|
|
||||||
TaskCreateRequest req = TaskCreateRequest.builder().taskType(nonParallelType).build();
|
TaskCreateRequest req = TaskCreateRequest.builder().taskType(nonParallelType).triggeredByCron(false).build();
|
||||||
taskService.runAsUser(req);
|
taskService.runAsUser(req);
|
||||||
|
|
||||||
APIException ex = assertThrows(APIException.class, () -> taskService.runAsUser(req));
|
APIException ex = assertThrows(APIException.class, () -> taskService.runAsUser(req));
|
||||||
@@ -193,7 +193,7 @@ class TaskServiceTest {
|
|||||||
user.setUsername("asyncUser");
|
user.setUsername("asyncUser");
|
||||||
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
|
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
|
||||||
|
|
||||||
TaskCreateRequest req = TaskCreateRequest.builder().taskType(asyncType).build();
|
TaskCreateRequest req = TaskCreateRequest.builder().taskType(asyncType).triggeredByCron(false).build();
|
||||||
TaskCreateResponse resp = taskService.runAsUser(req);
|
TaskCreateResponse resp = taskService.runAsUser(req);
|
||||||
|
|
||||||
assertEquals(asyncType, resp.getTaskType());
|
assertEquals(asyncType, resp.getTaskType());
|
||||||
@@ -210,7 +210,7 @@ class TaskServiceTest {
|
|||||||
user.setUsername("nullOptionsUser");
|
user.setUsername("nullOptionsUser");
|
||||||
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
|
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
|
||||||
|
|
||||||
TaskCreateRequest req = TaskCreateRequest.builder().taskType(type).options(null).build();
|
TaskCreateRequest req = TaskCreateRequest.builder().taskType(type).options(null).triggeredByCron(false).build();
|
||||||
TaskCreateResponse resp = taskService.runAsUser(req);
|
TaskCreateResponse resp = taskService.runAsUser(req);
|
||||||
assertEquals(type, resp.getTaskType());
|
assertEquals(type, resp.getTaskType());
|
||||||
}
|
}
|
||||||
@@ -225,20 +225,20 @@ class TaskServiceTest {
|
|||||||
user.setUsername("exceptionUser");
|
user.setUsername("exceptionUser");
|
||||||
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
|
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
|
||||||
|
|
||||||
TaskCreateRequest req = TaskCreateRequest.builder().taskType(type).build();
|
TaskCreateRequest req = TaskCreateRequest.builder().taskType(type).triggeredByCron(false).build();
|
||||||
assertThrows(RuntimeException.class, () -> taskService.runAsUser(req));
|
assertThrows(RuntimeException.class, () -> taskService.runAsUser(req));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testRunAsUserThrowsExceptionForNullUser() {
|
void testRunAsUserThrowsExceptionForNullUser() {
|
||||||
when(authenticationService.getAuthenticatedUser()).thenReturn(null);
|
when(authenticationService.getAuthenticatedUser()).thenReturn(null);
|
||||||
TaskCreateRequest req = TaskCreateRequest.builder().taskType(TaskType.CLEANUP_TEMP_METADATA).build();
|
TaskCreateRequest req = TaskCreateRequest.builder().taskType(TaskType.CLEANUP_TEMP_METADATA).triggeredByCron(false).build();
|
||||||
assertThrows(NullPointerException.class, () -> taskService.runAsUser(req));
|
assertThrows(NullPointerException.class, () -> taskService.runAsUser(req));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testExecuteTaskThrowsForMissingTaskInRegistry() {
|
void testExecuteTaskThrowsForMissingTaskInRegistry() {
|
||||||
TaskCreateRequest req = TaskCreateRequest.builder().taskType(TaskType.CLEANUP_DELETED_BOOKS).build();
|
TaskCreateRequest req = TaskCreateRequest.builder().taskType(TaskType.CLEANUP_DELETED_BOOKS).triggeredByCron(false).build();
|
||||||
BookLoreUser user = new BookLoreUser();
|
BookLoreUser user = new BookLoreUser();
|
||||||
user.setId(8L);
|
user.setId(8L);
|
||||||
user.setUsername("missingTaskUser");
|
user.setUsername("missingTaskUser");
|
||||||
@@ -253,7 +253,7 @@ class TaskServiceTest {
|
|||||||
user.setUsername("invalidOptionsUser");
|
user.setUsername("invalidOptionsUser");
|
||||||
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
|
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
|
||||||
when(objectMapper.convertValue(any(), eq(Map.class))).thenThrow(new IllegalArgumentException("Conversion failed"));
|
when(objectMapper.convertValue(any(), eq(Map.class))).thenThrow(new IllegalArgumentException("Conversion failed"));
|
||||||
TaskCreateRequest req = TaskCreateRequest.builder().taskType(TaskType.CLEANUP_TEMP_METADATA).options(new Object()).build();
|
TaskCreateRequest req = TaskCreateRequest.builder().taskType(TaskType.CLEANUP_TEMP_METADATA).options(new Object()).triggeredByCron(false).build();
|
||||||
when(mockTask.execute(any())).thenReturn(TaskCreateResponse.builder().taskType(TaskType.CLEANUP_TEMP_METADATA).build());
|
when(mockTask.execute(any())).thenReturn(TaskCreateResponse.builder().taskType(TaskType.CLEANUP_TEMP_METADATA).build());
|
||||||
TaskCreateResponse resp = taskService.runAsUser(req);
|
TaskCreateResponse resp = taskService.runAsUser(req);
|
||||||
assertEquals(TaskType.CLEANUP_TEMP_METADATA, resp.getTaskType());
|
assertEquals(TaskType.CLEANUP_TEMP_METADATA, resp.getTaskType());
|
||||||
|
|||||||
+3
-3
@@ -183,7 +183,7 @@ public class LibraryTestBuilder {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public LibraryTestBuilder addBook(String fileSubPath, String fileName) {
|
public LibraryTestBuilder addBook(String fileSubPath, String fileName) {
|
||||||
fileSubPath = removeLeadingSlash(fileSubPath);
|
String subPath = removeLeadingSlash(fileSubPath);
|
||||||
|
|
||||||
long id = bookRepository.size() + 1L;
|
long id = bookRepository.size() + 1L;
|
||||||
BookMetadataEntity metadata = BookMetadataEntity.builder()
|
BookMetadataEntity metadata = BookMetadataEntity.builder()
|
||||||
@@ -191,11 +191,11 @@ public class LibraryTestBuilder {
|
|||||||
.bookId(id)
|
.bookId(id)
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
String hash = computeFileHash(Path.of(fileSubPath, fileName));
|
String hash = computeFileHash(Path.of(subPath, fileName));
|
||||||
BookEntity bookEntity = BookEntity.builder()
|
BookEntity bookEntity = BookEntity.builder()
|
||||||
.id(id)
|
.id(id)
|
||||||
.fileName(fileName)
|
.fileName(fileName)
|
||||||
.fileSubPath(fileSubPath)
|
.fileSubPath(subPath)
|
||||||
.bookType(getBookFileType(fileName))
|
.bookType(getBookFileType(fileName))
|
||||||
.fileSizeKb(1024L)
|
.fileSizeKb(1024L)
|
||||||
.library(getLibraryEntity())
|
.library(getLibraryEntity())
|
||||||
|
|||||||
Reference in New Issue
Block a user