feat(pdf): integrate PDFium4j for PDF processing and metadata extraction (#281)
* feat(pdf): integrate PDFium4j for PDF processing and metadata extraction * feat(pdf): update PDFium4j to version 0.12.0 and optimize XMP metadata handling * feat(pdf): update PDFium4j to version 0.13.0 * feat(pdf): enhance cross-compilation support and improve XML parsing in metadata extraction * Delete dev.local-libs.docker-compose.yml * feat(pdf): update PDFium4j to version 0.14.0
This commit is contained in:
+3
-1
@@ -16,6 +16,8 @@ RUN --mount=type=cache,target=/workspace/.yarn/cache \
|
|||||||
|
|
||||||
FROM --platform=$BUILDPLATFORM gradle:9.3.1-jdk25-alpine AS backend-build
|
FROM --platform=$BUILDPLATFORM gradle:9.3.1-jdk25-alpine AS backend-build
|
||||||
|
|
||||||
|
ARG TARGETARCH
|
||||||
|
|
||||||
WORKDIR /workspace/booklore-api
|
WORKDIR /workspace/booklore-api
|
||||||
|
|
||||||
COPY booklore-api/gradlew booklore-api/gradlew.bat booklore-api/build.gradle.kts booklore-api/settings.gradle.kts ./
|
COPY booklore-api/gradlew booklore-api/gradlew.bat booklore-api/build.gradle.kts booklore-api/settings.gradle.kts ./
|
||||||
@@ -29,7 +31,7 @@ COPY booklore-api/ ./
|
|||||||
COPY --from=frontend-build /workspace/frontend/dist/grimmory/browser /tmp/frontend-dist
|
COPY --from=frontend-build /workspace/frontend/dist/grimmory/browser /tmp/frontend-dist
|
||||||
|
|
||||||
RUN --mount=type=cache,target=/home/gradle/.gradle \
|
RUN --mount=type=cache,target=/home/gradle/.gradle \
|
||||||
./gradlew --no-daemon -PfrontendDistDir=/tmp/frontend-dist bootJar
|
TARGETARCH=${TARGETARCH} ./gradlew --no-daemon -PfrontendDistDir=/tmp/frontend-dist bootJar
|
||||||
|
|
||||||
RUN set -eux; \
|
RUN set -eux; \
|
||||||
jar_path="$(find build/libs -maxdepth 1 -name '*.jar' ! -name '*plain.jar' | head -n 1)"; \
|
jar_path="$(find build/libs -maxdepth 1 -name '*.jar' ! -name '*plain.jar' | head -n 1)"; \
|
||||||
|
|||||||
@@ -26,11 +26,60 @@ java {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
val useLocalLibs = providers.gradleProperty("useLocalLibs").isPresent
|
||||||
|
|
||||||
repositories {
|
repositories {
|
||||||
|
if (useLocalLibs) mavenLocal()
|
||||||
mavenCentral()
|
mavenCentral()
|
||||||
maven(url = "https://jitpack.io")
|
maven(url = "https://jitpack.io")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun pdfiumNativesClassifier(): String {
|
||||||
|
// Support cross-compilation: check for explicit target overrides first
|
||||||
|
val targetPlatform = System.getenv("TARGETPLATFORM")
|
||||||
|
?: project.findProperty("targetPlatform")?.toString()
|
||||||
|
val targetArch = System.getenv("TARGETARCH")
|
||||||
|
?: project.findProperty("targetArch")?.toString()
|
||||||
|
|
||||||
|
val osName: String
|
||||||
|
val arch: String
|
||||||
|
|
||||||
|
if (targetPlatform != null) {
|
||||||
|
// Docker TARGETPLATFORM format: linux/amd64, linux/arm64
|
||||||
|
val parts = targetPlatform.split("/")
|
||||||
|
osName = parts.getOrElse(0) { "linux" }
|
||||||
|
arch = parts.getOrElse(1) { "amd64" }
|
||||||
|
} else {
|
||||||
|
osName = System.getProperty("os.name").lowercase()
|
||||||
|
arch = targetArch ?: System.getProperty("os.arch").lowercase()
|
||||||
|
}
|
||||||
|
|
||||||
|
val osKey = when {
|
||||||
|
"win" in osName -> "windows"
|
||||||
|
"mac" in osName || "darwin" in osName -> "darwin"
|
||||||
|
"nux" in osName || "linux" in osName -> {
|
||||||
|
val isMusl = try {
|
||||||
|
val libDir = File("/lib")
|
||||||
|
libDir.exists() && (libDir.listFiles()?.any { f -> f.name.startsWith("ld-musl-") } == true)
|
||||||
|
} catch (_: Exception) {
|
||||||
|
try {
|
||||||
|
File("/proc/self/maps").readText().contains("musl")
|
||||||
|
} catch (_: Exception) { false }
|
||||||
|
}
|
||||||
|
if (isMusl) "linux-musl" else "linux"
|
||||||
|
}
|
||||||
|
else -> error("Unsupported OS: $osName")
|
||||||
|
}
|
||||||
|
|
||||||
|
val archKey = when (arch) {
|
||||||
|
"x86_64", "amd64" -> "x64"
|
||||||
|
"aarch64", "arm64" -> "arm64"
|
||||||
|
else -> error("Unsupported architecture: $arch")
|
||||||
|
}
|
||||||
|
|
||||||
|
return "natives-$osKey-$archKey"
|
||||||
|
}
|
||||||
|
|
||||||
configurations {
|
configurations {
|
||||||
compileOnly {
|
compileOnly {
|
||||||
extendsFrom(configurations.annotationProcessor.get())
|
extendsFrom(configurations.annotationProcessor.get())
|
||||||
@@ -67,13 +116,9 @@ dependencies {
|
|||||||
annotationProcessor("org.projectlombok:lombok:1.18.44")
|
annotationProcessor("org.projectlombok:lombok:1.18.44")
|
||||||
|
|
||||||
// --- Book & Image Processing ---
|
// --- Book & Image Processing ---
|
||||||
implementation("org.apache.pdfbox:pdfbox:3.0.7")
|
val pdfium4jVersion = if (useLocalLibs) "+" else "0.14.0"
|
||||||
implementation("org.apache.pdfbox:pdfbox-io:3.0.7")
|
implementation("org.grimmory:pdfium4j:$pdfium4jVersion")
|
||||||
implementation("org.apache.pdfbox:xmpbox:3.0.7")
|
runtimeOnly("org.grimmory:pdfium4j:$pdfium4jVersion:${pdfiumNativesClassifier()}")
|
||||||
implementation("org.apache.pdfbox:jbig2-imageio:3.0.4")
|
|
||||||
// Required for JPEG2000 support in PDFBox (not covered by TwelveMonkeys)
|
|
||||||
implementation("com.github.jai-imageio:jai-imageio-core:1.4.0")
|
|
||||||
implementation("com.github.jai-imageio:jai-imageio-jpeg2000:1.4.0")
|
|
||||||
|
|
||||||
// --- TwelveMonkeys ImageIO ---
|
// --- TwelveMonkeys ImageIO ---
|
||||||
implementation("com.twelvemonkeys.imageio:imageio-jpeg:3.13.1")
|
implementation("com.twelvemonkeys.imageio:imageio-jpeg:3.13.1")
|
||||||
@@ -81,7 +126,9 @@ dependencies {
|
|||||||
implementation("com.twelvemonkeys.imageio:imageio-webp:3.13.1")
|
implementation("com.twelvemonkeys.imageio:imageio-webp:3.13.1")
|
||||||
implementation("com.twelvemonkeys.imageio:imageio-bmp:3.13.1")
|
implementation("com.twelvemonkeys.imageio:imageio-bmp:3.13.1")
|
||||||
|
|
||||||
implementation("io.documentnode:epub4j-core:4.2.3")
|
// epub4j-grimmory fork publishes as org.grimmory:epub4j-core
|
||||||
|
val epub4jCoords = if (useLocalLibs) "org.grimmory:epub4j-core:+" else "io.documentnode:epub4j-core:4.2.3"
|
||||||
|
implementation(epub4jCoords)
|
||||||
|
|
||||||
// --- Audio Metadata (Audiobook Support) ---
|
// --- Audio Metadata (Audiobook Support) ---
|
||||||
implementation("com.github.RouHim:jaudiotagger:2.0.19")
|
implementation("com.github.RouHim:jaudiotagger:2.0.19")
|
||||||
@@ -129,6 +176,9 @@ dependencies {
|
|||||||
testImplementation("org.assertj:assertj-core:3.27.7")
|
testImplementation("org.assertj:assertj-core:3.27.7")
|
||||||
testImplementation("org.mockito:mockito-inline:5.2.0")
|
testImplementation("org.mockito:mockito-inline:5.2.0")
|
||||||
testRuntimeOnly("com.h2database:h2")
|
testRuntimeOnly("com.h2database:h2")
|
||||||
|
|
||||||
|
// PDFBox for test PDF creation only (production code uses PDFium4j)
|
||||||
|
testImplementation("org.apache.pdfbox:pdfbox:3.0.7")
|
||||||
}
|
}
|
||||||
|
|
||||||
hibernate {
|
hibernate {
|
||||||
@@ -169,6 +219,7 @@ tasks.named<Copy>("processResources") {
|
|||||||
}
|
}
|
||||||
|
|
||||||
tasks.named<BootRun>("bootRun") {
|
tasks.named<BootRun>("bootRun") {
|
||||||
|
jvmArgs("--enable-native-access=ALL-UNNAMED")
|
||||||
if (System.getenv("REMOTE_DEBUG_ENABLED") == "true") {
|
if (System.getenv("REMOTE_DEBUG_ENABLED") == "true") {
|
||||||
jvmArgs("-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005")
|
jvmArgs("-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,11 +2,8 @@ package org.booklore.service.fileprocessor;
|
|||||||
|
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.apache.commons.lang3.StringUtils;
|
import org.apache.commons.lang3.StringUtils;
|
||||||
import org.apache.pdfbox.Loader;
|
import org.grimmory.pdfium4j.PdfDocument;
|
||||||
import org.apache.pdfbox.io.RandomAccessReadBufferedFile;
|
import org.grimmory.pdfium4j.PdfPage;
|
||||||
import org.apache.pdfbox.pdmodel.PDDocument;
|
|
||||||
import org.apache.pdfbox.rendering.ImageType;
|
|
||||||
import org.apache.pdfbox.rendering.PDFRenderer;
|
|
||||||
import org.booklore.mapper.BookMapper;
|
import org.booklore.mapper.BookMapper;
|
||||||
import org.booklore.model.dto.BookMetadata;
|
import org.booklore.model.dto.BookMetadata;
|
||||||
import org.booklore.model.dto.settings.LibraryFile;
|
import org.booklore.model.dto.settings.LibraryFile;
|
||||||
@@ -75,9 +72,8 @@ public class PdfProcessor extends AbstractFileProcessor implements BookFileProce
|
|||||||
@Override
|
@Override
|
||||||
public boolean generateCover(BookEntity bookEntity, BookFileEntity bookFile) {
|
public boolean generateCover(BookEntity bookEntity, BookFileEntity bookFile) {
|
||||||
File pdfFile = FileUtils.getBookFullPath(bookEntity, bookFile).toFile();
|
File pdfFile = FileUtils.getBookFullPath(bookEntity, bookFile).toFile();
|
||||||
try (RandomAccessReadBufferedFile randomAccessRead = new RandomAccessReadBufferedFile(pdfFile);
|
try (PdfDocument doc = PdfDocument.open(pdfFile.toPath())) {
|
||||||
PDDocument pdf = Loader.loadPDF(randomAccessRead)) {
|
return generateCoverImageAndSave(bookEntity.getId(), doc);
|
||||||
return generateCoverImageAndSave(bookEntity.getId(), pdf);
|
|
||||||
} catch (OutOfMemoryError e) {
|
} catch (OutOfMemoryError e) {
|
||||||
// Note: Catching OOM is generally discouraged, but for batch processing
|
// Note: Catching OOM is generally discouraged, but for batch processing
|
||||||
// of potentially large/corrupted PDFs, we prefer graceful degradation
|
// of potentially large/corrupted PDFs, we prefer graceful degradation
|
||||||
@@ -208,10 +204,10 @@ public class PdfProcessor extends AbstractFileProcessor implements BookFileProce
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean generateCoverImageAndSave(Long bookId, PDDocument document) throws IOException {
|
private boolean generateCoverImageAndSave(Long bookId, PdfDocument doc) throws IOException {
|
||||||
BufferedImage coverImage = null;
|
BufferedImage coverImage = null;
|
||||||
try {
|
try (PdfPage page = doc.page(0)) {
|
||||||
coverImage = new PDFRenderer(document).renderImageWithDPI(0, 150, ImageType.RGB);
|
coverImage = page.render(150).toBufferedImage();
|
||||||
return fileService.saveCoverImages(coverImage, bookId);
|
return fileService.saveCoverImages(coverImage, bookId);
|
||||||
} catch (OutOfMemoryError e) {
|
} catch (OutOfMemoryError e) {
|
||||||
log.error("Out of memory (heap space exhausted) while generating cover for bookId {}. Skipping cover generation.", bookId);
|
log.error("Out of memory (heap space exhausted) while generating cover for bookId {}. Skipping cover generation.", bookId);
|
||||||
|
|||||||
+2
-5
@@ -11,7 +11,6 @@ import org.w3c.dom.Node;
|
|||||||
import org.w3c.dom.NodeList;
|
import org.w3c.dom.NodeList;
|
||||||
|
|
||||||
import javax.xml.parsers.DocumentBuilder;
|
import javax.xml.parsers.DocumentBuilder;
|
||||||
import javax.xml.parsers.DocumentBuilderFactory;
|
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
import java.io.FileInputStream;
|
import java.io.FileInputStream;
|
||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
@@ -39,8 +38,7 @@ public class Fb2MetadataExtractor implements FileMetadataExtractor {
|
|||||||
@Override
|
@Override
|
||||||
public byte[] extractCover(File file) {
|
public byte[] extractCover(File file) {
|
||||||
try (InputStream inputStream = getInputStream(file)) {
|
try (InputStream inputStream = getInputStream(file)) {
|
||||||
DocumentBuilderFactory dbf = SecureXmlUtils.createSecureDocumentBuilderFactory(true);
|
DocumentBuilder builder = SecureXmlUtils.createSecureDocumentBuilder(true);
|
||||||
DocumentBuilder builder = dbf.newDocumentBuilder();
|
|
||||||
Document doc = builder.parse(inputStream);
|
Document doc = builder.parse(inputStream);
|
||||||
|
|
||||||
// Look for cover image in binary elements
|
// Look for cover image in binary elements
|
||||||
@@ -93,8 +91,7 @@ public class Fb2MetadataExtractor implements FileMetadataExtractor {
|
|||||||
@Override
|
@Override
|
||||||
public BookMetadata extractMetadata(File file) {
|
public BookMetadata extractMetadata(File file) {
|
||||||
try (InputStream inputStream = getInputStream(file)) {
|
try (InputStream inputStream = getInputStream(file)) {
|
||||||
DocumentBuilderFactory dbf = SecureXmlUtils.createSecureDocumentBuilderFactory(true);
|
DocumentBuilder builder = SecureXmlUtils.createSecureDocumentBuilder(true);
|
||||||
DocumentBuilder builder = dbf.newDocumentBuilder();
|
|
||||||
Document doc = builder.parse(inputStream);
|
Document doc = builder.parse(inputStream);
|
||||||
|
|
||||||
BookMetadata.BookMetadataBuilder metadataBuilder = BookMetadata.builder();
|
BookMetadata.BookMetadataBuilder metadataBuilder = BookMetadata.builder();
|
||||||
|
|||||||
+185
-181
@@ -2,38 +2,25 @@ package org.booklore.service.metadata.extractor;
|
|||||||
|
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.apache.commons.io.FilenameUtils;
|
import org.apache.commons.io.FilenameUtils;
|
||||||
import org.apache.commons.io.IOUtils;
|
|
||||||
import org.apache.commons.lang3.StringUtils;
|
import org.apache.commons.lang3.StringUtils;
|
||||||
import org.apache.pdfbox.Loader;
|
import org.grimmory.pdfium4j.PdfDocument;
|
||||||
import org.apache.pdfbox.cos.COSDictionary;
|
import org.grimmory.pdfium4j.model.MetadataTag;
|
||||||
import org.apache.pdfbox.cos.COSName;
|
|
||||||
import org.apache.pdfbox.io.RandomAccessReadBufferedFile;
|
|
||||||
import org.apache.pdfbox.pdmodel.PDDocument;
|
|
||||||
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
|
|
||||||
import org.apache.pdfbox.pdmodel.common.PDMetadata;
|
|
||||||
import org.apache.pdfbox.rendering.ImageType;
|
|
||||||
import org.apache.pdfbox.rendering.PDFRenderer;
|
|
||||||
import org.booklore.model.dto.BookMetadata;
|
import org.booklore.model.dto.BookMetadata;
|
||||||
import org.booklore.util.SecureXmlUtils;
|
import org.booklore.util.SecureXmlUtils;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
import org.w3c.dom.Document;
|
import org.w3c.dom.Document;
|
||||||
import org.w3c.dom.NodeList;
|
import org.w3c.dom.NodeList;
|
||||||
|
import org.xml.sax.InputSource;
|
||||||
|
|
||||||
import javax.imageio.ImageIO;
|
|
||||||
import javax.xml.namespace.NamespaceContext;
|
import javax.xml.namespace.NamespaceContext;
|
||||||
import javax.xml.parsers.DocumentBuilder;
|
import javax.xml.parsers.DocumentBuilder;
|
||||||
import javax.xml.xpath.XPath;
|
import javax.xml.xpath.XPath;
|
||||||
import javax.xml.xpath.XPathConstants;
|
import javax.xml.xpath.XPathConstants;
|
||||||
import javax.xml.xpath.XPathExpressionException;
|
import javax.xml.xpath.XPathExpressionException;
|
||||||
import javax.xml.xpath.XPathFactory;
|
import javax.xml.xpath.XPathFactory;
|
||||||
import java.awt.image.BufferedImage;
|
|
||||||
import java.io.ByteArrayInputStream;
|
|
||||||
import java.io.ByteArrayOutputStream;
|
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
import java.io.InputStream;
|
import java.io.StringReader;
|
||||||
import java.nio.charset.StandardCharsets;
|
|
||||||
import java.time.LocalDate;
|
import java.time.LocalDate;
|
||||||
import java.time.ZoneId;
|
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
import java.util.regex.Pattern;
|
import java.util.regex.Pattern;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
@@ -45,24 +32,17 @@ public class PdfMetadataExtractor implements FileMetadataExtractor {
|
|||||||
|
|
||||||
private static final Pattern COMMA_AMPERSAND_PATTERN = Pattern.compile("[,&]");
|
private static final Pattern COMMA_AMPERSAND_PATTERN = Pattern.compile("[,&]");
|
||||||
private static final Pattern ISBN_CLEANUP_PATTERN = Pattern.compile("[^0-9Xx]");
|
private static final Pattern ISBN_CLEANUP_PATTERN = Pattern.compile("[^0-9Xx]");
|
||||||
|
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 YEAR_MONTH_PATTERN = Pattern.compile("\\d{6}");
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public byte[] extractCover(File file) {
|
public byte[] extractCover(File file) {
|
||||||
BufferedImage coverImage = null;
|
try (PdfDocument doc = PdfDocument.open(file.toPath())) {
|
||||||
try (RandomAccessReadBufferedFile randomAccessRead = new RandomAccessReadBufferedFile(file);
|
return doc.renderPageToBytes(0, 300, "jpeg");
|
||||||
PDDocument pdf = Loader.loadPDF(randomAccessRead)) {
|
|
||||||
coverImage = new PDFRenderer(pdf).renderImageWithDPI(0, 300, ImageType.RGB);
|
|
||||||
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
|
|
||||||
ImageIO.write(coverImage, "jpg", baos);
|
|
||||||
return baos.toByteArray();
|
|
||||||
}
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.warn("Failed to extract cover from PDF: {}", file.getAbsolutePath(), e);
|
log.warn("Failed to extract cover from PDF: {}", file.getAbsolutePath(), e);
|
||||||
return null;
|
return null;
|
||||||
} finally {
|
|
||||||
if (coverImage != null) {
|
|
||||||
coverImage.flush(); // Release native resources
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -75,168 +55,158 @@ public class PdfMetadataExtractor implements FileMetadataExtractor {
|
|||||||
|
|
||||||
BookMetadata.BookMetadataBuilder metadataBuilder = BookMetadata.builder();
|
BookMetadata.BookMetadataBuilder metadataBuilder = BookMetadata.builder();
|
||||||
|
|
||||||
try (RandomAccessReadBufferedFile randomAccessRead = new RandomAccessReadBufferedFile(file);
|
try (PdfDocument doc = PdfDocument.open(file.toPath())) {
|
||||||
PDDocument pdf = Loader.loadPDF(randomAccessRead)) {
|
|
||||||
PDDocumentInformation info = pdf.getDocumentInformation();
|
|
||||||
|
|
||||||
if (info != null) {
|
String title = doc.metadata(MetadataTag.TITLE).orElse(null);
|
||||||
if (StringUtils.isNotBlank(info.getTitle())) {
|
if (StringUtils.isNotBlank(title)) {
|
||||||
metadataBuilder.title(info.getTitle());
|
metadataBuilder.title(title);
|
||||||
} else {
|
} else {
|
||||||
metadataBuilder.title(FilenameUtils.getBaseName(file.getName()));
|
metadataBuilder.title(FilenameUtils.getBaseName(file.getName()));
|
||||||
}
|
}
|
||||||
|
|
||||||
if (StringUtils.isNotBlank(info.getAuthor())) {
|
String author = doc.metadata(MetadataTag.AUTHOR).orElse(null);
|
||||||
List<String> authors = parseAuthors(info.getAuthor());
|
if (StringUtils.isNotBlank(author)) {
|
||||||
if (!authors.isEmpty()) {
|
List<String> authors = parseAuthors(author);
|
||||||
metadataBuilder.authors(authors);
|
if (!authors.isEmpty()) {
|
||||||
}
|
metadataBuilder.authors(authors);
|
||||||
}
|
|
||||||
|
|
||||||
if (StringUtils.isNotBlank(info.getSubject())) {
|
|
||||||
metadataBuilder.description(info.getSubject());
|
|
||||||
}
|
|
||||||
|
|
||||||
COSDictionary cosDict = info.getCOSObject();
|
|
||||||
if (cosDict != null && cosDict.containsKey(COSName.getPDFName("EBX_PUBLISHER"))) {
|
|
||||||
String ebxPublisher = cosDict.getString(COSName.getPDFName("EBX_PUBLISHER"));
|
|
||||||
if (StringUtils.isNotBlank(ebxPublisher)) {
|
|
||||||
metadataBuilder.publisher(ebxPublisher);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (info.getCreationDate() != null) {
|
|
||||||
LocalDate createdDate = convertCalendarToLocalDate(info.getCreationDate());
|
|
||||||
if (createdDate != null) {
|
|
||||||
metadataBuilder.publishedDate(createdDate);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
metadataBuilder.pageCount(pdf.getNumberOfPages());
|
|
||||||
|
|
||||||
if (StringUtils.isNotBlank(info.getKeywords())) {
|
|
||||||
String keywords = info.getKeywords();
|
|
||||||
String[] parts;
|
|
||||||
if (keywords.contains(";")) {
|
|
||||||
parts = keywords.split(";");
|
|
||||||
} else {
|
|
||||||
parts = keywords.split(",");
|
|
||||||
}
|
|
||||||
Set<String> categories = Arrays.stream(parts)
|
|
||||||
.map(String::trim)
|
|
||||||
.filter(StringUtils::isNotBlank)
|
|
||||||
.collect(Collectors.toSet());
|
|
||||||
if (!categories.isEmpty()) {
|
|
||||||
metadataBuilder.categories(categories);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
String languageValue = info.getCustomMetadataValue("Language");
|
|
||||||
if (StringUtils.isNotBlank(languageValue)) {
|
|
||||||
metadataBuilder.language(languageValue);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
PDMetadata metadata = pdf.getDocumentCatalog().getMetadata();
|
String subject = doc.metadata(MetadataTag.SUBJECT).orElse(null);
|
||||||
|
if (StringUtils.isNotBlank(subject)) {
|
||||||
|
metadataBuilder.description(subject);
|
||||||
|
}
|
||||||
|
|
||||||
if (metadata != null) {
|
String ebxPublisher = doc.metadata("EBX_PUBLISHER").orElse(null);
|
||||||
try (InputStream is = metadata.createInputStream()) {
|
if (StringUtils.isNotBlank(ebxPublisher)) {
|
||||||
if (is == null) {
|
metadataBuilder.publisher(ebxPublisher);
|
||||||
log.warn("PDMetadata InputStream is null");
|
}
|
||||||
} else {
|
|
||||||
String rawXmp = IOUtils.toString(is, StandardCharsets.UTF_8);
|
|
||||||
if (StringUtils.isNotBlank(rawXmp)) {
|
|
||||||
DocumentBuilder dBuilder = SecureXmlUtils.createSecureDocumentBuilder(true);
|
|
||||||
Document doc = dBuilder.parse(new ByteArrayInputStream(rawXmp.getBytes(StandardCharsets.UTF_8)));
|
|
||||||
|
|
||||||
XPathFactory xPathfactory = XPathFactory.newInstance();
|
String creationDate = doc.metadata(MetadataTag.CREATION_DATE).orElse(null);
|
||||||
XPath xpath = xPathfactory.newXPath();
|
if (StringUtils.isNotBlank(creationDate)) {
|
||||||
xpath.setNamespaceContext(new XmpNamespaceContext());
|
LocalDate date = parsePdfDate(creationDate);
|
||||||
|
if (date != null) {
|
||||||
|
metadataBuilder.publishedDate(date);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
extractDublinCoreMetadata(xpath, doc, metadataBuilder);
|
metadataBuilder.pageCount(doc.pageCount());
|
||||||
extractCalibreMetadata(xpath, doc, metadataBuilder);
|
|
||||||
extractBookloreMetadata(xpath, doc, metadataBuilder);
|
|
||||||
|
|
||||||
// Debug logging for troubleshooting extraction issues
|
String keywords = doc.metadata(MetadataTag.KEYWORDS).orElse(null);
|
||||||
if (log.isDebugEnabled()) {
|
if (StringUtils.isNotBlank(keywords)) {
|
||||||
BookMetadata debugMeta = metadataBuilder.build();
|
String[] parts;
|
||||||
log.debug("PDF XMP extraction results - subtitle: '{}', moods: {}, tags: {}",
|
if (keywords.contains(";")) {
|
||||||
debugMeta.getSubtitle(), debugMeta.getMoods(), debugMeta.getTags());
|
parts = keywords.split(";");
|
||||||
|
} else {
|
||||||
|
parts = keywords.split(",");
|
||||||
|
}
|
||||||
|
Set<String> categories = Arrays.stream(parts)
|
||||||
|
.map(String::trim)
|
||||||
|
.filter(StringUtils::isNotBlank)
|
||||||
|
.collect(java.util.stream.Collectors.toSet());
|
||||||
|
if (!categories.isEmpty()) {
|
||||||
|
metadataBuilder.categories(categories);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
String languageValue = doc.metadata("Language").orElse(null);
|
||||||
|
if (StringUtils.isNotBlank(languageValue)) {
|
||||||
|
metadataBuilder.language(languageValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
String rawXmp = doc.xmpMetadataString();
|
||||||
|
|
||||||
|
if (StringUtils.isNotBlank(rawXmp)) {
|
||||||
|
try {
|
||||||
|
DocumentBuilder dBuilder = SecureXmlUtils.createSecureDocumentBuilder(true);
|
||||||
|
Document xmpDoc = dBuilder.parse(new InputSource(new StringReader(rawXmp)));
|
||||||
|
|
||||||
|
XPathFactory xPathfactory = XPathFactory.newInstance();
|
||||||
|
XPath xpath = xPathfactory.newXPath();
|
||||||
|
xpath.setNamespaceContext(new XmpNamespaceContext());
|
||||||
|
|
||||||
|
extractDublinCoreMetadata(xpath, xmpDoc, metadataBuilder);
|
||||||
|
extractCalibreMetadata(xpath, xmpDoc, metadataBuilder);
|
||||||
|
extractBookloreMetadata(xpath, xmpDoc, metadataBuilder);
|
||||||
|
|
||||||
|
// Debug logging for troubleshooting extraction issues
|
||||||
|
if (log.isDebugEnabled()) {
|
||||||
|
BookMetadata debugMeta = metadataBuilder.build();
|
||||||
|
log.debug("PDF XMP extraction results - subtitle: '{}', moods: {}, tags: {}",
|
||||||
|
debugMeta.getSubtitle(), debugMeta.getMoods(), debugMeta.getTags());
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, String> identifiers = extractIdentifiers(xpath, xmpDoc);
|
||||||
|
if (!identifiers.isEmpty()) {
|
||||||
|
// Extract generic ISBN first
|
||||||
|
String isbn = identifiers.get("isbn");
|
||||||
|
if (StringUtils.isNotBlank(isbn)) {
|
||||||
|
isbn = ISBN_CLEANUP_PATTERN.matcher(isbn).replaceAll("");
|
||||||
|
if (isbn.length() == 10) {
|
||||||
|
metadataBuilder.isbn10(isbn);
|
||||||
|
} else if (isbn.length() == 13) {
|
||||||
|
metadataBuilder.isbn13(isbn);
|
||||||
|
} else {
|
||||||
|
metadataBuilder.isbn13(isbn); // Fallback
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Map<String, String> identifiers = extractIdentifiers(xpath, doc);
|
// Extract specific ISBN schemes (overwrites generic only if valid)
|
||||||
if (!identifiers.isEmpty()) {
|
String isbn13 = identifiers.get("isbn13");
|
||||||
// Extract generic ISBN first
|
if (StringUtils.isNotBlank(isbn13)) {
|
||||||
String isbn = identifiers.get("isbn");
|
String cleaned = ISBN_CLEANUP_PATTERN.matcher(isbn13).replaceAll("");
|
||||||
if (StringUtils.isNotBlank(isbn)) {
|
if (!cleaned.isBlank()) {
|
||||||
isbn = ISBN_CLEANUP_PATTERN.matcher(isbn).replaceAll("");
|
metadataBuilder.isbn13(cleaned);
|
||||||
if (isbn.length() == 10) {
|
|
||||||
metadataBuilder.isbn10(isbn);
|
|
||||||
} else if (isbn.length() == 13) {
|
|
||||||
metadataBuilder.isbn13(isbn);
|
|
||||||
} else {
|
|
||||||
metadataBuilder.isbn13(isbn); // Fallback
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Extract specific ISBN schemes (overwrites generic only if valid)
|
|
||||||
String isbn13 = identifiers.get("isbn13");
|
|
||||||
if (StringUtils.isNotBlank(isbn13)) {
|
|
||||||
String cleaned = ISBN_CLEANUP_PATTERN.matcher(isbn13).replaceAll("");
|
|
||||||
if (!cleaned.isBlank()) {
|
|
||||||
metadataBuilder.isbn13(cleaned);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
String isbn10 = identifiers.get("isbn10");
|
|
||||||
if (StringUtils.isNotBlank(isbn10)) {
|
|
||||||
String cleaned = ISBN_CLEANUP_PATTERN.matcher(isbn10).replaceAll("");
|
|
||||||
if (!cleaned.isBlank()) {
|
|
||||||
metadataBuilder.isbn10(cleaned);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
String google = identifiers.get("google");
|
|
||||||
if (StringUtils.isNotBlank(google)) {
|
|
||||||
metadataBuilder.googleId(google);
|
|
||||||
}
|
|
||||||
|
|
||||||
String amazon = identifiers.get("amazon");
|
|
||||||
if (StringUtils.isNotBlank(amazon)) {
|
|
||||||
metadataBuilder.asin(amazon);
|
|
||||||
}
|
|
||||||
|
|
||||||
String goodreads = identifiers.get("goodreads");
|
|
||||||
if (StringUtils.isNotBlank(goodreads)) {
|
|
||||||
metadataBuilder.goodreadsId(goodreads);
|
|
||||||
}
|
|
||||||
|
|
||||||
String comicvine = identifiers.get("comicvine");
|
|
||||||
if (StringUtils.isNotBlank(comicvine)) {
|
|
||||||
metadataBuilder.comicvineId(comicvine);
|
|
||||||
}
|
|
||||||
|
|
||||||
String ranobedb = identifiers.get("ranobedb");
|
|
||||||
if (StringUtils.isNotBlank(ranobedb)) {
|
|
||||||
metadataBuilder.ranobedbId(ranobedb);
|
|
||||||
}
|
|
||||||
|
|
||||||
String hardcover = identifiers.get("hardcover");
|
|
||||||
if (StringUtils.isNotBlank(hardcover)) {
|
|
||||||
metadataBuilder.hardcoverId(hardcover);
|
|
||||||
}
|
|
||||||
|
|
||||||
String hardcoverBookId = identifiers.get("hardcover_book_id");
|
|
||||||
if (StringUtils.isNotBlank(hardcoverBookId)) {
|
|
||||||
metadataBuilder.hardcoverBookId(hardcoverBookId);
|
|
||||||
}
|
|
||||||
|
|
||||||
String lubimyczytac = identifiers.get("lubimyczytac");
|
|
||||||
if (StringUtils.isNotBlank(lubimyczytac)) {
|
|
||||||
metadataBuilder.lubimyczytacId(lubimyczytac);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
String isbn10 = identifiers.get("isbn10");
|
||||||
|
if (StringUtils.isNotBlank(isbn10)) {
|
||||||
|
String cleaned = ISBN_CLEANUP_PATTERN.matcher(isbn10).replaceAll("");
|
||||||
|
if (!cleaned.isBlank()) {
|
||||||
|
metadataBuilder.isbn10(cleaned);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
String google = identifiers.get("google");
|
||||||
|
if (StringUtils.isNotBlank(google)) {
|
||||||
|
metadataBuilder.googleId(google);
|
||||||
|
}
|
||||||
|
|
||||||
|
String amazon = identifiers.get("amazon");
|
||||||
|
if (StringUtils.isNotBlank(amazon)) {
|
||||||
|
metadataBuilder.asin(amazon);
|
||||||
|
}
|
||||||
|
|
||||||
|
String goodreads = identifiers.get("goodreads");
|
||||||
|
if (StringUtils.isNotBlank(goodreads)) {
|
||||||
|
metadataBuilder.goodreadsId(goodreads);
|
||||||
|
}
|
||||||
|
|
||||||
|
String comicvine = identifiers.get("comicvine");
|
||||||
|
if (StringUtils.isNotBlank(comicvine)) {
|
||||||
|
metadataBuilder.comicvineId(comicvine);
|
||||||
|
}
|
||||||
|
|
||||||
|
String ranobedb = identifiers.get("ranobedb");
|
||||||
|
if (StringUtils.isNotBlank(ranobedb)) {
|
||||||
|
metadataBuilder.ranobedbId(ranobedb);
|
||||||
|
}
|
||||||
|
|
||||||
|
String hardcover = identifiers.get("hardcover");
|
||||||
|
if (StringUtils.isNotBlank(hardcover)) {
|
||||||
|
metadataBuilder.hardcoverId(hardcover);
|
||||||
|
}
|
||||||
|
|
||||||
|
String hardcoverBookId = identifiers.get("hardcover_book_id");
|
||||||
|
if (StringUtils.isNotBlank(hardcoverBookId)) {
|
||||||
|
metadataBuilder.hardcoverBookId(hardcoverBookId);
|
||||||
|
}
|
||||||
|
|
||||||
|
String lubimyczytac = identifiers.get("lubimyczytac");
|
||||||
|
if (StringUtils.isNotBlank(lubimyczytac)) {
|
||||||
|
metadataBuilder.lubimyczytacId(lubimyczytac);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.warn("Failed to parse XMP metadata with XML parser: {}", e.getMessage(), e);
|
log.warn("Failed to parse XMP metadata with XML parser: {}", e.getMessage(), e);
|
||||||
@@ -551,9 +521,43 @@ public class PdfMetadataExtractor implements FileMetadataExtractor {
|
|||||||
.toList();
|
.toList();
|
||||||
}
|
}
|
||||||
|
|
||||||
private LocalDate convertCalendarToLocalDate(Calendar calendar) {
|
/**
|
||||||
if (calendar == null) return null;
|
* Parses PDF date strings in the standard D:YYYYMMDDHHmmSS format.
|
||||||
return calendar.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
|
* Falls back to ISO date parsing if the D: prefix is not present.
|
||||||
|
*/
|
||||||
|
private LocalDate parsePdfDate(String pdfDate) {
|
||||||
|
if (pdfDate == null || pdfDate.isBlank()) return null;
|
||||||
|
try {
|
||||||
|
String s = pdfDate.startsWith("D:") ? pdfDate.substring(2) : pdfDate;
|
||||||
|
// Try ISO date format first (e.g. "2021-02-17")
|
||||||
|
if (ISO_DATE_PATTERN.matcher(s).matches()) {
|
||||||
|
return LocalDate.parse(s);
|
||||||
|
}
|
||||||
|
// Strip timezone info (e.g. +00'00' or Z)
|
||||||
|
int tzIdx = s.indexOf('+');
|
||||||
|
if (tzIdx < 0) tzIdx = s.indexOf('-', 8); // skip YYYYMMDD
|
||||||
|
if (tzIdx < 0) tzIdx = s.indexOf('Z');
|
||||||
|
if (tzIdx > 0) s = s.substring(0, tzIdx);
|
||||||
|
if (PDF_DATE_TIME_PATTERN.matcher(s).matches()) {
|
||||||
|
int year = Integer.parseInt(s.substring(0, 4));
|
||||||
|
int month = Integer.parseInt(s.substring(4, 6));
|
||||||
|
int day = Integer.parseInt(s.substring(6, 8));
|
||||||
|
return LocalDate.of(year, month, day);
|
||||||
|
}
|
||||||
|
if (YEAR_MONTH_PATTERN.matcher(s).matches()) {
|
||||||
|
return LocalDate.of(
|
||||||
|
Integer.parseInt(s.substring(0, 4)),
|
||||||
|
Integer.parseInt(s.substring(4, 6)),
|
||||||
|
1
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (s.matches("\\d{4}")) {
|
||||||
|
return LocalDate.of(Integer.parseInt(s.substring(0, 4)), 1, 1);
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.debug("Failed to parse PDF date '{}': {}", pdfDate, e.getMessage());
|
||||||
|
}
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
private String xpathEvaluate(XPath xpath, Document doc, String expression) throws XPathExpressionException {
|
private String xpathEvaluate(XPath xpath, Document doc, String expression) throws XPathExpressionException {
|
||||||
|
|||||||
@@ -1,118 +0,0 @@
|
|||||||
package org.booklore.service.metadata.writer;
|
|
||||||
|
|
||||||
import org.apache.xmpbox.XMPMetadata;
|
|
||||||
import org.apache.xmpbox.schema.XMPSchema;
|
|
||||||
|
|
||||||
import java.util.Locale;
|
|
||||||
import java.util.Set;
|
|
||||||
import java.util.stream.Collectors;
|
|
||||||
|
|
||||||
public class BookLoreSchema extends XMPSchema {
|
|
||||||
|
|
||||||
public static final String NAMESPACE = "http://booklore.org/metadata/1.0/";
|
|
||||||
public static final String PREFIX = "booklore";
|
|
||||||
|
|
||||||
public static final String SUBTITLE = "Subtitle";
|
|
||||||
public static final String MOODS = "Moods";
|
|
||||||
public static final String TAGS = "Tags";
|
|
||||||
public static final String RATING = "Rating";
|
|
||||||
public static final String AMAZON_RATING = "AmazonRating";
|
|
||||||
public static final String GOODREADS_RATING = "GoodreadsRating";
|
|
||||||
public static final String HARDCOVER_RATING = "HardcoverRating";
|
|
||||||
public static final String LUBIMYCZYTAC_RATING = "LubimyczytacRating";
|
|
||||||
public static final String RANOBEDB_RATING = "RanobedbRating";
|
|
||||||
public static final String LUBIMYCZYTAC_ID = "LubimyczytacId";
|
|
||||||
public static final String HARDCOVER_BOOK_ID = "HardcoverBookId";
|
|
||||||
public static final String ISBN_10 = "ISBN10";
|
|
||||||
|
|
||||||
public BookLoreSchema(XMPMetadata metadata) {
|
|
||||||
super(metadata, PREFIX, NAMESPACE);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
public void setSubtitle(String subtitle) {
|
|
||||||
if (subtitle != null && !subtitle.isBlank()) {
|
|
||||||
setTextPropertyValue(SUBTITLE, subtitle);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setIsbn10(String isbn10) {
|
|
||||||
if (isbn10 != null && !isbn10.isBlank()) {
|
|
||||||
setTextPropertyValue(ISBN_10, isbn10);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setLubimyczytacId(String id) {
|
|
||||||
if (id != null && !id.isBlank()) {
|
|
||||||
setTextPropertyValue(LUBIMYCZYTAC_ID, id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setHardcoverBookId(Integer id) {
|
|
||||||
if (id != null) {
|
|
||||||
setTextPropertyValue(HARDCOVER_BOOK_ID, id.toString());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
public void setRating(Double rating) {
|
|
||||||
if (rating != null) {
|
|
||||||
setTextPropertyValue(RATING, String.format(Locale.US, "%.2f", rating));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setAmazonRating(Double rating) {
|
|
||||||
if (rating != null) {
|
|
||||||
setTextPropertyValue(AMAZON_RATING, String.format(Locale.US, "%.2f", rating));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setGoodreadsRating(Double rating) {
|
|
||||||
if (rating != null) {
|
|
||||||
setTextPropertyValue(GOODREADS_RATING, String.format(Locale.US, "%.2f", rating));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setHardcoverRating(Double rating) {
|
|
||||||
if (rating != null) {
|
|
||||||
setTextPropertyValue(HARDCOVER_RATING, String.format(Locale.US, "%.2f", rating));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setLubimyczytacRating(Double rating) {
|
|
||||||
if (rating != null) {
|
|
||||||
setTextPropertyValue(LUBIMYCZYTAC_RATING, String.format(Locale.US, "%.2f", rating));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setRanobedbRating(Double rating) {
|
|
||||||
if (rating != null) {
|
|
||||||
setTextPropertyValue(RANOBEDB_RATING, String.format(Locale.US, "%.2f", rating));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setMoods(Set<String> moods) {
|
|
||||||
if (moods == null || moods.isEmpty()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
String joined = moods.stream()
|
|
||||||
.filter(m -> m != null && !m.isBlank())
|
|
||||||
.collect(Collectors.joining("; "));
|
|
||||||
if (!joined.isEmpty()) {
|
|
||||||
setTextPropertyValue(MOODS, joined);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setTags(Set<String> tags) {
|
|
||||||
if (tags == null || tags.isEmpty()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
String joined = tags.stream()
|
|
||||||
.filter(t -> t != null && !t.isBlank())
|
|
||||||
.collect(Collectors.joining("; "));
|
|
||||||
if (!joined.isEmpty()) {
|
|
||||||
setTextPropertyValue(TAGS, joined);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
+168
-259
@@ -2,40 +2,26 @@ package org.booklore.service.metadata.writer;
|
|||||||
|
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.apache.pdfbox.Loader;
|
import org.grimmory.pdfium4j.PdfDocument;
|
||||||
import org.apache.pdfbox.io.IOUtils;
|
import org.grimmory.pdfium4j.XmpMetadataWriter;
|
||||||
import org.apache.pdfbox.pdmodel.PDDocument;
|
import org.grimmory.pdfium4j.model.MetadataTag;
|
||||||
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
|
import org.grimmory.pdfium4j.model.SaveOptions;
|
||||||
import org.apache.pdfbox.pdmodel.common.PDMetadata;
|
import org.grimmory.pdfium4j.model.XmpMetadata;
|
||||||
import org.apache.xmpbox.XMPMetadata;
|
|
||||||
import org.apache.xmpbox.schema.DublinCoreSchema;
|
|
||||||
import org.apache.xmpbox.xml.XmpSerializer;
|
|
||||||
import org.booklore.model.MetadataClearFlags;
|
import org.booklore.model.MetadataClearFlags;
|
||||||
import org.booklore.model.dto.settings.MetadataPersistenceSettings;
|
import org.booklore.model.dto.settings.MetadataPersistenceSettings;
|
||||||
import org.booklore.model.entity.BookMetadataEntity;
|
import org.booklore.model.entity.BookMetadataEntity;
|
||||||
import org.booklore.model.enums.BookFileType;
|
import org.booklore.model.enums.BookFileType;
|
||||||
import org.booklore.service.appsettings.AppSettingService;
|
import org.booklore.service.appsettings.AppSettingService;
|
||||||
import org.booklore.util.SecureXmlUtils;
|
|
||||||
import org.booklore.service.metadata.BookLoreMetadata;
|
import org.booklore.service.metadata.BookLoreMetadata;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
import org.w3c.dom.Document;
|
|
||||||
import org.w3c.dom.Element;
|
|
||||||
|
|
||||||
import javax.xml.parsers.DocumentBuilder;
|
|
||||||
import javax.xml.transform.OutputKeys;
|
|
||||||
import javax.xml.transform.Transformer;
|
|
||||||
import javax.xml.transform.TransformerFactory;
|
|
||||||
import javax.xml.transform.dom.DOMSource;
|
|
||||||
import javax.xml.transform.stream.StreamResult;
|
|
||||||
import java.io.ByteArrayInputStream;
|
|
||||||
import java.io.ByteArrayOutputStream;
|
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.nio.file.Files;
|
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.time.ZoneId;
|
|
||||||
import java.time.ZonedDateTime;
|
import java.time.ZonedDateTime;
|
||||||
|
import java.time.format.DateTimeFormatter;
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@@ -70,12 +56,10 @@ public class PdfMetadataWriter implements MetadataWriter {
|
|||||||
log.warn("Could not create PDF temp backup for {}: {}", file.getName(), e.getMessage());
|
log.warn("Could not create PDF temp backup for {}: {}", file.getName(), e.getMessage());
|
||||||
}
|
}
|
||||||
|
|
||||||
try (PDDocument pdf = Loader.loadPDF(file, IOUtils.createTempFileOnlyStreamCache())) {
|
try (PdfDocument doc = PdfDocument.open(filePath)) {
|
||||||
pdf.setAllSecurityToBeRemoved(true);
|
applyMetadataToDocument(doc, metadataEntity, clear);
|
||||||
applyMetadataToDocument(pdf, metadataEntity, clear);
|
|
||||||
tempFile = File.createTempFile("pdfmeta-", ".pdf");
|
tempFile = File.createTempFile("pdfmeta-", ".pdf");
|
||||||
// PDFBox 3.x saves in compressed mode by default
|
doc.save(tempFile.toPath(), SaveOptions.SKIP_VALIDATION);
|
||||||
pdf.save(tempFile);
|
|
||||||
Files.move(tempFile.toPath(), filePath, StandardCopyOption.REPLACE_EXISTING);
|
Files.move(tempFile.toPath(), filePath, StandardCopyOption.REPLACE_EXISTING);
|
||||||
tempFile = null; // Prevent deletion in finally block after successful move
|
tempFile = null; // Prevent deletion in finally block after successful move
|
||||||
log.info("Successfully embedded metadata into PDF: {}", file.getName());
|
log.info("Successfully embedded metadata into PDF: {}", file.getName());
|
||||||
@@ -129,12 +113,10 @@ public class PdfMetadataWriter implements MetadataWriter {
|
|||||||
// Maximum length for PDF Info Dictionary keywords (some older PDF specs limit to 255 bytes)
|
// Maximum length for PDF Info Dictionary keywords (some older PDF specs limit to 255 bytes)
|
||||||
private static final int MAX_INFO_KEYWORDS_LENGTH = 255;
|
private static final int MAX_INFO_KEYWORDS_LENGTH = 255;
|
||||||
|
|
||||||
private void applyMetadataToDocument(PDDocument pdf, BookMetadataEntity entity, MetadataClearFlags clear) {
|
private void applyMetadataToDocument(PdfDocument doc, BookMetadataEntity entity, MetadataClearFlags clear) {
|
||||||
PDDocumentInformation info = pdf.getDocumentInformation();
|
|
||||||
MetadataCopyHelper helper = new MetadataCopyHelper(entity);
|
MetadataCopyHelper helper = new MetadataCopyHelper(entity);
|
||||||
|
|
||||||
// Build categories-only keywords for PDF legacy compatibility (Info Dictionary)
|
// --- PDF Info Dictionary (legacy) via PDFium4j ---
|
||||||
// Moods and tags are stored separately in XMP booklore namespace, so they should NOT be in Info Dict keywords
|
|
||||||
StringBuilder keywordsBuilder = new StringBuilder();
|
StringBuilder keywordsBuilder = new StringBuilder();
|
||||||
helper.copyCategories(clear != null && clear.isCategories(), cats -> {
|
helper.copyCategories(clear != null && clear.isCategories(), cats -> {
|
||||||
if (cats != null && !cats.isEmpty()) {
|
if (cats != null && !cats.isEmpty()) {
|
||||||
@@ -142,318 +124,245 @@ public class PdfMetadataWriter implements MetadataWriter {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
helper.copyTitle(clear != null && clear.isTitle(), title -> info.setTitle(title != null ? title : ""));
|
helper.copyTitle(clear != null && clear.isTitle(), title -> doc.setMetadata(MetadataTag.TITLE, title != null ? title : ""));
|
||||||
helper.copyPublisher(clear != null && clear.isPublisher(), pub -> info.setProducer(pub != null ? pub : ""));
|
helper.copyPublisher(clear != null && clear.isPublisher(), pub -> doc.setMetadata(MetadataTag.PRODUCER, pub != null ? pub : ""));
|
||||||
helper.copyAuthors(clear != null && clear.isAuthors(), authors -> info.setAuthor(authors != null ? String.join(", ", authors) : ""));
|
helper.copyAuthors(clear != null && clear.isAuthors(), authors -> doc.setMetadata(MetadataTag.AUTHOR, authors != null ? String.join(", ", authors) : ""));
|
||||||
helper.copyPublishedDate(clear != null && clear.isPublishedDate(), date -> {
|
helper.copyPublishedDate(clear != null && clear.isPublishedDate(), date -> {
|
||||||
Calendar cal = Calendar.getInstance();
|
if (date != null) {
|
||||||
cal.setTimeInMillis((date != null ? date : ZonedDateTime.now().toLocalDate())
|
// PDF date format: D:YYYYMMDDHHmmSS
|
||||||
.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli());
|
String pdfDate = String.format("D:%04d%02d%02d000000", date.getYear(), date.getMonthValue(), date.getDayOfMonth());
|
||||||
info.setCreationDate(cal);
|
doc.setMetadata(MetadataTag.CREATION_DATE, pdfDate);
|
||||||
|
} else {
|
||||||
|
doc.setMetadata(MetadataTag.CREATION_DATE, "");
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// Truncate keywords for legacy PDF Info Dictionary (255 byte limit in older specs)
|
|
||||||
String keywords = keywordsBuilder.toString();
|
String keywords = keywordsBuilder.toString();
|
||||||
if (keywords.length() > MAX_INFO_KEYWORDS_LENGTH) {
|
if (keywords.length() > MAX_INFO_KEYWORDS_LENGTH) {
|
||||||
keywords = keywords.substring(0, MAX_INFO_KEYWORDS_LENGTH - 3) + "...";
|
keywords = keywords.substring(0, MAX_INFO_KEYWORDS_LENGTH - 3) + "...";
|
||||||
log.debug("PDF keywords truncated from {} to {} characters for legacy compatibility",
|
log.debug("PDF keywords truncated from {} to {} characters for legacy compatibility",
|
||||||
keywordsBuilder.length(), keywords.length());
|
keywordsBuilder.length(), keywords.length());
|
||||||
}
|
}
|
||||||
info.setKeywords(keywords);
|
doc.setMetadata(MetadataTag.KEYWORDS, keywords);
|
||||||
|
|
||||||
|
// --- XMP metadata via PDFium4j XmpMetadataWriter (StringBuilder-based, no DOM) ---
|
||||||
try {
|
try {
|
||||||
XMPMetadata xmp = XMPMetadata.createXMPMetadata();
|
String newXmp = buildXmpPacket(helper, clear, entity);
|
||||||
DublinCoreSchema dc = xmp.createAndAddDublinCoreSchema();
|
String existingXmp = doc.xmpMetadataString();
|
||||||
|
|
||||||
helper.copyTitle(clear != null && clear.isTitle(), title -> dc.setTitle(title != null ? title : ""));
|
if (!isXmpMetadataDifferent(existingXmp, newXmp)) {
|
||||||
helper.copyDescription(clear != null && clear.isDescription(), desc -> dc.setDescription(desc != null ? desc : ""));
|
|
||||||
helper.copyPublisher(clear != null && clear.isPublisher(), pub -> dc.addPublisher(pub != null ? pub : ""));
|
|
||||||
|
|
||||||
// Write language as provided by user
|
|
||||||
helper.copyLanguage(clear != null && clear.isLanguage(), lang -> {
|
|
||||||
if (lang != null && !lang.isBlank()) {
|
|
||||||
dc.addLanguage(lang);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Use date-only format for dc:date (YYYY-MM-DD)
|
|
||||||
helper.copyPublishedDate(clear != null && clear.isPublishedDate(), date -> {
|
|
||||||
if (date != null) {
|
|
||||||
// XMPBox requires Calendar, but we can create one with just the date (no time)
|
|
||||||
Calendar cal = Calendar.getInstance();
|
|
||||||
cal.clear(); // Clear time fields
|
|
||||||
cal.set(date.getYear(), date.getMonthValue() - 1, date.getDayOfMonth());
|
|
||||||
dc.addDate(cal);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Clean author names (normalize whitespace)
|
|
||||||
helper.copyAuthors(clear != null && clear.isAuthors(), authors -> {
|
|
||||||
if (authors != null && !authors.isEmpty()) {
|
|
||||||
authors.stream()
|
|
||||||
.map(name -> name.replaceAll("\\s+", " ").trim())
|
|
||||||
.filter(name -> !name.isBlank())
|
|
||||||
.forEach(dc::addCreator);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Add categories as dc:subject
|
|
||||||
helper.copyCategories(clear != null && clear.isCategories(), cats -> {
|
|
||||||
if (cats != null && !cats.isEmpty()) {
|
|
||||||
cats.forEach(dc::addSubject);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Note: BookLore custom fields (subtitle, ratings, moods, tags as separate field)
|
|
||||||
// are added via raw XML manipulation in addCustomIdentifiersToXmp to avoid XMPBox namespace issues
|
|
||||||
// Moods and tags are stored separately in booklore namespace to avoid confusion with categories
|
|
||||||
|
|
||||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
|
||||||
new XmpSerializer().serialize(xmp, baos, true);
|
|
||||||
byte[] baseXmpBytes = baos.toByteArray();
|
|
||||||
|
|
||||||
byte[] newXmpBytes = addCustomIdentifiersToXmp(baseXmpBytes, entity, helper, clear);
|
|
||||||
|
|
||||||
byte[] existingXmpBytes = null;
|
|
||||||
PDMetadata existingMetadata = pdf.getDocumentCatalog().getMetadata();
|
|
||||||
if (existingMetadata != null) {
|
|
||||||
try {
|
|
||||||
existingXmpBytes = existingMetadata.toByteArray();
|
|
||||||
} catch (IOException ignore) {
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!isXmpMetadataDifferent(existingXmpBytes, newXmpBytes)) {
|
|
||||||
log.info("XMP metadata unchanged, skipping write");
|
log.info("XMP metadata unchanged, skipping write");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
PDMetadata pdMetadata = new PDMetadata(pdf);
|
doc.setXmpMetadata(newXmp);
|
||||||
pdMetadata.importXMPMetadata(newXmpBytes);
|
|
||||||
pdf.getDocumentCatalog().setMetadata(pdMetadata);
|
|
||||||
|
|
||||||
log.info("XMP metadata updated for PDF");
|
log.info("XMP metadata updated for PDF");
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.warn("Failed to embed XMP metadata: {}", e.getMessage(), e);
|
log.warn("Failed to embed XMP metadata: {}", e.getMessage(), e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Adds custom metadata to XMP using Booklore namespace for all custom fields.
|
* Builds the complete XMP packet using PDFium4j's StringBuilder-based XmpMetadataWriter.
|
||||||
* <p>
|
* Eliminates all DOM and TransformerFactory overhead from the old approach.
|
||||||
* Namespace strategy:
|
|
||||||
* - Dublin Core (dc:) for title, description, creator, publisher, date, subject, language
|
|
||||||
* - XMP Basic (xmp:) for metadata dates, creator tool
|
|
||||||
* - Booklore (booklore:) for series, subtitle, ISBNs, external IDs, ratings, moods, tags, page count
|
|
||||||
*/
|
*/
|
||||||
private byte[] addCustomIdentifiersToXmp(byte[] xmpBytes, BookMetadataEntity metadata, MetadataCopyHelper helper, MetadataClearFlags clear) throws Exception {
|
@SuppressWarnings("unchecked")
|
||||||
DocumentBuilder builder = SecureXmlUtils.createSecureDocumentBuilder(true);
|
private String buildXmpPacket(MetadataCopyHelper helper, MetadataClearFlags clear, BookMetadataEntity metadata) {
|
||||||
Document doc = builder.parse(new ByteArrayInputStream(xmpBytes));
|
// Capture DC field values from helper
|
||||||
|
String[] title = {null}, description = {null}, publisher = {null}, language = {null}, date = {null};
|
||||||
|
List<String>[] authors = new List[]{null};
|
||||||
|
List<String>[] subjects = new List[]{null};
|
||||||
|
|
||||||
Element rdfRoot = (Element) doc.getElementsByTagNameNS("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "RDF").item(0);
|
helper.copyTitle(clear != null && clear.isTitle(), t -> title[0] = t);
|
||||||
if (rdfRoot == null) throw new IllegalStateException("RDF root missing in XMP");
|
helper.copyDescription(clear != null && clear.isDescription(), d -> description[0] = d);
|
||||||
|
helper.copyPublisher(clear != null && clear.isPublisher(), p -> publisher[0] = p);
|
||||||
|
helper.copyLanguage(clear != null && clear.isLanguage(), l -> {
|
||||||
|
if (l != null && !l.isBlank()) language[0] = l;
|
||||||
|
});
|
||||||
|
helper.copyPublishedDate(clear != null && clear.isPublishedDate(), d -> {
|
||||||
|
if (d != null) date[0] = d.toString();
|
||||||
|
});
|
||||||
|
helper.copyAuthors(clear != null && clear.isAuthors(), a -> {
|
||||||
|
if (a != null && !a.isEmpty()) {
|
||||||
|
authors[0] = a.stream()
|
||||||
|
.map(name -> name.replaceAll("\\s+", " ").trim())
|
||||||
|
.filter(name -> !name.isBlank())
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
helper.copyCategories(clear != null && clear.isCategories(), c -> {
|
||||||
|
if (c != null && !c.isEmpty()) subjects[0] = new ArrayList<>(c);
|
||||||
|
});
|
||||||
|
|
||||||
// XMP Basic namespace for tool and date info
|
// Build custom fields map
|
||||||
Element xmpBasicDescription = doc.createElementNS("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "rdf:Description");
|
Map<String, String> customFields = new LinkedHashMap<>();
|
||||||
xmpBasicDescription.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xmp", "http://ns.adobe.com/xap/1.0/");
|
|
||||||
xmpBasicDescription.setAttributeNS("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "rdf:about", "");
|
|
||||||
|
|
||||||
xmpBasicDescription.appendChild(createXmpElement(doc, "xmp:CreatorTool", "Booklore"));
|
// XMP Basic (unprefixed → written as xmp: by XmpMetadataWriter)
|
||||||
// Use ISO-8601 format for current timestamps
|
customFields.put("CreatorTool", "Booklore");
|
||||||
String nowIso = ZonedDateTime.now().format(java.time.format.DateTimeFormatter.ISO_INSTANT);
|
String nowIso = ZonedDateTime.now().format(DateTimeFormatter.ISO_INSTANT);
|
||||||
xmpBasicDescription.appendChild(createXmpElement(doc, "xmp:MetadataDate", nowIso));
|
customFields.put("MetadataDate", nowIso);
|
||||||
xmpBasicDescription.appendChild(createXmpElement(doc, "xmp:ModifyDate", nowIso));
|
customFields.put("ModifyDate", nowIso);
|
||||||
if (metadata.getPublishedDate() != null) {
|
if (date[0] != null) {
|
||||||
// Use date-only format (YYYY-MM-DD) when we only have a date, not a full timestamp
|
customFields.put("CreateDate", date[0]);
|
||||||
xmpBasicDescription.appendChild(createXmpElement(doc, "xmp:CreateDate",
|
|
||||||
metadata.getPublishedDate().toString()));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
rdfRoot.appendChild(xmpBasicDescription);
|
// Booklore namespace simple fields
|
||||||
|
addBookloreSimpleFields(customFields, helper, clear, metadata);
|
||||||
|
|
||||||
// Booklore namespace for all custom metadata
|
XmpMetadata xmpMeta = new XmpMetadata(
|
||||||
Element bookloreDescription = doc.createElementNS("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "rdf:Description");
|
Optional.ofNullable(title[0]),
|
||||||
bookloreDescription.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" + BookLoreMetadata.NS_PREFIX, BookLoreMetadata.NS_URI);
|
authors[0] != null ? authors[0] : List.of(),
|
||||||
bookloreDescription.setAttributeNS("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "rdf:about", "");
|
Optional.ofNullable(description[0]),
|
||||||
|
subjects[0] != null ? subjects[0] : List.of(),
|
||||||
|
Optional.ofNullable(publisher[0]),
|
||||||
|
Optional.ofNullable(language[0]),
|
||||||
|
Optional.ofNullable(date[0]),
|
||||||
|
Optional.empty(),
|
||||||
|
List.of(),
|
||||||
|
Optional.empty(),
|
||||||
|
Map.of(),
|
||||||
|
customFields
|
||||||
|
);
|
||||||
|
|
||||||
|
XmpMetadataWriter xmpWriter = new XmpMetadataWriter()
|
||||||
|
.registerNamespace(BookLoreMetadata.NS_PREFIX, BookLoreMetadata.NS_URI);
|
||||||
|
String xmpPacket = xmpWriter.write(xmpMeta);
|
||||||
|
|
||||||
|
// Inject RDF Bag elements for tags/moods (not supported as simple custom fields)
|
||||||
|
return injectBagElements(xmpPacket, helper, clear);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void addBookloreSimpleFields(Map<String, String> customFields, MetadataCopyHelper helper,
|
||||||
|
MetadataClearFlags clear, BookMetadataEntity metadata) {
|
||||||
|
String prefix = BookLoreMetadata.NS_PREFIX + ":";
|
||||||
|
|
||||||
// Series Information - ONLY write if BOTH name AND number are valid
|
|
||||||
// A series name without a number is broken/incomplete data
|
|
||||||
if (hasValidSeries(metadata, clear)) {
|
if (hasValidSeries(metadata, clear)) {
|
||||||
appendBookloreElement(doc, bookloreDescription, "seriesName", metadata.getSeriesName());
|
customFields.put(prefix + "seriesName", metadata.getSeriesName());
|
||||||
appendBookloreElement(doc, bookloreDescription, "seriesNumber", formatSeriesNumber(metadata.getSeriesNumber()));
|
customFields.put(prefix + "seriesNumber", formatSeriesNumber(metadata.getSeriesNumber()));
|
||||||
|
|
||||||
// Series total is optional, only write if > 0
|
|
||||||
if (metadata.getSeriesTotal() != null && metadata.getSeriesTotal() > 0) {
|
if (metadata.getSeriesTotal() != null && metadata.getSeriesTotal() > 0) {
|
||||||
helper.copySeriesTotal(clear != null && clear.isSeriesTotal(), total -> {
|
helper.copySeriesTotal(clear != null && clear.isSeriesTotal(), total -> {
|
||||||
if (total != null && total > 0) {
|
if (total != null && total > 0) {
|
||||||
appendBookloreElement(doc, bookloreDescription, "seriesTotal", total.toString());
|
customFields.put(prefix + "seriesTotal", total.toString());
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Subtitle
|
|
||||||
helper.copySubtitle(clear != null && clear.isSubtitle(), subtitle -> {
|
helper.copySubtitle(clear != null && clear.isSubtitle(), subtitle -> {
|
||||||
if (subtitle != null && !subtitle.isBlank()) {
|
if (subtitle != null && !subtitle.isBlank()) customFields.put(prefix + "subtitle", subtitle);
|
||||||
appendBookloreElement(doc, bookloreDescription, "subtitle", subtitle);
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// ISBN Identifiers
|
|
||||||
helper.copyIsbn13(clear != null && clear.isIsbn13(), isbn -> {
|
helper.copyIsbn13(clear != null && clear.isIsbn13(), isbn -> {
|
||||||
if (isbn != null && !isbn.isBlank()) {
|
if (isbn != null && !isbn.isBlank()) customFields.put(prefix + "isbn13", isbn);
|
||||||
appendBookloreElement(doc, bookloreDescription, "isbn13", isbn);
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
helper.copyIsbn10(clear != null && clear.isIsbn10(), isbn -> {
|
helper.copyIsbn10(clear != null && clear.isIsbn10(), isbn -> {
|
||||||
if (isbn != null && !isbn.isBlank()) {
|
if (isbn != null && !isbn.isBlank()) customFields.put(prefix + "isbn10", isbn);
|
||||||
appendBookloreElement(doc, bookloreDescription, "isbn10", isbn);
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// External IDs (only if not blank)
|
|
||||||
helper.copyGoogleId(clear != null && clear.isGoogleId(), id -> {
|
helper.copyGoogleId(clear != null && clear.isGoogleId(), id -> {
|
||||||
if (id != null && !id.isBlank()) {
|
if (id != null && !id.isBlank()) customFields.put(prefix + "googleId", id);
|
||||||
appendBookloreElement(doc, bookloreDescription, "googleId", id);
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
helper.copyGoodreadsId(clear != null && clear.isGoodreadsId(), id -> {
|
helper.copyGoodreadsId(clear != null && clear.isGoodreadsId(), id -> {
|
||||||
String normalizedId = normalizeGoodreadsId(id);
|
String normalized = normalizeGoodreadsId(id);
|
||||||
if (normalizedId != null && !normalizedId.isBlank()) {
|
if (normalized != null && !normalized.isBlank()) customFields.put(prefix + "goodreadsId", normalized);
|
||||||
appendBookloreElement(doc, bookloreDescription, "goodreadsId", normalizedId);
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
helper.copyHardcoverId(clear != null && clear.isHardcoverId(), id -> {
|
helper.copyHardcoverId(clear != null && clear.isHardcoverId(), id -> {
|
||||||
if (id != null && !id.isBlank()) {
|
if (id != null && !id.isBlank()) customFields.put(prefix + "hardcoverId", id);
|
||||||
appendBookloreElement(doc, bookloreDescription, "hardcoverId", id);
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
helper.copyHardcoverBookId(clear != null && clear.isHardcoverBookId(), id -> {
|
helper.copyHardcoverBookId(clear != null && clear.isHardcoverBookId(), id -> {
|
||||||
if (id != null && !id.isBlank()) {
|
if (id != null && !id.isBlank()) customFields.put(prefix + "hardcoverBookId", id);
|
||||||
appendBookloreElement(doc, bookloreDescription, "hardcoverBookId", id);
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
helper.copyAsin(clear != null && clear.isAsin(), id -> {
|
helper.copyAsin(clear != null && clear.isAsin(), id -> {
|
||||||
if (id != null && !id.isBlank()) {
|
if (id != null && !id.isBlank()) customFields.put(prefix + "asin", id);
|
||||||
appendBookloreElement(doc, bookloreDescription, "asin", id);
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
helper.copyComicvineId(clear != null && clear.isComicvineId(), id -> {
|
helper.copyComicvineId(clear != null && clear.isComicvineId(), id -> {
|
||||||
if (id != null && !id.isBlank()) {
|
if (id != null && !id.isBlank()) customFields.put(prefix + "comicvineId", id);
|
||||||
appendBookloreElement(doc, bookloreDescription, "comicvineId", id);
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
helper.copyLubimyczytacId(clear != null && clear.isLubimyczytacId(), id -> {
|
helper.copyLubimyczytacId(clear != null && clear.isLubimyczytacId(), id -> {
|
||||||
if (id != null && !id.isBlank()) {
|
if (id != null && !id.isBlank()) customFields.put(prefix + "lubimyczytacId", id);
|
||||||
appendBookloreElement(doc, bookloreDescription, "lubimyczytacId", id);
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
helper.copyRanobedbId(clear != null && clear.isRanobedbId(), id -> {
|
helper.copyRanobedbId(clear != null && clear.isRanobedbId(), id -> {
|
||||||
if (id != null && !id.isBlank()) {
|
if (id != null && !id.isBlank()) customFields.put(prefix + "ranobedbId", id);
|
||||||
appendBookloreElement(doc, bookloreDescription, "ranobedbId", id);
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// Ratings (only if > 0)
|
helper.copyRating(false, rating -> addBookloreRating(customFields, prefix, "rating", rating));
|
||||||
helper.copyRating(false, rating -> appendBookloreRating(doc, bookloreDescription, "rating", rating));
|
helper.copyHardcoverRating(clear != null && clear.isHardcoverRating(),
|
||||||
helper.copyHardcoverRating(clear != null && clear.isHardcoverRating(), rating -> appendBookloreRating(doc, bookloreDescription, "hardcoverRating", rating));
|
rating -> addBookloreRating(customFields, prefix, "hardcoverRating", rating));
|
||||||
helper.copyGoodreadsRating(clear != null && clear.isGoodreadsRating(), rating -> appendBookloreRating(doc, bookloreDescription, "goodreadsRating", rating));
|
helper.copyGoodreadsRating(clear != null && clear.isGoodreadsRating(),
|
||||||
helper.copyAmazonRating(clear != null && clear.isAmazonRating(), rating -> appendBookloreRating(doc, bookloreDescription, "amazonRating", rating));
|
rating -> addBookloreRating(customFields, prefix, "goodreadsRating", rating));
|
||||||
helper.copyLubimyczytacRating(clear != null && clear.isLubimyczytacRating(), rating -> appendBookloreRating(doc, bookloreDescription, "lubimyczytacRating", rating));
|
helper.copyAmazonRating(clear != null && clear.isAmazonRating(),
|
||||||
helper.copyRanobedbRating(clear != null && clear.isRanobedbRating(), rating -> appendBookloreRating(doc, bookloreDescription, "ranobedbRating", rating));
|
rating -> addBookloreRating(customFields, prefix, "amazonRating", rating));
|
||||||
|
helper.copyLubimyczytacRating(clear != null && clear.isLubimyczytacRating(),
|
||||||
|
rating -> addBookloreRating(customFields, prefix, "lubimyczytacRating", rating));
|
||||||
|
helper.copyRanobedbRating(clear != null && clear.isRanobedbRating(),
|
||||||
|
rating -> addBookloreRating(customFields, prefix, "ranobedbRating", rating));
|
||||||
|
|
||||||
// Tags (as RDF Bag)
|
|
||||||
helper.copyTags(clear != null && clear.isTags(), tags -> {
|
|
||||||
if (tags != null && !tags.isEmpty()) {
|
|
||||||
appendBookloreBag(doc, bookloreDescription, "tags", tags);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Moods (as RDF Bag)
|
|
||||||
helper.copyMoods(clear != null && clear.isMoods(), moods -> {
|
|
||||||
if (moods != null && !moods.isEmpty()) {
|
|
||||||
appendBookloreBag(doc, bookloreDescription, "moods", moods);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Page Count
|
|
||||||
helper.copyPageCount(false, pageCount -> {
|
helper.copyPageCount(false, pageCount -> {
|
||||||
if (pageCount != null && pageCount > 0) {
|
if (pageCount != null && pageCount > 0) {
|
||||||
appendBookloreElement(doc, bookloreDescription, "pageCount", pageCount.toString());
|
customFields.put(prefix + "pageCount", pageCount.toString());
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
if (bookloreDescription.hasChildNodes()) {
|
|
||||||
rdfRoot.appendChild(bookloreDescription);
|
|
||||||
}
|
|
||||||
|
|
||||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
|
||||||
Transformer tf = TransformerFactory.newInstance().newTransformer();
|
|
||||||
tf.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
|
|
||||||
tf.setOutputProperty(OutputKeys.INDENT, "yes");
|
|
||||||
tf.transform(new DOMSource(doc), new StreamResult(baos));
|
|
||||||
return baos.toByteArray();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private Element createXmpElement(Document doc, String name, String content) {
|
private void addBookloreRating(Map<String, String> customFields, String prefix, String name, Double rating) {
|
||||||
Element el = doc.createElementNS("http://ns.adobe.com/xap/1.0/", name);
|
|
||||||
el.setTextContent(content);
|
|
||||||
return el;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void appendBookloreElement(Document doc, Element parent, String localName, String value) {
|
|
||||||
Element elem = doc.createElementNS(BookLoreMetadata.NS_URI, BookLoreMetadata.NS_PREFIX + ":" + localName);
|
|
||||||
elem.setTextContent(value);
|
|
||||||
parent.appendChild(elem);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void appendBookloreRating(Document doc, Element parent, String localName, Double rating) {
|
|
||||||
if (rating != null && rating > 0) {
|
if (rating != null && rating > 0) {
|
||||||
Element elem = doc.createElementNS(BookLoreMetadata.NS_URI, BookLoreMetadata.NS_PREFIX + ":" + localName);
|
customFields.put(prefix + name, String.format(Locale.US, "%.1f", rating));
|
||||||
elem.setTextContent(String.format(Locale.US, "%.1f", rating));
|
|
||||||
parent.appendChild(elem);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void appendBookloreBag(Document doc, Element parent, String localName, Set<String> values) {
|
/**
|
||||||
Element elem = doc.createElementNS(BookLoreMetadata.NS_URI, BookLoreMetadata.NS_PREFIX + ":" + localName);
|
* Injects RDF Bag elements for tags/moods into the XMP packet string.
|
||||||
Element rdfBag = doc.createElementNS("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "rdf:Bag");
|
* XmpMetadataWriter doesn't support RDF Bags in custom namespaces, so we
|
||||||
|
* insert them as a separate rdf:Description block before </rdf:RDF>.
|
||||||
|
*/
|
||||||
|
private String injectBagElements(String xmpPacket, MetadataCopyHelper helper, MetadataClearFlags clear) {
|
||||||
|
StringBuilder bags = new StringBuilder();
|
||||||
|
|
||||||
for (String value : values) {
|
helper.copyTags(clear != null && clear.isTags(), tags -> {
|
||||||
if (value != null && !value.isBlank()) {
|
if (tags != null && !tags.isEmpty()) appendBagXml(bags, "tags", tags);
|
||||||
Element li = doc.createElementNS("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "rdf:li");
|
});
|
||||||
li.setTextContent(value);
|
helper.copyMoods(clear != null && clear.isMoods(), moods -> {
|
||||||
rdfBag.appendChild(li);
|
if (moods != null && !moods.isEmpty()) appendBagXml(bags, "moods", moods);
|
||||||
|
});
|
||||||
|
|
||||||
|
if (bags.isEmpty()) return xmpPacket;
|
||||||
|
|
||||||
|
int idx = xmpPacket.lastIndexOf("</rdf:RDF>");
|
||||||
|
if (idx < 0) return xmpPacket;
|
||||||
|
return xmpPacket.substring(0, idx) + bags + xmpPacket.substring(idx);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void appendBagXml(StringBuilder sb, String localName, Set<String> values) {
|
||||||
|
sb.append("<rdf:Description rdf:about=\"\"\n");
|
||||||
|
sb.append(" xmlns:").append(BookLoreMetadata.NS_PREFIX).append("=\"")
|
||||||
|
.append(BookLoreMetadata.NS_URI).append("\">\n");
|
||||||
|
sb.append(" <").append(BookLoreMetadata.NS_PREFIX).append(':').append(localName).append(">\n");
|
||||||
|
sb.append(" <rdf:Bag>\n");
|
||||||
|
for (String v : values.stream().sorted().toList()) {
|
||||||
|
if (v != null && !v.isBlank()) {
|
||||||
|
sb.append(" <rdf:li>").append(escapeXml(v)).append("</rdf:li>\n");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
sb.append(" </rdf:Bag>\n");
|
||||||
elem.appendChild(rdfBag);
|
sb.append(" </").append(BookLoreMetadata.NS_PREFIX).append(':').append(localName).append(">\n");
|
||||||
parent.appendChild(elem);
|
sb.append("</rdf:Description>\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean isXmpMetadataDifferent(byte[] existingBytes, byte[] newBytes) {
|
private static String escapeXml(String s) {
|
||||||
if (existingBytes == null || newBytes == null) return true;
|
if (s == null) return "";
|
||||||
try {
|
return s.replace("&", "&").replace("<", "<").replace(">", ">").replace("\"", """);
|
||||||
DocumentBuilder builder = SecureXmlUtils.createSecureDocumentBuilder(false);
|
}
|
||||||
Document doc1 = builder.parse(new ByteArrayInputStream(existingBytes));
|
|
||||||
Document doc2 = builder.parse(new ByteArrayInputStream(newBytes));
|
private static final java.util.regex.Pattern TIMESTAMP_PATTERN = java.util.regex.Pattern.compile(
|
||||||
return !Objects.equals(
|
"<xmp:(MetadataDate|ModifyDate)>[^<]*</xmp:(MetadataDate|ModifyDate)>");
|
||||||
doc1.getDocumentElement().getTextContent().trim(),
|
|
||||||
doc2.getDocumentElement().getTextContent().trim()
|
private boolean isXmpMetadataDifferent(String existingXmp, String newXmp) {
|
||||||
);
|
if (existingXmp == null || existingXmp.isBlank() || newXmp == null) return true;
|
||||||
} catch (Exception e) {
|
// Strip regenerated timestamps before comparing so the check is deterministic
|
||||||
log.warn("XMP diff failed: {}", e.getMessage());
|
String normalizedExisting = TIMESTAMP_PATTERN.matcher(existingXmp).replaceAll("");
|
||||||
return true;
|
String normalizedNew = TIMESTAMP_PATTERN.matcher(newXmp).replaceAll("");
|
||||||
}
|
return !normalizedExisting.equals(normalizedNew);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ import lombok.RequiredArgsConstructor;
|
|||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
|
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
|
||||||
import org.apache.commons.compress.archivers.zip.ZipFile;
|
import org.apache.commons.compress.archivers.zip.ZipFile;
|
||||||
import org.apache.pdfbox.io.IOUtils;
|
|
||||||
import org.booklore.exception.ApiError;
|
import org.booklore.exception.ApiError;
|
||||||
import org.booklore.model.dto.response.EpubBookInfo;
|
import org.booklore.model.dto.response.EpubBookInfo;
|
||||||
import org.booklore.model.dto.response.EpubManifestItem;
|
import org.booklore.model.dto.response.EpubManifestItem;
|
||||||
@@ -745,7 +744,7 @@ public class EpubReaderService {
|
|||||||
ZipArchiveEntry entry = zipFile.getEntry(entryName);
|
ZipArchiveEntry entry = zipFile.getEntry(entryName);
|
||||||
if (entry != null) {
|
if (entry != null) {
|
||||||
try (InputStream in = new BufferedInputStream(zipFile.getInputStream(entry), BUFFER_SIZE)) {
|
try (InputStream in = new BufferedInputStream(zipFile.getInputStream(entry), BUFFER_SIZE)) {
|
||||||
IOUtils.copy(in, outputStream);
|
in.transferTo(outputStream);
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,14 +2,8 @@ package org.booklore.service.reader;
|
|||||||
|
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.apache.pdfbox.Loader;
|
import org.grimmory.pdfium4j.PdfDocument;
|
||||||
import org.apache.pdfbox.io.RandomAccessReadBufferedFile;
|
import org.grimmory.pdfium4j.model.Bookmark;
|
||||||
import org.apache.pdfbox.pdmodel.PDDocument;
|
|
||||||
import org.apache.pdfbox.pdmodel.PDPage;
|
|
||||||
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDDocumentOutline;
|
|
||||||
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem;
|
|
||||||
import org.apache.pdfbox.rendering.ImageType;
|
|
||||||
import org.apache.pdfbox.rendering.PDFRenderer;
|
|
||||||
import org.booklore.exception.ApiError;
|
import org.booklore.exception.ApiError;
|
||||||
import org.booklore.model.dto.response.PdfBookInfo;
|
import org.booklore.model.dto.response.PdfBookInfo;
|
||||||
import org.booklore.model.dto.response.PdfOutlineItem;
|
import org.booklore.model.dto.response.PdfOutlineItem;
|
||||||
@@ -20,8 +14,6 @@ import org.booklore.repository.BookRepository;
|
|||||||
import org.booklore.util.FileUtils;
|
import org.booklore.util.FileUtils;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
import javax.imageio.ImageIO;
|
|
||||||
import java.awt.image.BufferedImage;
|
|
||||||
import java.io.FileNotFoundException;
|
import java.io.FileNotFoundException;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.OutputStream;
|
import java.io.OutputStream;
|
||||||
@@ -146,26 +138,21 @@ public class PdfReaderService {
|
|||||||
throw new FileNotFoundException("PDF file is not readable: " + pdfPath);
|
throw new FileNotFoundException("PDF file is not readable: " + pdfPath);
|
||||||
}
|
}
|
||||||
long lastModified = Files.getLastModifiedTime(pdfPath).toMillis();
|
long lastModified = Files.getLastModifiedTime(pdfPath).toMillis();
|
||||||
try (RandomAccessReadBufferedFile randomAccessRead = new RandomAccessReadBufferedFile(pdfPath.toFile());
|
try (PdfDocument doc = PdfDocument.open(pdfPath)) {
|
||||||
PDDocument document = Loader.loadPDF(randomAccessRead)) {
|
int pageCount = doc.pageCount();
|
||||||
int pageCount = document.getNumberOfPages();
|
List<PdfOutlineItem> outline = extractOutline(doc);
|
||||||
List<PdfOutlineItem> outline = extractOutline(document);
|
|
||||||
return new CachedPdfMetadata(pageCount, lastModified, outline);
|
return new CachedPdfMetadata(pageCount, lastModified, outline);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private List<PdfOutlineItem> extractOutline(PDDocument document) {
|
private List<PdfOutlineItem> extractOutline(PdfDocument doc) {
|
||||||
List<PdfOutlineItem> outline = new ArrayList<>();
|
List<PdfOutlineItem> outline = new ArrayList<>();
|
||||||
try {
|
try {
|
||||||
PDDocumentOutline documentOutline = document.getDocumentCatalog().getDocumentOutline();
|
List<Bookmark> bookmarks = doc.bookmarks();
|
||||||
if (documentOutline != null) {
|
for (Bookmark bookmark : bookmarks) {
|
||||||
PDOutlineItem item = documentOutline.getFirstChild();
|
PdfOutlineItem outlineItem = convertBookmark(bookmark);
|
||||||
while (item != null) {
|
if (outlineItem != null) {
|
||||||
PdfOutlineItem outlineItem = buildOutlineItem(document, item);
|
outline.add(outlineItem);
|
||||||
if (outlineItem != null) {
|
|
||||||
outline.add(outlineItem);
|
|
||||||
}
|
|
||||||
item = item.getNextSibling();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
@@ -174,34 +161,22 @@ public class PdfReaderService {
|
|||||||
return outline;
|
return outline;
|
||||||
}
|
}
|
||||||
|
|
||||||
private PdfOutlineItem buildOutlineItem(PDDocument document, PDOutlineItem item) {
|
private PdfOutlineItem convertBookmark(Bookmark bookmark) {
|
||||||
try {
|
try {
|
||||||
String title = item.getTitle();
|
String title = bookmark.title();
|
||||||
if (title == null || title.isBlank()) {
|
if (title == null || title.isBlank()) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
Integer pageNumber = null;
|
// PDFium4j pageIndex is 0-based, PdfOutlineItem.pageNumber is 1-based
|
||||||
try {
|
Integer pageNumber = bookmark.isInternal() ? bookmark.pageIndex() + 1 : null;
|
||||||
PDPage page = item.findDestinationPage(document);
|
|
||||||
if (page != null) {
|
|
||||||
int pageIndex = document.getPages().indexOf(page);
|
|
||||||
if (pageIndex >= 0) {
|
|
||||||
pageNumber = pageIndex + 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (Exception e) {
|
|
||||||
log.debug("Failed to get page for outline item '{}': {}", title, e.getMessage());
|
|
||||||
}
|
|
||||||
|
|
||||||
List<PdfOutlineItem> children = new ArrayList<>();
|
List<PdfOutlineItem> children = new ArrayList<>();
|
||||||
PDOutlineItem child = item.getFirstChild();
|
for (Bookmark child : bookmark.children()) {
|
||||||
while (child != null) {
|
PdfOutlineItem childItem = convertBookmark(child);
|
||||||
PdfOutlineItem childItem = buildOutlineItem(document, child);
|
|
||||||
if (childItem != null) {
|
if (childItem != null) {
|
||||||
children.add(childItem);
|
children.add(childItem);
|
||||||
}
|
}
|
||||||
child = child.getNextSibling();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return PdfOutlineItem.builder()
|
return PdfOutlineItem.builder()
|
||||||
@@ -231,18 +206,10 @@ public class PdfReaderService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void renderPageToStream(Path pdfPath, int page, OutputStream outputStream) throws IOException {
|
private void renderPageToStream(Path pdfPath, int page, OutputStream outputStream) throws IOException {
|
||||||
try (RandomAccessReadBufferedFile randomAccessRead = new RandomAccessReadBufferedFile(pdfPath.toFile());
|
try (PdfDocument doc = PdfDocument.open(pdfPath)) {
|
||||||
PDDocument document = Loader.loadPDF(randomAccessRead)) {
|
// page is 1-based from the API, renderPageToBytes expects 0-based
|
||||||
PDFRenderer renderer = new PDFRenderer(document);
|
byte[] jpeg = doc.renderPageToBytes(page - 1, (int) DEFAULT_DPI, "jpeg");
|
||||||
BufferedImage image = null;
|
outputStream.write(jpeg);
|
||||||
try {
|
|
||||||
image = renderer.renderImageWithDPI(page - 1, DEFAULT_DPI, ImageType.RGB);
|
|
||||||
ImageIO.write(image, "JPEG", outputStream);
|
|
||||||
} finally {
|
|
||||||
if (image != null) {
|
|
||||||
image.flush();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
log.error("Failed to render PDF page {} from {}", page, pdfPath, e);
|
log.error("Failed to render PDF page {} from {}", page, pdfPath, e);
|
||||||
throw e;
|
throw e;
|
||||||
|
|||||||
@@ -12,28 +12,41 @@ import javax.xml.parsers.ParserConfigurationException;
|
|||||||
@UtilityClass
|
@UtilityClass
|
||||||
public class SecureXmlUtils {
|
public class SecureXmlUtils {
|
||||||
|
|
||||||
public static DocumentBuilderFactory createSecureDocumentBuilderFactory(boolean namespaceAware) throws ParserConfigurationException {
|
// DocumentBuilderFactory is thread-safe after configuration cache one per namespace-aware mode
|
||||||
|
private static final DocumentBuilderFactory NS_AWARE_FACTORY;
|
||||||
|
private static final DocumentBuilderFactory NON_NS_AWARE_FACTORY;
|
||||||
|
|
||||||
|
static {
|
||||||
try {
|
try {
|
||||||
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
|
NS_AWARE_FACTORY = buildFactory(true);
|
||||||
factory.setNamespaceAware(namespaceAware);
|
NON_NS_AWARE_FACTORY = buildFactory(false);
|
||||||
|
|
||||||
// Prevent XXE attacks
|
|
||||||
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
|
|
||||||
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
|
|
||||||
factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
|
|
||||||
factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
|
|
||||||
factory.setXIncludeAware(false);
|
|
||||||
factory.setExpandEntityReferences(false);
|
|
||||||
|
|
||||||
return factory;
|
|
||||||
} catch (ParserConfigurationException e) {
|
} catch (ParserConfigurationException e) {
|
||||||
log.error("CRITICAL: Failed to configure secure XML parser: {}", e.getMessage());
|
throw new ExceptionInInitializerError(e);
|
||||||
throw e;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static DocumentBuilderFactory buildFactory(boolean namespaceAware) throws ParserConfigurationException {
|
||||||
|
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
|
||||||
|
factory.setNamespaceAware(namespaceAware);
|
||||||
|
|
||||||
|
// Prevent XXE attacks
|
||||||
|
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
|
||||||
|
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
|
||||||
|
factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
|
||||||
|
factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
|
||||||
|
factory.setXIncludeAware(false);
|
||||||
|
factory.setExpandEntityReferences(false);
|
||||||
|
|
||||||
|
return factory;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static DocumentBuilderFactory getFactory(boolean namespaceAware) {
|
||||||
|
return namespaceAware ? NS_AWARE_FACTORY : NON_NS_AWARE_FACTORY;
|
||||||
|
}
|
||||||
|
|
||||||
public static DocumentBuilder createSecureDocumentBuilder(boolean namespaceAware)
|
public static DocumentBuilder createSecureDocumentBuilder(boolean namespaceAware)
|
||||||
throws ParserConfigurationException {
|
throws ParserConfigurationException {
|
||||||
return createSecureDocumentBuilderFactory(namespaceAware).newDocumentBuilder();
|
// newDocumentBuilder() is NOT thread-safe must create new builder each time
|
||||||
|
return getFactory(namespaceAware).newDocumentBuilder();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+3
@@ -26,6 +26,9 @@ import java.util.Set;
|
|||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
import org.booklore.test.RequiresPdfium;
|
||||||
|
|
||||||
|
@RequiresPdfium
|
||||||
class PdfMetadataExtractorTest {
|
class PdfMetadataExtractorTest {
|
||||||
|
|
||||||
private PdfMetadataExtractor extractor;
|
private PdfMetadataExtractor extractor;
|
||||||
|
|||||||
-171
@@ -1,171 +0,0 @@
|
|||||||
package org.booklore.service.metadata.writer;
|
|
||||||
|
|
||||||
import org.apache.xmpbox.XMPMetadata;
|
|
||||||
import org.apache.xmpbox.type.TextType;
|
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
|
||||||
import org.junit.jupiter.api.Nested;
|
|
||||||
import org.junit.jupiter.api.Test;
|
|
||||||
|
|
||||||
import java.util.Set;
|
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.*;
|
|
||||||
|
|
||||||
class BookLoreSchemaTest {
|
|
||||||
|
|
||||||
private XMPMetadata xmpMetadata;
|
|
||||||
private BookLoreSchema schema;
|
|
||||||
|
|
||||||
@BeforeEach
|
|
||||||
void setUp() {
|
|
||||||
xmpMetadata = XMPMetadata.createXMPMetadata();
|
|
||||||
schema = new BookLoreSchema(xmpMetadata);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Nested
|
|
||||||
class ScalarTextPropertiesTests {
|
|
||||||
@Test
|
|
||||||
void setSubtitle_addsPropertyToSchema() {
|
|
||||||
schema.setSubtitle("A Novel");
|
|
||||||
|
|
||||||
TextType property = (TextType) schema.getProperty(BookLoreSchema.SUBTITLE);
|
|
||||||
assertNotNull(property);
|
|
||||||
assertEquals("A Novel", property.getStringValue());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void setSubtitle_whenBlank_doesNotAddProperty() {
|
|
||||||
schema.setSubtitle(" ");
|
|
||||||
|
|
||||||
assertNull(schema.getProperty(BookLoreSchema.SUBTITLE));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void setIsbn10_addsPropertyToSchema() {
|
|
||||||
schema.setIsbn10("0123456789");
|
|
||||||
|
|
||||||
TextType property = (TextType) schema.getProperty(BookLoreSchema.ISBN_10);
|
|
||||||
assertNotNull(property);
|
|
||||||
assertEquals("0123456789", property.getStringValue());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void setLubimyczytacId_addsPropertyToSchema() {
|
|
||||||
schema.setLubimyczytacId("12345");
|
|
||||||
|
|
||||||
TextType property = (TextType) schema.getProperty(BookLoreSchema.LUBIMYCZYTAC_ID);
|
|
||||||
assertNotNull(property);
|
|
||||||
assertEquals("12345", property.getStringValue());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void setHardcoverBookId_addsPropertyToSchema() {
|
|
||||||
schema.setHardcoverBookId(98765);
|
|
||||||
|
|
||||||
TextType property = (TextType) schema.getProperty(BookLoreSchema.HARDCOVER_BOOK_ID);
|
|
||||||
assertNotNull(property);
|
|
||||||
assertEquals("98765", property.getStringValue());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Nested
|
|
||||||
class RatingPropertiesTests {
|
|
||||||
@Test
|
|
||||||
void setRating_formatsWithLocaleUS() {
|
|
||||||
schema.setRating(8.5);
|
|
||||||
|
|
||||||
TextType property = (TextType) schema.getProperty(BookLoreSchema.RATING);
|
|
||||||
assertNotNull(property);
|
|
||||||
assertEquals("8.50", property.getStringValue());
|
|
||||||
assertFalse(property.getStringValue().contains(","));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void setAmazonRating_formatsCorrectly() {
|
|
||||||
schema.setAmazonRating(4.25);
|
|
||||||
|
|
||||||
TextType property = (TextType) schema.getProperty(BookLoreSchema.AMAZON_RATING);
|
|
||||||
assertNotNull(property);
|
|
||||||
assertEquals("4.25", property.getStringValue());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void setGoodreadsRating_formatsCorrectly() {
|
|
||||||
schema.setGoodreadsRating(3.99);
|
|
||||||
|
|
||||||
TextType property = (TextType) schema.getProperty(BookLoreSchema.GOODREADS_RATING);
|
|
||||||
assertNotNull(property);
|
|
||||||
assertEquals("3.99", property.getStringValue());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void setRating_whenNull_doesNotAddProperty() {
|
|
||||||
schema.setRating(null);
|
|
||||||
|
|
||||||
assertNull(schema.getProperty(BookLoreSchema.RATING));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Nested
|
|
||||||
class TextCollectionPropertiesTests {
|
|
||||||
@Test
|
|
||||||
void setMoods_createsDelimitedText() {
|
|
||||||
schema.setMoods(Set.of("Dark", "Atmospheric", "Suspenseful"));
|
|
||||||
|
|
||||||
TextType property = (TextType) schema.getProperty(BookLoreSchema.MOODS);
|
|
||||||
assertNotNull(property);
|
|
||||||
String value = property.getStringValue();
|
|
||||||
assertTrue(value.contains("Dark"));
|
|
||||||
assertTrue(value.contains("Atmospheric"));
|
|
||||||
assertTrue(value.contains("Suspenseful"));
|
|
||||||
assertTrue(value.contains("; "));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void setMoods_whenEmpty_doesNotAddProperty() {
|
|
||||||
schema.setMoods(Set.of());
|
|
||||||
|
|
||||||
assertNull(schema.getProperty(BookLoreSchema.MOODS));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void setMoods_whenNull_doesNotAddProperty() {
|
|
||||||
schema.setMoods(null);
|
|
||||||
|
|
||||||
assertNull(schema.getProperty(BookLoreSchema.MOODS));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void setTags_createsDelimitedText() {
|
|
||||||
schema.setTags(Set.of("Fantasy", "Epic", "Magic"));
|
|
||||||
|
|
||||||
TextType property = (TextType) schema.getProperty(BookLoreSchema.TAGS);
|
|
||||||
assertNotNull(property);
|
|
||||||
String value = property.getStringValue();
|
|
||||||
assertTrue(value.contains("Fantasy"));
|
|
||||||
assertTrue(value.contains("Epic"));
|
|
||||||
assertTrue(value.contains("Magic"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void setTags_filtersBlankValues() {
|
|
||||||
schema.setTags(Set.of("Fantasy", " ", "Epic"));
|
|
||||||
|
|
||||||
TextType property = (TextType) schema.getProperty(BookLoreSchema.TAGS);
|
|
||||||
assertNotNull(property);
|
|
||||||
assertFalse(property.getStringValue().contains(" "));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Nested
|
|
||||||
class NamespaceTests {
|
|
||||||
@Test
|
|
||||||
void namespace_isCorrect() {
|
|
||||||
assertEquals("http://booklore.org/metadata/1.0/", BookLoreSchema.NAMESPACE);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void prefix_isCorrect() {
|
|
||||||
assertEquals("booklore", BookLoreSchema.PREFIX);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+11
-14
@@ -1,9 +1,7 @@
|
|||||||
package org.booklore.service.metadata.writer;
|
package org.booklore.service.metadata.writer;
|
||||||
|
|
||||||
import org.apache.pdfbox.Loader;
|
import org.grimmory.pdfium4j.PdfDocument;
|
||||||
import org.apache.pdfbox.pdmodel.PDDocument;
|
import org.grimmory.pdfium4j.model.PageSize;
|
||||||
import org.apache.pdfbox.pdmodel.PDPage;
|
|
||||||
import org.apache.pdfbox.pdmodel.common.PDMetadata;
|
|
||||||
import org.booklore.model.dto.BookMetadata;
|
import org.booklore.model.dto.BookMetadata;
|
||||||
import org.booklore.model.dto.settings.AppSettings;
|
import org.booklore.model.dto.settings.AppSettings;
|
||||||
import org.booklore.model.dto.settings.MetadataPersistenceSettings;
|
import org.booklore.model.dto.settings.MetadataPersistenceSettings;
|
||||||
@@ -21,7 +19,6 @@ import org.mockito.Mockito;
|
|||||||
|
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.nio.charset.StandardCharsets;
|
|
||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
import java.time.LocalDate;
|
import java.time.LocalDate;
|
||||||
@@ -33,6 +30,9 @@ import java.util.Set;
|
|||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.*;
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
import org.booklore.test.RequiresPdfium;
|
||||||
|
|
||||||
|
@RequiresPdfium
|
||||||
class PdfMetadataWriterTest {
|
class PdfMetadataWriterTest {
|
||||||
|
|
||||||
private PdfMetadataWriter writer;
|
private PdfMetadataWriter writer;
|
||||||
@@ -375,9 +375,9 @@ class PdfMetadataWriterTest {
|
|||||||
|
|
||||||
private File createEmptyPdf(String name) throws IOException {
|
private File createEmptyPdf(String name) throws IOException {
|
||||||
File pdf = tempDir.resolve(name).toFile();
|
File pdf = tempDir.resolve(name).toFile();
|
||||||
try (PDDocument doc = new PDDocument()) {
|
try (PdfDocument doc = PdfDocument.create()) {
|
||||||
doc.addPage(new PDPage());
|
doc.insertBlankPage(0, new PageSize(612, 792));
|
||||||
doc.save(pdf);
|
doc.save(pdf.toPath());
|
||||||
}
|
}
|
||||||
return pdf;
|
return pdf;
|
||||||
}
|
}
|
||||||
@@ -389,12 +389,9 @@ class PdfMetadataWriterTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private String readXmpContent(File pdf) throws IOException {
|
private String readXmpContent(File pdf) throws IOException {
|
||||||
try (PDDocument doc = Loader.loadPDF(pdf)) {
|
try (PdfDocument doc = PdfDocument.open(pdf.toPath())) {
|
||||||
PDMetadata metadata = doc.getDocumentCatalog().getMetadata();
|
String xmp = doc.xmpMetadataString();
|
||||||
if (metadata == null) {
|
return xmp != null ? xmp : "";
|
||||||
return "";
|
|
||||||
}
|
|
||||||
return new String(metadata.toByteArray(), StandardCharsets.UTF_8);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
package org.booklore.test;
|
||||||
|
|
||||||
|
import org.grimmory.pdfium4j.PdfiumLibrary;
|
||||||
|
import org.junit.jupiter.api.extension.ConditionEvaluationResult;
|
||||||
|
import org.junit.jupiter.api.extension.ExecutionCondition;
|
||||||
|
import org.junit.jupiter.api.extension.ExtensionContext;
|
||||||
|
|
||||||
|
public class PdfiumAvailableCondition implements ExecutionCondition {
|
||||||
|
|
||||||
|
private static final ConditionEvaluationResult ENABLED =
|
||||||
|
ConditionEvaluationResult.enabled("PDFium native library is available");
|
||||||
|
|
||||||
|
private static final Boolean AVAILABLE = probe();
|
||||||
|
|
||||||
|
private static Boolean probe() {
|
||||||
|
try {
|
||||||
|
PdfiumLibrary.initialize();
|
||||||
|
return true;
|
||||||
|
} catch (Exception | UnsatisfiedLinkError e) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
|
||||||
|
if (Boolean.TRUE.equals(AVAILABLE)) {
|
||||||
|
return ENABLED;
|
||||||
|
}
|
||||||
|
return ConditionEvaluationResult.disabled("PDFium native library not available on this platform");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package org.booklore.test;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
|
||||||
|
import java.lang.annotation.*;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Marks a test class or method as requiring PDFium native binaries.
|
||||||
|
* Tests annotated with this will be skipped (not failed) if the
|
||||||
|
* PDFium native library is not available on the current platform.
|
||||||
|
*/
|
||||||
|
@Target({ElementType.TYPE, ElementType.METHOD})
|
||||||
|
@Retention(RetentionPolicy.RUNTIME)
|
||||||
|
@ExtendWith(PdfiumAvailableCondition.class)
|
||||||
|
public @interface RequiresPdfium {
|
||||||
|
}
|
||||||
+7
-7
@@ -385,6 +385,13 @@ export class MetadataEditorComponent implements OnInit {
|
|||||||
this.metadataForm.addControl(field.controlName, new FormControl(defaultValue));
|
this.metadataForm.addControl(field.controlName, new FormControl(defaultValue));
|
||||||
this.metadataForm.addControl(field.lockedKey, new FormControl(false));
|
this.metadataForm.addControl(field.lockedKey, new FormControl(false));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
this.syncProviderFieldsEffect = effect(() => {
|
||||||
|
const settings = this.appSettingsService.appSettings();
|
||||||
|
if (settings?.metadataProviderSpecificFields) {
|
||||||
|
this.providerSpecificFields = settings.metadataProviderSpecificFields;
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
ngOnInit(): void {
|
ngOnInit(): void {
|
||||||
@@ -393,13 +400,6 @@ export class MetadataEditorComponent implements OnInit {
|
|||||||
this.metadataCenterViewMode = user.userSettings.metadataCenterViewMode ?? 'route';
|
this.metadataCenterViewMode = user.userSettings.metadataCenterViewMode ?? 'route';
|
||||||
this.autoSaveEnabled = user.userSettings.autoSaveMetadata ?? false;
|
this.autoSaveEnabled = user.userSettings.autoSaveMetadata ?? false;
|
||||||
}
|
}
|
||||||
|
|
||||||
this.syncProviderFieldsEffect = effect(() => {
|
|
||||||
const settings = this.appSettingsService.appSettings();
|
|
||||||
if (settings?.metadataProviderSpecificFields) {
|
|
||||||
this.providerSpecificFields = settings.metadataProviderSpecificFields;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private populateFormFromMetadata(metadata: BookMetadata): void {
|
private populateFormFromMetadata(metadata: BookMetadata): void {
|
||||||
|
|||||||
Reference in New Issue
Block a user