Item 5: comparar versões e atualizar plugins

This commit is contained in:
tonyhcj committed 2026-11-05 17:19:02 -03:00
1 parent 0d463e2047
commit 637e16b4d7
3 files changed
+162 -29

No files matched your search

@@ -4,3 +4,34 @@ import java.util.List;
import java.util.Optional;
import pitiupi.plugins.store.InstalledPluginRef;
public final class PluginStatus {
public enum State { NOT_INSTALLED, UP_TO_DATE, UPDATE_AVAILABLE, UNKNOWN_VERSION }
private PluginStatus() { }
/** Casa pelo id remoto contra arquivoId, identifier ou nome do arquivo (sem ".jar"/"pitiupi."). */
public static Optional<InstalledPluginRef> findInstalled(List<InstalledPluginRef> installed, String remoteId) {
for (InstalledPluginRef ref : installed) {
String stem = ref.getFileName().replaceFirst("\\.jar$", "").replaceFirst("^pitiupi\\.", "");
if (remoteId.equalsIgnoreCase(ref.getArquivoId().orElse(""))
|| remoteId.equalsIgnoreCase(ref.getIdentifier().orElse(""))
|| remoteId.equalsIgnoreCase(stem)) {
return Optional.of(ref);
}
}
return Optional.empty();
}
public static State of(RemotePluginEntry remote, Optional<InstalledPluginRef> installed) {
if (installed.isEmpty()) {
return State.NOT_INSTALLED;
}
Optional<String> v = installed.get().getVersion();
if (v.isEmpty()) {
return State.UNKNOWN_VERSION; // JAR nunca carregado: sem .plugin.meta ainda
}
return VersionCompare.compare(remote.version(), v.get()) > 0
? State.UPDATE_AVAILABLE : State.UP_TO_DATE;
}
}
@@ -1,2 +1,25 @@
package pitiupi.plugins.remote;
public final class VersionCompare {
private VersionCompare() { }
public static int compare(String a, String b) {
String[] x = a.trim().split("\\."), y = b.trim().split("\\.");
for (int i = 0; i < Math.max(x.length, y.length); i++) {
int cmp = Integer.compare(part(x, i), part(y, i));
if (cmp != 0) {
return cmp;
}
}
return 0;
}
private static int part(String[] p, int i) {
if (i >= p.length) {
return 0;
}
String digits = p[i].replaceAll("^(\\d*).*$", "$1"); // "3-beta" -> "3"
return digits.isEmpty() ? 0 : Integer.parseInt(digits);
}
}
@@ -10,32 +10,35 @@ import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingWorker;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Frame;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import pitiupi.errors.PitiupiException;
import pitiupi.platform.PitiupiHome;
import pitiupi.plugins.remote.PluginListFormat;
import pitiupi.plugins.remote.PluginRepositoryClient;
import pitiupi.plugins.remote.PluginStatus;
import pitiupi.plugins.remote.RemotePluginEntry;
import pitiupi.plugins.store.InstalledPluginRef;
import pitiupi.plugins.store.PluginStore;
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.*;
/**
* Plugins online: consulta um servidor, mostra a situação de cada plugin
* (não instalado, atualizado, atualização disponível) e instala ou atualiza.
*/
public final class RemotePluginsDialog extends JDialog {
private static final String CFG_URL = "plugins.serverUrl";
@@ -44,11 +47,14 @@ public final class RemotePluginsDialog extends JDialog {
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) {
new String[]{"Nome", "Versão", "Autor", "Descrição", "Situaçã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 final JButton installButton = new JButton("Instalar");
/** Plugins baixados nesta sessão: o .plugin.meta só é reescrito no próximo início. */
private final Set<String> pendingRestart = new HashSet<>();
private List<RemotePluginEntry> entries = List.of();
private URI currentBase;
@@ -71,14 +77,18 @@ public final class RemotePluginsDialog extends JDialog {
JScrollPane scroll = new JScrollPane(table);
ShellUi.borderlessScroll(scroll);
scroll.setPreferredSize(new Dimension(640, 260));
scroll.setPreferredSize(new Dimension(760, 260));
add(scroll, BorderLayout.CENTER);
JButton install = new JButton("Instalar");
install.addActionListener(e -> installSelected());
installButton.addActionListener(e -> installSelected());
table.getSelectionModel().addListSelectionListener(ev -> {
if (!ev.getValueIsAdjusting()) {
updateInstallLabel();
}
});
JPanel bottom = new JPanel(new BorderLayout());
bottom.add(status, BorderLayout.CENTER);
bottom.add(install, BorderLayout.EAST);
bottom.add(installButton, BorderLayout.EAST);
add(bottom, BorderLayout.SOUTH);
pack();
@@ -115,11 +125,51 @@ public final class RemotePluginsDialog extends JDialog {
}.execute();
}
/** Lê a pasta de plugins; se falhar, trata como "nada instalado". */
private List<InstalledPluginRef> installedNow() {
try {
return store.listInstalled();
} catch (IOException ex) {
return List.of();
}
}
private void fill() {
model.setRowCount(0);
List<InstalledPluginRef> installed = installedNow();
for (RemotePluginEntry e : entries) {
model.addRow(new Object[]{e.name(), e.version(), e.author(), e.description()});
Optional<InstalledPluginRef> inst = PluginStatus.findInstalled(installed, e.id());
model.addRow(new Object[]{
e.name(), e.version(), e.author(), e.description(), situation(e, inst)
});
}
updateInstallLabel();
}
private String situation(RemotePluginEntry e, Optional<InstalledPluginRef> inst) {
if (pendingRestart.contains(e.id())) {
return "reinício pendente";
}
return switch (PluginStatus.of(e, inst)) {
case NOT_INSTALLED -> "—";
case UP_TO_DATE -> "instalado (" + inst.get().getVersion().orElse("?") + ")";
case UPDATE_AVAILABLE -> "atualização: " + inst.get().getVersion().orElse("?")
+ " → " + e.version();
case UNKNOWN_VERSION -> "versão desconhecida";
};
}
private void updateInstallLabel() {
int row = table.getSelectedRow();
if (row < 0 || row >= entries.size()) {
installButton.setText("Instalar");
return;
}
RemotePluginEntry e = entries.get(table.convertRowIndexToModel(row));
Optional<InstalledPluginRef> inst = PluginStatus.findInstalled(installedNow(), e.id());
boolean update = !pendingRestart.contains(e.id())
&& PluginStatus.of(e, inst) == PluginStatus.State.UPDATE_AVAILABLE;
installButton.setText(update ? "Atualizar" : "Instalar");
}
private void installSelected() {
@@ -128,20 +178,41 @@ public final class RemotePluginsDialog extends JDialog {
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);
// Se o plugin já está instalado, o novo JAR substitui o arquivo existente
// (evita ter chat.jar e pitiupi.chat.jar ao mesmo tempo).
Optional<InstalledPluginRef> inst = PluginStatus.findInstalled(installedNow(), e.id());
final String targetName = inst.map(InstalledPluginRef::getFileName).orElse(e.file());
PluginStatus.State state = PluginStatus.of(e, inst);
String question;
if (pendingRestart.contains(e.id())) {
question = e.name() + " já foi baixado nesta sessão e aguarda reinício.\nBaixar de novo?";
} else if (state == PluginStatus.State.UP_TO_DATE) {
question = e.name() + " já está na versão " + inst.get().getVersion().orElse("?")
+ ".\nReinstalar mesmo assim?";
} else if (state == PluginStatus.State.UPDATE_AVAILABLE) {
question = "Atualizar " + e.name() + " de " + inst.get().getVersion().orElse("?")
+ " para " + e.version() + "?";
} else {
question = "Instalar " + e.name() + " " + e.version() + "?";
}
question += "\nServidor: " + currentBase
+ "\nUm plugin roda com o mesmo poder do programa. Só instale de quem você confia.";
int ok = JOptionPane.showConfirmDialog(this, question,
"Confirmar", 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);
store.installFromFile(tmp, targetName, false);
} finally {
Files.deleteIfExists(tmp);
}
@@ -150,6 +221,8 @@ public final class RemotePluginsDialog extends JDialog {
@Override protected void done() {
try {
get();
pendingRestart.add(e.id());
fill();
status.setText("Instalado: " + e.name());
ApplicationRestarter.promptRestartIfNeeded(RemotePluginsDialog.this);
} catch (Exception ex) {
@@ -161,11 +234,17 @@ public final class RemotePluginsDialog extends JDialog {
}
private void showError(Exception ex) {
Throwable t = ex instanceof java.util.concurrent.ExecutionException && ex.getCause() != null
Throwable t = ex instanceof 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() + ")";
String msg = "Erro: " + t.getMessage();
if (t instanceof PitiupiException pe) {
msg = pe.getUserMessage();
if (pe.getMessage() != null && !pe.getMessage().equals(msg)) {
msg += "\n(" + pe.getMessage() + ")";
}
if (pe.getCause() != null && pe.getCause().getMessage() != null) {
msg += "\n(" + pe.getCause().getMessage() + ")";
}
}
JOptionPane.showMessageDialog(this, msg, "Plugins online", JOptionPane.WARNING_MESSAGE);
}