fix(epub): support cover edits when no previous cover (#2278)
This commit is contained in:
+213
-48
@@ -10,6 +10,7 @@ import org.booklore.model.entity.BookMetadataEntity;
|
|||||||
import org.booklore.model.enums.BookFileType;
|
import org.booklore.model.enums.BookFileType;
|
||||||
import org.booklore.service.ArchiveService;
|
import org.booklore.service.ArchiveService;
|
||||||
import org.booklore.service.appsettings.AppSettingService;
|
import org.booklore.service.appsettings.AppSettingService;
|
||||||
|
import org.booklore.util.MimeDetector;
|
||||||
import org.booklore.util.SecureXmlUtils;
|
import org.booklore.util.SecureXmlUtils;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
import org.springframework.web.multipart.MultipartFile;
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
@@ -29,10 +30,12 @@ import javax.xml.transform.stream.StreamResult;
|
|||||||
import javax.xml.xpath.XPath;
|
import javax.xml.xpath.XPath;
|
||||||
import javax.xml.xpath.XPathConstants;
|
import javax.xml.xpath.XPathConstants;
|
||||||
import javax.xml.xpath.XPathFactory;
|
import javax.xml.xpath.XPathFactory;
|
||||||
|
import java.io.ByteArrayInputStream;
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
import java.io.FileInputStream;
|
import java.io.FileInputStream;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
|
import java.io.UncheckedIOException;
|
||||||
import java.net.URI;
|
import java.net.URI;
|
||||||
import java.net.URLDecoder;
|
import java.net.URLDecoder;
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
@@ -45,9 +48,7 @@ import java.util.stream.Collectors;
|
|||||||
import java.util.zip.CRC32;
|
import java.util.zip.CRC32;
|
||||||
import java.util.zip.ZipEntry;
|
import java.util.zip.ZipEntry;
|
||||||
import java.util.zip.ZipOutputStream;
|
import java.util.zip.ZipOutputStream;
|
||||||
|
|
||||||
import java.util.function.Predicate;
|
import java.util.function.Predicate;
|
||||||
import java.io.UncheckedIOException;
|
|
||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@Component
|
@Component
|
||||||
@@ -86,8 +87,7 @@ public class EpubMetadataWriter implements MetadataWriter {
|
|||||||
DocumentBuilder builder = SecureXmlUtils.createSecureDocumentBuilder(true);
|
DocumentBuilder builder = SecureXmlUtils.createSecureDocumentBuilder(true);
|
||||||
Document opfDoc = builder.parse(opfFile);
|
Document opfDoc = builder.parse(opfFile);
|
||||||
|
|
||||||
NodeList metadataList = opfDoc.getElementsByTagNameNS(OPF_NS, "metadata");
|
Element metadataElement = getOrCreateMetadataElement(opfDoc);
|
||||||
Element metadataElement = (Element) metadataList.item(0);
|
|
||||||
final String DC_NS = "http://purl.org/dc/elements/1.1/";
|
final String DC_NS = "http://purl.org/dc/elements/1.1/";
|
||||||
|
|
||||||
boolean[] hasChanges = {false};
|
boolean[] hasChanges = {false};
|
||||||
@@ -225,6 +225,7 @@ public class EpubMetadataWriter implements MetadataWriter {
|
|||||||
organizeMetadataElements(metadataElement);
|
organizeMetadataElements(metadataElement);
|
||||||
removeInvalidMetaRefines(metadataElement, opfDoc);
|
removeInvalidMetaRefines(metadataElement, opfDoc);
|
||||||
removeEmptyTextNodes(opfDoc);
|
removeEmptyTextNodes(opfDoc);
|
||||||
|
organizePackageElements(opfDoc);
|
||||||
Transformer transformer = TransformerFactory.newInstance().newTransformer();
|
Transformer transformer = TransformerFactory.newInstance().newTransformer();
|
||||||
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
|
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
|
||||||
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
|
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
|
||||||
@@ -276,13 +277,74 @@ public class EpubMetadataWriter implements MetadataWriter {
|
|||||||
if (replaceElementText(doc, parent, tag, ns, val, false)) flag[0] = true;
|
if (replaceElementText(doc, parent, tag, ns, val, false)) flag[0] = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void replaceMetaElement(Element metadataElement, Document doc, String name, String newVal, boolean[] flag) {
|
private Optional<Element> getElement(Element parent, String namespace, String tagName) {
|
||||||
String existing = getMetaContentByName(metadataElement, name);
|
NodeList metadataElements = parent.getElementsByTagNameNS(namespace, tagName);
|
||||||
if (!Objects.equals(existing, newVal)) {
|
|
||||||
removeMetaByName(metadataElement, name);
|
for (int i = 0; i < metadataElements.getLength(); i++ ) {
|
||||||
if (newVal != null) metadataElement.appendChild(createMetaElement(doc, name, newVal));
|
if (metadataElements.item(i) instanceof Element element) {
|
||||||
flag[0] = true;
|
return Optional.of(element);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<Element> getElements(Element parent, String namespace, String tagName) {
|
||||||
|
NodeList metadataElements = parent.getElementsByTagNameNS(namespace, tagName);
|
||||||
|
|
||||||
|
List<Element> elements = new ArrayList<>();
|
||||||
|
for (int i = 0; i < metadataElements.getLength(); i++ ) {
|
||||||
|
if (metadataElements.item(i) instanceof Element element) {
|
||||||
|
elements.add(element);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return elements;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Element getOrCreateElement(Element parent, String namespace, String tagName) {
|
||||||
|
return getElement(parent, namespace, tagName)
|
||||||
|
.orElseGet(() -> {
|
||||||
|
Element element = parent.getOwnerDocument().createElementNS(namespace, tagName);
|
||||||
|
parent.appendChild(element);
|
||||||
|
return element;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private Element getOrCreateMetadataElement(Document doc) {
|
||||||
|
return getOrCreateElement(doc.getDocumentElement(), OPF_NS, "metadata");
|
||||||
|
}
|
||||||
|
|
||||||
|
public Element getOrCreateManifestElement(Document doc) {
|
||||||
|
return getOrCreateElement(doc.getDocumentElement(), OPF_NS, "manifest");
|
||||||
|
}
|
||||||
|
|
||||||
|
public Element getOrCreateSpineElement(Document doc) {
|
||||||
|
return getOrCreateElement(doc.getDocumentElement(), OPF_NS, "spine");
|
||||||
|
}
|
||||||
|
|
||||||
|
private Element upsertMetaElement(Document doc, String name, String content) {
|
||||||
|
var metadata = getOrCreateMetadataElement(doc);
|
||||||
|
|
||||||
|
NodeList metaElements = metadata.getElementsByTagName("meta");
|
||||||
|
for (int i = 0; i < metaElements.getLength(); i++) {
|
||||||
|
if (metaElements.item(i) instanceof Element element) {
|
||||||
|
if (!name.equals(element.getAttribute("name"))) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Found target.
|
||||||
|
element.setAttribute("content", content);
|
||||||
|
return element;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// We couldn't find any meta element so we can create it.
|
||||||
|
Element element = doc.createElement("meta");
|
||||||
|
element.setAttribute("name", name);
|
||||||
|
element.setAttribute("content", content);
|
||||||
|
metadata.appendChild(element);
|
||||||
|
return element;
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean replaceElementText(Document doc, Element parent, String tagName, String namespaceURI, String newValue, boolean restoreMode) {
|
private boolean replaceElementText(Document doc, Element parent, String tagName, String namespaceURI, String newValue, boolean restoreMode) {
|
||||||
@@ -379,6 +441,7 @@ public class EpubMetadataWriter implements MetadataWriter {
|
|||||||
applyCoverImageToEpub(tempDir, opfDoc, coverData);
|
applyCoverImageToEpub(tempDir, opfDoc, coverData);
|
||||||
|
|
||||||
removeEmptyTextNodes(opfDoc);
|
removeEmptyTextNodes(opfDoc);
|
||||||
|
organizePackageElements(opfDoc);
|
||||||
Transformer transformer = TransformerFactory.newInstance().newTransformer();
|
Transformer transformer = TransformerFactory.newInstance().newTransformer();
|
||||||
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
|
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
|
||||||
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
|
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
|
||||||
@@ -406,37 +469,57 @@ public class EpubMetadataWriter implements MetadataWriter {
|
|||||||
return BookFileType.EPUB;
|
return BookFileType.EPUB;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void applyCoverImageToEpub(Path tempDir, Document opfDoc, byte[] coverData) throws IOException {
|
private String generateCoverId(Document doc, Path dir, String extension) {
|
||||||
NodeList manifestList = opfDoc.getElementsByTagNameNS(OPF_NS, "manifest");
|
// Generate an ID / file combination that does not exist yet.
|
||||||
if (manifestList.getLength() == 0) {
|
var ids = getDocumentIds(doc);
|
||||||
throw new IOException("No <manifest> element found in OPF document.");
|
String coverId = "cover";
|
||||||
|
while(ids.contains(coverId) || Files.exists(dir.resolve(coverId + extension))) {
|
||||||
|
coverId = "cover-" + UUID.randomUUID().toString();
|
||||||
|
}
|
||||||
|
return coverId;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Path getManifestItemPath(Path tempDir, Path opfDir, Element element) throws IOException {
|
||||||
|
String href = element.getAttribute("href");
|
||||||
|
String decodedHref = URLDecoder.decode(href, StandardCharsets.UTF_8);
|
||||||
|
if (decodedHref == null || decodedHref.isBlank()) {
|
||||||
|
throw new IOException("Manifest item has no href attribute");
|
||||||
}
|
}
|
||||||
|
|
||||||
Element manifest = (Element) manifestList.item(0);
|
Path filePath = opfDir.resolve(decodedHref).normalize();
|
||||||
|
|
||||||
|
if (!filePath.startsWith(tempDir)) {
|
||||||
|
throw new IOException("Manifest item file may not be outside the epub archive");
|
||||||
|
}
|
||||||
|
|
||||||
|
return filePath;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void applyCoverImageToEpub(Path tempDir, Document opfDoc, byte[] coverData) throws IOException {
|
||||||
|
String mediaType = MimeDetector.detect(new ByteArrayInputStream(coverData));
|
||||||
|
String extension = MimeDetector.getExtension(mediaType);
|
||||||
|
|
||||||
|
Element metadataElement = getOrCreateMetadataElement(opfDoc);
|
||||||
|
Element manifestElement = getOrCreateManifestElement(opfDoc);
|
||||||
Element existingCoverItem = null;
|
Element existingCoverItem = null;
|
||||||
|
|
||||||
// First, try to find cover via metadata reference (EPUB 3 style)
|
// First, try to find cover via metadata reference (EPUB 3 style)
|
||||||
NodeList metadataList = opfDoc.getElementsByTagNameNS(OPF_NS, "metadata");
|
String coverItemId = getMetaContentByName(metadataElement, "cover");
|
||||||
if (metadataList.getLength() > 0) {
|
if (coverItemId != null && !coverItemId.isBlank()) {
|
||||||
Element metadataElement = (Element) metadataList.item(0);
|
// Find the item with this id
|
||||||
String coverItemId = getMetaContentByName(metadataElement, "cover");
|
NodeList items = manifestElement.getElementsByTagNameNS(OPF_NS, "item");
|
||||||
|
for (int i = 0; i < items.getLength(); i++) {
|
||||||
if (coverItemId != null && !coverItemId.isBlank()) {
|
Element item = (Element) items.item(i);
|
||||||
// Find the item with this id
|
if (coverItemId.equals(item.getAttribute("id"))) {
|
||||||
NodeList items = manifest.getElementsByTagNameNS(OPF_NS, "item");
|
existingCoverItem = item;
|
||||||
for (int i = 0; i < items.getLength(); i++) {
|
break;
|
||||||
Element item = (Element) items.item(i);
|
|
||||||
if (coverItemId.equals(item.getAttribute("id"))) {
|
|
||||||
existingCoverItem = item;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// If not found, try looking for properties="cover-image" (EPUB 3)
|
// If not found, try looking for properties="cover-image" (EPUB 3)
|
||||||
if (existingCoverItem == null) {
|
if (existingCoverItem == null) {
|
||||||
NodeList items = manifest.getElementsByTagNameNS(OPF_NS, "item");
|
NodeList items = manifestElement.getElementsByTagNameNS(OPF_NS, "item");
|
||||||
for (int i = 0; i < items.getLength(); i++) {
|
for (int i = 0; i < items.getLength(); i++) {
|
||||||
Element item = (Element) items.item(i);
|
Element item = (Element) items.item(i);
|
||||||
String properties = item.getAttribute("properties");
|
String properties = item.getAttribute("properties");
|
||||||
@@ -449,7 +532,7 @@ public class EpubMetadataWriter implements MetadataWriter {
|
|||||||
|
|
||||||
// If still not found, try common id values (EPUB 2 fallback)
|
// If still not found, try common id values (EPUB 2 fallback)
|
||||||
if (existingCoverItem == null) {
|
if (existingCoverItem == null) {
|
||||||
NodeList items = manifest.getElementsByTagNameNS(OPF_NS, "item");
|
NodeList items = manifestElement.getElementsByTagNameNS(OPF_NS, "item");
|
||||||
for (int i = 0; i < items.getLength(); i++) {
|
for (int i = 0; i < items.getLength(); i++) {
|
||||||
Element item = (Element) items.item(i);
|
Element item = (Element) items.item(i);
|
||||||
String itemId = item.getAttribute("id");
|
String itemId = item.getAttribute("id");
|
||||||
@@ -460,16 +543,6 @@ public class EpubMetadataWriter implements MetadataWriter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (existingCoverItem == null) {
|
|
||||||
throw new IOException("No cover item found in manifest");
|
|
||||||
}
|
|
||||||
|
|
||||||
String coverHref = existingCoverItem.getAttribute("href");
|
|
||||||
String decodedCoverHref = URLDecoder.decode(coverHref, StandardCharsets.UTF_8);
|
|
||||||
if (decodedCoverHref == null || decodedCoverHref.isBlank()) {
|
|
||||||
throw new IOException("Cover item has no href attribute");
|
|
||||||
}
|
|
||||||
|
|
||||||
Path opfPath;
|
Path opfPath;
|
||||||
try {
|
try {
|
||||||
opfPath = findOpfPath(tempDir);
|
opfPath = findOpfPath(tempDir);
|
||||||
@@ -478,7 +551,69 @@ public class EpubMetadataWriter implements MetadataWriter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Path opfDir = opfPath.getParent();
|
Path opfDir = opfPath.getParent();
|
||||||
Path coverFilePath = opfDir.resolve(decodedCoverHref).normalize();
|
|
||||||
|
if (existingCoverItem != null) {
|
||||||
|
try {
|
||||||
|
getManifestItemPath(tempDir, opfDir, existingCoverItem);
|
||||||
|
} catch (IOException e) {
|
||||||
|
log.warn("Invalid cover for epub, ignoring", e);
|
||||||
|
existingCoverItem = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (existingCoverItem == null) {
|
||||||
|
// If there is no existing cover item, we should create one.
|
||||||
|
String coverId = generateCoverId(opfDoc, opfDir, extension);
|
||||||
|
|
||||||
|
existingCoverItem = opfDoc.createElementNS(OPF_NS, "item");
|
||||||
|
existingCoverItem.setAttribute("id", coverId);
|
||||||
|
existingCoverItem.setAttribute("media-type", mediaType);
|
||||||
|
existingCoverItem.setAttribute("href", coverId + extension);
|
||||||
|
|
||||||
|
// Add the item and set the
|
||||||
|
manifestElement.appendChild(existingCoverItem);
|
||||||
|
upsertMetaElement(opfDoc, "cover", coverId);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove all item's epub3 `properties` containing `cover-image`.
|
||||||
|
NodeList items = manifestElement.getElementsByTagNameNS(OPF_NS, "item");
|
||||||
|
for (int i = 0; i < items.getLength(); i++) {
|
||||||
|
if (items.item(i) instanceof Element item) {
|
||||||
|
// Remember: the `properties` attribute is a space delimited list,
|
||||||
|
// so we can't clear it entirely.
|
||||||
|
String properties = Arrays.stream(
|
||||||
|
item.getAttribute("properties")
|
||||||
|
.trim()
|
||||||
|
.split("\\s+")
|
||||||
|
)
|
||||||
|
.filter(s -> !"cover-image".equals(s))
|
||||||
|
.collect(Collectors.joining(" "));
|
||||||
|
|
||||||
|
if (properties.isBlank()) {
|
||||||
|
item.removeAttribute("properties");
|
||||||
|
} else {
|
||||||
|
item.setAttribute("properties", properties);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean isEpub3 = isEpub3(opfDoc);
|
||||||
|
|
||||||
|
if (isEpub3) {
|
||||||
|
// Add epub3 properties cover-image back to the target cover item.
|
||||||
|
String properties = existingCoverItem.getAttribute("properties")
|
||||||
|
.trim();
|
||||||
|
|
||||||
|
if (properties.isBlank()) {
|
||||||
|
properties = "cover-image";
|
||||||
|
} else {
|
||||||
|
properties += " cover-image";
|
||||||
|
}
|
||||||
|
|
||||||
|
existingCoverItem.setAttribute("properties", properties);
|
||||||
|
}
|
||||||
|
|
||||||
|
Path coverFilePath = getManifestItemPath(tempDir, opfDir, existingCoverItem);
|
||||||
|
|
||||||
Files.createDirectories(coverFilePath.getParent());
|
Files.createDirectories(coverFilePath.getParent());
|
||||||
Files.write(coverFilePath, coverData);
|
Files.write(coverFilePath, coverData);
|
||||||
@@ -603,12 +738,7 @@ public class EpubMetadataWriter implements MetadataWriter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void removeInvalidMetaRefines(Element metadataElement, Document doc) {
|
private Set<String> getDocumentIds(Document doc) {
|
||||||
// In an ideal world we could set the `validating` flag or
|
|
||||||
// otherwise set the `isId` attribute tag correctly for `id`
|
|
||||||
// but because we cannot, we can't use `getElementById()` on
|
|
||||||
// the document. With that in mind, we area going to read all
|
|
||||||
// tags, check if they have an `id`, and store that in a `Set`
|
|
||||||
Set<String> ids = new HashSet<>();
|
Set<String> ids = new HashSet<>();
|
||||||
|
|
||||||
NodeList nodes = doc.getElementsByTagName("*");
|
NodeList nodes = doc.getElementsByTagName("*");
|
||||||
@@ -623,6 +753,17 @@ public class EpubMetadataWriter implements MetadataWriter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return ids;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void removeInvalidMetaRefines(Element metadataElement, Document doc) {
|
||||||
|
// In an ideal world we could set the `validating` flag or
|
||||||
|
// otherwise set the `isId` attribute tag correctly for `id`
|
||||||
|
// but because we cannot, we can't use `getElementById()` on
|
||||||
|
// the document. With that in mind, we area going to read all
|
||||||
|
// tags, check if they have an `id`, and store that in a `Set`
|
||||||
|
var ids = getDocumentIds(doc);
|
||||||
|
|
||||||
NodeList metas = metadataElement.getElementsByTagNameNS("*", "meta");
|
NodeList metas = metadataElement.getElementsByTagNameNS("*", "meta");
|
||||||
for (int i = metas.getLength() - 1; i >= 0; i--) {
|
for (int i = metas.getLength() - 1; i >= 0; i--) {
|
||||||
Element meta = (Element) metas.item(i);
|
Element meta = (Element) metas.item(i);
|
||||||
@@ -1207,6 +1348,30 @@ public class EpubMetadataWriter implements MetadataWriter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void organizePackageElements(Document document) {
|
||||||
|
// Per the epubcheck dtd:
|
||||||
|
// <package> must have as children elements, in this order:
|
||||||
|
// <metadata>, <manifest>, and <spine>, and optionally may
|
||||||
|
// include <tours> and/or <guide>, then `<collection>` items.
|
||||||
|
Element metadata = getOrCreateMetadataElement(document);
|
||||||
|
Element manifest = getOrCreateManifestElement(document);
|
||||||
|
Element spine = getOrCreateSpineElement(document);
|
||||||
|
Optional<Element> tours = getElement(document.getDocumentElement(), OPF_NS, "tours");
|
||||||
|
Optional<Element> guide = getElement(document.getDocumentElement(), OPF_NS, "guide");
|
||||||
|
List<Element> collections = getElements(document.getDocumentElement(), OPF_NS, "collection");
|
||||||
|
|
||||||
|
Element packageElement = document.getDocumentElement();
|
||||||
|
|
||||||
|
packageElement.appendChild(metadata);
|
||||||
|
packageElement.appendChild(manifest);
|
||||||
|
packageElement.appendChild(spine);
|
||||||
|
tours.ifPresent(packageElement::appendChild);
|
||||||
|
guide.ifPresent(packageElement::appendChild);
|
||||||
|
for (var collection : collections) {
|
||||||
|
packageElement.appendChild(collection);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private void organizeMetadataElements(Element metadataElement) {
|
private void organizeMetadataElements(Element metadataElement) {
|
||||||
final String DC_NS = "http://purl.org/dc/elements/1.1/";
|
final String DC_NS = "http://purl.org/dc/elements/1.1/";
|
||||||
List<Element> identifiers = new ArrayList<>();
|
List<Element> identifiers = new ArrayList<>();
|
||||||
|
|||||||
@@ -8,10 +8,40 @@ import java.io.IOException;
|
|||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@UtilityClass
|
@UtilityClass
|
||||||
public class MimeDetector {
|
public class MimeDetector {
|
||||||
|
private static final Map<String, String> MEDIA_TYPE_EXTENSIONS = Map.ofEntries(
|
||||||
|
Map.entry("text/html", ".html"),
|
||||||
|
Map.entry("application/xhtml+xml", ".html"),
|
||||||
|
Map.entry("application/javascript", ".js"),
|
||||||
|
Map.entry("text/css", ".css"),
|
||||||
|
Map.entry("image/jpeg", ".jpg"),
|
||||||
|
Map.entry("image/png", ".png"),
|
||||||
|
Map.entry("image/gif", ".gif"),
|
||||||
|
Map.entry("image/svg+xml", ".svg"),
|
||||||
|
Map.entry("font/ttf", ".ttf"),
|
||||||
|
Map.entry("font/otf", ".otf"),
|
||||||
|
Map.entry("application/vnd.ms-fontobject", ".eot"),
|
||||||
|
Map.entry("application/xml", ".xml"),
|
||||||
|
Map.entry("application/x-dtbncx+xml", ".ncx"),
|
||||||
|
Map.entry("audio/mpeg", ".mp3"),
|
||||||
|
Map.entry("video/mp4", ".mp4"),
|
||||||
|
Map.entry("audio/mp4", ".m4a"),
|
||||||
|
Map.entry("audio/aac", ".aac"),
|
||||||
|
Map.entry("audio/wav", ".wav"),
|
||||||
|
Map.entry("audio/ogg", ".ogg"),
|
||||||
|
Map.entry("application/oebps-package+xml", ".opf"),
|
||||||
|
Map.entry("image/webp", ".webp"),
|
||||||
|
Map.entry("font/woff", ".woff"),
|
||||||
|
Map.entry("font/woff2", ".woff2"),
|
||||||
|
Map.entry("application/smil+xml", ".smil"),
|
||||||
|
Map.entry("audio/flac", ".flac"),
|
||||||
|
Map.entry("video/webm", ".webm"),
|
||||||
|
Map.entry("image/avif", ".avif")
|
||||||
|
);
|
||||||
|
|
||||||
// Tika is thread-safe one instance for the whole app.
|
// Tika is thread-safe one instance for the whole app.
|
||||||
private static final Tika TIKA = new Tika();
|
private static final Tika TIKA = new Tika();
|
||||||
@@ -48,6 +78,10 @@ public class MimeDetector {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public String getExtension(String mediaType) {
|
||||||
|
return MEDIA_TYPE_EXTENSIONS.getOrDefault(mediaType, ".bin");
|
||||||
|
}
|
||||||
|
|
||||||
public boolean isAudio(Path path) throws IOException {
|
public boolean isAudio(Path path) throws IOException {
|
||||||
return detect(path).startsWith("audio/");
|
return detect(path).startsWith("audio/");
|
||||||
}
|
}
|
||||||
|
|||||||
+114
@@ -36,6 +36,7 @@ import java.nio.file.Path;
|
|||||||
import java.util.Enumeration;
|
import java.util.Enumeration;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
import java.util.zip.ZipEntry;
|
import java.util.zip.ZipEntry;
|
||||||
import java.util.zip.ZipFile;
|
import java.util.zip.ZipFile;
|
||||||
import java.util.zip.ZipOutputStream;
|
import java.util.zip.ZipOutputStream;
|
||||||
@@ -151,6 +152,33 @@ class EpubMetadataWriterTest {
|
|||||||
assertThat(content).doesNotContain("refines=\"#example2\"");
|
assertThat(content).doesNotContain("refines=\"#example2\"");
|
||||||
assertThat(content).contains("refines=\"#example\"");
|
assertThat(content).contains("refines=\"#example\"");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Should sort package children in EPUB3")
|
||||||
|
void writeMetadata_shouldSortPackageChildren() throws Exception {
|
||||||
|
String opfContent = """
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<package xmlns="http://www.idpf.org/2007/opf" version="3.0">
|
||||||
|
<manifest></manifest>
|
||||||
|
<collection></collection>
|
||||||
|
<metadata xmlns:dc="http://purl.org/dc/elements/1.1/">
|
||||||
|
</metadata>
|
||||||
|
</package>""";
|
||||||
|
|
||||||
|
File epubFile = createEpubWithOpf(opfContent, "test-sort-package-" + System.nanoTime() + ".epub");
|
||||||
|
writer.saveMetadataToFile(epubFile, metadata, null, new MetadataClearFlags());
|
||||||
|
|
||||||
|
String content = readOpfContent(epubFile);
|
||||||
|
|
||||||
|
int manifestIndex = content.indexOf("<manifest");
|
||||||
|
int metadataIndex = content.indexOf("<metadata");
|
||||||
|
int spineIndex = content.indexOf("<spine");
|
||||||
|
int collectionIndex = content.indexOf("<collection");
|
||||||
|
|
||||||
|
assertThat(metadataIndex).isLessThan(manifestIndex);
|
||||||
|
assertThat(manifestIndex).isLessThan(spineIndex);
|
||||||
|
assertThat(spineIndex).isLessThan(collectionIndex);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Nested
|
@Nested
|
||||||
@@ -694,6 +722,92 @@ class EpubMetadataWriterTest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Nested
|
||||||
|
@DisplayName("Cover Tests")
|
||||||
|
class CoverTests {
|
||||||
|
@Test
|
||||||
|
void shouldCreateManifestItemIfNoneExist() throws Exception {
|
||||||
|
Path thumbnailPath = tempDir.resolve("thumbnail-" + System.nanoTime()).toAbsolutePath();
|
||||||
|
Files.write(thumbnailPath, new byte[]{0x01, 0x02, 0x03});
|
||||||
|
|
||||||
|
File epubFile = createEpubWithOpf(
|
||||||
|
"""
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<package xmlns="http://www.idpf.org/2007/opf" version="2.0">
|
||||||
|
<metadata xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:opf="http://www.idpf.org/2007/opf">
|
||||||
|
<dc:title>Test Book</dc:title>
|
||||||
|
</metadata>
|
||||||
|
</package>
|
||||||
|
""",
|
||||||
|
"no-cover-" + System.nanoTime() + ".epub"
|
||||||
|
);
|
||||||
|
|
||||||
|
writer.saveMetadataToFile(epubFile, metadata, thumbnailPath.toString(), new MetadataClearFlags());
|
||||||
|
|
||||||
|
|
||||||
|
String content = readOpfContent(epubFile);
|
||||||
|
assertThat(content).contains("href=\"cover.");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldAddEpub3CoverImageTag() throws Exception {
|
||||||
|
Path thumbnailPath = tempDir.resolve("thumbnail-" + System.nanoTime()).toAbsolutePath();
|
||||||
|
Files.write(thumbnailPath, new byte[]{0x01, 0x02, 0x03});
|
||||||
|
|
||||||
|
File epubFile = createEpubWithOpf(
|
||||||
|
"""
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<package xmlns="http://www.idpf.org/2007/opf" version="3.0">
|
||||||
|
<metadata xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:opf="http://www.idpf.org/2007/opf">
|
||||||
|
<dc:title>Test Book</dc:title>
|
||||||
|
</metadata>
|
||||||
|
</package>
|
||||||
|
""",
|
||||||
|
"no-cover-" + System.nanoTime() + ".epub"
|
||||||
|
);
|
||||||
|
|
||||||
|
writer.saveMetadataToFile(epubFile, metadata, thumbnailPath.toString(), new MetadataClearFlags());
|
||||||
|
|
||||||
|
|
||||||
|
String content = readOpfContent(epubFile);
|
||||||
|
assertThat(content).contains("properties=\"cover-image\"");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldAllowOnlyOneCoverImagePropertiesEpub3() throws Exception {
|
||||||
|
Path thumbnailPath = tempDir.resolve("thumbnail-" + System.nanoTime()).toAbsolutePath();
|
||||||
|
Files.write(thumbnailPath, new byte[]{0x01, 0x02, 0x03});
|
||||||
|
|
||||||
|
File epubFile = createEpubWithOpf(
|
||||||
|
"""
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<package xmlns="http://www.idpf.org/2007/opf" version="3.0">
|
||||||
|
<metadata xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:opf="http://www.idpf.org/2007/opf">
|
||||||
|
<dc:title>Test Book</dc:title>
|
||||||
|
</metadata>
|
||||||
|
<manifest>
|
||||||
|
<item href="foo" properties="cover-image" />
|
||||||
|
<item href="bar" properties="cover-image" />
|
||||||
|
</manifest>
|
||||||
|
</package>
|
||||||
|
""",
|
||||||
|
"cover-" + System.nanoTime() + ".epub"
|
||||||
|
);
|
||||||
|
|
||||||
|
writer.saveMetadataToFile(epubFile, metadata, thumbnailPath.toString(), new MetadataClearFlags());
|
||||||
|
|
||||||
|
|
||||||
|
String content = readOpfContent(epubFile);
|
||||||
|
var pattern = Pattern.compile("properties=\"cover-image\"");
|
||||||
|
var matcher = pattern.matcher(content);
|
||||||
|
int count = 0;
|
||||||
|
while (matcher.find()) {
|
||||||
|
count++;
|
||||||
|
}
|
||||||
|
assertThat(count).isEqualTo(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private Document parseOpf(File epubFile) throws Exception {
|
private Document parseOpf(File epubFile) throws Exception {
|
||||||
try (ZipFile zf = new ZipFile(epubFile)) {
|
try (ZipFile zf = new ZipFile(epubFile)) {
|
||||||
ZipEntry ze = zf.getEntry("OEBPS/content.opf");
|
ZipEntry ze = zf.getEntry("OEBPS/content.opf");
|
||||||
|
|||||||
Reference in New Issue
Block a user