fix(pdf-writer): use same-dir temp files and harden cleanup (#719)

This commit is contained in:
brios
2026-04-22 17:27:43 -04:00
committed by Zach Yale
parent 284e7bec49
commit 9601667061
2 changed files with 31 additions and 24 deletions
@@ -43,13 +43,13 @@ public class PdfMetadataWriter implements MetadataWriter {
} }
Path filePath = file.toPath(); Path filePath = file.toPath();
Path parentDir = filePath.getParent();
Path backupPath = null; Path backupPath = null;
boolean backupCreated = false; boolean backupCreated = false;
File tempFile = null; Path tempPath = null;
try { try {
String prefix = "pdfBackup-" + UUID.randomUUID() + "-"; backupPath = Files.createTempFile(parentDir, ".pdfBackup-", ".pdf");
backupPath = Files.createTempFile(prefix, ".pdf");
Files.copy(filePath, backupPath, StandardCopyOption.REPLACE_EXISTING); Files.copy(filePath, backupPath, StandardCopyOption.REPLACE_EXISTING);
backupCreated = true; backupCreated = true;
} catch (IOException e) { } catch (IOException e) {
@@ -58,10 +58,10 @@ public class PdfMetadataWriter implements MetadataWriter {
try (PdfDocument doc = PdfDocument.open(filePath)) { try (PdfDocument doc = PdfDocument.open(filePath)) {
applyMetadataToDocument(doc, metadataEntity, clear); applyMetadataToDocument(doc, metadataEntity, clear);
tempFile = File.createTempFile("pdfmeta-", ".pdf"); tempPath = Files.createTempFile(parentDir, ".pdfmeta-", ".pdf");
doc.save(tempFile.toPath(), SaveOptions.SKIP_VALIDATION); doc.save(tempPath, SaveOptions.SKIP_VALIDATION);
Files.move(tempFile.toPath(), filePath, StandardCopyOption.REPLACE_EXISTING); Files.move(tempPath, filePath, StandardCopyOption.REPLACE_EXISTING);
tempFile = null; // Prevent deletion in finally block after successful move tempPath = null;
log.info("Successfully embedded metadata into PDF: {}", file.getName()); log.info("Successfully embedded metadata into PDF: {}", file.getName());
} catch (Exception e) { } catch (Exception e) {
log.warn("Failed to write metadata to PDF {}: {}", file.getName(), e.getMessage(), e); log.warn("Failed to write metadata to PDF {}: {}", file.getName(), e.getMessage(), e);
@@ -74,8 +74,12 @@ public class PdfMetadataWriter implements MetadataWriter {
} }
} }
} finally { } finally {
if (tempFile != null && tempFile.exists()) { if (tempPath != null) {
tempFile.delete(); try {
Files.deleteIfExists(tempPath);
} catch (IOException e) {
log.warn("Could not delete PDF temp file: {}", e.getMessage());
}
} }
if (backupCreated) { if (backupCreated) {
try { try {
@@ -418,18 +422,17 @@ public class PdfMetadataWriter implements MetadataWriter {
return null; return null;
} }
// Extract numeric ID from slug format "12345678-book-title" // Extract numeric ID from slug format "12345678-book-title" or "12345678.Book_Title"
int dashIndex = goodreadsId.indexOf('-'); int sep = goodreadsId.indexOf('-');
if (dashIndex > 0) { if (sep < 0) sep = goodreadsId.indexOf('.');
String numericPart = goodreadsId.substring(0, dashIndex); if (sep > 0) {
// Validate it's actually numeric String numericPart = goodreadsId.substring(0, sep);
if (numericPart.matches("\\d+")) { if (numericPart.matches("\\d+")) {
return numericPart; return numericPart;
} }
} }
// Already just the ID, or return as-is if it's all numeric return goodreadsId;
return goodreadsId.matches("\\d+") ? goodreadsId : goodreadsId;
} }
} }
@@ -88,7 +88,7 @@ class PdfMetadataWriterTest {
meta.setPublishedDate(LocalDate.of(2022, 11, 22)); meta.setPublishedDate(LocalDate.of(2022, 11, 22));
meta.setLanguage("en"); meta.setLanguage("en");
meta.setPageCount(754); meta.setPageCount(754);
List<AuthorEntity> authors = new ArrayList<>(); List<AuthorEntity> authors = new ArrayList<>();
AuthorEntity author = new AuthorEntity(); AuthorEntity author = new AuthorEntity();
author.setName("Jason C McDonald"); author.setName("Jason C McDonald");
@@ -197,7 +197,7 @@ class PdfMetadataWriterTest {
writer.saveMetadataToFile(pdf, meta, null, null); writer.saveMetadataToFile(pdf, meta, null, null);
BookMetadata result = extractor.extractMetadata(pdf); BookMetadata result = extractor.extractMetadata(pdf);
assertEquals("52555538", result.getGoodreadsId(), assertEquals("52555538", result.getGoodreadsId(),
"Goodreads ID should be normalized to just the numeric part"); "Goodreads ID should be normalized to just the numeric part");
} }
@@ -287,17 +287,21 @@ class PdfMetadataWriterTest {
File pdf = createEmptyPdf("tags-moods.pdf"); File pdf = createEmptyPdf("tags-moods.pdf");
BookMetadataEntity meta = createBasicMetadata(); BookMetadataEntity meta = createBasicMetadata();
Set<TagEntity> tags = new HashSet<>(); Set<TagEntity> tags = new HashSet<>();
TagEntity tag1 = new TagEntity(); tag1.setName("Python"); TagEntity tag1 = new TagEntity();
TagEntity tag2 = new TagEntity(); tag2.setName("Programming"); tag1.setName("Python");
TagEntity tag2 = new TagEntity();
tag2.setName("Programming");
tags.add(tag1); tags.add(tag1);
tags.add(tag2); tags.add(tag2);
meta.setTags(tags); meta.setTags(tags);
Set<MoodEntity> moods = new HashSet<>(); Set<MoodEntity> moods = new HashSet<>();
MoodEntity mood1 = new MoodEntity(); mood1.setName("Educational"); MoodEntity mood1 = new MoodEntity();
MoodEntity mood2 = new MoodEntity(); mood2.setName("Technical"); mood1.setName("Educational");
MoodEntity mood2 = new MoodEntity();
mood2.setName("Technical");
moods.add(mood1); moods.add(mood1);
moods.add(mood2); moods.add(mood2);
meta.setMoods(moods); meta.setMoods(moods);