Item 3: baixar e instalar plugins por servidor HTTP

This commit is contained in:
tonyhcj committed 2026-11-05 10:01:47 -03:00
1 parent 18f3f643bb
commit da5d97822e
13 files changed
+385 -3

No files matched your search

Whitespace-only changes.
@@ -0,0 +1,56 @@
package pitiupi.plugins.remote;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
public final class PluginListFormat {
public static final String FILE_NAME = "lista-de-plugins.txt";
public static final String CORE_FILE_NAME = "atualizacao-pitiupi.txt";
private static final Pattern SAFE_JAR = Pattern.compile("[A-Za-z0-9._-]+\\.jar");
private static final Pattern SAFE_ID = Pattern.compile("[A-Za-z0-9._-]+");
private static final Pattern SHA256 = Pattern.compile("[0-9a-fA-F]{64}");
private PluginListFormat() { }
public static boolean isSafeJarName(String name) {
return name != null && SAFE_JAR.matcher(name).matches();
}
public static List<RemotePluginEntry> parse(String text) {
List<RemotePluginEntry> out = new ArrayList<>();
if (text.startsWith("\uFEFF")) {
text = text.substring(1);
}
for (String raw : text.split("\\R")) {
if (raw.isBlank() || raw.stripLeading().startsWith("#")) {
continue;
}
String[] c = raw.split("\t", -1);
if (c.length < 7) {
continue;
}
String id = c[0].trim(), file = c[5].trim(), sha = c[6].trim();
if (!SAFE_ID.matcher(id).matches() || !isSafeJarName(file)
|| !SHA256.matcher(sha).matches()) {
continue; // linha ruim não derruba a lista inteira
}
out.add(new RemotePluginEntry(id, c[1].trim(), c[2].trim(), c[3].trim(),
c[4].trim(), file, sha));
}
return out;
}
public static String format(List<RemotePluginEntry> entries) {
StringBuilder sb = new StringBuilder("# id\tnome\tversao\tautor\tdescricao\tarquivo\tsha256\n");
for (RemotePluginEntry e : entries) {
sb.append(String.join("\t", clean(e.id()), clean(e.name()), clean(e.version()),
clean(e.author()), clean(e.description()), e.file(), e.sha256())).append('\n');
}
return sb.toString();
}
private static String clean(String s) {
return s == null ? "" : s.replaceAll("[\\t\\r\\n]+", " ").trim();
}
}
@@ -0,0 +1,116 @@
package pitiupi.plugins.remote;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import java.util.HexFormat;
import java.util.List;
import pitiupi.errors.ErrorCode;
import pitiupi.errors.PitiupiException;
public final class PluginRepositoryClient {
private static final long MAX_JAR_BYTES = 50L * 1024 * 1024;
private static final long MAX_LIST_BYTES = 256L * 1024;
private final HttpClient http = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(5))
.followRedirects(HttpClient.Redirect.NORMAL)
.build();
/** "192.168.0.10:9090" vira "http://192.168.0.10:9090/". */
public static URI normalize(String input) {
String s = input == null ? "" : input.trim();
if (s.isEmpty()) {
throw new IllegalArgumentException("Informe o endereço do servidor.");
}
if (!s.contains("://")) {
s = "http://" + s;
}
URI uri = URI.create(s);
String scheme = uri.getScheme();
if (!"http".equals(scheme) && !"https".equals(scheme) || uri.getHost() == null) {
throw new IllegalArgumentException("Endereço inválido: " + input);
}
return URI.create(s.endsWith("/") ? s : s + "/");
}
public List<RemotePluginEntry> fetchList(URI base, String listName) throws PitiupiException {
try {
HttpRequest req = HttpRequest.newBuilder(base.resolve(listName))
.timeout(Duration.ofSeconds(10)).GET().build();
HttpResponse<byte[]> res = http.send(req, HttpResponse.BodyHandlers.ofByteArray());
if (res.statusCode() != 200) {
throw new PitiupiException(ErrorCode.PLUGIN_SERVER_UNREACHABLE, "HTTP " + res.statusCode());
}
if (res.body().length > MAX_LIST_BYTES) {
throw new PitiupiException(ErrorCode.PLUGIN_LIST_INVALID);
}
return PluginListFormat.parse(new String(res.body(), StandardCharsets.UTF_8));
} catch (IOException e) {
throw new PitiupiException(ErrorCode.PLUGIN_SERVER_UNREACHABLE, e);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new PitiupiException(ErrorCode.PLUGIN_SERVER_UNREACHABLE, e);
}
}
/** Baixa para um arquivo temporário em cacheDir, conferindo tamanho e SHA-256. */
public Path download(URI base, RemotePluginEntry entry, Path cacheDir) throws PitiupiException {
Path tmp = null;
try {
Files.createDirectories(cacheDir);
HttpRequest req = HttpRequest.newBuilder(base.resolve(entry.file()))
.timeout(Duration.ofSeconds(60)).GET().build();
HttpResponse<InputStream> res = http.send(req, HttpResponse.BodyHandlers.ofInputStream());
if (res.statusCode() != 200) {
res.body().close();
throw new PitiupiException(ErrorCode.PLUGIN_DOWNLOAD_FAILED, "HTTP " + res.statusCode());
}
tmp = Files.createTempFile(cacheDir, "dl-", ".part");
MessageDigest md = MessageDigest.getInstance("SHA-256");
long total = 0;
try (InputStream in = res.body(); OutputStream out = Files.newOutputStream(tmp)) {
byte[] buf = new byte[8192];
int n;
while ((n = in.read(buf)) != -1) {
total += n;
if (total > MAX_JAR_BYTES) {
throw new PitiupiException(ErrorCode.PLUGIN_DOWNLOAD_FAILED, "Arquivo grande demais");
}
md.update(buf, 0, n);
out.write(buf, 0, n);
}
}
if (!HexFormat.of().formatHex(md.digest()).equalsIgnoreCase(entry.sha256())) {
throw new PitiupiException(ErrorCode.PLUGIN_HASH_MISMATCH);
}
return tmp;
} catch (PitiupiException e) {
deleteQuietly(tmp);
throw e;
} catch (IOException | NoSuchAlgorithmException e) {
deleteQuietly(tmp);
throw new PitiupiException(ErrorCode.PLUGIN_DOWNLOAD_FAILED, e);
} catch (InterruptedException e) {
deleteQuietly(tmp);
Thread.currentThread().interrupt();
throw new PitiupiException(ErrorCode.PLUGIN_DOWNLOAD_FAILED, e);
}
}
private static void deleteQuietly(Path p) {
if (p != null) {
try { Files.deleteIfExists(p); } catch (IOException ignored) { }
}
}
}
Whitespace-only changes.
Whitespace-only changes.
@@ -0,0 +1,4 @@
package pitiupi.plugins.remote;
public record RemotePluginEntry(String id, String name, String version, String author,
String description, String file, String sha256) { }
@@ -0,0 +1,28 @@
package pitiupi.plugins.remote;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HexFormat;
public final class Sha256 {
private Sha256() { }
public static String of(Path file) throws IOException {
try (InputStream in = Files.newInputStream(file)) {
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] buf = new byte[8192];
int n;
while ((n = in.read(buf)) != -1) {
md.update(buf, 0, n);
}
return HexFormat.of().formatHex(md.digest());
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(e);
}
}
}
Whitespace-only changes.
@@ -45,7 +45,7 @@ public final class MainShellFrame extends JFrame implements ShellHost {
galleryPanel.setOpenHandler(this::openPluginTabFromGallery);
networkUsersPanel = new NetworkUsersPanel(connectionManager);
ShellMenuBar menuBar = new ShellMenuBar();
ShellMenuBar menuBar = new ShellMenuBar(this);
setJMenuBar(menuBar);
JPanel center = new JPanel(new BorderLayout());
Whitespace-only changes.
@@ -0,0 +1,172 @@
package pitiupi.presentation.shell;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingWorker;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Frame;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import pitiupi.errors.PitiupiException;
import pitiupi.plugins.store.InstalledPluginRef;
import pitiupi.presentation.shell.ui.ShellUi;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.net.URI;
import java.nio.file.*;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ExecutionException;
import pitiupi.plugins.remote.*;
import pitiupi.plugins.store.PluginStore;
import pitiupi.platform.PitiupiHome;
import pitiupi.errors.*;
public final class RemotePluginsDialog extends JDialog {
private static final String CFG_URL = "plugins.serverUrl";
private final PluginRepositoryClient client = new PluginRepositoryClient();
private final PluginStore store = new PluginStore();
private final JTextField urlField = new JTextField(28);
private final DefaultTableModel model = new DefaultTableModel(
new String[]{"Nome", "Versão", "Autor", "Descrição"}, 0) {
@Override public boolean isCellEditable(int r, int c) { return false; }
};
private final JTable table = new JTable(model);
private final JLabel status = ShellUi.mutedLabel(" ");
private List<RemotePluginEntry> entries = List.of();
private URI currentBase;
public RemotePluginsDialog(Frame owner) {
super(owner, "Plugins online", true);
setLayout(new BorderLayout(8, 8));
((JComponent) getContentPane()).setBorder(new EmptyBorder(8, 8, 8, 8));
try {
urlField.setText(PitiupiHome.get().config().getString(CFG_URL, ""));
} catch (IOException ignored) { }
JButton refresh = new JButton("Atualizar lista");
refresh.addActionListener(e -> refresh());
JPanel top = new JPanel(new BorderLayout(6, 0));
top.add(new JLabel("Servidor:"), BorderLayout.WEST);
top.add(urlField, BorderLayout.CENTER);
top.add(refresh, BorderLayout.EAST);
add(top, BorderLayout.NORTH);
JScrollPane scroll = new JScrollPane(table);
ShellUi.borderlessScroll(scroll);
scroll.setPreferredSize(new Dimension(640, 260));
add(scroll, BorderLayout.CENTER);
JButton install = new JButton("Instalar");
install.addActionListener(e -> installSelected());
JPanel bottom = new JPanel(new BorderLayout());
bottom.add(status, BorderLayout.CENTER);
bottom.add(install, BorderLayout.EAST);
add(bottom, BorderLayout.SOUTH);
pack();
setLocationRelativeTo(owner);
}
private void refresh() {
final URI base;
try {
base = PluginRepositoryClient.normalize(urlField.getText());
} catch (IllegalArgumentException ex) {
JOptionPane.showMessageDialog(this, ex.getMessage());
return;
}
try {
PitiupiHome.get().config().setString(CFG_URL, urlField.getText().trim());
} catch (IOException ignored) { }
status.setText("Consultando…");
new SwingWorker<List<RemotePluginEntry>, Void>() {
@Override protected List<RemotePluginEntry> doInBackground() throws Exception {
return client.fetchList(base, PluginListFormat.FILE_NAME);
}
@Override protected void done() {
try {
entries = get();
currentBase = base;
fill();
status.setText(entries.size() + " plugin(s) no servidor");
} catch (Exception ex) {
status.setText(" ");
showError(ex);
}
}
}.execute();
}
private void fill() {
model.setRowCount(0);
for (RemotePluginEntry e : entries) {
model.addRow(new Object[]{e.name(), e.version(), e.author(), e.description()});
}
}
private void installSelected() {
int row = table.getSelectedRow();
if (row < 0 || currentBase == null) {
return;
}
RemotePluginEntry e = entries.get(table.convertRowIndexToModel(row));
int ok = JOptionPane.showConfirmDialog(this,
"Instalar " + e.name() + " " + e.version() + " de " + currentBase + "?\n"
+ "Um plugin roda com o mesmo poder do programa. Só instale de quem você confia.",
"Confirmar instalação", JOptionPane.YES_NO_OPTION);
if (ok != JOptionPane.YES_OPTION) {
return;
}
final URI base = currentBase;
status.setText("Baixando " + e.file() + "…");
new SwingWorker<Void, Void>() {
@Override protected Void doInBackground() throws Exception {
Path tmp = client.download(base, e, PitiupiHome.get().cacheDirectory());
try {
store.installFromFile(tmp, e.file(), false);
} finally {
Files.deleteIfExists(tmp);
}
return null;
}
@Override protected void done() {
try {
get();
status.setText("Instalado: " + e.name());
ApplicationRestarter.promptRestartIfNeeded(RemotePluginsDialog.this);
} catch (Exception ex) {
status.setText(" ");
showError(ex);
}
}
}.execute();
}
private void showError(Exception ex) {
Throwable t = ex instanceof java.util.concurrent.ExecutionException && ex.getCause() != null
? ex.getCause() : ex;
String msg = t instanceof PitiupiException pe ? pe.getUserMessage() : "Erro: " + t.getMessage();
if (t.getCause() != null && t.getCause().getMessage() != null) {
msg += "\n(" + t.getCause().getMessage() + ")";
}
JOptionPane.showMessageDialog(this, msg, "Plugins online", JOptionPane.WARNING_MESSAGE);
}
}
Whitespace-only changes.
@@ -5,11 +5,17 @@ import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
/**
* Barra de menus mínima (apenas Ajuda).
* Barra de menus: Plugins (online) e Ajuda.
*/
public final class ShellMenuBar extends JMenuBar {
public ShellMenuBar() {
public ShellMenuBar(java.awt.Frame owner) {
JMenu plugins = new JMenu("Plugins");
JMenuItem online = new JMenuItem("Plugins online…");
online.addActionListener(e -> new RemotePluginsDialog(owner).setVisible(true));
plugins.add(online);
add(plugins);
JMenu help = new JMenu("Ajuda");
JMenuItem about = new JMenuItem("Sobre");
about.addActionListener(e -> new AboutDialog().setVisible(true));