refactor(regex): replace string manipulation with regex patterns for improved clarity and performance (#869)
This commit is contained in:
@@ -18,12 +18,14 @@ import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerCo
|
|||||||
import org.springframework.web.socket.config.annotation.WebSocketTransportRegistration;
|
import org.springframework.web.socket.config.annotation.WebSocketTransportRegistration;
|
||||||
|
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@Configuration
|
@Configuration
|
||||||
@EnableWebSocketMessageBroker
|
@EnableWebSocketMessageBroker
|
||||||
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
|
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
|
||||||
|
|
||||||
|
private static final Pattern COMMA_SPLIT_PATTERN = Pattern.compile("\\s*,\\s*");
|
||||||
private final WebSocketAuthInterceptor webSocketAuthInterceptor;
|
private final WebSocketAuthInterceptor webSocketAuthInterceptor;
|
||||||
private final Environment env;
|
private final Environment env;
|
||||||
|
|
||||||
@@ -67,7 +69,7 @@ public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
|
|||||||
} else if (allowedOrigins.isEmpty()) {
|
} else if (allowedOrigins.isEmpty()) {
|
||||||
log.info("WebSocket endpoint registered at /ws (same-origin only)");
|
log.info("WebSocket endpoint registered at /ws (same-origin only)");
|
||||||
} else {
|
} else {
|
||||||
String[] origins = Arrays.stream(allowedOrigins.split("\\s*,\\s*"))
|
String[] origins = Arrays.stream(COMMA_SPLIT_PATTERN.split(allowedOrigins))
|
||||||
.filter(s -> !s.isEmpty())
|
.filter(s -> !s.isEmpty())
|
||||||
.toArray(String[]::new);
|
.toArray(String[]::new);
|
||||||
endpoint.setAllowedOriginPatterns(origins);
|
endpoint.setAllowedOriginPatterns(origins);
|
||||||
|
|||||||
@@ -30,6 +30,7 @@ import java.util.Set;
|
|||||||
import java.util.concurrent.ConcurrentHashMap;
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
import java.util.concurrent.ConcurrentMap;
|
import java.util.concurrent.ConcurrentMap;
|
||||||
import java.util.concurrent.locks.ReentrantLock;
|
import java.util.concurrent.locks.ReentrantLock;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@Service
|
@Service
|
||||||
@@ -38,6 +39,7 @@ public class OidcAuthService {
|
|||||||
|
|
||||||
private static final String MOBILE_SCHEME = "booklore://";
|
private static final String MOBILE_SCHEME = "booklore://";
|
||||||
private static final String OAUTH2_CALLBACK_PATH = "/oauth2-callback";
|
private static final String OAUTH2_CALLBACK_PATH = "/oauth2-callback";
|
||||||
|
private static final Pattern TRAILING_SLASH_PATTERN = Pattern.compile("/+$");
|
||||||
|
|
||||||
private final AppSettingService appSettingService;
|
private final AppSettingService appSettingService;
|
||||||
private final OidcTokenClient oidcTokenClient;
|
private final OidcTokenClient oidcTokenClient;
|
||||||
@@ -154,7 +156,7 @@ public class OidcAuthService {
|
|||||||
private String resolveRequestOrigin(HttpServletRequest request) {
|
private String resolveRequestOrigin(HttpServletRequest request) {
|
||||||
String origin = request.getHeader("Origin");
|
String origin = request.getHeader("Origin");
|
||||||
if (origin != null && !origin.isBlank()) {
|
if (origin != null && !origin.isBlank()) {
|
||||||
return origin.replaceAll("/+$", "");
|
return TRAILING_SLASH_PATTERN.matcher(origin).replaceAll("");
|
||||||
}
|
}
|
||||||
String scheme = request.getScheme();
|
String scheme = request.getScheme();
|
||||||
String host = request.getServerName();
|
String host = request.getServerName();
|
||||||
|
|||||||
@@ -34,6 +34,7 @@ import java.nio.file.Files;
|
|||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
import java.util.Comparator;
|
import java.util.Comparator;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
import java.util.zip.ZipEntry;
|
import java.util.zip.ZipEntry;
|
||||||
import java.util.zip.ZipOutputStream;
|
import java.util.zip.ZipOutputStream;
|
||||||
|
|
||||||
@@ -42,6 +43,8 @@ import java.util.zip.ZipOutputStream;
|
|||||||
@Service
|
@Service
|
||||||
public class BookDownloadService {
|
public class BookDownloadService {
|
||||||
|
|
||||||
|
private static final Pattern NON_ALPHANUMERIC_PATTERN = Pattern.compile("[^a-zA-Z0-9\\-_]");
|
||||||
|
private static final Pattern ASCII_ONLY_PATTERN = Pattern.compile("\\p{ASCII}*");
|
||||||
private final BookRepository bookRepository;
|
private final BookRepository bookRepository;
|
||||||
private final BookFileRepository bookFileRepository;
|
private final BookFileRepository bookFileRepository;
|
||||||
private final KepubConversionService kepubConversionService;
|
private final KepubConversionService kepubConversionService;
|
||||||
@@ -137,7 +140,7 @@ public class BookDownloadService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private String getContentDisposition(String filename) {
|
private String getContentDisposition(String filename) {
|
||||||
Charset charset = filename.matches("\\p{ASCII}*") ?
|
Charset charset = ASCII_ONLY_PATTERN.matcher(filename).matches() ?
|
||||||
StandardCharsets.US_ASCII : StandardCharsets.UTF_8;
|
StandardCharsets.US_ASCII : StandardCharsets.UTF_8;
|
||||||
|
|
||||||
return ContentDisposition.builder("attachment")
|
return ContentDisposition.builder("attachment")
|
||||||
@@ -182,7 +185,7 @@ public class BookDownloadService {
|
|||||||
String bookTitle = bookEntity.getMetadata() != null && bookEntity.getMetadata().getTitle() != null
|
String bookTitle = bookEntity.getMetadata() != null && bookEntity.getMetadata().getTitle() != null
|
||||||
? bookEntity.getMetadata().getTitle()
|
? bookEntity.getMetadata().getTitle()
|
||||||
: "book-" + bookId;
|
: "book-" + bookId;
|
||||||
String safeTitle = bookTitle.replaceAll("[^a-zA-Z0-9\\-_]", "_");
|
String safeTitle = NON_ALPHANUMERIC_PATTERN.matcher(bookTitle).replaceAll("_");
|
||||||
String zipFileName = safeTitle + ".zip";
|
String zipFileName = safeTitle + ".zip";
|
||||||
|
|
||||||
response.setContentType("application/zip");
|
response.setContentType("application/zip");
|
||||||
|
|||||||
@@ -6,10 +6,14 @@ import org.booklore.model.entity.BookFileEntity;
|
|||||||
import org.booklore.model.enums.BookFileType;
|
import org.booklore.model.enums.BookFileType;
|
||||||
|
|
||||||
import java.net.URI;
|
import java.net.URI;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
@UtilityClass
|
@UtilityClass
|
||||||
class KoboEpubUtils {
|
class KoboEpubUtils {
|
||||||
|
|
||||||
|
private static final Pattern LEADING_SLASH_PATTERN = Pattern.compile("^/+");
|
||||||
|
private static final Pattern ANCHOR_PATTERN = Pattern.compile("#.*$");
|
||||||
|
|
||||||
static BookFileEntity getSyncedEpubFile(BookEntity book) {
|
static BookFileEntity getSyncedEpubFile(BookEntity book) {
|
||||||
BookFileEntity primaryFile = book != null ? book.getPrimaryBookFile() : null;
|
BookFileEntity primaryFile = book != null ? book.getPrimaryBookFile() : null;
|
||||||
if (primaryFile == null || primaryFile.getBookType() != BookFileType.EPUB) {
|
if (primaryFile == null || primaryFile.getBookType() != BookFileType.EPUB) {
|
||||||
@@ -23,7 +27,7 @@ class KoboEpubUtils {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
String normalizedPath = href.replaceFirst("#.*$", "")
|
String normalizedPath = ANCHOR_PATTERN.matcher(href).replaceFirst("")
|
||||||
.replace('\\', '/');
|
.replace('\\', '/');
|
||||||
try {
|
try {
|
||||||
String decodedPath = URI.create(normalizedPath).getPath();
|
String decodedPath = URI.create(normalizedPath).getPath();
|
||||||
@@ -39,7 +43,7 @@ class KoboEpubUtils {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
return decodedHref.replaceFirst("^/+", "");
|
return LEADING_SLASH_PATTERN.matcher(decodedHref).replaceFirst("");
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
+5
-2
@@ -32,12 +32,15 @@ import java.util.List;
|
|||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import java.util.logging.Level;
|
import java.util.logging.Level;
|
||||||
import java.util.logging.Logger;
|
import java.util.logging.Logger;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@Component
|
@Component
|
||||||
@AllArgsConstructor
|
@AllArgsConstructor
|
||||||
public class AudiobookMetadataExtractor implements FileMetadataExtractor {
|
public class AudiobookMetadataExtractor implements FileMetadataExtractor {
|
||||||
|
|
||||||
|
private static final Pattern CHAPTER_PATTERN = Pattern.compile("(?i)^(chp?|chapter)?\\d+$");
|
||||||
|
private static final Pattern NON_DIGIT_PATTERN = Pattern.compile("[^0-9]");
|
||||||
private final FfprobeService ffprobeService;
|
private final FfprobeService ffprobeService;
|
||||||
|
|
||||||
static {
|
static {
|
||||||
@@ -210,7 +213,7 @@ public class AudiobookMetadataExtractor implements FileMetadataExtractor {
|
|||||||
return 6;
|
return 6;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
return Integer.parseInt(channels.replaceAll("[^0-9]", ""));
|
return Integer.parseInt(NON_DIGIT_PATTERN.matcher(channels).replaceAll(""));
|
||||||
} catch (NumberFormatException e) {
|
} catch (NumberFormatException e) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -324,7 +327,7 @@ public class AudiobookMetadataExtractor implements FileMetadataExtractor {
|
|||||||
try {
|
try {
|
||||||
Object elementId = chapBody.getObjectValue("ElementID");
|
Object elementId = chapBody.getObjectValue("ElementID");
|
||||||
if (elementId instanceof String str && StringUtils.isNotBlank(str)) {
|
if (elementId instanceof String str && StringUtils.isNotBlank(str)) {
|
||||||
if (!str.matches("(?i)^(chp?|chapter)?\\d+$")) {
|
if (!CHAPTER_PATTERN.matcher(str).matches()) {
|
||||||
return str;
|
return str;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+6
-3
@@ -38,6 +38,9 @@ public class CbxMetadataExtractor implements FileMetadataExtractor {
|
|||||||
private static final Pattern COMICVINE_URL_PATTERN = Pattern.compile("comicvine\\.gamespot\\.com/(?:issue|volume)/(?:[^/]+/)?(\\d+-\\d+)");
|
private static final Pattern COMICVINE_URL_PATTERN = Pattern.compile("comicvine\\.gamespot\\.com/(?:issue|volume)/(?:[^/]+/)?(\\d+-\\d+)");
|
||||||
private static final Pattern COMICVINE_SITE_URL_PATTERN = Pattern.compile("comicvine\\.gamespot\\.com/(?:[^/]+/)?(40(?:00|50)-\\d+)/?");
|
private static final Pattern COMICVINE_SITE_URL_PATTERN = Pattern.compile("comicvine\\.gamespot\\.com/(?:[^/]+/)?(40(?:00|50)-\\d+)/?");
|
||||||
private static final Pattern HARDCOVER_URL_PATTERN = Pattern.compile("hardcover\\.app/books/([\\w-]+)");
|
private static final Pattern HARDCOVER_URL_PATTERN = Pattern.compile("hardcover\\.app/books/([\\w-]+)");
|
||||||
|
private static final Pattern BOOKLORE_TAG_PATTERN = Pattern.compile("\\[BookLore:[^\\]]+\\][^\\n]*(\n|$)");
|
||||||
|
private static final Pattern ISBN13_PATTERN = Pattern.compile("\\d{13}");
|
||||||
|
private static final Pattern ISBN_CLEANER_PATTERN = Pattern.compile("[- ]");
|
||||||
|
|
||||||
private final ArchiveService archiveService;
|
private final ArchiveService archiveService;
|
||||||
|
|
||||||
@@ -120,8 +123,8 @@ public class CbxMetadataExtractor implements FileMetadataExtractor {
|
|||||||
// Validate it's a 13-digit number (ISBN-13/EAN-13)
|
// Validate it's a 13-digit number (ISBN-13/EAN-13)
|
||||||
String gtin = getTextContent(document, "GTIN");
|
String gtin = getTextContent(document, "GTIN");
|
||||||
if (gtin != null && !gtin.isBlank()) {
|
if (gtin != null && !gtin.isBlank()) {
|
||||||
String normalized = gtin.replaceAll("[- ]", "");
|
String normalized = ISBN_CLEANER_PATTERN.matcher(gtin).replaceAll("");
|
||||||
if (normalized.matches("\\d{13}")) {
|
if (ISBN13_PATTERN.matcher(normalized).matches()) {
|
||||||
builder.isbn13(normalized);
|
builder.isbn13(normalized);
|
||||||
} else {
|
} else {
|
||||||
log.debug("Invalid GTIN format (expected 13 digits): {}", gtin);
|
log.debug("Invalid GTIN format (expected 13 digits): {}", gtin);
|
||||||
@@ -281,7 +284,7 @@ public class CbxMetadataExtractor implements FileMetadataExtractor {
|
|||||||
|
|
||||||
// If description is missing, use cleaned notes (removing BookLore tags)
|
// If description is missing, use cleaned notes (removing BookLore tags)
|
||||||
if (!hasDescription) {
|
if (!hasDescription) {
|
||||||
String cleanedNotes = notes.replaceAll("\\[BookLore:[^\\]]+\\][^\\n]*(\n|$)", "").trim();
|
String cleanedNotes = BOOKLORE_TAG_PATTERN.matcher(notes).replaceAll("").trim();
|
||||||
if (!cleanedNotes.isEmpty()) {
|
if (!cleanedNotes.isEmpty()) {
|
||||||
builder.description(cleanedNotes);
|
builder.description(cleanedNotes);
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-1
@@ -35,6 +35,7 @@ public class PdfMetadataExtractor implements FileMetadataExtractor {
|
|||||||
private static final Pattern ISO_DATE_PATTERN = Pattern.compile("\\d{4}-\\d{2}-\\d{2}");
|
private static final Pattern ISO_DATE_PATTERN = Pattern.compile("\\d{4}-\\d{2}-\\d{2}");
|
||||||
private static final Pattern PDF_DATE_TIME_PATTERN = Pattern.compile("\\d{8,}");
|
private static final Pattern PDF_DATE_TIME_PATTERN = Pattern.compile("\\d{8,}");
|
||||||
private static final Pattern YEAR_MONTH_PATTERN = Pattern.compile("\\d{6}");
|
private static final Pattern YEAR_MONTH_PATTERN = Pattern.compile("\\d{6}");
|
||||||
|
private static final Pattern YEAR_PATTERN = Pattern.compile("\\d{4}");
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public byte[] extractCover(File file) {
|
public byte[] extractCover(File file) {
|
||||||
@@ -551,7 +552,7 @@ public class PdfMetadataExtractor implements FileMetadataExtractor {
|
|||||||
1
|
1
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if (s.matches("\\d{4}")) {
|
if (YEAR_PATTERN.matcher(s).matches()) {
|
||||||
return LocalDate.of(Integer.parseInt(s.substring(0, 4)), 1, 1);
|
return LocalDate.of(Integer.parseInt(s.substring(0, 4)), 1, 1);
|
||||||
}
|
}
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
|
|||||||
@@ -41,6 +41,10 @@ public class GoogleParser implements BookParser {
|
|||||||
private static final int MAX_SEARCH_TERM_LENGTH = 60;
|
private static final int MAX_SEARCH_TERM_LENGTH = 60;
|
||||||
private static final int MAX_RESULTS = 20;
|
private static final int MAX_RESULTS = 20;
|
||||||
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
|
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
|
||||||
|
private static final Pattern ISO_DATE_PATTERN = Pattern.compile("\\d{4}-\\d{2}-\\d{2}");
|
||||||
|
private static final Pattern EDGE_CURL_PATTERN = Pattern.compile("&?edge=curl");
|
||||||
|
private static final Pattern ZOOM_PATTERN = Pattern.compile("zoom=\\d+");
|
||||||
|
private static final Pattern CATEGORY_SPLIT_PATTERN = Pattern.compile(" / ");
|
||||||
private final ObjectMapper objectMapper;
|
private final ObjectMapper objectMapper;
|
||||||
private final AppSettingService appSettingService;
|
private final AppSettingService appSettingService;
|
||||||
private final HttpClient httpClient;
|
private final HttpClient httpClient;
|
||||||
@@ -408,7 +412,7 @@ public class GoogleParser implements BookParser {
|
|||||||
.flatMap(cat -> {
|
.flatMap(cat -> {
|
||||||
// Split hierarchical categories (e.g., "Fiction / Fantasy / General")
|
// Split hierarchical categories (e.g., "Fiction / Fantasy / General")
|
||||||
if (cat.contains(" / ")) {
|
if (cat.contains(" / ")) {
|
||||||
return Arrays.stream(cat.split(" / "))
|
return Arrays.stream(CATEGORY_SPLIT_PATTERN.split(cat))
|
||||||
.map(String::trim)
|
.map(String::trim)
|
||||||
.filter(s -> !s.equalsIgnoreCase("General"));
|
.filter(s -> !s.equalsIgnoreCase("General"));
|
||||||
}
|
}
|
||||||
@@ -471,10 +475,10 @@ public class GoogleParser implements BookParser {
|
|||||||
imageUrl = imageUrl.replace("http://", "https://");
|
imageUrl = imageUrl.replace("http://", "https://");
|
||||||
|
|
||||||
if (imageUrl.contains("zoom=")) {
|
if (imageUrl.contains("zoom=")) {
|
||||||
imageUrl = imageUrl.replaceAll("zoom=\\d+", "zoom=0");
|
imageUrl = ZOOM_PATTERN.matcher(imageUrl).replaceAll("zoom=0");
|
||||||
}
|
}
|
||||||
|
|
||||||
imageUrl = imageUrl.replaceAll("&?edge=curl", "");
|
imageUrl = EDGE_CURL_PATTERN.matcher(imageUrl).replaceAll("");
|
||||||
|
|
||||||
return imageUrl;
|
return imageUrl;
|
||||||
}
|
}
|
||||||
@@ -540,7 +544,7 @@ public class GoogleParser implements BookParser {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
// Try full date format first (YYYY-MM-DD)
|
// Try full date format first (YYYY-MM-DD)
|
||||||
if (input.length() == 10 && input.matches("\\d{4}-\\d{2}-\\d{2}")) {
|
if (input.length() == 10 && ISO_DATE_PATTERN.matcher(input).matches()) {
|
||||||
return LocalDate.parse(input, DATE_FORMATTER);
|
return LocalDate.parse(input, DATE_FORMATTER);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -40,6 +40,7 @@ import java.nio.file.Files;
|
|||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
import java.nio.file.StandardCopyOption;
|
import java.nio.file.StandardCopyOption;
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
import java.util.zip.CRC32;
|
import java.util.zip.CRC32;
|
||||||
import java.util.zip.ZipEntry;
|
import java.util.zip.ZipEntry;
|
||||||
@@ -54,6 +55,7 @@ import org.grimmory.epub4j.archive.EpubContainers;
|
|||||||
public class EpubMetadataWriter implements MetadataWriter {
|
public class EpubMetadataWriter implements MetadataWriter {
|
||||||
|
|
||||||
private static final String OPF_NS = "http://www.idpf.org/2007/opf";
|
private static final String OPF_NS = "http://www.idpf.org/2007/opf";
|
||||||
|
private static final Pattern CALIBRE_PREFIX_PATTERN = Pattern.compile("calibre:\\s*https?://[^\\s]+");
|
||||||
private final AppSettingService appSettingService;
|
private final AppSettingService appSettingService;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -1111,7 +1113,7 @@ public class EpubMetadataWriter implements MetadataWriter {
|
|||||||
if (packageElement.hasAttribute("prefix")) {
|
if (packageElement.hasAttribute("prefix")) {
|
||||||
String prefix = packageElement.getAttribute("prefix");
|
String prefix = packageElement.getAttribute("prefix");
|
||||||
if (prefix.contains("calibre:")) {
|
if (prefix.contains("calibre:")) {
|
||||||
prefix = prefix.replaceAll("calibre:\\s*https?://[^\\s]+", "").trim();
|
prefix = CALIBRE_PREFIX_PATTERN.matcher(prefix).replaceAll("").trim();
|
||||||
if (prefix.isEmpty()) {
|
if (prefix.isEmpty()) {
|
||||||
packageElement.removeAttribute("prefix");
|
packageElement.removeAttribute("prefix");
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -23,12 +23,17 @@ import java.nio.file.StandardCopyOption;
|
|||||||
import java.time.ZonedDateTime;
|
import java.time.ZonedDateTime;
|
||||||
import java.time.format.DateTimeFormatter;
|
import java.time.format.DateTimeFormatter;
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@Component
|
@Component
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
public class PdfMetadataWriter implements MetadataWriter {
|
public class PdfMetadataWriter implements MetadataWriter {
|
||||||
|
|
||||||
|
private static final Pattern NUMERIC_PATTERN = Pattern.compile("\\d+");
|
||||||
|
private static final Pattern TRAILING_DOT_PATTERN = Pattern.compile("\\.$");
|
||||||
|
private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\s+");
|
||||||
|
private static final Pattern TRAILING_ZEROS_PATTERN = Pattern.compile("0+$");
|
||||||
private final AppSettingService appSettingService;
|
private final AppSettingService appSettingService;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -189,7 +194,7 @@ public class PdfMetadataWriter implements MetadataWriter {
|
|||||||
helper.copyAuthors(clear != null && clear.isAuthors(), a -> {
|
helper.copyAuthors(clear != null && clear.isAuthors(), a -> {
|
||||||
if (a != null && !a.isEmpty()) {
|
if (a != null && !a.isEmpty()) {
|
||||||
authors[0] = a.stream()
|
authors[0] = a.stream()
|
||||||
.map(name -> name.replaceAll("\\s+", " ").trim())
|
.map(name -> WHITESPACE_PATTERN.matcher(name).replaceAll(" ").trim())
|
||||||
.filter(name -> !name.isBlank())
|
.filter(name -> !name.isBlank())
|
||||||
.toList();
|
.toList();
|
||||||
}
|
}
|
||||||
@@ -406,7 +411,7 @@ public class PdfMetadataWriter implements MetadataWriter {
|
|||||||
// For decimals, show up to 2 decimal places but trim trailing zeros
|
// For decimals, show up to 2 decimal places but trim trailing zeros
|
||||||
String formatted = String.format(Locale.US, "%.2f", number);
|
String formatted = String.format(Locale.US, "%.2f", number);
|
||||||
// Remove trailing zeros after decimal point: "1.50" -> "1.5"
|
// Remove trailing zeros after decimal point: "1.50" -> "1.5"
|
||||||
formatted = formatted.replaceAll("0+$", "").replaceAll("\\.$", "");
|
formatted = TRAILING_DOT_PATTERN.matcher(TRAILING_ZEROS_PATTERN.matcher(formatted).replaceAll("")).replaceAll("");
|
||||||
return formatted;
|
return formatted;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -427,7 +432,7 @@ public class PdfMetadataWriter implements MetadataWriter {
|
|||||||
if (sep < 0) sep = goodreadsId.indexOf('.');
|
if (sep < 0) sep = goodreadsId.indexOf('.');
|
||||||
if (sep > 0) {
|
if (sep > 0) {
|
||||||
String numericPart = goodreadsId.substring(0, sep);
|
String numericPart = goodreadsId.substring(0, sep);
|
||||||
if (numericPart.matches("\\d+")) {
|
if (NUMERIC_PATTERN.matcher(numericPart).matches()) {
|
||||||
return numericPart;
|
return numericPart;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,8 @@ import java.nio.file.Path;
|
|||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Locale;
|
import java.util.Locale;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.booklore.model.dto.AudiobookMetadata;
|
import org.booklore.model.dto.AudiobookMetadata;
|
||||||
@@ -31,6 +33,7 @@ import org.springframework.transaction.annotation.Transactional;
|
|||||||
@Transactional
|
@Transactional
|
||||||
public class AudioMetadataService {
|
public class AudioMetadataService {
|
||||||
|
|
||||||
|
private static final Pattern NON_DIGIT_PATTERN = Pattern.compile("[^0-9]");
|
||||||
private final AudioFileUtilityService audioFileUtility;
|
private final AudioFileUtilityService audioFileUtility;
|
||||||
private final AudiobookMetadataExtractor audiobookMetadataExtractor;
|
private final AudiobookMetadataExtractor audiobookMetadataExtractor;
|
||||||
private final BookFileRepository bookFileRepository;
|
private final BookFileRepository bookFileRepository;
|
||||||
@@ -382,7 +385,7 @@ public class AudioMetadataService {
|
|||||||
if (channels.toLowerCase(Locale.ROOT).contains("stereo")) return 2;
|
if (channels.toLowerCase(Locale.ROOT).contains("stereo")) return 2;
|
||||||
if (channels.toLowerCase(Locale.ROOT).contains("mono")) return 1;
|
if (channels.toLowerCase(Locale.ROOT).contains("mono")) return 1;
|
||||||
try {
|
try {
|
||||||
return Integer.parseInt(channels.replaceAll("[^0-9]", ""));
|
return Integer.parseInt(NON_DIGIT_PATTERN.matcher(channels).replaceAll(""));
|
||||||
} catch (NumberFormatException e) {
|
} catch (NumberFormatException e) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,11 +23,13 @@ import java.time.Duration;
|
|||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@Service
|
@Service
|
||||||
public class EpubCfiService {
|
public class EpubCfiService {
|
||||||
|
|
||||||
|
private static final Pattern CFI_CLEANER_PATTERN = Pattern.compile("!/4(?=/)");
|
||||||
private final Cache<String, Document> documentCache;
|
private final Cache<String, Document> documentCache;
|
||||||
|
|
||||||
public EpubCfiService() {
|
public EpubCfiService() {
|
||||||
@@ -193,7 +195,7 @@ public class EpubCfiService {
|
|||||||
if (cfi == null) {
|
if (cfi == null) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
return cfi.replaceFirst("!/4(?=/)", "!");
|
return CFI_CLEANER_PATTERN.matcher(cfi).replaceFirst("!");
|
||||||
}
|
}
|
||||||
|
|
||||||
private Integer resolveSourceOffset(Document document, CfiExpression expression) {
|
private Integer resolveSourceOffset(Document document, CfiExpression expression) {
|
||||||
|
|||||||
+3
-1
@@ -23,6 +23,7 @@ import java.time.LocalDate;
|
|||||||
import java.util.Comparator;
|
import java.util.Comparator;
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
import java.util.zip.ZipEntry;
|
import java.util.zip.ZipEntry;
|
||||||
import java.util.zip.ZipFile;
|
import java.util.zip.ZipFile;
|
||||||
import java.util.zip.ZipOutputStream;
|
import java.util.zip.ZipOutputStream;
|
||||||
@@ -33,6 +34,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
|
|||||||
@EnabledIf("org.booklore.service.ArchiveService#isAvailable")
|
@EnabledIf("org.booklore.service.ArchiveService#isAvailable")
|
||||||
class CbxComicInfoComplianceTest {
|
class CbxComicInfoComplianceTest {
|
||||||
|
|
||||||
|
private static final Pattern EMPTY_LINES_PATTERN = Pattern.compile("(?s).*\\n\\s*\\n\\s*<.*");
|
||||||
private CbxMetadataWriter writer;
|
private CbxMetadataWriter writer;
|
||||||
private Path tempDir;
|
private Path tempDir;
|
||||||
|
|
||||||
@@ -117,7 +119,7 @@ class CbxComicInfoComplianceTest {
|
|||||||
assertOrder(xmlContent, "Web", "PageCount");
|
assertOrder(xmlContent, "Web", "PageCount");
|
||||||
|
|
||||||
// 2. Verify Formatting
|
// 2. Verify Formatting
|
||||||
assertFalse(xmlContent.matches("(?s).*\\n\\s*\\n\\s*<.*"), "Should not have empty lines between elements");
|
assertFalse(EMPTY_LINES_PATTERN.matcher(xmlContent).matches(), "Should not have empty lines between elements");
|
||||||
|
|
||||||
// 3. Verify HTML Stripping in Summary
|
// 3. Verify HTML Stripping in Summary
|
||||||
assertTrue(xmlContent.contains("<Summary>On his own and out of options, Hughie resorts to extreme measures...</Summary>"));
|
assertTrue(xmlContent.contains("<Summary>On his own and out of options, Hughie resorts to extreme measures...</Summary>"));
|
||||||
|
|||||||
Reference in New Issue
Block a user