|
| 1 | +package org.jabref.http.server.cayw; |
| 2 | + |
| 3 | +import java.io.BufferedReader; |
| 4 | +import java.io.IOException; |
| 5 | +import java.io.InputStream; |
| 6 | +import java.io.InputStreamReader; |
| 7 | +import java.nio.charset.StandardCharsets; |
| 8 | +import java.nio.file.Files; |
| 9 | +import java.util.ArrayList; |
| 10 | +import java.util.List; |
| 11 | +import java.util.Optional; |
| 12 | +import java.util.concurrent.CompletableFuture; |
| 13 | +import java.util.concurrent.CountDownLatch; |
| 14 | +import java.util.concurrent.ExecutionException; |
| 15 | + |
| 16 | +import javafx.application.Platform; |
| 17 | + |
| 18 | +import org.jabref.http.server.cayw.gui.CAYWEntry; |
| 19 | +import org.jabref.http.server.cayw.gui.SearchDialog; |
| 20 | +import org.jabref.logic.importer.fileformat.BibtexImporter; |
| 21 | +import org.jabref.logic.preferences.CliPreferences; |
| 22 | +import org.jabref.logic.preferences.JabRefCliPreferences; |
| 23 | +import org.jabref.model.database.BibDatabase; |
| 24 | +import org.jabref.model.database.BibDatabaseContext; |
| 25 | +import org.jabref.model.entry.BibEntry; |
| 26 | +import org.jabref.model.entry.field.StandardField; |
| 27 | +import org.jabref.model.util.DummyFileUpdateMonitor; |
| 28 | + |
| 29 | +import com.google.gson.Gson; |
| 30 | +import jakarta.inject.Inject; |
| 31 | +import jakarta.ws.rs.DefaultValue; |
| 32 | +import jakarta.ws.rs.GET; |
| 33 | +import jakarta.ws.rs.Path; |
| 34 | +import jakarta.ws.rs.Produces; |
| 35 | +import jakarta.ws.rs.QueryParam; |
| 36 | +import jakarta.ws.rs.core.MediaType; |
| 37 | +import jakarta.ws.rs.core.Response; |
| 38 | +import org.jspecify.annotations.Nullable; |
| 39 | +import org.slf4j.Logger; |
| 40 | +import org.slf4j.LoggerFactory; |
| 41 | + |
| 42 | +@Path("better-bibtex/cayw") |
| 43 | +public class CAYWResource { |
| 44 | + public static final Logger LOGGER = LoggerFactory.getLogger(CAYWResource.class); |
| 45 | + private static final String CHOCOLATEBIB_PATH = "/Chocolate.bib"; |
| 46 | + private static boolean initialized = false; |
| 47 | + |
| 48 | + @Inject |
| 49 | + private CliPreferences preferences; |
| 50 | + |
| 51 | + @Inject |
| 52 | + private Gson gson; |
| 53 | + |
| 54 | + @GET |
| 55 | + @Produces(MediaType.TEXT_PLAIN) |
| 56 | + public Response getCitation( |
| 57 | + @QueryParam("probe") String probe, |
| 58 | + @QueryParam("format") @DefaultValue("latex") String format, |
| 59 | + @QueryParam("clipboard") String clipboard, |
| 60 | + @QueryParam("minimize") String minimize, |
| 61 | + @QueryParam("texstudio") String texstudio, |
| 62 | + @QueryParam("selected") String selected, |
| 63 | + @QueryParam("select") String select, |
| 64 | + @QueryParam("librarypath") String libraryPath |
| 65 | + ) throws IOException, ExecutionException, InterruptedException { |
| 66 | + if (probe != null && !probe.isEmpty()) { |
| 67 | + return Response.ok("ready").build(); |
| 68 | + } |
| 69 | + |
| 70 | + BibDatabaseContext databaseContext = getBibDatabaseContext(libraryPath); |
| 71 | + |
| 72 | + /* unused until DatabaseSearcher is fixed |
| 73 | + PostgreServer postgreServer = new PostgreServer(); |
| 74 | + IndexManager.clearOldSearchIndices(); |
| 75 | + searcher = new DatabaseSearcher( |
| 76 | + databaseContext, |
| 77 | + new CurrentThreadTaskExecutor(), |
| 78 | + preferences, |
| 79 | + postgreServer); |
| 80 | + */ |
| 81 | + |
| 82 | + List<CAYWEntry<BibEntry>> entries = databaseContext.getEntries() |
| 83 | + .stream() |
| 84 | + .map(this::createCAYWEntry) |
| 85 | + .toList(); |
| 86 | + |
| 87 | + initializeGUI(); |
| 88 | + |
| 89 | + CompletableFuture<List<BibEntry>> future = new CompletableFuture<>(); |
| 90 | + Platform.runLater(() -> { |
| 91 | + SearchDialog<BibEntry> dialog = new SearchDialog<>(); |
| 92 | + // TODO: Using the DatabaseSearcher directly here results in a lot of exceptions being thrown, so we use an alternative for now until we have a nice way of using the DatabaseSearcher class. |
| 93 | + // searchDialog.set(new SearchDialog<>(s -> searcher.getMatches(new SearchQuery(s)), entries)); |
| 94 | + List<BibEntry> results = dialog.show(searchQuery -> |
| 95 | + entries.stream() |
| 96 | + .filter(bibEntryCAYWEntry -> matches(bibEntryCAYWEntry, searchQuery)) |
| 97 | + .map(CAYWEntry::getValue) |
| 98 | + .toList(), |
| 99 | + entries); |
| 100 | + |
| 101 | + future.complete(results); |
| 102 | + }); |
| 103 | + |
| 104 | + List<String> citationKeys = future.get().stream() |
| 105 | + .map(BibEntry::getCitationKey) |
| 106 | + .filter(Optional::isPresent) |
| 107 | + .map(Optional::get) |
| 108 | + .toList(); |
| 109 | + |
| 110 | + if (citationKeys.isEmpty()) { |
| 111 | + return Response.noContent().build(); |
| 112 | + } |
| 113 | + |
| 114 | + return Response.ok(gson.toJson(citationKeys)).build(); |
| 115 | + } |
| 116 | + |
| 117 | + private BibDatabaseContext getBibDatabaseContext(String libraryPath) throws IOException { |
| 118 | + InputStream libraryStream; |
| 119 | + if (libraryPath != null && !libraryPath.isEmpty()) { |
| 120 | + java.nio.file.Path path = java.nio.file.Path.of(libraryPath); |
| 121 | + if (!Files.exists(path)) { |
| 122 | + LOGGER.error("Library path does not exist, using the default chocolate.bib: {}", libraryPath); |
| 123 | + libraryStream = getChocolateBibAsStream(); |
| 124 | + } else { |
| 125 | + libraryStream = Files.newInputStream(path); |
| 126 | + } |
| 127 | + } else { |
| 128 | + // Use the latest opened library as the default library |
| 129 | + final List<java.nio.file.Path> lastOpenedLibraries = new ArrayList<>(JabRefCliPreferences.getInstance().getLastFilesOpenedPreferences().getLastFilesOpened()); |
| 130 | + if (lastOpenedLibraries.isEmpty()) { |
| 131 | + LOGGER.warn("No library path provided and no last opened libraries found, using the default chocolate.bib."); |
| 132 | + libraryStream = getChocolateBibAsStream(); |
| 133 | + } else { |
| 134 | + java.nio.file.Path lastOpenedLibrary = lastOpenedLibraries.getFirst(); |
| 135 | + if (!Files.exists(lastOpenedLibrary)) { |
| 136 | + LOGGER.error("Last opened library does not exist, using the default chocolate.bib: {}", lastOpenedLibrary); |
| 137 | + libraryStream = getChocolateBibAsStream(); |
| 138 | + } else { |
| 139 | + libraryStream = Files.newInputStream(lastOpenedLibrary); |
| 140 | + } |
| 141 | + } |
| 142 | + } |
| 143 | + |
| 144 | + BibtexImporter bibtexImporter = new BibtexImporter(preferences.getImportFormatPreferences(), new DummyFileUpdateMonitor()); |
| 145 | + BibDatabaseContext databaseContext; |
| 146 | + try (BufferedReader reader = new BufferedReader(new InputStreamReader(libraryStream, StandardCharsets.UTF_8))) { |
| 147 | + databaseContext = bibtexImporter.importDatabase(reader).getDatabaseContext(); |
| 148 | + } |
| 149 | + return databaseContext; |
| 150 | + } |
| 151 | + |
| 152 | + private synchronized void initializeGUI() { |
| 153 | + // TODO: Implement a better way to handle the window popup since this is a bit hacky. |
| 154 | + if (!initialized) { |
| 155 | + CountDownLatch latch = new CountDownLatch(1); |
| 156 | + Platform.startup(() -> { |
| 157 | + Platform.setImplicitExit(false); |
| 158 | + initialized = true; |
| 159 | + latch.countDown(); |
| 160 | + }); |
| 161 | + try { |
| 162 | + latch.await(); |
| 163 | + } catch (InterruptedException e) { |
| 164 | + Thread.currentThread().interrupt(); |
| 165 | + throw new RuntimeException("JavaFX initialization interrupted", e); |
| 166 | + } |
| 167 | + } |
| 168 | + } |
| 169 | + |
| 170 | + /// @return a stream to the `Chocolate.bib` file in the classpath (is null only if the file was moved or there are issues with the classpath) |
| 171 | + private @Nullable InputStream getChocolateBibAsStream() { |
| 172 | + return BibDatabase.class.getResourceAsStream(CHOCOLATEBIB_PATH); |
| 173 | + } |
| 174 | + |
| 175 | + private CAYWEntry<BibEntry> createCAYWEntry(BibEntry entry) { |
| 176 | + String label = entry.getCitationKey().orElse(""); |
| 177 | + String shortLabel = label; |
| 178 | + String description = entry.getField(StandardField.TITLE).orElse(entry.getAuthorTitleYear()); |
| 179 | + return new CAYWEntry<>(entry, label, shortLabel, description); |
| 180 | + } |
| 181 | + |
| 182 | + private boolean matches(CAYWEntry<BibEntry> entry, String searchText) { |
| 183 | + if (searchText == null || searchText.isEmpty()) { |
| 184 | + return true; |
| 185 | + } |
| 186 | + String lowerSearchText = searchText.toLowerCase(); |
| 187 | + return entry.getLabel().toLowerCase().contains(lowerSearchText) || |
| 188 | + entry.getDescription().toLowerCase().contains(lowerSearchText) || |
| 189 | + entry.getShortLabel().toLowerCase().contains(lowerSearchText); |
| 190 | + } |
| 191 | +} |
0 commit comments