Item 4: servidor HTTP embutido para compartilhar plugins

This commit is contained in:
tonyhcj committed 2026-11-05 16:21:35 -03:00
1 parent da5d97822e
commit 0d463e2047
8 files changed
+270 -2

No files matched your search

@@ -0,0 +1,24 @@
package pitiupi.platform;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Optional;
public final class AppVersion {
private AppVersion() { }
public static String current() {
String v = AppVersion.class.getPackage().getImplementationVersion();
return v != null ? v : "0.0.0-dev";
}
/** O JAR em execução, ou vazio se estiver rodando de pasta de classes (IDE). */
public static Optional<Path> runningJar() {
try {
Path p = Path.of(AppVersion.class.getProtectionDomain().getCodeSource().getLocation().toURI());
return Files.isRegularFile(p) && p.toString().endsWith(".jar") ? Optional.of(p) : Optional.empty();
} catch (Exception e) {
return Optional.empty();
}
}
}
@@ -0,0 +1,154 @@
package pitiupi.plugins.remote;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Stream;
import pitiupi.errors.ErrorCode;
import pitiupi.errors.PitiupiException;
import pitiupi.platform.AppVersion;
import pitiupi.plugins.store.PluginMetadataWriter;
public final class PluginServer {
private final Path sharedDir;
private HttpServer server;
private ExecutorService pool;
public PluginServer(Path sharedDir) {
this.sharedDir = sharedDir;
}
public synchronized void start(InetAddress bind, int port) throws PitiupiException {
if (server != null) {
return;
}
try {
// bind == null -> todas as interfaces
server = HttpServer.create(new InetSocketAddress(bind, port), 0);
pool = Executors.newFixedThreadPool(4);
server.setExecutor(pool);
server.createContext("/", this::handle);
server.start();
} catch (IOException e) {
server = null;
throw new PitiupiException(ErrorCode.PLUGIN_SERVER_START_FAILED, e);
}
}
public synchronized void stop() {
if (server != null) {
server.stop(0);
pool.shutdownNow();
server = null;
}
}
public synchronized boolean isRunning() { return server != null; }
public synchronized int getPort() { return server.getAddress().getPort(); }
private void handle(HttpExchange ex) throws IOException {
try (ex) {
if (!"GET".equals(ex.getRequestMethod())) {
reply(ex, 405, "text/plain", new byte[0]);
return;
}
String path = ex.getRequestURI().getPath();
if (("/" + PluginListFormat.FILE_NAME).equals(path)) {
byte[] body = PluginListFormat.format(buildList()).getBytes(StandardCharsets.UTF_8);
reply(ex, 200, "text/plain; charset=utf-8", body);
} else if (("/" + PluginListFormat.CORE_FILE_NAME).equals(path)) {
reply(ex, 200, "text/plain; charset=utf-8", coreList().getBytes(StandardCharsets.UTF_8));
} else {
Path jar = "/pitiupi.jar".equals(path) ? AppVersion.runningJar().orElse(null)
: findShared(path.substring(1));
if (jar == null) {
reply(ex, 404, "text/plain", new byte[0]);
return;
}
ex.getResponseHeaders().set("Content-Type", "application/java-archive");
ex.sendResponseHeaders(200, Files.size(jar));
try (OutputStream out = ex.getResponseBody()) {
Files.copy(jar, out);
}
}
} catch (IOException e) {
// cliente caiu no meio ou erro de leitura: a conexão é fechada pelo try-with-resources
}
}
/** Só serve arquivos que estão na pasta: o nome do pedido nunca vira caminho (sem path traversal). */
private Path findShared(String name) throws IOException {
if (!PluginListFormat.isSafeJarName(name)) {
return null;
}
try (Stream<Path> s = Files.list(sharedDir)) {
return s.filter(p -> p.getFileName().toString().equals(name))
.filter(Files::isRegularFile).findFirst().orElse(null);
}
}
List<RemotePluginEntry> buildList() throws IOException {
List<RemotePluginEntry> out = new ArrayList<>();
try (Stream<Path> s = Files.list(sharedDir)) {
for (Path jar : s.filter(p -> PluginListFormat.isSafeJarName(p.getFileName().toString()))
.sorted().toList()) {
String file = jar.getFileName().toString();
String stem = file.substring(0, file.length() - 4);
Properties meta = readMeta(jar);
out.add(new RemotePluginEntry(
meta.getProperty("arquivoId", stem),
meta.getProperty("displayName", meta.getProperty("name", stem)),
meta.getProperty("version", "0"),
meta.getProperty("author", ""),
meta.getProperty("description", ""),
file,
Sha256.of(jar)));
}
}
return out;
}
private String coreList() throws IOException {
Optional<Path> jar = AppVersion.runningJar();
if (jar.isEmpty()) {
return "";
}
return PluginListFormat.format(List.of(new RemotePluginEntry(
"pitiupi", "Pitiupi", AppVersion.current(), "", "", "pitiupi.jar", Sha256.of(jar.get()))));
}
private static Properties readMeta(Path jar) {
Properties p = new Properties();
Path meta = PluginMetadataWriter.metaPathFor(jar);
if (Files.isRegularFile(meta)) {
try (InputStream in = Files.newInputStream(meta)) {
p.load(in);
} catch (IOException ignored) { }
}
return p;
}
private static void reply(HttpExchange ex, int code, String type, byte[] body) throws IOException {
ex.getResponseHeaders().set("Content-Type", type);
ex.sendResponseHeaders(code, body.length == 0 ? -1 : body.length);
if (body.length > 0) {
try (OutputStream out = ex.getResponseBody()) {
out.write(body);
}
}
}
}
@@ -0,0 +1,6 @@
package pitiupi.plugins.remote;
import java.util.List;
import java.util.Optional;
import pitiupi.plugins.store.InstalledPluginRef;
@@ -0,0 +1,2 @@
package pitiupi.plugins.remote;
@@ -25,6 +25,8 @@ public final class MainShellFrame extends JFrame implements ShellHost {
private final PluginGalleryPanel galleryPanel;
private final SettingsPanel settingsPanel;
private final JLabel statusLabel = new JLabel(" ");
private final pitiupi.plugins.remote.PluginServer pluginServer =
new pitiupi.plugins.remote.PluginServer(pitiupi.platform.PitiupiHome.get().pluginsDirectory());
public MainShellFrame(String userName, int port) {
setTitle("Pitiupi");
@@ -45,7 +47,7 @@ public final class MainShellFrame extends JFrame implements ShellHost {
galleryPanel.setOpenHandler(this::openPluginTabFromGallery);
networkUsersPanel = new NetworkUsersPanel(connectionManager);
ShellMenuBar menuBar = new ShellMenuBar(this);
ShellMenuBar menuBar = new ShellMenuBar(this, pluginServer);
setJMenuBar(menuBar);
JPanel center = new JPanel(new BorderLayout());
@@ -126,6 +128,7 @@ public final class MainShellFrame extends JFrame implements ShellHost {
@Override
public void exit() {
pluginServer.stop();
connectionManager.shutdownGracefully();
setVisible(false);
dispose();
@@ -0,0 +1,58 @@
package pitiupi.presentation.shell;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel;
import javax.swing.border.EmptyBorder;
import java.awt.Frame;
import java.awt.GridLayout;
import pitiupi.errors.PitiupiException;
import pitiupi.plugins.remote.PluginServer;
import pitiupi.presentation.shell.ui.ShellUi;
public final class PluginServerDialog extends JDialog {
public PluginServerDialog(Frame owner, PluginServer server) {
super(owner, "Compartilhar meus plugins", true);
JSpinner port = new JSpinner(new SpinnerNumberModel(9090, 1024, 65535, 1));
JButton toggle = new JButton();
JTextField url = new JTextField(24);
url.setEditable(false);
Runnable sync = () -> {
boolean on = server.isRunning();
toggle.setText(on ? "Parar" : "Iniciar");
port.setEnabled(!on);
url.setText(on ? LocalNetworkInfo.bestLocalIpv4() + ":" + server.getPort() : "");
};
toggle.addActionListener(e -> {
try {
if (server.isRunning()) {
server.stop();
} else {
port.commitEdit();
server.start(LocalNetworkInfo.bestLocalInet4Address(), (Integer) port.getValue());
}
} catch (PitiupiException ex) {
JOptionPane.showMessageDialog(this, ex.getUserMessage()
+ (ex.getCause() != null ? "\n(" + ex.getCause().getMessage() + ")" : ""));
} catch (java.text.ParseException ignored) { }
sync.run();
});
JPanel p = new JPanel(new GridLayout(0, 2, 6, 6));
p.setBorder(new EmptyBorder(10, 10, 10, 10));
p.add(new JLabel("Porta HTTP:")); p.add(port);
p.add(new JLabel("Endereço p/ outros:")); p.add(url);
p.add(ShellUi.mutedLabel("Pasta compartilhada: plugins instalados."));
p.add(toggle);
add(p);
sync.run();
pack();
setLocationRelativeTo(owner);
}
}
@@ -0,0 +1,18 @@
package pitiupi.presentation.shell;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
import java.awt.Component;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.Optional;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import pitiupi.errors.ErrorCode;
import pitiupi.errors.PitiupiException;
import pitiupi.platform.AppVersion;
import pitiupi.platform.PitiupiHome;
import pitiupi.plugins.remote.*;
@@ -9,11 +9,14 @@ import javax.swing.JMenuItem;
*/
public final class ShellMenuBar extends JMenuBar {
public ShellMenuBar(java.awt.Frame owner) {
public ShellMenuBar(java.awt.Frame owner, pitiupi.plugins.remote.PluginServer server) {
JMenu plugins = new JMenu("Plugins");
JMenuItem online = new JMenuItem("Plugins online…");
online.addActionListener(e -> new RemotePluginsDialog(owner).setVisible(true));
plugins.add(online);
JMenuItem share = new JMenuItem("Compartilhar meus plugins…");
share.addActionListener(e -> new PluginServerDialog(owner, server).setVisible(true));
plugins.add(share);
add(plugins);
JMenu help = new JMenu("Ajuda");