MC/DuneKits/src/main/java/com/example/dunekits/DuneKits.java

206 lines
12 KiB
Java

package com.example.dunekits;
import com.google.gson.*;
import java.lang.reflect.*;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.sql.*;
import java.util.*;
import java.util.function.Consumer;
import java.util.logging.Level;
import org.bukkit.*;
import org.bukkit.command.*;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
/** Receipt delivery commits with DuneCore's authoritative inventory checkpoint. */
public final class DuneKits extends JavaPlugin implements CommandExecutor, org.bukkit.event.Listener {
private JavaPlugin core;
private Method transaction, factionOf, baseFactory;
private final Set<UUID> inflight = new HashSet<>();
private final Map<UUID, Long> notices = new HashMap<>();
@Override public void onEnable() {
Objects.requireNonNull(getCommand("kitclaim")).setExecutor(this);
Objects.requireNonNull(getCommand("dunekit")).setExecutor(this);
Plugin dependency = getServer().getPluginManager().getPlugin("DuneCore");
if (!(dependency instanceof JavaPlugin candidate) || !dependency.isEnabled()) {
getLogger().info("Verification mode: DuneCore is unavailable; no deliveries will run.");
return;
}
try {
core = candidate;
transaction = core.getClass().getMethod("transactNetworkInventory", Player.class, Consumer.class);
factionOf = core.getClass().getMethod("factionOf", Player.class);
baseFactory = core.getClass().getMethod("createFactionKit", String.class);
} catch (ReflectiveOperationException ex) {
core = null;
getLogger().severe("DuneCore lacks atomic inventory delivery support; claims remain queued.");
return;
}
getServer().getPluginManager().registerEvents(this, this);
getServer().getScheduler().runTaskTimer(this, () -> {
for (Player player : getServer().getOnlinePlayers()) { upgradeFactionIssues(player); request(player); }
}, 100L, 200L);
}
@Override public void onDisable() { inflight.clear(); notices.clear(); }
private static boolean mysql(Connection connection) throws SQLException { return connection.getMetaData().getDatabaseProductName().equalsIgnoreCase("MySQL"); }
private static void identity(PreparedStatement statement, int index, UUID value, boolean mysql) throws SQLException {
if (mysql) statement.setString(index, value.toString()); else statement.setObject(index, value);
}
private Connection connect() throws Exception {
String url = core.getConfig().getString("database.jdbc-url", "");
if (!url.startsWith("jdbc:postgresql://") && !url.startsWith("jdbc:mysql://")) throw new SQLException("Private shared inventory database required");
Properties settings = new Properties();
settings.setProperty("user", core.getConfig().getString("database.username", ""));
settings.setProperty("password", core.getConfig().getString("database.password", ""));
settings.setProperty("connectTimeout", "3"); settings.setProperty("socketTimeout", "5");
settings.setProperty("ApplicationName", "DuneKits");
// The running DuneCore already contains its matching PostgreSQL driver.
Driver driver = (Driver) Class.forName(url.startsWith("jdbc:mysql://") ? "com.mysql.cj.jdbc.Driver" : "org.postgresql.Driver", true, core.getClass().getClassLoader())
.getDeclaredConstructor().newInstance();
Connection connection = driver.connect(url, settings);
if (connection == null) throw new SQLException("Private inventory connection unavailable");
return connection;
}
private void request(Player player) {
if (core == null || !core.isEnabled() || !inflight.add(player.getUniqueId())) return;
UUID buyer = player.getUniqueId();
getServer().getScheduler().runTaskAsynchronously(this, () -> {
List<UUID> pending = new ArrayList<>();
try (Connection connection = connect(); PreparedStatement q = connection.prepareStatement(
KitDeliverySQL.pending(mysql(connection)))) {
identity(q, 1, buyer, mysql(connection));
try (ResultSet rows = q.executeQuery()) { while (rows.next()) pending.add(UUID.fromString(rows.getString(1))); }
} catch (Exception ex) {
// Never log credentials, snapshot contents or private item codes.
getLogger().fine("Pending kit read unavailable: " + ex.getClass().getSimpleName());
}
if (!isEnabled()) return;
getServer().getScheduler().runTask(this, () -> {
try {
Player current = getServer().getPlayer(buyer);
if (current != null && current.isOnline()) for (UUID id : pending) if (!deliver(current, id)) break;
} finally { inflight.remove(buyer); }
});
});
}
// Older DuneCore versions accept only leather in their existing wing-upgrade command.
// Reuse that exact executor and its price/consent checks, restoring the suit on refusal.
@org.bukkit.event.EventHandler(priority=org.bukkit.event.EventPriority.HIGHEST, ignoreCancelled=true)
public void onWingCommand(org.bukkit.event.player.PlayerCommandPreprocessEvent event) {
String[] words = event.getMessage().trim().split("\\s+");
if (core == null || words.length != 2 || !words[1].equalsIgnoreCase("elytra")
|| !Set.of("/dune", "/dunecore:dune").contains(words[0].toLowerCase(Locale.ROOT))) return;
PluginCommand command = getServer().getPluginCommand("dune");
Player player = event.getPlayer(); ItemStack current = player.getInventory().getChestplate();
if (command == null || command.getPlugin() != core || current == null || current.getType() != Material.NETHERITE_CHESTPLATE
|| !"stillsuit".equals(current.getItemMeta().getPersistentDataContainer().get(new NamespacedKey("dunerealms", "item"), org.bukkit.persistence.PersistentDataType.STRING))) return;
event.setCancelled(true);
ItemStack original = current.clone(), compatible = current.clone(); compatible.setType(Material.LEATHER_CHESTPLATE);
player.getInventory().setChestplate(compatible);
try { command.execute(player, "dune", new String[]{"elytra"}); }
finally { ItemStack after = player.getInventory().getChestplate(); if (after != null && after.isSimilar(compatible)) player.getInventory().setChestplate(original); }
}
private void upgradeFactionIssues(Player player) {
if (Arrays.stream(player.getInventory().getContents()).noneMatch(FactionSuitUpgrade::candidate)) return;
try {
String faction = (String) factionOf.invoke(core, player);
transaction.invoke(core, player, (Consumer<Connection>) connection -> {
ItemStack[] inventory = player.getInventory().getContents();
for (int i = 0; i < inventory.length; i++) if (FactionSuitUpgrade.candidate(inventory[i]))
player.getInventory().setItem(i, FactionSuitUpgrade.upgrade(inventory[i], faction));
});
} catch (Exception ex) { getLogger().fine("Faction suit conversion retained for retry: " + ex.getClass().getSimpleName()); }
}
private boolean deliver(Player player, UUID id) {
final boolean[] delivered = {false};
try {
Consumer<Connection> operation = connection -> {
try (PreparedStatement q = connection.prepareStatement(
KitDeliverySQL.lock(mysql(connection)))) {
identity(q, 1, id, mysql(connection)); identity(q, 2, player.getUniqueId(), mysql(connection));
String raw, hash;
try (ResultSet rows = q.executeQuery()) {
if (!rows.next()) return;
raw = rows.getString(1); hash = rows.getString(2);
}
if (raw == null || raw.getBytes(StandardCharsets.UTF_8).length > 65536 || !digest(raw).equals(hash)) throw KitSpec.invalid();
JsonObject snapshot = JsonParser.parseString(raw).getAsJsonObject();
Map<String, ItemStack> base = factionBase(player);
List<ItemStack> items = KitItemFactory.create(snapshot, base);
if (!player.getInventory().addItem(items.toArray(ItemStack[]::new)).isEmpty())
throw new NoRoom();
try (PreparedStatement update = connection.prepareStatement(
KitDeliverySQL.acknowledge(mysql(connection)))) {
identity(update, 1, id, mysql(connection)); identity(update, 2, player.getUniqueId(), mysql(connection));
if (update.executeUpdate() != 1) throw new SQLException("Delivery changed");
}
delivered[0] = true;
} catch (Exception ex) { throw new DeliveryFailure(ex); }
};
transaction.invoke(core, player, operation);
if (delivered[0]) player.sendMessage(ChatColor.GOLD + "Your redeemed DuneRealms kit has arrived.");
return true;
} catch (Exception ex) {
Throwable cause = ex instanceof InvocationTargetException invocation ? invocation.getCause() : ex;
while (cause.getCause() != null && cause instanceof DeliveryFailure) cause = cause.getCause();
long now = System.currentTimeMillis();
if (now - notices.getOrDefault(player.getUniqueId(), 0L) > 60000) {
player.sendMessage(ChatColor.YELLOW + (cause instanceof NoRoom
? "Make room for the complete kit. Your claim is still queued."
: "Kit delivery is pending. Your claim has been retained."));
notices.put(player.getUniqueId(), now);
}
getLogger().log(Level.FINE, "Kit delivery retained: " + cause.getClass().getSimpleName());
return false;
}
}
private Map<String, ItemStack> factionBase(Player player) throws ReflectiveOperationException {
String faction = (String) factionOf.invoke(core, player);
if (faction == null || faction.isBlank()) throw KitSpec.invalid();
Object result = baseFactory.invoke(core, faction);
if (!(result instanceof List<?> items)) throw KitSpec.invalid();
Map<String, ItemStack> base = new HashMap<>();
for (Object value : items) if (value instanceof ItemStack item)
for (String slot : KitSpec.SLOTS) if (item.getType().name().endsWith("_" + slot.toUpperCase(Locale.ROOT))) base.put(slot, item);
if (base.size() != 4) throw KitSpec.invalid();
return base;
}
static String digest(String raw) throws Exception {
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(raw.getBytes(StandardCharsets.UTF_8)));
}
@Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (command.getName().equals("kitclaim")) {
if (!(sender instanceof Player player)) { sender.sendMessage("Use this command in Minecraft."); return true; }
if (core == null) player.sendMessage("Kit delivery is unavailable. Your claim is retained.");
else { request(player); player.sendMessage("Checking your redeemed kits. Keep room for the complete set."); }
return true;
}
if (!sender.hasPermission("dunekits.verify")) return true;
if (args.length != 1 || !args[0].equals("verify")) return false;
try {
int checked = KitVerification.verify();
sender.sendMessage("DUNEKITS_VERIFY_OK: " + checked + " item metadata checks; no items issued.");
} catch (Exception ex) {
sender.sendMessage("DUNEKITS_VERIFY_FAILED: " + ex.getClass().getSimpleName());
getLogger().log(Level.WARNING, "Kit metadata verification failed", ex);
}
return true;
}
private static final class NoRoom extends RuntimeException {}
private static final class DeliveryFailure extends RuntimeException { DeliveryFailure(Throwable cause) { super(cause); } }
}