warps = new ArrayList<>();
if (rs != null) {
@@ -415,7 +443,7 @@ public class dataManager {
try {
conn = getConnection();
- ps = conn.prepareStatement("SELECT * FROM huskhomes_warp_data WHERE `name`=?;");
+ ps = conn.prepareStatement("SELECT * FROM " + Main.settings.getWarpsDataTable() + " WHERE `name`=?;");
ps.setString(1, name);
rs = ps.executeQuery();
if (rs != null) {
@@ -455,13 +483,13 @@ public class dataManager {
try {
conn = getConnection();
- ps = conn.prepareStatement("SELECT * FROM huskhomes_home_data WHERE `player_id`=? AND `name`=?;");
+ ps = conn.prepareStatement("SELECT * FROM " + Main.settings.getHomesDataTable() + " WHERE `player_id`=? AND `name`=?;");
ps.setInt(1, ownerID);
ps.setString(2, homeName);
rs = ps.executeQuery();
if (rs != null) {
int locationID = rs.getInt("location_id");
- sqliteDatabase.deleteTeleportationPoint(locationID);
+ database.deleteTeleportationPoint(locationID);
} else {
Bukkit.getLogger().severe("Failed to delete home teleportation location");
}
@@ -486,12 +514,12 @@ public class dataManager {
try {
conn = getConnection();
- ps = conn.prepareStatement("SELECT * FROM huskhomes_warp_data WHERE `name`=?;");
+ ps = conn.prepareStatement("SELECT * FROM " + Main.settings.getWarpsDataTable() + " WHERE `name`=?;");
ps.setString(1, warpName);
rs = ps.executeQuery();
if (rs != null) {
int locationID = rs.getInt("location_id");
- sqliteDatabase.deleteTeleportationPoint(locationID);
+ database.deleteTeleportationPoint(locationID);
} else {
Bukkit.getLogger().severe("Failed to delete warp teleportation location");
}
@@ -511,64 +539,36 @@ public class dataManager {
public static void updateHomePrivacy(String ownerName, String homeName, boolean isPublic) {
Integer playerID = getPlayerId(ownerName);
- if (Main.settings.getStorageType().equalsIgnoreCase("mysql")) {
-
- } else {
- sqliteDatabase.setHomePrivacy(homeName, playerID, isPublic);
- }
+ database.setHomePrivacy(homeName, playerID, isPublic);
}
public static void updateHomeName(String ownerName, String homeName, String newName) {
Integer playerID = getPlayerId(ownerName);
- if (Main.settings.getStorageType().equalsIgnoreCase("mysql")) {
-
- } else {
- sqliteDatabase.setHomeName(homeName, playerID, newName);
- }
+ database.setHomeName(homeName, playerID, newName);
}
public static void updateHomeDescription(String ownerName, String homeName, String newDescription) {
Integer playerID = getPlayerId(ownerName);
- if (Main.settings.getStorageType().equalsIgnoreCase("mysql")) {
-
- } else {
- sqliteDatabase.setHomeDescription(homeName, playerID, newDescription);
- }
+ database.setHomeDescription(homeName, playerID, newDescription);
}
public static void updateHomeLocation(String ownerName, String homeName, Location newLocation) {
Integer playerID = getPlayerId(ownerName);
deleteHomeTeleportLocation(playerID, homeName);
- if (Main.settings.getStorageType().equalsIgnoreCase("mysql")) {
-
- } else {
- sqliteDatabase.setHomeTeleportPoint(homeName, playerID, new TeleportationPoint(newLocation, Main.settings.getServerID()));
- }
+ database.setHomeTeleportPoint(homeName, playerID, new TeleportationPoint(newLocation, Main.settings.getServerID()));
}
public static void updateWarpName(String warpName, String newName) {
- if (Main.settings.getStorageType().equalsIgnoreCase("mysql")) {
-
- } else {
- sqliteDatabase.setWarpName(warpName, newName);
- }
+ database.setWarpName(warpName, newName);
}
public static void updateWarpDescription(String warpName, String newDescription) {
- if (Main.settings.getStorageType().equalsIgnoreCase("mysql")) {
-
- } else {
- sqliteDatabase.setWarpDescription(warpName, newDescription);
- }
+ database.setWarpDescription(warpName, newDescription);
}
public static void updateWarpLocation(String warpName, Location newLocation) {
deleteWarpTeleportLocation(warpName);
- if (Main.settings.getStorageType().equalsIgnoreCase("mysql")) {
-
- } else {
- sqliteDatabase.setWarpTeleportPoint(warpName, new TeleportationPoint(newLocation, Main.settings.getServerID()));
- }
+ database.setWarpTeleportPoint(warpName, new TeleportationPoint(newLocation, Main.settings.getServerID()));
}
// Return a home with a given owner username and home name
@@ -580,7 +580,7 @@ public class dataManager {
try {
conn = getConnection();
- ps = conn.prepareStatement("SELECT * FROM huskhomes_home_data WHERE `player_id`=? AND `name`=?;");
+ ps = conn.prepareStatement("SELECT * FROM " + Main.settings.getHomesDataTable() + " WHERE `player_id`=? AND `name`=?;");
ps.setInt(1, playerID);
ps.setString(2, homeName);
rs = ps.executeQuery();
@@ -624,7 +624,7 @@ public class dataManager {
try {
conn = getConnection();
- ps = conn.prepareStatement("SELECT * FROM huskhomes_warp_data WHERE `name`=?;");
+ ps = conn.prepareStatement("SELECT * FROM " + Main.settings.getWarpsDataTable() + " WHERE `name`=?;");
ps.setString(1, warpName);
rs = ps.executeQuery();
if (rs != null) {
@@ -665,7 +665,7 @@ public class dataManager {
try {
conn = getConnection();
- ps = conn.prepareStatement("SELECT * FROM huskhomes_home_data WHERE `player_id`=? AND `name`=?;");
+ ps = conn.prepareStatement("SELECT * FROM " + Main.settings.getHomesDataTable() + " WHERE `player_id`=? AND `name`=?;");
ps.setInt(1, playerID);
ps.setString(2, homeName);
rs = ps.executeQuery();
@@ -698,7 +698,7 @@ public class dataManager {
try {
conn = getConnection();
- ps = conn.prepareStatement("SELECT * FROM huskhomes_player_data WHERE `user_uuid`=?;");
+ ps = conn.prepareStatement("SELECT * FROM " + Main.settings.getPlayerDataTable() + " WHERE `user_uuid`=?;");
ps.setString(1, playerUUID);
rs = ps.executeQuery();
if (rs != null) {
@@ -729,7 +729,7 @@ public class dataManager {
try {
conn = getConnection();
- ps = conn.prepareStatement("SELECT * FROM huskhomes_location_data WHERE `location_id`=?;");
+ ps = conn.prepareStatement("SELECT * FROM " + Main.settings.getLocationsDataTable() + " WHERE `location_id`=?;");
ps.setInt(1, locationID);
rs = ps.executeQuery();
if (rs.next()) {
@@ -779,11 +779,7 @@ public class dataManager {
Integer playerID = getPlayerId(p.getName());
if (playerID != null) {
deletePlayerLastPosition(p);
- if (Main.settings.getStorageType().equalsIgnoreCase("mySQL")) {
-
- } else {
- sqliteDatabase.setTeleportationLastOrDest(playerID, point, "last");
- }
+ database.setTeleportationLastOrDest(playerID, point, "last");
} else {
Bukkit.getLogger().warning("Failed to update player last position records for " + p.getName());
}
@@ -794,11 +790,7 @@ public class dataManager {
Integer playerID = getPlayerId(playerName);
if (playerID != null) {
deletePlayerDestination(playerName);
- if (Main.settings.getStorageType().equalsIgnoreCase("mySQL")) {
-
- } else {
- sqliteDatabase.setTeleportationLastOrDest(playerID, point, "dest");
- }
+ database.setTeleportationLastOrDest(playerID, point, "dest");
} else {
Bukkit.getLogger().warning("Failed to update player destination records for " + playerName);
}
@@ -809,11 +801,7 @@ public class dataManager {
Integer playerID = getPlayerId(p.getName());
if (playerID != null) {
deletePlayerDestination(p);
- if (Main.settings.getStorageType().equalsIgnoreCase("mySQL")) {
-
- } else {
- sqliteDatabase.setTeleportationLastOrDest(playerID, point, "dest");
- }
+ database.setTeleportationLastOrDest(playerID, point, "dest");
} else {
Bukkit.getLogger().warning("Failed to update player destination records for " + p.getName());
}
@@ -823,65 +811,58 @@ public class dataManager {
Integer playerID = getPlayerId(p.getName());
if (playerID != null) {
deletePlayerDestination(p);
- if (Main.settings.getStorageType().equalsIgnoreCase("mySQL")) {
-
- } else {
- sqliteDatabase.setPlayerTeleporting(playerID, value);
- }
+ database.setPlayerTeleporting(playerID, value);
} else {
Bukkit.getLogger().warning("Failed to update player destination records for " + p.getName());
}
}
+ public static void clearPlayerDestination(String playerName) {
+ Integer playerID = getPlayerId(playerName);
+ if (playerID != null) {
+ deletePlayerDestination(playerName);
+ database.clearPlayerDestination(playerID);
+ }
+ }
+
+ public static void updateRtpCooldown(Player p) {
+ Integer playerID = getPlayerId(p.getName());
+ if (playerID != null) {
+ long currentTime = Instant.now().getEpochSecond();
+ int newCooldownTime = (int) currentTime + (60 * Main.settings.getRtpCooldown());
+ database.setRtpCooldown(playerID, newCooldownTime);
+ }
+ }
+
public static void deletePlayerDestination(String playerName) {
Integer destinationID = getPlayerInteger(playerName, "dest_location_id");
if (destinationID != null) {
- if (Main.settings.getStorageType().equalsIgnoreCase("mySQL")) {
-
- } else {
- sqliteDatabase.deleteTeleportationPoint(destinationID);
- }
+ database.deleteTeleportationPoint(destinationID);
}
}
public static void deletePlayerDestination(Player p) {
Integer destinationID = getPlayerInteger(p, "dest_location_id");
if (destinationID != null) {
- if (Main.settings.getStorageType().equalsIgnoreCase("mySQL")) {
-
- } else {
- sqliteDatabase.deleteTeleportationPoint(destinationID);
- }
+ database.deleteTeleportationPoint(destinationID);
}
}
public static void deletePlayerLastPosition(Player p) {
Integer lastPositionID = getPlayerInteger(p, "last_location_id");
if (lastPositionID != null) {
- if (Main.settings.getStorageType().equalsIgnoreCase("mySQL")) {
-
- } else {
- sqliteDatabase.deleteTeleportationPoint(lastPositionID);
- }
+ database.deleteTeleportationPoint(lastPositionID);
}
}
public static void addWarp(Warp warp) {
- if (Main.settings.getStorageType().equalsIgnoreCase("mySQL")) {
-
- } else {
- sqliteDatabase.addWarp(warp);
- }
+ database.addWarp(warp);
}
public static void addHome(Home home, Player p) {
Integer playerID = getPlayerId(p.getName());
if (playerID != null) {
- if (Main.settings.getStorageType().equalsIgnoreCase("mySQL")) {
-
- } else {
- sqliteDatabase.addHome(home, playerID);
- }
+ database.addHome(home, playerID);
} else {
Bukkit.getLogger().warning("Failed to add a home for " + p.getName());
}
@@ -891,41 +872,29 @@ public class dataManager {
Integer playerID = getPlayerId(p.getName());
if (playerID != null) {
deleteHomeTeleportLocation(playerID, homeName);
- if (Main.settings.getStorageType().equalsIgnoreCase("mySQL")) {
-
- } else {
- sqliteDatabase.deleteHome(homeName, playerID);
- }
+ database.deleteHome(homeName, playerID);
} else {
- Bukkit.getLogger().warning("PlayeR ID returned null when deleting a home");
+ Bukkit.getLogger().warning("Player ID returned null when deleting a home");
}
}
public static void deleteWarp(String warpName) {
deleteWarpTeleportLocation(warpName);
- if (Main.settings.getStorageType().equalsIgnoreCase("mySQL")) {
-
- } else {
- sqliteDatabase.deleteWarp(warpName);
- }
+ database.deleteWarp(warpName);
}
public static void setupStorage(String storageType) {
- if (storageType.equalsIgnoreCase("sqlite")) {
- initializeSQLite();
- } else if (storageType.equalsIgnoreCase("mysql")) {
- initializeMySQL();
- } else {
- Bukkit.getLogger().warning("Invalid storage method set in config.yml; defaulting to SQLite");
- initializeSQLite();
- }
+ initializeDatabase();
}
public static void createPlayer(Player p) {
- if (Main.settings.getStorageType().equalsIgnoreCase("mySQL")) {
+ database.addPlayer(p);
+ }
- } else {
- sqliteDatabase.addPlayer(p);
+ public static void checkPlayerNameChange(Player p) {
+ Integer playerID = getPlayerId(p.getUniqueId());
+ if (!getPlayerUsername(playerID).equals(p.getName())) {
+ database.updatePlayerUsername(playerID, p.getName());
}
}
}
\ No newline at end of file
diff --git a/src/main/java/me/william278/huskhomes2/editingHandler.java b/src/main/java/me/william278/huskhomes2/editingHandler.java
index 881aa83e..47c919b3 100644
--- a/src/main/java/me/william278/huskhomes2/editingHandler.java
+++ b/src/main/java/me/william278/huskhomes2/editingHandler.java
@@ -12,23 +12,23 @@ import org.bukkit.entity.Player;
public class editingHandler {
- private static TextComponent optionButton(String buttonText, ChatColor color, ClickEvent.Action actionType, String command, String hoverMessage, net.md_5.bungee.api.ChatColor hoverMessageColor, Boolean hoverMessageItalic) {
+ private static TextComponent optionButton(String buttonText, ChatColor color, ClickEvent.Action actionType, String command, String hoverMessage) {
TextComponent button = new TextComponent(buttonText);
button.setColor(color);
button.setClickEvent(new ClickEvent(actionType, (command)));
- button.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new Text(new ComponentBuilder(hoverMessage).color(hoverMessageColor).italic(hoverMessageItalic).create())));
+ button.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new Text(new ComponentBuilder(hoverMessage).color(ChatColor.GRAY).italic(true).create())));
return button;
}
private static ComponentBuilder editWarpOptions(Warp warp) {
ComponentBuilder options = new ComponentBuilder();
- options.append(optionButton("[Teleport] ", net.md_5.bungee.api.ChatColor.GREEN, ClickEvent.Action.RUN_COMMAND, "/warp " + warp.getName(), "Teleport to this warp", net.md_5.bungee.api.ChatColor.GRAY, true));
- options.append(optionButton("[Delete] ", net.md_5.bungee.api.ChatColor.RED, ClickEvent.Action.RUN_COMMAND, "/delwarp " + warp.getName(), "Delete this warp", net.md_5.bungee.api.ChatColor.GRAY, true));
- options.append(optionButton("[Relocate]\n", net.md_5.bungee.api.ChatColor.BLUE, ClickEvent.Action.RUN_COMMAND, "/editwarp " + warp.getName() + " location", "Update this warp's location", net.md_5.bungee.api.ChatColor.GRAY, true));
- options.append(optionButton("[Rename] ", net.md_5.bungee.api.ChatColor.YELLOW, ClickEvent.Action.SUGGEST_COMMAND, "/editwarp " + warp.getName() + " rename ", "Change the name of this warp", net.md_5.bungee.api.ChatColor.GRAY, true));
- options.append(optionButton("[Edit Description] ", net.md_5.bungee.api.ChatColor.GOLD, ClickEvent.Action.SUGGEST_COMMAND, "/editwarp " + warp.getName() + " description ", "Update this warp's description", net.md_5.bungee.api.ChatColor.GRAY, true));
+ options.append(optionButton("[Teleport] ", net.md_5.bungee.api.ChatColor.GREEN, ClickEvent.Action.RUN_COMMAND, "/warp " + warp.getName(), "Teleport to this warp"));
+ options.append(optionButton("[Delete] ", net.md_5.bungee.api.ChatColor.RED, ClickEvent.Action.RUN_COMMAND, "/delwarp " + warp.getName(), "Delete this warp"));
+ options.append(optionButton("[Relocate]\n", net.md_5.bungee.api.ChatColor.BLUE, ClickEvent.Action.RUN_COMMAND, "/editwarp " + warp.getName() + " location", "Update this warp's location"));
+ options.append(optionButton("[Rename] ", net.md_5.bungee.api.ChatColor.YELLOW, ClickEvent.Action.SUGGEST_COMMAND, "/editwarp " + warp.getName() + " rename ", "Change the name of this warp"));
+ options.append(optionButton("[Edit Description] ", net.md_5.bungee.api.ChatColor.GOLD, ClickEvent.Action.SUGGEST_COMMAND, "/editwarp " + warp.getName() + " description ", "Update this warp's description"));
return options;
}
@@ -36,17 +36,17 @@ public class editingHandler {
private static ComponentBuilder editHomeOptions(Player p, Home home) {
ComponentBuilder options = new ComponentBuilder();
- options.append(optionButton("[Teleport] ", net.md_5.bungee.api.ChatColor.GREEN, ClickEvent.Action.RUN_COMMAND, "/home " + home.getName(), "Teleport to your home", net.md_5.bungee.api.ChatColor.GRAY, true));
- options.append(optionButton("[Delete] ", net.md_5.bungee.api.ChatColor.RED, ClickEvent.Action.RUN_COMMAND, "/delhome " + home.getName(), "Delete your home", net.md_5.bungee.api.ChatColor.GRAY, true));
- options.append(optionButton("[Relocate]\n", net.md_5.bungee.api.ChatColor.BLUE, ClickEvent.Action.RUN_COMMAND, "/edithome " + home.getName() + " location", "Update your home's location", net.md_5.bungee.api.ChatColor.GRAY, true));
- options.append(optionButton("[Rename] ", net.md_5.bungee.api.ChatColor.YELLOW, ClickEvent.Action.SUGGEST_COMMAND, "/edithome " + home.getName() + " rename ", "Change the name of your home", net.md_5.bungee.api.ChatColor.GRAY, true));
- options.append(optionButton("[Edit Description] ", net.md_5.bungee.api.ChatColor.GOLD, ClickEvent.Action.SUGGEST_COMMAND, "/edithome " + home.getName() + " description ", "Update the description of your home", net.md_5.bungee.api.ChatColor.GRAY, true));
+ options.append(optionButton("[Teleport] ", net.md_5.bungee.api.ChatColor.GREEN, ClickEvent.Action.RUN_COMMAND, "/home " + home.getName(), "Teleport to your home"));
+ options.append(optionButton("[Delete] ", net.md_5.bungee.api.ChatColor.RED, ClickEvent.Action.RUN_COMMAND, "/delhome " + home.getName(), "Delete your home"));
+ options.append(optionButton("[Relocate]\n", net.md_5.bungee.api.ChatColor.BLUE, ClickEvent.Action.RUN_COMMAND, "/edithome " + home.getName() + " location", "Update your home's location"));
+ options.append(optionButton("[Rename] ", net.md_5.bungee.api.ChatColor.YELLOW, ClickEvent.Action.SUGGEST_COMMAND, "/edithome " + home.getName() + " rename ", "Change the name of your home"));
+ options.append(optionButton("[Edit Description] ", net.md_5.bungee.api.ChatColor.GOLD, ClickEvent.Action.SUGGEST_COMMAND, "/edithome " + home.getName() + " description ", "Update the description of your home"));
if (p.hasPermission("huskhomes.edithome.public")) {
if (home.isPublic()) {
- options.append(optionButton("[Make Public] ", net.md_5.bungee.api.ChatColor.DARK_GREEN, ClickEvent.Action.RUN_COMMAND, "/edithome " + home.getName() + " public", "Open your home to the public", net.md_5.bungee.api.ChatColor.GRAY, true));
+ options.append(optionButton("[Make Public] ", net.md_5.bungee.api.ChatColor.DARK_GREEN, ClickEvent.Action.RUN_COMMAND, "/edithome " + home.getName() + " public", "Open your home to the public"));
} else {
- options.append(optionButton("[Make Private] ", net.md_5.bungee.api.ChatColor.DARK_RED, ClickEvent.Action.RUN_COMMAND, "/edithome " + home.getName() + " private", "Make your home private", net.md_5.bungee.api.ChatColor.GRAY, true));
+ options.append(optionButton("[Make Private] ", net.md_5.bungee.api.ChatColor.DARK_RED, ClickEvent.Action.RUN_COMMAND, "/edithome " + home.getName() + " private", "Make your home private"));
}
}
return options;
@@ -55,14 +55,14 @@ public class editingHandler {
public static void showEditHomeOptions(Player p, Home home) {
p.sendMessage("");
messageManager.sendMessage(p, "edit_home_title", home.getName());
- messageManager.sendMessage(p, "edit_home_description", home.getDescription());
- messageManager.sendMessage(p, "edit_home_location",
- Double.toString(home.getX()),
- Double.toString(home.getY()),
- Double.toString(home.getZ()));
- messageManager.sendMessage(p, "edit_home_world", home.getWorldName());
+ messageManager.sendMessage(p, "edit_description", home.getDescription());
+ messageManager.sendMessage(p, "edit_location",
+ Integer.toString((int) home.getX()),
+ Integer.toString((int) home.getY()),
+ Integer.toString((int) home.getZ()));
+ messageManager.sendMessage(p, "edit_world", home.getWorldName());
if (Main.settings.doBungee()) {
- messageManager.sendMessage(p, "edit_home_server", home.getServer());
+ messageManager.sendMessage(p, "edit_server", home.getServer());
}
if (home.isPublic()) {
messageManager.sendMessage(p, "edit_home_privacy_public");
@@ -77,14 +77,14 @@ public class editingHandler {
public static void showEditWarpOptions(Player p, Warp warp) {
p.sendMessage("");
messageManager.sendMessage(p, "edit_warp_title", warp.getName());
- messageManager.sendMessage(p, "edit_home_description", warp.getDescription());
- messageManager.sendMessage(p, "edit_home_location",
- Double.toString(warp.getX()),
- Double.toString(warp.getY()),
- Double.toString(warp.getZ()));
- messageManager.sendMessage(p, "edit_home_world", warp.getWorldName());
+ messageManager.sendMessage(p, "edit_description", warp.getDescription());
+ messageManager.sendMessage(p, "edit_location",
+ Integer.toString((int) warp.getX()),
+ Integer.toString((int) warp.getY()),
+ Integer.toString((int) warp.getZ()));
+ messageManager.sendMessage(p, "edit_world", warp.getWorldName());
if (Main.settings.doBungee()) {
- messageManager.sendMessage(p, "edit_home_server", warp.getServer());
+ messageManager.sendMessage(p, "edit_server", warp.getServer());
}
p.sendMessage("");
p.spigot().sendMessage(editWarpOptions(warp).create());
diff --git a/src/main/java/me/william278/huskhomes2/listHandler.java b/src/main/java/me/william278/huskhomes2/listHandler.java
index d419837c..b79b4101 100644
--- a/src/main/java/me/william278/huskhomes2/listHandler.java
+++ b/src/main/java/me/william278/huskhomes2/listHandler.java
@@ -164,7 +164,7 @@ public class listHandler {
}
player.sendMessage("");
- messageManager.sendMessage(player, "warp_list_page_top", player.getName(), Integer.toString(warpsLowerBound + 1), Integer.toString(warpsUpperBound), Integer.toString(warps.size()));
+ messageManager.sendMessage(player, "warp_list_page_top", Integer.toString(warpsLowerBound + 1), Integer.toString(warpsUpperBound), Integer.toString(warps.size()));
for (int i = warpsLowerBound; i < warpsUpperBound; i++) {
try {
diff --git a/src/main/java/me/william278/huskhomes2/metricsManager.java b/src/main/java/me/william278/huskhomes2/metricsManager.java
new file mode 100644
index 00000000..9140843f
--- /dev/null
+++ b/src/main/java/me/william278/huskhomes2/metricsManager.java
@@ -0,0 +1,367 @@
+package me.william278.huskhomes2;
+
+import com.google.gson.JsonArray;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParser;
+import org.bukkit.Bukkit;
+import org.bukkit.configuration.file.YamlConfiguration;
+import org.bukkit.entity.Player;
+import org.bukkit.plugin.Plugin;
+import org.bukkit.plugin.RegisteredServiceProvider;
+import org.bukkit.plugin.ServicePriority;
+
+import javax.net.ssl.HttpsURLConnection;
+import java.io.*;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.net.URL;
+import java.nio.charset.StandardCharsets;
+import java.util.Collection;
+import java.util.Timer;
+import java.util.TimerTask;
+import java.util.UUID;
+import java.util.logging.Level;
+import java.util.zip.GZIPOutputStream;
+
+/**
+ * bStats collects some data for plugin authors.
+ *
+ * Check out https://bStats.org/ to learn more about bStats!
+ */
+@SuppressWarnings({"WeakerAccess", "unused"})
+public class metricsManager {
+
+ static {
+ // You can use the property to disable the check in your test environment
+ if (System.getProperty("bstats.relocatecheck") == null || !System.getProperty("bstats.relocatecheck").equals("false")) {
+ // Maven's Relocate is clever and changes strings, too. So we have to use this little "trick" ... :D
+ final String defaultPackage = new String(
+ new byte[]{'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's', '.', 'b', 'u', 'k', 'k', 'i', 't'});
+ final String examplePackage = new String(new byte[]{'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'});
+ // We want to make sure nobody just copy & pastes the example and use the wrong package names
+ if (metricsManager.class.getPackage().getName().equals(defaultPackage) || metricsManager.class.getPackage().getName().equals(examplePackage)) {
+ throw new IllegalStateException("bStats Metrics class has not been relocated correctly!");
+ }
+ }
+ }
+
+ // The version of this bStats class
+ public static final int B_STATS_VERSION = 1;
+
+ // The url to which the data is sent
+ private static final String URL = "https://bStats.org/submitData/bukkit";
+
+ // Is bStats enabled on this server?
+ private final boolean enabled;
+
+ // Should failed requests be logged?
+ private static boolean logFailedRequests;
+
+ // Should the sent data be logged?
+ private static boolean logSentData;
+
+ // Should the response text be logged?
+ private static boolean logResponseStatusText;
+
+ // The uuid of the server
+ private static String serverUUID;
+
+ // The plugin
+ private final Plugin plugin;
+
+ // The plugin id
+ private final int pluginId;
+
+ /**
+ * Class constructor.
+ *
+ * @param plugin The plugin which stats should be submitted.
+ * @param pluginId The id of the plugin.
+ * It can be found at What is my plugin id?
+ */
+ public metricsManager(Plugin plugin, int pluginId) {
+ if (plugin == null) {
+ throw new IllegalArgumentException("Plugin cannot be null!");
+ }
+ this.plugin = plugin;
+ this.pluginId = pluginId;
+
+ // Get the config file
+ File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats");
+ File configFile = new File(bStatsFolder, "config.yml");
+ YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile);
+
+ // Check if the config file exists
+ if (!config.isSet("serverUuid")) {
+
+ // Add default values
+ config.addDefault("enabled", true);
+ // Every server gets it's unique random id.
+ config.addDefault("serverUuid", UUID.randomUUID().toString());
+ // Should failed request be logged?
+ config.addDefault("logFailedRequests", false);
+ // Should the sent data be logged?
+ config.addDefault("logSentData", false);
+ // Should the response text be logged?
+ config.addDefault("logResponseStatusText", false);
+
+ // Inform the server owners about bStats
+ config.options().header(
+ "bStats collects some data for plugin authors like how many servers are using their plugins.\n" +
+ "To honor their work, you should not disable it.\n" +
+ "This has nearly no effect on the server performance!\n" +
+ "Check out https://bStats.org/ to learn more :)"
+ ).copyDefaults(true);
+ try {
+ config.save(configFile);
+ } catch (IOException ignored) { }
+ }
+
+ // Load the data
+ serverUUID = config.getString("serverUuid");
+ logFailedRequests = config.getBoolean("logFailedRequests", false);
+ enabled = config.getBoolean("enabled", true);
+ logSentData = config.getBoolean("logSentData", false);
+ logResponseStatusText = config.getBoolean("logResponseStatusText", false);
+ if (enabled) {
+ boolean found = false;
+ // Search for all other bStats Metrics classes to see if we are the first one
+ for (Class> service : Bukkit.getServicesManager().getKnownServices()) {
+ try {
+ service.getField("B_STATS_VERSION"); // Our identifier :)
+ found = true; // We aren't the first
+ break;
+ } catch (NoSuchFieldException ignored) { }
+ }
+ // Register our service
+ Bukkit.getServicesManager().register(metricsManager.class, this, plugin, ServicePriority.Normal);
+ if (!found) {
+ // We are the first!
+ startSubmitting();
+ }
+ }
+ }
+
+ /**
+ * Checks if bStats is enabled.
+ *
+ * @return Whether bStats is enabled or not.
+ */
+ public boolean isEnabled() {
+ return enabled;
+ }
+
+ /**
+ * Starts the Scheduler which submits our data every 30 minutes.
+ */
+ private void startSubmitting() {
+ final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags
+ timer.scheduleAtFixedRate(new TimerTask() {
+ @Override
+ public void run() {
+ if (!plugin.isEnabled()) { // Plugin was disabled
+ timer.cancel();
+ return;
+ }
+ // Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler
+ // Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;)
+ Bukkit.getScheduler().runTask(plugin, () -> submitData());
+ }
+ }, 1000 * 60 * 5, 1000 * 60 * 30);
+ // Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start
+ // WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted!
+ // WARNING: Just don't do it!
+ }
+
+ /**
+ * Gets the plugin specific data.
+ * This method is called using Reflection.
+ *
+ * @return The plugin specific data.
+ */
+ public JsonObject getPluginData() {
+ JsonObject data = new JsonObject();
+
+ String pluginName = plugin.getDescription().getName();
+ String pluginVersion = plugin.getDescription().getVersion();
+
+ data.addProperty("pluginName", pluginName); // Append the name of the plugin
+ data.addProperty("id", pluginId); // Append the id of the plugin
+ data.addProperty("pluginVersion", pluginVersion); // Append the version of the plugin
+ data.add("customCharts", new JsonArray());
+
+ return data;
+ }
+
+ /**
+ * Gets the server specific data.
+ *
+ * @return The server specific data.
+ */
+ private JsonObject getServerData() {
+ // Minecraft specific data
+ int playerAmount;
+ try {
+ // Around MC 1.8 the return type was changed to a collection from an array,
+ // This fixes java.lang.NoSuchMethodError: org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection;
+ Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers");
+ playerAmount = onlinePlayersMethod.getReturnType().equals(Collection.class)
+ ? ((Collection>) onlinePlayersMethod.invoke(Bukkit.getServer())).size()
+ : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length;
+ } catch (Exception e) {
+ playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed
+ }
+ int onlineMode = Bukkit.getOnlineMode() ? 1 : 0;
+ String bukkitVersion = Bukkit.getVersion();
+ String bukkitName = Bukkit.getName();
+
+ // OS/Java specific data
+ String javaVersion = System.getProperty("java.version");
+ String osName = System.getProperty("os.name");
+ String osArch = System.getProperty("os.arch");
+ String osVersion = System.getProperty("os.version");
+ int coreCount = Runtime.getRuntime().availableProcessors();
+
+ JsonObject data = new JsonObject();
+
+ data.addProperty("serverUUID", serverUUID);
+
+ data.addProperty("playerAmount", playerAmount);
+ data.addProperty("onlineMode", onlineMode);
+ data.addProperty("bukkitVersion", bukkitVersion);
+ data.addProperty("bukkitName", bukkitName);
+
+ data.addProperty("javaVersion", javaVersion);
+ data.addProperty("osName", osName);
+ data.addProperty("osArch", osArch);
+ data.addProperty("osVersion", osVersion);
+ data.addProperty("coreCount", coreCount);
+
+ return data;
+ }
+
+ /**
+ * Collects the data and sends it afterwards.
+ */
+ private void submitData() {
+ final JsonObject data = getServerData();
+
+ JsonArray pluginData = new JsonArray();
+ // Search for all other bStats Metrics classes to get their plugin data
+ for (Class> service : Bukkit.getServicesManager().getKnownServices()) {
+ try {
+ service.getField("B_STATS_VERSION"); // Our identifier :)
+
+ for (RegisteredServiceProvider> provider : Bukkit.getServicesManager().getRegistrations(service)) {
+ try {
+ Object plugin = provider.getService().getMethod("getPluginData").invoke(provider.getProvider());
+ if (plugin instanceof JsonObject) {
+ pluginData.add((JsonObject) plugin);
+ } else { // old bstats version compatibility
+ try {
+ Class> jsonObjectJsonSimple = Class.forName("org.json.simple.JSONObject");
+ if (plugin.getClass().isAssignableFrom(jsonObjectJsonSimple)) {
+ Method jsonStringGetter = jsonObjectJsonSimple.getDeclaredMethod("toJSONString");
+ jsonStringGetter.setAccessible(true);
+ String jsonString = (String) jsonStringGetter.invoke(plugin);
+ JsonObject object = new JsonParser().parse(jsonString).getAsJsonObject();
+ pluginData.add(object);
+ }
+ } catch (ClassNotFoundException e) {
+ // minecraft version 1.14+
+ if (logFailedRequests) {
+ this.plugin.getLogger().log(Level.SEVERE, "Encountered unexpected exception ", e);
+ }
+ }
+ }
+ } catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) {
+ }
+ }
+ } catch (NoSuchFieldException ignored) { }
+ }
+
+ data.add("plugins", pluginData);
+
+ // Create a new thread for the connection to the bStats server
+ new Thread(() -> {
+ try {
+ // Send the data
+ sendData(plugin, data);
+ } catch (Exception e) {
+ // Something went wrong! :(
+ if (logFailedRequests) {
+ plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e);
+ }
+ }
+ }).start();
+ }
+
+ /**
+ * Sends the data to the bStats server.
+ *
+ * @param plugin Any plugin. It's just used to get a logger instance.
+ * @param data The data to send.
+ * @throws Exception If the request failed.
+ */
+ private static void sendData(Plugin plugin, JsonObject data) throws Exception {
+ if (data == null) {
+ throw new IllegalArgumentException("Data cannot be null!");
+ }
+ if (Bukkit.isPrimaryThread()) {
+ throw new IllegalAccessException("This method must not be called from the main thread!");
+ }
+ if (logSentData) {
+ plugin.getLogger().info("Sending data to bStats: " + data);
+ }
+ HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();
+
+ // Compress the data to save bandwidth
+ byte[] compressedData = compress(data.toString());
+
+ // Add headers
+ connection.setRequestMethod("POST");
+ connection.addRequestProperty("Accept", "application/json");
+ connection.addRequestProperty("Connection", "close");
+ connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
+ connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
+ connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
+ connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);
+
+ // Send data
+ connection.setDoOutput(true);
+ try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) {
+ outputStream.write(compressedData);
+ }
+
+ StringBuilder builder = new StringBuilder();
+ try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
+ String line;
+ while ((line = bufferedReader.readLine()) != null) {
+ builder.append(line);
+ }
+ }
+
+ if (logResponseStatusText) {
+ plugin.getLogger().info("Sent data to bStats and received response: " + builder);
+ }
+ }
+
+ /**
+ * Gzips the given String.
+ *
+ * @param str The string to gzip.
+ * @return The gzipped String.
+ * @throws IOException If the compression failed.
+ */
+ private static byte[] compress(final String str) throws IOException {
+ if (str == null) {
+ return null;
+ }
+ ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
+ try(GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) {
+ gzip.write(str.getBytes(StandardCharsets.UTF_8));
+ }
+ return outputStream.toByteArray();
+ }
+
+}
\ No newline at end of file
diff --git a/src/main/java/me/william278/huskhomes2/runEverySecond.java b/src/main/java/me/william278/huskhomes2/runEverySecond.java
index cb4c3a75..de9131e7 100644
--- a/src/main/java/me/william278/huskhomes2/runEverySecond.java
+++ b/src/main/java/me/william278/huskhomes2/runEverySecond.java
@@ -1,6 +1,6 @@
package me.william278.huskhomes2;
-import me.william278.huskhomes2.Objects.TeleportationPoint;
+import me.william278.huskhomes2.Objects.RandomPoint;
import me.william278.huskhomes2.Objects.TimedTeleport;
import org.bukkit.Bukkit;
import org.bukkit.Sound;
@@ -68,12 +68,19 @@ public class runEverySecond {
}
} else {
// Execute the teleport
- if (timedTeleport.getTargetType().equals("point")) {
- teleportManager.teleportPlayer(teleporter, timedTeleport.getTargetPoint());
- } else {
- teleportManager.teleportPlayer(teleporter, timedTeleport.getTargetPlayerName());
+ String targetType = timedTeleport.getTargetType();
+ switch (targetType) {
+ case "point":
+ teleportManager.teleportPlayer(teleporter, timedTeleport.getTargetPoint());
+ break;
+ case "player":
+ teleportManager.teleportPlayer(teleporter, timedTeleport.getTargetPlayerName());
+ break;
+ case "random":
+ teleportManager.teleportPlayer(teleporter, new RandomPoint(teleporter));
+ dataManager.updateRtpCooldown(teleporter);
+ break;
}
-
completedTeleports.add(timedTeleport);
}
} else {
diff --git a/src/main/java/me/william278/huskhomes2/teleportManager.java b/src/main/java/me/william278/huskhomes2/teleportManager.java
index f4b1193c..bd849212 100644
--- a/src/main/java/me/william278/huskhomes2/teleportManager.java
+++ b/src/main/java/me/william278/huskhomes2/teleportManager.java
@@ -1,10 +1,12 @@
package me.william278.huskhomes2;
+import me.william278.huskhomes2.Objects.RandomPoint;
import me.william278.huskhomes2.Objects.TeleportationPoint;
import me.william278.huskhomes2.Objects.TimedTeleport;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
+import java.time.Instant;
import java.util.HashSet;
public class teleportManager {
@@ -25,18 +27,21 @@ public class teleportManager {
public static void teleportPlayer(Player p) {
TeleportationPoint teleportationPoint = dataManager.getPlayerDestination(p);
- String server = teleportationPoint.getServer();
- if (!Main.settings.doBungee() || server.equals(Main.settings.getServerID())) {
- p.teleport(teleportationPoint.getLocation());
- messageManager.sendMessage(p, "teleporting_complete");
- } else if (Main.settings.doBungee()) {
- dataManager.setPlayerDestinationLocation(p, teleportationPoint);
- pluginMessageHandler.sendPlayer(p, server);
+ if (teleportationPoint != null) {
+ String server = teleportationPoint.getServer();
+ if (!Main.settings.doBungee() || server.equals(Main.settings.getServerID())) {
+ p.teleport(teleportationPoint.getLocation());
+ messageManager.sendMessage(p, "teleporting_complete");
+ dataManager.clearPlayerDestination(p.getName());
+ } else if (Main.settings.doBungee()) {
+ dataManager.setPlayerDestinationLocation(p, teleportationPoint);
+ pluginMessageHandler.sendPlayer(p, server);
+ }
}
}
public static void queueTimedTeleport(Player player, String targetPlayer) {
- if (player.hasPermission("huskhomes.bypass_warmup_timers")) {
+ if (player.hasPermission("huskhomes.bypass_timer")) {
teleportPlayer(player, targetPlayer);
return;
}
@@ -45,7 +50,7 @@ public class teleportManager {
}
public static void queueTimedTeleport(Player player, TeleportationPoint point) {
- if (player.hasPermission("huskhomes.bypass_warmup_timers")) {
+ if (player.hasPermission("huskhomes.bypass_timer")) {
teleportPlayer(player, point);
return;
}
@@ -53,6 +58,26 @@ public class teleportManager {
queuedTeleports.add(new TimedTeleport(player, point));
}
+ public static void queueRandomTeleport(Player player) {
+ if (!player.hasPermission("huskhomes.rtp.bypass_cooldown")) {
+ long currentTime = Instant.now().getEpochSecond();
+ long cooldownTime = dataManager.getPlayerRtpCooldown(player);
+ if (currentTime < cooldownTime) {
+ long timeRemaining = cooldownTime - currentTime;
+ long timeRemainingMinutes = timeRemaining / 60;
+ messageManager.sendMessage(player, "error_rtp_cooldown", Long.toString(timeRemainingMinutes));
+ return;
+ }
+ }
+ if (player.hasPermission("huskhomes.bypass_timer")) {
+ teleportPlayer(player, new RandomPoint(player));
+ dataManager.updateRtpCooldown(player);
+ return;
+ }
+
+ queuedTeleports.add(new TimedTeleport(player));
+ }
+
private static void setTeleportationDestinationCrossServer(Player requester, String targetPlayerName) {
pluginMessageHandler.sendPluginMessage(requester, targetPlayerName, "set_teleportation_destination", requester.getName());
}
diff --git a/src/main/resources/Languages/en-gb.yml b/src/main/resources/Languages/en-gb.yml
index 085533d4..2639a9e5 100644
--- a/src/main/resources/Languages/en-gb.yml
+++ b/src/main/resources/Languages/en-gb.yml
@@ -14,10 +14,10 @@ error_home_invalid: '§4Error: §cYou do not have a home named "%1%"'
error_warp_invalid: '§4Error: §cThere is no warp set named "%1%"'
error_invalid_syntax: '§4Error: §cIncorrect syntax. Usage:\n §o%1%'
edit_home_title: '§aEdit home details for §l%1%§r§a:'
-edit_home_description: '• Description: §7%1%'
-edit_home_location: '• Location: §7%1%, %2%, %3%'
-edit_home_world: '• World: §7%1%'
-edit_home_server: '• Server: §7%1%'
+edit_description: '• Description: §7%1%'
+edit_location: '• Location: §7%1%, %2%, %3%'
+edit_world: '• World: §7%1%'
+edit_server: '• Server: §7%1%'
edit_home_privacy_private: '• Access: §cPrivate §7(Only you can use it)'
edit_home_privacy_public: '• Access: §2Public §7(Anyone can use it)'
edit_home_privacy_public_success: '§aSuccessfully made your home §l%1%§r§a open to the public.'
diff --git a/src/main/resources/Languages/zh-tw.yml b/src/main/resources/Languages/zh-tw.yml
index 96ce9739..a547b62e 100644
--- a/src/main/resources/Languages/zh-tw.yml
+++ b/src/main/resources/Languages/zh-tw.yml
@@ -12,10 +12,10 @@ home_deleted: '§a成功取消名爲§l%1%§r§a的家.'
error_home_invalid: '§c你并沒有名爲%1%的家'
error_invalid_syntax: '§c錯誤輸入.用法:\n §o%1%'
edit_home_title: '§a編輯名爲§l%1%§r§a的家:'
-edit_home_description: '• 介紹: §7%1%'
-edit_home_location: '• 坐標: §7%1%, %2%, %3%'
-edit_home_world: '• 世界: §7%1%'
-edit_home_server: '• 伺服器: §7%1%'
+edit_description: '• 介紹: §7%1%'
+edit_location: '• 坐標: §7%1%, %2%, %3%'
+edit_world: '• 世界: §7%1%'
+edit_server: '• 伺服器: §7%1%'
edit_home_privacy_private: '• 許可權: §c私人 §7(只有你可以使用)'
edit_home_privacy_public: '• 許可權: §2公開 §7(每個人都可以使用)'
edit_home_privacy_public_success: '§a已將名爲§l%1%§r§a設置成公開'
diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml
index dbd92e46..d2929339 100644
--- a/src/main/resources/config.yml
+++ b/src/main/resources/config.yml
@@ -18,5 +18,17 @@ spawn_command:
rtp_command:
enabled: true
range: 25000
+enable_warp_command:
data_storage_options:
- storage_type: 'SQLite'
\ No newline at end of file
+ storage_type: 'SQLite'
+ mysql_credentials:
+ host: localhost
+ database: database_name
+ username: root
+ password: password
+ port: 3306
+ table_names:
+ player_data: 'huskhomes_player_data'
+ locations_data: 'huskhomes_location_data'
+ homes_data: 'huskhomes_home_data'
+ warps_data: 'huskhomes_warp_data'
\ No newline at end of file