From a1f648df54ff31cecddb050eeebd7abe2c694503 Mon Sep 17 00:00:00 2001 From: ELgamer Date: Mon, 5 May 2025 13:19:47 +0200 Subject: [PATCH 01/21] Working on new features: - Plot corners are now stored in Earth coordinates, rather than plot world location. - Added /plotsystem update plot set difficulty [easy|normal|hard] to change the plot difficulty after creation. - Started system for updating a plotsystem location to expand it. - Don't allow wandering traders to spawn in plotsystem worlds. --- pom.xml | 4 +- .../java/net/bteuk/plotsystem/PlotSystem.java | 8 +- .../plotsystem/commands/CreateCommand.java | 2 +- .../plotsystem/commands/DeleteCommand.java | 5 - .../commands/PlotSystemCommand.java | 3 + .../plotsystem/commands/UpdateCommand.java | 299 ++++++++++++++++++ .../plotsystem/events/TeleportEvent.java | 14 +- .../plotsystem/utils/CopyRegionFormat.java | 23 +- .../bteuk/plotsystem/utils/SelectionTool.java | 9 +- .../plotsystem/utils/plugins/Multiverse.java | 3 + src/main/resources/paper-plugin.yml | 2 +- 11 files changed, 331 insertions(+), 41 deletions(-) create mode 100644 src/main/java/net/bteuk/plotsystem/commands/UpdateCommand.java diff --git a/pom.xml b/pom.xml index 4abe401..6c04e31 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ net.bteuk PlotSystem - 1.7.0 + 1.7.1 jar PlotSystem @@ -113,7 +113,7 @@ com.github.BTEUK Network - c8a9ff8b97 + 9a08eacbd6 provided diff --git a/src/main/java/net/bteuk/plotsystem/PlotSystem.java b/src/main/java/net/bteuk/plotsystem/PlotSystem.java index 1cfb765..d23ca45 100644 --- a/src/main/java/net/bteuk/plotsystem/PlotSystem.java +++ b/src/main/java/net/bteuk/plotsystem/PlotSystem.java @@ -139,9 +139,9 @@ public void enablePlugin() { // Create list of users. users = new ArrayList<>(); - // Remove all plots 'under review' on this server. - plotSQL.update( - "UPDATE plot_data AS pd INNER JOIN location_data AS ld ON ld.name=pd.location SET pd.status='submitted' WHERE pd.status='reviewing' AND ld.server='" + SERVER_NAME + "';"); + // TODO: Ensure no plots on this server are under review or under verification. + // plotSQL.update( + // "UPDATE plot_data AS pd INNER JOIN location_data AS ld ON ld.name=pd.location SET pd.status='submitted' WHERE pd.status='reviewing' AND ld.server='" + SERVER_NAME + "';"); // Create gui item gui = new ItemStack(Material.NETHER_STAR); @@ -188,7 +188,7 @@ public void enablePlugin() { // Get all active plots (unclaimed, claimed, submitted, reviewing) and add holograms. List active_plots = plotSQL.getIntList( - "SELECT pd.id FROM plot_data AS pd INNER JOIN location_data AS ld ON ld.name=pd.location WHERE pd.status IN ('unclaimed','claimed','submitted','reviewing') AND " + + "SELECT pd.id FROM plot_data AS pd INNER JOIN location_data AS ld ON ld.name=pd.location WHERE pd.status IN ('unclaimed','claimed','submitted') AND " + "ld.server='" + SERVER_NAME + "';"); active_plots.forEach(plot -> PlotHelper.addPlotHologram(new PlotHologram(plot))); } diff --git a/src/main/java/net/bteuk/plotsystem/commands/CreateCommand.java b/src/main/java/net/bteuk/plotsystem/commands/CreateCommand.java index 3b0f4c8..f252708 100644 --- a/src/main/java/net/bteuk/plotsystem/commands/CreateCommand.java +++ b/src/main/java/net/bteuk/plotsystem/commands/CreateCommand.java @@ -260,7 +260,7 @@ private void createLocation(CommandSender sender, String[] args) { Bukkit.getScheduler().runTaskAsynchronously(PlotSystem.getInstance(), () -> { - if (!WorldEditor.largeCopy(regionFormat.minPoint, regionFormat.maxPoint, regionFormat.pasteMinPoint, copy, paste)) { + if (!WorldEditor.largeCopy(regionFormat.minPoint(), regionFormat.maxPoint(), regionFormat.pasteMinPoint(), copy, paste)) { sender.sendMessage(ChatUtils.error("An error occured while transferring the terrain.")); } else { regions.remove(regionFormat); diff --git a/src/main/java/net/bteuk/plotsystem/commands/DeleteCommand.java b/src/main/java/net/bteuk/plotsystem/commands/DeleteCommand.java index 405123b..2d7a46b 100644 --- a/src/main/java/net/bteuk/plotsystem/commands/DeleteCommand.java +++ b/src/main/java/net/bteuk/plotsystem/commands/DeleteCommand.java @@ -27,10 +27,8 @@ public class DeleteCommand { private final PlotSQL plotSQL; public DeleteCommand(GlobalSQL globalSQL, PlotSQL plotSQL) { - this.globalSQL = globalSQL; this.plotSQL = plotSQL; - } public void delete(CommandSender sender, String[] args) { @@ -63,7 +61,6 @@ public void delete(CommandSender sender, String[] args) { sender.sendMessage(ChatUtils.error("/plotsystem delete [plot, location, zone]")); } - } private void deletePlot(CommandSender sender, String[] args) { @@ -167,12 +164,10 @@ private void deleteLocation(CommandSender sender, String[] args) { // If sender is a player, check for permission. if (sender instanceof Player p) { - if (!(p.hasPermission("uknet.plots.delete.location"))) { p.sendMessage(ChatUtils.error("You do not have permission to use this command.")); return; } - } // Check arg count. diff --git a/src/main/java/net/bteuk/plotsystem/commands/PlotSystemCommand.java b/src/main/java/net/bteuk/plotsystem/commands/PlotSystemCommand.java index bbf3df9..4ffdf0c 100644 --- a/src/main/java/net/bteuk/plotsystem/commands/PlotSystemCommand.java +++ b/src/main/java/net/bteuk/plotsystem/commands/PlotSystemCommand.java @@ -54,6 +54,9 @@ public void execute(CommandSourceStack stack, String[] args) { DeleteCommand deleteCommand = new DeleteCommand(globalSQL, plotSQL); deleteCommand.delete(sender, args); } + case "update" -> { + UpdateCommand.update(sender, args); + } case "help" -> help(sender); case "setalias" -> { diff --git a/src/main/java/net/bteuk/plotsystem/commands/UpdateCommand.java b/src/main/java/net/bteuk/plotsystem/commands/UpdateCommand.java new file mode 100644 index 0000000..7bcc23a --- /dev/null +++ b/src/main/java/net/bteuk/plotsystem/commands/UpdateCommand.java @@ -0,0 +1,299 @@ +package net.bteuk.plotsystem.commands; + +import com.sk89q.worldedit.math.BlockVector3; +import net.bteuk.network.Network; +import net.bteuk.network.lib.enums.PlotDifficulties; +import net.bteuk.network.lib.utils.ChatUtils; +import net.bteuk.network.sql.GlobalSQL; +import net.bteuk.network.sql.PlotSQL; +import net.bteuk.plotsystem.PlotSystem; +import net.bteuk.plotsystem.utils.CopyRegionFormat; +import net.bteuk.plotsystem.utils.plugins.WorldEditor; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.NamedTextColor; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; + +import static java.lang.Math.max; +import static java.lang.Math.min; +import static net.bteuk.network.utils.Constants.MAX_Y; +import static net.bteuk.network.utils.Constants.MIN_Y; +import static net.bteuk.plotsystem.PlotSystem.LOGGER; + +public class UpdateCommand { + + private static final Component GENERIC_ERROR_MESSAGE = ChatUtils.error("/plotsystem update [plot, location]"); + + private static final Component PLOT_ERROR_MESSAGE = ChatUtils.error("/plotsystem update plot set difficulty [easy|normal|hard]"); + + public static void update(CommandSender sender, String[] args) { + + if (args.length < 2) { + sender.sendMessage(GENERIC_ERROR_MESSAGE); + return; + } + + switch (args[1]) { + case "plot" -> updatePlot(sender, args); + case "location" -> updateLocation(sender, args); + default -> sender.sendMessage(GENERIC_ERROR_MESSAGE); + } + } + + private static void updatePlot(CommandSender sender, String[] args) { + // Check if the sender is a player. + // If so, check if they have permission. + if (sender instanceof Player p) { + if (!p.hasPermission("uknet.plots.update.plot")) { + p.sendMessage(ChatUtils.error("You do not have permission to use this command!")); + return; + } + } + + // Check if they have enough args and that the correct args have been given. + if (args.length < 6 || !args[3].equalsIgnoreCase("set") || !args[4].equalsIgnoreCase("difficulty")) { + sender.sendMessage(PLOT_ERROR_MESSAGE); + return; + } + + int plotID; + try { + plotID = Integer.parseInt(args[2]); + } catch (NumberFormatException e) { + sender.sendMessage(PLOT_ERROR_MESSAGE); + return; + } + + // Check if a valid difficulty was selected. + PlotDifficulties plotDifficulty; + try { + plotDifficulty = PlotDifficulties.valueOf(args[5].toUpperCase()); + } catch (IllegalArgumentException e) { + sender.sendMessage(PLOT_ERROR_MESSAGE); + return; + } + + PlotSQL plotSQL = Network.getInstance().getPlotSQL(); + + // Check if plot exists. + if (!plotSQL.hasRow("SELECT id FROM plot_data WHERE id=" + plotID + " AND status IN ('unclaimed','claimed','submitted');")) { + sender.sendMessage(ChatUtils.error("Plot %s does not exist.", args[2])); + return; + } + + // Update the plot difficulty. + plotSQL.update("UPDATE plot_data SET difficulty=" + plotDifficulty.getValue() + " WHERE id=" + plotID + ";"); + sender.sendMessage(ChatUtils.success("Updated difficulty of plot %s to %s.", args[2], args[5])); + } + + private static void updateLocation(CommandSender sender, String[] args) { + + // Check if the sender is a player. + // If so, check if they have permission. + if (sender instanceof Player p) { + if (!p.hasPermission("uknet.plots.update.location")) { + p.sendMessage(ChatUtils.error("You do not have permission to use this command!")); + return; + } + } + + // Check if they have enough args. + if (args.length < 9) { + sender.sendMessage(ChatUtils.error("/plotsystem update location [name] ")); + return; + } + + int xmin; + int ymin; + int zmin; + + int xmax; + int ymax; + int zmax; + + // Check if the coordinates are actual numbers. + try { + + xmin = Integer.parseInt(args[3]); + ymin = Integer.parseInt(args[4]); + zmin = Integer.parseInt(args[5]); + + xmax = Integer.parseInt(args[6]); + ymax = Integer.parseInt(args[7]); + zmax = Integer.parseInt(args[8]); + + } catch (NumberFormatException e) { + + sender.sendMessage(ChatUtils.error("/plotsystem update location [name] ")); + return; + + } + + PlotSQL plotSQL = Network.getInstance().getPlotSQL(); + + // Check if the location name exists. + if (!plotSQL.hasRow("SELECT name FROM location_data WHERE name='" + args[2] + "';")) { + sender.sendMessage(ChatUtils.error("Location %s does not exist.", args[2])); + return; + } + + // Get the exact regions of the selected coordinates. + int regionXMin = Math.floorDiv(xmin, 512); + int regionZMin = Math.floorDiv(zmin, 512); + + int regionXMax = Math.floorDiv(xmax, 512); + int regionZMax = Math.floorDiv(zmax, 512); + + // TODO: Calculate the coordinate transformation. + int xTransform = -(regionXMin * 512); + int zTransform = -(regionZMin * 512); + + // Get the worlds. + String saveWorld = PlotSystem.getInstance().getConfig().getString("save_world"); + if (saveWorld == null) { + sender.sendMessage(ChatUtils.error("The save world is not set in config.")); + return; + } + + // Get worlds. + World copy = Bukkit.getWorld(saveWorld); + World paste = Bukkit.getWorld(args[2]); + + // Check that the worlds are not null, else delete the Multiverse world. + if (copy == null || paste == null) { + sender.sendMessage("An error occurred, please contact an admin."); + return; + } + + // Determine which regions are new, only copy them. + List existingRegions = plotSQL.getStringList("SELECT region FROM regions WHERE location='" + args[2] + "';"); + List regionsToAdd = new ArrayList<>(); + + for (int i = regionXMin; i <= regionXMax; i++) { + for (int j = regionZMin; j <= regionZMax; j++) { + String region = String.format("%d,%d", i, j); + if (!existingRegions.contains(region)) { + regionsToAdd.add(new Region(region, i, j)); + } + } + } + + // Copy paste the regions in the save world. + // Iterate through the regions one-by-one. + // Run it asynchronously to not freeze the server. + sender.sendMessage(ChatUtils.success("Transferring terrain, this may take a while.")); + sender.sendMessage(ChatUtils.success("Please don't leave this server while this is in progress.")); + + // Create atomic boolean to query whether a region can be copied. + AtomicBoolean isReady = new AtomicBoolean(true); + + // Create a list of regions to copy paste. + ArrayList regions = new ArrayList<>(); + + final int yMin = max(ymin, MIN_Y); + final int yMax = min(ymax, MAX_Y - 1); + + for (Region region : regionsToAdd) { + // Split the region into 4 equal segments of 256x256. + regions.add(new CopyRegionFormat(copy, paste, BlockVector3.at(region.regionX() * 512, yMin, region.regionZ() * 512), + BlockVector3.at(region.regionX() * 512 + 255, yMax, region.regionZ() * 512 + 255), + BlockVector3.at(region.regionX() * 512 + xTransform, yMin, region.regionZ() * 512 + zTransform))); + + regions.add(new CopyRegionFormat(copy, paste, BlockVector3.at(region.regionX() * 512 + 256, yMin, region.regionZ() * 512), + BlockVector3.at(region.regionX() * 512 + 511, yMax, region.regionZ() * 512 + 255), + BlockVector3.at(region.regionX() * 512 + 256 + xTransform, yMin, region.regionZ() * 512 + zTransform))); + + regions.add(new CopyRegionFormat(copy, paste, BlockVector3.at(region.regionX() * 512, yMin, region.regionZ() * 512 + 256), + BlockVector3.at(region.regionX() * 512 + 255, yMax, region.regionZ() * 512 + 511), + BlockVector3.at(region.regionX() * 512 + xTransform, yMin, region.regionZ() * 512 + 256 + zTransform))); + + regions.add(new CopyRegionFormat(copy, paste, BlockVector3.at(region.regionX() * 512 + 256, yMin, region.regionZ() * 512 + 256), + BlockVector3.at(region.regionX() * 512 + 511, yMax, region.regionZ() * 512 + 511), + BlockVector3.at(region.regionX() * 512 + 256 + xTransform, yMin, region.regionZ() * 512 + 256 + zTransform))); + } + + LOGGER.info("Add segments to list, there are " + regions.size()); + sender.sendMessage(ChatUtils.success("Added " + regions.size() + " segments of 256x256 to the list to be copied.")); + + // Iterate until all regions are done. + Bukkit.getScheduler().runTaskAsynchronously(PlotSystem.getInstance(), () -> { + + while (!regions.isEmpty()) { + + if (isReady.get()) { + + // Set isReady to false so the loop will wait until the previous copy-paste is done. + isReady.set(false); + + CopyRegionFormat regionFormat = regions.getFirst(); + + Bukkit.getScheduler().runTaskAsynchronously(PlotSystem.getInstance(), () -> { + + if (!WorldEditor.largeCopy(regionFormat.minPoint(), regionFormat.maxPoint(), regionFormat.pasteMinPoint(), copy, paste)) { + sender.sendMessage(ChatUtils.error("An error occured while transferring the terrain.")); + } else { + regions.remove(regionFormat); + sender.sendMessage(ChatUtils.success("Segment copied, there are ").append(Component.text(regions.size(), NamedTextColor.DARK_AQUA)) + .append(ChatUtils.success(" remaining."))); + LOGGER.info("Segment copied, there are " + regions.size() + " remaining."); + isReady.set(true); + } + + }); + } + } + + GlobalSQL globalSQL = Network.getInstance().getGlobalSQL(); + + sender.sendMessage(ChatUtils.success("Terrain transfer has been completed.")); + + // TODO: Update the previous coordinates for the location. + // TODO: Add the regions to the database. + // TODO: Add the regions to the region database. + + int coordMin = globalSQL.addCoordinate(new Location(Bukkit.getWorld(args[2]), (regionXMin * 512), MIN_Y, (regionZMin * 512), 0, 0)); + + int coordMax = globalSQL.addCoordinate(new Location(Bukkit.getWorld(args[2]), ((regionXMax * 512) + 511), MAX_Y - 1, ((regionZMax * 512) + 511), 0, 0)); + + // Add the location to the database. + if (plotSQL.update( + "INSERT INTO location_data(name, alias, server, coordMin, coordMax, xTransform, zTransform) VALUES('" + args[2] + "','" + args[2] + "','" + PlotSystem.SERVER_NAME + "'," + coordMin + "," + coordMax + "," + xTransform + "," + zTransform + ");")) { + + sender.sendMessage(ChatUtils.success("Created new location ").append(Component.text(args[2], NamedTextColor.DARK_AQUA))); + + // Set the status of all effected regions in the region database. + for (int i = regionXMin; i <= regionXMax; i++) { + for (int j = regionZMin; j <= regionZMax; j++) { + + String region = i + "," + j; + + // Change region status in region database. + // If it already exists remove members. + globalSQL.update("INSERT INTO server_events(uuid,type,server,event) VALUES(NULL,'network','" + globalSQL.getString( + "SELECT name FROM server_data WHERE type='EARTH';") + "'," + "'region set plotsystem " + region + "');"); + + // Add region to database. + plotSQL.update("INSERT INTO regions(region,server,location) VALUES('" + region + "','" + PlotSystem.SERVER_NAME + "','" + args[2] + "');"); + + } + } + + } else { + + sender.sendMessage(ChatUtils.error("An error occurred, please check the console for more info.")); + LOGGER.warning("An error occured while adding new location!"); + + } + }); + } + + private record Region(String name, int regionX, int regionZ) { + } +} diff --git a/src/main/java/net/bteuk/plotsystem/events/TeleportEvent.java b/src/main/java/net/bteuk/plotsystem/events/TeleportEvent.java index fbb6200..03958bc 100644 --- a/src/main/java/net/bteuk/plotsystem/events/TeleportEvent.java +++ b/src/main/java/net/bteuk/plotsystem/events/TeleportEvent.java @@ -11,6 +11,7 @@ import net.bteuk.plotsystem.exceptions.RegionNotFoundException; import net.bteuk.plotsystem.utils.User; import net.bteuk.plotsystem.utils.plugins.WorldGuardFunctions; +import org.apache.commons.lang3.StringUtils; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.World; @@ -50,11 +51,16 @@ public static void event(String uuid, String[] event) { // If the plot is on the current server teleport them directly. // Else teleport them to the correct server and them teleport them to the plot. - if (server.equals(SERVER_NAME)) { + if (StringUtils.equals(server, SERVER_NAME)) { // Get world of plot. World world = Bukkit.getWorld(u.plotSQL.getString("SELECT location FROM plot_data WHERE id=" + id + ";")); + if (world == null) { + u.player.sendMessage(ChatUtils.error("An error occurred while teleporting to plot %s", String.valueOf(id))); + return; + } + // Get the plot status PlotStatus status = PlotStatus.fromDatabaseValue(u.plotSQL.getString("SELECT status FROM plot_data WHERE id=" + id + ";")); if (status == PlotStatus.COMPLETED) { @@ -72,6 +78,11 @@ public static void event(String uuid, String[] event) { } double x = sumX / (double) corners.length; double z = sumZ / (double) corners.length; + + // Add the coordinate transform to find the location in the build world. + x += u.plotSQL.getInt("SELECT xTransform FROM location_data WHERE name='" + world.getName() + "';"); + z += u.plotSQL.getInt("SELECT zTransform FROM location_data WHERE name='" + world.getName() + "';"); + Location l = new Location(world, x, Utils.getHighestYAt(world, (int) x, (int) z), z); PaperLib.teleportAsync(u.player, l); } else { @@ -146,5 +157,4 @@ public static void event(String uuid, String[] event) { } } - } diff --git a/src/main/java/net/bteuk/plotsystem/utils/CopyRegionFormat.java b/src/main/java/net/bteuk/plotsystem/utils/CopyRegionFormat.java index 719666e..5ac423a 100644 --- a/src/main/java/net/bteuk/plotsystem/utils/CopyRegionFormat.java +++ b/src/main/java/net/bteuk/plotsystem/utils/CopyRegionFormat.java @@ -3,25 +3,4 @@ import com.sk89q.worldedit.math.BlockVector3; import org.bukkit.World; -public class CopyRegionFormat { - - public final World copyWorld; - public final World pasteWorld; - - public final BlockVector3 minPoint; - public final BlockVector3 maxPoint; - - public final BlockVector3 pasteMinPoint; - - public CopyRegionFormat(World copyWorld, World pasteWorld, BlockVector3 minPoint, BlockVector3 maxPoint, BlockVector3 pasteMinPoint) { - - this.copyWorld = copyWorld; - this.pasteWorld = pasteWorld; - - this.minPoint = minPoint; - this.maxPoint = maxPoint; - - this.pasteMinPoint = pasteMinPoint; - - } -} +public record CopyRegionFormat(World copyWorld, World pasteWorld, BlockVector3 minPoint, BlockVector3 maxPoint, BlockVector3 pasteMinPoint) {} diff --git a/src/main/java/net/bteuk/plotsystem/utils/SelectionTool.java b/src/main/java/net/bteuk/plotsystem/utils/SelectionTool.java index 08cdb46..4a64d43 100644 --- a/src/main/java/net/bteuk/plotsystem/utils/SelectionTool.java +++ b/src/main/java/net/bteuk/plotsystem/utils/SelectionTool.java @@ -252,14 +252,15 @@ public void createPlot() { // Create the plot. if (createPlot(u.player, world, location, vector, plotSQL, size, difficulty)) { - // Store plot bounds. + int xTransform = plotSQL.getInt("SELECT xTransform FROM location_data WHERE name='" + location + "';"); + int zTransform = plotSQL.getInt("SELECT zTransform FROM location_data WHERE name='" + location + "';"); + + // Store the plot corners with coordinate transform. int i = 1; for (BlockVector2 point : vector) { - plotSQL.update("INSERT INTO plot_corners(id,corner,x,z) VALUES(" + - plotID + "," + i + "," + point.getX() + "," + point.getZ() + ");"); + plotID + "," + i + "," + (point.getX() - xTransform) + "," + (point.getZ() - zTransform) + ");"); i++; - } // Send feedback. diff --git a/src/main/java/net/bteuk/plotsystem/utils/plugins/Multiverse.java b/src/main/java/net/bteuk/plotsystem/utils/plugins/Multiverse.java index a5ce15e..95ffebc 100644 --- a/src/main/java/net/bteuk/plotsystem/utils/plugins/Multiverse.java +++ b/src/main/java/net/bteuk/plotsystem/utils/plugins/Multiverse.java @@ -72,6 +72,9 @@ public static boolean createVoidWorld(String name) { // Disable random tick. world.setGameRule(GameRule.RANDOM_TICK_SPEED, 0); + // Disable wandering traders. + world.setGameRule(GameRule.DO_TRADER_SPAWNING, false); + // Get worldguard. WorldGuard wg = WorldGuard.getInstance(); RegionManager regions = wg.getPlatform().getRegionContainer().get(BukkitAdapter.adapt(world)); diff --git a/src/main/resources/paper-plugin.yml b/src/main/resources/paper-plugin.yml index a017cda..0706d5c 100644 --- a/src/main/resources/paper-plugin.yml +++ b/src/main/resources/paper-plugin.yml @@ -1,7 +1,7 @@ name: PlotSystem version: '${project.version}' main: net.bteuk.plotsystem.PlotSystem -api-version: '1.21.1' +api-version: '1.21.4' dependencies: server: From f4d2c058de4d4800e120b9d3abd9be6423207bbe Mon Sep 17 00:00:00 2001 From: ELgamer Date: Sat, 10 May 2025 13:09:36 +0200 Subject: [PATCH 02/21] Added /plotsystem update location [name] to update an existing location with new regions. --- .../plotsystem/commands/UpdateCommand.java | 53 ++++++------------- 1 file changed, 17 insertions(+), 36 deletions(-) diff --git a/src/main/java/net/bteuk/plotsystem/commands/UpdateCommand.java b/src/main/java/net/bteuk/plotsystem/commands/UpdateCommand.java index 7bcc23a..42c00b8 100644 --- a/src/main/java/net/bteuk/plotsystem/commands/UpdateCommand.java +++ b/src/main/java/net/bteuk/plotsystem/commands/UpdateCommand.java @@ -151,9 +151,9 @@ private static void updateLocation(CommandSender sender, String[] args) { int regionXMax = Math.floorDiv(xmax, 512); int regionZMax = Math.floorDiv(zmax, 512); - // TODO: Calculate the coordinate transformation. - int xTransform = -(regionXMin * 512); - int zTransform = -(regionZMin * 512); + // Get the coordinate transformation of the location. + int xTransform = plotSQL.getInt("SELECT xTransform FROM location_data WHERE name='" + args[2] + "';"); + int zTransform = plotSQL.getInt("SELECT zTransform FROM location_data WHERE name='" + args[2] + "';"); // Get the worlds. String saveWorld = PlotSystem.getInstance().getConfig().getString("save_world"); @@ -254,43 +254,24 @@ private static void updateLocation(CommandSender sender, String[] args) { sender.sendMessage(ChatUtils.success("Terrain transfer has been completed.")); - // TODO: Update the previous coordinates for the location. - // TODO: Add the regions to the database. - // TODO: Add the regions to the region database. + int minCoordinateId = globalSQL.getInt("SELECT coordMin FROM location_data WHERE name='" + args[2] + "';"); + int maxCoordinateId = globalSQL.getInt("SELECT coordMax FROM location_data WHERE name='" + args[2] + "';"); - int coordMin = globalSQL.addCoordinate(new Location(Bukkit.getWorld(args[2]), (regionXMin * 512), MIN_Y, (regionZMin * 512), 0, 0)); - - int coordMax = globalSQL.addCoordinate(new Location(Bukkit.getWorld(args[2]), ((regionXMax * 512) + 511), MAX_Y - 1, ((regionZMax * 512) + 511), 0, 0)); + globalSQL.updateCoordinate(minCoordinateId, new Location(Bukkit.getWorld(args[2]), (regionXMin * 512), MIN_Y, (regionZMin * 512), 0, 0)); + globalSQL.updateCoordinate(maxCoordinateId, new Location(Bukkit.getWorld(args[2]), ((regionXMax * 512) + 511), MAX_Y - 1, ((regionZMax * 512) + 511), 0, 0)); // Add the location to the database. - if (plotSQL.update( - "INSERT INTO location_data(name, alias, server, coordMin, coordMax, xTransform, zTransform) VALUES('" + args[2] + "','" + args[2] + "','" + PlotSystem.SERVER_NAME + "'," + coordMin + "," + coordMax + "," + xTransform + "," + zTransform + ");")) { - - sender.sendMessage(ChatUtils.success("Created new location ").append(Component.text(args[2], NamedTextColor.DARK_AQUA))); - - // Set the status of all effected regions in the region database. - for (int i = regionXMin; i <= regionXMax; i++) { - for (int j = regionZMin; j <= regionZMax; j++) { - - String region = i + "," + j; - - // Change region status in region database. - // If it already exists remove members. - globalSQL.update("INSERT INTO server_events(uuid,type,server,event) VALUES(NULL,'network','" + globalSQL.getString( - "SELECT name FROM server_data WHERE type='EARTH';") + "'," + "'region set plotsystem " + region + "');"); - - // Add region to database. - plotSQL.update("INSERT INTO regions(region,server,location) VALUES('" + region + "','" + PlotSystem.SERVER_NAME + "','" + args[2] + "');"); - - } - } - - } else { - - sender.sendMessage(ChatUtils.error("An error occurred, please check the console for more info.")); - LOGGER.warning("An error occured while adding new location!"); - + for (Region region : regionsToAdd) { + // Change region status in region database. + // If it already exists remove members. + globalSQL.update("INSERT INTO server_events(uuid,type,server,event) VALUES(NULL,'network','" + globalSQL.getString( + "SELECT name FROM server_data WHERE type='EARTH';") + "'," + "'region set plotsystem " + region.name() + "');"); + + // Add region to database. + plotSQL.update("INSERT INTO regions(region,server,location) VALUES('" + region.name() + "','" + PlotSystem.SERVER_NAME + "','" + args[2] + "');"); } + + sender.sendMessage(ChatUtils.success("Update location %s", args[2])); }); } From 24ce4543527aa1c743ec76ea70b7bca2840829bb Mon Sep 17 00:00:00 2001 From: ELgamer Date: Sat, 10 May 2025 13:53:36 +0200 Subject: [PATCH 03/21] Record create and update location to share part of the code as it uses mostly the same mechanism. --- .../plotsystem/commands/CreateCommand.java | 284 +------------ .../plotsystem/commands/LocationCommand.java | 397 ++++++++++++++++++ .../commands/PlotSystemCommand.java | 9 +- .../plotsystem/commands/UpdateCommand.java | 212 +--------- 4 files changed, 414 insertions(+), 488 deletions(-) create mode 100644 src/main/java/net/bteuk/plotsystem/commands/LocationCommand.java diff --git a/src/main/java/net/bteuk/plotsystem/commands/CreateCommand.java b/src/main/java/net/bteuk/plotsystem/commands/CreateCommand.java index f252708..be98b04 100644 --- a/src/main/java/net/bteuk/plotsystem/commands/CreateCommand.java +++ b/src/main/java/net/bteuk/plotsystem/commands/CreateCommand.java @@ -1,49 +1,23 @@ package net.bteuk.plotsystem.commands; -import com.sk89q.worldedit.math.BlockVector3; import net.bteuk.network.Network; -import net.bteuk.network.eventing.events.EventManager; import net.bteuk.network.lib.utils.ChatUtils; -import net.bteuk.network.sql.GlobalSQL; import net.bteuk.network.sql.PlotSQL; import net.bteuk.network.utils.NetworkUser; import net.bteuk.plotsystem.PlotSystem; import net.bteuk.plotsystem.gui.CreatePlotGui; import net.bteuk.plotsystem.gui.CreateZoneGui; -import net.bteuk.plotsystem.utils.CopyRegionFormat; import net.bteuk.plotsystem.utils.User; -import net.bteuk.plotsystem.utils.plugins.Multiverse; -import net.bteuk.plotsystem.utils.plugins.WorldEditor; -import net.kyori.adventure.text.Component; -import net.kyori.adventure.text.format.NamedTextColor; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.World; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import java.util.ArrayList; -import java.util.concurrent.atomic.AtomicBoolean; - -import static java.lang.Math.max; -import static java.lang.Math.min; -import static net.bteuk.network.utils.Constants.MAX_Y; -import static net.bteuk.network.utils.Constants.MIN_Y; -import static net.bteuk.plotsystem.PlotSystem.LOGGER; - -public class CreateCommand { - - private final GlobalSQL globalSQL; - private final PlotSQL plotSQL; - - public CreateCommand(GlobalSQL globalSQL, PlotSQL plotSQL) { - - this.globalSQL = globalSQL; - this.plotSQL = plotSQL; +public final class CreateCommand { + private CreateCommand() { + // Do nothing } - public void create(CommandSender sender, String[] args) { + public static void create(CommandSender sender, String[] args) { if (args.length < 2) { @@ -54,14 +28,14 @@ public void create(CommandSender sender, String[] args) { switch (args[1]) { case "plot" -> createPlot(sender); - case "location" -> createLocation(sender, args); + case "location" -> LocationCommand.createLocation(sender, args); case "zone" -> createZone(sender); default -> sender.sendMessage(ChatUtils.error("/plotsystem create [plot, location, zone]")); } } - private void createPlot(CommandSender sender) { + private static void createPlot(CommandSender sender) { // Check if the sender is a player if (!(sender instanceof Player)) { @@ -104,249 +78,7 @@ private void createPlot(CommandSender sender) { } - private void createLocation(CommandSender sender, String[] args) { - - // Check if the sender is a player. - // If so, check if they have permission. - if (sender instanceof Player p) { - if (!p.hasPermission("uknet.plots.create.location")) { - - p.sendMessage(ChatUtils.error("You do not have permission to use this command!")); - return; - - } - } - - // Check if they have enough args. - if (args.length < 9) { - - sender.sendMessage(ChatUtils.error("/plotsystem create location [name] ")); - return; - - } - - int xmin; - int ymin; - int zmin; - - int xmax; - int ymax; - int zmax; - - // Check if the coordinates are actual numbers. - try { - - xmin = Integer.parseInt(args[3]); - ymin = Integer.parseInt(args[4]); - zmin = Integer.parseInt(args[5]); - - xmax = Integer.parseInt(args[6]); - ymax = Integer.parseInt(args[7]); - zmax = Integer.parseInt(args[8]); - - } catch (NumberFormatException e) { - - sender.sendMessage(ChatUtils.error("/plotsystem create location [name] ")); - return; - - } - - // Check if the location name is unique. - if (plotSQL.hasRow("SELECT name FROM location_data WHERE name='" + args[2] + "';")) { - - sender.sendMessage(ChatUtils.error("The location ") - .append(Component.text(args[2], NamedTextColor.DARK_RED)) - .append(ChatUtils.error(" already exists."))); - return; - - } - - // Get the exact regions of the selected coordinates. - int regionXMin = Math.floorDiv(xmin, 512); - int regionZMin = Math.floorDiv(zmin, 512); - - int regionXMax = Math.floorDiv(xmax, 512); - int regionZMax = Math.floorDiv(zmax, 512); - - // Calculate the coordinate transformation. - int xTransform = -(regionXMin * 512); - int zTransform = -(regionZMin * 512); - - // Create the world and add the regions. - Multiverse.createVoidWorld(args[2]); - - String saveWorld = PlotSystem.getInstance().getConfig().getString("save_world"); - - if (saveWorld == null) { - sender.sendMessage(ChatUtils.error("The save world is not set in config.")); - return; - } - - // Get worlds. - World copy = Bukkit.getWorld(saveWorld); - World paste = Bukkit.getWorld(args[2]); - - // Check that the worlds are not null, else delete the Multiverse world. - if (copy == null || paste == null) { - - sender.sendMessage("An error occurred, please contact an admin."); - Multiverse.deleteWorld(args[2]); - return; - - } - - // Copy paste the regions in the save world. - // Iterate through the regions one-by-one. - // Run it asynchronously to not freeze the server. - sender.sendMessage(ChatUtils.success("Transferring terrain, this may take a while.")); - - // Create atomic boolean to query whether a region can be copied. - AtomicBoolean isReady = new AtomicBoolean(true); - - // Create a list of regions to copy paste. - ArrayList regions = new ArrayList<>(); - - final int yMin = max(ymin, MIN_Y); - final int yMax = min(ymax, MAX_Y - 1); - - for (int i = regionXMin; i <= regionXMax; i++) { - for (int j = regionZMin; j <= regionZMax; j++) { - - // Split the region into 4 equal segments of 256x256. - regions.add(new CopyRegionFormat( - copy, paste, - BlockVector3.at(i * 512, yMin, j * 512), - BlockVector3.at(i * 512 + 255, yMax, j * 512 + 255), - BlockVector3.at(i * 512 + xTransform, yMin, j * 512 + zTransform)) - ); - - regions.add(new CopyRegionFormat( - copy, paste, - BlockVector3.at(i * 512 + 256, yMin, j * 512), - BlockVector3.at(i * 512 + 511, yMax, j * 512 + 255), - BlockVector3.at(i * 512 + 256 + xTransform, yMin, j * 512 + zTransform)) - ); - - regions.add(new CopyRegionFormat( - copy, paste, - BlockVector3.at(i * 512, yMin, j * 512 + 256), - BlockVector3.at(i * 512 + 255, yMax, j * 512 + 511), - BlockVector3.at(i * 512 + xTransform, yMin, j * 512 + 256 + zTransform)) - ); - - regions.add(new CopyRegionFormat( - copy, paste, - BlockVector3.at(i * 512 + 256, yMin, j * 512 + 256), - BlockVector3.at(i * 512 + 511, yMax, j * 512 + 511), - BlockVector3.at(i * 512 + 256 + xTransform, yMin, j * 512 + 256 + zTransform)) - ); - } - } - - LOGGER.info("Add segments to list, there are " + regions.size()); - sender.sendMessage(ChatUtils.success("Added " + regions.size() + " segments of 256x256 to the list to be copied.")); - - // Iterate until all regions are done. - Bukkit.getScheduler().runTaskAsynchronously(PlotSystem.getInstance(), () -> { - - while (!regions.isEmpty()) { - - if (isReady.get()) { - - // Set isReady to false so the loop will wait until the previous copy-paste is done. - isReady.set(false); - - CopyRegionFormat regionFormat = regions.getFirst(); - - Bukkit.getScheduler().runTaskAsynchronously(PlotSystem.getInstance(), () -> { - - if (!WorldEditor.largeCopy(regionFormat.minPoint(), regionFormat.maxPoint(), regionFormat.pasteMinPoint(), copy, paste)) { - sender.sendMessage(ChatUtils.error("An error occured while transferring the terrain.")); - } else { - regions.remove(regionFormat); - sender.sendMessage(ChatUtils.success("Segment copied, there are ") - .append(Component.text(regions.size(), NamedTextColor.DARK_AQUA)) - .append(ChatUtils.success(" remaining."))); - LOGGER.info("Segment copied, there are " + regions.size() + " remaining."); - isReady.set(true); - } - - }); - } - } - - sender.sendMessage(ChatUtils.success("Terrain transfer has been completed.")); - - int coordMin = globalSQL.addCoordinate(new Location( - Bukkit.getWorld(args[2]), - (regionXMin * 512), MIN_Y, (regionZMin * 512), 0, 0)); - - int coordMax = globalSQL.addCoordinate(new Location( - Bukkit.getWorld(args[2]), - ((regionXMax * 512) + 511), MAX_Y - 1, ((regionZMax * 512) + 511), 0, 0)); - - // Add the location to the database. - if (plotSQL.update("INSERT INTO location_data(name, alias, server, coordMin, coordMax, xTransform, zTransform) VALUES('" - + args[2] + "','" + args[2] + "','" + PlotSystem.SERVER_NAME + "'," + coordMin + "," + coordMax + "," + xTransform + "," + zTransform + ");")) { - - sender.sendMessage(ChatUtils.success("Created new location ") - .append(Component.text(args[2], NamedTextColor.DARK_AQUA))); - - // Set the status of all effected regions in the region database. - for (int i = regionXMin; i <= regionXMax; i++) { - for (int j = regionZMin; j <= regionZMax; j++) { - - String region = i + "," + j; - - // Change region status in region database. - // If it already exists remove members. - globalSQL.update("INSERT INTO server_events(uuid,type,server,event) VALUES(NULL,'network','" - + globalSQL.getString("SELECT name FROM server_data WHERE type='EARTH';") + "'," + - "'region set plotsystem " + region + "');"); - - // Add region to database. - plotSQL.update("INSERT INTO regions(region,server,location) VALUES('" + region + "','" + PlotSystem.SERVER_NAME + "','" + args[2] + "');"); - - } - } - - } else { - - sender.sendMessage(ChatUtils.error("An error occurred, please check the console for more info.")); - LOGGER.warning("An error occured while adding new location!"); - - } - - // If sender is a player teleport them to the location. - if (sender instanceof Player p) { - - // Get middle. - double x = ((globalSQL.getDouble("SELECT x FROM coordinates WHERE id=" + coordMax + ";") + - globalSQL.getDouble("SELECT x FROM coordinates WHERE id=" + coordMin + ";")) / 2) + - plotSQL.getInt("SELECT xTransform FROM location_data WHERE name='" + args[2] + "';"); - - double z = ((globalSQL.getDouble("SELECT z FROM coordinates WHERE id=" + coordMax + ";") + - globalSQL.getDouble("SELECT z FROM coordinates WHERE id=" + coordMin + ";")) / 2) + - plotSQL.getInt("SELECT zTransform FROM location_data WHERE name='" + args[2] + "';"); - - // Teleport to the location. - World world = Bukkit.getWorld(args[2]); - - double y = 64; - if (world != null) { - y = world.getHighestBlockYAt((int) x, (int) z); - y++; - } - - EventManager.createTeleportEvent(false, p.getUniqueId().toString(), "network", "teleport " + args[2] + " " + x + " " + y + " " + z + " " - + p.getLocation().getYaw() + " " + p.getLocation().getPitch(), - "&aTeleported to location &3" + plotSQL.getString("SELECT alias FROM location_data WHERE name='" + args[2] + "';"), p.getLocation()); - } - - }); - } - - public void createZone(CommandSender sender) { + public static void createZone(CommandSender sender) { // Check if the sender is a player if (!(sender instanceof Player)) { @@ -375,6 +107,8 @@ public void createZone(CommandSender sender) { } + PlotSQL plotSQL = Network.getInstance().getPlotSQL(); + // If the player already has a zones, cancel, as this is the maximum. // Lastly there is a limit of 21 total zones at a time. if (plotSQL.hasRow("SELECT id FROM zone_members WHERE uuid='" + u.player.getUniqueId() + "' AND is_owner=1;")) { diff --git a/src/main/java/net/bteuk/plotsystem/commands/LocationCommand.java b/src/main/java/net/bteuk/plotsystem/commands/LocationCommand.java new file mode 100644 index 0000000..ac00807 --- /dev/null +++ b/src/main/java/net/bteuk/plotsystem/commands/LocationCommand.java @@ -0,0 +1,397 @@ +package net.bteuk.plotsystem.commands; + +import com.sk89q.worldedit.math.BlockVector3; +import net.bteuk.network.Network; +import net.bteuk.network.eventing.events.EventManager; +import net.bteuk.network.lib.utils.ChatUtils; +import net.bteuk.network.sql.GlobalSQL; +import net.bteuk.network.sql.PlotSQL; +import net.bteuk.plotsystem.PlotSystem; +import net.bteuk.plotsystem.utils.CopyRegionFormat; +import net.bteuk.plotsystem.utils.plugins.Multiverse; +import net.bteuk.plotsystem.utils.plugins.WorldEditor; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.NamedTextColor; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; + +import static java.lang.Math.max; +import static java.lang.Math.min; +import static net.bteuk.network.utils.Constants.MAX_Y; +import static net.bteuk.network.utils.Constants.MIN_Y; +import static net.bteuk.plotsystem.PlotSystem.LOGGER; + +public final class LocationCommand { + + private static final Component LOCATION_CREATE_COMMAND_FORMAT = ChatUtils.error("/plotsystem create location [name] "); + private static final Component LOCATION_UPDATE_COMMAND_FORMAT = ChatUtils.error("/plotsystem update location [name] "); + + private LocationCommand() { + // Do nothing + } + + public static void createLocation(CommandSender sender, String[] args) { + + // Check if the sender is a player. + // If so, check if they have permission. + if (sender instanceof Player p) { + if (!p.hasPermission("uknet.plots.create.location")) { + p.sendMessage(ChatUtils.error("You do not have permission to use this command!")); + return; + } + } + + CommandArguments commandArguments = parseCommandArguments(sender, args, LOCATION_CREATE_COMMAND_FORMAT); + if (commandArguments == null) { + return; + } + + final PlotSQL plotSQL = Network.getInstance().getPlotSQL(); + + // Check if the location name is unique. + if (plotSQL.hasRow("SELECT name FROM location_data WHERE name='" + commandArguments.location() + "';")) { + sender.sendMessage(ChatUtils.error("The location ") + .append(Component.text(commandArguments.location(), NamedTextColor.DARK_RED)) + .append(ChatUtils.error(" already exists."))); + return; + } + + // Get the exact regions of the selected coordinates. + int regionXMin = Math.floorDiv(commandArguments.xmin(), 512); + int regionZMin = Math.floorDiv(commandArguments.zmin(), 512); + + int regionXMax = Math.floorDiv(commandArguments.xmax(), 512); + int regionZMax = Math.floorDiv(commandArguments.zmax(), 512); + + // Calculate the coordinate transformation. + int xTransform = -(regionXMin * 512); + int zTransform = -(regionZMin * 512); + + // Create the world and add the regions. + Multiverse.createVoidWorld(commandArguments.location()); + + String saveWorld = PlotSystem.getInstance().getConfig().getString("save_world"); + + if (saveWorld == null) { + sender.sendMessage(ChatUtils.error("The save world is not set in config.")); + return; + } + + // Get worlds. + World copy = Bukkit.getWorld(saveWorld); + World paste = Bukkit.getWorld(commandArguments.location()); + + // Check that the worlds are not null, else delete the Multiverse world. + if (copy == null || paste == null) { + sender.sendMessage("An error occurred, please contact an admin."); + Multiverse.deleteWorld(commandArguments.location()); + return; + } + + // Determine which regions are new, only copy them. + List regionsToAdd = new ArrayList<>(); + for (int i = regionXMin; i <= regionXMax; i++) { + for (int j = regionZMin; j <= regionZMax; j++) { + String region = String.format("%d,%d", i, j); + regionsToAdd.add(new Region(region, i, j)); + } + } + + // Create a list of regions to copy-paste. + RegionHolder regionHolder = new RegionHolder(regionsToAdd, commandArguments.ymin(), commandArguments.ymax(), copy, paste, xTransform, zTransform); + List regions = getCopyRegions(sender, regionHolder); + + // Copy-paste the regions in the save world. + // Iterate through the regions one-by-one. + // Run it asynchronously to not freeze the server. + Bukkit.getScheduler().runTaskAsynchronously(PlotSystem.getInstance(), () -> { + + copyRegions(sender, regions); + + final GlobalSQL globalSQL = Network.getInstance().getGlobalSQL(); + + int coordMin = globalSQL.addCoordinate(new Location( + Bukkit.getWorld(commandArguments.location()), + (regionXMin * 512), MIN_Y, (regionZMin * 512), 0, 0)); + + int coordMax = globalSQL.addCoordinate(new Location( + Bukkit.getWorld(commandArguments.location()), + ((regionXMax * 512) + 511), MAX_Y - 1, ((regionZMax * 512) + 511), 0, 0)); + + // Add the location to the database. + if (plotSQL.update("INSERT INTO location_data(name, alias, server, coordMin, coordMax, xTransform, zTransform) VALUES('" + + commandArguments.location() + "','" + commandArguments.location() + "','" + PlotSystem.SERVER_NAME + "'," + coordMin + "," + coordMax + "," + xTransform + "," + zTransform + ");")) { + + sender.sendMessage(ChatUtils.success("Created new location ") + .append(Component.text(commandArguments.location(), NamedTextColor.DARK_AQUA))); + + // Set the status of all effected regions in the region database. + for (int i = regionXMin; i <= regionXMax; i++) { + for (int j = regionZMin; j <= regionZMax; j++) { + + String region = i + "," + j; + + // Change region status in region database. + // If it already exists remove members. + globalSQL.update("INSERT INTO server_events(uuid,type,server,event) VALUES(NULL,'network','" + + globalSQL.getString("SELECT name FROM server_data WHERE type='EARTH';") + "'," + + "'region set plotsystem " + region + "');"); + + // Add region to database. + plotSQL.update("INSERT INTO regions(region,server,location) VALUES('" + region + "','" + PlotSystem.SERVER_NAME + "','" + commandArguments.location() + "');"); + + } + } + + } else { + + sender.sendMessage(ChatUtils.error("An error occurred, please check the console for more info.")); + LOGGER.warning("An error occured while adding new location!"); + + } + + teleportToLocation(sender, globalSQL, plotSQL, commandArguments.location(), coordMin, coordMax); + }); + } + + public static void updateLocation(CommandSender sender, String[] args) { + + // Check if the sender is a player. + // If so, check if they have permission. + if (sender instanceof Player p) { + if (!p.hasPermission("uknet.plots.update.location")) { + p.sendMessage(ChatUtils.error("You do not have permission to use this command!")); + return; + } + } + + CommandArguments commandArguments = parseCommandArguments(sender, args, LOCATION_UPDATE_COMMAND_FORMAT); + if (commandArguments == null) { + return; + } + + PlotSQL plotSQL = Network.getInstance().getPlotSQL(); + + // Check if the location name exists. + if (!plotSQL.hasRow("SELECT name FROM location_data WHERE name='" + commandArguments.location() + "';")) { + sender.sendMessage(ChatUtils.error("Location %s does not exist.", commandArguments.location())); + return; + } + + // Get the exact regions of the selected coordinates. + int regionXMin = Math.floorDiv(commandArguments.xmin(), 512); + int regionZMin = Math.floorDiv(commandArguments.zmin(), 512); + + int regionXMax = Math.floorDiv(commandArguments.xmax(), 512); + int regionZMax = Math.floorDiv(commandArguments.zmax(), 512); + + // Get the coordinate transformation of the location. + int xTransform = plotSQL.getInt("SELECT xTransform FROM location_data WHERE name='" + commandArguments.location() + "';"); + int zTransform = plotSQL.getInt("SELECT zTransform FROM location_data WHERE name='" + commandArguments.location() + "';"); + + // Get the worlds. + String saveWorld = PlotSystem.getInstance().getConfig().getString("save_world"); + if (saveWorld == null) { + sender.sendMessage(ChatUtils.error("The save world is not set in config.")); + return; + } + + // Get worlds. + World copy = Bukkit.getWorld(saveWorld); + World paste = Bukkit.getWorld(commandArguments.location()); + + // Check that the worlds are not null, else delete the Multiverse world. + if (copy == null || paste == null) { + sender.sendMessage("An error occurred, please contact an admin."); + return; + } + + // Determine which regions are new, only copy them. + List existingRegions = plotSQL.getStringList("SELECT region FROM regions WHERE location='" + commandArguments.location() + "';"); + List regionsToAdd = new ArrayList<>(); + for (int i = regionXMin; i <= regionXMax; i++) { + for (int j = regionZMin; j <= regionZMax; j++) { + String region = String.format("%d,%d", i, j); + if (!existingRegions.contains(region)) { + regionsToAdd.add(new Region(region, i, j)); + } + } + } + + // Create a list of regions to copy-paste. + RegionHolder regionHolder = new RegionHolder(regionsToAdd, commandArguments.ymin(), commandArguments.ymax(), copy, paste, xTransform, zTransform); + List regions = getCopyRegions(sender, regionHolder); + + // Copy-paste the regions in the save world. + // Iterate through the regions one-by-one. + // Run it asynchronously to not freeze the server. + Bukkit.getScheduler().runTaskAsynchronously(PlotSystem.getInstance(), () -> { + + copyRegions(sender, regions); + + GlobalSQL globalSQL = Network.getInstance().getGlobalSQL(); + + int minCoordinateId = globalSQL.getInt("SELECT coordMin FROM location_data WHERE name='" + commandArguments.location() + "';"); + int maxCoordinateId = globalSQL.getInt("SELECT coordMax FROM location_data WHERE name='" + commandArguments.location() + "';"); + + globalSQL.updateCoordinate(minCoordinateId, new Location(Bukkit.getWorld(commandArguments.location()), (regionXMin * 512), MIN_Y, (regionZMin * 512), 0, 0)); + globalSQL.updateCoordinate(maxCoordinateId, new Location(Bukkit.getWorld(commandArguments.location()), ((regionXMax * 512) + 511), MAX_Y - 1, ((regionZMax * 512) + 511), 0, 0)); + + // Add the location to the database. + for (Region region : regionsToAdd) { + // Change region status in region database. + // If it already exists remove members. + globalSQL.update("INSERT INTO server_events(uuid,type,server,event) VALUES(NULL,'network','" + globalSQL.getString( + "SELECT name FROM server_data WHERE type='EARTH';") + "'," + "'region set plotsystem " + region.name() + "');"); + + // Add region to database. + plotSQL.update("INSERT INTO regions(region,server,location) VALUES('" + region.name() + "','" + PlotSystem.SERVER_NAME + "','" + commandArguments.location() + "');"); + } + + sender.sendMessage(ChatUtils.success("Updated location %s", commandArguments.location())); + + teleportToLocation(sender, globalSQL, plotSQL, commandArguments.location(), minCoordinateId, maxCoordinateId); + }); + } + + private static CommandArguments parseCommandArguments(CommandSender sender, String[] args, Component error) { + // Check if they have enough args. + if (args.length < 9) { + sender.sendMessage(error); + return null; + } + + int xmin; + int ymin; + int zmin; + + int xmax; + int ymax; + int zmax; + + // Check if the coordinates are actual numbers. + try { + xmin = Integer.parseInt(args[3]); + ymin = Integer.parseInt(args[4]); + zmin = Integer.parseInt(args[5]); + + xmax = Integer.parseInt(args[6]); + ymax = Integer.parseInt(args[7]); + zmax = Integer.parseInt(args[8]); + } catch (NumberFormatException e) { + sender.sendMessage(error); + return null; + } + + return new CommandArguments(args[2], xmin, ymin, zmin, xmax, ymax, zmax); + } + + private static List getCopyRegions(CommandSender sender, RegionHolder regionHolder) { + List regionsToCopy = new ArrayList<>(); + + final int yMin = max(regionHolder.ymin(), MIN_Y); + final int yMax = min(regionHolder.ymax(), MAX_Y - 1); + + for (Region region : regionHolder.regionsToAdd()) { + // Split the region into 4 equal segments of 256x256. + regionsToCopy.add(new CopyRegionFormat(regionHolder.copyWorld(), regionHolder.pasteWorld(), BlockVector3.at(region.regionX() * 512, yMin, region.regionZ() * 512), + BlockVector3.at(region.regionX() * 512 + 255, yMax, region.regionZ() * 512 + 255), + BlockVector3.at(region.regionX() * 512 + regionHolder.xTransform(), yMin, region.regionZ() * 512 + regionHolder.zTransform()))); + + regionsToCopy.add(new CopyRegionFormat(regionHolder.copyWorld(), regionHolder.pasteWorld(), BlockVector3.at(region.regionX() * 512 + 256, yMin, region.regionZ() * 512), + BlockVector3.at(region.regionX() * 512 + 511, yMax, region.regionZ() * 512 + 255), + BlockVector3.at(region.regionX() * 512 + 256 + regionHolder.xTransform(), yMin, region.regionZ() * 512 + regionHolder.zTransform()))); + + regionsToCopy.add(new CopyRegionFormat(regionHolder.copyWorld(), regionHolder.pasteWorld(), BlockVector3.at(region.regionX() * 512, yMin, region.regionZ() * 512 + 256), + BlockVector3.at(region.regionX() * 512 + 255, yMax, region.regionZ() * 512 + 511), + BlockVector3.at(region.regionX() * 512 + regionHolder.xTransform(), yMin, region.regionZ() * 512 + 256 + regionHolder.zTransform()))); + + regionsToCopy.add( + new CopyRegionFormat(regionHolder.copyWorld(), regionHolder.pasteWorld(), BlockVector3.at(region.regionX() * 512 + 256, yMin, region.regionZ() * 512 + 256), + BlockVector3.at(region.regionX() * 512 + 511, yMax, region.regionZ() * 512 + 511), + BlockVector3.at(region.regionX() * 512 + 256 + regionHolder.xTransform(), yMin, region.regionZ() * 512 + 256 + regionHolder.zTransform()))); + } + + LOGGER.info("Add segments to list, there are " + regionsToCopy.size()); + sender.sendMessage(ChatUtils.success("Added " + regionsToCopy.size() + " segments of 256x256 to the list to be copied.")); + + return regionsToCopy; + } + + private static void copyRegions(CommandSender sender, List regions) { + + sender.sendMessage(ChatUtils.success("Transferring terrain, this may take a while.")); + sender.sendMessage(ChatUtils.success("Please don't leave this server while this is in progress.")); + + // Create atomic boolean to query whether a region can be copied. + AtomicBoolean isReady = new AtomicBoolean(true); + + while (!regions.isEmpty()) { + if (isReady.get()) { + // Set isReady to false so the loop will wait until the previous copy-paste is done. + isReady.set(false); + + CopyRegionFormat regionFormat = regions.getFirst(); + + Bukkit.getScheduler().runTaskAsynchronously(PlotSystem.getInstance(), () -> { + if (!WorldEditor.largeCopy(regionFormat.minPoint(), regionFormat.maxPoint(), regionFormat.pasteMinPoint(), regionFormat.copyWorld(), + regionFormat.pasteWorld())) { + sender.sendMessage(ChatUtils.error("An error occured while transferring the terrain.")); + } else { + regions.remove(regionFormat); + sender.sendMessage(ChatUtils.success("Segment copied, there are ").append(Component.text(regions.size(), NamedTextColor.DARK_AQUA)) + .append(ChatUtils.success(" remaining."))); + LOGGER.info("Segment copied, there are " + regions.size() + " remaining."); + isReady.set(true); + } + }); + } + } + + sender.sendMessage(ChatUtils.success("Terrain transfer has been completed.")); + } + + private static void teleportToLocation(CommandSender sender, GlobalSQL globalSQL, PlotSQL plotSQL, String location, int coordMin, int coordMax) { + // If sender is a player teleport them to the location. + if (sender instanceof Player p) { + + // Get middle. + double x = ((globalSQL.getDouble("SELECT x FROM coordinates WHERE id=" + coordMax + ";") + + globalSQL.getDouble("SELECT x FROM coordinates WHERE id=" + coordMin + ";")) / 2) + + plotSQL.getInt("SELECT xTransform FROM location_data WHERE name='" + location + "';"); + + double z = ((globalSQL.getDouble("SELECT z FROM coordinates WHERE id=" + coordMax + ";") + + globalSQL.getDouble("SELECT z FROM coordinates WHERE id=" + coordMin + ";")) / 2) + + plotSQL.getInt("SELECT zTransform FROM location_data WHERE name='" + location + "';"); + + // Teleport to the location. + World world = Bukkit.getWorld(location); + + double y = 64; + if (world != null) { + y = world.getHighestBlockYAt((int) x, (int) z); + y++; + } + + EventManager.createTeleportEvent(false, p.getUniqueId().toString(), "network", "teleport " + location + " " + x + " " + y + " " + z + " " + + p.getLocation().getYaw() + " " + p.getLocation().getPitch(), + "&aTeleported to location &3" + plotSQL.getString("SELECT alias FROM location_data WHERE name='" + location + "';"), p.getLocation()); + } + } + + private record CommandArguments(String location, int xmin, int ymin, int zmin, int xmax, int ymax, int zmax) { + } + + private record Region(String name, int regionX, int regionZ) { + } + + private record RegionHolder(List regionsToAdd, int ymin, int ymax, World copyWorld, World pasteWorld, int xTransform, int zTransform) { + } +} diff --git a/src/main/java/net/bteuk/plotsystem/commands/PlotSystemCommand.java b/src/main/java/net/bteuk/plotsystem/commands/PlotSystemCommand.java index 4ffdf0c..91deea6 100644 --- a/src/main/java/net/bteuk/plotsystem/commands/PlotSystemCommand.java +++ b/src/main/java/net/bteuk/plotsystem/commands/PlotSystemCommand.java @@ -46,17 +46,12 @@ public void execute(CommandSourceStack stack, String[] args) { switch (args[0]) { case "selectiontool" -> selectionTool(sender); - case "create" -> { - CreateCommand createCommand = new CreateCommand(globalSQL, plotSQL); - createCommand.create(sender, args); - } + case "create" -> CreateCommand.create(sender, args); case "delete" -> { DeleteCommand deleteCommand = new DeleteCommand(globalSQL, plotSQL); deleteCommand.delete(sender, args); } - case "update" -> { - UpdateCommand.update(sender, args); - } + case "update" -> UpdateCommand.update(sender, args); case "help" -> help(sender); case "setalias" -> { diff --git a/src/main/java/net/bteuk/plotsystem/commands/UpdateCommand.java b/src/main/java/net/bteuk/plotsystem/commands/UpdateCommand.java index 42c00b8..b14061f 100644 --- a/src/main/java/net/bteuk/plotsystem/commands/UpdateCommand.java +++ b/src/main/java/net/bteuk/plotsystem/commands/UpdateCommand.java @@ -1,38 +1,23 @@ package net.bteuk.plotsystem.commands; -import com.sk89q.worldedit.math.BlockVector3; import net.bteuk.network.Network; import net.bteuk.network.lib.enums.PlotDifficulties; import net.bteuk.network.lib.utils.ChatUtils; -import net.bteuk.network.sql.GlobalSQL; import net.bteuk.network.sql.PlotSQL; -import net.bteuk.plotsystem.PlotSystem; -import net.bteuk.plotsystem.utils.CopyRegionFormat; -import net.bteuk.plotsystem.utils.plugins.WorldEditor; import net.kyori.adventure.text.Component; -import net.kyori.adventure.text.format.NamedTextColor; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.World; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.atomic.AtomicBoolean; - -import static java.lang.Math.max; -import static java.lang.Math.min; -import static net.bteuk.network.utils.Constants.MAX_Y; -import static net.bteuk.network.utils.Constants.MIN_Y; -import static net.bteuk.plotsystem.PlotSystem.LOGGER; - -public class UpdateCommand { +public final class UpdateCommand { private static final Component GENERIC_ERROR_MESSAGE = ChatUtils.error("/plotsystem update [plot, location]"); private static final Component PLOT_ERROR_MESSAGE = ChatUtils.error("/plotsystem update plot set difficulty [easy|normal|hard]"); + private UpdateCommand() { + // Do nothing + } + public static void update(CommandSender sender, String[] args) { if (args.length < 2) { @@ -42,7 +27,7 @@ public static void update(CommandSender sender, String[] args) { switch (args[1]) { case "plot" -> updatePlot(sender, args); - case "location" -> updateLocation(sender, args); + case "location" -> LocationCommand.updateLocation(sender, args); default -> sender.sendMessage(GENERIC_ERROR_MESSAGE); } } @@ -92,189 +77,4 @@ private static void updatePlot(CommandSender sender, String[] args) { plotSQL.update("UPDATE plot_data SET difficulty=" + plotDifficulty.getValue() + " WHERE id=" + plotID + ";"); sender.sendMessage(ChatUtils.success("Updated difficulty of plot %s to %s.", args[2], args[5])); } - - private static void updateLocation(CommandSender sender, String[] args) { - - // Check if the sender is a player. - // If so, check if they have permission. - if (sender instanceof Player p) { - if (!p.hasPermission("uknet.plots.update.location")) { - p.sendMessage(ChatUtils.error("You do not have permission to use this command!")); - return; - } - } - - // Check if they have enough args. - if (args.length < 9) { - sender.sendMessage(ChatUtils.error("/plotsystem update location [name] ")); - return; - } - - int xmin; - int ymin; - int zmin; - - int xmax; - int ymax; - int zmax; - - // Check if the coordinates are actual numbers. - try { - - xmin = Integer.parseInt(args[3]); - ymin = Integer.parseInt(args[4]); - zmin = Integer.parseInt(args[5]); - - xmax = Integer.parseInt(args[6]); - ymax = Integer.parseInt(args[7]); - zmax = Integer.parseInt(args[8]); - - } catch (NumberFormatException e) { - - sender.sendMessage(ChatUtils.error("/plotsystem update location [name] ")); - return; - - } - - PlotSQL plotSQL = Network.getInstance().getPlotSQL(); - - // Check if the location name exists. - if (!plotSQL.hasRow("SELECT name FROM location_data WHERE name='" + args[2] + "';")) { - sender.sendMessage(ChatUtils.error("Location %s does not exist.", args[2])); - return; - } - - // Get the exact regions of the selected coordinates. - int regionXMin = Math.floorDiv(xmin, 512); - int regionZMin = Math.floorDiv(zmin, 512); - - int regionXMax = Math.floorDiv(xmax, 512); - int regionZMax = Math.floorDiv(zmax, 512); - - // Get the coordinate transformation of the location. - int xTransform = plotSQL.getInt("SELECT xTransform FROM location_data WHERE name='" + args[2] + "';"); - int zTransform = plotSQL.getInt("SELECT zTransform FROM location_data WHERE name='" + args[2] + "';"); - - // Get the worlds. - String saveWorld = PlotSystem.getInstance().getConfig().getString("save_world"); - if (saveWorld == null) { - sender.sendMessage(ChatUtils.error("The save world is not set in config.")); - return; - } - - // Get worlds. - World copy = Bukkit.getWorld(saveWorld); - World paste = Bukkit.getWorld(args[2]); - - // Check that the worlds are not null, else delete the Multiverse world. - if (copy == null || paste == null) { - sender.sendMessage("An error occurred, please contact an admin."); - return; - } - - // Determine which regions are new, only copy them. - List existingRegions = plotSQL.getStringList("SELECT region FROM regions WHERE location='" + args[2] + "';"); - List regionsToAdd = new ArrayList<>(); - - for (int i = regionXMin; i <= regionXMax; i++) { - for (int j = regionZMin; j <= regionZMax; j++) { - String region = String.format("%d,%d", i, j); - if (!existingRegions.contains(region)) { - regionsToAdd.add(new Region(region, i, j)); - } - } - } - - // Copy paste the regions in the save world. - // Iterate through the regions one-by-one. - // Run it asynchronously to not freeze the server. - sender.sendMessage(ChatUtils.success("Transferring terrain, this may take a while.")); - sender.sendMessage(ChatUtils.success("Please don't leave this server while this is in progress.")); - - // Create atomic boolean to query whether a region can be copied. - AtomicBoolean isReady = new AtomicBoolean(true); - - // Create a list of regions to copy paste. - ArrayList regions = new ArrayList<>(); - - final int yMin = max(ymin, MIN_Y); - final int yMax = min(ymax, MAX_Y - 1); - - for (Region region : regionsToAdd) { - // Split the region into 4 equal segments of 256x256. - regions.add(new CopyRegionFormat(copy, paste, BlockVector3.at(region.regionX() * 512, yMin, region.regionZ() * 512), - BlockVector3.at(region.regionX() * 512 + 255, yMax, region.regionZ() * 512 + 255), - BlockVector3.at(region.regionX() * 512 + xTransform, yMin, region.regionZ() * 512 + zTransform))); - - regions.add(new CopyRegionFormat(copy, paste, BlockVector3.at(region.regionX() * 512 + 256, yMin, region.regionZ() * 512), - BlockVector3.at(region.regionX() * 512 + 511, yMax, region.regionZ() * 512 + 255), - BlockVector3.at(region.regionX() * 512 + 256 + xTransform, yMin, region.regionZ() * 512 + zTransform))); - - regions.add(new CopyRegionFormat(copy, paste, BlockVector3.at(region.regionX() * 512, yMin, region.regionZ() * 512 + 256), - BlockVector3.at(region.regionX() * 512 + 255, yMax, region.regionZ() * 512 + 511), - BlockVector3.at(region.regionX() * 512 + xTransform, yMin, region.regionZ() * 512 + 256 + zTransform))); - - regions.add(new CopyRegionFormat(copy, paste, BlockVector3.at(region.regionX() * 512 + 256, yMin, region.regionZ() * 512 + 256), - BlockVector3.at(region.regionX() * 512 + 511, yMax, region.regionZ() * 512 + 511), - BlockVector3.at(region.regionX() * 512 + 256 + xTransform, yMin, region.regionZ() * 512 + 256 + zTransform))); - } - - LOGGER.info("Add segments to list, there are " + regions.size()); - sender.sendMessage(ChatUtils.success("Added " + regions.size() + " segments of 256x256 to the list to be copied.")); - - // Iterate until all regions are done. - Bukkit.getScheduler().runTaskAsynchronously(PlotSystem.getInstance(), () -> { - - while (!regions.isEmpty()) { - - if (isReady.get()) { - - // Set isReady to false so the loop will wait until the previous copy-paste is done. - isReady.set(false); - - CopyRegionFormat regionFormat = regions.getFirst(); - - Bukkit.getScheduler().runTaskAsynchronously(PlotSystem.getInstance(), () -> { - - if (!WorldEditor.largeCopy(regionFormat.minPoint(), regionFormat.maxPoint(), regionFormat.pasteMinPoint(), copy, paste)) { - sender.sendMessage(ChatUtils.error("An error occured while transferring the terrain.")); - } else { - regions.remove(regionFormat); - sender.sendMessage(ChatUtils.success("Segment copied, there are ").append(Component.text(regions.size(), NamedTextColor.DARK_AQUA)) - .append(ChatUtils.success(" remaining."))); - LOGGER.info("Segment copied, there are " + regions.size() + " remaining."); - isReady.set(true); - } - - }); - } - } - - GlobalSQL globalSQL = Network.getInstance().getGlobalSQL(); - - sender.sendMessage(ChatUtils.success("Terrain transfer has been completed.")); - - int minCoordinateId = globalSQL.getInt("SELECT coordMin FROM location_data WHERE name='" + args[2] + "';"); - int maxCoordinateId = globalSQL.getInt("SELECT coordMax FROM location_data WHERE name='" + args[2] + "';"); - - globalSQL.updateCoordinate(minCoordinateId, new Location(Bukkit.getWorld(args[2]), (regionXMin * 512), MIN_Y, (regionZMin * 512), 0, 0)); - globalSQL.updateCoordinate(maxCoordinateId, new Location(Bukkit.getWorld(args[2]), ((regionXMax * 512) + 511), MAX_Y - 1, ((regionZMax * 512) + 511), 0, 0)); - - // Add the location to the database. - for (Region region : regionsToAdd) { - // Change region status in region database. - // If it already exists remove members. - globalSQL.update("INSERT INTO server_events(uuid,type,server,event) VALUES(NULL,'network','" + globalSQL.getString( - "SELECT name FROM server_data WHERE type='EARTH';") + "'," + "'region set plotsystem " + region.name() + "');"); - - // Add region to database. - plotSQL.update("INSERT INTO regions(region,server,location) VALUES('" + region.name() + "','" + PlotSystem.SERVER_NAME + "','" + args[2] + "');"); - } - - sender.sendMessage(ChatUtils.success("Update location %s", args[2])); - }); - } - - private record Region(String name, int regionX, int regionZ) { - } } From fd840ea3e832c7a995623393aa15ddcc77b80280 Mon Sep 17 00:00:00 2001 From: ELgamer Date: Sat, 10 May 2025 14:10:51 +0200 Subject: [PATCH 04/21] Before deleting a location make sure there are no players in that world. --- .../plotsystem/commands/DeleteCommand.java | 79 +----------- .../plotsystem/commands/LocationCommand.java | 114 +++++++++++++++++- 2 files changed, 111 insertions(+), 82 deletions(-) diff --git a/src/main/java/net/bteuk/plotsystem/commands/DeleteCommand.java b/src/main/java/net/bteuk/plotsystem/commands/DeleteCommand.java index 2d7a46b..660c33c 100644 --- a/src/main/java/net/bteuk/plotsystem/commands/DeleteCommand.java +++ b/src/main/java/net/bteuk/plotsystem/commands/DeleteCommand.java @@ -8,7 +8,6 @@ import net.bteuk.plotsystem.exceptions.RegionManagerNotFoundException; import net.bteuk.plotsystem.utils.PlotHelper; import net.bteuk.plotsystem.utils.User; -import net.bteuk.plotsystem.utils.plugins.Multiverse; import net.bteuk.plotsystem.utils.plugins.WorldGuardFunctions; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; @@ -17,8 +16,6 @@ import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import java.util.ArrayList; - import static net.bteuk.plotsystem.PlotSystem.LOGGER; public class DeleteCommand { @@ -49,7 +46,7 @@ public void delete(CommandSender sender, String[] args) { case "location": - deleteLocation(sender, args); + LocationCommand.deleteLocation(sender, args); break; case "zone": @@ -159,78 +156,4 @@ private void deletePlot(CommandSender sender, String[] args) { e.printStackTrace(); } } - - private void deleteLocation(CommandSender sender, String[] args) { - - // If sender is a player, check for permission. - if (sender instanceof Player p) { - if (!(p.hasPermission("uknet.plots.delete.location"))) { - p.sendMessage(ChatUtils.error("You do not have permission to use this command.")); - return; - } - } - - // Check arg count. - if (args.length < 3) { - - sender.sendMessage(ChatUtils.error("/plotsystem delete location [name]")); - return; - - } - - // Check if location exists. - if (!(plotSQL.hasRow("SELECT name FROM location_data WHERE name='" + args[2] + "';"))) { - - sender.sendMessage(ChatUtils.error("The location ") - .append(Component.text(args[2], NamedTextColor.DARK_RED)) - .append(ChatUtils.error(" does not exist."))); - return; - - } - - // Check if the location is on this server. - if (!(plotSQL.getString("SELECT server FROM location_data WHERE name='" + args[2] + "';").equals(PlotSystem.SERVER_NAME))) { - - sender.sendMessage(ChatUtils.error("This location is not on this server.")); - return; - - } - - // If location has plots, cancel. - if (plotSQL.hasRow("SELECT id FROM plot_data WHERE location='" + args[2] + "' AND status<>'completed' AND status<>'deleted';")) { - - sender.sendMessage(ChatUtils.error("This location active has plots, all plots must be deleted or completed to remove the location.")); - return; - - } - - // Delete location. - if (Multiverse.deleteWorld(args[2])) { - - // Delete location from database. - plotSQL.update("DELETE FROM location_data WHERE name='" + args[2] + "';"); - sender.sendMessage(ChatUtils.success("Deleted location ") - .append(Component.text(args[2], NamedTextColor.DARK_AQUA))); - LOGGER.info("Deleted location " + args[2] + "."); - - // Get regions from database. - ArrayList regions = plotSQL.getStringList("SELECT region FROM regions WHERE location='" + args[2] + "';"); - - // Delete regions from database. - plotSQL.update("DELETE FROM regions WHERE location='" + args[2] + "';"); - - // Iterate through regions to unlock them on Earth. - for (String region : regions) { - globalSQL.update("INSERT INTO server_events(uuid,type,server,event) VALUES(NULL,'network','" - + globalSQL.getString("SELECT name FROM server_data WHERE type='earth';") + "'," + - "'region set default " + region + "');"); - } - - } else { - - sender.sendMessage(ChatUtils.error("An error occurred while deleting the world.")); - LOGGER.warning("An error occurred while deleting world " + args[2] + "."); - - } - } } diff --git a/src/main/java/net/bteuk/plotsystem/commands/LocationCommand.java b/src/main/java/net/bteuk/plotsystem/commands/LocationCommand.java index ac00807..be4e47f 100644 --- a/src/main/java/net/bteuk/plotsystem/commands/LocationCommand.java +++ b/src/main/java/net/bteuk/plotsystem/commands/LocationCommand.java @@ -6,6 +6,7 @@ import net.bteuk.network.lib.utils.ChatUtils; import net.bteuk.network.sql.GlobalSQL; import net.bteuk.network.sql.PlotSQL; +import net.bteuk.network.utils.Utils; import net.bteuk.plotsystem.PlotSystem; import net.bteuk.plotsystem.utils.CopyRegionFormat; import net.bteuk.plotsystem.utils.plugins.Multiverse; @@ -127,7 +128,8 @@ public static void createLocation(CommandSender sender, String[] args) { // Add the location to the database. if (plotSQL.update("INSERT INTO location_data(name, alias, server, coordMin, coordMax, xTransform, zTransform) VALUES('" - + commandArguments.location() + "','" + commandArguments.location() + "','" + PlotSystem.SERVER_NAME + "'," + coordMin + "," + coordMax + "," + xTransform + "," + zTransform + ");")) { + + commandArguments.location() + "','" + commandArguments.location() + "','" + PlotSystem.SERVER_NAME + "'," + coordMin + "," + coordMax + "," + xTransform + + "," + zTransform + ");")) { sender.sendMessage(ChatUtils.success("Created new location ") .append(Component.text(commandArguments.location(), NamedTextColor.DARK_AQUA))); @@ -145,7 +147,8 @@ public static void createLocation(CommandSender sender, String[] args) { "'region set plotsystem " + region + "');"); // Add region to database. - plotSQL.update("INSERT INTO regions(region,server,location) VALUES('" + region + "','" + PlotSystem.SERVER_NAME + "','" + commandArguments.location() + "');"); + plotSQL.update( + "INSERT INTO regions(region,server,location) VALUES('" + region + "','" + PlotSystem.SERVER_NAME + "','" + commandArguments.location() + "');"); } } @@ -242,7 +245,8 @@ public static void updateLocation(CommandSender sender, String[] args) { int maxCoordinateId = globalSQL.getInt("SELECT coordMax FROM location_data WHERE name='" + commandArguments.location() + "';"); globalSQL.updateCoordinate(minCoordinateId, new Location(Bukkit.getWorld(commandArguments.location()), (regionXMin * 512), MIN_Y, (regionZMin * 512), 0, 0)); - globalSQL.updateCoordinate(maxCoordinateId, new Location(Bukkit.getWorld(commandArguments.location()), ((regionXMax * 512) + 511), MAX_Y - 1, ((regionZMax * 512) + 511), 0, 0)); + globalSQL.updateCoordinate(maxCoordinateId, + new Location(Bukkit.getWorld(commandArguments.location()), ((regionXMax * 512) + 511), MAX_Y - 1, ((regionZMax * 512) + 511), 0, 0)); // Add the location to the database. for (Region region : regionsToAdd) { @@ -252,7 +256,8 @@ public static void updateLocation(CommandSender sender, String[] args) { "SELECT name FROM server_data WHERE type='EARTH';") + "'," + "'region set plotsystem " + region.name() + "');"); // Add region to database. - plotSQL.update("INSERT INTO regions(region,server,location) VALUES('" + region.name() + "','" + PlotSystem.SERVER_NAME + "','" + commandArguments.location() + "');"); + plotSQL.update( + "INSERT INTO regions(region,server,location) VALUES('" + region.name() + "','" + PlotSystem.SERVER_NAME + "','" + commandArguments.location() + "');"); } sender.sendMessage(ChatUtils.success("Updated location %s", commandArguments.location())); @@ -261,6 +266,83 @@ public static void updateLocation(CommandSender sender, String[] args) { }); } + public static void deleteLocation(CommandSender sender, String[] args) { + + // If sender is a player, check for permission. + if (sender instanceof Player p) { + if (!(p.hasPermission("uknet.plots.delete.location"))) { + p.sendMessage(ChatUtils.error("You do not have permission to use this command.")); + return; + } + } + + // Check arg count. + if (args.length < 3) { + sender.sendMessage(ChatUtils.error("/plotsystem delete location [name]")); + return; + } + + PlotSQL plotSQL = Network.getInstance().getPlotSQL(); + GlobalSQL globalSQL = Network.getInstance().getGlobalSQL(); + + // Check if location exists. + if (!(plotSQL.hasRow("SELECT name FROM location_data WHERE name='" + args[2] + "';"))) { + sender.sendMessage(ChatUtils.error("The location %s does not exist.", args[2])); + return; + } + + // Check if the location is on this server. + if (!(plotSQL.getString("SELECT server FROM location_data WHERE name='" + args[2] + "';").equals(PlotSystem.SERVER_NAME))) { + sender.sendMessage(ChatUtils.error("This location is not on this server.")); + return; + } + + // If location has plots, cancel. + if (plotSQL.hasRow("SELECT id FROM plot_data WHERE location='" + args[2] + "' AND status<>'completed' AND status<>'deleted';")) { + sender.sendMessage(ChatUtils.error("This location active has plots, all plots must be deleted or completed to remove the location.")); + return; + } + + // Teleport all players out of the world, so it can be deleted. + // Get the worlds. + String saveWorldName = PlotSystem.getInstance().getConfig().getString("save_world"); + if (saveWorldName == null) { + sender.sendMessage(ChatUtils.error("The save world is not set in config.")); + return; + } + + // Get save world. + World saveWorld = Bukkit.getWorld(saveWorldName); + + teleportPlayersFromLocation(args[2], saveWorld, plotSQL, globalSQL); + + // Delete location. + if (Multiverse.deleteWorld(args[2])) { + + // Delete location from database. + plotSQL.update("DELETE FROM location_data WHERE name='" + args[2] + "';"); + sender.sendMessage(ChatUtils.success("Deleted location ") + .append(Component.text(args[2], NamedTextColor.DARK_AQUA))); + LOGGER.info("Deleted location " + args[2] + "."); + + // Get regions from database. + ArrayList regions = plotSQL.getStringList("SELECT region FROM regions WHERE location='" + args[2] + "';"); + + // Delete regions from database. + plotSQL.update("DELETE FROM regions WHERE location='" + args[2] + "';"); + + // Iterate through regions to unlock them on Earth. + for (String region : regions) { + globalSQL.update("INSERT INTO server_events(uuid,type,server,event) VALUES(NULL,'network','" + + globalSQL.getString("SELECT name FROM server_data WHERE type='earth';") + "'," + + "'region set default " + region + "');"); + } + } else { + sender.sendMessage(ChatUtils.error("An error occurred while deleting the world.")); + LOGGER.warning("An error occurred while deleting world " + args[2] + "."); + } + } + private static CommandArguments parseCommandArguments(CommandSender sender, String[] args, Component error) { // Check if they have enough args. if (args.length < 9) { @@ -386,6 +468,30 @@ private static void teleportToLocation(CommandSender sender, GlobalSQL globalSQL } } + private static void teleportPlayersFromLocation(String location, World saveWorld, PlotSQL plotSQL, GlobalSQL globalSQL) { + int coordMin = globalSQL.getInt("SELECT coordMin FROM location_data WHERE name='" + location + "';"); + int coordMax = globalSQL.getInt("SELECT coordMax FROM location_data WHERE name='" + location + "';"); + + // Get middle. + double x = ((globalSQL.getDouble("SELECT x FROM coordinates WHERE id=" + coordMax + ";") + + globalSQL.getDouble("SELECT x FROM coordinates WHERE id=" + coordMin + ";")) / 2) + + plotSQL.getInt("SELECT xTransform FROM location_data WHERE name='" + location + "';"); + + double z = ((globalSQL.getDouble("SELECT z FROM coordinates WHERE id=" + coordMax + ";") + + globalSQL.getDouble("SELECT z FROM coordinates WHERE id=" + coordMin + ";")) / 2) + + plotSQL.getInt("SELECT zTransform FROM location_data WHERE name='" + location + "';"); + + x -= plotSQL.getInt("SELECT xTransform FROM location_data WHERE name='" + location + "';"); + z -= plotSQL.getInt("SELECT zTransform FROM location_data WHERE name='" + location + "';"); + + // Teleport all players away from the location. + Location teleportLocation = new Location(saveWorld, x, Utils.getHighestYAt(saveWorld, (int) x, (int) z), z); + PlotSystem.getInstance().getServer().getOnlinePlayers().forEach(player -> { + player.teleport(teleportLocation); + player.sendMessage(ChatUtils.success("Teleported to save world, location %s is being deleted.", location)); + }); + } + private record CommandArguments(String location, int xmin, int ymin, int zmin, int xmax, int ymax, int zmax) { } From 39bd41ab90aa6c390004215c71fb16cb5a74808d Mon Sep 17 00:00:00 2001 From: ELgamer Date: Thu, 15 May 2025 21:02:43 +0200 Subject: [PATCH 05/21] Update outlines when changing plot difficulty, fix bug with location update. --- .../java/net/bteuk/plotsystem/commands/LocationCommand.java | 6 +++--- .../net/bteuk/plotsystem/commands/PlotSystemCommand.java | 2 +- .../java/net/bteuk/plotsystem/commands/UpdateCommand.java | 4 ++++ 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/main/java/net/bteuk/plotsystem/commands/LocationCommand.java b/src/main/java/net/bteuk/plotsystem/commands/LocationCommand.java index be4e47f..0288e9a 100644 --- a/src/main/java/net/bteuk/plotsystem/commands/LocationCommand.java +++ b/src/main/java/net/bteuk/plotsystem/commands/LocationCommand.java @@ -180,7 +180,7 @@ public static void updateLocation(CommandSender sender, String[] args) { return; } - PlotSQL plotSQL = Network.getInstance().getPlotSQL(); + final PlotSQL plotSQL = Network.getInstance().getPlotSQL(); // Check if the location name exists. if (!plotSQL.hasRow("SELECT name FROM location_data WHERE name='" + commandArguments.location() + "';")) { @@ -241,8 +241,8 @@ public static void updateLocation(CommandSender sender, String[] args) { GlobalSQL globalSQL = Network.getInstance().getGlobalSQL(); - int minCoordinateId = globalSQL.getInt("SELECT coordMin FROM location_data WHERE name='" + commandArguments.location() + "';"); - int maxCoordinateId = globalSQL.getInt("SELECT coordMax FROM location_data WHERE name='" + commandArguments.location() + "';"); + int minCoordinateId = plotSQL.getInt("SELECT coordMin FROM location_data WHERE name='" + commandArguments.location() + "';"); + int maxCoordinateId = plotSQL.getInt("SELECT coordMax FROM location_data WHERE name='" + commandArguments.location() + "';"); globalSQL.updateCoordinate(minCoordinateId, new Location(Bukkit.getWorld(commandArguments.location()), (regionXMin * 512), MIN_Y, (regionZMin * 512), 0, 0)); globalSQL.updateCoordinate(maxCoordinateId, diff --git a/src/main/java/net/bteuk/plotsystem/commands/PlotSystemCommand.java b/src/main/java/net/bteuk/plotsystem/commands/PlotSystemCommand.java index 91deea6..4d937a0 100644 --- a/src/main/java/net/bteuk/plotsystem/commands/PlotSystemCommand.java +++ b/src/main/java/net/bteuk/plotsystem/commands/PlotSystemCommand.java @@ -29,7 +29,7 @@ public PlotSystemCommand(GlobalSQL globalSQL, PlotSQL plotSQL) { this.plotSQL = plotSQL; this.globalSQL = globalSQL; - setTabCompleter(new FixedArgSelector(Arrays.asList("create", "selectiontool", "delete", "help", "setalias", "movemarker"), 0)); + setTabCompleter(new FixedArgSelector(Arrays.asList("create", "selectiontool", "delete", "help", "setalias", "movemarker", "update"), 0)); } @Override diff --git a/src/main/java/net/bteuk/plotsystem/commands/UpdateCommand.java b/src/main/java/net/bteuk/plotsystem/commands/UpdateCommand.java index b14061f..277e3e7 100644 --- a/src/main/java/net/bteuk/plotsystem/commands/UpdateCommand.java +++ b/src/main/java/net/bteuk/plotsystem/commands/UpdateCommand.java @@ -4,6 +4,7 @@ import net.bteuk.network.lib.enums.PlotDifficulties; import net.bteuk.network.lib.utils.ChatUtils; import net.bteuk.network.sql.PlotSQL; +import net.bteuk.plotsystem.PlotSystem; import net.kyori.adventure.text.Component; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; @@ -76,5 +77,8 @@ private static void updatePlot(CommandSender sender, String[] args) { // Update the plot difficulty. plotSQL.update("UPDATE plot_data SET difficulty=" + plotDifficulty.getValue() + " WHERE id=" + plotID + ";"); sender.sendMessage(ChatUtils.success("Updated difficulty of plot %s to %s.", args[2], args[5])); + + // Update the plot outlines. + PlotSystem.getInstance().getUsers().forEach(PlotSystem.getInstance().getOutlines()::addNearbyOutlines); } } From b8dec3fbe92e30c8103c48e2292fed2f3fa9406e Mon Sep 17 00:00:00 2001 From: ELgamer Date: Sat, 24 May 2025 10:54:10 +0200 Subject: [PATCH 06/21] Don't allow the update location to make the location smaller. --- .../plotsystem/commands/LocationCommand.java | 41 +++++++++++++++---- 1 file changed, 34 insertions(+), 7 deletions(-) diff --git a/src/main/java/net/bteuk/plotsystem/commands/LocationCommand.java b/src/main/java/net/bteuk/plotsystem/commands/LocationCommand.java index 0288e9a..b06ebb3 100644 --- a/src/main/java/net/bteuk/plotsystem/commands/LocationCommand.java +++ b/src/main/java/net/bteuk/plotsystem/commands/LocationCommand.java @@ -6,6 +6,7 @@ import net.bteuk.network.lib.utils.ChatUtils; import net.bteuk.network.sql.GlobalSQL; import net.bteuk.network.sql.PlotSQL; +import net.bteuk.network.utils.Coordinate; import net.bteuk.network.utils.Utils; import net.bteuk.plotsystem.PlotSystem; import net.bteuk.plotsystem.utils.CopyRegionFormat; @@ -181,6 +182,7 @@ public static void updateLocation(CommandSender sender, String[] args) { } final PlotSQL plotSQL = Network.getInstance().getPlotSQL(); + final GlobalSQL globalSQL = Network.getInstance().getGlobalSQL(); // Check if the location name exists. if (!plotSQL.hasRow("SELECT name FROM location_data WHERE name='" + commandArguments.location() + "';")) { @@ -188,6 +190,18 @@ public static void updateLocation(CommandSender sender, String[] args) { return; } + // Check if the new area is equal or larger than the existing area. + final int minCoordinateId = plotSQL.getInt("SELECT coordMin FROM location_data WHERE name='" + commandArguments.location() + "';"); + final int maxCoordinateId = plotSQL.getInt("SELECT coordMax FROM location_data WHERE name='" + commandArguments.location() + "';"); + + Coordinate minCoordinate = globalSQL.getCoordinate(minCoordinateId); + Coordinate maxCoordinate = globalSQL.getCoordinate(maxCoordinateId); + + if (commandArguments.isSmallerThan(minCoordinate, maxCoordinate)) { + sender.sendMessage(ChatUtils.error("The new area must not be smaller than the current area.")); + return; + } + // Get the exact regions of the selected coordinates. int regionXMin = Math.floorDiv(commandArguments.xmin(), 512); int regionZMin = Math.floorDiv(commandArguments.zmin(), 512); @@ -239,11 +253,6 @@ public static void updateLocation(CommandSender sender, String[] args) { copyRegions(sender, regions); - GlobalSQL globalSQL = Network.getInstance().getGlobalSQL(); - - int minCoordinateId = plotSQL.getInt("SELECT coordMin FROM location_data WHERE name='" + commandArguments.location() + "';"); - int maxCoordinateId = plotSQL.getInt("SELECT coordMax FROM location_data WHERE name='" + commandArguments.location() + "';"); - globalSQL.updateCoordinate(minCoordinateId, new Location(Bukkit.getWorld(commandArguments.location()), (regionXMin * 512), MIN_Y, (regionZMin * 512), 0, 0)); globalSQL.updateCoordinate(maxCoordinateId, new Location(Bukkit.getWorld(commandArguments.location()), ((regionXMax * 512) + 511), MAX_Y - 1, ((regionZMax * 512) + 511), 0, 0)); @@ -469,8 +478,8 @@ private static void teleportToLocation(CommandSender sender, GlobalSQL globalSQL } private static void teleportPlayersFromLocation(String location, World saveWorld, PlotSQL plotSQL, GlobalSQL globalSQL) { - int coordMin = globalSQL.getInt("SELECT coordMin FROM location_data WHERE name='" + location + "';"); - int coordMax = globalSQL.getInt("SELECT coordMax FROM location_data WHERE name='" + location + "';"); + int coordMin = plotSQL.getInt("SELECT coordMin FROM location_data WHERE name='" + location + "';"); + int coordMax = plotSQL.getInt("SELECT coordMax FROM location_data WHERE name='" + location + "';"); // Get middle. double x = ((globalSQL.getDouble("SELECT x FROM coordinates WHERE id=" + coordMax + ";") + @@ -493,6 +502,24 @@ private static void teleportPlayersFromLocation(String location, World saveWorld } private record CommandArguments(String location, int xmin, int ymin, int zmin, int xmax, int ymax, int zmax) { + + /** + * Checks whether the area defined by the command arguments is smaller than the area defined by the given coordinates. + * + * @param coordMin the min coordinate + * @param coordMax the max coordinate + * @return whether the area is smaller than the input coordinates + */ + private boolean isSmallerThan(Coordinate coordMin, Coordinate coordMax) { + boolean smaller = coordMin == null || coordMax == null; + smaller = smaller || xmin > coordMin.getX(); + smaller = smaller || ymin > coordMin.getY(); + smaller = smaller || zmin > coordMin.getZ(); + smaller = smaller || xmax < coordMax.getX(); + smaller = smaller || ymax < coordMax.getY(); + smaller = smaller || zmax < coordMax.getZ(); + return smaller; + } } private record Region(String name, int regionX, int regionZ) { From 5d3bf1ffa7b7b185b22463db118f9aa7180a163a Mon Sep 17 00:00:00 2001 From: ELgamer Date: Thu, 12 Jun 2025 20:07:14 +0200 Subject: [PATCH 07/21] Don't allow plots to be under review or under verification on server start, reset them all back to default settings. - plotsystem update doesn't update the y. --- src/main/java/net/bteuk/plotsystem/PlotSystem.java | 5 ++--- .../bteuk/plotsystem/commands/LocationCommand.java | 12 +++++------- 2 files changed, 7 insertions(+), 10 deletions(-) diff --git a/src/main/java/net/bteuk/plotsystem/PlotSystem.java b/src/main/java/net/bteuk/plotsystem/PlotSystem.java index d23ca45..b6969c7 100644 --- a/src/main/java/net/bteuk/plotsystem/PlotSystem.java +++ b/src/main/java/net/bteuk/plotsystem/PlotSystem.java @@ -139,9 +139,8 @@ public void enablePlugin() { // Create list of users. users = new ArrayList<>(); - // TODO: Ensure no plots on this server are under review or under verification. - // plotSQL.update( - // "UPDATE plot_data AS pd INNER JOIN location_data AS ld ON ld.name=pd.location SET pd.status='submitted' WHERE pd.status='reviewing' AND ld.server='" + SERVER_NAME + "';"); + plotSQL.update("UPDATE plot_submission AS ps INNER JOIN plot_data AS pd ON ps.plot_id=pd.id SET ps.status='submitted' WHERE ps.status='under review' AND pd.location IN (SELECT name FROM location_data WHERE server='" + SERVER_NAME + "');"); + plotSQL.update("UPDATE plot_submission AS ps INNER JOIN plot_data AS pd ON ps.plot_id=pd.id SET ps.status='awaiting verification' WHERE ps.status='under verification' AND pd.location IN (SELECT name FROM location_data WHERE server='" + SERVER_NAME + "');"); // Create gui item gui = new ItemStack(Material.NETHER_STAR); diff --git a/src/main/java/net/bteuk/plotsystem/commands/LocationCommand.java b/src/main/java/net/bteuk/plotsystem/commands/LocationCommand.java index b06ebb3..ca92c26 100644 --- a/src/main/java/net/bteuk/plotsystem/commands/LocationCommand.java +++ b/src/main/java/net/bteuk/plotsystem/commands/LocationCommand.java @@ -243,7 +243,7 @@ public static void updateLocation(CommandSender sender, String[] args) { } // Create a list of regions to copy-paste. - RegionHolder regionHolder = new RegionHolder(regionsToAdd, commandArguments.ymin(), commandArguments.ymax(), copy, paste, xTransform, zTransform); + RegionHolder regionHolder = new RegionHolder(regionsToAdd, (int) minCoordinate.getY(), (int) maxCoordinate.getY(), copy, paste, xTransform, zTransform); List regions = getCopyRegions(sender, regionHolder); // Copy-paste the regions in the save world. @@ -512,12 +512,10 @@ private record CommandArguments(String location, int xmin, int ymin, int zmin, i */ private boolean isSmallerThan(Coordinate coordMin, Coordinate coordMax) { boolean smaller = coordMin == null || coordMax == null; - smaller = smaller || xmin > coordMin.getX(); - smaller = smaller || ymin > coordMin.getY(); - smaller = smaller || zmin > coordMin.getZ(); - smaller = smaller || xmax < coordMax.getX(); - smaller = smaller || ymax < coordMax.getY(); - smaller = smaller || zmax < coordMax.getZ(); + smaller = smaller || (xmin > coordMin.getX()); + smaller = smaller || (zmin > coordMin.getZ()); + smaller = smaller || (xmax < coordMax.getX()); + smaller = smaller || (zmax < coordMax.getZ()); return smaller; } } From 4b056e310878b23ce0e8131a142353cdcdfee6c6 Mon Sep 17 00:00:00 2001 From: LM-Wolfert Date: Fri, 24 Oct 2025 21:08:19 +0200 Subject: [PATCH 08/21] Start updating the plot system to use the NetworkAPI instead of having direct plugin access. --- pom.xml | 64 +++++++++------ .../java/net/bteuk/plotsystem/PlotSystem.java | 76 +++++++++--------- .../java/net/bteuk/plotsystem/Timers.java | 79 +++---------------- .../plotsystem/commands/ClaimCommand.java | 42 +++++----- .../bteuk/plotsystem/events/ClaimEvent.java | 42 ++++++---- .../bteuk/plotsystem/events/CloseEvent.java | 43 ++++++---- .../bteuk/plotsystem/events/DeleteEvent.java | 69 ++++++++-------- .../bteuk/plotsystem/events/EventManager.java | 6 +- .../net/bteuk/plotsystem/gui/ClaimGui.java | 23 +++--- .../bteuk/plotsystem/gui/CreatePlotGui.java | 15 ++-- .../bteuk/plotsystem/gui/CreateZoneGui.java | 38 ++++----- .../listeners/HologramClickEvent.java | 2 +- .../plotsystem/listeners/JoinServer.java | 43 ++-------- .../bteuk/plotsystem/utils/PlotHelper.java | 43 ++++------ .../bteuk/plotsystem/utils/SelectionTool.java | 56 ++++++------- .../java/net/bteuk/plotsystem/utils/User.java | 13 +-- .../net/bteuk/plotsystem/utils/Utils.java | 46 +++++++++++ .../utils/plugins/WGCreatePlot.java | 31 +++++--- 18 files changed, 348 insertions(+), 383 deletions(-) create mode 100644 src/main/java/net/bteuk/plotsystem/utils/Utils.java diff --git a/pom.xml b/pom.xml index 6c04e31..5758146 100644 --- a/pom.xml +++ b/pom.xml @@ -14,6 +14,13 @@ 21 UTF-8 + + 1.21.8-R0.1-SNAPSHOT + + fae3957ca2 + 5958727df9 + + 5.3.3 @@ -68,6 +75,11 @@ papermc https://repo.papermc.io/repository/maven-public/ + + smyler-releases + Smyler's maven repository + https://maven.smyler.net/releases + sonatype https://oss.sonatype.org/content/groups/public/ @@ -95,7 +107,7 @@ com.intellectualsites.bom bom-newest - 1.37 + 1.55 import pom @@ -106,16 +118,33 @@ io.papermc.paper paper-api - 1.21.4-R0.1-SNAPSHOT + ${paper.api.version} provided - com.github.BTEUK - Network - 9a08eacbd6 + com.github.BTEUK.Network + api + ${bteuk.network.version} provided + + com.github.BTEUK.Network + papercore + ${bteuk.network.version} + provided + + + com.github.BTEUK.BTEUKLib + Minecraft + ${bteuk.lib.version} + + + + net.buildtheearth.terraminusminus + terraminusminus-core + 2.0.0-1.21.4 + com.fastasyncworldedit @@ -137,35 +166,30 @@ com.sk89q.worldguard worldguard-bukkit - 7.0.12 + 7.0.14 provided - - org.apache.commons - commons-dbcp2 - 2.9.0 - commons-io commons-io - 2.13.0 + 2.20.0 - com.onarandombox.multiversecore - Multiverse-Core - 4.3.11 + org.mvplugins.multiverse.core + multiverse-core + ${multiverse.version} provided org.projectlombok lombok - 1.18.34 + 1.18.42 provided com.github.decentsoftware-eu decentholograms - 2.8.11 + 2.9.7 provided @@ -175,11 +199,5 @@ 5.9.2 test - - org.mockito - mockito-core - 5.4.0 - test - diff --git a/src/main/java/net/bteuk/plotsystem/PlotSystem.java b/src/main/java/net/bteuk/plotsystem/PlotSystem.java index b6969c7..6bb84ab 100644 --- a/src/main/java/net/bteuk/plotsystem/PlotSystem.java +++ b/src/main/java/net/bteuk/plotsystem/PlotSystem.java @@ -4,14 +4,15 @@ import io.papermc.paper.plugin.lifecycle.event.LifecycleEventManager; import io.papermc.paper.plugin.lifecycle.event.types.LifecycleEvents; import lombok.Getter; -import net.bteuk.network.Network; +import net.bteuk.minecraft.gui.GuiManager; +import net.bteuk.network.api.NetworkAPI; import net.bteuk.network.lib.utils.ChatUtils; -import net.bteuk.network.sql.GlobalSQL; -import net.bteuk.network.sql.PlotSQL; import net.bteuk.plotsystem.commands.ClaimCommand; import net.bteuk.plotsystem.commands.PlotSystemCommand; import net.bteuk.plotsystem.commands.ReviewCommand; import net.bteuk.plotsystem.commands.ToggleOutlines; +import net.bteuk.plotsystem.events.ClaimEvent; +import net.bteuk.plotsystem.events.CloseEvent; import net.bteuk.plotsystem.listeners.ClaimEnter; import net.bteuk.plotsystem.listeners.CloseInventory; import net.bteuk.plotsystem.listeners.HologramClickEvent; @@ -24,6 +25,7 @@ import net.bteuk.plotsystem.utils.PlotHologram; import net.bteuk.plotsystem.utils.User; import net.bteuk.plotsystem.utils.plugins.Multiverse; +import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.configuration.serialization.ConfigurationSerializable; import org.bukkit.configuration.serialization.ConfigurationSerialization; @@ -31,6 +33,7 @@ import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.plugin.java.JavaPlugin; import java.util.ArrayList; @@ -51,9 +54,6 @@ public class PlotSystem extends JavaPlugin { // Returns an instance of the plugin. @Getter static PlotSystem instance; - // SQL Classes. - public GlobalSQL globalSQL; - public PlotSQL plotSQL; public Timers timers; // Listeners public ClaimEnter claimEnter; @@ -67,6 +67,10 @@ public class PlotSystem extends JavaPlugin { @Getter private boolean isClosing = false; + private GuiManager guiManager; + + private PlotHelper plotHelper;; + @Override public void onEnable() { @@ -93,54 +97,47 @@ public void onEnable() { } - // Set databases from Network dependency. - globalSQL = Network.getInstance().getGlobalSQL(); - plotSQL = Network.getInstance().getPlotSQL(); - // Set the server name from config. SERVER_NAME = CONFIG.getString("server_name"); - // If the server is in the database. - if (globalSQL.hasRow("SELECT name FROM server_data WHERE name='" + SERVER_NAME + "';")) { - - // Add save world if it does not yet exist. - // Save world name is in config. - // This implies first launch with plugin. - if (!Multiverse.hasWorld(CONFIG.getString("save_world"))) { - // Create save world. - if (!Multiverse.createVoidWorld(CONFIG.getString("save_world"))) { + // Add save world if it does not yet exist. + // Save world name is in config. + // This implies first launch with plugin. + if (!Multiverse.hasWorld(CONFIG.getString("save_world"))) { + // Create save world. + if (!Multiverse.createVoidWorld(CONFIG.getString("save_world"))) { - LOGGER.warning("Failed to create save world!"); + LOGGER.warning("Failed to create save world!"); - } } - - LOGGER.info("Enabling Plugin"); - enablePlugin(); - - } else { - - // If the server is not in the database the network plugin was not successful. - LOGGER.severe("Server is not in database, check that the Network plugin is working correctly."); - } + + LOGGER.info("Enabling Plugin"); + enablePlugin(); } // Server enabling procedure when the config has been set up. public void enablePlugin() { + // Get the NetworkAPI. + RegisteredServiceProvider networkProvider = Bukkit.getServicesManager().getRegistration(NetworkAPI.class); + if (networkProvider == null) { + LOGGER.severe("Failed to get NetworkAPI, disabling plugin!"); + return; + } + final NetworkAPI networkAPI = networkProvider.getProvider(); + + this.guiManager = new GuiManager(); + this.plotHelper = new PlotHelper(); + // Register hologram click event. new HologramClickEvent(this); - // Initialise the plot helper. - PlotHelper.init(plotSQL); - // General Setup // Create list of users. users = new ArrayList<>(); - plotSQL.update("UPDATE plot_submission AS ps INNER JOIN plot_data AS pd ON ps.plot_id=pd.id SET ps.status='submitted' WHERE ps.status='under review' AND pd.location IN (SELECT name FROM location_data WHERE server='" + SERVER_NAME + "');"); - plotSQL.update("UPDATE plot_submission AS ps INNER JOIN plot_data AS pd ON ps.plot_id=pd.id SET ps.status='awaiting verification' WHERE ps.status='under verification' AND pd.location IN (SELECT name FROM location_data WHERE server='" + SERVER_NAME + "');"); + networkAPI.getPlotAPI().resetPlotSubmissions(SERVER_NAME); // Create gui item gui = new ItemStack(Material.NETHER_STAR); @@ -152,8 +149,7 @@ public void enablePlugin() { outlines = new Outlines(); // Setup Timers - timers = new Timers(this, globalSQL); - timers.startTimers(); + timers = new Timers(this, networkAPI); // Create bungeecord channel this.getServer().getMessenger().registerOutgoingPluginChannel(this, "BungeeCord"); @@ -165,11 +161,15 @@ public void enablePlugin() { selectionTool.setItemMeta(meta); // Listeners - new JoinServer(this, globalSQL, plotSQL); + new JoinServer(this, plotHelper); new QuitServer(this); new PlayerInteract(instance, plotSQL); new CloseInventory(this); + // Events + networkAPI.getEventAPI().registerEvent("claim", new ClaimEvent(networkAPI, guiManager)); + networkAPI.getEventAPI().registerEvent("close", new CloseEvent(networkAPI.getPlotAPI(), networkAPI.getChat())); + // Deals with tracking where players are in relation to plots. claimEnter = new ClaimEnter(this, plotSQL, globalSQL); diff --git a/src/main/java/net/bteuk/plotsystem/Timers.java b/src/main/java/net/bteuk/plotsystem/Timers.java index 44af4c4..25e36f3 100644 --- a/src/main/java/net/bteuk/plotsystem/Timers.java +++ b/src/main/java/net/bteuk/plotsystem/Timers.java @@ -1,91 +1,32 @@ package net.bteuk.plotsystem; -import com.sk89q.worldguard.WorldGuard; -import net.bteuk.network.sql.GlobalSQL; -import net.bteuk.plotsystem.events.EventManager; +import net.bteuk.network.api.NetworkAPI; +import net.bteuk.network.api.TimerAPI; import net.bteuk.plotsystem.utils.Inactive; import net.bteuk.plotsystem.utils.Outlines; import net.bteuk.plotsystem.utils.User; -import org.bukkit.Bukkit; import java.util.ArrayList; -import static net.bteuk.network.utils.Constants.LOGGER; - public class Timers { - - final WorldGuard wg; - // Plugin - private final PlotSystem instance; + private final TimerAPI timerAPI; // Users private final ArrayList users; - // Server name - private final String SERVER_NAME; - // SQL - private final GlobalSQL globalSQL; // Outlines. private final Outlines outlines; - // Server events - private ArrayList events; - private boolean isBusy = false; - - public Timers(PlotSystem instance, GlobalSQL globalSQL) { - this.instance = instance; + public Timers(PlotSystem instance, NetworkAPI networkAPI) { this.users = instance.getUsers(); - - this.globalSQL = globalSQL; - - SERVER_NAME = PlotSystem.SERVER_NAME; - - events = new ArrayList<>(); - - wg = WorldGuard.getInstance(); - + this.timerAPI = networkAPI.getTimerAPI(); outlines = instance.getOutlines(); - } public void startTimers() { - // 1 tick timer. - Bukkit.getScheduler().scheduleSyncRepeatingTask(instance, () -> { - - // Check for new server_events. - if (globalSQL.hasRow("SELECT uuid FROM server_events WHERE server='" + SERVER_NAME + "' AND type='plotsystem';")) { - - // If events is not empty, skip this iteration. - // Additionally isBusy needs to be false, implying that the server is not still running a previous iteration. - if (events.isEmpty() && !isBusy) { - - isBusy = true; - - // Get events for this server. - events = globalSQL.getEvents(SERVER_NAME, "plotsystem", events); - - for (String[] event : events) { - - // Deal with events here. - LOGGER.info("Event: " + event[1]); - - // Split the event by word. - String[] aEvent = event[1].split(" "); - - // Send the event to the event handler. - EventManager.event(event[0], aEvent); - - } - - // Clear events when done. - events.clear(); - isBusy = false; - } - } - }, 0L, 1L); - // 1 second timer. + // 1-second timer. // Update plot and zone outlines. - Bukkit.getScheduler().scheduleSyncRepeatingTask(instance, () -> { + timerAPI.registerTimer(() -> { for (User u : users) { @@ -120,11 +61,11 @@ public void startTimers() { } } - }, 0L, 20L); + }, 20L); - // 1 hour timer. + // 1-hour timer. // Remove inactive plots. - Bukkit.getScheduler().scheduleSyncRepeatingTask(instance, () -> { + timerAPI.registerTimer(() -> { Inactive.cancelInactivePlots(); Inactive.closeExpiredZones(); }, 1200L, 72000L); diff --git a/src/main/java/net/bteuk/plotsystem/commands/ClaimCommand.java b/src/main/java/net/bteuk/plotsystem/commands/ClaimCommand.java index df54b25..8025f7d 100644 --- a/src/main/java/net/bteuk/plotsystem/commands/ClaimCommand.java +++ b/src/main/java/net/bteuk/plotsystem/commands/ClaimCommand.java @@ -1,7 +1,10 @@ package net.bteuk.plotsystem.commands; +import io.papermc.paper.command.brigadier.BasicCommand; import io.papermc.paper.command.brigadier.CommandSourceStack; import net.bteuk.network.Network; +import net.bteuk.network.api.NetworkAPI; +import net.bteuk.network.api.PlotAPI; import net.bteuk.network.commands.AbstractCommand; import net.bteuk.network.lib.utils.ChatUtils; import net.bteuk.network.sql.PlotSQL; @@ -15,36 +18,35 @@ import net.kyori.adventure.text.format.NamedTextColor; import org.bukkit.entity.Player; -import static net.bteuk.network.utils.Constants.SERVER_NAME; -import static net.bteuk.network.utils.Constants.TUTORIALS; +import static net.bteuk.plotsystem.PlotSystem.SERVER_NAME; -public class ClaimCommand extends AbstractCommand { +public class ClaimCommand implements BasicCommand { public static final Component TUTORIAL_REQUIRED_MESSAGE = ChatUtils.error("To claim a plot you first complete the starter tutorial.") .append(ChatUtils.error(" Click here to open the tutorial menu!").clickEvent(ClickEvent.clickEvent(ClickEvent.Action.RUN_COMMAND, "/nav tutorials"))); - private final PlotSQL plotSQL; + private final PlotAPI plotAPI; - public ClaimCommand(PlotSQL plotSQL) { - this.plotSQL = plotSQL; + public ClaimCommand(NetworkAPI networkAPI) { + this.plotAPI = networkAPI.getPlotAPI(); } - public static boolean hasClaimPermission(User u, NetworkUser user, int plot) { + public static boolean hasClaimPermission(NetworkAPI networkAPI, Player player, int plot) { // Make sure the player has permission to claim plots, else they must complete the tutorial first. // Only checked if tutorials are enabled. - if (!(user.hasPermission("uknet.plots.claim.all") || user.hasPermission("uknet.plots.claim.easy")) && TUTORIALS) { - user.player.sendMessage(TUTORIAL_REQUIRED_MESSAGE); + if (!(player.hasPermission("uknet.plots.claim.all") || player.hasPermission("uknet.plots.claim.easy")) && networkAPI.isTutorialsEnabled()) { + player.sendMessage(TUTORIAL_REQUIRED_MESSAGE); return false; } // Check if the player has permission to claim a plot of this difficulty. - if (!user.hasPermission("uknet.plots.claim.all")) { + if (!player.hasPermission("uknet.plots.claim.all")) { switch (u.plotSQL.getInt("SELECT difficulty FROM plot_data WHERE id=" + plot + ";")) { case 1 -> { - if (!user.hasPermission("uknet.plots.claim.easy")) { - user.sendMessage(ChatUtils.error("You do not have permission to claim an ") + if (!player.hasPermission("uknet.plots.claim.easy")) { + player.sendMessage(ChatUtils.error("You do not have permission to claim an ") .append(Component.text("Easy", NamedTextColor.DARK_RED)) .append(ChatUtils.error(" plot."))); return false; @@ -52,8 +54,8 @@ public static boolean hasClaimPermission(User u, NetworkUser user, int plot) { } case 2 -> { - if (!user.hasPermission("uknet.plots.claim.normal")) { - user.sendMessage(ChatUtils.error("You do not have permission to claim a ") + if (!player.hasPermission("uknet.plots.claim.normal")) { + player.sendMessage(ChatUtils.error("You do not have permission to claim a ") .append(Component.text("Normal", NamedTextColor.DARK_RED)) .append(ChatUtils.error(" plot."))); return false; @@ -61,8 +63,8 @@ public static boolean hasClaimPermission(User u, NetworkUser user, int plot) { } case 3 -> { - if (!user.hasPermission("uknet.plots.claim.hard")) { - user.sendMessage(ChatUtils.error("You do not have permission to claim a ") + if (!player.hasPermission("uknet.plots.claim.hard")) { + player.sendMessage(ChatUtils.error("You do not have permission to claim a ") .append(Component.text("Hard", NamedTextColor.DARK_RED)) .append(ChatUtils.error(" plot."))); return false; @@ -126,17 +128,17 @@ public boolean validPlot(User u, int plot, boolean inPlot) { // If the plot is already claimed tell them. // If they are the owner or a member tell them. - if (plotSQL.hasRow("SELECT id FROM plot_members WHERE id=" + plot + " AND uuid='" + u.player.getUniqueId() + "' AND is_owner=1;")) { + if (plotAPI.isPlotOwner(u.inPlot, u.uuid)) { u.player.sendMessage(ChatUtils.error("You are already the owner of this plot!")); return false; - } else if (plotSQL.hasRow("SELECT id FROM plot_members WHERE id=" + plot + " AND uuid='" + u.player.getUniqueId() + "' AND is_owner=0;")) { + } else if (plotAPI.isPlotMember(u.inPlot, u.uuid)) { u.player.sendMessage(ChatUtils.error("You are already a member of this plot!")); return false; - } else if (plotSQL.hasRow("SELECT id FROM plot_data WHERE id=" + plot + " AND status='claimed';")) { + } else if (plotAPI.isPlotClaimed(u.inPlot)) { u.player.sendMessage(ChatUtils.error("This plot is already claimed!")); return false; @@ -144,7 +146,7 @@ public boolean validPlot(User u, int plot, boolean inPlot) { } // Check if you do not already have the maximum number of plots. - if (plotSQL.getInt("SELECT count(id) FROM plot_members WHERE uuid='" + u.uuid + "';") >= PlotSystem.getInstance().getConfig().getInt("plot_maximum")) { + if (plotAPI.getNumberOfPlots(u.uuid) >= PlotSystem.getInstance().getConfig().getInt("plot_maximum")) { u.player.sendMessage(ChatUtils.error("You have reached the maximum number of plots.")); return false; diff --git a/src/main/java/net/bteuk/plotsystem/events/ClaimEvent.java b/src/main/java/net/bteuk/plotsystem/events/ClaimEvent.java index 889004f..c36dde5 100644 --- a/src/main/java/net/bteuk/plotsystem/events/ClaimEvent.java +++ b/src/main/java/net/bteuk/plotsystem/events/ClaimEvent.java @@ -1,8 +1,10 @@ package net.bteuk.plotsystem.events; -import net.bteuk.network.Network; +import net.bteuk.minecraft.gui.GuiManager; +import net.bteuk.network.api.NetworkAPI; +import net.bteuk.network.api.PlotAPI; +import net.bteuk.network.api.entity.Event; import net.bteuk.network.lib.utils.ChatUtils; -import net.bteuk.network.utils.NetworkUser; import net.bteuk.plotsystem.PlotSystem; import net.bteuk.plotsystem.commands.ClaimCommand; import net.bteuk.plotsystem.gui.ClaimGui; @@ -12,13 +14,24 @@ import java.util.UUID; -import static net.bteuk.network.utils.Constants.TUTORIALS; import static net.bteuk.plotsystem.PlotSystem.LOGGER; import static net.bteuk.plotsystem.commands.ClaimCommand.TUTORIAL_REQUIRED_MESSAGE; -public class ClaimEvent { +public class ClaimEvent implements Event { - public static void event(String uuid, String[] event) { + private final NetworkAPI networkAPI; + + private final PlotAPI plotAPI; + + private final GuiManager guiManager; + + public ClaimEvent(NetworkAPI networkAPI, GuiManager guiManager) { + this.networkAPI = networkAPI; + this.plotAPI = networkAPI.getPlotAPI(); + this.guiManager = guiManager; + } + + public void event(String uuid, String[] event, String sMessage) { // Events for claiming if (event[1].equals("plot")) { @@ -35,7 +48,7 @@ public static void event(String uuid, String[] event) { // Make sure the player has permission to claim plots, else they must complete the tutorial first. // Only checked if tutorials are enabled. - if (!(p.hasPermission("uknet.plots.claim.all") || p.hasPermission("uknet.plots.claim.easy")) && TUTORIALS) { + if (!(p.hasPermission("uknet.plots.claim.all") || p.hasPermission("uknet.plots.claim.easy")) && networkAPI.isTutorialsEnabled()) { p.sendMessage(TUTORIAL_REQUIRED_MESSAGE); return; @@ -54,17 +67,17 @@ public static void event(String uuid, String[] event) { // If the plot is already claimed tell them. // If they are the owner or a member tell them. - if (u.plotSQL.hasRow("SELECT id FROM plot_members WHERE id=" + u.inPlot + " AND uuid='" + u.player.getUniqueId() + "' AND is_owner=1;")) { + if (plotAPI.isPlotOwner(u.inPlot, uuid)) { p.sendMessage(ChatUtils.error("You are already the owner of this plot!")); return; - } else if (u.plotSQL.hasRow("SELECT id FROM plot_members WHERE id=" + u.inPlot + " AND uuid='" + u.player.getUniqueId() + "' AND is_owner=0;")) { + } else if (plotAPI.isPlotMember(u.inPlot, uuid)) { p.sendMessage(ChatUtils.error("You are already a member of this plot!")); return; - } else if (u.plotSQL.hasRow("SELECT id FROM plot_data WHERE id=" + u.inPlot + " AND status='claimed';")) { + } else if (plotAPI.isPlotClaimed(u.inPlot)) { p.sendMessage(ChatUtils.error("This plot is already claimed!")); return; @@ -72,24 +85,21 @@ public static void event(String uuid, String[] event) { } // Check if you do not already have the maximum number of plots. - if (u.plotSQL.getInt("SELECT count(id) FROM plot_members WHERE uuid='" + uuid + "';") >= PlotSystem.getInstance().getConfig().getInt("plot_maximum")) { + if (plotAPI.getNumberOfPlots(uuid) >= PlotSystem.getInstance().getConfig().getInt("plot_maximum")) { p.sendMessage(ChatUtils.error("You have reached the maximum number of plots.")); return; } - // Open the claim gui. - NetworkUser user = Network.getInstance().getUser(u.player); - // Check if the player has permission to claim a plot of this difficulty. - if (!ClaimCommand.hasClaimPermission(u, user, u.inPlot)) { + if (!ClaimCommand.hasClaimPermission(networkAPI, p, u.inPlot)) { return; } u.player.closeInventory(); - u.claimGui = new ClaimGui(u, u.inPlot); - u.claimGui.open(user); + u.claimGui = new ClaimGui(u, u.inPlot, guiManager); + u.claimGui.open(p); } } diff --git a/src/main/java/net/bteuk/plotsystem/events/CloseEvent.java b/src/main/java/net/bteuk/plotsystem/events/CloseEvent.java index 6212047..ad20bf5 100644 --- a/src/main/java/net/bteuk/plotsystem/events/CloseEvent.java +++ b/src/main/java/net/bteuk/plotsystem/events/CloseEvent.java @@ -1,10 +1,11 @@ package net.bteuk.plotsystem.events; import com.sk89q.worldedit.math.BlockVector2; -import net.bteuk.network.Network; +import net.bteuk.network.api.ChatAPI; +import net.bteuk.network.api.PlotAPI; +import net.bteuk.network.api.entity.Event; import net.bteuk.network.lib.dto.DirectMessage; import net.bteuk.network.lib.utils.ChatUtils; -import net.bteuk.network.sql.PlotSQL; import net.bteuk.plotsystem.PlotSystem; import net.bteuk.plotsystem.exceptions.RegionManagerNotFoundException; import net.bteuk.plotsystem.exceptions.RegionNotFoundException; @@ -19,26 +20,34 @@ import static net.bteuk.plotsystem.PlotSystem.LOGGER; -public class CloseEvent { +public class CloseEvent implements Event { - public static void event(String uuid, String[] event) { + private final PlotAPI plotAPI; + + private final ChatAPI chatAPI; + + public CloseEvent(PlotAPI plotAPI, ChatAPI chatAPI) { + this.plotAPI = plotAPI; + this.chatAPI = chatAPI; + } + + public void event(String uuid, String[] event, String message) { // Event for save and closing. if (event[1].equals("zone")) { // PlotSQL - PlotSQL plotSQL = Network.getInstance().getPlotSQL(); FileConfiguration config = PlotSystem.getInstance().getConfig(); // Convert the string id to int id. int zone = Integer.parseInt(event[2]); // Get zone location. - String location = plotSQL.getString("SELECT location FROM zones WHERE id=" + zone + ";"); + String location = plotAPI.getZoneLocation(zone); // Check if the zone is on this server. - if (plotSQL.hasRow("SELECT name FROM location_data WHERE name='" + location + - "' AND server='" + PlotSystem.SERVER_NAME + "';")) { + String zoneServer = plotAPI.getLocationServer(location); + if (PlotSystem.SERVER_NAME.equals(zoneServer)) { // Get worlds of plot and save location. String save_world = config.getString("save_world"); @@ -52,8 +61,8 @@ public static void event(String uuid, String[] event) { assert (copyWorld != null); - int minusXTransform = -plotSQL.getInt("SELECT xTransform FROM location_data WHERE name='" + location + "';"); - int minusZTransform = -plotSQL.getInt("SELECT zTransform FROM location_data WHERE name='" + location + "';"); + int minusXTransform = -plotAPI.getXTransform(location); + int minusZTransform = -plotAPI.getZTransform(location); // Get the zone bounds. List copyVector; @@ -62,7 +71,7 @@ public static void event(String uuid, String[] event) { } catch (RegionManagerNotFoundException | RegionNotFoundException e) { DirectMessage directMessage = new DirectMessage("global", uuid, "server", ChatUtils.error("An error occurred while closing the zone, please contact an administrator."), false); - Network.getInstance().getChat().sendSocketMesage(directMessage); + chatAPI.sendDirectMessage(directMessage); return; } @@ -70,7 +79,7 @@ public static void event(String uuid, String[] event) { // The negative transform is used because the coordinates by default are transformed from the save to the paste world, which in this case it reversed. List pasteVector = new ArrayList<>(); for (BlockVector2 bv : copyVector) { - pasteVector.add(BlockVector2.at(bv.getX() + minusXTransform, bv.getZ() + minusZTransform)); + pasteVector.add(BlockVector2.at(bv.x() + minusXTransform, bv.z() + minusZTransform)); } Bukkit.getScheduler().runTaskAsynchronously(PlotSystem.getInstance(), () -> { @@ -83,20 +92,20 @@ public static void event(String uuid, String[] event) { } catch (RegionManagerNotFoundException e) { DirectMessage directMessage = new DirectMessage("global", uuid, "server", ChatUtils.error("An error occurred while closing the zone, please contact an administrator."), false); - Network.getInstance().getChat().sendSocketMesage(directMessage); + chatAPI.sendDirectMessage(directMessage); return; } // Remove all members of zone in database. - plotSQL.update("DELETE FROM zone_members WHERE id=" + zone + ";"); + plotAPI.clearZoneMembers(zone); // Set the zone status to closed. - plotSQL.update("UPDATE zones SET status='closed' WHERE id=" + zone + ";"); + plotAPI.setZoneStatus(zone, "closed"); - // Add message for the zone owner to the database to notify them that their zone was closed. + // Add a message for the zone owner to the database to notify them that their zone was closed. DirectMessage directMessage = new DirectMessage("global", uuid, "server", ChatUtils.success("Closed zone %s, its content has been saved.", String.valueOf(zone)), true); - Network.getInstance().getChat().sendSocketMesage(directMessage); + chatAPI.sendDirectMessage(directMessage); // Log plot removal to console. LOGGER.info("Zone " + zone + " has been closed."); diff --git a/src/main/java/net/bteuk/plotsystem/events/DeleteEvent.java b/src/main/java/net/bteuk/plotsystem/events/DeleteEvent.java index fa533b0..b29777b 100644 --- a/src/main/java/net/bteuk/plotsystem/events/DeleteEvent.java +++ b/src/main/java/net/bteuk/plotsystem/events/DeleteEvent.java @@ -1,12 +1,13 @@ package net.bteuk.plotsystem.events; import com.sk89q.worldedit.math.BlockVector2; -import net.bteuk.network.Network; +import net.bteuk.network.api.ChatAPI; +import net.bteuk.network.api.PlotAPI; +import net.bteuk.network.api.entity.Event; +import net.bteuk.network.api.plotsystem.PlotStatus; import net.bteuk.network.lib.dto.DirectMessage; import net.bteuk.network.lib.dto.PlotMessage; import net.bteuk.network.lib.utils.ChatUtils; -import net.bteuk.network.sql.PlotSQL; -import net.bteuk.network.utils.enums.PlotStatus; import net.bteuk.plotsystem.PlotSystem; import net.bteuk.plotsystem.exceptions.RegionManagerNotFoundException; import net.bteuk.plotsystem.exceptions.RegionNotFoundException; @@ -26,21 +27,30 @@ import static net.bteuk.plotsystem.PlotSystem.LOGGER; -public class DeleteEvent { +public class DeleteEvent implements Event { - public static void event(String uuid, String[] event) { + private final PlotAPI plotAPI; + + private final PlotHelper plotHelper; + + private final ChatAPI chatAPI; + + public DeleteEvent(PlotAPI plotAPI, PlotHelper plotHelper, ChatAPI chatAPI) { + this.plotAPI = plotAPI; + this.plotHelper = plotHelper; + this.chatAPI = chatAPI; + } + + public void event(String uuid, String[] event, String message) { // Events for deleting if (event[1].equals("plot")) { - // PlotSQL - PlotSQL plotSQL = Network.getInstance().getPlotSQL(); - // Convert the string id to int id. int id = Integer.parseInt(event[2]); // Get location which is the world. - String location = plotSQL.getString("SELECT location FROM plot_data WHERE id=" + id + ";"); + String location = plotAPI.getPlotLocation(id); // Get worlds of plot and save location. String save_world = PlotSystem.getInstance().getConfig().getString("save_world"); @@ -62,8 +72,8 @@ public static void event(String uuid, String[] event) { } - int minusXTransform = -plotSQL.getInt("SELECT xTransform FROM location_data WHERE name='" + location + "';"); - int minusZTransform = -plotSQL.getInt("SELECT zTransform FROM location_data WHERE name='" + location + "';"); + int minusXTransform = -plotAPI.getXTransform(location); + int minusZTransform = -plotAPI.getZTransform(location); // Get the plot bounds. List pasteVector; @@ -72,7 +82,7 @@ public static void event(String uuid, String[] event) { } catch (RegionNotFoundException | RegionManagerNotFoundException e) { DirectMessage directMessage = new DirectMessage("global", uuid, "server", ChatUtils.error("An error occurred while deleting the plot, please contact an administrator."), false); - Network.getInstance().getChat().sendSocketMesage(directMessage); + chatAPI.sendDirectMessage(directMessage); return; } @@ -80,7 +90,7 @@ public static void event(String uuid, String[] event) { // The negative transform is used because the coordinates by default are transformed from the save to the paste world, which in this case it reversed. List copyVector = new ArrayList<>(); for (BlockVector2 bv : pasteVector) { - copyVector.add(BlockVector2.at(bv.getX() + minusXTransform, bv.getZ() + minusZTransform)); + copyVector.add(BlockVector2.at(bv.x() + minusXTransform, bv.z() + minusZTransform)); } // Revert plot to original state. @@ -93,19 +103,19 @@ public static void event(String uuid, String[] event) { } catch (RegionNotFoundException | RegionManagerNotFoundException e) { DirectMessage directMessage = new DirectMessage("global", uuid, "server", ChatUtils.error("An error occurred while deleting the plot, please contact an administrator."), false); - Network.getInstance().getChat().sendSocketMesage(directMessage); + chatAPI.sendDirectMessage(directMessage); return; } // Remove all members of plot in database. - plotSQL.update("DELETE FROM plot_members WHERE id=" + id + ";"); + plotAPI.clearPlotMembers(id); // Remove the submitted plot if it is currently submitted. - plotSQL.update("DELETE FROM plot_submission WHERE plot_id=" + id + ";"); + plotAPI.removePlotSubmission(id); // Set plot status to unclaimed. PlotStatus currentStatus = PlotStatus.fromDatabaseValue(plotSQL.getString("SELECT status FROM plot_data WHERE id=" + id + ";")); - PlotHelper.updatePlotStatus(id, PlotStatus.UNCLAIMED); + plotHelper.updatePlotStatus(id, PlotStatus.UNCLAIMED); // Send message to plot owner. Player p = Bukkit.getPlayer(UUID.fromString(uuid)); @@ -121,7 +131,7 @@ public static void event(String uuid, String[] event) { DirectMessage directMessage = new DirectMessage("global", uuid, "server", ChatUtils.error("Plot %s deleted", String.valueOf(id)), true); - Network.getInstance().getChat().sendSocketMesage(directMessage); + chatAPI.sendDirectMessage(directMessage); } // If the plot was submitted, before deleting, send a message to reviewers letting them know it's no longer submitted. @@ -133,14 +143,11 @@ public static void event(String uuid, String[] event) { }); } else if (event[1].equals("zone")) { - // PlotSQL - PlotSQL plotSQL = Network.getInstance().getPlotSQL(); - // Convert the string id to int id. int id = Integer.parseInt(event[2]); - // Get location which is the world. - String location = plotSQL.getString("SELECT location FROM zones WHERE id=" + id + ";"); + // Get the location which is the world name. + String location = plotAPI.getZoneLocation(id); // Get worlds of plot and save location. String save_world = PlotSystem.getInstance().getConfig().getString("save_world"); @@ -161,8 +168,8 @@ public static void event(String uuid, String[] event) { } - int minusXTransform = -plotSQL.getInt("SELECT xTransform FROM location_data WHERE name='" + location + "';"); - int minusZTransform = -plotSQL.getInt("SELECT zTransform FROM location_data WHERE name='" + location + "';"); + int minusXTransform = -plotAPI.getXTransform(location); + int minusZTransform = -plotAPI.getZTransform(location); // Get the zone bounds. List pasteVector; @@ -171,7 +178,7 @@ public static void event(String uuid, String[] event) { } catch (RegionNotFoundException | RegionManagerNotFoundException e) { DirectMessage directMessage = new DirectMessage("global", uuid, "server", ChatUtils.error("An error occurred while deleting the zone, please contact an administrator."), false); - Network.getInstance().getChat().sendSocketMesage(directMessage); + chatAPI.sendDirectMessage(directMessage); return; } @@ -183,7 +190,7 @@ public static void event(String uuid, String[] event) { // The negative transform is used because the coordinates by default are transformed from the save to the paste world, which in this case it reversed. List copyVector = new ArrayList<>(); for (BlockVector2 bv : pasteVector) { - copyVector.add(BlockVector2.at(bv.getX() + minusXTransform, bv.getZ() + minusZTransform)); + copyVector.add(BlockVector2.at(bv.x() + minusXTransform, bv.z() + minusZTransform)); } // Revert zone to original state. @@ -196,19 +203,19 @@ public static void event(String uuid, String[] event) { } catch (RegionManagerNotFoundException e) { DirectMessage directMessage = new DirectMessage("global", uuid, "server", ChatUtils.error("An error occurred while deleting the zone, please contact an administrator."), false); - Network.getInstance().getChat().sendSocketMesage(directMessage); + chatAPI.sendDirectMessage(directMessage); return; } // Remove all members of zone in database. - plotSQL.update("DELETE FROM zone_members WHERE id=" + id + ";"); + plotAPI.clearZoneMembers(id); // Set zone status to closed. - plotSQL.update("UPDATE zones SET status='closed' WHERE id=" + id + ";"); + plotAPI.setZoneStatus(id, "closed"); DirectMessage directMessage = new DirectMessage("global", uuid, "server", ChatUtils.error("Zone %s deleted", String.valueOf(id)), true); - Network.getInstance().getChat().sendSocketMesage(directMessage); + chatAPI.sendDirectMessage(directMessage); }); } } diff --git a/src/main/java/net/bteuk/plotsystem/events/EventManager.java b/src/main/java/net/bteuk/plotsystem/events/EventManager.java index 10d57a3..c758d83 100644 --- a/src/main/java/net/bteuk/plotsystem/events/EventManager.java +++ b/src/main/java/net/bteuk/plotsystem/events/EventManager.java @@ -12,16 +12,14 @@ public static void event(String uuid, String[] event) { // Start the execution process by looking at the event message structure. switch (event[0]) { - case "teleport" -> TeleportEvent.event(uuid, event); + case "teleport" -> TeleportEvent.event(uuid, event); // TODO: also exists in Network case "submit" -> SubmitEvent.event(uuid, event); case "retract" -> RetractEvent.event(uuid, event); case "delete" -> DeleteEvent.event(uuid, event); case "leave" -> LeaveEvent.event(uuid, event); - case "claim" -> ClaimEvent.event(uuid, event); case "review" -> ReviewEvent.event(uuid, event); case "join" -> JoinEvent.event(uuid, event); - case "kick" -> KickEvent.event(uuid, event); - case "close" -> CloseEvent.event(uuid, event); + case "kick" -> KickEvent.event(uuid, event); // TODO: Also exists in Network case "outlines" -> OutlinesEvent.event(uuid, event); case "verify" -> VerifyEvent.event(uuid, event); } diff --git a/src/main/java/net/bteuk/plotsystem/gui/ClaimGui.java b/src/main/java/net/bteuk/plotsystem/gui/ClaimGui.java index 15a77f3..a1a7cab 100644 --- a/src/main/java/net/bteuk/plotsystem/gui/ClaimGui.java +++ b/src/main/java/net/bteuk/plotsystem/gui/ClaimGui.java @@ -1,24 +1,23 @@ package net.bteuk.plotsystem.gui; -import net.bteuk.network.gui.Gui; +import net.bteuk.minecraft.gui.Gui; +import net.bteuk.minecraft.gui.GuiManager; import net.bteuk.network.lib.utils.ChatUtils; -import net.bteuk.network.utils.Time; -import net.bteuk.network.utils.Utils; -import net.bteuk.network.utils.enums.PlotStatus; import net.bteuk.plotsystem.PlotSystem; import net.bteuk.plotsystem.exceptions.RegionManagerNotFoundException; import net.bteuk.plotsystem.exceptions.RegionNotFoundException; import net.bteuk.plotsystem.utils.PlotHelper; import net.bteuk.plotsystem.utils.PlotValues; import net.bteuk.plotsystem.utils.User; +import net.bteuk.plotsystem.utils.Utils; import net.bteuk.plotsystem.utils.plugins.WorldGuardFunctions; import net.buildtheearth.terraminusminus.generator.EarthGeneratorSettings; import net.buildtheearth.terraminusminus.projection.OutOfProjectionBoundsException; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.event.ClickEvent; import net.kyori.adventure.text.format.NamedTextColor; -import net.kyori.adventure.text.format.TextDecoration; import org.bukkit.Material; +import org.bukkit.entity.Player; import static net.bteuk.plotsystem.PlotSystem.LOGGER; @@ -28,15 +27,13 @@ public class ClaimGui extends Gui { private final int plot; - public ClaimGui(User user, int plot) { - - super(27, Component.text("Claim Plot", NamedTextColor.AQUA, TextDecoration.BOLD)); + public ClaimGui(User user, int plot, GuiManager guiManager) { + super(guiManager, 27, ChatUtils.title("Claim Plot")); this.user = user; this.plot = plot; createGui(); - } private void createGui() { @@ -52,11 +49,12 @@ private void createGui() { setItem(22, Utils.createItem(Material.ENDER_EYE, 1, ChatUtils.title("View Plot in Google Maps"), ChatUtils.line("Click to open a link to this plot in google maps.")), - u -> + clickEvent -> { + Player player = (Player) clickEvent.getWhoClicked(); - u.player.closeInventory(); + player.closeInventory(); // Get corners of the plot. int[][] corners = user.plotSQL.getPlotCorners(plot); @@ -84,7 +82,6 @@ private void createGui() { // Convert to irl coordinates. try { - final EarthGeneratorSettings bteGeneratorSettings = EarthGeneratorSettings.parse(EarthGeneratorSettings.BTE_DEFAULT_SETTINGS); double[] coords = bteGeneratorSettings.projection().toGeo(x, z); @@ -92,7 +89,7 @@ private void createGui() { Component message = ChatUtils.success("Click here to open the plot in Google Maps."); message = message.clickEvent(ClickEvent.clickEvent(ClickEvent.Action.OPEN_URL, "https://www.google.com/maps/@?api=1&map_action=map&basemap=satellite&zoom=21¢er=" + coords[1] + "," + coords[0])); - u.player.sendMessage(message); + player.sendMessage(message); } catch (OutOfProjectionBoundsException e) { e.printStackTrace(); diff --git a/src/main/java/net/bteuk/plotsystem/gui/CreatePlotGui.java b/src/main/java/net/bteuk/plotsystem/gui/CreatePlotGui.java index 01983e7..527d28e 100644 --- a/src/main/java/net/bteuk/plotsystem/gui/CreatePlotGui.java +++ b/src/main/java/net/bteuk/plotsystem/gui/CreatePlotGui.java @@ -1,9 +1,7 @@ package net.bteuk.plotsystem.gui; -import net.bteuk.network.gui.Gui; -import net.bteuk.network.lib.utils.ChatUtils; -import net.bteuk.network.utils.Utils; -import net.bteuk.plotsystem.PlotSystem; +import net.bteuk.minecraft.gui.Gui; +import net.bteuk.minecraft.gui.GuiManager; import net.bteuk.plotsystem.utils.PlotValues; import net.bteuk.plotsystem.utils.User; import net.kyori.adventure.text.Component; @@ -16,14 +14,13 @@ public class CreatePlotGui extends Gui { private final User user; // This gui handles the plot creation process, and will allow the user to set the parameters of the plot. - public CreatePlotGui(User user) { + public CreatePlotGui(GuiManager manager, User user) { - super(27, Component.text("Create Plot Menu", NamedTextColor.AQUA, TextDecoration.BOLD)); + super(manager, 27, Component.text("Create Plot Menu", NamedTextColor.AQUA, TextDecoration.BOLD)); this.user = user; createGui(); - } private void createGui() { @@ -116,9 +113,7 @@ private void createGui() { } public void refresh() { - - clearGui(); + this.clear(); createGui(); - } } diff --git a/src/main/java/net/bteuk/plotsystem/gui/CreateZoneGui.java b/src/main/java/net/bteuk/plotsystem/gui/CreateZoneGui.java index b581822..fc97d6a 100644 --- a/src/main/java/net/bteuk/plotsystem/gui/CreateZoneGui.java +++ b/src/main/java/net/bteuk/plotsystem/gui/CreateZoneGui.java @@ -1,10 +1,11 @@ package net.bteuk.plotsystem.gui; -import net.bteuk.network.gui.Gui; +import net.bteuk.minecraft.gui.Gui; +import net.bteuk.minecraft.gui.GuiManager; import net.bteuk.network.lib.utils.ChatUtils; -import net.bteuk.network.utils.Utils; import net.bteuk.plotsystem.PlotSystem; import net.bteuk.plotsystem.utils.User; +import net.bteuk.plotsystem.utils.Utils; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; import net.kyori.adventure.text.format.TextDecoration; @@ -15,9 +16,9 @@ public class CreateZoneGui extends Gui { private final User user; // This gui handles the plot creation process, and will allow the user to set the parameters of the plot. - public CreateZoneGui(User user) { + public CreateZoneGui(GuiManager manager, User user) { - super(27, Component.text("Create Plot Menu", NamedTextColor.AQUA, TextDecoration.BOLD)); + super(manager, 27, Component.text("Create Plot Menu", NamedTextColor.AQUA, TextDecoration.BOLD)); this.user = user; @@ -46,24 +47,20 @@ private void createGui() { }); // Set public/private. - if (user.selectionTool.is_public) { + if (user.selectionTool.isPublic) { setItem(11, Utils.createItem(Material.OAK_DOOR, 1, ChatUtils.title("Set the zone to private."), ChatUtils.line("Click to make the zone private."), ChatUtils.line("A private zone means the owner has"), ChatUtils.line("to invite members for them to build.")), - u -> - - { - + u -> { // Set private. - user.selectionTool.is_public = false; + user.selectionTool.isPublic = false; // Refresh the gui. refresh(); - user.player.getOpenInventory().getTopInventory().setContents(getInventory().getContents()); - + this.updatePlayerInventory(user.player); }); } else { @@ -73,19 +70,14 @@ private void createGui() { ChatUtils.line("Click to make the zone public."), ChatUtils.line("A public zone allows JrBuilder+"), ChatUtils.line("to join without having to request.")), - u -> - - { - + u -> { // Set private. - user.selectionTool.is_public = true; + user.selectionTool.isPublic = true; // Refresh the gui. refresh(); - user.player.getOpenInventory().getTopInventory().setContents(getInventory().getContents()); - + this.updatePlayerInventory(user.player); }); - } // Set expiration time. @@ -108,7 +100,7 @@ private void createGui() { // Refresh the gui. refresh(); - user.player.getOpenInventory().getTopInventory().setContents(getInventory().getContents()); + this.updatePlayerInventory(user.player); }); @@ -124,9 +116,7 @@ private void createGui() { } public void refresh() { - - clearGui(); + this.clear(); createGui(); - } } diff --git a/src/main/java/net/bteuk/plotsystem/listeners/HologramClickEvent.java b/src/main/java/net/bteuk/plotsystem/listeners/HologramClickEvent.java index 6af5bd6..2da19b2 100644 --- a/src/main/java/net/bteuk/plotsystem/listeners/HologramClickEvent.java +++ b/src/main/java/net/bteuk/plotsystem/listeners/HologramClickEvent.java @@ -1,6 +1,6 @@ package net.bteuk.plotsystem.listeners; -import net.bteuk.network.utils.enums.PlotStatus; +import net.bteuk.network.api.plotsystem.PlotStatus; import net.bteuk.plotsystem.PlotSystem; import net.bteuk.plotsystem.utils.ParseUtils; import org.bukkit.Bukkit; diff --git a/src/main/java/net/bteuk/plotsystem/listeners/JoinServer.java b/src/main/java/net/bteuk/plotsystem/listeners/JoinServer.java index e87431c..fe4ba8e 100644 --- a/src/main/java/net/bteuk/plotsystem/listeners/JoinServer.java +++ b/src/main/java/net/bteuk/plotsystem/listeners/JoinServer.java @@ -1,14 +1,10 @@ package net.bteuk.plotsystem.listeners; -import net.bteuk.network.sql.GlobalSQL; -import net.bteuk.network.sql.PlotSQL; import net.bteuk.plotsystem.PlotSystem; -import net.bteuk.plotsystem.events.EventManager; import net.bteuk.plotsystem.utils.PlotHelper; import net.bteuk.plotsystem.utils.User; import org.bukkit.Bukkit; import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; @@ -20,50 +16,23 @@ an alternative server which does have a tutorial. */ public class JoinServer implements Listener { - - private final GlobalSQL globalSQL; - private final PlotSQL plotSQL; private final PlotSystem instance; - public JoinServer(PlotSystem plugin, GlobalSQL globalSQL, PlotSQL plotSQL) { + private final PlotHelper plotHelper; + public JoinServer(PlotSystem plugin, PlotHelper plotHelper) { Bukkit.getServer().getPluginManager().registerEvents(this, plugin); this.instance = plugin; - this.globalSQL = globalSQL; - this.plotSQL = plotSQL; - + this.plotHelper = plotHelper; } - // Must run last. - @EventHandler(priority = EventPriority.HIGH) + @EventHandler public void joinEvent(PlayerJoinEvent e) { - // Create instance of User and add it to list. - User u = new User(e.getPlayer(), globalSQL, plotSQL); + User u = new User(e.getPlayer()); instance.addUser(u); // Add the player to relevant holograms. - PlotHelper.addPlayer(e.getPlayer()); - - // If the player has a join event, execute it. - // Delay by 1 second for all plugins to run their join events. - Bukkit.getScheduler().scheduleSyncDelayedTask(instance, () -> { - if (globalSQL.hasRow("SELECT uuid FROM join_events WHERE uuid='" + u.player.getUniqueId() + "' AND type='plotsystem';")) { - - // Get the event from the database. - String event = globalSQL.getString("SELECT event FROM join_events WHERE uuid='" + u.player.getUniqueId() + "' AND type='plotsystem'"); - - // Split the event by word. - String[] aEvent = event.split(" "); - - // Send the event to the event handler. - EventManager.event(u.uuid, aEvent); - - // Clear the events. - globalSQL.update("DELETE FROM join_events WHERE uuid='" + u.player.getUniqueId() + "' AND type='plotsystem';"); - - } - }, 20L); - + plotHelper.addPlayer(e.getPlayer()); } } diff --git a/src/main/java/net/bteuk/plotsystem/utils/PlotHelper.java b/src/main/java/net/bteuk/plotsystem/utils/PlotHelper.java index 89c4a47..93e757f 100644 --- a/src/main/java/net/bteuk/plotsystem/utils/PlotHelper.java +++ b/src/main/java/net/bteuk/plotsystem/utils/PlotHelper.java @@ -1,12 +1,11 @@ package net.bteuk.plotsystem.utils; import lombok.Setter; +import net.bteuk.network.api.plotsystem.PlotStatus; +import net.bteuk.network.api.plotsystem.ReviewCategory; +import net.bteuk.network.api.plotsystem.ReviewSelection; +import net.bteuk.network.api.plotsystem.SubmittedStatus; import net.bteuk.network.lib.enums.PlotDifficulties; -import net.bteuk.network.sql.PlotSQL; -import net.bteuk.network.utils.enums.PlotStatus; -import net.bteuk.network.utils.enums.SubmittedStatus; -import net.bteuk.network.utils.plotsystem.ReviewCategory; -import net.bteuk.network.utils.plotsystem.ReviewSelection; import net.bteuk.plotsystem.PlotSystem; import org.bukkit.Bukkit; import org.bukkit.configuration.ConfigurationSection; @@ -27,21 +26,9 @@ public class PlotHelper { @Setter - private static PlotSQL plotSQL; + private List holograms = new ArrayList<>(); - @Setter - private static List holograms = new ArrayList<>(); - - private static Map REVIEW_CATEGORY_THRESHOLDS; - - /** - * Initialise the plot helper by setting the relevant variables. - * - * @param plotSQL {@link PlotSQL} - */ - public static void init(PlotSQL plotSQL) { - setPlotSQL(plotSQL); - } + private Map REVIEW_CATEGORY_THRESHOLDS; /** * Update the submitted status of a plot, will update any relevant holograms. @@ -49,7 +36,7 @@ public static void init(PlotSQL plotSQL) { * @param id the plot id * @param submittedStatus the submitted status */ - public static boolean updateSubmittedStatus(int id, SubmittedStatus submittedStatus) { + public boolean updateSubmittedStatus(int id, SubmittedStatus submittedStatus) { return updatePlotStatus(id, PlotStatus.SUBMITTED, submittedStatus); } @@ -59,7 +46,7 @@ public static boolean updateSubmittedStatus(int id, SubmittedStatus submittedSta * @param id the plot id * @param plotStatus the plot status */ - public static boolean updatePlotStatus(int id, PlotStatus plotStatus) { + public boolean updatePlotStatus(int id, PlotStatus plotStatus) { SubmittedStatus submittedStatus = null; if (plotStatus == PlotStatus.SUBMITTED) { submittedStatus = SubmittedStatus.SUBMITTED; @@ -74,7 +61,7 @@ public static boolean updatePlotStatus(int id, PlotStatus plotStatus) { * @param status the plot status * @param submittedStatus the submitted status of the plot, if status is submitted */ - private static boolean updatePlotStatus(int id, PlotStatus status, SubmittedStatus submittedStatus) { + private boolean updatePlotStatus(int id, PlotStatus status, SubmittedStatus submittedStatus) { boolean hasChanged = false; if (!plotSQL.hasRow("SELECT 1 FROM plot_data WHERE id=" + id + " AND status='" + status.database_value + "'")) { plotSQL.update("UPDATE plot_data SET status='" + status.database_value + "' WHERE id=" + id + ";"); @@ -104,23 +91,23 @@ private static boolean updatePlotStatus(int id, PlotStatus status, SubmittedStat return hasChanged; } - public static void addPlotHologram(PlotHologram plotHologram) { + public void addPlotHologram(PlotHologram plotHologram) { holograms.add(plotHologram); } - public static void updatePlotHologram(int plot) { + public void updatePlotHologram(int plot) { holograms.stream().filter(plotHologram -> plotHologram.getPlot() == plot).forEach(PlotHologram::updateLocation); } - public static void addPlayer(Player player) { + public void addPlayer(Player player) { holograms.forEach(hologram -> hologram.setHologramVisibilityForPlayer(player)); } - public static ReviewSelection getReviewCategoryThreshold(PlotDifficulties difficulty, ReviewCategory category) { + public ReviewSelection getReviewCategoryThreshold(PlotDifficulties difficulty, ReviewCategory category) { return REVIEW_CATEGORY_THRESHOLDS.get(difficulty).getThreshold(category); } - public static boolean reviewCategoryThresholdReached(PlotDifficulties difficulty, ReviewCategory category, ReviewSelection selection) { + public boolean reviewCategoryThresholdReached(PlotDifficulties difficulty, ReviewCategory category, ReviewSelection selection) { if (REVIEW_CATEGORY_THRESHOLDS == null) { loadReviewCategoryThresholds(); } @@ -133,7 +120,7 @@ public static boolean reviewCategoryThresholdReached(PlotDifficulties difficulty }; } - private static void loadReviewCategoryThresholds() { + private void loadReviewCategoryThresholds() { ConfigurationSection categories = CONFIG.getConfigurationSection("categories"); REVIEW_CATEGORY_THRESHOLDS = new HashMap<>(); for (PlotDifficulties difficulty : PlotDifficulties.values()) { diff --git a/src/main/java/net/bteuk/plotsystem/utils/SelectionTool.java b/src/main/java/net/bteuk/plotsystem/utils/SelectionTool.java index 4a64d43..b030093 100644 --- a/src/main/java/net/bteuk/plotsystem/utils/SelectionTool.java +++ b/src/main/java/net/bteuk/plotsystem/utils/SelectionTool.java @@ -1,9 +1,9 @@ package net.bteuk.plotsystem.utils; import com.sk89q.worldedit.math.BlockVector2; +import net.bteuk.network.api.CoordinateAPI; +import net.bteuk.network.api.PlotAPI; import net.bteuk.network.lib.utils.ChatUtils; -import net.bteuk.network.sql.PlotSQL; -import net.bteuk.network.utils.Time; import net.bteuk.plotsystem.PlotSystem; import net.bteuk.plotsystem.utils.plugins.WGCreatePlot; import net.kyori.adventure.text.Component; @@ -16,6 +16,7 @@ import org.bukkit.inventory.PlayerInventory; import java.util.ArrayList; +import java.util.Objects; public class SelectionTool extends WGCreatePlot { @@ -27,19 +28,20 @@ public class SelectionTool extends WGCreatePlot { private final User u; // This vector of BlockVector2 (2d points (x,z)) represent the selected points. private final ArrayList vector; - // PlotSQL - private final PlotSQL plotSQL; // Outlines private final Outlines outlines; + + private final PlotAPI plotAPI; // Size and difficulty of the plot. // Represented by integer values of 1-3. // Size: 1=small, 2=medium, 3=large // Difficulty: 1=easy, 2=normal, 3=hard public int size; public int difficulty; + // Zones settings. public int hours; - public boolean is_public; + public boolean isPublic; // The world where the selection is being made. private World world; // The location (plot system location) where the plot is. @@ -47,22 +49,20 @@ public class SelectionTool extends WGCreatePlot { // Area of the plot (m^2). private int area; - // Constructor, sets up the basics of the selection tool, including default values fo size and difficulty. - public SelectionTool(User u, PlotSQL plotSQL) { - + public SelectionTool(User u, PlotAPI plotAPI, PlotHelper plotHelper, CoordinateAPI coordinateAPI) { + super(plotAPI, plotHelper, coordinateAPI); this.u = u; + this.plotAPI = plotAPI; vector = new ArrayList<>(); - this.plotSQL = plotSQL; // Set default size and difficulty size = 1; difficulty = 1; hours = 2; - is_public = false; + isPublic = false; outlines = PlotSystem.getInstance().getOutlines(); - } // Clear the selection. @@ -76,7 +76,7 @@ public void clear() { difficulty = 1; hours = 2; - is_public = false; + isPublic = false; // Remove outline blocks based on the previous selection. clearOutlines(); @@ -214,11 +214,11 @@ public void area() { if (i == (size() - 1)) { - sum += (((vector.get(i).getZ() + vector.getFirst().getZ()) / 2) * (vector.getFirst().getX() - vector.get(i).getX())); + sum += (((vector.get(i).z() + vector.getFirst().z()) / 2) * (vector.getFirst().x() - vector.get(i).x())); } else { - sum += (((vector.get(i).getZ() + vector.get(i + 1).getZ()) / 2) * (vector.get(i + 1).getX() - vector.get(i).getX())); + sum += (((vector.get(i).z() + vector.get(i + 1).z()) / 2) * (vector.get(i + 1).x() - vector.get(i).x())); } } @@ -250,16 +250,15 @@ public void setDefaultSize() { public void createPlot() { // Create the plot. - if (createPlot(u.player, world, location, vector, plotSQL, size, difficulty)) { + if (createPlot(u.player, world, location, vector, size, difficulty)) { - int xTransform = plotSQL.getInt("SELECT xTransform FROM location_data WHERE name='" + location + "';"); - int zTransform = plotSQL.getInt("SELECT zTransform FROM location_data WHERE name='" + location + "';"); + int xTransform = plotAPI.getXTransform(location); + int zTransform = plotAPI.getZTransform(location); // Store the plot corners with coordinate transform. int i = 1; for (BlockVector2 point : vector) { - plotSQL.update("INSERT INTO plot_corners(id,corner,x,z) VALUES(" + - plotID + "," + i + "," + (point.getX() - xTransform) + "," + (point.getZ() - zTransform) + ");"); + plotAPI.createPlotCorner(plotID, i, (point.x() - xTransform), (point.z() - zTransform)); i++; } @@ -267,9 +266,9 @@ public void createPlot() { u.player.sendMessage(ChatUtils.success("Plot created with ID ") .append(Component.text(plotID, NamedTextColor.DARK_AQUA)) .append(ChatUtils.success(", difficulty ")) - .append(Component.text(PlotValues.difficultyName(difficulty), NamedTextColor.DARK_AQUA)) + .append(Component.text(Objects.requireNonNull(PlotValues.difficultyName(difficulty)), NamedTextColor.DARK_AQUA)) .append(ChatUtils.success(" and size ")) - .append(Component.text(PlotValues.sizeName(size), NamedTextColor.DARK_AQUA))); + .append(Component.text(Objects.requireNonNull(PlotValues.sizeName(size)), NamedTextColor.DARK_AQUA))); PlotSystem.LOGGER.info("Plot created with ID " + plotID + ", difficulty " + PlotValues.difficultyName(difficulty) + " and size " + PlotValues.sizeName(size)); @@ -287,32 +286,29 @@ public void createPlot() { // This will make sure public/private and expiration time has been set. public void createZone() { - long expiration = Time.currentTime() + (hours * 1000L * 60L * 60L); + long expiration = System.currentTimeMillis() + (hours * 1000L * 60L * 60L); // Create the zone. - if (createZone(u.player, world, location, vector, plotSQL, expiration, is_public)) { + if (createZone(u.player, world, location, vector, expiration, isPublic)) { // Add owner. - plotSQL.update("INSERT INTO zone_members(id,uuid,is_owner) VALUES(" + plotID + ",'" + u.player.getUniqueId() + "',1);"); + plotAPI.createZoneMember(plotID, u.player.getUniqueId().toString()); // Store zone bounds. int i = 1; for (BlockVector2 point : vector) { - - plotSQL.update("INSERT INTO zone_corners(id,corner,x,z) VALUES(" + - plotID + "," + i + "," + point.getX() + "," + point.getZ() + ");"); + plotAPI.createZoneCorner(plotID, i, point.x(), point.z()); i++; - } // Send feedback. u.player.sendMessage(ChatUtils.success("Zone created with ID ") .append(Component.text(plotID, NamedTextColor.DARK_AQUA)) .append(ChatUtils.success(", it will expire at ")) - .append(Component.text(Time.getDateTime(expiration), NamedTextColor.DARK_AQUA)) + .append(Component.text(Utils.getDateTime(expiration), NamedTextColor.DARK_AQUA)) .append(ChatUtils.success(", this can be extended in the Zone Menu."))); PlotSystem.LOGGER.info("Zone created with ID " + plotID + - ", it will expire at " + Time.getDateTime(expiration)); + ", it will expire at " + Utils.getDateTime(expiration)); // Clear previous blocks. clearOutlines(); diff --git a/src/main/java/net/bteuk/plotsystem/utils/User.java b/src/main/java/net/bteuk/plotsystem/utils/User.java index f2b64c3..2aacc02 100644 --- a/src/main/java/net/bteuk/plotsystem/utils/User.java +++ b/src/main/java/net/bteuk/plotsystem/utils/User.java @@ -2,8 +2,6 @@ import lombok.Getter; import lombok.Setter; -import net.bteuk.network.sql.GlobalSQL; -import net.bteuk.network.sql.PlotSQL; import net.bteuk.plotsystem.PlotSystem; import net.bteuk.plotsystem.gui.ClaimGui; import net.bteuk.plotsystem.gui.CreatePlotGui; @@ -23,8 +21,7 @@ public class User { public final String name; public final SelectionTool selectionTool; - public final GlobalSQL globalSQL; - public final PlotSQL plotSQL; + // Skip outlines for these plots. @Getter private final List skipOutlines = new ArrayList<>(); @@ -45,11 +42,7 @@ public class User { @Setter private boolean disableOutlines; - public User(Player player, GlobalSQL globalSQL, PlotSQL plotSQL) { - - // Set sql - this.globalSQL = globalSQL; - this.plotSQL = plotSQL; + public User(Player player) { // Set player, uuid and name variable. this.player = player; @@ -57,7 +50,7 @@ public User(Player player, GlobalSQL globalSQL, PlotSQL plotSQL) { name = player.getName(); // Set selection tool, only players with the valid roles can use it. - selectionTool = new SelectionTool(this, plotSQL); + selectionTool = new SelectionTool(this); // Set last location to current location. lastLocation = player.getLocation(); diff --git a/src/main/java/net/bteuk/plotsystem/utils/Utils.java b/src/main/java/net/bteuk/plotsystem/utils/Utils.java new file mode 100644 index 0000000..f7c7148 --- /dev/null +++ b/src/main/java/net/bteuk/plotsystem/utils/Utils.java @@ -0,0 +1,46 @@ +package net.bteuk.plotsystem.utils; + +import net.kyori.adventure.text.Component; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.sql.Date; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.TimeZone; + +public class Utils { + public static ItemStack createItem(Material material, int amount, Component displayName, Component... loreString) { + + ItemStack item = ItemStack.of(material.isItem() ? material : Material.STRUCTURE_VOID); + item.setAmount(amount); + + ItemMeta meta = item.getItemMeta(); + meta.displayName(displayName); + List lore = new ArrayList<>(Arrays.asList(loreString)); + meta.lore(lore); + item.setItemMeta(meta); + + return item; + } + + // Converts milliseconds to date. + public static String getDate(long time) { + + SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); + formatter.setTimeZone(TimeZone.getTimeZone("Europe/London")); + Date date = new Date(time); + return formatter.format(date); + } + + // Converts milliseconds to datetime. + public static String getDateTime(long time) { + SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm Z"); + formatter.setTimeZone(TimeZone.getTimeZone("Europe/London")); + Date date = new Date(time); + return formatter.format(date); + } +} diff --git a/src/main/java/net/bteuk/plotsystem/utils/plugins/WGCreatePlot.java b/src/main/java/net/bteuk/plotsystem/utils/plugins/WGCreatePlot.java index 589e7de..82a234a 100644 --- a/src/main/java/net/bteuk/plotsystem/utils/plugins/WGCreatePlot.java +++ b/src/main/java/net/bteuk/plotsystem/utils/plugins/WGCreatePlot.java @@ -7,9 +7,10 @@ import com.sk89q.worldguard.protection.managers.RegionManager; import com.sk89q.worldguard.protection.managers.storage.StorageException; import com.sk89q.worldguard.protection.regions.ProtectedPolygonalRegion; -import net.bteuk.network.Network; +import net.bteuk.network.api.CoordinateAPI; +import net.bteuk.network.api.PlotAPI; import net.bteuk.network.lib.utils.ChatUtils; -import net.bteuk.network.sql.PlotSQL; +import net.bteuk.network.papercore.LocationAdapter; import net.bteuk.plotsystem.utils.PlotHelper; import net.bteuk.plotsystem.utils.PlotHologram; import org.bukkit.Location; @@ -18,22 +19,28 @@ import java.util.List; -import static net.bteuk.network.utils.Constants.MAX_Y; -import static net.bteuk.network.utils.Constants.MIN_Y; - /* This class adds the implementation of plot creation using worldguard. */ public class WGCreatePlot { + protected final PlotAPI plotAPI; + + private final PlotHelper plotHelper; + + private final CoordinateAPI coordinateAPI; + public int plotID; // Create a new instance of plots. - public WGCreatePlot() { + public WGCreatePlot(PlotAPI plotAPI, PlotHelper plotHelper, CoordinateAPI coordinateAPI) { + this.plotAPI = plotAPI; + this.plotHelper = plotHelper; + this.coordinateAPI = coordinateAPI; } // Create a plot with the current selection. - public boolean createPlot(Player p, World world, String location, List vector, PlotSQL plotSQL, int size, int difficulty) { + public boolean createPlot(Player p, World world, String location, List vector, int size, int difficulty) { // Get instance of WorldGuard. WorldGuard wg = WorldGuard.getInstance(); @@ -63,17 +70,17 @@ public boolean createPlot(Player p, World world, String location, List vector, PlotSQL plotSQL, long expiration, boolean is_public) { + public boolean createZone(Player p, World world, String location, List vector, long expiration, boolean isPublic) { // Get instance of WorldGuard. WorldGuard wg = WorldGuard.getInstance(); @@ -119,7 +126,7 @@ public boolean createZone(Player p, World world, String location, List Date: Mon, 27 Oct 2025 22:36:31 +0100 Subject: [PATCH 09/21] Progress with updating to Network API. --- pom.xml | 2 +- .../java/net/bteuk/plotsystem/PlotSystem.java | 17 ++- .../plotsystem/commands/ClaimCommand.java | 49 +++---- .../plotsystem/commands/CreateCommand.java | 71 +++++------ .../plotsystem/commands/DeleteCommand.java | 24 ++-- .../plotsystem/commands/LocationCommand.java | 67 +++++----- .../commands/PlotSystemCommand.java | 86 +++++++++---- .../plotsystem/commands/ReviewCommand.java | 15 +-- .../plotsystem/commands/ToggleOutlines.java | 9 +- .../plotsystem/commands/UpdateCommand.java | 19 ++- .../net/bteuk/plotsystem/gui/ClaimGui.java | 120 +++++++++--------- .../bteuk/plotsystem/gui/CreatePlotGui.java | 47 ++++--- .../bteuk/plotsystem/gui/CreateZoneGui.java | 19 ++- .../plotsystem/listeners/ClaimEnter.java | 58 ++++----- .../plotsystem/listeners/PlayerInteract.java | 22 ++-- .../plotsystem/reviewing/ReviewBook.java | 35 ++--- .../plotsystem/utils/plugins/Multiverse.java | 5 +- .../utils/plugins/WGCreatePlot.java | 8 +- 18 files changed, 338 insertions(+), 335 deletions(-) diff --git a/pom.xml b/pom.xml index 5758146..7d3b8cb 100644 --- a/pom.xml +++ b/pom.xml @@ -17,7 +17,7 @@ 1.21.8-R0.1-SNAPSHOT - fae3957ca2 + faa7ec07b2 5958727df9 5.3.3 diff --git a/src/main/java/net/bteuk/plotsystem/PlotSystem.java b/src/main/java/net/bteuk/plotsystem/PlotSystem.java index 6bb84ab..0e0397c 100644 --- a/src/main/java/net/bteuk/plotsystem/PlotSystem.java +++ b/src/main/java/net/bteuk/plotsystem/PlotSystem.java @@ -35,6 +35,7 @@ import org.bukkit.plugin.Plugin; import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.plugin.java.JavaPlugin; +import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; @@ -163,7 +164,7 @@ public void enablePlugin() { // Listeners new JoinServer(this, plotHelper); new QuitServer(this); - new PlayerInteract(instance, plotSQL); + new PlayerInteract(instance, networkAPI.getPlotAPI()); new CloseInventory(this); // Events @@ -171,25 +172,23 @@ public void enablePlugin() { networkAPI.getEventAPI().registerEvent("close", new CloseEvent(networkAPI.getPlotAPI(), networkAPI.getChat())); // Deals with tracking where players are in relation to plots. - claimEnter = new ClaimEnter(this, plotSQL, globalSQL); + claimEnter = new ClaimEnter(this, networkAPI.getPlotAPI(), networkAPI.getGlobalSQL()); // Commands - LifecycleEventManager manager = instance.getLifecycleManager(); + LifecycleEventManager<@NotNull Plugin> manager = instance.getLifecycleManager(); manager.registerEventHandler(LifecycleEvents.COMMANDS, event -> { final Commands commands = event.registrar(); - commands.register("plotsystem", "Deals will all plotsystem related commands.", List.of("ps"), new PlotSystemCommand(globalSQL, plotSQL)); - commands.register("claim", "Used to claim the plot you're standing in.", List.of("claim"), new ClaimCommand(plotSQL)); + commands.register("plotsystem", "Deals will all plotsystem related commands.", List.of("ps"), new PlotSystemCommand(networkAPI.getPlotAPI(), plotHelper, networkAPI.getCoordinateAPI(), guiManager)); + commands.register("claim", "Used to claim the plot you're standing in.", List.of("claim"), new ClaimCommand(networkAPI, guiManager, plotHelper)); commands.register("toggleoutlines", "Toggles the visibility of outlines.", new ToggleOutlines(this)); commands.register("review", "Command for editing selections to reviewing categories during the reviewing process.", new ReviewCommand(this)); }); // Get all active plots (unclaimed, claimed, submitted, reviewing) and add holograms. - List active_plots = plotSQL.getIntList( - "SELECT pd.id FROM plot_data AS pd INNER JOIN location_data AS ld ON ld.name=pd.location WHERE pd.status IN ('unclaimed','claimed','submitted') AND " + - "ld.server='" + SERVER_NAME + "';"); - active_plots.forEach(plot -> PlotHelper.addPlotHologram(new PlotHologram(plot))); + List active_plots = networkAPI.getPlotAPI().getActivePlots(SERVER_NAME); + active_plots.forEach(plot -> plotHelper.addPlotHologram(new PlotHologram(plot))); } public void onDisable() { diff --git a/src/main/java/net/bteuk/plotsystem/commands/ClaimCommand.java b/src/main/java/net/bteuk/plotsystem/commands/ClaimCommand.java index 8025f7d..39d58f5 100644 --- a/src/main/java/net/bteuk/plotsystem/commands/ClaimCommand.java +++ b/src/main/java/net/bteuk/plotsystem/commands/ClaimCommand.java @@ -2,21 +2,20 @@ import io.papermc.paper.command.brigadier.BasicCommand; import io.papermc.paper.command.brigadier.CommandSourceStack; -import net.bteuk.network.Network; +import net.bteuk.minecraft.gui.GuiManager; import net.bteuk.network.api.NetworkAPI; import net.bteuk.network.api.PlotAPI; -import net.bteuk.network.commands.AbstractCommand; import net.bteuk.network.lib.utils.ChatUtils; -import net.bteuk.network.sql.PlotSQL; -import net.bteuk.network.utils.NetworkUser; import net.bteuk.plotsystem.PlotSystem; import net.bteuk.plotsystem.gui.ClaimGui; import net.bteuk.plotsystem.utils.ParseUtils; +import net.bteuk.plotsystem.utils.PlotHelper; import net.bteuk.plotsystem.utils.User; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.event.ClickEvent; import net.kyori.adventure.text.format.NamedTextColor; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; import static net.bteuk.plotsystem.PlotSystem.SERVER_NAME; @@ -24,14 +23,24 @@ public class ClaimCommand implements BasicCommand { public static final Component TUTORIAL_REQUIRED_MESSAGE = ChatUtils.error("To claim a plot you first complete the starter tutorial.") - .append(ChatUtils.error(" Click here to open the tutorial menu!").clickEvent(ClickEvent.clickEvent(ClickEvent.Action.RUN_COMMAND, "/nav tutorials"))); + .append(ChatUtils.error(" Click here to open the tutorial menu!").clickEvent(ClickEvent.runCommand("/nav tutorials"))); + + private final NetworkAPI networkAPI; + private final PlotAPI plotAPI; - public ClaimCommand(NetworkAPI networkAPI) { + private final GuiManager guiManager; + + private final PlotHelper plotHelper; + + public ClaimCommand(NetworkAPI networkAPI, GuiManager guiManager, PlotHelper plotHelper) { + this.networkAPI = networkAPI; this.plotAPI = networkAPI.getPlotAPI(); + this.guiManager = guiManager; + this.plotHelper = plotHelper; } - public static boolean hasClaimPermission(NetworkAPI networkAPI, Player player, int plot) { + public static boolean hasClaimPermission(NetworkAPI networkAPI, Player player, PlotAPI plotAPI, int plot) { // Make sure the player has permission to claim plots, else they must complete the tutorial first. // Only checked if tutorials are enabled. @@ -42,7 +51,7 @@ public static boolean hasClaimPermission(NetworkAPI networkAPI, Player player, i // Check if the player has permission to claim a plot of this difficulty. if (!player.hasPermission("uknet.plots.claim.all")) { - switch (u.plotSQL.getInt("SELECT difficulty FROM plot_data WHERE id=" + plot + ";")) { + switch (plotAPI.getPlotDifficulty(plot)) { case 1 -> { if (!player.hasPermission("uknet.plots.claim.easy")) { @@ -77,16 +86,15 @@ public static boolean hasClaimPermission(NetworkAPI networkAPI, Player player, i } @Override - public void execute(CommandSourceStack stack, String[] args) { + public void execute(CommandSourceStack stack, String @NotNull [] args) { // Check if the sender is a player. - Player player = getPlayer(stack); - if (player == null) { + if (!(stack.getSender() instanceof Player player)) { return; } // Get the user. - User u = PlotSystem.getInstance().getUser(player); + User user = PlotSystem.getInstance().getUser(player); int plot = 0; boolean inPlot = false; @@ -94,23 +102,19 @@ public void execute(CommandSourceStack stack, String[] args) { plot = ParseUtils.toInt(args[0]); } if (plot == 0) { - plot = u.inPlot; + plot = user.inPlot; inPlot = true; } // If the plot is valid open the claim plot gui. - if (validPlot(u, plot, inPlot)) { - - NetworkUser user = Network.getInstance().getUser(u.player); - - if (!hasClaimPermission(u, user, plot)) { + if (validPlot(user, plot, inPlot)) { + if (!hasClaimPermission(networkAPI, player, plotAPI, plot)) { return; } // Open claim gui. - u.claimGui = new ClaimGui(u, plot); - u.claimGui.open(user); - + user.claimGui = new ClaimGui(user, plot, guiManager, plotAPI, plotHelper); + user.claimGui.open(player); } } @@ -153,8 +157,7 @@ public boolean validPlot(User u, int plot, boolean inPlot) { } // Check if the plot is on this server. - if (!plotSQL.hasRow( - "SELECT pd.id FROM plot_data AS pd INNER JOIN location_data AS ld ON ld.name=pd.location WHERE pd.id=" + plot + " AND ld.server='" + SERVER_NAME + "';")) { + if (!SERVER_NAME.equals(plotAPI.getLocationServer(plotAPI.getPlotLocation(plot)))) { u.player.sendMessage(ChatUtils.error("This plot is on another server, unable to claim it from here.")); return false; } diff --git a/src/main/java/net/bteuk/plotsystem/commands/CreateCommand.java b/src/main/java/net/bteuk/plotsystem/commands/CreateCommand.java index be98b04..02130b7 100644 --- a/src/main/java/net/bteuk/plotsystem/commands/CreateCommand.java +++ b/src/main/java/net/bteuk/plotsystem/commands/CreateCommand.java @@ -1,9 +1,8 @@ package net.bteuk.plotsystem.commands; -import net.bteuk.network.Network; +import net.bteuk.minecraft.gui.GuiManager; +import net.bteuk.network.api.PlotAPI; import net.bteuk.network.lib.utils.ChatUtils; -import net.bteuk.network.sql.PlotSQL; -import net.bteuk.network.utils.NetworkUser; import net.bteuk.plotsystem.PlotSystem; import net.bteuk.plotsystem.gui.CreatePlotGui; import net.bteuk.plotsystem.gui.CreateZoneGui; @@ -11,13 +10,18 @@ import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -public final class CreateCommand { +public class CreateCommand { - private CreateCommand() { - // Do nothing + private final GuiManager guiManager; + + private final PlotAPI plotAPI; + + public CreateCommand(GuiManager guiManager, PlotAPI plotAPI) { + this.guiManager = guiManager; + this.plotAPI = plotAPI; } - public static void create(CommandSender sender, String[] args) { + public void create(CommandSender sender, String[] args) { if (args.length < 2) { @@ -35,7 +39,7 @@ public static void create(CommandSender sender, String[] args) { } - private static void createPlot(CommandSender sender) { + private void createPlot(CommandSender sender) { // Check if the sender is a player if (!(sender instanceof Player)) { @@ -46,39 +50,35 @@ private static void createPlot(CommandSender sender) { } // Get the user - User u = PlotSystem.getInstance().getUser((Player) sender); + User user = PlotSystem.getInstance().getUser((Player) sender); // Check if the user has permission to use this command - if (!u.player.hasPermission("uknet.plots.create.plot")) { + if (!user.player.hasPermission("uknet.plots.create.plot")) { - u.player.sendMessage(ChatUtils.error("You do not have permission to use this command!")); + user.player.sendMessage(ChatUtils.error("You do not have permission to use this command!")); return; } // Check if the plot is valid, meaning that at least 3 points are selected with the selection tool. - if (u.selectionTool.size() < 3) { + if (user.selectionTool.size() < 3) { - u.player.sendMessage(ChatUtils.error("You must select at least 3 points for a valid plot!")); + user.player.sendMessage(ChatUtils.error("You must select at least 3 points for a valid plot!")); return; } // Open the plot creation menu // Calculate the area of the plot and set a default size estimate. - u.selectionTool.area(); - u.selectionTool.setDefaultSize(); - - // Get the user from the network plugin, this plugin handles all guis. - NetworkUser user = Network.getInstance().getUser(u.player); + user.selectionTool.area(); + user.selectionTool.setDefaultSize(); // Open the create gui. - u.createPlotGui = new CreatePlotGui(u); - u.createPlotGui.open(user); - + user.createPlotGui = new CreatePlotGui(guiManager, user); + user.createPlotGui.open(user.player); } - public static void createZone(CommandSender sender) { + public void createZone(CommandSender sender) { // Check if the sender is a player if (!(sender instanceof Player)) { @@ -89,45 +89,40 @@ public static void createZone(CommandSender sender) { } // Get the user - User u = PlotSystem.getInstance().getUser((Player) sender); + User user = PlotSystem.getInstance().getUser((Player) sender); // Check if the user has permission to use this command - if (!u.player.hasPermission("uknet.plots.create.zone")) { + if (!user.player.hasPermission("uknet.plots.create.zone")) { - u.player.sendMessage(ChatUtils.error("You do not have permission to use this command!")); + user.player.sendMessage(ChatUtils.error("You do not have permission to use this command!")); return; } // Check if the selection is valid, meaning that at least 3 points are selected with the selection tool. - if (u.selectionTool.size() < 3) { + if (user.selectionTool.size() < 3) { - u.player.sendMessage(ChatUtils.error("You must select at least 3 points for a valid zone!")); + user.player.sendMessage(ChatUtils.error("You must select at least 3 points for a valid zone!")); return; } - PlotSQL plotSQL = Network.getInstance().getPlotSQL(); - // If the player already has a zones, cancel, as this is the maximum. // Lastly there is a limit of 21 total zones at a time. - if (plotSQL.hasRow("SELECT id FROM zone_members WHERE uuid='" + u.player.getUniqueId() + "' AND is_owner=1;")) { + if (plotAPI.isZoneOwner(user.uuid)) { - u.player.sendMessage(ChatUtils.error("You already have a zone, close this before creating a new one.")); + user.player.sendMessage(ChatUtils.error("You already have a zone, close this before creating a new one.")); return; - } else if (plotSQL.getInt("SELECT count(id) FROM zones WHERE status='open';") >= 21) { + } else if (plotAPI.getNumberOfZones() >= 21) { - u.player.sendMessage(ChatUtils.error("There are currently 21 zones, this is the maximum.")); + user.player.sendMessage(ChatUtils.error("There are currently 21 zones, this is the maximum.")); return; } - // Get the user from the network plugin, this plugin handles all guis. - NetworkUser user = Network.getInstance().getUser(u.player); - // Open the create zone gui. - u.createZoneGui = new CreateZoneGui(u); - u.createZoneGui.open(user); + user.createZoneGui = new CreateZoneGui(guiManager, user); + user.createZoneGui.open(user.player); } } diff --git a/src/main/java/net/bteuk/plotsystem/commands/DeleteCommand.java b/src/main/java/net/bteuk/plotsystem/commands/DeleteCommand.java index 660c33c..6a98330 100644 --- a/src/main/java/net/bteuk/plotsystem/commands/DeleteCommand.java +++ b/src/main/java/net/bteuk/plotsystem/commands/DeleteCommand.java @@ -1,9 +1,8 @@ package net.bteuk.plotsystem.commands; +import net.bteuk.network.api.PlotAPI; +import net.bteuk.network.api.plotsystem.PlotStatus; import net.bteuk.network.lib.utils.ChatUtils; -import net.bteuk.network.sql.GlobalSQL; -import net.bteuk.network.sql.PlotSQL; -import net.bteuk.network.utils.enums.PlotStatus; import net.bteuk.plotsystem.PlotSystem; import net.bteuk.plotsystem.exceptions.RegionManagerNotFoundException; import net.bteuk.plotsystem.utils.PlotHelper; @@ -20,12 +19,13 @@ public class DeleteCommand { - private final GlobalSQL globalSQL; - private final PlotSQL plotSQL; + private final PlotAPI plotAPI; - public DeleteCommand(GlobalSQL globalSQL, PlotSQL plotSQL) { - this.globalSQL = globalSQL; - this.plotSQL = plotSQL; + private final PlotHelper plotHelper; + + public DeleteCommand(PlotAPI plotAPI, PlotHelper plotHelper) { + this.plotAPI = plotAPI; + this.plotHelper = plotHelper; } public void delete(CommandSender sender, String[] args) { @@ -120,14 +120,14 @@ private void deletePlot(CommandSender sender, String[] args) { sender.sendMessage(ChatUtils.error("This plot does not exist.")); } - // Check if plot is unclaimed - if (!(plotSQL.hasRow("SELECT id FROM plot_data WHERE id=" + plotID + " AND status='unclaimed'"))) { + // Check if the plot is unclaimed + if (!(plotAPI.isPlotUnclaimed(plotID))) { sender.sendMessage(ChatUtils.error("This plot is claimed, you can only delete unclaimed plots.")); return; } // Get world of plot. - World world = Bukkit.getWorld(plotSQL.getString("SELECT location FROM plot_data WHERE id=" + plotID + ";")); + World world = Bukkit.getWorld(plotAPI.getPlotLocation(plotID)); // If world is null then the plot is not on this server. if (world == null) { @@ -140,7 +140,7 @@ private void deletePlot(CommandSender sender, String[] args) { if (WorldGuardFunctions.delete(String.valueOf(plotID), world)) { // Set plot to deleted. - PlotHelper.updatePlotStatus(plotID, PlotStatus.DELETED); + plotHelper.updatePlotStatus(plotID, PlotStatus.DELETED); sender.sendMessage(ChatUtils.success("Plot ") .append(Component.text(plotID, NamedTextColor.DARK_AQUA)) .append(ChatUtils.success(" deleted."))); diff --git a/src/main/java/net/bteuk/plotsystem/commands/LocationCommand.java b/src/main/java/net/bteuk/plotsystem/commands/LocationCommand.java index ca92c26..1f54288 100644 --- a/src/main/java/net/bteuk/plotsystem/commands/LocationCommand.java +++ b/src/main/java/net/bteuk/plotsystem/commands/LocationCommand.java @@ -1,13 +1,13 @@ package net.bteuk.plotsystem.commands; import com.sk89q.worldedit.math.BlockVector3; -import net.bteuk.network.Network; -import net.bteuk.network.eventing.events.EventManager; +import net.bteuk.network.api.CoordinateAPI; +import net.bteuk.network.api.EventAPI; +import net.bteuk.network.api.NetworkAPI; +import net.bteuk.network.api.PlotAPI; +import net.bteuk.network.api.SQLAPI; import net.bteuk.network.lib.utils.ChatUtils; -import net.bteuk.network.sql.GlobalSQL; -import net.bteuk.network.sql.PlotSQL; -import net.bteuk.network.utils.Coordinate; -import net.bteuk.network.utils.Utils; +import net.bteuk.network.papercore.LocationAdapter; import net.bteuk.plotsystem.PlotSystem; import net.bteuk.plotsystem.utils.CopyRegionFormat; import net.bteuk.plotsystem.utils.plugins.Multiverse; @@ -26,8 +26,6 @@ import static java.lang.Math.max; import static java.lang.Math.min; -import static net.bteuk.network.utils.Constants.MAX_Y; -import static net.bteuk.network.utils.Constants.MIN_Y; import static net.bteuk.plotsystem.PlotSystem.LOGGER; public final class LocationCommand { @@ -35,11 +33,25 @@ public final class LocationCommand { private static final Component LOCATION_CREATE_COMMAND_FORMAT = ChatUtils.error("/plotsystem create location [name] "); private static final Component LOCATION_UPDATE_COMMAND_FORMAT = ChatUtils.error("/plotsystem update location [name] "); - private LocationCommand() { - // Do nothing + private final NetworkAPI networkAPI; + + private final PlotAPI plotAPI; + + private final CoordinateAPI coordinateAPI; + + private final EventAPI eventAPI; + + private final SQLAPI globalSQL; + + public LocationCommand(NetworkAPI networkAPI) { + this.networkAPI = networkAPI; + this.plotAPI = networkAPI.getPlotAPI(); + this.coordinateAPI = networkAPI.getCoordinateAPI(); + this.eventAPI = networkAPI.getEventAPI(); + this.globalSQL = networkAPI.getGlobalSQL(); } - public static void createLocation(CommandSender sender, String[] args) { + public void createLocation(CommandSender sender, String[] args) { // Check if the sender is a player. // If so, check if they have permission. @@ -55,10 +67,8 @@ public static void createLocation(CommandSender sender, String[] args) { return; } - final PlotSQL plotSQL = Network.getInstance().getPlotSQL(); - // Check if the location name is unique. - if (plotSQL.hasRow("SELECT name FROM location_data WHERE name='" + commandArguments.location() + "';")) { + if (plotAPI.hasLocation(commandArguments.location())) { sender.sendMessage(ChatUtils.error("The location ") .append(Component.text(commandArguments.location(), NamedTextColor.DARK_RED)) .append(ChatUtils.error(" already exists."))); @@ -117,20 +127,16 @@ public static void createLocation(CommandSender sender, String[] args) { copyRegions(sender, regions); - final GlobalSQL globalSQL = Network.getInstance().getGlobalSQL(); - - int coordMin = globalSQL.addCoordinate(new Location( + int coordMin = coordinateAPI.addCoordinate(LocationAdapter.adapt(new Location( Bukkit.getWorld(commandArguments.location()), - (regionXMin * 512), MIN_Y, (regionZMin * 512), 0, 0)); + (regionXMin * 512), networkAPI.getMinY(), (regionZMin * 512), 0, 0))); - int coordMax = globalSQL.addCoordinate(new Location( + int coordMax = coordinateAPI.addCoordinate(LocationAdapter.adapt(new Location( Bukkit.getWorld(commandArguments.location()), - ((regionXMax * 512) + 511), MAX_Y - 1, ((regionZMax * 512) + 511), 0, 0)); + ((regionXMax * 512) + 511), networkAPI.getMaxY() - 1, ((regionZMax * 512) + 511), 0, 0))); // Add the location to the database. - if (plotSQL.update("INSERT INTO location_data(name, alias, server, coordMin, coordMax, xTransform, zTransform) VALUES('" - + commandArguments.location() + "','" + commandArguments.location() + "','" + PlotSystem.SERVER_NAME + "'," + coordMin + "," + coordMax + "," + xTransform + - "," + zTransform + ");")) { + if (plotAPI.createLocation(commandArguments.location, commandArguments.location, PlotSystem.SERVER_NAME, coordMin, coordMax, xTransform, zTransform)) { sender.sendMessage(ChatUtils.success("Created new location ") .append(Component.text(commandArguments.location(), NamedTextColor.DARK_AQUA))); @@ -143,14 +149,10 @@ public static void createLocation(CommandSender sender, String[] args) { // Change region status in region database. // If it already exists remove members. - globalSQL.update("INSERT INTO server_events(uuid,type,server,event) VALUES(NULL,'network','" - + globalSQL.getString("SELECT name FROM server_data WHERE type='EARTH';") + "'," + - "'region set plotsystem " + region + "');"); + eventAPI.createEvent(null, globalSQL.getString("SELECT name FROM server_data WHERE type='EARTH';"), "region set plotsystem " + region); // Add region to database. - plotSQL.update( - "INSERT INTO regions(region,server,location) VALUES('" + region + "','" + PlotSystem.SERVER_NAME + "','" + commandArguments.location() + "');"); - + plotAPI.createPlotRegion(region, PlotSystem.SERVER_NAME, commandArguments.location()); } } @@ -165,7 +167,7 @@ public static void createLocation(CommandSender sender, String[] args) { }); } - public static void updateLocation(CommandSender sender, String[] args) { + public void updateLocation(CommandSender sender, String[] args) { // Check if the sender is a player. // If so, check if they have permission. @@ -181,11 +183,8 @@ public static void updateLocation(CommandSender sender, String[] args) { return; } - final PlotSQL plotSQL = Network.getInstance().getPlotSQL(); - final GlobalSQL globalSQL = Network.getInstance().getGlobalSQL(); - // Check if the location name exists. - if (!plotSQL.hasRow("SELECT name FROM location_data WHERE name='" + commandArguments.location() + "';")) { + if (!plotAPI.hasLocation(commandArguments.location())) { sender.sendMessage(ChatUtils.error("Location %s does not exist.", commandArguments.location())); return; } diff --git a/src/main/java/net/bteuk/plotsystem/commands/PlotSystemCommand.java b/src/main/java/net/bteuk/plotsystem/commands/PlotSystemCommand.java index 4d937a0..96f90f1 100644 --- a/src/main/java/net/bteuk/plotsystem/commands/PlotSystemCommand.java +++ b/src/main/java/net/bteuk/plotsystem/commands/PlotSystemCommand.java @@ -1,12 +1,12 @@ package net.bteuk.plotsystem.commands; +import io.papermc.paper.command.brigadier.BasicCommand; import io.papermc.paper.command.brigadier.CommandSourceStack; -import net.bteuk.network.Network; -import net.bteuk.network.commands.AbstractCommand; -import net.bteuk.network.commands.tabcompleters.FixedArgSelector; +import net.bteuk.minecraft.gui.GuiManager; +import net.bteuk.network.api.CoordinateAPI; +import net.bteuk.network.api.PlotAPI; import net.bteuk.network.lib.utils.ChatUtils; -import net.bteuk.network.sql.GlobalSQL; -import net.bteuk.network.sql.PlotSQL; +import net.bteuk.network.papercore.LocationAdapter; import net.bteuk.plotsystem.PlotSystem; import net.bteuk.plotsystem.utils.ParseUtils; import net.bteuk.plotsystem.utils.PlotHelper; @@ -15,21 +15,41 @@ import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; import org.bukkit.Location; +import org.bukkit.command.Command; import org.bukkit.command.CommandSender; +import org.bukkit.command.TabCompleter; import org.bukkit.entity.Player; +import org.bukkit.util.StringUtil; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import java.util.Arrays; +import java.util.ArrayList; +import java.util.List; -public class PlotSystemCommand extends AbstractCommand { +public class PlotSystemCommand implements BasicCommand, TabCompleter { - private final PlotSQL plotSQL; - private final GlobalSQL globalSQL; + private static final List options = List.of("create", "selectiontool", "delete", "help", "setalias", "movemarker", "update"); - public PlotSystemCommand(GlobalSQL globalSQL, PlotSQL plotSQL) { - this.plotSQL = plotSQL; - this.globalSQL = globalSQL; + private final PlotAPI plotAPI; - setTabCompleter(new FixedArgSelector(Arrays.asList("create", "selectiontool", "delete", "help", "setalias", "movemarker", "update"), 0)); + private final PlotHelper plotHelper; + + private final CoordinateAPI coordinateAPI; + + private final CreateCommand createCommand; + + private final DeleteCommand deleteCommand; + + private final UpdateCommand updateCommand; + + public PlotSystemCommand(PlotAPI plotAPI, PlotHelper plotHelper, CoordinateAPI coordinateAPI, GuiManager guiManager) { + this.plotAPI = plotAPI; + this.plotHelper = plotHelper; + this.coordinateAPI = coordinateAPI; + + this.createCommand = new CreateCommand(guiManager, plotAPI); + this.deleteCommand = new DeleteCommand(plotAPI, plotHelper); + this.updateCommand = new UpdateCommand(plotAPI); } @Override @@ -37,7 +57,7 @@ public void execute(CommandSourceStack stack, String[] args) { CommandSender sender = stack.getSender(); - // If there are no arguments return. + // If there are no arguments, return. if (args.length == 0) { sender.sendMessage(ChatUtils.error("/plotsystem help")); return; @@ -46,12 +66,9 @@ public void execute(CommandSourceStack stack, String[] args) { switch (args[0]) { case "selectiontool" -> selectionTool(sender); - case "create" -> CreateCommand.create(sender, args); - case "delete" -> { - DeleteCommand deleteCommand = new DeleteCommand(globalSQL, plotSQL); - deleteCommand.delete(sender, args); - } - case "update" -> UpdateCommand.update(sender, args); + case "create" -> createCommand.create(sender, args); + case "delete" -> deleteCommand.delete(sender, args); + case "update" -> updateCommand.update(sender, args); case "help" -> help(sender); case "setalias" -> { @@ -115,9 +132,9 @@ private void setAlias(CommandSender sender, String location, String alias) { } } - if (plotSQL.hasRow("SELECT name FROM location_data WHERE name='" + location + "';")) { + if (plotAPI.hasLocation(location)) { - plotSQL.update("UPDATE location_data SET alias='" + alias.replace("'", "\\'") + "' WHERE name='" + location + "';"); + plotAPI.setLocationAlias(location, alias); sender.sendMessage(ChatUtils.success("Set alias of location ") .append(Component.text(location, NamedTextColor.DARK_AQUA)) .append(ChatUtils.success(" to ")) @@ -164,22 +181,22 @@ private void moveHologram(CommandSender sender, String[] args) { } // Get the coordinate of the marker. - int coordinate_id = Network.getInstance().getPlotSQL().getInt("SELECT coordinate_id FROM plot_data WHERE id=" + plot + ";"); + int coordinate_id = plotAPI.getPlotCoordinate(plot); Location l = p.getLocation().clone(); l.setY(l.getY() + 2); if (coordinate_id == 0) { // Create a new coordinate id and add it to the plot data. - coordinate_id = Network.getInstance().getGlobalSQL().addCoordinate(l); - Network.getInstance().getPlotSQL().update("UPDATE plot_data SET coordinate_id=" + coordinate_id + " WHERE id=" + plot + ";"); + coordinate_id = coordinateAPI.addCoordinate(LocationAdapter.adapt(l)); + plotAPI.updatePlotCoordinate(plot, coordinate_id); // Add the hologram. - PlotHelper.addPlotHologram(new PlotHologram(plot)); + plotHelper.addPlotHologram(new PlotHologram(plot)); p.sendMessage(ChatUtils.success("Added marker to plot " + plot)); } else { // Update the existing coordinate location. - Network.getInstance().getGlobalSQL().updateCoordinate(coordinate_id, l); + coordinateAPI.updateCoordinate(coordinate_id, LocationAdapter.adapt(l)); // Update the hologram. - PlotHelper.updatePlotHologram(plot); + plotHelper.updatePlotHologram(plot); p.sendMessage(ChatUtils.success("Moved marker of plot " + plot)); } @@ -187,4 +204,17 @@ private void moveHologram(CommandSender sender, String[] args) { sender.sendMessage(ChatUtils.error("You must be a player to use this command.")); } } + + @Override + public @Nullable List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String @NotNull [] args) { + // Return list. + List returns = new ArrayList<>(); + + if (args.length == 1) { + StringUtil.copyPartialMatches(args[0], options, returns); + } else if (args.length == 0) { + return options; + } + return returns; + } } diff --git a/src/main/java/net/bteuk/plotsystem/commands/ReviewCommand.java b/src/main/java/net/bteuk/plotsystem/commands/ReviewCommand.java index 5478dce..fe32ee3 100644 --- a/src/main/java/net/bteuk/plotsystem/commands/ReviewCommand.java +++ b/src/main/java/net/bteuk/plotsystem/commands/ReviewCommand.java @@ -1,18 +1,19 @@ package net.bteuk.plotsystem.commands; +import io.papermc.paper.command.brigadier.BasicCommand; import io.papermc.paper.command.brigadier.CommandSourceStack; -import net.bteuk.network.commands.AbstractCommand; +import net.bteuk.network.api.plotsystem.ReviewCategory; +import net.bteuk.network.api.plotsystem.ReviewSelection; import net.bteuk.network.lib.utils.ChatUtils; -import net.bteuk.network.utils.plotsystem.ReviewCategory; -import net.bteuk.network.utils.plotsystem.ReviewSelection; import net.bteuk.plotsystem.PlotSystem; import net.bteuk.plotsystem.utils.User; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; /** * Command for editing selections to reviewing categories during the reviewing process. */ -public class ReviewCommand extends AbstractCommand { +public class ReviewCommand implements BasicCommand { private final PlotSystem instance; @@ -21,12 +22,10 @@ public ReviewCommand(PlotSystem instance) { } @Override - public void execute(CommandSourceStack stack, String[] args) { + public void execute(CommandSourceStack stack, String @NotNull [] args) { // Check if the player is actually reviewing, else ignore the command. - Player player = getPlayer(stack); - - if (player == null) { + if (!(stack.getSender() instanceof Player player)) { return; } diff --git a/src/main/java/net/bteuk/plotsystem/commands/ToggleOutlines.java b/src/main/java/net/bteuk/plotsystem/commands/ToggleOutlines.java index 43589bb..32817a6 100644 --- a/src/main/java/net/bteuk/plotsystem/commands/ToggleOutlines.java +++ b/src/main/java/net/bteuk/plotsystem/commands/ToggleOutlines.java @@ -1,7 +1,7 @@ package net.bteuk.plotsystem.commands; +import io.papermc.paper.command.brigadier.BasicCommand; import io.papermc.paper.command.brigadier.CommandSourceStack; -import net.bteuk.network.commands.AbstractCommand; import net.bteuk.network.lib.utils.ChatUtils; import net.bteuk.plotsystem.PlotSystem; import net.bteuk.plotsystem.utils.User; @@ -11,7 +11,7 @@ /** * Command to toggle the plot outlines for the current session of the player. */ -public class ToggleOutlines extends AbstractCommand { +public class ToggleOutlines implements BasicCommand { private final PlotSystem instance; @@ -20,11 +20,10 @@ public ToggleOutlines(PlotSystem instance) { } @Override - public void execute(@NotNull CommandSourceStack stack, @NotNull String[] args) { + public void execute(@NotNull CommandSourceStack stack, String @NotNull [] args) { // Check if the sender is a player. - Player player = getPlayer(stack); - if (player == null) { + if (!(stack.getSender() instanceof Player player)) { return; } diff --git a/src/main/java/net/bteuk/plotsystem/commands/UpdateCommand.java b/src/main/java/net/bteuk/plotsystem/commands/UpdateCommand.java index 277e3e7..722542f 100644 --- a/src/main/java/net/bteuk/plotsystem/commands/UpdateCommand.java +++ b/src/main/java/net/bteuk/plotsystem/commands/UpdateCommand.java @@ -1,9 +1,8 @@ package net.bteuk.plotsystem.commands; -import net.bteuk.network.Network; +import net.bteuk.network.api.PlotAPI; import net.bteuk.network.lib.enums.PlotDifficulties; import net.bteuk.network.lib.utils.ChatUtils; -import net.bteuk.network.sql.PlotSQL; import net.bteuk.plotsystem.PlotSystem; import net.kyori.adventure.text.Component; import org.bukkit.command.CommandSender; @@ -15,11 +14,13 @@ public final class UpdateCommand { private static final Component PLOT_ERROR_MESSAGE = ChatUtils.error("/plotsystem update plot set difficulty [easy|normal|hard]"); - private UpdateCommand() { - // Do nothing + private final PlotAPI plotAPI; + + public UpdateCommand(PlotAPI plotAPI) { + this.plotAPI = plotAPI; } - public static void update(CommandSender sender, String[] args) { + public void update(CommandSender sender, String[] args) { if (args.length < 2) { sender.sendMessage(GENERIC_ERROR_MESSAGE); @@ -33,7 +34,7 @@ public static void update(CommandSender sender, String[] args) { } } - private static void updatePlot(CommandSender sender, String[] args) { + private void updatePlot(CommandSender sender, String[] args) { // Check if the sender is a player. // If so, check if they have permission. if (sender instanceof Player p) { @@ -66,16 +67,14 @@ private static void updatePlot(CommandSender sender, String[] args) { return; } - PlotSQL plotSQL = Network.getInstance().getPlotSQL(); - // Check if plot exists. - if (!plotSQL.hasRow("SELECT id FROM plot_data WHERE id=" + plotID + " AND status IN ('unclaimed','claimed','submitted');")) { + if (!plotAPI.plotExists(plotID)) { sender.sendMessage(ChatUtils.error("Plot %s does not exist.", args[2])); return; } // Update the plot difficulty. - plotSQL.update("UPDATE plot_data SET difficulty=" + plotDifficulty.getValue() + " WHERE id=" + plotID + ";"); + plotAPI.setPlotDifficulty(plotID, plotDifficulty.getValue()); sender.sendMessage(ChatUtils.success("Updated difficulty of plot %s to %s.", args[2], args[5])); // Update the plot outlines. diff --git a/src/main/java/net/bteuk/plotsystem/gui/ClaimGui.java b/src/main/java/net/bteuk/plotsystem/gui/ClaimGui.java index a1a7cab..68a006a 100644 --- a/src/main/java/net/bteuk/plotsystem/gui/ClaimGui.java +++ b/src/main/java/net/bteuk/plotsystem/gui/ClaimGui.java @@ -2,6 +2,8 @@ import net.bteuk.minecraft.gui.Gui; import net.bteuk.minecraft.gui.GuiManager; +import net.bteuk.network.api.PlotAPI; +import net.bteuk.network.api.plotsystem.PlotStatus; import net.bteuk.network.lib.utils.ChatUtils; import net.bteuk.plotsystem.PlotSystem; import net.bteuk.plotsystem.exceptions.RegionManagerNotFoundException; @@ -27,11 +29,17 @@ public class ClaimGui extends Gui { private final int plot; - public ClaimGui(User user, int plot, GuiManager guiManager) { + private final PlotAPI plotAPI; + + private final PlotHelper plotHelper; + + public ClaimGui(User user, int plot, GuiManager guiManager, PlotAPI plotAPI, PlotHelper plotHelper) { super(guiManager, 27, ChatUtils.title("Claim Plot")); this.user = user; this.plot = plot; + this.plotAPI = plotAPI; + this.plotHelper = plotHelper; createGui(); } @@ -49,15 +57,13 @@ private void createGui() { setItem(22, Utils.createItem(Material.ENDER_EYE, 1, ChatUtils.title("View Plot in Google Maps"), ChatUtils.line("Click to open a link to this plot in google maps.")), - clickEvent -> - - { + clickEvent -> { Player player = (Player) clickEvent.getWhoClicked(); player.closeInventory(); // Get corners of the plot. - int[][] corners = user.plotSQL.getPlotCorners(plot); + int[][] corners = plotAPI.getPlotCorners(plot); int sumX = 0; int sumZ = 0; @@ -74,10 +80,8 @@ private void createGui() { double z = sumZ / (double) corners.length; // Subtract the coordinate transform to make the coordinates in the real location. - x -= user.plotSQL.getInt("SELECT xTransform FROM location_data WHERE name='" + - user.plotSQL.getString("SELECT location FROM plot_data WHERE id=" + plot + ";") + "';"); - z -= user.plotSQL.getInt("SELECT zTransform FROM location_data WHERE name='" + - user.plotSQL.getString("SELECT location FROM plot_data WHERE id=" + plot + ";") + "';"); + x -= plotAPI.getXTransform(plotAPI.getPlotLocation(plot)); + z -= plotAPI.getZTransform(plotAPI.getPlotLocation(plot)); // Convert to irl coordinates. @@ -87,8 +91,8 @@ private void createGui() { // Generate link to google maps. Component message = ChatUtils.success("Click here to open the plot in Google Maps."); - message = message.clickEvent(ClickEvent.clickEvent(ClickEvent.Action.OPEN_URL, - "https://www.google.com/maps/@?api=1&map_action=map&basemap=satellite&zoom=21¢er=" + coords[1] + "," + coords[0])); + message = message.clickEvent( + ClickEvent.openUrl("https://www.google.com/maps/@?api=1&map_action=map&basemap=satellite&zoom=21¢er=" + coords[1] + "," + coords[0])); player.sendMessage(message); } catch (OutOfProjectionBoundsException e) { @@ -100,81 +104,71 @@ private void createGui() { setItem(4, Utils.createItem(Material.EMERALD, 1, ChatUtils.title("Claim Plot"), ChatUtils.line("Click to claim the plot and start building.")), - u -> + event -> { + if (event.getWhoClicked() instanceof Player player) { + player.closeInventory(); - { + // Check if the plot is not already claimed, since it may happen that the gui is spammed. + if (eUser.plotSQL.hasRow("SELECT id FROM plot_data WHERE id=" + plot + " AND status='unclaimed';")) { - User eUser = PlotSystem.getInstance().getUser(u.player); - u.player.closeInventory(); + // If the plot status can be updated, add the player as plot owner. + if (plotHelper.updatePlotStatus(plot, PlotStatus.CLAIMED)) { - // Check if the plot is not already claimed, since it may happen that the gui is spammed. - if (eUser.plotSQL.hasRow("SELECT id FROM plot_data WHERE id=" + plot + " AND status='unclaimed';")) { + // If the player can't be given owner, set the plot status back to unclaimed. + if (eUser.plotSQL.update( + "INSERT INTO plot_members(id,uuid,is_owner,last_enter) VALUES(" + plot + ",'" + eUser.uuid + "',1," + Time.currentTime() + ");")) { - // If the plot status can be updated, add the player as plot owner. - if (PlotHelper.updatePlotStatus(plot, PlotStatus.CLAIMED)) { + // Add player to worldguard region. + try { + if (WorldGuardFunctions.addMember(String.valueOf(plot), player.getUniqueId().toString(), player.getWorld())) { - // If the player can't be given owner, set the plot status back to unclaimed. - if (eUser.plotSQL.update( - "INSERT INTO plot_members(id,uuid,is_owner,last_enter) VALUES(" + plot + ",'" + eUser.uuid + "',1," + Time.currentTime() + ");")) { + player.sendMessage(ChatUtils.success("Successfully claimed plot ") + .append(Component.text(plot, NamedTextColor.DARK_AQUA)) + .append(ChatUtils.success(", good luck building."))); + // Send link to plot in Google Maps. + player.performCommand("ll"); + LOGGER.info("Plot " + plot + " successfully claimed."); - // Add player to worldguard region. - try { - if (WorldGuardFunctions.addMember(String.valueOf(plot), eUser.uuid, eUser.player.getWorld())) { + } else { - eUser.player.sendMessage(ChatUtils.success("Successfully claimed plot ") - .append(Component.text(plot, NamedTextColor.DARK_AQUA)) - .append(ChatUtils.success(", good luck building."))); - // Send link to plot in Google Maps. - eUser.player.performCommand("ll"); - LOGGER.info("Plot " + plot + " successfully claimed by " + eUser.name); - - } else { - - eUser.player.sendMessage(ChatUtils.error("An error occurred while claiming the plot.")); - LOGGER.warning("Plot " + plot + " was claimed but they were not added to the worldguard region."); + player.sendMessage(ChatUtils.error("An error occurred while claiming the plot.")); + LOGGER.warning("Plot " + plot + " was claimed but they were not added to the worldguard region."); + } + } catch (RegionManagerNotFoundException | RegionNotFoundException e) { + player.sendMessage(ChatUtils.error("An error occurred while claiming the plot, please notify an admin.")); + e.printStackTrace(); } - } catch (RegionManagerNotFoundException | RegionNotFoundException e) { - eUser.player.sendMessage(ChatUtils.error("An error occurred while claiming the plot, please notify an admin.")); - e.printStackTrace(); - } - } else { + } else { - eUser.player.sendMessage(ChatUtils.error("An error occurred while claiming the plot.")); - LOGGER.warning("Plot owner insert failed for plot " + plot); + player.sendMessage(ChatUtils.error("An error occurred while claiming the plot.")); + LOGGER.warning("Plot owner insert failed for plot " + plot); - // Attempt to set plot back to unclaimed - if (PlotHelper.updatePlotStatus(plot, PlotStatus.UNCLAIMED)) { + // Attempt to set plot back to unclaimed + if (plotHelper.updatePlotStatus(plot, PlotStatus.UNCLAIMED)) { - LOGGER.warning("Plot " + plot + " has been set back to unclaimed."); + LOGGER.warning("Plot " + plot + " has been set back to unclaimed."); - } else { + } else { - LOGGER.severe("Plot " + plot + " is set to claimed but has no owner!"); + LOGGER.severe("Plot " + plot + " is set to claimed but has no owner!"); + } } - } - } else { + } else { - eUser.player.sendMessage(ChatUtils.error("An error occurred while claiming the plot.")); - LOGGER.warning("Status could not be changed to claimed for plot " + plot); + player.sendMessage(ChatUtils.error("An error occurred while claiming the plot.")); + LOGGER.warning("Status could not be changed to claimed for plot " + plot); - } - } else { + } + } else { - eUser.player.sendMessage(ChatUtils.error("This plot is already claimed, it could be due to clicking the claim button multiple times.")); + player.sendMessage(ChatUtils.error("This plot is already claimed, it could be due to clicking the claim button multiple times.")); + } } - }); } - - public void refresh() { - - clearGui(); - createGui(); - - } } diff --git a/src/main/java/net/bteuk/plotsystem/gui/CreatePlotGui.java b/src/main/java/net/bteuk/plotsystem/gui/CreatePlotGui.java index 527d28e..e7d5429 100644 --- a/src/main/java/net/bteuk/plotsystem/gui/CreatePlotGui.java +++ b/src/main/java/net/bteuk/plotsystem/gui/CreatePlotGui.java @@ -2,12 +2,18 @@ import net.bteuk.minecraft.gui.Gui; import net.bteuk.minecraft.gui.GuiManager; +import net.bteuk.network.lib.utils.ChatUtils; +import net.bteuk.plotsystem.PlotSystem; import net.bteuk.plotsystem.utils.PlotValues; import net.bteuk.plotsystem.utils.User; +import net.bteuk.plotsystem.utils.Utils; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; import net.kyori.adventure.text.format.TextDecoration; import org.bukkit.Material; +import org.bukkit.entity.Player; + +import java.util.Objects; public class CreatePlotGui extends Gui { @@ -26,43 +32,36 @@ public CreatePlotGui(GuiManager manager, User user) { private void createGui() { // Choose plot size. - setItem(11, Utils.createItem(PlotValues.sizeMaterial(user.selectionTool.size), 1, - ChatUtils.title(PlotValues.sizeName(user.selectionTool.size)), + setItem(11, Utils.createItem(Objects.requireNonNull(PlotValues.sizeMaterial(user.selectionTool.size)), 1, + ChatUtils.title(Objects.requireNonNull(PlotValues.sizeName(user.selectionTool.size))), ChatUtils.line("Click to cycle through sizes.")), - u -> - - { + event -> { + Player player = (Player) event.getWhoClicked(); // Get an instance of the plotsystem user. - User eUser = PlotSystem.getInstance().getUser(u.player); + User eUser = PlotSystem.getInstance().getUser(player); // Change the size by 1. // If less than 3 (large) increase by 1, else return to 1. if (eUser.selectionTool.size == 3) { - eUser.selectionTool.size = 1; - } else { - eUser.selectionTool.size++; - } // Update the gui. refresh(); - u.player.getOpenInventory().getTopInventory().setContents(getInventory().getContents()); - + updatePlayerInventory(player); }); // Choose plot difficulty. - setItem(15, Utils.createItem(PlotValues.difficultyMaterial(user.selectionTool.difficulty), 1, - ChatUtils.title(PlotValues.difficultyName(user.selectionTool.difficulty)), + setItem(15, Utils.createItem(Objects.requireNonNull(PlotValues.difficultyMaterial(user.selectionTool.difficulty)), 1, + ChatUtils.title(Objects.requireNonNull(PlotValues.difficultyName(user.selectionTool.difficulty))), ChatUtils.line("Click to cycle through different difficulties.")), - u -> - - { + event -> { + Player player = (Player) event.getWhoClicked(); - User eUser = PlotSystem.getInstance().getUser(u.player); + User eUser = PlotSystem.getInstance().getUser(player); // Change the difficulty by 1. // If less than 3 (hard) increase by 1, else return to 1. @@ -78,22 +77,20 @@ private void createGui() { // Update the gui. refresh(); - u.player.getOpenInventory().getTopInventory().setContents(getInventory().getContents()); - + updatePlayerInventory(player); }); // Create plot. setItem(13, Utils.createItem(Material.DIAMOND, 1, ChatUtils.title("Create Plot"), ChatUtils.line("Click create a new plot with the settings selected.")), - u -> - - { + event -> { + Player player = (Player) event.getWhoClicked(); - User eUser = PlotSystem.getInstance().getUser(u.player); + User eUser = PlotSystem.getInstance().getUser(player); // Close the inventory. - u.player.closeInventory(); + player.closeInventory(); // Create plot with the selection created by the user. eUser.selectionTool.createPlot(); diff --git a/src/main/java/net/bteuk/plotsystem/gui/CreateZoneGui.java b/src/main/java/net/bteuk/plotsystem/gui/CreateZoneGui.java index fc97d6a..25a4a36 100644 --- a/src/main/java/net/bteuk/plotsystem/gui/CreateZoneGui.java +++ b/src/main/java/net/bteuk/plotsystem/gui/CreateZoneGui.java @@ -3,19 +3,19 @@ import net.bteuk.minecraft.gui.Gui; import net.bteuk.minecraft.gui.GuiManager; import net.bteuk.network.lib.utils.ChatUtils; -import net.bteuk.plotsystem.PlotSystem; import net.bteuk.plotsystem.utils.User; import net.bteuk.plotsystem.utils.Utils; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; import net.kyori.adventure.text.format.TextDecoration; import org.bukkit.Material; +import org.bukkit.entity.Player; public class CreateZoneGui extends Gui { private final User user; - // This gui handles the plot creation process, and will allow the user to set the parameters of the plot. + // This gui handles the plot creation process and will allow the user to set the parameters of the plot. public CreateZoneGui(GuiManager manager, User user) { super(manager, 27, Component.text("Create Plot Menu", NamedTextColor.AQUA, TextDecoration.BOLD)); @@ -32,17 +32,14 @@ private void createGui() { setItem(13, Utils.createItem(Material.DIAMOND, 1, ChatUtils.title("Create Zone"), ChatUtils.line("Click create a new zone with the settings selected.")), - u -> - - { - - User eUser = PlotSystem.getInstance().getUser(u.player); + event -> { + Player player = (Player) event.getWhoClicked(); // Close the inventory. - u.player.closeInventory(); + player.closeInventory(); // Create plot with the selection created by the user. - eUser.selectionTool.createZone(); + user.selectionTool.createZone(); }); @@ -54,7 +51,7 @@ private void createGui() { ChatUtils.line("Click to make the zone private."), ChatUtils.line("A private zone means the owner has"), ChatUtils.line("to invite members for them to build.")), - u -> { + event -> { // Set private. user.selectionTool.isPublic = false; @@ -70,7 +67,7 @@ private void createGui() { ChatUtils.line("Click to make the zone public."), ChatUtils.line("A public zone allows JrBuilder+"), ChatUtils.line("to join without having to request.")), - u -> { + event -> { // Set private. user.selectionTool.isPublic = true; diff --git a/src/main/java/net/bteuk/plotsystem/listeners/ClaimEnter.java b/src/main/java/net/bteuk/plotsystem/listeners/ClaimEnter.java index 9ef960d..e7a458e 100644 --- a/src/main/java/net/bteuk/plotsystem/listeners/ClaimEnter.java +++ b/src/main/java/net/bteuk/plotsystem/listeners/ClaimEnter.java @@ -5,10 +5,9 @@ import com.sk89q.worldguard.protection.ApplicableRegionSet; import com.sk89q.worldguard.protection.regions.ProtectedRegion; import com.sk89q.worldguard.protection.regions.RegionQuery; +import net.bteuk.network.api.PlotAPI; +import net.bteuk.network.api.SQLAPI; import net.bteuk.network.lib.utils.ChatUtils; -import net.bteuk.network.sql.GlobalSQL; -import net.bteuk.network.sql.PlotSQL; -import net.bteuk.network.utils.Time; import net.bteuk.plotsystem.PlotSystem; import net.bteuk.plotsystem.utils.User; import net.kyori.adventure.text.Component; @@ -23,15 +22,13 @@ public class ClaimEnter implements Listener { - final PlotSQL plotSQL; - final GlobalSQL globalSQL; - - public ClaimEnter(PlotSystem plugin, PlotSQL plotSQL, GlobalSQL globalSQl) { + final PlotAPI plotAPI; + final SQLAPI globalSQL; + public ClaimEnter(PlotSystem plugin, PlotAPI plotAPI, SQLAPI globalSQl) { Bukkit.getServer().getPluginManager().registerEvents(this, plugin); - this.plotSQL = plotSQL; + this.plotAPI = plotAPI; this.globalSQL = globalSQl; - } @EventHandler @@ -115,30 +112,21 @@ public void checkRegion(User u) { // If the plot is claimed, send the relevant message. if (u.inPlot != 0) { - if (!plotSQL.hasRow("SELECT id FROM plot_members WHERE id=" + u.inPlot + ";")) { - + String plotOwner = plotAPI.getPlotOwner(u.inPlot); + if (plotOwner == null) { u.player.sendActionBar( ChatUtils.success("You have left plot ") .append(Component.text(u.inPlot, NamedTextColor.DARK_AQUA))); - } else { - // If you are the owner of the plot send the relevant message. - if (plotSQL.hasRow("SELECT id FROM plot_members WHERE id=" + u.inPlot + " AND uuid='" + u.uuid + "' AND is_owner=1;")) { - + if (plotOwner.equals(u.uuid)) { u.player.sendActionBar( ChatUtils.success("You have left your plot.")); - } else { - // If you are not an owner or member send the relevant message. - u.player.sendActionBar( - ChatUtils.success("You have left ") - .append(Component.text(globalSQL.getString("SELECT name FROM player_data WHERE uuid = '" + - plotSQL.getString("SELECT uuid FROM plot_members WHERE id=" + u.inPlot + " AND is_owner=1;") + "';") + "'s", - NamedTextColor.DARK_AQUA)) - .append(ChatUtils.success(" plot."))); - + u.player.sendActionBar(ChatUtils.success("You have left ") + .append(Component.text(globalSQL.getString("SELECT name FROM player_data WHERE uuid = '" + plotOwner + "';") + "'s", + NamedTextColor.DARK_AQUA)).append(ChatUtils.success(" plot."))); } } @@ -170,7 +158,8 @@ private void checkPlot(User u, int plot) { u.inPlot = plot; // If the plot is claimed, send the relevant message. - if (!plotSQL.hasRow("SELECT id FROM plot_members WHERE id=" + plot + ";")) { + String plotOwner = plotAPI.getPlotOwner(plot); + if (plotOwner == null) { u.player.sendActionBar( ChatUtils.success("You have entered plot ") @@ -180,18 +169,18 @@ private void checkPlot(User u, int plot) { } else { // If you are the owner of the plot send the relevant message. - if (plotSQL.hasRow("SELECT id FROM plot_members WHERE id=" + plot + " AND uuid='" + u.uuid + "' AND is_owner=1;")) { + if (plotOwner.equals(u.uuid)) { - plotSQL.update("UPDATE plot_members SET last_enter=" + Time.currentTime() + ",inactivity_notice=0 WHERE id=" + plot + " AND uuid='" + u.uuid + "';"); + plotAPI.setPlotLastEnter(plot, u.uuid); u.player.sendActionBar( ChatUtils.success("You have entered plot ") .append(Component.text(u.inPlot, NamedTextColor.DARK_AQUA)) .append(ChatUtils.success(", you are the owner of this plot."))); // If you are a member of the plot send the relevant message. - } else if (plotSQL.hasRow("SELECT id FROM plot_members WHERE id=" + plot + " AND uuid='" + u.uuid + "' AND is_owner=0;")) { + } else if (plotAPI.isPlotMember(plot, u.uuid)) { - plotSQL.update("UPDATE plot_members SET last_enter=" + Time.currentTime() + " WHERE id=" + plot + " AND uuid='" + u.uuid + "';"); + plotAPI.setPlotLastEnter(plot, u.uuid); u.player.sendActionBar( ChatUtils.success("You have entered plot ") .append(Component.text(u.inPlot, NamedTextColor.DARK_AQUA)) @@ -202,8 +191,7 @@ private void checkPlot(User u, int plot) { // If you are not an owner or member send the relevant message. u.player.sendActionBar( ChatUtils.success("You have entered ") - .append(Component.text(globalSQL.getString("SELECT name FROM player_data WHERE uuid = '" + - plotSQL.getString("SELECT uuid FROM plot_members WHERE id=" + plot + " AND is_owner=1;") + "';") + "'s", NamedTextColor.DARK_AQUA)) + .append(Component.text(globalSQL.getString("SELECT name FROM player_data WHERE uuid = '" + plotOwner + "';") + "'s", NamedTextColor.DARK_AQUA)) .append(ChatUtils.success(" plot."))); } @@ -212,10 +200,8 @@ private void checkPlot(User u, int plot) { } else { // If you are the owner or member of this plot update your last enter time. - if (plotSQL.hasRow("SELECT id FROM plot_members WHERE id=" + u.inPlot + " AND uuid='" + u.uuid + "';")) { - - plotSQL.update("UPDATE plot_members SET last_enter=" + Time.currentTime() + " WHERE id=" + u.inPlot + " AND uuid='" + u.uuid + "';"); - + if (plotAPI.hasRow("SELECT id FROM plot_members WHERE id=" + u.inPlot + " AND uuid='" + u.uuid + "';")) { + plotAPI.setPlotLastEnter(u.inPlot, u.uuid); } } } @@ -231,7 +217,7 @@ private void checkZone(User u, int zone) { u.inZone = zone; // Check if the zone is public. - if (plotSQL.hasRow("SELECT id FROM zones WHERE id=" + zone + " AND is_public=1;")) { + if (plotAPI.hasRow("SELECT id FROM zones WHERE id=" + zone + " AND is_public=1;")) { u.player.sendActionBar( ChatUtils.success("You have entered zone ") diff --git a/src/main/java/net/bteuk/plotsystem/listeners/PlayerInteract.java b/src/main/java/net/bteuk/plotsystem/listeners/PlayerInteract.java index 58ce4f8..127a681 100644 --- a/src/main/java/net/bteuk/plotsystem/listeners/PlayerInteract.java +++ b/src/main/java/net/bteuk/plotsystem/listeners/PlayerInteract.java @@ -1,7 +1,7 @@ package net.bteuk.plotsystem.listeners; +import net.bteuk.network.api.PlotAPI; import net.bteuk.network.lib.utils.ChatUtils; -import net.bteuk.network.sql.PlotSQL; import net.bteuk.plotsystem.PlotSystem; import net.bteuk.plotsystem.exceptions.RegionManagerNotFoundException; import net.bteuk.plotsystem.utils.User; @@ -20,16 +20,16 @@ public class PlayerInteract implements Listener { - final PlotSQL plotSQL; + private final PlotSystem instance; - public PlayerInteract(PlotSystem plugin, PlotSQL plotSQL) { + private final PlotAPI plotAPI; - // Register the listener. - Bukkit.getServer().getPluginManager().registerEvents(this, plugin); - - // Set the reference to the plotSQL. - this.plotSQL = plotSQL; + public PlayerInteract(PlotSystem instance, PlotAPI plotAPI) { + this.instance = instance; + this.plotAPI = plotAPI; + // Register the listener. + Bukkit.getServer().getPluginManager().registerEvents(this, instance); } @EventHandler @@ -60,14 +60,12 @@ public void interactEvent(PlayerInteractEvent e) { e.setCancelled(true); // Check if they are in a world where plots are allowed to be created. - if (!plotSQL.hasRow("SELECT name FROM location_data WHERE name='" + Objects.requireNonNull(e.getClickedBlock()).getWorld().getName() + "';")) { - + if (!plotAPI.hasLocation(Objects.requireNonNull(e.getClickedBlock()).getWorld().getName())) { u.player.sendMessage(ChatUtils.error("You can't create plots in this world!")); return; - } - // If the selected point is in an existing plot cancel. + // If the selected point is in an existing plot, cancel. try { if (WorldGuardFunctions.inRegion(e.getClickedBlock())) { diff --git a/src/main/java/net/bteuk/plotsystem/reviewing/ReviewBook.java b/src/main/java/net/bteuk/plotsystem/reviewing/ReviewBook.java index 7a7c61e..4b298d9 100644 --- a/src/main/java/net/bteuk/plotsystem/reviewing/ReviewBook.java +++ b/src/main/java/net/bteuk/plotsystem/reviewing/ReviewBook.java @@ -1,10 +1,10 @@ package net.bteuk.plotsystem.reviewing; +import net.bteuk.network.api.PlotAPI; +import net.bteuk.network.api.plotsystem.ReviewCategory; +import net.bteuk.network.api.plotsystem.ReviewCategoryFeedback; +import net.bteuk.network.api.plotsystem.ReviewSelection; import net.bteuk.network.lib.utils.ChatUtils; -import net.bteuk.network.sql.PlotSQL; -import net.bteuk.network.utils.plotsystem.ReviewCategory; -import net.bteuk.network.utils.plotsystem.ReviewCategoryFeedback; -import net.bteuk.network.utils.plotsystem.ReviewSelection; import net.bteuk.plotsystem.PlotSystem; import net.kyori.adventure.inventory.Book; import net.kyori.adventure.text.Component; @@ -26,7 +26,11 @@ import org.bukkit.inventory.meta.WritableBookMeta; import org.jetbrains.annotations.NotNull; -import java.util.*; +import java.util.Collection; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; public class ReviewBook implements Listener { @@ -36,8 +40,6 @@ public class ReviewBook implements Listener { private static final ItemStack REVIEW_BOOK = createReviewBook(); - private final PlotSQL plotSQL = PlotSystem.getInstance().plotSQL; - private final HashMap reviewCategorySelection = new LinkedHashMap<>(); private final HashMap reviewCategoryFeedback = new HashMap<>(); @@ -48,13 +50,16 @@ public class ReviewBook implements Listener { private final ReviewHotbar reviewHotbar; + private final PlotAPI plotAPI; + private Book book; - public ReviewBook(PlotSystem instance, Player player, ReviewHotbar reviewHotbar) { + public ReviewBook(PlotSystem instance, Player player, ReviewHotbar reviewHotbar, PlotAPI plotAPI) { this.instance = instance; this.player = player; this.reviewHotbar = reviewHotbar; + this.plotAPI = plotAPI; initReviewCategorySelection(); updateReviewBook(); @@ -93,11 +98,11 @@ private static Component getReviewSelectionLine(Map.Entry initialReviewCateg reviewCategorySelection.put(categoryFeedback.category(), categoryFeedback.selection()); if (categoryFeedback.bookId() != 0) { // Get the pages of the book. - ArrayList pages = plotSQL.getStringList("SELECT contents FROM book_data WHERE id=" + categoryFeedback.bookId() + " ORDER BY page ASC;"); + List pages = plotAPI.getBookPages(categoryFeedback.bookId()); reviewCategoryFeedback.put(categoryFeedback.category(), createCategoryFeedback(categoryFeedback.category(), pages.toArray(String[]::new))); } @@ -185,7 +190,7 @@ public Map updateFeedback(int reviewId, if (isEdited(newBook)) { bookId = saveBook(newBook); } - plotSQL.update("UPDATE plot_category_feedback SET selection='" + newSelection.name() + "', book_id=" + bookId + " WHERE review_id=" + reviewId + " AND category='" + category.name() + "';"); + plotAPI.updatePlotCategoryFeedback(reviewId, category.name(), newSelection.name(), bookId); updatedReviewFeedback.put(category, new ReviewCategoryFeedback(category, newSelection, bookId)); } } @@ -307,7 +312,7 @@ private void saveCategoryFeedback(int reviewId, ReviewCategory category, ReviewS // Only save if there is at least a selection or feedback. // The General category can have no selection while having feedback. if (selection != ReviewSelection.NONE || bookId != 0) { - plotSQL.savePlotReviewCategoryFeedback(reviewId, category.name(), selection.name(), bookId); + plotAPI.savePlotReviewCategoryFeedback(reviewId, category.name(), selection.name(), bookId); } } @@ -317,14 +322,14 @@ private int saveBook(EditableBook book) { List pages = book.getBookPages(); // Create new book id. - int bookId = 1 + plotSQL.getInt("SELECT id FROM book_data ORDER BY id DESC;"); + int bookId = 1 + plotAPI.getHighestBookId(); // Iterate through all pages and store them in database. int i = 1; for (String page : pages) { if (!page.isBlank()) { - plotSQL.saveBook(bookId, i, page); + plotAPI.saveBook(bookId, i, page); i++; } } diff --git a/src/main/java/net/bteuk/plotsystem/utils/plugins/Multiverse.java b/src/main/java/net/bteuk/plotsystem/utils/plugins/Multiverse.java index 95ffebc..8c957d4 100644 --- a/src/main/java/net/bteuk/plotsystem/utils/plugins/Multiverse.java +++ b/src/main/java/net/bteuk/plotsystem/utils/plugins/Multiverse.java @@ -1,8 +1,5 @@ package net.bteuk.plotsystem.utils.plugins; -import com.onarandombox.MultiverseCore.MultiverseCore; -import com.onarandombox.MultiverseCore.api.MVWorldManager; -import com.onarandombox.MultiverseCore.api.MultiverseWorld; import com.sk89q.worldedit.bukkit.BukkitAdapter; import com.sk89q.worldguard.WorldGuard; import com.sk89q.worldguard.protection.flags.Flag; @@ -17,6 +14,8 @@ import org.bukkit.GameRule; import org.bukkit.World; import org.bukkit.WorldType; +import org.mvplugins.multiverse.core.MultiverseCore; +import org.mvplugins.multiverse.core.world.MultiverseWorld; import java.util.HashMap; import java.util.Map; diff --git a/src/main/java/net/bteuk/plotsystem/utils/plugins/WGCreatePlot.java b/src/main/java/net/bteuk/plotsystem/utils/plugins/WGCreatePlot.java index 82a234a..af8e99c 100644 --- a/src/main/java/net/bteuk/plotsystem/utils/plugins/WGCreatePlot.java +++ b/src/main/java/net/bteuk/plotsystem/utils/plugins/WGCreatePlot.java @@ -8,6 +8,7 @@ import com.sk89q.worldguard.protection.managers.storage.StorageException; import com.sk89q.worldguard.protection.regions.ProtectedPolygonalRegion; import net.bteuk.network.api.CoordinateAPI; +import net.bteuk.network.api.NetworkAPI; import net.bteuk.network.api.PlotAPI; import net.bteuk.network.lib.utils.ChatUtils; import net.bteuk.network.papercore.LocationAdapter; @@ -24,6 +25,8 @@ */ public class WGCreatePlot { + private final NetworkAPI networkAPI; + protected final PlotAPI plotAPI; private final PlotHelper plotHelper; @@ -33,8 +36,9 @@ public class WGCreatePlot { public int plotID; // Create a new instance of plots. - public WGCreatePlot(PlotAPI plotAPI, PlotHelper plotHelper, CoordinateAPI coordinateAPI) { - this.plotAPI = plotAPI; + public WGCreatePlot(NetworkAPI networkAPI, PlotHelper plotHelper) { + this.networkAPI = networkAPI; + this.plotAPI = networkAPI.getPlotAPI(); this.plotHelper = plotHelper; this.coordinateAPI = coordinateAPI; } From df2bc10b8d86ffccc58b23899f852e6053cfcfbe Mon Sep 17 00:00:00 2001 From: LM-Wolfert Date: Sat, 1 Nov 2025 18:05:45 +0100 Subject: [PATCH 10/21] Progress --- pom.xml | 2 +- .../java/net/bteuk/plotsystem/PlotSystem.java | 3 +- .../plotsystem/commands/CreateCommand.java | 7 +- .../plotsystem/commands/DeleteCommand.java | 9 +- .../plotsystem/commands/LocationCommand.java | 117 +++++++----------- .../commands/PlotSystemCommand.java | 8 +- .../plotsystem/commands/UpdateCommand.java | 7 +- .../net/bteuk/plotsystem/utils/Utils.java | 11 ++ .../plotsystem/utils/plugins/Multiverse.java | 41 +++--- 9 files changed, 103 insertions(+), 102 deletions(-) diff --git a/pom.xml b/pom.xml index 7d3b8cb..5c2577f 100644 --- a/pom.xml +++ b/pom.xml @@ -17,7 +17,7 @@ 1.21.8-R0.1-SNAPSHOT - faa7ec07b2 + 4cb0a3c1f3 5958727df9 5.3.3 diff --git a/src/main/java/net/bteuk/plotsystem/PlotSystem.java b/src/main/java/net/bteuk/plotsystem/PlotSystem.java index 0e0397c..7e87e01 100644 --- a/src/main/java/net/bteuk/plotsystem/PlotSystem.java +++ b/src/main/java/net/bteuk/plotsystem/PlotSystem.java @@ -8,6 +8,7 @@ import net.bteuk.network.api.NetworkAPI; import net.bteuk.network.lib.utils.ChatUtils; import net.bteuk.plotsystem.commands.ClaimCommand; +import net.bteuk.plotsystem.commands.LocationCommand; import net.bteuk.plotsystem.commands.PlotSystemCommand; import net.bteuk.plotsystem.commands.ReviewCommand; import net.bteuk.plotsystem.commands.ToggleOutlines; @@ -179,7 +180,7 @@ public void enablePlugin() { manager.registerEventHandler(LifecycleEvents.COMMANDS, event -> { final Commands commands = event.registrar(); - commands.register("plotsystem", "Deals will all plotsystem related commands.", List.of("ps"), new PlotSystemCommand(networkAPI.getPlotAPI(), plotHelper, networkAPI.getCoordinateAPI(), guiManager)); + commands.register("plotsystem", "Deals will all plotsystem related commands.", List.of("ps"), new PlotSystemCommand(networkAPI.getPlotAPI(), plotHelper, networkAPI.getCoordinateAPI(), guiManager, new LocationCommand(networkAPI))); commands.register("claim", "Used to claim the plot you're standing in.", List.of("claim"), new ClaimCommand(networkAPI, guiManager, plotHelper)); commands.register("toggleoutlines", "Toggles the visibility of outlines.", new ToggleOutlines(this)); commands.register("review", "Command for editing selections to reviewing categories during the reviewing process.", new ReviewCommand(this)); diff --git a/src/main/java/net/bteuk/plotsystem/commands/CreateCommand.java b/src/main/java/net/bteuk/plotsystem/commands/CreateCommand.java index 02130b7..900aed1 100644 --- a/src/main/java/net/bteuk/plotsystem/commands/CreateCommand.java +++ b/src/main/java/net/bteuk/plotsystem/commands/CreateCommand.java @@ -16,9 +16,12 @@ public class CreateCommand { private final PlotAPI plotAPI; - public CreateCommand(GuiManager guiManager, PlotAPI plotAPI) { + private final LocationCommand locationCommand; + + public CreateCommand(GuiManager guiManager, PlotAPI plotAPI, LocationCommand locationCommand) { this.guiManager = guiManager; this.plotAPI = plotAPI; + this.locationCommand = locationCommand; } public void create(CommandSender sender, String[] args) { @@ -32,7 +35,7 @@ public void create(CommandSender sender, String[] args) { switch (args[1]) { case "plot" -> createPlot(sender); - case "location" -> LocationCommand.createLocation(sender, args); + case "location" -> locationCommand.createLocation(sender, args); case "zone" -> createZone(sender); default -> sender.sendMessage(ChatUtils.error("/plotsystem create [plot, location, zone]")); } diff --git a/src/main/java/net/bteuk/plotsystem/commands/DeleteCommand.java b/src/main/java/net/bteuk/plotsystem/commands/DeleteCommand.java index 6a98330..6299e8e 100644 --- a/src/main/java/net/bteuk/plotsystem/commands/DeleteCommand.java +++ b/src/main/java/net/bteuk/plotsystem/commands/DeleteCommand.java @@ -23,9 +23,12 @@ public class DeleteCommand { private final PlotHelper plotHelper; - public DeleteCommand(PlotAPI plotAPI, PlotHelper plotHelper) { + private final LocationCommand locationCommand; + + public DeleteCommand(PlotAPI plotAPI, PlotHelper plotHelper, LocationCommand locationCommand) { this.plotAPI = plotAPI; this.plotHelper = plotHelper; + this.locationCommand = locationCommand; } public void delete(CommandSender sender, String[] args) { @@ -46,7 +49,7 @@ public void delete(CommandSender sender, String[] args) { case "location": - LocationCommand.deleteLocation(sender, args); + locationCommand.deleteLocation(sender, args); break; case "zone": @@ -116,7 +119,7 @@ private void deletePlot(CommandSender sender, String[] args) { } // Check if plot exists. - if (!plotSQL.hasRow("SELECT id FROM plot_data WHERE id=" + plotID + ";")) { + if (!plotAPI.plotExists(plotID)) { sender.sendMessage(ChatUtils.error("This plot does not exist.")); } diff --git a/src/main/java/net/bteuk/plotsystem/commands/LocationCommand.java b/src/main/java/net/bteuk/plotsystem/commands/LocationCommand.java index 1f54288..99867bd 100644 --- a/src/main/java/net/bteuk/plotsystem/commands/LocationCommand.java +++ b/src/main/java/net/bteuk/plotsystem/commands/LocationCommand.java @@ -6,10 +6,12 @@ import net.bteuk.network.api.NetworkAPI; import net.bteuk.network.api.PlotAPI; import net.bteuk.network.api.SQLAPI; +import net.bteuk.network.api.entity.NetworkLocation; import net.bteuk.network.lib.utils.ChatUtils; import net.bteuk.network.papercore.LocationAdapter; import net.bteuk.plotsystem.PlotSystem; import net.bteuk.plotsystem.utils.CopyRegionFormat; +import net.bteuk.plotsystem.utils.Utils; import net.bteuk.plotsystem.utils.plugins.Multiverse; import net.bteuk.plotsystem.utils.plugins.WorldEditor; import net.kyori.adventure.text.Component; @@ -69,9 +71,8 @@ public void createLocation(CommandSender sender, String[] args) { // Check if the location name is unique. if (plotAPI.hasLocation(commandArguments.location())) { - sender.sendMessage(ChatUtils.error("The location ") - .append(Component.text(commandArguments.location(), NamedTextColor.DARK_RED)) - .append(ChatUtils.error(" already exists."))); + sender.sendMessage( + ChatUtils.error("The location ").append(Component.text(commandArguments.location(), NamedTextColor.DARK_RED)).append(ChatUtils.error(" already exists."))); return; } @@ -127,19 +128,16 @@ public void createLocation(CommandSender sender, String[] args) { copyRegions(sender, regions); - int coordMin = coordinateAPI.addCoordinate(LocationAdapter.adapt(new Location( - Bukkit.getWorld(commandArguments.location()), - (regionXMin * 512), networkAPI.getMinY(), (regionZMin * 512), 0, 0))); + int coordMin = coordinateAPI.addCoordinate( + LocationAdapter.adapt(new Location(Bukkit.getWorld(commandArguments.location()), (regionXMin * 512), networkAPI.getMinY(), (regionZMin * 512), 0, 0))); - int coordMax = coordinateAPI.addCoordinate(LocationAdapter.adapt(new Location( - Bukkit.getWorld(commandArguments.location()), - ((regionXMax * 512) + 511), networkAPI.getMaxY() - 1, ((regionZMax * 512) + 511), 0, 0))); + int coordMax = coordinateAPI.addCoordinate(LocationAdapter.adapt( + new Location(Bukkit.getWorld(commandArguments.location()), ((regionXMax * 512) + 511), networkAPI.getMaxY() - 1, ((regionZMax * 512) + 511), 0, 0))); // Add the location to the database. if (plotAPI.createLocation(commandArguments.location, commandArguments.location, PlotSystem.SERVER_NAME, coordMin, coordMax, xTransform, zTransform)) { - sender.sendMessage(ChatUtils.success("Created new location ") - .append(Component.text(commandArguments.location(), NamedTextColor.DARK_AQUA))); + sender.sendMessage(ChatUtils.success("Created new location ").append(Component.text(commandArguments.location(), NamedTextColor.DARK_AQUA))); // Set the status of all effected regions in the region database. for (int i = regionXMin; i <= regionXMax; i++) { @@ -163,7 +161,7 @@ public void createLocation(CommandSender sender, String[] args) { } - teleportToLocation(sender, globalSQL, plotSQL, commandArguments.location(), coordMin, coordMax); + teleportToLocation(sender, commandArguments.location(), coordMin, coordMax); }); } @@ -190,11 +188,11 @@ public void updateLocation(CommandSender sender, String[] args) { } // Check if the new area is equal or larger than the existing area. - final int minCoordinateId = plotSQL.getInt("SELECT coordMin FROM location_data WHERE name='" + commandArguments.location() + "';"); - final int maxCoordinateId = plotSQL.getInt("SELECT coordMax FROM location_data WHERE name='" + commandArguments.location() + "';"); + final int minCoordinateId = plotAPI.getLocationCoordMin(commandArguments.location()); + final int maxCoordinateId = plotAPI.getLocationCoordMax(commandArguments.location()); - Coordinate minCoordinate = globalSQL.getCoordinate(minCoordinateId); - Coordinate maxCoordinate = globalSQL.getCoordinate(maxCoordinateId); + NetworkLocation minCoordinate = coordinateAPI.getLocation(minCoordinateId); + NetworkLocation maxCoordinate = coordinateAPI.getLocation(maxCoordinateId); if (commandArguments.isSmallerThan(minCoordinate, maxCoordinate)) { sender.sendMessage(ChatUtils.error("The new area must not be smaller than the current area.")); @@ -209,8 +207,8 @@ public void updateLocation(CommandSender sender, String[] args) { int regionZMax = Math.floorDiv(commandArguments.zmax(), 512); // Get the coordinate transformation of the location. - int xTransform = plotSQL.getInt("SELECT xTransform FROM location_data WHERE name='" + commandArguments.location() + "';"); - int zTransform = plotSQL.getInt("SELECT zTransform FROM location_data WHERE name='" + commandArguments.location() + "';"); + int xTransform = plotAPI.getXTransform(commandArguments.location()); + int zTransform = plotAPI.getZTransform(commandArguments.location()); // Get the worlds. String saveWorld = PlotSystem.getInstance().getConfig().getString("save_world"); @@ -242,7 +240,7 @@ public void updateLocation(CommandSender sender, String[] args) { } // Create a list of regions to copy-paste. - RegionHolder regionHolder = new RegionHolder(regionsToAdd, (int) minCoordinate.getY(), (int) maxCoordinate.getY(), copy, paste, xTransform, zTransform); + RegionHolder regionHolder = new RegionHolder(regionsToAdd, (int) minCoordinate.y(), (int) maxCoordinate.y(), copy, paste, xTransform, zTransform); List regions = getCopyRegions(sender, regionHolder); // Copy-paste the regions in the save world. @@ -252,29 +250,28 @@ public void updateLocation(CommandSender sender, String[] args) { copyRegions(sender, regions); - globalSQL.updateCoordinate(minCoordinateId, new Location(Bukkit.getWorld(commandArguments.location()), (regionXMin * 512), MIN_Y, (regionZMin * 512), 0, 0)); - globalSQL.updateCoordinate(maxCoordinateId, - new Location(Bukkit.getWorld(commandArguments.location()), ((regionXMax * 512) + 511), MAX_Y - 1, ((regionZMax * 512) + 511), 0, 0)); + World world = Bukkit.getWorld(commandArguments.location()); + coordinateAPI.updateCoordinate(minCoordinateId, LocationAdapter.adapt(new Location(world, (regionXMin * 512), world.getMinHeight(), (regionZMin * 512), 0, 0))); + coordinateAPI.updateCoordinate(maxCoordinateId, + LocationAdapter.adapt(new Location(world, ((regionXMax * 512) + 511), world.getMaxHeight() - 1, ((regionZMax * 512) + 511), 0, 0))); // Add the location to the database. for (Region region : regionsToAdd) { // Change region status in region database. // If it already exists remove members. - globalSQL.update("INSERT INTO server_events(uuid,type,server,event) VALUES(NULL,'network','" + globalSQL.getString( - "SELECT name FROM server_data WHERE type='EARTH';") + "'," + "'region set plotsystem " + region.name() + "');"); + eventAPI.createEvent(null, globalSQL.getString("SELECT name FROM server_data WHERE type='EARTH';"), "region set plotsystem " + region.name()); // Add region to database. - plotSQL.update( - "INSERT INTO regions(region,server,location) VALUES('" + region.name() + "','" + PlotSystem.SERVER_NAME + "','" + commandArguments.location() + "');"); + plotAPI.createPlotRegion(region.name(), PlotSystem.SERVER_NAME, commandArguments.location()); } sender.sendMessage(ChatUtils.success("Updated location %s", commandArguments.location())); - teleportToLocation(sender, globalSQL, plotSQL, commandArguments.location(), minCoordinateId, maxCoordinateId); + teleportToLocation(sender, commandArguments.location(), minCoordinateId, maxCoordinateId); }); } - public static void deleteLocation(CommandSender sender, String[] args) { + public void deleteLocation(CommandSender sender, String[] args) { // If sender is a player, check for permission. if (sender instanceof Player p) { @@ -290,9 +287,6 @@ public static void deleteLocation(CommandSender sender, String[] args) { return; } - PlotSQL plotSQL = Network.getInstance().getPlotSQL(); - GlobalSQL globalSQL = Network.getInstance().getGlobalSQL(); - // Check if location exists. if (!(plotSQL.hasRow("SELECT name FROM location_data WHERE name='" + args[2] + "';"))) { sender.sendMessage(ChatUtils.error("The location %s does not exist.", args[2])); @@ -300,7 +294,7 @@ public static void deleteLocation(CommandSender sender, String[] args) { } // Check if the location is on this server. - if (!(plotSQL.getString("SELECT server FROM location_data WHERE name='" + args[2] + "';").equals(PlotSystem.SERVER_NAME))) { + if (!(plotAPI.getLocationServer(args[2]).equals(PlotSystem.SERVER_NAME))) { sender.sendMessage(ChatUtils.error("This location is not on this server.")); return; } @@ -322,15 +316,14 @@ public static void deleteLocation(CommandSender sender, String[] args) { // Get save world. World saveWorld = Bukkit.getWorld(saveWorldName); - teleportPlayersFromLocation(args[2], saveWorld, plotSQL, globalSQL); + teleportPlayersFromLocation(args[2], saveWorld); // Delete location. if (Multiverse.deleteWorld(args[2])) { // Delete location from database. plotSQL.update("DELETE FROM location_data WHERE name='" + args[2] + "';"); - sender.sendMessage(ChatUtils.success("Deleted location ") - .append(Component.text(args[2], NamedTextColor.DARK_AQUA))); + sender.sendMessage(ChatUtils.success("Deleted location ").append(Component.text(args[2], NamedTextColor.DARK_AQUA))); LOGGER.info("Deleted location " + args[2] + "."); // Get regions from database. @@ -341,9 +334,7 @@ public static void deleteLocation(CommandSender sender, String[] args) { // Iterate through regions to unlock them on Earth. for (String region : regions) { - globalSQL.update("INSERT INTO server_events(uuid,type,server,event) VALUES(NULL,'network','" - + globalSQL.getString("SELECT name FROM server_data WHERE type='earth';") + "'," + - "'region set default " + region + "');"); + eventAPI.createEvent(null, globalSQL.getString("SELECT name FROM server_data WHERE type='EARTH';"), "region set default " + region); } } else { sender.sendMessage(ChatUtils.error("An error occurred while deleting the world.")); @@ -383,11 +374,11 @@ private static CommandArguments parseCommandArguments(CommandSender sender, Stri return new CommandArguments(args[2], xmin, ymin, zmin, xmax, ymax, zmax); } - private static List getCopyRegions(CommandSender sender, RegionHolder regionHolder) { + private List getCopyRegions(CommandSender sender, RegionHolder regionHolder) { List regionsToCopy = new ArrayList<>(); - final int yMin = max(regionHolder.ymin(), MIN_Y); - final int yMax = min(regionHolder.ymax(), MAX_Y - 1); + final int yMin = max(regionHolder.ymin(), networkAPI.getMinY()); + final int yMax = min(regionHolder.ymax(), networkAPI.getMaxY() - 1); for (Region region : regionHolder.regionsToAdd()) { // Split the region into 4 equal segments of 256x256. @@ -448,18 +439,14 @@ private static void copyRegions(CommandSender sender, List reg sender.sendMessage(ChatUtils.success("Terrain transfer has been completed.")); } - private static void teleportToLocation(CommandSender sender, GlobalSQL globalSQL, PlotSQL plotSQL, String location, int coordMin, int coordMax) { + private void teleportToLocation(CommandSender sender, String location, int coordMin, int coordMax) { // If sender is a player teleport them to the location. if (sender instanceof Player p) { // Get middle. - double x = ((globalSQL.getDouble("SELECT x FROM coordinates WHERE id=" + coordMax + ";") + - globalSQL.getDouble("SELECT x FROM coordinates WHERE id=" + coordMin + ";")) / 2) + - plotSQL.getInt("SELECT xTransform FROM location_data WHERE name='" + location + "';"); + double x = ((coordinateAPI.getX(coordMax) + coordinateAPI.getX(coordMin)) / 2) + plotAPI.getXTransform(location); - double z = ((globalSQL.getDouble("SELECT z FROM coordinates WHERE id=" + coordMax + ";") + - globalSQL.getDouble("SELECT z FROM coordinates WHERE id=" + coordMin + ";")) / 2) + - plotSQL.getInt("SELECT zTransform FROM location_data WHERE name='" + location + "';"); + double z = ((coordinateAPI.getZ(coordMax) + coordinateAPI.getZ(coordMin)) / 2) + plotAPI.getZTransform(location); // Teleport to the location. World world = Bukkit.getWorld(location); @@ -470,27 +457,19 @@ private static void teleportToLocation(CommandSender sender, GlobalSQL globalSQL y++; } - EventManager.createTeleportEvent(false, p.getUniqueId().toString(), "network", "teleport " + location + " " + x + " " + y + " " + z + " " - + p.getLocation().getYaw() + " " + p.getLocation().getPitch(), - "&aTeleported to location &3" + plotSQL.getString("SELECT alias FROM location_data WHERE name='" + location + "';"), p.getLocation()); + eventAPI.createTeleportEvent(false, p.getUniqueId().toString(), + "teleport " + location + " " + x + " " + y + " " + z + " " + p.getLocation().getYaw() + " " + p.getLocation().getPitch(), + "&aTeleported to location &3" + plotAPI.getLocationAlias(location), LocationAdapter.adapt(p.getLocation())); } } - private static void teleportPlayersFromLocation(String location, World saveWorld, PlotSQL plotSQL, GlobalSQL globalSQL) { - int coordMin = plotSQL.getInt("SELECT coordMin FROM location_data WHERE name='" + location + "';"); - int coordMax = plotSQL.getInt("SELECT coordMax FROM location_data WHERE name='" + location + "';"); + private void teleportPlayersFromLocation(String location, World saveWorld) { + int coordMin = plotAPI.getLocationCoordMin(location); + int coordMax = plotAPI.getLocationCoordMax(location); // Get middle. - double x = ((globalSQL.getDouble("SELECT x FROM coordinates WHERE id=" + coordMax + ";") + - globalSQL.getDouble("SELECT x FROM coordinates WHERE id=" + coordMin + ";")) / 2) + - plotSQL.getInt("SELECT xTransform FROM location_data WHERE name='" + location + "';"); - - double z = ((globalSQL.getDouble("SELECT z FROM coordinates WHERE id=" + coordMax + ";") + - globalSQL.getDouble("SELECT z FROM coordinates WHERE id=" + coordMin + ";")) / 2) + - plotSQL.getInt("SELECT zTransform FROM location_data WHERE name='" + location + "';"); - - x -= plotSQL.getInt("SELECT xTransform FROM location_data WHERE name='" + location + "';"); - z -= plotSQL.getInt("SELECT zTransform FROM location_data WHERE name='" + location + "';"); + double x = ((coordinateAPI.getX(coordMax) + coordinateAPI.getX(coordMin)) / 2); + double z = ((coordinateAPI.getZ(coordMax) + coordinateAPI.getZ(coordMin)) / 2); // Teleport all players away from the location. Location teleportLocation = new Location(saveWorld, x, Utils.getHighestYAt(saveWorld, (int) x, (int) z), z); @@ -509,12 +488,12 @@ private record CommandArguments(String location, int xmin, int ymin, int zmin, i * @param coordMax the max coordinate * @return whether the area is smaller than the input coordinates */ - private boolean isSmallerThan(Coordinate coordMin, Coordinate coordMax) { + private boolean isSmallerThan(NetworkLocation coordMin, NetworkLocation coordMax) { boolean smaller = coordMin == null || coordMax == null; - smaller = smaller || (xmin > coordMin.getX()); - smaller = smaller || (zmin > coordMin.getZ()); - smaller = smaller || (xmax < coordMax.getX()); - smaller = smaller || (zmax < coordMax.getZ()); + smaller = smaller || (xmin > coordMin.x()); + smaller = smaller || (zmin > coordMin.z()); + smaller = smaller || (xmax < coordMax.x()); + smaller = smaller || (zmax < coordMax.z()); return smaller; } } diff --git a/src/main/java/net/bteuk/plotsystem/commands/PlotSystemCommand.java b/src/main/java/net/bteuk/plotsystem/commands/PlotSystemCommand.java index 96f90f1..73b5b04 100644 --- a/src/main/java/net/bteuk/plotsystem/commands/PlotSystemCommand.java +++ b/src/main/java/net/bteuk/plotsystem/commands/PlotSystemCommand.java @@ -42,14 +42,14 @@ public class PlotSystemCommand implements BasicCommand, TabCompleter { private final UpdateCommand updateCommand; - public PlotSystemCommand(PlotAPI plotAPI, PlotHelper plotHelper, CoordinateAPI coordinateAPI, GuiManager guiManager) { + public PlotSystemCommand(PlotAPI plotAPI, PlotHelper plotHelper, CoordinateAPI coordinateAPI, GuiManager guiManager, LocationCommand locationCommand) { this.plotAPI = plotAPI; this.plotHelper = plotHelper; this.coordinateAPI = coordinateAPI; - this.createCommand = new CreateCommand(guiManager, plotAPI); - this.deleteCommand = new DeleteCommand(plotAPI, plotHelper); - this.updateCommand = new UpdateCommand(plotAPI); + this.createCommand = new CreateCommand(guiManager, plotAPI, locationCommand); + this.deleteCommand = new DeleteCommand(plotAPI, plotHelper, locationCommand); + this.updateCommand = new UpdateCommand(plotAPI, locationCommand); } @Override diff --git a/src/main/java/net/bteuk/plotsystem/commands/UpdateCommand.java b/src/main/java/net/bteuk/plotsystem/commands/UpdateCommand.java index 722542f..f25264d 100644 --- a/src/main/java/net/bteuk/plotsystem/commands/UpdateCommand.java +++ b/src/main/java/net/bteuk/plotsystem/commands/UpdateCommand.java @@ -16,8 +16,11 @@ public final class UpdateCommand { private final PlotAPI plotAPI; - public UpdateCommand(PlotAPI plotAPI) { + private final LocationCommand locationCommand; + + public UpdateCommand(PlotAPI plotAPI, LocationCommand locationCommand) { this.plotAPI = plotAPI; + this.locationCommand = locationCommand; } public void update(CommandSender sender, String[] args) { @@ -29,7 +32,7 @@ public void update(CommandSender sender, String[] args) { switch (args[1]) { case "plot" -> updatePlot(sender, args); - case "location" -> LocationCommand.updateLocation(sender, args); + case "location" -> locationCommand.updateLocation(sender, args); default -> sender.sendMessage(GENERIC_ERROR_MESSAGE); } } diff --git a/src/main/java/net/bteuk/plotsystem/utils/Utils.java b/src/main/java/net/bteuk/plotsystem/utils/Utils.java index f7c7148..b520bb3 100644 --- a/src/main/java/net/bteuk/plotsystem/utils/Utils.java +++ b/src/main/java/net/bteuk/plotsystem/utils/Utils.java @@ -2,6 +2,7 @@ import net.kyori.adventure.text.Component; import org.bukkit.Material; +import org.bukkit.World; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; @@ -43,4 +44,14 @@ public static String getDateTime(long time) { Date date = new Date(time); return formatter.format(date); } + + public static int getHighestYAt(World w, int x, int z) { + for (int i = (w.getMaxHeight() - 1); i >= w.getMinHeight(); i--) { + if (w.getBlockAt(x, i, z).getType() != Material.AIR) { + return i + 1; + } + } + // Return 65 as the default y. + return 65; + } } diff --git a/src/main/java/net/bteuk/plotsystem/utils/plugins/Multiverse.java b/src/main/java/net/bteuk/plotsystem/utils/plugins/Multiverse.java index 8c957d4..7156554 100644 --- a/src/main/java/net/bteuk/plotsystem/utils/plugins/Multiverse.java +++ b/src/main/java/net/bteuk/plotsystem/utils/plugins/Multiverse.java @@ -15,7 +15,11 @@ import org.bukkit.World; import org.bukkit.WorldType; import org.mvplugins.multiverse.core.MultiverseCore; +import org.mvplugins.multiverse.core.MultiverseCoreApi; import org.mvplugins.multiverse.core.world.MultiverseWorld; +import org.mvplugins.multiverse.core.world.WorldManager; +import org.mvplugins.multiverse.core.world.entity.EntitySpawnConfig; +import org.mvplugins.multiverse.core.world.options.CreateWorldOptions; import java.util.HashMap; import java.util.Map; @@ -26,32 +30,26 @@ public class Multiverse { public static boolean createVoidWorld(String name) { - MultiverseCore core = (MultiverseCore) Bukkit.getServer().getPluginManager().getPlugin("Multiverse-Core"); + MultiverseCoreApi core = MultiverseCoreApi.get(); if (core == null) { LOGGER.severe("Multiverse is a dependency of PlotSystem!"); return false; } - MVWorldManager worldManager = core.getMVWorldManager(); + WorldManager worldManager = core.getWorldManager(); + + worldManager.createWorld( + CreateWorldOptions.worldName(name).environment(World.Environment.NORMAL).worldType(WorldType.FLAT).generateStructures(false).generator("VoidGen:{biome" + + ":PLAINS}")) + .onSuccess(world -> { + world.setGameMode(GameMode.CREATIVE); + world.setDifficulty(Difficulty.PEACEFUL); + world.setAllowWeather(false); + world.setHunger(false); + world.setKeepSpawnInMemory(false); + }); - worldManager.addWorld( - name, - World.Environment.NORMAL, - null, - WorldType.FLAT, - false, - "VoidGen:{biome:PLAINS}" - ); - - MultiverseWorld MVWorld = worldManager.getMVWorld(name); - MVWorld.setGameMode(GameMode.CREATIVE); - MVWorld.setAllowAnimalSpawn(false); - MVWorld.setAllowMonsterSpawn(false); - MVWorld.setDifficulty(Difficulty.PEACEFUL); - MVWorld.setEnableWeather(false); - MVWorld.setHunger(false); - MVWorld.setKeepSpawnInMemory(false); // Get world from bukkit. World world = Bukkit.getWorld(name); @@ -71,8 +69,11 @@ public static boolean createVoidWorld(String name) { // Disable random tick. world.setGameRule(GameRule.RANDOM_TICK_SPEED, 0); - // Disable wandering traders. + // Disable spawning. + world.setGameRule(GameRule.DO_MOB_SPAWNING, false); world.setGameRule(GameRule.DO_TRADER_SPAWNING, false); + world.setGameRule(GameRule.DO_WARDEN_SPAWNING, false); + world.setGameRule(GameRule.DO_PATROL_SPAWNING, false); // Get worldguard. WorldGuard wg = WorldGuard.getInstance(); From e3b339b15ff63df1d119fab9f92c4f32932322ce Mon Sep 17 00:00:00 2001 From: LM-Wolfert Date: Sun, 2 Nov 2025 16:08:09 +0100 Subject: [PATCH 11/21] More progress --- pom.xml | 2 +- .../java/net/bteuk/plotsystem/PlotSystem.java | 14 ++- .../plotsystem/commands/ClaimCommand.java | 6 +- .../plotsystem/commands/LocationCommand.java | 14 +-- .../commands/PlotSystemCommand.java | 2 +- .../bteuk/plotsystem/events/ClaimEvent.java | 9 +- .../bteuk/plotsystem/events/DeleteEvent.java | 4 +- .../bteuk/plotsystem/events/EventManager.java | 4 - ...vent.java => PlotsystemTeleportEvent.java} | 89 ++++++++++--------- .../bteuk/plotsystem/events/RetractEvent.java | 37 +++++--- .../bteuk/plotsystem/events/ReviewEvent.java | 37 ++++---- .../bteuk/plotsystem/events/SubmitEvent.java | 27 ++++-- .../net/bteuk/plotsystem/utils/Holograms.java | 17 ++++ .../bteuk/plotsystem/utils/PlotHelper.java | 19 ++-- .../bteuk/plotsystem/utils/PlotHologram.java | 37 ++++---- .../plotsystem/utils/plugins/Multiverse.java | 33 +++---- .../utils/plugins/WGCreatePlot.java | 2 +- 17 files changed, 209 insertions(+), 144 deletions(-) rename src/main/java/net/bteuk/plotsystem/events/{TeleportEvent.java => PlotsystemTeleportEvent.java} (58%) create mode 100644 src/main/java/net/bteuk/plotsystem/utils/Holograms.java diff --git a/pom.xml b/pom.xml index 5c2577f..e9070a3 100644 --- a/pom.xml +++ b/pom.xml @@ -17,7 +17,7 @@ 1.21.8-R0.1-SNAPSHOT - 4cb0a3c1f3 + 66ae8e9052 5958727df9 5.3.3 diff --git a/src/main/java/net/bteuk/plotsystem/PlotSystem.java b/src/main/java/net/bteuk/plotsystem/PlotSystem.java index 7e87e01..bd2b9f8 100644 --- a/src/main/java/net/bteuk/plotsystem/PlotSystem.java +++ b/src/main/java/net/bteuk/plotsystem/PlotSystem.java @@ -14,6 +14,10 @@ import net.bteuk.plotsystem.commands.ToggleOutlines; import net.bteuk.plotsystem.events.ClaimEvent; import net.bteuk.plotsystem.events.CloseEvent; +import net.bteuk.plotsystem.events.DeleteEvent; +import net.bteuk.plotsystem.events.PlotsystemTeleportEvent; +import net.bteuk.plotsystem.events.RetractEvent; +import net.bteuk.plotsystem.events.ReviewEvent; import net.bteuk.plotsystem.listeners.ClaimEnter; import net.bteuk.plotsystem.listeners.CloseInventory; import net.bteuk.plotsystem.listeners.HologramClickEvent; @@ -130,7 +134,7 @@ public void enablePlugin() { final NetworkAPI networkAPI = networkProvider.getProvider(); this.guiManager = new GuiManager(); - this.plotHelper = new PlotHelper(); + this.plotHelper = new PlotHelper(networkAPI.getPlotAPI()); // Register hologram click event. new HologramClickEvent(this); @@ -169,8 +173,12 @@ public void enablePlugin() { new CloseInventory(this); // Events - networkAPI.getEventAPI().registerEvent("claim", new ClaimEvent(networkAPI, guiManager)); + networkAPI.getEventAPI().registerEvent("claim", new ClaimEvent(networkAPI, guiManager, plotHelper)); networkAPI.getEventAPI().registerEvent("close", new CloseEvent(networkAPI.getPlotAPI(), networkAPI.getChat())); + networkAPI.getEventAPI().registerEvent("retract", new RetractEvent(networkAPI.getPlotAPI(), plotHelper, networkAPI.getChat())); + networkAPI.getEventAPI().registerEvent("plotsystemteleport", new PlotsystemTeleportEvent(networkAPI.getPlotAPI(), networkAPI.getEventAPI(), networkAPI.getServerAPI())); + networkAPI.getEventAPI().registerEvent("review", new ReviewEvent(networkAPI.getPlotAPI(), plotHelper)); + networkAPI.getEventAPI().registerEvent("delete", new DeleteEvent(networkAPI.getPlotAPI(), plotHelper, networkAPI.getChat())); // Deals with tracking where players are in relation to plots. claimEnter = new ClaimEnter(this, networkAPI.getPlotAPI(), networkAPI.getGlobalSQL()); @@ -189,7 +197,7 @@ public void enablePlugin() { // Get all active plots (unclaimed, claimed, submitted, reviewing) and add holograms. List active_plots = networkAPI.getPlotAPI().getActivePlots(SERVER_NAME); - active_plots.forEach(plot -> plotHelper.addPlotHologram(new PlotHologram(plot))); + active_plots.forEach(plot -> plotHelper.addPlotHologram(new PlotHologram(plot, networkAPI.getPlotAPI(), networkAPI.getCoordinateAPI()))); } public void onDisable() { diff --git a/src/main/java/net/bteuk/plotsystem/commands/ClaimCommand.java b/src/main/java/net/bteuk/plotsystem/commands/ClaimCommand.java index 39d58f5..b018ee0 100644 --- a/src/main/java/net/bteuk/plotsystem/commands/ClaimCommand.java +++ b/src/main/java/net/bteuk/plotsystem/commands/ClaimCommand.java @@ -40,7 +40,7 @@ public ClaimCommand(NetworkAPI networkAPI, GuiManager guiManager, PlotHelper plo this.plotHelper = plotHelper; } - public static boolean hasClaimPermission(NetworkAPI networkAPI, Player player, PlotAPI plotAPI, int plot) { + public static boolean hasClaimPermission(NetworkAPI networkAPI, Player player, int plot) { // Make sure the player has permission to claim plots, else they must complete the tutorial first. // Only checked if tutorials are enabled. @@ -51,7 +51,7 @@ public static boolean hasClaimPermission(NetworkAPI networkAPI, Player player, P // Check if the player has permission to claim a plot of this difficulty. if (!player.hasPermission("uknet.plots.claim.all")) { - switch (plotAPI.getPlotDifficulty(plot)) { + switch (networkAPI.getPlotAPI().getPlotDifficulty(plot)) { case 1 -> { if (!player.hasPermission("uknet.plots.claim.easy")) { @@ -108,7 +108,7 @@ public void execute(CommandSourceStack stack, String @NotNull [] args) { // If the plot is valid open the claim plot gui. if (validPlot(user, plot, inPlot)) { - if (!hasClaimPermission(networkAPI, player, plotAPI, plot)) { + if (!hasClaimPermission(networkAPI, player, plot)) { return; } diff --git a/src/main/java/net/bteuk/plotsystem/commands/LocationCommand.java b/src/main/java/net/bteuk/plotsystem/commands/LocationCommand.java index 99867bd..fc6288e 100644 --- a/src/main/java/net/bteuk/plotsystem/commands/LocationCommand.java +++ b/src/main/java/net/bteuk/plotsystem/commands/LocationCommand.java @@ -228,7 +228,7 @@ public void updateLocation(CommandSender sender, String[] args) { } // Determine which regions are new, only copy them. - List existingRegions = plotSQL.getStringList("SELECT region FROM regions WHERE location='" + commandArguments.location() + "';"); + List existingRegions = plotAPI.getLocationRegions(commandArguments.location()); List regionsToAdd = new ArrayList<>(); for (int i = regionXMin; i <= regionXMax; i++) { for (int j = regionZMin; j <= regionZMax; j++) { @@ -288,7 +288,7 @@ public void deleteLocation(CommandSender sender, String[] args) { } // Check if location exists. - if (!(plotSQL.hasRow("SELECT name FROM location_data WHERE name='" + args[2] + "';"))) { + if (!(plotAPI.locationExists(args[2]))) { sender.sendMessage(ChatUtils.error("The location %s does not exist.", args[2])); return; } @@ -300,7 +300,7 @@ public void deleteLocation(CommandSender sender, String[] args) { } // If location has plots, cancel. - if (plotSQL.hasRow("SELECT id FROM plot_data WHERE location='" + args[2] + "' AND status<>'completed' AND status<>'deleted';")) { + if (!plotAPI.getActivePlotsForLocation(args[2]).isEmpty()) { sender.sendMessage(ChatUtils.error("This location active has plots, all plots must be deleted or completed to remove the location.")); return; } @@ -322,15 +322,15 @@ public void deleteLocation(CommandSender sender, String[] args) { if (Multiverse.deleteWorld(args[2])) { // Delete location from database. - plotSQL.update("DELETE FROM location_data WHERE name='" + args[2] + "';"); + plotAPI.deleteLocation(args[2]); sender.sendMessage(ChatUtils.success("Deleted location ").append(Component.text(args[2], NamedTextColor.DARK_AQUA))); LOGGER.info("Deleted location " + args[2] + "."); - // Get regions from database. - ArrayList regions = plotSQL.getStringList("SELECT region FROM regions WHERE location='" + args[2] + "';"); + // Get regions from the database. + List regions = plotAPI.getLocationRegions(args[2]); // Delete regions from database. - plotSQL.update("DELETE FROM regions WHERE location='" + args[2] + "';"); + plotAPI.deleteRegionsForLocation(args[2]); // Iterate through regions to unlock them on Earth. for (String region : regions) { diff --git a/src/main/java/net/bteuk/plotsystem/commands/PlotSystemCommand.java b/src/main/java/net/bteuk/plotsystem/commands/PlotSystemCommand.java index 73b5b04..3e6c94f 100644 --- a/src/main/java/net/bteuk/plotsystem/commands/PlotSystemCommand.java +++ b/src/main/java/net/bteuk/plotsystem/commands/PlotSystemCommand.java @@ -190,7 +190,7 @@ private void moveHologram(CommandSender sender, String[] args) { coordinate_id = coordinateAPI.addCoordinate(LocationAdapter.adapt(l)); plotAPI.updatePlotCoordinate(plot, coordinate_id); // Add the hologram. - plotHelper.addPlotHologram(new PlotHologram(plot)); + plotHelper.addPlotHologram(new PlotHologram(plot, plotAPI, coordinateAPI)); p.sendMessage(ChatUtils.success("Added marker to plot " + plot)); } else { // Update the existing coordinate location. diff --git a/src/main/java/net/bteuk/plotsystem/events/ClaimEvent.java b/src/main/java/net/bteuk/plotsystem/events/ClaimEvent.java index c36dde5..b7cb31c 100644 --- a/src/main/java/net/bteuk/plotsystem/events/ClaimEvent.java +++ b/src/main/java/net/bteuk/plotsystem/events/ClaimEvent.java @@ -8,6 +8,7 @@ import net.bteuk.plotsystem.PlotSystem; import net.bteuk.plotsystem.commands.ClaimCommand; import net.bteuk.plotsystem.gui.ClaimGui; +import net.bteuk.plotsystem.utils.PlotHelper; import net.bteuk.plotsystem.utils.User; import org.bukkit.Bukkit; import org.bukkit.entity.Player; @@ -25,10 +26,13 @@ public class ClaimEvent implements Event { private final GuiManager guiManager; - public ClaimEvent(NetworkAPI networkAPI, GuiManager guiManager) { + private final PlotHelper plotHelper; + + public ClaimEvent(NetworkAPI networkAPI, GuiManager guiManager, PlotHelper plotHelper) { this.networkAPI = networkAPI; this.plotAPI = networkAPI.getPlotAPI(); this.guiManager = guiManager; + this.plotHelper = plotHelper; } public void event(String uuid, String[] event, String sMessage) { @@ -98,9 +102,8 @@ public void event(String uuid, String[] event, String sMessage) { } u.player.closeInventory(); - u.claimGui = new ClaimGui(u, u.inPlot, guiManager); + u.claimGui = new ClaimGui(u, u.inPlot, guiManager, plotAPI, plotHelper); u.claimGui.open(p); - } } } diff --git a/src/main/java/net/bteuk/plotsystem/events/DeleteEvent.java b/src/main/java/net/bteuk/plotsystem/events/DeleteEvent.java index b29777b..f043de6 100644 --- a/src/main/java/net/bteuk/plotsystem/events/DeleteEvent.java +++ b/src/main/java/net/bteuk/plotsystem/events/DeleteEvent.java @@ -114,7 +114,7 @@ public void event(String uuid, String[] event, String message) { plotAPI.removePlotSubmission(id); // Set plot status to unclaimed. - PlotStatus currentStatus = PlotStatus.fromDatabaseValue(plotSQL.getString("SELECT status FROM plot_data WHERE id=" + id + ";")); + PlotStatus currentStatus = plotAPI.getPlotStatus(id); plotHelper.updatePlotStatus(id, PlotStatus.UNCLAIMED); // Send message to plot owner. @@ -138,7 +138,7 @@ public void event(String uuid, String[] event, String message) { if (currentStatus == PlotStatus.SUBMITTED) { // Send message to reviewers that a plot submission has been deleted. PlotMessage plotMessage = new PlotMessage("A submitted plot has been deleted, there %s %s submitted %s.", false); - Network.getInstance().getChat().sendSocketMesage(plotMessage); + chatAPI.sendPlotMessage(plotMessage); } }); } else if (event[1].equals("zone")) { diff --git a/src/main/java/net/bteuk/plotsystem/events/EventManager.java b/src/main/java/net/bteuk/plotsystem/events/EventManager.java index c758d83..9da6621 100644 --- a/src/main/java/net/bteuk/plotsystem/events/EventManager.java +++ b/src/main/java/net/bteuk/plotsystem/events/EventManager.java @@ -12,12 +12,8 @@ public static void event(String uuid, String[] event) { // Start the execution process by looking at the event message structure. switch (event[0]) { - case "teleport" -> TeleportEvent.event(uuid, event); // TODO: also exists in Network case "submit" -> SubmitEvent.event(uuid, event); - case "retract" -> RetractEvent.event(uuid, event); - case "delete" -> DeleteEvent.event(uuid, event); case "leave" -> LeaveEvent.event(uuid, event); - case "review" -> ReviewEvent.event(uuid, event); case "join" -> JoinEvent.event(uuid, event); case "kick" -> KickEvent.event(uuid, event); // TODO: Also exists in Network case "outlines" -> OutlinesEvent.event(uuid, event); diff --git a/src/main/java/net/bteuk/plotsystem/events/TeleportEvent.java b/src/main/java/net/bteuk/plotsystem/events/PlotsystemTeleportEvent.java similarity index 58% rename from src/main/java/net/bteuk/plotsystem/events/TeleportEvent.java rename to src/main/java/net/bteuk/plotsystem/events/PlotsystemTeleportEvent.java index 03958bc..3c69e28 100644 --- a/src/main/java/net/bteuk/plotsystem/events/TeleportEvent.java +++ b/src/main/java/net/bteuk/plotsystem/events/PlotsystemTeleportEvent.java @@ -1,15 +1,16 @@ package net.bteuk.plotsystem.events; import io.papermc.lib.PaperLib; -import net.bteuk.network.eventing.events.EventManager; +import net.bteuk.network.api.EventAPI; +import net.bteuk.network.api.PlotAPI; +import net.bteuk.network.api.ServerAPI; +import net.bteuk.network.api.entity.Event; +import net.bteuk.network.api.plotsystem.PlotStatus; import net.bteuk.network.lib.utils.ChatUtils; -import net.bteuk.network.utils.SwitchServer; -import net.bteuk.network.utils.Utils; -import net.bteuk.network.utils.enums.PlotStatus; -import net.bteuk.plotsystem.PlotSystem; +import net.bteuk.network.papercore.PlayerAdapter; import net.bteuk.plotsystem.exceptions.RegionManagerNotFoundException; import net.bteuk.plotsystem.exceptions.RegionNotFoundException; -import net.bteuk.plotsystem.utils.User; +import net.bteuk.plotsystem.utils.Utils; import net.bteuk.plotsystem.utils.plugins.WorldGuardFunctions; import org.apache.commons.lang3.StringUtils; import org.bukkit.Bukkit; @@ -19,53 +20,62 @@ import java.util.UUID; -import static net.bteuk.network.utils.Constants.SERVER_NAME; import static net.bteuk.plotsystem.PlotSystem.LOGGER; +import static net.bteuk.plotsystem.PlotSystem.SERVER_NAME; -public class TeleportEvent { +public class PlotsystemTeleportEvent implements Event { - public static void event(String uuid, String[] event) { + private final PlotAPI plotAPI; + + private final EventAPI eventAPI; + + private final ServerAPI serverAPI; + + public PlotsystemTeleportEvent(PlotAPI plotAPI, EventAPI eventAPI, ServerAPI serverAPI) { + this.plotAPI = plotAPI; + this.eventAPI = eventAPI; + this.serverAPI = serverAPI; + } + + public void event(String uuid, String[] event, String message) { // Events for teleporting if (event[1].equals("plot")) { // Get the user. - Player p = Bukkit.getPlayer(UUID.fromString(uuid)); + Player player = Bukkit.getPlayer(UUID.fromString(uuid)); - if (p == null) { + if (player == null) { // Send warning to console if player can't be found. LOGGER.warning(("Attempting to teleport player with uuid " + uuid + " but they are not on this server.")); return; } - User u = PlotSystem.getInstance().getUser(p); - // Convert the string id to int id. int id = Integer.parseInt(event[2]); // Teleport to specific plot id. // Get the server of the plot. - String server = u.plotSQL.getString("SELECT server FROM location_data WHERE name='" - + u.plotSQL.getString("SELECT location FROM plot_data WHERE id=" + id + ";") - + "';"); + String location = plotAPI.getPlotLocation(id); + String server = plotAPI.getLocationServer(location); // If the plot is on the current server teleport them directly. // Else teleport them to the correct server and them teleport them to the plot. if (StringUtils.equals(server, SERVER_NAME)) { // Get world of plot. - World world = Bukkit.getWorld(u.plotSQL.getString("SELECT location FROM plot_data WHERE id=" + id + ";")); + World world = Bukkit.getWorld(location); if (world == null) { - u.player.sendMessage(ChatUtils.error("An error occurred while teleporting to plot %s", String.valueOf(id))); + player.sendMessage(ChatUtils.error("An error occurred while teleporting to plot %s", String.valueOf(id))); return; } // Get the plot status - PlotStatus status = PlotStatus.fromDatabaseValue(u.plotSQL.getString("SELECT status FROM plot_data WHERE id=" + id + ";")); + PlotStatus status = plotAPI.getPlotStatus(id); if (status == PlotStatus.COMPLETED) { // Use the plot corners to get the location of the plot, since it no longer exists as a WorldGuard region. - int[][] corners = u.plotSQL.getPlotCorners(id); + int[][] corners = plotAPI.getPlotCorners(id); int sumX = 0; int sumZ = 0; @@ -80,36 +90,36 @@ public static void event(String uuid, String[] event) { double z = sumZ / (double) corners.length; // Add the coordinate transform to find the location in the build world. - x += u.plotSQL.getInt("SELECT xTransform FROM location_data WHERE name='" + world.getName() + "';"); - z += u.plotSQL.getInt("SELECT zTransform FROM location_data WHERE name='" + world.getName() + "';"); + x += plotAPI.getXTransform(location); + z += plotAPI.getZTransform(location); Location l = new Location(world, x, Utils.getHighestYAt(world, (int) x, (int) z), z); - PaperLib.teleportAsync(u.player, l); + PaperLib.teleportAsync(player, l); } else { // Get location of plot and teleport the player there. try { Location l = WorldGuardFunctions.getCurrentLocation(event[2], world); - PaperLib.teleportAsync(u.player, l); + PaperLib.teleportAsync(player, l); } catch (RegionNotFoundException | RegionManagerNotFoundException e) { - p.sendMessage(ChatUtils.error("You could not be teleported to the plot, please notify an admin.")); + player.sendMessage(ChatUtils.error("You could not be teleported to the plot, please notify an admin.")); e.printStackTrace(); } } } else { // Set the server join event. - EventManager.createJoinEvent(u.player.getUniqueId().toString(), "plotsystem", "teleport plot" + id); + eventAPI.createJoinEvent(player.getUniqueId().toString(), "plotsystemteleport plot" + id); // Teleport them to another server. - SwitchServer.switchServer(u.player, server); + serverAPI.switchServer(PlayerAdapter.adapt(player), server); } } else if (event[1].equals("zone")) { // Get the user. - Player p = Bukkit.getPlayer(UUID.fromString(uuid)); + Player player = Bukkit.getPlayer(UUID.fromString(uuid)); - if (p == null) { + if (player == null) { // Send warning to console if player can't be found. LOGGER.warning(("Attempting to teleport player with uuid " + uuid + " but they are not on this server.")); @@ -117,42 +127,37 @@ public static void event(String uuid, String[] event) { } - User u = PlotSystem.getInstance().getUser(p); - // Convert the string id to int id. int id = Integer.parseInt(event[2]); String zoneName = "z" + event[2]; // Teleport to specific zone id. // Get the server of the zone. - String server = u.plotSQL.getString("SELECT server FROM location_data WHERE name='" - + u.plotSQL.getString("SELECT location FROM zones WHERE id=" + id + ";") - + "';"); + String location = plotAPI.getZoneLocation(id); + String server = plotAPI.getLocationServer(location); - // If the zone is on the current server teleport them directly. + // If the zone is on the current server, teleport them directly. // Else teleport them to the correct server and them teleport them to the zone. if (server.equals(SERVER_NAME)) { // Get world of zone. - World world = Bukkit.getWorld(u.plotSQL.getString("SELECT location FROM zones WHERE id=" + id + ";")); + World world = Bukkit.getWorld(location); // Get location of zone and teleport the player there. try { Location l = WorldGuardFunctions.getCurrentLocation(zoneName, world); - u.player.teleport(l); + player.teleport(l); } catch (RegionNotFoundException | RegionManagerNotFoundException e) { - p.sendMessage(ChatUtils.error("You could not be teleported to the zone, please notify an admin.")); + player.sendMessage(ChatUtils.error("You could not be teleported to the zone, please notify an admin.")); e.printStackTrace(); } } else { - // Set the server join event. - EventManager.createJoinEvent(u.player.getUniqueId().toString(), "plotsystem", "teleport zone" + id); + eventAPI.createJoinEvent(player.getUniqueId().toString(), "plotsystemteleport zone" + id); // Teleport them to another server. - SwitchServer.switchServer(u.player, server); - + serverAPI.switchServer(PlayerAdapter.adapt(player), server); } } diff --git a/src/main/java/net/bteuk/plotsystem/events/RetractEvent.java b/src/main/java/net/bteuk/plotsystem/events/RetractEvent.java index 84a1bc9..8b82a1f 100644 --- a/src/main/java/net/bteuk/plotsystem/events/RetractEvent.java +++ b/src/main/java/net/bteuk/plotsystem/events/RetractEvent.java @@ -1,17 +1,30 @@ package net.bteuk.plotsystem.events; -import net.bteuk.network.Network; +import net.bteuk.network.api.ChatAPI; +import net.bteuk.network.api.PlotAPI; +import net.bteuk.network.api.entity.Event; +import net.bteuk.network.api.plotsystem.PlotStatus; import net.bteuk.network.lib.dto.DirectMessage; import net.bteuk.network.lib.dto.PlotMessage; import net.bteuk.network.lib.utils.ChatUtils; -import net.bteuk.network.utils.enums.PlotStatus; -import net.bteuk.plotsystem.PlotSystem; import net.bteuk.plotsystem.utils.PlotHelper; import net.kyori.adventure.text.Component; -public class RetractEvent { +public class RetractEvent implements Event { - public static void event(String uuid, String[] event) { + private final PlotAPI plotAPI; + + private final PlotHelper plotHelper; + + private final ChatAPI chatAPI; + + public RetractEvent(PlotAPI plotAPI, PlotHelper plotHelper, ChatAPI chatAPI) { + this.plotAPI = plotAPI; + this.plotHelper = plotHelper; + this.chatAPI = chatAPI; + } + + public void event(String uuid, String[] event, String sMessage) { // Events for retracting if (event[1].equals("plot")) { @@ -22,22 +35,22 @@ public static void event(String uuid, String[] event) { Component message; // Check if plot is submitted. - if (PlotSystem.getInstance().plotSQL.hasRow("SELECT id FROM plot_data WHERE id=" + id + " AND status='submitted';")) { + if (plotAPI.getPlotStatus(id) == PlotStatus.SUBMITTED) { // Set plot status to claimed. - PlotHelper.updatePlotStatus(id, PlotStatus.CLAIMED); + plotHelper.updatePlotStatus(id, PlotStatus.CLAIMED); // Remove submitted plot entry. - PlotSystem.getInstance().plotSQL.update("DELETE FROM plot_submission WHERE plot_id=" + id + ";"); + plotAPI.removePlotSubmission(id); - // Update last submit time in playerdata so the player doesn't have a cooldown anymore.. - PlotSystem.getInstance().globalSQL.update("UPDATE player_data SET last_submit=0 WHERE uuid='" + uuid + "';"); + // Update last submit time in playerdata so the player doesn't have a cooldown anymore. + plotAPI.updateLastSubmit(uuid, 0); message = ChatUtils.success("Retracted submission for Plot %s", String.valueOf(id)); // Send message to reviewers that a plot submission has been retracted. PlotMessage plotMessage = new PlotMessage("A submitted plot has been retracted, there %s %s submitted %s.", false); - Network.getInstance().getChat().sendSocketMesage(plotMessage); + chatAPI.sendPlotMessage(plotMessage); } else { @@ -48,7 +61,7 @@ public static void event(String uuid, String[] event) { DirectMessage directMessage = new DirectMessage("global", uuid, "server", message, true); - Network.getInstance().getChat().sendSocketMesage(directMessage); + chatAPI.sendDirectMessage(directMessage); } } diff --git a/src/main/java/net/bteuk/plotsystem/events/ReviewEvent.java b/src/main/java/net/bteuk/plotsystem/events/ReviewEvent.java index 4885624..55158b5 100644 --- a/src/main/java/net/bteuk/plotsystem/events/ReviewEvent.java +++ b/src/main/java/net/bteuk/plotsystem/events/ReviewEvent.java @@ -1,10 +1,10 @@ package net.bteuk.plotsystem.events; import io.papermc.lib.PaperLib; -import net.bteuk.network.Network; +import net.bteuk.network.api.PlotAPI; +import net.bteuk.network.api.entity.Event; +import net.bteuk.network.api.plotsystem.SubmittedStatus; import net.bteuk.network.lib.utils.ChatUtils; -import net.bteuk.network.sql.PlotSQL; -import net.bteuk.network.utils.enums.SubmittedStatus; import net.bteuk.plotsystem.PlotSystem; import net.bteuk.plotsystem.exceptions.RegionManagerNotFoundException; import net.bteuk.plotsystem.exceptions.RegionNotFoundException; @@ -23,9 +23,18 @@ import static net.bteuk.plotsystem.PlotSystem.LOGGER; -public class ReviewEvent { +public class ReviewEvent implements Event { - public static void event(String uuid, String[] event) { + private final PlotAPI plotAPI; + + private final PlotHelper plotHelper; + + public ReviewEvent(PlotAPI plotAPI, PlotHelper plotHelper) { + this.plotAPI = plotAPI; + this.plotHelper = plotHelper; + } + + public void event(String uuid, String[] event, String message) { // Events for claiming if (event[1].equals("plot")) { @@ -55,22 +64,20 @@ public static void event(String uuid, String[] event) { // Convert the string id to int id. int id = Integer.parseInt(event[2]); - // Get plotsql. - PlotSQL plotSQL = Network.getInstance().getPlotSQL(); - // Get world of plot. - World world = Bukkit.getWorld(plotSQL.getString("SELECT location FROM plot_data WHERE id=" + id + ";")); + String location = plotAPI.getPlotLocation(id); + World world = Bukkit.getWorld(location); // Check if the plot is still submitted. - if (plotSQL.hasRow("SELECT 1 FROM plot_submission WHERE plot_id=" + id + " AND status='" + SubmittedStatus.SUBMITTED.database_value + "';")) { + if (plotAPI.getPlotSubmissionStatus(id) == SubmittedStatus.SUBMITTED) { - //Set the plot to under review. - PlotHelper.updateSubmittedStatus(id, SubmittedStatus.UNDER_REVIEW); + // Set the plot to under review. + plotHelper.updateSubmittedStatus(id, SubmittedStatus.UNDER_REVIEW); - //Create new review instance for user. + // Create new review instance for user. user.setReview(new Review(PlotSystem.getInstance(), id, user)); - //Add the reviewer to the plot. + // Add the reviewer to the plot. try { WorldGuardFunctions.addMember(String.valueOf(id), uuid, world); } catch (RegionManagerNotFoundException | RegionNotFoundException e) { @@ -78,7 +85,7 @@ public static void event(String uuid, String[] event) { e.printStackTrace(); } - //Teleport the reviewer to the plot. + // Teleport the reviewer to the plot. try { Location l = WorldGuardFunctions.getCurrentLocation(event[2], world); CompletableFuture teleport = PaperLib.teleportAsync(player, l); diff --git a/src/main/java/net/bteuk/plotsystem/events/SubmitEvent.java b/src/main/java/net/bteuk/plotsystem/events/SubmitEvent.java index 538037a..60e6cc3 100644 --- a/src/main/java/net/bteuk/plotsystem/events/SubmitEvent.java +++ b/src/main/java/net/bteuk/plotsystem/events/SubmitEvent.java @@ -1,18 +1,29 @@ package net.bteuk.plotsystem.events; -import net.bteuk.network.Network; +import net.bteuk.network.api.PlotAPI; +import net.bteuk.network.api.SQLAPI; import net.bteuk.network.lib.dto.DirectMessage; import net.bteuk.network.lib.dto.PlotMessage; import net.bteuk.network.lib.utils.ChatUtils; -import net.bteuk.network.utils.Time; -import net.bteuk.network.utils.enums.PlotStatus; import net.bteuk.plotsystem.PlotSystem; import net.bteuk.plotsystem.utils.PlotHelper; import net.kyori.adventure.text.Component; public class SubmitEvent { - public static void event(String uuid, String[] event) { + private final PlotAPI plotAPI; + + private final PlotHelper plotHelper; + + private final SQLAPI globalSQL; + + public SubmitEvent(PlotAPI plotAPI, PlotHelper plotHelper, SQLAPI globalSQL) { + this.plotAPI = plotAPI; + this.plotHelper = plotHelper; + this.globalSQL = globalSQL; + } + + public void event(String uuid, String[] event) { // Events for submitting if (event[1].equals("plot")) { @@ -22,13 +33,13 @@ public static void event(String uuid, String[] event) { // Check if the player can submit a plot at this point in time. long lCoolDown = PlotSystem.getInstance().getConfig().getInt("submit_cooldown") * 60L * 1000L; - long lSubmit = PlotSystem.getInstance().globalSQL.getLong("SELECT last_submit FROM player_data WHERE uuid='" + uuid + "';"); + long lSubmit = globalSQL.getLong("SELECT last_submit FROM player_data WHERE uuid='" + uuid + "';"); Component message; - if (Time.currentTime() - lSubmit <= lCoolDown) { + if (System.currentTimeMillis() - lSubmit <= lCoolDown) { - long lon_dif = lCoolDown - (Time.currentTime() - lSubmit); + long lon_dif = lCoolDown - (System.currentTimeMillis() - lSubmit); int sec = (int) ((lon_dif / 1000) % 60); int min = (int) ((lon_dif / 1000) / 60); @@ -50,7 +61,7 @@ public static void event(String uuid, String[] event) { } else { // Check if plot is claimed. - if (PlotSystem.getInstance().plotSQL.hasRow("SELECT id FROM plot_data WHERE id=" + plotID + " AND status='claimed';")) { + if (plotAPI.isPlotClaimed(plotID)) { // Create new submitted plot key. PlotSystem.getInstance().plotSQL.update( diff --git a/src/main/java/net/bteuk/plotsystem/utils/Holograms.java b/src/main/java/net/bteuk/plotsystem/utils/Holograms.java new file mode 100644 index 0000000..b5df684 --- /dev/null +++ b/src/main/java/net/bteuk/plotsystem/utils/Holograms.java @@ -0,0 +1,17 @@ +package net.bteuk.plotsystem.utils; + +import eu.decentsoftware.holograms.api.DHAPI; +import eu.decentsoftware.holograms.api.holograms.Hologram; +import org.bukkit.Location; + +import java.util.List; + +public class Holograms { + public static Hologram createHologram(String name, Location location, List text) { + name = name.replace(" ", "_"); + if (DHAPI.getHologram(name) == null) { + return DHAPI.createHologram(name, location, text); + } + return null; + } +} diff --git a/src/main/java/net/bteuk/plotsystem/utils/PlotHelper.java b/src/main/java/net/bteuk/plotsystem/utils/PlotHelper.java index 93e757f..5605cab 100644 --- a/src/main/java/net/bteuk/plotsystem/utils/PlotHelper.java +++ b/src/main/java/net/bteuk/plotsystem/utils/PlotHelper.java @@ -1,6 +1,7 @@ package net.bteuk.plotsystem.utils; import lombok.Setter; +import net.bteuk.network.api.PlotAPI; import net.bteuk.network.api.plotsystem.PlotStatus; import net.bteuk.network.api.plotsystem.ReviewCategory; import net.bteuk.network.api.plotsystem.ReviewSelection; @@ -30,14 +31,20 @@ public class PlotHelper { private Map REVIEW_CATEGORY_THRESHOLDS; + private final PlotAPI plotAPI; + + public PlotHelper(PlotAPI plotAPI) { + this.plotAPI = plotAPI; + } + /** * Update the submitted status of a plot, will update any relevant holograms. * * @param id the plot id * @param submittedStatus the submitted status */ - public boolean updateSubmittedStatus(int id, SubmittedStatus submittedStatus) { - return updatePlotStatus(id, PlotStatus.SUBMITTED, submittedStatus); + public void updateSubmittedStatus(int id, SubmittedStatus submittedStatus) { + updatePlotStatus(id, PlotStatus.SUBMITTED, submittedStatus); } /** @@ -63,12 +70,12 @@ public boolean updatePlotStatus(int id, PlotStatus plotStatus) { */ private boolean updatePlotStatus(int id, PlotStatus status, SubmittedStatus submittedStatus) { boolean hasChanged = false; - if (!plotSQL.hasRow("SELECT 1 FROM plot_data WHERE id=" + id + " AND status='" + status.database_value + "'")) { - plotSQL.update("UPDATE plot_data SET status='" + status.database_value + "' WHERE id=" + id + ";"); + if (plotAPI.getPlotStatus(id) != status) { + plotAPI.setPlotStatus(id, status.database_value); hasChanged = true; } - if (submittedStatus != null && !plotSQL.hasRow("SELECT 1 FROM plot_submission WHERE plot_id=" + id + " AND status='" + submittedStatus.database_value + "'")) { - plotSQL.update("UPDATE plot_submission SET status='" + submittedStatus.database_value + "' WHERE plot_id=" + id + ";"); + if (submittedStatus != null && plotAPI.getPlotSubmissionStatus(id) != submittedStatus) { + plotAPI.setPlotSubmissionStatus(id, submittedStatus.database_value); hasChanged = true; } // Delay the hologram update until the plot has been completely updated. diff --git a/src/main/java/net/bteuk/plotsystem/utils/PlotHologram.java b/src/main/java/net/bteuk/plotsystem/utils/PlotHologram.java index 96e6304..07a203f 100644 --- a/src/main/java/net/bteuk/plotsystem/utils/PlotHologram.java +++ b/src/main/java/net/bteuk/plotsystem/utils/PlotHologram.java @@ -2,10 +2,11 @@ import eu.decentsoftware.holograms.api.holograms.Hologram; import lombok.Getter; -import net.bteuk.network.Network; -import net.bteuk.network.utils.Holograms; -import net.bteuk.network.utils.enums.PlotStatus; -import net.bteuk.network.utils.enums.SubmittedStatus; +import net.bteuk.network.api.CoordinateAPI; +import net.bteuk.network.api.PlotAPI; +import net.bteuk.network.api.entity.NetworkLocation; +import net.bteuk.network.api.plotsystem.PlotStatus; +import net.bteuk.network.api.plotsystem.SubmittedStatus; import net.bteuk.plotsystem.PlotSystem; import org.bukkit.Bukkit; import org.bukkit.Location; @@ -23,13 +24,19 @@ public class PlotHologram { @Getter private final int plot; + + private final PlotAPI plotAPI; + + private final CoordinateAPI coordinateAPI; private final HashMap holograms = new HashMap<>(); private PlotStatus plotStatus; private SubmittedStatus submittedStatus; private Location location; - public PlotHologram(int plot) { + public PlotHologram(int plot, PlotAPI plotAPI, CoordinateAPI coordinateAPI) { this.plot = plot; + this.plotAPI = plotAPI; + this.coordinateAPI = coordinateAPI; createHologram(); } @@ -73,16 +80,15 @@ public void setHologramVisibilityForPlayer(Player p) { PlotHologramType showType = PlotHologramType.ALL; if (plotStatus == PlotStatus.CLAIMED || plotStatus == PlotStatus.SUBMITTED) { // Check if the player is the plot owner. - if (Network.getInstance().getPlotSQL().hasRow("SELECT id FROM plot_members WHERE id=" + plot + " AND uuid='" + p.getUniqueId() + "' AND is_owner=1;")) { + if (plotAPI.isPlotOwner(plot, p.getUniqueId().toString())) { showType = PlotHologramType.OWNER; - } else if (Network.getInstance().getPlotSQL().hasRow("SELECT id FROM plot_members WHERE id=" + plot + " AND uuid='" + p.getUniqueId() + "' AND is_owner=0;")) { + } else if (plotAPI.isPlotMember(plot, p.getUniqueId().toString())) { showType = PlotHologramType.MEMBER; } else { if (plotStatus == PlotStatus.SUBMITTED) { switch (submittedStatus) { case SUBMITTED -> { - if (Network.getInstance().getPlotSQL() - .canReviewPlot(plot, p.getUniqueId().toString(), p.hasPermission("group.architect"), p.hasPermission("group.reviewer"))) { + if (plotAPI.canReviewPlot(plot, p.getUniqueId().toString(), p.hasPermission("group.architect"), p.hasPermission("group.reviewer"))) { showType = PlotHologramType.REVIEWER; } } @@ -95,7 +101,7 @@ public void setHologramVisibilityForPlayer(Player p) { } case AWAITING_VERIFICATION -> { - if (Network.getInstance().getPlotSQL().canVerifyPlot(plot, p.getUniqueId().toString(), p.hasPermission("group.reviewer"))) { + if (plotAPI.canVerifyPlot(plot, p.getUniqueId().toString(), p.hasPermission("group.reviewer"))) { showType = PlotHologramType.REVIEWER; } } @@ -128,20 +134,21 @@ public boolean isEmpty() { */ private void createHologram() { // Get the plot status. - plotStatus = PlotStatus.fromDatabaseValue(Network.getInstance().getPlotSQL().getString("SELECT status FROM plot_data WHERE id=" + plot + ";")); + plotStatus = plotAPI.getPlotStatus(plot); // If the status is submitted get the submitted status. if (plotStatus == PlotStatus.SUBMITTED) { - submittedStatus = SubmittedStatus.fromDatabaseValue(Network.getInstance().getPlotSQL().getString("SELECT status FROM plot_submission WHERE plot_id=" + plot + ";")); + submittedStatus = plotAPI.getPlotSubmissionStatus(plot); } // Get the location of the hologram. - int coordinate = Network.getInstance().getPlotSQL().getInt("SELECT coordinate_id FROM plot_data WHERE id=" + plot); + int coordinate = plotAPI.getPlotCoordinate(plot); if (coordinate != 0) { - location = Network.getInstance().getGlobalSQL().getLocation(coordinate); + NetworkLocation networkLocation = coordinateAPI.getLocation(coordinate); + location = new Location(Bukkit.getWorld(networkLocation.world()), networkLocation.x(), networkLocation.y(), networkLocation.z(), networkLocation.yaw(), networkLocation.pitch()); } - // Create the holograms, depending on the status, multiple holograms may be necessary for specific players. + // Create the holograms; depending on the status, multiple holograms may be necessary for specific players. createHolograms(); // Set the hologram visibility. diff --git a/src/main/java/net/bteuk/plotsystem/utils/plugins/Multiverse.java b/src/main/java/net/bteuk/plotsystem/utils/plugins/Multiverse.java index 7156554..4cfca3a 100644 --- a/src/main/java/net/bteuk/plotsystem/utils/plugins/Multiverse.java +++ b/src/main/java/net/bteuk/plotsystem/utils/plugins/Multiverse.java @@ -14,15 +14,14 @@ import org.bukkit.GameRule; import org.bukkit.World; import org.bukkit.WorldType; -import org.mvplugins.multiverse.core.MultiverseCore; import org.mvplugins.multiverse.core.MultiverseCoreApi; -import org.mvplugins.multiverse.core.world.MultiverseWorld; import org.mvplugins.multiverse.core.world.WorldManager; -import org.mvplugins.multiverse.core.world.entity.EntitySpawnConfig; import org.mvplugins.multiverse.core.world.options.CreateWorldOptions; +import org.mvplugins.multiverse.core.world.options.RemoveWorldOptions; import java.util.HashMap; import java.util.Map; +import java.util.concurrent.atomic.AtomicBoolean; import static net.bteuk.plotsystem.PlotSystem.LOGGER; @@ -134,42 +133,34 @@ public static boolean createVoidWorld(String name) { public static boolean hasWorld(String name) { - MultiverseCore core = (MultiverseCore) Bukkit.getServer().getPluginManager().getPlugin("Multiverse-Core"); + MultiverseCoreApi core = MultiverseCoreApi.get(); if (core == null) { LOGGER.severe("Multiverse is a dependency of PlotSystem!"); return false; } - // If the world exists return true. - - MVWorldManager worldManager = core.getMVWorldManager(); - - MultiverseWorld world = worldManager.getMVWorld(name); + WorldManager worldManager = core.getWorldManager(); - return world != null; + return worldManager.getWorld(name).isDefined(); } public static boolean deleteWorld(String name) { - MultiverseCore core = (MultiverseCore) Bukkit.getServer().getPluginManager().getPlugin("Multiverse-Core"); + MultiverseCoreApi core = MultiverseCoreApi.get(); if (core == null) { LOGGER.severe("Multiverse is a dependency of PlotSystem!"); return false; } - // If world exists delete it. - MVWorldManager worldManager = core.getMVWorldManager(); - - MultiverseWorld world = worldManager.getMVWorld(name); + WorldManager worldManager = core.getWorldManager(); - if (world == null) { - return false; - } else { - worldManager.deleteWorld(name); - return true; - } + AtomicBoolean success = new AtomicBoolean(false); + worldManager.getWorld(name).peek( + world -> success.set(worldManager.removeWorld(RemoveWorldOptions.world(world)).isSuccess()) + ); + return success.get(); } } diff --git a/src/main/java/net/bteuk/plotsystem/utils/plugins/WGCreatePlot.java b/src/main/java/net/bteuk/plotsystem/utils/plugins/WGCreatePlot.java index af8e99c..c21433c 100644 --- a/src/main/java/net/bteuk/plotsystem/utils/plugins/WGCreatePlot.java +++ b/src/main/java/net/bteuk/plotsystem/utils/plugins/WGCreatePlot.java @@ -84,7 +84,7 @@ public boolean createPlot(Player p, World world, String location, List Date: Sat, 15 Nov 2025 12:18:53 +0100 Subject: [PATCH 12/21] Complete migration to NetworkAPI. --- pom.xml | 19 ++- .../java/net/bteuk/plotsystem/PlotSystem.java | 25 ++- .../java/net/bteuk/plotsystem/Timers.java | 51 +++--- .../plotsystem/commands/ToggleOutlines.java | 8 +- .../plotsystem/commands/UpdateCommand.java | 2 +- .../bteuk/plotsystem/events/EventManager.java | 23 --- .../bteuk/plotsystem/events/JoinEvent.java | 62 ++++--- .../bteuk/plotsystem/events/LeaveEvent.java | 41 +++-- .../plotsystem/events/OutlinesEvent.java | 29 ++-- ...ickEvent.java => PlotsystemKickEvent.java} | 53 +++--- .../bteuk/plotsystem/events/RetractEvent.java | 12 +- .../bteuk/plotsystem/events/ReviewEvent.java | 13 +- .../bteuk/plotsystem/events/SubmitEvent.java | 25 +-- .../bteuk/plotsystem/events/VerifyEvent.java | 35 ++-- .../net/bteuk/plotsystem/gui/ClaimGui.java | 19 ++- .../plotsystem/listeners/ClaimEnter.java | 5 +- .../plotsystem/listeners/JoinServer.java | 8 +- .../plotsystem/listeners/PlayerInteract.java | 3 - .../reviewing/PreviousFeedbackGui.java | 92 +++++----- .../bteuk/plotsystem/reviewing/Review.java | 24 +-- .../plotsystem/reviewing/ReviewAction.java | 143 ++++++++-------- .../plotsystem/reviewing/ReviewActionGui.java | 33 ++-- .../bteuk/plotsystem/reviewing/ReviewGui.java | 9 +- .../plotsystem/reviewing/ReviewHotbar.java | 2 +- .../plotsystem/reviewing/Verification.java | 54 +++--- .../plotsystem/reviewing/VerificationGui.java | 19 ++- .../bteuk/plotsystem/utils/BlockLocation.java | 16 +- .../plotsystem/utils/BlockLocations.java | 76 ++++----- .../net/bteuk/plotsystem/utils/Inactive.java | 159 ++++++++---------- .../net/bteuk/plotsystem/utils/Outlines.java | 35 ++-- .../bteuk/plotsystem/utils/PlotHelper.java | 2 +- .../bteuk/plotsystem/utils/PlotValues.java | 8 +- .../bteuk/plotsystem/utils/SelectionTool.java | 9 +- .../java/net/bteuk/plotsystem/utils/User.java | 7 +- .../bteuk/plotsystem/utils/math/Point.java | 4 +- .../utils/plugins/WGCreatePlot.java | 22 +-- .../plotsystem/utils/plugins/WorldEditor.java | 10 +- .../utils/plugins/WorldGuardFunctions.java | 35 ++-- 38 files changed, 594 insertions(+), 598 deletions(-) delete mode 100644 src/main/java/net/bteuk/plotsystem/events/EventManager.java rename src/main/java/net/bteuk/plotsystem/events/{KickEvent.java => PlotsystemKickEvent.java} (66%) diff --git a/pom.xml b/pom.xml index e9070a3..b32524e 100644 --- a/pom.xml +++ b/pom.xml @@ -12,15 +12,18 @@ PlotSystem - 21 + 21 + ${java-version} UTF-8 1.21.8-R0.1-SNAPSHOT - 66ae8e9052 + 0c82879524 5958727df9 5.3.3 + + 1.18.42 @@ -28,9 +31,15 @@ org.apache.maven.plugins maven-compiler-plugin - 3.8.1 + 3.11.0 - ${java.version} + + + org.projectlombok + lombok + ${lombok.version} + + @@ -183,7 +192,7 @@ org.projectlombok lombok - 1.18.42 + ${lombok.version} provided diff --git a/src/main/java/net/bteuk/plotsystem/PlotSystem.java b/src/main/java/net/bteuk/plotsystem/PlotSystem.java index bd2b9f8..5f34ac6 100644 --- a/src/main/java/net/bteuk/plotsystem/PlotSystem.java +++ b/src/main/java/net/bteuk/plotsystem/PlotSystem.java @@ -15,9 +15,15 @@ import net.bteuk.plotsystem.events.ClaimEvent; import net.bteuk.plotsystem.events.CloseEvent; import net.bteuk.plotsystem.events.DeleteEvent; +import net.bteuk.plotsystem.events.JoinEvent; +import net.bteuk.plotsystem.events.LeaveEvent; +import net.bteuk.plotsystem.events.OutlinesEvent; +import net.bteuk.plotsystem.events.PlotsystemKickEvent; import net.bteuk.plotsystem.events.PlotsystemTeleportEvent; import net.bteuk.plotsystem.events.RetractEvent; import net.bteuk.plotsystem.events.ReviewEvent; +import net.bteuk.plotsystem.events.SubmitEvent; +import net.bteuk.plotsystem.events.VerifyEvent; import net.bteuk.plotsystem.listeners.ClaimEnter; import net.bteuk.plotsystem.listeners.CloseInventory; import net.bteuk.plotsystem.listeners.HologramClickEvent; @@ -60,7 +66,6 @@ public class PlotSystem extends JavaPlugin { // Returns an instance of the plugin. @Getter static PlotSystem instance; - public Timers timers; // Listeners public ClaimEnter claimEnter; // Returns the User ArrayList. @@ -154,9 +159,6 @@ public void enablePlugin() { // Outlines, this will be accessed from other classes, so it must have a getter and setter. outlines = new Outlines(); - // Setup Timers - timers = new Timers(this, networkAPI); - // Create bungeecord channel this.getServer().getMessenger().registerOutgoingPluginChannel(this, "BungeeCord"); @@ -167,7 +169,7 @@ public void enablePlugin() { selectionTool.setItemMeta(meta); // Listeners - new JoinServer(this, plotHelper); + new JoinServer(this, networkAPI, plotHelper); new QuitServer(this); new PlayerInteract(instance, networkAPI.getPlotAPI()); new CloseInventory(this); @@ -177,8 +179,14 @@ public void enablePlugin() { networkAPI.getEventAPI().registerEvent("close", new CloseEvent(networkAPI.getPlotAPI(), networkAPI.getChat())); networkAPI.getEventAPI().registerEvent("retract", new RetractEvent(networkAPI.getPlotAPI(), plotHelper, networkAPI.getChat())); networkAPI.getEventAPI().registerEvent("plotsystemteleport", new PlotsystemTeleportEvent(networkAPI.getPlotAPI(), networkAPI.getEventAPI(), networkAPI.getServerAPI())); - networkAPI.getEventAPI().registerEvent("review", new ReviewEvent(networkAPI.getPlotAPI(), plotHelper)); + networkAPI.getEventAPI().registerEvent("review", new ReviewEvent(networkAPI, plotHelper, guiManager)); networkAPI.getEventAPI().registerEvent("delete", new DeleteEvent(networkAPI.getPlotAPI(), plotHelper, networkAPI.getChat())); + networkAPI.getEventAPI().registerEvent("submit", new SubmitEvent(networkAPI.getPlotAPI(), plotHelper, networkAPI.getGlobalSQL(), networkAPI.getChat())); + networkAPI.getEventAPI().registerEvent("leave", new LeaveEvent(networkAPI.getPlotAPI(), plotHelper, networkAPI.getChat())); + networkAPI.getEventAPI().registerEvent("join", new JoinEvent(networkAPI.getPlotAPI(), plotHelper, networkAPI.getChat(), networkAPI.getGlobalSQL())); + networkAPI.getEventAPI().registerEvent("plotsystemkick", new PlotsystemKickEvent(networkAPI.getPlotAPI(), networkAPI.getChat(), networkAPI.getGlobalSQL())); + networkAPI.getEventAPI().registerEvent("outlines", new OutlinesEvent(networkAPI.getPlotAPI())); + networkAPI.getEventAPI().registerEvent("verify", new VerifyEvent(networkAPI, plotHelper, guiManager)); // Deals with tracking where players are in relation to plots. claimEnter = new ClaimEnter(this, networkAPI.getPlotAPI(), networkAPI.getGlobalSQL()); @@ -190,7 +198,7 @@ public void enablePlugin() { commands.register("plotsystem", "Deals will all plotsystem related commands.", List.of("ps"), new PlotSystemCommand(networkAPI.getPlotAPI(), plotHelper, networkAPI.getCoordinateAPI(), guiManager, new LocationCommand(networkAPI))); commands.register("claim", "Used to claim the plot you're standing in.", List.of("claim"), new ClaimCommand(networkAPI, guiManager, plotHelper)); - commands.register("toggleoutlines", "Toggles the visibility of outlines.", new ToggleOutlines(this)); + commands.register("toggleoutlines", "Toggles the visibility of outlines.", new ToggleOutlines(this, networkAPI.getPlotAPI())); commands.register("review", "Command for editing selections to reviewing categories during the reviewing process.", new ReviewCommand(this)); }); @@ -198,6 +206,9 @@ public void enablePlugin() { // Get all active plots (unclaimed, claimed, submitted, reviewing) and add holograms. List active_plots = networkAPI.getPlotAPI().getActivePlots(SERVER_NAME); active_plots.forEach(plot -> plotHelper.addPlotHologram(new PlotHologram(plot, networkAPI.getPlotAPI(), networkAPI.getCoordinateAPI()))); + + // Setup Timers + Timers.registerTimers(networkAPI, plotHelper, outlines, users); } public void onDisable() { diff --git a/src/main/java/net/bteuk/plotsystem/Timers.java b/src/main/java/net/bteuk/plotsystem/Timers.java index 25e36f3..cfc6f51 100644 --- a/src/main/java/net/bteuk/plotsystem/Timers.java +++ b/src/main/java/net/bteuk/plotsystem/Timers.java @@ -1,52 +1,45 @@ package net.bteuk.plotsystem; import net.bteuk.network.api.NetworkAPI; -import net.bteuk.network.api.TimerAPI; import net.bteuk.plotsystem.utils.Inactive; import net.bteuk.plotsystem.utils.Outlines; +import net.bteuk.plotsystem.utils.PlotHelper; import net.bteuk.plotsystem.utils.User; -import java.util.ArrayList; +import java.util.List; -public class Timers { - private final TimerAPI timerAPI; - // Users - private final ArrayList users; - // Outlines. - private final Outlines outlines; +public final class Timers { - public Timers(PlotSystem instance, NetworkAPI networkAPI) { - this.users = instance.getUsers(); - this.timerAPI = networkAPI.getTimerAPI(); - outlines = instance.getOutlines(); + private static boolean registered = false; + + private Timers() { + // Private constructor } - public void startTimers() { + public static void registerTimers(NetworkAPI networkAPI, PlotHelper plotHelper, Outlines outlines, List users) { + if (registered) { + PlotSystem.LOGGER.warning("Timers already registered!"); + return; + } // 1-second timer. // Update plot and zone outlines. - timerAPI.registerTimer(() -> { + networkAPI.getTimerAPI().registerTimer(() -> { for (User u : users) { - /* - Check if the location of the player has changed by more than 50 blocks, - or if the player has switched world. - If either are true, recalculate the outlines. - Else try to update the existing outlines, - catch a nullpointerexception, - this implies that the player has no outlines - then also add the outlines anew. + /* Check if the location of the player has changed by more than 50 blocks, or if the player has switched world. If either are true, recalculate the outlines. + Else try to update the existing outlines, catch a nullpointerexception, this implies that the player has no outlines then also add the outlines anew. */ if (!u.player.getWorld().equals(u.lastLocation.getWorld())) { - outlines.addNearbyOutlines(u); + outlines.addNearbyOutlines(u, networkAPI.getPlotAPI()); u.lastLocation = u.player.getLocation(); } else if (u.player.getLocation().distance(u.lastLocation) >= 50) { - outlines.addNearbyOutlines(u); + outlines.addNearbyOutlines(u, networkAPI.getPlotAPI()); u.lastLocation = u.player.getLocation(); } else { @@ -54,7 +47,7 @@ public void startTimers() { try { outlines.refreshOutlinesForPlayer(u.player); } catch (NullPointerException e) { - outlines.addNearbyOutlines(u); + outlines.addNearbyOutlines(u, networkAPI.getPlotAPI()); u.lastLocation = u.player.getLocation(); } @@ -65,9 +58,11 @@ public void startTimers() { // 1-hour timer. // Remove inactive plots. - timerAPI.registerTimer(() -> { - Inactive.cancelInactivePlots(); - Inactive.closeExpiredZones(); + networkAPI.getTimerAPI().registerTimer(() -> { + Inactive.cancelInactivePlots(networkAPI, plotHelper); + Inactive.closeExpiredZones(networkAPI); }, 1200L, 72000L); + + registered = true; } } \ No newline at end of file diff --git a/src/main/java/net/bteuk/plotsystem/commands/ToggleOutlines.java b/src/main/java/net/bteuk/plotsystem/commands/ToggleOutlines.java index 32817a6..b2c7c63 100644 --- a/src/main/java/net/bteuk/plotsystem/commands/ToggleOutlines.java +++ b/src/main/java/net/bteuk/plotsystem/commands/ToggleOutlines.java @@ -2,6 +2,7 @@ import io.papermc.paper.command.brigadier.BasicCommand; import io.papermc.paper.command.brigadier.CommandSourceStack; +import net.bteuk.network.api.PlotAPI; import net.bteuk.network.lib.utils.ChatUtils; import net.bteuk.plotsystem.PlotSystem; import net.bteuk.plotsystem.utils.User; @@ -15,8 +16,11 @@ public class ToggleOutlines implements BasicCommand { private final PlotSystem instance; - public ToggleOutlines(PlotSystem instance) { + private final PlotAPI plotAPI; + + public ToggleOutlines(PlotSystem instance, PlotAPI plotAPI) { this.instance = instance; + this.plotAPI = plotAPI; } @Override @@ -37,7 +41,7 @@ public void execute(@NotNull CommandSourceStack stack, String @NotNull [] args) if (u.isDisableOutlines()) { // Enable outlines. u.setDisableOutlines(false); - instance.getOutlines().addNearbyOutlines(u); + instance.getOutlines().addNearbyOutlines(u, plotAPI); player.sendMessage(ChatUtils.success("Enabled outlines")); } else { // Disable outlines. diff --git a/src/main/java/net/bteuk/plotsystem/commands/UpdateCommand.java b/src/main/java/net/bteuk/plotsystem/commands/UpdateCommand.java index f25264d..73c466d 100644 --- a/src/main/java/net/bteuk/plotsystem/commands/UpdateCommand.java +++ b/src/main/java/net/bteuk/plotsystem/commands/UpdateCommand.java @@ -81,6 +81,6 @@ private void updatePlot(CommandSender sender, String[] args) { sender.sendMessage(ChatUtils.success("Updated difficulty of plot %s to %s.", args[2], args[5])); // Update the plot outlines. - PlotSystem.getInstance().getUsers().forEach(PlotSystem.getInstance().getOutlines()::addNearbyOutlines); + PlotSystem.getInstance().getUsers().forEach(user -> PlotSystem.getInstance().getOutlines().addNearbyOutlines(user, plotAPI)); } } diff --git a/src/main/java/net/bteuk/plotsystem/events/EventManager.java b/src/main/java/net/bteuk/plotsystem/events/EventManager.java deleted file mode 100644 index 9da6621..0000000 --- a/src/main/java/net/bteuk/plotsystem/events/EventManager.java +++ /dev/null @@ -1,23 +0,0 @@ -package net.bteuk.plotsystem.events; - -import java.util.Arrays; - -import static net.bteuk.plotsystem.PlotSystem.LOGGER; - -public class EventManager { - - public static void event(String uuid, String[] event) { - - LOGGER.info("Event: " + Arrays.toString(event)); - - // Start the execution process by looking at the event message structure. - switch (event[0]) { - case "submit" -> SubmitEvent.event(uuid, event); - case "leave" -> LeaveEvent.event(uuid, event); - case "join" -> JoinEvent.event(uuid, event); - case "kick" -> KickEvent.event(uuid, event); // TODO: Also exists in Network - case "outlines" -> OutlinesEvent.event(uuid, event); - case "verify" -> VerifyEvent.event(uuid, event); - } - } -} diff --git a/src/main/java/net/bteuk/plotsystem/events/JoinEvent.java b/src/main/java/net/bteuk/plotsystem/events/JoinEvent.java index 8089bcd..5ed94b3 100644 --- a/src/main/java/net/bteuk/plotsystem/events/JoinEvent.java +++ b/src/main/java/net/bteuk/plotsystem/events/JoinEvent.java @@ -1,10 +1,11 @@ package net.bteuk.plotsystem.events; -import net.bteuk.network.Network; +import net.bteuk.network.api.ChatAPI; +import net.bteuk.network.api.PlotAPI; +import net.bteuk.network.api.SQLAPI; +import net.bteuk.network.api.entity.Event; import net.bteuk.network.lib.dto.DirectMessage; import net.bteuk.network.lib.utils.ChatUtils; -import net.bteuk.network.sql.PlotSQL; -import net.bteuk.network.utils.Time; import net.bteuk.plotsystem.PlotSystem; import net.bteuk.plotsystem.exceptions.RegionManagerNotFoundException; import net.bteuk.plotsystem.exceptions.RegionNotFoundException; @@ -16,9 +17,24 @@ import java.util.UUID; -public class JoinEvent { +public class JoinEvent implements Event { - public static void event(String uuid, String[] event) { + private final PlotAPI plotAPI; + + private final PlotHelper plotHelper; + + private final ChatAPI chatAPI; + + private final SQLAPI globalAPI; + + public JoinEvent(PlotAPI plotAPI, PlotHelper plotHelper, ChatAPI chatAPI, SQLAPI globalAPI) { + this.plotAPI = plotAPI; + this.plotHelper = plotHelper; + this.chatAPI = chatAPI; + this.globalAPI = globalAPI; + } + + public void event(String uuid, String[] event, String sMessage) { // Events for retracting if (event[1].equals("plot")) { @@ -31,46 +47,44 @@ public static void event(String uuid, String[] event) { Component message = ChatUtils.success("You have joined Plot %s", String.valueOf(id)); - PlotSQL plotSQL = Network.getInstance().getPlotSQL(); - // Check if you have not already reached the maximum number of plots. - if (plotSQL.getInt("SELECT count(id) FROM plot_members WHERE uuid='" + uuid + "';") >= PlotSystem.getInstance().getConfig().getInt("plot_maximum")) { + if (plotAPI.getNumberOfPlots(uuid) >= PlotSystem.getInstance().getConfig().getInt("plot_maximum")) { message = ChatUtils.error("You have reached the maximum number of plots."); } else { // Add the player to the database. - plotSQL.update("INSERT INTO plot_members(id,uuid,is_owner,last_enter) VALUES(" + id + ",'" + uuid + "',0," + Time.currentTime() + ");"); + plotAPI.createPlotMember(id, uuid); // Add the player to the worldguard region. try { - WorldGuardFunctions.addMember(String.valueOf(id), uuid, Bukkit.getWorld(plotSQL.getString("SELECT location FROM plot_data WHERE id=" + id + ";"))); + WorldGuardFunctions.addMember(String.valueOf(id), uuid, Bukkit.getWorld(plotAPI.getPlotLocation(id))); } catch (RegionManagerNotFoundException | RegionNotFoundException e) { DirectMessage directMessage = new DirectMessage("global", uuid, "server", ChatUtils.error("An error occurred while adding you to the plot, please contact an administrator."), false); - Network.getInstance().getChat().sendSocketMesage(directMessage); + chatAPI.sendDirectMessage(directMessage); return; } // Send a message to the plot owner. - DirectMessage directMessage = new DirectMessage("global", plotSQL.getString("SELECT uuid FROM plot_members WHERE id=" + id + " AND is_owner=1;"), "server", - ChatUtils.success("%s has joined your plot %s", Network.getInstance().getGlobalSQL().getString("SELECT name FROM player_data WHERE uuid='" + uuid + "';"), + DirectMessage directMessage = new DirectMessage("global", plotAPI.getPlotOwner(id), "server", + ChatUtils.success("%s has joined your plot %s", globalAPI.getString("SELECT name FROM player_data WHERE uuid='" + uuid + "';"), String.valueOf(id)), false); - Network.getInstance().getChat().sendSocketMesage(directMessage); + chatAPI.sendDirectMessage(directMessage); // If the player is on the server, update the hologram. if (p != null) { - PlotHelper.updatePlotHologram(id); + plotHelper.updatePlotHologram(id); } } DirectMessage directMessage = new DirectMessage("global", uuid, "server", message, false); - Network.getInstance().getChat().sendSocketMesage(directMessage); + chatAPI.sendDirectMessage(directMessage); } else if (event[1].equals("zone")) { @@ -79,30 +93,28 @@ public static void event(String uuid, String[] event) { Component message = ChatUtils.success("You have joined Zone %s", String.valueOf(id)); - PlotSQL plotSQL = Network.getInstance().getPlotSQL(); - // Add the player to the database. - plotSQL.update("INSERT INTO zone_members(id,uuid,is_owner) VALUES(" + id + ",'" + uuid + "',0);"); + plotAPI.createZoneMember(id, uuid); // Add the player to the worldguard region. try { - WorldGuardFunctions.addMember("z" + id, uuid, Bukkit.getWorld(plotSQL.getString("SELECT location FROM zones WHERE id=" + id + ";"))); + WorldGuardFunctions.addMember("z" + id, uuid, Bukkit.getWorld(plotAPI.getZoneLocation(id))); } catch (RegionManagerNotFoundException | RegionNotFoundException e) { DirectMessage directMessage = new DirectMessage("global", uuid, "server", ChatUtils.error("An error occurred while adding you to the zone, please contact an administrator."), false); - Network.getInstance().getChat().sendSocketMesage(directMessage); + chatAPI.sendDirectMessage(directMessage); return; } // Send a message to the zone owner. - DirectMessage ownerMessage = new DirectMessage("global", plotSQL.getString("SELECT uuid FROM zone_members WHERE id=" + id + " AND is_owner=1;"), "server", - ChatUtils.success("%s has joined your Zone %s", Network.getInstance().getGlobalSQL().getString("SELECT name FROM player_data WHERE uuid='" + uuid + "';"), + DirectMessage ownerMessage = new DirectMessage("global", plotAPI.getZoneOwner(id), "server", + ChatUtils.success("%s has joined your Zone %s", globalAPI.getString("SELECT name FROM player_data WHERE uuid='" + uuid + "';"), String.valueOf(id)), true); - Network.getInstance().getChat().sendSocketMesage(ownerMessage); + chatAPI.sendDirectMessage(ownerMessage); DirectMessage directMessage = new DirectMessage("global", uuid, "server", message, false); - Network.getInstance().getChat().sendSocketMesage(directMessage); + chatAPI.sendDirectMessage(directMessage); } } diff --git a/src/main/java/net/bteuk/plotsystem/events/LeaveEvent.java b/src/main/java/net/bteuk/plotsystem/events/LeaveEvent.java index 289fdd4..d9abed5 100644 --- a/src/main/java/net/bteuk/plotsystem/events/LeaveEvent.java +++ b/src/main/java/net/bteuk/plotsystem/events/LeaveEvent.java @@ -1,9 +1,10 @@ package net.bteuk.plotsystem.events; -import net.bteuk.network.Network; +import net.bteuk.network.api.ChatAPI; +import net.bteuk.network.api.PlotAPI; +import net.bteuk.network.api.entity.Event; import net.bteuk.network.lib.dto.DirectMessage; import net.bteuk.network.lib.utils.ChatUtils; -import net.bteuk.plotsystem.PlotSystem; import net.bteuk.plotsystem.exceptions.RegionManagerNotFoundException; import net.bteuk.plotsystem.exceptions.RegionNotFoundException; import net.bteuk.plotsystem.utils.PlotHelper; @@ -17,9 +18,21 @@ import static net.bteuk.plotsystem.PlotSystem.LOGGER; -public class LeaveEvent { +public class LeaveEvent implements Event { - public static void event(String uuid, String[] event) { + private final PlotAPI plotAPI; + + private final PlotHelper plotHelper; + + private final ChatAPI chatAPI; + + public LeaveEvent(PlotAPI plotAPI, PlotHelper plotHelper, ChatAPI chatAPI) { + this.plotAPI = plotAPI; + this.plotHelper = plotHelper; + this.chatAPI = chatAPI; + } + + public void event(String uuid, String[] event, String message) { // Events for leaving if (event[1].equals("plot")) { @@ -28,7 +41,7 @@ public static void event(String uuid, String[] event) { int id = Integer.parseInt(event[2]); // Get worlds of plot. - World world = Bukkit.getWorld(PlotSystem.getInstance().plotSQL.getString("SELECT location FROM plot_data WHERE id=" + id + ";")); + World world = Bukkit.getWorld(plotAPI.getPlotLocation(id)); if (world == null) { @@ -39,30 +52,30 @@ public static void event(String uuid, String[] event) { } - // Remove member from plot. + // Remove member from the plot. try { WorldGuardFunctions.removeMember(event[2], uuid, world); } catch (RegionManagerNotFoundException | RegionNotFoundException e) { DirectMessage directMessage = new DirectMessage("global", uuid, "server", ChatUtils.error("An error occurred while removing you from the plot, please contact an administrator."), false); - Network.getInstance().getChat().sendSocketMesage(directMessage); + chatAPI.sendDirectMessage(directMessage); return; } // Remove members from plot in database. - PlotSystem.getInstance().plotSQL.update("DELETE FROM plot_members WHERE id=" + id + " AND uuid='" + uuid + "';"); + plotAPI.removePlotMember(id, uuid); // Send message to plot owner. Player p = Bukkit.getPlayer(UUID.fromString(uuid)); if (p != null) { // Update the hologram since they are on the server. - PlotHelper.updatePlotHologram(id); + plotHelper.updatePlotHologram(id); } DirectMessage directMessage = new DirectMessage("global", uuid, "server", ChatUtils.success("You have left Plot %s", String.valueOf(id)), true); - Network.getInstance().getChat().sendSocketMesage(directMessage); + chatAPI.sendDirectMessage(directMessage); } else if (event[1].equals("zone")) { @@ -70,7 +83,7 @@ public static void event(String uuid, String[] event) { int id = Integer.parseInt(event[2]); // Get worlds of plot. - World world = Bukkit.getWorld(PlotSystem.getInstance().plotSQL.getString("SELECT location FROM zones WHERE id=" + id + ";")); + World world = Bukkit.getWorld(plotAPI.getZoneLocation(id)); if (world == null) { @@ -87,16 +100,16 @@ public static void event(String uuid, String[] event) { } catch (RegionManagerNotFoundException | RegionNotFoundException e) { DirectMessage directMessage = new DirectMessage("global", uuid, "server", ChatUtils.error("An error occurred while removing you from the zone, please contact an administrator."), false); - Network.getInstance().getChat().sendSocketMesage(directMessage); + chatAPI.sendDirectMessage(directMessage); return; } // Remove members from zone in database. - PlotSystem.getInstance().plotSQL.update("DELETE FROM zone_members WHERE id=" + id + " AND uuid='" + uuid + "';"); + plotAPI.removeZoneMember(id, uuid); DirectMessage directMessage = new DirectMessage("global", uuid, "server", ChatUtils.success("You have left Zone %s", String.valueOf(id)), true); - Network.getInstance().getChat().sendSocketMesage(directMessage); + chatAPI.sendDirectMessage(directMessage); } } } diff --git a/src/main/java/net/bteuk/plotsystem/events/OutlinesEvent.java b/src/main/java/net/bteuk/plotsystem/events/OutlinesEvent.java index 8a39996..63a91c4 100644 --- a/src/main/java/net/bteuk/plotsystem/events/OutlinesEvent.java +++ b/src/main/java/net/bteuk/plotsystem/events/OutlinesEvent.java @@ -1,5 +1,7 @@ package net.bteuk.plotsystem.events; +import net.bteuk.network.api.PlotAPI; +import net.bteuk.network.api.entity.Event; import net.bteuk.network.lib.utils.ChatUtils; import net.bteuk.plotsystem.PlotSystem; import net.bteuk.plotsystem.utils.User; @@ -13,18 +15,25 @@ /** * Event to allow adding/removing outlines for specific plots. */ -public class OutlinesEvent { - public static void event(String uuid, String[] event) { +public class OutlinesEvent implements Event { + + private final PlotAPI plotAPI; + + public OutlinesEvent(PlotAPI plotAPI) { + this.plotAPI = plotAPI; + } + + public void event(String uuid, String[] event, String message) { // Get the user. - Player p = Bukkit.getPlayer(UUID.fromString(uuid)); - if (p == null) { + Player player = Bukkit.getPlayer(UUID.fromString(uuid)); + if (player == null) { LOGGER.warning("Player " + uuid + " is not on the server the event was sent to!"); return; } - User user = PlotSystem.getInstance().getUser(p); + User user = PlotSystem.getInstance().getUser(player); if (user == null) { - LOGGER.warning("User " + p.getName() + " is not on the server the event was sent to!"); + LOGGER.warning("User " + player.getName() + " is not on the server the event was sent to!"); return; } @@ -35,17 +44,17 @@ public static void event(String uuid, String[] event) { // Remove the plot from the list of ignored outlines. user.getSkipOutlines().remove(event[2]); // Add the outlines back - PlotSystem.getInstance().getOutlines().addPlotOutlineForPlayer(event[2], p); + PlotSystem.getInstance().getOutlines().addPlotOutlineForPlayer(event[2], player, plotAPI); // Notify player. - p.sendMessage(ChatUtils.success("Enabled outlines for plot " + event[2])); + player.sendMessage(ChatUtils.success("Enabled outlines for plot " + event[2])); } else { // Disable: // Add the plot to the list of ignored outlines. user.getSkipOutlines().add(event[2]); // Remove the outline. - PlotSystem.getInstance().getOutlines().removePlotOutlineForPlayer(event[2], p); + PlotSystem.getInstance().getOutlines().removePlotOutlineForPlayer(event[2], player); // Notify player. - p.sendMessage(ChatUtils.success("Disabled outlines for plot " + event[2])); + player.sendMessage(ChatUtils.success("Disabled outlines for plot " + event[2])); } } } diff --git a/src/main/java/net/bteuk/plotsystem/events/KickEvent.java b/src/main/java/net/bteuk/plotsystem/events/PlotsystemKickEvent.java similarity index 66% rename from src/main/java/net/bteuk/plotsystem/events/KickEvent.java rename to src/main/java/net/bteuk/plotsystem/events/PlotsystemKickEvent.java index 199840d..bdd503f 100644 --- a/src/main/java/net/bteuk/plotsystem/events/KickEvent.java +++ b/src/main/java/net/bteuk/plotsystem/events/PlotsystemKickEvent.java @@ -1,94 +1,101 @@ package net.bteuk.plotsystem.events; -import net.bteuk.network.Network; +import net.bteuk.network.api.ChatAPI; +import net.bteuk.network.api.PlotAPI; +import net.bteuk.network.api.SQLAPI; +import net.bteuk.network.api.entity.Event; import net.bteuk.network.lib.dto.DirectMessage; import net.bteuk.network.lib.utils.ChatUtils; -import net.bteuk.network.sql.GlobalSQL; -import net.bteuk.network.sql.PlotSQL; import net.bteuk.plotsystem.exceptions.RegionManagerNotFoundException; import net.bteuk.plotsystem.exceptions.RegionNotFoundException; import net.bteuk.plotsystem.utils.plugins.WorldGuardFunctions; import net.kyori.adventure.text.Component; import org.bukkit.Bukkit; -public class KickEvent { +public class PlotsystemKickEvent implements Event { - public static void event(String uuid, String[] event) { + private final PlotAPI plotAPI; + + private final ChatAPI chatAPI; + + private final SQLAPI globalSQL; + + public PlotsystemKickEvent(PlotAPI plotAPI, ChatAPI chatAPI, SQLAPI globalSQL) { + this.plotAPI = plotAPI; + this.chatAPI = chatAPI; + this.globalSQL = globalSQL; + } + + public void event(String uuid, String[] event, String message) { // Events for retracting if (event[1].equals("plot")) { - GlobalSQL globalSQL = Network.getInstance().getGlobalSQL(); - PlotSQL plotSQL = Network.getInstance().getPlotSQL(); - // Convert the string id to int id. int id = Integer.parseInt(event[2]); - String ownerId = plotSQL.getString("SELECT uuid FROM plot_members WHERE id=" + id + " AND is_owner=1"); + String ownerId = plotAPI.getPlotOwner(id); Component messageOwner = ChatUtils.success("You have kicked %s from plot %s", globalSQL.getString("SELECT name FROM player_data WHERE uuid='" + uuid + "';"), String.valueOf(id)); Component messageMember = ChatUtils.error("You have been kicked from Plot %s", String.valueOf(id)); // Remove the player to the database. - plotSQL.update("DELETE FROM plot_members WHERE id=" + id + " AND uuid='" + uuid + "';"); + plotAPI.removePlotMember(id, uuid); // Remove the player to the worldguard region. try { - WorldGuardFunctions.removeMember(String.valueOf(id), uuid, Bukkit.getWorld(plotSQL.getString("SELECT location FROM plot_data WHERE id=" + id + ";"))); + WorldGuardFunctions.removeMember(String.valueOf(id), uuid, Bukkit.getWorld(plotAPI.getPlotLocation(id))); } catch (RegionManagerNotFoundException | RegionNotFoundException e) { DirectMessage directMessage = new DirectMessage("global", ownerId, "server", ChatUtils.error("An error occurred while trying to kick the user from the plot, please contact an administrator."), false); - Network.getInstance().getChat().sendSocketMesage(directMessage); + chatAPI.sendDirectMessage(directMessage); return; } // Send message to plot owner. DirectMessage ownerMessage = new DirectMessage("global", ownerId, "server", messageOwner, true); - Network.getInstance().getChat().sendSocketMesage(ownerMessage); + chatAPI.sendDirectMessage(ownerMessage); // Send message to plot member. DirectMessage memberMessage = new DirectMessage("global", uuid, "server", messageMember, true); - Network.getInstance().getChat().sendSocketMesage(memberMessage); + chatAPI.sendDirectMessage(memberMessage); } else if (event[1].equals("zone")) { - GlobalSQL globalSQL = Network.getInstance().getGlobalSQL(); - PlotSQL plotSQL = Network.getInstance().getPlotSQL(); - // Convert the string id to int id. int id = Integer.parseInt(event[2]); - String ownerId = plotSQL.getString("SELECT uuid FROM zone_members WHERE id=" + id + " AND is_owner=1"); + String ownerId = plotAPI.getZoneOwner(id); Component messageOwner = ChatUtils.success("You have kicked %s from Zone %s", globalSQL.getString("SELECT name FROM player_data WHERE uuid='" + uuid + "';"), String.valueOf(id)); Component messageMember = ChatUtils.error("You have been kicked from Zone %s", String.valueOf(id)); // Remove the player to the database. - plotSQL.update("DELETE FROM zone_members WHERE id=" + id + " AND uuid='" + uuid + "';"); + plotAPI.removeZoneMember(id, uuid); // Remove the player to the worldguard region. try { - WorldGuardFunctions.removeMember("z" + event[2], uuid, Bukkit.getWorld(plotSQL.getString("SELECT location FROM zones WHERE id=" + id + ";"))); + WorldGuardFunctions.removeMember("z" + event[2], uuid, Bukkit.getWorld(plotAPI.getZoneLocation(id))); } catch (RegionManagerNotFoundException | RegionNotFoundException e) { DirectMessage directMessage = new DirectMessage("global", ownerId, "server", ChatUtils.error("An error occurred while trying to kick the user from the zone, please contact an administrator."), false); - Network.getInstance().getChat().sendSocketMesage(directMessage); + chatAPI.sendDirectMessage(directMessage); return; } // Send message to zone owner. DirectMessage ownerMessage = new DirectMessage("global", ownerId, "server", messageOwner, true); - Network.getInstance().getChat().sendSocketMesage(ownerMessage); + chatAPI.sendDirectMessage(ownerMessage); // Send message to zone member. DirectMessage memberMessage = new DirectMessage("global", uuid, "server", messageMember, true); - Network.getInstance().getChat().sendSocketMesage(memberMessage); + chatAPI.sendDirectMessage(memberMessage); } } diff --git a/src/main/java/net/bteuk/plotsystem/events/RetractEvent.java b/src/main/java/net/bteuk/plotsystem/events/RetractEvent.java index 8b82a1f..0066157 100644 --- a/src/main/java/net/bteuk/plotsystem/events/RetractEvent.java +++ b/src/main/java/net/bteuk/plotsystem/events/RetractEvent.java @@ -34,29 +34,27 @@ public void event(String uuid, String[] event, String sMessage) { Component message; - // Check if plot is submitted. + // Check if the plot is submitted. if (plotAPI.getPlotStatus(id) == PlotStatus.SUBMITTED) { - // Set plot status to claimed. + // Set plot status to 'claimed'. plotHelper.updatePlotStatus(id, PlotStatus.CLAIMED); - // Remove submitted plot entry. + // Remove the submitted plot entry. plotAPI.removePlotSubmission(id); - // Update last submit time in playerdata so the player doesn't have a cooldown anymore. + // Update last submit time in player data so the player doesn't have a cooldown any more. plotAPI.updateLastSubmit(uuid, 0); message = ChatUtils.success("Retracted submission for Plot %s", String.valueOf(id)); - // Send message to reviewers that a plot submission has been retracted. + // Send a message to reviewers that a plot submission has been retracted. PlotMessage plotMessage = new PlotMessage("A submitted plot has been retracted, there %s %s submitted %s.", false); chatAPI.sendPlotMessage(plotMessage); } else { - // If plot is not submitted set the message accordingly. message = ChatUtils.error("Plot submission can not be retracted as it is not currently submitted."); - } DirectMessage directMessage = new DirectMessage("global", uuid, "server", diff --git a/src/main/java/net/bteuk/plotsystem/events/ReviewEvent.java b/src/main/java/net/bteuk/plotsystem/events/ReviewEvent.java index 55158b5..c915cab 100644 --- a/src/main/java/net/bteuk/plotsystem/events/ReviewEvent.java +++ b/src/main/java/net/bteuk/plotsystem/events/ReviewEvent.java @@ -1,6 +1,8 @@ package net.bteuk.plotsystem.events; import io.papermc.lib.PaperLib; +import net.bteuk.minecraft.gui.GuiManager; +import net.bteuk.network.api.NetworkAPI; import net.bteuk.network.api.PlotAPI; import net.bteuk.network.api.entity.Event; import net.bteuk.network.api.plotsystem.SubmittedStatus; @@ -25,13 +27,16 @@ public class ReviewEvent implements Event { + private final NetworkAPI networkAPI; private final PlotAPI plotAPI; - private final PlotHelper plotHelper; + private final GuiManager guiManager; - public ReviewEvent(PlotAPI plotAPI, PlotHelper plotHelper) { - this.plotAPI = plotAPI; + public ReviewEvent(NetworkAPI networkAPI, PlotHelper plotHelper, GuiManager guiManager) { + this.networkAPI = networkAPI; + this.plotAPI = networkAPI.getPlotAPI(); this.plotHelper = plotHelper; + this.guiManager = guiManager; } public void event(String uuid, String[] event, String message) { @@ -75,7 +80,7 @@ public void event(String uuid, String[] event, String message) { plotHelper.updateSubmittedStatus(id, SubmittedStatus.UNDER_REVIEW); // Create new review instance for user. - user.setReview(new Review(PlotSystem.getInstance(), id, user)); + user.setReview(new Review(PlotSystem.getInstance(), id, user, networkAPI, plotHelper, guiManager)); // Add the reviewer to the plot. try { diff --git a/src/main/java/net/bteuk/plotsystem/events/SubmitEvent.java b/src/main/java/net/bteuk/plotsystem/events/SubmitEvent.java index 60e6cc3..ce93c18 100644 --- a/src/main/java/net/bteuk/plotsystem/events/SubmitEvent.java +++ b/src/main/java/net/bteuk/plotsystem/events/SubmitEvent.java @@ -1,7 +1,10 @@ package net.bteuk.plotsystem.events; +import net.bteuk.network.api.ChatAPI; import net.bteuk.network.api.PlotAPI; import net.bteuk.network.api.SQLAPI; +import net.bteuk.network.api.entity.Event; +import net.bteuk.network.api.plotsystem.PlotStatus; import net.bteuk.network.lib.dto.DirectMessage; import net.bteuk.network.lib.dto.PlotMessage; import net.bteuk.network.lib.utils.ChatUtils; @@ -9,7 +12,7 @@ import net.bteuk.plotsystem.utils.PlotHelper; import net.kyori.adventure.text.Component; -public class SubmitEvent { +public class SubmitEvent implements Event { private final PlotAPI plotAPI; @@ -17,13 +20,16 @@ public class SubmitEvent { private final SQLAPI globalSQL; - public SubmitEvent(PlotAPI plotAPI, PlotHelper plotHelper, SQLAPI globalSQL) { + private final ChatAPI chatAPI; + + public SubmitEvent(PlotAPI plotAPI, PlotHelper plotHelper, SQLAPI globalSQL, ChatAPI chatAPI) { this.plotAPI = plotAPI; this.plotHelper = plotHelper; this.globalSQL = globalSQL; + this.chatAPI = chatAPI; } - public void event(String uuid, String[] event) { + public void event(String uuid, String[] event, String sMessage) { // Events for submitting if (event[1].equals("plot")) { @@ -64,20 +70,19 @@ public void event(String uuid, String[] event) { if (plotAPI.isPlotClaimed(plotID)) { // Create new submitted plot key. - PlotSystem.getInstance().plotSQL.update( - "INSERT INTO plot_submission(plot_id,submit_time,status,last_query) VALUES(" + plotID + "," + Time.currentTime() + ",'submitted'," + Time.currentTime() + ");"); + plotAPI.createPlotSubmission(plotID); // Set plot status to submitted. - PlotHelper.updatePlotStatus(plotID, PlotStatus.SUBMITTED); + plotHelper.updatePlotStatus(plotID, PlotStatus.SUBMITTED); - // Update last submit time in playerdata. - PlotSystem.getInstance().globalSQL.update("UPDATE player_data SET last_submit=" + Time.currentTime() + " WHERE uuid='" + uuid + "';"); + // Update last submit time. + plotAPI.updateLastSubmit(uuid, System.currentTimeMillis()); message = ChatUtils.success("Submitted plot %s", String.valueOf(plotID)); // Send message to reviewers that a plot has been submitted. PlotMessage plotMessage = new PlotMessage("A plot has been submitted, there %s %s submitted %s.", false); - Network.getInstance().getChat().sendSocketMesage(plotMessage); + chatAPI.sendPlotMessage(plotMessage); } else { @@ -89,7 +94,7 @@ public void event(String uuid, String[] event) { DirectMessage directMessage = new DirectMessage("global", uuid, "server", message, true); - Network.getInstance().getChat().sendSocketMesage(directMessage); + chatAPI.sendDirectMessage(directMessage); } } diff --git a/src/main/java/net/bteuk/plotsystem/events/VerifyEvent.java b/src/main/java/net/bteuk/plotsystem/events/VerifyEvent.java index fc4d917..f20f632 100644 --- a/src/main/java/net/bteuk/plotsystem/events/VerifyEvent.java +++ b/src/main/java/net/bteuk/plotsystem/events/VerifyEvent.java @@ -1,10 +1,12 @@ package net.bteuk.plotsystem.events; import io.papermc.lib.PaperLib; -import net.bteuk.network.Network; +import net.bteuk.minecraft.gui.GuiManager; +import net.bteuk.network.api.NetworkAPI; +import net.bteuk.network.api.PlotAPI; +import net.bteuk.network.api.entity.Event; +import net.bteuk.network.api.plotsystem.SubmittedStatus; import net.bteuk.network.lib.utils.ChatUtils; -import net.bteuk.network.sql.PlotSQL; -import net.bteuk.network.utils.enums.SubmittedStatus; import net.bteuk.plotsystem.PlotSystem; import net.bteuk.plotsystem.exceptions.RegionManagerNotFoundException; import net.bteuk.plotsystem.exceptions.RegionNotFoundException; @@ -23,9 +25,21 @@ import static net.bteuk.plotsystem.PlotSystem.LOGGER; -public class VerifyEvent { +public class VerifyEvent implements Event { - public static void event(String uuid, String[] event) { + private final NetworkAPI networkAPI; + private final PlotAPI plotAPI; + private final PlotHelper plotHelper; + private final GuiManager guiManager; + + public VerifyEvent(NetworkAPI networkAPI, PlotHelper plotHelper, GuiManager guiManager) { + this.networkAPI = networkAPI; + this.plotAPI = networkAPI.getPlotAPI(); + this.plotHelper = plotHelper; + this.guiManager = guiManager; + } + + public void event(String uuid, String[] event, String message) { // Events for claiming if (event[1].equals("plot")) { @@ -55,20 +69,17 @@ public static void event(String uuid, String[] event) { // Convert the string id to int id. int id = Integer.parseInt(event[2]); - // Get plotsql. - PlotSQL plotSQL = Network.getInstance().getPlotSQL(); - // Get world of plot. - World world = Bukkit.getWorld(plotSQL.getString("SELECT location FROM plot_data WHERE id=" + id + ";")); + World world = Bukkit.getWorld(plotAPI.getPlotLocation(id)); // Check if the plot is still awaiting verification. - if (plotSQL.hasRow("SELECT 1 FROM plot_submission WHERE plot_id=" + id + " AND status='" + SubmittedStatus.AWAITING_VERIFICATION.database_value + "';")) { + if (plotAPI.getPlotSubmissionStatus(id) == SubmittedStatus.AWAITING_VERIFICATION) { // Set the plot to under review. - PlotHelper.updateSubmittedStatus(id, SubmittedStatus.UNDER_VERIFICATION); + plotHelper.updateSubmittedStatus(id, SubmittedStatus.UNDER_VERIFICATION); // Create new verification instance for user. - user.setReview(new Verification(PlotSystem.getInstance(), id, user)); + user.setReview(new Verification(PlotSystem.getInstance(), id, user, networkAPI, plotHelper, guiManager)); // Add the reviewer to the plot. try { diff --git a/src/main/java/net/bteuk/plotsystem/gui/ClaimGui.java b/src/main/java/net/bteuk/plotsystem/gui/ClaimGui.java index 68a006a..7d82778 100644 --- a/src/main/java/net/bteuk/plotsystem/gui/ClaimGui.java +++ b/src/main/java/net/bteuk/plotsystem/gui/ClaimGui.java @@ -5,7 +5,6 @@ import net.bteuk.network.api.PlotAPI; import net.bteuk.network.api.plotsystem.PlotStatus; import net.bteuk.network.lib.utils.ChatUtils; -import net.bteuk.plotsystem.PlotSystem; import net.bteuk.plotsystem.exceptions.RegionManagerNotFoundException; import net.bteuk.plotsystem.exceptions.RegionNotFoundException; import net.bteuk.plotsystem.utils.PlotHelper; @@ -46,13 +45,15 @@ public ClaimGui(User user, int plot, GuiManager guiManager, PlotAPI plotAPI, Plo private void createGui() { - setItem(20, Utils.createItem(PlotValues.sizeMaterial(user.plotSQL.getInt("SELECT size FROM plot_data WHERE id=" + plot + ";")), 1, + int size = plotAPI.getPlotSize(plot); + setItem(20, Utils.createItem(PlotValues.sizeMaterial(size), 1, ChatUtils.title("Plot Size"), - ChatUtils.line(PlotValues.sizeName(user.plotSQL.getInt("SELECT size FROM plot_data WHERE id=" + plot + ";"))))); + ChatUtils.line(PlotValues.sizeName(size)))); - setItem(24, Utils.createItem(PlotValues.difficultyMaterial(user.plotSQL.getInt("SELECT difficulty FROM plot_data WHERE id=" + plot + ";")), 1, + int difficulty = plotAPI.getPlotDifficulty(plot); + setItem(24, Utils.createItem(PlotValues.difficultyMaterial(difficulty), 1, ChatUtils.title("Plot Difficulty"), - ChatUtils.line(PlotValues.difficultyName(user.plotSQL.getInt("SELECT difficulty FROM plot_data WHERE id=" + plot + ";"))))); + ChatUtils.line(PlotValues.difficultyName(difficulty)))); setItem(22, Utils.createItem(Material.ENDER_EYE, 1, ChatUtils.title("View Plot in Google Maps"), @@ -109,16 +110,16 @@ private void createGui() { player.closeInventory(); // Check if the plot is not already claimed, since it may happen that the gui is spammed. - if (eUser.plotSQL.hasRow("SELECT id FROM plot_data WHERE id=" + plot + " AND status='unclaimed';")) { + PlotStatus plotStatus = plotAPI.getPlotStatus(plot); + if (plotStatus == PlotStatus.UNCLAIMED) { // If the plot status can be updated, add the player as plot owner. if (plotHelper.updatePlotStatus(plot, PlotStatus.CLAIMED)) { // If the player can't be given owner, set the plot status back to unclaimed. - if (eUser.plotSQL.update( - "INSERT INTO plot_members(id,uuid,is_owner,last_enter) VALUES(" + plot + ",'" + eUser.uuid + "',1," + Time.currentTime() + ");")) { + if (plotAPI.createPlotOwner(plot, user.uuid)) { - // Add player to worldguard region. + // Add player to the worldguard region. try { if (WorldGuardFunctions.addMember(String.valueOf(plot), player.getUniqueId().toString(), player.getWorld())) { diff --git a/src/main/java/net/bteuk/plotsystem/listeners/ClaimEnter.java b/src/main/java/net/bteuk/plotsystem/listeners/ClaimEnter.java index e7a458e..2b46431 100644 --- a/src/main/java/net/bteuk/plotsystem/listeners/ClaimEnter.java +++ b/src/main/java/net/bteuk/plotsystem/listeners/ClaimEnter.java @@ -198,9 +198,8 @@ private void checkPlot(User u, int plot) { } } else { - // If you are the owner or member of this plot update your last enter time. - if (plotAPI.hasRow("SELECT id FROM plot_members WHERE id=" + u.inPlot + " AND uuid='" + u.uuid + "';")) { + if (plotAPI.isPlotOwner(u.inPlot, u.uuid) || plotAPI.isPlotMember(u.inPlot, u.uuid)) { plotAPI.setPlotLastEnter(u.inPlot, u.uuid); } } @@ -217,7 +216,7 @@ private void checkZone(User u, int zone) { u.inZone = zone; // Check if the zone is public. - if (plotAPI.hasRow("SELECT id FROM zones WHERE id=" + zone + " AND is_public=1;")) { + if (plotAPI.isZonePublic(zone)) { u.player.sendActionBar( ChatUtils.success("You have entered zone ") diff --git a/src/main/java/net/bteuk/plotsystem/listeners/JoinServer.java b/src/main/java/net/bteuk/plotsystem/listeners/JoinServer.java index fe4ba8e..7738c4d 100644 --- a/src/main/java/net/bteuk/plotsystem/listeners/JoinServer.java +++ b/src/main/java/net/bteuk/plotsystem/listeners/JoinServer.java @@ -1,5 +1,6 @@ package net.bteuk.plotsystem.listeners; +import net.bteuk.network.api.NetworkAPI; import net.bteuk.plotsystem.PlotSystem; import net.bteuk.plotsystem.utils.PlotHelper; import net.bteuk.plotsystem.utils.User; @@ -17,19 +18,20 @@ */ public class JoinServer implements Listener { private final PlotSystem instance; - + private final NetworkAPI networkAPI; private final PlotHelper plotHelper; - public JoinServer(PlotSystem plugin, PlotHelper plotHelper) { + public JoinServer(PlotSystem plugin, NetworkAPI networkAPI, PlotHelper plotHelper) { Bukkit.getServer().getPluginManager().registerEvents(this, plugin); this.instance = plugin; + this.networkAPI = networkAPI; this.plotHelper = plotHelper; } @EventHandler public void joinEvent(PlayerJoinEvent e) { // Create instance of User and add it to list. - User u = new User(e.getPlayer()); + User u = new User(e.getPlayer(), networkAPI, plotHelper); instance.addUser(u); // Add the player to relevant holograms. diff --git a/src/main/java/net/bteuk/plotsystem/listeners/PlayerInteract.java b/src/main/java/net/bteuk/plotsystem/listeners/PlayerInteract.java index 127a681..f5f9d0e 100644 --- a/src/main/java/net/bteuk/plotsystem/listeners/PlayerInteract.java +++ b/src/main/java/net/bteuk/plotsystem/listeners/PlayerInteract.java @@ -20,12 +20,9 @@ public class PlayerInteract implements Listener { - private final PlotSystem instance; - private final PlotAPI plotAPI; public PlayerInteract(PlotSystem instance, PlotAPI plotAPI) { - this.instance = instance; this.plotAPI = plotAPI; // Register the listener. diff --git a/src/main/java/net/bteuk/plotsystem/reviewing/PreviousFeedbackGui.java b/src/main/java/net/bteuk/plotsystem/reviewing/PreviousFeedbackGui.java index 3da0ed4..7b4aae6 100644 --- a/src/main/java/net/bteuk/plotsystem/reviewing/PreviousFeedbackGui.java +++ b/src/main/java/net/bteuk/plotsystem/reviewing/PreviousFeedbackGui.java @@ -1,116 +1,106 @@ package net.bteuk.plotsystem.reviewing; -import net.bteuk.network.Network; -import net.bteuk.network.gui.Gui; +import net.bteuk.minecraft.gui.Gui; +import net.bteuk.minecraft.gui.GuiManager; +import net.bteuk.network.api.PlotAPI; +import net.bteuk.network.api.SQLAPI; +import net.bteuk.network.api.plotsystem.ReviewFeedback; import net.bteuk.network.lib.utils.ChatUtils; -import net.bteuk.network.sql.GlobalSQL; -import net.bteuk.network.sql.PlotSQL; -import net.bteuk.network.utils.Utils; -import net.bteuk.network.utils.plotsystem.ReviewFeedback; import net.bteuk.plotsystem.utils.User; +import net.bteuk.plotsystem.utils.Utils; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; import net.kyori.adventure.text.format.TextDecoration; import org.bukkit.Material; +import org.bukkit.entity.Player; public class PreviousFeedbackGui extends Gui { - private final PlotSQL plotSQL; - private final GlobalSQL globalSQL; - private final int plotID; private final User user; - public PreviousFeedbackGui(int plotID, User user) { + private final PlotAPI plotAPI; + + private final SQLAPI globalSQL; - super(45, Component.text("Previous Feedback", NamedTextColor.AQUA, TextDecoration.BOLD)); + public PreviousFeedbackGui(GuiManager guiManager, int plotID, User user, PlotAPI plotAPI, SQLAPI globalSQL) { + super(guiManager, 45, Component.text("Previous Feedback", NamedTextColor.AQUA, TextDecoration.BOLD)); this.plotID = plotID; this.user = user; - - //Get plot sql. - plotSQL = Network.getInstance().getPlotSQL(); - - //Get global sql. - globalSQL = Network.getInstance().getGlobalSQL(); + this.plotAPI = plotAPI; + this.globalSQL = globalSQL; createGui(); - } private void createGui() { - //Get plot owner uuid. - String uuid = plotSQL.getString("SELECT uuid FROM plot_members WHERE id=" + plotID + " AND is_owner=1;"); + // Get the plot owner uuid. + String uuid = plotAPI.getPlotOwner(plotID); - //Get the number of times the plot was denied for the current plot owner. - int deniedCount = plotSQL.getInt("SELECT COUNT(attempt) FROM plot_review WHERE plot_id=" + plotID + " AND uuid='" + uuid + "' AND completed=1 AND accepted=0;"); + // Get the number of times the plot was denied for the current plot owner. + int deniedCount = plotAPI.getDeniedPlotCount(plotID, uuid); - //Slot count. + // Slot count. int slot = 10; - //Iterate through the deniedCount inversely. - //We cap the number at 21, since we'd never expect a player to have more plots denied than that, - //it also saves us having to create multiple pages. + // Iterate through the deniedCount inversely. + // We cap the number at 21, since we'd never expect a player to have more plots denied than that; + // It also saves us having to create multiple pages. for (int i = deniedCount; i > 0; i--) { - //If the slot is greater than the number that fit in a page, stop. + // If the slot is greater than the number that fit in a page, stop. if (slot > 34) { break; } - //Add player to gui. + // Add player to gui. int finalI = i; setItem(slot, Utils.createItem(Material.WRITTEN_BOOK, 1, ChatUtils.title("Feedback for submission " + i), ChatUtils.line("Click to view feedback for this submission."), ChatUtils.line("Reviewed by ") - .append(Component.text(globalSQL.getString("SELECT name FROM player_data WHERE uuid='" - + plotSQL.getString("SELECT reviewer FROM plot_review WHERE plot_id=" + plotID + " AND uuid='" + uuid + "' AND attempt=" + i + ";") + "';"), NamedTextColor.GRAY))), + .append(Component.text(globalSQL.getString("SELECT name FROM player_data WHERE uuid='" + plotAPI.getPlotReviewer(plotID, uuid, i) + "';"), + NamedTextColor.GRAY))), - u -> + clickEvent -> { // Close the inventory. - u.player.closeInventory(); + clickEvent.getWhoClicked().closeInventory(); - // Create book. - int reviewId = plotSQL.getInt("SELECT id FROM plot_review WHERE plot_id=" + plotID + " AND uuid='" + uuid + "' AND attempt=" + finalI + ";"); + // Create the book. + int reviewId = plotAPI.getReviewId(plotID, uuid, finalI); // Open the book. - u.player.openBook(ReviewFeedback.createFeedbackBook(reviewId)); + clickEvent.getWhoClicked().openBook(ReviewFeedback.createFeedbackBook(globalSQL, plotAPI, reviewId)); }); - - //Increase slot accordingly. + // Increase the slot accordingly. if (slot % 9 == 7) { - //Increase row, basically add 3. + // Increase row, basically add 3. slot += 3; } else { - //Increase value by 1. + // Increase value by 1. slot++; } } - //Return to plot info menu. + // Return to the review menu. setItem(44, Utils.createItem(Material.SPRUCE_DOOR, 1, ChatUtils.title("Return"), ChatUtils.line("Go back to the review menu.")), - u -> { - //Go back to the review gui. - u.player.closeInventory(); - user.getReview().getReviewActionGui().open(u); + clickEvent -> { + // Go back to the review gui. + if (clickEvent.getWhoClicked() instanceof Player player) { + player.closeInventory(); + user.getReview().getReviewActionGui().open(player); + } } ); } - - public void refresh() { - this.clearGui(); - createGui(); - } - - } diff --git a/src/main/java/net/bteuk/plotsystem/reviewing/Review.java b/src/main/java/net/bteuk/plotsystem/reviewing/Review.java index a8fa362..6dcb3f5 100644 --- a/src/main/java/net/bteuk/plotsystem/reviewing/Review.java +++ b/src/main/java/net/bteuk/plotsystem/reviewing/Review.java @@ -1,11 +1,12 @@ package net.bteuk.plotsystem.reviewing; import lombok.Getter; -import net.bteuk.network.Network; +import net.bteuk.minecraft.gui.GuiManager; +import net.bteuk.network.api.NetworkAPI; +import net.bteuk.network.api.plotsystem.SubmittedStatus; import net.bteuk.network.lib.dto.PlotMessage; import net.bteuk.network.lib.utils.ChatUtils; import net.bteuk.network.lib.utils.Reviewing; -import net.bteuk.network.utils.enums.SubmittedStatus; import net.bteuk.plotsystem.PlotSystem; import net.bteuk.plotsystem.exceptions.RegionManagerNotFoundException; import net.bteuk.plotsystem.exceptions.RegionNotFoundException; @@ -30,18 +31,17 @@ public class Review extends ReviewAction { * @param plotID the plot to review * @param user the reviewer */ - public Review(PlotSystem instance, int plotID, User user) { - super(instance, plotID, user); + public Review(PlotSystem instance, int plotID, User user, NetworkAPI networkAPI, PlotHelper plotHelper, GuiManager guiManager) { + super(instance, plotID, user, networkAPI, plotHelper, guiManager); // Create the review gui. - reviewActionGui = new ReviewGui(this); - + reviewActionGui = new ReviewGui(this, guiManager, networkAPI.getPlotAPI(), networkAPI.getGlobalSQL()); } @Override public void cancel() { // Set the plot back to 'submitted'. - PlotHelper.updateSubmittedStatus(plotID, SubmittedStatus.SUBMITTED); + plotHelper.updateSubmittedStatus(plotID, SubmittedStatus.SUBMITTED); // Send feedback. if (user.player.isOnline()) { @@ -59,14 +59,14 @@ public void cancel() { */ public void save(boolean accept) { - double verificationChance = Reviewing.getReassessmentChance(plotSQL.getReviewerReputation(user.uuid)); + double verificationChance = Reviewing.getReassessmentChance(plotAPI.getReviewerReputation(user.uuid)); boolean requiresVerification = false; if (CONFIG.getBoolean("reviewer_verification", true) || !user.player.hasPermission("group.reviewer")) { requiresVerification = Math.random() < verificationChance; } // Create a review entry in the database. - int reviewId = plotSQL.createReview(plotID, plotOwner, user.uuid, accept, !requiresVerification); + int reviewId = plotAPI.createReview(plotID, plotOwner, user.uuid, accept, !requiresVerification); // Save feedback for each category. saveFeedback(reviewId); @@ -85,7 +85,7 @@ public void save(boolean accept) { protected void notifyReviewers() { // Send message to reviewers that a plot has been reviewed. PlotMessage plotMessage = new PlotMessage("A plot has been reviewed, there %s %s submitted %s.", false); - Network.getInstance().getChat().sendSocketMesage(plotMessage); + chatAPI.sendPlotMessage(plotMessage); } private void saveFeedback(int reviewId) { @@ -101,13 +101,13 @@ private void setAwaitingVerification(boolean accept) { } // Update the submitted status of the plot to 'awaiting verification'. - plotSQL.update("UPDATE plot_submission SET status='" + SubmittedStatus.AWAITING_VERIFICATION.database_value + "' WHERE plot_id=" + plotID + ";"); + plotHelper.updateSubmittedStatus(plotID, SubmittedStatus.AWAITING_VERIFICATION); notifyReviewers(); // Send message to reviewers that a plot has been verified. PlotMessage plotMessage = new PlotMessage("A plot has been reviewed and is awaiting verification, there %s %s %s awaiting verification.", true); - Network.getInstance().getChat().sendSocketMesage(plotMessage); + chatAPI.sendPlotMessage(plotMessage); sendReviewerVerificationMessage(accept); } diff --git a/src/main/java/net/bteuk/plotsystem/reviewing/ReviewAction.java b/src/main/java/net/bteuk/plotsystem/reviewing/ReviewAction.java index 502edb0..a12017c 100644 --- a/src/main/java/net/bteuk/plotsystem/reviewing/ReviewAction.java +++ b/src/main/java/net/bteuk/plotsystem/reviewing/ReviewAction.java @@ -2,20 +2,21 @@ import com.sk89q.worldedit.math.BlockVector2; import lombok.Getter; -import net.bteuk.network.Network; -import net.bteuk.network.gui.Gui; +import net.bteuk.minecraft.gui.Gui; +import net.bteuk.minecraft.gui.GuiManager; +import net.bteuk.network.api.ChatAPI; +import net.bteuk.network.api.NetworkAPI; +import net.bteuk.network.api.PlotAPI; +import net.bteuk.network.api.RoleAPI; +import net.bteuk.network.api.SQLAPI; +import net.bteuk.network.api.entity.Role; +import net.bteuk.network.api.plotsystem.PlotStatus; +import net.bteuk.network.api.plotsystem.ReviewCategory; +import net.bteuk.network.api.plotsystem.ReviewSelection; import net.bteuk.network.lib.dto.DirectMessage; import net.bteuk.network.lib.dto.DiscordDirectMessage; import net.bteuk.network.lib.enums.PlotDifficulties; import net.bteuk.network.lib.utils.ChatUtils; -import net.bteuk.network.sql.PlotSQL; -import net.bteuk.network.utils.NetworkUser; -import net.bteuk.network.utils.Role; -import net.bteuk.network.utils.Roles; -import net.bteuk.network.utils.Time; -import net.bteuk.network.utils.enums.PlotStatus; -import net.bteuk.network.utils.plotsystem.ReviewCategory; -import net.bteuk.network.utils.plotsystem.ReviewSelection; import net.bteuk.plotsystem.PlotSystem; import net.bteuk.plotsystem.exceptions.RegionManagerNotFoundException; import net.bteuk.plotsystem.exceptions.RegionNotFoundException; @@ -40,15 +41,23 @@ public abstract class ReviewAction { - protected final PlotSQL plotSQL; - - // User instance. protected final User user; - // Plot id. @Getter protected final int plotID; + protected final PlotAPI plotAPI; + + protected final PlotHelper plotHelper; + + private final SQLAPI globalSQL; + + private final GuiManager guiManager; + + protected final ChatAPI chatAPI; + + private final RoleAPI roleAPI; + @Getter protected final String plotOwner; @@ -57,34 +66,38 @@ public abstract class ReviewAction { private final ReviewHotbar hotbarListener; @Getter private final ReviewBook reviewBook; - // Previous feedback Gui. protected PreviousFeedbackGui previousFeedbackGui; protected PlotDifficulties plotDifficulty = PlotDifficulties.EASY; - public ReviewAction(PlotSystem instance, int plotID, User user) { + public ReviewAction(PlotSystem instance, int plotID, User user, NetworkAPI networkAPI, PlotHelper plotHelper, GuiManager guiManager) { this.user = user; this.plotID = plotID; - this.plotSQL = instance.plotSQL; + this.plotAPI = networkAPI.getPlotAPI(); + this.plotHelper = plotHelper; + this.globalSQL = networkAPI.getGlobalSQL(); + this.guiManager = guiManager; + this.chatAPI = networkAPI.getChat(); + this.roleAPI = networkAPI.getRoleAPI(); // Get the plot world. - this.plotWorld = Bukkit.getWorld(plotSQL.getString("SELECT location FROM plot_data WHERE id=" + plotID + ";")); + this.plotWorld = Bukkit.getWorld(plotAPI.getPlotLocation(plotID)); - // Get plot owner. - this.plotOwner = plotSQL.getString("SELECT uuid FROM plot_members WHERE id=" + plotID + " AND is_owner=1;"); + // Get the plot owner. + this.plotOwner = plotAPI.getPlotOwner(plotID); // Save the users hotbar to revert to after reviewing. // Then clear their inventory and set it up for reviewing. initialInventory = user.player.getInventory().getContents(); user.player.getInventory().clear(); - // Setup the hotbar for the reviewer. + // Set up the hotbar for the reviewer. hotbarListener = new ReviewHotbar(PlotSystem.getInstance(), user); // Create the review book. - reviewBook = new ReviewBook(instance, user.player, hotbarListener); + reviewBook = new ReviewBook(instance, user.player, hotbarListener, plotAPI); - int plotDifficulty = plotSQL.getInt("SELECT difficulty FROM plot_data WHERE id=" + plotID + ";"); + int plotDifficulty = plotAPI.getPlotDifficulty(plotID); for (PlotDifficulties difficulty : PlotDifficulties.values()) { if (difficulty.getValue() == plotDifficulty) { this.plotDifficulty = difficulty; @@ -148,11 +161,8 @@ public void closeReviewAction() { * Opens the review action gui. */ public void openReviewActionGui() { - NetworkUser networkUser = Network.getInstance().getUser(user.player); - if (networkUser != null) { - networkUser.player.closeInventory(); - getReviewActionGui().open(networkUser); - } + user.player.closeInventory(); + getReviewActionGui().open(user.player); } /** @@ -169,11 +179,11 @@ public void cancel() { } public void toBeforeView() { - // Teleport to plot in original state. + // Teleport to plot in its original state. user.player.closeInventory(); try { - Location l = WorldGuardFunctions.getBeforeLocation(String.valueOf(plotID), plotWorld); + Location l = WorldGuardFunctions.getBeforeLocation(String.valueOf(plotID), plotWorld, plotAPI); user.player.teleport(l); } catch (RegionManagerNotFoundException | RegionNotFoundException | WorldNotFoundException e) { user.player.sendMessage(ChatUtils.error("Unable to teleport you to the before view of this plot, please contact an admin.")); @@ -183,10 +193,10 @@ public void toBeforeView() { // Try to create the outline of the before view. try { // Get outlines of the plot. - List vector = WorldGuardFunctions.getPointsTransformedToSaveWorld(String.valueOf(plotID), plotWorld); + List vector = WorldGuardFunctions.getPointsTransformedToSaveWorld(String.valueOf(plotID), plotWorld, plotAPI); // Get the plot difficulty. - int difficulty = plotSQL.getInt("SELECT difficulty FROM plot_data WHERE id=" + plotID + ";"); + int difficulty = plotAPI.getPlotDifficulty(plotID); // Draw the outline. PlotSystem.getInstance().getOutlines().addOutline(user.player, vector, difficultyMaterial(difficulty).createBlockData()); @@ -210,14 +220,11 @@ public void toCurrentView() { public void openPreviousFeedbackGui() { if (previousFeedbackGui == null) { - previousFeedbackGui = new PreviousFeedbackGui(plotID, user); + previousFeedbackGui = new PreviousFeedbackGui(guiManager, plotID, user, plotAPI, globalSQL); } - NetworkUser networkUser = Network.getInstance().getUser(user.player); - if (networkUser != null) { - networkUser.player.closeInventory(); - previousFeedbackGui.open(Network.getInstance().getUser(user.player)); - } + user.player.closeInventory(); + previousFeedbackGui.open(user.player); } public void saveIfPossible(boolean accept) { @@ -247,12 +254,12 @@ private boolean canSave(boolean accept) { user.player.sendMessage(ChatUtils.error("Category %s must have a selection.", category.getDisplayName())); canSave = false; } else { - boolean thresholdReached = PlotHelper.reviewCategoryThresholdReached(plotDifficulty, category, selection); + boolean thresholdReached = plotHelper.reviewCategoryThresholdReached(plotDifficulty, category, selection); thresholdsReached = thresholdsReached && thresholdReached; if (accept && !thresholdReached) { // Notify the reviewer that the plot can not be accepted with this category selection. - ReviewSelection requiredThreshold = PlotHelper.getReviewCategoryThreshold(plotDifficulty, category); + ReviewSelection requiredThreshold = plotHelper.getReviewCategoryThreshold(plotDifficulty, category); if (requiredThreshold == null) { user.player.sendMessage( ChatUtils.error("Category %s does not have a configured threshold, please notify an administrator!", category.getDisplayName())); @@ -281,14 +288,14 @@ private boolean canSave(boolean accept) { protected void completeReview(boolean accept) { // Get world of plot. - World world = Bukkit.getWorld(plotSQL.getString("SELECT location FROM plot_data WHERE id=" + plotID + ";")); + World world = Bukkit.getWorld(plotAPI.getPlotLocation(plotID)); if (world == null) { LOGGER.warning("World of the plot is null!"); return; } - // Remove submitted plot entry. - plotSQL.update("DELETE FROM plot_submission WHERE plot_id=" + plotID + ";"); + // Remove the submitted plot entry. + plotAPI.removePlotSubmission(plotID); if (accept) { // Accept the plot. @@ -313,10 +320,10 @@ protected void removeReviewerFromPlot() { private void completePlot(World plotWorld) { // Remove plot members. - plotSQL.update("DELETE FROM plot_members WHERE id=" + plotID + ";"); + plotAPI.clearPlotMembers(plotID); // Set plot to 'completed'. - PlotHelper.updatePlotStatus(plotID, PlotStatus.COMPLETED); + plotHelper.updatePlotStatus(plotID, PlotStatus.COMPLETED); // Copy the plot to the save world. savePlot(plotWorld); @@ -336,11 +343,11 @@ private void completePlot(World plotWorld) { private void denyPlot(World plotWorld) { - // Update last visit time, to prevent inactivity removal of plot. - plotSQL.update("UPDATE plot_members SET last_enter=" + Time.currentTime() + " WHERE id=" + plotID + ";"); + // Update last visit time for the owner to prevent inactivity removal of the plot. + plotAPI.setPlotLastEnter(plotID, plotOwner); // Set status of the plot back to 'claimed'. - PlotHelper.updatePlotStatus(plotID, PlotStatus.CLAIMED); + plotHelper.updatePlotStatus(plotID, PlotStatus.CLAIMED); // Remove the reviewer from the plot. try { @@ -355,7 +362,7 @@ private void denyPlot(World plotWorld) { private void savePlot(World plotWorld) { - // Get the save world. + // Get the save-world. String save_world = PlotSystem.getInstance().getConfig().getString("save_world"); if (save_world == null) { LOGGER.warning("Save world is not set in config!"); @@ -369,23 +376,23 @@ private void savePlot(World plotWorld) { } // Get the negative coordinate transform. - int xTransform = -plotSQL.getInt("SELECT xTransform FROM location_data WHERE name='" + plotWorld.getName() + "';"); - int zTransform = -plotSQL.getInt("SELECT zTransform FROM location_data WHERE name='" + plotWorld.getName() + "';"); + int xTransform = -plotAPI.getXTransform(plotWorld.getName()); + int zTransform = -plotAPI.getZTransform(plotWorld.getName()); List copyVector; try { copyVector = WorldGuardFunctions.getPoints(String.valueOf(plotID), plotWorld); } catch (RegionManagerNotFoundException | RegionNotFoundException e) { - //u.player.sendMessage(ChatUtils.error("An error occurred in the plot accepting process, please contact an admin.")); - e.printStackTrace(); + user.player.sendMessage(ChatUtils.error("An error occurred in the plot accepting process, please contact an admin.")); + LOGGER.severe("An error occurred in the plot accepting process, please contact an admin: " + e.getMessage()); return; } - // Create paste vector by taking the copy vector coordinate and adding the coordinate transform. + // Create the paste vector by taking the copy vector coordinate and adding the coordinate transform. List pasteVector = new ArrayList<>(); for (BlockVector2 bv : copyVector) { - pasteVector.add(BlockVector2.at(bv.getX() + xTransform, bv.getZ() + zTransform)); + pasteVector.add(BlockVector2.at(bv.x() + xTransform, bv.z() + zTransform)); } Bukkit.getScheduler().runTaskAsynchronously(PlotSystem.getInstance(), () -> { @@ -396,25 +403,25 @@ private void savePlot(World plotWorld) { private void updateRole() { // Get the plot difficulty and player role. - int difficulty = plotSQL.getInt("SELECT difficulty FROM plot_data WHERE id=" + plotID + ";"); - String builderRole = Roles.builderRole(plotOwner).join(); + int difficulty = plotAPI.getPlotDifficulty(plotID); + String builderRole = roleAPI.getBuilderRole(plotOwner).join(); LOGGER.info(String.format("Plot owner %s has builder role %s", plotOwner, builderRole)); - //Calculate the role the player will be promoted to, if any. + // Calculate the role the player will be promoted to, if any. String newRole = getNewRole(difficulty, builderRole); if (newRole != null) { - Role role = Roles.getRoles().stream().filter(r -> r.getId().equals(newRole)).findFirst().orElse(null); + Role role = roleAPI.getRoles().stream().filter(r -> r.getId().equals(newRole)).findFirst().orElse(null); if (role != null) { DiscordDirectMessage discordDirectMessage = new DiscordDirectMessage(plotOwner, "You have been promoted to **" + role.getName() + "**"); - Network.getInstance().getChat().sendSocketMesage(discordDirectMessage); + chatAPI.sendDiscordDirectMessage(discordDirectMessage); } else { LOGGER.warning(String.format("Role %s could not be found, check the Network roles.yml", newRole)); } // Add the new role and remove the old one. - String name = Network.getInstance().getGlobalSQL().getString("SELECT name FROM player_data WHERE uuid='" + plotOwner + "';"); - Roles.alterRole(plotOwner, name, newRole, false, true).join(); - Roles.alterRole(plotOwner, name, builderRole, true, false).join(); + String name = globalSQL.getString("SELECT name FROM player_data WHERE uuid='" + plotOwner + "';"); + roleAPI.alterRole(plotOwner, name, newRole, false, true).join(); + roleAPI.alterRole(plotOwner, name, builderRole, true, false).join(); } else { LOGGER.info("Plot was accepted but no new role was given."); } @@ -433,10 +440,10 @@ private void sendReviewerMessage(boolean accept) { } private void notifyPlotOwnerAccepted() { - // Send message to plot owner. + // Send a message to the plot owner. DirectMessage directMessage = new DirectMessage("global", plotOwner, "server", ChatUtils.success("Plot %s has been accepted.", String.valueOf(plotID)), true); - Network.getInstance().getChat().sendSocketMesage(directMessage); + chatAPI.sendDirectMessage(directMessage); StringBuilder discordMessage = new StringBuilder("Plot " + plotID + " has been accepted"); addFeedbackToDiscordMessage(discordMessage); @@ -447,8 +454,8 @@ private void notifyPlotOwnerDenied() { DirectMessage directMessage = new DirectMessage("global", plotOwner, "server", ChatUtils.error("Plot %s has been denied, feedback has been provided in the plot menu.", String.valueOf(plotID)) .append(ChatUtils.error("\nClick here to view the feedback!") - .clickEvent(ClickEvent.clickEvent(ClickEvent.Action.RUN_COMMAND, String.format("/plot feedback %d", plotID)))), true); - Network.getInstance().getChat().sendSocketMesage(directMessage); + .clickEvent(ClickEvent.runCommand(String.format("/plot feedback %d", plotID)))), true); + chatAPI.sendDirectMessage(directMessage); StringBuilder discordMessage = new StringBuilder("Plot " + plotID + " has been denied."); addFeedbackToDiscordMessage(discordMessage); @@ -468,7 +475,7 @@ private void sendDiscordMessage(StringBuilder builder) { // Split the feedback per 2000 characters if necessary. for (int i = 0; i < builder.length(); i += 2000) { DiscordDirectMessage discordDirectMessage = new DiscordDirectMessage(plotOwner, builder.substring(i, Math.min(i + 2000, builder.length()))); - Network.getInstance().getChat().sendSocketMesage(discordDirectMessage); + chatAPI.sendDiscordDirectMessage(discordDirectMessage); } } } diff --git a/src/main/java/net/bteuk/plotsystem/reviewing/ReviewActionGui.java b/src/main/java/net/bteuk/plotsystem/reviewing/ReviewActionGui.java index 05a64a4..800868f 100644 --- a/src/main/java/net/bteuk/plotsystem/reviewing/ReviewActionGui.java +++ b/src/main/java/net/bteuk/plotsystem/reviewing/ReviewActionGui.java @@ -1,27 +1,27 @@ package net.bteuk.plotsystem.reviewing; -import net.bteuk.network.Network; -import net.bteuk.network.gui.Gui; +import net.bteuk.minecraft.gui.Gui; +import net.bteuk.minecraft.gui.GuiManager; +import net.bteuk.network.api.PlotAPI; +import net.bteuk.network.api.SQLAPI; import net.bteuk.network.lib.utils.ChatUtils; -import net.bteuk.network.sql.GlobalSQL; -import net.bteuk.network.sql.PlotSQL; -import net.bteuk.network.utils.Utils; +import net.bteuk.plotsystem.utils.Utils; import net.kyori.adventure.text.Component; import org.bukkit.Material; public abstract class ReviewActionGui extends Gui { - protected final GlobalSQL globalSQL; - protected final PlotSQL plotSQL; protected ReviewAction reviewAction; - public ReviewActionGui(Component title, ReviewAction reviewAction) { - super(27, title); + protected final PlotAPI plotAPI; + protected final SQLAPI globalSQL; - this.reviewAction = reviewAction; + public ReviewActionGui(GuiManager guiManager, Component title, ReviewAction reviewAction, PlotAPI plotAPI, SQLAPI globalSQL) { + super(guiManager, 27, title); - this.globalSQL = Network.getInstance().getGlobalSQL(); - this.plotSQL = Network.getInstance().getPlotSQL(); + this.reviewAction = reviewAction; + this.plotAPI = plotAPI; + this.globalSQL = globalSQL; createGui(); } @@ -54,8 +54,8 @@ private void createGui() { ChatUtils.line("Deny the plot and return it to the plot owner.")), u -> reviewAction.saveIfPossible(false)); - //View previous feedback, if it exists. - if (plotSQL.hasRow("SELECT 1 FROM plot_review WHERE uuid='" + reviewAction.getPlotOwner() + "' AND plot_id=" + reviewAction.getPlotID() + " AND accepted=0;")) { + // View previous feedback if it exists. + if (plotAPI.getDeniedPlotCount(reviewAction.getPlotID(), reviewAction.getPlotOwner()) > 0) { setItem(18, Utils.createItem(Material.LECTERN, 1, ChatUtils.title("Previous Feedback"), @@ -68,9 +68,4 @@ private void createGui() { // Cancel review action. createCancelReviewActionItem(); } - - public void refresh() { - this.clearGui(); - createGui(); - } } diff --git a/src/main/java/net/bteuk/plotsystem/reviewing/ReviewGui.java b/src/main/java/net/bteuk/plotsystem/reviewing/ReviewGui.java index 05d2899..ab0b0f6 100644 --- a/src/main/java/net/bteuk/plotsystem/reviewing/ReviewGui.java +++ b/src/main/java/net/bteuk/plotsystem/reviewing/ReviewGui.java @@ -1,7 +1,10 @@ package net.bteuk.plotsystem.reviewing; +import net.bteuk.minecraft.gui.GuiManager; +import net.bteuk.network.api.PlotAPI; +import net.bteuk.network.api.SQLAPI; import net.bteuk.network.lib.utils.ChatUtils; -import net.bteuk.network.utils.Utils; +import net.bteuk.plotsystem.utils.Utils; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; import net.kyori.adventure.text.format.TextDecoration; @@ -9,8 +12,8 @@ public class ReviewGui extends ReviewActionGui { - public ReviewGui(Review review) { - super(Component.text("Review Menu", NamedTextColor.AQUA, TextDecoration.BOLD), review); + public ReviewGui(Review review, GuiManager guiManager, PlotAPI plotAPI, SQLAPI globalSQL) { + super(guiManager, Component.text("Review Menu", NamedTextColor.AQUA, TextDecoration.BOLD), review, plotAPI, globalSQL); } @Override diff --git a/src/main/java/net/bteuk/plotsystem/reviewing/ReviewHotbar.java b/src/main/java/net/bteuk/plotsystem/reviewing/ReviewHotbar.java index fb6b9aa..64d2314 100644 --- a/src/main/java/net/bteuk/plotsystem/reviewing/ReviewHotbar.java +++ b/src/main/java/net/bteuk/plotsystem/reviewing/ReviewHotbar.java @@ -1,9 +1,9 @@ package net.bteuk.plotsystem.reviewing; import net.bteuk.network.lib.utils.ChatUtils; -import net.bteuk.network.utils.Utils; import net.bteuk.plotsystem.PlotSystem; import net.bteuk.plotsystem.utils.User; +import net.bteuk.plotsystem.utils.Utils; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.HumanEntity; diff --git a/src/main/java/net/bteuk/plotsystem/reviewing/Verification.java b/src/main/java/net/bteuk/plotsystem/reviewing/Verification.java index 3a5ecb3..8b00140 100644 --- a/src/main/java/net/bteuk/plotsystem/reviewing/Verification.java +++ b/src/main/java/net/bteuk/plotsystem/reviewing/Verification.java @@ -1,13 +1,14 @@ package net.bteuk.plotsystem.reviewing; import lombok.Getter; -import net.bteuk.network.Network; +import net.bteuk.minecraft.gui.GuiManager; +import net.bteuk.network.api.NetworkAPI; +import net.bteuk.network.api.plotsystem.ReviewCategory; +import net.bteuk.network.api.plotsystem.ReviewCategoryFeedback; +import net.bteuk.network.api.plotsystem.ReviewSelection; +import net.bteuk.network.api.plotsystem.SubmittedStatus; import net.bteuk.network.lib.dto.PlotMessage; import net.bteuk.network.lib.utils.ChatUtils; -import net.bteuk.network.utils.enums.SubmittedStatus; -import net.bteuk.network.utils.plotsystem.ReviewCategory; -import net.bteuk.network.utils.plotsystem.ReviewCategoryFeedback; -import net.bteuk.network.utils.plotsystem.ReviewSelection; import net.bteuk.plotsystem.PlotSystem; import net.bteuk.plotsystem.utils.PlotHelper; import net.bteuk.plotsystem.utils.User; @@ -42,27 +43,23 @@ public class Verification extends ReviewAction { * @param plotID the plot to review * @param user the reviewer */ - public Verification(PlotSystem instance, int plotID, User user) { - super(instance, plotID, user); + public Verification(PlotSystem instance, int plotID, User user, NetworkAPI networkAPI, PlotHelper plotHelper, GuiManager guiManager) { + super(instance, plotID, user, networkAPI, plotHelper, guiManager); - this.reviewId = plotSQL.getInt("SELECT id FROM plot_review WHERE plot_id=" + plotID + " AND completed=0;"); - this.reviewer = plotSQL.getString("SELECT reviewer FROM plot_review WHERE id=" + this.reviewId + ";"); + this.reviewId = networkAPI.getPlotAPI().getActiveReviewId(plotID); + this.reviewer = networkAPI.getPlotAPI().getPlotReviewer(reviewId); // Get the feedback from the reviewer. - List reviewCategories = plotSQL.getStringList("SELECT category FROM plot_category_feedback WHERE review_id=" + reviewId + ";"); - for (String category : reviewCategories) { - previousReviewFeedback.put(ReviewCategory.valueOf(category), new ReviewCategoryFeedback( - ReviewCategory.valueOf(category), - ReviewSelection.valueOf(plotSQL.getString("SELECT selection FROM plot_category_feedback WHERE review_id=" + reviewId + " AND category='" + category + "';")), - plotSQL.getInt("SELECT book_id FROM plot_category_feedback WHERE review_id=" + reviewId + " AND category='" + category + "';") - )); + List reviewCategories = networkAPI.getPlotAPI().getReviewCategories(reviewId); + for (ReviewCategory category : reviewCategories) { + previousReviewFeedback.put(category, new ReviewCategoryFeedback(category, networkAPI.getPlotAPI().getReviewSelection(reviewId, category), + networkAPI.getPlotAPI().getReviewBookId(reviewId, category))); } getReviewBook().initReviewBook(previousReviewFeedback.values()); // Create the review gui. - reviewActionGui = new VerificationGui(this); - + reviewActionGui = new VerificationGui(this, guiManager, networkAPI.getPlotAPI(), networkAPI.getGlobalSQL()); } @Override @@ -71,14 +68,14 @@ public void save(boolean accept) { // Determine whether changes have been made in the verification. determineChanges(accept); - int verificationId = plotSQL.createVerification(reviewId, user.uuid, changedOutcome != accept, accept); + int verificationId = plotAPI.createVerification(reviewId, user.uuid, changedOutcome != accept, accept); updateFeedback(verificationId, reviewId, previousReviewFeedback); - plotSQL.update("UPDATE plot_review SET accepted=" + accept + ", completed=1 WHERE id=" + reviewId + ";"); + plotAPI.completeReview(reviewId, accept); completeReview(accept); // Update the reviewer reputation. - plotSQL.update("UPDATE reviewers SET reputation=" + getReputationChange() + " WHERE uuid='" + reviewer + "';"); + plotAPI.updateReviewerReputation(reviewer, getReputationChange()); // Close gui and clear review if exists. this.closeReviewAction(); @@ -87,7 +84,7 @@ public void save(boolean accept) { @Override public void cancel() { // Set the plot back to 'awaiting verification'. - PlotHelper.updateSubmittedStatus(plotID, SubmittedStatus.AWAITING_VERIFICATION); + plotHelper.updateSubmittedStatus(plotID, SubmittedStatus.AWAITING_VERIFICATION); // Send feedback. user.player.sendMessage(ChatUtils.success("Cancelled verification of plot ") @@ -106,9 +103,8 @@ private void updateFeedback(int verificationId, int reviewId, Map (player.getLocation().getX() + 128) ? (player.getLocation().getBlockX() + 128) : region.getMaximumPoint().getX(); - int maxZ = region.getMaximumPoint().getZ() > (player.getLocation().getZ() + 128) ? (player.getLocation().getBlockZ() + 128) : region.getMaximumPoint().getZ(); + int maxX = region.getMaximumPoint().x() > (player.getLocation().x() + 128) ? (player.getLocation().getBlockX() + 128) : region.getMaximumPoint().x(); + int maxZ = region.getMaximumPoint().z() > (player.getLocation().z() + 128) ? (player.getLocation().getBlockZ() + 128) : region.getMaximumPoint().z(); // Iterate in the bounding box. for (int i = minX; i <= maxX; i++) { @@ -60,7 +60,7 @@ public void addOutline(ProtectedRegion region, BlockData block) { if (!(region.contains(BlockVector2.at(i - 1, j)) && region.contains(BlockVector2.at(i + 1, j)) && region.contains(BlockVector2.at(i, j - 1)) && region.contains( BlockVector2.at(i, j + 1)))) { - BlockLocation bl = new BlockLocation(i, j, block); + BlockLocation bl = new BlockLocation(block, i, j); locations.add(bl); @@ -75,11 +75,11 @@ public void addOutline(ProtectedRegion region, BlockData block) { // Additionally replace the fake block with air. public void removeOutline(ProtectedRegion region) { - int minX = region.getMinimumPoint().getX() < (player.getLocation().getX() - 128) ? (player.getLocation().getBlockX() - 128) : region.getMinimumPoint().getX(); - int minZ = region.getMinimumPoint().getZ() < (player.getLocation().getZ() - 128) ? (player.getLocation().getBlockZ() - 128) : region.getMinimumPoint().getZ(); + int minX = region.getMinimumPoint().x() < (player.getLocation().x() - 128) ? (player.getLocation().getBlockX() - 128) : region.getMinimumPoint().x(); + int minZ = region.getMinimumPoint().z() < (player.getLocation().z() - 128) ? (player.getLocation().getBlockZ() - 128) : region.getMinimumPoint().z(); - int maxX = region.getMaximumPoint().getX() > (player.getLocation().getX() + 128) ? (player.getLocation().getBlockX() + 128) : region.getMaximumPoint().getX(); - int maxZ = region.getMaximumPoint().getZ() > (player.getLocation().getZ() + 128) ? (player.getLocation().getBlockZ() + 128) : region.getMaximumPoint().getZ(); + int maxX = region.getMaximumPoint().x() > (player.getLocation().x() + 128) ? (player.getLocation().getBlockX() + 128) : region.getMaximumPoint().x(); + int maxZ = region.getMaximumPoint().z() > (player.getLocation().z() + 128) ? (player.getLocation().getBlockZ() + 128) : region.getMaximumPoint().z(); // Iterate in the bounding box. for (int i = minX; i <= maxX; i++) { @@ -94,7 +94,7 @@ public void removeOutline(ProtectedRegion region) { if (!(region.contains(BlockVector2.at(i - 1, j)) && region.contains(BlockVector2.at(i + 1, j)) && region.contains(BlockVector2.at(i, j - 1)) && region.contains( BlockVector2.at(i, j + 1)))) { - BlockLocation bl = new BlockLocation(i, j, Material.AIR.createBlockData()); + BlockLocation bl = new BlockLocation(Material.AIR.createBlockData(), i, j); locations.remove(bl); drawBlock(bl); @@ -110,7 +110,7 @@ public void removeOutline(ProtectedRegion region) { */ public void removeOutlines() { for (BlockLocation loc : locations) { - BlockLocation bl = new BlockLocation(loc.getX(), loc.getZ(), Material.AIR.createBlockData()); + BlockLocation bl = new BlockLocation(Material.AIR.createBlockData(), loc.x(), loc.z()); drawBlock(bl); } locations.clear(); @@ -120,7 +120,7 @@ public void removeOutlines() { public void addPoint(BlockVector2 bv, BlockData block) { // Add the point to the list. - BlockLocation bl = new BlockLocation(bv.getX(), bv.getZ(), block); + BlockLocation bl = new BlockLocation(block, bv.x(), bv.z()); tempLocations.add(bl); // Draw the point. @@ -132,7 +132,7 @@ public void addPoint(BlockVector2 bv, BlockData block) { public void removePoint(BlockVector2 bv) { // Remove the points from the list. - BlockLocation bl = new BlockLocation(bv.getX(), bv.getZ(), Material.AIR.createBlockData()); + BlockLocation bl = new BlockLocation(Material.AIR.createBlockData(), bv.x(), bv.z()); tempLocations.remove(bl); // Set the block to air. @@ -144,8 +144,8 @@ public void removePoint(BlockVector2 bv) { public void addLine(BlockVector2 bv1, BlockVector2 bv2, BlockData block) { // Get length in x and z direction. - int lengthX = bv2.getX() - bv1.getX(); - int lengthZ = bv2.getZ() - bv1.getZ(); + int lengthX = bv2.x() - bv1.x(); + int lengthZ = bv2.z() - bv1.z(); int length = max(abs(lengthX), abs(lengthZ)); @@ -153,10 +153,9 @@ public void addLine(BlockVector2 bv1, BlockVector2 bv2, BlockData block) { for (int i = 0; i <= length; i++) { // Remove the points from the list. - BlockLocation bl = new BlockLocation( - ((int) (round(bv1.getX() + ((i * lengthX) / (double) length)))), - ((int) (round(bv1.getZ() + ((i * lengthZ) / (double) length)))), - block); + BlockLocation bl = new BlockLocation(block, + ((int) (round(bv1.x() + ((i * lengthX) / (double) length)))), + ((int) (round(bv1.z() + ((i * lengthZ) / (double) length))))); tempLocations.add(bl); drawBlock(bl); @@ -168,8 +167,8 @@ public void addLine(BlockVector2 bv1, BlockVector2 bv2, BlockData block) { public void removeLine(BlockVector2 bv1, BlockVector2 bv2) { // Get length in x and z direction. - int lengthX = bv2.getX() - bv1.getX(); - int lengthZ = bv2.getZ() - bv1.getZ(); + int lengthX = bv2.x() - bv1.x(); + int lengthZ = bv2.z() - bv1.z(); int length = max(abs(lengthX), abs(lengthZ)); @@ -177,10 +176,9 @@ public void removeLine(BlockVector2 bv1, BlockVector2 bv2) { for (int i = 0; i <= length; i++) { // Remove the points from the list. - BlockLocation bl = new BlockLocation( - ((int) (round(bv1.getX() + ((i * lengthX) / (double) length)))), - ((int) (round(bv1.getZ() + ((i * lengthZ) / (double) length)))), - Material.AIR.createBlockData()); + BlockLocation bl = new BlockLocation(Material.AIR.createBlockData(), + ((int) (round(bv1.x() + ((i * lengthX) / (double) length)))), + ((int) (round(bv1.z() + ((i * lengthZ) / (double) length))))); tempLocations.remove(bl); drawBlock(bl); @@ -191,11 +189,11 @@ public void removeLine(BlockVector2 bv1, BlockVector2 bv2) { // Add all the block locations that make up the outline of the region. public void addTempOutline(ProtectedRegion region, BlockData block) { - int minX = region.getMinimumPoint().getX(); - int minZ = region.getMinimumPoint().getZ(); + int minX = region.getMinimumPoint().x(); + int minZ = region.getMinimumPoint().z(); - int maxX = region.getMaximumPoint().getX(); - int maxZ = region.getMaximumPoint().getZ(); + int maxX = region.getMaximumPoint().x(); + int maxZ = region.getMaximumPoint().z(); // Iterate in the bounding box. for (int i = minX; i <= maxX; i++) { @@ -210,7 +208,7 @@ public void addTempOutline(ProtectedRegion region, BlockData block) { if (!(region.contains(BlockVector2.at(i - 1, j)) && region.contains(BlockVector2.at(i + 1, j)) && region.contains(BlockVector2.at(i, j - 1)) && region.contains( BlockVector2.at(i, j + 1)))) { - BlockLocation bl = new BlockLocation(i, j, block); + BlockLocation bl = new BlockLocation(block, i, j); tempLocations.add(bl); @@ -225,11 +223,11 @@ public void addTempOutline(ProtectedRegion region, BlockData block) { // Additionally replace the fake block with air. public void removeTempOutline(ProtectedRegion region) { - int minX = region.getMinimumPoint().getX(); - int minZ = region.getMinimumPoint().getZ(); + int minX = region.getMinimumPoint().x(); + int minZ = region.getMinimumPoint().z(); - int maxX = region.getMaximumPoint().getX(); - int maxZ = region.getMaximumPoint().getZ(); + int maxX = region.getMaximumPoint().x(); + int maxZ = region.getMaximumPoint().z(); // Iterate in the bounding box. for (int i = minX; i <= maxX; i++) { @@ -244,7 +242,7 @@ public void removeTempOutline(ProtectedRegion region) { if (!(region.contains(BlockVector2.at(i - 1, j)) && region.contains(BlockVector2.at(i + 1, j)) && region.contains(BlockVector2.at(i, j - 1)) && region.contains( BlockVector2.at(i, j + 1)))) { - BlockLocation bl = new BlockLocation(i, j, Material.AIR.createBlockData()); + BlockLocation bl = new BlockLocation(Material.AIR.createBlockData(), i, j); tempLocations.remove(bl); drawBlock(bl); @@ -289,9 +287,9 @@ public void drawOutlines() { private void drawBlock(BlockLocation bl) { player.sendBlockChange( new Location( - world, bl.getX(), - (world.getHighestBlockYAt(bl.getX(), bl.getZ()) + 1), - bl.getZ() - ), bl.getBlock()); + world, bl.x(), + (world.getHighestBlockYAt(bl.x(), bl.z()) + 1), + bl.z() + ), bl.block()); } } diff --git a/src/main/java/net/bteuk/plotsystem/utils/Inactive.java b/src/main/java/net/bteuk/plotsystem/utils/Inactive.java index a750a5b..1391fd8 100644 --- a/src/main/java/net/bteuk/plotsystem/utils/Inactive.java +++ b/src/main/java/net/bteuk/plotsystem/utils/Inactive.java @@ -1,13 +1,11 @@ package net.bteuk.plotsystem.utils; import com.sk89q.worldedit.math.BlockVector2; -import net.bteuk.network.Network; +import net.bteuk.network.api.NetworkAPI; +import net.bteuk.network.api.plotsystem.PlotStatus; import net.bteuk.network.lib.dto.DirectMessage; import net.bteuk.network.lib.dto.DiscordDirectMessage; import net.bteuk.network.lib.utils.ChatUtils; -import net.bteuk.network.sql.PlotSQL; -import net.bteuk.network.utils.Time; -import net.bteuk.network.utils.enums.PlotStatus; import net.bteuk.plotsystem.PlotSystem; import net.bteuk.plotsystem.exceptions.RegionManagerNotFoundException; import net.bteuk.plotsystem.exceptions.RegionNotFoundException; @@ -22,43 +20,37 @@ public class Inactive { - public static void cancelInactivePlots() { + public static void cancelInactivePlots(NetworkAPI networkAPI, PlotHelper plotHelper) { // Get config. FileConfiguration config = PlotSystem.getInstance().getConfig(); // Get all plots claimed by inactive players. int plotInactivityDays = config.getInt("plot_inactive_cancel"); - long time = Time.currentTime(); + long time = System.currentTimeMillis(); long timeCap = plotInactivityDays * 24L * 60L * 60L * 1000L; long timeDif = time - timeCap; - // Get plot sql. - PlotSQL plotSQL = Network.getInstance().getPlotSQL(); - // Get plots that will be deleted for inactive in 1 day. - // If the inactivity is less than 3 days don't bother. + // If the inactivity is less than 3 days, don't bother. if (plotInactivityDays >= 3) { - // The bound will be 1 hour, since this timer goes all every hour. long timeCapPlus1 = timeDif + (24 * 60 * 60 * 1000); - List nearlyInactivePlots = plotSQL.getIntList("SELECT pm.id FROM plot_members AS pm INNER JOIN plot_data AS pd ON pd.id=pm.id " + - "WHERE pm.is_owner=1 AND pm.last_enter>=" + timeDif + " AND pm.last_enter<" + timeCapPlus1 + " AND pd.status='claimed' AND pm.inactivity_notice=0 AND pd" + - ".location IN (" + - "SELECT ld.name FROM location_data AS ld WHERE ld.server='" + PlotSystem.SERVER_NAME + "');"); + List nearlyInactivePlots = networkAPI.getPlotAPI() + .getClaimedPlotsLastEnteredBetweenWithoutInactivityNoticeForServer(timeDif, timeCapPlus1, PlotSystem.SERVER_NAME); // Send DM to users that their plot will be deleted in 24 hours. if (nearlyInactivePlots != null) { nearlyInactivePlots.forEach(plotId -> { // Get the uuid of the plot owner. - String uuid = plotSQL.getString("SELECT uuid FROM plot_members WHERE id=" + plotId + " AND is_owner=1;"); + String uuid = networkAPI.getPlotAPI().getPlotOwner(plotId); if (uuid != null) { // Set the inactivity notice to 1 and send a dm. - plotSQL.update("UPDATE plot_members SET inactivity_notice=1 WHERE id=" + plotId + " AND uuid='" + uuid + "';"); + networkAPI.getPlotAPI().setPlotInactivityNotice(plotId, uuid); DiscordDirectMessage discordDirectMessage = new DiscordDirectMessage(uuid, String.format("Plot %d has been inactive for %d days. The plot will be deleted in 24 hours, to prevent this please enter the plot.", plotId, plotInactivityDays - 1)); - Network.getInstance().getChat().sendSocketMesage(discordDirectMessage); + networkAPI.getChat().sendDiscordDirectMessage(discordDirectMessage); } }); } @@ -66,9 +58,7 @@ public static void cancelInactivePlots() { // Get inactive plots. // Check if they are claimed (not submitted), the last enter time is greater than the inactivity time and the location is on this server. - List inactivePlots = plotSQL.getIntList("SELECT pm.id FROM plot_members AS pm INNER JOIN plot_data AS pd ON pd.id=pm.id " + - "WHERE pm.is_owner=1 AND pm.last_enter<" + timeDif + " AND pd.status='claimed' AND pd.location IN (" + - "SELECT ld.name FROM location_data AS ld WHERE ld.server='" + PlotSystem.SERVER_NAME + "');"); + List inactivePlots = networkAPI.getPlotAPI().getInactivePlotsForServer(timeDif, PlotSystem.SERVER_NAME); // If there are no inactive plots, end the method. if (inactivePlots == null || inactivePlots.isEmpty()) { @@ -81,7 +71,7 @@ public static void cancelInactivePlots() { for (int plot : inactivePlots) { // Get plot location. - String location = plotSQL.getString("SELECT location FROM plot_data WHERE id=" + plot + ";"); + String location = networkAPI.getPlotAPI().getPlotLocation(plot); // Get worlds of plot and save location. String save_world = config.getString("save_world"); @@ -93,8 +83,8 @@ public static void cancelInactivePlots() { World copyWorld = Bukkit.getWorld(save_world); World pasteWorld = Bukkit.getWorld(location); - int minusXTransform = -plotSQL.getInt("SELECT xTransform FROM location_data WHERE name='" + location + "';"); - int minusZTransform = -plotSQL.getInt("SELECT zTransform FROM location_data WHERE name='" + location + "';"); + int minusXTransform = -networkAPI.getPlotAPI().getXTransform(location); + int minusZTransform = -networkAPI.getPlotAPI().getZTransform(location); // Get the plot bounds. List pasteVector; @@ -109,7 +99,7 @@ public static void cancelInactivePlots() { // The negative transform is used because the coordinates by default are transformed from the save to the paste world, which in this case it reversed. List copyVector = new ArrayList<>(); for (BlockVector2 bv : pasteVector) { - copyVector.add(BlockVector2.at(bv.getX() + minusXTransform, bv.getZ() + minusZTransform)); + copyVector.add(BlockVector2.at(bv.x() + minusXTransform, bv.z() + minusZTransform)); } assert copyWorld != null; @@ -126,19 +116,19 @@ public static void cancelInactivePlots() { } // Get the uuid of the plot owner. - String uuid = plotSQL.getString("SELECT uuid FROM plot_members WHERE id=" + plot + " AND is_owner=1;"); + String uuid = networkAPI.getPlotAPI().getPlotOwner(plot); // Remove all members of plot in database. - plotSQL.update("DELETE FROM plot_members WHERE id=" + plot + ";"); + networkAPI.getPlotAPI().clearPlotMembers(plot); // Set plot status to unclaimed. - PlotHelper.updatePlotStatus(plot, PlotStatus.UNCLAIMED); + plotHelper.updatePlotStatus(plot, PlotStatus.UNCLAIMED); DirectMessage directMessage = new DirectMessage("global", uuid, "server", ChatUtils.error("Plot %s has been removed due to inactivity!", String.valueOf(plot)), true); DiscordDirectMessage discordDirectMessage = new DiscordDirectMessage(uuid, String.format("Plot %d has been removed due to inactivity!", plot)); - Network.getInstance().getChat().sendSocketMesage(directMessage); - Network.getInstance().getChat().sendSocketMesage(discordDirectMessage); + networkAPI.getChat().sendDirectMessage(directMessage); + networkAPI.getChat().sendDiscordDirectMessage(discordDirectMessage); // Log plot removal to console. PlotSystem.LOGGER.info("Plot " + plot + " removed due to inactivity!"); @@ -147,19 +137,16 @@ public static void cancelInactivePlots() { } } - public static void closeExpiredZones() { + public static void closeExpiredZones(NetworkAPI networkAPI) { // Get config. FileConfiguration config = PlotSystem.getInstance().getConfig(); // Get current time, this will be compared with the expiration time. - long time = Time.currentTime(); - - // Get plot sql. - PlotSQL plotSQL = Network.getInstance().getPlotSQL(); + long time = System.currentTimeMillis(); // Get active zones that have expired. - List expiredZones = plotSQL.getIntList("SELECT id FROM zones WHERE status='open' AND expiration<" + time + ";"); + List expiredZones = networkAPI.getPlotAPI().getExpiredZonesForServer(time, PlotSystem.SERVER_NAME); // If there are no inactive plots, end the method. if (expiredZones == null || expiredZones.isEmpty()) { @@ -170,72 +157,66 @@ public static void closeExpiredZones() { for (int zone : expiredZones) { // Get zone location. - String location = plotSQL.getString("SELECT location FROM zones WHERE id=" + zone + ";"); - - // Check if the zone is on this server. - if (plotSQL.hasRow("SELECT name FROM location_data WHERE name='" + location + - "' AND server='" + PlotSystem.SERVER_NAME + "';")) { - - // Get worlds of plot and save location. - String save_world = config.getString("save_world"); - if (save_world == null) { - PlotSystem.LOGGER.warning("Save World is not defined in config, plot delete event has therefore failed!"); - continue; - } + String location = networkAPI.getPlotAPI().getZoneLocation(zone); - World copyWorld = Bukkit.getWorld(location); - World pasteWorld = Bukkit.getWorld(save_world); + // Get worlds of plot and save location. + String save_world = config.getString("save_world"); + if (save_world == null) { + PlotSystem.LOGGER.warning("Save World is not defined in config, plot delete event has therefore failed!"); + continue; + } - int minusXTransform = -plotSQL.getInt("SELECT xTransform FROM location_data WHERE name='" + location + "';"); - int minusZTransform = -plotSQL.getInt("SELECT zTransform FROM location_data WHERE name='" + location + "';"); + World copyWorld = Bukkit.getWorld(location); + World pasteWorld = Bukkit.getWorld(save_world); - // Get the zone bounds. - List copyVector; - try { - copyVector = WorldGuardFunctions.getPoints("z" + zone, copyWorld); - } catch (RegionNotFoundException | RegionManagerNotFoundException e) { - e.printStackTrace(); - continue; - } + int minusXTransform = -networkAPI.getPlotAPI().getXTransform(location); + int minusZTransform = -networkAPI.getPlotAPI().getZTransform(location); - // Create the copyVector by transforming the points in the paste vector with the negative transform. - // The negative transform is used because the coordinates by default are transformed from the save to the paste world, which in this case it reversed. - List pasteVector = new ArrayList<>(); - for (BlockVector2 bv : copyVector) { - pasteVector.add(BlockVector2.at(bv.getX() + minusXTransform, bv.getZ() + minusZTransform)); - } + // Get the zone bounds. + List copyVector; + try { + copyVector = WorldGuardFunctions.getPoints("z" + zone, copyWorld); + } catch (RegionNotFoundException | RegionManagerNotFoundException e) { + e.printStackTrace(); + continue; + } - assert copyWorld != null; + // Create the copyVector by transforming the points in the paste vector with the negative transform. + // The negative transform is used because the coordinates by default are transformed from the save to the paste world, which in this case it reversed. + List pasteVector = new ArrayList<>(); + for (BlockVector2 bv : copyVector) { + pasteVector.add(BlockVector2.at(bv.x() + minusXTransform, bv.z() + minusZTransform)); + } - // Save the zone by copying from the building world to the save world. - Bukkit.getScheduler().runTaskAsynchronously(PlotSystem.getInstance(), () -> { - WorldEditor.updateWorld(copyVector, pasteVector, copyWorld, pasteWorld); + assert copyWorld != null; - // Delete the worldguard region. - try { - WorldGuardFunctions.delete("z" + zone, copyWorld); - } catch (RegionManagerNotFoundException e) { - e.printStackTrace(); - } + // Save the zone by copying from the building world to the save world. + Bukkit.getScheduler().runTaskAsynchronously(PlotSystem.getInstance(), () -> { + WorldEditor.updateWorld(copyVector, pasteVector, copyWorld, pasteWorld); - // Get the uuid of the zone owner. - String uuid = plotSQL.getString("SELECT uuid FROM zone_members WHERE id=" + zone + " AND is_owner=1;"); + // Delete the worldguard region. + try { + WorldGuardFunctions.delete("z" + zone, copyWorld); + } catch (RegionManagerNotFoundException e) { + e.printStackTrace(); + } - // Remove all members of zone in database. - plotSQL.update("DELETE FROM zone_members WHERE id=" + zone + ";"); + // Get the uuid of the zone owner. + String uuid = networkAPI.getPlotAPI().getZoneOwner(zone); - // Set the zone status to closed. - plotSQL.update("UPDATE zones SET status='closed' WHERE id=" + zone + ";"); + // Remove all members of zone in database. + networkAPI.getPlotAPI().clearZoneMembers(zone); - DirectMessage directMessage = new DirectMessage("global", uuid, "server", - ChatUtils.error("Zone %s has expired, its content has been saved.", String.valueOf(zone)), true); - Network.getInstance().getChat().sendSocketMesage(directMessage); + // Set the zone status to closed. + networkAPI.getPlotAPI().setZoneStatus(zone, "closed"); - // Log plot removal to console. - PlotSystem.LOGGER.info("Zone " + zone + " has expired."); + DirectMessage directMessage = new DirectMessage("global", uuid, "server", + ChatUtils.error("Zone %s has expired, its content has been saved.", String.valueOf(zone)), true); + networkAPI.getChat().sendDirectMessage(directMessage); - }); - } + // Log plot removal to console. + PlotSystem.LOGGER.info("Zone " + zone + " has expired."); + }); } } } diff --git a/src/main/java/net/bteuk/plotsystem/utils/Outlines.java b/src/main/java/net/bteuk/plotsystem/utils/Outlines.java index a6f096a..658c19e 100644 --- a/src/main/java/net/bteuk/plotsystem/utils/Outlines.java +++ b/src/main/java/net/bteuk/plotsystem/utils/Outlines.java @@ -9,7 +9,7 @@ import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion; import com.sk89q.worldguard.protection.regions.ProtectedPolygonalRegion; import com.sk89q.worldguard.protection.regions.ProtectedRegion; -import net.bteuk.plotsystem.PlotSystem; +import net.bteuk.network.api.PlotAPI; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.World; @@ -19,9 +19,6 @@ import java.util.HashMap; import java.util.List; -import static net.bteuk.network.utils.Constants.MAX_Y; -import static net.bteuk.network.utils.Constants.MIN_Y; - /** * This class deals with plot and zone outlines. * It will have methods to refresh outlines. @@ -57,7 +54,7 @@ public void removePlayer(Player player) { outlineBlockLocations.remove(player); } - public void addPlotOutlineForPlayer(String plotID, Player player) { + public void addPlotOutlineForPlayer(String plotID, Player player, PlotAPI plotAPI) { BlockLocations blockLocations = outlineBlockLocations.get(player); if (blockLocations != null) { RegionManager regions = wg.getPlatform().getRegionContainer().get(BukkitAdapter.adapt(player.getWorld())); @@ -71,7 +68,7 @@ public void addPlotOutlineForPlayer(String plotID, Player player) { // Get plot difficulty. int intPlotID = ParseUtils.toInt(plotID); if (intPlotID != 0) { - int difficulty = PlotSystem.getInstance().plotSQL.getInt("SELECT difficulty FROM plot_data WHERE id=" + intPlotID + ";"); + int difficulty = plotAPI.getPlotDifficulty(intPlotID); blockLocations.addOutline(region, difficultyMaterial(difficulty)); } } @@ -116,7 +113,7 @@ public void refreshOutlinesForPlayer(Player player) { * * @param user the user to add outlines for. */ - public void addNearbyOutlines(User user) { + public void addNearbyOutlines(User user, PlotAPI plotAPI) { Player player = user.player; // If the player does not have a key, add it. @@ -164,7 +161,7 @@ public void addNearbyOutlines(User user) { } else { // Get plot difficulty. - int difficulty = PlotSystem.getInstance().plotSQL.getInt("SELECT difficulty FROM plot_data WHERE id=" + plotID + ";"); + int difficulty = plotAPI.getPlotDifficulty(plotID); locations.addOutline(protectedRegion, difficultyMaterial(difficulty)); @@ -183,13 +180,13 @@ public void addOutline(List vector, World world, BlockData block) if (p.getWorld().equals(world)) { - ProtectedRegion region = new ProtectedPolygonalRegion("test", vector, MIN_Y, (MAX_Y - 1)); + ProtectedRegion region = new ProtectedPolygonalRegion("test", vector, world.getMinHeight(), (world.getMaxHeight() - 1)); // Check if they are within 100 blocks of the region min and max point. - if (p.getLocation().getX() > (region.getMinimumPoint().getX() - 100) && - p.getLocation().getZ() > (region.getMinimumPoint().getZ() - 100) && - p.getLocation().getX() < (region.getMaximumPoint().getX() + 100) && - p.getLocation().getZ() < (region.getMaximumPoint().getZ() + 100)) { + if (p.getLocation().getX() > (region.getMinimumPoint().x() - 100) && + p.getLocation().getZ() > (region.getMinimumPoint().z() - 100) && + p.getLocation().getX() < (region.getMaximumPoint().x() + 100) && + p.getLocation().getZ() < (region.getMaximumPoint().z() + 100)) { // If the player does not have a key, add it. BlockLocations locations; @@ -220,10 +217,10 @@ public void removeOutline(ProtectedRegion region, World world) { if (p.getWorld().equals(world)) { // Check if they are within 100 blocks of the region min and max point. - if (p.getLocation().getX() > (region.getMinimumPoint().getX() - 100) && - p.getLocation().getZ() > (region.getMinimumPoint().getZ() - 100) && - p.getLocation().getX() < (region.getMaximumPoint().getX() + 100) && - p.getLocation().getZ() < (region.getMaximumPoint().getZ() + 100)) { + if (p.getLocation().getX() > (region.getMinimumPoint().x() - 100) && + p.getLocation().getZ() > (region.getMinimumPoint().z() - 100) && + p.getLocation().getX() < (region.getMaximumPoint().x() + 100) && + p.getLocation().getZ() < (region.getMaximumPoint().z() + 100)) { // Remove the outline. if (outlineBlockLocations.containsKey(p)) { @@ -260,7 +257,7 @@ public void addOutline(Player player, List vector, BlockData block locations = addPlayer(player); } - ProtectedRegion region = new ProtectedPolygonalRegion("test", vector, MIN_Y, (MAX_Y - 1)); + ProtectedRegion region = new ProtectedPolygonalRegion("test", vector, player.getWorld().getMinHeight(), (player.getWorld().getMaxHeight() - 1)); // Add points and draw it. locations.addTempOutline(region, block); @@ -271,7 +268,7 @@ public void addOutline(Player player, List vector, BlockData block // This is for players drawing outlines with the selectiontool. public void removeOutline(Player player, List vector) { - ProtectedRegion region = new ProtectedPolygonalRegion("test", vector, MIN_Y, (MAX_Y - 1)); + ProtectedRegion region = new ProtectedPolygonalRegion("test", vector, player.getWorld().getMinHeight(), (player.getWorld().getMaxHeight() - 1)); // Remove the outline. if (outlineBlockLocations.containsKey(player)) { diff --git a/src/main/java/net/bteuk/plotsystem/utils/PlotHelper.java b/src/main/java/net/bteuk/plotsystem/utils/PlotHelper.java index 5605cab..7e9516a 100644 --- a/src/main/java/net/bteuk/plotsystem/utils/PlotHelper.java +++ b/src/main/java/net/bteuk/plotsystem/utils/PlotHelper.java @@ -75,7 +75,7 @@ private boolean updatePlotStatus(int id, PlotStatus status, SubmittedStatus subm hasChanged = true; } if (submittedStatus != null && plotAPI.getPlotSubmissionStatus(id) != submittedStatus) { - plotAPI.setPlotSubmissionStatus(id, submittedStatus.database_value); + plotAPI.setPlotSubmissionStatus(id, submittedStatus.getDatabaseValue()); hasChanged = true; } // Delay the hologram update until the plot has been completely updated. diff --git a/src/main/java/net/bteuk/plotsystem/utils/PlotValues.java b/src/main/java/net/bteuk/plotsystem/utils/PlotValues.java index 1de6eee..167956c 100644 --- a/src/main/java/net/bteuk/plotsystem/utils/PlotValues.java +++ b/src/main/java/net/bteuk/plotsystem/utils/PlotValues.java @@ -15,7 +15,7 @@ public static String difficultyName(int difficulty) { case 1 -> "Easy"; case 2 -> "Normal"; case 3 -> "Hard"; - default -> null; + default -> throw new IllegalArgumentException("Difficulty must be 1, 2 or 3!"); }; } @@ -26,7 +26,7 @@ public static String sizeName(int size) { case 1 -> "Small"; case 2 -> "Medium"; case 3 -> "Large"; - default -> null; + default -> throw new IllegalArgumentException("Size must be 1, 2 or 3!"); }; } @@ -37,7 +37,7 @@ public static Material sizeMaterial(int size) { case 1 -> Material.LIME_CONCRETE; case 2 -> Material.YELLOW_CONCRETE; case 3 -> Material.RED_CONCRETE; - default -> null; + default -> throw new IllegalArgumentException("Size must be 1, 2 or 3!"); }; } @@ -48,7 +48,7 @@ public static Material difficultyMaterial(int difficulty) { case 1 -> Material.LIME_CONCRETE; case 2 -> Material.YELLOW_CONCRETE; case 3 -> Material.RED_CONCRETE; - default -> null; + default -> throw new IllegalArgumentException("Difficulty must be 1, 2 or 3!"); }; } diff --git a/src/main/java/net/bteuk/plotsystem/utils/SelectionTool.java b/src/main/java/net/bteuk/plotsystem/utils/SelectionTool.java index b030093..0dfa8c3 100644 --- a/src/main/java/net/bteuk/plotsystem/utils/SelectionTool.java +++ b/src/main/java/net/bteuk/plotsystem/utils/SelectionTool.java @@ -1,8 +1,7 @@ package net.bteuk.plotsystem.utils; import com.sk89q.worldedit.math.BlockVector2; -import net.bteuk.network.api.CoordinateAPI; -import net.bteuk.network.api.PlotAPI; +import net.bteuk.network.api.NetworkAPI; import net.bteuk.network.lib.utils.ChatUtils; import net.bteuk.plotsystem.PlotSystem; import net.bteuk.plotsystem.utils.plugins.WGCreatePlot; @@ -31,7 +30,6 @@ public class SelectionTool extends WGCreatePlot { // Outlines private final Outlines outlines; - private final PlotAPI plotAPI; // Size and difficulty of the plot. // Represented by integer values of 1-3. // Size: 1=small, 2=medium, 3=large @@ -49,10 +47,9 @@ public class SelectionTool extends WGCreatePlot { // Area of the plot (m^2). private int area; - public SelectionTool(User u, PlotAPI plotAPI, PlotHelper plotHelper, CoordinateAPI coordinateAPI) { - super(plotAPI, plotHelper, coordinateAPI); + public SelectionTool(User u, NetworkAPI networkAPI, PlotHelper plotHelper) { + super(networkAPI, plotHelper); this.u = u; - this.plotAPI = plotAPI; vector = new ArrayList<>(); // Set default size and difficulty diff --git a/src/main/java/net/bteuk/plotsystem/utils/User.java b/src/main/java/net/bteuk/plotsystem/utils/User.java index 2aacc02..2873ee4 100644 --- a/src/main/java/net/bteuk/plotsystem/utils/User.java +++ b/src/main/java/net/bteuk/plotsystem/utils/User.java @@ -2,6 +2,7 @@ import lombok.Getter; import lombok.Setter; +import net.bteuk.network.api.NetworkAPI; import net.bteuk.plotsystem.PlotSystem; import net.bteuk.plotsystem.gui.ClaimGui; import net.bteuk.plotsystem.gui.CreatePlotGui; @@ -42,7 +43,7 @@ public class User { @Setter private boolean disableOutlines; - public User(Player player) { + public User(Player player, NetworkAPI networkAPI, PlotHelper plotHelper) { // Set player, uuid and name variable. this.player = player; @@ -50,12 +51,12 @@ public User(Player player) { name = player.getName(); // Set selection tool, only players with the valid roles can use it. - selectionTool = new SelectionTool(this); + selectionTool = new SelectionTool(this, networkAPI, plotHelper); // Set last location to current location. lastLocation = player.getLocation(); // Set outlines for player. - PlotSystem.getInstance().getOutlines().addNearbyOutlines(this); + PlotSystem.getInstance().getOutlines().addNearbyOutlines(this, networkAPI.getPlotAPI()); } } diff --git a/src/main/java/net/bteuk/plotsystem/utils/math/Point.java b/src/main/java/net/bteuk/plotsystem/utils/math/Point.java index 77c2d64..b743aee 100644 --- a/src/main/java/net/bteuk/plotsystem/utils/math/Point.java +++ b/src/main/java/net/bteuk/plotsystem/utils/math/Point.java @@ -14,8 +14,8 @@ public static BlockVector2 getAveragePoint(List points) { for (BlockVector2 bv : points) { - x += bv.getX() / size; - z += bv.getZ() / size; + x += bv.x() / size; + z += bv.z() / size; } diff --git a/src/main/java/net/bteuk/plotsystem/utils/plugins/WGCreatePlot.java b/src/main/java/net/bteuk/plotsystem/utils/plugins/WGCreatePlot.java index c21433c..8e8f46a 100644 --- a/src/main/java/net/bteuk/plotsystem/utils/plugins/WGCreatePlot.java +++ b/src/main/java/net/bteuk/plotsystem/utils/plugins/WGCreatePlot.java @@ -40,25 +40,23 @@ public WGCreatePlot(NetworkAPI networkAPI, PlotHelper plotHelper) { this.networkAPI = networkAPI; this.plotAPI = networkAPI.getPlotAPI(); this.plotHelper = plotHelper; - this.coordinateAPI = coordinateAPI; + this.coordinateAPI = networkAPI.getCoordinateAPI(); } // Create a plot with the current selection. public boolean createPlot(Player p, World world, String location, List vector, int size, int difficulty) { - // Get instance of WorldGuard. + // Get an instance of WorldGuard. WorldGuard wg = WorldGuard.getInstance(); // Get regions. RegionManager regions = wg.getPlatform().getRegionContainer().get(BukkitAdapter.adapt(world)); - - // Checking if regions isn't null, would indicate that the world doesn't exist. if (regions == null) { return false; } - // Create region to test. - ProtectedPolygonalRegion region = new ProtectedPolygonalRegion("test", vector, MIN_Y, (MAX_Y - 1)); + // Create a region to test. + ProtectedPolygonalRegion region = new ProtectedPolygonalRegion("test", vector, networkAPI.getMinY(), (networkAPI.getMaxY() - 1)); // Check whether the region overlaps an existing plot, if true stop the process. ApplicableRegionSet set = regions.getApplicableRegions(region); @@ -87,7 +85,7 @@ public boolean createPlot(Player p, World world, String location, List vector, long expiration, boolean isPublic) { - // Get instance of WorldGuard. + // Get an instance of WorldGuard. WorldGuard wg = WorldGuard.getInstance(); // Get regions. RegionManager regions = wg.getPlatform().getRegionContainer().get(BukkitAdapter.adapt(world)); - - // Checking if regions isn't null, would indicate that the world doesn't exist. if (regions == null) { return false; } - // Create region to test. - ProtectedPolygonalRegion region = new ProtectedPolygonalRegion("test", vector, MIN_Y, (MAX_Y - 1)); + // Create a region to test. + ProtectedPolygonalRegion region = new ProtectedPolygonalRegion("test", vector, networkAPI.getMinY(), (networkAPI.getMaxY() - 1)); // Check whether the region overlaps an existing plot, if true stop the process. ApplicableRegionSet set = regions.getApplicableRegions(region); @@ -133,7 +129,7 @@ public boolean createZone(Player p, World world, String location, List copyVector, List pasteVector, World copy, World paste) { @@ -34,8 +30,8 @@ public static boolean updateWorld(List copyVector, List getPointsTransformedToSaveWorld(String regionName, World world) throws RegionNotFoundException, RegionManagerNotFoundException { + public static List getPointsTransformedToSaveWorld(String regionName, World world, PlotAPI plotAPI) throws RegionNotFoundException, RegionManagerNotFoundException { List vector = getPoints(regionName, world); List newVector = new ArrayList<>(); // Get the negative coordinate transform. - PlotSQL plotSQL = Network.getInstance().getPlotSQL(); - - int xTransform = -plotSQL.getInt("SELECT xTransform FROM location_data WHERE name='" + world.getName() + "';"); - int zTransform = -plotSQL.getInt("SELECT zTransform FROM location_data WHERE name='" + world.getName() + "';"); + int xTransform = -plotAPI.getXTransform(world.getName()); + int zTransform = -plotAPI.getZTransform(world.getName()); // Apply to transform to each coordinate. - vector.forEach(bv -> newVector.add(BlockVector2.at(bv.getX() + xTransform, bv.getZ() + zTransform))); + vector.forEach(bv -> newVector.add(BlockVector2.at(bv.x() + xTransform, bv.z() + zTransform))); return newVector; From e8d33284870c559d5b5a94aaa23f63159d8a8f56 Mon Sep 17 00:00:00 2001 From: LM-Wolfert Date: Sun, 30 Nov 2025 13:56:54 +0100 Subject: [PATCH 13/21] Up to 1.8.0 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index b32524e..da6c361 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ net.bteuk PlotSystem - 1.7.1 + 1.8.0 jar PlotSystem From a0a3a0cb8a03f25f987af9bcc5f014516dd1ae87 Mon Sep 17 00:00:00 2001 From: LM-Wolfert Date: Sun, 30 Nov 2025 15:09:44 +0100 Subject: [PATCH 14/21] Small fixes --- src/main/java/net/bteuk/plotsystem/PlotSystem.java | 2 ++ src/main/java/net/bteuk/plotsystem/gui/ClaimGui.java | 5 ----- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/src/main/java/net/bteuk/plotsystem/PlotSystem.java b/src/main/java/net/bteuk/plotsystem/PlotSystem.java index 5f34ac6..8812523 100644 --- a/src/main/java/net/bteuk/plotsystem/PlotSystem.java +++ b/src/main/java/net/bteuk/plotsystem/PlotSystem.java @@ -4,6 +4,7 @@ import io.papermc.paper.plugin.lifecycle.event.LifecycleEventManager; import io.papermc.paper.plugin.lifecycle.event.types.LifecycleEvents; import lombok.Getter; +import net.bteuk.minecraft.gui.GuiListener; import net.bteuk.minecraft.gui.GuiManager; import net.bteuk.network.api.NetworkAPI; import net.bteuk.network.lib.utils.ChatUtils; @@ -139,6 +140,7 @@ public void enablePlugin() { final NetworkAPI networkAPI = networkProvider.getProvider(); this.guiManager = new GuiManager(); + new GuiListener(guiManager).register(this); this.plotHelper = new PlotHelper(networkAPI.getPlotAPI()); // Register hologram click event. diff --git a/src/main/java/net/bteuk/plotsystem/gui/ClaimGui.java b/src/main/java/net/bteuk/plotsystem/gui/ClaimGui.java index 7d82778..c2e3dfd 100644 --- a/src/main/java/net/bteuk/plotsystem/gui/ClaimGui.java +++ b/src/main/java/net/bteuk/plotsystem/gui/ClaimGui.java @@ -80,12 +80,7 @@ private void createGui() { double x = sumX / (double) corners.length; double z = sumZ / (double) corners.length; - // Subtract the coordinate transform to make the coordinates in the real location. - x -= plotAPI.getXTransform(plotAPI.getPlotLocation(plot)); - z -= plotAPI.getZTransform(plotAPI.getPlotLocation(plot)); - // Convert to irl coordinates. - try { final EarthGeneratorSettings bteGeneratorSettings = EarthGeneratorSettings.parse(EarthGeneratorSettings.BTE_DEFAULT_SETTINGS); double[] coords = bteGeneratorSettings.projection().toGeo(x, z); From 7e1235884897d4492318e642833cbf80e67a7673 Mon Sep 17 00:00:00 2001 From: LM-Wolfert Date: Thu, 11 Dec 2025 18:45:21 +0100 Subject: [PATCH 15/21] Fixed Create Zone Gui title. --- src/main/java/net/bteuk/plotsystem/gui/CreateZoneGui.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/net/bteuk/plotsystem/gui/CreateZoneGui.java b/src/main/java/net/bteuk/plotsystem/gui/CreateZoneGui.java index 25a4a36..45def70 100644 --- a/src/main/java/net/bteuk/plotsystem/gui/CreateZoneGui.java +++ b/src/main/java/net/bteuk/plotsystem/gui/CreateZoneGui.java @@ -18,7 +18,7 @@ public class CreateZoneGui extends Gui { // This gui handles the plot creation process and will allow the user to set the parameters of the plot. public CreateZoneGui(GuiManager manager, User user) { - super(manager, 27, Component.text("Create Plot Menu", NamedTextColor.AQUA, TextDecoration.BOLD)); + super(manager, 27, Component.text("Create Zone Menu", NamedTextColor.AQUA, TextDecoration.BOLD)); this.user = user; @@ -38,7 +38,7 @@ private void createGui() { // Close the inventory. player.closeInventory(); - // Create plot with the selection created by the user. + // Create a zone with the selection created by the user. user.selectionTool.createZone(); }); From f8bf8f6d38cbd42e1426167c0e1fc38e5b714770 Mon Sep 17 00:00:00 2001 From: LM-Wolfert Date: Sat, 13 Dec 2025 11:03:54 +0100 Subject: [PATCH 16/21] Fix sql statement in verification menu. --- .../java/net/bteuk/plotsystem/reviewing/VerificationGui.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/net/bteuk/plotsystem/reviewing/VerificationGui.java b/src/main/java/net/bteuk/plotsystem/reviewing/VerificationGui.java index 9186148..3e72817 100644 --- a/src/main/java/net/bteuk/plotsystem/reviewing/VerificationGui.java +++ b/src/main/java/net/bteuk/plotsystem/reviewing/VerificationGui.java @@ -21,7 +21,7 @@ protected void createGuiInfoItem() { setItem(4, Utils.createItem(Material.BOOK, 1, ChatUtils.title("Plot Info"), ChatUtils.line("Plot ID: " + reviewAction.getPlotID()), ChatUtils.line("Plot Owner: " + globalSQL.getString("SELECT name FROM player_data WHERE uuid='" + reviewAction.getPlotOwner() + "';")), - ChatUtils.line("Plot Reviewer: " + globalSQL.getString("SELECT name FROM player_data WHERE uuid='" + plotAPI.getPlotReviewer(reviewId))), + ChatUtils.line("Plot Reviewer: " + globalSQL.getString("SELECT name FROM player_data WHERE uuid='" + plotAPI.getPlotReviewer(reviewId) + "';")), ChatUtils.line("The reviewer ").append(ChatUtils.line(plotAPI.getReviewOutcome(reviewId) ? "accepted" : "denied")).append(ChatUtils.line(" this plot.")))); } From e2fe43de8d74098a51e46441a2c51f94663124a9 Mon Sep 17 00:00:00 2001 From: LM-Wolfert Date: Sun, 14 Dec 2025 11:42:31 +0100 Subject: [PATCH 17/21] When creating a zone, add the creator as owner. --- src/main/java/net/bteuk/plotsystem/utils/SelectionTool.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/net/bteuk/plotsystem/utils/SelectionTool.java b/src/main/java/net/bteuk/plotsystem/utils/SelectionTool.java index 0dfa8c3..ba0bca0 100644 --- a/src/main/java/net/bteuk/plotsystem/utils/SelectionTool.java +++ b/src/main/java/net/bteuk/plotsystem/utils/SelectionTool.java @@ -289,7 +289,7 @@ public void createZone() { if (createZone(u.player, world, location, vector, expiration, isPublic)) { // Add owner. - plotAPI.createZoneMember(plotID, u.player.getUniqueId().toString()); + plotAPI.createZoneOwner(plotID, u.player.getUniqueId().toString()); // Store zone bounds. int i = 1; From b616cc4e4c57d7944193da1456ffffd22da930c9 Mon Sep 17 00:00:00 2001 From: LM-Wolfert Date: Thu, 18 Dec 2025 21:58:53 +0100 Subject: [PATCH 18/21] Fixed timers for inactive plots/zones. --- .../java/net/bteuk/plotsystem/Timers.java | 4 +- .../net/bteuk/plotsystem/utils/Inactive.java | 15 ++-- .../plotsystem/utils/plugins/WorldEditor.java | 87 +++++++++---------- 3 files changed, 54 insertions(+), 52 deletions(-) diff --git a/src/main/java/net/bteuk/plotsystem/Timers.java b/src/main/java/net/bteuk/plotsystem/Timers.java index cfc6f51..030fd4f 100644 --- a/src/main/java/net/bteuk/plotsystem/Timers.java +++ b/src/main/java/net/bteuk/plotsystem/Timers.java @@ -54,14 +54,14 @@ public static void registerTimers(NetworkAPI networkAPI, PlotHelper plotHelper, } } - }, 20L); + }, 1000L); // 1-hour timer. // Remove inactive plots. networkAPI.getTimerAPI().registerTimer(() -> { Inactive.cancelInactivePlots(networkAPI, plotHelper); Inactive.closeExpiredZones(networkAPI); - }, 1200L, 72000L); + }, 3600000L, 60000L); registered = true; } diff --git a/src/main/java/net/bteuk/plotsystem/utils/Inactive.java b/src/main/java/net/bteuk/plotsystem/utils/Inactive.java index 1391fd8..d51abf7 100644 --- a/src/main/java/net/bteuk/plotsystem/utils/Inactive.java +++ b/src/main/java/net/bteuk/plotsystem/utils/Inactive.java @@ -18,6 +18,8 @@ import java.util.ArrayList; import java.util.List; +import static net.bteuk.plotsystem.PlotSystem.LOGGER; + public class Inactive { public static void cancelInactivePlots(NetworkAPI networkAPI, PlotHelper plotHelper) { @@ -65,7 +67,7 @@ public static void cancelInactivePlots(NetworkAPI networkAPI, PlotHelper plotHel return; } - PlotSystem.LOGGER.info("Found " + inactivePlots.size() + " inactive plots, clearing them."); + LOGGER.info("Found " + inactivePlots.size() + " inactive plots, clearing them."); // Iterate through all inactive plots and cancel them. for (int plot : inactivePlots) { @@ -76,7 +78,7 @@ public static void cancelInactivePlots(NetworkAPI networkAPI, PlotHelper plotHel // Get worlds of plot and save location. String save_world = config.getString("save_world"); if (save_world == null) { - PlotSystem.LOGGER.warning("Save World is not defined in config, plot delete event has therefore failed!"); + LOGGER.warning("Save World is not defined in config, plot delete event has therefore failed!"); continue; } @@ -131,7 +133,7 @@ public static void cancelInactivePlots(NetworkAPI networkAPI, PlotHelper plotHel networkAPI.getChat().sendDiscordDirectMessage(discordDirectMessage); // Log plot removal to console. - PlotSystem.LOGGER.info("Plot " + plot + " removed due to inactivity!"); + LOGGER.info("Plot " + plot + " removed due to inactivity!"); }); } @@ -162,7 +164,7 @@ public static void closeExpiredZones(NetworkAPI networkAPI) { // Get worlds of plot and save location. String save_world = config.getString("save_world"); if (save_world == null) { - PlotSystem.LOGGER.warning("Save World is not defined in config, plot delete event has therefore failed!"); + LOGGER.warning("Save World is not defined in config, plot delete event has therefore failed!"); continue; } @@ -192,7 +194,10 @@ public static void closeExpiredZones(NetworkAPI networkAPI) { // Save the zone by copying from the building world to the save world. Bukkit.getScheduler().runTaskAsynchronously(PlotSystem.getInstance(), () -> { + LOGGER.info("Zone " + zone + " has expired, saving it."); + long start = System.currentTimeMillis(); WorldEditor.updateWorld(copyVector, pasteVector, copyWorld, pasteWorld); + LOGGER.info("Zone " + zone + " has expired, saved in " + (System.currentTimeMillis() - start) + "ms."); // Delete the worldguard region. try { @@ -215,7 +220,7 @@ public static void closeExpiredZones(NetworkAPI networkAPI) { networkAPI.getChat().sendDirectMessage(directMessage); // Log plot removal to console. - PlotSystem.LOGGER.info("Zone " + zone + " has expired."); + LOGGER.info("Zone " + zone + " has expired."); }); } } diff --git a/src/main/java/net/bteuk/plotsystem/utils/plugins/WorldEditor.java b/src/main/java/net/bteuk/plotsystem/utils/plugins/WorldEditor.java index b35e946..d1b91e4 100644 --- a/src/main/java/net/bteuk/plotsystem/utils/plugins/WorldEditor.java +++ b/src/main/java/net/bteuk/plotsystem/utils/plugins/WorldEditor.java @@ -4,15 +4,12 @@ import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.bukkit.BukkitWorld; -import com.sk89q.worldedit.extent.clipboard.BlockArrayClipboard; import com.sk89q.worldedit.function.operation.ForwardExtentCopy; -import com.sk89q.worldedit.function.operation.Operation; import com.sk89q.worldedit.function.operation.Operations; import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.Polygonal2DRegion; -import com.sk89q.worldedit.session.ClipboardHolder; import net.bteuk.plotsystem.PlotSystem; import org.bukkit.Bukkit; import org.bukkit.World; @@ -26,48 +23,37 @@ public class WorldEditor { public static boolean updateWorld(List copyVector, List pasteVector, World copy, World paste) { - // Get the worlds in worldEdit format com.sk89q.worldedit.world.World copyWorld = new BukkitWorld(copy); com.sk89q.worldedit.world.World pasteWorld = new BukkitWorld(paste); Polygonal2DRegion copyRegion = new Polygonal2DRegion(copyWorld, copyVector, copyWorld.getMinY(), copyWorld.getMaxY() - 1); Polygonal2DRegion pasteRegion = new Polygonal2DRegion(pasteWorld, pasteVector, copyWorld.getMinY(), copyWorld.getMaxY() - 1); - BlockArrayClipboard clipboard = new BlockArrayClipboard(copyRegion); try ( - EditSession editSession = WorldEdit.getInstance().newEditSessionBuilder() - .world(copyWorld).fastMode(true).checkMemory(false).limitUnlimited().changeSetNull().build() + EditSession from = WorldEdit.getInstance().newEditSessionBuilder() + .world(copyWorld) + .fastMode(true) + .checkMemory(true) + .changeSetNull() + .build(); + EditSession to = WorldEdit.getInstance().newEditSessionBuilder() + .world(pasteWorld) + .fastMode(true) + .checkMemory(true) + .changeSetNull() + .build() ) { - ForwardExtentCopy forwardExtentCopy = new ForwardExtentCopy( - editSession, copyRegion, clipboard, copyRegion.getMinimumPoint() + ForwardExtentCopy forward = new ForwardExtentCopy( + from, copyRegion, to, pasteRegion.getMinimumPoint() ); - forwardExtentCopy.setCopyingBiomes(true); - // configure here - Operations.complete(forwardExtentCopy); - } catch (WorldEditException e) { - e.printStackTrace(); - return false; - } - - try ( - EditSession editSession = WorldEdit.getInstance().newEditSessionBuilder() - .world(pasteWorld).fastMode(true).checkMemory(false).limitUnlimited().changeSetNull().build() - ) { - - Operation operation = new ClipboardHolder(clipboard) - .createPaste(editSession) - .to(pasteRegion.getMinimumPoint()) - .copyBiomes(true) - // configure here - .build(); - Operations.complete(operation); - editSession.flushQueue(); + forward.setCopyingBiomes(true); + Operations.complete(forward); + to.flushQueue(); } catch (WorldEditException e) { e.printStackTrace(); return false; } - // Remove all entities in both worlds. Bukkit.getScheduler().runTask(PlotSystem.getInstance(), () -> { deleteEntities(copy); deleteEntities(paste); @@ -78,16 +64,19 @@ public static boolean updateWorld(List copyVector, List entities = world.getEntities(); From 30cf9e0b60d23115e791e79e45f44536baf6ba04 Mon Sep 17 00:00:00 2001 From: LM-Wolfert Date: Fri, 19 Dec 2025 16:35:07 +0100 Subject: [PATCH 19/21] Revert FAWE copy-paste code. --- .../plotsystem/utils/plugins/WorldEditor.java | 87 ++++++++++--------- 1 file changed, 45 insertions(+), 42 deletions(-) diff --git a/src/main/java/net/bteuk/plotsystem/utils/plugins/WorldEditor.java b/src/main/java/net/bteuk/plotsystem/utils/plugins/WorldEditor.java index d1b91e4..b35e946 100644 --- a/src/main/java/net/bteuk/plotsystem/utils/plugins/WorldEditor.java +++ b/src/main/java/net/bteuk/plotsystem/utils/plugins/WorldEditor.java @@ -4,12 +4,15 @@ import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.bukkit.BukkitWorld; +import com.sk89q.worldedit.extent.clipboard.BlockArrayClipboard; import com.sk89q.worldedit.function.operation.ForwardExtentCopy; +import com.sk89q.worldedit.function.operation.Operation; import com.sk89q.worldedit.function.operation.Operations; import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.Polygonal2DRegion; +import com.sk89q.worldedit.session.ClipboardHolder; import net.bteuk.plotsystem.PlotSystem; import org.bukkit.Bukkit; import org.bukkit.World; @@ -23,37 +26,48 @@ public class WorldEditor { public static boolean updateWorld(List copyVector, List pasteVector, World copy, World paste) { + // Get the worlds in worldEdit format com.sk89q.worldedit.world.World copyWorld = new BukkitWorld(copy); com.sk89q.worldedit.world.World pasteWorld = new BukkitWorld(paste); Polygonal2DRegion copyRegion = new Polygonal2DRegion(copyWorld, copyVector, copyWorld.getMinY(), copyWorld.getMaxY() - 1); Polygonal2DRegion pasteRegion = new Polygonal2DRegion(pasteWorld, pasteVector, copyWorld.getMinY(), copyWorld.getMaxY() - 1); + BlockArrayClipboard clipboard = new BlockArrayClipboard(copyRegion); try ( - EditSession from = WorldEdit.getInstance().newEditSessionBuilder() - .world(copyWorld) - .fastMode(true) - .checkMemory(true) - .changeSetNull() - .build(); - EditSession to = WorldEdit.getInstance().newEditSessionBuilder() - .world(pasteWorld) - .fastMode(true) - .checkMemory(true) - .changeSetNull() - .build() + EditSession editSession = WorldEdit.getInstance().newEditSessionBuilder() + .world(copyWorld).fastMode(true).checkMemory(false).limitUnlimited().changeSetNull().build() ) { - ForwardExtentCopy forward = new ForwardExtentCopy( - from, copyRegion, to, pasteRegion.getMinimumPoint() + ForwardExtentCopy forwardExtentCopy = new ForwardExtentCopy( + editSession, copyRegion, clipboard, copyRegion.getMinimumPoint() ); - forward.setCopyingBiomes(true); - Operations.complete(forward); - to.flushQueue(); + forwardExtentCopy.setCopyingBiomes(true); + // configure here + Operations.complete(forwardExtentCopy); + } catch (WorldEditException e) { + e.printStackTrace(); + return false; + } + + try ( + EditSession editSession = WorldEdit.getInstance().newEditSessionBuilder() + .world(pasteWorld).fastMode(true).checkMemory(false).limitUnlimited().changeSetNull().build() + ) { + + Operation operation = new ClipboardHolder(clipboard) + .createPaste(editSession) + .to(pasteRegion.getMinimumPoint()) + .copyBiomes(true) + // configure here + .build(); + Operations.complete(operation); + editSession.flushQueue(); } catch (WorldEditException e) { e.printStackTrace(); return false; } + // Remove all entities in both worlds. Bukkit.getScheduler().runTask(PlotSystem.getInstance(), () -> { deleteEntities(copy); deleteEntities(paste); @@ -64,19 +78,16 @@ public static boolean updateWorld(List copyVector, List entities = world.getEntities(); From 179c7cacfc9e30267b6fc73baad0d9e13eabbcdf Mon Sep 17 00:00:00 2001 From: LM-Wolfert Date: Fri, 16 Jan 2026 21:27:46 +0100 Subject: [PATCH 20/21] Fixed bug that teleported all players when deleting a location, rather than only the players currently in the world of that location. --- .../java/net/bteuk/plotsystem/commands/LocationCommand.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/java/net/bteuk/plotsystem/commands/LocationCommand.java b/src/main/java/net/bteuk/plotsystem/commands/LocationCommand.java index fc6288e..7db62e4 100644 --- a/src/main/java/net/bteuk/plotsystem/commands/LocationCommand.java +++ b/src/main/java/net/bteuk/plotsystem/commands/LocationCommand.java @@ -474,8 +474,10 @@ private void teleportPlayersFromLocation(String location, World saveWorld) { // Teleport all players away from the location. Location teleportLocation = new Location(saveWorld, x, Utils.getHighestYAt(saveWorld, (int) x, (int) z), z); PlotSystem.getInstance().getServer().getOnlinePlayers().forEach(player -> { - player.teleport(teleportLocation); - player.sendMessage(ChatUtils.success("Teleported to save world, location %s is being deleted.", location)); + if (player.getWorld().getName().equals(location)) { + player.teleport(teleportLocation); + player.sendMessage(ChatUtils.success("Teleported to save world, location %s is being deleted.", location)); + } }); } From ef27b1aba3a34b7e2bc038e776ce73a5fc2233c1 Mon Sep 17 00:00:00 2001 From: LM-Wolfert Date: Sat, 24 Jan 2026 17:24:26 +0100 Subject: [PATCH 21/21] Added /ps updateflags to set all the flags in a plotsystem location. --- .../commands/PlotSystemCommand.java | 45 ++++++-- .../plotsystem/utils/plugins/Multiverse.java | 63 +---------- .../utils/plugins/WorldGuardFunctions.java | 107 +++++++++++++++++- 3 files changed, 143 insertions(+), 72 deletions(-) diff --git a/src/main/java/net/bteuk/plotsystem/commands/PlotSystemCommand.java b/src/main/java/net/bteuk/plotsystem/commands/PlotSystemCommand.java index 3e6c94f..f188a67 100644 --- a/src/main/java/net/bteuk/plotsystem/commands/PlotSystemCommand.java +++ b/src/main/java/net/bteuk/plotsystem/commands/PlotSystemCommand.java @@ -8,27 +8,31 @@ import net.bteuk.network.lib.utils.ChatUtils; import net.bteuk.network.papercore.LocationAdapter; import net.bteuk.plotsystem.PlotSystem; +import net.bteuk.plotsystem.exceptions.RegionManagerNotFoundException; import net.bteuk.plotsystem.utils.ParseUtils; import net.bteuk.plotsystem.utils.PlotHelper; import net.bteuk.plotsystem.utils.PlotHologram; import net.bteuk.plotsystem.utils.User; +import net.bteuk.plotsystem.utils.plugins.WorldGuardFunctions; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; +import org.bukkit.Bukkit; import org.bukkit.Location; -import org.bukkit.command.Command; +import org.bukkit.World; import org.bukkit.command.CommandSender; -import org.bukkit.command.TabCompleter; import org.bukkit.entity.Player; import org.bukkit.util.StringUtil; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; import java.util.ArrayList; +import java.util.Collection; import java.util.List; -public class PlotSystemCommand implements BasicCommand, TabCompleter { +import static net.bteuk.plotsystem.PlotSystem.LOGGER; - private static final List options = List.of("create", "selectiontool", "delete", "help", "setalias", "movemarker", "update"); +public class PlotSystemCommand implements BasicCommand { + + private static final List options = List.of("create", "selectiontool", "delete", "help", "setalias", "movemarker", "update", "updateflags"); private final PlotAPI plotAPI; @@ -63,7 +67,7 @@ public void execute(CommandSourceStack stack, String[] args) { return; } - switch (args[0]) { + switch (args[0].toLowerCase()) { case "selectiontool" -> selectionTool(sender); case "create" -> createCommand.create(sender, args); @@ -79,6 +83,7 @@ public void execute(CommandSourceStack stack, String[] args) { } } case "movemarker" -> moveHologram(sender, args); + case "updateflags" -> updateFlags(sender, args); default -> sender.sendMessage(ChatUtils.error("/plotsystem help")); } } @@ -205,8 +210,34 @@ private void moveHologram(CommandSender sender, String[] args) { } } + public void updateFlags(CommandSender sender, String[] args) { + if (!sender.hasPermission("uknet.plots.updateflags")) { + sender.sendMessage(ChatUtils.error("You do not have permission to use this command.")); + return; + } + + if (args.length < 2) { + sender.sendMessage(ChatUtils.error("/plotsystem updateflags ")); + return; + } + + World world = Bukkit.getWorld(args[1]); + + if (world == null) { + sender.sendMessage(ChatUtils.error("Location " + args[1] + " does not exist on this server.")); + return; + } + + try { + WorldGuardFunctions.setWorldFlags(world); + } catch (RegionManagerNotFoundException e) { + sender.sendMessage(ChatUtils.error("An error occurred while updating flags, please contact an admin.")); + LOGGER.severe("Unable to update flags for world " + args[1] + ":" + e.getMessage()); + } + } + @Override - public @Nullable List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String @NotNull [] args) { + public @NotNull Collection suggest(@NotNull CommandSourceStack commandSourceStack, String @NotNull [] args) { // Return list. List returns = new ArrayList<>(); diff --git a/src/main/java/net/bteuk/plotsystem/utils/plugins/Multiverse.java b/src/main/java/net/bteuk/plotsystem/utils/plugins/Multiverse.java index 4cfca3a..c1723a1 100644 --- a/src/main/java/net/bteuk/plotsystem/utils/plugins/Multiverse.java +++ b/src/main/java/net/bteuk/plotsystem/utils/plugins/Multiverse.java @@ -1,13 +1,6 @@ package net.bteuk.plotsystem.utils.plugins; -import com.sk89q.worldedit.bukkit.BukkitAdapter; -import com.sk89q.worldguard.WorldGuard; -import com.sk89q.worldguard.protection.flags.Flag; -import com.sk89q.worldguard.protection.flags.Flags; -import com.sk89q.worldguard.protection.flags.StateFlag; -import com.sk89q.worldguard.protection.managers.RegionManager; -import com.sk89q.worldguard.protection.managers.storage.StorageException; -import com.sk89q.worldguard.protection.regions.GlobalProtectedRegion; +import net.bteuk.plotsystem.exceptions.RegionManagerNotFoundException; import org.bukkit.Bukkit; import org.bukkit.Difficulty; import org.bukkit.GameMode; @@ -19,8 +12,6 @@ import org.mvplugins.multiverse.core.world.options.CreateWorldOptions; import org.mvplugins.multiverse.core.world.options.RemoveWorldOptions; -import java.util.HashMap; -import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import static net.bteuk.plotsystem.PlotSystem.LOGGER; @@ -74,56 +65,10 @@ public static boolean createVoidWorld(String name) { world.setGameRule(GameRule.DO_WARDEN_SPAWNING, false); world.setGameRule(GameRule.DO_PATROL_SPAWNING, false); - // Get worldguard. - WorldGuard wg = WorldGuard.getInstance(); - RegionManager regions = wg.getPlatform().getRegionContainer().get(BukkitAdapter.adapt(world)); - - if (regions == null) { - LOGGER.warning("Regions is null!"); - return false; - } - - // Create global region and add all necessary flags. - GlobalProtectedRegion globalRegion = new GlobalProtectedRegion("__global__"); - - Map, Object> flags = new HashMap<>(); - flags.put(Flags.OTHER_EXPLOSION, StateFlag.State.DENY); - flags.put(Flags.WATER_FLOW, StateFlag.State.DENY); - flags.put(Flags.LEAF_DECAY, StateFlag.State.DENY); - flags.put(Flags.CORAL_FADE, StateFlag.State.DENY); - flags.put(Flags.LIGHTNING, StateFlag.State.DENY); - flags.put(Flags.SNOW_MELT, StateFlag.State.DENY); - flags.put(Flags.FROSTED_ICE_FORM, StateFlag.State.DENY); - flags.put(Flags.ICE_MELT, StateFlag.State.DENY); - flags.put(Flags.TRAMPLE_BLOCKS, StateFlag.State.DENY); - flags.put(Flags.FIRE_SPREAD, StateFlag.State.DENY); - flags.put(Flags.PISTONS, StateFlag.State.DENY); - flags.put(Flags.SOIL_DRY, StateFlag.State.DENY); - flags.put(Flags.LAVA_FLOW, StateFlag.State.DENY); - flags.put(Flags.GRASS_SPREAD, StateFlag.State.DENY); - flags.put(Flags.LAVA_FIRE, StateFlag.State.DENY); - flags.put(Flags.SNOW_FALL, StateFlag.State.DENY); - flags.put(Flags.PASSTHROUGH, StateFlag.State.DENY); - flags.put(Flags.ICE_FORM, StateFlag.State.DENY); - flags.put(Flags.GHAST_FIREBALL, StateFlag.State.DENY); - flags.put(Flags.FROSTED_ICE_MELT, StateFlag.State.DENY); - flags.put(Flags.CHEST_ACCESS, StateFlag.State.DENY); - flags.put(Flags.ENDERDRAGON_BLOCK_DAMAGE, StateFlag.State.DENY); - flags.put(Flags.ENDER_BUILD, StateFlag.State.DENY); - flags.put(Flags.ENTITY_ITEM_FRAME_DESTROY, StateFlag.State.DENY); - flags.put(Flags.ENTITY_PAINTING_DESTROY, StateFlag.State.DENY); - flags.put(Flags.PLACE_VEHICLE, StateFlag.State.DENY); - flags.put(Flags.POTION_SPLASH, StateFlag.State.DENY); - flags.put(Flags.RIDE, StateFlag.State.DENY); - - globalRegion.setFlags(flags); - - regions.addRegion(globalRegion); - try { - regions.saveChanges(); - } catch (StorageException e) { - e.printStackTrace(); + WorldGuardFunctions.setWorldFlags(world); + } catch (RegionManagerNotFoundException e) { + LOGGER.severe("Failed to set world flags: " + e.getMessage()); } LOGGER.info("Created new world with name " + name); diff --git a/src/main/java/net/bteuk/plotsystem/utils/plugins/WorldGuardFunctions.java b/src/main/java/net/bteuk/plotsystem/utils/plugins/WorldGuardFunctions.java index 5065120..93b5d16 100644 --- a/src/main/java/net/bteuk/plotsystem/utils/plugins/WorldGuardFunctions.java +++ b/src/main/java/net/bteuk/plotsystem/utils/plugins/WorldGuardFunctions.java @@ -5,8 +5,12 @@ import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldguard.WorldGuard; import com.sk89q.worldguard.protection.ApplicableRegionSet; +import com.sk89q.worldguard.protection.flags.Flag; +import com.sk89q.worldguard.protection.flags.Flags; +import com.sk89q.worldguard.protection.flags.StateFlag; import com.sk89q.worldguard.protection.managers.RegionManager; import com.sk89q.worldguard.protection.managers.storage.StorageException; +import com.sk89q.worldguard.protection.regions.GlobalProtectedRegion; import com.sk89q.worldguard.protection.regions.ProtectedPolygonalRegion; import com.sk89q.worldguard.protection.regions.ProtectedRegion; import com.sk89q.worldguard.protection.regions.RegionContainer; @@ -24,26 +28,32 @@ import org.bukkit.configuration.file.FileConfiguration; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.UUID; public class WorldGuardFunctions { - public static Location getCurrentLocation(String regionName, World world) throws RegionNotFoundException, RegionManagerNotFoundException { - + private static RegionManager getRegionManager(World world) throws RegionManagerNotFoundException { // Get worldguard instance WorldGuard wg = WorldGuard.getInstance(); // Get worldguard region data RegionContainer container = wg.getPlatform().getRegionContainer(); - RegionManager buildRegions = container.get(BukkitAdapter.adapt(world)); - - if (buildRegions == null) { + RegionManager regionManager = container.get(BukkitAdapter.adapt(world)); + if (regionManager == null) { throw new RegionManagerNotFoundException("RegionManager for world " + world.getName() + " is null!"); - } + return regionManager; + } + + public static Location getCurrentLocation(String regionName, World world) throws RegionNotFoundException, RegionManagerNotFoundException { + + RegionManager buildRegions = getRegionManager(world); + // Get the worldguard region and teleport to player to one of the corners. ProtectedPolygonalRegion region = (ProtectedPolygonalRegion) buildRegions.getRegion(regionName); @@ -324,4 +334,89 @@ public static List getPointsTransformedToSaveWorld(String regionNa return newVector; } + + /** + * Sets the global flags as intended for a world. + * @param world the world to set the flags for. + */ + public static void setWorldFlags(World world) throws RegionManagerNotFoundException { + + RegionManager regionManager = getRegionManager(world); + + // Create the global region and add all necessary flags. + ProtectedRegion region = regionManager.getRegion("__global__"); + + GlobalProtectedRegion globalRegion; + if (region instanceof GlobalProtectedRegion) { + globalRegion = (GlobalProtectedRegion) region; + } else { + globalRegion = new GlobalProtectedRegion("__global__"); + } + + Map, Object> flags = new HashMap<>(); + + // Destruction + flags.put(Flags.PASSTHROUGH, StateFlag.State.DENY); + flags.put(Flags.OTHER_EXPLOSION, StateFlag.State.DENY); + flags.put(Flags.LIGHTNING, StateFlag.State.DENY); + flags.put(Flags.TRAMPLE_BLOCKS, StateFlag.State.DENY); + flags.put(Flags.GHAST_FIREBALL, StateFlag.State.DENY); + flags.put(Flags.ENDERDRAGON_BLOCK_DAMAGE, StateFlag.State.DENY); + flags.put(Flags.ENDER_BUILD, StateFlag.State.DENY); + flags.put(Flags.ENTITY_ITEM_FRAME_DESTROY, StateFlag.State.DENY); + flags.put(Flags.ENTITY_PAINTING_DESTROY, StateFlag.State.DENY); + flags.put(Flags.TNT, StateFlag.State.DENY); + flags.put(Flags.WIND_CHARGE_BURST, StateFlag.State.DENY); + flags.put(Flags.CREEPER_EXPLOSION, StateFlag.State.DENY); + flags.put(Flags.BREEZE_WIND_CHARGE, StateFlag.State.DENY); + flags.put(Flags.WITHER_DAMAGE, StateFlag.State.DENY); + flags.put(Flags.RAVAGER_RAVAGE, StateFlag.State.DENY); + + // Fluids + flags.put(Flags.WATER_FLOW, StateFlag.State.DENY); + flags.put(Flags.LAVA_FLOW, StateFlag.State.DENY); + + // Block updates. + flags.put(Flags.LEAF_DECAY, StateFlag.State.DENY); + flags.put(Flags.CORAL_FADE, StateFlag.State.DENY); + flags.put(Flags.SNOW_MELT, StateFlag.State.DENY); + flags.put(Flags.FROSTED_ICE_FORM, StateFlag.State.DENY); + flags.put(Flags.ICE_MELT, StateFlag.State.DENY); + flags.put(Flags.FIRE_SPREAD, StateFlag.State.DENY); + flags.put(Flags.PISTONS, StateFlag.State.DENY); + flags.put(Flags.SOIL_DRY, StateFlag.State.DENY); + flags.put(Flags.GRASS_SPREAD, StateFlag.State.DENY); + flags.put(Flags.LAVA_FIRE, StateFlag.State.DENY); + flags.put(Flags.SNOW_FALL, StateFlag.State.DENY); + flags.put(Flags.ICE_FORM, StateFlag.State.DENY); + flags.put(Flags.FROSTED_ICE_MELT, StateFlag.State.DENY); + flags.put(Flags.SNOWMAN_TRAILS, StateFlag.State.DENY); + flags.put(Flags.MUSHROOMS, StateFlag.State.DENY); + flags.put(Flags.VINE_GROWTH, StateFlag.State.DENY); + flags.put(Flags.MYCELIUM_SPREAD, StateFlag.State.DENY); + flags.put(Flags.ROCK_GROWTH, StateFlag.State.DENY); + flags.put(Flags.SCULK_GROWTH, StateFlag.State.DENY); + flags.put(Flags.CROP_GROWTH, StateFlag.State.DENY); + flags.put(Flags.COPPER_FADE, StateFlag.State.DENY); + flags.put(Flags.MOISTURE_CHANGE, StateFlag.State.DENY); + + // Access + flags.put(Flags.CHEST_ACCESS, StateFlag.State.DENY); + flags.put(Flags.PLACE_VEHICLE, StateFlag.State.DENY); + flags.put(Flags.POTION_SPLASH, StateFlag.State.DENY); + flags.put(Flags.RIDE, StateFlag.State.DENY); + flags.put(Flags.MOB_SPAWNING, StateFlag.State.DENY); + flags.put(Flags.RESPAWN_ANCHORS, StateFlag.State.DENY); + flags.put(Flags.FIREWORK_DAMAGE, StateFlag.State.DENY); + + globalRegion.setFlags(flags); + + regionManager.addRegion(globalRegion); + + try { + regionManager.saveChanges(); + } catch (StorageException e) { + throw new RuntimeException("Failed to save changes to region manager!", e); + } + } }