diff --git a/pom.xml b/pom.xml
index 4abe401..da6c361 100644
--- a/pom.xml
+++ b/pom.xml
@@ -6,14 +6,24 @@
net.bteuk
PlotSystem
- 1.7.0
+ 1.8.0
jar
PlotSystem
- 21
+ 21
+ ${java-version}
UTF-8
+
+ 1.21.8-R0.1-SNAPSHOT
+
+ 0c82879524
+ 5958727df9
+
+ 5.3.3
+
+ 1.18.42
@@ -21,9 +31,15 @@
org.apache.maven.plugins
maven-compiler-plugin
- 3.8.1
+ 3.11.0
- ${java.version}
+
+
+ org.projectlombok
+ lombok
+ ${lombok.version}
+
+
@@ -68,6 +84,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 +116,7 @@
com.intellectualsites.bom
bom-newest
- 1.37
+ 1.55
import
pom
@@ -106,16 +127,33 @@
io.papermc.paper
paper-api
- 1.21.4-R0.1-SNAPSHOT
+ ${paper.api.version}
provided
- com.github.BTEUK
- Network
- c8a9ff8b97
+ 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 +175,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
+ ${lombok.version}
provided
com.github.decentsoftware-eu
decentholograms
- 2.8.11
+ 2.9.7
provided
@@ -175,11 +208,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 1cfb765..8812523 100644
--- a/src/main/java/net/bteuk/plotsystem/PlotSystem.java
+++ b/src/main/java/net/bteuk/plotsystem/PlotSystem.java
@@ -4,14 +4,27 @@
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.GuiListener;
+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.LocationCommand;
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.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;
@@ -24,6 +37,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,7 +45,9 @@
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 org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
@@ -51,10 +67,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;
// Returns the User ArrayList.
@@ -67,6 +79,10 @@ public class PlotSystem extends JavaPlugin {
@Getter
private boolean isClosing = false;
+ private GuiManager guiManager;
+
+ private PlotHelper plotHelper;;
+
@Override
public void onEnable() {
@@ -93,55 +109,48 @@ 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();
+ new GuiListener(guiManager).register(this);
+ this.plotHelper = new PlotHelper(networkAPI.getPlotAPI());
+
// Register hologram click event.
new HologramClickEvent(this);
- // Initialise the plot helper.
- PlotHelper.init(plotSQL);
-
// General Setup
// 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 + "';");
+ networkAPI.getPlotAPI().resetPlotSubmissions(SERVER_NAME);
// Create gui item
gui = new ItemStack(Material.NETHER_STAR);
@@ -152,10 +161,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, globalSQL);
- timers.startTimers();
-
// Create bungeecord channel
this.getServer().getMessenger().registerOutgoingPluginChannel(this, "BungeeCord");
@@ -166,31 +171,46 @@ public void enablePlugin() {
selectionTool.setItemMeta(meta);
// Listeners
- new JoinServer(this, globalSQL, plotSQL);
+ new JoinServer(this, networkAPI, plotHelper);
new QuitServer(this);
- new PlayerInteract(instance, plotSQL);
+ new PlayerInteract(instance, networkAPI.getPlotAPI());
new CloseInventory(this);
+ // Events
+ 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, 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, 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("toggleoutlines", "Toggles the visibility of outlines.", new ToggleOutlines(this));
+ 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, networkAPI.getPlotAPI()));
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','reviewing') 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, 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 44af4c4..030fd4f 100644
--- a/src/main/java/net/bteuk/plotsystem/Timers.java
+++ b/src/main/java/net/bteuk/plotsystem/Timers.java
@@ -1,111 +1,45 @@
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.plotsystem.utils.Inactive;
import net.bteuk.plotsystem.utils.Outlines;
+import net.bteuk.plotsystem.utils.PlotHelper;
import net.bteuk.plotsystem.utils.User;
-import org.bukkit.Bukkit;
-import java.util.ArrayList;
+import java.util.List;
-import static net.bteuk.network.utils.Constants.LOGGER;
+public final class Timers {
-public class Timers {
-
- final WorldGuard wg;
- // Plugin
- private final PlotSystem instance;
- // 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;
- this.users = instance.getUsers();
-
- this.globalSQL = globalSQL;
-
- SERVER_NAME = PlotSystem.SERVER_NAME;
-
- events = new ArrayList<>();
-
- wg = WorldGuard.getInstance();
-
- outlines = instance.getOutlines();
+ private static boolean registered = false;
+ private Timers() {
+ // Private constructor
}
- 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) {
+ public static void registerTimers(NetworkAPI networkAPI, PlotHelper plotHelper, Outlines outlines, List users) {
- isBusy = true;
+ if (registered) {
+ PlotSystem.LOGGER.warning("Timers already registered!");
+ return;
+ }
- // 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, () -> {
+ 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 {
@@ -113,20 +47,22 @@ public void startTimers() {
try {
outlines.refreshOutlinesForPlayer(u.player);
} catch (NullPointerException e) {
- outlines.addNearbyOutlines(u);
+ outlines.addNearbyOutlines(u, networkAPI.getPlotAPI());
u.lastLocation = u.player.getLocation();
}
}
}
- }, 0L, 20L);
+ }, 1000L);
- // 1 hour timer.
+ // 1-hour timer.
// Remove inactive plots.
- Bukkit.getScheduler().scheduleSyncRepeatingTask(instance, () -> {
- Inactive.cancelInactivePlots();
- Inactive.closeExpiredZones();
- }, 1200L, 72000L);
+ networkAPI.getTimerAPI().registerTimer(() -> {
+ Inactive.cancelInactivePlots(networkAPI, plotHelper);
+ Inactive.closeExpiredZones(networkAPI);
+ }, 3600000L, 60000L);
+
+ registered = true;
}
}
\ No newline at end of file
diff --git a/src/main/java/net/bteuk/plotsystem/commands/ClaimCommand.java b/src/main/java/net/bteuk/plotsystem/commands/ClaimCommand.java
index df54b25..b018ee0 100644
--- a/src/main/java/net/bteuk/plotsystem/commands/ClaimCommand.java
+++ b/src/main/java/net/bteuk/plotsystem/commands/ClaimCommand.java
@@ -1,50 +1,61 @@
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.minecraft.gui.GuiManager;
+import net.bteuk.network.api.NetworkAPI;
+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.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.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;
+ .append(ChatUtils.error(" Click here to open the tutorial menu!").clickEvent(ClickEvent.runCommand("/nav tutorials")));
- public ClaimCommand(PlotSQL plotSQL) {
- this.plotSQL = plotSQL;
+ private final NetworkAPI networkAPI;
+
+ private final PlotAPI plotAPI;
+
+ 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(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")) {
- switch (u.plotSQL.getInt("SELECT difficulty FROM plot_data WHERE id=" + plot + ";")) {
+ if (!player.hasPermission("uknet.plots.claim.all")) {
+ switch (networkAPI.getPlotAPI().getPlotDifficulty(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 +63,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 +72,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;
@@ -75,16 +86,15 @@ public static boolean hasClaimPermission(User u, NetworkUser user, int plot) {
}
@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;
@@ -92,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, 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);
}
}
@@ -126,17 +132,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,15 +150,14 @@ 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;
}
// 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 3b0f4c8..900aed1 100644
--- a/src/main/java/net/bteuk/plotsystem/commands/CreateCommand.java
+++ b/src/main/java/net/bteuk/plotsystem/commands/CreateCommand.java
@@ -1,46 +1,27 @@
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.minecraft.gui.GuiManager;
+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.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;
+ private final GuiManager guiManager;
- public CreateCommand(GlobalSQL globalSQL, PlotSQL plotSQL) {
+ private final PlotAPI plotAPI;
- this.globalSQL = globalSQL;
- this.plotSQL = plotSQL;
+ 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) {
@@ -54,7 +35,7 @@ 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]"));
}
@@ -72,278 +53,32 @@ private 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);
-
- }
-
- 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());
- }
-
- });
+ user.createPlotGui = new CreatePlotGui(guiManager, user);
+ user.createPlotGui.open(user.player);
}
public void createZone(CommandSender sender) {
@@ -357,43 +92,40 @@ public 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;
}
// 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 405123b..6299e8e 100644
--- a/src/main/java/net/bteuk/plotsystem/commands/DeleteCommand.java
+++ b/src/main/java/net/bteuk/plotsystem/commands/DeleteCommand.java
@@ -1,14 +1,12 @@
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;
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,20 +15,20 @@
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
-import java.util.ArrayList;
-
import static net.bteuk.plotsystem.PlotSystem.LOGGER;
public class DeleteCommand {
- private final GlobalSQL globalSQL;
- private final PlotSQL plotSQL;
+ private final PlotAPI plotAPI;
- public DeleteCommand(GlobalSQL globalSQL, PlotSQL plotSQL) {
+ private final PlotHelper plotHelper;
- this.globalSQL = globalSQL;
- this.plotSQL = plotSQL;
+ 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) {
@@ -51,7 +49,7 @@ public void delete(CommandSender sender, String[] args) {
case "location":
- deleteLocation(sender, args);
+ locationCommand.deleteLocation(sender, args);
break;
case "zone":
@@ -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) {
@@ -122,18 +119,18 @@ 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."));
}
- // 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) {
@@ -146,7 +143,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.")));
@@ -162,80 +159,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
new file mode 100644
index 0000000..7db62e4
--- /dev/null
+++ b/src/main/java/net/bteuk/plotsystem/commands/LocationCommand.java
@@ -0,0 +1,508 @@
+package net.bteuk.plotsystem.commands;
+
+import com.sk89q.worldedit.math.BlockVector3;
+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.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;
+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.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 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 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;
+ }
+
+ // 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.")));
+ 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);
+
+ 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)));
+
+ // 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)));
+
+ // 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.
+ eventAPI.createEvent(null, globalSQL.getString("SELECT name FROM server_data WHERE type='EARTH';"), "region set plotsystem " + region);
+
+ // Add region to database.
+ plotAPI.createPlotRegion(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, commandArguments.location(), coordMin, coordMax);
+ });
+ }
+
+ public 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;
+ }
+
+ // Check if the location name exists.
+ if (!plotAPI.hasLocation(commandArguments.location())) {
+ sender.sendMessage(ChatUtils.error("Location %s does not exist.", commandArguments.location()));
+ return;
+ }
+
+ // Check if the new area is equal or larger than the existing area.
+ final int minCoordinateId = plotAPI.getLocationCoordMin(commandArguments.location());
+ final int maxCoordinateId = plotAPI.getLocationCoordMax(commandArguments.location());
+
+ 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."));
+ 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 = plotAPI.getXTransform(commandArguments.location());
+ int zTransform = plotAPI.getZTransform(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 = plotAPI.getLocationRegions(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, (int) minCoordinate.y(), (int) maxCoordinate.y(), 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);
+
+ 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.
+ eventAPI.createEvent(null, globalSQL.getString("SELECT name FROM server_data WHERE type='EARTH';"), "region set plotsystem " + region.name());
+
+ // Add region to database.
+ plotAPI.createPlotRegion(region.name(), PlotSystem.SERVER_NAME, commandArguments.location());
+ }
+
+ sender.sendMessage(ChatUtils.success("Updated location %s", commandArguments.location()));
+
+ teleportToLocation(sender, commandArguments.location(), minCoordinateId, maxCoordinateId);
+ });
+ }
+
+ public 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 (!(plotAPI.locationExists(args[2]))) {
+ sender.sendMessage(ChatUtils.error("The location %s does not exist.", args[2]));
+ return;
+ }
+
+ // Check if the location is on this server.
+ if (!(plotAPI.getLocationServer(args[2]).equals(PlotSystem.SERVER_NAME))) {
+ sender.sendMessage(ChatUtils.error("This location is not on this server."));
+ return;
+ }
+
+ // If location has plots, cancel.
+ 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;
+ }
+
+ // 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);
+
+ // Delete location.
+ if (Multiverse.deleteWorld(args[2])) {
+
+ // Delete location from database.
+ 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 the database.
+ List regions = plotAPI.getLocationRegions(args[2]);
+
+ // Delete regions from database.
+ plotAPI.deleteRegionsForLocation(args[2]);
+
+ // Iterate through regions to unlock them on Earth.
+ for (String region : regions) {
+ 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."));
+ 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) {
+ 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 List getCopyRegions(CommandSender sender, RegionHolder regionHolder) {
+ List regionsToCopy = new ArrayList<>();
+
+ 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.
+ 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 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 = ((coordinateAPI.getX(coordMax) + coordinateAPI.getX(coordMin)) / 2) + plotAPI.getXTransform(location);
+
+ double z = ((coordinateAPI.getZ(coordMax) + coordinateAPI.getZ(coordMin)) / 2) + plotAPI.getZTransform(location);
+
+ // Teleport to the location.
+ World world = Bukkit.getWorld(location);
+
+ double y = 64;
+ if (world != null) {
+ y = world.getHighestBlockYAt((int) x, (int) z);
+ y++;
+ }
+
+ 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 void teleportPlayersFromLocation(String location, World saveWorld) {
+ int coordMin = plotAPI.getLocationCoordMin(location);
+ int coordMax = plotAPI.getLocationCoordMax(location);
+
+ // Get middle.
+ 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);
+ PlotSystem.getInstance().getServer().getOnlinePlayers().forEach(player -> {
+ if (player.getWorld().getName().equals(location)) {
+ 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) {
+
+ /**
+ * 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(NetworkLocation coordMin, NetworkLocation coordMax) {
+ boolean smaller = coordMin == null || coordMax == null;
+ smaller = smaller || (xmin > coordMin.x());
+ smaller = smaller || (zmin > coordMin.z());
+ smaller = smaller || (xmax < coordMax.x());
+ smaller = smaller || (zmax < coordMax.z());
+ return smaller;
+ }
+ }
+
+ 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 bbf3df9..f188a67 100644
--- a/src/main/java/net/bteuk/plotsystem/commands/PlotSystemCommand.java
+++ b/src/main/java/net/bteuk/plotsystem/commands/PlotSystemCommand.java
@@ -1,35 +1,59 @@
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.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.World;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
+import org.bukkit.util.StringUtil;
+import org.jetbrains.annotations.NotNull;
-import java.util.Arrays;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
-public class PlotSystemCommand extends AbstractCommand {
+import static net.bteuk.plotsystem.PlotSystem.LOGGER;
- private final PlotSQL plotSQL;
- private final GlobalSQL globalSQL;
+public class PlotSystemCommand implements BasicCommand {
- public PlotSystemCommand(GlobalSQL globalSQL, PlotSQL plotSQL) {
- this.plotSQL = plotSQL;
- this.globalSQL = globalSQL;
+ private static final List options = List.of("create", "selectiontool", "delete", "help", "setalias", "movemarker", "update", "updateflags");
- setTabCompleter(new FixedArgSelector(Arrays.asList("create", "selectiontool", "delete", "help", "setalias", "movemarker"), 0));
+ private final PlotAPI plotAPI;
+
+ 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, LocationCommand locationCommand) {
+ this.plotAPI = plotAPI;
+ this.plotHelper = plotHelper;
+ this.coordinateAPI = coordinateAPI;
+
+ this.createCommand = new CreateCommand(guiManager, plotAPI, locationCommand);
+ this.deleteCommand = new DeleteCommand(plotAPI, plotHelper, locationCommand);
+ this.updateCommand = new UpdateCommand(plotAPI, locationCommand);
}
@Override
@@ -37,23 +61,18 @@ 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;
}
- switch (args[0]) {
+ switch (args[0].toLowerCase()) {
case "selectiontool" -> selectionTool(sender);
- case "create" -> {
- CreateCommand createCommand = new CreateCommand(globalSQL, plotSQL);
- createCommand.create(sender, args);
- }
- case "delete" -> {
- DeleteCommand deleteCommand = new DeleteCommand(globalSQL, plotSQL);
- deleteCommand.delete(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" -> {
@@ -64,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"));
}
}
@@ -117,9 +137,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 "))
@@ -166,22 +186,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, plotAPI, coordinateAPI));
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));
}
@@ -189,4 +209,43 @@ private void moveHologram(CommandSender sender, String[] args) {
sender.sendMessage(ChatUtils.error("You must be a player to use this command."));
}
}
+
+ 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 @NotNull Collection suggest(@NotNull CommandSourceStack commandSourceStack, 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..b2c7c63 100644
--- a/src/main/java/net/bteuk/plotsystem/commands/ToggleOutlines.java
+++ b/src/main/java/net/bteuk/plotsystem/commands/ToggleOutlines.java
@@ -1,7 +1,8 @@
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.PlotAPI;
import net.bteuk.network.lib.utils.ChatUtils;
import net.bteuk.plotsystem.PlotSystem;
import net.bteuk.plotsystem.utils.User;
@@ -11,20 +12,22 @@
/**
* 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;
- public ToggleOutlines(PlotSystem instance) {
+ private final PlotAPI plotAPI;
+
+ public ToggleOutlines(PlotSystem instance, PlotAPI plotAPI) {
this.instance = instance;
+ this.plotAPI = plotAPI;
}
@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;
}
@@ -38,7 +41,7 @@ public void execute(@NotNull CommandSourceStack stack, @NotNull String[] 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
new file mode 100644
index 0000000..73c466d
--- /dev/null
+++ b/src/main/java/net/bteuk/plotsystem/commands/UpdateCommand.java
@@ -0,0 +1,86 @@
+package net.bteuk.plotsystem.commands;
+
+import net.bteuk.network.api.PlotAPI;
+import net.bteuk.network.lib.enums.PlotDifficulties;
+import net.bteuk.network.lib.utils.ChatUtils;
+import net.bteuk.plotsystem.PlotSystem;
+import net.kyori.adventure.text.Component;
+import org.bukkit.command.CommandSender;
+import org.bukkit.entity.Player;
+
+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 final 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) {
+
+ if (args.length < 2) {
+ sender.sendMessage(GENERIC_ERROR_MESSAGE);
+ return;
+ }
+
+ switch (args[1]) {
+ case "plot" -> updatePlot(sender, args);
+ case "location" -> locationCommand.updateLocation(sender, args);
+ default -> sender.sendMessage(GENERIC_ERROR_MESSAGE);
+ }
+ }
+
+ 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) {
+ 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;
+ }
+
+ // Check if plot exists.
+ if (!plotAPI.plotExists(plotID)) {
+ sender.sendMessage(ChatUtils.error("Plot %s does not exist.", args[2]));
+ return;
+ }
+
+ // Update the plot difficulty.
+ plotAPI.setPlotDifficulty(plotID, plotDifficulty.getValue());
+ sender.sendMessage(ChatUtils.success("Updated difficulty of plot %s to %s.", args[2], args[5]));
+
+ // Update the plot outlines.
+ PlotSystem.getInstance().getUsers().forEach(user -> PlotSystem.getInstance().getOutlines().addNearbyOutlines(user, plotAPI));
+ }
+}
diff --git a/src/main/java/net/bteuk/plotsystem/events/ClaimEvent.java b/src/main/java/net/bteuk/plotsystem/events/ClaimEvent.java
index 889004f..b7cb31c 100644
--- a/src/main/java/net/bteuk/plotsystem/events/ClaimEvent.java
+++ b/src/main/java/net/bteuk/plotsystem/events/ClaimEvent.java
@@ -1,24 +1,41 @@
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;
+import net.bteuk.plotsystem.utils.PlotHelper;
import net.bteuk.plotsystem.utils.User;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
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;
+
+ 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) {
// Events for claiming
if (event[1].equals("plot")) {
@@ -35,7 +52,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 +71,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,25 +89,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, plotAPI, plotHelper);
+ 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..f043de6 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);
+ PlotStatus currentStatus = plotAPI.getPlotStatus(id);
+ plotHelper.updatePlotStatus(id, PlotStatus.UNCLAIMED);
// Send message to plot owner.
Player p = Bukkit.getPlayer(UUID.fromString(uuid));
@@ -121,26 +131,23 @@ 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.
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")) {
- // 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
deleted file mode 100644
index 10d57a3..0000000
--- a/src/main/java/net/bteuk/plotsystem/events/EventManager.java
+++ /dev/null
@@ -1,29 +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 "teleport" -> TeleportEvent.event(uuid, event);
- 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 "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/TeleportEvent.java b/src/main/java/net/bteuk/plotsystem/events/PlotsystemTeleportEvent.java
similarity index 56%
rename from src/main/java/net/bteuk/plotsystem/events/TeleportEvent.java
rename to src/main/java/net/bteuk/plotsystem/events/PlotsystemTeleportEvent.java
index fbb6200..3c69e28 100644
--- a/src/main/java/net/bteuk/plotsystem/events/TeleportEvent.java
+++ b/src/main/java/net/bteuk/plotsystem/events/PlotsystemTeleportEvent.java
@@ -1,16 +1,18 @@
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;
import org.bukkit.Location;
import org.bukkit.World;
@@ -18,48 +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 (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 + ";"));
+ World world = Bukkit.getWorld(location);
+
+ if (world == null) {
+ 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;
@@ -72,33 +88,38 @@ 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 += 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."));
@@ -106,45 +127,39 @@ 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..0066157 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")) {
@@ -21,34 +34,32 @@ 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';")) {
+ // Check if the plot is submitted.
+ if (plotAPI.getPlotStatus(id) == PlotStatus.SUBMITTED) {
- // Set plot status to claimed.
- PlotHelper.updatePlotStatus(id, PlotStatus.CLAIMED);
+ // Set plot status to 'claimed'.
+ plotHelper.updatePlotStatus(id, PlotStatus.CLAIMED);
- // Remove submitted plot entry.
- PlotSystem.getInstance().plotSQL.update("DELETE FROM plot_submission WHERE plot_id=" + id + ";");
+ // Remove the submitted plot entry.
+ 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 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);
- Network.getInstance().getChat().sendSocketMesage(plotMessage);
+ 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",
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..c915cab 100644
--- a/src/main/java/net/bteuk/plotsystem/events/ReviewEvent.java
+++ b/src/main/java/net/bteuk/plotsystem/events/ReviewEvent.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 ReviewEvent {
+public class ReviewEvent 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 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) {
// Events for claiming
if (event[1].equals("plot")) {
@@ -55,22 +69,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.
- user.setReview(new Review(PlotSystem.getInstance(), id, user));
+ // Create new review instance for user.
+ user.setReview(new Review(PlotSystem.getInstance(), id, user, networkAPI, plotHelper, guiManager));
- //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 +90,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..ce93c18 100644
--- a/src/main/java/net/bteuk/plotsystem/events/SubmitEvent.java
+++ b/src/main/java/net/bteuk/plotsystem/events/SubmitEvent.java
@@ -1,18 +1,35 @@
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.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.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 class SubmitEvent implements Event {
- public static void event(String uuid, String[] event) {
+ private final PlotAPI plotAPI;
+
+ private final PlotHelper plotHelper;
+
+ private final 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, String sMessage) {
// Events for submitting
if (event[1].equals("plot")) {
@@ -22,13 +39,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,23 +67,22 @@ 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(
- "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 {
@@ -78,7 +94,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/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 15a77f3..c2e3dfd 100644
--- a/src/main/java/net/bteuk/plotsystem/gui/ClaimGui.java
+++ b/src/main/java/net/bteuk/plotsystem/gui/ClaimGui.java
@@ -1,24 +1,24 @@
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.api.PlotAPI;
+import net.bteuk.network.api.plotsystem.PlotStatus;
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,38 +28,43 @@ public class ClaimGui extends Gui {
private final int plot;
- public ClaimGui(User user, int plot) {
+ private final PlotAPI plotAPI;
- super(27, Component.text("Claim Plot", NamedTextColor.AQUA, TextDecoration.BOLD));
+ 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();
-
}
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"),
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);
+ int[][] corners = plotAPI.getPlotCorners(plot);
int sumX = 0;
int sumZ = 0;
@@ -75,24 +80,16 @@ 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 -= 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 + ";") + "';");
-
// Convert to irl coordinates.
-
try {
-
final EarthGeneratorSettings bteGeneratorSettings = EarthGeneratorSettings.parse(EarthGeneratorSettings.BTE_DEFAULT_SETTINGS);
double[] coords = bteGeneratorSettings.projection().toGeo(x, z);
// 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]));
- u.player.sendMessage(message);
+ 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) {
e.printStackTrace();
@@ -103,81 +100,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();
- User eUser = PlotSystem.getInstance().getUser(u.player);
- u.player.closeInventory();
+ // Check if the plot is not already claimed, since it may happen that the gui is spammed.
+ PlotStatus plotStatus = plotAPI.getPlotStatus(plot);
+ if (plotStatus == PlotStatus.UNCLAIMED) {
- // 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 plot status can be updated, add the player as plot owner.
+ if (plotHelper.updatePlotStatus(plot, PlotStatus.CLAIMED)) {
- // 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 (plotAPI.createPlotOwner(plot, user.uuid)) {
- // 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() + ");")) {
+ // Add player to the worldguard region.
+ try {
+ if (WorldGuardFunctions.addMember(String.valueOf(plot), player.getUniqueId().toString(), player.getWorld())) {
- // Add player to worldguard region.
- try {
- if (WorldGuardFunctions.addMember(String.valueOf(plot), eUser.uuid, eUser.player.getWorld())) {
+ 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.");
- 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 {
- } 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 01983e7..e7d5429 100644
--- a/src/main/java/net/bteuk/plotsystem/gui/CreatePlotGui.java
+++ b/src/main/java/net/bteuk/plotsystem/gui/CreatePlotGui.java
@@ -1,71 +1,67 @@
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.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 {
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() {
// 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.
@@ -81,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();
@@ -116,9 +110,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..45def70 100644
--- a/src/main/java/net/bteuk/plotsystem/gui/CreateZoneGui.java
+++ b/src/main/java/net/bteuk/plotsystem/gui/CreateZoneGui.java
@@ -1,23 +1,24 @@
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;
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.
- public CreateZoneGui(User user) {
+ // 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(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;
@@ -31,39 +32,32 @@ 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();
+ // Create a zone with the selection created by the user.
+ user.selectionTool.createZone();
});
// 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 ->
-
- {
-
+ event -> {
// 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 +67,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 ->
-
- {
-
+ event -> {
// 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 +97,7 @@ private void createGui() {
// Refresh the gui.
refresh();
- user.player.getOpenInventory().getTopInventory().setContents(getInventory().getContents());
+ this.updatePlayerInventory(user.player);
});
@@ -124,9 +113,7 @@ private void createGui() {
}
public void refresh() {
-
- clearGui();
+ this.clear();
createGui();
-
}
}
diff --git a/src/main/java/net/bteuk/plotsystem/listeners/ClaimEnter.java b/src/main/java/net/bteuk/plotsystem/listeners/ClaimEnter.java
index 9ef960d..2b46431 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,20 +191,16 @@ 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.")));
}
}
} 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.isPlotOwner(u.inPlot, u.uuid) || plotAPI.isPlotMember(u.inPlot, u.uuid)) {
+ plotAPI.setPlotLastEnter(u.inPlot, u.uuid);
}
}
}
@@ -231,7 +216,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.isZonePublic(zone)) {
u.player.sendActionBar(
ChatUtils.success("You have entered zone ")
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..7738c4d 100644
--- a/src/main/java/net/bteuk/plotsystem/listeners/JoinServer.java
+++ b/src/main/java/net/bteuk/plotsystem/listeners/JoinServer.java
@@ -1,14 +1,11 @@
package net.bteuk.plotsystem.listeners;
-import net.bteuk.network.sql.GlobalSQL;
-import net.bteuk.network.sql.PlotSQL;
+import net.bteuk.network.api.NetworkAPI;
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 +17,24 @@
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;
+ private final NetworkAPI networkAPI;
+ private final PlotHelper plotHelper;
- public JoinServer(PlotSystem plugin, GlobalSQL globalSQL, PlotSQL plotSQL) {
-
+ public JoinServer(PlotSystem plugin, NetworkAPI networkAPI, PlotHelper plotHelper) {
Bukkit.getServer().getPluginManager().registerEvents(this, plugin);
this.instance = plugin;
- this.globalSQL = globalSQL;
- this.plotSQL = plotSQL;
-
+ this.networkAPI = networkAPI;
+ 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(), networkAPI, plotHelper);
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/listeners/PlayerInteract.java b/src/main/java/net/bteuk/plotsystem/listeners/PlayerInteract.java
index 58ce4f8..f5f9d0e 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,13 @@
public class PlayerInteract implements Listener {
- final PlotSQL plotSQL;
+ private final PlotAPI plotAPI;
- public PlayerInteract(PlotSystem plugin, PlotSQL plotSQL) {
+ public PlayerInteract(PlotSystem instance, PlotAPI plotAPI) {
+ this.plotAPI = plotAPI;
// Register the listener.
- Bukkit.getServer().getPluginManager().registerEvents(this, plugin);
-
- // Set the reference to the plotSQL.
- this.plotSQL = plotSQL;
-
+ Bukkit.getServer().getPluginManager().registerEvents(this, instance);
}
@EventHandler
@@ -60,14 +57,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/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/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/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/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/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/Inactive.java b/src/main/java/net/bteuk/plotsystem/utils/Inactive.java
index a750a5b..d51abf7 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;
@@ -20,45 +18,41 @@
import java.util.ArrayList;
import java.util.List;
+import static net.bteuk.plotsystem.PlotSystem.LOGGER;
+
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,35 +60,33 @@ 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()) {
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) {
// 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");
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;
}
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 +101,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,40 +118,37 @@ 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!");
+ LOGGER.info("Plot " + plot + " removed due to inactivity!");
});
}
}
- 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 +159,69 @@ public static void closeExpiredZones() {
for (int zone : expiredZones) {
// Get zone location.
- String location = plotSQL.getString("SELECT location FROM zones WHERE id=" + zone + ";");
+ String location = networkAPI.getPlotAPI().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 + "';")) {
-
- // 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;
- }
-
- 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) {
+ 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(), () -> {
+ 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.");
- // 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.
+ 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 89c4a47..7e9516a 100644
--- a/src/main/java/net/bteuk/plotsystem/utils/PlotHelper.java
+++ b/src/main/java/net/bteuk/plotsystem/utils/PlotHelper.java
@@ -1,12 +1,12 @@
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;
+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,20 +27,14 @@
public class PlotHelper {
@Setter
- private static PlotSQL plotSQL;
+ private List holograms = new ArrayList<>();
- @Setter
- private static List holograms = new ArrayList<>();
+ private Map REVIEW_CATEGORY_THRESHOLDS;
- private static Map REVIEW_CATEGORY_THRESHOLDS;
+ private final PlotAPI plotAPI;
- /**
- * Initialise the plot helper by setting the relevant variables.
- *
- * @param plotSQL {@link PlotSQL}
- */
- public static void init(PlotSQL plotSQL) {
- setPlotSQL(plotSQL);
+ public PlotHelper(PlotAPI plotAPI) {
+ this.plotAPI = plotAPI;
}
/**
@@ -49,8 +43,8 @@ public static void init(PlotSQL plotSQL) {
* @param id the plot id
* @param submittedStatus the submitted status
*/
- public static boolean updateSubmittedStatus(int id, SubmittedStatus submittedStatus) {
- return updatePlotStatus(id, PlotStatus.SUBMITTED, submittedStatus);
+ public void updateSubmittedStatus(int id, SubmittedStatus submittedStatus) {
+ updatePlotStatus(id, PlotStatus.SUBMITTED, submittedStatus);
}
/**
@@ -59,7 +53,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,14 +68,14 @@ 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 + ";");
+ 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.getDatabaseValue());
hasChanged = true;
}
// Delay the hologram update until the plot has been completely updated.
@@ -104,23 +98,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 +127,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/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/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 08cdb46..ba0bca0 100644
--- a/src/main/java/net/bteuk/plotsystem/utils/SelectionTool.java
+++ b/src/main/java/net/bteuk/plotsystem/utils/SelectionTool.java
@@ -1,9 +1,8 @@
package net.bteuk.plotsystem.utils;
import com.sk89q.worldedit.math.BlockVector2;
+import net.bteuk.network.api.NetworkAPI;
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 +15,7 @@
import org.bukkit.inventory.PlayerInventory;
import java.util.ArrayList;
+import java.util.Objects;
public class SelectionTool extends WGCreatePlot {
@@ -27,19 +27,19 @@ 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;
+
// 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 +47,19 @@ 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, NetworkAPI networkAPI, PlotHelper plotHelper) {
+ super(networkAPI, plotHelper);
this.u = u;
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 +73,7 @@ public void clear() {
difficulty = 1;
hours = 2;
- is_public = false;
+ isPublic = false;
// Remove outline blocks based on the previous selection.
clearOutlines();
@@ -214,11 +211,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,25 +247,25 @@ 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 = plotAPI.getXTransform(location);
+ int zTransform = plotAPI.getZTransform(location);
- // Store plot bounds.
+ // 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() + ");");
+ plotAPI.createPlotCorner(plotID, i, (point.x() - xTransform), (point.z() - zTransform));
i++;
-
}
// Send feedback.
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));
@@ -286,32 +283,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.createZoneOwner(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..2873ee4 100644
--- a/src/main/java/net/bteuk/plotsystem/utils/User.java
+++ b/src/main/java/net/bteuk/plotsystem/utils/User.java
@@ -2,8 +2,7 @@
import lombok.Getter;
import lombok.Setter;
-import net.bteuk.network.sql.GlobalSQL;
-import net.bteuk.network.sql.PlotSQL;
+import net.bteuk.network.api.NetworkAPI;
import net.bteuk.plotsystem.PlotSystem;
import net.bteuk.plotsystem.gui.ClaimGui;
import net.bteuk.plotsystem.gui.CreatePlotGui;
@@ -23,8 +22,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 +43,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, NetworkAPI networkAPI, PlotHelper plotHelper) {
// Set player, uuid and name variable.
this.player = player;
@@ -57,12 +51,12 @@ 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, 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/Utils.java b/src/main/java/net/bteuk/plotsystem/utils/Utils.java
new file mode 100644
index 0000000..b520bb3
--- /dev/null
+++ b/src/main/java/net/bteuk/plotsystem/utils/Utils.java
@@ -0,0 +1,57 @@
+package net.bteuk.plotsystem.utils;
+
+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;
+
+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);
+ }
+
+ 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/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/Multiverse.java b/src/main/java/net/bteuk/plotsystem/utils/plugins/Multiverse.java
index a5ce15e..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,25 +1,18 @@
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;
-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;
import org.bukkit.GameRule;
import org.bukkit.World;
import org.bukkit.WorldType;
+import org.mvplugins.multiverse.core.MultiverseCoreApi;
+import org.mvplugins.multiverse.core.world.WorldManager;
+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;
@@ -27,32 +20,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.addWorld(
- name,
- World.Environment.NORMAL,
- null,
- WorldType.FLAT,
- false,
- "VoidGen:{biome:PLAINS}"
- );
+ 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);
+ });
- 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);
@@ -72,56 +59,16 @@ public static boolean createVoidWorld(String name) {
// Disable random tick.
world.setGameRule(GameRule.RANDOM_TICK_SPEED, 0);
- // 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);
+ // 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);
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);
@@ -131,42 +78,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();
+ WorldManager worldManager = core.getWorldManager();
- MultiverseWorld world = worldManager.getMVWorld(name);
-
- 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 589e7de..8e8f46a 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,11 @@
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.NetworkAPI;
+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,36 +20,43 @@
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 {
+ private final NetworkAPI networkAPI;
+
+ 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(NetworkAPI networkAPI, PlotHelper plotHelper) {
+ this.networkAPI = networkAPI;
+ this.plotAPI = networkAPI.getPlotAPI();
+ this.plotHelper = plotHelper;
+ this.coordinateAPI = networkAPI.getCoordinateAPI();
}
// 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.
+ // 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);
@@ -63,20 +72,20 @@ 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.
+ // 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);
@@ -119,10 +126,10 @@ 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;
}
+
+ /**
+ * 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);
+ }
+ }
}
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: