Skip to content

EPUB import (v2) #13217

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ Note that this project **does not** adhere to [Semantic Versioning](https://semv
- We added support for import of a Refer/BibIX file format. [#13069](https://github.com/JabRef/jabref/issues/13069)
- We added a new `jabkit` command `pseudonymize` to pseudonymize the library. [#13109](https://github.com/JabRef/jabref/issues/13109)
- We added functionality to focus running instance when trying to start a second instance. [#13129](https://github.com/JabRef/jabref/issues/13129)
- We added EPUB files import. [#13217](https://github.com/JabRef/jabref/pull/13217)

### Changed

Expand Down
2 changes: 1 addition & 1 deletion jabgui/src/main/java/org/jabref/gui/LibraryTab.java
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,6 @@
import org.jabref.gui.undo.UndoableFieldChange;
import org.jabref.gui.undo.UndoableInsertEntries;
import org.jabref.gui.undo.UndoableRemoveEntries;
import org.jabref.gui.util.OptionalObjectProperty;
import org.jabref.gui.util.UiTaskExecutor;
import org.jabref.logic.ai.AiService;
import org.jabref.logic.citationstyle.CitationStyleCache;
Expand All @@ -71,6 +70,7 @@
import org.jabref.logic.search.PostgreServer;
import org.jabref.logic.shared.DatabaseLocation;
import org.jabref.logic.util.BackgroundTask;
import org.jabref.logic.util.OptionalObjectProperty;
import org.jabref.logic.util.TaskExecutor;
import org.jabref.logic.util.io.FileUtil;
import org.jabref.model.FieldChange;
Expand Down
2 changes: 1 addition & 1 deletion jabgui/src/main/java/org/jabref/gui/StateManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,9 @@
import org.jabref.gui.sidepane.SidePaneType;
import org.jabref.gui.util.CustomLocalDragboard;
import org.jabref.gui.util.DialogWindowState;
import org.jabref.gui.util.OptionalObjectProperty;
import org.jabref.logic.search.IndexManager;
import org.jabref.logic.util.BackgroundTask;
import org.jabref.logic.util.OptionalObjectProperty;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.groups.GroupTreeNode;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
import org.jabref.gui.collab.stringdelete.BibTexStringDelete;
import org.jabref.gui.collab.stringrename.BibTexStringRename;
import org.jabref.gui.undo.NamedCompound;
import org.jabref.gui.util.OptionalObjectProperty;
import org.jabref.logic.util.OptionalObjectProperty;
import org.jabref.model.database.BibDatabaseContext;

public sealed abstract class DatabaseChange permits EntryAdd, EntryChange, EntryDelete, GroupChange, MetadataChange, PreambleChange, BibTexStringAdd, BibTexStringChange, BibTexStringDelete, BibTexStringRename {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,18 @@ public List<ImportFilesResultItemViewModel> call() {
message = bibtexParserResult.getErrorMessage();
}
addResultToList(file, success, message);
} else if (FileUtil.isEpubFile(file)) {
ParserResult result = contentImporter.importEpubContent(file);
List<BibEntry> entries = result.getDatabase().getEntries();
boolean success = !result.hasWarnings();
String message;
if (success) {
message = Localization.lang("ePUB entry was successfully imported");
} else {
message = result.getErrorMessage();
}
entriesToAdd.addAll(entries);
addResultToList(file, true, message);
} else {
BibEntry emptyEntryWithLink = createEmptyEntryWithLink(file);
entriesToAdd.add(emptyEntryWithLink);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public enum StandardExternalFileType implements ExternalFileType {
TIFF(Localization.lang("%0 image", "TIFF"), "tiff", "image/tiff", "gimp", "picture", IconTheme.JabRefIcons.PICTURE),
URL("URL", "html", "text/html", "firefox", "www", IconTheme.JabRefIcons.WWW),
MHT("MHT", "mht", "multipart/related", "firefox", "www", IconTheme.JabRefIcons.WWW),
ePUB("ePUB", "epub", "application/epub+zip", "firefox", "www", IconTheme.JabRefIcons.WWW),
ePUB("ePUB", "epub", "application/epub+zip", "firefox", "www", IconTheme.JabRefIcons.BOOK),
MARKDOWN("Markdown", "md", "text/markdown", "emacs", "emacs", IconTheme.JabRefIcons.FILE_TEXT);
private final String name;
private final String extension;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@
import org.jabref.gui.search.MatchCategory;
import org.jabref.gui.util.BindingsHelper;
import org.jabref.gui.util.FilteredListProxy;
import org.jabref.gui.util.OptionalObjectProperty;
import org.jabref.logic.search.IndexManager;
import org.jabref.logic.search.SearchPreferences;
import org.jabref.logic.util.BackgroundTask;
import org.jabref.logic.util.OptionalObjectProperty;
import org.jabref.logic.util.TaskExecutor;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@
import org.jabref.gui.preferences.keybindings.presets.BashKeyBindingPreset;
import org.jabref.gui.preferences.keybindings.presets.KeyBindingPreset;
import org.jabref.gui.preferences.keybindings.presets.NewEntryBindingPreset;
import org.jabref.gui.util.OptionalObjectProperty;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.util.OptionalObjectProperty;

public class KeyBindingsTabViewModel implements PreferenceTabViewModel {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,9 @@
import org.jabref.gui.keyboard.KeyBindingRepository;
import org.jabref.gui.search.SearchType;
import org.jabref.gui.undo.CountingUndoManager;
import org.jabref.gui.util.OptionalObjectProperty;
import org.jabref.logic.bibtex.FieldPreferences;
import org.jabref.logic.importer.ImportFormatPreferences;
import org.jabref.logic.util.OptionalObjectProperty;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.BibEntryTypesManager;
import org.jabref.model.entry.field.UnknownField;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import org.jabref.gui.LibraryTabContainer;
import org.jabref.gui.StateManager;
import org.jabref.gui.preferences.GuiPreferences;
import org.jabref.gui.util.OptionalObjectProperty;
import org.jabref.logic.util.OptionalObjectProperty;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.types.EntryType;
import org.jabref.model.entry.types.StandardEntryType;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@
import org.jabref.gui.frame.SidePanePreferences;
import org.jabref.gui.preferences.GuiPreferences;
import org.jabref.gui.util.CustomLocalDragboard;
import org.jabref.gui.util.OptionalObjectProperty;
import org.jabref.logic.ai.AiService;
import org.jabref.logic.journals.JournalAbbreviationRepository;
import org.jabref.logic.util.OptionalObjectProperty;
import org.jabref.logic.util.TaskExecutor;
import org.jabref.model.entry.BibEntryTypesManager;
import org.jabref.model.util.FileUpdateMonitor;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import org.jabref.gui.StateManager;
import org.jabref.gui.frame.OpenConsoleAction;
import org.jabref.gui.preferences.GuiPreferences;
import org.jabref.logic.util.OptionalObjectProperty;
import org.jabref.model.database.BibDatabaseContext;

import org.junit.jupiter.api.BeforeEach;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,14 @@
import java.io.IOException;
import java.nio.file.Path;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathExpressionException;

import org.jabref.logic.FilePreferences;
import org.jabref.logic.importer.ImportFormatPreferences;
import org.jabref.logic.importer.OpenDatabase;
import org.jabref.logic.importer.ParserResult;
import org.jabref.logic.importer.fileformat.EpubImporter;
import org.jabref.logic.importer.fileformat.PdfMergeMetadataImporter;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.util.FileUpdateMonitor;
Expand All @@ -30,4 +34,12 @@ public ParserResult importPDFContent(Path file, BibDatabaseContext context, File
public ParserResult importFromBibFile(Path bibFile, FileUpdateMonitor fileUpdateMonitor) throws IOException {
return OpenDatabase.loadDatabase(bibFile, importFormatPreferences, fileUpdateMonitor);
}

public ParserResult importEpubContent(Path file) {
try {
return new EpubImporter(importFormatPreferences).importDatabase(file);
} catch (IOException | XPathExpressionException | ParserConfigurationException e) {
return ParserResult.fromError(e);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@
import java.util.SortedSet;
import java.util.TreeSet;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathExpressionException;

import org.jabref.logic.citationkeypattern.CitationKeyPatternPreferences;
import org.jabref.logic.importer.fileformat.BiblioscapeImporter;
import org.jabref.logic.importer.fileformat.BibtexImporter;
Expand All @@ -17,6 +20,7 @@
import org.jabref.logic.importer.fileformat.CopacImporter;
import org.jabref.logic.importer.fileformat.EndnoteImporter;
import org.jabref.logic.importer.fileformat.EndnoteXmlImporter;
import org.jabref.logic.importer.fileformat.EpubImporter;
import org.jabref.logic.importer.fileformat.InspecImporter;
import org.jabref.logic.importer.fileformat.IsiImporter;
import org.jabref.logic.importer.fileformat.MedlineImporter;
Expand All @@ -38,10 +42,14 @@
import org.jabref.model.entry.BibEntry;
import org.jabref.model.util.FileUpdateMonitor;

public class ImportFormatReader {
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ImportFormatReader {
public static final String BIBTEX_FORMAT = "BibTeX";

private static final Logger LOGGER = LoggerFactory.getLogger(ImportFormatReader.class);

/**
* All import formats.
* Sorted accordingly to {@link Importer#compareTo}, which defaults to alphabetically by the name
Expand Down Expand Up @@ -91,6 +99,15 @@ public void reset() {
formats.add(new BibtexImporter(importFormatPreferences, fileUpdateMonitor));
formats.add(new CitaviXmlImporter());

// {@link EpubImporter} constructs `XPath`s internally, and compilation may throw errors.
// {@link EpubReader} also constructs {@link DocumentBuilder}, whose "constructor" can also throw error.
// Hacky workaround.
try {
formats.add(new EpubImporter(importFormatPreferences));
} catch (XPathExpressionException | ParserConfigurationException e) {
LOGGER.error("Unable to construct `EpubImporter`. `EpubImporter` will not be added to available importers", e);
}

// Get custom import formats
formats.addAll(importerPreferences.getCustomImporters());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
Expand Down Expand Up @@ -50,6 +51,10 @@ public static ParserResult fromErrorMessage(String message) {
return parserResult;
}

public static ParserResult fromEntry(BibEntry entry) {
return new ParserResult(Collections.singleton(entry));
}

private static String getErrorMessage(Exception exception) {
String errorMessage = exception.getLocalizedMessage();
if (exception.getCause() != null) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
package org.jabref.logic.importer.fileformat;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.jabref.logic.importer.ImportFormatPreferences;
import org.jabref.logic.importer.Importer;
import org.jabref.logic.importer.ParserResult;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.util.FileType;
import org.jabref.logic.util.OptionalObjectProperty;
import org.jabref.logic.util.StandardFileType;
import org.jabref.logic.util.io.FileUtil;
import org.jabref.logic.util.io.XMLUtil;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.LinkedFile;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.entry.types.StandardEntryType;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

public class EpubImporter extends Importer {
private static final char[] EPUB_HEADER_MAGIC_NUMBER = {0x50, 0x4b, 0x03, 0x04};

private final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
private final DocumentBuilder builder = factory.newDocumentBuilder();

private final XPathFactory xPathFactory = XPathFactory.newInstance();
private final XPath xpath = xPathFactory.newXPath();

private final XPathExpression titlePath = xpath.compile("/package/metadata/title");
private final XPathExpression creatorPath = xpath.compile("/package/metadata/creator");
private final XPathExpression identifierPath = xpath.compile("/package/metadata/identifier");
private final XPathExpression languagePath = xpath.compile("/package/metadata/language");
private final XPathExpression sourcePath = xpath.compile("/package/metadata/source");
private final XPathExpression descriptionPath = xpath.compile("/package/metadata/description");
private final XPathExpression subjectPath = xpath.compile("/package/metadata/subject");

private final ImportFormatPreferences importFormatPreferences;

public EpubImporter(ImportFormatPreferences importFormatPreferences) throws XPathExpressionException, ParserConfigurationException {
this.importFormatPreferences = importFormatPreferences;
}

// ePUB is a ZIP-based format, so this method will clash with other ZIP-based formats.
// Currently, only `.ctv6bak` is found.
@Override
public boolean isRecognizedFormat(BufferedReader input) throws IOException {
char[] header = new char[EPUB_HEADER_MAGIC_NUMBER.length];
int nRead = input.read(header);
return nRead == EPUB_HEADER_MAGIC_NUMBER.length && Arrays.equals(header, EPUB_HEADER_MAGIC_NUMBER);
}

@Override
public ParserResult importDatabase(Path filePath) throws IOException {
// TODO: JabRef has {@link DublinCoreExtractor}, which is exactly the schema used in OPF. However, that class
// is tied to {@link DublinCoreSchema}, which is tied to {@link XMPSchema}. It seems there are no way to pass
// ordinary XML nodes to {@link DublinCoreSchema}.
//
// Current implementation uses some hand-crafted {@link XPath}s, which work okayish, but not as good as a
// full-featured {@link DublinCoreExtractor}.

try (FileSystem fileSystem = FileSystems.newFileSystem(filePath)) {
OptionalObjectProperty<Path> metadataFilePath = OptionalObjectProperty.empty();

Files.walkFileTree(fileSystem.getPath("/"), new SimpleFileVisitor<>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
if (file.toString().endsWith(".opf")) {
metadataFilePath.set(Optional.of(file));
return FileVisitResult.TERMINATE;
}
return FileVisitResult.CONTINUE;
}
});

if (metadataFilePath.get().isEmpty()) {
return ParserResult.fromErrorMessage(Localization.lang("Could not find metadata file. Possibly corrupted ePUB file."));
}

File metadataFile = FileUtil.remapZipPath(metadataFilePath.get().get()).toFile();
Document document = builder.parse(metadataFile);

Optional<String> title = XMLUtil.getNodeContentByXPath(document, titlePath);
Optional<String> identifier = XMLUtil.getNodeContentByXPath(document, identifierPath);
Optional<String> source = XMLUtil.getNodeContentByXPath(document, sourcePath);
Optional<String> description = XMLUtil.getNodeContentByXPath(document, descriptionPath);

List<String> authors = XMLUtil.getNodesContentByXPath(document, creatorPath);
List<String> subjects = XMLUtil.getNodesContentByXPath(document, subjectPath);
List<String> languages = XMLUtil.getNodesContentByXPath(document, languagePath);

LinkedFile linkedFile = new LinkedFile("", filePath.toAbsolutePath(), StandardFileType.EPUB.getName());

BibEntry entry = new BibEntry(StandardEntryType.Book)
.withField(StandardField.TITLE, title)
.withField(StandardField.ABSTRACT, description)
.withField(StandardField.URL, source.isPresent() ? source : identifier)
.withField(StandardField.AUTHOR, !authors.isEmpty() ? Optional.of(String.join(" and ", authors)) : Optional.empty())
.withField(StandardField.LANGUAGE, !languages.isEmpty() ? Optional.of(String.join(" and ", languages)) : Optional.empty())
.withKeywords(subjects, importFormatPreferences.bibEntryPreferences().getKeywordSeparator())
.withFile(linkedFile);

return ParserResult.fromEntry(entry);
} catch (SAXException | XPathExpressionException e) {
return ParserResult.fromError(e);
}
}

@Override
public ParserResult importDatabase(BufferedReader input) throws IOException {
throw new UnsupportedOperationException("EpubImporter does not support importDatabase(BufferedReader reader). "
+ "Instead use importDatabase(Path filePath).");
}

@Override
public String getId() {
return "epub";
}

@Override
public String getName() {
return "ePUB";
}

@Override
public String getDescription() {
return Localization.lang("Import the popular e-book file format ePUB");
}

@Override
public FileType getFileType() {
return StandardFileType.EPUB;
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package org.jabref.gui.util;
package org.jabref.logic.util;

import java.util.Optional;

Expand Down
Loading
Loading