refactor: use FileService for fetching / writing images to books (#2840)

This commit is contained in:
James Ward
2026-10-03 17:46:47 -06:00
committed by GitHub
parent 09552f6293
commit d58345b350
15 changed files with 212 additions and 327 deletions
@@ -20,7 +20,6 @@ import org.booklore.service.file.FileFingerprint;
import org.booklore.service.fileprocessor.BookFileProcessor;
import org.booklore.service.fileprocessor.BookFileProcessorRegistry;
import org.booklore.service.metadata.sidecar.SidecarMetadataWriter;
import org.booklore.service.metadata.writer.MetadataWriter;
import org.booklore.service.metadata.writer.MetadataWriterFactory;
import org.booklore.util.BookCoverUtils;
import org.booklore.util.FileService;
@@ -35,14 +34,14 @@ import org.springframework.transaction.support.TransactionSynchronizationManager
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Instant;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;
@Slf4j
@@ -102,6 +101,17 @@ public class BookCoverService {
notifyBookCoverUpdate(bookEntity);
}
/**
* Update cover image from a local path for a single book.
*/
private void updateCoverFromPath(BookEntity bookEntity, Path coverPath) {
writeCoverToBookFile(bookEntity, coverPath);
updateBookCoverMetadata(bookEntity);
bookRepository.save(bookEntity);
notifyBookCoverUpdate(bookEntity);
writeSidecarMetadata(bookEntity);
}
/**
* Update cover image from uploaded file for a single book.
*/
@@ -114,11 +124,7 @@ public class BookCoverService {
}
fileService.createThumbnailFromFile(bookId, file);
writeCoverToBookFile(bookEntity, (writer, targetFile) -> writer.replaceCoverImageFromUpload(targetFile, file));
updateBookCoverMetadata(bookEntity);
bookRepository.save(bookEntity);
notifyBookCoverUpdate(bookEntity);
writeSidecarMetadata(bookEntity);
updateCoverFromPath(bookEntity, Path.of(fileService.getCoverFile(bookId)));
}
/**
@@ -133,17 +139,24 @@ public class BookCoverService {
}
fileService.createThumbnailFromUrl(bookId, url);
writeCoverToBookFile(bookEntity, (writer, targetFile) -> writer.replaceCoverImageFromUrl(targetFile, url));
updateBookCoverMetadata(bookEntity);
bookRepository.save(bookEntity);
notifyBookCoverUpdate(bookEntity);
writeSidecarMetadata(bookEntity);
updateCoverFromPath(bookEntity, Path.of(fileService.getCoverFile(bookId)));
}
// =========================
// SECTION: AUDIOBOOK COVER UPDATES
// =========================
/**
* Update audiobook cover image from a local path for a single book.
*/
private void updateAudiobookCoverFromPath(BookEntity bookEntity, Path coverPath) {
writeAudiobookCoverToFile(bookEntity, coverPath);
updateAudiobookCoverMetadata(bookEntity);
bookRepository.save(bookEntity);
notifyBookCoverUpdate(bookEntity);
writeSidecarMetadata(bookEntity);
}
/**
* Update audiobook cover image from uploaded file for a single book.
*/
@@ -156,11 +169,7 @@ public class BookCoverService {
}
fileService.createAudiobookThumbnailFromFile(bookId, file);
writeAudiobookCoverToFile(bookEntity, (writer, targetFile) -> writer.replaceCoverImageFromUpload(targetFile, file));
updateAudiobookCoverMetadata(bookEntity);
bookRepository.save(bookEntity);
notifyBookCoverUpdate(bookEntity);
writeSidecarMetadata(bookEntity);
updateAudiobookCoverFromPath(bookEntity, Path.of(fileService.getAudiobookCoverFile(bookId)));
}
/**
@@ -175,11 +184,7 @@ public class BookCoverService {
}
fileService.createAudiobookThumbnailFromUrl(bookId, url);
writeAudiobookCoverToFile(bookEntity, (writer, targetFile) -> writer.replaceCoverImageFromUrl(targetFile, url));
updateAudiobookCoverMetadata(bookEntity);
bookRepository.save(bookEntity);
notifyBookCoverUpdate(bookEntity);
writeSidecarMetadata(bookEntity);
updateAudiobookCoverFromPath(bookEntity, Path.of(fileService.getAudiobookCoverFile(bookId)));
}
/**
@@ -379,7 +384,7 @@ public class BookCoverService {
if (hasUnlockedEbookSlot(book)) {
try {
fileService.createThumbnailFromBytes(book.getId(), coverBytes);
writeCoverToBookFile(book, (writer, targetFile) -> writer.replaceCoverImageFromBytes(targetFile, coverBytes));
writeCoverToBookFile(book, coverBytes);
updateBookCoverMetadata(book);
updated = true;
} catch (Exception e) {
@@ -389,7 +394,7 @@ public class BookCoverService {
if (hasUnlockedAudiobookSlot(book)) {
try {
fileService.createAudiobookThumbnailFromBytes(book.getId(), coverBytes);
writeAudiobookCoverToFile(book, (writer, targetFile) -> writer.replaceCoverImageFromBytes(targetFile, coverBytes));
writeAudiobookCoverToFile(book, coverBytes);
updateAudiobookCoverMetadata(book);
updated = true;
} catch (Exception e) {
@@ -575,14 +580,14 @@ public class BookCoverService {
private void applyCustomBookCover(BookEntity bookEntity) {
byte[] coverBytes = coverImageGenerator.generateCover(bookEntity.getMetadata().getTitle(), getAuthorNames(bookEntity));
fileService.createThumbnailFromBytes(bookEntity.getId(), coverBytes);
writeCoverToBookFile(bookEntity, (writer, targetFile) -> writer.replaceCoverImageFromBytes(targetFile, coverBytes));
writeCoverToBookFile(bookEntity, coverBytes);
updateBookCoverMetadata(bookEntity);
}
private void applyCustomAudiobookCover(BookEntity bookEntity) {
byte[] coverBytes = coverImageGenerator.generateSquareCover(bookEntity.getMetadata().getTitle(), getAuthorNames(bookEntity));
fileService.createAudiobookThumbnailFromBytes(bookEntity.getId(), coverBytes);
writeAudiobookCoverToFile(bookEntity, (writer, targetFile) -> writer.replaceCoverImageFromBytes(targetFile, coverBytes));
writeAudiobookCoverToFile(bookEntity, coverBytes);
updateAudiobookCoverMetadata(bookEntity);
}
@@ -595,7 +600,19 @@ public class BookCoverService {
return null;
}
private void writeCoverToBookFile(BookEntity bookEntity, BiConsumer<MetadataWriter, File> writerAction) {
private void writeCoverToBookFile(BookEntity bookEntity, Path path) {
if (path == null) {
return;
}
try {
writeCoverToBookFile(bookEntity, Files.readAllBytes(path));
} catch (IOException e) {
log.warn("Unable to read cover from path: {}", path, e);
}
}
private void writeCoverToBookFile(BookEntity bookEntity, byte[] contents) {
if (!appProperties.isLocalStorage()) {
return;
}
@@ -610,14 +627,26 @@ public class BookCoverService {
if ((ebookFile.getBookType() != BookFileType.CBX || convertCbrCb7ToCbz)) {
metadataWriterFactory.getWriter(ebookFile.getBookType())
.ifPresent(writer -> {
writerAction.accept(writer, ebookFile.getFullFilePath().toFile());
writer.replaceCoverImageFromBytes(ebookFile.getFullFilePath().toFile(), contents);
String newHash = FileFingerprint.generateHash(ebookFile.getFullFilePath());
ebookFile.setCurrentHash(newHash);
});
}
}
private void writeAudiobookCoverToFile(BookEntity bookEntity, BiConsumer<MetadataWriter, File> writerAction) {
private void writeAudiobookCoverToFile(BookEntity bookEntity, Path path) {
if (path == null) {
return;
}
try {
writeAudiobookCoverToFile(bookEntity, Files.readAllBytes(path));
} catch (IOException e) {
log.warn("Unable to read cover from path: {}", path, e);
}
}
private void writeAudiobookCoverToFile(BookEntity bookEntity, byte[] contents) {
if (!appProperties.isLocalStorage()) {
return;
}
@@ -632,7 +661,7 @@ public class BookCoverService {
metadataWriterFactory.getWriter(BookFileType.AUDIOBOOK)
.ifPresent(writer -> {
writerAction.accept(writer, audiobookFile.getFullFilePath().toFile());
writer.replaceCoverImageFromBytes(audiobookFile.getFullFilePath().toFile(), contents);
if (!audiobookFile.isFolderBased()) {
String newHash = FileFingerprint.generateHash(audiobookFile.getFullFilePath());
audiobookFile.setCurrentHash(newHash);
@@ -111,7 +111,7 @@ public class BookMetadataUpdater {
updateMoodsIfNeeded(newMetadata, metadata, clearFlags, mergeMoods, replaceMode);
updateTagsIfNeeded(newMetadata, metadata, clearFlags, mergeTags, replaceMode);
bookReviewUpdateService.updateBookReviews(newMetadata, metadata, clearFlags, mergeCategories);
updateThumbnailIfNeeded(bookId, bookEntity, newMetadata, metadata, updateThumbnail, bookType);
boolean hasUpdatedThumbnail = updateThumbnailIfNeeded(bookId, bookEntity, newMetadata, metadata, updateThumbnail, bookType);
updateAudiobookMetadataIfNeeded(bookEntity, newMetadata, metadata, clearFlags, replaceMode);
updateComicMetadataIfNeeded(newMetadata, metadata, replaceMode);
updateLocks(newMetadata, metadata);
@@ -128,13 +128,20 @@ public class BookMetadataUpdater {
if (appProperties.isLocalStorage() && primaryFile != null && bookType != null && ((writeToFile.isAnyFormatEnabled() && hasValueChangesForFileWrite) || thumbnailRequiresUpdate)) {
metadataWriterFactory.getWriter(bookType).ifPresent(writer -> {
try {
String thumbnailUrl = updateThumbnail ? newMetadata.getThumbnailUrl() : null;
if ((StringUtils.hasText(thumbnailUrl) && isLocalOrPrivateUrl(thumbnailUrl) || Boolean.TRUE.equals(metadata.getCoverLocked()))) {
log.debug("Blocked local/private thumbnail URL: {}", thumbnailUrl);
thumbnailUrl = null;
File file = bookEntity.getFullFilePath().toFile();
if (hasUpdatedThumbnail) {
Path imagePath;
if (bookType == BookFileType.AUDIOBOOK) {
imagePath = Path.of(fileService.getAudiobookCoverFile(bookEntity.getId()));
} else {
imagePath = Path.of(fileService.getCoverFile(bookEntity.getId()));
}
byte[] coverContents = Files.readAllBytes(imagePath);
writer.replaceCoverImageFromBytes(file, coverContents);
}
File file = new File(bookEntity.getFullFilePath().toUri());
writer.saveMetadataToFile(file, metadata, thumbnailUrl, clearFlags);
writer.saveMetadataToFile(file, metadata, clearFlags);
updateFileNameIfConverted(primaryFile, file.toPath());
String newHash = file.isDirectory()
? FileFingerprint.generateFolderHash(bookEntity.getFullFilePath())
@@ -664,24 +671,36 @@ public class BookMetadataUpdater {
}
}
private void updateThumbnailIfNeeded(long bookId, BookEntity bookEntity, BookMetadata m, BookMetadataEntity e, boolean set, BookFileType bookType) {
if (Boolean.TRUE.equals(e.getCoverLocked())) {
return;
private boolean updateThumbnailIfNeeded(long bookId, BookEntity bookEntity, BookMetadata m, BookMetadataEntity e, boolean set, BookFileType bookType) {
if (!set) {
return false;
}
if (!set) return;
if (!StringUtils.hasText(m.getThumbnailUrl()) || isLocalOrPrivateUrl(m.getThumbnailUrl())) return;
if (!StringUtils.hasText(m.getThumbnailUrl())) {
return false;
}
try {
if (bookType == BookFileType.AUDIOBOOK) {
if (Boolean.TRUE.equals(e.getAudiobookCoverLocked())) return;
if (Boolean.TRUE.equals(e.getAudiobookCoverLocked())) {
return false;
}
fileService.createAudiobookThumbnailFromUrl(bookId, m.getThumbnailUrl());
bookEntity.getMetadata().setAudiobookCoverUpdatedOn(Instant.now());
} else {
if (Boolean.TRUE.equals(e.getCoverLocked())) {
return false;
}
fileService.createThumbnailFromUrl(bookId, m.getThumbnailUrl());
bookEntity.getMetadata().setCoverUpdatedOn(Instant.now());
}
bookEntity.setBookCoverHash(BookCoverUtils.generateCoverHash());
return true;
} catch (Exception ex) {
log.warn("Failed to download cover for book {}: {}", bookId, ex.getMessage());
return false;
}
}
@@ -756,17 +775,4 @@ public class BookMetadataUpdater {
bookFile.setFileName(cbzFileName);
}
}
private boolean isLocalOrPrivateUrl(String url) {
try {
URI uri = new URI(url);
String host = uri.getHost();
if ("localhost".equalsIgnoreCase(host) || "127.0.0.1".equals(host)) return true;
InetAddress addr = InetAddress.getByName(host);
return addr.isLoopbackAddress() || addr.isSiteLocalAddress();
} catch (Exception e) {
log.warn("Invalid thumbnail URL '{}': {}", url, e.getMessage());
return true;
}
}
}
@@ -70,7 +70,7 @@ public class MetadataManagementService {
Optional<MetadataWriter> writerOpt = metadataWriterFactory.getWriter(bookType);
if (writerOpt.isPresent()) {
File file = book.getFullFilePath().toFile();
writerOpt.get().saveMetadataToFile(file, metadata, null, null);
writerOpt.get().saveMetadataToFile(file, metadata, null);
String newHash = FileFingerprint.generateHash(book.getFullFilePath());
primaryFile.setCurrentHash(newHash);
bookModified = true;
@@ -15,10 +15,8 @@ import org.jaudiotagger.tag.Tag;
import org.jaudiotagger.tag.images.Artwork;
import org.jaudiotagger.tag.images.ArtworkFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
@@ -37,17 +35,7 @@ public class AudiobookMetadataWriter implements MetadataWriter {
private final AppSettingService appSettingService;
@Override
public void saveMetadataToFile(File audioFile, BookMetadataEntity metadata, String thumbnailUrl, MetadataClearFlags clear) {
if (audioFile.isDirectory()) {
if (StringUtils.isNotBlank(thumbnailUrl)) {
byte[] coverData = loadImage(thumbnailUrl);
if (coverData != null) {
saveCoverToFolder(audioFile.toPath(), coverData);
}
}
return;
}
public void saveMetadataToFile(File audioFile, BookMetadataEntity metadata, MetadataClearFlags clear) {
if (!shouldSaveMetadataToFile(audioFile)) {
return;
}
@@ -120,22 +108,6 @@ public class AudiobookMetadataWriter implements MetadataWriter {
setTagField(tag, FieldKey.TRACK_TOTAL, trackTotal, hasChanges);
});
if (StringUtils.isNotBlank(thumbnailUrl)) {
byte[] coverData = loadImage(thumbnailUrl);
if (coverData != null) {
try {
tag.deleteArtworkField();
Artwork artwork = ArtworkFactory.getNew();
artwork.setBinaryData(coverData);
artwork.setMimeType(detectMimeType(coverData));
tag.setField(artwork);
hasChanges[0] = true;
} catch (Exception e) {
log.warn("Failed to set cover art for {}: {}", audioFile.getName(), e.getMessage());
}
}
}
if (hasChanges[0]) {
f.commit();
log.info("Metadata updated in audiobook: {}", audioFile.getName());
@@ -217,56 +189,17 @@ public class AudiobookMetadataWriter implements MetadataWriter {
@Override
public void replaceCoverImageFromBytes(File bookFile, byte[] coverData) {
if (coverData == null || coverData.length == 0) {
log.warn("Cover update failed: empty or null byte array.");
return;
}
if (!shouldSaveMetadataToFile(bookFile)) {
return;
}
if (bookFile.isDirectory()) {
saveCoverToFolder(bookFile.toPath(), coverData);
} else {
replaceCoverImageInternal(bookFile, coverData, "byte array");
}
}
@Override
public void replaceCoverImageFromUpload(File bookFile, MultipartFile multipartFile) {
if (multipartFile == null || multipartFile.isEmpty()) {
log.warn("Cover upload failed: empty or null file.");
return;
}
try {
byte[] coverData = multipartFile.getBytes();
replaceCoverImageFromBytes(bookFile, coverData);
} catch (IOException e) {
log.warn("Failed to read uploaded cover image: {}", e.getMessage(), e);
}
}
@Override
public void replaceCoverImageFromUrl(File bookFile, String url) {
if (url == null || url.isBlank()) {
log.warn("Cover update via URL failed: empty or null URL.");
return;
}
byte[] coverData = loadImage(url);
if (coverData == null) {
log.warn("Failed to load image from URL: {}", url);
return;
}
replaceCoverImageFromBytes(bookFile, coverData);
}
private void replaceCoverImageInternal(File audioFile, byte[] coverData, String source) {
try {
AudioFile f = AudioFileIO.read(audioFile);
AudioFile f = AudioFileIO.read(bookFile);
Tag tag = f.getTagOrCreateAndSetDefault();
tag.deleteArtworkField();
@@ -276,9 +209,9 @@ public class AudiobookMetadataWriter implements MetadataWriter {
tag.setField(artwork);
f.commit();
log.info("Cover image updated in audiobook from {}: {}", source, audioFile.getName());
log.info("Cover image updated in audiobook: {}", bookFile.getName());
} catch (Exception e) {
log.warn("Failed to update audiobook cover image from {}: {}", source, e.getMessage(), e);
log.warn("Failed to update audiobook cover image: {}", e.getMessage(), e);
}
}
@@ -312,17 +245,6 @@ public class AudiobookMetadataWriter implements MetadataWriter {
return true;
}
private byte[] loadImage(String pathOrUrl) {
try (InputStream stream = pathOrUrl.startsWith("http")
? URI.create(pathOrUrl).toURL().openStream()
: new FileInputStream(pathOrUrl)) {
return stream.readAllBytes();
} catch (IOException e) {
log.warn("Failed to load image from {}: {}", pathOrUrl, e.getMessage());
return null;
}
}
private String detectMimeType(byte[] data) {
if (data.length > 3 && data[0] == (byte) 0x89 && data[1] == (byte) 0x50 && data[2] == (byte) 0x4E && data[3] == (byte) 0x47) {
return "image/png";
@@ -56,7 +56,7 @@ public class CbxMetadataWriter implements MetadataWriter {
private final ArchiveService archiveService;
@Override
public void saveMetadataToFile(File file, BookMetadataEntity metadata, String thumbnailUrl, MetadataClearFlags clearFlags) {
public void saveMetadataToFile(File file, BookMetadataEntity metadata, MetadataClearFlags clearFlags) {
if (!shouldSaveMetadataToFile(file)) {
return;
}
@@ -14,7 +14,6 @@ import org.booklore.util.SecureXmlUtils;
import org.booklore.util.epub.EpubContentReader;
import org.booklore.util.epub.EpubContentWriter;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
@@ -33,10 +32,7 @@ import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
@@ -58,7 +54,7 @@ public class EpubMetadataWriter implements MetadataWriter {
private final ArchiveService archiveService;
@Override
public void saveMetadataToFile(File epubFile, BookMetadataEntity metadata, String thumbnailUrl, MetadataClearFlags clear) {
public void saveMetadataToFile(File epubFile, BookMetadataEntity metadata, MetadataClearFlags clear) {
if (!shouldSaveMetadataToFile(epubFile)) {
return;
}
@@ -214,14 +210,6 @@ public class EpubMetadataWriter implements MetadataWriter {
hasChanges[0] = true;
});
if (StringUtils.isNotBlank(thumbnailUrl)) {
byte[] coverData = loadImage(thumbnailUrl);
if (coverData != null) {
applyCoverImageToEpub(tempDir, opfDoc, coverData);
hasChanges[0] = true;
}
}
if (!hasChanges[0] && hasBookloreMetadataChanges(metadataElement, metadata)) {
hasChanges[0] = true;
}
@@ -385,58 +373,12 @@ public class EpubMetadataWriter implements MetadataWriter {
return changed;
}
@Override
public void replaceCoverImageFromBytes(File bookFile, byte[] file) {
if (!shouldSaveMetadataToFile(bookFile)) {
return;
}
if (file == null || file.length == 0) {
log.warn("Cover update failed: empty or null byte array.");
public void replaceCoverImageFromBytes(File epubFile, byte[] contents) {
if (!shouldSaveMetadataToFile(epubFile)) {
return;
}
replaceCoverImageInternal(bookFile, file, "byte array");
}
@Override
public void replaceCoverImageFromUpload(File bookFile, MultipartFile multipartFile) {
if (!shouldSaveMetadataToFile(bookFile)) {
return;
}
if (multipartFile == null || multipartFile.isEmpty()) {
log.warn("Cover upload failed: empty or null file.");
return;
}
try {
byte[] coverData = multipartFile.getBytes();
replaceCoverImageInternal(bookFile, coverData, "upload");
} catch (IOException e) {
log.warn("Failed to read uploaded cover image: {}", e.getMessage(), e);
}
}
@Override
public void replaceCoverImageFromUrl(File bookFile, String url) {
if (!shouldSaveMetadataToFile(bookFile)) {
return;
}
if (url == null || url.isBlank()) {
log.warn("Cover update via URL failed: empty or null URL.");
return;
}
byte[] coverData = loadImage(url);
if (coverData == null) {
log.warn("Failed to load image from URL: {}", url);
return;
}
replaceCoverImageInternal(bookFile, coverData, "URL");
}
private void replaceCoverImageInternal(File epubFile, byte[] coverData, String source) {
Path tempDir = null;
try {
tempDir = Files.createTempDirectory("epub_cover_" + UUID.randomUUID());
@@ -448,7 +390,7 @@ public class EpubMetadataWriter implements MetadataWriter {
DocumentBuilder builder = SecureXmlUtils.createSecureDocumentBuilder(true);
Document opfDoc = builder.parse(opfPath.toFile());
applyCoverImageToEpub(tempDir, opfDoc, coverData);
applyCoverImageToEpub(tempDir, opfDoc, contents);
removeEmptyTextNodes(opfDoc);
organizePackageElements(opfDoc);
@@ -463,10 +405,10 @@ public class EpubMetadataWriter implements MetadataWriter {
if (!epubFile.delete()) throw new IOException("Could not delete original EPUB");
if (!tempEpub.renameTo(epubFile)) throw new IOException("Could not rename temp EPUB");
log.info("Cover image updated in EPUB from {}: {}", source, epubFile.getName());
log.info("Cover image updated in EPUB: {}", epubFile.getName());
} catch (Exception e) {
log.warn("Failed to update EPUB cover image from {}: {}", source, e.getMessage(), e);
log.warn("Failed to update EPUB cover image: {}", e.getMessage(), e);
} finally {
if (tempDir != null) {
deleteDirectoryRecursively(tempDir);
@@ -651,15 +593,6 @@ public class EpubMetadataWriter implements MetadataWriter {
return EpubContentReader.findOPFInExtractedEpub(tempDir);
}
private byte[] loadImage(String pathOrUrl) {
try (InputStream stream = pathOrUrl.startsWith("http") ? URI.create(pathOrUrl).toURL().openStream() : new FileInputStream(pathOrUrl)) {
return stream.readAllBytes();
} catch (IOException e) {
log.warn("Failed to load image from {}: {}", pathOrUrl, e.getMessage());
return null;
}
}
private void removeMetaByName(Element metadataElement, String name) {
NodeList metas = metadataElement.getElementsByTagNameNS("*", "meta");
for (int i = metas.getLength() - 1; i >= 0; i--) {
@@ -3,23 +3,16 @@ package org.booklore.service.metadata.writer;
import org.booklore.model.MetadataClearFlags;
import org.booklore.model.entity.BookMetadataEntity;
import org.booklore.model.enums.BookFileType;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
public interface MetadataWriter {
void saveMetadataToFile(File file, BookMetadataEntity metadata, String thumbnailUrl, MetadataClearFlags clearFlags);
void saveMetadataToFile(File file, BookMetadataEntity metadata, MetadataClearFlags clearFlags);
boolean shouldSaveMetadataToFile(File file);
default void replaceCoverImageFromUpload(File bookFile, MultipartFile file) {
}
default void replaceCoverImageFromBytes(File bookFile, byte[] file) {
}
default void replaceCoverImageFromUrl(File bookFile, String url) {
default void replaceCoverImageFromBytes(File bookFile, byte[] contents) {
}
BookFileType getSupportedBookType();
@@ -36,7 +36,7 @@ public class PdfMetadataWriter implements MetadataWriter {
private final AppSettingService appSettingService;
@Override
public void saveMetadataToFile(File file, BookMetadataEntity metadataEntity, String thumbnailUrl, MetadataClearFlags clear) {
public void saveMetadataToFile(File file, BookMetadataEntity metadataEntity, MetadataClearFlags clear) {
if (!shouldSaveMetadataToFile(file)) {
return;
}
@@ -159,7 +159,7 @@ class Rar5IntegrationTest {
BookMetadataEntity metadata = new BookMetadataEntity();
metadata.setTitle("Updated RAR5 Title");
writer.saveMetadataToFile(cbrCopy.toFile(), metadata, null, null);
writer.saveMetadataToFile(cbrCopy.toFile(), metadata, null);
Path cbzPath = tempDir.resolve("test.cbz");
assertThat(cbzPath).exists();
@@ -18,15 +18,14 @@ import org.booklore.service.metadata.writer.MetadataWriter;
import org.booklore.service.metadata.writer.MetadataWriterFactory;
import org.booklore.service.file.FileFingerprint;
import org.booklore.util.FileService;
import org.booklore.util.MimeDetector;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.booklore.config.security.service.AuthenticationService;
import org.booklore.model.dto.BookLoreUser;
import org.booklore.model.enums.PermissionType;
import org.booklore.model.websocket.LogNotification;
import org.booklore.model.websocket.Topic;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockedStatic;
@@ -38,6 +37,8 @@ import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.*;
import java.util.concurrent.Executor;
@@ -68,12 +69,24 @@ class BookCoverServiceTest {
@InjectMocks
private BookCoverService service;
private MockedStatic<Files> filesMock;
private MockedStatic<MimeDetector> mimeDetectorMock;
@BeforeEach
void setUp() {
mimeDetectorMock = mockStatic(MimeDetector.class);
filesMock = mockStatic(Files.class);
lenient().when(appProperties.isLocalStorage()).thenReturn(true);
lenient().when(authenticationService.getAuthenticatedUser()).thenReturn(BookLoreUser.builder().username("testuser").build());
}
@AfterEach
void tearDown() {
filesMock.close();
mimeDetectorMock.close();
}
private BookEntity buildBook(long id, boolean coverLocked) {
BookMetadataEntity metadata = BookMetadataEntity.builder()
.title("Test Book")
@@ -443,6 +456,8 @@ class BookCoverServiceTest {
when(file.getBytes()).thenReturn(new byte[]{1, 2, 3});
} catch (Exception _) {}
mimeDetectorMock.when(() -> MimeDetector.detect(any(InputStream.class))).thenReturn("image/jpeg");
service.updateCoverFromFileForBooks(Set.of(1L, 2L), file);
verify(bookQueryService).findAllWithMetadataByIds(Set.of(1L, 2L));
@@ -472,6 +487,8 @@ class BookCoverServiceTest {
when(file.getSize()).thenReturn(1024L);
when(file.getInputStream()).thenReturn(new ByteArrayInputStream(new byte[]{1, 2, 3}));
mimeDetectorMock.when(() -> MimeDetector.detect(any(InputStream.class))).thenReturn("application/wad");
assertThatThrownBy(() -> service.updateCoverFromFileForBooks(Set.of(1L), file))
.isInstanceOf(APIException.class)
.hasMessageContaining("JPEG and PNG");
@@ -504,6 +521,8 @@ class BookCoverServiceTest {
when(file.getBytes()).thenReturn(new byte[]{1, 2, 3});
} catch (Exception _) {}
mimeDetectorMock.when(() -> MimeDetector.detect(any(InputStream.class))).thenReturn("image/jpeg");
when(bookQueryService.findAllWithMetadataByIds(any())).thenReturn(List.of());
service.updateCoverFromFileForBooks(Set.of(1L), file);
@@ -524,6 +543,8 @@ class BookCoverServiceTest {
when(bookQueryService.findAllWithMetadataByIds(any())).thenReturn(List.of());
mimeDetectorMock.when(() -> MimeDetector.detect(any(InputStream.class))).thenReturn("image/png");
service.updateCoverFromFileForBooks(Set.of(1L), file);
}
@@ -551,6 +572,7 @@ class BookCoverServiceTest {
BookEntity book = buildBook(1L, false);
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(book));
when(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of());
when(fileService.getCoverFile(1)).thenReturn("cover.jpg");
service.updateCoverFromUrl(1L, "https://example.com/cover.jpg");
@@ -569,6 +591,7 @@ class BookCoverServiceTest {
BookEntity book = buildBook(1L, false);
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(book));
when(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of());
when(fileService.getCoverFile(1)).thenReturn("cover.jpg");
MultipartFile file = mock(MultipartFile.class);
service.updateCoverFromFile(1L, file);
@@ -587,6 +610,8 @@ class BookCoverServiceTest {
BookEntity book = buildBookWithAudiobookLock(1L, false);
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(book));
when(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of());
when(fileService.getAudiobookCoverFile(1)).thenReturn("cover.jpg");
MultipartFile file = mock(MultipartFile.class);
service.updateAudiobookCoverFromFile(1L, file);
@@ -615,6 +640,7 @@ class BookCoverServiceTest {
BookEntity book = buildBookWithAudiobookLock(1L, false);
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(book));
when(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of());
when(fileService.getAudiobookCoverFile(1)).thenReturn("cover.jpg");
service.updateAudiobookCoverFromUrl(1L, "https://example.com/audiobook-cover.jpg");
@@ -815,6 +841,8 @@ class BookCoverServiceTest {
runAsyncInline();
runTransactionsInline();
mimeDetectorMock.when(() -> MimeDetector.detect(any(InputStream.class))).thenReturn("image/jpeg");
service.updateCoverFromFileForBooks(Set.of(1L), file);
verify(fileService).createAudiobookThumbnailFromBytes(eq(1L), any());
@@ -961,7 +989,9 @@ class BookCoverServiceTest {
when(file.getInputStream()).thenReturn(new ByteArrayInputStream(new byte[]{(byte) 0xFF, (byte) 0xD8, (byte) 0xFF}));
when(appSettingService.getAppSettings()).thenReturn(appSettings);
when(appSettings.getMaxFileUploadSizeInMb()).thenReturn(10);
mimeDetectorMock.when(() -> MimeDetector.detect(any(InputStream.class))).thenReturn("image/jpeg");
service.updateCoverFromFileForBooks(Set.of(1L), file);
verify(bookQueryService).findAllWithMetadataByIds(any());
@@ -1095,13 +1125,16 @@ class BookCoverServiceTest {
when(metadataWriterFactory.getWriter(BookFileType.EPUB)).thenReturn(Optional.of(epubWriter));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(book));
when(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of());
when(fileService.getCoverFile(1)).thenReturn("cover.jpg");
filesMock.when(() -> Files.readAllBytes(any())).thenReturn(new byte[]{});
try (MockedStatic<FileFingerprint> fpMock = mockStatic(FileFingerprint.class)) {
fpMock.when(() -> FileFingerprint.generateHash(epubFile.getFullFilePath())).thenReturn("hash");
service.updateCoverFromUrl(1L, "https://example.com/cover.jpg");
verify(epubWriter).replaceCoverImageFromUrl(epubFile.getFullFilePath().toFile(), "https://example.com/cover.jpg");
verify(epubWriter).replaceCoverImageFromBytes(eq(epubFile.getFullFilePath().toFile()), any(byte[].class));
verify(metadataWriterFactory, never()).getWriter(BookFileType.AUDIOBOOK);
assertThat(epubFile.getCurrentHash()).isEqualTo("hash");
assertThat(audiobookFile.getCurrentHash()).isNull();
@@ -1114,6 +1147,7 @@ class BookCoverServiceTest {
book.setBookFiles(new HashSet<>());
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(book));
when(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of());
when(fileService.getCoverFile(1)).thenReturn("cover.jpg");
service.updateCoverFromUrl(1L, "https://example.com/cover.jpg");
@@ -1132,6 +1166,8 @@ class BookCoverServiceTest {
BookCoverUpdateProjection projection = mock(BookCoverUpdateProjection.class);
when(bookRepository.findCoverUpdateInfoByIds(List.of(1L))).thenReturn(List.of(projection));
when(fileService.getCoverFile(1)).thenReturn("cover.jpg");
service.updateCoverFromUrl(1L, "https://example.com/cover.jpg");
verify(notificationService).sendMessage(any(), eq(List.of(projection)));
@@ -1143,6 +1179,7 @@ class BookCoverServiceTest {
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(book));
BookCoverUpdateProjection projection = mock(BookCoverUpdateProjection.class);
when(bookRepository.findCoverUpdateInfoByIds(List.of(1L))).thenReturn(List.of(projection));
when(fileService.getCoverFile(1)).thenReturn("cover.jpg");
TransactionSynchronizationManager.initSynchronization();
try {
@@ -1166,6 +1203,8 @@ class BookCoverServiceTest {
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(book));
when(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of());
when(fileService.getCoverFile(1)).thenReturn("cover.jpg");
service.updateCoverFromUrl(1L, "https://example.com/cover.jpg");
verify(notificationService, never()).sendMessage(any(), anyList());
@@ -1221,6 +1260,7 @@ class BookCoverServiceTest {
book.setBookFiles(Set.of(bookFile));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(book));
when(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of());
when(fileService.getCoverFile(1)).thenReturn("cover.jpg");
service.updateCoverFromUrl(1L, "https://example.com/cover.jpg");
@@ -1239,6 +1279,7 @@ class BookCoverServiceTest {
book.setBookFiles(Set.of(audiobookFile));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(book));
when(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of());
when(fileService.getAudiobookCoverFile(1)).thenReturn("cover.jpg");
service.updateAudiobookCoverFromUrl(1L, "https://example.com/audiobook-cover.jpg");
@@ -1256,6 +1297,7 @@ class BookCoverServiceTest {
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(book));
when(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of());
when(sidecarMetadataWriter.isWriteOnUpdateEnabled()).thenReturn(true);
when(fileService.getCoverFile(1)).thenReturn("cover.jpg");
service.updateCoverFromUrl(1L, "https://example.com/cover.jpg");
@@ -1268,6 +1310,7 @@ class BookCoverServiceTest {
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(book));
when(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of());
when(sidecarMetadataWriter.isWriteOnUpdateEnabled()).thenReturn(true);
when(fileService.getAudiobookCoverFile(1)).thenReturn("cover.jpg");
service.updateAudiobookCoverFromUrl(1L, "https://example.com/audiobook-cover.jpg");
@@ -1280,6 +1323,7 @@ class BookCoverServiceTest {
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(book));
when(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of());
when(sidecarMetadataWriter.isWriteOnUpdateEnabled()).thenReturn(false);
when(fileService.getCoverFile(1)).thenReturn("cover.jpg");
service.updateCoverFromUrl(1L, "https://example.com/cover.jpg");
@@ -1292,6 +1336,7 @@ class BookCoverServiceTest {
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(book));
when(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of());
when(sidecarMetadataWriter.isWriteOnUpdateEnabled()).thenReturn(true);
when(fileService.getCoverFile(1)).thenReturn("cover.jpg");
doThrow(new RuntimeException("sidecar unavailable")).when(sidecarMetadataWriter).writeSidecarMetadata(book);
service.updateCoverFromUrl(1L, "https://example.com/cover.jpg");
@@ -254,7 +254,7 @@ class MetadataManagementServiceTest {
service.consolidateMetadata(MergeMetadataType.authors, List.of("Target"), List.of("Old"));
}
verify(writer).saveMetadataToFile(any(), eq(metadata), isNull(), isNull());
verify(writer).saveMetadataToFile(any(), eq(metadata), isNull());
verify(bookRepository).saveAndFlush(book);
Files.deleteIfExists(tempFile);
@@ -97,7 +97,7 @@ class CbxComicInfoComplianceTest {
metadata.setIsbn10("160690373X");
metadata.setHardcoverRating(4.0d);
writer.saveMetadataToFile(cbz, metadata, null, new MetadataClearFlags());
writer.saveMetadataToFile(cbz, metadata, new MetadataClearFlags());
String xmlContent = readComicInfoFromCbz(cbz);
System.out.println("Generated XML:\n" + xmlContent);
@@ -119,7 +119,7 @@ class CbxMetadataWriterTest {
meta.setCategories(cats);
// Execute
writer.saveMetadataToFile(cbz, meta, null, new MetadataClearFlags());
writer.saveMetadataToFile(cbz, meta, new MetadataClearFlags());
// Assert ComicInfo.xml exists and contains our fields
try (ZipFile zip = new ZipFile(cbz)) {
@@ -195,7 +195,7 @@ class CbxMetadataWriterTest {
moods.add(mood);
meta.setMoods(moods);
writer.saveMetadataToFile(cbz, meta, null, new MetadataClearFlags());
writer.saveMetadataToFile(cbz, meta, new MetadataClearFlags());
try (ZipFile zip = new ZipFile(cbz)) {
ZipEntry ci = zip.getEntry("ComicInfo.xml");
@@ -247,7 +247,7 @@ class CbxMetadataWriterTest {
meta.setTitle("New Title");
meta.setDescription("New Summary");
writer.saveMetadataToFile(out.toFile(), meta, null, new MetadataClearFlags());
writer.saveMetadataToFile(out.toFile(), meta, new MetadataClearFlags());
try (ZipFile zip = new ZipFile(out.toFile())) {
ZipEntry ci = zip.getEntry("ComicInfo.xml");
@@ -267,7 +267,7 @@ class CbxMetadataWriterTest {
BookMetadataEntity meta = new BookMetadataEntity();
meta.setTitle("Mismatched Title");
writer.saveMetadataToFile(zipAsCbr, meta, null, new MetadataClearFlags());
writer.saveMetadataToFile(zipAsCbr, meta, new MetadataClearFlags());
try (ZipFile zip = new ZipFile(zipAsCbz.toFile())) {
ZipEntry ci = zip.getEntry("ComicInfo.xml");
@@ -354,7 +354,7 @@ class CbxMetadataWriterTest {
meta.setComicMetadata(comic);
writer.saveMetadataToFile(cbz, meta, null, new MetadataClearFlags());
writer.saveMetadataToFile(cbz, meta, new MetadataClearFlags());
try (ZipFile zip = new ZipFile(cbz)) {
ZipEntry ci = zip.getEntry("ComicInfo.xml");
@@ -58,7 +58,6 @@ class EpubMetadataWriterTest {
private EpubMetadataWriter writer;
private BookMetadataEntity metadata;
private BookEntity bookEntity;
@TempDir
Path tempDir;
@@ -86,16 +85,6 @@ class EpubMetadataWriterTest {
AuthorEntity author = new AuthorEntity();
author.setName("Test Author");
metadata.setAuthors(List.of(author));
bookEntity = new BookEntity();
LibraryPathEntity libraryPath = new LibraryPathEntity();
libraryPath.setPath(tempDir.toString());
bookEntity.setLibraryPath(libraryPath);
BookFileEntity primaryFile = new BookFileEntity();
primaryFile.setBook(bookEntity);
bookEntity.setBookFiles(Set.of(primaryFile));
bookEntity.getPrimaryBookFile().setFileSubPath("");
bookEntity.getPrimaryBookFile().setFileName("test.epub");
}
@Nested
@@ -117,7 +106,7 @@ class EpubMetadataWriterTest {
""", existingMetadata);
File epubFile = createEpubWithOpf(opfContent, "test-metadata-" + System.nanoTime() + ".epub");
assertDoesNotThrow(() -> writer.saveMetadataToFile(epubFile, metadata, null, new MetadataClearFlags()));
assertDoesNotThrow(() -> writer.saveMetadataToFile(epubFile, metadata, new MetadataClearFlags()));
assertTrue(epubFile.exists());
assertTrue(epubFile.length() > 0);
@@ -146,7 +135,7 @@ class EpubMetadataWriterTest {
</package>""";
File epubFile = createEpubWithOpf(opfContent, "test-epub3-role-" + System.nanoTime() + ".epub");
writer.saveMetadataToFile(epubFile, metadata, null, new MetadataClearFlags());
writer.saveMetadataToFile(epubFile, metadata, new MetadataClearFlags());
String content = readOpfContent(epubFile);
assertThat(content).doesNotContain("refines=\"#example2\"");
@@ -166,7 +155,7 @@ class EpubMetadataWriterTest {
</package>""";
File epubFile = createEpubWithOpf(opfContent, "test-sort-package-" + System.nanoTime() + ".epub");
writer.saveMetadataToFile(epubFile, metadata, null, new MetadataClearFlags());
writer.saveMetadataToFile(epubFile, metadata, new MetadataClearFlags());
String content = readOpfContent(epubFile);
@@ -193,7 +182,7 @@ class EpubMetadataWriterTest {
</package>""";
File epubFile = createEpubWithOpf(opfContent, "test-sort-package-" + System.nanoTime() + ".epub");
writer.saveMetadataToFile(epubFile, metadata, null, new MetadataClearFlags());
writer.saveMetadataToFile(epubFile, metadata, new MetadataClearFlags());
String content = readOpfContent(epubFile);
@@ -213,29 +202,11 @@ class EpubMetadataWriterTest {
File epubFile = tempDir.resolve("test_unicode.epub").toFile();
Files.write(epubFile.toPath(), epubContent);
assertDoesNotThrow(() -> writer.saveMetadataToFile(epubFile, metadata, null, new MetadataClearFlags()));
assertDoesNotThrow(() -> writer.saveMetadataToFile(epubFile, metadata, new MetadataClearFlags()));
assertTrue(epubFile.exists());
assertTrue(epubFile.length() > 0);
}
@Test
@DisplayName("Should handle URL-encoded cover href during cover replacement")
void replaceCoverImageFromUpload_withUnicodeHref_handlesDecoding() throws IOException {
byte[] epubContent = createEpubWithUnicodeCoverHref();
File epubFile = tempDir.resolve("test_cover_unicode.epub").toFile();
Files.write(epubFile.toPath(), epubContent);
byte[] imageBytes = createMinimalPngImage();
MultipartFile coverFile = new MockMultipartFile(
"cover.png",
"cover.png",
"image/png",
imageBytes
);
assertDoesNotThrow(() -> writer.replaceCoverImageFromUpload(epubFile, coverFile));
}
}
@Nested
@@ -261,11 +232,11 @@ class EpubMetadataWriterTest {
author.setName("Updated Author");
newMeta.setAuthors(List.of(author));
writer.saveMetadataToFile(epubFile, newMeta, null, new MetadataClearFlags());
writer.saveMetadataToFile(epubFile, newMeta, new MetadataClearFlags());
String contentAfterFirstSave = readOpfContent(epubFile);
newMeta.setTitle("Updated Title 2"); // Change title to force write
writer.saveMetadataToFile(epubFile, newMeta, null, new MetadataClearFlags());
writer.saveMetadataToFile(epubFile, newMeta, new MetadataClearFlags());
String contentAfterSecondSave = readOpfContent(epubFile);
long lines1 = contentAfterFirstSave.lines().count();
@@ -292,7 +263,7 @@ class EpubMetadataWriterTest {
</package>""";
File epubFile = createEpubWithOpf(opfContent, "test-epub3-creator-" + System.nanoTime() + ".epub");
writer.saveMetadataToFile(epubFile, metadata, null, new MetadataClearFlags());
writer.saveMetadataToFile(epubFile, metadata, new MetadataClearFlags());
Document doc = parseOpf(epubFile);
NodeList creators = doc.getElementsByTagNameNS("http://purl.org/dc/elements/1.1/", "creator");
@@ -328,7 +299,7 @@ class EpubMetadataWriterTest {
</package>""";
File epubFile = createEpubWithOpf(opfContent, "test-epub3-role-" + System.nanoTime() + ".epub");
writer.saveMetadataToFile(epubFile, metadata, null, new MetadataClearFlags());
writer.saveMetadataToFile(epubFile, metadata, new MetadataClearFlags());
String content = readOpfContent(epubFile);
assertThat(content).contains("scheme=\"marc:relators\"");
@@ -352,7 +323,7 @@ class EpubMetadataWriterTest {
</package>""";
File epubFile = createEpubWithOpf(opfContent, "test-epub2-creator-" + System.nanoTime() + ".epub");
writer.saveMetadataToFile(epubFile, metadata, null, new MetadataClearFlags());
writer.saveMetadataToFile(epubFile, metadata, new MetadataClearFlags());
String content = readOpfContent(epubFile);
assertThat(content).contains("opf:file-as=");
@@ -379,7 +350,7 @@ class EpubMetadataWriterTest {
metadata.setPageCount(200);
File epubFile = createEpubWithOpf(opfContent, "test-epub2-no-epub3-" + System.nanoTime() + ".epub");
writer.saveMetadataToFile(epubFile, metadata, null, new MetadataClearFlags());
writer.saveMetadataToFile(epubFile, metadata, new MetadataClearFlags());
String content = readOpfContent(epubFile);
// EPUB2 should not have prefix attribute on package
@@ -416,9 +387,6 @@ class EpubMetadataWriterTest {
byte[] coverImageB = new byte[]{0x0B};
byte[] coverImageC = new byte[]{0x0C};
File coverImageFile = tempDir.resolve("new-cover-" + System.nanoTime() + ".png").toFile();
Files.write(coverImageFile.toPath(), coverImageC);
File epubFile = tempDir.resolve("test-duplicate-" + System.nanoTime() + ".epub").toFile();
try (var zos = new ZipArchiveOutputStream(new FileOutputStream(epubFile))) {
@@ -452,7 +420,7 @@ class EpubMetadataWriterTest {
zos.closeArchiveEntry();
}
writer.saveMetadataToFile(epubFile, metadata, coverImageFile.toString(), new MetadataClearFlags());
writer.replaceCoverImageFromBytes(epubFile, coverImageC);
try (ZipFile zf = new ZipFile(epubFile)) {
var entry = zf.getEntry("cover.png");
@@ -475,7 +443,7 @@ class EpubMetadataWriterTest {
</package>""";
File epubFile = createEpubWithOpf(opfContent, "test-mimetype-" + System.nanoTime() + ".epub");
writer.saveMetadataToFile(epubFile, metadata, null, new MetadataClearFlags());
writer.saveMetadataToFile(epubFile, metadata, new MetadataClearFlags());
try (ZipFile zf = new ZipFile(epubFile)) {
Enumeration<? extends ZipEntry> entries = zf.entries();
@@ -505,7 +473,7 @@ class EpubMetadataWriterTest {
</package>""";
File epubFile = createEpubWithOpf(opfContent, "test-no-dup-mimetype-" + System.nanoTime() + ".epub");
writer.saveMetadataToFile(epubFile, metadata, null, new MetadataClearFlags());
writer.saveMetadataToFile(epubFile, metadata, new MetadataClearFlags());
try (ZipFile zf = new ZipFile(epubFile)) {
int mimetypeCount = 0;
@@ -537,9 +505,6 @@ class EpubMetadataWriterTest {
byte[] coverImageA = new byte[]{0x0A};
byte[] coverImageB = new byte[]{0x0B};
File coverImageFile = tempDir.resolve("new-cover-" + System.nanoTime() + ".bin").toFile();
Files.write(coverImageFile.toPath(), coverImageB);
File epubFile = tempDir.resolve("test-duplicate-" + System.nanoTime() + ".epub").toFile();
try (var zos = new ZipArchiveOutputStream(new FileOutputStream(epubFile))) {
@@ -569,7 +534,7 @@ class EpubMetadataWriterTest {
zos.closeArchiveEntry();
}
writer.saveMetadataToFile(epubFile, metadata, coverImageFile.toString(), new MetadataClearFlags());
writer.replaceCoverImageFromBytes(epubFile, coverImageB);
try (ZipFile zf = new ZipFile(epubFile)) {
var entry = zf.getEntry("cover+example.bin");
@@ -601,7 +566,7 @@ class EpubMetadataWriterTest {
metadata.setSeriesNumber(3.0f);
File epubFile = createEpubWithOpf(opfContent, "test-epub3-series-" + System.nanoTime() + ".epub");
writer.saveMetadataToFile(epubFile, metadata, null, new MetadataClearFlags());
writer.saveMetadataToFile(epubFile, metadata, new MetadataClearFlags());
String content = readOpfContent(epubFile);
assertThat(content).contains("property=\"belongs-to-collection\"");
@@ -632,7 +597,7 @@ class EpubMetadataWriterTest {
metadata.setSeriesNumber(5.0f);
File epubFile = createEpubWithOpf(opfContent, "test-epub2-series-" + System.nanoTime() + ".epub");
writer.saveMetadataToFile(epubFile, metadata, null, new MetadataClearFlags());
writer.saveMetadataToFile(epubFile, metadata, new MetadataClearFlags());
String content = readOpfContent(epubFile);
assertThat(content).contains("name=\"calibre:series\"");
@@ -665,7 +630,7 @@ class EpubMetadataWriterTest {
metadata.setSubtitle("A Great Subtitle");
File epubFile = createEpubWithOpf(opfContent, "test-epub3-subtitle-" + System.nanoTime() + ".epub");
writer.saveMetadataToFile(epubFile, metadata, null, new MetadataClearFlags());
writer.saveMetadataToFile(epubFile, metadata, new MetadataClearFlags());
String content = readOpfContent(epubFile);
assertThat(content).contains("A Great Subtitle");
@@ -688,7 +653,7 @@ class EpubMetadataWriterTest {
metadata.setSubtitle(null);
File epubFile = createEpubWithOpf(opfContent, "test-epub3-subtitle-" + System.nanoTime() + ".epub");
writer.saveMetadataToFile(epubFile, metadata, null, new MetadataClearFlags());
writer.saveMetadataToFile(epubFile, metadata, new MetadataClearFlags());
String content = readOpfContent(epubFile);
assertThat(content).doesNotContain(">subtitle</opf:meta>");
@@ -707,7 +672,7 @@ class EpubMetadataWriterTest {
metadata.setSubtitle(null);
File epubFile = createEpubWithOpf(opfContent, "test-epub3-subtitle-" + System.nanoTime() + ".epub");
writer.saveMetadataToFile(epubFile, metadata, null, new MetadataClearFlags());
writer.saveMetadataToFile(epubFile, metadata, new MetadataClearFlags());
String content = readOpfContent(epubFile);
assertThat(content).doesNotContain(">subtitle</opf:meta>");
@@ -733,7 +698,7 @@ class EpubMetadataWriterTest {
metadata.setSubtitle("A Great Subtitle");
File epubFile = createEpubWithOpf(opfContent, "test-epub2-subtitle-" + System.nanoTime() + ".epub");
writer.saveMetadataToFile(epubFile, metadata, null, new MetadataClearFlags());
writer.saveMetadataToFile(epubFile, metadata, new MetadataClearFlags());
String content = readOpfContent(epubFile);
// Title should remain unchanged (not appended with subtitle)
@@ -765,7 +730,7 @@ class EpubMetadataWriterTest {
metadata.setPageCount(350);
File epubFile = createEpubWithOpf(opfContent, "test-epub3-booklore-" + System.nanoTime() + ".epub");
writer.saveMetadataToFile(epubFile, metadata, null, new MetadataClearFlags());
writer.saveMetadataToFile(epubFile, metadata, new MetadataClearFlags());
String content = readOpfContent(epubFile);
assertThat(content).contains("property=\"booklore:page_count\"");
@@ -793,7 +758,7 @@ class EpubMetadataWriterTest {
metadata.setPageCount(350);
File epubFile = createEpubWithOpf(opfContent, "test-epub2-booklore-" + System.nanoTime() + ".epub");
writer.saveMetadataToFile(epubFile, metadata, null, new MetadataClearFlags());
writer.saveMetadataToFile(epubFile, metadata, new MetadataClearFlags());
String content = readOpfContent(epubFile);
assertThat(content).contains("name=\"booklore:page_count\"");
@@ -810,8 +775,7 @@ class EpubMetadataWriterTest {
class CoverTests {
@Test
void shouldCreateManifestItemIfNoneExist() throws Exception {
Path thumbnailPath = tempDir.resolve("thumbnail-" + System.nanoTime()).toAbsolutePath();
Files.write(thumbnailPath, new byte[]{0x01, 0x02, 0x03});
var thumbnailData = new byte[]{0x01, 0x02, 0x03};
File epubFile = createEpubWithOpf(
"""
@@ -825,8 +789,7 @@ class EpubMetadataWriterTest {
"no-cover-" + System.nanoTime() + ".epub"
);
writer.saveMetadataToFile(epubFile, metadata, thumbnailPath.toString(), new MetadataClearFlags());
writer.replaceCoverImageFromBytes(epubFile, thumbnailData);
String content = readOpfContent(epubFile);
assertThat(content).contains("href=\"cover.");
@@ -834,8 +797,7 @@ class EpubMetadataWriterTest {
@Test
void shouldAddEpub3CoverImageTag() throws Exception {
Path thumbnailPath = tempDir.resolve("thumbnail-" + System.nanoTime()).toAbsolutePath();
Files.write(thumbnailPath, new byte[]{0x01, 0x02, 0x03});
var thumbnailData = new byte[]{0x01, 0x02, 0x03};
File epubFile = createEpubWithOpf(
"""
@@ -849,8 +811,7 @@ class EpubMetadataWriterTest {
"no-cover-" + System.nanoTime() + ".epub"
);
writer.saveMetadataToFile(epubFile, metadata, thumbnailPath.toString(), new MetadataClearFlags());
writer.replaceCoverImageFromBytes(epubFile, thumbnailData);
String content = readOpfContent(epubFile);
assertThat(content).contains("properties=\"cover-image\"");
@@ -858,8 +819,7 @@ class EpubMetadataWriterTest {
@Test
void shouldAllowOnlyOneCoverImagePropertiesEpub3() throws Exception {
Path thumbnailPath = tempDir.resolve("thumbnail-" + System.nanoTime()).toAbsolutePath();
Files.write(thumbnailPath, new byte[]{0x01, 0x02, 0x03});
var thumbnailData = new byte[]{0x01, 0x02, 0x03};
File epubFile = createEpubWithOpf(
"""
@@ -877,8 +837,7 @@ class EpubMetadataWriterTest {
"cover-" + System.nanoTime() + ".epub"
);
writer.saveMetadataToFile(epubFile, metadata, thumbnailPath.toString(), new MetadataClearFlags());
writer.replaceCoverImageFromBytes(epubFile, thumbnailData);
String content = readOpfContent(epubFile);
var pattern = Pattern.compile("properties=\"cover-image\"");
@@ -892,8 +851,7 @@ class EpubMetadataWriterTest {
@Test
void shouldMitigateMediaTypeMismatch() throws Exception {
Path thumbnailPath = tempDir.resolve("thumbnail-" + System.nanoTime()).toAbsolutePath();
Files.write(thumbnailPath, new byte[]{0x01, 0x02, 0x03});
var thumbnailData = new byte[]{0x01, 0x02, 0x03};
File epubFile = createEpubWithOpf(
"""
@@ -909,8 +867,7 @@ class EpubMetadataWriterTest {
"no-cover-" + System.nanoTime() + ".epub"
);
writer.saveMetadataToFile(epubFile, metadata, thumbnailPath.toString(), new MetadataClearFlags());
writer.replaceCoverImageFromBytes(epubFile, thumbnailData);
String content = readOpfContent(epubFile);
@@ -95,7 +95,7 @@ class PdfMetadataWriterTest {
authors.add(author);
meta.setAuthors(authors);
writer.saveMetadataToFile(pdf, meta, null, null);
writer.saveMetadataToFile(pdf, meta, null);
BookMetadata result = extractor.extractMetadata(pdf);
assertEquals("Dead Simple Python", result.getTitle());
@@ -115,7 +115,7 @@ class PdfMetadataWriterTest {
meta.setSeriesNumber(22f);
meta.setSeriesTotal(193);
writer.saveMetadataToFile(pdf, meta, null, null);
writer.saveMetadataToFile(pdf, meta, null);
BookMetadata result = extractor.extractMetadata(pdf);
assertEquals("The Walking Dead", result.getSeriesName());
@@ -132,7 +132,7 @@ class PdfMetadataWriterTest {
meta.setSeriesName("Programming"); // Name without number - BROKEN DATA
meta.setSeriesNumber(null);
writer.saveMetadataToFile(pdf, meta, null, null);
writer.saveMetadataToFile(pdf, meta, null);
BookMetadata result = extractor.extractMetadata(pdf);
// Series should NOT be written since it's incomplete
@@ -149,7 +149,7 @@ class PdfMetadataWriterTest {
meta.setSeriesName("Test Series");
meta.setSeriesNumber(0f); // Zero is invalid
writer.saveMetadataToFile(pdf, meta, null, null);
writer.saveMetadataToFile(pdf, meta, null);
BookMetadata result = extractor.extractMetadata(pdf);
// Series should NOT be written since number is zero
@@ -165,7 +165,7 @@ class PdfMetadataWriterTest {
meta.setSeriesName("Test Series");
meta.setSeriesNumber(22f); // Whole number
writer.saveMetadataToFile(pdf, meta, null, null);
writer.saveMetadataToFile(pdf, meta, null);
// Read raw XMP to verify formatting
String xmpContent = readXmpContent(pdf);
@@ -181,7 +181,7 @@ class PdfMetadataWriterTest {
meta.setSeriesName("Test Series");
meta.setSeriesNumber(1.5f);
writer.saveMetadataToFile(pdf, meta, null, null);
writer.saveMetadataToFile(pdf, meta, null);
BookMetadata result = extractor.extractMetadata(pdf);
assertEquals(1.5f, result.getSeriesNumber());
@@ -194,7 +194,7 @@ class PdfMetadataWriterTest {
BookMetadataEntity meta = createBasicMetadata();
meta.setGoodreadsId("52555538-dead-simple-python"); // Full slug format
writer.saveMetadataToFile(pdf, meta, null, null);
writer.saveMetadataToFile(pdf, meta, null);
BookMetadata result = extractor.extractMetadata(pdf);
assertEquals("52555538", result.getGoodreadsId(),
@@ -208,7 +208,7 @@ class PdfMetadataWriterTest {
BookMetadataEntity meta = createBasicMetadata();
meta.setGoodreadsId("12345678");
writer.saveMetadataToFile(pdf, meta, null, null);
writer.saveMetadataToFile(pdf, meta, null);
BookMetadata result = extractor.extractMetadata(pdf);
assertEquals("12345678", result.getGoodreadsId());
@@ -230,7 +230,7 @@ class PdfMetadataWriterTest {
meta.setLubimyczytacId("123456");
meta.setRanobedbId("7890");
writer.saveMetadataToFile(pdf, meta, null, null);
writer.saveMetadataToFile(pdf, meta, null);
BookMetadata result = extractor.extractMetadata(pdf);
assertEquals("9781718500921", result.getIsbn13());
@@ -256,7 +256,7 @@ class PdfMetadataWriterTest {
meta.setLubimyczytacRating(8.5);
meta.setRanobedbRating(7.8);
writer.saveMetadataToFile(pdf, meta, null, null);
writer.saveMetadataToFile(pdf, meta, null);
BookMetadata result = extractor.extractMetadata(pdf);
assertEquals(4.4, result.getGoodreadsRating(), 0.01);
@@ -274,7 +274,7 @@ class PdfMetadataWriterTest {
meta.setGoodreadsRating(0.0);
meta.setHardcoverRating(0.0);
writer.saveMetadataToFile(pdf, meta, null, null);
writer.saveMetadataToFile(pdf, meta, null);
String xmpContent = readXmpContent(pdf);
assertFalse(xmpContent.contains("goodreadsRating"),
@@ -306,7 +306,7 @@ class PdfMetadataWriterTest {
moods.add(mood2);
meta.setMoods(moods);
writer.saveMetadataToFile(pdf, meta, null, null);
writer.saveMetadataToFile(pdf, meta, null);
BookMetadata result = extractor.extractMetadata(pdf);
assertTrue(result.getTags().contains("Python"));
@@ -322,7 +322,7 @@ class PdfMetadataWriterTest {
BookMetadataEntity meta = createBasicMetadata();
meta.setSubtitle("Idiomatic Python for the Impatient Programmer");
writer.saveMetadataToFile(pdf, meta, null, null);
writer.saveMetadataToFile(pdf, meta, null);
BookMetadata result = extractor.extractMetadata(pdf);
assertEquals("Idiomatic Python for the Impatient Programmer", result.getSubtitle());
@@ -335,7 +335,7 @@ class PdfMetadataWriterTest {
BookMetadataEntity meta = createBasicMetadata();
meta.setPublishedDate(LocalDate.of(2021, 2, 17));
writer.saveMetadataToFile(pdf, meta, null, null);
writer.saveMetadataToFile(pdf, meta, null);
String xmpContent = readXmpContent(pdf);
// CreateDate should be date-only format: 2021-02-17
@@ -352,7 +352,7 @@ class PdfMetadataWriterTest {
meta.setSeriesNumber(1f);
meta.setIsbn13("1234567890123");
writer.saveMetadataToFile(pdf, meta, null, null);
writer.saveMetadataToFile(pdf, meta, null);
String xmpContent = readXmpContent(pdf);
assertTrue(xmpContent.contains("xmlns:booklore=\"http://booklore.org/metadata/1.0/\""),
@@ -369,7 +369,7 @@ class PdfMetadataWriterTest {
BookMetadataEntity meta = createBasicMetadata();
writer.saveMetadataToFile(pdf, meta, null, null);
writer.saveMetadataToFile(pdf, meta, null);
String xmpContent = readXmpContent(pdf);
assertTrue(xmpContent.contains("<xmp:CreatorTool>Booklore</xmp:CreatorTool>"));