From 18b244ed65d6005ee315cc35e47d2a36e38e9b70 Mon Sep 17 00:00:00 2001 From: William278 Date: Mon, 14 Dec 2020 15:50:30 +0000 Subject: [PATCH] Added mySQL support, RTP command and bStats metric collection --- pom.xml | 2 +- .../huskhomes2/Commands/rtpCommand.java | 31 ++ .../Data/{SQLite => }/Database.java | 114 ++++-- .../Errors => ErrorLogging}/Error.java | 2 +- .../Errors => ErrorLogging}/Errors.java | 2 +- .../me/william278/huskhomes2/Data/SQL.java | 101 +++++ .../huskhomes2/Data/SQLite/SQLite.java | 65 ---- .../huskhomes2/Events/onPlayerJoin.java | 2 + .../java/me/william278/huskhomes2/Main.java | 15 + .../huskhomes2/Objects/RandomPoint.java | 42 +- .../huskhomes2/Objects/Settings.java | 83 +++- .../huskhomes2/Objects/TimedTeleport.java | 12 + .../me/william278/huskhomes2/dataManager.java | 267 ++++++------- .../william278/huskhomes2/editingHandler.java | 56 +-- .../me/william278/huskhomes2/listHandler.java | 2 +- .../william278/huskhomes2/metricsManager.java | 367 ++++++++++++++++++ .../william278/huskhomes2/runEverySecond.java | 19 +- .../huskhomes2/teleportManager.java | 43 +- src/main/resources/Languages/en-gb.yml | 8 +- src/main/resources/Languages/zh-tw.yml | 8 +- src/main/resources/config.yml | 14 +- 21 files changed, 941 insertions(+), 314 deletions(-) create mode 100644 src/main/java/me/william278/huskhomes2/Commands/rtpCommand.java rename src/main/java/me/william278/huskhomes2/Data/{SQLite => }/Database.java (74%) rename src/main/java/me/william278/huskhomes2/Data/{SQLite/Errors => ErrorLogging}/Error.java (88%) rename src/main/java/me/william278/huskhomes2/Data/{SQLite/Errors => ErrorLogging}/Errors.java (89%) create mode 100644 src/main/java/me/william278/huskhomes2/Data/SQL.java delete mode 100644 src/main/java/me/william278/huskhomes2/Data/SQLite/SQLite.java create mode 100644 src/main/java/me/william278/huskhomes2/metricsManager.java diff --git a/pom.xml b/pom.xml index 08f4a4f7..597457d2 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ me.William278 HuskHomes - 0.1 + 2.0 jar HuskHomes diff --git a/src/main/java/me/william278/huskhomes2/Commands/rtpCommand.java b/src/main/java/me/william278/huskhomes2/Commands/rtpCommand.java new file mode 100644 index 00000000..0263d474 --- /dev/null +++ b/src/main/java/me/william278/huskhomes2/Commands/rtpCommand.java @@ -0,0 +1,31 @@ +package me.william278.huskhomes2.Commands; + +import me.william278.huskhomes2.Main; +import me.william278.huskhomes2.messageManager; +import me.william278.huskhomes2.teleportManager; +import org.bukkit.World; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +public class rtpCommand implements CommandExecutor { + + @Override + public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { + if (sender instanceof Player) { + Player p = (Player) sender; + if (Main.settings.doRtpCommand()) { + if (p.getWorld().getEnvironment() == World.Environment.NORMAL) { + teleportManager.queueRandomTeleport(p); + } else { + messageManager.sendMessage(p, "error_rtp_invalid_dimension"); + } + } else { + messageManager.sendMessage(p, "error_command_disabled"); + } + return true; + } + return false; + } +} diff --git a/src/main/java/me/william278/huskhomes2/Data/SQLite/Database.java b/src/main/java/me/william278/huskhomes2/Data/Database.java similarity index 74% rename from src/main/java/me/william278/huskhomes2/Data/SQLite/Database.java rename to src/main/java/me/william278/huskhomes2/Data/Database.java index 8a2863f7..5d4d6a53 100644 --- a/src/main/java/me/william278/huskhomes2/Data/SQLite/Database.java +++ b/src/main/java/me/william278/huskhomes2/Data/Database.java @@ -1,7 +1,7 @@ -package me.william278.huskhomes2.Data.SQLite; +package me.william278.huskhomes2.Data; -import me.william278.huskhomes2.Data.SQLite.Errors.Error; -import me.william278.huskhomes2.Data.SQLite.Errors.Errors; +import me.william278.huskhomes2.Data.ErrorLogging.Error; +import me.william278.huskhomes2.Data.ErrorLogging.Errors; import me.william278.huskhomes2.Main; import me.william278.huskhomes2.Objects.Home; import me.william278.huskhomes2.Objects.TeleportationPoint; @@ -29,7 +29,7 @@ public abstract class Database { public void initialize() { connection = getSQLConnection(); try { - PreparedStatement ps = connection.prepareStatement("SELECT * FROM huskhomes_player_data WHERE `user_uuid`=?"); + PreparedStatement ps = connection.prepareStatement("SELECT * FROM " + Main.settings.getPlayerDataTable() + " WHERE `user_uuid`=?"); ResultSet rs = ps.executeQuery(); close(ps, rs); @@ -41,7 +41,7 @@ public abstract class Database { // Insert a teleportation point public void addTeleportationPoint(TeleportationPoint point, Connection conn) { try { - PreparedStatement ps = conn.prepareStatement("INSERT INTO huskhomes_location_data (world,server,x,y,z,yaw,pitch) VALUES(?,?,?,?,?,?,?);"); + PreparedStatement ps = conn.prepareStatement("INSERT INTO " + Main.settings.getLocationsDataTable() + " (world,server,x,y,z,yaw,pitch) VALUES(?,?,?,?,?,?,?);"); ps.setString(1, point.getWorldName()); ps.setString(2, point.getServer()); @@ -65,7 +65,7 @@ public abstract class Database { conn = getSQLConnection(); addTeleportationPoint(home, conn); - ps = conn.prepareStatement("INSERT INTO huskhomes_home_data (player_id,location_id,name,description,public) VALUES(?,(SELECT last_insert_rowid()),?,?,?);"); + ps = conn.prepareStatement("INSERT INTO " + Main.settings.getHomesDataTable() + " (player_id,location_id,name,description,public) VALUES(?,(SELECT last_insert_rowid()),?,?,?);"); ps.setInt(1, playerID); ps.setString(2, home.getName()); ps.setString(3, home.getDescription()); @@ -97,7 +97,7 @@ public abstract class Database { addTeleportationPoint(warp, conn); // Insert the warp with the location_id of the last inserted teleport point - ps = conn.prepareStatement("INSERT INTO huskhomes_warp_data (location_id,name,description) VALUES((SELECT last_insert_rowid()),?,?);"); + ps = conn.prepareStatement("INSERT INTO " + Main.settings.getWarpsDataTable() + " (location_id,name,description) VALUES((SELECT last_insert_rowid()),?,?);"); ps.setString(1, warp.getName()); ps.setString(2, warp.getDescription()); ps.executeUpdate(); @@ -124,7 +124,7 @@ public abstract class Database { conn = getSQLConnection(); // Delete the warp with the given name - ps = conn.prepareStatement("DELETE FROM huskhomes_warp_data WHERE `name`=?;"); + ps = conn.prepareStatement("DELETE FROM " + Main.settings.getWarpsDataTable() + " WHERE `name`=?;"); ps.setString(1, warpName); ps.executeUpdate(); @@ -151,7 +151,7 @@ public abstract class Database { conn = getSQLConnection(); // Delete the home with the given name and player ID - ps = conn.prepareStatement("DELETE FROM huskhomes_home_data WHERE `name`=? AND `player_id`=?;"); + ps = conn.prepareStatement("DELETE FROM " + Main.settings.getHomesDataTable() + " WHERE `name`=? AND `player_id`=?;"); ps.setString(1, homeName); ps.setInt(2, playerID); ps.executeUpdate(); @@ -178,7 +178,7 @@ public abstract class Database { try { conn = getSQLConnection(); - ps = conn.prepareStatement("INSERT INTO huskhomes_player_data (user_uuid,username,home_slots,rtp_cooldown,is_teleporting) VALUES(?,?,?,?,?);"); + ps = conn.prepareStatement("INSERT INTO " + Main.settings.getPlayerDataTable() + " (user_uuid,username,home_slots,rtp_cooldown,is_teleporting) VALUES(?,?,?,?,?);"); ps.setString(1, p.getUniqueId().toString()); ps.setString(2, p.getName()); ps.setInt(3, 5); //TODO: Update default home slots to be based on permission & config @@ -200,15 +200,37 @@ public abstract class Database { } } + public void updatePlayerUsername(int playerID, String newName) { + Connection conn = null; + PreparedStatement ps = null; + + try { + conn = getSQLConnection(); + ps = conn.prepareStatement("UPDATE " + Main.settings.getPlayerDataTable() + " SET `username`=? WHERE `player_id`=?;"); + ps.setString(1, newName); + ps.setInt(2, playerID); + ps.executeUpdate(); + } catch (SQLException ex) { + plugin.getLogger().log(Level.SEVERE, Errors.sqlConnectionExecute(), ex); + } finally { + try { + if (ps != null) + ps.close(); + if (conn != null) + conn.close(); + } catch (SQLException ex) { + plugin.getLogger().log(Level.SEVERE, Errors.sqlConnectionClose(), ex); + } + } + } + public void setPlayerTeleporting(int playerID, boolean value) { Connection conn = null; PreparedStatement ps = null; try { conn = getSQLConnection(); - - // Set the home location ID to the new teleport point for the given home - ps = conn.prepareStatement("UPDATE huskhomes_player_data SET `is_teleporting`=? WHERE `player_id`=?;"); + ps = conn.prepareStatement("UPDATE " + Main.settings.getPlayerDataTable() + " SET `is_teleporting`=? WHERE `player_id`=?;"); ps.setBoolean(1, value); ps.setInt(2, playerID); ps.executeUpdate(); @@ -226,6 +248,30 @@ public abstract class Database { } } + public void setRtpCooldown(int playerID, int newTime) { + Connection conn = null; + PreparedStatement ps = null; + + try { + conn = getSQLConnection(); + ps = conn.prepareStatement("UPDATE " + Main.settings.getPlayerDataTable() + " SET `rtp_cooldown`=? WHERE `player_id`=?;"); + ps.setInt(1, newTime); + ps.setInt(2, playerID); + ps.executeUpdate(); + } catch (SQLException ex) { + plugin.getLogger().log(Level.SEVERE, Errors.sqlConnectionExecute(), ex); + } finally { + try { + if (ps != null) + ps.close(); + if (conn != null) + conn.close(); + } catch (SQLException ex) { + plugin.getLogger().log(Level.SEVERE, Errors.sqlConnectionClose(), ex); + } + } + } + // Delete a teleportation point from SQL public void deleteTeleportationPoint(int locationID) { Connection conn = null; @@ -234,7 +280,7 @@ public abstract class Database { try { conn = getSQLConnection(); - ps = conn.prepareStatement("DELETE FROM huskhomes_location_data WHERE `location_id`=?;"); + ps = conn.prepareStatement("DELETE FROM " + Main.settings.getLocationsDataTable() + " WHERE `location_id`=?;"); ps.setInt(1, locationID); ps.executeUpdate(); @@ -261,7 +307,7 @@ public abstract class Database { conn = getSQLConnection(); // Set the home location ID to the new teleport point for the given home - ps = conn.prepareStatement("UPDATE huskhomes_home_data SET `public`=? WHERE `name`=? AND `player_id`=?;"); + ps = conn.prepareStatement("UPDATE " + Main.settings.getHomesDataTable() + " SET `public`=? WHERE `name`=? AND `player_id`=?;"); ps.setBoolean(1, isPublic); ps.setString(2, homeName); ps.setInt(3, ownerID); @@ -292,7 +338,7 @@ public abstract class Database { addTeleportationPoint(point, conn); // Set the home location ID to the new teleport point for the given home - ps = conn.prepareStatement("UPDATE huskhomes_home_data SET `location_id`=(SELECT last_insert_rowid()) WHERE `name`=? AND `player_id`=?;"); + ps = conn.prepareStatement("UPDATE " + Main.settings.getHomesDataTable() + " SET `location_id`=(SELECT last_insert_rowid()) WHERE `name`=? AND `player_id`=?;"); ps.setString(1, homeName); ps.setInt(2, ownerID); ps.executeUpdate(); @@ -322,7 +368,7 @@ public abstract class Database { addTeleportationPoint(point, conn); // Set the warp location ID to the new teleport point - ps = conn.prepareStatement("UPDATE huskhomes_warp_data SET `location_id`=(SELECT last_insert_rowid()) WHERE `name`=?;"); + ps = conn.prepareStatement("UPDATE " + Main.settings.getWarpsDataTable() + " SET `location_id`=(SELECT last_insert_rowid()) WHERE `name`=?;"); ps.setString(1, warpName); ps.executeUpdate(); } catch (SQLException ex) { @@ -347,7 +393,7 @@ public abstract class Database { conn = getSQLConnection(); // Update the home description - ps = conn.prepareStatement("UPDATE huskhomes_home_data SET `description`=? WHERE `name`=? AND `player_id`=?;"); + ps = conn.prepareStatement("UPDATE " + Main.settings.getHomesDataTable() + " SET `description`=? WHERE `name`=? AND `player_id`=?;"); ps.setString(1, newDescription); ps.setString(2, homeName); ps.setInt(3, ownerID); @@ -375,7 +421,7 @@ public abstract class Database { conn = getSQLConnection(); // Update the warp description - ps = conn.prepareStatement("UPDATE huskhomes_warp_data SET `description`=? WHERE `name`=?;"); + ps = conn.prepareStatement("UPDATE " + Main.settings.getWarpsDataTable() + " SET `description`=? WHERE `name`=?;"); ps.setString(1, newDescription); ps.setString(2, warpName); ps.executeUpdate(); @@ -402,7 +448,7 @@ public abstract class Database { conn = getSQLConnection(); // Update the home name - ps = conn.prepareStatement("UPDATE huskhomes_home_data SET `name`=? WHERE `name`=? AND `player_id`=?;"); + ps = conn.prepareStatement("UPDATE " + Main.settings.getHomesDataTable() + " SET `name`=? WHERE `name`=? AND `player_id`=?;"); ps.setString(1, newHomeName); ps.setString(2, oldHomeName); ps.setInt(3, ownerID); @@ -431,7 +477,7 @@ public abstract class Database { conn = getSQLConnection(); // Update the warp name - ps = conn.prepareStatement("UPDATE huskhomes_warp_data SET `name`=? WHERE `name`=?;"); + ps = conn.prepareStatement("UPDATE " + Main.settings.getWarpsDataTable() + " SET `name`=? WHERE `name`=?;"); ps.setString(1, newWarpName); ps.setString(2, oldWarpName); @@ -462,7 +508,31 @@ public abstract class Database { addTeleportationPoint(point, conn); // Set the destination location with the location_id of the last inserted teleport point - ps = conn.prepareStatement("UPDATE huskhomes_player_data SET `" + type + "_location_id`=(SELECT last_insert_rowid()) WHERE `player_id`=?;"); + ps = conn.prepareStatement("UPDATE " + Main.settings.getPlayerDataTable() + " SET `" + type + "_location_id`=(SELECT last_insert_rowid()) WHERE `player_id`=?;"); + ps.setInt(1, playerID); + ps.executeUpdate(); + } catch (SQLException ex) { + plugin.getLogger().log(Level.SEVERE, Errors.sqlConnectionExecute(), ex); + } finally { + try { + if (ps != null) + ps.close(); + if (conn != null) + conn.close(); + } catch (SQLException ex) { + plugin.getLogger().log(Level.SEVERE, Errors.sqlConnectionClose(), ex); + } + } + } + + // Clear a player's destination + public void clearPlayerDestination(int playerID) { + Connection conn = null; + PreparedStatement ps = null; + + try { + conn = getSQLConnection(); + ps = conn.prepareStatement("UPDATE " + Main.settings.getPlayerDataTable() + " SET `dest_location_id`=NULL WHERE `player_id`=?;"); ps.setInt(1, playerID); ps.executeUpdate(); } catch (SQLException ex) { diff --git a/src/main/java/me/william278/huskhomes2/Data/SQLite/Errors/Error.java b/src/main/java/me/william278/huskhomes2/Data/ErrorLogging/Error.java similarity index 88% rename from src/main/java/me/william278/huskhomes2/Data/SQLite/Errors/Error.java rename to src/main/java/me/william278/huskhomes2/Data/ErrorLogging/Error.java index 66893550..f72d13bf 100644 --- a/src/main/java/me/william278/huskhomes2/Data/SQLite/Errors/Error.java +++ b/src/main/java/me/william278/huskhomes2/Data/ErrorLogging/Error.java @@ -1,4 +1,4 @@ -package me.william278.huskhomes2.Data.SQLite.Errors; +package me.william278.huskhomes2.Data.ErrorLogging; import me.william278.huskhomes2.Main; diff --git a/src/main/java/me/william278/huskhomes2/Data/SQLite/Errors/Errors.java b/src/main/java/me/william278/huskhomes2/Data/ErrorLogging/Errors.java similarity index 89% rename from src/main/java/me/william278/huskhomes2/Data/SQLite/Errors/Errors.java rename to src/main/java/me/william278/huskhomes2/Data/ErrorLogging/Errors.java index 6c5681dc..55cf2331 100644 --- a/src/main/java/me/william278/huskhomes2/Data/SQLite/Errors/Errors.java +++ b/src/main/java/me/william278/huskhomes2/Data/ErrorLogging/Errors.java @@ -1,4 +1,4 @@ -package me.william278.huskhomes2.Data.SQLite.Errors; +package me.william278.huskhomes2.Data.ErrorLogging; public class Errors { public static String sqlConnectionExecute(){ diff --git a/src/main/java/me/william278/huskhomes2/Data/SQL.java b/src/main/java/me/william278/huskhomes2/Data/SQL.java new file mode 100644 index 00000000..9f3b171a --- /dev/null +++ b/src/main/java/me/william278/huskhomes2/Data/SQL.java @@ -0,0 +1,101 @@ +package me.william278.huskhomes2.Data; + +import me.william278.huskhomes2.Main; +import me.william278.huskhomes2.dataManager; +import org.bukkit.Bukkit; + +import java.io.File; +import java.io.IOException; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.logging.Level; + +public class SQL extends Database { + + final String SQLiteDatabaseName = "HuskHomesData"; + + public SQL(Main instance) { + super(instance); + } + + // Initialise connection via mySQL + private Connection getMySQLConnection() { + String host = Main.settings.getMySQLhost(); + int port = Main.settings.getMySQLport(); + String database = Main.settings.getMySQLdatabase(); + String username = Main.settings.getMySQLusername(); + String password = Main.settings.getMySQLpassword(); + + try { + synchronized (Main.getInstance()) { + Class.forName("com.mysql.jdbc.Driver"); + return DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + database, username, password); + } + } catch (SQLException e) { + Main.disablePlugin("Could not connect to the mySQL Database with the credentials provided!"); + } catch (ClassNotFoundException e) { + Main.disablePlugin("A critical exception occurred when attempting to establish a mySQL connection."); + e.printStackTrace(); + } + return null; + } + + // Initialise connection via SQLite + private Connection getSQLiteConnection() { + File dataFolder = new File(plugin.getDataFolder(), SQLiteDatabaseName + ".db"); + if (!dataFolder.exists()) { + try { + if (!dataFolder.createNewFile()) { + plugin.getLogger().log(Level.SEVERE, "File write error: " + SQLiteDatabaseName + ".db"); + } + } catch (IOException e) { + plugin.getLogger().log(Level.SEVERE, "File write error: " + SQLiteDatabaseName + ".db"); + } + } + try { + if (connection != null && !connection.isClosed()) { + return connection; + } + Class.forName("org.sqlite.JDBC"); + connection = DriverManager.getConnection("jdbc:sqlite:" + plugin.getDataFolder().getAbsolutePath() + "/" + SQLiteDatabaseName + ".db"); + return connection; + } catch (SQLException ex) { + plugin.getLogger().log(Level.SEVERE, "An exception occurred initialising the SQLite database", ex); + } catch (ClassNotFoundException ex) { + plugin.getLogger().log(Level.SEVERE, "You need the SQLite JBDC library; please download and place this in the /lib folder."); + } + return null; + } + + public Connection getSQLConnection() { + String dataStorageType = Main.settings.getStorageType().toLowerCase(); + switch (dataStorageType) { + case "mysql": + return getMySQLConnection(); + case "sqlite": + return getSQLiteConnection(); + default: + Bukkit.getLogger().warning("An invalid data storage type was specified in config.yml; defaulting to SQLite"); + return getSQLiteConnection(); + } + } + + public void load() { + connection = getSQLConnection(); + + try { + Statement s = connection.createStatement(); + s.execute(dataManager.createPlayerTable); + s.execute(dataManager.createLocationsTable); + s.execute(dataManager.createHomesTable); + s.execute(dataManager.createWarpsTable); + s.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + + initialize(); + } +} \ No newline at end of file diff --git a/src/main/java/me/william278/huskhomes2/Data/SQLite/SQLite.java b/src/main/java/me/william278/huskhomes2/Data/SQLite/SQLite.java deleted file mode 100644 index 88e43b61..00000000 --- a/src/main/java/me/william278/huskhomes2/Data/SQLite/SQLite.java +++ /dev/null @@ -1,65 +0,0 @@ -package me.william278.huskhomes2.Data.SQLite; - -import me.william278.huskhomes2.Main; -import me.william278.huskhomes2.dataManager; - -import java.io.File; -import java.io.IOException; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.logging.Level; - -public class SQLite extends Database { - - final String databaseName = "HuskHomesData"; - - public SQLite(Main instance) { - super(instance); - } - - // SQL creation stuff, You can leave the blow stuff untouched. - public Connection getSQLConnection() { - File dataFolder = new File(plugin.getDataFolder(), databaseName + ".db"); - if (!dataFolder.exists()) { - try { - if (!dataFolder.createNewFile()) { - plugin.getLogger().log(Level.SEVERE, "File write error: " + databaseName + ".db"); - } - } catch (IOException e) { - plugin.getLogger().log(Level.SEVERE, "File write error: " + databaseName + ".db"); - } - } - try { - if (connection != null && !connection.isClosed()) { - return connection; - } - Class.forName("org.sqlite.JDBC"); - connection = DriverManager.getConnection("jdbc:sqlite:" + plugin.getDataFolder().getAbsolutePath() + "/" + databaseName + ".db"); - return connection; - } catch (SQLException ex) { - plugin.getLogger().log(Level.SEVERE, "An exception occurred initialising the SQLite database", ex); - } catch (ClassNotFoundException ex) { - plugin.getLogger().log(Level.SEVERE, "You need the SQLite JBDC library; please download and place this in the /lib folder."); - } - return null; - } - - public void load() { - connection = getSQLConnection(); - - try { - Statement s = connection.createStatement(); - s.execute(dataManager.createPlayerTable); - s.execute(dataManager.createLocationsTable); - s.execute(dataManager.createHomesTable); - s.execute(dataManager.createWarpsTable); - s.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - - initialize(); - } -} \ No newline at end of file diff --git a/src/main/java/me/william278/huskhomes2/Events/onPlayerJoin.java b/src/main/java/me/william278/huskhomes2/Events/onPlayerJoin.java index 3670fd6c..4f9d7415 100644 --- a/src/main/java/me/william278/huskhomes2/Events/onPlayerJoin.java +++ b/src/main/java/me/william278/huskhomes2/Events/onPlayerJoin.java @@ -18,6 +18,8 @@ public class onPlayerJoin implements Listener { // Create player on SQL if they don't exist already if (!dataManager.playerExists(p)) { dataManager.createPlayer(p); + } else { + dataManager.checkPlayerNameChange(p); } // If bungee mode, check if the player joined the server from a teleport and act accordingly diff --git a/src/main/java/me/william278/huskhomes2/Main.java b/src/main/java/me/william278/huskhomes2/Main.java index 5cd60897..e6e816c5 100644 --- a/src/main/java/me/william278/huskhomes2/Main.java +++ b/src/main/java/me/william278/huskhomes2/Main.java @@ -4,6 +4,7 @@ import me.william278.huskhomes2.Commands.*; import me.william278.huskhomes2.Events.onPlayerDeath; import me.william278.huskhomes2.Events.onPlayerJoin; import me.william278.huskhomes2.Objects.Settings; +import org.bukkit.Bukkit; import org.bukkit.plugin.java.JavaPlugin; public final class Main extends JavaPlugin { @@ -17,11 +18,19 @@ public final class Main extends JavaPlugin { } public static Settings settings; + // Disable the plugin for the given reason + public static void disablePlugin(String reason) { + getInstance().getLogger().severe("Disabling HuskHomes plugin because: " + reason); + Bukkit.getPluginManager().disablePlugin(getInstance()); + } + + // Initialise bungee plugin channels private static void setupBungeeChannels(Main plugin) { plugin.getServer().getMessenger().registerOutgoingPluginChannel(plugin, "BungeeCord"); plugin.getServer().getMessenger().registerIncomingPluginChannel(plugin, "BungeeCord", new pluginMessageHandler()); } + // Register commands private static void registerCommands(Main plugin) { plugin.getCommand("back").setExecutor(new backCommand()); plugin.getCommand("delhome").setExecutor(new delHomeCommand()); @@ -43,8 +52,10 @@ public final class Main extends JavaPlugin { plugin.getCommand("tphere").setExecutor(new tpHereCommand()); plugin.getCommand("warp").setExecutor(new warpCommand()); plugin.getCommand("warplist").setExecutor(new warpListCommand()); + plugin.getCommand("rtp").setExecutor(new rtpCommand()); } + // Register events private static void registerEvents(Main plugin) { plugin.getServer().getPluginManager().registerEvents(new onPlayerJoin(), plugin); plugin.getServer().getPluginManager().registerEvents(new onPlayerDeath(), plugin); @@ -81,7 +92,11 @@ public final class Main extends JavaPlugin { // Register events registerEvents(this); + // Start Loop runEverySecond.startLoop(); + + // bStats initialisation + new metricsManager(this, 8430); } @Override diff --git a/src/main/java/me/william278/huskhomes2/Objects/RandomPoint.java b/src/main/java/me/william278/huskhomes2/Objects/RandomPoint.java index 74005e72..61897e5c 100644 --- a/src/main/java/me/william278/huskhomes2/Objects/RandomPoint.java +++ b/src/main/java/me/william278/huskhomes2/Objects/RandomPoint.java @@ -13,35 +13,37 @@ import java.util.Random; public class RandomPoint extends TeleportationPoint { //List of all the unsafe blocks - final static HashSet bad_blocks = new HashSet<>(); + final static HashSet unsafeBlocks = new HashSet<>(); static{ - bad_blocks.add(Material.LAVA); - bad_blocks.add(Material.FIRE); - bad_blocks.add(Material.CACTUS); - bad_blocks.add(Material.WATER); - bad_blocks.add(Material.MAGMA_BLOCK); - bad_blocks.add(Material.JUNGLE_LEAVES); - bad_blocks.add(Material.SPRUCE_LEAVES); + unsafeBlocks.add(Material.LAVA); + unsafeBlocks.add(Material.FIRE); + unsafeBlocks.add(Material.CACTUS); + unsafeBlocks.add(Material.WATER); + unsafeBlocks.add(Material.MAGMA_BLOCK); + unsafeBlocks.add(Material.JUNGLE_LEAVES); + unsafeBlocks.add(Material.SPRUCE_LEAVES); } private Location randomLocation(World world) { - //Generate Random Location + //Generate a random location Random random = new Random(); - int x = 0; - int z = 0; - int y = 0; - int negativex = 0; - int negativez = 0; + int x; + int z; + int y; + int negativeX; + int negativeZ; + x = random.nextInt(Main.settings.getRtpRange()); z = random.nextInt(Main.settings.getRtpRange()); - negativex = random.nextInt(2); - negativez = random.nextInt(2); - if (negativex == 1) { + negativeX = random.nextInt(2); + negativeZ = random.nextInt(2); + + if (negativeX == 1) { x = x * -1; } - if (negativez == 1) + if (negativeZ == 1) z = z * -1; y = 150; @@ -53,17 +55,17 @@ public class RandomPoint extends TeleportationPoint { } private boolean isLocationSafe(Location location){ - int x = location.getBlockX(); int y = location.getBlockY(); int z = location.getBlockZ(); + //Get instances of the blocks around where the player would spawn Block block = location.getWorld().getBlockAt(x, y, z); Block below = location.getWorld().getBlockAt(x, y - 1, z); Block above = location.getWorld().getBlockAt(x, y + 1, z); //Check to see if the surroundings are safe or not - return !(bad_blocks.contains(below.getType())) || (block.getType().isSolid()) || (above.getType().isSolid()); + return !(unsafeBlocks.contains(below.getType())) || (block.getType().isSolid()) || (above.getType().isSolid()); } private Location getRandomLocation(World world) { diff --git a/src/main/java/me/william278/huskhomes2/Objects/Settings.java b/src/main/java/me/william278/huskhomes2/Objects/Settings.java index b20ddb5b..370e2952 100644 --- a/src/main/java/me/william278/huskhomes2/Objects/Settings.java +++ b/src/main/java/me/william278/huskhomes2/Objects/Settings.java @@ -1,5 +1,6 @@ package me.william278.huskhomes2.Objects; +import org.bukkit.Bukkit; import org.bukkit.configuration.file.FileConfiguration; public class Settings { @@ -8,15 +9,28 @@ public class Settings { String server; String storageType; + String playerDataTable; + String locationsDataTable; + String homesDataTable; + String warpsDataTable; + + int mySQLport; + String mySQLhost; + String mySQLdatabase; + String mySQLusername; + String mySQLpassword; int maximumHomes; int teleportRequestExpiryTime; int teleportWarmupTime; + int rtpRange; + int rtpCooldown; boolean doBungee; boolean doRtpCommand; boolean doSpawnCommand; + boolean doWarpCommand; private void setSettings(FileConfiguration configFile) { this.language = configFile.getString("language"); @@ -25,10 +39,31 @@ public class Settings { this.storageType = configFile.getString("data_storage_options.storage_type"); + // Resolve conflict between storage type and bungee mode + if (storageType.equalsIgnoreCase("sqlite") && doBungee) { + Bukkit.getLogger().warning("Bungee mode was set in config to be enabled but storage type was set to SQLite!"); + Bukkit.getLogger().warning("A mySQL Database is required to utilise Bungee mode, so bungee mode has been disabled."); + Bukkit.getLogger().warning("To use Bungee mode and cross-server teleportation, please update your data storage settings to use \"mysql\" and update the connection details accordingly."); + this.doBungee = false; + } + + this.mySQLhost = configFile.getString("data_storage_options.mysql_database.host"); + this.mySQLdatabase = configFile.getString("data_storage_options.mysql_database.database"); + this.mySQLusername = configFile.getString("data_storage_options.mysql_database.username"); + this.mySQLpassword = configFile.getString("data_storage_options.mysql_database.password"); + this.mySQLport = configFile.getInt("data_storage_options.mysql_database.port"); + + this.playerDataTable = configFile.getString("data_storage_options.table_names.player_data"); + this.locationsDataTable = configFile.getString("data_storage_options.table_names.locations_data"); + this.homesDataTable = configFile.getString("data_storage_options.table_names.homes_data"); + this.warpsDataTable = configFile.getString("data_storage_options.table_names.warps_data"); + this.doSpawnCommand = configFile.getBoolean("spawn_command.enabled"); + this.doWarpCommand = configFile.getBoolean("enable_warp_command"); this.doRtpCommand = configFile.getBoolean("rtp_command.enabled"); this.rtpRange = configFile.getInt("rtp_command.range"); + this.rtpCooldown = configFile.getInt("rtp_command.cooldown"); this.maximumHomes = configFile.getInt("general.max_sethomes"); this.teleportRequestExpiryTime = configFile.getInt("general.teleport_request_expiry_time"); @@ -64,9 +99,17 @@ public class Settings { return doBungee; } - public int getMaximumHomes() { return maximumHomes; } + public int getMaximumHomes() { + return maximumHomes; + } - public int getTeleportRequestExpiryTime() { return teleportRequestExpiryTime; } + public int getRtpCooldown() { + return rtpCooldown; + } + + public int getTeleportRequestExpiryTime() { + return teleportRequestExpiryTime; + } public int getRtpRange() { return rtpRange; @@ -76,4 +119,40 @@ public class Settings { return doRtpCommand; } + public String getPlayerDataTable() { + return playerDataTable; + } + + public String getLocationsDataTable() { + return locationsDataTable; + } + + public String getHomesDataTable() { + return homesDataTable; + } + + public String getWarpsDataTable() { + return warpsDataTable; + } + + public int getMySQLport() { + return mySQLport; + } + + public String getMySQLhost() { + return mySQLhost; + } + + public String getMySQLdatabase() { + return mySQLdatabase; + } + + public String getMySQLusername() { + return mySQLusername; + } + + public String getMySQLpassword() { + return mySQLpassword; + } + } diff --git a/src/main/java/me/william278/huskhomes2/Objects/TimedTeleport.java b/src/main/java/me/william278/huskhomes2/Objects/TimedTeleport.java index 38f41d0e..7029449c 100644 --- a/src/main/java/me/william278/huskhomes2/Objects/TimedTeleport.java +++ b/src/main/java/me/william278/huskhomes2/Objects/TimedTeleport.java @@ -3,6 +3,7 @@ package me.william278.huskhomes2.Objects; import me.william278.huskhomes2.Main; import me.william278.huskhomes2.messageManager; import org.bukkit.Location; +import org.bukkit.World; import org.bukkit.entity.Player; public class TimedTeleport { @@ -31,6 +32,17 @@ public class TimedTeleport { messageManager.sendMessage(teleporter, "teleporting_please_stand_still"); } + public TimedTeleport(Player teleporter) { + this.teleporter = teleporter; + this.initialTeleporterLocation = teleporter.getLocation(); + this.initialTeleporterHealth = teleporter.getHealth(); + this.targetType = "random"; + this.timeRemaining = warmupTime; + + messageManager.sendMessage(teleporter, "teleporting_countdown_start", Integer.toString(this.warmupTime)); + messageManager.sendMessage(teleporter, "teleporting_please_stand_still"); + } + public TimedTeleport(Player teleporter, String targetPlayerName) { this.teleporter = teleporter; this.initialTeleporterLocation = teleporter.getLocation(); diff --git a/src/main/java/me/william278/huskhomes2/dataManager.java b/src/main/java/me/william278/huskhomes2/dataManager.java index f99c1372..817d8db7 100644 --- a/src/main/java/me/william278/huskhomes2/dataManager.java +++ b/src/main/java/me/william278/huskhomes2/dataManager.java @@ -1,8 +1,8 @@ package me.william278.huskhomes2; -import me.william278.huskhomes2.Data.SQLite.Database; -import me.william278.huskhomes2.Data.SQLite.Errors.Errors; -import me.william278.huskhomes2.Data.SQLite.SQLite; +import me.william278.huskhomes2.Data.Database; +import me.william278.huskhomes2.Data.ErrorLogging.Errors; +import me.william278.huskhomes2.Data.SQL; import me.william278.huskhomes2.Objects.Home; import me.william278.huskhomes2.Objects.TeleportationPoint; import me.william278.huskhomes2.Objects.Warp; @@ -14,6 +14,7 @@ import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; +import java.time.Instant; import java.util.ArrayList; import java.util.UUID; import java.util.logging.Level; @@ -21,7 +22,7 @@ import java.util.logging.Level; // This class handles the saving of data; whether that be through SQLite or SQL public class dataManager { - public static String createPlayerTable = "CREATE TABLE IF NOT EXISTS huskhomes_player_data (" + + public static String createPlayerTable = "CREATE TABLE IF NOT EXISTS " + Main.settings.getPlayerDataTable() + " (" + "`player_id` integer NOT NULL," + "`user_uuid` char(36) NOT NULL UNIQUE," + "`username` varchar(16) NOT NULL," + @@ -31,11 +32,11 @@ public class dataManager { "`dest_location_id` integer NULL," + "`last_location_id` integer NULL," + "PRIMARY KEY (`player_id`)," + - "FOREIGN KEY (`dest_location_id`) REFERENCES huskhomes_location_data (`location_id`) ON DELETE CASCADE ON UPDATE NO ACTION," + - "FOREIGN KEY (`last_location_id`) REFERENCES huskhomes_location_data (`location_id`) ON DELETE CASCADE ON UPDATE NO ACTION" + + "FOREIGN KEY (`dest_location_id`) REFERENCES " + Main.settings.getLocationsDataTable() + " (`location_id`) ON DELETE CASCADE ON UPDATE NO ACTION," + + "FOREIGN KEY (`last_location_id`) REFERENCES " + Main.settings.getLocationsDataTable() + " (`location_id`) ON DELETE CASCADE ON UPDATE NO ACTION" + ");"; - public static String createLocationsTable = "CREATE TABLE IF NOT EXISTS huskhomes_location_data (" + + public static String createLocationsTable = "CREATE TABLE IF NOT EXISTS " + Main.settings.getLocationsDataTable() + " (" + "`location_id` integer PRIMARY KEY," + "`server` text NOT NULL," + "`world` text NOT NULL," + @@ -46,46 +47,73 @@ public class dataManager { "`pitch` float NOT NULL" + ");"; - public static String createHomesTable = "CREATE TABLE IF NOT EXISTS huskhomes_home_data (" + + public static String createHomesTable = "CREATE TABLE IF NOT EXISTS " + Main.settings.getHomesDataTable() + " (" + "`player_id` integer NOT NULL," + "`location_id` integer NOT NULL," + "`name` double NOT NULL," + "`description` varchar NOT NULL," + "`public` boolean NOT NULL," + "PRIMARY KEY (`player_id`, `location_id`)," + - "FOREIGN KEY (`player_id`) REFERENCES huskhomes_player_data (`player_id`) ON DELETE CASCADE ON UPDATE NO ACTION," + - "FOREIGN KEY (`location_id`) REFERENCES huskhomes_location_data (`location_id`) ON DELETE CASCADE ON UPDATE NO ACTION" + + "FOREIGN KEY (`player_id`) REFERENCES " + Main.settings.getPlayerDataTable() + " (`player_id`) ON DELETE CASCADE ON UPDATE NO ACTION," + + "FOREIGN KEY (`location_id`) REFERENCES " + Main.settings.getLocationsDataTable() + " (`location_id`) ON DELETE CASCADE ON UPDATE NO ACTION" + ");"; - public static String createWarpsTable = "CREATE TABLE IF NOT EXISTS huskhomes_warp_data (" + + public static String createWarpsTable = "CREATE TABLE IF NOT EXISTS " + Main.settings.getWarpsDataTable() + " (" + "`location_id` integer NOT NULL," + "`name` varchar NOT NULL UNIQUE," + "`description` varchar NOT NULL," + "PRIMARY KEY (`location_id`)," + - "FOREIGN KEY (`location_id`) REFERENCES huskhomes_location_data (`location_id`) ON DELETE CASCADE ON UPDATE NO ACTION" + + "FOREIGN KEY (`location_id`) REFERENCES " + Main.settings.getLocationsDataTable() + " (`location_id`) ON DELETE CASCADE ON UPDATE NO ACTION" + ");"; - private static Main plugin = Main.getInstance(); + private static final Main plugin = Main.getInstance(); - private static Database sqliteDatabase; + private static Database database; private static Connection getConnection() { - if (Main.settings.getStorageType().equalsIgnoreCase("mysql")) { - return null; //TODO: Add mySQL support - } else { - initializeSQLite(); - return sqliteDatabase.getSQLConnection(); + initializeDatabase(); + return database.getSQLConnection(); + } + + private static void initializeDatabase() { + database = new SQL(Main.getInstance()); + database.load(); + } + + // Return a player's ID from their UUID + private static Integer getPlayerId(UUID playerUUID) { + Connection conn = null; + PreparedStatement ps = null; + ResultSet rs; + + try { + conn = getConnection(); + ps = conn.prepareStatement("SELECT * FROM " + Main.settings.getPlayerDataTable() + " WHERE `user_uuid`=?;"); + ps.setString(1, playerUUID.toString()); + rs = ps.executeQuery(); + if (rs != null) { + if (rs.next()) { + return rs.getInt("player_id"); + } else { + return null; + } + } else { + return null; // If the player doesn't exist, playerID will be null + } + } catch (SQLException ex) { + plugin.getLogger().log(Level.SEVERE, Errors.sqlConnectionExecute(), ex); + } finally { + try { + if (ps != null) + ps.close(); + if (conn != null) + conn.close(); + } catch (SQLException ex) { + plugin.getLogger().log(Level.SEVERE, Errors.sqlConnectionClose(), ex); + } } - } - - private static void initializeSQLite() { - sqliteDatabase = new SQLite(Main.getInstance()); - sqliteDatabase.load(); - } - - private static void initializeMySQL() { - + return null; } // Return a player's ID from their username @@ -96,7 +124,7 @@ public class dataManager { try { conn = getConnection(); - ps = conn.prepareStatement("SELECT * FROM huskhomes_player_data WHERE `username`=?;"); + ps = conn.prepareStatement("SELECT * FROM " + Main.settings.getPlayerDataTable() + " WHERE `username`=?;"); ps.setString(1, playerUsername); rs = ps.executeQuery(); if (rs != null) { @@ -131,7 +159,7 @@ public class dataManager { try { conn = getConnection(); - ps = conn.prepareStatement("SELECT * FROM huskhomes_player_data WHERE `player_id`=?;"); + ps = conn.prepareStatement("SELECT * FROM " + Main.settings.getPlayerDataTable() + " WHERE `player_id`=?;"); ps.setInt(1, playerID); rs = ps.executeQuery(); if (rs != null) { @@ -177,7 +205,7 @@ public class dataManager { try { conn = getConnection(); - ps = conn.prepareStatement("SELECT * FROM huskhomes_player_data WHERE `player_id`=?;"); + ps = conn.prepareStatement("SELECT * FROM " + Main.settings.getPlayerDataTable() + " WHERE `player_id`=?;"); ps.setInt(1, playerID); rs = ps.executeQuery(); if (rs != null) { @@ -224,7 +252,7 @@ public class dataManager { try { conn = getConnection(); - ps = conn.prepareStatement("SELECT * FROM huskhomes_player_data WHERE `player_id`=?;"); + ps = conn.prepareStatement("SELECT * FROM " + Main.settings.getPlayerDataTable() + " WHERE `player_id`=?;"); ps.setInt(1, playerID); rs = ps.executeQuery(); if (rs != null) { @@ -278,8 +306,8 @@ public class dataManager { } // Return how many home slots a player has - public static Integer getPlayerRtpCooldown(Player p) { - return getPlayerInteger(p, "rtp_cooldown"); + public static Long getPlayerRtpCooldown(Player p) { + return (long) getPlayerInteger(p, "rtp_cooldown"); } // Return a player's homes. @@ -291,7 +319,7 @@ public class dataManager { try { conn = getConnection(); - ps = conn.prepareStatement("SELECT * FROM huskhomes_home_data WHERE `player_id`=?;"); + ps = conn.prepareStatement("SELECT * FROM " + Main.settings.getHomesDataTable() + " WHERE `player_id`=?;"); ps.setInt(1, playerID); rs = ps.executeQuery(); if (rs != null) { @@ -335,7 +363,7 @@ public class dataManager { try { conn = getConnection(); - ps = conn.prepareStatement("SELECT * FROM huskhomes_home_data WHERE `public`;"); + ps = conn.prepareStatement("SELECT * FROM " + Main.settings.getHomesDataTable() + " WHERE `public`;"); rs = ps.executeQuery(); if (rs != null) { ArrayList publicHomes = new ArrayList<>(); @@ -375,7 +403,7 @@ public class dataManager { try { conn = getConnection(); - ps = conn.prepareStatement("SELECT * FROM huskhomes_warp_data;"); + ps = conn.prepareStatement("SELECT * FROM " + Main.settings.getWarpsDataTable() + ";"); rs = ps.executeQuery(); ArrayList 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