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;
|
||||
@Getter
|
||||
public final long accessTokenExpirationMs = 1000L * 60 * 60 * 10; // 10 hours
|
||||
public static final long accessTokenExpirationMs = 1000L * 60 * 60 * 10; // 10 hours
|
||||
@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() {
|
||||
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.core.annotation.Order;
|
||||
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.method.configuration.EnableMethodSecurity;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
@@ -154,17 +152,10 @@ public class SecurityConfig {
|
||||
|
||||
@Bean
|
||||
public AuthenticationManager authenticationManager(HttpSecurity http) throws Exception {
|
||||
return http.getSharedObject(AuthenticationManagerBuilder.class)
|
||||
.authenticationProvider(authenticationProvider())
|
||||
.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public AuthenticationProvider authenticationProvider() {
|
||||
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
|
||||
provider.setUserDetailsService(opdsUserDetailsService);
|
||||
provider.setPasswordEncoder(passwordEncoder());
|
||||
return provider;
|
||||
// Configure the shared AuthenticationManagerBuilder with the UserDetailsService and PasswordEncoder
|
||||
AuthenticationManagerBuilder auth = http.getSharedObject(AuthenticationManagerBuilder.class);
|
||||
auth.userDetailsService(opdsUserDetailsService).passwordEncoder(passwordEncoder());
|
||||
return auth.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
|
||||
+1
-1
@@ -109,7 +109,7 @@ public class AuthenticationService {
|
||||
|
||||
Optional<BookLoreUserEntity> user = userRepository.findByUsername(username);
|
||||
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()) {
|
||||
|
||||
+4
-1
@@ -22,6 +22,7 @@ import org.springframework.web.bind.annotation.RestController;
|
||||
import java.io.IOException;
|
||||
import java.net.URLEncoder;
|
||||
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")
|
||||
@AllArgsConstructor
|
||||
@@ -29,6 +30,8 @@ import java.nio.charset.StandardCharsets;
|
||||
@RequestMapping("/api/v1/media")
|
||||
public class BookMediaController {
|
||||
|
||||
private static final Pattern NON_ASCII_PATTERN = Pattern.compile("[^\\x00-\\x7F]");
|
||||
|
||||
private final BookService bookService;
|
||||
private final PdfReaderService pdfReaderService;
|
||||
private final CbxReaderService cbxReaderService;
|
||||
@@ -103,7 +106,7 @@ public class BookMediaController {
|
||||
: MediaType.IMAGE_JPEG;
|
||||
|
||||
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",
|
||||
fallbackFilename, encodedFilename);
|
||||
return ResponseEntity.ok()
|
||||
|
||||
+2
@@ -72,6 +72,8 @@ public class MetadataController {
|
||||
.updateThumbnail(true)
|
||||
.mergeCategories(mergeCategories)
|
||||
.replaceMode(MetadataReplaceMode.REPLACE_ALL)
|
||||
.mergeMoods(true)
|
||||
.mergeTags(true)
|
||||
.build();
|
||||
|
||||
bookMetadataUpdater.setBookMetadata(context);
|
||||
|
||||
+3
-3
@@ -10,12 +10,12 @@ import java.util.Map;
|
||||
|
||||
@Converter
|
||||
@Slf4j
|
||||
public class JpaJsonConverter implements AttributeConverter<Map<String, Object>, String> {
|
||||
public class JpaJsonConverter implements AttributeConverter<Map, String> {
|
||||
|
||||
private static final ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
@Override
|
||||
public String convertToDatabaseColumn(Map<String, Object> attribute) {
|
||||
public String convertToDatabaseColumn(Map attribute) {
|
||||
if (attribute == null) {
|
||||
return null;
|
||||
}
|
||||
@@ -28,7 +28,7 @@ public class JpaJsonConverter implements AttributeConverter<Map<String, Object>,
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Object> convertToEntityAttribute(String dbData) {
|
||||
public Map convertToEntityAttribute(String dbData) {
|
||||
if (dbData == null || dbData.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
+3
-3
@@ -8,12 +8,12 @@ import java.io.IOException;
|
||||
import java.util.Map;
|
||||
|
||||
@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();
|
||||
|
||||
@Override
|
||||
public String convertToDatabaseColumn(Map<String, String> attribute) {
|
||||
public String convertToDatabaseColumn(Map attribute) {
|
||||
try {
|
||||
return objectMapper.writeValueAsString(attribute);
|
||||
} catch (IOException e) {
|
||||
@@ -22,7 +22,7 @@ public class MapToStringConverter implements AttributeConverter<Map<String, Stri
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, String> convertToEntityAttribute(String dbData) {
|
||||
public Map convertToEntityAttribute(String dbData) {
|
||||
try {
|
||||
return objectMapper.readValue(dbData, Map.class);
|
||||
} catch (IOException e) {
|
||||
|
||||
+2
-2
@@ -13,7 +13,7 @@ import java.util.regex.Pattern;
|
||||
public interface KoboReadingStateMapper {
|
||||
|
||||
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 = "statisticsJson", expression = "java(toJson(dto.getStatistics()))")
|
||||
@@ -51,6 +51,6 @@ public interface KoboReadingStateMapper {
|
||||
|
||||
default String cleanString(String value) {
|
||||
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
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (!(o instanceof BookMetadataCategoryKey)) return false;
|
||||
BookMetadataCategoryKey that = (BookMetadataCategoryKey) o;
|
||||
if (!(o instanceof BookMetadataCategoryKey that)) return false;
|
||||
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.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@Slf4j
|
||||
@AllArgsConstructor
|
||||
@Service
|
||||
public class BookDownloadService {
|
||||
|
||||
private static final Pattern NON_ASCII_PATTERN = Pattern.compile("[^\\x00-\\x7F]");
|
||||
|
||||
private final BookRepository bookRepository;
|
||||
private final KepubConversionService kepubConversionService;
|
||||
private final AppSettingService appSettingService;
|
||||
@@ -55,7 +58,7 @@ public class BookDownloadService {
|
||||
|
||||
String encodedFilename = URLEncoder.encode(file.getFileName().toString(), StandardCharsets.UTF_8)
|
||||
.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",
|
||||
fallbackFilename, encodedFilename);
|
||||
return ResponseEntity.ok()
|
||||
@@ -114,7 +117,7 @@ public class BookDownloadService {
|
||||
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
|
||||
response.setContentLengthLong(file.length());
|
||||
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",
|
||||
fallbackFilename, encodedFilename);
|
||||
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 {
|
||||
Path dir = currentDir;
|
||||
Set<String> ignoredFilenames = Set.of(".DS_Store", "Thumbs.db");
|
||||
currentDir = currentDir.toAbsolutePath().normalize();
|
||||
dir = dir.toAbsolutePath().normalize();
|
||||
|
||||
Set<Path> normalizedRoots = new HashSet<>();
|
||||
for (Path root : libraryRoots) {
|
||||
normalizedRoots.add(root.toAbsolutePath().normalize());
|
||||
}
|
||||
|
||||
while (currentDir != null) {
|
||||
while (dir != null) {
|
||||
boolean isLibraryRoot = false;
|
||||
for (Path root : normalizedRoots) {
|
||||
try {
|
||||
if (Files.isSameFile(root, currentDir)) {
|
||||
if (Files.isSameFile(root, dir)) {
|
||||
isLibraryRoot = true;
|
||||
break;
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.warn("Failed to compare paths: {} and {}", root, currentDir);
|
||||
log.warn("Failed to compare paths: {} and {}", root, dir);
|
||||
}
|
||||
}
|
||||
|
||||
if (isLibraryRoot) {
|
||||
log.debug("Reached library root: {}. Stopping cleanup.", currentDir);
|
||||
log.debug("Reached library root: {}. Stopping cleanup.", dir);
|
||||
break;
|
||||
}
|
||||
|
||||
File[] files = currentDir.toFile().listFiles();
|
||||
File[] files = dir.toFile().listFiles();
|
||||
if (files == null) {
|
||||
log.warn("Cannot read directory: {}. Stopping cleanup.", currentDir);
|
||||
log.warn("Cannot read directory: {}. Stopping cleanup.", dir);
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -637,15 +638,15 @@ public class BookService {
|
||||
}
|
||||
}
|
||||
try {
|
||||
Files.delete(currentDir);
|
||||
log.info("Deleted empty directory: {}", currentDir);
|
||||
Files.delete(dir);
|
||||
log.info("Deleted empty directory: {}", dir);
|
||||
} catch (IOException e) {
|
||||
log.warn("Failed to delete directory: {}", currentDir, e);
|
||||
log.warn("Failed to delete directory: {}", dir, e);
|
||||
break;
|
||||
}
|
||||
currentDir = currentDir.getParent();
|
||||
dir = dir.getParent();
|
||||
} else {
|
||||
log.debug("Directory {} contains important files. Stopping cleanup.", currentDir);
|
||||
log.debug("Directory {} contains important files. Stopping cleanup.", dir);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
+3
@@ -144,6 +144,9 @@ public class BookDropService {
|
||||
private BookdropFinalizeResult processFinalizationRequest(BookdropFinalizeRequest request) {
|
||||
BookdropFinalizeResult results = BookdropFinalizeResult.builder()
|
||||
.processedAt(Instant.now())
|
||||
.totalFiles(0)
|
||||
.successfullyImported(0)
|
||||
.failed(0)
|
||||
.build();
|
||||
|
||||
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.EmailProviderV2Entity;
|
||||
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.Topic;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
@@ -179,7 +180,7 @@ public class SendEmailV2Service {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
|
||||
Long defaultProviderId = preferenceRepository.findByUserId(user.getId())
|
||||
.map(pref -> pref.getDefaultProviderId())
|
||||
.map(UserEmailProviderPreferenceEntity::getDefaultProviderId)
|
||||
.orElseThrow(ApiError.DEFAULT_EMAIL_PROVIDER_NOT_FOUND::createException);
|
||||
|
||||
return emailProviderRepository.findAccessibleProvider(defaultProviderId, user.getId())
|
||||
|
||||
+4
-1
@@ -23,12 +23,15 @@ import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@Slf4j
|
||||
@AllArgsConstructor
|
||||
@Service
|
||||
public class AdditionalFileService {
|
||||
|
||||
private static final Pattern NON_ASCII = Pattern.compile("[^\\x00-\\x7F]");
|
||||
|
||||
private final BookAdditionalFileRepository additionalFileRepository;
|
||||
private final AdditionalFileMapper additionalFileMapper;
|
||||
private final MonitoringRegistrationService monitoringRegistrationService;
|
||||
@@ -81,7 +84,7 @@ public class AdditionalFileService {
|
||||
Resource resource = new UrlResource(filePath.toUri());
|
||||
|
||||
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",
|
||||
fallbackFilename, encodedFilename);
|
||||
return ResponseEntity.ok()
|
||||
|
||||
+8
-7
@@ -80,24 +80,25 @@ public class FileMoveHelper {
|
||||
}
|
||||
|
||||
public void deleteEmptyParentDirsUpToLibraryFolders(Path currentDir, Set<Path> libraryRoots) throws IOException {
|
||||
Path dir = currentDir;
|
||||
Set<String> ignoredFilenames = Set.of(".DS_Store", "Thumbs.db");
|
||||
currentDir = currentDir.toAbsolutePath().normalize();
|
||||
dir = dir.toAbsolutePath().normalize();
|
||||
Set<Path> normalizedRoots = new HashSet<>();
|
||||
for (Path root : libraryRoots) {
|
||||
normalizedRoots.add(root.toAbsolutePath().normalize());
|
||||
}
|
||||
while (currentDir != null) {
|
||||
if (isLibraryRoot(currentDir, normalizedRoots)) {
|
||||
while (dir != null) {
|
||||
if (isLibraryRoot(dir, normalizedRoots)) {
|
||||
break;
|
||||
}
|
||||
File[] files = currentDir.toFile().listFiles();
|
||||
File[] files = dir.toFile().listFiles();
|
||||
if (files == null) {
|
||||
log.warn("Cannot read directory: {}. Stopping cleanup.", currentDir);
|
||||
log.warn("Cannot read directory: {}. Stopping cleanup.", dir);
|
||||
break;
|
||||
}
|
||||
if (hasOnlyIgnoredFiles(files, ignoredFilenames)) {
|
||||
deleteIgnoredFilesAndDirectory(files, currentDir);
|
||||
currentDir = currentDir.getParent();
|
||||
deleteIgnoredFilesAndDirectory(files, dir);
|
||||
dir = dir.getParent();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
|
||||
+2
-6
@@ -101,15 +101,11 @@ public class FileMoveService {
|
||||
|
||||
for (Long libraryId : targetLibraryIds) {
|
||||
Optional<LibraryEntity> optionalLibrary = libraryRepository.findById(libraryId);
|
||||
optionalLibrary.ifPresent(library -> {
|
||||
monitoringRegistrationService.registerLibrary(libraryMapper.toLibrary(library));
|
||||
});
|
||||
optionalLibrary.ifPresent(library -> monitoringRegistrationService.registerLibrary(libraryMapper.toLibrary(library)));
|
||||
}
|
||||
for (Long libraryId : sourceLibraryIds) {
|
||||
Optional<LibraryEntity> optionalLibrary = libraryRepository.findById(libraryId);
|
||||
optionalLibrary.ifPresent(library -> {
|
||||
monitoringRegistrationService.registerLibrary(libraryMapper.toLibrary(library));
|
||||
});
|
||||
optionalLibrary.ifPresent(library -> monitoringRegistrationService.registerLibrary(libraryMapper.toLibrary(library)));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -121,7 +121,7 @@ public class EpubProcessor extends AbstractFileProcessor implements BookFileProc
|
||||
metadata.setPageCount(epubMetadata.getPageCount());
|
||||
|
||||
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.setPersonalRating(epubMetadata.getPersonalRating());
|
||||
|
||||
+1
-2
@@ -47,13 +47,12 @@ public class KoboLibrarySyncService {
|
||||
|
||||
if (prevSnapshot.isPresent()) {
|
||||
int maxRemaining = 5;
|
||||
List<KoboSnapshotBookEntity> addedAll = new ArrayList<>();
|
||||
List<KoboSnapshotBookEntity> removedAll = new ArrayList<>();
|
||||
|
||||
koboLibrarySnapshotService.updateSyncedStatusForExistingBooks(prevSnapshot.get().getId(), currSnapshot.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();
|
||||
shouldContinueSync = addedPage.hasNext();
|
||||
|
||||
|
||||
+2
@@ -90,6 +90,8 @@ public class LibraryRescanHelper {
|
||||
.replaceMode(context.getOptions().getMetadataReplaceMode())
|
||||
.updateThumbnail(false)
|
||||
.mergeCategories(false)
|
||||
.mergeMoods(true)
|
||||
.mergeTags(true)
|
||||
.build();
|
||||
bookMetadataUpdater.setBookMetadata(metadataUpdateContext);
|
||||
} catch (Exception e) {
|
||||
|
||||
+3
-3
@@ -266,7 +266,7 @@ public class MetadataManagementService {
|
||||
if (targetValues.size() != 1) {
|
||||
throw new IllegalArgumentException("Series merge requires exactly one target value");
|
||||
}
|
||||
String targetSeriesName = targetValues.get(0);
|
||||
String targetSeriesName = targetValues.getFirst();
|
||||
|
||||
for (String oldSeriesName : valuesToMerge) {
|
||||
List<BookMetadataEntity> booksWithOldSeries = bookMetadataRepository.findAllBySeriesNameIgnoreCase(oldSeriesName);
|
||||
@@ -289,7 +289,7 @@ public class MetadataManagementService {
|
||||
if (targetValues.size() != 1) {
|
||||
throw new IllegalArgumentException("Publisher merge requires exactly one target value");
|
||||
}
|
||||
String targetPublisher = targetValues.get(0);
|
||||
String targetPublisher = targetValues.getFirst();
|
||||
|
||||
for (String oldPublisher : valuesToMerge) {
|
||||
List<BookMetadataEntity> booksWithOldPublisher = bookMetadataRepository.findAllByPublisherIgnoreCase(oldPublisher);
|
||||
@@ -312,7 +312,7 @@ public class MetadataManagementService {
|
||||
if (targetValues.size() != 1) {
|
||||
throw new IllegalArgumentException("Language merge requires exactly one target value");
|
||||
}
|
||||
String targetLanguage = targetValues.get(0);
|
||||
String targetLanguage = targetValues.getFirst();
|
||||
|
||||
for (String oldLanguage : valuesToMerge) {
|
||||
List<BookMetadataEntity> booksWithOldLanguage = bookMetadataRepository.findAllByLanguageIgnoreCase(oldLanguage);
|
||||
|
||||
+8
-5
@@ -283,6 +283,8 @@ public class MetadataRefreshService {
|
||||
.updateThumbnail(replaceCover)
|
||||
.mergeCategories(mergeCategories)
|
||||
.replaceMode(MetadataReplaceMode.REPLACE_MISSING)
|
||||
.mergeMoods(true)
|
||||
.mergeTags(true)
|
||||
.build();
|
||||
|
||||
bookMetadataUpdater.setBookMetadata(context);
|
||||
@@ -293,13 +295,14 @@ public class MetadataRefreshService {
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
protected Set<MetadataProvider> getAllProvidersUsingIndividualFields(MetadataRefreshOptions refreshOptions) {
|
||||
MetadataRefreshOptions.FieldOptions fieldOptions = refreshOptions.getFieldOptions();
|
||||
Set<MetadataProvider> uniqueProviders = new HashSet<>();
|
||||
Set<MetadataProvider> uniqueProviders = EnumSet.noneOf(MetadataProvider.class);
|
||||
|
||||
if (fieldOptions != null) {
|
||||
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) {
|
||||
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) {
|
||||
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) {
|
||||
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) {
|
||||
|
||||
+78
-80
@@ -92,27 +92,27 @@ public class CbxMetadataExtractor implements FileMetadataExtractor {
|
||||
}
|
||||
|
||||
// CBR path (RAR)
|
||||
Archive archive = null;
|
||||
try {
|
||||
archive = new Archive(file);
|
||||
FileHeader header = findComicInfoHeader(archive);
|
||||
if (header == null) {
|
||||
try (Archive archive = new Archive(file)) {
|
||||
try {
|
||||
FileHeader header = findComicInfoHeader(archive);
|
||||
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();
|
||||
}
|
||||
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) {
|
||||
@@ -374,61 +374,60 @@ public class CbxMetadataExtractor implements FileMetadataExtractor {
|
||||
}
|
||||
|
||||
// CBR path
|
||||
Archive archive = null;
|
||||
try {
|
||||
archive = new Archive(file);
|
||||
try (Archive archive = new Archive(file)) {
|
||||
try {
|
||||
|
||||
// Try via ComicInfo.xml first
|
||||
FileHeader comicInfo = findComicInfoHeader(archive);
|
||||
if (comicInfo != null) {
|
||||
byte[] xmlBytes = readRarEntryBytes(archive, comicInfo);
|
||||
if (xmlBytes != null) {
|
||||
try (InputStream is = new ByteArrayInputStream(xmlBytes)) {
|
||||
Document document = buildSecureDocument(is);
|
||||
String imageName = findFrontCoverImageName(document);
|
||||
if (imageName != null) {
|
||||
FileHeader byName = findRarHeaderByName(archive, imageName);
|
||||
if (byName != null) {
|
||||
byte[] bytes = readRarEntryBytes(archive, byName);
|
||||
if (canDecode(bytes)) return bytes;
|
||||
}
|
||||
try {
|
||||
int index = Integer.parseInt(imageName);
|
||||
FileHeader byIndex = findRarImageHeaderByIndex(archive, index);
|
||||
if (byIndex != null) {
|
||||
byte[] bytes = readRarEntryBytes(archive, byIndex);
|
||||
if (canDecode(bytes)) return bytes;
|
||||
}
|
||||
if (index > 0) {
|
||||
FileHeader offByOne = findRarImageHeaderByIndex(archive, index - 1);
|
||||
if (offByOne != null) {
|
||||
byte[] bytes = readRarEntryBytes(archive, offByOne);
|
||||
if (canDecode(bytes)) return bytes;
|
||||
// Try via ComicInfo.xml first
|
||||
FileHeader comicInfo = findComicInfoHeader(archive);
|
||||
if (comicInfo != null) {
|
||||
byte[] xmlBytes = readRarEntryBytes(archive, comicInfo);
|
||||
if (xmlBytes != null) {
|
||||
try (InputStream is = new ByteArrayInputStream(xmlBytes)) {
|
||||
Document document = buildSecureDocument(is);
|
||||
String imageName = findFrontCoverImageName(document);
|
||||
if (imageName != null) {
|
||||
FileHeader byName = findRarHeaderByName(archive, imageName);
|
||||
if (byName != null) {
|
||||
byte[] bytes = readRarEntryBytes(archive, byName);
|
||||
if (canDecode(bytes)) return bytes;
|
||||
}
|
||||
try {
|
||||
int index = Integer.parseInt(imageName);
|
||||
FileHeader byIndex = findRarImageHeaderByIndex(archive, index);
|
||||
if (byIndex != null) {
|
||||
byte[] bytes = readRarEntryBytes(archive, byIndex);
|
||||
if (canDecode(bytes)) return bytes;
|
||||
}
|
||||
if (index > 0) {
|
||||
FileHeader offByOne = findRarImageHeaderByIndex(archive, index - 1);
|
||||
if (offByOne != null) {
|
||||
byte[] bytes = readRarEntryBytes(archive, offByOne);
|
||||
if (canDecode(bytes)) return bytes;
|
||||
}
|
||||
}
|
||||
} catch (NumberFormatException ignore) {
|
||||
// ignore and continue fallback
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (NumberFormatException ignore) {
|
||||
// ignore and continue fallback
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: iterate images alphabetically until a decodable one is found
|
||||
FileHeader firstImage = findFirstAlphabeticalImageHeader(archive);
|
||||
if (firstImage != null) {
|
||||
java.util.List<FileHeader> images = listRarImageHeaders(archive);
|
||||
for (FileHeader fh : images) {
|
||||
byte[] bytes = readRarEntryBytes(archive, fh);
|
||||
if (canDecode(bytes)) return bytes;
|
||||
}
|
||||
// Fallback: iterate images alphabetically until a decodable one is found
|
||||
FileHeader firstImage = findFirstAlphabeticalImageHeader(archive);
|
||||
if (firstImage != null) {
|
||||
List<FileHeader> images = listRarImageHeaders(archive);
|
||||
for (FileHeader fh : images) {
|
||||
byte[] bytes = readRarEntryBytes(archive, fh);
|
||||
if (canDecode(bytes)) return bytes;
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to extract cover image from CBR", e);
|
||||
return generatePlaceholderCover(250, 350);
|
||||
}
|
||||
} catch (Exception ignore) {
|
||||
}
|
||||
} 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);
|
||||
}
|
||||
@@ -508,10 +507,9 @@ public class CbxMetadataExtractor implements FileMetadataExtractor {
|
||||
NodeList pages = document.getElementsByTagName("Page");
|
||||
for (int i = 0; i < pages.getLength(); i++) {
|
||||
org.w3c.dom.Node node = pages.item(i);
|
||||
if (node instanceof org.w3c.dom.Element) {
|
||||
org.w3c.dom.Element page = (org.w3c.dom.Element) node;
|
||||
String type = page.getAttribute("Type");
|
||||
if (type != null && type.equalsIgnoreCase("FrontCover")) {
|
||||
if (node instanceof org.w3c.dom.Element page) {
|
||||
String type = page.getAttribute("Type");
|
||||
if (type != null && "FrontCover".equalsIgnoreCase(type)) {
|
||||
String imageFile = page.getAttribute("ImageFile");
|
||||
if (imageFile != null && !imageFile.isBlank()) {
|
||||
return imageFile.trim();
|
||||
@@ -545,7 +543,7 @@ public class CbxMetadataExtractor implements FileMetadataExtractor {
|
||||
if (norm.startsWith("__MACOSX/") || norm.contains("/__MACOSX/")) return false;
|
||||
String base = baseName(norm);
|
||||
if (base.startsWith(".")) return false;
|
||||
if (base.equalsIgnoreCase(".ds_store")) return false;
|
||||
if (".ds_store".equalsIgnoreCase(base)) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -656,7 +654,7 @@ public class CbxMetadataExtractor implements FileMetadataExtractor {
|
||||
}
|
||||
if (images.isEmpty()) return null;
|
||||
images.sort((a, b) -> naturalCompare(a.getFileName(), b.getFileName()));
|
||||
return images.get(0);
|
||||
return images.getFirst();
|
||||
}
|
||||
|
||||
private ZipEntry findFirstAlphabeticalImageEntry(ZipFile zipFile) {
|
||||
@@ -670,7 +668,7 @@ public class CbxMetadataExtractor implements FileMetadataExtractor {
|
||||
}
|
||||
if (images.isEmpty()) return null;
|
||||
images.sort((a, b) -> naturalCompare(a.getName(), b.getName()));
|
||||
return images.get(0);
|
||||
return images.getFirst();
|
||||
}
|
||||
|
||||
// ==== 7z (.cb7) helpers ====
|
||||
@@ -678,7 +676,7 @@ public class CbxMetadataExtractor implements FileMetadataExtractor {
|
||||
for (SevenZArchiveEntry e : sevenZ.getEntries()) {
|
||||
if (e == null || e.isDirectory()) continue;
|
||||
String name = e.getName();
|
||||
if (name != null && name.equalsIgnoreCase("ComicInfo.xml")) {
|
||||
if (name != null && "ComicInfo.xml".equalsIgnoreCase(name)) {
|
||||
return e;
|
||||
}
|
||||
}
|
||||
@@ -718,7 +716,7 @@ public class CbxMetadataExtractor implements FileMetadataExtractor {
|
||||
}
|
||||
if (images.isEmpty()) return null;
|
||||
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 {
|
||||
@@ -766,7 +764,7 @@ public class CbxMetadataExtractor implements FileMetadataExtractor {
|
||||
private boolean likelyCoverName(String base) {
|
||||
if (base == null) return false;
|
||||
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) {
|
||||
|
||||
+4
-4
@@ -132,12 +132,12 @@ public class EpubMetadataExtractor implements FileMetadataExtractor {
|
||||
String content = el.hasAttribute("content") ? el.getAttribute("content").trim() : text;
|
||||
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);
|
||||
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 {
|
||||
builderMeta.seriesNumber(Float.parseFloat(content));
|
||||
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);
|
||||
}
|
||||
|
||||
if (name.equals("calibre:rating") || prop.equals("booklore:personal_rating")) {
|
||||
if ("calibre:rating".equals(name) || "booklore:personal_rating".equals(prop)) {
|
||||
safeParseDouble(content, builderMeta::personalRating);
|
||||
}
|
||||
|
||||
|
||||
+11
-9
@@ -40,7 +40,9 @@ public class AmazonBookParser implements BookParser {
|
||||
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 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(
|
||||
Map.entry("com", new LocaleInfo("en-US,en;q=0.9", Locale.US)),
|
||||
Map.entry("co.uk", new LocaleInfo("en-GB,en;q=0.9", Locale.UK)),
|
||||
@@ -58,13 +60,13 @@ public class AmazonBookParser implements BookParser {
|
||||
Map.entry("se", new LocaleInfo("en-GB,en;q=0.9,sv;q=0.8", new Locale.Builder().setLanguage("sv").setRegion("SE").build())),
|
||||
Map.entry("pl", new LocaleInfo("en-GB,en;q=0.9,pl;q=0.8", new Locale.Builder().setLanguage("pl").setRegion("PL").build()))
|
||||
);
|
||||
|
||||
|
||||
private final AppSettingService appSettingService;
|
||||
|
||||
|
||||
private static class LocaleInfo {
|
||||
final String acceptLanguage;
|
||||
final Locale locale;
|
||||
|
||||
|
||||
LocaleInfo(String acceptLanguage, Locale locale) {
|
||||
this.acceptLanguage = acceptLanguage;
|
||||
this.locale = locale;
|
||||
@@ -510,6 +512,7 @@ public class AmazonBookParser implements BookParser {
|
||||
|
||||
private List<BookReview> getReviews(Document doc, int maxReviews) {
|
||||
List<BookReview> reviews = new ArrayList<>();
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
|
||||
String domain = appSettingService.getAppSettings().getMetadataProviderSettings().getAmazon().getDomain();
|
||||
LocaleInfo localeInfo = getLocaleInfoForDomain(domain);
|
||||
|
||||
@@ -556,8 +559,7 @@ public class AmazonBookParser implements BookParser {
|
||||
|
||||
if (!fullDateText.isEmpty()) {
|
||||
try {
|
||||
Pattern pattern = Pattern.compile("Reviewed in (.+?) on (.+)");
|
||||
Matcher matcher = pattern.matcher(fullDateText);
|
||||
Matcher matcher = REVIEWED_IN_ON_PATTERN.matcher(fullDateText);
|
||||
String datePart = fullDateText;
|
||||
|
||||
if (matcher.find() && matcher.groupCount() == 2) {
|
||||
@@ -671,9 +673,9 @@ public class AmazonBookParser implements BookParser {
|
||||
try {
|
||||
String domain = appSettingService.getAppSettings().getMetadataProviderSettings().getAmazon().getDomain();
|
||||
String amazonCookie = appSettingService.getAppSettings().getMetadataProviderSettings().getAmazon().getCookie();
|
||||
|
||||
|
||||
LocaleInfo localeInfo = getLocaleInfoForDomain(domain);
|
||||
|
||||
|
||||
Connection connection = Jsoup.connect(url)
|
||||
.header("accept", "text/html, application/json")
|
||||
.header("accept-language", localeInfo.acceptLanguage)
|
||||
@@ -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) {
|
||||
try {
|
||||
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_ALPHANUMERIC_CJK_PATTERN = Pattern.compile("[^a-zA-Z0-9\\u4e00-\\u9fff]");
|
||||
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;
|
||||
|
||||
@Override
|
||||
@@ -49,7 +57,7 @@ public class DoubanBookParser implements BookParser {
|
||||
if (searchResults == null || searchResults.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
BookMetadata topResult = searchResults.get(0);
|
||||
BookMetadata topResult = searchResults.getFirst();
|
||||
|
||||
// If Douban reviews are enabled, fetch detailed metadata including reviews
|
||||
if (topResult.getDoubanId() != null && areDoubanReviewsEnabled()) {
|
||||
@@ -123,12 +131,11 @@ public class DoubanBookParser implements BookParser {
|
||||
String jsonData = null;
|
||||
|
||||
// Use regex to find the JSON object in window.__DATA__
|
||||
Pattern pattern = Pattern.compile("window\\.__DATA__\\s*=\\s*(\\{.*\\});", Pattern.DOTALL);
|
||||
Matcher matcher = pattern.matcher(htmlContent);
|
||||
if (matcher.find()) {
|
||||
jsonData = matcher.group(1);
|
||||
log.debug("Successfully extracted JSON data, length: {}", jsonData.length());
|
||||
}
|
||||
Matcher matcher = WINDOW_DATA_JSON_PATTERN.matcher(htmlContent);
|
||||
if (matcher.find()) {
|
||||
jsonData = matcher.group(1);
|
||||
log.debug("Successfully extracted JSON data, length: {}", jsonData.length());
|
||||
}
|
||||
|
||||
if (jsonData == null) {
|
||||
log.warn("No JSON data found in Douban search response");
|
||||
@@ -156,7 +163,7 @@ public class DoubanBookParser implements BookParser {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (itemsNode.size() == 0) {
|
||||
if (itemsNode.isEmpty()) {
|
||||
log.info("No books found for the search query");
|
||||
return null;
|
||||
}
|
||||
@@ -244,12 +251,11 @@ public class DoubanBookParser implements BookParser {
|
||||
if (url == null || url.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
Pattern pattern = Pattern.compile("/subject/(\\d+)/");
|
||||
Matcher matcher = pattern.matcher(url);
|
||||
if (matcher.find()) {
|
||||
return matcher.group(1);
|
||||
}
|
||||
return null;
|
||||
Matcher matcher = SUBJECT_ID_PATTERN.matcher(url);
|
||||
if (matcher.find()) {
|
||||
return matcher.group(1);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private BookMetadata getBookMetadata(String doubanBookId) {
|
||||
@@ -580,11 +586,10 @@ public class DoubanBookParser implements BookParser {
|
||||
Float ratingValue = null;
|
||||
if (!ratingElements.isEmpty()) {
|
||||
String ratingClass = ratingElements.first().className();
|
||||
Pattern pattern = Pattern.compile("rating(\\d+)");
|
||||
Matcher matcher = pattern.matcher(ratingClass);
|
||||
if (matcher.find()) {
|
||||
ratingValue = Float.parseFloat(matcher.group(1)) / 2.0f; // Convert 5-star scale to 10-star scale
|
||||
}
|
||||
Matcher matcher = RATING_NUMBER_PATTERN.matcher(ratingClass);
|
||||
if (matcher.find()) {
|
||||
ratingValue = Float.parseFloat(matcher.group(1)) / 2.0f; // Convert 5-star scale to 10-star scale
|
||||
}
|
||||
}
|
||||
|
||||
Elements dateElements = reviewElement.select(".comment-info .comment-time");
|
||||
@@ -715,13 +720,12 @@ public class DoubanBookParser implements BookParser {
|
||||
if (dateString == null || dateString.trim().isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
dateString = dateString.trim();
|
||||
String trim = dateString.trim();
|
||||
|
||||
// Try regex patterns first for more flexibility
|
||||
try {
|
||||
// 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 = pattern.matcher(dateString);
|
||||
Matcher matcher = DATE_YMD_PATTERN.matcher(trim);
|
||||
if (matcher.matches()) {
|
||||
int year = Integer.parseInt(matcher.group(1));
|
||||
int month = Integer.parseInt(matcher.group(2));
|
||||
@@ -730,8 +734,8 @@ public class DoubanBookParser implements BookParser {
|
||||
}
|
||||
|
||||
// Pattern for yyyy-MM or yyyy-M
|
||||
pattern = Pattern.compile("(\\d{4})[-/](\\d{1,2})");
|
||||
matcher = pattern.matcher(dateString);
|
||||
Pattern pattern = Pattern.compile("(\\d{4})[-/](\\d{1,2})");
|
||||
matcher = pattern.matcher(trim);
|
||||
if (matcher.matches()) {
|
||||
int year = Integer.parseInt(matcher.group(1));
|
||||
int month = Integer.parseInt(matcher.group(2));
|
||||
@@ -740,7 +744,7 @@ public class DoubanBookParser implements BookParser {
|
||||
|
||||
// Pattern for yyyy
|
||||
pattern = Pattern.compile("(\\d{4})");
|
||||
matcher = pattern.matcher(dateString);
|
||||
matcher = pattern.matcher(trim);
|
||||
if (matcher.matches()) {
|
||||
int year = Integer.parseInt(matcher.group(1));
|
||||
return LocalDate.of(year, 1, 1);
|
||||
@@ -749,7 +753,7 @@ public class DoubanBookParser implements BookParser {
|
||||
// Chinese patterns
|
||||
// Pattern for 年月日: 2011年1月10日
|
||||
pattern = Pattern.compile("(\\d{4})年(\\d{1,2})月(\\d{1,2})日");
|
||||
matcher = pattern.matcher(dateString);
|
||||
matcher = pattern.matcher(trim);
|
||||
if (matcher.matches()) {
|
||||
int year = Integer.parseInt(matcher.group(1));
|
||||
int month = Integer.parseInt(matcher.group(2));
|
||||
@@ -759,7 +763,7 @@ public class DoubanBookParser implements BookParser {
|
||||
|
||||
// Pattern for 年月: 2111年12月
|
||||
pattern = Pattern.compile("(\\d{4})年(\\d{1,2})月");
|
||||
matcher = pattern.matcher(dateString);
|
||||
matcher = pattern.matcher(trim);
|
||||
if (matcher.matches()) {
|
||||
int year = Integer.parseInt(matcher.group(1));
|
||||
int month = Integer.parseInt(matcher.group(2));
|
||||
@@ -768,14 +772,14 @@ public class DoubanBookParser implements BookParser {
|
||||
|
||||
// Pattern for 年: 2011年
|
||||
pattern = Pattern.compile("(\\d{4})年");
|
||||
matcher = pattern.matcher(dateString);
|
||||
matcher = pattern.matcher(trim);
|
||||
if (matcher.matches()) {
|
||||
int year = Integer.parseInt(matcher.group(1));
|
||||
return LocalDate.of(year, 1, 1);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
log.warn("Exception while parsing date '{}': {}", dateString, e.getMessage());
|
||||
log.warn("Exception while parsing date '{}': {}", trim, e.getMessage());
|
||||
}
|
||||
|
||||
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 int COUNT_DETAILED_METADATA_TO_GET = 3;
|
||||
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;
|
||||
|
||||
@Override
|
||||
@@ -63,7 +65,7 @@ public class GoodReadsParser implements BookParser {
|
||||
.orElse(null);
|
||||
|
||||
if (ogUrl != null && !ogUrl.isBlank()) {
|
||||
String goodreadsId = ogUrl.substring(ogUrl.lastIndexOf("/") + 1);
|
||||
String goodreadsId = ogUrl.substring(ogUrl.lastIndexOf('/') + 1);
|
||||
if (!goodreadsId.isBlank()) {
|
||||
BookMetadata metadata = parseBookDetails(doc, goodreadsId);
|
||||
if (metadata != null) {
|
||||
@@ -309,7 +311,7 @@ public class GoodReadsParser implements BookParser {
|
||||
}
|
||||
|
||||
private String handleStringNull(String s) {
|
||||
if (s != null && s.equals("null")) {
|
||||
if (s != null && "null".equals(s)) {
|
||||
return null;
|
||||
}
|
||||
return s;
|
||||
@@ -495,9 +497,11 @@ public class GoodReadsParser implements BookParser {
|
||||
private Integer extractGoodReadsIdPreview(Element book) {
|
||||
try {
|
||||
Element bookTitle = book.select("a.bookTitle").first();
|
||||
if (bookTitle == null) {
|
||||
return null;
|
||||
}
|
||||
String href = bookTitle.attr("href");
|
||||
Pattern pattern = Pattern.compile("/book/show/(\\d+)");
|
||||
Matcher matcher = pattern.matcher(href);
|
||||
Matcher matcher = BOOK_SHOW_ID_PATTERN.matcher(href);
|
||||
if (matcher.find()) {
|
||||
return Integer.valueOf(matcher.group(1));
|
||||
}
|
||||
|
||||
+1
-1
@@ -397,7 +397,7 @@ public class CbxMetadataWriter implements MetadataWriter {
|
||||
String n = name.replace('\\', '/');
|
||||
if (n.endsWith("/")) return false;
|
||||
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) {
|
||||
|
||||
+7
-21
@@ -107,9 +107,7 @@ public class EpubMetadataWriter implements MetadataWriter {
|
||||
hasChanges[0] = true;
|
||||
});
|
||||
|
||||
helper.copySeriesName(clear != null && clear.isSeriesName(), val -> {
|
||||
replaceMetaElement(metadataElement, opfDoc, "calibre:series", val, hasChanges);
|
||||
});
|
||||
helper.copySeriesName(clear != null && clear.isSeriesName(), val -> replaceMetaElement(metadataElement, opfDoc, "calibre:series", val, hasChanges));
|
||||
|
||||
helper.copySeriesNumber(clear != null && clear.isSeriesNumber(), val -> {
|
||||
String formatted = val != null ? String.format("%.1f", val) : null;
|
||||
@@ -136,24 +134,12 @@ public class EpubMetadataWriter implements MetadataWriter {
|
||||
};
|
||||
|
||||
switch (scheme) {
|
||||
case "AMAZON" -> helper.copyAsin(clearFlag, idValue -> {
|
||||
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 "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);
|
||||
});
|
||||
case "AMAZON" -> helper.copyAsin(clearFlag, idValue -> 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 "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);
|
||||
});
|
||||
|
||||
helper.copyAuthors(clear != null && clear.isAuthors(), authors -> {
|
||||
(authors != null ? authors : List.of("")).forEach(dc::addCreator);
|
||||
});
|
||||
helper.copyAuthors(clear != null && clear.isAuthors(), authors -> (authors != null ? authors : List.of("")).forEach(dc::addCreator));
|
||||
|
||||
helper.copyCategories(clear != null && clear.isCategories(), cats -> {
|
||||
(cats != null ? cats : List.of("")).forEach(dc::addSubject);
|
||||
});
|
||||
helper.copyCategories(clear != null && clear.isCategories(), cats -> (cats != null ? cats : List.of("")).forEach(dc::addSubject));
|
||||
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
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.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import lombok.Getter;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
@@ -143,6 +144,7 @@ public class BookVectorService {
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@Getter
|
||||
public static class ScoredBook {
|
||||
private final Long bookId;
|
||||
private final double score;
|
||||
@@ -152,13 +154,6 @@ public class BookVectorService {
|
||||
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);
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
/**
|
||||
* Create and persist a remote-provisioned user based on incoming headers.
|
||||
* This is the preferred (non-deprecated) entry point for remote provisioning.
|
||||
*/
|
||||
@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;
|
||||
if (groups != null && appProperties.getRemoteAuth().getAdminGroup() != null) {
|
||||
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);
|
||||
}
|
||||
List<String> groupsList = Arrays.asList(WHITESPACE_PATTERN.split(groupsContent));
|
||||
@@ -199,9 +202,9 @@ public class UserProvisioningService {
|
||||
}
|
||||
|
||||
protected BookLoreUserEntity createUser(BookLoreUserEntity user) {
|
||||
user = userRepository.save(user);
|
||||
userDefaultsService.addDefaultShelves(user);
|
||||
userDefaultsService.addDefaultSettings(user);
|
||||
return user;
|
||||
BookLoreUserEntity save = userRepository.save(user);
|
||||
userDefaultsService.addDefaultShelves(save);
|
||||
userDefaultsService.addDefaultSettings(save);
|
||||
return save;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,30 +9,32 @@ public class BookUtils {
|
||||
private static final Pattern PARENTHESES_WITH_OPTIONAL_SPACE_PATTERN = Pattern.compile("\\s?\\(.*?\\)");
|
||||
|
||||
public static String cleanFileName(String fileName) {
|
||||
if (fileName == null) {
|
||||
String name = fileName;
|
||||
if (name == null) {
|
||||
return null;
|
||||
}
|
||||
fileName = fileName.replace("(Z-Library)", "").trim();
|
||||
fileName = PARENTHESES_WITH_OPTIONAL_SPACE_PATTERN.matcher(fileName).replaceAll("").trim(); // Remove the author name inside parentheses (e.g. (Jon Yablonski))
|
||||
int dotIndex = fileName.lastIndexOf('.'); // Remove the file extension (e.g., .pdf, .docx)
|
||||
name = name.replace("(Z-Library)", "").trim();
|
||||
name = PARENTHESES_WITH_OPTIONAL_SPACE_PATTERN.matcher(name).replaceAll("").trim(); // Remove the author name inside parentheses (e.g. (Jon Yablonski))
|
||||
int dotIndex = name.lastIndexOf('.'); // Remove the file extension (e.g., .pdf, .docx)
|
||||
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) {
|
||||
term = SPECIAL_CHARACTERS_PATTERN.matcher(term).replaceAll("").trim();
|
||||
if (term.length() > 60) {
|
||||
String[] words = WHITESPACE_PATTERN.split(term);
|
||||
String s = term;
|
||||
s = SPECIAL_CHARACTERS_PATTERN.matcher(s).replaceAll("").trim();
|
||||
if (s.length() > 60) {
|
||||
String[] words = WHITESPACE_PATTERN.split(s);
|
||||
StringBuilder truncated = new StringBuilder();
|
||||
for (String word : words) {
|
||||
if (truncated.length() + word.length() + 1 > 60) break;
|
||||
if (!truncated.isEmpty()) truncated.append(" ");
|
||||
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.File;
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.net.URL;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
@@ -154,7 +155,8 @@ public class FileService {
|
||||
|
||||
public BufferedImage downloadImageFromUrl(String imageUrl) throws IOException {
|
||||
try {
|
||||
URL url = new URL(imageUrl);
|
||||
URI uri = URI.create(imageUrl);
|
||||
URL url = uri.toURL();
|
||||
BufferedImage image = ImageIO.read(url);
|
||||
if (image == null) {
|
||||
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) {
|
||||
if (value == null) return true;
|
||||
if (value instanceof String s) return s.isBlank();
|
||||
if (value instanceof Collection<?> c) return c.isEmpty();
|
||||
return false;
|
||||
return switch (value) {
|
||||
case null -> true;
|
||||
case String s -> s.isBlank();
|
||||
case Collection<?> c -> c.isEmpty();
|
||||
default -> false;
|
||||
};
|
||||
}
|
||||
|
||||
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 FILE_EXTENSION_PATTERN = Pattern.compile(".*\\.[a-zA-Z0-9]+$");
|
||||
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) {
|
||||
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) {
|
||||
String extension = "";
|
||||
int lastDot = currentFilename.lastIndexOf(".");
|
||||
int lastDot = currentFilename.lastIndexOf('.');
|
||||
if (lastDot >= 0 && lastDot < currentFilename.length() - 1) {
|
||||
extension = sanitize(currentFilename.substring(lastDot + 1)); // e.g. "epub"
|
||||
}
|
||||
@@ -100,7 +101,7 @@ public class PathPatternResolver {
|
||||
// Handle optional blocks enclosed in <...>
|
||||
Pattern optionalBlockPattern = Pattern.compile("<([^<>]*)>");
|
||||
Matcher matcher = optionalBlockPattern.matcher(pattern);
|
||||
StringBuffer resolved = new StringBuffer();
|
||||
StringBuilder resolved = new StringBuilder();
|
||||
|
||||
while (matcher.find()) {
|
||||
String block = matcher.group(1);
|
||||
@@ -134,7 +135,7 @@ public class PathPatternResolver {
|
||||
// Replace known placeholders with values, preserve unknown ones
|
||||
Pattern placeholderPattern = Pattern.compile("\\{(.*?)}");
|
||||
Matcher placeholderMatcher = placeholderPattern.matcher(result);
|
||||
StringBuffer finalResult = new StringBuffer();
|
||||
StringBuilder finalResult = new StringBuilder();
|
||||
|
||||
while (placeholderMatcher.find()) {
|
||||
String key = placeholderMatcher.group(1);
|
||||
@@ -166,8 +167,7 @@ public class PathPatternResolver {
|
||||
|
||||
private static String sanitize(String input) {
|
||||
if (input == null) return "";
|
||||
return WHITESPACE_PATTERN.matcher(CONTROL_CHARACTER_PATTERN.matcher(input
|
||||
.replaceAll("[\\\\/:*?\"<>|]", "")).replaceAll("")).replaceAll(" ")
|
||||
return WHITESPACE_PATTERN.matcher(CONTROL_CHARACTER_PATTERN.matcher(INVALID_CHARS_PATTERN.matcher(input).replaceAll("")).replaceAll("")).replaceAll(" ")
|
||||
.trim();
|
||||
}
|
||||
|
||||
|
||||
+1
-2
@@ -55,14 +55,13 @@ class AdditionalFileServiceTest {
|
||||
private BookAdditionalFileEntity fileEntity;
|
||||
private AdditionalFile additionalFile;
|
||||
private BookEntity bookEntity;
|
||||
private LibraryPathEntity libraryPathEntity;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws IOException {
|
||||
Path testFile = tempDir.resolve("test-file.pdf");
|
||||
Files.createFile(testFile);
|
||||
|
||||
libraryPathEntity = new LibraryPathEntity();
|
||||
LibraryPathEntity libraryPathEntity = new LibraryPathEntity();
|
||||
libraryPathEntity.setId(1L);
|
||||
libraryPathEntity.setPath(tempDir.toString());
|
||||
|
||||
|
||||
+3
-3
@@ -73,7 +73,7 @@ class BookNoteServiceTest {
|
||||
.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();
|
||||
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();
|
||||
|
||||
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.save(existing)).thenReturn(saved);
|
||||
when(mapper.toDto(saved)).thenReturn(dto);
|
||||
@@ -162,7 +162,7 @@ class BookNoteServiceTest {
|
||||
.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());
|
||||
|
||||
assertThrows(EntityNotFoundException.class, () -> service.createOrUpdateNote(req));
|
||||
|
||||
+9
-9
@@ -100,10 +100,10 @@ class BookReviewServiceTest {
|
||||
Set<MetadataPublicReviewsSettings.ReviewProviderConfig> configs = new HashSet<>();
|
||||
for (MetadataProvider provider : providers) {
|
||||
MetadataPublicReviewsSettings.ReviewProviderConfig config =
|
||||
MetadataPublicReviewsSettings.ReviewProviderConfig.builder()
|
||||
.provider(provider)
|
||||
.enabled(true)
|
||||
.build();
|
||||
MetadataPublicReviewsSettings.ReviewProviderConfig.builder()
|
||||
.provider(provider)
|
||||
.enabled(true)
|
||||
.maxReviews(10).build();
|
||||
configs.add(config);
|
||||
}
|
||||
|
||||
@@ -193,7 +193,7 @@ class BookReviewServiceTest {
|
||||
when(bookRepository.findById(bookId)).thenReturn(Optional.of(bookEntity));
|
||||
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()
|
||||
.bookReviews(Collections.singletonList(freshReview))
|
||||
.build());
|
||||
@@ -204,7 +204,7 @@ class BookReviewServiceTest {
|
||||
List<BookReview> result = service.getByBookId(bookId);
|
||||
|
||||
assertEquals(1, result.size());
|
||||
assertEquals(freshReview, result.get(0));
|
||||
assertEquals(freshReview, result.getFirst());
|
||||
verify(bookReviewUpdateService).addReviewsToBook(
|
||||
Collections.singletonList(freshReview), bookEntity.getMetadata());
|
||||
verify(bookRepository).save(bookEntity);
|
||||
@@ -229,7 +229,7 @@ class BookReviewServiceTest {
|
||||
when(bookRepository.findById(bookId)).thenReturn(Optional.of(bookEntity));
|
||||
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()
|
||||
.bookReviews(Collections.singletonList(freshReview))
|
||||
.build());
|
||||
@@ -305,7 +305,7 @@ class BookReviewServiceTest {
|
||||
BookReview amazonReview = createBookReview(MetadataProvider.Amazon);
|
||||
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()
|
||||
.bookReviews(Collections.singletonList(amazonReview))
|
||||
.build());
|
||||
@@ -330,7 +330,7 @@ class BookReviewServiceTest {
|
||||
AppSettings appSettings = new AppSettings();
|
||||
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()
|
||||
.bookReviews(null)
|
||||
.build());
|
||||
|
||||
+1
-3
@@ -140,9 +140,7 @@ class BookdropMetadataServiceTest {
|
||||
|
||||
when(bookdropFileRepository.findById(sampleFile.getId())).thenReturn(Optional.of(sampleFile));
|
||||
|
||||
assertThatThrownBy(() -> {
|
||||
bookdropMetadataService.attachInitialMetadata(sampleFile.getId());
|
||||
}).isInstanceOf(APIException.class)
|
||||
assertThatThrownBy(() -> bookdropMetadataService.attachInitialMetadata(sampleFile.getId())).isInstanceOf(APIException.class)
|
||||
.hasMessageContaining("Invalid file format");
|
||||
}
|
||||
|
||||
|
||||
+3
-5
@@ -46,8 +46,6 @@ class KoreaderServiceTest {
|
||||
KoreaderService service;
|
||||
|
||||
private KoreaderUserDetails details;
|
||||
private Authentication auth;
|
||||
private SecurityContext context;
|
||||
|
||||
@BeforeEach
|
||||
void setUpAuth() {
|
||||
@@ -55,8 +53,8 @@ class KoreaderServiceTest {
|
||||
when(details.getUsername()).thenReturn("u");
|
||||
when(details.getPassword()).thenReturn("md5pwd");
|
||||
when(details.getBookLoreUserId()).thenReturn(42L);
|
||||
auth = mock(Authentication.class);
|
||||
context = new SecurityContextImpl();
|
||||
Authentication auth = mock(Authentication.class);
|
||||
SecurityContext context = new SecurityContextImpl();
|
||||
when(auth.getPrincipal()).thenReturn(details);
|
||||
context.setAuthentication(auth);
|
||||
SecurityContextHolder.setContext(context);
|
||||
@@ -77,7 +75,7 @@ class KoreaderServiceTest {
|
||||
when(details.getPassword()).thenReturn("MD5PWD");
|
||||
|
||||
ResponseEntity<Map<String, String>> resp = service.authorizeUser();
|
||||
assertEquals(200, resp.getStatusCodeValue());
|
||||
assertEquals(200, resp.getStatusCode().value());
|
||||
assertEquals("u", resp.getBody().get("username"));
|
||||
}
|
||||
|
||||
|
||||
+1
-2
@@ -34,14 +34,13 @@ class KoreaderUserServiceTest {
|
||||
@InjectMocks
|
||||
KoreaderUserService service;
|
||||
|
||||
private BookLoreUser ownerDto;
|
||||
private BookLoreUserEntity ownerEntity;
|
||||
private KoreaderUserEntity entity;
|
||||
private KoreaderUser dto;
|
||||
|
||||
@BeforeEach
|
||||
void init() {
|
||||
ownerDto = mock(BookLoreUser.class);
|
||||
BookLoreUser ownerDto = mock(BookLoreUser.class);
|
||||
when(ownerDto.getId()).thenReturn(123L);
|
||||
when(ownerDto.getUsername()).thenReturn("ownerName");
|
||||
when(authService.getAuthenticatedUser()).thenReturn(ownerDto);
|
||||
|
||||
+8
-8
@@ -77,7 +77,7 @@ class OpdsBookServiceTest {
|
||||
|
||||
List<Library> libraries = new ArrayList<>();
|
||||
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);
|
||||
|
||||
@@ -86,7 +86,7 @@ class OpdsBookServiceTest {
|
||||
|
||||
@Test
|
||||
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);
|
||||
|
||||
List<Library> result = opdsBookService.getAccessibleLibraries(null);
|
||||
@@ -104,7 +104,7 @@ class OpdsBookServiceTest {
|
||||
BookLoreUser.UserPermissions perms = mock(BookLoreUser.UserPermissions.class);
|
||||
when(user.getPermissions()).thenReturn(perms);
|
||||
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);
|
||||
|
||||
List<Library> result = opdsBookService.getAccessibleLibraries(details);
|
||||
@@ -115,7 +115,7 @@ class OpdsBookServiceTest {
|
||||
@Test
|
||||
void getAccessibleLibraries_returnsAllLibraries_forAdmin() {
|
||||
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);
|
||||
|
||||
List<Library> result = opdsBookService.getAccessibleLibraries(details);
|
||||
@@ -194,7 +194,7 @@ class OpdsBookServiceTest {
|
||||
BookLoreUser.UserPermissions perms = mock(BookLoreUser.UserPermissions.class);
|
||||
when(user.getPermissions()).thenReturn(perms);
|
||||
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);
|
||||
|
||||
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);
|
||||
|
||||
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
|
||||
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);
|
||||
|
||||
String name = opdsBookService.getLibraryName(1L);
|
||||
@@ -264,7 +264,7 @@ class OpdsBookServiceTest {
|
||||
void getRandomBooks_returnsBooks_whenLibrariesAccessible() {
|
||||
OpdsUserDetails details = v2UserDetails(1L, true, Set.of(1L));
|
||||
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);
|
||||
|
||||
when(bookOpdsRepository.findRandomBookIdsByLibraryIds(anyList())).thenReturn(List.of(1L, 2L));
|
||||
|
||||
+2
-3
@@ -86,12 +86,11 @@ class BookDropServiceTest {
|
||||
|
||||
private BookdropFileEntity bookdropFileEntity;
|
||||
private LibraryEntity libraryEntity;
|
||||
private LibraryPathEntity libraryPathEntity;
|
||||
private BookdropFile bookdropFile;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws IOException {
|
||||
libraryPathEntity = new LibraryPathEntity();
|
||||
LibraryPathEntity libraryPathEntity = new LibraryPathEntity();
|
||||
libraryPathEntity.setId(1L);
|
||||
libraryPathEntity.setPath(tempDir.toString());
|
||||
|
||||
@@ -142,7 +141,7 @@ class BookDropServiceTest {
|
||||
Page<BookdropFile> result = bookDropService.getFilesByStatus("pending", pageable);
|
||||
|
||||
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(mapper).toDto(bookdropFileEntity);
|
||||
}
|
||||
|
||||
+6
-6
@@ -215,7 +215,7 @@ class AbstractFileProcessorTest {
|
||||
@Test
|
||||
void processFile_shouldReturnUpdated_whenDuplicateFoundWithDifferentLibraryPath() {
|
||||
// Given
|
||||
LibraryEntity library = LibraryEntity.builder().id(2L).build();
|
||||
LibraryEntity library = LibraryEntity.builder().id(2L).watch(false).build();
|
||||
LibraryPathEntity newLibraryPath = LibraryPathEntity.builder()
|
||||
.id(2L)
|
||||
.library(library)
|
||||
@@ -232,7 +232,7 @@ class AbstractFileProcessorTest {
|
||||
|
||||
Book duplicateBook = createMockBook(1L, "file.pdf");
|
||||
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");
|
||||
|
||||
try (MockedStatic<FileFingerprint> fingerprintMock = mockStatic(FileFingerprint.class)) {
|
||||
@@ -331,7 +331,7 @@ class AbstractFileProcessorTest {
|
||||
@Test
|
||||
void processFile_shouldHandleNullFileSubPath() {
|
||||
// Given
|
||||
LibraryEntity library = LibraryEntity.builder().id(1L).build();
|
||||
LibraryEntity library = LibraryEntity.builder().id(1L).watch(false).build();
|
||||
LibraryPathEntity libraryPath = LibraryPathEntity.builder()
|
||||
.id(1L)
|
||||
.library(library)
|
||||
@@ -373,7 +373,7 @@ class AbstractFileProcessorTest {
|
||||
@Test
|
||||
void processFile_shouldHandleMultipleMetadataChangesSimultaneously() {
|
||||
// Given
|
||||
LibraryEntity newLibrary = LibraryEntity.builder().id(2L).build();
|
||||
LibraryEntity newLibrary = LibraryEntity.builder().id(2L).watch(false).build();
|
||||
LibraryPathEntity newLibraryPath = LibraryPathEntity.builder()
|
||||
.id(2L)
|
||||
.library(newLibrary)
|
||||
@@ -390,7 +390,7 @@ class AbstractFileProcessorTest {
|
||||
|
||||
Book duplicateBook = createMockBook(1L, "old-file.pdf");
|
||||
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");
|
||||
|
||||
try (MockedStatic<FileFingerprint> fingerprintMock = mockStatic(FileFingerprint.class)) {
|
||||
@@ -442,7 +442,7 @@ class AbstractFileProcessorTest {
|
||||
|
||||
// Helper methods
|
||||
private LibraryFile createMockLibraryFile() {
|
||||
LibraryEntity library = LibraryEntity.builder().id(1L).build();
|
||||
LibraryEntity library = LibraryEntity.builder().id(1L).watch(false).build();
|
||||
LibraryPathEntity libraryPath = LibraryPathEntity.builder()
|
||||
.id(1L)
|
||||
.library(library)
|
||||
|
||||
+2
-2
@@ -62,7 +62,7 @@ class LibraryRescanHelperTest {
|
||||
|
||||
LibraryRescanOptions options = LibraryRescanOptions.builder()
|
||||
.metadataReplaceMode(MetadataReplaceMode.REPLACE_ALL)
|
||||
.build();
|
||||
.updateMetadataFromFiles(true).build();
|
||||
|
||||
rescanContext = RescanLibraryContext.builder()
|
||||
.libraryId(1L)
|
||||
@@ -226,7 +226,7 @@ class LibraryRescanHelperTest {
|
||||
|
||||
List<TaskProgressPayload> payloads = payloadCaptor.getAllValues();
|
||||
assertEquals(3, payloads.size());
|
||||
assertEquals(0, payloads.get(0).getProgress());
|
||||
assertEquals(0, payloads.getFirst().getProgress());
|
||||
assertEquals(TaskStatus.IN_PROGRESS, payloads.get(0).getTaskStatus());
|
||||
assertEquals(TaskType.REFRESH_LIBRARY_METADATA, payloads.get(0).getTaskType());
|
||||
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.Path;
|
||||
import java.time.LocalDate;
|
||||
import java.util.Comparator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.zip.ZipEntry;
|
||||
@@ -42,15 +43,14 @@ class CbxMetadataExtractorTest {
|
||||
if (tempDir != null) {
|
||||
// best-effort cleanup
|
||||
Files.walk(tempDir)
|
||||
.sorted((a, b) -> b.compareTo(a))
|
||||
.sorted(Comparator.reverseOrder())
|
||||
.forEach(p -> { try { Files.deleteIfExists(p); } catch (Exception ignore) {} });
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractMetadata_fromCbz_withComicInfo_populatesFields() throws Exception {
|
||||
String xml = "" +
|
||||
"<ComicInfo>" +
|
||||
String xml = "<ComicInfo>" +
|
||||
" <Title>My Comic</Title>" +
|
||||
" <Summary>A short summary</Summary>" +
|
||||
" <Publisher>Indie</Publisher>" +
|
||||
@@ -88,8 +88,7 @@ class CbxMetadataExtractorTest {
|
||||
|
||||
@Test
|
||||
void extractCover_fromCbz_usesComicInfoImageFile() throws Exception {
|
||||
String xml = "" +
|
||||
"<ComicInfo>" +
|
||||
String xml = "<ComicInfo>" +
|
||||
" <Pages>" +
|
||||
" <Page Type=\"FrontCover\" ImageFile=\"images/002.jpg\"/>" +
|
||||
" </Pages>" +
|
||||
@@ -130,7 +129,7 @@ class CbxMetadataExtractorTest {
|
||||
@Test
|
||||
void extractMetadata_nonArchive_fallbackTitle() throws Exception {
|
||||
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());
|
||||
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.Path;
|
||||
import java.time.LocalDate;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.zip.ZipEntry;
|
||||
@@ -43,7 +44,7 @@ class CbxMetadataWriterTest {
|
||||
void cleanup() throws Exception {
|
||||
if (tempDir != null) {
|
||||
Files.walk(tempDir)
|
||||
.sorted((a, b) -> b.compareTo(a))
|
||||
.sorted(Comparator.reverseOrder())
|
||||
.forEach(p -> { try { Files.deleteIfExists(p); } catch (Exception ignore) {} });
|
||||
}
|
||||
}
|
||||
@@ -142,10 +143,11 @@ class CbxMetadataWriterTest {
|
||||
void writeMetadataToFile_cbz_updatesExistingComicInfo() throws Exception {
|
||||
// Create a CBZ *with* an existing ComicInfo.xml
|
||||
Path out = tempDir.resolve("with_meta.cbz");
|
||||
String xml = "<ComicInfo>\n" +
|
||||
" <Title>Old Title</Title>\n" +
|
||||
" <Summary>Old Summary</Summary>\n" +
|
||||
"</ComicInfo>";
|
||||
String xml = """
|
||||
<ComicInfo>
|
||||
<Title>Old Title</Title>
|
||||
<Summary>Old Summary</Summary>
|
||||
</ComicInfo>""";
|
||||
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(out.toFile()))) {
|
||||
put(zos, "ComicInfo.xml", xml.getBytes(StandardCharsets.UTF_8));
|
||||
put(zos, "a.jpg", new byte[]{1});
|
||||
|
||||
+1
-1
@@ -57,7 +57,7 @@ class OpdsFeedServiceTest {
|
||||
OpdsUserDetails userDetails = mock(OpdsUserDetails.class);
|
||||
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));
|
||||
|
||||
String xml = opdsFeedService.generateLibrariesNavigation(request);
|
||||
|
||||
+4
-4
@@ -71,7 +71,7 @@ class TaskCronServiceTest {
|
||||
|
||||
List<TaskCronConfigurationEntity> result = service.getAllEnabledCronConfigs();
|
||||
assertEquals(1, result.size());
|
||||
assertEquals(TaskType.CLEAR_CBX_CACHE, result.get(0).getTaskType());
|
||||
assertEquals(TaskType.CLEAR_CBX_CACHE, result.getFirst().getTaskType());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -117,7 +117,7 @@ class TaskCronServiceTest {
|
||||
@Test
|
||||
void testPatchCronConfig_updateExisting() {
|
||||
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);
|
||||
|
||||
when(authService.getAuthenticatedUser()).thenReturn(user);
|
||||
@@ -136,7 +136,7 @@ class TaskCronServiceTest {
|
||||
@Test
|
||||
void testPatchCronConfig_createNew() {
|
||||
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(repository.findByTaskType(type)).thenReturn(Optional.empty());
|
||||
@@ -155,7 +155,7 @@ class TaskCronServiceTest {
|
||||
@Test
|
||||
void testPatchCronConfig_invalidCronExpression_throws() {
|
||||
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(repository.findByTaskType(type)).thenReturn(Optional.empty());
|
||||
|
||||
+12
-12
@@ -69,7 +69,7 @@ class TaskServiceTest {
|
||||
|
||||
@Test
|
||||
void testRunAsUserThrowsExceptionForNullTaskType() {
|
||||
TaskCreateRequest req = TaskCreateRequest.builder().build();
|
||||
TaskCreateRequest req = TaskCreateRequest.builder().triggeredByCron(false).build();
|
||||
APIException ex = assertThrows(APIException.class, () -> taskService.runAsUser(req));
|
||||
assertEquals(HttpStatus.BAD_REQUEST, ex.getStatus());
|
||||
}
|
||||
@@ -94,14 +94,14 @@ class TaskServiceTest {
|
||||
user.setUsername("user1");
|
||||
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
|
||||
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);
|
||||
assertEquals(TaskType.CLEANUP_TEMP_METADATA, resp.getTaskType());
|
||||
}
|
||||
|
||||
@Test
|
||||
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();
|
||||
user.setId(1L);
|
||||
user.setUsername("user1");
|
||||
@@ -119,8 +119,8 @@ class TaskServiceTest {
|
||||
user.setUsername("parallelUser");
|
||||
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
|
||||
|
||||
TaskCreateRequest req1 = TaskCreateRequest.builder().taskType(parallelType).build();
|
||||
TaskCreateRequest req2 = TaskCreateRequest.builder().taskType(parallelType).build();
|
||||
TaskCreateRequest req1 = TaskCreateRequest.builder().taskType(parallelType).triggeredByCron(false).build();
|
||||
TaskCreateRequest req2 = TaskCreateRequest.builder().taskType(parallelType).triggeredByCron(false).build();
|
||||
|
||||
TaskCreateResponse resp1 = taskService.runAsUser(req1);
|
||||
TaskCreateResponse resp2 = taskService.runAsUser(req2);
|
||||
@@ -152,7 +152,7 @@ class TaskServiceTest {
|
||||
user.setUsername("nonParallelUser");
|
||||
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
|
||||
|
||||
TaskCreateRequest req = TaskCreateRequest.builder().taskType(nonParallelType).build();
|
||||
TaskCreateRequest req = TaskCreateRequest.builder().taskType(nonParallelType).triggeredByCron(false).build();
|
||||
taskService.runAsUser(req);
|
||||
|
||||
APIException ex = assertThrows(APIException.class, () -> taskService.runAsUser(req));
|
||||
@@ -193,7 +193,7 @@ class TaskServiceTest {
|
||||
user.setUsername("asyncUser");
|
||||
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);
|
||||
|
||||
assertEquals(asyncType, resp.getTaskType());
|
||||
@@ -210,7 +210,7 @@ class TaskServiceTest {
|
||||
user.setUsername("nullOptionsUser");
|
||||
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);
|
||||
assertEquals(type, resp.getTaskType());
|
||||
}
|
||||
@@ -225,20 +225,20 @@ class TaskServiceTest {
|
||||
user.setUsername("exceptionUser");
|
||||
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));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRunAsUserThrowsExceptionForNullUser() {
|
||||
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));
|
||||
}
|
||||
|
||||
@Test
|
||||
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();
|
||||
user.setId(8L);
|
||||
user.setUsername("missingTaskUser");
|
||||
@@ -253,7 +253,7 @@ class TaskServiceTest {
|
||||
user.setUsername("invalidOptionsUser");
|
||||
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
|
||||
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());
|
||||
TaskCreateResponse resp = taskService.runAsUser(req);
|
||||
assertEquals(TaskType.CLEANUP_TEMP_METADATA, resp.getTaskType());
|
||||
|
||||
+3
-3
@@ -183,7 +183,7 @@ public class LibraryTestBuilder {
|
||||
}
|
||||
|
||||
public LibraryTestBuilder addBook(String fileSubPath, String fileName) {
|
||||
fileSubPath = removeLeadingSlash(fileSubPath);
|
||||
String subPath = removeLeadingSlash(fileSubPath);
|
||||
|
||||
long id = bookRepository.size() + 1L;
|
||||
BookMetadataEntity metadata = BookMetadataEntity.builder()
|
||||
@@ -191,11 +191,11 @@ public class LibraryTestBuilder {
|
||||
.bookId(id)
|
||||
.build();
|
||||
|
||||
String hash = computeFileHash(Path.of(fileSubPath, fileName));
|
||||
String hash = computeFileHash(Path.of(subPath, fileName));
|
||||
BookEntity bookEntity = BookEntity.builder()
|
||||
.id(id)
|
||||
.fileName(fileName)
|
||||
.fileSubPath(fileSubPath)
|
||||
.fileSubPath(subPath)
|
||||
.bookType(getBookFileType(fileName))
|
||||
.fileSizeKb(1024L)
|
||||
.library(getLibraryEntity())
|
||||
|
||||
Reference in New Issue
Block a user