diff --git a/Dockerfile b/Dockerfile index 4aada8068..27c7f503e 100644 --- a/Dockerfile +++ b/Dockerfile @@ -16,6 +16,8 @@ RUN --mount=type=cache,target=/workspace/.yarn/cache \ FROM --platform=$BUILDPLATFORM gradle:9.3.1-jdk25-alpine AS backend-build +ARG TARGETARCH + WORKDIR /workspace/booklore-api 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 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; \ jar_path="$(find build/libs -maxdepth 1 -name '*.jar' ! -name '*plain.jar' | head -n 1)"; \ diff --git a/booklore-api/build.gradle.kts b/booklore-api/build.gradle.kts index b6dbba9dc..b58bba58d 100644 --- a/booklore-api/build.gradle.kts +++ b/booklore-api/build.gradle.kts @@ -26,11 +26,60 @@ java { } } +val useLocalLibs = providers.gradleProperty("useLocalLibs").isPresent + repositories { + if (useLocalLibs) mavenLocal() mavenCentral() 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 { compileOnly { extendsFrom(configurations.annotationProcessor.get()) @@ -67,13 +116,9 @@ dependencies { annotationProcessor("org.projectlombok:lombok:1.18.44") // --- Book & Image Processing --- - implementation("org.apache.pdfbox:pdfbox:3.0.7") - implementation("org.apache.pdfbox:pdfbox-io:3.0.7") - implementation("org.apache.pdfbox:xmpbox:3.0.7") - 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") + val pdfium4jVersion = if (useLocalLibs) "+" else "0.14.0" + implementation("org.grimmory:pdfium4j:$pdfium4jVersion") + runtimeOnly("org.grimmory:pdfium4j:$pdfium4jVersion:${pdfiumNativesClassifier()}") // --- TwelveMonkeys ImageIO --- 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-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) --- implementation("com.github.RouHim:jaudiotagger:2.0.19") @@ -129,6 +176,9 @@ dependencies { testImplementation("org.assertj:assertj-core:3.27.7") testImplementation("org.mockito:mockito-inline:5.2.0") testRuntimeOnly("com.h2database:h2") + + // PDFBox for test PDF creation only (production code uses PDFium4j) + testImplementation("org.apache.pdfbox:pdfbox:3.0.7") } hibernate { @@ -169,6 +219,7 @@ tasks.named("processResources") { } tasks.named("bootRun") { + jvmArgs("--enable-native-access=ALL-UNNAMED") if (System.getenv("REMOTE_DEBUG_ENABLED") == "true") { jvmArgs("-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005") } diff --git a/booklore-api/src/main/java/org/booklore/service/fileprocessor/PdfProcessor.java b/booklore-api/src/main/java/org/booklore/service/fileprocessor/PdfProcessor.java index c89831f94..5e56930f2 100644 --- a/booklore-api/src/main/java/org/booklore/service/fileprocessor/PdfProcessor.java +++ b/booklore-api/src/main/java/org/booklore/service/fileprocessor/PdfProcessor.java @@ -2,11 +2,8 @@ package org.booklore.service.fileprocessor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; -import org.apache.pdfbox.Loader; -import org.apache.pdfbox.io.RandomAccessReadBufferedFile; -import org.apache.pdfbox.pdmodel.PDDocument; -import org.apache.pdfbox.rendering.ImageType; -import org.apache.pdfbox.rendering.PDFRenderer; +import org.grimmory.pdfium4j.PdfDocument; +import org.grimmory.pdfium4j.PdfPage; import org.booklore.mapper.BookMapper; import org.booklore.model.dto.BookMetadata; import org.booklore.model.dto.settings.LibraryFile; @@ -75,9 +72,8 @@ public class PdfProcessor extends AbstractFileProcessor implements BookFileProce @Override public boolean generateCover(BookEntity bookEntity, BookFileEntity bookFile) { File pdfFile = FileUtils.getBookFullPath(bookEntity, bookFile).toFile(); - try (RandomAccessReadBufferedFile randomAccessRead = new RandomAccessReadBufferedFile(pdfFile); - PDDocument pdf = Loader.loadPDF(randomAccessRead)) { - return generateCoverImageAndSave(bookEntity.getId(), pdf); + try (PdfDocument doc = PdfDocument.open(pdfFile.toPath())) { + return generateCoverImageAndSave(bookEntity.getId(), doc); } catch (OutOfMemoryError e) { // Note: Catching OOM is generally discouraged, but for batch processing // 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; - try { - coverImage = new PDFRenderer(document).renderImageWithDPI(0, 150, ImageType.RGB); + try (PdfPage page = doc.page(0)) { + coverImage = page.render(150).toBufferedImage(); return fileService.saveCoverImages(coverImage, bookId); } catch (OutOfMemoryError e) { log.error("Out of memory (heap space exhausted) while generating cover for bookId {}. Skipping cover generation.", bookId); diff --git a/booklore-api/src/main/java/org/booklore/service/metadata/extractor/Fb2MetadataExtractor.java b/booklore-api/src/main/java/org/booklore/service/metadata/extractor/Fb2MetadataExtractor.java index 27c4dc7f9..9f41d3dd4 100644 --- a/booklore-api/src/main/java/org/booklore/service/metadata/extractor/Fb2MetadataExtractor.java +++ b/booklore-api/src/main/java/org/booklore/service/metadata/extractor/Fb2MetadataExtractor.java @@ -11,7 +11,6 @@ import org.w3c.dom.Node; import org.w3c.dom.NodeList; import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; @@ -39,8 +38,7 @@ public class Fb2MetadataExtractor implements FileMetadataExtractor { @Override public byte[] extractCover(File file) { try (InputStream inputStream = getInputStream(file)) { - DocumentBuilderFactory dbf = SecureXmlUtils.createSecureDocumentBuilderFactory(true); - DocumentBuilder builder = dbf.newDocumentBuilder(); + DocumentBuilder builder = SecureXmlUtils.createSecureDocumentBuilder(true); Document doc = builder.parse(inputStream); // Look for cover image in binary elements @@ -93,8 +91,7 @@ public class Fb2MetadataExtractor implements FileMetadataExtractor { @Override public BookMetadata extractMetadata(File file) { try (InputStream inputStream = getInputStream(file)) { - DocumentBuilderFactory dbf = SecureXmlUtils.createSecureDocumentBuilderFactory(true); - DocumentBuilder builder = dbf.newDocumentBuilder(); + DocumentBuilder builder = SecureXmlUtils.createSecureDocumentBuilder(true); Document doc = builder.parse(inputStream); BookMetadata.BookMetadataBuilder metadataBuilder = BookMetadata.builder(); diff --git a/booklore-api/src/main/java/org/booklore/service/metadata/extractor/PdfMetadataExtractor.java b/booklore-api/src/main/java/org/booklore/service/metadata/extractor/PdfMetadataExtractor.java index 888744eb2..d864faccd 100644 --- a/booklore-api/src/main/java/org/booklore/service/metadata/extractor/PdfMetadataExtractor.java +++ b/booklore-api/src/main/java/org/booklore/service/metadata/extractor/PdfMetadataExtractor.java @@ -2,38 +2,25 @@ package org.booklore.service.metadata.extractor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.FilenameUtils; -import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; -import org.apache.pdfbox.Loader; -import org.apache.pdfbox.cos.COSDictionary; -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.grimmory.pdfium4j.PdfDocument; +import org.grimmory.pdfium4j.model.MetadataTag; import org.booklore.model.dto.BookMetadata; import org.booklore.util.SecureXmlUtils; import org.springframework.stereotype.Component; import org.w3c.dom.Document; import org.w3c.dom.NodeList; +import org.xml.sax.InputSource; -import javax.imageio.ImageIO; import javax.xml.namespace.NamespaceContext; import javax.xml.parsers.DocumentBuilder; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; 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.InputStream; -import java.nio.charset.StandardCharsets; +import java.io.StringReader; import java.time.LocalDate; -import java.time.ZoneId; import java.util.*; import java.util.regex.Pattern; 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 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 public byte[] extractCover(File file) { - BufferedImage coverImage = null; - try (RandomAccessReadBufferedFile randomAccessRead = new RandomAccessReadBufferedFile(file); - 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(); - } + try (PdfDocument doc = PdfDocument.open(file.toPath())) { + return doc.renderPageToBytes(0, 300, "jpeg"); } catch (Exception e) { log.warn("Failed to extract cover from PDF: {}", file.getAbsolutePath(), e); 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(); - try (RandomAccessReadBufferedFile randomAccessRead = new RandomAccessReadBufferedFile(file); - PDDocument pdf = Loader.loadPDF(randomAccessRead)) { - PDDocumentInformation info = pdf.getDocumentInformation(); + try (PdfDocument doc = PdfDocument.open(file.toPath())) { - if (info != null) { - if (StringUtils.isNotBlank(info.getTitle())) { - metadataBuilder.title(info.getTitle()); - } else { - metadataBuilder.title(FilenameUtils.getBaseName(file.getName())); - } + String title = doc.metadata(MetadataTag.TITLE).orElse(null); + if (StringUtils.isNotBlank(title)) { + metadataBuilder.title(title); + } else { + metadataBuilder.title(FilenameUtils.getBaseName(file.getName())); + } - if (StringUtils.isNotBlank(info.getAuthor())) { - List authors = parseAuthors(info.getAuthor()); - 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 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); + String author = doc.metadata(MetadataTag.AUTHOR).orElse(null); + if (StringUtils.isNotBlank(author)) { + List authors = parseAuthors(author); + if (!authors.isEmpty()) { + metadataBuilder.authors(authors); } } - PDMetadata metadata = pdf.getDocumentCatalog().getMetadata(); + String subject = doc.metadata(MetadataTag.SUBJECT).orElse(null); + if (StringUtils.isNotBlank(subject)) { + metadataBuilder.description(subject); + } - if (metadata != null) { - try (InputStream is = metadata.createInputStream()) { - if (is == null) { - 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))); + String ebxPublisher = doc.metadata("EBX_PUBLISHER").orElse(null); + if (StringUtils.isNotBlank(ebxPublisher)) { + metadataBuilder.publisher(ebxPublisher); + } - XPathFactory xPathfactory = XPathFactory.newInstance(); - XPath xpath = xPathfactory.newXPath(); - xpath.setNamespaceContext(new XmpNamespaceContext()); + String creationDate = doc.metadata(MetadataTag.CREATION_DATE).orElse(null); + if (StringUtils.isNotBlank(creationDate)) { + LocalDate date = parsePdfDate(creationDate); + if (date != null) { + metadataBuilder.publishedDate(date); + } + } - extractDublinCoreMetadata(xpath, doc, metadataBuilder); - extractCalibreMetadata(xpath, doc, metadataBuilder); - extractBookloreMetadata(xpath, doc, 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()); + metadataBuilder.pageCount(doc.pageCount()); + + String keywords = doc.metadata(MetadataTag.KEYWORDS).orElse(null); + if (StringUtils.isNotBlank(keywords)) { + String[] parts; + if (keywords.contains(";")) { + parts = keywords.split(";"); + } else { + parts = keywords.split(","); + } + Set 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 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 identifiers = extractIdentifiers(xpath, doc); - 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 - } - } - - // 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); - } + // 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); + } } } catch (Exception e) { log.warn("Failed to parse XMP metadata with XML parser: {}", e.getMessage(), e); @@ -551,9 +521,43 @@ public class PdfMetadataExtractor implements FileMetadataExtractor { .toList(); } - private LocalDate convertCalendarToLocalDate(Calendar calendar) { - if (calendar == null) return null; - return calendar.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); + /** + * Parses PDF date strings in the standard D:YYYYMMDDHHmmSS format. + * 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 { diff --git a/booklore-api/src/main/java/org/booklore/service/metadata/writer/BookLoreSchema.java b/booklore-api/src/main/java/org/booklore/service/metadata/writer/BookLoreSchema.java deleted file mode 100644 index d730d6600..000000000 --- a/booklore-api/src/main/java/org/booklore/service/metadata/writer/BookLoreSchema.java +++ /dev/null @@ -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 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 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); - } - } -} - diff --git a/booklore-api/src/main/java/org/booklore/service/metadata/writer/PdfMetadataWriter.java b/booklore-api/src/main/java/org/booklore/service/metadata/writer/PdfMetadataWriter.java index 7087e8fd1..df5c7c456 100644 --- a/booklore-api/src/main/java/org/booklore/service/metadata/writer/PdfMetadataWriter.java +++ b/booklore-api/src/main/java/org/booklore/service/metadata/writer/PdfMetadataWriter.java @@ -2,40 +2,26 @@ package org.booklore.service.metadata.writer; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.apache.pdfbox.Loader; -import org.apache.pdfbox.io.IOUtils; -import org.apache.pdfbox.pdmodel.PDDocument; -import org.apache.pdfbox.pdmodel.PDDocumentInformation; -import org.apache.pdfbox.pdmodel.common.PDMetadata; -import org.apache.xmpbox.XMPMetadata; -import org.apache.xmpbox.schema.DublinCoreSchema; -import org.apache.xmpbox.xml.XmpSerializer; +import org.grimmory.pdfium4j.PdfDocument; +import org.grimmory.pdfium4j.XmpMetadataWriter; +import org.grimmory.pdfium4j.model.MetadataTag; +import org.grimmory.pdfium4j.model.SaveOptions; +import org.grimmory.pdfium4j.model.XmpMetadata; import org.booklore.model.MetadataClearFlags; import org.booklore.model.dto.settings.MetadataPersistenceSettings; import org.booklore.model.entity.BookMetadataEntity; import org.booklore.model.enums.BookFileType; import org.booklore.service.appsettings.AppSettingService; -import org.booklore.util.SecureXmlUtils; import org.booklore.service.metadata.BookLoreMetadata; 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.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; -import java.time.ZoneId; import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; import java.util.*; @Slf4j @@ -70,12 +56,10 @@ public class PdfMetadataWriter implements MetadataWriter { log.warn("Could not create PDF temp backup for {}: {}", file.getName(), e.getMessage()); } - try (PDDocument pdf = Loader.loadPDF(file, IOUtils.createTempFileOnlyStreamCache())) { - pdf.setAllSecurityToBeRemoved(true); - applyMetadataToDocument(pdf, metadataEntity, clear); + try (PdfDocument doc = PdfDocument.open(filePath)) { + applyMetadataToDocument(doc, metadataEntity, clear); tempFile = File.createTempFile("pdfmeta-", ".pdf"); - // PDFBox 3.x saves in compressed mode by default - pdf.save(tempFile); + doc.save(tempFile.toPath(), SaveOptions.SKIP_VALIDATION); Files.move(tempFile.toPath(), filePath, StandardCopyOption.REPLACE_EXISTING); tempFile = null; // Prevent deletion in finally block after successful move 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) private static final int MAX_INFO_KEYWORDS_LENGTH = 255; - private void applyMetadataToDocument(PDDocument pdf, BookMetadataEntity entity, MetadataClearFlags clear) { - PDDocumentInformation info = pdf.getDocumentInformation(); + private void applyMetadataToDocument(PdfDocument doc, BookMetadataEntity entity, MetadataClearFlags clear) { MetadataCopyHelper helper = new MetadataCopyHelper(entity); - // Build categories-only keywords for PDF legacy compatibility (Info Dictionary) - // Moods and tags are stored separately in XMP booklore namespace, so they should NOT be in Info Dict keywords + // --- PDF Info Dictionary (legacy) via PDFium4j --- StringBuilder keywordsBuilder = new StringBuilder(); helper.copyCategories(clear != null && clear.isCategories(), cats -> { 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.copyPublisher(clear != null && clear.isPublisher(), pub -> info.setProducer(pub != null ? pub : "")); - helper.copyAuthors(clear != null && clear.isAuthors(), authors -> info.setAuthor(authors != null ? String.join(", ", authors) : "")); + helper.copyTitle(clear != null && clear.isTitle(), title -> doc.setMetadata(MetadataTag.TITLE, title != null ? title : "")); + helper.copyPublisher(clear != null && clear.isPublisher(), pub -> doc.setMetadata(MetadataTag.PRODUCER, pub != null ? pub : "")); + helper.copyAuthors(clear != null && clear.isAuthors(), authors -> doc.setMetadata(MetadataTag.AUTHOR, authors != null ? String.join(", ", authors) : "")); helper.copyPublishedDate(clear != null && clear.isPublishedDate(), date -> { - Calendar cal = Calendar.getInstance(); - cal.setTimeInMillis((date != null ? date : ZonedDateTime.now().toLocalDate()) - .atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli()); - info.setCreationDate(cal); + if (date != null) { + // PDF date format: D:YYYYMMDDHHmmSS + String pdfDate = String.format("D:%04d%02d%02d000000", date.getYear(), date.getMonthValue(), date.getDayOfMonth()); + 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(); if (keywords.length() > MAX_INFO_KEYWORDS_LENGTH) { keywords = keywords.substring(0, MAX_INFO_KEYWORDS_LENGTH - 3) + "..."; log.debug("PDF keywords truncated from {} to {} characters for legacy compatibility", keywordsBuilder.length(), keywords.length()); } - info.setKeywords(keywords); + doc.setMetadata(MetadataTag.KEYWORDS, keywords); + // --- XMP metadata via PDFium4j XmpMetadataWriter (StringBuilder-based, no DOM) --- try { - XMPMetadata xmp = XMPMetadata.createXMPMetadata(); - DublinCoreSchema dc = xmp.createAndAddDublinCoreSchema(); + String newXmp = buildXmpPacket(helper, clear, entity); + String existingXmp = doc.xmpMetadataString(); - helper.copyTitle(clear != null && clear.isTitle(), title -> dc.setTitle(title != null ? title : "")); - 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)) { + if (!isXmpMetadataDifferent(existingXmp, newXmp)) { log.info("XMP metadata unchanged, skipping write"); return; } - PDMetadata pdMetadata = new PDMetadata(pdf); - pdMetadata.importXMPMetadata(newXmpBytes); - pdf.getDocumentCatalog().setMetadata(pdMetadata); - + doc.setXmpMetadata(newXmp); log.info("XMP metadata updated for PDF"); } catch (Exception e) { log.warn("Failed to embed XMP metadata: {}", e.getMessage(), e); } } - /** - * Adds custom metadata to XMP using Booklore namespace for all custom fields. - *

- * 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 + * Builds the complete XMP packet using PDFium4j's StringBuilder-based XmpMetadataWriter. + * Eliminates all DOM and TransformerFactory overhead from the old approach. */ - private byte[] addCustomIdentifiersToXmp(byte[] xmpBytes, BookMetadataEntity metadata, MetadataCopyHelper helper, MetadataClearFlags clear) throws Exception { - DocumentBuilder builder = SecureXmlUtils.createSecureDocumentBuilder(true); - Document doc = builder.parse(new ByteArrayInputStream(xmpBytes)); + @SuppressWarnings("unchecked") + private String buildXmpPacket(MetadataCopyHelper helper, MetadataClearFlags clear, BookMetadataEntity metadata) { + // Capture DC field values from helper + String[] title = {null}, description = {null}, publisher = {null}, language = {null}, date = {null}; + List[] authors = new List[]{null}; + List[] subjects = new List[]{null}; - Element rdfRoot = (Element) doc.getElementsByTagNameNS("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "RDF").item(0); - if (rdfRoot == null) throw new IllegalStateException("RDF root missing in XMP"); + helper.copyTitle(clear != null && clear.isTitle(), t -> title[0] = t); + 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 - Element xmpBasicDescription = doc.createElementNS("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "rdf:Description"); - 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", ""); + // Build custom fields map + Map customFields = new LinkedHashMap<>(); - xmpBasicDescription.appendChild(createXmpElement(doc, "xmp:CreatorTool", "Booklore")); - // Use ISO-8601 format for current timestamps - String nowIso = ZonedDateTime.now().format(java.time.format.DateTimeFormatter.ISO_INSTANT); - xmpBasicDescription.appendChild(createXmpElement(doc, "xmp:MetadataDate", nowIso)); - xmpBasicDescription.appendChild(createXmpElement(doc, "xmp:ModifyDate", nowIso)); - if (metadata.getPublishedDate() != null) { - // Use date-only format (YYYY-MM-DD) when we only have a date, not a full timestamp - xmpBasicDescription.appendChild(createXmpElement(doc, "xmp:CreateDate", - metadata.getPublishedDate().toString())); + // XMP Basic (unprefixed → written as xmp: by XmpMetadataWriter) + customFields.put("CreatorTool", "Booklore"); + String nowIso = ZonedDateTime.now().format(DateTimeFormatter.ISO_INSTANT); + customFields.put("MetadataDate", nowIso); + customFields.put("ModifyDate", nowIso); + if (date[0] != null) { + customFields.put("CreateDate", date[0]); } - rdfRoot.appendChild(xmpBasicDescription); + // Booklore namespace simple fields + addBookloreSimpleFields(customFields, helper, clear, metadata); - // Booklore namespace for all custom metadata - Element bookloreDescription = doc.createElementNS("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "rdf:Description"); - bookloreDescription.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" + BookLoreMetadata.NS_PREFIX, BookLoreMetadata.NS_URI); - bookloreDescription.setAttributeNS("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "rdf:about", ""); + XmpMetadata xmpMeta = new XmpMetadata( + Optional.ofNullable(title[0]), + authors[0] != null ? authors[0] : List.of(), + 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 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)) { - appendBookloreElement(doc, bookloreDescription, "seriesName", metadata.getSeriesName()); - appendBookloreElement(doc, bookloreDescription, "seriesNumber", formatSeriesNumber(metadata.getSeriesNumber())); - - // Series total is optional, only write if > 0 + customFields.put(prefix + "seriesName", metadata.getSeriesName()); + customFields.put(prefix + "seriesNumber", formatSeriesNumber(metadata.getSeriesNumber())); + if (metadata.getSeriesTotal() != null && metadata.getSeriesTotal() > 0) { helper.copySeriesTotal(clear != null && clear.isSeriesTotal(), total -> { 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 -> { - if (subtitle != null && !subtitle.isBlank()) { - appendBookloreElement(doc, bookloreDescription, "subtitle", subtitle); - } + if (subtitle != null && !subtitle.isBlank()) customFields.put(prefix + "subtitle", subtitle); }); - // ISBN Identifiers helper.copyIsbn13(clear != null && clear.isIsbn13(), isbn -> { - if (isbn != null && !isbn.isBlank()) { - appendBookloreElement(doc, bookloreDescription, "isbn13", isbn); - } + if (isbn != null && !isbn.isBlank()) customFields.put(prefix + "isbn13", isbn); }); - helper.copyIsbn10(clear != null && clear.isIsbn10(), isbn -> { - if (isbn != null && !isbn.isBlank()) { - appendBookloreElement(doc, bookloreDescription, "isbn10", isbn); - } + if (isbn != null && !isbn.isBlank()) customFields.put(prefix + "isbn10", isbn); }); - // External IDs (only if not blank) helper.copyGoogleId(clear != null && clear.isGoogleId(), id -> { - if (id != null && !id.isBlank()) { - appendBookloreElement(doc, bookloreDescription, "googleId", id); - } + if (id != null && !id.isBlank()) customFields.put(prefix + "googleId", id); }); - helper.copyGoodreadsId(clear != null && clear.isGoodreadsId(), id -> { - String normalizedId = normalizeGoodreadsId(id); - if (normalizedId != null && !normalizedId.isBlank()) { - appendBookloreElement(doc, bookloreDescription, "goodreadsId", normalizedId); - } + String normalized = normalizeGoodreadsId(id); + if (normalized != null && !normalized.isBlank()) customFields.put(prefix + "goodreadsId", normalized); }); - helper.copyHardcoverId(clear != null && clear.isHardcoverId(), id -> { - if (id != null && !id.isBlank()) { - appendBookloreElement(doc, bookloreDescription, "hardcoverId", id); - } + if (id != null && !id.isBlank()) customFields.put(prefix + "hardcoverId", id); }); - helper.copyHardcoverBookId(clear != null && clear.isHardcoverBookId(), id -> { - if (id != null && !id.isBlank()) { - appendBookloreElement(doc, bookloreDescription, "hardcoverBookId", id); - } + if (id != null && !id.isBlank()) customFields.put(prefix + "hardcoverBookId", id); }); - helper.copyAsin(clear != null && clear.isAsin(), id -> { - if (id != null && !id.isBlank()) { - appendBookloreElement(doc, bookloreDescription, "asin", id); - } + if (id != null && !id.isBlank()) customFields.put(prefix + "asin", id); }); - helper.copyComicvineId(clear != null && clear.isComicvineId(), id -> { - if (id != null && !id.isBlank()) { - appendBookloreElement(doc, bookloreDescription, "comicvineId", id); - } + if (id != null && !id.isBlank()) customFields.put(prefix + "comicvineId", id); }); - helper.copyLubimyczytacId(clear != null && clear.isLubimyczytacId(), id -> { - if (id != null && !id.isBlank()) { - appendBookloreElement(doc, bookloreDescription, "lubimyczytacId", id); - } + if (id != null && !id.isBlank()) customFields.put(prefix + "lubimyczytacId", id); }); - helper.copyRanobedbId(clear != null && clear.isRanobedbId(), id -> { - if (id != null && !id.isBlank()) { - appendBookloreElement(doc, bookloreDescription, "ranobedbId", id); - } + if (id != null && !id.isBlank()) customFields.put(prefix + "ranobedbId", id); }); - // Ratings (only if > 0) - helper.copyRating(false, rating -> appendBookloreRating(doc, bookloreDescription, "rating", rating)); - helper.copyHardcoverRating(clear != null && clear.isHardcoverRating(), rating -> appendBookloreRating(doc, bookloreDescription, "hardcoverRating", rating)); - helper.copyGoodreadsRating(clear != null && clear.isGoodreadsRating(), rating -> appendBookloreRating(doc, bookloreDescription, "goodreadsRating", rating)); - helper.copyAmazonRating(clear != null && clear.isAmazonRating(), rating -> appendBookloreRating(doc, bookloreDescription, "amazonRating", rating)); - helper.copyLubimyczytacRating(clear != null && clear.isLubimyczytacRating(), rating -> appendBookloreRating(doc, bookloreDescription, "lubimyczytacRating", rating)); - helper.copyRanobedbRating(clear != null && clear.isRanobedbRating(), rating -> appendBookloreRating(doc, bookloreDescription, "ranobedbRating", rating)); + helper.copyRating(false, rating -> addBookloreRating(customFields, prefix, "rating", rating)); + helper.copyHardcoverRating(clear != null && clear.isHardcoverRating(), + rating -> addBookloreRating(customFields, prefix, "hardcoverRating", rating)); + helper.copyGoodreadsRating(clear != null && clear.isGoodreadsRating(), + rating -> addBookloreRating(customFields, prefix, "goodreadsRating", rating)); + helper.copyAmazonRating(clear != null && clear.isAmazonRating(), + 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 -> { 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) { - 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) { + private void addBookloreRating(Map customFields, String prefix, String name, Double rating) { if (rating != null && rating > 0) { - Element elem = doc.createElementNS(BookLoreMetadata.NS_URI, BookLoreMetadata.NS_PREFIX + ":" + localName); - elem.setTextContent(String.format(Locale.US, "%.1f", rating)); - parent.appendChild(elem); + customFields.put(prefix + name, String.format(Locale.US, "%.1f", rating)); } } - private void appendBookloreBag(Document doc, Element parent, String localName, Set values) { - Element elem = doc.createElementNS(BookLoreMetadata.NS_URI, BookLoreMetadata.NS_PREFIX + ":" + localName); - Element rdfBag = doc.createElementNS("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "rdf:Bag"); - - for (String value : values) { - if (value != null && !value.isBlank()) { - Element li = doc.createElementNS("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "rdf:li"); - li.setTextContent(value); - rdfBag.appendChild(li); + /** + * Injects RDF Bag elements for tags/moods into the XMP packet string. + * 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(); + + helper.copyTags(clear != null && clear.isTags(), tags -> { + if (tags != null && !tags.isEmpty()) appendBagXml(bags, "tags", tags); + }); + helper.copyMoods(clear != null && clear.isMoods(), moods -> { + if (moods != null && !moods.isEmpty()) appendBagXml(bags, "moods", moods); + }); + + if (bags.isEmpty()) return xmpPacket; + + int idx = xmpPacket.lastIndexOf(""); + if (idx < 0) return xmpPacket; + return xmpPacket.substring(0, idx) + bags + xmpPacket.substring(idx); + } + + private void appendBagXml(StringBuilder sb, String localName, Set values) { + sb.append("\n"); + sb.append(" <").append(BookLoreMetadata.NS_PREFIX).append(':').append(localName).append(">\n"); + sb.append(" \n"); + for (String v : values.stream().sorted().toList()) { + if (v != null && !v.isBlank()) { + sb.append(" ").append(escapeXml(v)).append("\n"); } } - - elem.appendChild(rdfBag); - parent.appendChild(elem); + sb.append(" \n"); + sb.append(" \n"); + sb.append("\n"); } - private boolean isXmpMetadataDifferent(byte[] existingBytes, byte[] newBytes) { - if (existingBytes == null || newBytes == null) return true; - try { - DocumentBuilder builder = SecureXmlUtils.createSecureDocumentBuilder(false); - Document doc1 = builder.parse(new ByteArrayInputStream(existingBytes)); - Document doc2 = builder.parse(new ByteArrayInputStream(newBytes)); - return !Objects.equals( - doc1.getDocumentElement().getTextContent().trim(), - doc2.getDocumentElement().getTextContent().trim() - ); - } catch (Exception e) { - log.warn("XMP diff failed: {}", e.getMessage()); - return true; - } + private static String escapeXml(String s) { + if (s == null) return ""; + return s.replace("&", "&").replace("<", "<").replace(">", ">").replace("\"", """); + } + + private static final java.util.regex.Pattern TIMESTAMP_PATTERN = java.util.regex.Pattern.compile( + "[^<]*"); + + private boolean isXmpMetadataDifferent(String existingXmp, String newXmp) { + if (existingXmp == null || existingXmp.isBlank() || newXmp == null) return true; + // Strip regenerated timestamps before comparing so the check is deterministic + String normalizedExisting = TIMESTAMP_PATTERN.matcher(existingXmp).replaceAll(""); + String normalizedNew = TIMESTAMP_PATTERN.matcher(newXmp).replaceAll(""); + return !normalizedExisting.equals(normalizedNew); } /** diff --git a/booklore-api/src/main/java/org/booklore/service/reader/EpubReaderService.java b/booklore-api/src/main/java/org/booklore/service/reader/EpubReaderService.java index 34643b74c..357ce549c 100644 --- a/booklore-api/src/main/java/org/booklore/service/reader/EpubReaderService.java +++ b/booklore-api/src/main/java/org/booklore/service/reader/EpubReaderService.java @@ -4,7 +4,6 @@ import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipFile; -import org.apache.pdfbox.io.IOUtils; import org.booklore.exception.ApiError; import org.booklore.model.dto.response.EpubBookInfo; import org.booklore.model.dto.response.EpubManifestItem; @@ -745,7 +744,7 @@ public class EpubReaderService { ZipArchiveEntry entry = zipFile.getEntry(entryName); if (entry != null) { try (InputStream in = new BufferedInputStream(zipFile.getInputStream(entry), BUFFER_SIZE)) { - IOUtils.copy(in, outputStream); + in.transferTo(outputStream); } return true; } diff --git a/booklore-api/src/main/java/org/booklore/service/reader/PdfReaderService.java b/booklore-api/src/main/java/org/booklore/service/reader/PdfReaderService.java index 9e6b204c4..8ad8a715a 100644 --- a/booklore-api/src/main/java/org/booklore/service/reader/PdfReaderService.java +++ b/booklore-api/src/main/java/org/booklore/service/reader/PdfReaderService.java @@ -2,14 +2,8 @@ package org.booklore.service.reader; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.apache.pdfbox.Loader; -import org.apache.pdfbox.io.RandomAccessReadBufferedFile; -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.grimmory.pdfium4j.PdfDocument; +import org.grimmory.pdfium4j.model.Bookmark; import org.booklore.exception.ApiError; import org.booklore.model.dto.response.PdfBookInfo; import org.booklore.model.dto.response.PdfOutlineItem; @@ -20,8 +14,6 @@ import org.booklore.repository.BookRepository; import org.booklore.util.FileUtils; import org.springframework.stereotype.Service; -import javax.imageio.ImageIO; -import java.awt.image.BufferedImage; import java.io.FileNotFoundException; import java.io.IOException; import java.io.OutputStream; @@ -146,26 +138,21 @@ public class PdfReaderService { throw new FileNotFoundException("PDF file is not readable: " + pdfPath); } long lastModified = Files.getLastModifiedTime(pdfPath).toMillis(); - try (RandomAccessReadBufferedFile randomAccessRead = new RandomAccessReadBufferedFile(pdfPath.toFile()); - PDDocument document = Loader.loadPDF(randomAccessRead)) { - int pageCount = document.getNumberOfPages(); - List outline = extractOutline(document); + try (PdfDocument doc = PdfDocument.open(pdfPath)) { + int pageCount = doc.pageCount(); + List outline = extractOutline(doc); return new CachedPdfMetadata(pageCount, lastModified, outline); } } - private List extractOutline(PDDocument document) { + private List extractOutline(PdfDocument doc) { List outline = new ArrayList<>(); try { - PDDocumentOutline documentOutline = document.getDocumentCatalog().getDocumentOutline(); - if (documentOutline != null) { - PDOutlineItem item = documentOutline.getFirstChild(); - while (item != null) { - PdfOutlineItem outlineItem = buildOutlineItem(document, item); - if (outlineItem != null) { - outline.add(outlineItem); - } - item = item.getNextSibling(); + List bookmarks = doc.bookmarks(); + for (Bookmark bookmark : bookmarks) { + PdfOutlineItem outlineItem = convertBookmark(bookmark); + if (outlineItem != null) { + outline.add(outlineItem); } } } catch (Exception e) { @@ -174,34 +161,22 @@ public class PdfReaderService { return outline; } - private PdfOutlineItem buildOutlineItem(PDDocument document, PDOutlineItem item) { + private PdfOutlineItem convertBookmark(Bookmark bookmark) { try { - String title = item.getTitle(); + String title = bookmark.title(); if (title == null || title.isBlank()) { return null; } - Integer pageNumber = null; - try { - 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()); - } + // PDFium4j pageIndex is 0-based, PdfOutlineItem.pageNumber is 1-based + Integer pageNumber = bookmark.isInternal() ? bookmark.pageIndex() + 1 : null; List children = new ArrayList<>(); - PDOutlineItem child = item.getFirstChild(); - while (child != null) { - PdfOutlineItem childItem = buildOutlineItem(document, child); + for (Bookmark child : bookmark.children()) { + PdfOutlineItem childItem = convertBookmark(child); if (childItem != null) { children.add(childItem); } - child = child.getNextSibling(); } return PdfOutlineItem.builder() @@ -231,18 +206,10 @@ public class PdfReaderService { } private void renderPageToStream(Path pdfPath, int page, OutputStream outputStream) throws IOException { - try (RandomAccessReadBufferedFile randomAccessRead = new RandomAccessReadBufferedFile(pdfPath.toFile()); - PDDocument document = Loader.loadPDF(randomAccessRead)) { - PDFRenderer renderer = new PDFRenderer(document); - BufferedImage image = null; - try { - image = renderer.renderImageWithDPI(page - 1, DEFAULT_DPI, ImageType.RGB); - ImageIO.write(image, "JPEG", outputStream); - } finally { - if (image != null) { - image.flush(); - } - } + try (PdfDocument doc = PdfDocument.open(pdfPath)) { + // page is 1-based from the API, renderPageToBytes expects 0-based + byte[] jpeg = doc.renderPageToBytes(page - 1, (int) DEFAULT_DPI, "jpeg"); + outputStream.write(jpeg); } catch (IOException e) { log.error("Failed to render PDF page {} from {}", page, pdfPath, e); throw e; diff --git a/booklore-api/src/main/java/org/booklore/util/SecureXmlUtils.java b/booklore-api/src/main/java/org/booklore/util/SecureXmlUtils.java index 45e3f48a5..e2a021942 100644 --- a/booklore-api/src/main/java/org/booklore/util/SecureXmlUtils.java +++ b/booklore-api/src/main/java/org/booklore/util/SecureXmlUtils.java @@ -12,28 +12,41 @@ import javax.xml.parsers.ParserConfigurationException; @UtilityClass 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 { - 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; + NS_AWARE_FACTORY = buildFactory(true); + NON_NS_AWARE_FACTORY = buildFactory(false); } catch (ParserConfigurationException e) { - log.error("CRITICAL: Failed to configure secure XML parser: {}", e.getMessage()); - throw e; + throw new ExceptionInInitializerError(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) throws ParserConfigurationException { - return createSecureDocumentBuilderFactory(namespaceAware).newDocumentBuilder(); + // newDocumentBuilder() is NOT thread-safe must create new builder each time + return getFactory(namespaceAware).newDocumentBuilder(); } } diff --git a/booklore-api/src/test/java/org/booklore/service/metadata/extractor/PdfMetadataExtractorTest.java b/booklore-api/src/test/java/org/booklore/service/metadata/extractor/PdfMetadataExtractorTest.java index 6ad1b10a5..ff9bf9ecc 100644 --- a/booklore-api/src/test/java/org/booklore/service/metadata/extractor/PdfMetadataExtractorTest.java +++ b/booklore-api/src/test/java/org/booklore/service/metadata/extractor/PdfMetadataExtractorTest.java @@ -26,6 +26,9 @@ import java.util.Set; import static org.assertj.core.api.Assertions.assertThat; +import org.booklore.test.RequiresPdfium; + +@RequiresPdfium class PdfMetadataExtractorTest { private PdfMetadataExtractor extractor; diff --git a/booklore-api/src/test/java/org/booklore/service/metadata/writer/BookLoreSchemaTest.java b/booklore-api/src/test/java/org/booklore/service/metadata/writer/BookLoreSchemaTest.java deleted file mode 100644 index 2ba9574d6..000000000 --- a/booklore-api/src/test/java/org/booklore/service/metadata/writer/BookLoreSchemaTest.java +++ /dev/null @@ -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); - } - } -} diff --git a/booklore-api/src/test/java/org/booklore/service/metadata/writer/PdfMetadataWriterTest.java b/booklore-api/src/test/java/org/booklore/service/metadata/writer/PdfMetadataWriterTest.java index f9c27e2be..b0990c2c8 100644 --- a/booklore-api/src/test/java/org/booklore/service/metadata/writer/PdfMetadataWriterTest.java +++ b/booklore-api/src/test/java/org/booklore/service/metadata/writer/PdfMetadataWriterTest.java @@ -1,9 +1,7 @@ package org.booklore.service.metadata.writer; -import org.apache.pdfbox.Loader; -import org.apache.pdfbox.pdmodel.PDDocument; -import org.apache.pdfbox.pdmodel.PDPage; -import org.apache.pdfbox.pdmodel.common.PDMetadata; +import org.grimmory.pdfium4j.PdfDocument; +import org.grimmory.pdfium4j.model.PageSize; import org.booklore.model.dto.BookMetadata; import org.booklore.model.dto.settings.AppSettings; import org.booklore.model.dto.settings.MetadataPersistenceSettings; @@ -21,7 +19,6 @@ import org.mockito.Mockito; import java.io.File; import java.io.IOException; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.time.LocalDate; @@ -33,6 +30,9 @@ import java.util.Set; import static org.junit.jupiter.api.Assertions.*; +import org.booklore.test.RequiresPdfium; + +@RequiresPdfium class PdfMetadataWriterTest { private PdfMetadataWriter writer; @@ -375,9 +375,9 @@ class PdfMetadataWriterTest { private File createEmptyPdf(String name) throws IOException { File pdf = tempDir.resolve(name).toFile(); - try (PDDocument doc = new PDDocument()) { - doc.addPage(new PDPage()); - doc.save(pdf); + try (PdfDocument doc = PdfDocument.create()) { + doc.insertBlankPage(0, new PageSize(612, 792)); + doc.save(pdf.toPath()); } return pdf; } @@ -389,12 +389,9 @@ class PdfMetadataWriterTest { } private String readXmpContent(File pdf) throws IOException { - try (PDDocument doc = Loader.loadPDF(pdf)) { - PDMetadata metadata = doc.getDocumentCatalog().getMetadata(); - if (metadata == null) { - return ""; - } - return new String(metadata.toByteArray(), StandardCharsets.UTF_8); + try (PdfDocument doc = PdfDocument.open(pdf.toPath())) { + String xmp = doc.xmpMetadataString(); + return xmp != null ? xmp : ""; } } } diff --git a/booklore-api/src/test/java/org/booklore/test/PdfiumAvailableCondition.java b/booklore-api/src/test/java/org/booklore/test/PdfiumAvailableCondition.java new file mode 100644 index 000000000..70dd12615 --- /dev/null +++ b/booklore-api/src/test/java/org/booklore/test/PdfiumAvailableCondition.java @@ -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"); + } +} diff --git a/booklore-api/src/test/java/org/booklore/test/RequiresPdfium.java b/booklore-api/src/test/java/org/booklore/test/RequiresPdfium.java new file mode 100644 index 000000000..9ec82b3ee --- /dev/null +++ b/booklore-api/src/test/java/org/booklore/test/RequiresPdfium.java @@ -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 { +} diff --git a/frontend/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.ts b/frontend/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.ts index f0ae910b8..a84086241 100644 --- a/frontend/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.ts +++ b/frontend/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.ts @@ -385,6 +385,13 @@ export class MetadataEditorComponent implements OnInit { this.metadataForm.addControl(field.controlName, new FormControl(defaultValue)); 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 { @@ -393,13 +400,6 @@ export class MetadataEditorComponent implements OnInit { this.metadataCenterViewMode = user.userSettings.metadataCenterViewMode ?? 'route'; 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 {