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:
Balázs Szücs
2025-11-20 21:09:39 -07:00
committed by GitHub
parent cb8f5e7a29
commit 5c42e2e765
51 changed files with 325 additions and 330 deletions
@@ -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();
@@ -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
@@ -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()) {
@@ -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()
@@ -72,6 +72,8 @@ public class MetadataController {
.updateThumbnail(true)
.mergeCategories(mergeCategories)
.replaceMode(MetadataReplaceMode.REPLACE_ALL)
.mergeMoods(true)
.mergeTags(true)
.build();
bookMetadataUpdater.setBookMetadata(context);
@@ -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;
}
@@ -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) {
@@ -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("");
}
}
@@ -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);
}
@@ -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);
@@ -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;
}
}
@@ -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();
@@ -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())
@@ -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()
@@ -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;
}
@@ -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)));
}
}
@@ -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());
@@ -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();
@@ -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) {
@@ -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);
@@ -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) {
@@ -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) {
@@ -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);
}
@@ -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));
@@ -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;
@@ -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));
}
@@ -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) {
@@ -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));
}
}
@@ -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);
@@ -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;
}
}
}
@@ -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);
@@ -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();
}