From c899010fd5e4a59743c71471df5a2e9c2a67fdd3 Mon Sep 17 00:00:00 2001 From: KingFaris10 Date: Wed, 8 Apr 2015 18:00:17 +0100 Subject: [PATCH] KingKits v3.3.5 KingKits v3.3.5 update. --- pom.xml | 2 +- .../java/com/faris/kingkits/KingKits.java | 2251 ++++++++--------- .../java/com/faris/kingkits/KingKitsAPI.java | 632 +++++ .../java/com/faris/kingkits/KingKitsSQL.java | 122 + src/main/java/com/faris/kingkits/Kit.java | 1384 +++++----- .../java/com/faris/kingkits/Permissions.java | 56 +- src/main/java/com/faris/kingkits/Vault.java | 39 +- .../com/faris/kingkits/gui/GuiKingKits.java | 95 + .../com/faris/kingkits/gui/GuiKitMenu.java | 220 ++ .../com/faris/kingkits/gui/GuiPreviewKit.java | 121 + .../com/faris/kingkits/guis/GuiKingKits.java | 100 - .../com/faris/kingkits/guis/GuiKitMenu.java | 221 -- .../faris/kingkits/guis/GuiPreviewKit.java | 122 - .../java/com/faris/kingkits/helper/Lang.java | 156 ++ .../faris/kingkits/helper/UUIDFetcher.java | 352 +++ .../com/faris/kingkits/helper/Utilities.java | 425 ++++ .../helper/container/ConfigCommand.java | 45 + .../container}/KitStack.java | 4 +- .../kingkits/helper/value/CommandValues.java | 12 + .../kingkits/helper/value/ConfigValues.java | 107 + .../faris/kingkits/helpers/ConfigCommand.java | 45 - .../java/com/faris/kingkits/helpers/Lang.java | 156 -- .../faris/kingkits/helpers/NameFetcher.java | 49 - .../faris/kingkits/helpers/UUIDFetcher.java | 96 - .../com/faris/kingkits/helpers/Utils.java | 427 ---- .../com/faris/kingkits/hooks/PvPKits.java | 857 +++---- .../faris/kingkits/listener/KingCommand.java | 101 + .../kingkits/listener/PlayerCommand.java | 25 + .../listener/command/CreateKitCommand.java | 165 ++ .../command/CreateUserKitCommand.java | 192 ++ .../listener/command/DeleteKitCommand.java | 86 + .../command/DeleteUserKitCommand.java | 86 + .../listener/command/KingKitsCommand.java | 264 ++ .../kingkits/listener/command/KitCommand.java | 139 + .../listener/command/RefillCommand.java | 195 ++ .../listener/command/RenameKitCommand.java | 94 + .../command/RenameUserKitCommand.java | 109 + .../kingkits/listener/command/SetKit.java | 192 ++ .../listener/event/EventListener.java | 1057 ++++++++ .../event/custom/KingKitsPreReloadEvent.java | 16 +- .../event/custom/KingKitsReloadEvent.java | 66 + .../event/custom/PlayerCreateKitEvent.java | 131 + .../event/custom/PlayerKilledEvent.java | 17 +- .../listener/event/custom/PlayerKitEvent.java | 188 ++ .../faris/kingkits/listeners/KingCommand.java | 103 - .../kingkits/listeners/PlayerCommand.java | 25 - .../listeners/commands/CreateKitCommand.java | 165 -- .../commands/CreateUserKitCommand.java | 191 -- .../listeners/commands/DeleteKitCommand.java | 86 - .../commands/DeleteUserKitCommand.java | 86 - .../listeners/commands/KingKitsCommand.java | 264 -- .../listeners/commands/KitCommand.java | 139 - .../listeners/commands/RefillCommand.java | 195 -- .../listeners/commands/RenameKitCommand.java | 94 - .../commands/RenameUserKitCommand.java | 109 - .../kingkits/listeners/commands/SetKit.java | 195 -- .../listeners/event/EventListener.java | 1103 -------- .../event/custom/KingKitsReloadEvent.java | 65 - .../event/custom/PlayerCreateKitEvent.java | 131 - .../event/custom/PlayerKitEvent.java | 187 -- .../com/faris/kingkits/sql/KingKitsSQL.java | 122 - .../faris/kingkits/updater/BukkitUpdater.java | 1450 ++++++----- .../faris/kingkits/updater/SpigotUpdater.java | 186 +- .../faris/kingkits/values/CommandValues.java | 12 - .../faris/kingkits/values/ConfigValues.java | 107 - src/main/java/org/mcstats/Metrics.java | 1398 +++++----- 66 files changed, 9054 insertions(+), 8578 deletions(-) create mode 100644 src/main/java/com/faris/kingkits/KingKitsAPI.java create mode 100644 src/main/java/com/faris/kingkits/KingKitsSQL.java create mode 100644 src/main/java/com/faris/kingkits/gui/GuiKingKits.java create mode 100644 src/main/java/com/faris/kingkits/gui/GuiKitMenu.java create mode 100644 src/main/java/com/faris/kingkits/gui/GuiPreviewKit.java delete mode 100644 src/main/java/com/faris/kingkits/guis/GuiKingKits.java delete mode 100644 src/main/java/com/faris/kingkits/guis/GuiKitMenu.java delete mode 100644 src/main/java/com/faris/kingkits/guis/GuiPreviewKit.java create mode 100644 src/main/java/com/faris/kingkits/helper/Lang.java create mode 100644 src/main/java/com/faris/kingkits/helper/UUIDFetcher.java create mode 100644 src/main/java/com/faris/kingkits/helper/Utilities.java create mode 100644 src/main/java/com/faris/kingkits/helper/container/ConfigCommand.java rename src/main/java/com/faris/kingkits/{helpers => helper/container}/KitStack.java (81%) create mode 100644 src/main/java/com/faris/kingkits/helper/value/CommandValues.java create mode 100644 src/main/java/com/faris/kingkits/helper/value/ConfigValues.java delete mode 100644 src/main/java/com/faris/kingkits/helpers/ConfigCommand.java delete mode 100644 src/main/java/com/faris/kingkits/helpers/Lang.java delete mode 100644 src/main/java/com/faris/kingkits/helpers/NameFetcher.java delete mode 100644 src/main/java/com/faris/kingkits/helpers/UUIDFetcher.java delete mode 100644 src/main/java/com/faris/kingkits/helpers/Utils.java create mode 100644 src/main/java/com/faris/kingkits/listener/KingCommand.java create mode 100644 src/main/java/com/faris/kingkits/listener/PlayerCommand.java create mode 100644 src/main/java/com/faris/kingkits/listener/command/CreateKitCommand.java create mode 100644 src/main/java/com/faris/kingkits/listener/command/CreateUserKitCommand.java create mode 100644 src/main/java/com/faris/kingkits/listener/command/DeleteKitCommand.java create mode 100644 src/main/java/com/faris/kingkits/listener/command/DeleteUserKitCommand.java create mode 100644 src/main/java/com/faris/kingkits/listener/command/KingKitsCommand.java create mode 100644 src/main/java/com/faris/kingkits/listener/command/KitCommand.java create mode 100644 src/main/java/com/faris/kingkits/listener/command/RefillCommand.java create mode 100644 src/main/java/com/faris/kingkits/listener/command/RenameKitCommand.java create mode 100644 src/main/java/com/faris/kingkits/listener/command/RenameUserKitCommand.java create mode 100644 src/main/java/com/faris/kingkits/listener/command/SetKit.java create mode 100644 src/main/java/com/faris/kingkits/listener/event/EventListener.java rename src/main/java/com/faris/kingkits/{listeners => listener}/event/custom/KingKitsPreReloadEvent.java (77%) create mode 100644 src/main/java/com/faris/kingkits/listener/event/custom/KingKitsReloadEvent.java create mode 100644 src/main/java/com/faris/kingkits/listener/event/custom/PlayerCreateKitEvent.java rename src/main/java/com/faris/kingkits/{listeners => listener}/event/custom/PlayerKilledEvent.java (68%) create mode 100644 src/main/java/com/faris/kingkits/listener/event/custom/PlayerKitEvent.java delete mode 100644 src/main/java/com/faris/kingkits/listeners/KingCommand.java delete mode 100644 src/main/java/com/faris/kingkits/listeners/PlayerCommand.java delete mode 100644 src/main/java/com/faris/kingkits/listeners/commands/CreateKitCommand.java delete mode 100644 src/main/java/com/faris/kingkits/listeners/commands/CreateUserKitCommand.java delete mode 100644 src/main/java/com/faris/kingkits/listeners/commands/DeleteKitCommand.java delete mode 100644 src/main/java/com/faris/kingkits/listeners/commands/DeleteUserKitCommand.java delete mode 100644 src/main/java/com/faris/kingkits/listeners/commands/KingKitsCommand.java delete mode 100644 src/main/java/com/faris/kingkits/listeners/commands/KitCommand.java delete mode 100644 src/main/java/com/faris/kingkits/listeners/commands/RefillCommand.java delete mode 100644 src/main/java/com/faris/kingkits/listeners/commands/RenameKitCommand.java delete mode 100644 src/main/java/com/faris/kingkits/listeners/commands/RenameUserKitCommand.java delete mode 100644 src/main/java/com/faris/kingkits/listeners/commands/SetKit.java delete mode 100644 src/main/java/com/faris/kingkits/listeners/event/EventListener.java delete mode 100644 src/main/java/com/faris/kingkits/listeners/event/custom/KingKitsReloadEvent.java delete mode 100644 src/main/java/com/faris/kingkits/listeners/event/custom/PlayerCreateKitEvent.java delete mode 100644 src/main/java/com/faris/kingkits/listeners/event/custom/PlayerKitEvent.java delete mode 100644 src/main/java/com/faris/kingkits/sql/KingKitsSQL.java delete mode 100644 src/main/java/com/faris/kingkits/values/CommandValues.java delete mode 100644 src/main/java/com/faris/kingkits/values/ConfigValues.java diff --git a/pom.xml b/pom.xml index 3bdccb0..ff84b29 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.faris KingKits - 3.3.4 + 3.3.5 jar diff --git a/src/main/java/com/faris/kingkits/KingKits.java b/src/main/java/com/faris/kingkits/KingKits.java index dced7b9..d182d65 100644 --- a/src/main/java/com/faris/kingkits/KingKits.java +++ b/src/main/java/com/faris/kingkits/KingKits.java @@ -1,40 +1,30 @@ package com.faris.kingkits; -import com.faris.kingkits.guis.GuiKingKits; -import com.faris.kingkits.guis.GuiKitMenu; -import com.faris.kingkits.guis.GuiPreviewKit; -import com.faris.kingkits.helpers.Lang; -import com.faris.kingkits.helpers.UUIDFetcher; -import com.faris.kingkits.helpers.Utils; -import com.faris.kingkits.hooks.PvPKits; -import com.faris.kingkits.listeners.commands.*; -import com.faris.kingkits.listeners.event.EventListener; -import com.faris.kingkits.sql.KingKitsSQL; +import com.faris.kingkits.gui.GuiKingKits; +import com.faris.kingkits.gui.GuiKitMenu; +import com.faris.kingkits.gui.GuiPreviewKit; +import com.faris.kingkits.helper.Lang; +import com.faris.kingkits.helper.UUIDFetcher; +import com.faris.kingkits.helper.Utilities; +import com.faris.kingkits.helper.value.CommandValues; +import com.faris.kingkits.helper.value.ConfigValues; +import com.faris.kingkits.listener.command.*; +import com.faris.kingkits.listener.event.EventListener; import com.faris.kingkits.updater.BukkitUpdater; import com.faris.kingkits.updater.SpigotUpdater; -import com.faris.kingkits.values.CommandValues; -import com.faris.kingkits.values.ConfigValues; import org.apache.commons.lang.Validate; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.Color; -import org.bukkit.Material; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.configuration.serialization.ConfigurationSerialization; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.inventory.meta.LeatherArmorMeta; -import org.bukkit.permissions.Permission; -import org.bukkit.plugin.java.JavaPlugin; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; -import org.bukkit.scoreboard.DisplaySlot; -import org.bukkit.scoreboard.Scoreboard; -import org.bukkit.util.FileUtil; +import org.bukkit.*; +import org.bukkit.configuration.*; +import org.bukkit.configuration.file.*; +import org.bukkit.configuration.serialization.*; +import org.bukkit.enchantments.*; +import org.bukkit.entity.*; +import org.bukkit.inventory.*; +import org.bukkit.permissions.*; +import org.bukkit.plugin.java.*; +import org.bukkit.potion.*; +import org.bukkit.scoreboard.*; +import org.bukkit.util.*; import org.mcstats.Metrics; import java.io.File; @@ -49,1169 +39,1038 @@ @SuppressWarnings({"unused", "deprecation"}) public class KingKits extends JavaPlugin { - private static KingKits pluginInstance = null; - - // Class Variables - private PvPKits pvpKits = null; - private KingKitsSQL kkSql = null; - public Permissions permissions = new Permissions(); - public CommandValues cmdValues = new CommandValues(); - public ConfigValues configValues = new ConfigValues(); - public Vault vault = new Vault(this); - - // Plugin Variables - public Map usingKits = new HashMap(); - public Map playerKits = new HashMap(); - public Map playerScores = new HashMap(); - public Map compassTargets = new HashMap(); - public Map playerKillstreaks = new HashMap(); - - // Listeners - private EventListener pListener = null; - private KingKitsCommand cmdKingKits = null; - private KitCommand cmdKitL = null; - private CreateKitCommand cmdKitC = null; - private DeleteKitCommand cmdKitD = null; - private RenameKitCommand cmdKitR = null; - private RefillCommand cmdRefill = null; - private CreateUserKitCommand cmdKitUC = null; - private DeleteUserKitCommand cmdKitUD = null; - private RenameUserKitCommand cmdKitUR = null; - - public Map kitList = new HashMap(); - public Map> userKitList = new HashMap>(); - private int cooldownTaskID = -1; - - public void onEnable() { - pluginInstance = this; - - this.pvpKits = new PvPKits(); - // Clear all lists - this.usingKits.clear(); - this.playerKits.clear(); - this.playerScores.clear(); - this.compassTargets.clear(); - this.playerKillstreaks.clear(); - - // Initialise variables - ConfigurationSerialization.registerClass(Kit.class); - try { - this.loadConfiguration(); - } catch (Exception ex) { - ex.printStackTrace(); - } - try { - Lang.init(this); - } catch (Exception ex) { - ex.printStackTrace(); - } - - this.pListener = new EventListener(this); - // Update commands - this.cmdKingKits = new KingKitsCommand(this); - this.cmdKitL = new KitCommand(this); - this.cmdKitC = new CreateKitCommand(this); - this.cmdKitD = new DeleteKitCommand(this); - this.cmdRefill = new RefillCommand(this); - this.cmdKitR = new RenameKitCommand(this); - this.cmdKitUC = new CreateUserKitCommand(this); - this.cmdKitUD = new DeleteUserKitCommand(this); - this.cmdKitUR = new RenameUserKitCommand(this); - - // Register commands - this.getCommand("kingkits").setExecutor(this.cmdKingKits); - this.getCommand("kingkits").setAliases(Arrays.asList("kk")); - this.getCommand("pvpkit").setExecutor(this.cmdKitL); - this.getCommand("createkit").setExecutor(this.cmdKitC); - this.getCommand("deletekit").setExecutor(this.cmdKitD); - this.getCommand("refill").setExecutor(this.cmdRefill); - this.getCommand("refill").setAliases(Arrays.asList("soup")); - this.getCommand("renamekit").setExecutor(this.cmdKitR); - this.getCommand("createukit").setExecutor(this.cmdKitUC); - this.getCommand("deleteukit").setExecutor(this.cmdKitUD); - this.getCommand("renameukit").setExecutor(this.cmdKitUR); - - // Register permissions - for (Permission registeredPerm : this.permissions.permissionsList) - this.getServer().getPluginManager().addPermission(registeredPerm); - for (int i = 1; i <= 54; i++) { - try { - this.getServer().getPluginManager().addPermission(new Permission("kingkits.kit.limit." + i)); - } catch (Exception ex) { - continue; - } - } - this.getServer().getPluginManager().registerEvents(this.pListener, this); - - // Check for updates - if (this.configValues.checkForUpdates) { - if (this.getServer().getVersion().contains("Spigot")) { - SpigotUpdater updater = new SpigotUpdater(this, 2209, false); - if (updater.getResult() == SpigotUpdater.UpdateResult.UPDATE_AVAILABLE) { - String title = "============================================"; - String titleSpace = " "; - this.getLogger().info(title); - try { - this.getLogger().info(titleSpace.substring(0, titleSpace.length() / 2 - "KingKits".length() + 3) + "KingKits" + titleSpace.substring(0, titleSpace.length() / 2 - "KingKits".length())); - } catch (Exception ex) { - this.getServer().getConsoleSender().sendMessage("KingKits"); - } - this.getLogger().info(title); - this.getLogger().info("A new version is available: KingKits v" + updater.getVersion()); - this.getLogger().info("Your current version: KingKits v" + this.getDescription().getVersion()); - this.getLogger().info((this.configValues.automaticUpdates ? "Automatic updates do not work for Spigot. " : "") + "Download it from: http://www.spigotmc.org/threads/kingkits.37947"); - } - } else { - BukkitUpdater updater = new BukkitUpdater(this, 56371, this.getFile(), BukkitUpdater.UpdateType.NO_DOWNLOAD, false); - if (updater.getResult() == BukkitUpdater.UpdateResult.UPDATE_AVAILABLE) { - String title = "============================================"; - String titleSpace = " "; - this.getLogger().info(title); - try { - this.getLogger().info(titleSpace.substring(0, titleSpace.length() / 2 - "KingKits".length() + 3) + "KingKits" + titleSpace.substring(0, titleSpace.length() / 2 - "KingKits".length())); - } catch (Exception ex) { - this.getServer().getConsoleSender().sendMessage("KingKits"); - } - this.getLogger().info(title); - this.getLogger().info("A new version is available: " + updater.getLatestName()); - this.getLogger().info("Your current version: KingKits v" + this.getDescription().getVersion()); - if (this.configValues.automaticUpdates) { - this.getLogger().info("Downloading " + updater.getLatestName() + "..."); - updater = new BukkitUpdater(this, 56371, this.getFile(), BukkitUpdater.UpdateType.NO_VERSION_CHECK, false); - BukkitUpdater.UpdateResult updateResult = updater.getResult(); - if (updateResult == BukkitUpdater.UpdateResult.FAIL_APIKEY) - this.getLogger().warning("Download failed: Improperly configured the server's API key in the configuration"); - else if (updateResult == BukkitUpdater.UpdateResult.FAIL_DBO) - this.getLogger().warning("Download failed: Could not connect to BukkitDev."); - else if (updateResult == BukkitUpdater.UpdateResult.FAIL_DOWNLOAD) - this.getLogger().warning("Download failed: Could not download the file."); - else if (updateResult == BukkitUpdater.UpdateResult.FAIL_NOVERSION) - this.getLogger().warning("Download failed: The latest version has an incorrect title."); - else this.getLogger().info("The latest version of KingKits has been downloaded."); - } else { - this.getLogger().info("Download it from: " + updater.getLatestFileLink()); - } - } - } - } - - try { - new Metrics(this).start(); - } catch (Exception ex) { - this.getLogger().warning("Could not start metrics due to a(n) " + ex.getClass().getSimpleName() + " error."); - ex.printStackTrace(); - } - } - - public void onDisable() { - if (this.cooldownTaskID != -1) this.getServer().getScheduler().cancelTask(this.cooldownTaskID); - - if (this.kkSql != null) { - this.kkSql.onDisable(); - this.kkSql = null; - } - - // Clear inventories on reload - if (this.configValues.clearInvsOnReload) { - for (Player target : Utils.getOnlinePlayers()) { - if (PvPKits.hasKit(target.getName(), false)) { - target.getInventory().clear(); - target.getInventory().setArmorContents(null); - target.setMaxHealth(20D); - for (PotionEffect potionEffect : target.getActivePotionEffects()) - target.removePotionEffect(potionEffect.getType()); - } - } - } - - ConfigurationSerialization.unregisterClass(Kit.class); - - // Clear all lists - this.usingKits.clear(); - this.playerKits.clear(); - this.playerScores.clear(); - this.compassTargets.clear(); - this.playerKillstreaks.clear(); - this.kitList.clear(); - this.userKitList.clear(); - - // Unregister all permissions - for (Permission registeredPerm : this.permissions.permissionsList) - this.getServer().getPluginManager().removePermission(registeredPerm); - for (int i = 1; i <= 54; i++) { - try { - this.getServer().getPluginManager().removePermission(new Permission("kingkits.kit.limit." + i)); - } catch (Exception ex) { - continue; - } - } - - this.permissions = null; - - try { - for (Entry playerEntry : GuiKingKits.guiKitMenuMap.entrySet()) { - playerEntry.getValue().closeMenu(true, this.getServer().getPlayerExact(playerEntry.getKey()) != null); - } - GuiKingKits.guiKitMenuMap.clear(); - } catch (Exception ex) { - ex.printStackTrace(); - } - - try { - for (Entry playerEntry : GuiKingKits.guiPreviewKitMap.entrySet()) { - playerEntry.getValue().closeMenu(true, this.getServer().getPlayerExact(playerEntry.getKey()) != null); - } - GuiKingKits.guiPreviewKitMap.clear(); - } catch (Exception ex) { - ex.printStackTrace(); - } - - pluginInstance = null; - } - - // Load Configurations - public void loadConfiguration() throws Exception { - try { - if (this.cooldownTaskID != -1 && this.getServer().getScheduler().isQueued(this.cooldownTaskID)) - this.getServer().getScheduler().cancelTask(this.cooldownTaskID); - if (KingKitsSQL.isInitialised() || KingKitsSQL.isOpen()) KingKitsSQL.closeConnection(); - this.getConfig().options().header("KingKits Configuration"); - this.getConfig().addDefault("Op bypass", true); - this.getConfig().addDefault("MySQL.Enabled", false); - this.getConfig().addDefault("MySQL.Host", "127.0.0.1"); - this.getConfig().addDefault("MySQL.Port", 3306); - this.getConfig().addDefault("MySQL.Username", "root"); - this.getConfig().addDefault("MySQL.Password", ""); - this.getConfig().addDefault("MySQL.Database", "kingkits"); - this.getConfig().addDefault("MySQL.Table prefix", "kk_"); - this.getConfig().addDefault("GUI.Title", "PvP Kits"); - this.getConfig().addDefault("GUI.Size", 36); - this.getConfig().addDefault("PvP Worlds", Arrays.asList("All")); - this.getConfig().addDefault("Multiple world inventories plugin", "Multiverse-Inventories"); - this.getConfig().addDefault("Multi-inventories", this.getServer().getPluginManager().isPluginEnabled(this.getConfig().getString("Multiple world inventories plugin"))); - this.getConfig().addDefault("Enable kits command", true); - this.getConfig().addDefault("Enable create kits command", true); - this.getConfig().addDefault("Enable delete kits command", true); - this.getConfig().addDefault("Enable rename kits command", true); - this.getConfig().addDefault("Enable create user kits command", true); - this.getConfig().addDefault("Enable delete user kits command", true); - this.getConfig().addDefault("Enable rename user kits command", true); - this.getConfig().addDefault("Enable refill command", true); - this.getConfig().addDefault("Kit sign", "[Kit]"); - this.getConfig().addDefault("Kit list sign", "[KList]"); - this.getConfig().addDefault("Kit sign valid", "[&1Kit&0]"); - this.getConfig().addDefault("Kit sign invalid", "[&cKit&0]"); - this.getConfig().addDefault("Kit list sign valid", "[&1KList&0]"); - this.getConfig().addDefault("Kit cooldown enabled", false); - if (this.getConfig().contains("Kit cooldown")) this.getConfig().set("Kit cooldown", null); - this.getConfig().addDefault("List kits on join", true); - this.getConfig().addDefault("Use permissions on join", true); - this.getConfig().addDefault("Use permissions for kit list", true); - this.getConfig().addDefault("Kit list mode", "Text"); - this.getConfig().addDefault("Sort kits alphabetically", true); - this.getConfig().addDefault("Remove items on leave", true); - this.getConfig().addDefault("Drop items on death", false); - this.getConfig().addDefault("Drop items", false); - this.getConfig().addDefault("Drop animations", Arrays.asList(Material.BOWL.getId())); - this.getConfig().addDefault("Allow picking up items", true); - this.getConfig().addDefault("Clear inventories on reload", true); - this.getConfig().addDefault("One kit per life", false); - this.getConfig().addDefault("Check for updates", true); - this.getConfig().addDefault("Automatically update", false); - this.getConfig().addDefault("Enable score", false); - this.getConfig().addDefault("Score chat prefix", "&6[&a&6]"); - this.getConfig().addDefault("Score per kill", 2); - this.getConfig().addDefault("Max score", Integer.MAX_VALUE); - this.getConfig().addDefault("Remove potion effects on leave", true); - this.getConfig().addDefault("Set compass target to nearest player", true); - this.getConfig().addDefault("Quick soup", true); - this.getConfig().addDefault("Quick soup heal", 2.5D); - this.getConfig().addDefault("Requires kit to use refill", true); - this.getConfig().addDefault("Command to run when changing kits", ""); - this.getConfig().addDefault("Disable block placing and breaking", false); - this.getConfig().addDefault("Disable death messages", false); - this.getConfig().addDefault("Lock hunger level", true); - this.getConfig().addDefault("Hunger lock", 20); - this.getConfig().addDefault("Custom message", "&6You have chosen the kit &c&6."); - this.getConfig().addDefault("Disable gamemode while using a kit", false); - this.getConfig().addDefault("Enable killstreaks", false); - this.getConfig().addDefault("Disable item breaking", true); - this.getConfig().addDefault("Kit menu on join", false); - this.getConfig().addDefault("Clear items on kit creation", true); - this.getConfig().addDefault("Kit particle effects", false); - this.getConfig().addDefault("Show kit preview", false); - this.getConfig().addDefault("Replace items when selecting a kit", true); - if (this.getConfig().contains("Scoreboards")) this.getConfig().set("Scoreboards", null); - if (this.getConfig().contains("Scoreboard title")) this.getConfig().set("Scoreboard title", null); - this.getConfig().options().copyDefaults(true); - this.getConfig().options().copyHeader(true); - this.saveConfig(); - - this.configValues.opBypass = this.getConfig().getBoolean("Op bypass"); - this.configValues.pvpWorlds = this.getConfig().getStringList("PvP Worlds"); - this.configValues.multiInvsPlugin = this.getConfig().getString("Multiple world inventories plugin"); - this.configValues.multiInvs = this.getConfig().getBoolean("Multi-inventories"); - if (!this.configValues.multiInvs && this.getServer().getPluginManager().isPluginEnabled(this.getConfig().getString("Multiple world inventories plugin"))) { - this.configValues.multiInvs = true; - this.getConfig().set("Multi-inventories", true); - this.saveConfig(); - } - this.cmdValues.pvpKits = this.getConfig().getBoolean("Enable kits command"); - this.cmdValues.createKits = this.getConfig().getBoolean("Enable create kits command"); - this.cmdValues.deleteKits = this.getConfig().getBoolean("Enable delete kits command"); - this.cmdValues.renameKits = this.getConfig().getBoolean("Enable rename kits command"); - this.cmdValues.createUKits = this.getConfig().getBoolean("Enable create user kits command"); - this.cmdValues.deleteUKits = this.getConfig().getBoolean("Enable delete user kits command"); - this.cmdValues.renameUKits = this.getConfig().getBoolean("Enable rename user kits command"); - this.cmdValues.refillKits = this.getConfig().getBoolean("Enable refill command"); - this.configValues.strKitSign = Utils.replaceChatColour(this.getConfig().getString("Kit sign")); - this.configValues.strKitListSign = Utils.replaceChatColour(this.getConfig().getString("Kit list sign")); - this.configValues.strKitSignValid = Utils.replaceChatColour(this.getConfig().getString("Kit sign valid")); - this.configValues.strKitSignInvalid = Utils.replaceChatColour(this.getConfig().getString("Kit sign invalid")); - this.configValues.strKitListSignValid = Utils.replaceChatColour(this.getConfig().getString("Kit list sign valid")); - this.configValues.kitCooldown = this.getConfig().getBoolean("Kit cooldown enabled"); - this.configValues.listKitsOnJoin = this.getConfig().getBoolean("List kits on join"); - this.configValues.kitListMode = this.getConfig().getString("Kit list mode"); - this.configValues.sortAlphabetically = this.getConfig().getBoolean("Sort kits alphabetically"); - this.configValues.kitListPermissionsJoin = this.getConfig().getBoolean("Use permissions on join"); - this.configValues.kitListPermissions = this.getConfig().getBoolean("Use permissions for kit list"); - this.configValues.removeItemsOnLeave = this.getConfig().getBoolean("Remove items on leave"); - this.configValues.dropItemsOnDeath = this.getConfig().getBoolean("Drop items on death"); - this.configValues.dropItems = this.getConfig().getBoolean("Drop items"); - this.configValues.dropAnimations = this.getConfig().getIntegerList("Drop animations"); - this.configValues.allowPickingUpItems = this.getConfig().getBoolean("Allow picking up items"); - this.configValues.clearInvsOnReload = this.getConfig().getBoolean("Clear inventories on reload"); - this.configValues.oneKitPerLife = this.getConfig().getBoolean("One kit per life"); - this.configValues.checkForUpdates = this.getConfig().getBoolean("Check for updates"); - this.configValues.automaticUpdates = this.getConfig().getBoolean("Automatically update"); - this.configValues.removePotionEffectsOnLeave = this.getConfig().getBoolean("Remove potion effects on leave"); - this.configValues.rightClickCompass = this.getConfig().getBoolean("Set compass target to nearest player"); - this.configValues.quickSoup = this.getConfig().getBoolean("Quick soup"); - this.configValues.quickSoupHeal = (float) (Math.ceil(this.getConfig().getDouble("Quick soup heal") * 2) / 2); - this.configValues.quickSoupKitOnly = this.getConfig().getBoolean("Requires kit to use refill"); - this.configValues.banBlockBreakingAndPlacing = this.getConfig().getBoolean("Disable block placing and breaking"); - this.configValues.disableDeathMessages = this.getConfig().getBoolean("Disable death messages"); - this.configValues.lockHunger = this.getConfig().getBoolean("Lock hunger level"); - this.configValues.hungerLock = this.getConfig().getInt("Hunger lock"); - this.configValues.customMessages = this.getConfig().getString("Custom message"); - this.configValues.commandToRun = this.getConfig().getString("Command to run when changing kits"); - this.configValues.disableGamemode = this.getConfig().getBoolean("Disable gamemode while using a kit"); - this.configValues.killstreaks = this.getConfig().getBoolean("Enable killstreaks"); - this.configValues.disableItemBreaking = this.getConfig().getBoolean("Disable item breaking"); - this.configValues.kitMenuOnJoin = this.getConfig().getBoolean("Kit menu on join"); - this.configValues.removeItemsOnCreateKit = this.getConfig().getBoolean("Clear items on kit creation"); - this.configValues.kitParticleEffects = this.getConfig().getBoolean("Kit particle effects"); - this.configValues.showKitPreview = this.getConfig().getBoolean("Show kit preview"); - this.configValues.replaceItems = this.getConfig().getBoolean("Replace items when selecting a kit"); - - this.configValues.guiTitle = Utils.replaceChatColour(this.getConfig().getString("GUI.Title")); - this.configValues.guiSize = this.getConfig().getInt("GUI.Size"); - if (this.configValues.guiSize <= 0 || this.configValues.guiSize % 9 != 0 || this.configValues.guiSize > 54) - this.configValues.guiSize = 36; - - - this.configValues.scores = this.getConfig().getBoolean("Enable score"); - this.configValues.scoreIncrement = this.getConfig().getInt("Score per kill"); - String scoreChatPrefix = this.getConfig().getString("Score chat prefix"); - if (!scoreChatPrefix.contains("")) { - this.getConfig().set("Score chat prefix", "&6[&a&6]"); - this.saveConfig(); - } - this.configValues.scoreFormat = this.getConfig().getString("Score chat prefix"); - this.configValues.maxScore = this.getConfig().getInt("Max score"); - - this.loadMySQL(); - this.loadPvPKits(); - this.loadUserKits(); - this.loadScores(); - this.loadEconomy(); - this.loadKillstreaks(); - - for (Player onlinePlayer : Utils.getOnlinePlayers()) { - Scoreboard playerScoreboard = onlinePlayer.getScoreboard(); - if (playerScoreboard != null) { - if (playerScoreboard.getObjective("KingKits") != null) { - playerScoreboard.resetScores(Bukkit.getOfflinePlayer(ChatColor.GREEN + "Score:")); - playerScoreboard.resetScores(Bukkit.getOfflinePlayer(ChatColor.GREEN + "Killstreak:")); - playerScoreboard.clearSlot(DisplaySlot.SIDEBAR); - if (playerScoreboard.getObjectives().isEmpty()) - onlinePlayer.setScoreboard(this.getServer().getScoreboardManager().getNewScoreboard()); - else onlinePlayer.setScoreboard(playerScoreboard); - } - } - } - - if (this.configValues.kitCooldown) { - this.cooldownTaskID = this.getServer().getScheduler().runTaskTimer(this, new Runnable() { - public void run() { - boolean hasBeenModified = false; - for (Map.Entry configEntrySet : getCooldownConfig().getValues(false).entrySet()) { - Map playerMap = null; - if (configEntrySet.getValue() instanceof ConfigurationSection) - playerMap = ((ConfigurationSection) configEntrySet.getValue()).getValues(false); - else if (configEntrySet.getValue() instanceof Map) - playerMap = (Map) configEntrySet.getValue(); - if (playerMap != null) { - for (Map.Entry entrySet : playerMap.entrySet()) { - String strValue = entrySet.getValue().toString(); - if (Utils.isLong(strValue)) { - Kit targetKit = kitList.get(entrySet.getKey()); - if (targetKit != null) { - long kitCooldown = targetKit.getCooldown(); - long playerCooldown = Long.parseLong(strValue); - if (System.currentTimeMillis() - playerCooldown >= kitCooldown * 1000) { - getCooldownConfig().set(configEntrySet.getKey() + "." + entrySet.getKey(), null); - if (playerMap.size() == 1) - getCooldownConfig().set(configEntrySet.getKey(), null); - hasBeenModified = true; - } - } - } - } - } - } - if (hasBeenModified) saveCooldownConfig(); - } - }, 1200L, 1200L).getTaskId(); - } - } catch (Exception ex) { - throw ex; - } - } - - private void loadMySQL() { - if (KingKitsSQL.isOpen()) KingKitsSQL.closeConnection(); - KingKitsSQL.sqlEnabled = this.getConfig().getBoolean("MySQL.Enabled", false); - this.kkSql = new KingKitsSQL(this.getConfig().getString("MySQL.Host", "127.0.0.1"), this.getConfig().getInt("MySQL.Port", 3306), this.getConfig().getString("MySQL.Username", "root"), this.getConfig().getString("MySQL.Password", ""), this.getConfig().getString("MySQL.Database", "kingkits"), this.getConfig().getString("MySQL.Table prefix", "kk_")); - } - - private void loadPvPKits() { - try { - this.convertOldConfig(); - this.getKitsConfig().options().header("KingKits Kits Configuration."); - - this.getKitsConfig().addDefault("First run", true); - if (this.getKitsConfig().getBoolean("First run")) { - Kit defaultKit = new Kit("Default").setRealName("Default").setCommands(Arrays.asList("feed ", "tell &6You have been fed for using the default kit.")); - List defaultKitItems = new ArrayList(), defaultKitArmour = new ArrayList(); - - ItemStack defaultSword = new ItemStack(Material.IRON_SWORD); - defaultSword.addEnchantment(Enchantment.DURABILITY, 3); - defaultKitItems.add(Utils.ItemUtils.setLores(Utils.ItemUtils.setName(defaultSword, "Default Kit Sword"), Arrays.asList("&6Iron Slayer"))); - defaultKitItems.add(new ItemStack(Material.GOLDEN_APPLE, 2)); - defaultKitArmour.add(new ItemStack(Material.IRON_HELMET)); - defaultKitArmour.add(Utils.ItemUtils.setDye(new ItemStack(Material.LEATHER_CHESTPLATE), 10040115)); - defaultKitArmour.add(new ItemStack(Material.IRON_LEGGINGS)); - defaultKitArmour.add(new ItemStack(Material.IRON_BOOTS)); - defaultKitItems.add(new ItemStack(Material.POTION, 1, (short) 8201)); - - defaultKit.setItems(defaultKitItems); - defaultKit.setArmour(defaultKitArmour); - defaultKit.setPotionEffects(Arrays.asList(new PotionEffect(PotionEffectType.SPEED, 200, 1))); - - this.getKitsConfig().addDefault("Default", defaultKit.serialize()); - this.getKitsConfig().set("First run", false); - } - this.getKitsConfig().options().copyDefaults(true); - this.getKitsConfig().options().copyHeader(true); - this.saveKitsConfig(); - - this.kitList.clear(); - List kitList = this.getConfigKitList(); - for (String kitName : kitList) { - try { - Object objKitConfigSection = this.getKitsConfig().get(kitName); - Kit kit = null; - if (objKitConfigSection instanceof ConfigurationSection) - kit = Kit.deserialize(((ConfigurationSection) objKitConfigSection).getValues(false)); - else if (objKitConfigSection instanceof Map) - kit = Kit.deserialize((Map) objKitConfigSection); - if (kit != null) this.kitList.put(kitName, kit.setRealName(kitName).setUserKit(false)); - else - this.getLogger().warning("Could not register the kit '" + kitName + "' it has been invalidly defined in the configuration."); - } catch (Exception ex) { - this.getLogger().warning("Could not register the kit '" + kitName + "' due to a(n) " + ex.getClass().getSimpleName() + " error:"); - ex.printStackTrace(); - } - } - - this.setupPermissions(true); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - private void loadUserKits() { - try { - this.getUserKitsConfig().options().header("KingKits User Kits Configuration."); - this.getUserKitsConfig().options().copyHeader(true); - this.saveUserKitsConfig(); - - this.userKitList.clear(); - List userList = new ArrayList(this.getUserKitsConfig().getKeys(false)); - for (String userName : userList) { - List userKits = new ArrayList(); - try { - for (Map.Entry kitEntry : this.getUserKitsConfig().getConfigurationSection(userName).getValues(false).entrySet()) { - try { - String kitName = kitEntry.getKey(); - Object objKitConfigSection = kitEntry.getValue(); - Kit kit = null; - if (objKitConfigSection instanceof ConfigurationSection) - kit = Kit.deserialize(((ConfigurationSection) objKitConfigSection).getValues(false)); - else if (objKitConfigSection instanceof Map) - kit = Kit.deserialize((Map) objKitConfigSection); - if (kit != null) userKits.add(kit.setRealName(kitName).setUserKit(true)); - } catch (Exception ex) { - continue; - } - } - } catch (Exception ex) { - ex.printStackTrace(); - } - if (!userKits.isEmpty()) this.userKitList.put(userName, userKits); - } - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - private void loadScores() { - try { - this.getScoresConfig().options().header("KingKits Score Configuration"); - Map scores = new HashMap(); - scores.put("Player1", 2); - if (!this.getScoresConfig().contains("Scores")) this.getScoresConfig().createSection("Scores", scores); - this.getScoresConfig().options().copyDefaults(true); - this.getScoresConfig().options().copyHeader(true); - this.saveScoresConfig(); - - Map scoresMap = this.getScoresConfig().getConfigurationSection("Scores").getValues(true); - List unconvertedScores = new ArrayList(); - for (Entry scoreEntry : scoresMap.entrySet()) { - if (!Utils.isUUID(scoreEntry.getKey())) unconvertedScores.add(scoreEntry.getKey()); - } - boolean hasConverted = false; - try { - Map uuidList = new UUIDFetcher(unconvertedScores).call(); - for (Entry uuidEntry : uuidList.entrySet()) { - scoresMap.put(uuidEntry.getValue().toString(), scoresMap.get(uuidEntry.getKey())); - this.getScoresConfig().set("Scores." + uuidEntry.getValue().toString(), scoresMap.get(uuidEntry.getKey())); - } - hasConverted = true; - } catch (Exception ex) { - ex.printStackTrace(); - hasConverted = false; - } - for (String unconvertedPlayer : unconvertedScores) { - scoresMap.remove(unconvertedPlayer); - if (hasConverted) { - this.getScoresConfig().set("Scores." + unconvertedPlayer, null); - } - } - this.saveScoresConfig(); - this.playerScores = new HashMap(); - for (Entry mapEntry : scoresMap.entrySet()) { - if (Utils.isUUID(mapEntry.getKey())) - this.playerScores.put(UUID.fromString(mapEntry.getKey()), mapEntry.getValue()); - } - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - private void loadEconomy() { - this.getEconomyConfig().options().header("KingKits Economy Configuration"); - this.getEconomyConfig().addDefault("Use economy", false); - this.getEconomyConfig().addDefault("Enable cost per kit", false); - this.getEconomyConfig().addDefault("Enable cost per refill", false); - this.getEconomyConfig().addDefault("Cost per refill", 2.50); - this.getEconomyConfig().addDefault("Currency", "dollars"); - this.getEconomyConfig().addDefault("Message", "&a was taken from your balance."); - this.getEconomyConfig().addDefault("Enable money per kill", false); - this.getEconomyConfig().addDefault("Money per kill", 5.00); - this.getEconomyConfig().addDefault("Money per kill message", "&aYou received for killing ."); - this.getEconomyConfig().addDefault("Enable money per death", false); - this.getEconomyConfig().addDefault("Money per death", 5.00); - this.getEconomyConfig().addDefault("Money per death message", "&aYou lost for being killed by ."); - if (this.getEconomyConfig().contains("Cost per kit")) this.getEconomyConfig().set("Cost per kit", null); - this.getEconomyConfig().options().copyDefaults(true); - this.getEconomyConfig().options().copyHeader(true); - this.saveEconomyConfig(); - - this.configValues.vaultValues.useEconomy = this.getEconomyConfig().getBoolean("Use economy"); - - boolean useCostPerKit = this.getEconomyConfig().getBoolean("Enable cost per kit"); - if (useCostPerKit && !this.configValues.vaultValues.useEconomy) { - this.getEconomyConfig().set("Enable cost per kit", false); - this.saveEconomyConfig(); - this.reloadEconomyConfig(); - } - this.configValues.vaultValues.useCostPerKit = this.getEconomyConfig().getBoolean("Enable cost per kit"); - - boolean useCostPerRefill = this.getEconomyConfig().getBoolean("Enable cost per refill"); - if (useCostPerRefill && !this.configValues.vaultValues.useEconomy) { - this.getEconomyConfig().set("Enable cost per refill", false); - this.saveEconomyConfig(); - this.reloadEconomyConfig(); - } - this.configValues.vaultValues.useCostPerRefill = this.getEconomyConfig().getBoolean("Enable cost per refill"); - - this.configValues.vaultValues.costPerRefill = this.getEconomyConfig().getDouble("Cost per refill"); - - boolean useMoneyPerKill = this.getEconomyConfig().getBoolean("Enable money per kill"); - if (useMoneyPerKill && !this.configValues.vaultValues.useEconomy) { - this.getEconomyConfig().set("Enable money per kill", false); - this.saveEconomyConfig(); - this.reloadEconomyConfig(); - } - this.configValues.vaultValues.useMoneyPerKill = this.getEconomyConfig().getBoolean("Enable money per kill"); - this.configValues.vaultValues.moneyPerKill = this.getEconomyConfig().getDouble("Money per kill"); - - boolean useMoneyPerDeath = this.getEconomyConfig().getBoolean("Enable money per death"); - if (useMoneyPerDeath && !this.configValues.vaultValues.useEconomy) { - this.getEconomyConfig().set("Enable money per death", false); - this.saveEconomyConfig(); - this.reloadEconomyConfig(); - } - this.configValues.vaultValues.useMoneyPerDeath = this.getEconomyConfig().getBoolean("Enable money per death"); - this.configValues.vaultValues.moneyPerDeath = this.getEconomyConfig().getDouble("Money per death"); - } - - private void loadKillstreaks() { - this.getKillstreaksConfig().options().header("KingKits Killstreak Configuration"); - this.getKillstreaksConfig().addDefault("First run", true); - if (this.getKillstreaksConfig().getBoolean("First run")) { - this.getKillstreaksConfig().set("Killstreak 9001", Arrays.asList("broadcast &c&a's killstreak is over 9000!", "msg Well done!")); - this.getKillstreaksConfig().set("First run", false); - } - this.getKillstreaksConfig().options().copyDefaults(true); - this.getKillstreaksConfig().options().copyHeader(true); - this.saveKillstreaksConfig(); - } - - public boolean checkConfig() { - String scoreChatPrefix = this.getConfig().getString("Score chat prefix"); - if (!scoreChatPrefix.contains("")) { - this.getConfig().set("Score chat prefix", "&6[&a&6]"); - this.saveConfig(); - return false; - } - return true; - } - - private void setupPermissions(boolean unregisterFirst) { - if (unregisterFirst) { - try { - List kitNames = new ArrayList(this.getKitsConfig().getKeys(false)); - for (int pos = 0; pos < kitNames.size(); pos++) { - String kit = kitNames.get(pos); - if (kit.split(" ").length > 1) kit = kit.split(" ")[0]; - try { - this.getServer().getPluginManager().removePermission(new Permission("kingkits.kits." + kit.toLowerCase())); - } catch (Exception ex) { - } - } - } catch (Exception ex) { - } - } - try { - List kitNames = new ArrayList(this.getKitsConfig().getKeys(false)); - for (int pos = 0; pos < kitNames.size(); pos++) { - String kit = kitNames.get(pos); - if (kit.split(" ").length > 1) kit = kit.split(" ")[0]; - try { - this.getServer().getPluginManager().addPermission(new Permission("kingkits.kits." + kit.toLowerCase())); - } catch (Exception ex) { - this.getLogger().info("Couldn't register the permission node: " + "kingkits.kits." + kit.toLowerCase()); - this.getLogger().info("This error probably occurred because it's already registered."); - } - } - } catch (Exception ex) { - } - } - - public String getEconomyMessage(double amount) { - this.reloadEconomyConfig(); - String message = this.getEconomyConfig().getString("Message"); - String currency = this.getEconomyConfig().getString("Currency"); - if (amount == 1) { - if (currency.contains("s")) { - if (currency.lastIndexOf('s') == message.length()) currency = this.replaceLast(currency, "s", ""); - } - } - message = message.replace("", currency); - message = message.replace("", String.valueOf(amount)); - return Utils.replaceChatColour(message); - } - - public List getConfigKitList() { - List configKeys = new ArrayList(this.getKitsConfig().getKeys(false)); - configKeys.remove("First run"); - return configKeys; - } - - public long getCooldown(String playerName, String kitName) { - if (playerName != null && kitName != null && this.kitList.containsKey(kitName) && this.getCooldownConfig().contains(playerName)) { - Object objCooldownPlayer = this.getCooldownConfig().get(playerName); - Map playerKitCooldowns = objCooldownPlayer instanceof ConfigurationSection ? ((ConfigurationSection) objCooldownPlayer).getValues(false) : (objCooldownPlayer instanceof Map ? (Map) objCooldownPlayer : new HashMap()); - if (playerKitCooldowns.containsKey(kitName)) { - String strPlayerCooldown = playerKitCooldowns.get(kitName) != null ? playerKitCooldowns.get(kitName).toString() : null; - if (!Utils.isLong(strPlayerCooldown)) { - this.getCooldownConfig().set(playerName + "." + kitName, null); - this.saveCooldownConfig(); - } else { - return Long.parseLong(strPlayerCooldown); - } - } - } - return System.currentTimeMillis(); - } - - public Map getCooldowns(String playerName) { - Map kitCooldowns = new HashMap(); - if (playerName != null && this.getCooldownConfig().contains(playerName)) { - Object objCooldownPlayer = this.getCooldownConfig().get(playerName); - Map configKitCooldowns = objCooldownPlayer instanceof ConfigurationSection ? ((ConfigurationSection) objCooldownPlayer).getValues(false) : (objCooldownPlayer instanceof Map ? (Map) objCooldownPlayer : new HashMap()); - for (Entry kitEntry : configKitCooldowns.entrySet()) { - String strPlayerCooldown = kitEntry.getValue().toString(); - if (!Utils.isLong(strPlayerCooldown)) { - this.getCooldownConfig().set(playerName + "." + strPlayerCooldown, null); - this.saveCooldownConfig(); - } else { - kitCooldowns.put(kitEntry.getKey(), Long.parseLong(strPlayerCooldown)); - } - } - } - return kitCooldowns; - } - - public List getKitList() { - return new ArrayList(this.kitList.keySet()); - } - - public List getKitList(String playerName) { - List kitList = this.userKitList.get(playerName); - List strKitList = new ArrayList(); - if (kitList != null) { - for (Kit kit : kitList) { - if (kit != null) strKitList.add(kit.getRealName()); - } - } - return strKitList; - } - - public String getMPKMessage(Player killer, double amount) { - this.reloadEconomyConfig(); - String message = this.getEconomyConfig().getString("Money per kill message"); - String currency = this.getEconomyConfig().getString("Currency"); - if (amount == 1) { - if (currency.contains("s")) { - if (currency.lastIndexOf('s') == message.length() - 1) currency = this.replaceLast(currency, "s", ""); - } - } - message = message.replace("", currency); - message = message.replace("", String.valueOf(amount)); - message = message.replace("", killer.getName()); - return Utils.replaceChatColour(message); - } - - public String getMPDMessage(Player dead, double amount) { - this.reloadEconomyConfig(); - String message = this.getEconomyConfig().getString("Money per death message"); - String currency = this.getEconomyConfig().getString("Currency"); - if (amount == 1) { - if (currency.contains("s")) { - if (currency.lastIndexOf('s') == message.length() - 1) currency = this.replaceLast(currency, "s", ""); - } - } - message = message.replace("", currency); - message = message.replace("", String.valueOf(amount)); - message = message.replace("", dead.getKiller().getName()); - return Utils.replaceChatColour(message); - } - - private String replaceLast(String s, String character, String targetChar) { - String string = s; - if (string.contains(character)) { - StringBuilder b = new StringBuilder(string); - b.replace(string.lastIndexOf(character), string.lastIndexOf(character) + 1, targetChar); - string = b.toString(); - } - return string; - } - - private FileConfiguration kitsConfig = null; - private File customKitsConfig = null; - - public void reloadKitsConfig() { - if (this.customKitsConfig == null) this.customKitsConfig = new File(this.getDataFolder(), "kits.yml"); - try { - this.kitsConfig = this.loadConfigSafely(this.customKitsConfig); - } catch (Exception ex) { - ex.printStackTrace(); - if (this.customKitsConfig.exists()) { - File kitDestination = new File(this.getDataFolder(), "kits.broken.yml"); - if (kitDestination.exists()) { - try { - kitDestination.delete(); - } catch (Exception ex2) { - } - } - FileUtil.copy(this.customKitsConfig, kitDestination); - try { - this.customKitsConfig.delete(); - } catch (Exception ex2) { - } - } - try { - this.customKitsConfig.createNewFile(); - this.kitsConfig = this.loadConfigSafely(this.customKitsConfig); - } catch (Exception ex2) { - } - } - } - - public FileConfiguration getKitsConfig() { - if (this.kitsConfig == null || this.customKitsConfig == null) this.reloadKitsConfig(); - return this.kitsConfig; - } - - public void saveKitsConfig() { - if (this.kitsConfig == null || this.customKitsConfig == null) return; - try { - this.getKitsConfig().save(this.customKitsConfig); - } catch (IOException ex) { - this.getLogger().log(Level.SEVERE, "Could not save the Kits config as " + this.customKitsConfig.getName(), ex); - } - } - - private FileConfiguration scoresConfig = null; - private File customScoresConfig = null; - - public void reloadScoresConfig() { - if (this.customScoresConfig == null) this.customScoresConfig = new File(this.getDataFolder(), "scores.yml"); - this.scoresConfig = this.loadConfigSafely(this.customScoresConfig); - } - - public FileConfiguration getScoresConfig() { - if (this.scoresConfig == null || this.customScoresConfig == null) this.reloadScoresConfig(); - return this.scoresConfig; - } - - public void saveScoresConfig() { - if (this.scoresConfig == null || this.customScoresConfig == null) return; - try { - this.getScoresConfig().save(this.customScoresConfig); - } catch (IOException ex) { - this.getLogger().log(Level.SEVERE, "Could not save the Scores config as " + this.customScoresConfig.getName(), ex); - } - } - - private FileConfiguration economyConfig = null; - private File customEconomyConfig = null; - - public void reloadEconomyConfig() { - if (this.customEconomyConfig == null) this.customEconomyConfig = new File(this.getDataFolder(), "economy.yml"); - this.economyConfig = this.loadConfigSafely(this.customEconomyConfig); - } - - public FileConfiguration getEconomyConfig() { - if (this.economyConfig == null || this.customEconomyConfig == null) this.reloadEconomyConfig(); - return this.economyConfig; - } - - public void saveEconomyConfig() { - if (this.economyConfig == null || this.customEconomyConfig == null) return; - try { - this.getEconomyConfig().save(this.customEconomyConfig); - } catch (IOException ex) { - this.getLogger().log(Level.SEVERE, "Could not save the Economy config as " + this.customEconomyConfig.getName(), ex); - } - } - - private FileConfiguration killstreaksConfig = null; - private File customKillstreaksConfig = null; - - public void reloadKillstreaksConfig() { - if (this.customKillstreaksConfig == null) - this.customKillstreaksConfig = new File(this.getDataFolder(), "killstreaks.yml"); - this.killstreaksConfig = this.loadConfigSafely(this.customKillstreaksConfig); - } - - public FileConfiguration getKillstreaksConfig() { - if (this.killstreaksConfig == null || this.customKillstreaksConfig == null) this.reloadKillstreaksConfig(); - return this.killstreaksConfig; - } - - public void saveKillstreaksConfig() { - if (this.killstreaksConfig == null || this.customKillstreaksConfig == null) return; - try { - this.getKillstreaksConfig().save(this.customKillstreaksConfig); - } catch (IOException ex) { - this.getLogger().log(Level.SEVERE, "Could not save the Killstreaks config as " + this.customKillstreaksConfig.getName(), ex); - } - } - - private FileConfiguration cooldownConfig = null; - private File customCooldownConfig = null; - - public void reloadCooldownConfig() { - if (this.customCooldownConfig == null) - this.customCooldownConfig = new File(this.getDataFolder(), "cooldown.yml"); - this.cooldownConfig = this.loadConfigSafely(this.customCooldownConfig); - } - - public FileConfiguration getCooldownConfig() { - if (this.cooldownConfig == null || this.customCooldownConfig == null) this.reloadCooldownConfig(); - return this.cooldownConfig; - } - - public void saveCooldownConfig() { - if (this.cooldownConfig == null || this.customCooldownConfig == null) return; - try { - this.cooldownConfig.save(this.customCooldownConfig); - } catch (IOException ex) { - this.getLogger().log(Level.SEVERE, "Could not save the cooldown config as " + this.customCooldownConfig.getName(), ex); - } - } - - private FileConfiguration userKitsConfig = null; - private File customUserKitsConfig = null; - - public void reloadUserKitsConfig() { - if (this.customUserKitsConfig == null) - this.customUserKitsConfig = new File(this.getDataFolder(), "userkits.yml"); - this.userKitsConfig = this.loadConfigSafely(this.customUserKitsConfig); - } - - public FileConfiguration getUserKitsConfig() { - if (this.userKitsConfig == null || this.customUserKitsConfig == null) this.reloadUserKitsConfig(); - return this.userKitsConfig; - } - - public void saveUserKitsConfig() { - if (this.userKitsConfig == null || this.customUserKitsConfig == null) return; - try { - this.userKitsConfig.save(this.customUserKitsConfig); - } catch (IOException ex) { - this.getLogger().log(Level.SEVERE, "Could not save the user kits config as " + this.customUserKitsConfig.getName(), ex); - } - } - - private FileConfiguration loadConfigSafely(File configFile) { - try { - return customLoadConfiguration(configFile); - } catch (Exception ex) { - if (ex.getClass() != FileNotFoundException.class) - this.getServer().getLogger().log(Level.SEVERE, "Cannot load " + configFile, ex); - if (configFile.exists()) { - String filePath = configFile.getAbsolutePath(); - String brokenFilePath = filePath.substring(0, filePath.indexOf(".yml")) + "-" + System.currentTimeMillis() + ".yml.broken"; - File configDestination = new File(brokenFilePath); - try { - FileInputStream configFileInputStream = new FileInputStream(configFile); - Files.copy(configFileInputStream, configDestination.toPath(), StandardCopyOption.REPLACE_EXISTING); - configFileInputStream.close(); - configFile.delete(); - } catch (Exception ex2) { - } - } else { - } - try { - configFile.createNewFile(); - return customLoadConfiguration(configFile); - } catch (Exception ex2) { - } - } - return YamlConfiguration.loadConfiguration(new File(this.getDataFolder(), "temp" + System.currentTimeMillis() + ".yml")); - } - - /** - * Reloads all the configurations * - */ - public void reloadAllConfigs() { - this.reloadConfig(); - this.reloadKitsConfig(); - this.reloadUserKitsConfig(); - - this.reloadScoresConfig(); - this.reloadEconomyConfig(); - this.reloadKillstreaksConfig(); - this.reloadCooldownConfig(); - } - - private void convertOldConfig() { - File kitsFolder = new File(this.getDataFolder(), "kits"); - if (kitsFolder.exists() && kitsFolder.isDirectory()) { - File oldKitsFile = new File(kitsFolder, "config.yml"); - FileConfiguration oldKitsFileConfig = YamlConfiguration.loadConfiguration(oldKitsFile); - File oldCPKFile = new File(kitsFolder, "costperkit.yml"); - FileConfiguration oldCPKFileConfig = YamlConfiguration.loadConfiguration(oldCPKFile); - File oldDyesFile = new File(kitsFolder, "dyes.yml"); - FileConfiguration oldDyesFileConfig = YamlConfiguration.loadConfiguration(oldDyesFile); - File oldEnchantmentsFile = new File(kitsFolder, "enchantments.yml"); - FileConfiguration oldEnchantmentsFileConfig = YamlConfiguration.loadConfiguration(oldEnchantmentsFile); - File oldGUIFile = new File(kitsFolder, "guiitems.yml"); - FileConfiguration oldGUIFileConfig = YamlConfiguration.loadConfiguration(oldGUIFile); - File oldLoresFile = new File(kitsFolder, "lores.yml"); - FileConfiguration oldLoresFileConfig = YamlConfiguration.loadConfiguration(oldLoresFile); - File oldPotionsFile = new File(kitsFolder, "potions.yml"); - FileConfiguration oldPotionsFileConfig = YamlConfiguration.loadConfiguration(oldPotionsFile); - - List kitList = oldKitsFileConfig.getStringList("Kits"); - if (kitList != null) { - for (String kitName : kitList) { - if (oldKitsFileConfig.contains(kitName)) { - Kit kit = new Kit(kitName).setRealName(kitName); - List kitItems = new ArrayList(), kitArmour = new ArrayList(); - List strKitItems = oldKitsFileConfig.getStringList(kitName); - for (String strKitItem : strKitItems) { - String[] kitSplit = strKitItem.contains(" ") ? strKitItem.split(" ") : null; - if (kitSplit != null) { - if (kitSplit.length >= 3) { - String strID = kitSplit[0]; - if (Utils.isInteger(strID)) { - int itemID = Integer.parseInt(strID); - int itemAmount = Utils.isInteger(kitSplit[1]) ? Integer.parseInt(kitSplit[1]) : 1; - short itemData = Utils.isShort(kitSplit[2]) ? Short.parseShort(kitSplit[2]) : (short) 0; - try { - ItemStack kitItem = new ItemStack(itemID, itemAmount, itemData); - if (kitSplit.length > 3) { - StringBuilder sbKitItemName = new StringBuilder(); - for (int kitSplitIndex = 3; kitSplitIndex < kitSplit.length; kitSplitIndex++) { - sbKitItemName.append(kitSplit[kitSplitIndex] + " "); - } - String kitItemName = sbKitItemName.toString().trim(); - if (!kitItemName.isEmpty()) { - if (kitItem.hasItemMeta()) { - ItemMeta kitMeta = kitItem.getItemMeta(); - kitMeta.setDisplayName(Utils.replaceChatColour(kitItemName)); - kitItem.setItemMeta(kitMeta); - } - } - } - if (oldDyesFileConfig.contains(kitName + " " + kitItem.getType().getId())) { - int itemDye = oldDyesFileConfig.getInt(kitName + " " + kitItem.getType().getId()); - if (kitItem.hasItemMeta()) { - ItemMeta kitItemMeta = kitItem.getItemMeta(); - if (kitItemMeta instanceof LeatherArmorMeta) { - LeatherArmorMeta kitItemLeatherArmorMeta = (LeatherArmorMeta) kitItemMeta; - Color targetDyeColor = Color.fromRGB(itemDye); - if (targetDyeColor != null) { - kitItemLeatherArmorMeta.setColor(targetDyeColor); - kitItem.setItemMeta(kitItemLeatherArmorMeta); - } - } - } - } - if (oldEnchantmentsFileConfig.contains(kitName + " " + kitItem.getType().getId())) { - List itemEnchantments = oldEnchantmentsFileConfig.getStringList(kitName + " " + kitItem.getType().getId()); - if (itemEnchantments != null) { - for (String itemEnchantment : itemEnchantments) { - if (itemEnchantment.contains(" ")) { - String[] enchantmentSplit = itemEnchantment.split(" "); - if (enchantmentSplit.length >= 2) { - String enchantmentName = enchantmentSplit[0]; - Enchantment targetEnchantment = Utils.isInteger(enchantmentName) ? Enchantment.getById(Integer.parseInt(enchantmentName)) : Enchantment.getByName(enchantmentName); - if (targetEnchantment != null) { - int targetLevel = Utils.isInteger(enchantmentSplit[1]) ? Integer.parseInt(enchantmentSplit[1]) : 1; - kitItem.addUnsafeEnchantment(targetEnchantment, targetLevel); - } - } - } - } - } - } - if (oldLoresFileConfig.contains(kitName + " " + kitItem.getType().getId())) { - List kitItemLores = oldLoresFileConfig.getStringList(kitName + " " + kitItem.getType().getId()); - if (kitItemLores != null) { - if (kitItem.hasItemMeta()) { - ItemMeta kitItemMeta = kitItem.getItemMeta(); - kitItemMeta.setLore(Utils.replaceChatColours(kitItemLores)); - kitItem.setItemMeta(kitItemMeta); - } - } - } - if (kitItem != null) { - if (kitArmour.size() < 4) { - String strKitType = kitItem.getType().toString().toLowerCase(); - if (strKitType.endsWith("helmet") || strKitType.endsWith("chestplate") || strKitType.endsWith("leggings") || strKitType.endsWith("pants") || strKitType.endsWith("boots")) { - kitArmour.add(kitItem); - } else { - kitItems.add(kitItem); - } - } else { - kitItems.add(kitItem); - } - } - } catch (Exception ex) { - continue; - } - } - } - } - } - kit.setItems(kitItems); - kit.setArmour(kitArmour); - if (oldCPKFileConfig.contains(kitName)) kit.setCost(oldCPKFileConfig.getDouble(kitName, 0D)); - if (oldGUIFileConfig.contains(kitName)) { - int targetItemID = oldGUIFileConfig.getInt(kitName); - try { - kit.setGuiItem(new ItemStack(targetItemID)); - } catch (Exception ex) { - } - } - if (oldPotionsFileConfig.contains(kitName)) { - List kitPotionEffects = new ArrayList(); - List strPotions = oldPotionsFileConfig.getStringList(kitName); - if (strPotions != null) { - for (String strPotion : strPotions) { - if (strPotion.contains(" ")) { - String[] potionSplit = strPotion.split(" "); - if (potionSplit.length >= 3) { - String potionName = potionSplit[0]; - PotionEffectType potionEffectType = Utils.isInteger(potionName) ? PotionEffectType.getById(Integer.parseInt(potionName)) : PotionEffectType.getByName(potionName.toUpperCase()); - if (potionEffectType != null) { - int potionAmplifier = Utils.isInteger(potionSplit[1]) ? Integer.parseInt(potionSplit[1]) : Utils.romanNumeralToInteger(potionSplit[1]); - if (potionAmplifier == 0) potionAmplifier++; - else if (potionAmplifier < 0) potionAmplifier *= -1; - potionAmplifier--; - int potionDuration = Utils.isInteger(potionSplit[2]) ? Integer.parseInt(potionSplit[2]) : 10; - try { - kitPotionEffects.add(new PotionEffect(potionEffectType, potionDuration, potionAmplifier)); - } catch (Exception ex) { - continue; - } - } - } - } - } - kit.setPotionEffects(kitPotionEffects); - } - } - - this.getKitsConfig().set(kitName, kit.serialize()); - } - } - } - this.getKitsConfig().set("First run", this.getKitsConfig().getValues(false).isEmpty()); - if (!Utils.renameDirectory(kitsFolder, new File(this.getDataFolder(), "oldkits"))) { - if (!Utils.deleteDirectory(kitsFolder, kitsFolder.listFiles().length == 0)) - this.getLogger().log(Level.SEVERE, "Could not rename or delete the 'kits' folder in /plugins/KingKits. You must manually delete the folder and then reload KingKits to prevent configuration events."); - } - } - } - - public static KingKits getInstance() { - return pluginInstance; - } - - private static YamlConfiguration customLoadConfiguration(File file) throws Exception { - Validate.notNull(file, "File cannot be null"); - YamlConfiguration config = new YamlConfiguration(); - config.load(file); - return config; - } + private static KingKits pluginInstance = null; + + // Class variables + private KingKitsSQL kingKitsSQL = null; + public Permissions permissions = new Permissions(); + public CommandValues cmdValues = new CommandValues(); + public ConfigValues configValues = new ConfigValues(); + public Vault vault = new Vault(); + + // Plugin variables + public Map usingKits = null; + public Map playerKits = null; + public Map playerScores = null; + public Map compassTargets = null; + public Map playerKillstreaks = null; + + // Listeners + private EventListener playerListener = null; + private KingKitsCommand cmdKingKits = null; + private KitCommand cmdKitL = null; + private CreateKitCommand cmdKitC = null; + private DeleteKitCommand cmdKitD = null; + private RenameKitCommand cmdKitR = null; + private RefillCommand cmdRefill = null; + private CreateUserKitCommand cmdKitUC = null; + private DeleteUserKitCommand cmdKitUD = null; + private RenameUserKitCommand cmdKitUR = null; + + public Map kitList = null; + public Map> userKitList = null; + private int cooldownTaskID = -1; + + public void onEnable() { + pluginInstance = this; + + // Initialise all the collections + this.usingKits = new HashMap(); + this.playerKits = new HashMap(); + this.playerScores = new HashMap(); + this.compassTargets = new HashMap(); + this.playerKillstreaks = new HashMap(); + this.kitList = new HashMap(); + this.userKitList = new HashMap>(); + + // Initialise variables + ConfigurationSerialization.registerClass(Kit.class); + try { + this.loadConfiguration(); + } catch (Exception ex) { + ex.printStackTrace(); + } + try { + Lang.init(this); + } catch (Exception ex) { + ex.printStackTrace(); + } + + // Initialise commands + this.cmdKingKits = new KingKitsCommand(this); + this.cmdKitL = new KitCommand(this); + this.cmdKitC = new CreateKitCommand(this); + this.cmdKitD = new DeleteKitCommand(this); + this.cmdRefill = new RefillCommand(this); + this.cmdKitR = new RenameKitCommand(this); + this.cmdKitUC = new CreateUserKitCommand(this); + this.cmdKitUD = new DeleteUserKitCommand(this); + this.cmdKitUR = new RenameUserKitCommand(this); + + // Register commands + this.getCommand("kingkits").setExecutor(this.cmdKingKits); + this.getCommand("kingkits").setAliases(Arrays.asList("kk")); + this.getCommand("pvpkit").setExecutor(this.cmdKitL); + this.getCommand("createkit").setExecutor(this.cmdKitC); + this.getCommand("deletekit").setExecutor(this.cmdKitD); + this.getCommand("refill").setExecutor(this.cmdRefill); + this.getCommand("refill").setAliases(Arrays.asList("soup")); + this.getCommand("renamekit").setExecutor(this.cmdKitR); + this.getCommand("createukit").setExecutor(this.cmdKitUC); + this.getCommand("deleteukit").setExecutor(this.cmdKitUD); + this.getCommand("renameukit").setExecutor(this.cmdKitUR); + + // Register permissions + for (Permission registeredPerm : this.permissions.permissionsList) + this.getServer().getPluginManager().addPermission(registeredPerm); + for (int i = 1; i <= 54; i++) { + try { + this.getServer().getPluginManager().addPermission(new Permission("kingkits.kit.limit." + i)); + } catch (Exception ex) { + continue; + } + } + this.getServer().getPluginManager().registerEvents(this.playerListener = new EventListener(), this); + + // Check for updates + if (this.configValues.checkForUpdates) { + if (this.getServer().getVersion().contains("Spigot")) { + final int pluginID = 2209; + SpigotUpdater updater = new SpigotUpdater(this, pluginID, false); + if (updater.getResult() == SpigotUpdater.UpdateResult.UPDATE_AVAILABLE) { + String title = "============================================"; + String titleSpace = " "; + this.getLogger().info(title); + try { + this.getLogger().info(titleSpace.substring(0, titleSpace.length() / 2 - "KingKits".length() + 3) + "KingKits" + titleSpace.substring(0, titleSpace.length() / 2 - "KingKits".length())); + } catch (Exception ex) { + this.getServer().getConsoleSender().sendMessage("KingKits"); + } + this.getLogger().info(title); + this.getLogger().info("A new version is available: KingKits v" + updater.getVersion()); + this.getLogger().info("Your current version: KingKits v" + this.getDescription().getVersion()); + this.getLogger().info((this.configValues.automaticUpdates ? "Automatic updates do not work for Spigot. " : "") + "Download it from: http://www.spigotmc.org/threads/kingkits.37947"); + } + } else { + final int pluginID = 56371; + BukkitUpdater updater = new BukkitUpdater(this, pluginID, this.getFile(), BukkitUpdater.UpdateType.NO_DOWNLOAD, false); + if (updater.getResult() == BukkitUpdater.UpdateResult.UPDATE_AVAILABLE) { + String header = "============================================"; + String titleSpace = " "; + this.getLogger().info(header); + try { + this.getLogger().info(titleSpace.substring(0, titleSpace.length() / 2 - "KingKits".length() + 3) + "KingKits" + titleSpace.substring(0, titleSpace.length() / 2 - "KingKits".length())); + } catch (Exception ex) { + this.getServer().getConsoleSender().sendMessage("== KingKits =="); + } + this.getLogger().info(header); + this.getLogger().info("A new version is available: " + updater.getLatestName()); + this.getLogger().info("Your current version: KingKits v" + this.getDescription().getVersion()); + if (this.configValues.automaticUpdates) { + this.getLogger().info("Downloading " + updater.getLatestName() + "..."); + updater = new BukkitUpdater(this, pluginID, this.getFile(), BukkitUpdater.UpdateType.NO_VERSION_CHECK, false); + BukkitUpdater.UpdateResult updateResult = updater.getResult(); + switch (updateResult) { + case DISABLED: + this.getLogger().warning("Plugin updater disabled in the updater's configuration."); + case FAIL_APIKEY: + this.getLogger().warning("Download failed: Improperly configured the server's API key in the configuration"); + break; + case FAIL_DBO: + this.getLogger().warning("Download failed: Could not connect to BukkitDev."); + break; + case FAIL_DOWNLOAD: + this.getLogger().warning("Download failed: Could not download the file."); + break; + case FAIL_NOVERSION: + this.getLogger().warning("Download failed: The latest version has an incorrect title."); + break; + default: + this.getLogger().info("The latest version of KingKits has been downloaded."); + break; + } + } else { + this.getLogger().info("Download it from: " + updater.getLatestFileLink()); + } + } + } + } + + try { + new Metrics(this).start(); + } catch (Exception ex) { + this.getLogger().log(Level.WARNING, "Could not start metrics due to a(n) " + ex.getClass().getSimpleName() + " error.", ex); + } + } + + public void onDisable() { + this.getServer().getScheduler().cancelTasks(this); + + if (this.kingKitsSQL != null) { + this.kingKitsSQL.onDisable(); + this.kingKitsSQL = null; + } + + // Clear inventories on reload + if (this.configValues.clearInvsOnReload) { + for (Player target : Utilities.getOnlinePlayers()) { + if (KingKitsAPI.hasKit(target.getName(), false)) { + target.getInventory().clear(); + target.getInventory().setArmorContents(null); + target.setMaxHealth(20D); + for (PotionEffect potionEffect : target.getActivePotionEffects()) + target.removePotionEffect(potionEffect.getType()); + } + } + } + + ConfigurationSerialization.unregisterClass(Kit.class); + + // Clear all lists + this.usingKits = null; + this.playerKits = null; + this.playerScores = null; + this.compassTargets = null; + this.playerKillstreaks = null; + this.kitList = null; + this.userKitList = null; + + // Unregister all permissions + for (Permission registeredPerm : this.permissions.permissionsList) + this.getServer().getPluginManager().removePermission(registeredPerm); + for (int i = 1; i <= 54; i++) { + try { + this.getServer().getPluginManager().removePermission(new Permission("kingkits.kit.limit." + i)); + } catch (Exception ex) { + continue; + } + } + + try { + for (Entry playerEntry : GuiKingKits.guiKitMenuMap.entrySet()) { + playerEntry.getValue().closeMenu(true, this.getServer().getPlayerExact(playerEntry.getKey()) != null); + } + GuiKingKits.guiKitMenuMap.clear(); + } catch (Exception ex) { + ex.printStackTrace(); + } + try { + for (Entry playerEntry : GuiKingKits.guiPreviewKitMap.entrySet()) { + playerEntry.getValue().closeMenu(true, this.getServer().getPlayerExact(playerEntry.getKey()) != null); + } + GuiKingKits.guiPreviewKitMap.clear(); + } catch (Exception ex) { + ex.printStackTrace(); + } + + this.permissions = null; + + pluginInstance = null; + } + + // Load Configurations + public void loadConfiguration() throws Exception { + try { + if (this.cooldownTaskID != -1 && this.getServer().getScheduler().isQueued(this.cooldownTaskID)) + this.getServer().getScheduler().cancelTask(this.cooldownTaskID); + if (KingKitsSQL.isInitialised() || KingKitsSQL.isOpen()) KingKitsSQL.closeConnection(); + this.getConfig().options().header("KingKits Configuration"); + this.getConfig().addDefault("Op bypass", true); + this.getConfig().addDefault("MySQL.Enabled", false); + this.getConfig().addDefault("MySQL.Host", "127.0.0.1"); + this.getConfig().addDefault("MySQL.Port", 3306); + this.getConfig().addDefault("MySQL.Username", "root"); + this.getConfig().addDefault("MySQL.Password", ""); + this.getConfig().addDefault("MySQL.Database", "kingkits"); + this.getConfig().addDefault("MySQL.Table prefix", "kk_"); + this.getConfig().addDefault("GUI.Title", "PvP Kits"); + this.getConfig().addDefault("GUI.Size", 36); + this.getConfig().addDefault("PvP Worlds", Arrays.asList("All")); + this.getConfig().addDefault("Multiple world inventories plugin", "Multiverse-Inventories"); + this.getConfig().addDefault("Multi-inventories", this.getServer().getPluginManager().isPluginEnabled(this.getConfig().getString("Multiple world inventories plugin"))); + this.getConfig().addDefault("Enable kits command", true); + this.getConfig().addDefault("Enable create kits command", true); + this.getConfig().addDefault("Enable delete kits command", true); + this.getConfig().addDefault("Enable rename kits command", true); + this.getConfig().addDefault("Enable create user kits command", true); + this.getConfig().addDefault("Enable delete user kits command", true); + this.getConfig().addDefault("Enable rename user kits command", true); + this.getConfig().addDefault("Enable refill command", true); + this.getConfig().addDefault("Kit sign", "[Kit]"); + this.getConfig().addDefault("Kit list sign", "[KList]"); + this.getConfig().addDefault("Kit sign valid", "[&1Kit&0]"); + this.getConfig().addDefault("Kit sign invalid", "[&cKit&0]"); + this.getConfig().addDefault("Kit list sign valid", "[&1KList&0]"); + this.getConfig().addDefault("Kit cooldown enabled", false); + if (this.getConfig().contains("Kit cooldown")) this.getConfig().set("Kit cooldown", null); + this.getConfig().addDefault("List kits on join", true); + this.getConfig().addDefault("Use permissions on join", true); + this.getConfig().addDefault("Use permissions for kit list", true); + this.getConfig().addDefault("Kit list mode", "Text"); + this.getConfig().addDefault("Sort kits alphabetically", true); + this.getConfig().addDefault("Remove items on leave", true); + this.getConfig().addDefault("Drop items on death", false); + this.getConfig().addDefault("Drop items", false); + this.getConfig().addDefault("Drop animations", Arrays.asList(Material.BOWL.getId())); + this.getConfig().addDefault("Allow picking up items", true); + this.getConfig().addDefault("Clear inventories on reload", true); + this.getConfig().addDefault("One kit per life", false); + this.getConfig().addDefault("Check for updates", true); + this.getConfig().addDefault("Automatically update", false); + this.getConfig().addDefault("Enable score", false); + this.getConfig().addDefault("Score chat prefix", "&6[&a&6]"); + this.getConfig().addDefault("Score per kill", 2); + this.getConfig().addDefault("Max score", Integer.MAX_VALUE); + this.getConfig().addDefault("Remove potion effects on leave", true); + this.getConfig().addDefault("Set compass target to nearest player", true); + this.getConfig().addDefault("Quick soup", true); + this.getConfig().addDefault("Quick soup heal", 2.5D); + this.getConfig().addDefault("Requires kit to use refill", true); + this.getConfig().addDefault("Command to run when changing kits", ""); + this.getConfig().addDefault("Disable block placing and breaking", false); + this.getConfig().addDefault("Disable death messages", false); + this.getConfig().addDefault("Lock hunger level", true); + this.getConfig().addDefault("Hunger lock", 20); + this.getConfig().addDefault("Custom message", "&6You have chosen the kit &c&6."); + this.getConfig().addDefault("Disable gamemode while using a kit", false); + this.getConfig().addDefault("Enable killstreaks", false); + this.getConfig().addDefault("Disable item breaking", true); + this.getConfig().addDefault("Kit menu on join", false); + this.getConfig().addDefault("Clear items on kit creation", true); + this.getConfig().addDefault("Kit particle effects", false); + this.getConfig().addDefault("Show kit preview", false); + this.getConfig().addDefault("Replace items when selecting a kit", true); + if (this.getConfig().contains("Scoreboards")) this.getConfig().set("Scoreboards", null); + if (this.getConfig().contains("Scoreboard title")) this.getConfig().set("Scoreboard title", null); + this.getConfig().options().copyDefaults(true); + this.getConfig().options().copyHeader(true); + this.saveConfig(); + + this.configValues.opBypass = this.getConfig().getBoolean("Op bypass"); + this.configValues.pvpWorlds = this.getConfig().getStringList("PvP Worlds"); + this.configValues.multiInvsPlugin = this.getConfig().getString("Multiple world inventories plugin"); + this.configValues.multiInvs = this.getConfig().getBoolean("Multi-inventories"); + if (!this.configValues.multiInvs && this.getServer().getPluginManager().isPluginEnabled(this.getConfig().getString("Multiple world inventories plugin"))) { + this.configValues.multiInvs = true; + this.getConfig().set("Multi-inventories", true); + this.saveConfig(); + } + this.cmdValues.pvpKits = this.getConfig().getBoolean("Enable kits command"); + this.cmdValues.createKits = this.getConfig().getBoolean("Enable create kits command"); + this.cmdValues.deleteKits = this.getConfig().getBoolean("Enable delete kits command"); + this.cmdValues.renameKits = this.getConfig().getBoolean("Enable rename kits command"); + this.cmdValues.createUKits = this.getConfig().getBoolean("Enable create user kits command"); + this.cmdValues.deleteUKits = this.getConfig().getBoolean("Enable delete user kits command"); + this.cmdValues.renameUKits = this.getConfig().getBoolean("Enable rename user kits command"); + this.cmdValues.refillKits = this.getConfig().getBoolean("Enable refill command"); + this.configValues.strKitSign = Utilities.replaceChatColour(this.getConfig().getString("Kit sign")); + this.configValues.strKitListSign = Utilities.replaceChatColour(this.getConfig().getString("Kit list sign")); + this.configValues.strKitSignValid = Utilities.replaceChatColour(this.getConfig().getString("Kit sign valid")); + this.configValues.strKitSignInvalid = Utilities.replaceChatColour(this.getConfig().getString("Kit sign invalid")); + this.configValues.strKitListSignValid = Utilities.replaceChatColour(this.getConfig().getString("Kit list sign valid")); + this.configValues.kitCooldown = this.getConfig().getBoolean("Kit cooldown enabled"); + this.configValues.listKitsOnJoin = this.getConfig().getBoolean("List kits on join"); + this.configValues.kitListMode = this.getConfig().getString("Kit list mode"); + this.configValues.sortAlphabetically = this.getConfig().getBoolean("Sort kits alphabetically"); + this.configValues.kitListPermissionsJoin = this.getConfig().getBoolean("Use permissions on join"); + this.configValues.kitListPermissions = this.getConfig().getBoolean("Use permissions for kit list"); + this.configValues.removeItemsOnLeave = this.getConfig().getBoolean("Remove items on leave"); + this.configValues.dropItemsOnDeath = this.getConfig().getBoolean("Drop items on death"); + this.configValues.dropItems = this.getConfig().getBoolean("Drop items"); + this.configValues.dropAnimations = this.getConfig().getIntegerList("Drop animations"); + this.configValues.allowPickingUpItems = this.getConfig().getBoolean("Allow picking up items"); + this.configValues.clearInvsOnReload = this.getConfig().getBoolean("Clear inventories on reload"); + this.configValues.oneKitPerLife = this.getConfig().getBoolean("One kit per life"); + this.configValues.checkForUpdates = this.getConfig().getBoolean("Check for updates"); + this.configValues.automaticUpdates = this.getConfig().getBoolean("Automatically update"); + this.configValues.removePotionEffectsOnLeave = this.getConfig().getBoolean("Remove potion effects on leave"); + this.configValues.rightClickCompass = this.getConfig().getBoolean("Set compass target to nearest player"); + this.configValues.quickSoup = this.getConfig().getBoolean("Quick soup"); + this.configValues.quickSoupHeal = (float) (Math.ceil(this.getConfig().getDouble("Quick soup heal") * 2) / 2); + this.configValues.quickSoupKitOnly = this.getConfig().getBoolean("Requires kit to use refill"); + this.configValues.banBlockBreakingAndPlacing = this.getConfig().getBoolean("Disable block placing and breaking"); + this.configValues.disableDeathMessages = this.getConfig().getBoolean("Disable death messages"); + this.configValues.lockHunger = this.getConfig().getBoolean("Lock hunger level"); + this.configValues.hungerLock = this.getConfig().getInt("Hunger lock"); + this.configValues.customMessages = this.getConfig().getString("Custom message"); + this.configValues.commandToRun = this.getConfig().getString("Command to run when changing kits"); + this.configValues.disableGamemode = this.getConfig().getBoolean("Disable gamemode while using a kit"); + this.configValues.killstreaks = this.getConfig().getBoolean("Enable killstreaks"); + this.configValues.disableItemBreaking = this.getConfig().getBoolean("Disable item breaking"); + this.configValues.kitMenuOnJoin = this.getConfig().getBoolean("Kit menu on join"); + this.configValues.removeItemsOnCreateKit = this.getConfig().getBoolean("Clear items on kit creation"); + this.configValues.kitParticleEffects = this.getConfig().getBoolean("Kit particle effects"); + this.configValues.showKitPreview = this.getConfig().getBoolean("Show kit preview"); + this.configValues.replaceItems = this.getConfig().getBoolean("Replace items when selecting a kit"); + + this.configValues.guiTitle = Utilities.replaceChatColour(this.getConfig().getString("GUI.Title")); + this.configValues.guiSize = this.getConfig().getInt("GUI.Size"); + if (this.configValues.guiSize <= 0 || this.configValues.guiSize % 9 != 0 || this.configValues.guiSize > 54) + this.configValues.guiSize = 36; + + + this.configValues.scores = this.getConfig().getBoolean("Enable score"); + this.configValues.scoreIncrement = this.getConfig().getInt("Score per kill"); + String scoreChatPrefix = this.getConfig().getString("Score chat prefix"); + if (!scoreChatPrefix.contains("")) { + this.getConfig().set("Score chat prefix", "&6[&a&6]"); + this.saveConfig(); + } + this.configValues.scoreFormat = this.getConfig().getString("Score chat prefix"); + this.configValues.maxScore = this.getConfig().getInt("Max score"); + + this.loadMySQL(); + this.loadPvPKits(); + this.loadUserKits(); + this.loadScores(); + this.loadEconomy(); + this.loadKillstreaks(); + + for (Player onlinePlayer : Utilities.getOnlinePlayers()) { + Scoreboard playerScoreboard = onlinePlayer.getScoreboard(); + if (playerScoreboard != null) { + if (playerScoreboard.getObjective("KingKits") != null) { + playerScoreboard.resetScores(Bukkit.getOfflinePlayer(ChatColor.GREEN + "Score:")); + playerScoreboard.resetScores(Bukkit.getOfflinePlayer(ChatColor.GREEN + "Killstreak:")); + playerScoreboard.clearSlot(DisplaySlot.SIDEBAR); + if (playerScoreboard.getObjectives().isEmpty()) + onlinePlayer.setScoreboard(this.getServer().getScoreboardManager().getNewScoreboard()); + else onlinePlayer.setScoreboard(playerScoreboard); + } + } + } + + if (this.configValues.kitCooldown) { + this.cooldownTaskID = this.getServer().getScheduler().runTaskTimer(this, new Runnable() { + public void run() { + boolean hasBeenModified = false; + for (Map.Entry configEntrySet : getCooldownConfig().getValues(false).entrySet()) { + Map playerMap = null; + if (configEntrySet.getValue() instanceof ConfigurationSection) + playerMap = ((ConfigurationSection) configEntrySet.getValue()).getValues(false); + else if (configEntrySet.getValue() instanceof Map) + playerMap = (Map) configEntrySet.getValue(); + if (playerMap != null) { + for (Map.Entry entrySet : playerMap.entrySet()) { + String strValue = entrySet.getValue().toString(); + if (Utilities.isLong(strValue)) { + Kit targetKit = kitList.get(entrySet.getKey()); + if (targetKit != null) { + long kitCooldown = targetKit.getCooldown(); + long playerCooldown = Long.parseLong(strValue); + if (System.currentTimeMillis() - playerCooldown >= kitCooldown * 1000) { + getCooldownConfig().set(configEntrySet.getKey() + "." + entrySet.getKey(), null); + if (playerMap.size() == 1) + getCooldownConfig().set(configEntrySet.getKey(), null); + hasBeenModified = true; + } + } + } + } + } + } + if (hasBeenModified) saveCooldownConfig(); + } + }, 1200L, 1200L).getTaskId(); + } + } catch (Exception ex) { + throw ex; + } + } + + private void loadMySQL() { + if (KingKitsSQL.isOpen()) KingKitsSQL.closeConnection(); + KingKitsSQL.sqlEnabled = this.getConfig().getBoolean("MySQL.Enabled", false); + this.kingKitsSQL = new KingKitsSQL(this.getConfig().getString("MySQL.Host", "127.0.0.1"), this.getConfig().getInt("MySQL.Port", 3306), this.getConfig().getString("MySQL.Username", "root"), this.getConfig().getString("MySQL.Password", ""), this.getConfig().getString("MySQL.Database", "kingkits"), this.getConfig().getString("MySQL.Table prefix", "kk_")); + } + + private void loadPvPKits() { + try { + this.getKitsConfig().options().header("KingKits Kits Configuration."); + this.getKitsConfig().addDefault("First run", true); + if (this.getKitsConfig().getBoolean("First run")) { + Kit defaultKit = new Kit("Default").setRealName("Default").setCommands(Arrays.asList("feed ", "tell &6You have been fed for using the default kit.")); + List defaultKitItems = new ArrayList(), defaultKitArmour = new ArrayList(); + + ItemStack defaultSword = new ItemStack(Material.IRON_SWORD); + defaultSword.addEnchantment(Enchantment.DURABILITY, 3); + defaultKitItems.add(Utilities.ItemUtils.setLores(Utilities.ItemUtils.setName(defaultSword, "Default Kit Sword"), Arrays.asList("&6Iron Slayer"))); + defaultKitItems.add(new ItemStack(Material.GOLDEN_APPLE, 2)); + defaultKitArmour.add(new ItemStack(Material.IRON_HELMET)); + defaultKitArmour.add(Utilities.ItemUtils.setDye(new ItemStack(Material.LEATHER_CHESTPLATE), 10040115)); + defaultKitArmour.add(new ItemStack(Material.IRON_LEGGINGS)); + defaultKitArmour.add(new ItemStack(Material.IRON_BOOTS)); + defaultKitItems.add(new ItemStack(Material.POTION, 1, (short) 8201)); + + defaultKit.setItems(defaultKitItems); + defaultKit.setArmour(defaultKitArmour); + defaultKit.setPotionEffects(Arrays.asList(new PotionEffect(PotionEffectType.SPEED, 200, 1))); + + this.getKitsConfig().addDefault("Default", defaultKit.serialize()); + this.getKitsConfig().set("First run", false); + } + this.getKitsConfig().options().copyDefaults(true); + this.getKitsConfig().options().copyHeader(true); + this.saveKitsConfig(); + + this.kitList.clear(); + List kitList = this.getConfigKitList(); + for (String kitName : kitList) { + try { + Object objKitConfigSection = this.getKitsConfig().get(kitName); + Kit kit = null; + if (objKitConfigSection instanceof ConfigurationSection) + kit = Kit.deserialize(((ConfigurationSection) objKitConfigSection).getValues(false)); + else if (objKitConfigSection instanceof Map) + kit = Kit.deserialize((Map) objKitConfigSection); + if (kit != null) this.kitList.put(kitName, kit.setRealName(kitName).setUserKit(false)); + else + this.getLogger().warning("Could not register the kit '" + kitName + "' it has been invalidly defined in the configuration."); + } catch (Exception ex) { + this.getLogger().warning("Could not register the kit '" + kitName + "' due to a(n) " + ex.getClass().getSimpleName() + " error:"); + ex.printStackTrace(); + } + } + + this.setupPermissions(true); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + private void loadUserKits() { + try { + this.getUserKitsConfig().options().header("KingKits User Kits Configuration."); + this.getUserKitsConfig().options().copyHeader(true); + this.saveUserKitsConfig(); + + this.userKitList.clear(); + this.convertOldConfigUserKits(); + List userList = new ArrayList(this.getUserKitsConfig().getKeys(false)); + for (String strPlayerUUID : userList) { + UUID playerUUID = Utilities.isUUID(strPlayerUUID) ? UUID.fromString(strPlayerUUID) : null; + if (playerUUID == null) continue; + List userKits = new ArrayList(); + try { + for (Map.Entry kitEntry : this.getUserKitsConfig().getConfigurationSection(strPlayerUUID).getValues(false).entrySet()) { + try { + String kitName = kitEntry.getKey(); + Object objKitConfigSection = kitEntry.getValue(); + Kit kit = null; + if (objKitConfigSection instanceof ConfigurationSection) + kit = Kit.deserialize(((ConfigurationSection) objKitConfigSection).getValues(false)); + else if (objKitConfigSection instanceof Map) + kit = Kit.deserialize((Map) objKitConfigSection); + if (kit != null) userKits.add(kit.setRealName(kitName).setUserKit(true)); + } catch (Exception ex) { + continue; + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + if (!userKits.isEmpty()) this.userKitList.put(playerUUID, userKits); + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + private void loadScores() { + try { + this.getScoresConfig().options().header("KingKits Score Configuration"); + if (!this.getScoresConfig().contains("Scores")) + this.getScoresConfig().createSection("Scores", Collections.singletonMap(UUID.fromString("f9843dd6-0a5f-4009-b451-847291bda6b3"), 0)); + this.getScoresConfig().options().copyDefaults(true); + this.getScoresConfig().options().copyHeader(true); + this.saveScoresConfig(); + + Map scoresMap = this.getScoresConfig().getConfigurationSection("Scores").getValues(true); + List unconvertedScores = new ArrayList(); + for (Entry scoreEntry : scoresMap.entrySet()) { + if (!Utilities.isUUID(scoreEntry.getKey())) unconvertedScores.add(scoreEntry.getKey()); + } + boolean hasConverted = false; + try { + Map uuidList = UUIDFetcher.lookupNames(unconvertedScores); + for (Entry uuidEntry : uuidList.entrySet()) { + scoresMap.put(uuidEntry.getValue().toString(), scoresMap.get(uuidEntry.getKey())); + this.getScoresConfig().set("Scores." + uuidEntry.getValue().toString(), scoresMap.get(uuidEntry.getKey())); + } + hasConverted = true; + } catch (Exception ex) { + ex.printStackTrace(); + hasConverted = false; + } + for (String unconvertedPlayer : unconvertedScores) { + scoresMap.remove(unconvertedPlayer); + if (hasConverted) this.getScoresConfig().set("Scores." + unconvertedPlayer, null); + } + this.saveScoresConfig(); + this.playerScores = new HashMap(); + for (Entry mapEntry : scoresMap.entrySet()) { + if (Utilities.isUUID(mapEntry.getKey())) + this.playerScores.put(UUID.fromString(mapEntry.getKey()), mapEntry.getValue()); + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + private void loadEconomy() { + this.getEconomyConfig().options().header("KingKits Economy Configuration"); + this.getEconomyConfig().addDefault("Use economy", false); + this.getEconomyConfig().addDefault("Enable cost per kit", false); + this.getEconomyConfig().addDefault("Enable cost per refill", false); + this.getEconomyConfig().addDefault("Cost per refill", 2.50); + this.getEconomyConfig().addDefault("Currency", "dollars"); + this.getEconomyConfig().addDefault("Message", "&a was taken from your balance."); + this.getEconomyConfig().addDefault("Enable money per kill", false); + this.getEconomyConfig().addDefault("Money per kill", 5.00); + this.getEconomyConfig().addDefault("Money per kill message", "&aYou received for killing ."); + this.getEconomyConfig().addDefault("Enable money per death", false); + this.getEconomyConfig().addDefault("Money per death", 5.00); + this.getEconomyConfig().addDefault("Money per death message", "&aYou lost for being killed by ."); + if (this.getEconomyConfig().contains("Cost per kit")) this.getEconomyConfig().set("Cost per kit", null); + this.getEconomyConfig().options().copyDefaults(true); + this.getEconomyConfig().options().copyHeader(true); + this.saveEconomyConfig(); + + this.configValues.vaultValues.useEconomy = this.getEconomyConfig().getBoolean("Use economy"); + + boolean useCostPerKit = this.getEconomyConfig().getBoolean("Enable cost per kit"); + if (useCostPerKit && !this.configValues.vaultValues.useEconomy) { + this.getEconomyConfig().set("Enable cost per kit", false); + this.saveEconomyConfig(); + this.reloadEconomyConfig(); + } + this.configValues.vaultValues.useCostPerKit = this.getEconomyConfig().getBoolean("Enable cost per kit"); + + boolean useCostPerRefill = this.getEconomyConfig().getBoolean("Enable cost per refill"); + if (useCostPerRefill && !this.configValues.vaultValues.useEconomy) { + this.getEconomyConfig().set("Enable cost per refill", false); + this.saveEconomyConfig(); + this.reloadEconomyConfig(); + } + this.configValues.vaultValues.useCostPerRefill = this.getEconomyConfig().getBoolean("Enable cost per refill"); + + this.configValues.vaultValues.costPerRefill = this.getEconomyConfig().getDouble("Cost per refill"); + + boolean useMoneyPerKill = this.getEconomyConfig().getBoolean("Enable money per kill"); + if (useMoneyPerKill && !this.configValues.vaultValues.useEconomy) { + this.getEconomyConfig().set("Enable money per kill", false); + this.saveEconomyConfig(); + this.reloadEconomyConfig(); + } + this.configValues.vaultValues.useMoneyPerKill = this.getEconomyConfig().getBoolean("Enable money per kill"); + this.configValues.vaultValues.moneyPerKill = this.getEconomyConfig().getDouble("Money per kill"); + + boolean useMoneyPerDeath = this.getEconomyConfig().getBoolean("Enable money per death"); + if (useMoneyPerDeath && !this.configValues.vaultValues.useEconomy) { + this.getEconomyConfig().set("Enable money per death", false); + this.saveEconomyConfig(); + this.reloadEconomyConfig(); + } + this.configValues.vaultValues.useMoneyPerDeath = this.getEconomyConfig().getBoolean("Enable money per death"); + this.configValues.vaultValues.moneyPerDeath = this.getEconomyConfig().getDouble("Money per death"); + } + + private void loadKillstreaks() { + this.getKillstreaksConfig().options().header("KingKits Killstreak Configuration"); + this.getKillstreaksConfig().addDefault("First run", true); + if (this.getKillstreaksConfig().getBoolean("First run")) { + this.getKillstreaksConfig().set("Killstreak 9001", Arrays.asList("broadcast &c&a's killstreak is over 9000!", "msg Well done!")); + this.getKillstreaksConfig().set("First run", false); + } + this.getKillstreaksConfig().options().copyDefaults(true); + this.getKillstreaksConfig().options().copyHeader(true); + this.saveKillstreaksConfig(); + } + + public boolean checkConfig() { + String scoreChatPrefix = this.getConfig().getString("Score chat prefix"); + if (!scoreChatPrefix.contains("")) { + this.getConfig().set("Score chat prefix", "&6[&a&6]"); + this.saveConfig(); + return false; + } + return true; + } + + private void setupPermissions(boolean unregisterFirst) { + if (unregisterFirst) { + try { + List kitNames = new ArrayList(this.getKitsConfig().getKeys(false)); + for (int pos = 0; pos < kitNames.size(); pos++) { + String kit = kitNames.get(pos); + if (kit.split(" ").length > 1) kit = kit.split(" ")[0]; + try { + this.getServer().getPluginManager().removePermission(new Permission("kingkits.kits." + kit.toLowerCase())); + } catch (Exception ex) { + } + } + } catch (Exception ex) { + } + } + try { + List kitNames = new ArrayList(this.getKitsConfig().getKeys(false)); + for (int pos = 0; pos < kitNames.size(); pos++) { + String kit = kitNames.get(pos); + if (kit.split(" ").length > 1) kit = kit.split(" ")[0]; + try { + this.getServer().getPluginManager().addPermission(new Permission("kingkits.kits." + kit.toLowerCase())); + } catch (Exception ex) { + this.getLogger().info("Couldn't register the permission node: " + "kingkits.kits." + kit.toLowerCase()); + this.getLogger().info("This error probably occurred because it's already registered."); + } + } + } catch (Exception ex) { + } + } + + public String getEconomyMessage(double amount) { + this.reloadEconomyConfig(); + String message = this.getEconomyConfig().getString("Message"); + String currency = this.getEconomyConfig().getString("Currency"); + if (amount == 1) { + if (currency.contains("s")) { + if (currency.lastIndexOf('s') == message.length()) currency = this.replaceLast(currency, "s", ""); + } + } + message = message.replace("", currency); + message = message.replace("", String.valueOf(amount)); + return Utilities.replaceChatColour(message); + } + + public List getConfigKitList() { + List configKeys = new ArrayList(this.getKitsConfig().getKeys(false)); + configKeys.remove("First run"); + return configKeys; + } + + public long getCooldown(String playerName, String kitName) { + if (playerName != null && kitName != null && this.kitList.containsKey(kitName) && this.getCooldownConfig().contains(playerName)) { + Object objCooldownPlayer = this.getCooldownConfig().get(playerName); + Map playerKitCooldowns = objCooldownPlayer instanceof ConfigurationSection ? ((ConfigurationSection) objCooldownPlayer).getValues(false) : (objCooldownPlayer instanceof Map ? (Map) objCooldownPlayer : new HashMap()); + if (playerKitCooldowns.containsKey(kitName)) { + String strPlayerCooldown = playerKitCooldowns.get(kitName) != null ? playerKitCooldowns.get(kitName).toString() : null; + if (!Utilities.isLong(strPlayerCooldown)) { + this.getCooldownConfig().set(playerName + "." + kitName, null); + this.saveCooldownConfig(); + } else { + return Long.parseLong(strPlayerCooldown); + } + } + } + return System.currentTimeMillis(); + } + + public Map getCooldowns(String playerName) { + Map kitCooldowns = new HashMap(); + if (playerName != null && this.getCooldownConfig().contains(playerName)) { + Object objCooldownPlayer = this.getCooldownConfig().get(playerName); + Map configKitCooldowns = objCooldownPlayer instanceof ConfigurationSection ? ((ConfigurationSection) objCooldownPlayer).getValues(false) : (objCooldownPlayer instanceof Map ? (Map) objCooldownPlayer : new HashMap()); + for (Entry kitEntry : configKitCooldowns.entrySet()) { + String strPlayerCooldown = kitEntry.getValue().toString(); + if (!Utilities.isLong(strPlayerCooldown)) { + this.getCooldownConfig().set(playerName + "." + strPlayerCooldown, null); + this.saveCooldownConfig(); + } else { + kitCooldowns.put(kitEntry.getKey(), Long.parseLong(strPlayerCooldown)); + } + } + } + return kitCooldowns; + } + + public List getKitList() { + return new ArrayList(this.kitList.keySet()); + } + + public List getKitList(UUID playerUUID) { + List kitList = this.userKitList.get(playerUUID); + List strKitList = new ArrayList(); + if (kitList != null) { + for (Kit kit : kitList) { + if (kit != null) strKitList.add(kit.getRealName()); + } + } + return strKitList; + } + + public String getMPKMessage(Player killer, double amount) { + this.reloadEconomyConfig(); + String message = this.getEconomyConfig().getString("Money per kill message"); + String currency = this.getEconomyConfig().getString("Currency"); + if (amount == 1) { + if (currency.contains("s")) { + if (currency.lastIndexOf('s') == message.length() - 1) currency = this.replaceLast(currency, "s", ""); + } + } + message = message.replace("", currency); + message = message.replace("", String.valueOf(amount)); + message = message.replace("", killer.getName()); + return Utilities.replaceChatColour(message); + } + + public String getMPDMessage(Player dead, double amount) { + this.reloadEconomyConfig(); + String message = this.getEconomyConfig().getString("Money per death message"); + String currency = this.getEconomyConfig().getString("Currency"); + if (amount == 1) { + if (currency.contains("s")) { + if (currency.lastIndexOf('s') == message.length() - 1) currency = this.replaceLast(currency, "s", ""); + } + } + message = message.replace("", currency); + message = message.replace("", String.valueOf(amount)); + message = message.replace("", dead.getKiller().getName()); + return Utilities.replaceChatColour(message); + } + + private String replaceLast(String s, String character, String targetChar) { + String string = s; + if (string.contains(character)) { + StringBuilder b = new StringBuilder(string); + b.replace(string.lastIndexOf(character), string.lastIndexOf(character) + 1, targetChar); + string = b.toString(); + } + return string; + } + + private FileConfiguration kitsConfig = null; + private File customKitsConfig = null; + + public void reloadKitsConfig() { + if (this.customKitsConfig == null) this.customKitsConfig = new File(this.getDataFolder(), "kits.yml"); + try { + this.kitsConfig = loadConfigSafely(this.customKitsConfig); + } catch (Exception ex) { + ex.printStackTrace(); + if (this.customKitsConfig.exists()) { + File kitDestination = new File(this.getDataFolder(), "kits.broken.yml"); + if (kitDestination.exists()) { + try { + kitDestination.delete(); + } catch (Exception ex2) { + } + } + FileUtil.copy(this.customKitsConfig, kitDestination); + try { + this.customKitsConfig.delete(); + } catch (Exception ex2) { + } + } + try { + this.customKitsConfig.createNewFile(); + this.kitsConfig = loadConfigSafely(this.customKitsConfig); + } catch (Exception ex2) { + } + } + } + + public FileConfiguration getKitsConfig() { + if (this.kitsConfig == null || this.customKitsConfig == null) this.reloadKitsConfig(); + return this.kitsConfig; + } + + public void saveKitsConfig() { + if (this.kitsConfig == null || this.customKitsConfig == null) return; + try { + this.getKitsConfig().save(this.customKitsConfig); + } catch (IOException ex) { + this.getLogger().log(Level.SEVERE, "Could not save the Kits config as " + this.customKitsConfig.getName(), ex); + } + } + + private FileConfiguration scoresConfig = null; + private File customScoresConfig = null; + + public void reloadScoresConfig() { + if (this.customScoresConfig == null) this.customScoresConfig = new File(this.getDataFolder(), "scores.yml"); + this.scoresConfig = loadConfigSafely(this.customScoresConfig); + } + + public FileConfiguration getScoresConfig() { + if (this.scoresConfig == null || this.customScoresConfig == null) this.reloadScoresConfig(); + return this.scoresConfig; + } + + public void saveScoresConfig() { + if (this.scoresConfig == null || this.customScoresConfig == null) return; + try { + this.getScoresConfig().save(this.customScoresConfig); + } catch (IOException ex) { + this.getLogger().log(Level.SEVERE, "Could not save the Scores config as " + this.customScoresConfig.getName(), ex); + } + } + + private FileConfiguration economyConfig = null; + private File customEconomyConfig = null; + + public void reloadEconomyConfig() { + if (this.customEconomyConfig == null) this.customEconomyConfig = new File(this.getDataFolder(), "economy.yml"); + this.economyConfig = loadConfigSafely(this.customEconomyConfig); + } + + public FileConfiguration getEconomyConfig() { + if (this.economyConfig == null || this.customEconomyConfig == null) this.reloadEconomyConfig(); + return this.economyConfig; + } + + public void saveEconomyConfig() { + if (this.economyConfig == null || this.customEconomyConfig == null) return; + try { + this.getEconomyConfig().save(this.customEconomyConfig); + } catch (IOException ex) { + this.getLogger().log(Level.SEVERE, "Could not save the Economy config as " + this.customEconomyConfig.getName(), ex); + } + } + + private FileConfiguration killstreaksConfig = null; + private File customKillstreaksConfig = null; + + public void reloadKillstreaksConfig() { + if (this.customKillstreaksConfig == null) + this.customKillstreaksConfig = new File(this.getDataFolder(), "killstreaks.yml"); + this.killstreaksConfig = loadConfigSafely(this.customKillstreaksConfig); + } + + public FileConfiguration getKillstreaksConfig() { + if (this.killstreaksConfig == null || this.customKillstreaksConfig == null) this.reloadKillstreaksConfig(); + return this.killstreaksConfig; + } + + public void saveKillstreaksConfig() { + if (this.killstreaksConfig == null || this.customKillstreaksConfig == null) return; + try { + this.getKillstreaksConfig().save(this.customKillstreaksConfig); + } catch (IOException ex) { + this.getLogger().log(Level.SEVERE, "Could not save the Killstreaks config as " + this.customKillstreaksConfig.getName(), ex); + } + } + + private FileConfiguration cooldownConfig = null; + private File customCooldownConfig = null; + + public void reloadCooldownConfig() { + if (this.customCooldownConfig == null) + this.customCooldownConfig = new File(this.getDataFolder(), "cooldown.yml"); + this.cooldownConfig = loadConfigSafely(this.customCooldownConfig); + } + + public FileConfiguration getCooldownConfig() { + if (this.cooldownConfig == null || this.customCooldownConfig == null) this.reloadCooldownConfig(); + return this.cooldownConfig; + } + + public void saveCooldownConfig() { + if (this.cooldownConfig == null || this.customCooldownConfig == null) return; + try { + this.cooldownConfig.save(this.customCooldownConfig); + } catch (IOException ex) { + this.getLogger().log(Level.SEVERE, "Could not save the cooldown config as " + this.customCooldownConfig.getName(), ex); + } + } + + private FileConfiguration userKitsConfig = null; + private File customUserKitsConfig = null; + + public void reloadUserKitsConfig() { + if (this.customUserKitsConfig == null) + this.customUserKitsConfig = new File(this.getDataFolder(), "userkits.yml"); + this.userKitsConfig = loadConfigSafely(this.customUserKitsConfig); + } + + public FileConfiguration getUserKitsConfig() { + if (this.userKitsConfig == null || this.customUserKitsConfig == null) this.reloadUserKitsConfig(); + return this.userKitsConfig; + } + + public void saveUserKitsConfig() { + if (this.userKitsConfig == null || this.customUserKitsConfig == null) return; + try { + this.userKitsConfig.save(this.customUserKitsConfig); + } catch (IOException ex) { + this.getLogger().log(Level.SEVERE, "Could not save the user kits config as " + this.customUserKitsConfig.getName(), ex); + } + } + + public void reloadAllConfigs() { + this.reloadConfig(); + this.reloadKitsConfig(); + this.reloadUserKitsConfig(); + + this.reloadScoresConfig(); + this.reloadEconomyConfig(); + this.reloadKillstreaksConfig(); + this.reloadCooldownConfig(); + } + + private void convertOldConfigUserKits() { + List keyList = new ArrayList(this.getUserKitsConfig().getKeys(false)); + Map addMap = new HashMap(); + List checkList = new ArrayList(); + + for (int i = 0; i < keyList.size(); i++) { + String strPlayerName = keyList.get(i); + if (strPlayerName != null && !Utilities.isUUID(strPlayerName)) checkList.add(strPlayerName); + } + try { + Map resultMap = UUIDFetcher.lookupNames(checkList); + addMap.putAll(resultMap); + } catch (Exception ex) { + ex.printStackTrace(); + } + + if (!addMap.isEmpty()) { + for (Map.Entry addEntry : addMap.entrySet()) { + if (addEntry.getValue() != null) + this.getUserKitsConfig().set(addEntry.getValue().toString(), this.getUserKitsConfig().get(addEntry.getKey())); + else continue; + this.getUserKitsConfig().set(addEntry.getKey(), null); + } + addMap.clear(); + this.saveUserKitsConfig(); + } + } + + public static KingKits getInstance() { + return pluginInstance; + } + + private static FileConfiguration loadConfigSafely(File configFile) { + try { + return customLoadConfiguration(configFile); + } catch (Exception ex) { + if (ex.getClass() != FileNotFoundException.class) + Bukkit.getServer().getLogger().log(Level.SEVERE, "Cannot load " + configFile, ex); + if (configFile.exists()) { + String filePath = configFile.getAbsolutePath(); + String brokenFilePath = filePath.substring(0, filePath.indexOf(".yml")) + "-" + System.currentTimeMillis() + ".yml.broken"; + File configDestination = new File(brokenFilePath); + try { + FileInputStream configFileInputStream = new FileInputStream(configFile); + Files.copy(configFileInputStream, configDestination.toPath(), StandardCopyOption.REPLACE_EXISTING); + configFileInputStream.close(); + configFile.delete(); + } catch (Exception ex2) { + } + } + try { + configFile.createNewFile(); + return customLoadConfiguration(configFile); + } catch (Exception ex2) { + } + } + return YamlConfiguration.loadConfiguration(new File(getInstance().getDataFolder(), "temp" + System.currentTimeMillis() + ".yml")); + } + + private static YamlConfiguration customLoadConfiguration(File file) throws Exception { + Validate.notNull(file, "File cannot be null"); + YamlConfiguration config = new YamlConfiguration(); + config.load(file); + return config; + } } diff --git a/src/main/java/com/faris/kingkits/KingKitsAPI.java b/src/main/java/com/faris/kingkits/KingKitsAPI.java new file mode 100644 index 0000000..43f592f --- /dev/null +++ b/src/main/java/com/faris/kingkits/KingKitsAPI.java @@ -0,0 +1,632 @@ +package com.faris.kingkits; + +import com.faris.kingkits.gui.GuiKitMenu; +import com.faris.kingkits.gui.GuiPreviewKit; +import com.faris.kingkits.helper.Utilities; +import com.faris.kingkits.helper.container.KitStack; +import com.faris.kingkits.listener.command.SetKit; +import org.bukkit.*; +import org.bukkit.entity.*; +import org.bukkit.inventory.*; +import org.bukkit.permissions.*; +import org.bukkit.potion.*; + +import java.util.*; +import java.util.logging.Logger; + +public class KingKitsAPI { + + /** + * Create a kit. + * + * @param kitName The name of the kit + * @param itemsInKit The items in the kit + * @param potionEffects The potion effects given when using the kit + * @param guiItem The item shown in the GUI (can be null) + * @param costOfKit The cost of the kit + * @return Whether the creation of the kit has been successful or not. + */ + public static boolean createKit(String kitName, List itemsInKit, List potionEffects, ItemStack guiItem, double costOfKit) { + Map mapItemsInKit = new HashMap<>(); + if (itemsInKit != null) { + for (int i = 0; i < itemsInKit.size(); i++) { + mapItemsInKit.put(i, itemsInKit.get(i)); + } + } + return createKit(kitName, mapItemsInKit, potionEffects, guiItem, costOfKit); + } + + /** + * Create a kit. + * + * @param kitName The name of the kit + * @param itemsInKit The items in the kit with their slot numbers + * @param potionEffects The potion effects given when using the kit + * @param guiItem The item shown in the GUI (can be null) + * @param costOfKit The cost of the kit + * @return Whether the creation of the kit has been successful or not. + */ + public static boolean createKit(String kitName, Map itemsInKit, List potionEffects, ItemStack guiItem, double costOfKit) { + if (KingKits.getInstance() == null) return false; + if (itemsInKit != null && !itemsInKit.isEmpty()) { + boolean containsKit = kitExists(kitName); + if (containsKit) { + List currentKits = KingKits.getInstance().getConfigKitList(); + List currentKitsLC = Utilities.toLowerCaseList(currentKits); + if (currentKitsLC.contains(kitName.toLowerCase())) + kitName = currentKits.get(currentKitsLC.indexOf(kitName.toLowerCase())); + KingKits.getInstance().getKitsConfig().set(kitName, null); + KingKits.getInstance().saveKitsConfig(); + KingKits.getInstance().kitList.remove(kitName); + } + Kit kit = new Kit(kitName, costOfKit, itemsInKit, potionEffects == null ? new ArrayList() : potionEffects).setGuiItem(guiItem != null ? guiItem : new ItemStack(Material.DIAMOND_SWORD)); + KingKits.getInstance().getKitsConfig().set(kitName, kit.serialize()); + KingKits.getInstance().saveKitsConfig(); + KingKits.getInstance().kitList.put(kitName, kit); + + try { + KingKits.getInstance().getServer().getPluginManager().addPermission(new Permission("kingkits.kits." + kitName.toLowerCase())); + } catch (Exception ex) { + getPluginLogger().warning(ex.getClass().getSimpleName() + " error: " + ex.getMessage()); + } + return true; + } + return false; + } + + /** + * Create a user kit. + * + * @param playerUUID The UUID of the owner of the kit + * @param kitName The name of the kit + * @param itemsInKit The items in the user kit + * @param potionEffects The potion effects given when using the user kit + * @param guiItem The item shown in the GUI (can be null) + * @param costOfKit The cost of the user kit + * @return Whether the creation of the user kit has been successful or not. + */ + public static boolean createUserKit(UUID playerUUID, String kitName, List itemsInKit, List potionEffects, ItemStack guiItem, double costOfKit) { + Map mapItemsInKit = new HashMap<>(); + if (itemsInKit != null) { + for (int i = 0; i < itemsInKit.size(); i++) { + mapItemsInKit.put(i, itemsInKit.get(i)); + } + } + return createUserKit(playerUUID, kitName, mapItemsInKit, potionEffects, guiItem, costOfKit); + } + + + /** + * Create a user kit. + * + * @param playerUUID The user kit's owner's UUID + * @param kitName The name of the kit + * @param itemsInKit The items in the user kit with their slot numbers + * @param potionEffects The potion effects given when using the user kit + * @param guiItem The item shown in the GUI (can be null) + * @param costOfKit The cost of the user kit + * @return Whether the creation of the user kit has been successful or not. + */ + public static boolean createUserKit(UUID playerUUID, String kitName, Map itemsInKit, List potionEffects, ItemStack guiItem, double costOfKit) { + if (KingKits.getInstance() == null) return false; + if (playerUUID != null && kitName != null && itemsInKit != null && !itemsInKit.isEmpty()) { + if (isUserKit(kitName, playerUUID)) deleteUserKit(playerUUID, kitName); + Kit kit = new Kit(kitName, costOfKit, itemsInKit, potionEffects == null ? new ArrayList() : potionEffects).setGuiItem(guiItem != null ? guiItem : new ItemStack(Material.DIAMOND_SWORD)).setUserKit(true); + KingKits.getInstance().getUserKitsConfig().set(playerUUID.toString() + "." + kitName, kit.serialize()); + KingKits.getInstance().saveUserKitsConfig(); + List currentUserKits = KingKits.getInstance().userKitList.get(playerUUID); + if (currentUserKits == null) currentUserKits = new ArrayList(); + currentUserKits.add(kit); + KingKits.getInstance().userKitList.put(playerUUID, currentUserKits); + return true; + } + return false; + } + + /** + * Delete a kit. + * + * @param kitName The name of the kit + * @return Whether the deletion of the kit has been successful or not. + */ + public static boolean deleteKit(String kitName) { + if (kitName != null) { + List kits = KingKits.getInstance() != null ? KingKits.getInstance().getConfigKitList() : new ArrayList(); + List kitsLC = Utilities.toLowerCaseList(kits); + if (kitsLC.contains(kitName.toLowerCase())) { + kitName = kits.get(kitsLC.indexOf(kitName.toLowerCase())); + KingKits.getInstance().getKitsConfig().set(kitName, null); + KingKits.getInstance().saveKitsConfig(); + KingKits.getInstance().kitList.remove(kitName); + return true; + } + } + return false; + } + + + /** + * Delete a user kit. + * + * @param playerUUID The user kit's owner's UUID + * @param kitName The name of the user kit + * @return Whether the deletion of the user kit has been successful or not. + */ + public static boolean deleteUserKit(UUID playerUUID, String kitName) { + if (kitName != null) { + List kits = KingKits.getInstance() != null ? KingKits.getInstance().getKitList(playerUUID) : new ArrayList(); + List kitsLC = Utilities.toLowerCaseList(kits); + if (kitsLC.contains(kitName.toLowerCase())) { + kitName = kits.get(kitsLC.indexOf(kitName.toLowerCase())); + KingKits.getInstance().getUserKitsConfig().set(playerUUID.toString() + "." + kitName, null); + List userKits = KingKits.getInstance().userKitList.get(playerUUID); + if (userKits != null) { + for (int i = 0; i < userKits.size(); i++) { + Kit kit = userKits.get(i); + if (kit != null && (kit.getRealName().equalsIgnoreCase(kitName) || Utilities.stripColour(kit.getName()).equalsIgnoreCase(kitName))) { + userKits.remove(i); + break; + } + } + KingKits.getInstance().userKitList.put(playerUUID, userKits); + if (userKits.isEmpty()) KingKits.getInstance().getUserKitsConfig().set(playerUUID.toString(), null); + } + KingKits.getInstance().saveUserKitsConfig(); + return true; + } + } + return false; + } + + /** + * Get the killstreak of a player. + * + * @param player The player + * @return The player's killstreak. + */ + public static long getKillstreak(Player player) { + return player != null ? getKillstreak(player.getName()) : 0L; + } + + /** + * Get the killstreak of a player. + * + * @param playerUsername The player's username + * @return The player's killstreak. + */ + public static long getKillstreak(String playerUsername) { + return KingKits.getInstance() != null && KingKits.getInstance().playerKillstreaks.containsKey(playerUsername) ? KingKits.getInstance().playerKillstreaks.get(playerUsername) : 0L; + } + + /** + * Get the name of the kit that a player is using. + * + * @param player The player + * @return The name of the kit that the player is using. + */ + public static String getKit(Player player) { + if (player == null) return null; + return getKit(player.getName()); + } + + + /** + * Get the name of the kit that a player is using. + * + * @param playerUsername The player's username + * @return The name of the kit that the player is using. + */ + public static String getKit(String playerUsername) { + return KingKits.getInstance() != null && KingKits.getInstance().usingKits != null ? KingKits.getInstance().usingKits.get(playerUsername) : null; + } + + /** + * Get a kit by the kit's name. + * This does not get user kits. + * + * @param kitName The name of the kit + * @param caseInsensitive True if the casing of the letters does not matter + * @return The kit. + */ + public static Kit getKitByName(String kitName, boolean caseInsensitive) { + if (KingKits.getInstance() == null) return null; + String strippedKitName = Utilities.stripColour(kitName); + for (Kit kit : KingKits.getInstance().kitList.values()) { + if (kit != null && (caseInsensitive ? strippedKitName.equalsIgnoreCase(Utilities.stripColour(kit.getRealName())) || strippedKitName.equalsIgnoreCase(Utilities.stripColour(kit.getName())) : strippedKitName.equalsIgnoreCase(Utilities.stripColour(kit.getRealName())) || strippedKitName.equals(Utilities.stripColour(kit.getName())))) + return kit; + } + return strippedKitName != null ? KingKits.getInstance().kitList.get(strippedKitName) : null; + } + + /** + * Get a kit by the kit's name. + * This also gets user kits. + * + * @param kitName The name of the kit (case insensitive) + * @param playerUUID The player's UUID (can be null) + * @return The kit. + */ + public static Kit getKitByName(String kitName, UUID playerUUID) { + if (KingKits.getInstance() == null) return null; + String strippedKitName = Utilities.stripColour(kitName); + if (playerUUID != null) { + Kit kit = getUserKitByName(kitName, playerUUID); + if (kit != null) return kit; + } + if (strippedKitName != null) { + for (Kit kit : KingKits.getInstance().kitList.values()) { + if (kit != null && (strippedKitName.equalsIgnoreCase(Utilities.stripColour(kit.getRealName())) || strippedKitName.equalsIgnoreCase(Utilities.stripColour(kit.getName())))) + return kit; + } + } + return strippedKitName != null ? KingKits.getInstance().kitList.get(strippedKitName) : null; + } + + /** + * Get a list of all the kits. + * + * @return A list of all the kits. + */ + public static List getKits() { + return KingKits.getInstance() != null ? new ArrayList<>(KingKits.getInstance().kitList.values()) : new ArrayList(); + } + + /** + * Get a Map of all the players and the name of the kit they are using. + * + * @return A Map of all the players and the name of the kit they are using. + */ + public static Map getPlayersKits() { + return KingKits.getInstance() != null ? Collections.unmodifiableMap(KingKits.getInstance().usingKits) : new HashMap(); + } + + /** + * Get KingKit's plugin logger. + * + * @return KingKit's plugin logger. + */ + public static Logger getPluginLogger() { + if (KingKits.getInstance() == null) return Logger.getLogger("Minecraft"); + return KingKits.getInstance().getLogger(); + } + + /** + * Get the score of a player. + * + * @param player The player + * @return The score of the player. + */ + public static int getScore(Player player) { + return player != null ? getScore(player.getUniqueId()) : 0; + } + + /** + * Get the score of a player. + * + * @param playerUUID The player's UUID + * @return The score of the player. + */ + public static int getScore(UUID playerUUID) { + return KingKits.getInstance() != null && KingKits.getInstance().playerScores.containsKey(playerUUID) ? (Integer) KingKits.getInstance().playerScores.get(playerUUID) : 0; + } + + /** + * Get a Map of all the players and their scores. + * + * @return The scores of all the players. + */ + public static Map getScores() { + Map playerScores = new HashMap<>(); + if (KingKits.getInstance() != null) { + for (Map.Entry entryScores : KingKits.getInstance().playerScores.entrySet()) { + if (entryScores.getValue() instanceof Integer) + playerScores.put(entryScores.getKey(), (Integer) entryScores.getValue()); + } + } + return playerScores; + } + + /** + * Get a user kit by the user kit's name. + * + * @param kitName The user kit's name + * @param playerUUID The UUID of the owner of the kit + * @return The user kit. + */ + public static Kit getUserKitByName(String kitName, UUID playerUUID) { + if (KingKits.getInstance() == null) return null; + String strippedKitName = Utilities.stripColour(kitName); + if (playerUUID != null && strippedKitName != null && KingKits.getInstance().userKitList.containsKey(playerUUID)) { + List kits = KingKits.getInstance().userKitList.get(playerUUID); + if (kits != null) { + for (Kit kit : kits) { + if (kit != null && (strippedKitName.equalsIgnoreCase(Utilities.stripColour(kit.getRealName())) || strippedKitName.equalsIgnoreCase(Utilities.stripColour(kit.getName())))) + return kit; + } + } + } + return null; + } + + /** + * Check if a player has a kit. + * + * @param player The player + * @return Whether the player has a kit or not. + */ + public static boolean hasKit(Player player) { + return player != null && hasKit(player.getName(), false); + } + + /** + * Check if a player has a kit. + * + * @param playerUsername The player's username + * @return Whether the player has a kit or not. + */ + public static boolean hasKit(String playerUsername) { + return hasKit(playerUsername, false); + } + + /** + * Check if a player has a kit. + * + * @param player The player + * @param ignoreOPs Whether or not to ignore OPs + * @return Whether the player has a kit or not. + */ + public static boolean hasKit(Player player, boolean ignoreOPs) { + return player != null && hasKit(player.getName(), ignoreOPs); + } + + + /** + * Check if a player has a kit. + * + * @param playerUsername The player's username + * @param ignoreOPs Whether or not to ignore OPs + * @return Whether the player has a kit or not. + */ + public static boolean hasKit(String playerUsername, boolean ignoreOPs) { + return KingKits.getInstance() != null && (ignoreOPs ? KingKits.getInstance().playerKits.get(playerUsername) != null : KingKits.getInstance().usingKits.get(playerUsername) != null); + } + + /** + * Check if a kit is a user kit. + * + * @param kitName The kit's name + */ + public static boolean isUserKit(String kitName, UUID playerUUID) { + String strippedKitName = Utilities.stripColour(kitName); + if (playerUUID != null && !strippedKitName.isEmpty() && KingKits.getInstance().userKitList.containsKey(playerUUID)) { + List kits = KingKits.getInstance().userKitList.get(playerUUID); + if (kits != null) { + for (Kit kit : kits) { + if (kit != null && (strippedKitName.equalsIgnoreCase(Utilities.stripColour(kit.getRealName())) || strippedKitName.equals(Utilities.stripColour(kit.getName())))) { + return true; + } + } + } + } + return false; + } + + /** + * Check if a player is using a specified kit. + * This returns false if the player is using a user kit. + * + * @param kitName The kit's name + * @param player The player + * @return Whether a player is using the kit (and it is not a user kit) or not. + */ + public static boolean isUsingKit(String kitName, Player player) { + return isUsingKit(kitName, player, false); + } + + + /** + * Check if a player is using a specified kit. + * + * @param kitName The kit's name + * @param player The player + * @param allowUserKits Whether to allow the checking of user kits too + * @return Whether a player is using the kit or not. + */ + public static boolean isUsingKit(String kitName, Player player, boolean allowUserKits) { + if (kitName != null && player != null) { + String playerKit = getKit(player); + if (playerKit != null) { + if (!allowUserKits) { + Kit kit = getKitByName(playerKit, true); + return kit != null && !kit.isUserKit() && playerKit.equalsIgnoreCase(kitName); + } else { + return playerKit.equalsIgnoreCase(kitName); + } + } + } + return false; + } + + /** + * Check if a kit exists. + * + * @param kitName The name of the kit to check + * @return Whether a kit with the specified name exists or not. + */ + public static boolean kitExists(String kitName) { + if (kitName != null) { + List kitList = new ArrayList<>(); + if (KingKits.getInstance().getKitsConfig().contains("Kits")) kitList = KingKits.getInstance().getKitList(); + List kitListLC = Utilities.toLowerCaseList(kitList); + return kitListLC.contains(kitName.toLowerCase()); + } + return false; + } + + /** + * Remove a player from the kits list. + * + * @param player The player + */ + public static void removePlayer(Player player) { + if (player != null) removePlayer(player.getName()); + } + + /** + * Remove a player from the kits list. + * + * @param playerUsername The player's username + */ + public static void removePlayer(String playerUsername) { + KingKits.getInstance().usingKits.remove(playerUsername); + KingKits.getInstance().playerKits.remove(playerUsername); + } + + /** + * Set the kit of a player. + * + * @param playerUsername The player's username + * @param kitName The name of the kit + */ + public static void setPlayerKit(String playerUsername, String kitName) { + setPlayerKit(getPluginLogger(), playerUsername, kitName); + } + + /** + * Set the kit of a player. + * + * @param pluginLogger The plugin's logger + * @param playerUsername The player's username + * @param kitName The name of the kit + */ + public static void setPlayerKit(Logger pluginLogger, String playerUsername, String kitName) { + boolean useSyso = playerUsername == null; + if (kitExists(kitName)) { + Player target = Bukkit.getPlayerExact(playerUsername); + if (target != null && target.isOnline()) { + if (hasKit(target.getName(), false)) { + target.getInventory().clear(); + target.getInventory().setArmorContents(null); + removePlayer(target.getName()); + } + try { + SetKit.setKit(target, kitName, true); + } catch (Exception ex) { + String msg = "Error, couldn't set the player's kit to " + kitName + "."; + if (useSyso) System.out.println(msg); + else pluginLogger.info(msg); + String msg2 = "Error Log: \n" + ex.getMessage(); + if (useSyso) System.out.println(msg2); + else pluginLogger.info(msg2); + } + } else { + String msg = "Target player '" + playerUsername + "' is not online/does not exist."; + if (useSyso) System.out.println(msg); + else pluginLogger.info(msg); + } + } else { + String msg = "Kit " + kitName + " doesn't exist."; + if (useSyso) System.out.println(msg); + else pluginLogger.info(msg); + } + } + + /** + * Set the score of a player. + * + * @param player The player + * @param score The score + */ + public static void setScore(Player player, int score) { + if (player != null) setScore(player.getUniqueId(), score); + } + + /** + * Set the score of a player. + * + * @param playerUUID The player's UUID + * @param score The score + */ + public static void setScore(UUID playerUUID, int score) { + if (playerUUID != null) { + if (KingKits.getInstance().playerScores.containsKey(playerUUID)) + KingKits.getInstance().playerScores.remove(playerUUID); + if (score < 0) score *= -1; + KingKits.getInstance().playerScores.put(playerUUID, score); + } + } + + /** + * Show the kit menu to a player. + * + * @param player The player + */ + public static void showKitMenu(Player player) { + showKitMenu(player, false); + } + + /** + * Show the kit menu to a player. + * + * @param player The player + * @param ignoreChecks Whether or not to ignore checking the configuration 'Kit list mode' + */ + public static void showKitMenu(Player player, boolean ignoreChecks) { + if (KingKits.getInstance() != null && player != null && (!ignoreChecks || KingKits.getInstance().configValues.kitListMode.equalsIgnoreCase("Gui") || KingKits.getInstance().configValues.kitListMode.equalsIgnoreCase("Menu"))) { + List kitValues = new ArrayList<>(); + if (KingKits.getInstance().configValues.sortAlphabetically) { + List kitNames = new ArrayList<>(KingKits.getInstance().kitList.keySet()); + if (KingKits.getInstance().userKitList.containsKey(player.getUniqueId())) { + List userKits = KingKits.getInstance().userKitList.get(player.getUniqueId()); + for (Kit userKit : userKits) { + if (userKit != null) kitNames.add(userKit.getRealName()); + } + } + Collections.sort(kitNames, Utilities.ALPHABETICAL_ORDER); + + for (Iterator kitIterator = kitNames.iterator(); kitIterator.hasNext(); ) { + Kit kit = getKitByName(kitIterator.next(), player.getUniqueId()); + if (kit != null) { + if (!kit.isUserKit() && !KingKits.getInstance().configValues.kitListPermissions) { + if (!player.hasPermission("kingkits.kits." + kit.getRealName().toLowerCase())) continue; + } + kitValues.add(kit); + } + } + } else { + for (Kit kit : KingKits.getInstance().kitList.values()) { + if (kit != null) { + if (!KingKits.getInstance().configValues.kitListPermissions) { + if (!player.hasPermission("kingkits.kits." + kit.getRealName().toLowerCase())) continue; + } + kitValues.add(kit); + } + } + if (KingKits.getInstance().userKitList.containsKey(player.getUniqueId())) + kitValues.addAll(KingKits.getInstance().userKitList.get(player.getUniqueId())); + } + + KitStack[] kitStacks = new KitStack[kitValues.size()]; + for (int index = 0; index < kitValues.size(); index++) { + Kit kit = kitValues.get(index); + kitStacks[index] = new KitStack(kit.getName(), kit.getGuiItem()); + } + ChatColor menuColour = kitStacks.length > 0 ? ChatColor.AQUA : ChatColor.RED; + new GuiKitMenu(player, KingKits.getInstance().configValues.guiTitle.replace("", menuColour.toString()), kitStacks).openMenu(); + } + } + + /** + * Show the kit preview menu to a player. + * + * @param player The player + * @param kitName The kit's name + */ + public static void showKitPreview(Player player, String kitName) { + if (KingKits.getInstance() != null && player != null && kitName != null) { + Kit kit = getKitByName(kitName, false); + if (kit != null) new GuiPreviewKit(player, kit.getRealName()).openMenu(); + } + } + +} \ No newline at end of file diff --git a/src/main/java/com/faris/kingkits/KingKitsSQL.java b/src/main/java/com/faris/kingkits/KingKitsSQL.java new file mode 100644 index 0000000..e704e4b --- /dev/null +++ b/src/main/java/com/faris/kingkits/KingKitsSQL.java @@ -0,0 +1,122 @@ +package com.faris.kingkits; + +import org.bukkit.entity.*; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; + +/** + * @author KingFaris10 + */ +public class KingKitsSQL { + private static Connection connection; + public static boolean sqlEnabled = false; + + private static String sqlHost = null, sqlUsername = null, sqlPassword = null, sqlDatabase = null, sqlTablePrefix = "kk_"; + private static int sqlPort = -1; + + public KingKitsSQL(String sqlHost, int sqlPort, String sqlUsername, String sqlPassword, String sqlDatabase, String sqlTablePrefix) { + KingKitsSQL.sqlHost = sqlHost; + KingKitsSQL.sqlPort = sqlPort; + KingKitsSQL.sqlUsername = sqlUsername; + KingKitsSQL.sqlPassword = sqlPassword; + KingKitsSQL.sqlDatabase = sqlDatabase; + KingKitsSQL.sqlTablePrefix = sqlTablePrefix; + } + + public void onDisable() { + try { + if (connection != null && !connection.isClosed()) connection.close(); + } catch (Exception ex) { + ex.printStackTrace(); + } + connection = null; + } + + public static boolean isInitialised() { + return sqlHost != null && sqlPort != -1 && sqlDatabase != null && sqlUsername != null && sqlPassword != null; + } + + public static boolean isOpen() { + try { + return connection != null && !connection.isClosed(); + } catch (Exception ex) { + ex.printStackTrace(); + return connection != null; + } + } + + public synchronized static void openConnection() { + try { + if (isInitialised() && sqlEnabled) + connection = DriverManager.getConnection("jdbc:mysql://" + sqlHost + ":" + sqlPort + "/" + sqlDatabase, sqlUsername, sqlPassword); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + public synchronized static void closeConnection() { + try { + if (connection != null) connection.close(); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + private synchronized static void createDefaultTable(String table) throws Exception { + try { + PreparedStatement createSql = connection.prepareStatement("CREATE TABLE IF NOT EXISTS " + sqlDatabase + "." + table + " (uuid varchar(36), score int(11));"); + createSql.execute(); + createSql.close(); + } catch (Exception ex) { + throw ex; + } + } + + private synchronized static boolean tableContainsPlayer(Player player, String table) { + try { + if (isInitialised() && player != null) { + PreparedStatement searchSql = connection.prepareStatement("SELECT * FROM `" + table + "` WHERE uuid=?;"); + searchSql.setString(1, player.getUniqueId().toString()); + + ResultSet searchResult = searchSql.executeQuery(); + boolean containsPlayer = searchResult.next(); + searchSql.close(); + searchResult.close(); + + return containsPlayer; + } + } catch (Exception ex) { + ex.printStackTrace(); + } + return false; + } + + public static void setScore(Player player, int score) { + if (sqlEnabled && isInitialised() && player != null) { + try { + openConnection(); + createDefaultTable((sqlTablePrefix + "score")); + if (tableContainsPlayer(player, (sqlTablePrefix + "score"))) { + PreparedStatement scoreSql = connection.prepareStatement("UPDATE `" + (sqlTablePrefix + "score") + "` SET score=? WHERE uuid=?;"); + scoreSql.setInt(1, score); + scoreSql.setString(2, player.getUniqueId().toString()); + scoreSql.executeUpdate(); + scoreSql.close(); + } else { + PreparedStatement scoreSql = connection.prepareStatement("INSERT INTO `" + (sqlTablePrefix + "score") + "` values(?," + score + ");"); + scoreSql.setString(1, player.getUniqueId().toString()); + scoreSql.execute(); + scoreSql.close(); + } + } catch (Exception ex) { + ex.printStackTrace(); + } finally { + closeConnection(); + } + } + } + +} diff --git a/src/main/java/com/faris/kingkits/Kit.java b/src/main/java/com/faris/kingkits/Kit.java index f46f6d4..1834665 100644 --- a/src/main/java/com/faris/kingkits/Kit.java +++ b/src/main/java/com/faris/kingkits/Kit.java @@ -1,703 +1,699 @@ package com.faris.kingkits; -import com.faris.kingkits.helpers.Utils; +import com.faris.kingkits.helper.Utilities; import org.apache.commons.lang.Validate; import org.apache.commons.lang.WordUtils; -import org.bukkit.Color; -import org.bukkit.Material; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.serialization.ConfigurationSerializable; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.inventory.meta.LeatherArmorMeta; -import org.bukkit.inventory.meta.SkullMeta; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; +import org.bukkit.*; +import org.bukkit.configuration.*; +import org.bukkit.configuration.serialization.*; +import org.bukkit.enchantments.*; +import org.bukkit.inventory.*; +import org.bukkit.inventory.meta.*; +import org.bukkit.potion.*; import java.util.*; public class Kit implements Iterable, ConfigurationSerializable { - private String kitName = ""; - private String realName = ""; - private boolean userKit = false; - private double kitCost = 0D; - private long kitCooldown = 0; - - private List kitCommands = new ArrayList(); - private boolean commandAlias = false; - - private ItemStack guiItem = null; - private int guiPosition = -1; - - private Map kitItems = new HashMap(); - private List kitArmour = new ArrayList(); - private List potionEffects = new ArrayList(); - private Map> killstreakCommands = new HashMap>(); - private List kitDescription = new ArrayList(); - - private boolean itemBreaking = true; - - private int maxHealth = 20; - - public Kit(String kitName) { - Validate.notNull(kitName); - Validate.notEmpty(kitName); - this.kitName = kitName; - this.guiItem = new ItemStack(Material.DIAMOND_SWORD, 1); - } - - public Kit(String kitName, double kitCost) { - Validate.notNull(kitName); - Validate.notEmpty(kitName); - this.kitName = kitName; - this.kitCost = kitCost; - this.guiItem = new ItemStack(Material.DIAMOND_SWORD, 1); - } - - public Kit(String kitName, Map kitItems) { - Validate.notNull(kitName); - Validate.notNull(kitItems); - Validate.notEmpty(kitName); - this.kitName = kitName; - this.kitItems = kitItems; - this.guiItem = new ItemStack(Material.DIAMOND_SWORD, 1); - } - - public Kit(String kitName, Map kitItems, List potionEffects) { - Validate.notNull(kitName); - Validate.notNull(kitItems); - Validate.notNull(potionEffects); - Validate.notEmpty(kitName); - this.kitName = kitName; - this.kitItems = kitItems; - this.potionEffects = potionEffects; - this.guiItem = new ItemStack(Material.DIAMOND_SWORD, 1); - } - - public Kit(String kitName, double kitCost, Map kitItems) { - Validate.notNull(kitName); - Validate.notNull(kitItems); - Validate.notEmpty(kitName); - this.kitName = kitName; - this.kitItems = kitItems; - this.kitCost = kitCost; - this.guiItem = new ItemStack(Material.DIAMOND_SWORD, 1); - } - - public Kit(String kitName, double kitCost, Map kitItems, List potionEffects) { - Validate.notNull(kitName); - Validate.notNull(kitItems); - Validate.notNull(potionEffects); - Validate.notEmpty(kitName); - this.kitName = kitName; - this.kitItems = kitItems; - this.kitCost = kitCost; - this.potionEffects = potionEffects; - this.guiItem = new ItemStack(Material.DIAMOND_SWORD, 1); - } - - public Kit addItem(ItemStack itemStack) { - Validate.notNull(itemStack); - int freeSlot = this.getFreeSlot(); - if (freeSlot >= 0 && freeSlot < 36) this.kitItems.put(freeSlot, itemStack); - return this; - } - - public boolean canItemsBreak() { - return this.itemBreaking; - } - - public List getArmour() { - return Collections.unmodifiableList(this.kitArmour); - } - - public List getCommands() { - return this.kitCommands; - } - - public long getCooldown() { - return this.kitCooldown; - } - - public double getCost() { - return this.kitCost; - } - - public List getDescription() { - return this.kitDescription; - } - - private int getFreeSlot() { - for (int i = 0; i < 36; i++) { - if (!this.kitItems.containsKey(new Integer(i))) return i; - } - return this.kitItems.size() + 1; - } - - public ItemStack getGuiItem() { - return this.guiItem; - } - - public int getGuiPosition() { - return this.guiPosition > 0 ? this.guiPosition : -1; - } - - public List getItems() { - return new ArrayList(this.kitItems.values()); - } - - public Map getItemsWithSlot() { - return Collections.unmodifiableMap(this.kitItems); - } - - public Map> getKillstreaks() { - return this.killstreakCommands; - } - - public int getMaxHealth() { - return this.maxHealth; - } - - public List getMergedItems() { - List kitItems = new ArrayList(this.kitItems.values()); - kitItems.addAll(this.kitArmour); - return Collections.unmodifiableList(kitItems); - } - - public String getName() { - return this.kitName; - } - - public List getPotionEffects() { - return Collections.unmodifiableList(this.potionEffects); - } - - public String getRealName() { - return this.realName; - } - - public boolean hasAlias() { - return this.commandAlias; - } - - public boolean hasCooldown() { - return KingKits.getInstance().configValues.kitCooldown && this.kitCooldown > 0; - } - - public boolean hasDescription() { - return !this.kitDescription.isEmpty(); - } - - public boolean isUserKit() { - return this.userKit; - } - - public Kit removeItem(ItemStack itemStack) { - Validate.notNull(itemStack); - this.kitItems.remove(itemStack); - return this; - } - - public Kit setAlias(boolean commandAlias) { - this.commandAlias = commandAlias; - return this; - } - - public Kit setArmour(List armour) { - if (armour != null) this.kitArmour = armour; - return this; - } - - public Kit setBreakableItems(boolean breakableItems) { - this.itemBreaking = breakableItems; - return this; - } - - public Kit setCommands(List commands) { - Validate.notNull(commands); - this.kitCommands = commands; - return this; - } - - public Kit setCooldown(long cooldown) { - if (this.kitCooldown >= 0L) this.kitCooldown = cooldown; - return this; - } - - public Kit setCost(double cost) { - this.kitCost = cost; - return this; - } - - public Kit setDescription(List description) { - if (description != null) this.kitDescription = description; - return this; - } - - public Kit setGuiItem(ItemStack guiItem) { - this.guiItem = guiItem != null ? guiItem : new ItemStack(Material.AIR); - return this; - } - - public Kit setGuiPosition(int guiPosition) { - this.guiPosition = guiPosition > 0 ? guiPosition : -1; - return this; - } - - public Kit setItems(List items) { - if (items != null) { - this.kitItems = new HashMap(); - for (int i = 0; i < items.size(); i++) { - this.kitItems.put(i, items.get(i)); - } - } - return this; - } - - public Kit setItems(Map items) { - if (items != null) this.kitItems = items; - return this; - } - - public Kit setKillstreaks(Map> killstreaks) { - if (killstreaks != null) this.killstreakCommands = killstreaks; - return this; - } - - public Kit setMaxHealth(int maxHealth) { - this.maxHealth = maxHealth; - return this; - } - - public Kit setName(String name) { - Validate.notNull(name); - Validate.notEmpty(name); - this.kitName = name; - return this; - } - - public Kit setPotionEffects(List potionEffects) { - Validate.notNull(potionEffects); - this.potionEffects = potionEffects; - return this; - } - - public Kit setRealName(String realName) { - Validate.notNull(realName); - this.realName = realName; - return this; - } - - public Kit setUserKit(boolean userKit) { - this.userKit = userKit; - return this; - } - - @SuppressWarnings("deprecation") - @Override - public Map serialize() { - Map serializedKit = new HashMap(); - serializedKit.put("Name", this.kitName != null ? this.kitName : "Kit" + new Random().nextInt()); - serializedKit.put("Cost", this.kitCost); - serializedKit.put("Cooldown", this.kitCooldown); - if (!this.userKit) serializedKit.put("Command alias", false); - serializedKit.put("Commands", this.kitCommands); - serializedKit.put("Item breaking", this.itemBreaking); - serializedKit.put("Max health", this.maxHealth); - serializedKit.put("GUI Position", this.guiPosition); - serializedKit.put("Description", this.kitDescription); - - /** GUI Item **/ - if (this.guiItem != null) { - Map guiItemMap = new HashMap(); - guiItemMap.put("Type", this.guiItem.getType().toString()); - guiItemMap.put("Amount", this.guiItem.getAmount()); - guiItemMap.put("Data", this.guiItem.getDurability()); - // Dye colour - int dyeColour = Utils.ItemUtils.getDye(this.guiItem); - if (dyeColour > 0) - guiItemMap.put("Dye", dyeColour); - // Skull skin - if (this.guiItem.getItemMeta() instanceof SkullMeta) { - SkullMeta skullMeta = (SkullMeta) this.guiItem.getItemMeta(); - if (skullMeta.getOwner() != null) guiItemMap.put("Skin", skullMeta.getOwner()); - } - // Enchantments - Map enchantmentMap = new HashMap(); - for (Map.Entry entrySet : this.guiItem.getEnchantments().entrySet()) - enchantmentMap.put(entrySet.getKey().getName(), entrySet.getValue()); - if (!enchantmentMap.isEmpty()) guiItemMap.put("Enchantments", enchantmentMap); - // Lores - if (this.guiItem.hasItemMeta() && this.guiItem.getItemMeta().hasLore()) - guiItemMap.put("Lore", this.guiItem.getItemMeta().getLore()); - serializedKit.put("GUI Item", guiItemMap); - } - - /** Items **/ - if (this.kitItems != null && !this.kitItems.isEmpty()) { - Map itemsMap = new HashMap(); - for (int i = 0; i < 36; i++) { - ItemStack kitItem = this.kitItems.size() > i ? this.kitItems.get(i) : null; - if (kitItem != null && kitItem.getType() != Material.AIR) { - Map kitItemMap = new LinkedHashMap(); - kitItemMap.put("Type", kitItem.getType().toString()); - String itemName = kitItem.hasItemMeta() && kitItem.getItemMeta().hasDisplayName() ? kitItem.getItemMeta().getDisplayName() : null; - if (itemName != null) kitItemMap.put("Name", Utils.replaceBukkitColour(itemName)); - kitItemMap.put("Amount", kitItem.getAmount()); - kitItemMap.put("Data", kitItem.getDurability()); - if (kitItem.getItemMeta() instanceof LeatherArmorMeta) { - kitItemMap.put("Dye", Utils.ItemUtils.getDye(kitItem)); - } - if (kitItem.getItemMeta() instanceof SkullMeta) { - SkullMeta skullMeta = (SkullMeta) kitItem.getItemMeta(); - if (skullMeta.getOwner() != null) kitItemMap.put("Skin", skullMeta.getOwner()); - } - Map enchantmentMap = new HashMap(); - for (Map.Entry entrySet : kitItem.getEnchantments().entrySet()) - enchantmentMap.put(entrySet.getKey().getName(), entrySet.getValue()); - if (!enchantmentMap.isEmpty()) kitItemMap.put("Enchantments", enchantmentMap); - if (kitItem.hasItemMeta() && kitItem.getItemMeta().hasLore()) - kitItemMap.put("Lore", Utils.replaceBukkitColours(kitItem.getItemMeta().getLore())); - itemsMap.put("Slot " + i, kitItemMap); - } - } - serializedKit.put("Items", itemsMap); - } - - /** Armour **/ - if (this.kitArmour != null && !this.kitArmour.isEmpty()) { - Map armourMap = new HashMap(); - for (ItemStack kitArmour : this.kitArmour) { - if (kitArmour != null) { - Map kitArmourMap = new HashMap(); - String armourName = kitArmour.hasItemMeta() && kitArmour.getItemMeta().hasDisplayName() ? kitArmour.getItemMeta().getDisplayName() : null; - if (armourName != null) kitArmourMap.put("Name", Utils.replaceBukkitColour(armourName)); - kitArmourMap.put("Type", kitArmour.getType().toString()); - kitArmourMap.put("Data", kitArmour.getDurability()); - int dyeColour = Utils.ItemUtils.getDye(kitArmour); - if (dyeColour > 0) - kitArmourMap.put("Dye", dyeColour); - if (kitArmour.getItemMeta() instanceof SkullMeta) { - SkullMeta skullMeta = (SkullMeta) kitArmour.getItemMeta(); - if (skullMeta.getOwner() != null) kitArmourMap.put("Skin", skullMeta.getOwner()); - } - Map enchantmentMap = new HashMap(); - for (Map.Entry entrySet : kitArmour.getEnchantments().entrySet()) - enchantmentMap.put(entrySet.getKey().getName(), entrySet.getValue()); - if (!enchantmentMap.isEmpty()) kitArmourMap.put("Enchantments", enchantmentMap); - if (kitArmour.hasItemMeta() && kitArmour.getItemMeta().hasLore()) - kitArmourMap.put("Lore", Utils.replaceBukkitColours(kitArmour.getItemMeta().getLore())); - String[] armourNameSplit = kitArmour.getType().toString().contains("_") ? kitArmour.getType().toString().split("_") : null; - String armourNameKey = armourNameSplit != null && armourNameSplit.length > 1 ? WordUtils.capitalize(armourNameSplit[1].toLowerCase()) : WordUtils.capitalizeFully(kitArmour.getType().toString().toLowerCase()).replace("_", " "); - armourMap.put(armourNameKey, kitArmourMap); - } - } - serializedKit.put("Armour", armourMap); - } - - /** Potion Effects **/ - if (this.potionEffects != null && !this.potionEffects.isEmpty()) { - Map potionEffectsMap = new HashMap(); - for (PotionEffect potionEffect : this.potionEffects) { - Map potionEffectMap = new HashMap(); - potionEffectMap.put("Level", potionEffect.getAmplifier() + 1); - potionEffectMap.put("Duration", potionEffect.getDuration() / 20); - potionEffectsMap.put(WordUtils.capitalizeFully(potionEffect.getType().getName().toLowerCase().replace("_", " ")), potionEffectMap); - } - if (!potionEffectsMap.isEmpty()) serializedKit.put("Potion Effects", potionEffectsMap); - } - - if (this.killstreakCommands != null && !this.killstreakCommands.isEmpty()) { - Map killstreakCmds = new HashMap(); - for (Map.Entry> killstreakEntry : this.killstreakCommands.entrySet()) { - if (killstreakEntry.getValue() != null && !killstreakEntry.getValue().isEmpty()) { - killstreakCmds.put("Killstreak " + killstreakEntry.getKey(), killstreakEntry.getValue()); - } - } - if (!killstreakCmds.isEmpty()) serializedKit.put("Killstreaks", killstreakCmds); - } - - return serializedKit; - } - - @Override - public Kit clone() { - return new Kit(this.kitName).setRealName(this.realName).setCooldown(this.kitCooldown).setCommands(this.kitCommands).setGuiItem(this.guiItem).setPotionEffects(this.potionEffects).setCost(this.kitCost).setItems(this.kitItems).setArmour(this.kitArmour); - } - - @Override - public ListIterator iterator() { - return this.getMergedItems().listIterator(); - } - - @Override - public String toString() { - return this.serialize().toString(); - } - - public static Kit deserialize(Map kitSection) throws NullPointerException, ClassCastException { - Kit kit = null; - if (kitSection.containsKey("Name")) { - try { - String kitName = getObject(kitSection, "Name", String.class); - kit = new Kit(kitName); - if (kitSection.containsKey("Cost")) kit.setCost(getObject(kitSection, "Cost", Double.class)); - if (kitSection.containsKey("Cooldown")) - kit.setCooldown(getObject(kitSection, "Cooldown", Long.class)); - if (kitSection.get("Command alias") != null) { - kit.setAlias(Boolean.valueOf(kitSection.get("Command alias").toString())); - } - if (kitSection.containsKey("Commands")) kit.setCommands(getObject(kitSection, "Commands", List.class)); - if (kitSection.get("Item breaking") != null) { - kit.setBreakableItems(Boolean.valueOf(kitSection.get("Item breaking").toString())); - } - if (kitSection.containsKey("Max health")) - kit.setMaxHealth(getObject(kitSection, "Max health", Integer.class)); - if (kitSection.containsKey("GUI Position")) - kit.setGuiPosition(getObject(kitSection, "GUI Position", Integer.class)); - if (kitSection.containsKey("Description")) - kit.setDescription(getObject(kitSection, "Description", List.class)); - if (kitSection.containsKey("GUI Item")) { - Map guiItemMap = getValues(kitSection, "GUI Item"); - ItemStack guiItem = null; - if (guiItemMap.containsKey("Type")) { - String strType = (guiItemMap.get("Type") != null ? guiItemMap.get("Type") : "").toString(); - Material itemType = Utils.isInteger(strType) ? Material.getMaterial(Integer.parseInt(strType)) : Material.getMaterial(strType.toUpperCase()); - if (itemType == null || itemType == Material.AIR) itemType = Material.DIAMOND_SWORD; - int itemAmount = guiItemMap.containsKey("Amount") ? getObject(guiItemMap, "Amount", Integer.class) : 1; - short itemData = guiItemMap.containsKey("Data") ? getObject(guiItemMap, "Data", Short.class) : (short) 0; - guiItem = new ItemStack(itemType, itemAmount, itemData); - if (guiItemMap.containsKey("Dye")) { - int itemDye = getObject(guiItemMap, "Dye", Integer.class); - if (itemDye > 0) Utils.ItemUtils.setDye(guiItem, itemDye); - } - if (guiItemMap.containsKey("Skin") && guiItem.getItemMeta() instanceof SkullMeta) { - SkullMeta skullMeta = (SkullMeta) guiItem.getItemMeta(); - skullMeta.setOwner(getObject(guiItemMap, "Skin", String.class)); - guiItem.setItemMeta(skullMeta); - } - if (guiItemMap.containsKey("Enchantments")) { - Map guiItemEnchantments = getValues(guiItemMap, "Enchantments"); - for (Map.Entry entrySet : guiItemEnchantments.entrySet()) { - Enchantment enchantmentType = Utils.isInteger(entrySet.getKey()) ? Enchantment.getById(Integer.parseInt(entrySet.getKey())) : Enchantment.getByName(Utils.getEnchantmentName(entrySet.getKey())); - if (enchantmentType != null) { - String enchantmentValue = entrySet.getValue().toString(); - int enchantmentLevel = Utils.isInteger(enchantmentValue) ? Integer.parseInt(enchantmentValue) : 1; - guiItem.addUnsafeEnchantment(enchantmentType, enchantmentLevel); - } - } - } - if (guiItemMap.containsKey("Lore")) { - List guiItemLore = getObject(guiItemMap, "Lore", List.class); - ItemMeta guiItemMeta = guiItem.getItemMeta(); - if (guiItemMeta != null) { - guiItemMeta.setLore(Utils.replaceChatColours(guiItemLore)); - guiItem.setItemMeta(guiItemMeta); - } - } - } - if (guiItem != null) kit.setGuiItem(guiItem); - } - if (kitSection.containsKey("Items")) { - Map itemsMap = getValues(kitSection, "Items"); - Map kitItems = new HashMap() { - { - for (int i = 0; i < 36; i++) { - this.put(i, new ItemStack(Material.AIR)); - } - } - }; - - for (Map.Entry entrySet : itemsMap.entrySet()) { - String strSlot = entrySet.getKey(); - if (strSlot.contains(" ")) { - String[] slotSplit = strSlot.split(" "); - if (slotSplit[0].equals("Slot") && Utils.isInteger(slotSplit[1])) { - Map kitMap = getValues(entrySet); - String strType = kitMap.containsKey("Type") ? getObject(kitMap, "Type", String.class) : Material.AIR.toString(); - ItemStack kitItem = null; - Material itemType = Utils.isInteger(strType) ? Material.getMaterial(Integer.parseInt(strType)) : Material.getMaterial(strType); - if (itemType == null) continue; - String itemName = kitMap.containsKey("Name") ? getObject(kitMap, "Name", String.class) : ""; - int itemAmount = kitMap.containsKey("Amount") ? getObject(kitMap, "Amount", Integer.class) : 1; - short itemData = kitMap.containsKey("Data") ? getObject(kitMap, "Data", Short.class) : (short) 0; - kitItem = new ItemStack(itemType, itemAmount, itemData); - if (itemName != null && !itemName.isEmpty()) { - ItemMeta itemMeta = kitItem.getItemMeta(); - if (itemMeta != null) { - itemMeta.setDisplayName(Utils.replaceChatColour(itemName)); - kitItem.setItemMeta(itemMeta); - } - } - if (kitMap.containsKey("Dye")) { - int itemDye = getObject(kitMap, "Dye", Integer.class); - if (itemDye > 0) Utils.ItemUtils.setDye(kitItem, itemDye); - } - if (kitMap.containsKey("Skin") && kitItem.getItemMeta() instanceof SkullMeta) { - SkullMeta skullMeta = (SkullMeta) kitItem.getItemMeta(); - skullMeta.setOwner(getObject(kitMap, "Skin", String.class)); - kitItem.setItemMeta(skullMeta); - } - if (kitMap.containsKey("Enchantments")) { - Map guiItemEnchantments = getValues(kitMap, "Enchantments"); - for (Map.Entry enchantmentEntrySet : guiItemEnchantments.entrySet()) { - Enchantment enchantmentType = Utils.isInteger(entrySet.getKey()) ? Enchantment.getById(Integer.parseInt(enchantmentEntrySet.getKey())) : Enchantment.getByName(Utils.getEnchantmentName(enchantmentEntrySet.getKey())); - if (enchantmentType != null) { - String enchantmentValue = enchantmentEntrySet.getValue().toString(); - int enchantmentLevel = Utils.isInteger(enchantmentValue) ? Integer.parseInt(enchantmentValue) : 1; - kitItem.addUnsafeEnchantment(enchantmentType, enchantmentLevel); - } - } - } - if (kitMap.containsKey("Lore")) { - List guiItemLore = getObject(kitMap, "Lore", List.class); - ItemMeta guiItemMeta = kitItem.getItemMeta(); - if (guiItemMeta != null) { - guiItemMeta.setLore(Utils.replaceChatColours(guiItemLore)); - kitItem.setItemMeta(guiItemMeta); - } - } - try { - if (kitItem != null) kitItems.put(Integer.parseInt(slotSplit[1]), kitItem); - } catch (Exception ex) { - System.out.println("Could not register the item at slot " + slotSplit[1] + " in the kit '" + kitName + "' due to a(n) " + ex.getClass().getSimpleName() + " error."); - } - } - } - } - kit.setItems(kitItems); - } - if (kitSection.containsKey("Armour")) { - Map armourItemsMap = getValues(kitSection, "Armour"); - List kitArmour = new ArrayList(); - for (Map.Entry entrySet : armourItemsMap.entrySet()) { - Map kitMap = getValues(entrySet); - String strType = getObject(kitMap, "Type", String.class); - ItemStack kitArmourItem = null; - Material itemType = Utils.isInteger(strType) ? Material.getMaterial(Integer.parseInt(strType)) : Material.getMaterial(strType); - if (itemType == null) continue; - String itemName = kitMap.containsKey("Name") ? getObject(kitMap, "Name", String.class) : ""; - String strItemDye = kitMap.containsKey("Dye") ? kitMap.get("Dye").toString() : "-1"; - int itemDye = Utils.isInteger(strItemDye) ? Integer.parseInt(strItemDye) : Utils.getDye(strItemDye); - int itemAmount = kitMap.containsKey("Amount") ? getObject(kitMap, "Amount", Integer.class) : 1; - short itemData = kitMap.containsKey("Data") ? getObject(kitMap, "Data", Short.class) : (short) 0; - kitArmourItem = new ItemStack(itemType, itemAmount); - kitArmourItem.setDurability(itemData); - if (itemName != null && !itemName.isEmpty()) { - ItemMeta itemMeta = kitArmourItem.getItemMeta(); - if (itemMeta != null) { - itemMeta.setDisplayName(Utils.replaceChatColour(itemName)); - kitArmourItem.setItemMeta(itemMeta); - } - } - if (itemDye != -1) { - ItemMeta itemMeta = kitArmourItem.getItemMeta(); - if (itemMeta != null && itemMeta instanceof LeatherArmorMeta) { - LeatherArmorMeta leatherArmorMeta = (LeatherArmorMeta) itemMeta; - leatherArmorMeta.setColor(Color.fromRGB(itemDye)); - kitArmourItem.setItemMeta(leatherArmorMeta); - } - } - if (kitMap.containsKey("Skin") && kitArmourItem.getItemMeta() instanceof SkullMeta) { - SkullMeta skullMeta = (SkullMeta) kitArmourItem.getItemMeta(); - skullMeta.setOwner(getObject(kitMap, "Skin", String.class)); - kitArmourItem.setItemMeta(skullMeta); - } - if (kitMap.containsKey("Enchantments")) { - Map kitArmourEnchantments = getValues(kitMap, "Enchantments"); - for (Map.Entry enchantmentEntrySet : kitArmourEnchantments.entrySet()) { - Enchantment enchantmentType = Utils.isInteger(entrySet.getKey()) ? Enchantment.getById(Integer.parseInt(enchantmentEntrySet.getKey())) : Enchantment.getByName(Utils.getEnchantmentName(enchantmentEntrySet.getKey())); - if (enchantmentType != null) { - String enchantmentValue = enchantmentEntrySet.getValue().toString(); - int enchantmentLevel = Utils.isInteger(enchantmentValue) ? Integer.parseInt(enchantmentValue) : 1; - kitArmourItem.addUnsafeEnchantment(enchantmentType, enchantmentLevel); - } - } - } - if (kitMap.containsKey("Lore")) { - List armourItemLore = getObject(kitMap, "Lore", List.class); - ItemMeta armourItemMeta = kitArmourItem.getItemMeta(); - if (armourItemMeta != null) { - armourItemMeta.setLore(Utils.replaceChatColours(armourItemLore)); - kitArmourItem.setItemMeta(armourItemMeta); - } - } - if (kitArmourItem != null) kitArmour.add(kitArmourItem); - } - kit.setArmour(kitArmour); - } - if (kitSection.containsKey("Potion Effects")) { - List potionEffectList = new ArrayList(); - Map potionEffectsMap = getValues(kitSection, "Potion Effects"); - if (potionEffectsMap != null) { - for (Map.Entry potionEntrySet : potionEffectsMap.entrySet()) { - PotionEffectType effectType = Utils.isInteger(potionEntrySet.getKey()) ? PotionEffectType.getById(Integer.parseInt(potionEntrySet.getKey())) : PotionEffectType.getByName(Utils.getPotionName(potionEntrySet.getKey())); - if (effectType != null && (potionEntrySet.getValue() instanceof ConfigurationSection || potionEntrySet.getValue() instanceof Map)) { - Map potionEntrySetMap = getValues(potionEntrySet); - int potionLevel = potionEntrySetMap.containsKey("Level") ? getObject(potionEntrySetMap, "Level", Integer.class) : 1; - if (potionLevel > 0) potionLevel--; - int potionDuration = potionEntrySetMap.containsKey("Duration") ? getObject(potionEntrySetMap, "Duration", Integer.class) : Integer.MAX_VALUE; - try { - potionEffectList.add(new PotionEffect(effectType, potionDuration == -1 ? Integer.MAX_VALUE : potionDuration * 20, potionLevel)); - } catch (Exception ex) { - potionEffectList.add(new PotionEffect(effectType, Integer.MAX_VALUE, potionLevel)); - } - } - } - kit.setPotionEffects(potionEffectList); - } - } - if (kitSection.containsKey("Killstreaks")) { - Map> killstreakCmds = new HashMap>(); - Map killstreakMap = getValues(kitSection, "Killstreaks"); - if (killstreakMap != null) { - for (Map.Entry killstreakEntry : killstreakMap.entrySet()) { - if (killstreakEntry.getValue() instanceof List) { - if (killstreakEntry.getKey() != null && killstreakEntry.getKey().startsWith("Killstreak ")) { - String strKillstreak = killstreakEntry.getKey().replaceFirst("Killstreak ", ""); - if (Utils.isLong(strKillstreak)) { - try { - long killstreak = Long.parseLong(strKillstreak); - List cmds = (List) killstreakEntry.getValue(); - if (cmds != null && !cmds.isEmpty()) killstreakCmds.put(killstreak, cmds); - } catch (Exception ex) { - continue; - } - } - } - } - } - kit.setKillstreaks(killstreakCmds); - } - } - } catch (Exception ex) { - ex.printStackTrace(); - } - } - return kit; - } - - @SuppressWarnings("unused") - public static T getObject(Map map, String key, Class unused) throws ClassCastException { - try { - T value = map.containsKey(key) ? (T) map.get(key) : null; - return value != null ? (unused == Long.class ? (T) ((Long) Long.parseLong(value.toString())) : (unused == Integer.class ? (T) ((Integer) Integer.parseInt(value.toString())) : (unused == Short.class ? (T) ((Short) Short.parseShort(value.toString())) : (unused == Double.class ? (T) ((Double) Double.parseDouble(value.toString())) : value)))) : null; - } catch (ClassCastException ex) { - throw ex; - } - } - - public static Map getValues(Map mainMap, String key) { - Object object = mainMap != null ? mainMap.get(key) : null; - return object instanceof ConfigurationSection ? ((ConfigurationSection) object).getValues(false) : (object instanceof Map ? (Map) object : new HashMap()); - } - - public static Map getValues(Object object) { - return object instanceof ConfigurationSection ? ((ConfigurationSection) object).getValues(false) : (object instanceof Map ? (Map) object : new HashMap()); - } - - public static Map getValues(Map.Entry entrySet) { - return entrySet != null ? getValues(entrySet.getValue()) : null; - } + private String kitName = ""; + private String realName = ""; + private boolean userKit = false; + private double kitCost = 0D; + private long kitCooldown = 0; + + private List kitCommands = new ArrayList(); + private boolean commandAlias = false; + + private ItemStack guiItem = null; + private int guiPosition = -1; + + private Map kitItems = new HashMap(); + private List kitArmour = new ArrayList(); + private List potionEffects = new ArrayList(); + private Map> killstreakCommands = new HashMap>(); + private List kitDescription = new ArrayList(); + + private boolean itemBreaking = true; + + private int maxHealth = 20; + + public Kit(String kitName) { + Validate.notNull(kitName); + Validate.notEmpty(kitName); + this.kitName = kitName; + this.guiItem = new ItemStack(Material.DIAMOND_SWORD, 1); + } + + public Kit(String kitName, double kitCost) { + Validate.notNull(kitName); + Validate.notEmpty(kitName); + this.kitName = kitName; + this.kitCost = kitCost; + this.guiItem = new ItemStack(Material.DIAMOND_SWORD, 1); + } + + public Kit(String kitName, Map kitItems) { + Validate.notNull(kitName); + Validate.notNull(kitItems); + Validate.notEmpty(kitName); + this.kitName = kitName; + this.kitItems = kitItems; + this.guiItem = new ItemStack(Material.DIAMOND_SWORD, 1); + } + + public Kit(String kitName, Map kitItems, List potionEffects) { + Validate.notNull(kitName); + Validate.notNull(kitItems); + Validate.notNull(potionEffects); + Validate.notEmpty(kitName); + this.kitName = kitName; + this.kitItems = kitItems; + this.potionEffects = potionEffects; + this.guiItem = new ItemStack(Material.DIAMOND_SWORD, 1); + } + + public Kit(String kitName, double kitCost, Map kitItems) { + Validate.notNull(kitName); + Validate.notNull(kitItems); + Validate.notEmpty(kitName); + this.kitName = kitName; + this.kitItems = kitItems; + this.kitCost = kitCost; + this.guiItem = new ItemStack(Material.DIAMOND_SWORD, 1); + } + + public Kit(String kitName, double kitCost, Map kitItems, List potionEffects) { + Validate.notNull(kitName); + Validate.notNull(kitItems); + Validate.notNull(potionEffects); + Validate.notEmpty(kitName); + this.kitName = kitName; + this.kitItems = kitItems; + this.kitCost = kitCost; + this.potionEffects = potionEffects; + this.guiItem = new ItemStack(Material.DIAMOND_SWORD, 1); + } + + public Kit addItem(ItemStack itemStack) { + Validate.notNull(itemStack); + int freeSlot = this.getFreeSlot(); + if (freeSlot >= 0 && freeSlot < 36) this.kitItems.put(freeSlot, itemStack); + return this; + } + + public boolean canItemsBreak() { + return this.itemBreaking; + } + + public List getArmour() { + return Collections.unmodifiableList(this.kitArmour); + } + + public List getCommands() { + return this.kitCommands; + } + + public long getCooldown() { + return this.kitCooldown; + } + + public double getCost() { + return this.kitCost; + } + + public List getDescription() { + return this.kitDescription; + } + + private int getFreeSlot() { + for (int i = 0; i < 36; i++) { + if (!this.kitItems.containsKey(new Integer(i))) return i; + } + return this.kitItems.size() + 1; + } + + public ItemStack getGuiItem() { + return this.guiItem; + } + + public int getGuiPosition() { + return this.guiPosition > 0 ? this.guiPosition : -1; + } + + public List getItems() { + return new ArrayList(this.kitItems.values()); + } + + public Map getItemsWithSlot() { + return Collections.unmodifiableMap(this.kitItems); + } + + public Map> getKillstreaks() { + return this.killstreakCommands; + } + + public int getMaxHealth() { + return this.maxHealth; + } + + public List getMergedItems() { + List kitItems = new ArrayList(this.kitItems.values()); + kitItems.addAll(this.kitArmour); + return Collections.unmodifiableList(kitItems); + } + + public String getName() { + return this.kitName; + } + + public List getPotionEffects() { + return Collections.unmodifiableList(this.potionEffects); + } + + public String getRealName() { + return this.realName; + } + + public boolean hasAlias() { + return this.commandAlias; + } + + public boolean hasCooldown() { + return KingKits.getInstance().configValues.kitCooldown && this.kitCooldown > 0; + } + + public boolean hasDescription() { + return !this.kitDescription.isEmpty(); + } + + public boolean isUserKit() { + return this.userKit; + } + + public Kit removeItem(ItemStack itemStack) { + Validate.notNull(itemStack); + this.kitItems.remove(itemStack); + return this; + } + + public Kit setAlias(boolean commandAlias) { + this.commandAlias = commandAlias; + return this; + } + + public Kit setArmour(List armour) { + if (armour != null) this.kitArmour = armour; + return this; + } + + public Kit setBreakableItems(boolean breakableItems) { + this.itemBreaking = breakableItems; + return this; + } + + public Kit setCommands(List commands) { + Validate.notNull(commands); + this.kitCommands = commands; + return this; + } + + public Kit setCooldown(long cooldown) { + if (this.kitCooldown >= 0L) this.kitCooldown = cooldown; + return this; + } + + public Kit setCost(double cost) { + this.kitCost = cost; + return this; + } + + public Kit setDescription(List description) { + if (description != null) this.kitDescription = description; + return this; + } + + public Kit setGuiItem(ItemStack guiItem) { + this.guiItem = guiItem != null ? guiItem : new ItemStack(Material.AIR); + return this; + } + + public Kit setGuiPosition(int guiPosition) { + this.guiPosition = guiPosition > 0 ? guiPosition : -1; + return this; + } + + public Kit setItems(List items) { + if (items != null) { + this.kitItems = new HashMap(); + for (int i = 0; i < items.size(); i++) { + this.kitItems.put(i, items.get(i)); + } + } + return this; + } + + public Kit setItems(Map items) { + if (items != null) this.kitItems = items; + return this; + } + + public Kit setKillstreaks(Map> killstreaks) { + if (killstreaks != null) this.killstreakCommands = killstreaks; + return this; + } + + public Kit setMaxHealth(int maxHealth) { + this.maxHealth = maxHealth; + return this; + } + + public Kit setName(String name) { + Validate.notNull(name); + Validate.notEmpty(name); + this.kitName = name; + return this; + } + + public Kit setPotionEffects(List potionEffects) { + Validate.notNull(potionEffects); + this.potionEffects = potionEffects; + return this; + } + + public Kit setRealName(String realName) { + Validate.notNull(realName); + this.realName = realName; + return this; + } + + public Kit setUserKit(boolean userKit) { + this.userKit = userKit; + return this; + } + + @SuppressWarnings("deprecation") + @Override + public Map serialize() { + Map serializedKit = new HashMap(); + serializedKit.put("Name", this.kitName != null ? this.kitName : "Kit" + new Random().nextInt()); + serializedKit.put("Cost", this.kitCost); + serializedKit.put("Cooldown", this.kitCooldown); + if (!this.userKit) serializedKit.put("Command alias", false); + serializedKit.put("Commands", this.kitCommands); + serializedKit.put("Item breaking", this.itemBreaking); + serializedKit.put("Max health", this.maxHealth); + serializedKit.put("GUI Position", this.guiPosition); + serializedKit.put("Description", this.kitDescription); + + /** GUI Item **/ + if (this.guiItem != null) { + Map guiItemMap = new HashMap(); + guiItemMap.put("Type", this.guiItem.getType().toString()); + guiItemMap.put("Amount", this.guiItem.getAmount()); + guiItemMap.put("Data", this.guiItem.getDurability()); + // Dye colour + int dyeColour = Utilities.ItemUtils.getDye(this.guiItem); + if (dyeColour > 0) + guiItemMap.put("Dye", dyeColour); + // Skull skin + if (this.guiItem.getItemMeta() instanceof SkullMeta) { + SkullMeta skullMeta = (SkullMeta) this.guiItem.getItemMeta(); + if (skullMeta.getOwner() != null) guiItemMap.put("Skin", skullMeta.getOwner()); + } + // Enchantments + Map enchantmentMap = new HashMap(); + for (Map.Entry entrySet : this.guiItem.getEnchantments().entrySet()) + enchantmentMap.put(entrySet.getKey().getName(), entrySet.getValue()); + if (!enchantmentMap.isEmpty()) guiItemMap.put("Enchantments", enchantmentMap); + // Lores + if (this.guiItem.hasItemMeta() && this.guiItem.getItemMeta().hasLore()) + guiItemMap.put("Lore", this.guiItem.getItemMeta().getLore()); + serializedKit.put("GUI Item", guiItemMap); + } + + /** Items **/ + if (this.kitItems != null && !this.kitItems.isEmpty()) { + Map itemsMap = new HashMap(); + for (int i = 0; i < 36; i++) { + ItemStack kitItem = this.kitItems.size() > i ? this.kitItems.get(i) : null; + if (kitItem != null && kitItem.getType() != Material.AIR) { + Map kitItemMap = new LinkedHashMap(); + kitItemMap.put("Type", kitItem.getType().toString()); + String itemName = kitItem.hasItemMeta() && kitItem.getItemMeta().hasDisplayName() ? kitItem.getItemMeta().getDisplayName() : null; + if (itemName != null) kitItemMap.put("Name", Utilities.replaceBukkitColour(itemName)); + kitItemMap.put("Amount", kitItem.getAmount()); + kitItemMap.put("Data", kitItem.getDurability()); + if (kitItem.getItemMeta() instanceof LeatherArmorMeta) { + kitItemMap.put("Dye", Utilities.ItemUtils.getDye(kitItem)); + } + if (kitItem.getItemMeta() instanceof SkullMeta) { + SkullMeta skullMeta = (SkullMeta) kitItem.getItemMeta(); + if (skullMeta.getOwner() != null) kitItemMap.put("Skin", skullMeta.getOwner()); + } + Map enchantmentMap = new HashMap(); + for (Map.Entry entrySet : kitItem.getEnchantments().entrySet()) + enchantmentMap.put(entrySet.getKey().getName(), entrySet.getValue()); + if (!enchantmentMap.isEmpty()) kitItemMap.put("Enchantments", enchantmentMap); + if (kitItem.hasItemMeta() && kitItem.getItemMeta().hasLore()) + kitItemMap.put("Lore", Utilities.replaceBukkitColours(kitItem.getItemMeta().getLore())); + itemsMap.put("Slot " + i, kitItemMap); + } + } + serializedKit.put("Items", itemsMap); + } + + /** Armour **/ + if (this.kitArmour != null && !this.kitArmour.isEmpty()) { + Map armourMap = new HashMap(); + for (ItemStack kitArmour : this.kitArmour) { + if (kitArmour != null) { + Map kitArmourMap = new HashMap(); + String armourName = kitArmour.hasItemMeta() && kitArmour.getItemMeta().hasDisplayName() ? kitArmour.getItemMeta().getDisplayName() : null; + if (armourName != null) kitArmourMap.put("Name", Utilities.replaceBukkitColour(armourName)); + kitArmourMap.put("Type", kitArmour.getType().toString()); + kitArmourMap.put("Data", kitArmour.getDurability()); + int dyeColour = Utilities.ItemUtils.getDye(kitArmour); + if (dyeColour > 0) + kitArmourMap.put("Dye", dyeColour); + if (kitArmour.getItemMeta() instanceof SkullMeta) { + SkullMeta skullMeta = (SkullMeta) kitArmour.getItemMeta(); + if (skullMeta.getOwner() != null) kitArmourMap.put("Skin", skullMeta.getOwner()); + } + Map enchantmentMap = new HashMap(); + for (Map.Entry entrySet : kitArmour.getEnchantments().entrySet()) + enchantmentMap.put(entrySet.getKey().getName(), entrySet.getValue()); + if (!enchantmentMap.isEmpty()) kitArmourMap.put("Enchantments", enchantmentMap); + if (kitArmour.hasItemMeta() && kitArmour.getItemMeta().hasLore()) + kitArmourMap.put("Lore", Utilities.replaceBukkitColours(kitArmour.getItemMeta().getLore())); + String[] armourNameSplit = kitArmour.getType().toString().contains("_") ? kitArmour.getType().toString().split("_") : null; + String armourNameKey = armourNameSplit != null && armourNameSplit.length > 1 ? WordUtils.capitalize(armourNameSplit[1].toLowerCase()) : WordUtils.capitalizeFully(kitArmour.getType().toString().toLowerCase()).replace("_", " "); + armourMap.put(armourNameKey, kitArmourMap); + } + } + serializedKit.put("Armour", armourMap); + } + + /** Potion Effects **/ + if (this.potionEffects != null && !this.potionEffects.isEmpty()) { + Map potionEffectsMap = new HashMap(); + for (PotionEffect potionEffect : this.potionEffects) { + Map potionEffectMap = new HashMap(); + potionEffectMap.put("Level", potionEffect.getAmplifier() + 1); + potionEffectMap.put("Duration", potionEffect.getDuration() / 20); + potionEffectsMap.put(WordUtils.capitalizeFully(potionEffect.getType().getName().toLowerCase().replace("_", " ")), potionEffectMap); + } + if (!potionEffectsMap.isEmpty()) serializedKit.put("Potion Effects", potionEffectsMap); + } + + if (this.killstreakCommands != null && !this.killstreakCommands.isEmpty()) { + Map killstreakCmds = new HashMap(); + for (Map.Entry> killstreakEntry : this.killstreakCommands.entrySet()) { + if (killstreakEntry.getValue() != null && !killstreakEntry.getValue().isEmpty()) { + killstreakCmds.put("Killstreak " + killstreakEntry.getKey(), killstreakEntry.getValue()); + } + } + if (!killstreakCmds.isEmpty()) serializedKit.put("Killstreaks", killstreakCmds); + } + + return serializedKit; + } + + @Override + public Kit clone() { + return new Kit(this.kitName).setRealName(this.realName).setCooldown(this.kitCooldown).setCommands(this.kitCommands).setGuiItem(this.guiItem).setPotionEffects(this.potionEffects).setCost(this.kitCost).setItems(this.kitItems).setArmour(this.kitArmour); + } + + @Override + public ListIterator iterator() { + return this.getMergedItems().listIterator(); + } + + @Override + public String toString() { + return this.serialize().toString(); + } + + public static Kit deserialize(Map kitSection) throws NullPointerException, ClassCastException { + Kit kit = null; + if (kitSection.containsKey("Name")) { + try { + String kitName = getObject(kitSection, "Name", String.class); + kit = new Kit(kitName); + if (kitSection.containsKey("Cost")) kit.setCost(getObject(kitSection, "Cost", Double.class)); + if (kitSection.containsKey("Cooldown")) + kit.setCooldown(getObject(kitSection, "Cooldown", Long.class)); + if (kitSection.get("Command alias") != null) { + kit.setAlias(Boolean.valueOf(kitSection.get("Command alias").toString())); + } + if (kitSection.containsKey("Commands")) kit.setCommands(getObject(kitSection, "Commands", List.class)); + if (kitSection.get("Item breaking") != null) { + kit.setBreakableItems(Boolean.valueOf(kitSection.get("Item breaking").toString())); + } + if (kitSection.containsKey("Max health")) + kit.setMaxHealth(getObject(kitSection, "Max health", Integer.class)); + if (kitSection.containsKey("GUI Position")) + kit.setGuiPosition(getObject(kitSection, "GUI Position", Integer.class)); + if (kitSection.containsKey("Description")) + kit.setDescription(getObject(kitSection, "Description", List.class)); + if (kitSection.containsKey("GUI Item")) { + Map guiItemMap = getValues(kitSection, "GUI Item"); + ItemStack guiItem = null; + if (guiItemMap.containsKey("Type")) { + String strType = (guiItemMap.get("Type") != null ? guiItemMap.get("Type") : "").toString(); + Material itemType = Utilities.isInteger(strType) ? Material.getMaterial(Integer.parseInt(strType)) : Material.getMaterial(strType.toUpperCase()); + if (itemType == null || itemType == Material.AIR) itemType = Material.DIAMOND_SWORD; + int itemAmount = guiItemMap.containsKey("Amount") ? getObject(guiItemMap, "Amount", Integer.class) : 1; + short itemData = guiItemMap.containsKey("Data") ? getObject(guiItemMap, "Data", Short.class) : (short) 0; + guiItem = new ItemStack(itemType, itemAmount, itemData); + if (guiItemMap.containsKey("Dye")) { + int itemDye = getObject(guiItemMap, "Dye", Integer.class); + if (itemDye > 0) Utilities.ItemUtils.setDye(guiItem, itemDye); + } + if (guiItemMap.containsKey("Skin") && guiItem.getItemMeta() instanceof SkullMeta) { + SkullMeta skullMeta = (SkullMeta) guiItem.getItemMeta(); + skullMeta.setOwner(getObject(guiItemMap, "Skin", String.class)); + guiItem.setItemMeta(skullMeta); + } + if (guiItemMap.containsKey("Enchantments")) { + Map guiItemEnchantments = getValues(guiItemMap, "Enchantments"); + for (Map.Entry entrySet : guiItemEnchantments.entrySet()) { + Enchantment enchantmentType = Utilities.isInteger(entrySet.getKey()) ? Enchantment.getById(Integer.parseInt(entrySet.getKey())) : Enchantment.getByName(Utilities.getEnchantmentName(entrySet.getKey())); + if (enchantmentType != null) { + String enchantmentValue = entrySet.getValue().toString(); + int enchantmentLevel = Utilities.isInteger(enchantmentValue) ? Integer.parseInt(enchantmentValue) : 1; + guiItem.addUnsafeEnchantment(enchantmentType, enchantmentLevel); + } + } + } + if (guiItemMap.containsKey("Lore")) { + List guiItemLore = getObject(guiItemMap, "Lore", List.class); + ItemMeta guiItemMeta = guiItem.getItemMeta(); + if (guiItemMeta != null) { + guiItemMeta.setLore(Utilities.replaceChatColours(guiItemLore)); + guiItem.setItemMeta(guiItemMeta); + } + } + } + if (guiItem != null) kit.setGuiItem(guiItem); + } + if (kitSection.containsKey("Items")) { + Map itemsMap = getValues(kitSection, "Items"); + Map kitItems = new HashMap() { + { + for (int i = 0; i < 36; i++) { + this.put(i, new ItemStack(Material.AIR)); + } + } + }; + + for (Map.Entry entrySet : itemsMap.entrySet()) { + String strSlot = entrySet.getKey(); + if (strSlot.contains(" ")) { + String[] slotSplit = strSlot.split(" "); + if (slotSplit[0].equals("Slot") && Utilities.isInteger(slotSplit[1])) { + Map kitMap = getValues(entrySet); + String strType = kitMap.containsKey("Type") ? getObject(kitMap, "Type", String.class) : Material.AIR.toString(); + ItemStack kitItem = null; + Material itemType = Utilities.isInteger(strType) ? Material.getMaterial(Integer.parseInt(strType)) : Material.getMaterial(strType); + if (itemType == null) continue; + String itemName = kitMap.containsKey("Name") ? getObject(kitMap, "Name", String.class) : ""; + int itemAmount = kitMap.containsKey("Amount") ? getObject(kitMap, "Amount", Integer.class) : 1; + short itemData = kitMap.containsKey("Data") ? getObject(kitMap, "Data", Short.class) : (short) 0; + kitItem = new ItemStack(itemType, itemAmount, itemData); + if (itemName != null && !itemName.isEmpty()) { + ItemMeta itemMeta = kitItem.getItemMeta(); + if (itemMeta != null) { + itemMeta.setDisplayName(Utilities.replaceChatColour(itemName)); + kitItem.setItemMeta(itemMeta); + } + } + if (kitMap.containsKey("Dye")) { + int itemDye = getObject(kitMap, "Dye", Integer.class); + if (itemDye > 0) Utilities.ItemUtils.setDye(kitItem, itemDye); + } + if (kitMap.containsKey("Skin") && kitItem.getItemMeta() instanceof SkullMeta) { + SkullMeta skullMeta = (SkullMeta) kitItem.getItemMeta(); + skullMeta.setOwner(getObject(kitMap, "Skin", String.class)); + kitItem.setItemMeta(skullMeta); + } + if (kitMap.containsKey("Enchantments")) { + Map guiItemEnchantments = getValues(kitMap, "Enchantments"); + for (Map.Entry enchantmentEntrySet : guiItemEnchantments.entrySet()) { + Enchantment enchantmentType = Utilities.isInteger(entrySet.getKey()) ? Enchantment.getById(Integer.parseInt(enchantmentEntrySet.getKey())) : Enchantment.getByName(Utilities.getEnchantmentName(enchantmentEntrySet.getKey())); + if (enchantmentType != null) { + String enchantmentValue = enchantmentEntrySet.getValue().toString(); + int enchantmentLevel = Utilities.isInteger(enchantmentValue) ? Integer.parseInt(enchantmentValue) : 1; + kitItem.addUnsafeEnchantment(enchantmentType, enchantmentLevel); + } + } + } + if (kitMap.containsKey("Lore")) { + List guiItemLore = getObject(kitMap, "Lore", List.class); + ItemMeta guiItemMeta = kitItem.getItemMeta(); + if (guiItemMeta != null) { + guiItemMeta.setLore(Utilities.replaceChatColours(guiItemLore)); + kitItem.setItemMeta(guiItemMeta); + } + } + try { + if (kitItem != null) kitItems.put(Integer.parseInt(slotSplit[1]), kitItem); + } catch (Exception ex) { + System.out.println("Could not register the item at slot " + slotSplit[1] + " in the kit '" + kitName + "' due to a(n) " + ex.getClass().getSimpleName() + " error."); + } + } + } + } + kit.setItems(kitItems); + } + if (kitSection.containsKey("Armour")) { + Map armourItemsMap = getValues(kitSection, "Armour"); + List kitArmour = new ArrayList(); + for (Map.Entry entrySet : armourItemsMap.entrySet()) { + Map kitMap = getValues(entrySet); + String strType = getObject(kitMap, "Type", String.class); + ItemStack kitArmourItem = null; + Material itemType = Utilities.isInteger(strType) ? Material.getMaterial(Integer.parseInt(strType)) : Material.getMaterial(strType); + if (itemType == null) continue; + String itemName = kitMap.containsKey("Name") ? getObject(kitMap, "Name", String.class) : ""; + String strItemDye = kitMap.containsKey("Dye") ? kitMap.get("Dye").toString() : "-1"; + int itemDye = Utilities.isInteger(strItemDye) ? Integer.parseInt(strItemDye) : Utilities.getDye(strItemDye); + int itemAmount = kitMap.containsKey("Amount") ? getObject(kitMap, "Amount", Integer.class) : 1; + short itemData = kitMap.containsKey("Data") ? getObject(kitMap, "Data", Short.class) : (short) 0; + kitArmourItem = new ItemStack(itemType, itemAmount); + kitArmourItem.setDurability(itemData); + if (itemName != null && !itemName.isEmpty()) { + ItemMeta itemMeta = kitArmourItem.getItemMeta(); + if (itemMeta != null) { + itemMeta.setDisplayName(Utilities.replaceChatColour(itemName)); + kitArmourItem.setItemMeta(itemMeta); + } + } + if (itemDye != -1) { + ItemMeta itemMeta = kitArmourItem.getItemMeta(); + if (itemMeta != null && itemMeta instanceof LeatherArmorMeta) { + LeatherArmorMeta leatherArmorMeta = (LeatherArmorMeta) itemMeta; + leatherArmorMeta.setColor(Color.fromRGB(itemDye)); + kitArmourItem.setItemMeta(leatherArmorMeta); + } + } + if (kitMap.containsKey("Skin") && kitArmourItem.getItemMeta() instanceof SkullMeta) { + SkullMeta skullMeta = (SkullMeta) kitArmourItem.getItemMeta(); + skullMeta.setOwner(getObject(kitMap, "Skin", String.class)); + kitArmourItem.setItemMeta(skullMeta); + } + if (kitMap.containsKey("Enchantments")) { + Map kitArmourEnchantments = getValues(kitMap, "Enchantments"); + for (Map.Entry enchantmentEntrySet : kitArmourEnchantments.entrySet()) { + Enchantment enchantmentType = Utilities.isInteger(entrySet.getKey()) ? Enchantment.getById(Integer.parseInt(enchantmentEntrySet.getKey())) : Enchantment.getByName(Utilities.getEnchantmentName(enchantmentEntrySet.getKey())); + if (enchantmentType != null) { + String enchantmentValue = enchantmentEntrySet.getValue().toString(); + int enchantmentLevel = Utilities.isInteger(enchantmentValue) ? Integer.parseInt(enchantmentValue) : 1; + kitArmourItem.addUnsafeEnchantment(enchantmentType, enchantmentLevel); + } + } + } + if (kitMap.containsKey("Lore")) { + List armourItemLore = getObject(kitMap, "Lore", List.class); + ItemMeta armourItemMeta = kitArmourItem.getItemMeta(); + if (armourItemMeta != null) { + armourItemMeta.setLore(Utilities.replaceChatColours(armourItemLore)); + kitArmourItem.setItemMeta(armourItemMeta); + } + } + if (kitArmourItem != null) kitArmour.add(kitArmourItem); + } + kit.setArmour(kitArmour); + } + if (kitSection.containsKey("Potion Effects")) { + List potionEffectList = new ArrayList(); + Map potionEffectsMap = getValues(kitSection, "Potion Effects"); + if (potionEffectsMap != null) { + for (Map.Entry potionEntrySet : potionEffectsMap.entrySet()) { + PotionEffectType effectType = Utilities.isInteger(potionEntrySet.getKey()) ? PotionEffectType.getById(Integer.parseInt(potionEntrySet.getKey())) : PotionEffectType.getByName(Utilities.getPotionName(potionEntrySet.getKey())); + if (effectType != null && (potionEntrySet.getValue() instanceof ConfigurationSection || potionEntrySet.getValue() instanceof Map)) { + Map potionEntrySetMap = getValues(potionEntrySet); + int potionLevel = potionEntrySetMap.containsKey("Level") ? getObject(potionEntrySetMap, "Level", Integer.class) : 1; + if (potionLevel > 0) potionLevel--; + int potionDuration = potionEntrySetMap.containsKey("Duration") ? getObject(potionEntrySetMap, "Duration", Integer.class) : Integer.MAX_VALUE; + try { + potionEffectList.add(new PotionEffect(effectType, potionDuration == -1 ? Integer.MAX_VALUE : potionDuration * 20, potionLevel)); + } catch (Exception ex) { + potionEffectList.add(new PotionEffect(effectType, Integer.MAX_VALUE, potionLevel)); + } + } + } + kit.setPotionEffects(potionEffectList); + } + } + if (kitSection.containsKey("Killstreaks")) { + Map> killstreakCmds = new HashMap>(); + Map killstreakMap = getValues(kitSection, "Killstreaks"); + if (killstreakMap != null) { + for (Map.Entry killstreakEntry : killstreakMap.entrySet()) { + if (killstreakEntry.getValue() instanceof List) { + if (killstreakEntry.getKey() != null && killstreakEntry.getKey().startsWith("Killstreak ")) { + String strKillstreak = killstreakEntry.getKey().replaceFirst("Killstreak ", ""); + if (Utilities.isLong(strKillstreak)) { + try { + long killstreak = Long.parseLong(strKillstreak); + List cmds = (List) killstreakEntry.getValue(); + if (cmds != null && !cmds.isEmpty()) killstreakCmds.put(killstreak, cmds); + } catch (Exception ex) { + continue; + } + } + } + } + } + kit.setKillstreaks(killstreakCmds); + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } + return kit; + } + + @SuppressWarnings("unused") + public static T getObject(Map map, String key, Class unused) throws ClassCastException { + try { + T value = map.containsKey(key) ? (T) map.get(key) : null; + return value != null ? (unused == Long.class ? (T) ((Long) Long.parseLong(value.toString())) : (unused == Integer.class ? (T) ((Integer) Integer.parseInt(value.toString())) : (unused == Short.class ? (T) ((Short) Short.parseShort(value.toString())) : (unused == Double.class ? (T) ((Double) Double.parseDouble(value.toString())) : value)))) : null; + } catch (ClassCastException ex) { + throw ex; + } + } + + public static Map getValues(Map mainMap, String key) { + Object object = mainMap != null ? mainMap.get(key) : null; + return object instanceof ConfigurationSection ? ((ConfigurationSection) object).getValues(false) : (object instanceof Map ? (Map) object : new HashMap()); + } + + public static Map getValues(Object object) { + return object instanceof ConfigurationSection ? ((ConfigurationSection) object).getValues(false) : (object instanceof Map ? (Map) object : new HashMap()); + } + + public static Map getValues(Map.Entry entrySet) { + return entrySet != null ? getValues(entrySet.getValue()) : null; + } } diff --git a/src/main/java/com/faris/kingkits/Permissions.java b/src/main/java/com/faris/kingkits/Permissions.java index ed7ff5b..3ad3889 100644 --- a/src/main/java/com/faris/kingkits/Permissions.java +++ b/src/main/java/com/faris/kingkits/Permissions.java @@ -1,38 +1,38 @@ package com.faris.kingkits; -import org.bukkit.permissions.Permission; +import org.bukkit.permissions.*; import java.util.ArrayList; import java.util.List; public class Permissions { - public List permissionsList = new ArrayList(); + public List permissionsList = new ArrayList(); - public Permission kitUseCommand = this.registerPermission(new Permission("kingkits.kit.use")); - public Permission kitUseOtherCommand = this.registerPermission(new Permission("kingkits.kit.use.other")); - public Permission kitCreateCommand = this.registerPermission(new Permission("kingkits.kit.create")); - public Permission kitDeleteCommand = this.registerPermission(new Permission("kingkits.kit.delete")); - public Permission kitRenameCommand = this.registerPermission(new Permission("kingkits.kit.rename")); - public Permission kitUCreateCommand = this.registerPermission(new Permission("kingkits.kit.ucreate")); - public Permission kitUDeleteCommand = this.registerPermission(new Permission("kingkits.kit.udelete")); - public Permission kitURenameCommand = this.registerPermission(new Permission("kingkits.kit.urename")); - public Permission kitList = this.registerPermission(new Permission("kingkits.kit.list")); - public Permission kitBypassCooldown = this.registerPermission(new Permission("kingkits.kit.cooldown.bypass")); - public Permission kitUseSign = this.registerPermission(new Permission("kingkits.kit.sign.use")); - public Permission kitCreateSign = this.registerPermission(new Permission("kingkits.kit.sign.create")); - public Permission kitListSign = this.registerPermission(new Permission("kingkits.kit.sign.list")); - public Permission rightClickCompass = this.registerPermission(new Permission("kingkits.compass")); - public Permission quickSoup = this.registerPermission(new Permission("kingkits.quicksoup")); - public Permission refillSoupSingle = this.registerPermission(new Permission("kingkits.refill.single")); - public Permission refillSoupAll = this.registerPermission(new Permission("kingkits.refill.all")); - public Permission cmdConfigManagement = this.registerPermission(new Permission("kingkits.command.config")); - public Permission killstreak = this.registerPermission(new Permission("kingkits.command.killstreak")); - public Permission cmdReloadConfig = this.registerPermission(new Permission("kingkits.command.reload")); - public Permission cmdSetCooldown = this.registerPermission(new Permission("kingkits.command.setcooldown")); + public Permission kitUseCommand = this.registerPermission(new Permission("kingkits.kit.use")); + public Permission kitUseOtherCommand = this.registerPermission(new Permission("kingkits.kit.use.other")); + public Permission kitCreateCommand = this.registerPermission(new Permission("kingkits.kit.create")); + public Permission kitDeleteCommand = this.registerPermission(new Permission("kingkits.kit.delete")); + public Permission kitRenameCommand = this.registerPermission(new Permission("kingkits.kit.rename")); + public Permission kitUCreateCommand = this.registerPermission(new Permission("kingkits.kit.ucreate")); + public Permission kitUDeleteCommand = this.registerPermission(new Permission("kingkits.kit.udelete")); + public Permission kitURenameCommand = this.registerPermission(new Permission("kingkits.kit.urename")); + public Permission kitList = this.registerPermission(new Permission("kingkits.kit.list")); + public Permission kitBypassCooldown = this.registerPermission(new Permission("kingkits.kit.cooldown.bypass")); + public Permission kitUseSign = this.registerPermission(new Permission("kingkits.kit.sign.use")); + public Permission kitCreateSign = this.registerPermission(new Permission("kingkits.kit.sign.create")); + public Permission kitListSign = this.registerPermission(new Permission("kingkits.kit.sign.list")); + public Permission rightClickCompass = this.registerPermission(new Permission("kingkits.compass")); + public Permission quickSoup = this.registerPermission(new Permission("kingkits.quicksoup")); + public Permission refillSoupSingle = this.registerPermission(new Permission("kingkits.refill.single")); + public Permission refillSoupAll = this.registerPermission(new Permission("kingkits.refill.all")); + public Permission cmdConfigManagement = this.registerPermission(new Permission("kingkits.command.config")); + public Permission killstreak = this.registerPermission(new Permission("kingkits.command.killstreak")); + public Permission cmdReloadConfig = this.registerPermission(new Permission("kingkits.command.reload")); + public Permission cmdSetCooldown = this.registerPermission(new Permission("kingkits.command.setcooldown")); - private Permission registerPermission(Permission permission) { - if (this.permissionsList == null) this.permissionsList = new ArrayList(); - if (!this.permissionsList.contains(permission)) this.permissionsList.add(permission); - return permission; - } + private Permission registerPermission(Permission permission) { + if (this.permissionsList == null) this.permissionsList = new ArrayList(); + if (!this.permissionsList.contains(permission)) this.permissionsList.add(permission); + return permission; + } } diff --git a/src/main/java/com/faris/kingkits/Vault.java b/src/main/java/com/faris/kingkits/Vault.java index 01a4c01..59ce02d 100644 --- a/src/main/java/com/faris/kingkits/Vault.java +++ b/src/main/java/com/faris/kingkits/Vault.java @@ -1,26 +1,29 @@ package com.faris.kingkits; -import org.bukkit.plugin.RegisteredServiceProvider; +import org.bukkit.*; +import org.bukkit.plugin.*; public class Vault { - private KingKits plugin = null; - private boolean printed = false; - public Vault(KingKits pluginInstance) { - this.plugin = pluginInstance; - this.printed = false; - } + private boolean printed = false; - public Object getEconomy() { - if (this.plugin.configValues.vaultValues.useEconomy) { - RegisteredServiceProvider economyProvider = this.plugin.getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class); - if (economyProvider != null) return economyProvider.getProvider(); - } - if (!this.printed) { - System.out.println("Vault could not be found."); - this.printed = true; - } - return null; - } + public Vault() { + this.printed = false; + } + + public Object getEconomy() { + if (KingKits.getInstance() != null && KingKits.getInstance().configValues.vaultValues.useEconomy) { + try { + RegisteredServiceProvider economyProvider = Bukkit.getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class); + if (economyProvider != null) return economyProvider.getProvider(); + } catch (Exception ex) { + if (!this.printed) { + System.out.println("Vault could not be found."); + this.printed = true; + } + } + } + return null; + } } diff --git a/src/main/java/com/faris/kingkits/gui/GuiKingKits.java b/src/main/java/com/faris/kingkits/gui/GuiKingKits.java new file mode 100644 index 0000000..e84b015 --- /dev/null +++ b/src/main/java/com/faris/kingkits/gui/GuiKingKits.java @@ -0,0 +1,95 @@ +package com.faris.kingkits.gui; + +import com.faris.kingkits.KingKits; +import org.apache.commons.lang.Validate; +import org.bukkit.*; +import org.bukkit.entity.*; +import org.bukkit.event.*; +import org.bukkit.event.inventory.*; +import org.bukkit.inventory.*; + +import java.util.HashMap; +import java.util.Map; + +public abstract class GuiKingKits implements Listener { + public static Map guiKitMenuMap = new HashMap(); + public static Map guiPreviewKitMap = new HashMap(); + + private Player player = null; + private String playerName = null; + protected Inventory guiInventory = null; + + /** + * Create a new GUI instance. + * + * @param player - The player that is using the menu + * @param inventory - The inventory. + */ + public GuiKingKits(Player player, Inventory inventory) { + Validate.notNull(player); + + this.player = player; + this.playerName = this.player.getName(); + + this.guiInventory = inventory; + if (this.guiInventory == null) + this.guiInventory = this.player.getServer().createInventory(this.player, InventoryType.CHEST); + + if (KingKits.getInstance() != null) + this.player.getServer().getPluginManager().registerEvents(this, this.getPlugin()); + else + this.player.getServer().getPluginManager().registerEvents(this, Bukkit.getPluginManager().getPlugin("KingKits")); + } + + public boolean openMenu() { + this.closeMenu(false, false); + if (!guiPreviewKitMap.containsKey(this.playerName)) { + if (this.getPlayer() != null) { + this.guiInventory.clear(); + this.fillInventory(); + this.getPlayer().openInventory(this.guiInventory); + return true; + } + } + return false; + } + + protected abstract void fillInventory(); + + public void closeMenu(boolean unregisterEvents, boolean closeInventory) { + if (this.guiInventory != null) this.guiInventory.clear(); + if (unregisterEvents) HandlerList.unregisterAll(this); + if (closeInventory && this.player != null) this.player.closeInventory(); + } + + @EventHandler + protected abstract void onPlayerClickInventory(InventoryClickEvent event); + + @EventHandler(priority = EventPriority.LOW) + protected void onPlayerCloseInventory(InventoryCloseEvent event) { + try { + if (this.guiInventory != null && event.getInventory() != null) { + if (event.getPlayer() instanceof Player) { + if (this.playerName.equals(event.getPlayer().getName())) { + this.closeMenu(true, false); + } + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + public Player getPlayer() { + return this.player; + } + + protected String getPlayerName() { + return this.playerName != null ? this.playerName : ""; + } + + protected KingKits getPlugin() { + return KingKits.getInstance(); + } + +} diff --git a/src/main/java/com/faris/kingkits/gui/GuiKitMenu.java b/src/main/java/com/faris/kingkits/gui/GuiKitMenu.java new file mode 100644 index 0000000..6433a12 --- /dev/null +++ b/src/main/java/com/faris/kingkits/gui/GuiKitMenu.java @@ -0,0 +1,220 @@ +package com.faris.kingkits.gui; + +import com.faris.kingkits.KingKits; +import com.faris.kingkits.KingKitsAPI; +import com.faris.kingkits.Kit; +import com.faris.kingkits.helper.Lang; +import com.faris.kingkits.helper.UUIDFetcher; +import com.faris.kingkits.helper.Utilities; +import com.faris.kingkits.helper.container.KitStack; +import com.faris.kingkits.listener.command.SetKit; +import org.bukkit.*; +import org.bukkit.entity.*; +import org.bukkit.event.*; +import org.bukkit.event.inventory.*; +import org.bukkit.event.inventory.InventoryType.*; +import org.bukkit.inventory.*; +import org.bukkit.inventory.meta.*; + +import java.util.ArrayList; +import java.util.List; + +public class GuiKitMenu extends GuiKingKits { + private KitStack[] guiKitStacks = null; + + /** + * Create a new gui menu instance. + * + * @param player - The player that is using the menu + * @param title - The title of the menu + * @param kitStacks - The kits in the menu + */ + public GuiKitMenu(Player player, String title, KitStack[] kitStacks) { + super(player, player.getServer().createInventory(null, KingKits.getInstance() != null ? KingKits.getInstance().configValues.guiSize : 36, title)); + this.guiKitStacks = kitStacks; + } + + @Override + public boolean openMenu() { + try { + if (guiKitMenuMap.containsKey(this.getPlayerName())) { + GuiKitMenu guiKitMenu = guiKitMenuMap.get(this.getPlayerName()); + if (guiKitMenu != null) guiKitMenu.closeMenu(true, true); + guiKitMenuMap.remove(this.getPlayerName()); + } + if (super.openMenu()) { + guiKitMenuMap.put(this.getPlayerName(), this); + return true; + } + } catch (Exception ex) { + ex.printStackTrace(); + } + return false; + } + + @Override + public void closeMenu(boolean unregisterEvents, boolean closeInventory) { + super.closeMenu(unregisterEvents, closeInventory); + guiKitMenuMap.remove(this.getPlayerName()); + } + + @Override + protected void fillInventory() { + if (this.getPlugin().configValues.sortAlphabetically) { + for (int i = 0; i < this.guiKitStacks.length; i++) { + try { + ItemStack currentStack = this.guiKitStacks[i].getItemStack(); + if (currentStack != null) { + if (currentStack.getType() != Material.AIR) { + if (currentStack.getItemMeta() != null) { + ItemMeta itemMeta = currentStack.getItemMeta(); + Kit targetKit = KingKitsAPI.getKitByName(this.guiKitStacks[i].getKitName(), (this.getPlayer() != null ? this.getPlayer().getUniqueId() : UUIDFetcher.lookupName(this.getPlayerName()).getId())); + + ChatColor kitColour = this.getPlayer().hasPermission("kingkits.kits." + (targetKit != null ? targetKit.getRealName().toLowerCase() : Utilities.stripColour(this.guiKitStacks[i].getKitName().toLowerCase()))) ? ChatColor.GREEN : ChatColor.DARK_RED; + itemMeta.setDisplayName(ChatColor.RESET + "" + kitColour + this.guiKitStacks[i].getKitName()); + + if (targetKit != null && targetKit.hasDescription()) { + List kitDescription = new ArrayList(); + for (String descriptionLine : targetKit.getDescription()) { + descriptionLine = Utilities.replaceChatColour(descriptionLine); + descriptionLine = descriptionLine.replace("", this.getPlayerName()); + descriptionLine = descriptionLine.replace("", targetKit.getName()); + descriptionLine = descriptionLine.replace("", String.valueOf(targetKit.getCost())); + descriptionLine = descriptionLine.replace("", String.valueOf(targetKit.getCooldown())); + descriptionLine = descriptionLine.replace("", String.valueOf(targetKit.getMaxHealth())); + kitDescription.add(descriptionLine); + } + itemMeta.setLore(kitDescription); + } + + currentStack.setItemMeta(itemMeta); + } + this.guiInventory.addItem(currentStack); + } + } + } catch (Exception ex) { + continue; + } + } + } else { + List addItems = new ArrayList(); + for (int i = 0; i < this.guiKitStacks.length; i++) { + try { + ItemStack currentStack = this.guiKitStacks[i].getItemStack(); + if (currentStack != null) { + if (currentStack.getType() != Material.AIR) { + Kit targetKit = KingKitsAPI.getKitByName(this.guiKitStacks[i].getKitName(), (this.getPlayer() != null ? this.getPlayer().getUniqueId() : UUIDFetcher.lookupName(this.getPlayerName()).getId())); + if (currentStack.getItemMeta() != null) { + ItemMeta itemMeta = currentStack.getItemMeta(); + ChatColor kitColour = this.getPlayer().hasPermission("kingkits.kits." + (targetKit != null ? targetKit.getRealName().toLowerCase() : Utilities.stripColour(this.guiKitStacks[i].getKitName().toLowerCase()))) ? ChatColor.GREEN : ChatColor.DARK_RED; + itemMeta.setDisplayName(ChatColor.RESET + "" + kitColour + this.guiKitStacks[i].getKitName()); + currentStack.setItemMeta(itemMeta); + } + if (targetKit != null && targetKit.getGuiPosition() > 0 && targetKit.getGuiPosition() < this.guiInventory.getSize()) { + try { + this.guiInventory.setItem(targetKit.getGuiPosition() - 1, currentStack); + } catch (Exception ex) { + ex.printStackTrace(); + addItems.add(currentStack); + } + } else { + addItems.add(currentStack); + } + } + } + } catch (Exception ex) { + continue; + } + } + for (ItemStack itemStack : addItems) { + this.guiInventory.addItem(itemStack); + } + } + } + + /** + * Returns the kit item stacks * + */ + public KitStack[] getKitStacks() { + return this.guiKitStacks; + } + + /** + * Sets the kit item stacks * + */ + public GuiKitMenu setKitStacks(KitStack[] kitStacks) { + this.guiKitStacks = kitStacks; + return this; + } + + @EventHandler + protected void onPlayerClickInventory(InventoryClickEvent event) { + try { + if (this.guiInventory != null && event.getInventory() != null && event.getWhoClicked() != null) { + if (event.getWhoClicked() instanceof Player) { + if (event.getSlot() >= 0) { + if (event.getSlotType() == SlotType.CONTAINER) { + if (event.getWhoClicked().getName().equals(this.getPlayerName())) { + if (event.getCurrentItem() != null && event.getCurrentItem().getType() != Material.AIR) { + ItemStack clickedItem = event.getCurrentItem(); + event.setCurrentItem(null); + event.setCancelled(true); + this.closeMenu(true, true); + if (clickedItem != null && clickedItem.getType() != Material.AIR && clickedItem.getItemMeta() != null) { + final String kitName = Utilities.stripColour(clickedItem.getItemMeta().getDisplayName()); + if (kitName != null) { + final Kit kit = KingKitsAPI.getKitByName(kitName, event.getWhoClicked().getUniqueId()); + if (kit != null) { + if (KingKitsAPI.isUserKit(kit.getRealName(), event.getWhoClicked().getUniqueId()) || event.getWhoClicked().hasPermission("kingkits.kits." + (kit.getRealName().toLowerCase()))) { + final Player player = (Player) event.getWhoClicked(); + boolean validCooldown = true; + if (kit != null && kit.hasCooldown() && !player.hasPermission(this.getPlugin().permissions.kitBypassCooldown)) { + if (this.getPlugin().getCooldownConfig().contains(player.getName() + "." + kit.getRealName())) { + long currentCooldown = this.getPlugin().getCooldown(player.getName(), kit.getRealName()); + if (System.currentTimeMillis() - currentCooldown >= kit.getCooldown() * 1000) { + this.getPlugin().getCooldownConfig().set(player.getName() + "." + kit.getRealName(), null); + this.getPlugin().saveCooldownConfig(); + } else { + Lang.sendMessage(player, Lang.KIT_DELAY, String.valueOf(kit.getCooldown() - ((System.currentTimeMillis() - currentCooldown) / 1000))); + validCooldown = false; + } + } + } + if (validCooldown) { + SetKit.setKingKit(player, kit != null ? kit.getRealName() : kitName, true); + } + } else if (this.getPlugin().configValues.showKitPreview) { + if (!guiPreviewKitMap.containsKey(event.getWhoClicked().getName())) { + final Player player = (Player) event.getWhoClicked(); + player.getServer().getScheduler().runTaskLater(this.getPlugin(), new Runnable() { + public void run() { + if (player != null) { + if (!guiPreviewKitMap.containsKey(player.getName())) { + new GuiPreviewKit(player, kitName).openMenu(); + } + } + } + }, 3L); + } + } + } + } + } + } + } + } + } + } + } + } catch (Exception ex) { + if (event.getInventory() != null && this.guiInventory != null) { + if (this.getPlayer().equals(event.getWhoClicked().getName())) { + event.setCurrentItem(null); + event.setCancelled(true); + this.closeMenu(true, true); + } + } + ex.printStackTrace(); + } + } +} diff --git a/src/main/java/com/faris/kingkits/gui/GuiPreviewKit.java b/src/main/java/com/faris/kingkits/gui/GuiPreviewKit.java new file mode 100644 index 0000000..a107dba --- /dev/null +++ b/src/main/java/com/faris/kingkits/gui/GuiPreviewKit.java @@ -0,0 +1,121 @@ +package com.faris.kingkits.gui; + +import com.faris.kingkits.KingKitsAPI; +import com.faris.kingkits.Kit; +import com.faris.kingkits.helper.Lang; +import org.bukkit.*; +import org.bukkit.entity.*; +import org.bukkit.event.*; +import org.bukkit.event.inventory.*; +import org.bukkit.inventory.*; +import org.bukkit.inventory.meta.*; + +import java.util.ArrayList; +import java.util.List; + +public class GuiPreviewKit extends GuiKingKits { + private List guiItemStacks = null; + + /** + * Create a new Kit GUI preview instance. + * + * @param player - The player that is using the menu + * @param kitName - The kit name + */ + public GuiPreviewKit(Player player, String kitName) { + super(player, player.getServer().createInventory(player, 45, Lang.GUI_PREVIEW_TITLE.getMessage(kitName))); + Kit kit = KingKitsAPI.getKitByName(kitName, true); + this.guiItemStacks = kit != null ? kit.getMergedItems() : new ArrayList(); + } + + @Override + public boolean openMenu() { + try { + if (guiPreviewKitMap.containsKey(this.getPlayerName())) { + GuiPreviewKit guiPreviewKitMenu = guiPreviewKitMap.get(this.getPlayerName()); + if (guiPreviewKitMenu != null) guiPreviewKitMenu.closeMenu(true, true); + guiPreviewKitMap.remove(this.getPlayerName()); + } + if (super.openMenu()) { + guiPreviewKitMap.put(this.getPlayerName(), this); + return true; + } + } catch (Exception ex) { + ex.printStackTrace(); + } + return false; + } + + @Override + public void closeMenu(boolean unregisterEvents, boolean closeInventory) { + super.closeMenu(unregisterEvents, closeInventory); + guiPreviewKitMap.remove(this.getPlayerName()); + } + + @Override + protected void fillInventory() { + for (int itemStackPos = 0; itemStackPos < this.guiItemStacks.size(); itemStackPos++) { + if (itemStackPos < 36) { + ItemStack itemStack = this.guiItemStacks.get(itemStackPos); + if (itemStack != null && itemStack.getType() != Material.AIR) { + this.guiInventory.addItem(itemStack); + } + } + } + ItemStack backItem = new ItemStack(Material.STONE_BUTTON); + ItemMeta backItemMeta = backItem.getItemMeta(); + if (backItemMeta != null) { + backItemMeta.setDisplayName(Lang.GUI_PREVIEW_BACK.getMessage()); + backItem.setItemMeta(backItemMeta); + } + this.guiInventory.setItem(this.guiInventory.getSize() - 1, backItem); + } + + @EventHandler + protected void onPlayerClickInventory(InventoryClickEvent event) { + try { + if (event.getWhoClicked().getName().equals(this.getPlayerName())) { + event.setCancelled(true); + if (event.getWhoClicked() instanceof Player) { + final Player player = (Player) event.getWhoClicked(); + if (event.getSlot() == this.guiInventory.getSize() - 1 && event.getCurrentItem().getType() == Material.STONE_BUTTON) { + this.closeMenu(true, true); + if (!guiKitMenuMap.containsKey(event.getWhoClicked().getName())) { + player.getServer().getScheduler().runTaskLater(this.getPlugin(), new Runnable() { + public void run() { + if (player != null) { + KingKitsAPI.showKitMenu(player); + } + } + }, 3L); + } + } else { + player.getServer().getScheduler().runTaskLater(this.getPlugin(), new Runnable() { + @SuppressWarnings("deprecation") + public void run() { + if (player != null && player.isOnline()) player.updateInventory(); + } + }, 2L); + } + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + @EventHandler(priority = EventPriority.LOW) + protected void onPlayerCloseInventory(InventoryCloseEvent event) { + try { + if (this.guiInventory != null && event.getInventory() != null) { + if (event.getPlayer() instanceof Player) { + if (this.getPlayerName().equals(event.getPlayer().getName())) { + this.closeMenu(true, false); + } + } + } + } catch (Exception ex) { + } + } + +} diff --git a/src/main/java/com/faris/kingkits/guis/GuiKingKits.java b/src/main/java/com/faris/kingkits/guis/GuiKingKits.java deleted file mode 100644 index 56b91fe..0000000 --- a/src/main/java/com/faris/kingkits/guis/GuiKingKits.java +++ /dev/null @@ -1,100 +0,0 @@ -package com.faris.kingkits.guis; - -import com.faris.kingkits.KingKits; -import org.apache.commons.lang.Validate; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.HandlerList; -import org.bukkit.event.Listener; -import org.bukkit.event.inventory.InventoryClickEvent; -import org.bukkit.event.inventory.InventoryCloseEvent; -import org.bukkit.event.inventory.InventoryType; -import org.bukkit.inventory.Inventory; - -import java.util.HashMap; -import java.util.Map; - -public abstract class GuiKingKits implements Listener { - public static Map guiKitMenuMap = new HashMap(); - public static Map guiPreviewKitMap = new HashMap(); - - private Player player = null; - private String playerName = null; - protected Inventory guiInventory = null; - - /** - * Create a new GUI instance. - * - * @param player - The player that is using the menu - * @param inventory - The inventory. - */ - public GuiKingKits(Player player, Inventory inventory) { - Validate.notNull(player); - - this.player = player; - this.playerName = this.player.getName(); - - this.guiInventory = inventory; - if (this.guiInventory == null) - this.guiInventory = this.player.getServer().createInventory(this.player, InventoryType.CHEST); - - if (KingKits.getInstance() != null) - this.player.getServer().getPluginManager().registerEvents(this, this.getPlugin()); - else - this.player.getServer().getPluginManager().registerEvents(this, Bukkit.getPluginManager().getPlugin("KingKits")); - } - - public boolean openMenu() { - this.closeMenu(false, false); - if (!guiPreviewKitMap.containsKey(this.playerName)) { - if (this.getPlayer() != null) { - this.guiInventory.clear(); - this.fillInventory(); - this.getPlayer().openInventory(this.guiInventory); - return true; - } - } - return false; - } - - protected abstract void fillInventory(); - - public void closeMenu(boolean unregisterEvents, boolean closeInventory) { - if (this.guiInventory != null) this.guiInventory.clear(); - if (unregisterEvents) HandlerList.unregisterAll(this); - if (closeInventory && this.player != null) this.player.closeInventory(); - } - - @EventHandler - protected abstract void onPlayerClickInventory(InventoryClickEvent event); - - @EventHandler(priority = EventPriority.LOW) - protected void onPlayerCloseInventory(InventoryCloseEvent event) { - try { - if (this.guiInventory != null && event.getInventory() != null) { - if (event.getPlayer() instanceof Player) { - if (this.playerName.equals(event.getPlayer().getName())) { - this.closeMenu(true, false); - } - } - } - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - public Player getPlayer() { - return this.player; - } - - protected String getPlayerName() { - return this.playerName != null ? this.playerName : ""; - } - - protected KingKits getPlugin() { - return KingKits.getInstance(); - } - -} diff --git a/src/main/java/com/faris/kingkits/guis/GuiKitMenu.java b/src/main/java/com/faris/kingkits/guis/GuiKitMenu.java deleted file mode 100644 index f822b0e..0000000 --- a/src/main/java/com/faris/kingkits/guis/GuiKitMenu.java +++ /dev/null @@ -1,221 +0,0 @@ -package com.faris.kingkits.guis; - -import com.faris.kingkits.KingKits; -import com.faris.kingkits.Kit; -import com.faris.kingkits.helpers.KitStack; -import com.faris.kingkits.helpers.Lang; -import com.faris.kingkits.helpers.Utils; -import com.faris.kingkits.hooks.PvPKits; -import com.faris.kingkits.listeners.commands.SetKit; -import org.bukkit.ChatColor; -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.inventory.InventoryClickEvent; -import org.bukkit.event.inventory.InventoryType.SlotType; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; - -import java.util.ArrayList; -import java.util.List; - -public class GuiKitMenu extends GuiKingKits { - private KitStack[] guiKitStacks = null; - - /** - * Create a new gui menu instance. - * - * @param player - The player that is using the menu - * @param title - The title of the menu - * @param kitStacks - The kits in the menu - */ - public GuiKitMenu(Player player, String title, KitStack[] kitStacks) { - super(player, player.getServer().createInventory(null, KingKits.getInstance() != null ? KingKits.getInstance().configValues.guiSize : 36, title)); - this.guiKitStacks = kitStacks; - } - - @Override - public boolean openMenu() { - try { - if (guiKitMenuMap.containsKey(this.getPlayerName())) { - GuiKitMenu guiKitMenu = guiKitMenuMap.get(this.getPlayerName()); - if (guiKitMenu != null) { - guiKitMenu.closeMenu(true, true); - guiKitMenuMap.remove(this.getPlayerName()); - } - } - if (super.openMenu()) { - guiKitMenuMap.put(this.getPlayerName(), this); - return true; - } - } catch (Exception ex) { - } - return false; - } - - @Override - public void closeMenu(boolean unregisterEvents, boolean closeInventory) { - super.closeMenu(unregisterEvents, closeInventory); - guiKitMenuMap.remove(this.getPlayerName()); - } - - @Override - protected void fillInventory() { - if (this.getPlugin().configValues.sortAlphabetically) { - for (int i = 0; i < this.guiKitStacks.length; i++) { - try { - ItemStack currentStack = this.guiKitStacks[i].getItemStack(); - if (currentStack != null) { - if (currentStack.getType() != Material.AIR) { - if (currentStack.getItemMeta() != null) { - ItemMeta itemMeta = currentStack.getItemMeta(); - Kit targetKit = PvPKits.getKitByName(this.guiKitStacks[i].getKitName(), this.getPlayerName()); - - ChatColor kitColour = this.getPlayer().hasPermission("kingkits.kits." + (targetKit != null ? targetKit.getRealName().toLowerCase() : Utils.stripColour(this.guiKitStacks[i].getKitName().toLowerCase()))) ? ChatColor.GREEN : ChatColor.DARK_RED; - itemMeta.setDisplayName(ChatColor.RESET + "" + kitColour + this.guiKitStacks[i].getKitName()); - - if (targetKit != null && targetKit.hasDescription()) { - List kitDescription = new ArrayList(); - for (String descriptionLine : targetKit.getDescription()) { - descriptionLine = Utils.replaceChatColour(descriptionLine); - descriptionLine = descriptionLine.replace("", this.getPlayerName()); - descriptionLine = descriptionLine.replace("", targetKit.getName()); - descriptionLine = descriptionLine.replace("", String.valueOf(targetKit.getCost())); - descriptionLine = descriptionLine.replace("", String.valueOf(targetKit.getCooldown())); - descriptionLine = descriptionLine.replace("", String.valueOf(targetKit.getMaxHealth())); - kitDescription.add(descriptionLine); - } - itemMeta.setLore(kitDescription); - } - - currentStack.setItemMeta(itemMeta); - } - this.guiInventory.addItem(currentStack); - } - } - } catch (Exception ex) { - continue; - } - } - } else { - List addItems = new ArrayList(); - for (int i = 0; i < this.guiKitStacks.length; i++) { - try { - ItemStack currentStack = this.guiKitStacks[i].getItemStack(); - if (currentStack != null) { - if (currentStack.getType() != Material.AIR) { - Kit targetKit = PvPKits.getKitByName(this.guiKitStacks[i].getKitName(), this.getPlayerName()); - if (currentStack.getItemMeta() != null) { - ItemMeta itemMeta = currentStack.getItemMeta(); - ChatColor kitColour = this.getPlayer().hasPermission("kingkits.kits." + (targetKit != null ? targetKit.getRealName().toLowerCase() : Utils.stripColour(this.guiKitStacks[i].getKitName().toLowerCase()))) ? ChatColor.GREEN : ChatColor.DARK_RED; - itemMeta.setDisplayName(ChatColor.RESET + "" + kitColour + this.guiKitStacks[i].getKitName()); - currentStack.setItemMeta(itemMeta); - } - if (targetKit != null && targetKit.getGuiPosition() > 0 && targetKit.getGuiPosition() < this.guiInventory.getSize()) { - try { - this.guiInventory.setItem(targetKit.getGuiPosition() - 1, currentStack); - } catch (Exception ex) { - ex.printStackTrace(); - addItems.add(currentStack); - } - } else { - addItems.add(currentStack); - } - } - } - } catch (Exception ex) { - continue; - } - } - for (ItemStack itemStack : addItems) { - this.guiInventory.addItem(itemStack); - } - } - } - - /** - * Returns the kit item stacks * - */ - public KitStack[] getKitStacks() { - return this.guiKitStacks; - } - - /** - * Sets the kit item stacks * - */ - public GuiKitMenu setKitStacks(KitStack[] kitStacks) { - this.guiKitStacks = kitStacks; - return this; - } - - @EventHandler - protected void onPlayerClickInventory(InventoryClickEvent event) { - try { - if (this.guiInventory != null && event.getInventory() != null && event.getWhoClicked() != null) { - if (event.getWhoClicked() instanceof Player) { - if (event.getSlot() >= 0) { - if (event.getSlotType() == SlotType.CONTAINER) { - if (event.getWhoClicked().getName().equals(this.getPlayerName())) { - if (event.getCurrentItem() != null && event.getCurrentItem().getType() != Material.AIR) { - ItemStack clickedItem = event.getCurrentItem(); - event.setCurrentItem(null); - event.setCancelled(true); - this.closeMenu(true, true); - if (clickedItem != null && clickedItem.getType() != Material.AIR && clickedItem.getItemMeta() != null) { - final String kitName = Utils.stripColour(clickedItem.getItemMeta().getDisplayName()); - if (kitName != null) { - final Kit kit = PvPKits.getKitByName(kitName, this.getPlayerName()); - if (kit != null) { - if (PvPKits.isUserKit(event.getWhoClicked().getName(), kit.getRealName()) || event.getWhoClicked().hasPermission("kingkits.kits." + (kit.getRealName().toLowerCase()))) { - final Player player = (Player) event.getWhoClicked(); - boolean validCooldown = true; - if (kit != null && kit.hasCooldown() && !player.hasPermission(this.getPlugin().permissions.kitBypassCooldown)) { - if (this.getPlugin().getCooldownConfig().contains(player.getName() + "." + kit.getRealName())) { - long currentCooldown = this.getPlugin().getCooldown(player.getName(), kit.getRealName()); - if (System.currentTimeMillis() - currentCooldown >= kit.getCooldown() * 1000) { - this.getPlugin().getCooldownConfig().set(player.getName() + "." + kit.getRealName(), null); - this.getPlugin().saveCooldownConfig(); - } else { - Lang.sendMessage(player, Lang.KIT_DELAY, String.valueOf(kit.getCooldown() - ((System.currentTimeMillis() - currentCooldown) / 1000))); - validCooldown = false; - } - } - } - if (validCooldown) { - SetKit.setKingKit(player, kit != null ? kit.getRealName() : kitName, true); - } - } else if (this.getPlugin().configValues.showKitPreview) { - if (!guiPreviewKitMap.containsKey(event.getWhoClicked().getName())) { - final Player player = (Player) event.getWhoClicked(); - player.getServer().getScheduler().runTaskLater(this.getPlugin(), new Runnable() { - public void run() { - if (player != null) { - if (!guiPreviewKitMap.containsKey(player.getName())) { - new GuiPreviewKit(player, kitName).openMenu(); - } - } - } - }, 3L); - } - } - } - } - } - } - } - } - } - } - } - } catch (Exception ex) { - if (event.getInventory() != null && this.guiInventory != null) { - if (this.getPlayer().equals(event.getWhoClicked().getName())) { - event.setCurrentItem(null); - event.setCancelled(true); - this.closeMenu(true, true); - } - } - ex.printStackTrace(); - } - } -} diff --git a/src/main/java/com/faris/kingkits/guis/GuiPreviewKit.java b/src/main/java/com/faris/kingkits/guis/GuiPreviewKit.java deleted file mode 100644 index c88c0aa..0000000 --- a/src/main/java/com/faris/kingkits/guis/GuiPreviewKit.java +++ /dev/null @@ -1,122 +0,0 @@ -package com.faris.kingkits.guis; - -import com.faris.kingkits.Kit; -import com.faris.kingkits.helpers.Lang; -import com.faris.kingkits.hooks.PvPKits; -import org.bukkit.ChatColor; -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.inventory.InventoryClickEvent; -import org.bukkit.event.inventory.InventoryCloseEvent; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; - -import java.util.ArrayList; -import java.util.List; - -public class GuiPreviewKit extends GuiKingKits { - private List guiItemStacks = null; - - /** - * Create a new Kit GUI preview instance. - * - * @param player - The player that is using the menu - * @param kitName - The kit name - */ - public GuiPreviewKit(Player player, String kitName) { - super(player, player.getServer().createInventory(player, 45, Lang.GUI_PREVIEW_TITLE.getMessage(kitName))); - Kit kit = PvPKits.getKitByName(kitName); - this.guiItemStacks = kit != null ? kit.getMergedItems() : new ArrayList(); - } - - @Override - public boolean openMenu() { - if (guiPreviewKitMap.containsKey(this.getPlayerName())) { - GuiPreviewKit guiPreviewKitMenu = guiPreviewKitMap.get(this.getPlayerName()); - if (guiPreviewKitMenu != null) { - guiPreviewKitMenu.closeMenu(true, true); - guiPreviewKitMap.remove(this.getPlayerName()); - } - } - if (super.openMenu()) { - guiPreviewKitMap.put(this.getPlayerName(), this); - return true; - } - return false; - } - - @Override - public void closeMenu(boolean unregisterEvents, boolean closeInventory) { - super.closeMenu(unregisterEvents, closeInventory); - guiPreviewKitMap.remove(this.getPlayerName()); - } - - @Override - protected void fillInventory() { - for (int itemStackPos = 0; itemStackPos < this.guiItemStacks.size(); itemStackPos++) { - if (itemStackPos < 36) { - ItemStack itemStack = this.guiItemStacks.get(itemStackPos); - if (itemStack != null && itemStack.getType() != Material.AIR) { - this.guiInventory.addItem(itemStack); - } - } - } - ItemStack backItem = new ItemStack(Material.STONE_BUTTON); - ItemMeta backItemMeta = backItem.getItemMeta(); - if (backItemMeta != null) { - backItemMeta.setDisplayName(Lang.GUI_PREVIEW_BACK.getMessage()); - backItem.setItemMeta(backItemMeta); - } - this.guiInventory.setItem(this.guiInventory.getSize() - 1, backItem); - } - - @EventHandler - protected void onPlayerClickInventory(InventoryClickEvent event) { - try { - if (event.getWhoClicked().getName().equals(this.getPlayerName())) { - event.setCancelled(true); - if (event.getWhoClicked() instanceof Player) { - final Player player = (Player) event.getWhoClicked(); - if (event.getSlot() == this.guiInventory.getSize() - 1 && event.getCurrentItem().getType() == Material.STONE_BUTTON) { - this.closeMenu(true, true); - if (!guiKitMenuMap.containsKey(event.getWhoClicked().getName())) { - player.getServer().getScheduler().runTaskLater(this.getPlugin(), new Runnable() { - public void run() { - if (player != null) { - PvPKits.showKitMenu(player); - } - } - }, 3L); - } - } else { - player.getServer().getScheduler().runTaskLater(this.getPlugin(), new Runnable() { - @SuppressWarnings("deprecation") - public void run() { - if (player != null && player.isOnline()) player.updateInventory(); - } - }, 2L); - } - } - } - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - @EventHandler(priority = EventPriority.LOW) - protected void onPlayerCloseInventory(InventoryCloseEvent event) { - try { - if (this.guiInventory != null && event.getInventory() != null) { - if (event.getPlayer() instanceof Player) { - if (this.getPlayerName().equals(event.getPlayer().getName())) { - this.closeMenu(true, false); - } - } - } - } catch (Exception ex) { - } - } - -} diff --git a/src/main/java/com/faris/kingkits/helper/Lang.java b/src/main/java/com/faris/kingkits/helper/Lang.java new file mode 100644 index 0000000..4913d21 --- /dev/null +++ b/src/main/java/com/faris/kingkits/helper/Lang.java @@ -0,0 +1,156 @@ +package com.faris.kingkits.helper; + +import org.bukkit.command.*; +import org.bukkit.configuration.file.*; +import org.bukkit.plugin.java.*; + +import java.io.File; + +/** + * Based off 1Rogue's Lang class. + */ +public enum Lang { + PREFIX("Prefix.Plugin", "&6[&4KingKits&6] &a"), + + COMMAND_GEN_IN_GAME("Command.General.In-game", "&cYou must be a player to use that command!"), + COMMAND_GEN_ERROR("Command.General.Error", "&cAn error occurred."), + COMMAND_GEN_NO_PERMISSION("Command.General.No permission", "&4You do not have access to that command."), + COMMAND_GEN_USAGE("Command.General.Usage", "&cUsage: &4/%s"), + COMMAND_GEN_DISABLED("Command.General.Disabled", "&cThis command is disabled in the configuration."), + COMMAND_GEN_WORLD("Command.General.World", "&cYou cannot use this command in the world you are in."), + COMMAND_GEN_NOT_ONLINE("Command.General.Not online", "%s does not exist or is not online."), + + COMMAND_CREATE_ILLEGAL_CHARACTERS("Command.Create kit.Illegal characters", "&6The kit name must only consist of letters, numbers and underscores."), + COMMAND_CREATE_DENIED("Command.Create kit.Denied", "&cA plugin has not allowed you to create this kit."), + COMMAND_CREATE_EMPTY_INV("Command.Create kit.Empty inventory", "&cYou have nothing in your inventory!"), + COMMAND_CREATE_OVERWRITTEN("Command.Create kit.Overwrite", "&4%s &6has been overwritten."), + COMMAND_CREATE_CREATED("Command.Create kit.Created", "&4%s &6has been created."), + COMMAND_CREATE_KIT_DESCRIPTION("Command.Create kit.Global.Description", "&cDescription: &4Create your own PvP kit with every item in your inventory."), + COMMAND_CREATE_UKIT_DESCRIPTION("Command.Create kit.User.Description", "&cDescription: &4Create your own personal PvP kit with every item in your inventory."), + COMMAND_CREATE_UKIT_EXISTS("Command.Create kit.User.Global kit exists", "&cA PvP kit already exists with that name!"), + COMMAND_CREATE_UKIT_MAX_PERSONAL_KITS("Command.Create kit.User.Maximum personal kits", "&cYou have reached the maximum number of personal kits you can create."), + + COMMAND_DELETE_ERROR("Command.Delete kit.Error", "&4%s&6's deletion was unsuccessful."), + COMMAND_DELETE_DELETED("Command.Delete kit.Deleted", "&4%s &6was successfully deleted."), + COMMAND_DELETE_PLAYER("Command.Delete kit.Player message", "&4%s &cdeleted the kit you were using!"), + COMMAND_DELETE_KIT_NONEXISTENT("Command.Delete kit.Global.Non-existent", "&4That kit does not exist."), + COMMAND_DELETE_KIT_DESCRIPTION("Command.Delete kit.Global.Description", "&cDescription: &4Delete a PvP Kit."), + COMMAND_DELETE_UKIT_NONEXISTENT("Command.Delete kit.User.Non-existent", "&4That user kit does not exist."), + COMMAND_DELETE_UKIT_DESCRIPTION("Command.Delete kit.User.Description", "&cDescription: &4Delete a personal PvP Kit."), + + COMMAND_KIT_LIST_NO_PERMISSION("Command.Kit.List.No permission", "&4You do not have permission to list the kits."), + COMMAND_KIT_OTHER_PLAYER("Command.Kit.Other player", "&6You set %s's kit. This may not have been successful if you typed an invalid kit name, if they already have a kit, if they do not have permission to use that kit or they do not have enough money."), + + COMMAND_REFILL_BOWL("Command.Refill.Bowl", "&cYou must have a bowl in your hand."), + COMMAND_REFILL_NOT_ENOUGH_MONEY("Command.Refill.Not enough money", "&aYou do not have enough money to refill your bowl(s)."), + COMMAND_REFILL_FULL_INV("Command.Refill.Full inventory", "&cYou have a full inventory!"), + + COMMAND_RENAME_ILLEGAL_CHARACTERS("Command.Rename kit.Illegal characters", "&6The new kit name must only consist of letters, numbers and underscores."), + COMMAND_RENAME_ALREADY_EXISTS("Command.Rename kit.Exists", "&c%s already exists."), + COMMAND_RENAME_RENAMED("Command.Rename kit.Renamed", "&6Successfully renamed %s to %s."), + COMMAND_RENAME_KIT_DESCRIPTION("Command.Rename kit.Global.Description", "&cDescription: &4Rename a PvP kit."), + COMMAND_RENAME_UKIT_DESCRIPTION("Command.Rename kit.User.Description", "&cDescription: &4Rename a user PvP kit."), + + COMPASS_POINTING_PLAYER("Compass.Player", "&eYour compass is pointing to %s."), + COMPASS_POINTING_SPAWN("Compass.Spawn", "Your compass is pointing to spawn."), + + GEN_KIT_LIST("General.Kit list", "&6PvP Kits: &a%s"), + GEN_KIT_LIST_TITLE("General.Kit list title", "&aKits (%s):"), + GEN_NO_KIT_SELECTED("General.No kit selected", "&cYou have not chosen a kit."), + GEN_NO_KITS("General.No kits", "&4There are no kits."), + GEN_NO_KITS_AVAILABLE("General.No kits available", "&cNo kits available"), + GEN_ITEM_DROP("General.Item drop", "&cYou cannot drop this item whilst using a kit."), + GEN_ITEM_PICKUP("General.Item pickup", "&cYou cannot drop this item whilst using a kit."), + + GUI_PREVIEW_TITLE("GUI.Preview.Title", "&c%s &7kit preview"), + GUI_PREVIEW_BACK("GUI.Preview.Back", "&bBack"), + + KIT_NO_PERMISSION("Kit.No permission", "&cYou do not have permission to use the kit &4%s&c."), + KIT_DELAY("Kit.Delay", "&cYou must wait %s second(s) before using this kit again."), + KIT_ALREADY_CHOSEN("Kit.Already chosen", "&6You have already chosen a kit!"), + KIT_NONEXISTENT("Kit.Non-existent", "&4%s &6does not exist."), + KIT_NOT_ENOUGH_MONEY("Kit.Not enough money", "&aYou do not have enough money to change kits."), + + SIGN_CREATE_NO_PERMISSION("Sign.Create.No permission", "&4You do not have access to create a KingKits %s sign."), + SIGN_CREATE_SECOND_LINE("Sign.Create.Second line empty", "&cPlease enter a kit name on the second line."), + + SIGN_GENERAL_INCORRECTLY_SETUP("Sign.General.Incorrectly set up", "&cThat sign has incorrectly been set up."), + + SIGN_USE_NO_PERMISSION("Sign.Use.No permission", "&cYou do not have permission to use this sign."); + + private static YamlConfiguration config = null; + private static File configFile = null; + + private String key = ""; + private String defaultValue = ""; + + private Lang(String key, String defValue) { + this.key = key; + this.defaultValue = defValue; + } + + public String getMessage() { + return replaceChatColours(this.getRawMessage()); + } + + public String getMessage(Object... format) { + return replaceChatColours(String.format(this.getRawMessage(), format)); + } + + public String getRawMessage() { + return config != null ? config.getString(this.key, this.defaultValue) : this.defaultValue; + } + + public String getReplacedMessage(Object... objects) { + String langMessage = this.getRawMessage(); + if (objects != null) { + Object firstObject = ""; + for (int i = 0; i < objects.length; i++) { + if (i == 0 || i % 2 == 0) { + firstObject = objects[i] != null ? objects[i].toString() : "null"; + } else { + if (firstObject != null) + langMessage = langMessage.replace(firstObject.toString(), (objects[i] != null ? objects[i].toString() : "null")); + } + } + } + return replaceChatColours(langMessage); + } + + public static void sendMessage(CommandSender sender, Lang lang) { + sender.sendMessage(PREFIX.getMessage() + lang.getMessage()); + } + + public static void sendMessage(CommandSender sender, Lang lang, Object... objects) { + sender.sendMessage(PREFIX.getMessage() + lang.getMessage(objects)); + } + + public static void sendReplacedMessage(CommandSender sender, Lang lang, Object... objects) { + sender.sendMessage(lang.getReplacedMessage(objects)); + } + + public static void sendRawMessage(CommandSender sender, Lang lang) { + sender.sendMessage(lang.getMessage()); + } + + public static void sendRawMessage(CommandSender sender, Lang lang, Object... objects) { + sender.sendMessage(lang.getMessage(objects)); + } + + public static void init(JavaPlugin plugin) { + configFile = new File(plugin.getDataFolder(), "messages.yml"); + config = YamlConfiguration.loadConfiguration(configFile); + + for (Lang value : values()) { + if (!config.isSet(value.key)) config.set(value.key, value.defaultValue); + } + try { + config.save(configFile); + } catch (Exception ex) { + } + } + + private static String replaceChatColours(String aString) { + return Utilities.replaceChatColour(aString); + } +} \ No newline at end of file diff --git a/src/main/java/com/faris/kingkits/helper/UUIDFetcher.java b/src/main/java/com/faris/kingkits/helper/UUIDFetcher.java new file mode 100644 index 0000000..d3da4e5 --- /dev/null +++ b/src/main/java/com/faris/kingkits/helper/UUIDFetcher.java @@ -0,0 +1,352 @@ +/** + * The MIT License (MIT) + * + * Copyright (c) 2015 Techcable + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.faris.kingkits.helper; + +import org.bukkit.*; +import org.bukkit.entity.*; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.lang.ref.SoftReference; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.*; + +/** + * Utilities to lookup player usernames and UUIDs from mojang. + * This caches results so you won't have issues with the rate limit. + * + * @author Techcable + */ +public class UUIDFetcher { + + private static Cache nameCache = new Cache<>(); + + /** + * Lookup a profile with the given name. + * + * @param name Look for a profile with this name. + * @return A profile with the given name + */ + public static PlayerProfile lookupName(String name) { + if (name != null) { + try { + if (nameCache.contains(name)) return nameCache.get(name); + List response = postNames(Collections.singletonList(name)); + if (response == null || response.isEmpty()) return null; + return response.get(0); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + return null; + } + + /** + * Lookup a profile with the given name. + * + * @param names Look for a profile with this name. + * @return A profile with the given name + */ + public static Map lookupNames(List names) { + Map playerProfiles = new HashMap(); + if (names != null && !names.isEmpty()) { + List removeIndexes = new ArrayList(); + for (int i = 0; i < names.size(); i++) { + String name = names.get(i); + if (nameCache.contains(name)) { + PlayerProfile playerProfile = nameCache.get(name); + playerProfiles.put(playerProfile.getName(), playerProfile.getId()); + removeIndexes.add(new Integer(i)); + } + } + for (Integer removeIndex : removeIndexes) names.remove(removeIndex.intValue()); + try { + List response = postNames(names); + if (response != null) { + for (PlayerProfile playerProfile : response) { + playerProfiles.put(playerProfile.getName(), playerProfile.getId()); + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } + return playerProfiles; + } + + /** + * Lookup a profile with the given UUID. + * + * @param playerUUID Look for a profile with this UUID. + * @return A profile with the given UUID. + */ + public static PlayerProfile lookupID(UUID playerUUID) { + return playerUUID != null && Bukkit.getPlayer(playerUUID) != null ? fromPlayer(Bukkit.getPlayer(playerUUID)) : lookupProperties(playerUUID); + } + + /** + * Lookup the player's properties + * + * @param playerUUID Player's UUID to lookup. + * @return The player's profile with properties + */ + private static PlayerProfile lookupProperties(UUID playerUUID) { + try { + if (idCache.contains(playerUUID)) return idCache.get(playerUUID); + Object rawResponse = getJson("https://sessionserver.mojang.com/session/minecraft/profile/" + toString(playerUUID)); + if (rawResponse == null || !(rawResponse instanceof JSONObject)) return null; + JSONObject response = (JSONObject) rawResponse; + PlayerProfile profile = deserializeProfile(response); + if (profile == null) return null; + idCache.put(playerUUID, profile); + return profile; + } catch (Exception ex) { + ex.printStackTrace(); + return null; + } + } + + /** + * Represents a player. + * + * @author Techcable + */ + public static class PlayerProfile { + public PlayerProfile(UUID id, String name) { + this.id = id; + this.name = name; + } + + private JSONArray properties; + private final UUID id; + private final String name; + + /** + * Get this player's UUID. + * + * @return This player's UUID + */ + public UUID getId() { + return this.id; + } + + /** + * Get this player's name. + * + * @return This player's name + */ + public String getName() { + return this.name; + } + + /** + * Get a JSON array with this player's properties. + * Returns null if this players properties haven't been retrieved. + * + * @return A JSON array with this player's properties or null if not retrieved + */ + public JSONArray getProperties() { + return this.properties != null ? this.properties : (this.properties = new JSONArray()); + } + } + + + private static Cache idCache = new Cache<>(); + + private static List postNames(List names) throws Exception { + JSONArray request = new JSONArray(); + for (String name : names) { + request.add(name); + } + Object rawResponse = postJson("https://api.mojang.com/profiles/minecraft", request); + if (!(rawResponse instanceof JSONArray)) return null; + JSONArray response = (JSONArray) rawResponse; + List profiles = new ArrayList<>(); + for (Object rawEntry : response) { + if (!(rawEntry instanceof JSONObject)) return null; + JSONObject entry = (JSONObject) rawEntry; + PlayerProfile profile = deserializeProfile(entry); + if (profile != null) profiles.add(profile); + } + return profiles; + } + + private static PlayerProfile deserializeProfile(JSONObject jsonObject) { + if (jsonObject == null || !jsonObject.containsKey("name") || !jsonObject.containsKey("id")) return null; + if (!(jsonObject.get("name") instanceof String) || !(jsonObject.get("id") instanceof String)) return null; + String name = (String) jsonObject.get("name"); + UUID playerUUID = toUUID((String) jsonObject.get("id")); + if (playerUUID == null) return null; + PlayerProfile profile = new PlayerProfile(playerUUID, name); + if (jsonObject.containsKey("properties") && jsonObject.get("properties") instanceof JSONArray) { + profile.properties = (JSONArray) jsonObject.get("properties"); + } + return profile; + } + + /* + * Utilities + */ + + private static String toString(UUID uuid) { + return uuid.toString().replace("-", ""); + } + + private static UUID toUUID(String raw) { + if (raw == null) return null; + String dashed; + if (raw.length() == 32) { + dashed = raw.substring(0, 8) + "-" + raw.substring(8, 12) + "-" + raw.substring(12, 16) + "-" + raw.substring(16, 20) + "-" + raw.substring(20, 32); + } else { + dashed = raw; + } + return UUID.fromString(dashed); + } + + private static JSONParser JSON_PARSER = new JSONParser(); + + private static Object getJson(String rawUrl) { + BufferedReader reader = null; + try { + URL url = new URL(rawUrl); + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("GET"); + + reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); + StringBuffer result = new StringBuffer(); + String line; + while ((line = reader.readLine()) != null) result.append(line); + return JSON_PARSER.parse(result.toString()); + } catch (Exception ex) { + return null; + } finally { + try { + if (reader != null) reader.close(); + } catch (IOException ex) { + ex.printStackTrace(); + return null; + } + } + } + + private static String post(String rawUrl, String body) { + BufferedReader reader = null; + OutputStream out = null; + + try { + URL url = new URL(rawUrl); + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("POST"); + connection.setDoOutput(true); + connection.setDoInput(true); + connection.setRequestProperty("Content-Type", "application/json"); + out = connection.getOutputStream(); + out.write(body.getBytes()); + reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); + StringBuffer result = new StringBuffer(); + String line; + while ((line = reader.readLine()) != null) result.append(line); + return result.toString(); + } catch (IOException ex) { + ex.printStackTrace(); + return null; + } finally { + try { + if (out != null) out.close(); + if (reader != null) reader.close(); + } catch (IOException ex) { + ex.printStackTrace(); + return null; + } + } + } + + private static Object postJson(String url, JSONArray body) { + String rawResponse = post(url, body.toJSONString()); + if (rawResponse == null) return null; + try { + return JSON_PARSER.parse(rawResponse); + } catch (Exception e) { + return null; + } + } + + private static class Cache { + private long expireTime = 1000 * 60 * 5; // 5 minutes (default) + private Map> map = new HashMap<>(); + + public boolean contains(K key) { + return map.containsKey(key) && get(key) != null; + } + + public V get(K key) { + CachedEntry entry = map.get(key); + if (entry == null) return null; + if (entry.isExpired()) { + map.remove(key); + return null; + } else { + return entry.getValue(); + } + } + + public void put(K key, V value) { + map.put(key, new CachedEntry(value, expireTime)); + } + + private static class CachedEntry { + public CachedEntry(V value, long expireTime) { + this.value = new SoftReference(value); + this.expires = expireTime + System.currentTimeMillis(); + } + + private final SoftReference value; //Caching is low memory priortiy + private final long expires; + + public V getValue() { + if (isExpired()) { + return null; + } + return value.get(); + } + + public boolean isExpired() { + if (value.get() == null) return true; + return expires != -1 && expires > System.currentTimeMillis(); + } + } + } + + private static PlayerProfile fromPlayer(Player player) { + return new PlayerProfile(player.getUniqueId(), player.getName()); + } + +} \ No newline at end of file diff --git a/src/main/java/com/faris/kingkits/helper/Utilities.java b/src/main/java/com/faris/kingkits/helper/Utilities.java new file mode 100644 index 0000000..30e4ef2 --- /dev/null +++ b/src/main/java/com/faris/kingkits/helper/Utilities.java @@ -0,0 +1,425 @@ +package com.faris.kingkits.helper; + + +import com.faris.kingkits.KingKits; +import org.bukkit.*; +import org.bukkit.configuration.file.*; +import org.bukkit.enchantments.*; +import org.bukkit.entity.*; +import org.bukkit.inventory.*; +import org.bukkit.inventory.meta.*; +import org.bukkit.potion.*; + +import java.io.File; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.UUID; + +public class Utilities { + + public static boolean deleteDirectory(File directory, boolean ignoreErrors) { + try { + if (directory.exists() && directory.isDirectory()) { + File files[] = directory.listFiles(); + for (int i = 0; i < files.length; i++) { + if (files[i].isDirectory()) { + deleteDirectory(files[i], true); + } else { + files[i].delete(); + } + } + } + } catch (Exception ex) { + if (!ignoreErrors) ex.printStackTrace(); + } + return (directory.delete()); + } + + public static int getDye(String friendlyName) { + if (friendlyName != null) { + if (friendlyName.equalsIgnoreCase("Aqua")) return Color.AQUA.asRGB(); + else if (friendlyName.equalsIgnoreCase("Black")) return Color.BLACK.asRGB(); + else if (friendlyName.equalsIgnoreCase("Blue")) return Color.BLUE.asRGB(); + else if (friendlyName.equalsIgnoreCase("Fuchsia")) return Color.FUCHSIA.asRGB(); + else if (friendlyName.equalsIgnoreCase("Gray") || friendlyName.equalsIgnoreCase("Grey")) + return Color.GRAY.asRGB(); + else if (friendlyName.equalsIgnoreCase("Green")) return Color.GREEN.asRGB(); + else if (friendlyName.equalsIgnoreCase("Lime")) return Color.LIME.asRGB(); + else if (friendlyName.equalsIgnoreCase("Maroon")) return Color.MAROON.asRGB(); + else if (friendlyName.equalsIgnoreCase("Navy")) return Color.NAVY.asRGB(); + else if (friendlyName.equalsIgnoreCase("Olive")) return Color.OLIVE.asRGB(); + else if (friendlyName.equalsIgnoreCase("Orange")) return Color.ORANGE.asRGB(); + else if (friendlyName.equalsIgnoreCase("Purple")) return Color.PURPLE.asRGB(); + else if (friendlyName.equalsIgnoreCase("Red")) return Color.RED.asRGB(); + else if (friendlyName.equalsIgnoreCase("Silver")) return Color.SILVER.asRGB(); + else if (friendlyName.equalsIgnoreCase("Teal")) return Color.TEAL.asRGB(); + else if (friendlyName.equalsIgnoreCase("White")) return Color.WHITE.asRGB(); + else if (friendlyName.equalsIgnoreCase("Yellow")) return Color.YELLOW.asRGB(); + } + return -1; + } + + public static String getEnchantmentName(String friendlyName) { + if (friendlyName != null) { + if (friendlyName.equalsIgnoreCase("Sharpness") || friendlyName.equalsIgnoreCase("Sharp")) + return Enchantment.DAMAGE_ALL.getName(); + else if (friendlyName.equalsIgnoreCase("Bane of Arthropods") || friendlyName.equalsIgnoreCase("Arthropods") || friendlyName.equalsIgnoreCase("Bane") || friendlyName.equalsIgnoreCase("Arthro")) + return Enchantment.DAMAGE_ARTHROPODS.getName(); + else if (friendlyName.equalsIgnoreCase("Smite") || friendlyName.equalsIgnoreCase("Undead")) + return Enchantment.DAMAGE_UNDEAD.getName(); + else if (friendlyName.equalsIgnoreCase("Power")) return Enchantment.ARROW_DAMAGE.getName(); + else if (friendlyName.equalsIgnoreCase("Flame") || friendlyName.equalsIgnoreCase("Flames")) + return Enchantment.ARROW_FIRE.getName(); + else if (friendlyName.equalsIgnoreCase("Infinite") || friendlyName.equalsIgnoreCase("Infinity")) + return Enchantment.ARROW_INFINITE.getName(); + else if (friendlyName.equalsIgnoreCase("Punch") || friendlyName.equalsIgnoreCase("Push")) + return Enchantment.ARROW_KNOCKBACK.getName(); + else if (friendlyName.equalsIgnoreCase("Efficiency") || friendlyName.equalsIgnoreCase("Eff")) + return Enchantment.DIG_SPEED.getName(); + else if (friendlyName.equalsIgnoreCase("Unbreaking") || friendlyName.equalsIgnoreCase("Durability") || friendlyName.equalsIgnoreCase("Dura")) + return Enchantment.DURABILITY.getName(); + else if (friendlyName.equalsIgnoreCase("Fire Aspect") || friendlyName.equalsIgnoreCase("Fire")) + return Enchantment.FIRE_ASPECT.getName(); + else if (friendlyName.equalsIgnoreCase("Knockback") || friendlyName.equalsIgnoreCase("Knock")) + return Enchantment.KNOCKBACK.getName(); + else if (friendlyName.equalsIgnoreCase("Fortune") || friendlyName.equalsIgnoreCase("Fort")) + return Enchantment.LOOT_BONUS_BLOCKS.getName(); + else if (friendlyName.equalsIgnoreCase("Looting") || friendlyName.equalsIgnoreCase("Loot")) + return Enchantment.LOOT_BONUS_MOBS.getName(); + else if (friendlyName.equalsIgnoreCase("Luck") || friendlyName.equalsIgnoreCase("Luck of the Sea")) + return Enchantment.LUCK.getName(); + else if (friendlyName.equalsIgnoreCase("Lure")) return Enchantment.LURE.getName(); + else if (friendlyName.equalsIgnoreCase("Oxygen") || friendlyName.equalsIgnoreCase("Breathing") || friendlyName.equalsIgnoreCase("Respiration")) + return Enchantment.OXYGEN.getName(); + else if (friendlyName.equalsIgnoreCase("Protection") || friendlyName.equalsIgnoreCase("Prot")) + return Enchantment.PROTECTION_ENVIRONMENTAL.getName(); + else if (friendlyName.equalsIgnoreCase("Blast Protection") || friendlyName.equalsIgnoreCase("BlastProt")) + return Enchantment.PROTECTION_EXPLOSIONS.getName(); + else if (friendlyName.equalsIgnoreCase("Fall Protection") || friendlyName.equalsIgnoreCase("FallProt") || friendlyName.equalsIgnoreCase("Feather") || friendlyName.equalsIgnoreCase("Feather Falling")) + return Enchantment.PROTECTION_FALL.getName(); + else if (friendlyName.equalsIgnoreCase("Fire Protection") || friendlyName.equalsIgnoreCase("FireProt")) + return Enchantment.PROTECTION_FIRE.getName(); + else if (friendlyName.equalsIgnoreCase("Projectile Protection") || friendlyName.equalsIgnoreCase("ProjProt")) + return Enchantment.PROTECTION_PROJECTILE.getName(); + else if (friendlyName.equalsIgnoreCase("Silk Touch") || friendlyName.equalsIgnoreCase("SilkTouch") || friendlyName.equalsIgnoreCase("Silk")) + return Enchantment.SILK_TOUCH.getName(); + else if (friendlyName.equalsIgnoreCase("Thorns")) + return Enchantment.THORNS.getName(); + else if (friendlyName.equalsIgnoreCase("Water Worker") || friendlyName.equalsIgnoreCase("Aqua Affinity")) + return Enchantment.WATER_WORKER.getName(); + else if (friendlyName.equalsIgnoreCase("Depth Strider")) + return Enchantment.DEPTH_STRIDER.getName(); + } + return friendlyName != null ? friendlyName.toUpperCase().replace(" ", "_") : ""; + } + + public static FileConfiguration getKingKitsSpecialConfig() { + try { + File kkSpecialConfig = new File(KingKits.getInstance().getDataFolder().getAbsoluteFile().getParentFile(), "KingKitsSpecial/config.yml"); + return kkSpecialConfig.exists() ? YamlConfiguration.loadConfiguration(kkSpecialConfig) : null; + } catch (Exception ex) { + return null; + } + } + + public static List getOnlinePlayers() { + List onlinePlayers = new ArrayList(); + for (World world : Bukkit.getWorlds()) { + if (world != null) onlinePlayers.addAll(world.getPlayers()); + } + return onlinePlayers; + } + + public static String getPotionName(String friendlyName) { + if (friendlyName != null) { + if (friendlyName.equalsIgnoreCase("Confusion")) return PotionEffectType.CONFUSION.getName(); + else if (friendlyName.equalsIgnoreCase("Slow") || friendlyName.equalsIgnoreCase("Slowness")) + return PotionEffectType.SLOW.getName(); + else if (friendlyName.equalsIgnoreCase("Resistance")) return PotionEffectType.DAMAGE_RESISTANCE.getName(); + else if (friendlyName.equalsIgnoreCase("Absorption")) return PotionEffectType.ABSORPTION.getName(); + else if (friendlyName.equalsIgnoreCase("Blindness")) return PotionEffectType.BLINDNESS.getName(); + else if (friendlyName.equalsIgnoreCase("Fast") || friendlyName.equalsIgnoreCase("Haste")) + return PotionEffectType.FAST_DIGGING.getName(); + else if (friendlyName.equalsIgnoreCase("Fire")) return PotionEffectType.FIRE_RESISTANCE.getName(); + else if (friendlyName.equalsIgnoreCase("Harm") || friendlyName.equalsIgnoreCase("Harming")) + return PotionEffectType.HARM.getName(); + else if (friendlyName.equalsIgnoreCase("Heal") || friendlyName.equalsIgnoreCase("Healing")) + return PotionEffectType.HEAL.getName(); + else if (friendlyName.equalsIgnoreCase("Boost")) return PotionEffectType.HEALTH_BOOST.getName(); + else if (friendlyName.equalsIgnoreCase("Hunger")) return PotionEffectType.HUNGER.getName(); + else if (friendlyName.equalsIgnoreCase("Strength")) return PotionEffectType.INCREASE_DAMAGE.getName(); + else if (friendlyName.equalsIgnoreCase("Invisibility")) return PotionEffectType.INVISIBILITY.getName(); + else if (friendlyName.equalsIgnoreCase("Jump")) return PotionEffectType.JUMP.getName(); + else if (friendlyName.equalsIgnoreCase("Night")) return PotionEffectType.NIGHT_VISION.getName(); + else if (friendlyName.equalsIgnoreCase("Poison")) return PotionEffectType.POISON.getName(); + else if (friendlyName.equalsIgnoreCase("Regen")) return PotionEffectType.REGENERATION.getName(); + else if (friendlyName.equalsIgnoreCase("Saturation")) return PotionEffectType.SATURATION.getName(); + else if (friendlyName.equalsIgnoreCase("Fatigue")) return PotionEffectType.SLOW_DIGGING.getName(); + else if (friendlyName.equalsIgnoreCase("Speed")) return PotionEffectType.SPEED.getName(); + else if (friendlyName.equalsIgnoreCase("Water")) return PotionEffectType.WATER_BREATHING.getName(); + else if (friendlyName.equalsIgnoreCase("Weakness")) return PotionEffectType.WEAKNESS.getName(); + else if (friendlyName.equalsIgnoreCase("Wither")) return PotionEffectType.WITHER.getName(); + } + return friendlyName != null ? friendlyName.toUpperCase().replace(" ", "_") : ""; + } + + public static boolean isInteger(String aString) { + try { + Integer.parseInt(aString); + return true; + } catch (Exception ex) { + return false; + } + } + + public static boolean isItemNull(ItemStack item) { + return item == null || item.getType() == Material.AIR; + } + + public static boolean isLong(String aString) { + try { + Long.parseLong(aString); + return true; + } catch (Exception ex) { + return false; + } + } + + public static boolean isShort(String aString) { + try { + Short.parseShort(aString); + return true; + } catch (Exception ex) { + return false; + } + } + + public static boolean isUUID(String string) { + try { + UUID.fromString(string); + return true; + } catch (Exception ex) { + return false; + } + } + + public static int processDecimal(int decimal, int lastNumber, int lastDecimal) { + if (lastNumber > decimal) { + return lastDecimal - decimal; + } else { + return lastDecimal + decimal; + } + } + + public static boolean renameDirectory(File directory, File newDirectory) { + try { + if (directory.isDirectory()) { + directory.renameTo(newDirectory); + } else { + directory.mkdir(); + directory.renameTo(newDirectory); + } + return true; + } catch (Exception ex) { + return false; + } + } + + public static String replaceColours(String aString) { + char[] b = aString.toCharArray(); + for (int i = 0; i < b.length - 1; i++) { + if (b[i] == '&' && "0123456789AaBbCcDdEeFf".indexOf(b[i + 1]) > -1) { + b[i] = ChatColor.COLOR_CHAR; + b[i + 1] = Character.toLowerCase(b[i + 1]); + } + } + return new String(b); + } + + public static String replaceFormat(String aString) { + char[] b = aString.toCharArray(); + for (int i = 0; i < b.length - 1; i++) { + if (b[i] == '&' && "KkLlMmNnOoRr".indexOf(b[i + 1]) > -1) { + b[i] = ChatColor.COLOR_CHAR; + b[i + 1] = Character.toLowerCase(b[i + 1]); + } + } + return new String(b); + } + + public static String replaceBukkitColour(String aString) { + if (aString == null) return ""; + String newString = aString; + for (ChatColor chatColor : ChatColor.values()) { + newString = newString.replace(chatColor.toString(), "&" + chatColor.getChar()); + } + return newString; + } + + public static List replaceBukkitColours(List someStrings) { + List stringList = new ArrayList(); + if (someStrings != null) { + for (String aString : someStrings) { + if (aString != null) + stringList.add(replaceBukkitColour(aString)); + } + } + return stringList; + } + + public static String replaceChatColour(String aString) { + if (aString == null) return ""; + return ChatColor.translateAlternateColorCodes('&', aString); + } + + public static List replaceChatColours(List someStrings) { + List stringList = new ArrayList(); + if (someStrings != null) { + for (String aString : someStrings) { + if (aString != null) + stringList.add(replaceChatColour(aString)); + } + } + return stringList; + } + + public static int romanNumeralToInteger(String romanNumber) { + int romanInteger = 0; + int lastNumber = 0; + String romanNumeral = romanNumber.toUpperCase(); + for (int x = romanNumeral.length() - 1; x >= 0; x--) { + char convertToDecimal = romanNumeral.charAt(x); + switch (convertToDecimal) { + case 'M': + romanInteger = processDecimal(1000, lastNumber, romanInteger); + lastNumber = 1000; + break; + + case 'D': + romanInteger = processDecimal(500, lastNumber, romanInteger); + lastNumber = 500; + break; + + case 'C': + romanInteger = processDecimal(100, lastNumber, romanInteger); + lastNumber = 100; + break; + + case 'L': + romanInteger = processDecimal(50, lastNumber, romanInteger); + lastNumber = 50; + break; + + case 'X': + romanInteger = processDecimal(10, lastNumber, romanInteger); + lastNumber = 10; + break; + + case 'V': + romanInteger = processDecimal(5, lastNumber, romanInteger); + lastNumber = 5; + break; + + case 'I': + romanInteger = processDecimal(1, lastNumber, romanInteger); + lastNumber = 1; + break; + } + } + return romanInteger; + } + + public static String stripColour(String kitName) { + return kitName != null ? ChatColor.stripColor(kitName) : ""; + } + + public static Comparator ALPHABETICAL_ORDER = new Comparator() { + public int compare(String str1, String str2) { + int res = String.CASE_INSENSITIVE_ORDER.compare(str1, str2); + if (res == 0) { + res = str1.compareTo(str2); + } + return res; + } + }; + + public static List toLowerCaseList(List normalList) { + List list = new ArrayList(); + for (String s : normalList) + list.add(s.toLowerCase()); + return list; + } + + public static class ItemUtils { + public static int getDye(ItemStack itemStack) { + if (itemStack != null) { + if (itemStack.hasItemMeta()) { + ItemMeta itemMeta = itemStack.getItemMeta(); + if (itemMeta instanceof LeatherArmorMeta) { + LeatherArmorMeta leatherArmorMeta = (LeatherArmorMeta) itemMeta; + return leatherArmorMeta.getColor() != null ? leatherArmorMeta.getColor().asRGB() : -1; + } + } + } + return -1; + } + + public static String getName(ItemStack itemStack) { + if (itemStack != null) { + ItemMeta itemMeta = itemStack.getItemMeta(); + if (itemMeta != null) { + if (itemMeta.hasDisplayName()) return itemMeta.getDisplayName(); + else return ""; + } + } + return ""; + } + + public static List getLore(ItemStack itemStack) { + if (itemStack != null) { + if (itemStack.hasItemMeta() && itemStack.getItemMeta().hasLore()) + return itemStack.getItemMeta().getLore(); + } + return new ArrayList(); + } + + public static ItemStack setDye(ItemStack itemStack, int itemDye) { + if (itemStack != null && itemDye > 0) { + ItemMeta itemMeta = itemStack.getItemMeta(); + if (itemMeta != null && itemMeta instanceof LeatherArmorMeta) { + LeatherArmorMeta leatherArmorMeta = (LeatherArmorMeta) itemMeta; + Color itemDyeColor = Color.fromRGB(itemDye); + if (itemDyeColor != null) { + leatherArmorMeta.setColor(itemDyeColor); + itemStack.setItemMeta(itemMeta); + } + } + } + return itemStack; + } + + public static ItemStack setName(ItemStack itemStack, String itemName) { + if (itemStack != null && itemName != null) { + ItemMeta itemMeta = itemStack.getItemMeta(); + if (itemMeta != null) { + itemMeta.setDisplayName(replaceChatColour(itemName)); + itemStack.setItemMeta(itemMeta); + } + } + return itemStack; + } + + public static ItemStack setLores(ItemStack itemStack, List itemLores) { + if (itemStack != null && itemLores != null) { + ItemMeta itemMeta = itemStack.getItemMeta(); + if (itemMeta != null) { + itemMeta.setLore(replaceChatColours(itemLores)); + itemStack.setItemMeta(itemMeta); + } + } + return itemStack; + } + } + +} diff --git a/src/main/java/com/faris/kingkits/helper/container/ConfigCommand.java b/src/main/java/com/faris/kingkits/helper/container/ConfigCommand.java new file mode 100644 index 0000000..6926acb --- /dev/null +++ b/src/main/java/com/faris/kingkits/helper/container/ConfigCommand.java @@ -0,0 +1,45 @@ +package com.faris.kingkits.helper.container; + +public class ConfigCommand { + private String command = ""; + private String description = ""; + private String config = ""; + + /** + * Create a new instance of ConfigCommands * + */ + public ConfigCommand(String strCommand, String strDescription, String config) { + this.command = strCommand; + this.description = strDescription; + this.config = config; + } + + /** + * Get the config type * + */ + public String getConfig() { + return this.config; + } + + /** + * Get the config command * + */ + public String getCommand() { + return this.command; + } + + /** + * Get the config command's config key * + */ + public String getDescription() { + return this.description; + } + + /** + * Returns the command and config key as a String * + */ + public String toString() { + return this.command + ":" + this.description; + } + +} diff --git a/src/main/java/com/faris/kingkits/helpers/KitStack.java b/src/main/java/com/faris/kingkits/helper/container/KitStack.java similarity index 81% rename from src/main/java/com/faris/kingkits/helpers/KitStack.java rename to src/main/java/com/faris/kingkits/helper/container/KitStack.java index 7de03e1..26fb8f3 100644 --- a/src/main/java/com/faris/kingkits/helpers/KitStack.java +++ b/src/main/java/com/faris/kingkits/helper/container/KitStack.java @@ -1,6 +1,6 @@ -package com.faris.kingkits.helpers; +package com.faris.kingkits.helper.container; -import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.*; public class KitStack { diff --git a/src/main/java/com/faris/kingkits/helper/value/CommandValues.java b/src/main/java/com/faris/kingkits/helper/value/CommandValues.java new file mode 100644 index 0000000..6c3769c --- /dev/null +++ b/src/main/java/com/faris/kingkits/helper/value/CommandValues.java @@ -0,0 +1,12 @@ +package com.faris.kingkits.helper.value; + +public class CommandValues { + public boolean pvpKits = true; + public boolean createKits = true; + public boolean deleteKits = true; + public boolean renameKits = true; + public boolean createUKits = true; + public boolean deleteUKits = true; + public boolean renameUKits = true; + public boolean refillKits = true; +} diff --git a/src/main/java/com/faris/kingkits/helper/value/ConfigValues.java b/src/main/java/com/faris/kingkits/helper/value/ConfigValues.java new file mode 100644 index 0000000..23106ee --- /dev/null +++ b/src/main/java/com/faris/kingkits/helper/value/ConfigValues.java @@ -0,0 +1,107 @@ +package com.faris.kingkits.helper.value; + +import org.bukkit.*; + +import java.util.Arrays; +import java.util.List; + +public class ConfigValues { + // Booleans + public boolean checkForUpdates = true; + public boolean automaticUpdates = false; + + public boolean opBypass = true; + + public boolean listKitsOnJoin = true; + public boolean kitListPermissionsJoin = false; + public boolean sortAlphabetically = true; + + public boolean kitListPermissions = true; + + public boolean dropItemsOnDeath = false; + public boolean dropItems = false; + @SuppressWarnings("deprecation") + public List dropAnimations = Arrays.asList(Material.BOWL.getId()); + public boolean allowPickingUpItems = true; + + public boolean clearInvsOnReload = true; + + public boolean oneKitPerLife = false; + + public boolean removeItemsOnLeave = true; + public boolean removePotionEffectsOnLeave = true; + public boolean removeItemsOnCreateKit = true; + + public boolean rightClickCompass = true; + + public boolean quickSoup = true; + public boolean quickSoupKitOnly = true; + public double quickSoupHeal = 2.5; + + public boolean banBlockBreakingAndPlacing = false; + + public boolean disableDeathMessages = false; + + public boolean lockHunger = true; + public int hungerLock = 20; + + public boolean disableGamemode = false; + + public boolean killstreaks = false; + + public boolean disableItemBreaking = true; + + public boolean kitMenuOnJoin = false; + + public boolean kitParticleEffects = false; + + public boolean showKitPreview = false; + + public boolean kitCooldown = false; + + public boolean replaceItems = true; + + // GUI + public String guiTitle = "PvP Kits"; + public int guiSize = 36; + + // Scores + public boolean scores = false; + public String scoreFormat = "&6[&a&6]"; + public int scoreIncrement = 2; + public int maxScore = Integer.MAX_VALUE; + + // Vault + public VaultValues vaultValues = new VaultValues(); + + public class VaultValues { + public boolean useEconomy = false; + + public boolean useCostPerKit = false; + public boolean useCostPerRefill = false; + public double costPerRefill = 2.5D; + + public boolean useMoneyPerKill = false; + public double moneyPerKill = 5D; + public boolean useMoneyPerDeath = false; + public double moneyPerDeath = 5D; + } + + // Strings + public String commandToRun = ""; + + public List pvpWorlds = Arrays.asList("All"); + public String multiInvsPlugin = "Multiverse-Inventories"; + public boolean multiInvs = false; + + public String customMessages = ""; + + public String kitListMode = "Text"; + + public String strKitSign = "[Kit]"; + public String strKitListSign = "[KList]"; + public String strKitSignValid = "[Kit]"; + public String strKitSignInvalid = "[Kit]"; + public String strKitListSignValid = "[KList]"; + +} diff --git a/src/main/java/com/faris/kingkits/helpers/ConfigCommand.java b/src/main/java/com/faris/kingkits/helpers/ConfigCommand.java deleted file mode 100644 index 44404cf..0000000 --- a/src/main/java/com/faris/kingkits/helpers/ConfigCommand.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.faris.kingkits.helpers; - -public class ConfigCommand { - private String command = ""; - private String description = ""; - private String config = ""; - - /** - * Create a new instance of ConfigCommands * - */ - public ConfigCommand(String strCommand, String strDescription, String config) { - this.command = strCommand; - this.description = strDescription; - this.config = config; - } - - /** - * Get the config type * - */ - public String getConfig() { - return this.config; - } - - /** - * Get the config command * - */ - public String getCommand() { - return this.command; - } - - /** - * Get the config command's config key * - */ - public String getDescription() { - return this.description; - } - - /** - * Returns the command and config key as a String * - */ - public String toString() { - return this.command + ":" + this.description; - } - -} diff --git a/src/main/java/com/faris/kingkits/helpers/Lang.java b/src/main/java/com/faris/kingkits/helpers/Lang.java deleted file mode 100644 index 86be168..0000000 --- a/src/main/java/com/faris/kingkits/helpers/Lang.java +++ /dev/null @@ -1,156 +0,0 @@ -package com.faris.kingkits.helpers; - -import org.bukkit.command.CommandSender; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.plugin.java.JavaPlugin; - -import java.io.File; - -/** - * Based off 1Rogue's Lang class. - */ -public enum Lang { - PREFIX("Prefix.Plugin", "&6[&4KingKits&6] &a"), - - COMMAND_GEN_IN_GAME("Command.General.In-game", "&cYou must be a player to use that command!"), - COMMAND_GEN_ERROR("Command.General.Error", "&cAn error occurred."), - COMMAND_GEN_NO_PERMISSION("Command.General.No permission", "&4You do not have access to that command."), - COMMAND_GEN_USAGE("Command.General.Usage", "&cUsage: &4/%s"), - COMMAND_GEN_DISABLED("Command.General.Disabled", "&cThis command is disabled in the configuration."), - COMMAND_GEN_WORLD("Command.General.World", "&cYou cannot use this command in the world you are in."), - COMMAND_GEN_NOT_ONLINE("Command.General.Not online", "%s does not exist or is not online."), - - COMMAND_CREATE_ILLEGAL_CHARACTERS("Command.Create kit.Illegal characters", "&6The kit name must only consist of letters, numbers and underscores."), - COMMAND_CREATE_DENIED("Command.Create kit.Denied", "&cA plugin has not allowed you to create this kit."), - COMMAND_CREATE_EMPTY_INV("Command.Create kit.Empty inventory", "&cYou have nothing in your inventory!"), - COMMAND_CREATE_OVERWRITTEN("Command.Create kit.Overwrite", "&4%s &6has been overwritten."), - COMMAND_CREATE_CREATED("Command.Create kit.Created", "&4%s &6has been created."), - COMMAND_CREATE_KIT_DESCRIPTION("Command.Create kit.Global.Description", "&cDescription: &4Create your own PvP kit with every item in your inventory."), - COMMAND_CREATE_UKIT_DESCRIPTION("Command.Create kit.User.Description", "&cDescription: &4Create your own personal PvP kit with every item in your inventory."), - COMMAND_CREATE_UKIT_EXISTS("Command.Create kit.User.Global kit exists", "&cA PvP kit already exists with that name!"), - COMMAND_CREATE_UKIT_MAX_PERSONAL_KITS("Command.Create kit.User.Maximum personal kits", "&cYou have reached the maximum number of personal kits you can create."), - - COMMAND_DELETE_ERROR("Command.Delete kit.Error", "&4%s&6's deletion was unsuccessful."), - COMMAND_DELETE_DELETED("Command.Delete kit.Deleted", "&4%s &6was successfully deleted."), - COMMAND_DELETE_PLAYER("Command.Delete kit.Player message", "&4%s &cdeleted the kit you were using!"), - COMMAND_DELETE_KIT_NONEXISTENT("Command.Delete kit.Global.Non-existent", "&4That kit does not exist."), - COMMAND_DELETE_KIT_DESCRIPTION("Command.Delete kit.Global.Description", "&cDescription: &4Delete a PvP Kit."), - COMMAND_DELETE_UKIT_NONEXISTENT("Command.Delete kit.User.Non-existent", "&4That user kit does not exist."), - COMMAND_DELETE_UKIT_DESCRIPTION("Command.Delete kit.User.Description", "&cDescription: &4Delete a personal PvP Kit."), - - COMMAND_KIT_LIST_NO_PERMISSION("Command.Kit.List.No permission", "&4You do not have permission to list the kits."), - COMMAND_KIT_OTHER_PLAYER("Command.Kit.Other player", "&6You set %s's kit. This may not have been successful if you typed an invalid kit name, if they already have a kit, if they do not have permission to use that kit or they do not have enough money."), - - COMMAND_REFILL_BOWL("Command.Refill.Bowl", "&cYou must have a bowl in your hand."), - COMMAND_REFILL_NOT_ENOUGH_MONEY("Command.Refill.Not enough money", "&aYou do not have enough money to refill your bowl(s)."), - COMMAND_REFILL_FULL_INV("Command.Refill.Full inventory", "&cYou have a full inventory!"), - - COMMAND_RENAME_ILLEGAL_CHARACTERS("Command.Rename kit.Illegal characters", "&6The new kit name must only consist of letters, numbers and underscores."), - COMMAND_RENAME_ALREADY_EXISTS("Command.Rename kit.Exists", "&c%s already exists."), - COMMAND_RENAME_RENAMED("Command.Rename kit.Renamed", "&6Successfully renamed %s to %s."), - COMMAND_RENAME_KIT_DESCRIPTION("Command.Rename kit.Global.Description", "&cDescription: &4Rename a PvP kit."), - COMMAND_RENAME_UKIT_DESCRIPTION("Command.Rename kit.User.Description", "&cDescription: &4Rename a user PvP kit."), - - COMPASS_POINTING_PLAYER("Compass.Player", "&eYour compass is pointing to %s."), - COMPASS_POINTING_SPAWN("Compass.Spawn", "Your compass is pointing to spawn."), - - GEN_KIT_LIST("General.Kit list", "&6PvP Kits: &a%s"), - GEN_KIT_LIST_TITLE("General.Kit list title", "&aKits (%s):"), - GEN_NO_KIT_SELECTED("General.No kit selected", "&cYou have not chosen a kit."), - GEN_NO_KITS("General.No kits", "&4There are no kits."), - GEN_NO_KITS_AVAILABLE("General.No kits available", "&cNo kits available"), - GEN_ITEM_DROP("General.Item drop", "&cYou cannot drop this item whilst using a kit."), - GEN_ITEM_PICKUP("General.Item pickup", "&cYou cannot drop this item whilst using a kit."), - - GUI_PREVIEW_TITLE("GUI.Preview.Title", "&c%s &7kit preview"), - GUI_PREVIEW_BACK("GUI.Preview.Back", "&bBack"), - - KIT_NO_PERMISSION("Kit.No permission", "&cYou do not have permission to use the kit &4%s&c."), - KIT_DELAY("Kit.Delay", "&cYou must wait %s second(s) before using this kit again."), - KIT_ALREADY_CHOSEN("Kit.Already chosen", "&6You have already chosen a kit!"), - KIT_NONEXISTENT("Kit.Non-existent", "&4%s &6does not exist."), - KIT_NOT_ENOUGH_MONEY("Kit.Not enough money", "&aYou do not have enough money to change kits."), - - SIGN_CREATE_NO_PERMISSION("Sign.Create.No permission", "&4You do not have access to create a KingKits %s sign."), - SIGN_CREATE_SECOND_LINE("Sign.Create.Second line empty", "&cPlease enter a kit name on the second line."), - - SIGN_GENERAL_INCORRECTLY_SETUP("Sign.General.Incorrectly set up", "&cThat sign has incorrectly been set up."), - - SIGN_USE_NO_PERMISSION("Sign.Use.No permission", "&cYou do not have permission to use this sign."); - - private static YamlConfiguration config = null; - private static File configFile = null; - - private String key = ""; - private String defaultValue = ""; - - private Lang(String key, String defValue) { - this.key = key; - this.defaultValue = defValue; - } - - public String getMessage() { - return replaceChatColours(this.getRawMessage()); - } - - public String getMessage(Object... format) { - return replaceChatColours(String.format(this.getRawMessage(), format)); - } - - public String getRawMessage() { - return config != null ? config.getString(this.key, this.defaultValue) : this.defaultValue; - } - - public String getReplacedMessage(Object... objects) { - String langMessage = this.getRawMessage(); - if (objects != null) { - Object firstObject = ""; - for (int i = 0; i < objects.length; i++) { - if (i == 0 || i % 2 == 0) { - firstObject = objects[i] != null ? objects[i].toString() : "null"; - } else { - if (firstObject != null) - langMessage = langMessage.replace(firstObject.toString(), (objects[i] != null ? objects[i].toString() : "null")); - } - } - } - return replaceChatColours(langMessage); - } - - public static void sendMessage(CommandSender sender, Lang lang) { - sender.sendMessage(PREFIX.getMessage() + lang.getMessage()); - } - - public static void sendMessage(CommandSender sender, Lang lang, Object... objects) { - sender.sendMessage(PREFIX.getMessage() + lang.getMessage(objects)); - } - - public static void sendReplacedMessage(CommandSender sender, Lang lang, Object... objects) { - sender.sendMessage(lang.getReplacedMessage(objects)); - } - - public static void sendRawMessage(CommandSender sender, Lang lang) { - sender.sendMessage(lang.getMessage()); - } - - public static void sendRawMessage(CommandSender sender, Lang lang, Object... objects) { - sender.sendMessage(lang.getMessage(objects)); - } - - public static void init(JavaPlugin plugin) { - configFile = new File(plugin.getDataFolder(), "messages.yml"); - config = YamlConfiguration.loadConfiguration(configFile); - - for (Lang value : values()) { - if (!config.isSet(value.key)) config.set(value.key, value.defaultValue); - } - try { - config.save(configFile); - } catch (Exception ex) { - } - } - - private static String replaceChatColours(String aString) { - return Utils.replaceChatColour(aString); - } -} \ No newline at end of file diff --git a/src/main/java/com/faris/kingkits/helpers/NameFetcher.java b/src/main/java/com/faris/kingkits/helpers/NameFetcher.java deleted file mode 100644 index 6e2c837..0000000 --- a/src/main/java/com/faris/kingkits/helpers/NameFetcher.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.faris.kingkits.helpers; - -import com.google.common.collect.ImmutableList; -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; - -import java.io.InputStreamReader; -import java.net.HttpURLConnection; -import java.net.URL; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.Callable; - -public class NameFetcher implements Callable> { - private static final String PROFILE_URL = "https://sessionserver.mojang.com/session/minecraft/profile/"; - private final JSONParser jsonParser = new JSONParser(); - private final List uuids; - - public NameFetcher(List uuids) { - this.uuids = ImmutableList.copyOf(uuids); - } - - @Override - public Map call() throws Exception { - boolean printedError = false; - Map uuidStringMap = new HashMap(); - for (UUID uuid : uuids) { - HttpURLConnection connection = (HttpURLConnection) new URL(PROFILE_URL + uuid.toString().replace("-", "")).openConnection(); - JSONObject response = (JSONObject) jsonParser.parse(new InputStreamReader(connection.getInputStream())); - String name = (String) response.get("name"); - if (name == null) { - continue; - } - String cause = (String) response.get("cause"); - String errorMessage = (String) response.get("errorMessage"); - if (cause != null && cause.length() > 0) { - if (!printedError) { - System.out.println(errorMessage); - printedError = true; - } - continue; - } - uuidStringMap.put(uuid, name); - } - return uuidStringMap; - } -} \ No newline at end of file diff --git a/src/main/java/com/faris/kingkits/helpers/UUIDFetcher.java b/src/main/java/com/faris/kingkits/helpers/UUIDFetcher.java deleted file mode 100644 index e5aa3b9..0000000 --- a/src/main/java/com/faris/kingkits/helpers/UUIDFetcher.java +++ /dev/null @@ -1,96 +0,0 @@ -package com.faris.kingkits.helpers; - -import com.google.common.collect.ImmutableList; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; - -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.net.HttpURLConnection; -import java.net.URL; -import java.nio.ByteBuffer; -import java.util.*; -import java.util.concurrent.Callable; - -public class UUIDFetcher implements Callable> { - private static final double PROFILES_PER_REQUEST = 100; - private static final String PROFILE_URL = "https://api.mojang.com/profiles/minecraft"; - private final JSONParser jsonParser = new JSONParser(); - private final List names; - private final boolean rateLimiting; - - public UUIDFetcher(List names, boolean rateLimiting) { - this.names = ImmutableList.copyOf(names); - this.rateLimiting = rateLimiting; - } - - public UUIDFetcher(List names) { - this(names, true); - } - - public Map call() throws Exception { - Map uuidMap = new HashMap(); - int requests = (int) Math.ceil(names.size() / PROFILES_PER_REQUEST); - for (int i = 0; i < requests; i++) { - HttpURLConnection connection = createConnection(); - String body = JSONArray.toJSONString(names.subList(i * 100, Math.min((i + 1) * 100, names.size()))); - writeBody(connection, body); - JSONArray array = (JSONArray) jsonParser.parse(new InputStreamReader(connection.getInputStream())); - for (Object profile : array) { - JSONObject jsonProfile = (JSONObject) profile; - String id = (String) jsonProfile.get("id"); - String name = (String) jsonProfile.get("name"); - UUID uuid = UUIDFetcher.getUUID(id); - uuidMap.put(name, uuid); - } - if (rateLimiting && i != requests - 1) { - Thread.sleep(100L); - } - } - return uuidMap; - } - - private static void writeBody(HttpURLConnection connection, String body) throws Exception { - OutputStream stream = connection.getOutputStream(); - stream.write(body.getBytes()); - stream.flush(); - stream.close(); - } - - private static HttpURLConnection createConnection() throws Exception { - URL url = new URL(PROFILE_URL); - HttpURLConnection connection = (HttpURLConnection) url.openConnection(); - connection.setRequestMethod("POST"); - connection.setRequestProperty("Content-Type", "application/json"); - connection.setUseCaches(false); - connection.setDoInput(true); - connection.setDoOutput(true); - return connection; - } - - private static UUID getUUID(String id) { - return UUID.fromString(id.substring(0, 8) + "-" + id.substring(8, 12) + "-" + id.substring(12, 16) + "-" + id.substring(16, 20) + "-" + id.substring(20, 32)); - } - - public static byte[] toBytes(UUID uuid) { - ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[16]); - byteBuffer.putLong(uuid.getMostSignificantBits()); - byteBuffer.putLong(uuid.getLeastSignificantBits()); - return byteBuffer.array(); - } - - public static UUID fromBytes(byte[] array) { - if (array.length != 16) { - throw new IllegalArgumentException("Illegal byte array length: " + array.length); - } - ByteBuffer byteBuffer = ByteBuffer.wrap(array); - long mostSignificant = byteBuffer.getLong(); - long leastSignificant = byteBuffer.getLong(); - return new UUID(mostSignificant, leastSignificant); - } - - public static UUID getUUIDOf(String name) throws Exception { - return new UUIDFetcher(Arrays.asList(name)).call().get(name); - } -} \ No newline at end of file diff --git a/src/main/java/com/faris/kingkits/helpers/Utils.java b/src/main/java/com/faris/kingkits/helpers/Utils.java deleted file mode 100644 index 6d4e911..0000000 --- a/src/main/java/com/faris/kingkits/helpers/Utils.java +++ /dev/null @@ -1,427 +0,0 @@ -package com.faris.kingkits.helpers; - - -import com.faris.kingkits.KingKits; -import org.bukkit.*; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.inventory.meta.LeatherArmorMeta; -import org.bukkit.potion.PotionEffectType; - -import java.io.File; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.List; -import java.util.UUID; - -public class Utils { - - public static boolean deleteDirectory(File directory, boolean ignoreErrors) { - try { - if (directory.exists() && directory.isDirectory()) { - File files[] = directory.listFiles(); - for (int i = 0; i < files.length; i++) { - if (files[i].isDirectory()) { - deleteDirectory(files[i], true); - } else { - files[i].delete(); - } - } - } - } catch (Exception ex) { - if (!ignoreErrors) ex.printStackTrace(); - } - return (directory.delete()); - } - - public static int getDye(String friendlyName) { - if (friendlyName != null) { - if (friendlyName.equalsIgnoreCase("Aqua")) return Color.AQUA.asRGB(); - else if (friendlyName.equalsIgnoreCase("Black")) return Color.BLACK.asRGB(); - else if (friendlyName.equalsIgnoreCase("Blue")) return Color.BLUE.asRGB(); - else if (friendlyName.equalsIgnoreCase("Fuchsia")) return Color.FUCHSIA.asRGB(); - else if (friendlyName.equalsIgnoreCase("Gray") || friendlyName.equalsIgnoreCase("Grey")) - return Color.GRAY.asRGB(); - else if (friendlyName.equalsIgnoreCase("Green")) return Color.GREEN.asRGB(); - else if (friendlyName.equalsIgnoreCase("Lime")) return Color.LIME.asRGB(); - else if (friendlyName.equalsIgnoreCase("Maroon")) return Color.MAROON.asRGB(); - else if (friendlyName.equalsIgnoreCase("Navy")) return Color.NAVY.asRGB(); - else if (friendlyName.equalsIgnoreCase("Olive")) return Color.OLIVE.asRGB(); - else if (friendlyName.equalsIgnoreCase("Orange")) return Color.ORANGE.asRGB(); - else if (friendlyName.equalsIgnoreCase("Purple")) return Color.PURPLE.asRGB(); - else if (friendlyName.equalsIgnoreCase("Red")) return Color.RED.asRGB(); - else if (friendlyName.equalsIgnoreCase("Silver")) return Color.SILVER.asRGB(); - else if (friendlyName.equalsIgnoreCase("Teal")) return Color.TEAL.asRGB(); - else if (friendlyName.equalsIgnoreCase("White")) return Color.WHITE.asRGB(); - else if (friendlyName.equalsIgnoreCase("Yellow")) return Color.YELLOW.asRGB(); - } - return -1; - } - - public static String getEnchantmentName(String friendlyName) { - if (friendlyName != null) { - if (friendlyName.equalsIgnoreCase("Sharpness") || friendlyName.equalsIgnoreCase("Sharp")) - return Enchantment.DAMAGE_ALL.getName(); - else if (friendlyName.equalsIgnoreCase("Bane of Arthropods") || friendlyName.equalsIgnoreCase("Arthropods") || friendlyName.equalsIgnoreCase("Bane") || friendlyName.equalsIgnoreCase("Arthro")) - return Enchantment.DAMAGE_ARTHROPODS.getName(); - else if (friendlyName.equalsIgnoreCase("Smite") || friendlyName.equalsIgnoreCase("Undead")) - return Enchantment.DAMAGE_UNDEAD.getName(); - else if (friendlyName.equalsIgnoreCase("Power")) return Enchantment.ARROW_DAMAGE.getName(); - else if (friendlyName.equalsIgnoreCase("Flame") || friendlyName.equalsIgnoreCase("Flames")) - return Enchantment.ARROW_FIRE.getName(); - else if (friendlyName.equalsIgnoreCase("Infinite") || friendlyName.equalsIgnoreCase("Infinity")) - return Enchantment.ARROW_INFINITE.getName(); - else if (friendlyName.equalsIgnoreCase("Punch") || friendlyName.equalsIgnoreCase("Push")) - return Enchantment.ARROW_KNOCKBACK.getName(); - else if (friendlyName.equalsIgnoreCase("Efficiency") || friendlyName.equalsIgnoreCase("Eff")) - return Enchantment.DIG_SPEED.getName(); - else if (friendlyName.equalsIgnoreCase("Unbreaking") || friendlyName.equalsIgnoreCase("Durability") || friendlyName.equalsIgnoreCase("Dura")) - return Enchantment.DURABILITY.getName(); - else if (friendlyName.equalsIgnoreCase("Fire Aspect") || friendlyName.equalsIgnoreCase("Fire")) - return Enchantment.FIRE_ASPECT.getName(); - else if (friendlyName.equalsIgnoreCase("Knockback") || friendlyName.equalsIgnoreCase("Knock")) - return Enchantment.KNOCKBACK.getName(); - else if (friendlyName.equalsIgnoreCase("Fortune") || friendlyName.equalsIgnoreCase("Fort")) - return Enchantment.LOOT_BONUS_BLOCKS.getName(); - else if (friendlyName.equalsIgnoreCase("Looting") || friendlyName.equalsIgnoreCase("Loot")) - return Enchantment.LOOT_BONUS_MOBS.getName(); - else if (friendlyName.equalsIgnoreCase("Luck") || friendlyName.equalsIgnoreCase("Luck of the Sea")) - return Enchantment.LUCK.getName(); - else if (friendlyName.equalsIgnoreCase("Lure")) return Enchantment.LURE.getName(); - else if (friendlyName.equalsIgnoreCase("Oxygen") || friendlyName.equalsIgnoreCase("Breathing") || friendlyName.equalsIgnoreCase("Respiration")) - return Enchantment.OXYGEN.getName(); - else if (friendlyName.equalsIgnoreCase("Protection") || friendlyName.equalsIgnoreCase("Prot")) - return Enchantment.PROTECTION_ENVIRONMENTAL.getName(); - else if (friendlyName.equalsIgnoreCase("Blast Protection") || friendlyName.equalsIgnoreCase("BlastProt")) - return Enchantment.PROTECTION_EXPLOSIONS.getName(); - else if (friendlyName.equalsIgnoreCase("Fall Protection") || friendlyName.equalsIgnoreCase("FallProt") || friendlyName.equalsIgnoreCase("Feather") || friendlyName.equalsIgnoreCase("Feather Falling")) - return Enchantment.PROTECTION_FALL.getName(); - else if (friendlyName.equalsIgnoreCase("Fire Protection") || friendlyName.equalsIgnoreCase("FireProt")) - return Enchantment.PROTECTION_FIRE.getName(); - else if (friendlyName.equalsIgnoreCase("Projectile Protection") || friendlyName.equalsIgnoreCase("ProjProt")) - return Enchantment.PROTECTION_PROJECTILE.getName(); - else if (friendlyName.equalsIgnoreCase("Silk Touch") || friendlyName.equalsIgnoreCase("SilkTouch") || friendlyName.equalsIgnoreCase("Silk")) - return Enchantment.SILK_TOUCH.getName(); - else if (friendlyName.equalsIgnoreCase("Thorns")) - return Enchantment.THORNS.getName(); - else if (friendlyName.equalsIgnoreCase("Water Worker") || friendlyName.equalsIgnoreCase("Aqua Affinity")) - return Enchantment.WATER_WORKER.getName(); - else if (friendlyName.equalsIgnoreCase("Depth Strider")) - return Enchantment.DEPTH_STRIDER.getName(); - } - return friendlyName != null ? friendlyName.toUpperCase().replace(" ", "_") : ""; - } - - public static FileConfiguration getKingKitsSpecialConfig() { - try { - File kkSpecialConfig = new File(KingKits.getInstance().getDataFolder().getAbsoluteFile().getParentFile(), "KingKitsSpecial/config.yml"); - return kkSpecialConfig.exists() ? YamlConfiguration.loadConfiguration(kkSpecialConfig) : null; - } catch (Exception ex) { - return null; - } - } - - public static List getOnlinePlayers() { - List onlinePlayers = new ArrayList(); - for (World world : Bukkit.getWorlds()) { - if (world != null) onlinePlayers.addAll(world.getPlayers()); - } - return onlinePlayers; - } - - public static String getPotionName(String friendlyName) { - if (friendlyName != null) { - if (friendlyName.equalsIgnoreCase("Confusion")) return PotionEffectType.CONFUSION.getName(); - else if (friendlyName.equalsIgnoreCase("Slow") || friendlyName.equalsIgnoreCase("Slowness")) - return PotionEffectType.SLOW.getName(); - else if (friendlyName.equalsIgnoreCase("Resistance")) return PotionEffectType.DAMAGE_RESISTANCE.getName(); - else if (friendlyName.equalsIgnoreCase("Absorption")) return PotionEffectType.ABSORPTION.getName(); - else if (friendlyName.equalsIgnoreCase("Blindness")) return PotionEffectType.BLINDNESS.getName(); - else if (friendlyName.equalsIgnoreCase("Fast") || friendlyName.equalsIgnoreCase("Haste")) - return PotionEffectType.FAST_DIGGING.getName(); - else if (friendlyName.equalsIgnoreCase("Fire")) return PotionEffectType.FIRE_RESISTANCE.getName(); - else if (friendlyName.equalsIgnoreCase("Harm") || friendlyName.equalsIgnoreCase("Harming")) - return PotionEffectType.HARM.getName(); - else if (friendlyName.equalsIgnoreCase("Heal") || friendlyName.equalsIgnoreCase("Healing")) - return PotionEffectType.HEAL.getName(); - else if (friendlyName.equalsIgnoreCase("Boost")) return PotionEffectType.HEALTH_BOOST.getName(); - else if (friendlyName.equalsIgnoreCase("Hunger")) return PotionEffectType.HUNGER.getName(); - else if (friendlyName.equalsIgnoreCase("Strength")) return PotionEffectType.INCREASE_DAMAGE.getName(); - else if (friendlyName.equalsIgnoreCase("Invisibility")) return PotionEffectType.INVISIBILITY.getName(); - else if (friendlyName.equalsIgnoreCase("Jump")) return PotionEffectType.JUMP.getName(); - else if (friendlyName.equalsIgnoreCase("Night")) return PotionEffectType.NIGHT_VISION.getName(); - else if (friendlyName.equalsIgnoreCase("Poison")) return PotionEffectType.POISON.getName(); - else if (friendlyName.equalsIgnoreCase("Regen")) return PotionEffectType.REGENERATION.getName(); - else if (friendlyName.equalsIgnoreCase("Saturation")) return PotionEffectType.SATURATION.getName(); - else if (friendlyName.equalsIgnoreCase("Fatigue")) return PotionEffectType.SLOW_DIGGING.getName(); - else if (friendlyName.equalsIgnoreCase("Speed")) return PotionEffectType.SPEED.getName(); - else if (friendlyName.equalsIgnoreCase("Water")) return PotionEffectType.WATER_BREATHING.getName(); - else if (friendlyName.equalsIgnoreCase("Weakness")) return PotionEffectType.WEAKNESS.getName(); - else if (friendlyName.equalsIgnoreCase("Wither")) return PotionEffectType.WITHER.getName(); - } - return friendlyName != null ? friendlyName.toUpperCase().replace(" ", "_") : ""; - } - - public static boolean isInteger(String aString) { - try { - Integer.parseInt(aString); - return true; - } catch (Exception ex) { - return false; - } - } - - public static boolean isItemNull(ItemStack item) { - return item == null || item.getType() == Material.AIR; - } - - public static boolean isLong(String aString) { - try { - Long.parseLong(aString); - return true; - } catch (Exception ex) { - return false; - } - } - - public static boolean isShort(String aString) { - try { - Short.parseShort(aString); - return true; - } catch (Exception ex) { - return false; - } - } - - public static boolean isUUID(String string) { - try { - UUID.fromString(string); - return true; - } catch (Exception ex) { - return false; - } - } - - public static int processDecimal(int decimal, int lastNumber, int lastDecimal) { - if (lastNumber > decimal) { - return lastDecimal - decimal; - } else { - return lastDecimal + decimal; - } - } - - public static boolean renameDirectory(File directory, File newDirectory) { - try { - if (directory.isDirectory()) { - directory.renameTo(newDirectory); - } else { - directory.mkdir(); - directory.renameTo(newDirectory); - } - return true; - } catch (Exception ex) { - return false; - } - } - - public static String replaceColours(String aString) { - char[] b = aString.toCharArray(); - for (int i = 0; i < b.length - 1; i++) { - if (b[i] == '&' && "0123456789AaBbCcDdEeFf".indexOf(b[i + 1]) > -1) { - b[i] = ChatColor.COLOR_CHAR; - b[i + 1] = Character.toLowerCase(b[i + 1]); - } - } - return new String(b); - } - - public static String replaceFormat(String aString) { - char[] b = aString.toCharArray(); - for (int i = 0; i < b.length - 1; i++) { - if (b[i] == '&' && "KkLlMmNnOoRr".indexOf(b[i + 1]) > -1) { - b[i] = ChatColor.COLOR_CHAR; - b[i + 1] = Character.toLowerCase(b[i + 1]); - } - } - return new String(b); - } - - public static String replaceBukkitColour(String aString) { - if (aString == null) return ""; - String newString = aString; - for (ChatColor chatColor : ChatColor.values()) { - newString = newString.replace(chatColor.toString(), "&" + chatColor.getChar()); - } - return newString; - } - - public static List replaceBukkitColours(List someStrings) { - List stringList = new ArrayList(); - if (someStrings != null) { - for (String aString : someStrings) { - if (aString != null) - stringList.add(replaceBukkitColour(aString)); - } - } - return stringList; - } - - public static String replaceChatColour(String aString) { - if (aString == null) return ""; - return ChatColor.translateAlternateColorCodes('&', aString); - } - - public static List replaceChatColours(List someStrings) { - List stringList = new ArrayList(); - if (someStrings != null) { - for (String aString : someStrings) { - if (aString != null) - stringList.add(replaceChatColour(aString)); - } - } - return stringList; - } - - public static int romanNumeralToInteger(String romanNumber) { - int romanInteger = 0; - int lastNumber = 0; - String romanNumeral = romanNumber.toUpperCase(); - for (int x = romanNumeral.length() - 1; x >= 0; x--) { - char convertToDecimal = romanNumeral.charAt(x); - switch (convertToDecimal) { - case 'M': - romanInteger = processDecimal(1000, lastNumber, romanInteger); - lastNumber = 1000; - break; - - case 'D': - romanInteger = processDecimal(500, lastNumber, romanInteger); - lastNumber = 500; - break; - - case 'C': - romanInteger = processDecimal(100, lastNumber, romanInteger); - lastNumber = 100; - break; - - case 'L': - romanInteger = processDecimal(50, lastNumber, romanInteger); - lastNumber = 50; - break; - - case 'X': - romanInteger = processDecimal(10, lastNumber, romanInteger); - lastNumber = 10; - break; - - case 'V': - romanInteger = processDecimal(5, lastNumber, romanInteger); - lastNumber = 5; - break; - - case 'I': - romanInteger = processDecimal(1, lastNumber, romanInteger); - lastNumber = 1; - break; - } - } - return romanInteger; - } - - public static String stripColour(String kitName) { - return kitName != null ? ChatColor.stripColor(kitName) : ""; - } - - public static Comparator ALPHABETICAL_ORDER = new Comparator() { - public int compare(String str1, String str2) { - int res = String.CASE_INSENSITIVE_ORDER.compare(str1, str2); - if (res == 0) { - res = str1.compareTo(str2); - } - return res; - } - }; - - public static List toLowerCaseList(List normalList) { - List list = new ArrayList(); - for (String s : normalList) - list.add(s.toLowerCase()); - return list; - } - - public static class ItemUtils { - public static int getDye(ItemStack itemStack) { - if (itemStack != null) { - if (itemStack.hasItemMeta()) { - ItemMeta itemMeta = itemStack.getItemMeta(); - if (itemMeta instanceof LeatherArmorMeta) { - LeatherArmorMeta leatherArmorMeta = (LeatherArmorMeta) itemMeta; - return leatherArmorMeta.getColor() != null ? leatherArmorMeta.getColor().asRGB() : -1; - } - } - } - return -1; - } - - public static String getName(ItemStack itemStack) { - if (itemStack != null) { - ItemMeta itemMeta = itemStack.getItemMeta(); - if (itemMeta != null) { - if (itemMeta.hasDisplayName()) return itemMeta.getDisplayName(); - else return ""; - } - } - return ""; - } - - public static List getLore(ItemStack itemStack) { - if (itemStack != null) { - if (itemStack.hasItemMeta() && itemStack.getItemMeta().hasLore()) - return itemStack.getItemMeta().getLore(); - } - return new ArrayList(); - } - - public static ItemStack setDye(ItemStack itemStack, int itemDye) { - if (itemStack != null && itemDye > 0) { - ItemMeta itemMeta = itemStack.getItemMeta(); - if (itemMeta != null && itemMeta instanceof LeatherArmorMeta) { - LeatherArmorMeta leatherArmorMeta = (LeatherArmorMeta) itemMeta; - Color itemDyeColor = Color.fromRGB(itemDye); - if (itemDyeColor != null) { - leatherArmorMeta.setColor(itemDyeColor); - itemStack.setItemMeta(itemMeta); - } - } - } - return itemStack; - } - - public static ItemStack setName(ItemStack itemStack, String itemName) { - if (itemStack != null && itemName != null) { - ItemMeta itemMeta = itemStack.getItemMeta(); - if (itemMeta != null) { - itemMeta.setDisplayName(replaceChatColour(itemName)); - itemStack.setItemMeta(itemMeta); - } - } - return itemStack; - } - - public static ItemStack setLores(ItemStack itemStack, List itemLores) { - if (itemStack != null && itemLores != null) { - ItemMeta itemMeta = itemStack.getItemMeta(); - if (itemMeta != null) { - itemMeta.setLore(replaceChatColours(itemLores)); - itemStack.setItemMeta(itemMeta); - } - } - return itemStack; - } - } - -} diff --git a/src/main/java/com/faris/kingkits/hooks/PvPKits.java b/src/main/java/com/faris/kingkits/hooks/PvPKits.java index 5000aaf..fa17c74 100644 --- a/src/main/java/com/faris/kingkits/hooks/PvPKits.java +++ b/src/main/java/com/faris/kingkits/hooks/PvPKits.java @@ -1,511 +1,366 @@ package com.faris.kingkits.hooks; import com.faris.kingkits.KingKits; +import com.faris.kingkits.KingKitsAPI; import com.faris.kingkits.Kit; -import com.faris.kingkits.guis.GuiKitMenu; -import com.faris.kingkits.helpers.KitStack; -import com.faris.kingkits.helpers.Utils; -import com.faris.kingkits.listeners.commands.SetKit; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import org.bukkit.permissions.Permission; -import org.bukkit.potion.PotionEffect; - -import java.util.*; +import com.faris.kingkits.helper.UUIDFetcher; +import org.bukkit.entity.*; +import org.bukkit.inventory.*; +import org.bukkit.potion.*; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; import java.util.logging.Logger; + +@Deprecated +/** + * Moved to {@link com.faris.kingkits.KingKitsAPI} so that the class will never be affected by package renames. + */ public class PvPKits { - /** - * Get KingKit's logger. - */ - public static Logger getPluginLogger() { - return KingKits.getInstance().getLogger(); - } - - /** - * Create a kit. - * Returns if the creation of the kit is successful. - * - * @param kitName The kit name. - * @param itemsInKit The items in the kit. - * @param potionEffects The potion effects in the kit. Set to null if there are none. - * @param guiItem The item to be shown in the GUI Inventory when using GUI mode. Set to null if you want it to be a diamond sword. - * @param costOfKit The cost of the kit. - */ - public static boolean createKit(String kitName, List itemsInKit, List potionEffects, ItemStack guiItem, double costOfKit) { - Map mapItemsInKit = new HashMap(); - for (int i = 0; i < itemsInKit.size(); i++) { - mapItemsInKit.put(i, itemsInKit.get(i)); - } - return createKit(kitName, mapItemsInKit, potionEffects, guiItem, costOfKit); - } - - /** - * Create a kit. - * Returns if the creation of the kit is successful. - * - * @param kitName The kit name. - * @param itemsInKit The items in the kit with their slot number. - * @param potionEffects The potion effects in the kit. Set to null if there are none. - * @param guiItem The item to be shown in the GUI Inventory when using GUI mode. Set to null if you want it to be a diamond sword. - * @param costOfKit The cost of the kit. - */ - public static boolean createKit(String kitName, Map itemsInKit, List potionEffects, ItemStack guiItem, double costOfKit) { - if (KingKits.getInstance() == null) return false; - if (!itemsInKit.isEmpty()) { - boolean containsKit = kitExists(kitName); - if (containsKit) { - List currentKits = KingKits.getInstance().getConfigKitList(); - List currentKitsLC = Utils.toLowerCaseList(currentKits); - if (currentKitsLC.contains(kitName.toLowerCase())) - kitName = currentKits.get(currentKitsLC.indexOf(kitName.toLowerCase())); - - KingKits.getInstance().getKitsConfig().set(kitName, null); - KingKits.getInstance().saveKitsConfig(); - } - Kit kit = new Kit(kitName, costOfKit, itemsInKit, potionEffects).setGuiItem(guiItem != null ? guiItem : new ItemStack(Material.DIAMOND_SWORD)); - KingKits.getInstance().getKitsConfig().set(kitName, kit.serialize()); - KingKits.getInstance().saveKitsConfig(); - KingKits.getInstance().kitList.put(kitName, kit); - - try { - KingKits.getInstance().getServer().getPluginManager().addPermission(new Permission("kingkits.kits." + kitName.toLowerCase())); - } catch (Exception ex) { - getPluginLogger().warning(ex.getClass().getSimpleName() + " error: " + ex.getMessage()); - } - return true; - } - return false; - } - - /** - * Delete a kit. - * Returns if the deletion of the kit is successful. - * - * @param kitName The name of the kit to be deleted. - */ - public static boolean deleteKit(String kitName) { - List kits = KingKits.getInstance() != null ? KingKits.getInstance().getConfigKitList() : new ArrayList(); - List kitsLC = Utils.toLowerCaseList(kits); - if (kitsLC.contains(kitName.toLowerCase())) { - kitName = kits.get(kitsLC.indexOf(kitName.toLowerCase())); - KingKits.getInstance().getKitsConfig().set(kitName, null); - KingKits.getInstance().saveKitsConfig(); - KingKits.getInstance().kitList.remove(kitName); - return true; - } - return false; - } - - /** - * Returns the player's killstreak. - * Returns 0 if the player doesn't exist, is null or has no killstreak. - * - * @param player The player. - */ - public static long getKillstreak(Player player) { - if (player == null) return 0L; - return getKillstreak(player.getName()); - } - - /** - * Returns the player's killstreak. - * Returns 0 if the player doesn't exist or has no killstreak. - * - * @param player The name of the player. - */ - public static long getKillstreak(String player) { - if (KingKits.getInstance() != null && KingKits.getInstance().playerKillstreaks.containsKey(player)) - return KingKits.getInstance().playerKillstreaks.get(player); - else return 0L; - } - - /** - * Get player's kit : Returns null if the player is null or doesn't have a kit. - * - * @param player The player to get the kit name from. - */ - public static String getKit(Player player) { - if (player == null) return null; - return getKit(player.getName()); - } - - /** - * Get player's kit : Returns null if the player doesn't have a kit. - * - * @param player The player to get the kit name from. - */ - public static String getKit(String player) { - return KingKits.getInstance() != null && KingKits.getInstance().usingKits != null ? KingKits.getInstance().usingKits.get(player) : null; - } - - /** - * Get a kit by its name. - * - * @param kitName The kit's name. - * @return The kit. - */ - public static Kit getKitByName(String kitName) { - String strippedKitName = Utils.stripColour(kitName); - for (Kit kit : KingKits.getInstance().kitList.values()) { - if (kit != null && (strippedKitName.equalsIgnoreCase(Utils.stripColour(kit.getRealName())) || strippedKitName.equals(Utils.stripColour(kit.getName())))) { - return kit; - } - } - return strippedKitName != null ? KingKits.getInstance().kitList.get(strippedKitName) : null; - } - - /** - * Get a kit by its name. - * - * @param kitName The kit's name. - * @param playerName The player's name. - * @return The kit. - */ - public static Kit getKitByName(String kitName, String playerName) { - String strippedKitName = Utils.stripColour(kitName); - if (playerName != null && strippedKitName != null && KingKits.getInstance().userKitList.containsKey(playerName)) { - List kits = KingKits.getInstance().userKitList.get(playerName); - if (kits != null) { - for (Kit kit : kits) { - if (kit != null && (strippedKitName.equalsIgnoreCase(Utils.stripColour(kit.getRealName())) || strippedKitName.equals(Utils.stripColour(kit.getName())))) { - return kit; - } - } - } - } - for (Kit kit : KingKits.getInstance().kitList.values()) { - if (kit != null && (strippedKitName.equalsIgnoreCase(Utils.stripColour(kit.getRealName())) || strippedKitName.equals(Utils.stripColour(kit.getName())))) { - return kit; - } - } - return strippedKitName != null ? KingKits.getInstance().kitList.get(strippedKitName) : null; - } - - /** - * Get a kit by its name, ignoring cases for display name. - * - * @param kitName The kit's name. - * @return The kit. - */ - public static Kit getKitByNameCaseInsensitive(String kitName) { - String strippedKitName = Utils.stripColour(kitName); - for (Kit kit : KingKits.getInstance().kitList.values()) { - if (kit != null && (strippedKitName.equalsIgnoreCase(Utils.stripColour(kit.getRealName())) || strippedKitName.equalsIgnoreCase(Utils.stripColour(kit.getName())))) { - return kit; - } - } - return strippedKitName != null ? KingKits.getInstance().kitList.get(strippedKitName) : null; - } - - /** - * Get a list of the register kits. - * - * @return A list of registered kits. - */ - public static List getKits() { - return new ArrayList(KingKits.getInstance().kitList.values()); - } - - /** - * Get players using a specific kit : Returns an empty list if the kit doesn't exist or no players are using that kit. - * - * @param kitName The kit to obtain the list of players. - */ - public static List getPlayersUsingKit(String kitName) { - List playersUsingKit = new ArrayList(); - List playersInKitMap = new ArrayList(KingKits.getInstance().usingKits.keySet()); - for (int pos = 0; pos < KingKits.getInstance().usingKits.size(); pos++) { - String kit = KingKits.getInstance().usingKits.get(pos); - if (kit.equalsIgnoreCase(kitName)) { - playersUsingKit.add(playersInKitMap.get(pos)); - } - } - return playersUsingKit; - } - - /** - * Get players using and their kits : Returns an empty map if no one is using a kit. - */ - public static Map getPlayersAndKits() { - return Collections.unmodifiableMap(KingKits.getInstance().usingKits); - } - - /** - * Returns the target player's score. - * Returns -1 if the player doesn't exist in the scores configuration or the player is null. - * - * @param player The player who's score is meant to be returned. - */ - public static int getScore(Player player) { - if (player == null) return -1; - return getScore(player.getUniqueId().toString()); - } - - /** - * Returns the target player's score. - * - * @param playerUUID The player who's score is meant to be returned. Returns -1 if the player doesn't exist in the scores configuration. - */ - public static int getScore(String playerUUID) { - UUID uuid = UUID.fromString(playerUUID); - if (KingKits.getInstance().playerScores.containsKey(uuid)) { - return (Integer) KingKits.getInstance().playerScores.get(uuid); - } else { - return -1; - } - } - - /** - * Returns a Map of all the player's scores and their usernames. - */ - public static Map getScores() { - Map playerScores = new HashMap(); - if (KingKits.getInstance() != null) { - for (Map.Entry entryScores : KingKits.getInstance().playerScores.entrySet()) { - if (entryScores.getValue() instanceof Integer) - playerScores.put(entryScores.getKey(), (Integer) entryScores.getValue()); - } - } - return playerScores; - } - - /** - * Returns if a player has a kit. - * - * @param player The player to check. - */ - public static boolean hasKit(Player player) { - if (player == null) return false; - return hasKit(player.getName()); - } - - /** - * Returns if a player has a kit. - * - * @param player The player to check. - */ - public static boolean hasKit(String player) { - return KingKits.getInstance() != null && KingKits.getInstance().usingKits != null && KingKits.getInstance().usingKits.get(player) != null; - } - - /** - * Returns if a player has a kit. - * - * @param player The player to check. - * @param ignoreOPs Input true if you should ignore OPs. - */ - public static boolean hasKit(Player player, boolean ignoreOPs) { - if (player == null) return false; - return hasKit(player.getName(), ignoreOPs); - } - - /** - * Returns if a player has a kit. - * - * @param player The player to check. - * @param ignoreOPs Input true if you should ignore OPs. - */ - public static boolean hasKit(String player, boolean ignoreOPs) { - if (ignoreOPs) { - return KingKits.getInstance() != null && KingKits.getInstance().playerKits != null && KingKits.getInstance().playerKits.get(player) != null; - } else { - return KingKits.getInstance() != null && KingKits.getInstance().usingKits != null && KingKits.getInstance().usingKits.get(player) != null; - } - } - - /** - * Check if a kit belongs to a player. - * - * @param kitName The kit name. - * @param playerName The player to check. - */ - public static boolean isUserKit(String kitName, String playerName) { - String strippedKitName = Utils.stripColour(kitName); - if (playerName != null && strippedKitName != null && KingKits.getInstance().userKitList.containsKey(playerName)) { - List kits = KingKits.getInstance().userKitList.get(playerName); - if (kits != null) { - for (Kit kit : kits) { - if (kit != null && (strippedKitName.equalsIgnoreCase(Utils.stripColour(kit.getRealName())) || strippedKitName.equals(Utils.stripColour(kit.getName())))) { - return true; - } - } - } - } - return false; - } - - /** - * Returns if a kit exists. - * - * @param kitName The kit name to check. - */ - public static boolean kitExists(String kitName) { - List kitList = new ArrayList(); - if (KingKits.getInstance().getKitsConfig().contains("Kits")) - kitList = KingKits.getInstance().getKitList(); - List kitListLC = Utils.toLowerCaseList(kitList); - return kitListLC.contains(kitName.toLowerCase()); - } - - /** - * Remove a player from a kit. - * Note: Doesn't clear the player's inventory. - * - * @param player The player to remove from a kit. - */ - public static void removePlayer(Player player) { - if (player != null) removePlayer(player.getName()); - } - - /** - * Remove a player from a kit. - * Note: Doesn't clear the player's inventory. - * - * @param player The player's name to remove from a kit. - */ - public static void removePlayer(String player) { - if (hasKit(player, false)) { - KingKits.getInstance().usingKits.remove(player); - KingKits.getInstance().playerKits.remove(player); - } - } - - /** - * Remove a player from a kit. - * Note: Clears a player's inventory. - * - * @param pluginLogger Your plugin's logger. - * @param player The player who's kit is to be changed. - * @param kit The kit that the player should be set as. - */ - @SuppressWarnings("deprecation") - public static void setPlayerKit(Logger pluginLogger, String player, String kit) { - boolean useSyso = false; - if (pluginLogger == null) useSyso = true; - if (kitExists(kit)) { - Player target = Bukkit.getPlayerExact(player); - if (target != null) { - if (target.isOnline()) { - if (hasKit(target.getName(), false)) { - target.getInventory().clear(); - target.getInventory().setArmorContents(null); - removePlayer(target.getName()); - } - try { - SetKit.setKit(target, kit, true); - } catch (Exception ex) { - String msg = "Error, couldn't set the player's kit to " + kit + "."; - if (useSyso) System.out.println(msg); - else pluginLogger.info(msg); - String msg2 = "Error Log: \n" + ex.getMessage(); - if (useSyso) System.out.println(msg2); - else pluginLogger.info(msg2); - } - } else { - String msg = "Target player '" + player + "' is not online/does not exist."; - if (useSyso) System.out.println(msg); - else pluginLogger.info(msg); - } - } else { - String msg = "Target player '" + player + "' is not online/does not exist."; - if (useSyso) System.out.println(msg); - else pluginLogger.info(msg); - } - } else { - String msg = "Kit " + kit + " doesn't exist."; - if (useSyso) System.out.println(msg); - else pluginLogger.info(msg); - } - } - - /** - * Set the score of a player. - * - * @param player The player who's score is meant to be set. - * @param value The new score of the player. - */ - public static void setScore(Player player, int value) { - if (player != null) setScore(player.getUniqueId().toString(), value); - } - - /** - * Set the score of a player. - * - * @param uuid The UUID of the player whose score is meant to be set. - * @param value The new score of the player. - */ - public static void setScore(String uuid, int value) { - UUID playerUUID = UUID.fromString(uuid); - if (KingKits.getInstance().playerScores.containsKey(playerUUID)) - KingKits.getInstance().playerScores.remove(playerUUID); - if (value < 0) value *= -1; - if (value > Integer.MAX_VALUE) value -= Integer.MAX_VALUE; - KingKits.getInstance().playerScores.put(playerUUID, value); - } - - /** - * Display the Kit GUI menu to a player. - * - * @param player The Kit GUI viewer. - */ - public static void showKitMenu(Player player) { - showKitMenu(player, false); - } - - @SuppressWarnings("deprecation") - /** - * Display the Kit GUI menu to a player. - * @param player The Kit GUI viewer. - * @param ignoreChecks Ignore the checking of whether the kit list mode is set to GUI/Menu. - */ - public static void showKitMenu(Player player, boolean ignoreChecks) { - if (KingKits.getInstance() != null && player != null && (!ignoreChecks ? KingKits.getInstance().configValues.kitListMode.equalsIgnoreCase("Gui") || KingKits.getInstance().configValues.kitListMode.equalsIgnoreCase("Menu") : true)) { - List kitValues = new ArrayList(); - if (KingKits.getInstance().configValues.sortAlphabetically) { - List kitNames = new ArrayList(KingKits.getInstance().kitList.keySet()); - if (KingKits.getInstance().userKitList.containsKey(player.getName())) { - List userKits = KingKits.getInstance().userKitList.get(player.getName()); - for (Kit userKit : userKits) { - if (userKit != null) kitNames.add(userKit.getRealName()); - } - } - Collections.sort(kitNames, Utils.ALPHABETICAL_ORDER); - - for (int index = 0; index < kitNames.size(); index++) { - Kit kit = getKitByName(kitNames.get(index), player.getName()); - if (kit != null) { - if (!kit.isUserKit() && !KingKits.getInstance().configValues.kitListPermissions) { - if (!player.hasPermission("kingkits.kits." + kit.getRealName().toLowerCase())) continue; - } - kitValues.add(kit); - } - } - } else { - for (Kit kit : KingKits.getInstance().kitList.values()) { - if (kit != null) { - if (!KingKits.getInstance().configValues.kitListPermissions) { - if (!player.hasPermission("kingkits.kits." + kit.getRealName().toLowerCase())) continue; - } - kitValues.add(kit); - } - } - if (KingKits.getInstance().userKitList.containsKey(player.getName())) - kitValues.addAll(KingKits.getInstance().userKitList.get(player.getName())); - } - - KitStack[] kitStacks = new KitStack[kitValues.size()]; - for (int index = 0; index < kitValues.size(); index++) { - Kit kit = kitValues.get(index); - kitStacks[index] = new KitStack(kit.getName(), kit.getGuiItem()); - } - ChatColor menuColour = kitStacks.length > 0 ? ChatColor.AQUA : ChatColor.RED; - new GuiKitMenu(player, KingKits.getInstance().configValues.guiTitle.replace("", menuColour.toString()), kitStacks).openMenu(); - } - } + + /** + * Get KingKits' logger. + */ + public static Logger getPluginLogger() { + return KingKits.getInstance().getLogger(); + } + + + /** + * Create a kit. + * Returns if the creation of the kit is successful. + * + * @param kitName The kit name. + * @param itemsInKit The items in the kit. + * @param potionEffects The potion effects in the kit. Set to null if there are none. + * @param guiItem The item to be shown in the GUI Inventory when using GUI mode. Set to null if you want it to be a diamond sword. + * @param costOfKit The cost of the kit. + */ + public static boolean createKit(String kitName, List itemsInKit, List potionEffects, ItemStack guiItem, double costOfKit) { + return KingKitsAPI.createKit(kitName, itemsInKit, potionEffects, guiItem, costOfKit); + } + + + /** + * Create a kit. + * Returns if the creation of the kit is successful. + * + * @param kitName The kit name. + * @param itemsInKit The items in the kit with their slot number. + * @param potionEffects The potion effects in the kit. Set to null if there are none. + * @param guiItem The item to be shown in the GUI Inventory when using GUI mode. Set to null if you want it to be a diamond sword. + * @param costOfKit The cost of the kit. + */ + public static boolean createKit(String kitName, Map itemsInKit, List potionEffects, ItemStack guiItem, double costOfKit) { + return KingKitsAPI.createKit(kitName, itemsInKit, potionEffects, guiItem, costOfKit); + } + + + /** + * Delete a kit. + * Returns if the deletion of the kit is successful. + * + * @param kitName The name of the kit to be deleted. + */ + public static boolean deleteKit(String kitName) { + return KingKitsAPI.deleteKit(kitName); + } + + + /** + * Returns the player's killstreak. + * Returns 0 if the player doesn't exist, is null or has no killstreak. + * + * @param player The player. + */ + public static long getKillstreak(Player player) { + return KingKitsAPI.getKillstreak(player); + } + + + /** + * Returns the player's killstreak. + * Returns 0 if the player doesn't exist or has no killstreak. + * + * @param player The name of the player. + */ + public static long getKillstreak(String player) { + return KingKitsAPI.getKillstreak(player); + } + + + /** + * Get player's kit : Returns null if the player is null or doesn't have a kit. + * + * @param player The player to get the kit name from. + */ + public static String getKit(Player player) { + return KingKitsAPI.getKit(player); + } + + + /** + * Get player's kit : Returns null if the player doesn't have a kit. + * + * @param player The player to get the kit name from. + */ + public static String getKit(String player) { + return KingKitsAPI.getKit(player); + } + + + /** + * Get a kit by its name. + * + * @param kitName The kit's name. + * @return The kit. + */ + public static Kit getKitByName(String kitName) { + return KingKitsAPI.getKitByName(kitName, false); + } + + + /** + * Get a kit by its name. + * + * @param kitName The kit's name. + * @param playerName The player's name. + * @return The kit. Empty if the failed to get the player's UUID. + */ + public static Kit getKitByName(String kitName, String playerName) { + try { + return KingKitsAPI.getKitByName(kitName, UUIDFetcher.lookupName(playerName).getId()); + } catch (Exception ex) { + } + return null; + } + + + /** + * Get a kit by its name, ignoring cases for display name. + * + * @param kitName The kit's name. + * @return The kit. + */ + public static Kit getKitByNameCaseInsensitive(String kitName) { + return KingKitsAPI.getKitByName(kitName, true); + } + + + /** + * Get a list of the register kits. + * + * @return A list of registered kits. + */ + public static List getKits() { + return KingKitsAPI.getKits(); + } + + + /** + * Get players using a specific kit : Returns an empty list if the kit doesn't exist or no players are using that kit. + * + * @param kitName The kit to obtain the list of players. + */ + public static List getPlayersUsingKit(String kitName) { + List playersUsingKit = new ArrayList(); + List playersInKitMap = new ArrayList(KingKits.getInstance().usingKits.keySet()); + for (int pos = 0; pos < KingKits.getInstance().usingKits.size(); pos++) { + String kit = KingKits.getInstance().usingKits.get(pos); + if (kit.equalsIgnoreCase(kitName)) { + playersUsingKit.add(playersInKitMap.get(pos)); + } + } + return playersUsingKit; + } + + + /** + * Get players using and their kits : Returns an empty map if no one is using a kit. + */ + public static Map getPlayersAndKits() { + return KingKitsAPI.getPlayersKits(); + } + + + /** + * Returns the target player's score. + * Returns -1 if the player doesn't exist in the scores configuration or the player is null. + * + * @param player The player who's score is meant to be returned. + */ + public static int getScore(Player player) { + return KingKitsAPI.getScore(player.getUniqueId()); + } + + + /** + * Returns the target player's score. + * + * @param playerUUID The player who's score is meant to be returned. Returns -1 if the player doesn't exist in the scores configuration. + */ + public static int getScore(String playerUUID) { + return KingKitsAPI.getScore(playerUUID != null ? UUID.fromString(playerUUID) : null); + } + + + /** + * Returns a Map of all the player's scores and their usernames. + */ + public static Map getScores() { + return KingKitsAPI.getScores(); + } + + + /** + * Returns if a player has a kit. + * + * @param player The player to check. + */ + public static boolean hasKit(Player player) { + return KingKitsAPI.hasKit(player); + } + + + /** + * Returns if a player has a kit. + * + * @param player The player to check. + */ + public static boolean hasKit(String player) { + return KingKitsAPI.hasKit(player); + } + + + /** + * Returns if a player has a kit. + * + * @param player The player to check. + * @param ignoreOPs Input true if you should ignore OPs. + */ + public static boolean hasKit(Player player, boolean ignoreOPs) { + return KingKitsAPI.hasKit(player, ignoreOPs); + } + + + /** + * Returns if a player has a kit. + * + * @param player The player to check. + * @param ignoreOPs Input true if you should ignore OPs. + */ + public static boolean hasKit(String player, boolean ignoreOPs) { + return KingKitsAPI.hasKit(player, ignoreOPs); + } + + + /** + * Check if a kit belongs to a player. + * + * @param kitName The kit name. + * @param playerName The player to check. + */ + public static boolean isUserKit(String kitName, String playerName) { + try { + return KingKitsAPI.isUserKit(kitName, UUIDFetcher.lookupName(playerName).getId()); + } catch (Exception ex) { + } + return false; + } + + + /** + * Returns if a kit exists. + * + * @param kitName The kit name to check. + */ + public static boolean kitExists(String kitName) { + return KingKitsAPI.kitExists(kitName); + } + + + /** + * Remove a player from a kit. + * Note: Doesn't clear the player's inventory. + * + * @param player The player to remove from a kit. + */ + public static void removePlayer(Player player) { + KingKitsAPI.removePlayer(player); + } + + + /** + * Remove a player from a kit. + * Note: Doesn't clear the player's inventory. + * + * @param player The player's name to remove from a kit. + */ + public static void removePlayer(String player) { + KingKitsAPI.removePlayer(player); + } + + + /** + * Remove a player from a kit. + * Note: Clears a player's inventory. + * + * @param pluginLogger Your plugin's logger. + * @param player The player who's kit is to be changed. + * @param kit The kit that the player should be set as. + */ + public static void setPlayerKit(Logger pluginLogger, String player, String kit) { + KingKitsAPI.setPlayerKit(pluginLogger, player, kit); + } + + + /** + * Set the score of a player. + * + * @param player The player who's score is meant to be set. + * @param value The new score of the player. + */ + public static void setScore(Player player, int value) { + KingKitsAPI.setScore(player, value); + } + + + /** + * Set the score of a player. + * + * @param uuid The UUID of the player whose score is meant to be set. + * @param value The new score of the player. + */ + public static void setScore(String uuid, int value) { + try { + KingKitsAPI.setScore(UUID.fromString(uuid), value); + } catch (Exception ex) { + } + } + + + /** + * Display the Kit GUI menu to a player. + * + * @param player The Kit GUI viewer. + */ + public static void showKitMenu(Player player) { + KingKitsAPI.showKitMenu(player); + } + + + /** + * Display the Kit GUI menu to a player. + * + * @param player The Kit GUI viewer. + * @param ignoreChecks Ignore the checking of whether the kit list mode is set to GUI/Menu. + */ + public static void showKitMenu(Player player, boolean ignoreChecks) { + KingKitsAPI.showKitMenu(player, ignoreChecks); + } } \ No newline at end of file diff --git a/src/main/java/com/faris/kingkits/listener/KingCommand.java b/src/main/java/com/faris/kingkits/listener/KingCommand.java new file mode 100644 index 0000000..209a782 --- /dev/null +++ b/src/main/java/com/faris/kingkits/listener/KingCommand.java @@ -0,0 +1,101 @@ +package com.faris.kingkits.listener; + +import com.faris.kingkits.KingKits; +import com.faris.kingkits.helper.Lang; +import com.faris.kingkits.helper.Utilities; +import org.bukkit.command.*; +import org.bukkit.entity.*; + +public abstract class KingCommand implements CommandExecutor { + private KingKits plugin = null; + + public KingCommand(KingKits pluginInstance) { + this.plugin = pluginInstance; + } + + /** + * Ignore this method * + */ + public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { + return this.onCommand(sender, cmd.getName(), args); + } + + /** + * Called when a command is typed by a player or the console * + */ + protected abstract boolean onCommand(CommandSender sender, String command, String[] args); + + /** + * Returns the plugin instance * + */ + protected KingKits getPlugin() { + return this.plugin; + } + + /** + * Returns whether or not a String contains illegal characters. (i.e. Non-alphanumerical) + * + * @param strMessage - The String. + * @return Whether or not a String contains illegal characters. + */ + protected boolean containsIllegalCharacters(String strMessage) { + return !strMessage.matches("[a-zA-Z0-9_ ]*"); + } + + /** + * Returns if a sender is not a player * + */ + protected boolean isConsole(CommandSender sender) { + if (sender != null) { + return !(sender instanceof Player); + } else { + return false; + } + } + + /** + * Returns if a string is a boolean * + */ + protected boolean isBoolean(String booleanString) { + return booleanString.equalsIgnoreCase("true") || booleanString.equalsIgnoreCase("false"); + } + + /** + * Returns if a string is a double * + */ + protected boolean isDouble(String doubleString) { + try { + double d = Double.parseDouble(doubleString); + return Math.floor(d) != d; + } catch (Exception ex) { + return false; + } + } + + /** + * Returns if a string is numeric * + */ + protected boolean isInteger(String numericString) { + try { + double d = Double.parseDouble(numericString); + return Math.floor(d) == d; + } catch (Exception ex) { + return false; + } + } + + /** + * Returns a string with the real colours * + */ + protected String rCC(String message) { + return Utilities.replaceChatColour(message); + } + + /** + * Send the "no access" message to a player/console * + */ + protected void sendNoAccess(CommandSender sender) { + Lang.sendMessage(sender, Lang.COMMAND_GEN_NO_PERMISSION); + } + +} diff --git a/src/main/java/com/faris/kingkits/listener/PlayerCommand.java b/src/main/java/com/faris/kingkits/listener/PlayerCommand.java new file mode 100644 index 0000000..4fa4057 --- /dev/null +++ b/src/main/java/com/faris/kingkits/listener/PlayerCommand.java @@ -0,0 +1,25 @@ +package com.faris.kingkits.listener; + +import com.faris.kingkits.KingKits; +import com.faris.kingkits.helper.Lang; +import org.bukkit.command.*; +import org.bukkit.entity.*; + +public abstract class PlayerCommand extends KingCommand { + + public PlayerCommand(KingKits pluginInstance) { + super(pluginInstance); + } + + @Override + protected boolean onCommand(CommandSender sender, String command, String[] args) { + if (this.isConsole(sender)) { + Lang.sendMessage(sender, Lang.COMMAND_GEN_IN_GAME); + return true; + } + return this.onCommand((Player) sender, command, args); + } + + protected abstract boolean onCommand(Player player, String command, String[] args); + +} diff --git a/src/main/java/com/faris/kingkits/listener/command/CreateKitCommand.java b/src/main/java/com/faris/kingkits/listener/command/CreateKitCommand.java new file mode 100644 index 0000000..2dcdb00 --- /dev/null +++ b/src/main/java/com/faris/kingkits/listener/command/CreateKitCommand.java @@ -0,0 +1,165 @@ +package com.faris.kingkits.listener.command; + +import com.faris.kingkits.KingKits; +import com.faris.kingkits.Kit; +import com.faris.kingkits.helper.Lang; +import com.faris.kingkits.helper.Utilities; +import com.faris.kingkits.listener.PlayerCommand; +import com.faris.kingkits.listener.event.custom.PlayerCreateKitEvent; +import org.bukkit.*; +import org.bukkit.entity.*; +import org.bukkit.inventory.*; +import org.bukkit.permissions.*; +import org.bukkit.potion.*; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class CreateKitCommand extends PlayerCommand { + + public CreateKitCommand(KingKits instance) { + super(instance); + } + + @SuppressWarnings("deprecation") + @Override + protected boolean onCommand(Player p, String command, String[] args) { + if (command.equalsIgnoreCase("createkit")) { + if (p.hasPermission(this.getPlugin().permissions.kitCreateCommand)) { + if (this.getPlugin().cmdValues.createKits) { + if (this.getPlugin().configValues.pvpWorlds.contains("All") || this.getPlugin().configValues.pvpWorlds.contains(p.getWorld().getName())) { + if (args.length == 0) { + Lang.sendMessage(p, Lang.COMMAND_GEN_USAGE, command.toLowerCase() + " [| ]"); + Lang.sendMessage(p, Lang.COMMAND_CREATE_KIT_DESCRIPTION); + } else if (args.length > 0 && args.length < 3) { + String kitName = args[0]; + + boolean containsKit = this.getPlugin().getKitsConfig().contains(kitName); + if (!containsKit) { + List currentKits = this.getPlugin().getKitList(); + List currentKitsLC = Utilities.toLowerCaseList(currentKits); + if (currentKitsLC.contains(kitName.toLowerCase())) + kitName = currentKits.get(currentKitsLC.indexOf(kitName.toLowerCase())); + containsKit = this.getPlugin().getKitsConfig().contains(kitName); + } + + if (!this.containsIllegalCharacters(kitName)) { + if (args.length == 2) { + if (args[1].contains(":")) { + String[] guiSplit = args[1].split(":"); + if (guiSplit.length == 2) { + if (!this.isInteger(guiSplit[0]) || !this.isInteger(guiSplit[1])) { + Lang.sendMessage(p, Lang.COMMAND_GEN_USAGE, command.toLowerCase() + " [| ]"); + return true; + } + } else { + if (!this.isInteger(args[1])) { + Lang.sendMessage(p, Lang.COMMAND_GEN_USAGE, command.toLowerCase() + " [| ]"); + return true; + } + } + } else { + if (!this.isInteger(args[1])) { + Lang.sendMessage(p, Lang.COMMAND_GEN_USAGE, command.toLowerCase() + " [| ]"); + return true; + } + } + } + + Map itemsInInv = new HashMap(); + List armourInInv = new ArrayList(); + ItemStack[] pContents = p.getInventory().getContents(); + if (pContents == null) pContents = new ItemStack[p.getInventory().getSize()]; + for (int i = 0; i < p.getInventory().getSize(); i++) { + if (pContents.length > i && pContents[i] != null) itemsInInv.put(i, pContents[i]); + else itemsInInv.put(i, new ItemStack(Material.AIR)); + } + for (ItemStack armour : p.getInventory().getArmorContents()) + if (armour != null && armour.getType() != Material.AIR) armourInInv.add(armour); + PlayerCreateKitEvent createKitEvent = new PlayerCreateKitEvent(p, kitName, itemsInInv, armourInInv, false); + p.getServer().getPluginManager().callEvent(createKitEvent); + + if (!createKitEvent.isCancelled()) { + itemsInInv = createKitEvent.getKitContentsWithSlots(); + armourInInv = createKitEvent.getKitArmour(); + if (itemsInInv.size() > 0 || armourInInv.size() > 0) { + if (containsKit) { + this.getPlugin().getKitsConfig().set(kitName, null); + this.getPlugin().saveKitsConfig(); + if (this.getPlugin().kitList.containsKey(kitName)) + this.getPlugin().kitList.remove(kitName); + } + + final Kit kit = new Kit(kitName, itemsInInv).setRealName(kitName).setArmour(armourInInv); + if (args.length == 2) { + ItemStack guiItem = null; + try { + guiItem = new ItemStack(Integer.parseInt(args[1])); + } catch (Exception ex) { + } + try { + if (args[1].contains(":")) { + String[] guiSplit = args[1].split(":"); + guiItem = new ItemStack(Integer.parseInt(guiSplit[0])); + guiItem.setDurability(Short.parseShort(guiSplit[1])); + } + } catch (Exception ex) { + } + if (guiItem != null) { + if (guiItem.getType() != Material.AIR) { + kit.setGuiItem(guiItem); + } + } + } + + List kitPotionEffects = new ArrayList(); + for (PotionEffect potionEffect : p.getActivePotionEffects()) { + if (potionEffect != null) kitPotionEffects.add(potionEffect); + } + if (!kitPotionEffects.isEmpty()) kit.setPotionEffects(kitPotionEffects); + + kit.setMaxHealth((int) p.getMaxHealth()); + + this.getPlugin().getKitsConfig().set(kitName, kit.serialize()); + this.getPlugin().kitList.put(kitName, kit); + this.getPlugin().saveKitsConfig(); + + try { + p.getServer().getPluginManager().addPermission(new Permission("kingkits.kits." + kitName.toLowerCase())); + } catch (Exception ex) { + } + Lang.sendMessage(p, containsKit ? Lang.COMMAND_CREATE_OVERWRITTEN : Lang.COMMAND_CREATE_CREATED, kitName); + + if (this.getPlugin().configValues.removeItemsOnCreateKit) { + p.getInventory().clear(); + p.getInventory().setArmorContents(null); + } + } else { + Lang.sendMessage(p, Lang.COMMAND_CREATE_EMPTY_INV); + } + } else { + Lang.sendMessage(p, Lang.COMMAND_CREATE_DENIED); + } + } else { + Lang.sendMessage(p, Lang.COMMAND_CREATE_ILLEGAL_CHARACTERS); + } + } else { + Lang.sendMessage(p, Lang.COMMAND_GEN_USAGE, command.toLowerCase() + " [| ]"); + } + } else { + Lang.sendMessage(p, Lang.COMMAND_GEN_WORLD); + } + } else { + Lang.sendMessage(p, Lang.COMMAND_GEN_DISABLED); + } + } else { + this.sendNoAccess(p); + } + return true; + } + return false; + } + +} diff --git a/src/main/java/com/faris/kingkits/listener/command/CreateUserKitCommand.java b/src/main/java/com/faris/kingkits/listener/command/CreateUserKitCommand.java new file mode 100644 index 0000000..3c010ca --- /dev/null +++ b/src/main/java/com/faris/kingkits/listener/command/CreateUserKitCommand.java @@ -0,0 +1,192 @@ +package com.faris.kingkits.listener.command; + +import com.faris.kingkits.KingKits; +import com.faris.kingkits.Kit; +import com.faris.kingkits.helper.Lang; +import com.faris.kingkits.helper.Utilities; +import com.faris.kingkits.listener.PlayerCommand; +import com.faris.kingkits.listener.event.custom.PlayerCreateKitEvent; +import org.bukkit.*; +import org.bukkit.entity.*; +import org.bukkit.inventory.*; +import org.bukkit.potion.*; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class CreateUserKitCommand extends PlayerCommand { + + public CreateUserKitCommand(KingKits instance) { + super(instance); + } + + @SuppressWarnings("deprecation") + @Override + protected boolean onCommand(Player player, String command, String[] args) { + if (command.equalsIgnoreCase("createukit")) { + if (player.hasPermission(this.getPlugin().permissions.kitUCreateCommand)) { + if (this.getPlugin().cmdValues.createUKits) { + if (this.getPlugin().configValues.pvpWorlds.contains("All") || this.getPlugin().configValues.pvpWorlds.contains(player.getWorld().getName())) { + if (args.length == 0) { + Lang.sendMessage(player, Lang.COMMAND_GEN_USAGE, command.toLowerCase() + " [| ]"); + Lang.sendMessage(player, Lang.COMMAND_CREATE_UKIT_DESCRIPTION); + } else if (args.length > 0 && args.length < 3) { + String kitName = args[0]; + + boolean containsRealKit = this.getPlugin().getKitsConfig().contains(kitName); + if (!containsRealKit) { + List currentKits = this.getPlugin().getKitList(); + List currentKitsLC = Utilities.toLowerCaseList(currentKits); + containsRealKit = currentKitsLC.contains(kitName.toLowerCase()); + } + + if (!containsRealKit) { + List currentKits = this.getPlugin().getKitList(player.getUniqueId()); + boolean containsKit = this.getPlugin().getUserKitsConfig().contains(player.getUniqueId().toString() + "." + kitName); + if (!containsKit) { + List currentKitsLC = Utilities.toLowerCaseList(currentKits); + if (currentKitsLC.contains(kitName.toLowerCase())) + kitName = currentKits.get(currentKitsLC.indexOf(kitName.toLowerCase())); + containsKit = currentKits.contains(kitName); + } + + if (!this.containsIllegalCharacters(kitName)) { + List playerKits = this.getPlugin().userKitList.get(player.getUniqueId()); + if (playerKits == null) playerKits = new ArrayList(); + int maxSizePerm = 0; + for (int i = 1; i <= 54; i++) { + if (maxSizePerm < i && player.hasPermission("kingkits.kit.limit." + i)) + maxSizePerm = i; + } + if (maxSizePerm > playerKits.size()) { + if (args.length == 2) { + if (args[1].contains(":")) { + String[] guiSplit = args[1].split(":"); + if (guiSplit.length == 2) { + if (!this.isInteger(guiSplit[0]) || !this.isInteger(guiSplit[1])) { + Lang.sendMessage(player, Lang.COMMAND_GEN_USAGE, command.toLowerCase() + " [| ]"); + return true; + } + } else { + if (!this.isInteger(args[1])) { + Lang.sendMessage(player, Lang.COMMAND_GEN_USAGE, command.toLowerCase() + " [| ]"); + return true; + } + } + } else { + if (!this.isInteger(args[1])) { + Lang.sendMessage(player, Lang.COMMAND_GEN_USAGE, command.toLowerCase() + " [| ]"); + return true; + } + } + } + + Map itemsInInv = new HashMap(); + List armourInInv = new ArrayList(); + ItemStack[] pContents = player.getInventory().getContents(); + if (pContents == null) + pContents = new ItemStack[player.getInventory().getSize()]; + for (int i = 0; i < player.getInventory().getSize(); i++) { + if (pContents.length > i && pContents[i] != null) + itemsInInv.put(i, pContents[i]); + else itemsInInv.put(i, new ItemStack(Material.AIR)); + } + for (ItemStack armour : player.getInventory().getArmorContents()) + if (armour != null && armour.getType() != Material.AIR) + armourInInv.add(armour); + PlayerCreateKitEvent createKitEvent = new PlayerCreateKitEvent(player, kitName, itemsInInv, armourInInv, true); + player.getServer().getPluginManager().callEvent(createKitEvent); + + if (!createKitEvent.isCancelled()) { + itemsInInv = createKitEvent.getKitContentsWithSlots(); + armourInInv = createKitEvent.getKitArmour(); + if (itemsInInv.size() > 0 || armourInInv.size() > 0) { + if (containsKit) { + this.getPlugin().getUserKitsConfig().set(player.getUniqueId().toString() + "." + kitName, null); + this.getPlugin().saveUserKitsConfig(); + if (playerKits != null) { + List newKits = new ArrayList(); + for (Kit playerKit : playerKits) { + if (playerKit != null && !playerKit.getRealName().toLowerCase().equals(kitName.toLowerCase())) + newKits.add(playerKit); + } + this.getPlugin().userKitList.put(player.getUniqueId(), newKits); + } + } + + final Kit kit = new Kit(kitName, itemsInInv).setRealName(kitName).setArmour(armourInInv).setUserKit(true); + if (args.length == 2) { + ItemStack guiItem = null; + try { + guiItem = new ItemStack(Integer.parseInt(args[1])); + } catch (Exception ex) { + } + try { + if (args[1].contains(":")) { + String[] guiSplit = args[1].split(":"); + guiItem = new ItemStack(Integer.parseInt(guiSplit[0])); + guiItem.setDurability(Short.parseShort(guiSplit[1])); + } + } catch (Exception ex) { + } + if (guiItem != null) { + if (guiItem.getType() != Material.AIR) { + kit.setGuiItem(guiItem); + } + } + } + + List kitPotionEffects = new ArrayList(); + for (PotionEffect potionEffect : player.getActivePotionEffects()) { + if (potionEffect != null) kitPotionEffects.add(potionEffect); + } + if (!kitPotionEffects.isEmpty()) kit.setPotionEffects(kitPotionEffects); + kit.setMaxHealth((int) player.getMaxHealth()); + + this.getPlugin().getUserKitsConfig().set(player.getUniqueId().toString() + "." + kitName, kit.serialize()); + if (playerKits == null) playerKits = new ArrayList(); + playerKits.add(kit); + this.getPlugin().userKitList.put(player.getUniqueId(), playerKits); + this.getPlugin().saveUserKitsConfig(); + + Lang.sendMessage(player, containsKit ? Lang.COMMAND_CREATE_OVERWRITTEN : Lang.COMMAND_CREATE_CREATED, kitName); + + if (this.getPlugin().configValues.removeItemsOnCreateKit) { + player.getInventory().clear(); + player.getInventory().setArmorContents(null); + } + } else { + Lang.sendMessage(player, Lang.COMMAND_CREATE_EMPTY_INV); + } + } else { + Lang.sendMessage(player, Lang.COMMAND_CREATE_DENIED); + } + } else { + Lang.sendMessage(player, Lang.COMMAND_CREATE_UKIT_MAX_PERSONAL_KITS); + } + } else { + Lang.sendMessage(player, Lang.COMMAND_CREATE_ILLEGAL_CHARACTERS); + } + } else { + Lang.sendMessage(player, Lang.COMMAND_CREATE_UKIT_EXISTS); + } + } else { + Lang.sendMessage(player, Lang.COMMAND_GEN_USAGE, command.toLowerCase() + " [| ]"); + } + } else { + Lang.sendMessage(player, Lang.COMMAND_GEN_WORLD); + } + } else { + Lang.sendMessage(player, Lang.COMMAND_GEN_DISABLED); + } + } else { + this.sendNoAccess(player); + } + return true; + } + return false; + } + +} diff --git a/src/main/java/com/faris/kingkits/listener/command/DeleteKitCommand.java b/src/main/java/com/faris/kingkits/listener/command/DeleteKitCommand.java new file mode 100644 index 0000000..67d2ada --- /dev/null +++ b/src/main/java/com/faris/kingkits/listener/command/DeleteKitCommand.java @@ -0,0 +1,86 @@ +package com.faris.kingkits.listener.command; + +import com.faris.kingkits.KingKits; +import com.faris.kingkits.KingKitsAPI; +import com.faris.kingkits.helper.Lang; +import com.faris.kingkits.helper.Utilities; +import com.faris.kingkits.listener.PlayerCommand; +import org.bukkit.entity.*; +import org.bukkit.potion.*; + +import java.util.List; + +public class DeleteKitCommand extends PlayerCommand { + + public DeleteKitCommand(KingKits instance) { + super(instance); + } + + @Override + protected boolean onCommand(Player player, String command, String[] args) { + if (command.equalsIgnoreCase("deletekit")) { + if (player.hasPermission(this.getPlugin().permissions.kitDeleteCommand)) { + if (this.getPlugin().cmdValues.deleteKits) { + if (this.getPlugin().configValues.pvpWorlds.contains("All") || this.getPlugin().configValues.pvpWorlds.contains(player.getWorld().getName())) { + if (args.length == 0) { + Lang.sendMessage(player, Lang.COMMAND_GEN_USAGE, command.toLowerCase() + " "); + Lang.sendMessage(player, Lang.COMMAND_DELETE_KIT_DESCRIPTION); + } else if (args.length == 1) { + String kitName = args[0]; + List listKits = this.getPlugin().getKitList(); + List listKitsLC = Utilities.toLowerCaseList(listKits); + if (listKitsLC.contains(kitName.toLowerCase())) { + try { + kitName = listKits.get(listKitsLC.indexOf(kitName.toLowerCase())); + this.getPlugin().getKitsConfig().set(kitName, null); + this.getPlugin().saveKitsConfig(); + if (this.getPlugin().kitList.containsKey(kitName)) + this.getPlugin().kitList.remove(kitName); + + Lang.sendMessage(player, Lang.COMMAND_DELETE_DELETED, kitName); + for (Player target : Utilities.getOnlinePlayers()) { + if (target != null) { + if (this.getPlugin().usingKits.get(target.getName()) != null) { + String targetKit = this.getPlugin().usingKits.get(target.getName()); + if (targetKit.equalsIgnoreCase(kitName)) { + KingKitsAPI.removePlayer(target.getName()); + if (!player.getName().equals(target.getName())) { + target.getInventory().clear(); + target.getInventory().setArmorContents(null); + for (PotionEffect potionEffect : target.getActivePotionEffects()) + target.removePotionEffect(potionEffect.getType()); + target.setMaxHealth(20D); + Lang.sendMessage(target, Lang.COMMAND_DELETE_PLAYER, player.getName()); + } + } + } + } + } + if (this.getPlugin().usingKits.containsKey(player.getName()) && this.getPlugin().usingKits.get(player.getName()).equalsIgnoreCase(kitName)) { + this.getPlugin().usingKits.remove(player.getName()); + this.getPlugin().playerKits.remove(player.getName()); + } + } catch (Exception ex) { + ex.printStackTrace(); + Lang.sendMessage(player, Lang.COMMAND_DELETE_ERROR, kitName); + } + } else { + Lang.sendMessage(player, Lang.COMMAND_DELETE_KIT_NONEXISTENT); + } + } else { + Lang.sendMessage(player, Lang.COMMAND_GEN_USAGE, command.toLowerCase() + " "); + } + } else { + Lang.sendMessage(player, Lang.COMMAND_GEN_WORLD); + } + } else { + Lang.sendMessage(player, Lang.COMMAND_GEN_DISABLED); + } + } else { + this.sendNoAccess(player); + } + return true; + } + return false; + } +} diff --git a/src/main/java/com/faris/kingkits/listener/command/DeleteUserKitCommand.java b/src/main/java/com/faris/kingkits/listener/command/DeleteUserKitCommand.java new file mode 100644 index 0000000..d2ca2ea --- /dev/null +++ b/src/main/java/com/faris/kingkits/listener/command/DeleteUserKitCommand.java @@ -0,0 +1,86 @@ +package com.faris.kingkits.listener.command; + +import com.faris.kingkits.KingKits; +import com.faris.kingkits.Kit; +import com.faris.kingkits.helper.Lang; +import com.faris.kingkits.helper.Utilities; +import com.faris.kingkits.listener.PlayerCommand; +import org.bukkit.entity.*; + +import java.util.ArrayList; +import java.util.List; + +public class DeleteUserKitCommand extends PlayerCommand { + + public DeleteUserKitCommand(KingKits instance) { + super(instance); + } + + @Override + protected boolean onCommand(Player player, String command, String[] args) { + if (command.equalsIgnoreCase("deleteukit")) { + if (player.hasPermission(this.getPlugin().permissions.kitUDeleteCommand)) { + if (this.getPlugin().cmdValues.deleteKits) { + if (this.getPlugin().configValues.pvpWorlds.contains("All") || this.getPlugin().configValues.pvpWorlds.contains(player.getWorld().getName())) { + if (args.length == 0) { + Lang.sendMessage(player, Lang.COMMAND_GEN_USAGE, command.toLowerCase() + " "); + Lang.sendMessage(player, Lang.COMMAND_DELETE_UKIT_DESCRIPTION); + } else if (args.length == 1) { + String kitName = args[0]; + List listKits = this.getPlugin().getKitList(player.getUniqueId()); + List listKitsLC = Utilities.toLowerCaseList(listKits); + if (listKitsLC.contains(kitName.toLowerCase())) { + try { + kitName = listKits.get(listKitsLC.indexOf(kitName.toLowerCase())); + this.getPlugin().getUserKitsConfig().set(player.getUniqueId().toString() + "." + kitName, null); + this.getPlugin().saveUserKitsConfig(); + if (this.getPlugin().userKitList.containsKey(player.getUniqueId())) { + List kitList = this.getPlugin().userKitList.get(player.getUniqueId()); + if (kitList == null) kitList = new ArrayList(); + int deleteIndex = -1; + for (int i = 0; i < kitList.size(); i++) { + Kit targetKit = kitList.get(i); + if (targetKit != null && targetKit.getRealName().toLowerCase().equals(kitName.toLowerCase())) { + deleteIndex = i; + break; + } + } + if (deleteIndex != -1) kitList.remove(deleteIndex); + if (kitList.isEmpty()) { + this.getPlugin().userKitList.remove(player.getUniqueId()); + this.getPlugin().getUserKitsConfig().set(player.getUniqueId().toString(), null); + this.getPlugin().saveUserKitsConfig(); + } else { + this.getPlugin().userKitList.put(player.getUniqueId(), kitList); + } + } + + Lang.sendMessage(player, Lang.COMMAND_DELETE_DELETED, kitName); + if (this.getPlugin().usingKits.containsKey(player.getName()) && this.getPlugin().usingKits.get(player.getName()).equalsIgnoreCase(kitName)) { + this.getPlugin().usingKits.remove(player.getName()); + this.getPlugin().playerKits.remove(player.getName()); + } + } catch (Exception ex) { + ex.printStackTrace(); + Lang.sendMessage(player, Lang.COMMAND_DELETE_ERROR, kitName); + } + } else { + Lang.sendMessage(player, Lang.COMMAND_DELETE_UKIT_NONEXISTENT); + } + } else { + Lang.sendMessage(player, Lang.COMMAND_GEN_USAGE, command.toLowerCase() + " "); + } + } else { + Lang.sendMessage(player, Lang.COMMAND_GEN_WORLD); + } + } else { + Lang.sendMessage(player, Lang.COMMAND_GEN_DISABLED); + } + } else { + this.sendNoAccess(player); + } + return true; + } + return false; + } +} diff --git a/src/main/java/com/faris/kingkits/listener/command/KingKitsCommand.java b/src/main/java/com/faris/kingkits/listener/command/KingKitsCommand.java new file mode 100644 index 0000000..ed3473f --- /dev/null +++ b/src/main/java/com/faris/kingkits/listener/command/KingKitsCommand.java @@ -0,0 +1,264 @@ +package com.faris.kingkits.listener.command; + +import com.faris.kingkits.KingKits; +import com.faris.kingkits.KingKitsAPI; +import com.faris.kingkits.Kit; +import com.faris.kingkits.helper.Lang; +import com.faris.kingkits.helper.Utilities; +import com.faris.kingkits.helper.container.ConfigCommand; +import com.faris.kingkits.listener.KingCommand; +import com.faris.kingkits.listener.event.custom.KingKitsPreReloadEvent; +import com.faris.kingkits.listener.event.custom.KingKitsReloadEvent; +import org.apache.commons.lang.WordUtils; +import org.bukkit.*; +import org.bukkit.command.*; +import org.bukkit.configuration.*; +import org.bukkit.entity.*; +import org.bukkit.scoreboard.*; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Map; + +public class KingKitsCommand extends KingCommand { + + private List configCommands = new ArrayList(); + + public KingKitsCommand(KingKits pluginInstance) { + super(pluginInstance); + + for (Map.Entry entrySet : this.getPlugin().getConfig().getValues(false).entrySet()) { + if (!(entrySet.getValue() instanceof Collection) && !(entrySet.getValue() instanceof ConfigurationSection) && !(entrySet.getValue() instanceof Map)) { + this.configCommands.add(new ConfigCommand(WordUtils.capitalizeFully(entrySet.getKey().toLowerCase()).replace(" ", ""), entrySet.getKey(), "Config")); + } + } + for (Map.Entry entrySet : this.getPlugin().getEconomyConfig().getValues(false).entrySet()) { + if (!(entrySet.getValue() instanceof Collection) && !(entrySet.getValue() instanceof ConfigurationSection) && !(entrySet.getValue() instanceof Map)) { + this.configCommands.add(new ConfigCommand(WordUtils.capitalizeFully(entrySet.getKey().toLowerCase()).replace(" ", ""), entrySet.getKey(), "Economy")); + } + } + } + + @Override + protected boolean onCommand(CommandSender sender, String command, String[] args) { + if (command.equalsIgnoreCase("kingkits") || command.equalsIgnoreCase("kk")) { + try { + if (args.length == 0) { + sender.sendMessage(ChatColor.GOLD + "KingKits v" + this.getPlugin().getDescription().getVersion()); + } else if (args.length > 0) { + String strCommand = args[0]; + if (strCommand.equalsIgnoreCase("reload")) { + if (sender.isOp() || sender.hasPermission(this.getPlugin().permissions.cmdReloadConfig)) { + if (args.length == 1) { + KingKitsPreReloadEvent kkPreReloadEvent = new KingKitsPreReloadEvent(sender); + sender.getServer().getPluginManager().callEvent(kkPreReloadEvent); + if (!kkPreReloadEvent.isCancelled()) { + try { + this.getPlugin().reloadAllConfigs(); + this.getPlugin().loadConfiguration(); + Lang.init(this.getPlugin()); + try { + if (sender.getServer().getPluginManager().isPluginEnabled("KingKitsSpecial") && sender.getServer().getPluginCommand("kkspecial") != null) { + sender.getServer().dispatchCommand(sender.getServer().getConsoleSender(), "kkspecial reload"); + } + } catch (Exception ex) { + } + + sender.sendMessage(ChatColor.GOLD + "You reloaded KingKits configurations."); + KingKitsReloadEvent kkReloadEvent = new KingKitsReloadEvent(sender); + sender.getServer().getPluginManager().callEvent(kkReloadEvent); + } catch (Exception ex) { + sender.sendMessage(ChatColor.RED + "Failed to reload KingKits configurations."); + + KingKitsReloadEvent kkReloadEvent = new KingKitsReloadEvent(sender, ex); + sender.getServer().getPluginManager().callEvent(kkReloadEvent); + } + } else { + sender.sendMessage(ChatColor.RED + "A plugin has not allowed you to reload the configuration."); + } + } else { + Lang.sendMessage(sender, Lang.COMMAND_GEN_USAGE, command.toLowerCase() + " " + strCommand.toLowerCase()); + } + } else { + this.sendNoAccess(sender); + } + } else if (strCommand.equalsIgnoreCase("config")) { + if (sender.hasPermission(this.getPlugin().permissions.cmdConfigManagement)) { + if (args.length == 2) { + String configProperty = args[1]; + if (configProperty.equalsIgnoreCase("list")) { + sender.sendMessage(ChatColor.GREEN + "KingKits config command property list (" + this.configCommands.size() + "): "); + StringBuilder configListBuilder = new StringBuilder(); + for (int i = 0; i < this.configCommands.size(); i++) { + if (i == this.configCommands.size() - 1) + configListBuilder.append(this.configCommands.get(i).getCommand()); + else configListBuilder.append(this.configCommands.get(i).getCommand() + ", "); + } + sender.sendMessage(ChatColor.GOLD + configListBuilder.toString().trim()); + } else { + Lang.sendMessage(sender, Lang.COMMAND_GEN_USAGE, command.toLowerCase() + " " + strCommand.toLowerCase() + " "); + } + } else if (args.length == 3) { + String configKey = args[1]; + String configValue = args[2]; + if (this.containsCommand(this.configCommands, configKey)) { + sender.sendMessage(this.updateConfig(configKey, configValue)); + } else { + sender.sendMessage(ChatColor.RED + "Invalid config property: " + ChatColor.DARK_RED + configKey); + sender.sendMessage(ChatColor.RED + "To list all the config properties you can edit, type: " + ChatColor.DARK_RED + "/" + command.toLowerCase() + " " + strCommand.toLowerCase() + " list"); + } + } else { + Lang.sendMessage(sender, Lang.COMMAND_GEN_USAGE, command.toLowerCase() + " " + strCommand.toLowerCase() + " "); + } + } else { + this.sendNoAccess(sender); + } + } else if (strCommand.equalsIgnoreCase("removescoreboards")) { + if (sender.isOp()) { + if (args.length == 1) { + Scoreboard newScoreboard = sender.getServer().getScoreboardManager().getNewScoreboard(); + for (Player onlinePlayer : sender.getServer().getOnlinePlayers()) { + Scoreboard pScoreboard = onlinePlayer.getScoreboard(); + if (pScoreboard != null && pScoreboard.getObjective("KingKits") != null) { + onlinePlayer.setScoreboard(newScoreboard); + } + } + sender.getServer().dispatchCommand(sender.getServer().getConsoleSender(), "scoreboard objectives remove KingKits"); + } else { + Lang.sendMessage(sender, Lang.COMMAND_GEN_USAGE, command.toLowerCase() + " " + strCommand.toLowerCase()); + } + } else { + this.sendNoAccess(sender); + } + } else if (strCommand.equalsIgnoreCase("killstreak")) { + if (!this.isConsole(sender)) { + Player player = (Player) sender; + if (player.hasPermission(this.getPlugin().permissions.killstreak)) { + if (args.length == 1) { + long killstreak = KingKitsAPI.getKillstreak(player); + sender.sendMessage(ChatColor.GOLD + "Killstreak: " + ChatColor.DARK_RED + killstreak); + } else { + Lang.sendMessage(sender, Lang.COMMAND_GEN_USAGE, command.toLowerCase() + " " + strCommand.toLowerCase()); + } + } else { + this.sendNoAccess(sender); + } + } else { + Lang.sendMessage(sender, Lang.COMMAND_GEN_IN_GAME); + } + } else if (strCommand.equalsIgnoreCase("setcooldown")) { + if (sender.hasPermission(this.getPlugin().permissions.cmdSetCooldown)) { + if (args.length == 3) { + String strTargetKit = args[1]; + List kitList = this.getPlugin().getKitList(); + List lcKitList = Utilities.toLowerCaseList(kitList); + if (lcKitList.contains(strTargetKit.toLowerCase())) { + if (!kitList.contains(strTargetKit)) + strTargetKit = kitList.get(lcKitList.indexOf(strTargetKit.toLowerCase())); + Kit targetKit = this.getPlugin().kitList.get(strTargetKit); + if (targetKit != null) { + String strCooldown = args[2]; + if (Utilities.isInteger(strCooldown)) { + int cooldown = Integer.parseInt(strCooldown); + if (cooldown >= 0) { + targetKit.setCooldown(cooldown); + this.getPlugin().kitList.put(strTargetKit, targetKit); + this.getPlugin().getKitsConfig().set(strTargetKit + ".Cooldown", cooldown); + this.getPlugin().saveKitsConfig(); + + sender.sendMessage(ChatColor.GOLD + "Changed the cooldown for '" + targetKit.getRealName() + "' to " + cooldown + " second(s)."); + } else { + sender.sendMessage(ChatColor.RED + "Please enter a valid integer between 0 and " + Integer.MAX_VALUE + " (inclusive) for the kit cooldown."); + } + } else { + sender.sendMessage(ChatColor.RED + "Please enter a valid integer between 0 and " + Integer.MAX_VALUE + " (inclusive) for the kit cooldown."); + } + } else { + Lang.sendMessage(sender, Lang.KIT_NONEXISTENT); + } + } else { + Lang.sendMessage(sender, Lang.KIT_NONEXISTENT); + } + } else { + Lang.sendMessage(sender, Lang.COMMAND_GEN_USAGE, command.toLowerCase() + " " + strCommand.toLowerCase() + " "); + } + } else { + this.sendNoAccess(sender); + } + } else { + sender.sendMessage(ChatColor.RED + "Unknown KingKits command: " + ChatColor.DARK_RED + strCommand); + } + } + } catch (Exception ex) { + if (Math.random() < 0.25) ex.printStackTrace(); + } + return true; + } + return false; + } + + /** + * Returns if a list of config commands contains a command (as a string) * + */ + private boolean containsCommand(List configCmds, String command) { + for (ConfigCommand cmd : configCmds) { + if (cmd.getCommand().equalsIgnoreCase(command)) return true; + } + return false; + } + + /** + * Updates the config with the property key and value * + */ + public String updateConfig(String propertyKey, Object propertyValue) { + try { + String key = ""; + String config = ""; + if (this.containsCommand(this.configCommands, propertyKey)) { + for (int i = 0; i < this.configCommands.size(); i++) { + if (this.configCommands.get(i).getCommand().equalsIgnoreCase(propertyKey)) { + ConfigCommand configCommand = this.configCommands.get(i); + key = configCommand.getDescription(); + config = configCommand.getConfig(); + } + } + if (key == "") return ChatColor.RED + "Failed to find the key '" + propertyKey + "' in the config."; + } else return ChatColor.RED + "Failed to find the key '" + propertyKey + "' in the config."; + if (config.equalsIgnoreCase("Config")) { + String value = String.valueOf(propertyValue); + if (this.isBoolean(value)) { + this.getPlugin().getConfig().set(key, Boolean.parseBoolean(value)); + } else if (this.isDouble(value)) { + this.getPlugin().getConfig().set(key, Double.parseDouble(value)); + } else if (this.isInteger(value)) { + this.getPlugin().getConfig().set(key, Integer.parseInt(value)); + } else { + this.getPlugin().getConfig().set(key, propertyValue); + } + this.getPlugin().saveConfig(); + } else if (config.equalsIgnoreCase("Economy")) { + String value = String.valueOf(propertyValue); + if (this.isBoolean(value)) { + this.getPlugin().getEconomyConfig().set(key, Boolean.parseBoolean(value)); + } else if (this.isDouble(value)) { + this.getPlugin().getEconomyConfig().set(key, Double.parseDouble(value)); + } else if (this.isInteger(value)) { + this.getPlugin().getEconomyConfig().set(key, Integer.parseInt(value)); + } else { + this.getPlugin().getEconomyConfig().set(key, propertyValue); + } + this.getPlugin().saveEconomyConfig(); + } + if (!this.getPlugin().checkConfig()) return ChatColor.RED + "Could not update " + propertyKey + "."; + this.getPlugin().reloadAllConfigs(); + this.getPlugin().loadConfiguration(); + + return ChatColor.GOLD + "Successfully updated " + propertyKey + " in the config."; + } catch (Exception ex) { + if (Math.random() < 0.25) ex.printStackTrace(); + return ChatColor.RED + "Error: Couldn't update the config with the property."; + } + } + +} diff --git a/src/main/java/com/faris/kingkits/listener/command/KitCommand.java b/src/main/java/com/faris/kingkits/listener/command/KitCommand.java new file mode 100644 index 0000000..d81427c --- /dev/null +++ b/src/main/java/com/faris/kingkits/listener/command/KitCommand.java @@ -0,0 +1,139 @@ +package com.faris.kingkits.listener.command; + +import com.faris.kingkits.KingKits; +import com.faris.kingkits.KingKitsAPI; +import com.faris.kingkits.Kit; +import com.faris.kingkits.gui.GuiKingKits; +import com.faris.kingkits.gui.GuiPreviewKit; +import com.faris.kingkits.helper.Lang; +import com.faris.kingkits.helper.Utilities; +import com.faris.kingkits.listener.KingCommand; +import org.bukkit.command.*; +import org.bukkit.entity.*; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class KitCommand extends KingCommand { + + public KitCommand(KingKits instance) { + super(instance); + } + + @SuppressWarnings("deprecation") + @Override + protected boolean onCommand(CommandSender sender, String command, String[] args) { + if (command.equalsIgnoreCase("pvpkit")) { + if (sender.hasPermission(this.getPlugin().permissions.kitUseCommand)) { + if (this.getPlugin().cmdValues.pvpKits) { + if (this.isConsole(sender) || this.getPlugin().configValues.pvpWorlds.contains("All") || this.getPlugin().configValues.pvpWorlds.contains(((Player) sender).getWorld().getName())) { + if (args.length == 0) { + if (sender.hasPermission(this.getPlugin().permissions.kitList)) { + if (this.isConsole(sender) || (!this.getPlugin().configValues.kitListMode.equalsIgnoreCase("Gui") && !this.getPlugin().configValues.kitListMode.equalsIgnoreCase("Menu"))) { + List kitList = new ArrayList(this.getPlugin().kitList.keySet()); + Lang.sendMessage(sender, Lang.GEN_KIT_LIST_TITLE, String.valueOf(kitList.size())); + if (!kitList.isEmpty()) { + if (this.getPlugin().configValues.sortAlphabetically) + Collections.sort(kitList, Utilities.ALPHABETICAL_ORDER); + for (int kitPos = 0; kitPos < kitList.size(); kitPos++) { + String kitName = kitList.get(kitPos).split(" ")[0]; + if (sender.hasPermission("kingkits.kits." + kitName.toLowerCase())) { + sender.sendMessage(rCC("&6" + (kitPos + 1) + ". " + kitName)); + } else { + if (this.getPlugin().configValues.kitListPermissions) + sender.sendMessage(rCC("&4" + (kitPos + 1) + ". " + kitName)); + } + } + } else { + Lang.sendMessage(sender, Lang.GEN_NO_KITS); + } + } else { + KingKitsAPI.showKitMenu((Player) sender); + } + } else { + Lang.sendMessage(sender, Lang.COMMAND_KIT_LIST_NO_PERMISSION); + } + } else if (args.length == 1) { + if (!this.isConsole(sender)) { + Player player = (Player) sender; + String kitName = args[0]; + List kitList = this.getPlugin().getKitList(); + List kitListLC = Utilities.toLowerCaseList(kitList); + if (kitListLC.contains(kitName.toLowerCase())) + kitName = kitList.get(kitListLC.indexOf(kitName.toLowerCase())); + try { + final Kit kit = KingKitsAPI.getKitByName(kitName, false); + if (kit != null && kit.hasCooldown() && !player.hasPermission(this.getPlugin().permissions.kitBypassCooldown)) { + if (this.getPlugin().getCooldownConfig().contains(player.getName() + "." + kit.getRealName())) { + long currentCooldown = this.getPlugin().getCooldown(player.getName(), kit.getRealName()); + if (System.currentTimeMillis() - currentCooldown >= kit.getCooldown() * 1000) { + this.getPlugin().getCooldownConfig().set(player.getName() + "." + kit.getRealName(), null); + this.getPlugin().saveCooldownConfig(); + } else { + Lang.sendMessage(player, Lang.KIT_DELAY, String.valueOf((kit.getCooldown() - ((System.currentTimeMillis() - currentCooldown) / 1000)))); + return true; + } + } + } + if (this.getPlugin().configValues.showKitPreview && !player.hasPermission("kingkits.kits." + kitName.toLowerCase())) { + if (!GuiKingKits.guiKitMenuMap.containsKey(player.getName()) && !GuiKingKits.guiPreviewKitMap.containsKey(player.getName())) { + if (this.getPlugin().getKitsConfig().contains(kitName)) { + GuiPreviewKit guiPreviewKit = new GuiPreviewKit(player, kitName); + guiPreviewKit.openMenu(); + } else { + SetKit.setKingKit(player, kitName, true); + } + } else { + SetKit.setKingKit(player, kitName, true); + } + } else { + SetKit.setKingKit(player, kitName, true); + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } else { + Lang.sendMessage(sender, Lang.COMMAND_GEN_IN_GAME); + } + } else if (args.length == 2) { + if (sender.hasPermission(this.getPlugin().permissions.kitUseOtherCommand)) { + String strTarget = args[1]; + Player target = sender.getServer().getPlayer(strTarget); + if (target != null && target.isOnline()) { + String kitName = args[0]; + List kitList = this.getPlugin().getKitList(); + List kitListLC = Utilities.toLowerCaseList(kitList); + if (kitListLC.contains(kitName.toLowerCase())) + kitName = kitList.get(kitListLC.indexOf(kitName.toLowerCase())); + try { + SetKit.setKit(target, kitName, false); + } catch (Exception ex) { + ex.printStackTrace(); + Lang.sendMessage(sender, Lang.COMMAND_GEN_ERROR); + return true; + } + Lang.sendMessage(sender, Lang.COMMAND_KIT_OTHER_PLAYER, target.getName()); + } else { + Lang.sendMessage(sender, Lang.COMMAND_GEN_NOT_ONLINE, strTarget); + } + } else { + this.sendNoAccess(sender); + } + } else { + Lang.sendMessage(sender, Lang.COMMAND_GEN_USAGE, command.toLowerCase() + " [| ]"); + } + } else { + Lang.sendMessage(sender, Lang.COMMAND_GEN_WORLD); + } + } else { + Lang.sendMessage(sender, Lang.COMMAND_GEN_DISABLED); + } + } else { + this.sendNoAccess(sender); + } + return true; + } + return false; + } +} diff --git a/src/main/java/com/faris/kingkits/listener/command/RefillCommand.java b/src/main/java/com/faris/kingkits/listener/command/RefillCommand.java new file mode 100644 index 0000000..3a7c82d --- /dev/null +++ b/src/main/java/com/faris/kingkits/listener/command/RefillCommand.java @@ -0,0 +1,195 @@ +package com.faris.kingkits.listener.command; + +import com.faris.kingkits.KingKits; +import com.faris.kingkits.helper.Lang; +import com.faris.kingkits.listener.PlayerCommand; +import org.bukkit.*; +import org.bukkit.entity.*; +import org.bukkit.inventory.*; + +public class RefillCommand extends PlayerCommand { + + public RefillCommand(KingKits instance) { + super(instance); + } + + @Override + protected boolean onCommand(Player p, String command, String[] args) { + if (command.equalsIgnoreCase("refill") || command.equalsIgnoreCase("soup")) { + try { + if (p.hasPermission(this.getPlugin().permissions.refillSoupSingle) || p.hasPermission(this.getPlugin().permissions.refillSoupAll)) { + if (this.getPlugin().cmdValues.refillKits) { + if (this.getPlugin().configValues.pvpWorlds.contains("All") || this.getPlugin().configValues.pvpWorlds.contains(p.getWorld().getName())) { + if (this.getPlugin().configValues.quickSoupKitOnly) { + if (!this.getPlugin().usingKits.containsKey(p.getName())) { + Lang.sendMessage(p, Lang.GEN_NO_KIT_SELECTED); + return true; + } + } + if (args.length == 0) { + if (p.hasPermission(this.getPlugin().permissions.refillSoupSingle)) { + if (p.getInventory().getItemInHand() != null) { + if (p.getInventory().getItemInHand().getType() == Material.BOWL) { + int invContentsSize = 0; + ItemStack[] itemContents = p.getInventory().getContents(); + for (ItemStack itemContent : itemContents) { + if (itemContent != null) { + if (itemContent.getType() != Material.AIR) invContentsSize++; + } + } + if (invContentsSize < p.getInventory().getSize()) { + ItemStack itemInHand = p.getInventory().getItemInHand(); + int amount = itemInHand.getAmount(); + if (amount <= 1) { + p.getInventory().setItemInHand(new ItemStack(Material.MUSHROOM_SOUP, 1)); + } else { + itemInHand.setAmount(amount - 1); + p.getInventory().setItemInHand(itemInHand); + p.getInventory().addItem(new ItemStack(Material.MUSHROOM_SOUP, 1)); + } + if (this.getPlugin().configValues.vaultValues.useEconomy && this.getPlugin().configValues.vaultValues.useCostPerRefill) { + try { + net.milkbowl.vault.economy.Economy economy = (net.milkbowl.vault.economy.Economy) this.getPlugin().vault.getEconomy(); + if (economy.hasAccount(p)) { + double cost = this.getPlugin().configValues.vaultValues.costPerRefill; + if (economy.getBalance(p) >= cost) { + economy.withdrawPlayer(p, cost); + if (cost != 0) + p.sendMessage(this.getPlugin().getEconomyMessage(cost)); + } else { + Lang.sendMessage(p, Lang.COMMAND_REFILL_NOT_ENOUGH_MONEY); + return true; + } + } else { + Lang.sendMessage(p, Lang.COMMAND_REFILL_NOT_ENOUGH_MONEY); + return true; + } + } catch (Exception ex) { + } + } + } else { + Lang.sendMessage(p, Lang.COMMAND_REFILL_FULL_INV); + } + } else { + Lang.sendMessage(p, Lang.COMMAND_REFILL_BOWL); + } + } else { + Lang.sendMessage(p, Lang.COMMAND_REFILL_BOWL); + } + } else { + this.sendNoAccess(p); + } + } else if (args.length == 1) { + if (args[0].equalsIgnoreCase("all")) { + if (p.hasPermission(this.getPlugin().permissions.refillSoupAll)) { + if (p.getInventory().getItemInHand() != null) { + if (p.getInventory().getItemInHand().getType() == Material.BOWL) { + int invContentsSize = 0; + ItemStack[] inventoryContents = p.getInventory().getContents(); + for (ItemStack itemContent : inventoryContents) { + if (itemContent != null) { + if (itemContent.getType() != Material.AIR) invContentsSize++; + } + } + if (invContentsSize < p.getInventory().getSize()) { + int bowlAmount = p.getInventory().getItemInHand().getAmount(); + int invSize = 0; + int bowlsGiven = 0; + ItemStack[] itemContents = p.getInventory().getContents(); + int invMaxSize = p.getInventory().getSize(); + for (int i = 0; i < itemContents.length; i++) { + if (itemContents[i] != null) { + if (itemContents[i].getType() != Material.AIR) invSize++; + } + } + for (int i = 0; i < bowlAmount; i++) { + if (invSize < invMaxSize) { + invSize++; + bowlsGiven++; + } + } + if (this.getPlugin().configValues.vaultValues.useEconomy && this.getPlugin().configValues.vaultValues.useCostPerRefill) { + try { + net.milkbowl.vault.economy.Economy economy = (net.milkbowl.vault.economy.Economy) this.getPlugin().vault.getEconomy(); + if (economy.hasAccount(p)) { + double cost = this.getPlugin().configValues.vaultValues.costPerRefill * bowlsGiven; + if (economy.getBalance(p) >= cost) { + economy.withdrawPlayer(p, cost); + if (cost != 0) + p.sendMessage(this.getPlugin().getEconomyMessage(cost)); + } else { + Lang.sendMessage(p, Lang.COMMAND_REFILL_NOT_ENOUGH_MONEY); + return true; + } + } else { + Lang.sendMessage(p, Lang.COMMAND_REFILL_NOT_ENOUGH_MONEY); + return true; + } + } catch (Exception ex) { + } + } + for (int i = 0; i < bowlsGiven; i++) { + p.getInventory().addItem(new ItemStack(Material.MUSHROOM_SOUP, 1)); + } + if (p.getInventory().getItemInHand().getAmount() - bowlsGiven > 0) + p.getInventory().setItemInHand(new ItemStack(Material.BOWL, p.getInventory().getItemInHand().getAmount() - bowlsGiven)); + else p.getInventory().setItemInHand(new ItemStack(Material.AIR)); + } else { + if (p.getInventory().getItemInHand().getAmount() == 1) { + if (this.getPlugin().configValues.vaultValues.useEconomy && this.getPlugin().configValues.vaultValues.useCostPerRefill) { + try { + net.milkbowl.vault.economy.Economy economy = (net.milkbowl.vault.economy.Economy) this.getPlugin().vault.getEconomy(); + if (economy.hasAccount(p)) { + double cost = this.getPlugin().configValues.vaultValues.costPerRefill; + if (economy.getBalance(p) >= cost) { + economy.withdrawPlayer(p, cost); + if (cost != 0) + p.sendMessage(this.getPlugin().getEconomyMessage(cost)); + } else { + Lang.sendMessage(p, Lang.COMMAND_REFILL_NOT_ENOUGH_MONEY); + return true; + } + } else { + Lang.sendMessage(p, Lang.COMMAND_REFILL_NOT_ENOUGH_MONEY); + return true; + } + } catch (Exception ex) { + } + p.getInventory().setItemInHand(new ItemStack(Material.MUSHROOM_SOUP)); + } + } + } + } else { + Lang.sendMessage(p, Lang.COMMAND_REFILL_BOWL); + } + } else { + Lang.sendMessage(p, Lang.COMMAND_REFILL_BOWL); + } + } else { + this.sendNoAccess(p); + } + } else { + Lang.sendMessage(p, Lang.COMMAND_GEN_USAGE, command.toLowerCase() + " []"); + } + } else { + Lang.sendMessage(p, Lang.COMMAND_GEN_USAGE, command.toLowerCase() + " []"); + } + } else { + Lang.sendMessage(p, Lang.COMMAND_GEN_WORLD); + } + } else { + Lang.sendMessage(p, Lang.COMMAND_GEN_DISABLED); + } + } else { + this.sendNoAccess(p); + } + } catch (Exception ex) { + ex.printStackTrace(); + Lang.sendMessage(p, Lang.COMMAND_GEN_ERROR); + } + return true; + } + return false; + } + +} diff --git a/src/main/java/com/faris/kingkits/listener/command/RenameKitCommand.java b/src/main/java/com/faris/kingkits/listener/command/RenameKitCommand.java new file mode 100644 index 0000000..d7d6afc --- /dev/null +++ b/src/main/java/com/faris/kingkits/listener/command/RenameKitCommand.java @@ -0,0 +1,94 @@ +package com.faris.kingkits.listener.command; + +import com.faris.kingkits.KingKits; +import com.faris.kingkits.Kit; +import com.faris.kingkits.helper.Lang; +import com.faris.kingkits.helper.Utilities; +import com.faris.kingkits.listener.PlayerCommand; +import org.bukkit.entity.*; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class RenameKitCommand extends PlayerCommand { + + public RenameKitCommand(KingKits pluginInstance) { + super(pluginInstance); + } + + @Override + protected boolean onCommand(Player p, String command, String[] args) { + if (command.equalsIgnoreCase("renamekit")) { + try { + if (p.hasPermission(this.getPlugin().permissions.kitRenameCommand)) { + if (this.getPlugin().cmdValues.renameKits) { + if (this.getPlugin().configValues.pvpWorlds.contains("All") || this.getPlugin().configValues.pvpWorlds.contains(p.getWorld().getName())) { + if (args.length == 0) { + Lang.sendMessage(p, Lang.COMMAND_GEN_USAGE, command.toLowerCase() + " [ ]"); + Lang.sendMessage(p, Lang.COMMAND_RENAME_KIT_DESCRIPTION); + } else if (args.length == 2) { + String strKit = args[0]; + String strNewKit = args[1]; + List currentKits = this.getPlugin().getKitList(); + List currentKitsLC = Utilities.toLowerCaseList(currentKits); + if (currentKitsLC.contains(strKit.toLowerCase())) + strKit = currentKits.get(currentKitsLC.indexOf(strKit.toLowerCase())); + if (!this.getPlugin().getKitsConfig().contains(strNewKit) && !currentKitsLC.contains(strNewKit.toLowerCase())) { + if (!this.containsIllegalCharacters(strNewKit)) { + final Kit kit = this.getPlugin().kitList.get(strKit); + if (kit != null) { + this.getPlugin().getKitsConfig().set(strKit, null); + kit.setName(strNewKit); + kit.setRealName(strNewKit); + this.getPlugin().getKitsConfig().set(strNewKit, kit.serialize()); + this.getPlugin().saveKitsConfig(); + + Map newKits = new HashMap(); + for (Map.Entry entrySet : this.getPlugin().usingKits.entrySet()) { + if (entrySet.getValue() != null && entrySet.getValue().equals(strKit)) + newKits.put(entrySet.getKey(), strNewKit); + } + this.getPlugin().usingKits.putAll(newKits); + + newKits = new HashMap(); + for (Map.Entry entrySet : this.getPlugin().playerKits.entrySet()) { + if (entrySet.getValue() != null && entrySet.getValue().equals(strKit)) + newKits.put(entrySet.getKey(), strNewKit); + } + this.getPlugin().playerKits.putAll(newKits); + + this.getPlugin().kitList.remove(strKit); + this.getPlugin().kitList.put(strNewKit, kit); + + Lang.sendMessage(p, Lang.COMMAND_RENAME_RENAMED, strKit, strNewKit); + } else { + Lang.sendMessage(p, Lang.KIT_NONEXISTENT, strKit); + } + } else { + Lang.sendMessage(p, Lang.COMMAND_RENAME_ILLEGAL_CHARACTERS); + } + } else { + Lang.sendMessage(p, Lang.COMMAND_RENAME_ALREADY_EXISTS, strNewKit); + } + } else { + Lang.sendMessage(p, Lang.COMMAND_GEN_USAGE, command.toLowerCase() + " [ ]"); + } + } else { + Lang.sendMessage(p, Lang.COMMAND_GEN_WORLD); + } + } else { + Lang.sendMessage(p, Lang.COMMAND_GEN_DISABLED); + } + } else { + this.sendNoAccess(p); + } + } catch (Exception ex) { + Lang.sendMessage(p, Lang.COMMAND_GEN_ERROR); + } + return true; + } + return false; + } + +} diff --git a/src/main/java/com/faris/kingkits/listener/command/RenameUserKitCommand.java b/src/main/java/com/faris/kingkits/listener/command/RenameUserKitCommand.java new file mode 100644 index 0000000..317351e --- /dev/null +++ b/src/main/java/com/faris/kingkits/listener/command/RenameUserKitCommand.java @@ -0,0 +1,109 @@ +package com.faris.kingkits.listener.command; + +import com.faris.kingkits.KingKits; +import com.faris.kingkits.KingKitsAPI; +import com.faris.kingkits.Kit; +import com.faris.kingkits.helper.Lang; +import com.faris.kingkits.helper.Utilities; +import com.faris.kingkits.listener.PlayerCommand; +import org.bukkit.entity.*; + +import java.util.ArrayList; +import java.util.List; + +public class RenameUserKitCommand extends PlayerCommand { + + public RenameUserKitCommand(KingKits pluginInstance) { + super(pluginInstance); + } + + @Override + protected boolean onCommand(Player p, String command, String[] args) { + if (command.equalsIgnoreCase("renameukit")) { + try { + if (p.hasPermission(this.getPlugin().permissions.kitURenameCommand)) { + if (this.getPlugin().cmdValues.renameUKits) { + if (this.getPlugin().configValues.pvpWorlds.contains("All") || this.getPlugin().configValues.pvpWorlds.contains(p.getWorld().getName())) { + if (args.length == 0) { + Lang.sendMessage(p, Lang.COMMAND_GEN_USAGE, command.toLowerCase() + " [ ]"); + Lang.sendMessage(p, Lang.COMMAND_RENAME_KIT_DESCRIPTION); + } else if (args.length == 2) { + String strKit = args[0]; + String strNewKit = args[1]; + List currentKits = this.getPlugin().getKitList(p.getUniqueId()); + List currentKitsLC = Utilities.toLowerCaseList(currentKits); + if (currentKitsLC.contains(strKit.toLowerCase())) + strKit = currentKits.get(currentKitsLC.indexOf(strKit.toLowerCase())); + if (!this.getPlugin().getUserKitsConfig().contains(p.getName() + "." + strNewKit) && !currentKitsLC.contains(strNewKit.toLowerCase())) { + if (!this.containsIllegalCharacters(strNewKit)) { + if (KingKitsAPI.isUserKit(strKit, p.getUniqueId())) { + final Kit kit = KingKitsAPI.getKitByName(strKit, p.getUniqueId()); + strKit = kit.getRealName(); + kit.setName(strNewKit); + kit.setRealName(strNewKit); + this.getPlugin().getUserKitsConfig().set(p.getName() + "." + strKit, null); + this.getPlugin().getUserKitsConfig().set(p.getName() + "." + strNewKit, kit.serialize()); + this.getPlugin().saveUserKitsConfig(); + + if (this.getPlugin().userKitList.containsKey(p.getUniqueId())) { + List kitList = this.getPlugin().userKitList.get(p.getUniqueId()); + if (kitList == null) kitList = new ArrayList(); + int deleteIndex = -1; + for (int i = 0; i < kitList.size(); i++) { + Kit targetKit = kitList.get(i); + if (targetKit != null && targetKit.getRealName().toLowerCase().equals(strKit)) { + deleteIndex = i; + break; + } + } + if (deleteIndex != -1) { + kitList.remove(deleteIndex); + if (kitList.isEmpty()) { + this.getPlugin().userKitList.remove(p.getUniqueId()); + this.getPlugin().getUserKitsConfig().set(p.getUniqueId().toString(), null); + this.getPlugin().saveUserKitsConfig(); + } else { + this.getPlugin().userKitList.put(p.getUniqueId(), kitList); + } + } + } + List kitList = this.getPlugin().userKitList.get(p.getUniqueId()); + if (kitList == null) kitList = new ArrayList(); + if (!kitList.contains(kit)) kitList.add(kit); + this.getPlugin().userKitList.put(p.getUniqueId(), kitList); + + if (this.getPlugin().usingKits.containsKey(p.getName()) && this.getPlugin().usingKits.get(p.getName()).equalsIgnoreCase(strKit)) + this.getPlugin().usingKits.put(p.getName(), strNewKit); + if (this.getPlugin().playerKits.containsKey(p.getName()) && this.getPlugin().playerKits.get(p.getName()).equalsIgnoreCase(strKit)) + this.getPlugin().playerKits.put(p.getName(), strNewKit); + + Lang.sendMessage(p, Lang.COMMAND_RENAME_RENAMED, strKit, strNewKit); + } else { + Lang.sendMessage(p, Lang.KIT_NONEXISTENT, strKit); + } + } else { + Lang.sendMessage(p, Lang.COMMAND_RENAME_ILLEGAL_CHARACTERS); + } + } else { + Lang.sendMessage(p, Lang.COMMAND_RENAME_ALREADY_EXISTS, strNewKit); + } + } else { + Lang.sendMessage(p, Lang.COMMAND_GEN_USAGE, command.toLowerCase() + " [ ]"); + } + } else { + Lang.sendMessage(p, Lang.COMMAND_GEN_WORLD); + } + } else { + Lang.sendMessage(p, Lang.COMMAND_GEN_DISABLED); + } + } else { + this.sendNoAccess(p); + } + } catch (Exception ex) { + Lang.sendMessage(p, Lang.COMMAND_GEN_ERROR); + } + return true; + } + return false; + } +} diff --git a/src/main/java/com/faris/kingkits/listener/command/SetKit.java b/src/main/java/com/faris/kingkits/listener/command/SetKit.java new file mode 100644 index 0000000..e6cb0c8 --- /dev/null +++ b/src/main/java/com/faris/kingkits/listener/command/SetKit.java @@ -0,0 +1,192 @@ +package com.faris.kingkits.listener.command; + +import com.faris.kingkits.KingKits; +import com.faris.kingkits.KingKitsAPI; +import com.faris.kingkits.Kit; +import com.faris.kingkits.helper.Lang; +import com.faris.kingkits.helper.Utilities; +import com.faris.kingkits.listener.event.custom.PlayerKitEvent; +import org.bukkit.*; +import org.bukkit.entity.*; +import org.bukkit.inventory.*; +import org.bukkit.potion.*; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class SetKit { + + public static void setKingKit(Player player, String kitName, boolean sendMessages) throws Exception { + final Kit kit = setKit(player, sendMessages, kitName); + if (kit != null) { + KingKits pl = KingKits.getInstance(); + if (kit.hasCooldown() && !player.hasPermission(pl.permissions.kitBypassCooldown)) { + final String playerName = player.getName(); + final String newKitName = kit.getRealName(); + pl.getCooldownConfig().set(playerName + "." + newKitName, System.currentTimeMillis()); + pl.saveCooldownConfig(); + } + } + } + + + public static boolean setKit(Player player, String kitName, boolean sendMessages) throws Exception { + return setKit(player, sendMessages, kitName) != null; + } + + @SuppressWarnings("deprecation") + public static Kit setKit(Player player, boolean sendMessages, String kitName) throws Exception { + if (player == null || kitName == null) return null; + KingKits plugin = KingKits.getInstance(); + if (plugin.configValues.pvpWorlds.contains("All") || plugin.configValues.pvpWorlds.contains(player.getWorld().getName())) { + Kit newKit = KingKitsAPI.getKitByName(Utilities.stripColour(kitName), player.getUniqueId()); + if (newKit != null) { + kitName = newKit.getRealName(); + if (newKit.isUserKit() || player.hasPermission("kingkits.kits." + newKit.getRealName().toLowerCase())) { + if (plugin.configValues.oneKitPerLife) { + if (plugin.configValues.opBypass) { + if (!player.isOp()) { + if (plugin.playerKits.containsKey(player.getName())) { + if (sendMessages) Lang.sendMessage(player, Lang.KIT_ALREADY_CHOSEN); + return null; + } + } + } else { + if (plugin.usingKits.containsKey(player.getName())) { + if (sendMessages) Lang.sendMessage(player, Lang.KIT_ALREADY_CHOSEN); + return null; + } + } + } + String oldKit = plugin.playerKits.containsKey(player.getName()) ? plugin.playerKits.get(player.getName()) : ""; + PlayerKitEvent playerKitEvent = new PlayerKitEvent(player, kitName, oldKit, newKit.getItemsWithSlot(), newKit.getArmour(), newKit.getPotionEffects()); + playerKitEvent.setCommands(newKit.getCommands()); + player.getServer().getPluginManager().callEvent(playerKitEvent); + if (!playerKitEvent.isCancelled()) { + if (plugin.configValues.vaultValues.useEconomy && plugin.configValues.vaultValues.useCostPerKit) { + try { + net.milkbowl.vault.economy.Economy economy = (net.milkbowl.vault.economy.Economy) plugin.vault.getEconomy(); + double kitCost = newKit.getCost(); + if (kitCost > 0D) { + if (economy.hasAccount(player.getName())) { + if (economy.getBalance(player.getName()) >= kitCost) { + economy.withdrawPlayer(player.getName(), kitCost); + player.sendMessage(ChatColor.GREEN + plugin.getEconomyMessage(kitCost)); + } else { + if (sendMessages) Lang.sendMessage(player, Lang.KIT_NOT_ENOUGH_MONEY); + return null; + } + } else { + if (sendMessages) Lang.sendMessage(player, Lang.KIT_NOT_ENOUGH_MONEY); + return null; + } + } + } catch (Exception ex) { + } + } + + if (plugin.configValues.replaceItems) { + player.getInventory().clear(); + player.getInventory().setArmorContents(null); + } + player.setGameMode(GameMode.SURVIVAL); + for (PotionEffect potionEffect : player.getActivePotionEffects()) + player.removePotionEffect(potionEffect.getType()); + if (plugin.configValues.replaceItems) { + Map kitItems = playerKitEvent.getKitContentsWithSlots(); + for (Map.Entry kitItem : kitItems.entrySet()) { + try { + if (kitItem.getValue() != null && kitItem.getValue().getType() != Material.AIR) { + int slot = kitItem.getKey(); + if (slot >= 0 && slot < player.getInventory().getSize()) { + player.getInventory().setItem(slot, kitItem.getValue()); + } + } + } catch (Exception ex) { + continue; + } + } + } else { + List kitItems = playerKitEvent.getKitContents(); + for (int i = 0; i < kitItems.size(); i++) { + try { + ItemStack kitItem = kitItems.get(i); + if (kitItem != null && kitItem.getType() != Material.AIR) + player.getInventory().addItem(kitItem); + } catch (Exception ex) { + continue; + } + } + } + List armourItems = playerKitEvent.getKitArmour(); + List leftOverArmour = new ArrayList(); + for (ItemStack armourItem : armourItems) { + if (armourItem != null) { + String strArmourType = armourItem.getType().toString().toLowerCase(); + if (strArmourType.endsWith("helmet") && (plugin.configValues.replaceItems ? true : Utilities.isItemNull(player.getInventory().getHelmet()))) + player.getInventory().setHelmet(armourItem); + else if (strArmourType.endsWith("chestplate") && (plugin.configValues.replaceItems ? true : Utilities.isItemNull(player.getInventory().getChestplate()))) + player.getInventory().setChestplate(armourItem); + else if ((strArmourType.endsWith("leggings") || strArmourType.endsWith("pants")) && (plugin.configValues.replaceItems ? true : Utilities.isItemNull(player.getInventory().getLeggings()))) + player.getInventory().setLeggings(armourItem); + else if (strArmourType.endsWith("boots") && (plugin.configValues.replaceItems ? true : Utilities.isItemNull(player.getInventory().getBoots()))) + player.getInventory().setBoots(armourItem); + else if ((plugin.configValues.replaceItems || (!strArmourType.endsWith("helmet") && !strArmourType.endsWith("chestplate") && !strArmourType.endsWith("leggings") && !strArmourType.endsWith("pants") && !strArmourType.endsWith("boots"))) && player.getInventory().getHelmet() == null) + leftOverArmour.add(armourItem); + else player.getInventory().addItem(armourItem); + } + } + if (!leftOverArmour.isEmpty()) { + player.getInventory().setHelmet(leftOverArmour.get(0)); + for (int i = 1; i < leftOverArmour.size(); i++) + player.getInventory().addItem(leftOverArmour.get(i)); + } + player.setMaxHealth(newKit.getMaxHealth()); + player.addPotionEffects(playerKitEvent.getPotionEffects()); + + plugin.playerKits.remove(player.getName()); + plugin.usingKits.remove(player.getName()); + if (plugin.configValues.opBypass) { + if (!player.isOp()) plugin.playerKits.put(player.getName(), newKit.getRealName()); + } else { + plugin.playerKits.put(player.getName(), newKit.getRealName()); + } + plugin.usingKits.put(player.getName(), newKit.getRealName()); + if (plugin.configValues.commandToRun.length() > 0) { + String cmdToRun = plugin.configValues.commandToRun; + cmdToRun = cmdToRun.replace("", kitName); + cmdToRun = cmdToRun.replace("", player.getName()).replace("", player.getDisplayName()); + player.getServer().dispatchCommand(player.getServer().getConsoleSender(), cmdToRun); + } + for (String cmdToRun : playerKitEvent.getCommands()) { + cmdToRun = cmdToRun.replace("", kitName); + cmdToRun = cmdToRun.replace("", player.getName()).replace("", player.getDisplayName()); + player.getServer().dispatchCommand(player.getServer().getConsoleSender(), cmdToRun); + } + if (plugin.configValues.customMessages != "" && plugin.configValues.customMessages != "''") + player.sendMessage(r(plugin.configValues.customMessages).replace("", player.getName()).replace("", player.getDisplayName()).replace("", kitName)); + if (plugin.configValues.kitParticleEffects) + player.playEffect(player.getLocation().add(0, 1, 0), Effect.ENDER_SIGNAL, (byte) 0); + + player.updateInventory(); + return newKit; + } else { + for (PotionEffect potionEffect : player.getActivePotionEffects()) + player.removePotionEffect(potionEffect.getType()); + } + } else { + if (sendMessages) Lang.sendMessage(player, Lang.KIT_NO_PERMISSION, kitName); + } + } else { + if (sendMessages) Lang.sendMessage(player, Lang.KIT_NONEXISTENT, kitName); + } + } + return null; + } + + private static String r(String val) { + return Utilities.replaceChatColour(val); + } + +} diff --git a/src/main/java/com/faris/kingkits/listener/event/EventListener.java b/src/main/java/com/faris/kingkits/listener/event/EventListener.java new file mode 100644 index 0000000..a11f9b3 --- /dev/null +++ b/src/main/java/com/faris/kingkits/listener/event/EventListener.java @@ -0,0 +1,1057 @@ +package com.faris.kingkits.listener.event; + +import com.faris.kingkits.KingKits; +import com.faris.kingkits.KingKitsAPI; +import com.faris.kingkits.KingKitsSQL; +import com.faris.kingkits.Kit; +import com.faris.kingkits.gui.GuiKingKits; +import com.faris.kingkits.gui.GuiKitMenu; +import com.faris.kingkits.gui.GuiPreviewKit; +import com.faris.kingkits.helper.Lang; +import com.faris.kingkits.helper.Utilities; +import com.faris.kingkits.listener.command.SetKit; +import com.faris.kingkits.listener.event.custom.PlayerKilledEvent; +import org.bukkit.*; +import org.bukkit.block.*; +import org.bukkit.entity.*; +import org.bukkit.event.*; +import org.bukkit.event.block.*; +import org.bukkit.event.entity.*; +import org.bukkit.event.player.*; +import org.bukkit.inventory.*; +import org.bukkit.potion.*; +import org.bukkit.scoreboard.*; + +import java.util.List; +import java.util.Map; +import java.util.UUID; + +public class EventListener implements Listener { + + /** + * Register custom kill event * + */ + @EventHandler(priority = EventPriority.HIGHEST) + public void registerKillEvent(PlayerDeathEvent event) { + try { + if (event.getEntity().getKiller() != null) { + if (!event.getEntity().getUniqueId().equals(event.getEntity().getKiller().getUniqueId())) + event.getEntity().getServer().getPluginManager().callEvent(new PlayerKilledEvent(event.getEntity().getKiller(), event.getEntity())); + } + } catch (Exception ex) { + } + } + + @EventHandler(priority = EventPriority.LOW) + public void onPlayerJoin(PlayerJoinEvent event) { + try { + // List kits on join + try { + if (this.getPlugin().configValues.listKitsOnJoin) { + if (this.getPlugin().configValues.pvpWorlds.contains("All") || this.getPlugin().configValues.pvpWorlds.contains(event.getPlayer().getWorld().getName())) { + this.listKitsOnJoin(event.getPlayer()); + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + + // Kit menu + try { + if (this.getPlugin().configValues.kitMenuOnJoin) { + final Player player = event.getPlayer(); + player.getServer().getScheduler().runTaskLater(this.getPlugin(), new Runnable() { + @SuppressWarnings("deprecation") + public void run() { + if (player != null && player.isOnline()) { + if (!GuiKingKits.guiKitMenuMap.containsKey(player.getName()) && !GuiKingKits.guiPreviewKitMap.containsKey(player.getName())) { + KingKitsAPI.showKitMenu(player, false); + } + } + } + }, 15L); + } + } catch (Exception ex) { + ex.printStackTrace(); + } + + // Scoreboard + try { + if (event.getPlayer().getScoreboard() != null) { + Objective scoreboardObj = event.getPlayer().getScoreboard().getObjective("KingKits"); + if (scoreboardObj != null) { + Scoreboard playerBoard = event.getPlayer().getScoreboard(); + playerBoard.resetScores(ChatColor.GREEN + "Score:"); + playerBoard.resetScores(ChatColor.GREEN + "Killstreak:"); + event.getPlayer().getScoreboard().resetScores(ChatColor.GREEN + "Score:"); + event.getPlayer().getScoreboard().resetScores(ChatColor.GREEN + "Killstreak:"); + playerBoard.clearSlot(DisplaySlot.SIDEBAR); + event.getPlayer().setScoreboard(playerBoard); + } + } + } catch (Exception ex) { + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + @EventHandler + public void onPlayerLeave(PlayerQuitEvent event) { + try { + // Remove kits + final Player player = event.getPlayer(); + try { + if (this.getPlugin().configValues.removeItemsOnLeave) { + if (this.getPlugin().playerKits.containsKey(player.getName()) || this.getPlugin().usingKits.containsKey(player.getName())) { + player.getInventory().clear(); + player.getInventory().setArmorContents(null); + } + } + if (this.getPlugin().playerKits.containsKey(player.getName())) + this.getPlugin().playerKits.remove(player.getName()); + if (this.getPlugin().usingKits.containsKey(player.getName())) { + this.getPlugin().usingKits.remove(player.getName()); + player.setMaxHealth(20D); + } + if (GuiKingKits.guiKitMenuMap.containsKey(player.getName())) { + GuiKitMenu guiKitMenu = GuiKingKits.guiKitMenuMap.get(player.getName()); + if (guiKitMenu != null) guiKitMenu.closeMenu(true, true); + GuiKingKits.guiKitMenuMap.remove(player.getName()); + } + if (GuiKingKits.guiPreviewKitMap.containsKey(player.getName())) { + GuiPreviewKit guiPreviewKit = GuiKingKits.guiPreviewKitMap.get(player.getName()); + if (guiPreviewKit != null) guiPreviewKit.closeMenu(true, true); + GuiKingKits.guiPreviewKitMap.remove(player.getName()); + } + player.updateInventory(); + } catch (Exception ex) { + ex.printStackTrace(); + } + + // Remove potion effects + try { + if (this.getPlugin().configValues.removePotionEffectsOnLeave) { + if (this.getPlugin().configValues.pvpWorlds.contains("All") || this.getPlugin().configValues.pvpWorlds.contains(event.getPlayer().getWorld().getName())) { + for (PotionEffect potionEffectOnPlayer : event.getPlayer().getActivePotionEffects()) { + PotionEffectType potionEffectType = potionEffectOnPlayer.getType(); + event.getPlayer().removePotionEffect(potionEffectType); + } + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + + // Remove compass target + try { + if (this.getPlugin().configValues.rightClickCompass) { + if (this.getPlugin().compassTargets.containsValue(event.getPlayer().getUniqueId())) { + Player tracker = null; + for (Map.Entry compassEntry : this.getPlugin().compassTargets.entrySet()) { + Player key = Bukkit.getServer().getPlayer(compassEntry.getKey()); + Player value = Bukkit.getServer().getPlayer(compassEntry.getValue()); + if (key != null && value != null && key.isOnline() && value.isOnline()) { + if (event.getPlayer().getName().equalsIgnoreCase(value.getName())) + tracker = key; + } + } + if (tracker != null) this.getPlugin().compassTargets.remove(tracker.getUniqueId()); + } + if (this.getPlugin().compassTargets.containsKey(event.getPlayer().getUniqueId())) + this.getPlugin().compassTargets.remove(event.getPlayer().getUniqueId()); + } + } catch (Exception ex) { + ex.printStackTrace(); + } + + // Remove killstreak + try { + this.getPlugin().playerKillstreaks.remove(event.getPlayer().getName()); + } catch (Exception ex) { + } + } catch (Exception ex) { + } + } + + @EventHandler + public void onPlayerInteract(PlayerInteractEvent event) { + // Quick soup + try { + if (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK) { + if (event.getItem() != null) { + if (event.getItem().getType() == Material.MUSHROOM_SOUP) { + if (this.getPlugin().configValues.quickSoup) { + if (event.getPlayer().hasPermission(this.getPlugin().permissions.quickSoup) || (this.getPlugin().configValues.opBypass && event.getPlayer().isOp())) { + if (this.getPlugin().configValues.pvpWorlds.contains("All") || this.getPlugin().configValues.pvpWorlds.contains(event.getPlayer().getWorld().getName())) { + Player player = event.getPlayer(); + int soupAmount = player.getInventory().getItemInHand().getAmount(); + if (soupAmount > 0) { + boolean valid = true; + if (player.getHealth() < player.getMaxHealth()) { + if (player.getHealth() + (this.getPlugin().configValues.quickSoupHeal * 2) > player.getMaxHealth()) + player.setHealth(player.getMaxHealth()); + else + player.setHealth(player.getHealth() + (this.getPlugin().configValues.quickSoupHeal * 2)); + } else if (player.getFoodLevel() < 20) { + if (player.getFoodLevel() + 6 > 20) player.setFoodLevel(20); + else player.setFoodLevel(player.getFoodLevel() + 6); + } else { + valid = false; + } + if (valid) { + if (soupAmount == 1) { + player.getInventory().setItemInHand(new ItemStack(Material.BOWL, 1)); + } else { + int newAmount = soupAmount - 1; + ItemStack newItem = player.getInventory().getItemInHand(); + newItem.setAmount(newAmount); + player.getInventory().setItemInHand(newItem); + player.getInventory().addItem(new ItemStack(Material.BOWL, 1)); + } + event.setCancelled(true); + } + } + } + } + } + } + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + @EventHandler(ignoreCancelled = true) + public void onPlayerInteractIgnoreCancelled(PlayerInteractEvent event) { + try { + // No tool damage + try { + if (event.getItem() != null) { + if (this.getPlugin().usingKits.containsKey(event.getPlayer().getName())) { + if (this.isTool(event.getItem().getType()) || event.getItem().getType() == Material.FISHING_ROD || event.getItem().getType() == Material.FLINT_AND_STEEL) { + boolean repair = false; + if (this.getPlugin().configValues.disableItemBreaking) { + repair = true; + } else { + Kit kit = KingKitsAPI.getKitByName(this.getPlugin().usingKits.get(event.getPlayer().getName()), false); + if (kit != null && !kit.canItemsBreak()) { + repair = true; + } + } + if (repair) event.getItem().setDurability((short) 0); + } + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + + // Right clicking a sign + try { + if (event.getAction() == Action.RIGHT_CLICK_BLOCK) { + if (event.getPlayer().getWorld() != null) { + if (this.getPlugin().configValues.pvpWorlds.contains("All") || this.getPlugin().configValues.pvpWorlds.contains(event.getPlayer().getWorld().getName())) { + Player player = event.getPlayer(); + BlockState block = event.getClickedBlock().getState(); + if ((block instanceof Sign)) { + Sign sign = (Sign) block; + String signLine0 = sign.getLine(0); + if (signLine0.equalsIgnoreCase((this.getPlugin().configValues.strKitSignValid.startsWith("&0") ? this.getPlugin().configValues.strKitSignValid.replaceFirst("&0", "") : this.getPlugin().configValues.strKitSignValid))) { + if (player.hasPermission(this.getPlugin().permissions.kitUseSign)) { + String line1 = sign.getLine(1); + if (line1 != null) { + if (!line1.equalsIgnoreCase("")) { + List kitList = this.getPlugin().getKitList(); + List kitListLC = Utilities.toLowerCaseList(kitList); + if (kitListLC.contains(line1.toLowerCase())) { + String kitName = kitList.get(kitListLC.indexOf(line1.toLowerCase())); + try { + final Kit kit = KingKitsAPI.getKitByName(kitName, false); + boolean validCooldown = true; + if (kit != null && kit.hasCooldown() && !player.hasPermission(this.getPlugin().permissions.kitBypassCooldown)) { + if (this.getPlugin().getCooldownConfig().contains(player.getName() + "." + kit.getRealName())) { + long currentCooldown = this.getPlugin().getCooldown(player.getName(), kit.getRealName()); + if (System.currentTimeMillis() - currentCooldown >= kit.getCooldown() * 1000) { + this.getPlugin().getCooldownConfig().set(player.getName() + "." + kit.getRealName(), null); + this.getPlugin().saveCooldownConfig(); + } else { + Lang.sendMessage(player, Lang.KIT_DELAY, String.valueOf((kit.getCooldown() - ((System.currentTimeMillis() - currentCooldown) / 1000)))); + validCooldown = false; + } + } + } + if (validCooldown) SetKit.setKingKit(player, kitName, true); + } catch (Exception ex) { + ex.printStackTrace(); + Lang.sendMessage(player, Lang.COMMAND_GEN_ERROR); + } + } else { + Lang.sendMessage(player, Lang.KIT_NONEXISTENT, line1); + sign.setLine(0, this.getPlugin().configValues.strKitSignInvalid); + sign.update(true); + } + } else { + Lang.sendMessage(player, Lang.SIGN_GENERAL_INCORRECTLY_SETUP); + sign.setLine(0, this.getPlugin().configValues.strKitSignInvalid); + sign.update(true); + } + } else { + Lang.sendMessage(player, Lang.SIGN_GENERAL_INCORRECTLY_SETUP); + sign.setLine(0, this.getPlugin().configValues.strKitSignInvalid); + sign.update(true); + } + } else { + Lang.sendMessage(player, Lang.SIGN_USE_NO_PERMISSION); + } + event.setCancelled(true); + } else if (signLine0.equalsIgnoreCase(this.getPlugin().configValues.strKitListSignValid.startsWith("&0") ? this.getPlugin().configValues.strKitListSignValid.replaceFirst("&0", "") : this.getPlugin().configValues.strKitListSignValid)) { + if (player.hasPermission(this.getPlugin().permissions.kitListSign)) { + if (!this.getPlugin().configValues.kitListMode.equalsIgnoreCase("Gui") && !this.getPlugin().configValues.kitListMode.equalsIgnoreCase("Menu")) { + List kitList = this.getPlugin().getKitList(); + Lang.sendMessage(player, Lang.GEN_KIT_LIST_TITLE, String.valueOf(kitList.size())); + if (!kitList.isEmpty()) { + for (int kitPos = 0; kitPos < kitList.size(); kitPos++) { + String kitName = kitList.get(kitPos).split(" ")[0]; + if (player.hasPermission("kingkits.kits." + kitName.toLowerCase())) { + player.sendMessage(this.r("&6" + (kitPos + 1) + ". " + kitName)); + } else { + if (this.getPlugin().configValues.kitListPermissions) + player.sendMessage(this.r("&4" + (kitPos + 1) + ". " + kitName)); + } + } + } else { + Lang.sendMessage(player, Lang.GEN_NO_KITS); + } + } else { + KingKitsAPI.showKitMenu(player); + } + } else { + Lang.sendMessage(player, Lang.SIGN_USE_NO_PERMISSION); + } + event.setCancelled(true); + } + } + } + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } catch (Exception ex) { + } + } + + @EventHandler + public void onSignChange(SignChangeEvent event) { + try { + // Creating a sign + try { + if (this.getPlugin().configValues.pvpWorlds.contains("All") || this.getPlugin().configValues.pvpWorlds.contains(event.getPlayer().getWorld().getName())) { + Player p = event.getPlayer(); + String signType = event.getLine(0); + if (signType.equalsIgnoreCase(this.getPlugin().configValues.strKitSign)) { + if (p.hasPermission(this.getPlugin().permissions.kitCreateSign)) { + if (!event.getLine(1).isEmpty()) { + event.setLine(0, this.getPlugin().configValues.strKitSignValid); + } else { + event.setLine(0, this.getPlugin().configValues.strKitSignInvalid); + Lang.sendMessage(p, Lang.SIGN_CREATE_SECOND_LINE); + } + } else { + Lang.sendMessage(p, Lang.SIGN_CREATE_NO_PERMISSION, "create"); + event.setLine(0, ""); + event.setLine(1, ""); + event.setLine(2, ""); + event.setLine(3, ""); + } + } else if (signType.equalsIgnoreCase(this.getPlugin().configValues.strKitListSign)) { + if (p.hasPermission(this.getPlugin().permissions.kitListSign)) { + event.setLine(0, this.getPlugin().configValues.strKitListSignValid); + } else { + Lang.sendMessage(p, Lang.SIGN_CREATE_NO_PERMISSION, "list"); + event.setLine(0, ""); + event.setLine(1, ""); + event.setLine(2, ""); + event.setLine(3, ""); + } + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } catch (Exception ex) { + } + } + + @EventHandler + public void onPlayerDeath(PlayerDeathEvent event) { + try { + boolean inPvPWorld = this.getPlugin().configValues.pvpWorlds.contains("All") || this.getPlugin().configValues.pvpWorlds.contains(event.getEntity().getWorld().getName()); + + // Scores + try { + if (this.getPlugin().configValues.scores) { + if (inPvPWorld) { + final Player killer = event.getEntity().getKiller(); + if (killer != null && !event.getEntity().getName().equals(killer.getName())) { + try { + if (!this.getPlugin().playerScores.containsKey(killer.getUniqueId())) + this.getPlugin().playerScores.put(killer.getUniqueId(), 0); + int currentScore = (Integer) this.getPlugin().playerScores.get(killer.getUniqueId()); + int newScore = currentScore + this.getPlugin().configValues.scoreIncrement; + if (newScore > this.getPlugin().configValues.maxScore) + newScore = this.getPlugin().configValues.maxScore; + this.getPlugin().playerScores.put(killer.getUniqueId(), newScore); + this.getPlugin().getScoresConfig().set("Scores." + killer.getUniqueId(), (long) newScore); + this.getPlugin().saveScoresConfig(); + + if (KingKitsSQL.sqlEnabled) { + final int kScore = newScore; + killer.getServer().getScheduler().runTaskAsynchronously(this.getPlugin(), new Runnable() { + @Override + public void run() { + KingKitsSQL.setScore(killer, kScore); + } + }); + } + } catch (Exception ex) { + } + } + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + + // Core + try { + Player player = event.getEntity(); + boolean hadKit = false; + if (this.getPlugin().playerKits.containsKey(player.getName())) { + this.getPlugin().playerKits.remove(player.getName()); + hadKit = true; + } + if (this.getPlugin().usingKits.containsKey(player.getName())) { + this.getPlugin().usingKits.remove(player.getName()); + hadKit = true; + } + if (inPvPWorld && !this.getPlugin().configValues.dropItemsOnDeath) + event.getDrops().clear(); + if (hadKit) { + player.setMaxHealth(20D); + player.getInventory().clear(); + player.getInventory().setArmorContents(null); + player.updateInventory(); + + for (PotionEffect activeEffect : player.getActivePotionEffects()) + player.removePotionEffect(activeEffect.getType()); + } + } catch (Exception ex) { + ex.printStackTrace(); + } + + // Disable death messages + try { + if (this.getPlugin().configValues.disableDeathMessages) { + if (inPvPWorld) event.setDeathMessage(""); + } + } catch (Exception ex) { + } + + // Remove money. + if (event.getEntity().getKiller() != null) { + try { + if (this.getPlugin().configValues.vaultValues.useEconomy && this.getPlugin().configValues.vaultValues.useMoneyPerDeath) { + if (!event.getEntity().getName().equalsIgnoreCase(event.getEntity().getKiller().getName())) { + if (this.getPlugin().configValues.pvpWorlds.contains("All") || this.getPlugin().configValues.pvpWorlds.contains(event.getEntity().getKiller().getWorld().getName())) { + net.milkbowl.vault.economy.Economy economy = (net.milkbowl.vault.economy.Economy) this.getPlugin().vault.getEconomy(); + economy.withdrawPlayer(event.getEntity(), this.getPlugin().configValues.vaultValues.moneyPerDeath); + event.getEntity().sendMessage(this.getPlugin().getMPDMessage(event.getEntity(), this.getPlugin().configValues.vaultValues.moneyPerDeath)); + } + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + // Killstreaks + if (this.getPlugin().configValues.killstreaks && this.getPlugin().playerKillstreaks.containsKey(event.getEntity().getName())) + this.getPlugin().playerKillstreaks.remove(event.getEntity().getName()); + } catch (Exception ex) { + } + } + + @SuppressWarnings("deprecation") + @EventHandler + public void onPlayerDropItem(PlayerDropItemEvent event) { + try { + // Ban dropping items + try { + if (event.getItemDrop() != null) { + if (event.getPlayer().getWorld() != null) { + if (!this.getPlugin().configValues.dropItems) { + if (this.getPlugin().configValues.pvpWorlds.contains("All") || this.getPlugin().configValues.pvpWorlds.contains(event.getPlayer().getWorld().getName())) { + if (this.getPlugin().configValues.opBypass) { + if (!event.getPlayer().isOp()) { + if (this.getPlugin().playerKits.containsKey(event.getPlayer().getName())) { + if (this.getPlugin().configValues.dropAnimations.contains(event.getItemDrop().getItemStack().getType().getId())) { + event.getItemDrop().remove(); + } else { + Lang.sendMessage(event.getPlayer(), Lang.GEN_ITEM_DROP); + event.setCancelled(true); + } + } + } + } else { + if (this.getPlugin().usingKits.containsKey(event.getPlayer().getName())) { + if (this.getPlugin().configValues.dropAnimations.contains(event.getItemDrop().getItemStack().getType().getId())) { + event.getItemDrop().remove(); + } else { + Lang.sendMessage(event.getPlayer(), Lang.GEN_ITEM_DROP); + event.setCancelled(true); + } + } + } + } + } + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } catch (Exception ex) { + } + } + + @EventHandler + public void onPlayerPickupItem(PlayerPickupItemEvent event) { + try { + // Ban picking items + try { + if (event.getItem() != null) { + if (event.getPlayer().getWorld() != null) { + if (!this.getPlugin().configValues.allowPickingUpItems) { + if (this.getPlugin().configValues.pvpWorlds.contains("All") || this.getPlugin().configValues.pvpWorlds.contains(event.getPlayer().getWorld().getName())) { + if (this.getPlugin().configValues.opBypass) { + if (!event.getPlayer().isOp()) { + if (this.getPlugin().playerKits.containsKey(event.getPlayer().getName())) { + event.setCancelled(true); + } + } + } else { + if (this.getPlugin().usingKits.containsKey(event.getPlayer().getName())) { + event.setCancelled(true); + } + } + } + } + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } catch (Exception ex) { + } + } + + @EventHandler(ignoreCancelled = true) + public void onPlayerChat(AsyncPlayerChatEvent event) { + try { + // Score chat prefix + try { + if (this.getPlugin().configValues.scores) { + if (this.getPlugin().configValues.pvpWorlds.contains("All") || this.getPlugin().configValues.pvpWorlds.contains(event.getPlayer().getWorld().getName())) { + Player player = event.getPlayer(); + if (!this.getPlugin().playerScores.containsKey(player.getUniqueId())) { + this.getPlugin().playerScores.put(player.getUniqueId(), 0); + this.getPlugin().getScoresConfig().set("Scores." + player.getUniqueId(), 0); + this.getPlugin().saveScoresConfig(); + } + event.setFormat(Utilities.replaceChatColour(this.getPlugin().configValues.scoreFormat).replace("", String.valueOf(this.getPlugin().playerScores.get(player.getUniqueId()))) + ChatColor.WHITE + " " + event.getFormat()); + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } catch (Exception ex) { + } + } + + @EventHandler + public void onPlayerInteractCompass(PlayerInteractEvent event) { + try { + if (this.getPlugin().configValues.rightClickCompass) { + if (this.getPlugin().configValues.pvpWorlds.contains("All") || this.getPlugin().configValues.pvpWorlds.contains(event.getPlayer().getWorld().getName())) { + if (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK) { + if (event.getPlayer().getInventory().getItemInHand() != null) { + if (event.getPlayer().getInventory().getItemInHand().getType() == Material.COMPASS) { + if (event.getPlayer().hasPermission(this.getPlugin().permissions.rightClickCompass) || event.getPlayer().isOp()) { + Player nearestPlayer = null; + double distance = -1D; + for (Player target : event.getPlayer().getServer().getOnlinePlayers()) { + if (!target.getName().equalsIgnoreCase(event.getPlayer().getName())) { + if (event.getPlayer().getLocation().getWorld().getName().equalsIgnoreCase(target.getLocation().getWorld().getName())) { + if (distance == -1D) { + distance = event.getPlayer().getLocation().distanceSquared(target.getLocation()); + nearestPlayer = target; + } else { + double distanceSquared = event.getPlayer().getLocation().distanceSquared(target.getLocation()); + if (distanceSquared <= distance) { + distance = distanceSquared; + nearestPlayer = target; + } + } + } + } + } + if (nearestPlayer != null) { + event.getPlayer().setCompassTarget(nearestPlayer.getLocation()); + Lang.sendMessage(event.getPlayer(), Lang.COMPASS_POINTING_PLAYER, nearestPlayer.getName()); + if (this.getPlugin().compassTargets.containsKey(event.getPlayer().getUniqueId())) + this.getPlugin().compassTargets.remove(event.getPlayer().getUniqueId()); + this.getPlugin().compassTargets.put(event.getPlayer().getUniqueId(), nearestPlayer.getUniqueId()); + } else { + event.getPlayer().setCompassTarget(event.getPlayer().getWorld().getSpawnLocation()); + Lang.sendMessage(event.getPlayer(), Lang.COMPASS_POINTING_SPAWN); + } + } + } + } + } + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + @EventHandler(ignoreCancelled = true) + public void onPlayerMove(PlayerMoveEvent event) { + try { + // Compass tracking updater + try { + if (this.getPlugin().configValues.rightClickCompass) { + if (this.getPlugin().compassTargets.containsValue(event.getPlayer().getUniqueId())) { + Player tracker = null; + for (Map.Entry compassTargetsEntry : this.getPlugin().compassTargets.entrySet()) { + Player key = Bukkit.getPlayer(compassTargetsEntry.getKey()); + Player value = Bukkit.getPlayer(compassTargetsEntry.getValue()); + if (key != null) { + if (value != null) { + if (key.isOnline()) { + if (value.isOnline()) { + if (event.getPlayer().getUniqueId().equals(value.getUniqueId())) + tracker = key.getPlayer(); + } + } + } + } + } + if (tracker != null) tracker.setCompassTarget(event.getPlayer().getLocation()); + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } catch (Exception ex) { + } + } + + @EventHandler(ignoreCancelled = true) + public void onBlockBreak(BlockBreakEvent event) { + try { + // Disable block breaking + try { + if (this.getPlugin().configValues.banBlockBreakingAndPlacing) { + if (this.getPlugin().configValues.pvpWorlds.contains("All") || this.getPlugin().configValues.pvpWorlds.contains(event.getPlayer().getWorld().getName())) { + if (this.getPlugin().configValues.opBypass) { + if (!event.getPlayer().isOp()) event.setCancelled(true); + } else { + event.setCancelled(true); + } + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + + // Disable item breaking + try { + if (event.getPlayer().getGameMode() == GameMode.SURVIVAL) { + String playerKit = this.getPlugin().usingKits.get(event.getPlayer().getName()); + if (playerKit != null) { + boolean repair = false; + if (this.getPlugin().configValues.disableItemBreaking) { + repair = true; + } else { + Kit kit = KingKitsAPI.getKitByName(playerKit, false); + if (kit != null && !kit.canItemsBreak()) { + repair = true; + } + } + if (repair) { + final Player player = event.getPlayer(); + if (player.getItemInHand() != null && (this.isTool(player.getItemInHand().getType()) || player.getItemInHand().getType() == Material.FISHING_ROD || player.getItemInHand().getType() == Material.FLINT_AND_STEEL)) { + player.getServer().getScheduler().runTask(this.getPlugin(), new Runnable() { + @Override + public void run() { + if (player != null && player.isOnline() && player.getItemInHand() != null && (isTool(player.getItemInHand().getType()) || player.getItemInHand().getType() == Material.FISHING_ROD || player.getItemInHand().getType() == Material.FLINT_AND_STEEL)) { + ItemStack item = player.getItemInHand(); + item.setDurability((short) 0); + player.setItemInHand(item); + player.updateInventory(); + } + } + }); + } + } + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } catch (Exception ex) { + } + } + + @EventHandler(ignoreCancelled = true) + public void onBlockPlace(BlockPlaceEvent event) { + try { + // Disable block placing + try { + if (this.getPlugin().configValues.banBlockBreakingAndPlacing) { + if (this.getPlugin().configValues.pvpWorlds.contains("All") || this.getPlugin().configValues.pvpWorlds.contains(event.getPlayer().getWorld().getName())) { + if (this.getPlugin().configValues.opBypass) { + if (!event.getPlayer().isOp()) event.setCancelled(true); + } else { + event.setCancelled(true); + } + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } catch (Exception ex) { + } + } + + @EventHandler + public void onFoodLevelChange(FoodLevelChangeEvent event) { + try { + // Lock hunger bar + try { + if (this.getPlugin().configValues.lockHunger) { + if (event.getEntity() instanceof Player) { + Player player = (Player) event.getEntity(); + if (this.getPlugin().configValues.pvpWorlds.contains("All") || this.getPlugin().configValues.pvpWorlds.contains(player.getWorld().getName())) + event.setFoodLevel(this.getPlugin().configValues.hungerLock); + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } catch (Exception ex) { + } + } + + @EventHandler + public void onPlayerKill(PlayerKilledEvent event) { + try { + // Give killer money + try { + Player killer = event.getPlayer(); + if (this.getPlugin().configValues.vaultValues.useEconomy && this.getPlugin().configValues.vaultValues.useMoneyPerKill) { + if (this.getPlugin().configValues.pvpWorlds.contains("All") || this.getPlugin().configValues.pvpWorlds.contains(killer.getWorld().getName())) { + net.milkbowl.vault.economy.Economy economy = (net.milkbowl.vault.economy.Economy) this.getPlugin().vault.getEconomy(); + if (!economy.hasAccount(killer)) economy.createPlayerAccount(killer); + economy.depositPlayer(killer, this.getPlugin().configValues.vaultValues.moneyPerKill); + killer.sendMessage(this.getPlugin().getMPKMessage(event.getDead(), this.getPlugin().configValues.vaultValues.moneyPerKill)); + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + + // Update their killstreak + try { + if (this.getPlugin().configValues.killstreaks) { + if (this.getPlugin().configValues.pvpWorlds.contains("All") || this.getPlugin().configValues.pvpWorlds.contains(event.getPlayer().getWorld().getName())) { + if (!this.getPlugin().playerKillstreaks.containsKey(event.getPlayer().getName())) + this.getPlugin().playerKillstreaks.put(event.getPlayer().getName(), 0L); + + long currentKillstreak = this.getPlugin().playerKillstreaks.get(event.getPlayer().getName()); + if (currentKillstreak + 1L > Long.MAX_VALUE - 1) + this.getPlugin().playerKillstreaks.put(event.getPlayer().getName(), 0L); + else + this.getPlugin().playerKillstreaks.put(event.getPlayer().getName(), this.getPlugin().playerKillstreaks.get(event.getPlayer().getName()) + 1L); + + currentKillstreak = this.getPlugin().playerKillstreaks.get(event.getPlayer().getName()); + if (this.getPlugin().getKillstreaksConfig().contains("Killstreak " + currentKillstreak)) { + List killstreakCommands = this.getPlugin().getKillstreaksConfig().getStringList("Killstreak " + currentKillstreak); + for (String killstreakCommand : killstreakCommands) + event.getPlayer().getServer().dispatchCommand(event.getPlayer().getServer().getConsoleSender(), killstreakCommand.replace("", event.getPlayer().getName()).replace("", event.getPlayer().getDisplayName()).replace("", "" + currentKillstreak)); + } + if (KingKitsAPI.hasKit(event.getPlayer())) { + Kit playerKit = KingKitsAPI.getKitByName(KingKitsAPI.getKit(event.getPlayer()), false); + if (playerKit != null) { + if (playerKit.getKillstreaks().containsKey(currentKillstreak)) { + List killstreakCommands = playerKit.getKillstreaks().get(currentKillstreak); + for (String killstreakCommand : killstreakCommands) + event.getPlayer().getServer().dispatchCommand(event.getPlayer().getServer().getConsoleSender(), killstreakCommand.replace("", event.getPlayer().getName()).replace("", event.getPlayer().getDisplayName()).replace("", "" + currentKillstreak)); + } + } + } + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } catch (Exception ex) { + } + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onPlayerChangeWorld(PlayerChangedWorldEvent event) { + try { + // Remove kit + try { + if (!this.getPlugin().configValues.pvpWorlds.contains("All") && !this.getPlugin().configValues.pvpWorlds.contains(event.getPlayer().getWorld().getName())) { + if (this.getPlugin().playerKits.containsKey(event.getPlayer().getName())) + this.getPlugin().playerKits.remove(event.getPlayer().getName()); + if (this.getPlugin().usingKits.containsKey(event.getPlayer().getName())) { + this.getPlugin().usingKits.remove(event.getPlayer().getName()); + event.getPlayer().setMaxHealth(20D); + if (!this.getPlugin().getServer().getPluginManager().isPluginEnabled(this.getPlugin().configValues.multiInvsPlugin) && !this.getPlugin().configValues.multiInvs) { + event.getPlayer().getInventory().clear(); + event.getPlayer().getInventory().setArmorContents(null); + event.getPlayer().updateInventory(); + } + for (PotionEffect potionEffectOnPlayer : event.getPlayer().getActivePotionEffects()) + event.getPlayer().removePotionEffect(potionEffectOnPlayer.getType()); + } + } else if (this.getPlugin().configValues.pvpWorlds.contains("All") || (!this.getPlugin().configValues.pvpWorlds.contains(event.getFrom().getName()) && this.getPlugin().configValues.pvpWorlds.contains(event.getPlayer().getWorld().getName()))) { + if (!this.getPlugin().getServer().getPluginManager().isPluginEnabled(this.getPlugin().configValues.multiInvsPlugin) && !this.getPlugin().configValues.multiInvs) { + event.getPlayer().getInventory().clear(); + event.getPlayer().getInventory().setArmorContents(null); + event.getPlayer().updateInventory(); + } + for (PotionEffect potionEffectOnPlayer : event.getPlayer().getActivePotionEffects()) + event.getPlayer().removePotionEffect(potionEffectOnPlayer.getType()); + if (this.getPlugin().configValues.listKitsOnJoin) this.listKitsOnJoin(event.getPlayer()); + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } catch (Exception ex) { + } + } + + @EventHandler(ignoreCancelled = true) + public void onPlayerChangeGamemode(PlayerGameModeChangeEvent event) { + try { + // Disable gamemode changing + try { + if (this.getPlugin().configValues.disableGamemode) { + if (event.getNewGameMode() == GameMode.CREATIVE) { + if (!(this.getPlugin().configValues.opBypass && event.getPlayer().isOp())) { + if (this.getPlugin().configValues.pvpWorlds.contains("All") || this.getPlugin().configValues.pvpWorlds.contains(event.getPlayer().getWorld().getName())) + event.setCancelled(true); + } + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } catch (Exception ex) { + } + } + + @EventHandler(ignoreCancelled = true) + public void onEntityDamageByEntityEvent(EntityDamageByEntityEvent event) { + try { + // Weapons unbreakable + try { + if (event.getDamager() instanceof Player) { + final Player player = (Player) event.getDamager(); + if (player.getGameMode() == GameMode.SURVIVAL) { + if (player.getItemInHand() != null && this.getPlugin().usingKits.containsKey(player.getName())) { + boolean repair = false; + if ((this.isTool(player.getItemInHand().getType()) || player.getItemInHand().getType() == Material.FISHING_ROD || player.getItemInHand().getType() == Material.FLINT_AND_STEEL)) { + if (this.getPlugin().configValues.disableItemBreaking) { + repair = true; + } else { + Kit kit = KingKitsAPI.getKitByName(this.getPlugin().usingKits.get(player.getName()), false); + if (kit != null && !kit.canItemsBreak()) { + repair = true; + } + } + } + if (repair) { + player.getServer().getScheduler().runTask(this.getPlugin(), new Runnable() { + @Override + public void run() { + if (player != null && player.isOnline() && getPlugin().usingKits.containsKey(player.getName()) && player.getItemInHand() != null && (isTool(player.getItemInHand().getType()) || player.getItemInHand().getType() == Material.FISHING_ROD || player.getItemInHand().getType() == Material.FLINT_AND_STEEL)) { + ItemStack item = player.getItemInHand(); + item.setDurability((short) 0); + player.setItemInHand(item); + player.updateInventory(); + } + } + }); + } + } + } + } + if (event.getEntity() instanceof Player) { + Player player = (Player) event.getEntity(); + if (player.getGameMode() == GameMode.SURVIVAL) { + if (this.getPlugin().usingKits.containsKey(player.getName())) { + boolean repair = false; + if (this.getPlugin().configValues.disableItemBreaking) { + repair = true; + } else { + Kit kit = KingKitsAPI.getKitByName(this.getPlugin().usingKits.get(player.getName()), false); + if (kit != null && !kit.canItemsBreak()) { + repair = true; + } + } + if (repair) { + ItemStack[] armour = player.getInventory().getArmorContents(); + for (ItemStack i : armour) + if (i != null && isArmour(i.getType())) i.setDurability((short) 0); + player.getInventory().setArmorContents(armour); + player.updateInventory(); + } + } + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } catch (Exception ex) { + } + } + + @EventHandler(ignoreCancelled = true) + public void onBowShoot(EntityShootBowEvent event) { + try { + // Unbreakable bow + try { + if (event.getEntity() instanceof Player) { + Player player = (Player) event.getEntity(); + if (this.getPlugin().usingKits.containsKey(player.getName())) { + boolean repair = false; + if (this.getPlugin().configValues.disableItemBreaking) { + repair = true; + } else { + Kit kit = KingKitsAPI.getKitByName(this.getPlugin().usingKits.get(player.getName()), false); + if (kit != null && !kit.canItemsBreak()) { + repair = true; + } + } + if (repair) + event.getBow().setDurability((short) 0); + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } catch (Exception ex) { + } + } + + @EventHandler(priority = EventPriority.HIGH) + public void onPlayerRunCommand(PlayerCommandPreprocessEvent event) { + try { + // Kit command alias + try { + if (!event.isCancelled()) { + String strCommand = event.getMessage().contains(" ") ? event.getMessage().split(" ")[0].substring(1) : event.getMessage().substring(1); + Kit targetKit = KingKitsAPI.getKitByName(strCommand, true); + if (targetKit != null && !targetKit.isUserKit() && targetKit.hasAlias()) { + event.setCancelled(true); + event.getPlayer().performCommand("pvpkit " + targetKit.getName()); + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } catch (Exception ex) { + } + } + + /** + * Gets the plugin instance * + */ + private KingKits getPlugin() { + return KingKits.getInstance(); + } + + private void listKitsOnJoin(final Player p) { + p.getServer().getScheduler().runTaskLater(this.getPlugin(), new Runnable() { + public void run() { + if (p != null && p.isOnline()) { + List kitList = getPlugin().getKitList(); + StringBuilder sbKits = new StringBuilder(); + for (int kitPos = 0; kitPos < kitList.size(); kitPos++) { + String kit = kitList.get(kitPos); + ChatColor col = ChatColor.GREEN; + boolean ignoreKit = false; + if (!p.hasPermission("kingkits.kits." + kit.toLowerCase())) { + if (!getPlugin().configValues.kitListPermissionsJoin) ignoreKit = true; + else col = ChatColor.DARK_RED; + } + if (!ignoreKit) { + if (kitPos == kitList.size() - 1) sbKits.append(col).append(kit); + else sbKits.append(col).append(kit).append(", "); + } else { + if (kitPos == kitList.size() - 1) + sbKits = new StringBuilder().append(replaceLast(sbKits.toString(), ",", "")); + } + } + if (sbKits.toString().trim().isEmpty()) + sbKits = new StringBuilder().append(Lang.GEN_NO_KITS_AVAILABLE.getMessage()); + Lang.sendMessage(p, Lang.GEN_KIT_LIST, sbKits.toString()); + } + } + }, 25L); + } + + /** + * Returns if a material is an armour piece + */ + private boolean isArmour(Material material) { + return material.name().endsWith("HELMET") || material.name().endsWith("CHESTPLATE") || material.name().endsWith("LEGGINGS") || material.name().endsWith("BOOTS"); + } + + /** + * Returns if a material is a tool/sword * + */ + private boolean isTool(Material material) { + return material.name().endsWith("SWORD") || material.name().endsWith("PICKAXE") || material.name().endsWith("AXE") || material.name().endsWith("SPADE") || material.name().endsWith("SHOVEL") || material.name().endsWith("HOE"); + } + + /** + * Replaces the last occurrence of a string in a string * + */ + private String replaceLast(String text, String original, String replacement) { + String message = text; + if (message.contains(original)) { + StringBuilder stringBuilder = new StringBuilder(text); + stringBuilder.replace(text.lastIndexOf(original), text.lastIndexOf(original) + 1, replacement); + message = stringBuilder.toString(); + } + return message; + } + + /** + * Returns a string with the real colours * + */ + private String r(String message) { + return Utilities.replaceChatColour(message); + } + +} diff --git a/src/main/java/com/faris/kingkits/listeners/event/custom/KingKitsPreReloadEvent.java b/src/main/java/com/faris/kingkits/listener/event/custom/KingKitsPreReloadEvent.java similarity index 77% rename from src/main/java/com/faris/kingkits/listeners/event/custom/KingKitsPreReloadEvent.java rename to src/main/java/com/faris/kingkits/listener/event/custom/KingKitsPreReloadEvent.java index 34c5c95..51fc726 100644 --- a/src/main/java/com/faris/kingkits/listeners/event/custom/KingKitsPreReloadEvent.java +++ b/src/main/java/com/faris/kingkits/listener/event/custom/KingKitsPreReloadEvent.java @@ -1,11 +1,10 @@ -package com.faris.kingkits.listeners.event.custom; +package com.faris.kingkits.listener.event.custom; -import org.bukkit.command.CommandSender; -import org.bukkit.event.Cancellable; -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; +import org.bukkit.command.*; +import org.bukkit.event.*; public class KingKitsPreReloadEvent extends Event implements Cancellable { + private static final HandlerList handlers = new HandlerList(); private CommandSender theSender = null; @@ -13,13 +12,16 @@ public class KingKitsPreReloadEvent extends Event implements Cancellable { /** * Create a new KingKitsPreReloadEvent instance. + * * @param sender - The CommandSender that is reloading the configuration. - **/ + */ public KingKitsPreReloadEvent(CommandSender sender) { this.theSender = sender; } - /** Returns the player **/ + /** + * Returns the player * + */ public CommandSender getSender() { return this.theSender; } diff --git a/src/main/java/com/faris/kingkits/listener/event/custom/KingKitsReloadEvent.java b/src/main/java/com/faris/kingkits/listener/event/custom/KingKitsReloadEvent.java new file mode 100644 index 0000000..c30b13d --- /dev/null +++ b/src/main/java/com/faris/kingkits/listener/event/custom/KingKitsReloadEvent.java @@ -0,0 +1,66 @@ +package com.faris.kingkits.listener.event.custom; + +import org.bukkit.command.*; +import org.bukkit.event.*; + +public class KingKitsReloadEvent extends Event { + + private static final HandlerList handlers = new HandlerList(); + + private CommandSender theSender = null; + private Exception failedException = null; + + /** + * Create a new KingKitsReloadEvent instance. + * + * @param sender - The CommandSender that is reloading the configuration. + */ + public KingKitsReloadEvent(CommandSender sender) { + this.theSender = sender; + } + + /** + * Create a new KingKitsReloadEvent instance. + * + * @param sender - The CommandSender that is reloading the configuration. + * @param failedException - If the reload has not been successful, this will hold the error thrown instance. If successful, this will be null. + */ + public KingKitsReloadEvent(CommandSender sender, Exception failedException) { + this.theSender = sender; + this.failedException = failedException; + } + + /** + * Get the error exception. + * + * @return The Exception if failed to reload, if succeeded, this will return null. + */ + public Exception getException() { + return this.failedException; + } + + /** + * Returns the player * + */ + public CommandSender getSender() { + return this.theSender; + } + + public HandlerList getHandlers() { + return handlers; + } + + /** + * Check whether or not the reload has been successful. + * + * @return True if the reload has not been successful, false if it has been successful. + */ + public boolean hasFailed() { + return this.failedException != null; + } + + public static HandlerList getHandlerList() { + return handlers; + } + +} diff --git a/src/main/java/com/faris/kingkits/listener/event/custom/PlayerCreateKitEvent.java b/src/main/java/com/faris/kingkits/listener/event/custom/PlayerCreateKitEvent.java new file mode 100644 index 0000000..dbc8a68 --- /dev/null +++ b/src/main/java/com/faris/kingkits/listener/event/custom/PlayerCreateKitEvent.java @@ -0,0 +1,131 @@ +package com.faris.kingkits.listener.event.custom; + +import org.bukkit.*; +import org.bukkit.entity.*; +import org.bukkit.event.*; +import org.bukkit.event.player.*; +import org.bukkit.inventory.*; + +import java.util.*; + +public class PlayerCreateKitEvent extends PlayerEvent implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + + private String kitName = ""; + private Map kitContents = new HashMap(); + private List armourContents = new ArrayList(); + + private boolean isCancelled = false; + private boolean isUserKit = false; + + /** + * Create a new PlayerCreateKitEvent instance. + * + * @param player - The player. + * @param kitName - The new kit. + * @param newKitItems - The kit items. + * @param isUserKit - Whether the kit is a private user kit or not. + */ + public PlayerCreateKitEvent(Player player, String kitName, final List newKitItems, List armourContents, boolean isUserKit) { + this(player, kitName, new HashMap() { + { + for (int i = 0; i < newKitItems.size(); i++) { + this.put(i, newKitItems.get(i)); + } + } + }, armourContents, isUserKit); + + } + + /** + * Create a new PlayerCreateKitEvent instance. + * + * @param player - The player. + * @param kitName - The new kit. + * @param newKitItems - The kit items. + * @param isUserKit - Whether the kit is a private user kit or not. + */ + public PlayerCreateKitEvent(Player player, String kitName, Map newKitItems, List armourContents, boolean isUserKit) { + super(player); + this.kitName = kitName; + this.kitContents = newKitItems; + this.armourContents = armourContents; + this.isUserKit = isUserKit; + } + + /** + * Returns the kit's name * + */ + public String getKit() { + return this.kitName; + } + + /** + * Returns an unmodifiable List of armour in the new kit * + */ + public List getKitArmour() { + return Collections.unmodifiableList(this.armourContents); + } + + /** + * Returns an unmodifiable List of items in the new kit * + */ + public List getKitContents() { + return new ArrayList(this.kitContents.values()); + } + + public Map getKitContentsWithSlots() { + return Collections.unmodifiableMap(this.kitContents); + } + + public boolean isUserKit() { + return this.isUserKit; + } + + /** + * Set the item contents of the new kit * + */ + public void setArmourContents(List armourContents) { + if (armourContents != null) this.armourContents = armourContents; + } + + /** + * Set the item contents of the new kit * + */ + public void setKitContents(List kitContents) { + if (kitContents != null) { + this.kitContents = new HashMap(); + for (int i = 0; i < kitContents.size(); i++) { + ItemStack kitContent = kitContents.get(i); + this.kitContents.put(i, kitContent == null ? new ItemStack(Material.AIR) : kitContent); + } + } + } + + /** + * Set the item contents of the new kit * + */ + public void setKitContents(Map kitContents) { + if (kitContents != null) this.kitContents = kitContents; + } + + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + @Override + public boolean isCancelled() { + return this.isCancelled; + } + + @Override + public void setCancelled(boolean flag) { + this.isCancelled = flag; + } + +} diff --git a/src/main/java/com/faris/kingkits/listeners/event/custom/PlayerKilledEvent.java b/src/main/java/com/faris/kingkits/listener/event/custom/PlayerKilledEvent.java similarity index 68% rename from src/main/java/com/faris/kingkits/listeners/event/custom/PlayerKilledEvent.java rename to src/main/java/com/faris/kingkits/listener/event/custom/PlayerKilledEvent.java index 12d5f33..8f38de5 100644 --- a/src/main/java/com/faris/kingkits/listeners/event/custom/PlayerKilledEvent.java +++ b/src/main/java/com/faris/kingkits/listener/event/custom/PlayerKilledEvent.java @@ -1,10 +1,11 @@ -package com.faris.kingkits.listeners.event.custom; +package com.faris.kingkits.listener.event.custom; -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; -import org.bukkit.event.player.PlayerEvent; +import org.bukkit.entity.*; +import org.bukkit.event.*; +import org.bukkit.event.player.*; public class PlayerKilledEvent extends PlayerEvent { + private static final HandlerList handlers = new HandlerList(); private Player theDead = null; @@ -14,12 +15,16 @@ public PlayerKilledEvent(Player killer, Player dead) { this.theDead = dead; } - /** Returns the dead player **/ + /** + * Returns the dead player * + */ public Player getDead() { return this.theDead; } - /** Returns the killer **/ + /** + * Returns the killer * + */ public Player getKiller() { return this.getPlayer(); } diff --git a/src/main/java/com/faris/kingkits/listener/event/custom/PlayerKitEvent.java b/src/main/java/com/faris/kingkits/listener/event/custom/PlayerKitEvent.java new file mode 100644 index 0000000..59580c2 --- /dev/null +++ b/src/main/java/com/faris/kingkits/listener/event/custom/PlayerKitEvent.java @@ -0,0 +1,188 @@ +package com.faris.kingkits.listener.event.custom; + +import org.bukkit.entity.*; +import org.bukkit.event.*; +import org.bukkit.event.player.*; +import org.bukkit.inventory.*; +import org.bukkit.potion.*; + +import java.util.*; + +public class PlayerKitEvent extends PlayerEvent implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + + private String kitName = ""; + private String oldKit = ""; + private Map kitContents = new HashMap(); + private List armourItems = new ArrayList(); + private List potionEffects = new ArrayList(); + private List kitCommands = new ArrayList(); + + private boolean isCancelled = false; + + /** + * Create a new PlayerKitEvent instance. + * + * @param player - The player. + * @param kitName - The new kit. + */ + public PlayerKitEvent(Player player, String kitName) { + super(player); + this.kitName = kitName; + } + + /** + * Create a new PlayerKitEvent instance. + * + * @param player - The player. + * @param kitName - The new kit. + * @param oldKit - The previous kit the player was. + */ + public PlayerKitEvent(Player player, String kitName, String oldKit) { + super(player); + this.kitName = kitName; + this.oldKit = oldKit; + } + + /** + * Create a new PlayerKitEvent instance. + * + * @param player - The player. + * @param kitName - The new kit. + * @param oldKit - The previous kit the player was. + * @param newKitItems - The kit items. + * @param armourItems - The kit's armour items. + */ + public PlayerKitEvent(Player player, String kitName, String oldKit, Map newKitItems, List armourItems) { + super(player); + this.kitName = kitName; + this.oldKit = oldKit; + this.kitContents = newKitItems; + this.armourItems = armourItems; + } + + /** + * Create a new PlayerKitEvent instance. + * + * @param player - The player. + * @param kitName - The new kit. + * @param oldKit - The previous kit the player was. + * @param newKitItems - The kit items. + * @param armourItems - The kit's armour items. + */ + public PlayerKitEvent(Player player, String kitName, String oldKit, Map newKitItems, List armourItems, List potionEffects) { + super(player); + this.kitName = kitName; + this.oldKit = oldKit; + this.kitContents = newKitItems; + this.armourItems = armourItems; + this.potionEffects = potionEffects; + } + + /** + * @return An unmodifiable List of all the kit-specific-commands run. + */ + public List getCommands() { + return Collections.unmodifiableList(this.kitCommands); + } + + /** + * @return The kit's name. + */ + public String getKit() { + return this.kitName; + } + + /** + * @return An unmodifiable List of the armour items in the kit. + */ + public List getKitArmour() { + return Collections.unmodifiableList(this.armourItems); + } + + /** + * @return An unmodifiable List of items in the kit. + */ + public List getKitContents() { + return new ArrayList(this.kitContents.values()); + } + + /** + * @return An unmodifiable Map of items in the kit with their slots. + */ + public Map getKitContentsWithSlots() { + return Collections.unmodifiableMap(this.kitContents); + } + + /** + * @return An unmodifiable List of all the potion effects. + */ + public List getPotionEffects() { + return Collections.unmodifiableList(this.potionEffects); + } + + /** + * @return The player's old kit name. + */ + public String getOldKit() { + return this.oldKit; + } + + public void setCommands(List commands) { + this.kitCommands = commands != null ? commands : new ArrayList(); + } + + /** + * Set the armour contents in the kit * + */ + public void setKitArmour(List armourContents) { + this.armourItems = armourContents != null ? armourContents : new ArrayList(); + } + + /** + * Set the item contents of the kit * + */ + public void setKitContents(List kitContents) { + this.kitContents = new HashMap(); + if (kitContents != null) { + for (int i = 0; i < kitContents.size(); i++) { + ItemStack kitContent = kitContents.get(i); + if (kitContent != null) this.kitContents.put(i, kitContent); + } + } + } + + /** + * Set the item contents of the kit * + */ + public void setKitContents(Map kitContents) { + this.kitContents = kitContents != null ? kitContents : new HashMap(); + } + + /** + * Set the potion effects gained when using the kit * + */ + public void setPotionEffects(List potionEffects) { + this.potionEffects = potionEffects != null ? potionEffects : new ArrayList(); + } + + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + @Override + public boolean isCancelled() { + return this.isCancelled; + } + + @Override + public void setCancelled(boolean flag) { + this.isCancelled = flag; + } + +} diff --git a/src/main/java/com/faris/kingkits/listeners/KingCommand.java b/src/main/java/com/faris/kingkits/listeners/KingCommand.java deleted file mode 100644 index d8efce2..0000000 --- a/src/main/java/com/faris/kingkits/listeners/KingCommand.java +++ /dev/null @@ -1,103 +0,0 @@ -package com.faris.kingkits.listeners; - -import com.faris.kingkits.KingKits; -import com.faris.kingkits.helpers.Lang; -import com.faris.kingkits.helpers.Utils; -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -public abstract class KingCommand implements CommandExecutor { - private KingKits plugin = null; - - public KingCommand(KingKits pluginInstance) { - this.plugin = pluginInstance; - } - - /** - * Ignore this method * - */ - public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { - return this.onCommand(sender, cmd.getName(), args); - } - - /** - * Called when a command is typed by a player or the console * - */ - protected abstract boolean onCommand(CommandSender sender, String command, String[] args); - - /** - * Returns the plugin instance * - */ - protected KingKits getPlugin() { - return this.plugin; - } - - /** - * Returns whether or not a String contains illegal characters. (i.e. Non-alphanumerical) - * - * @param strMessage - The String. - * @return Whether or not a String contains illegal characters. - */ - protected boolean containsIllegalCharacters(String strMessage) { - return !strMessage.matches("[a-zA-Z0-9_ ]*"); - } - - /** - * Returns if a sender is not a player * - */ - protected boolean isConsole(CommandSender sender) { - if (sender != null) { - return !(sender instanceof Player); - } else { - return false; - } - } - - /** - * Returns if a string is a boolean * - */ - protected boolean isBoolean(String booleanString) { - return booleanString.equalsIgnoreCase("true") || booleanString.equalsIgnoreCase("false"); - } - - /** - * Returns if a string is a double * - */ - protected boolean isDouble(String doubleString) { - try { - double d = Double.parseDouble(doubleString); - return Math.floor(d) != d; - } catch (Exception ex) { - return false; - } - } - - /** - * Returns if a string is numeric * - */ - protected boolean isInteger(String numericString) { - try { - double d = Double.parseDouble(numericString); - return Math.floor(d) == d; - } catch (Exception ex) { - return false; - } - } - - /** - * Returns a string with the real colours * - */ - protected String r(String message) { - return Utils.replaceChatColour(message); - } - - /** - * Send the "no access" message to a player/console * - */ - protected void sendNoAccess(CommandSender sender) { - Lang.sendMessage(sender, Lang.COMMAND_GEN_NO_PERMISSION); - } - -} diff --git a/src/main/java/com/faris/kingkits/listeners/PlayerCommand.java b/src/main/java/com/faris/kingkits/listeners/PlayerCommand.java deleted file mode 100644 index f934d07..0000000 --- a/src/main/java/com/faris/kingkits/listeners/PlayerCommand.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.faris.kingkits.listeners; - -import com.faris.kingkits.KingKits; -import com.faris.kingkits.helpers.Lang; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -public abstract class PlayerCommand extends KingCommand { - - public PlayerCommand(KingKits pluginInstance) { - super(pluginInstance); - } - - @Override - protected boolean onCommand(CommandSender sender, String command, String[] args) { - if (this.isConsole(sender)) { - Lang.sendMessage(sender, Lang.COMMAND_GEN_IN_GAME); - return true; - } - return this.onCommand((Player) sender, command, args); - } - - protected abstract boolean onCommand(Player player, String command, String[] args); - -} diff --git a/src/main/java/com/faris/kingkits/listeners/commands/CreateKitCommand.java b/src/main/java/com/faris/kingkits/listeners/commands/CreateKitCommand.java deleted file mode 100644 index d07d8f2..0000000 --- a/src/main/java/com/faris/kingkits/listeners/commands/CreateKitCommand.java +++ /dev/null @@ -1,165 +0,0 @@ -package com.faris.kingkits.listeners.commands; - -import com.faris.kingkits.KingKits; -import com.faris.kingkits.Kit; -import com.faris.kingkits.helpers.Lang; -import com.faris.kingkits.helpers.Utils; -import com.faris.kingkits.listeners.PlayerCommand; -import com.faris.kingkits.listeners.event.custom.PlayerCreateKitEvent; -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import org.bukkit.permissions.Permission; -import org.bukkit.potion.PotionEffect; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class CreateKitCommand extends PlayerCommand { - - public CreateKitCommand(KingKits instance) { - super(instance); - } - - @SuppressWarnings("deprecation") - @Override - protected boolean onCommand(Player p, String command, String[] args) { - if (command.equalsIgnoreCase("createkit")) { - if (p.hasPermission(this.getPlugin().permissions.kitCreateCommand)) { - if (this.getPlugin().cmdValues.createKits) { - if (this.getPlugin().configValues.pvpWorlds.contains("All") || this.getPlugin().configValues.pvpWorlds.contains(p.getWorld().getName())) { - if (args.length == 0) { - Lang.sendMessage(p, Lang.COMMAND_GEN_USAGE, command.toLowerCase() + " [| ]"); - Lang.sendMessage(p, Lang.COMMAND_CREATE_KIT_DESCRIPTION); - } else if (args.length > 0 && args.length < 3) { - String kitName = args[0]; - - boolean containsKit = this.getPlugin().getKitsConfig().contains(kitName); - if (!containsKit) { - List currentKits = this.getPlugin().getKitList(); - List currentKitsLC = Utils.toLowerCaseList(currentKits); - if (currentKitsLC.contains(kitName.toLowerCase())) - kitName = currentKits.get(currentKitsLC.indexOf(kitName.toLowerCase())); - containsKit = this.getPlugin().getKitsConfig().contains(kitName); - } - - if (!this.containsIllegalCharacters(kitName)) { - if (args.length == 2) { - if (args[1].contains(":")) { - String[] guiSplit = args[1].split(":"); - if (guiSplit.length == 2) { - if (!this.isInteger(guiSplit[0]) || !this.isInteger(guiSplit[1])) { - Lang.sendMessage(p, Lang.COMMAND_GEN_USAGE, command.toLowerCase() + " [| ]"); - return true; - } - } else { - if (!this.isInteger(args[1])) { - Lang.sendMessage(p, Lang.COMMAND_GEN_USAGE, command.toLowerCase() + " [| ]"); - return true; - } - } - } else { - if (!this.isInteger(args[1])) { - Lang.sendMessage(p, Lang.COMMAND_GEN_USAGE, command.toLowerCase() + " [| ]"); - return true; - } - } - } - - Map itemsInInv = new HashMap(); - List armourInInv = new ArrayList(); - ItemStack[] pContents = p.getInventory().getContents(); - if (pContents == null) pContents = new ItemStack[p.getInventory().getSize()]; - for (int i = 0; i < p.getInventory().getSize(); i++) { - if (pContents.length > i && pContents[i] != null) itemsInInv.put(i, pContents[i]); - else itemsInInv.put(i, new ItemStack(Material.AIR)); - } - for (ItemStack armour : p.getInventory().getArmorContents()) - if (armour != null && armour.getType() != Material.AIR) armourInInv.add(armour); - PlayerCreateKitEvent createKitEvent = new PlayerCreateKitEvent(p, kitName, itemsInInv, armourInInv, false); - p.getServer().getPluginManager().callEvent(createKitEvent); - - if (!createKitEvent.isCancelled()) { - itemsInInv = createKitEvent.getKitContentsWithSlots(); - armourInInv = createKitEvent.getKitArmour(); - if (itemsInInv.size() > 0 || armourInInv.size() > 0) { - if (containsKit) { - this.getPlugin().getKitsConfig().set(kitName, null); - this.getPlugin().saveKitsConfig(); - if (this.getPlugin().kitList.containsKey(kitName)) - this.getPlugin().kitList.remove(kitName); - } - - final Kit kit = new Kit(kitName, itemsInInv).setRealName(kitName).setArmour(armourInInv); - if (args.length == 2) { - ItemStack guiItem = null; - try { - guiItem = new ItemStack(Integer.parseInt(args[1])); - } catch (Exception ex) { - } - try { - if (args[1].contains(":")) { - String[] guiSplit = args[1].split(":"); - guiItem = new ItemStack(Integer.parseInt(guiSplit[0])); - guiItem.setDurability(Short.parseShort(guiSplit[1])); - } - } catch (Exception ex) { - } - if (guiItem != null) { - if (guiItem.getType() != Material.AIR) { - kit.setGuiItem(guiItem); - } - } - } - - List kitPotionEffects = new ArrayList(); - for (PotionEffect potionEffect : p.getActivePotionEffects()) { - if (potionEffect != null) kitPotionEffects.add(potionEffect); - } - if (!kitPotionEffects.isEmpty()) kit.setPotionEffects(kitPotionEffects); - - kit.setMaxHealth((int) p.getMaxHealth()); - - this.getPlugin().getKitsConfig().set(kitName, kit.serialize()); - this.getPlugin().kitList.put(kitName, kit); - this.getPlugin().saveKitsConfig(); - - try { - p.getServer().getPluginManager().addPermission(new Permission("kingkits.kits." + kitName.toLowerCase())); - } catch (Exception ex) { - } - Lang.sendMessage(p, containsKit ? Lang.COMMAND_CREATE_OVERWRITTEN : Lang.COMMAND_CREATE_CREATED, kitName); - - if (this.getPlugin().configValues.removeItemsOnCreateKit) { - p.getInventory().clear(); - p.getInventory().setArmorContents(null); - } - } else { - Lang.sendMessage(p, Lang.COMMAND_CREATE_EMPTY_INV); - } - } else { - Lang.sendMessage(p, Lang.COMMAND_CREATE_DENIED); - } - } else { - Lang.sendMessage(p, Lang.COMMAND_CREATE_ILLEGAL_CHARACTERS); - } - } else { - Lang.sendMessage(p, Lang.COMMAND_GEN_USAGE, command.toLowerCase() + " [| ]"); - } - } else { - Lang.sendMessage(p, Lang.COMMAND_GEN_WORLD); - } - } else { - Lang.sendMessage(p, Lang.COMMAND_GEN_DISABLED); - } - } else { - this.sendNoAccess(p); - } - return true; - } - return false; - } - -} diff --git a/src/main/java/com/faris/kingkits/listeners/commands/CreateUserKitCommand.java b/src/main/java/com/faris/kingkits/listeners/commands/CreateUserKitCommand.java deleted file mode 100644 index eb4df5c..0000000 --- a/src/main/java/com/faris/kingkits/listeners/commands/CreateUserKitCommand.java +++ /dev/null @@ -1,191 +0,0 @@ -package com.faris.kingkits.listeners.commands; - -import com.faris.kingkits.KingKits; -import com.faris.kingkits.Kit; -import com.faris.kingkits.helpers.Lang; -import com.faris.kingkits.helpers.Utils; -import com.faris.kingkits.listeners.PlayerCommand; -import com.faris.kingkits.listeners.event.custom.PlayerCreateKitEvent; -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import org.bukkit.potion.PotionEffect; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class CreateUserKitCommand extends PlayerCommand { - - public CreateUserKitCommand(KingKits instance) { - super(instance); - } - - @SuppressWarnings("deprecation") - @Override - protected boolean onCommand(Player p, String command, String[] args) { - if (command.equalsIgnoreCase("createukit")) { - if (p.hasPermission(this.getPlugin().permissions.kitUCreateCommand)) { - if (this.getPlugin().cmdValues.createUKits) { - if (this.getPlugin().configValues.pvpWorlds.contains("All") || this.getPlugin().configValues.pvpWorlds.contains(p.getWorld().getName())) { - if (args.length == 0) { - Lang.sendMessage(p, Lang.COMMAND_GEN_USAGE, command.toLowerCase() + " [| ]"); - Lang.sendMessage(p, Lang.COMMAND_CREATE_UKIT_DESCRIPTION); - } else if (args.length > 0 && args.length < 3) { - String kitName = args[0]; - - boolean containsRealKit = this.getPlugin().getKitsConfig().contains(kitName); - if (!containsRealKit) { - List currentKits = this.getPlugin().getKitList(); - List currentKitsLC = Utils.toLowerCaseList(currentKits); - containsRealKit = currentKitsLC.contains(kitName.toLowerCase()); - } - - if (!containsRealKit) { - List currentKits = this.getPlugin().getKitList(p.getName()); - boolean containsKit = this.getPlugin().getUserKitsConfig().contains(p.getName() + "." + kitName); - if (!containsKit) { - List currentKitsLC = Utils.toLowerCaseList(currentKits); - if (currentKitsLC.contains(kitName.toLowerCase())) - kitName = currentKits.get(currentKitsLC.indexOf(kitName.toLowerCase())); - containsKit = currentKits.contains(kitName); - } - - if (!this.containsIllegalCharacters(kitName)) { - List playerKits = this.getPlugin().userKitList.get(p.getName()); - if (playerKits == null) playerKits = new ArrayList(); - int maxSizePerm = 0; - for (int i = 1; i <= 54; i++) { - if (maxSizePerm < i && p.hasPermission("kingkits.kit.limit." + i)) - maxSizePerm = i; - } - if (maxSizePerm > playerKits.size()) { - if (args.length == 2) { - if (args[1].contains(":")) { - String[] guiSplit = args[1].split(":"); - if (guiSplit.length == 2) { - if (!this.isInteger(guiSplit[0]) || !this.isInteger(guiSplit[1])) { - Lang.sendMessage(p, Lang.COMMAND_GEN_USAGE, command.toLowerCase() + " [| ]"); - return true; - } - } else { - if (!this.isInteger(args[1])) { - Lang.sendMessage(p, Lang.COMMAND_GEN_USAGE, command.toLowerCase() + " [| ]"); - return true; - } - } - } else { - if (!this.isInteger(args[1])) { - Lang.sendMessage(p, Lang.COMMAND_GEN_USAGE, command.toLowerCase() + " [| ]"); - return true; - } - } - } - - Map itemsInInv = new HashMap(); - List armourInInv = new ArrayList(); - ItemStack[] pContents = p.getInventory().getContents(); - if (pContents == null) pContents = new ItemStack[p.getInventory().getSize()]; - for (int i = 0; i < p.getInventory().getSize(); i++) { - if (pContents.length > i && pContents[i] != null) - itemsInInv.put(i, pContents[i]); - else itemsInInv.put(i, new ItemStack(Material.AIR)); - } - for (ItemStack armour : p.getInventory().getArmorContents()) - if (armour != null && armour.getType() != Material.AIR) - armourInInv.add(armour); - PlayerCreateKitEvent createKitEvent = new PlayerCreateKitEvent(p, kitName, itemsInInv, armourInInv, true); - p.getServer().getPluginManager().callEvent(createKitEvent); - - if (!createKitEvent.isCancelled()) { - itemsInInv = createKitEvent.getKitContentsWithSlots(); - armourInInv = createKitEvent.getKitArmour(); - if (itemsInInv.size() > 0 || armourInInv.size() > 0) { - if (containsKit) { - this.getPlugin().getUserKitsConfig().set(p.getName() + "." + kitName, null); - this.getPlugin().saveUserKitsConfig(); - if (playerKits != null) { - List newKits = new ArrayList(); - for (Kit playerKit : playerKits) { - if (playerKit != null && !playerKit.getRealName().toLowerCase().equals(kitName.toLowerCase())) - newKits.add(playerKit); - } - this.getPlugin().userKitList.put(p.getName(), newKits); - } - } - - final Kit kit = new Kit(kitName, itemsInInv).setRealName(kitName).setArmour(armourInInv).setUserKit(true); - if (args.length == 2) { - ItemStack guiItem = null; - try { - guiItem = new ItemStack(Integer.parseInt(args[1])); - } catch (Exception ex) { - } - try { - if (args[1].contains(":")) { - String[] guiSplit = args[1].split(":"); - guiItem = new ItemStack(Integer.parseInt(guiSplit[0])); - guiItem.setDurability(Short.parseShort(guiSplit[1])); - } - } catch (Exception ex) { - } - if (guiItem != null) { - if (guiItem.getType() != Material.AIR) { - kit.setGuiItem(guiItem); - } - } - } - - List kitPotionEffects = new ArrayList(); - for (PotionEffect potionEffect : p.getActivePotionEffects()) { - if (potionEffect != null) kitPotionEffects.add(potionEffect); - } - if (!kitPotionEffects.isEmpty()) kit.setPotionEffects(kitPotionEffects); - kit.setMaxHealth((int) p.getMaxHealth()); - - this.getPlugin().getUserKitsConfig().set(p.getName() + "." + kitName, kit.serialize()); - if (playerKits == null) playerKits = new ArrayList(); - playerKits.add(kit); - this.getPlugin().userKitList.put(p.getName(), playerKits); - this.getPlugin().saveUserKitsConfig(); - - Lang.sendMessage(p, containsKit ? Lang.COMMAND_CREATE_OVERWRITTEN : Lang.COMMAND_CREATE_CREATED, kitName); - - if (this.getPlugin().configValues.removeItemsOnCreateKit) { - p.getInventory().clear(); - p.getInventory().setArmorContents(null); - } - } else { - Lang.sendMessage(p, Lang.COMMAND_CREATE_EMPTY_INV); - } - } else { - Lang.sendMessage(p, Lang.COMMAND_CREATE_DENIED); - } - } else { - Lang.sendMessage(p, Lang.COMMAND_CREATE_UKIT_MAX_PERSONAL_KITS); - } - } else { - Lang.sendMessage(p, Lang.COMMAND_CREATE_ILLEGAL_CHARACTERS); - } - } else { - Lang.sendMessage(p, Lang.COMMAND_CREATE_UKIT_EXISTS); - } - } else { - Lang.sendMessage(p, Lang.COMMAND_GEN_USAGE, command.toLowerCase() + " [| ]"); - } - } else { - Lang.sendMessage(p, Lang.COMMAND_GEN_WORLD); - } - } else { - Lang.sendMessage(p, Lang.COMMAND_GEN_DISABLED); - } - } else { - this.sendNoAccess(p); - } - return true; - } - return false; - } - -} diff --git a/src/main/java/com/faris/kingkits/listeners/commands/DeleteKitCommand.java b/src/main/java/com/faris/kingkits/listeners/commands/DeleteKitCommand.java deleted file mode 100644 index 0580908..0000000 --- a/src/main/java/com/faris/kingkits/listeners/commands/DeleteKitCommand.java +++ /dev/null @@ -1,86 +0,0 @@ -package com.faris.kingkits.listeners.commands; - -import com.faris.kingkits.KingKits; -import com.faris.kingkits.helpers.Lang; -import com.faris.kingkits.helpers.Utils; -import com.faris.kingkits.hooks.PvPKits; -import com.faris.kingkits.listeners.PlayerCommand; -import org.bukkit.entity.Player; -import org.bukkit.potion.PotionEffect; - -import java.util.List; - -public class DeleteKitCommand extends PlayerCommand { - - public DeleteKitCommand(KingKits instance) { - super(instance); - } - - @Override - protected boolean onCommand(Player player, String command, String[] args) { - if (command.equalsIgnoreCase("deletekit")) { - if (player.hasPermission(this.getPlugin().permissions.kitDeleteCommand)) { - if (this.getPlugin().cmdValues.deleteKits) { - if (this.getPlugin().configValues.pvpWorlds.contains("All") || this.getPlugin().configValues.pvpWorlds.contains(player.getWorld().getName())) { - if (args.length == 0) { - Lang.sendMessage(player, Lang.COMMAND_GEN_USAGE, command.toLowerCase() + " "); - Lang.sendMessage(player, Lang.COMMAND_DELETE_KIT_DESCRIPTION); - } else if (args.length == 1) { - String kitName = args[0]; - List listKits = this.getPlugin().getKitList(); - List listKitsLC = Utils.toLowerCaseList(listKits); - if (listKitsLC.contains(kitName.toLowerCase())) { - try { - kitName = listKits.get(listKitsLC.indexOf(kitName.toLowerCase())); - this.getPlugin().getKitsConfig().set(kitName, null); - this.getPlugin().saveKitsConfig(); - if (this.getPlugin().kitList.containsKey(kitName)) - this.getPlugin().kitList.remove(kitName); - - Lang.sendMessage(player, Lang.COMMAND_DELETE_DELETED, kitName); - for (Player target : Utils.getOnlinePlayers()) { - if (target != null) { - if (this.getPlugin().usingKits.get(target.getName()) != null) { - String targetKit = this.getPlugin().usingKits.get(target.getName()); - if (targetKit.equalsIgnoreCase(kitName)) { - PvPKits.removePlayer(target.getName()); - if (!player.getName().equals(target.getName())) { - target.getInventory().clear(); - target.getInventory().setArmorContents(null); - for (PotionEffect potionEffect : target.getActivePotionEffects()) - target.removePotionEffect(potionEffect.getType()); - target.setMaxHealth(20D); - Lang.sendMessage(target, Lang.COMMAND_DELETE_PLAYER, player.getName()); - } - } - } - } - } - if (this.getPlugin().usingKits.containsKey(player.getName()) && this.getPlugin().usingKits.get(player.getName()).equalsIgnoreCase(kitName)) { - this.getPlugin().usingKits.remove(player.getName()); - this.getPlugin().playerKits.remove(player.getName()); - } - } catch (Exception ex) { - ex.printStackTrace(); - Lang.sendMessage(player, Lang.COMMAND_DELETE_ERROR, kitName); - } - } else { - Lang.sendMessage(player, Lang.COMMAND_DELETE_KIT_NONEXISTENT); - } - } else { - Lang.sendMessage(player, Lang.COMMAND_GEN_USAGE, command.toLowerCase() + " "); - } - } else { - Lang.sendMessage(player, Lang.COMMAND_GEN_WORLD); - } - } else { - Lang.sendMessage(player, Lang.COMMAND_GEN_DISABLED); - } - } else { - this.sendNoAccess(player); - } - return true; - } - return false; - } -} diff --git a/src/main/java/com/faris/kingkits/listeners/commands/DeleteUserKitCommand.java b/src/main/java/com/faris/kingkits/listeners/commands/DeleteUserKitCommand.java deleted file mode 100644 index 2d04ff3..0000000 --- a/src/main/java/com/faris/kingkits/listeners/commands/DeleteUserKitCommand.java +++ /dev/null @@ -1,86 +0,0 @@ -package com.faris.kingkits.listeners.commands; - -import com.faris.kingkits.KingKits; -import com.faris.kingkits.Kit; -import com.faris.kingkits.helpers.Lang; -import com.faris.kingkits.helpers.Utils; -import com.faris.kingkits.listeners.PlayerCommand; -import org.bukkit.entity.Player; - -import java.util.ArrayList; -import java.util.List; - -public class DeleteUserKitCommand extends PlayerCommand { - - public DeleteUserKitCommand(KingKits instance) { - super(instance); - } - - @Override - protected boolean onCommand(Player player, String command, String[] args) { - if (command.equalsIgnoreCase("deleteukit")) { - if (player.hasPermission(this.getPlugin().permissions.kitUDeleteCommand)) { - if (this.getPlugin().cmdValues.deleteKits) { - if (this.getPlugin().configValues.pvpWorlds.contains("All") || this.getPlugin().configValues.pvpWorlds.contains(player.getWorld().getName())) { - if (args.length == 0) { - Lang.sendMessage(player, Lang.COMMAND_GEN_USAGE, command.toLowerCase() + " "); - Lang.sendMessage(player, Lang.COMMAND_DELETE_UKIT_DESCRIPTION); - } else if (args.length == 1) { - String kitName = args[0]; - List listKits = this.getPlugin().getKitList(player.getName()); - List listKitsLC = Utils.toLowerCaseList(listKits); - if (listKitsLC.contains(kitName.toLowerCase())) { - try { - kitName = listKits.get(listKitsLC.indexOf(kitName.toLowerCase())); - this.getPlugin().getUserKitsConfig().set(player.getName() + "." + kitName, null); - this.getPlugin().saveUserKitsConfig(); - if (this.getPlugin().userKitList.containsKey(player.getName())) { - List kitList = this.getPlugin().userKitList.get(player.getName()); - if (kitList == null) kitList = new ArrayList(); - int deleteIndex = -1; - for (int i = 0; i < kitList.size(); i++) { - Kit targetKit = kitList.get(i); - if (targetKit != null && targetKit.getRealName().toLowerCase().equals(kitName.toLowerCase())) { - deleteIndex = i; - break; - } - } - if (deleteIndex != -1) kitList.remove(deleteIndex); - if (kitList.isEmpty()) { - this.getPlugin().userKitList.remove(player.getName()); - this.getPlugin().getUserKitsConfig().set(player.getName(), null); - this.getPlugin().saveUserKitsConfig(); - } else { - this.getPlugin().userKitList.put(player.getName(), kitList); - } - } - - Lang.sendMessage(player, Lang.COMMAND_DELETE_DELETED, kitName); - if (this.getPlugin().usingKits.containsKey(player.getName()) && this.getPlugin().usingKits.get(player.getName()).equalsIgnoreCase(kitName)) { - this.getPlugin().usingKits.remove(player.getName()); - this.getPlugin().playerKits.remove(player.getName()); - } - } catch (Exception ex) { - ex.printStackTrace(); - Lang.sendMessage(player, Lang.COMMAND_DELETE_ERROR, kitName); - } - } else { - Lang.sendMessage(player, Lang.COMMAND_DELETE_UKIT_NONEXISTENT); - } - } else { - Lang.sendMessage(player, Lang.COMMAND_GEN_USAGE, command.toLowerCase() + " "); - } - } else { - Lang.sendMessage(player, Lang.COMMAND_GEN_WORLD); - } - } else { - Lang.sendMessage(player, Lang.COMMAND_GEN_DISABLED); - } - } else { - this.sendNoAccess(player); - } - return true; - } - return false; - } -} diff --git a/src/main/java/com/faris/kingkits/listeners/commands/KingKitsCommand.java b/src/main/java/com/faris/kingkits/listeners/commands/KingKitsCommand.java deleted file mode 100644 index e899dbd..0000000 --- a/src/main/java/com/faris/kingkits/listeners/commands/KingKitsCommand.java +++ /dev/null @@ -1,264 +0,0 @@ -package com.faris.kingkits.listeners.commands; - -import com.faris.kingkits.KingKits; -import com.faris.kingkits.Kit; -import com.faris.kingkits.helpers.ConfigCommand; -import com.faris.kingkits.helpers.Lang; -import com.faris.kingkits.helpers.Utils; -import com.faris.kingkits.hooks.PvPKits; -import com.faris.kingkits.listeners.KingCommand; -import com.faris.kingkits.listeners.event.custom.KingKitsPreReloadEvent; -import com.faris.kingkits.listeners.event.custom.KingKitsReloadEvent; -import org.apache.commons.lang.WordUtils; -import org.bukkit.ChatColor; -import org.bukkit.command.CommandSender; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.entity.Player; -import org.bukkit.scoreboard.Scoreboard; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Map; - -public class KingKitsCommand extends KingCommand { - - private List configCommands = new ArrayList(); - - public KingKitsCommand(KingKits pluginInstance) { - super(pluginInstance); - - for (Map.Entry entrySet : this.getPlugin().getConfig().getValues(false).entrySet()) { - if (!(entrySet.getValue() instanceof Collection) && !(entrySet.getValue() instanceof ConfigurationSection) && !(entrySet.getValue() instanceof Map)) { - this.configCommands.add(new ConfigCommand(WordUtils.capitalizeFully(entrySet.getKey().toLowerCase()).replace(" ", ""), entrySet.getKey(), "Config")); - } - } - for (Map.Entry entrySet : this.getPlugin().getEconomyConfig().getValues(false).entrySet()) { - if (!(entrySet.getValue() instanceof Collection) && !(entrySet.getValue() instanceof ConfigurationSection) && !(entrySet.getValue() instanceof Map)) { - this.configCommands.add(new ConfigCommand(WordUtils.capitalizeFully(entrySet.getKey().toLowerCase()).replace(" ", ""), entrySet.getKey(), "Economy")); - } - } - } - - @Override - protected boolean onCommand(CommandSender sender, String command, String[] args) { - if (command.equalsIgnoreCase("kingkits") || command.equalsIgnoreCase("kk")) { - try { - if (args.length == 0) { - sender.sendMessage(ChatColor.GOLD + "KingKits v" + this.getPlugin().getDescription().getVersion()); - } else if (args.length > 0) { - String strCommand = args[0]; - if (strCommand.equalsIgnoreCase("reload")) { - if (sender.isOp() || sender.hasPermission(this.getPlugin().permissions.cmdReloadConfig)) { - if (args.length == 1) { - KingKitsPreReloadEvent kkPreReloadEvent = new KingKitsPreReloadEvent(sender); - sender.getServer().getPluginManager().callEvent(kkPreReloadEvent); - if (!kkPreReloadEvent.isCancelled()) { - try { - this.getPlugin().reloadAllConfigs(); - this.getPlugin().loadConfiguration(); - Lang.init(this.getPlugin()); - try { - if (sender.getServer().getPluginManager().isPluginEnabled("KingKitsSpecial") && sender.getServer().getPluginCommand("kkspecial") != null) { - sender.getServer().dispatchCommand(sender.getServer().getConsoleSender(), "kkspecial reload"); - } - } catch (Exception ex) { - } - - sender.sendMessage(ChatColor.GOLD + "You reloaded KingKits configurations."); - KingKitsReloadEvent kkReloadEvent = new KingKitsReloadEvent(sender); - sender.getServer().getPluginManager().callEvent(kkReloadEvent); - } catch (Exception ex) { - sender.sendMessage(ChatColor.RED + "Failed to reload KingKits configurations."); - - KingKitsReloadEvent kkReloadEvent = new KingKitsReloadEvent(sender, ex); - sender.getServer().getPluginManager().callEvent(kkReloadEvent); - } - } else { - sender.sendMessage(ChatColor.RED + "A plugin has not allowed you to reload the configuration."); - } - } else { - Lang.sendMessage(sender, Lang.COMMAND_GEN_USAGE, command.toLowerCase() + " " + strCommand.toLowerCase()); - } - } else { - this.sendNoAccess(sender); - } - } else if (strCommand.equalsIgnoreCase("config")) { - if (sender.hasPermission(this.getPlugin().permissions.cmdConfigManagement)) { - if (args.length == 2) { - String configProperty = args[1]; - if (configProperty.equalsIgnoreCase("list")) { - sender.sendMessage(ChatColor.GREEN + "KingKits config command property list (" + this.configCommands.size() + "): "); - StringBuilder configListBuilder = new StringBuilder(); - for (int i = 0; i < this.configCommands.size(); i++) { - if (i == this.configCommands.size() - 1) - configListBuilder.append(this.configCommands.get(i).getCommand()); - else configListBuilder.append(this.configCommands.get(i).getCommand() + ", "); - } - sender.sendMessage(ChatColor.GOLD + configListBuilder.toString().trim()); - } else { - Lang.sendMessage(sender, Lang.COMMAND_GEN_USAGE, command.toLowerCase() + " " + strCommand.toLowerCase() + " "); - } - } else if (args.length == 3) { - String configKey = args[1]; - String configValue = args[2]; - if (this.containsCommand(this.configCommands, configKey)) { - sender.sendMessage(this.updateConfig(configKey, configValue)); - } else { - sender.sendMessage(ChatColor.RED + "Invalid config property: " + ChatColor.DARK_RED + configKey); - sender.sendMessage(ChatColor.RED + "To list all the config properties you can edit, type: " + ChatColor.DARK_RED + "/" + command.toLowerCase() + " " + strCommand.toLowerCase() + " list"); - } - } else { - Lang.sendMessage(sender, Lang.COMMAND_GEN_USAGE, command.toLowerCase() + " " + strCommand.toLowerCase() + " "); - } - } else { - this.sendNoAccess(sender); - } - } else if (strCommand.equalsIgnoreCase("removescoreboards")) { - if (sender.isOp()) { - if (args.length == 1) { - Scoreboard newScoreboard = sender.getServer().getScoreboardManager().getNewScoreboard(); - for (Player onlinePlayer : sender.getServer().getOnlinePlayers()) { - Scoreboard pScoreboard = onlinePlayer.getScoreboard(); - if (pScoreboard != null && pScoreboard.getObjective("KingKits") != null) { - onlinePlayer.setScoreboard(newScoreboard); - } - } - sender.getServer().dispatchCommand(sender.getServer().getConsoleSender(), "scoreboard objectives remove KingKits"); - } else { - Lang.sendMessage(sender, Lang.COMMAND_GEN_USAGE, command.toLowerCase() + " " + strCommand.toLowerCase()); - } - } else { - this.sendNoAccess(sender); - } - } else if (strCommand.equalsIgnoreCase("killstreak")) { - if (!this.isConsole(sender)) { - Player player = (Player) sender; - if (player.hasPermission(this.getPlugin().permissions.killstreak)) { - if (args.length == 1) { - long killstreak = PvPKits.getKillstreak(player); - sender.sendMessage(ChatColor.GOLD + "Killstreak: " + ChatColor.DARK_RED + killstreak); - } else { - Lang.sendMessage(sender, Lang.COMMAND_GEN_USAGE, command.toLowerCase() + " " + strCommand.toLowerCase()); - } - } else { - this.sendNoAccess(sender); - } - } else { - Lang.sendMessage(sender, Lang.COMMAND_GEN_IN_GAME); - } - } else if (strCommand.equalsIgnoreCase("setcooldown")) { - if (sender.hasPermission(this.getPlugin().permissions.cmdSetCooldown)) { - if (args.length == 3) { - String strTargetKit = args[1]; - List kitList = this.getPlugin().getKitList(); - List lcKitList = Utils.toLowerCaseList(kitList); - if (lcKitList.contains(strTargetKit.toLowerCase())) { - if (!kitList.contains(strTargetKit)) - strTargetKit = kitList.get(lcKitList.indexOf(strTargetKit.toLowerCase())); - Kit targetKit = this.getPlugin().kitList.get(strTargetKit); - if (targetKit != null) { - String strCooldown = args[2]; - if (Utils.isInteger(strCooldown)) { - int cooldown = Integer.parseInt(strCooldown); - if (cooldown >= 0) { - targetKit.setCooldown(cooldown); - this.getPlugin().kitList.put(strTargetKit, targetKit); - this.getPlugin().getKitsConfig().set(strTargetKit + ".Cooldown", cooldown); - this.getPlugin().saveKitsConfig(); - - sender.sendMessage(ChatColor.GOLD + "Changed the cooldown for '" + targetKit.getRealName() + "' to " + cooldown + " second(s)."); - } else { - sender.sendMessage(ChatColor.RED + "Please enter a valid integer between 0 and " + Integer.MAX_VALUE + " (inclusive) for the kit cooldown."); - } - } else { - sender.sendMessage(ChatColor.RED + "Please enter a valid integer between 0 and " + Integer.MAX_VALUE + " (inclusive) for the kit cooldown."); - } - } else { - Lang.sendMessage(sender, Lang.KIT_NONEXISTENT); - } - } else { - Lang.sendMessage(sender, Lang.KIT_NONEXISTENT); - } - } else { - Lang.sendMessage(sender, Lang.COMMAND_GEN_USAGE, command.toLowerCase() + " " + strCommand.toLowerCase() + " "); - } - } else { - this.sendNoAccess(sender); - } - } else { - sender.sendMessage(ChatColor.RED + "Unknown KingKits command: " + ChatColor.DARK_RED + strCommand); - } - } - } catch (Exception ex) { - if (Math.random() < 0.25) ex.printStackTrace(); - } - return true; - } - return false; - } - - /** - * Returns if a list of config commands contains a command (as a string) * - */ - private boolean containsCommand(List configCmds, String command) { - for (ConfigCommand cmd : configCmds) { - if (cmd.getCommand().equalsIgnoreCase(command)) return true; - } - return false; - } - - /** - * Updates the config with the property key and value * - */ - public String updateConfig(String propertyKey, Object propertyValue) { - try { - String key = ""; - String config = ""; - if (this.containsCommand(this.configCommands, propertyKey)) { - for (int i = 0; i < this.configCommands.size(); i++) { - if (this.configCommands.get(i).getCommand().equalsIgnoreCase(propertyKey)) { - ConfigCommand configCommand = this.configCommands.get(i); - key = configCommand.getDescription(); - config = configCommand.getConfig(); - } - } - if (key == "") return ChatColor.RED + "Failed to find the key '" + propertyKey + "' in the config."; - } else return ChatColor.RED + "Failed to find the key '" + propertyKey + "' in the config."; - if (config.equalsIgnoreCase("Config")) { - String value = String.valueOf(propertyValue); - if (this.isBoolean(value)) { - this.getPlugin().getConfig().set(key, Boolean.parseBoolean(value)); - } else if (this.isDouble(value)) { - this.getPlugin().getConfig().set(key, Double.parseDouble(value)); - } else if (this.isInteger(value)) { - this.getPlugin().getConfig().set(key, Integer.parseInt(value)); - } else { - this.getPlugin().getConfig().set(key, propertyValue); - } - this.getPlugin().saveConfig(); - } else if (config.equalsIgnoreCase("Economy")) { - String value = String.valueOf(propertyValue); - if (this.isBoolean(value)) { - this.getPlugin().getEconomyConfig().set(key, Boolean.parseBoolean(value)); - } else if (this.isDouble(value)) { - this.getPlugin().getEconomyConfig().set(key, Double.parseDouble(value)); - } else if (this.isInteger(value)) { - this.getPlugin().getEconomyConfig().set(key, Integer.parseInt(value)); - } else { - this.getPlugin().getEconomyConfig().set(key, propertyValue); - } - this.getPlugin().saveEconomyConfig(); - } - if (!this.getPlugin().checkConfig()) return ChatColor.RED + "Could not update " + propertyKey + "."; - this.getPlugin().reloadAllConfigs(); - this.getPlugin().loadConfiguration(); - - return ChatColor.GOLD + "Successfully updated " + propertyKey + " in the config."; - } catch (Exception ex) { - if (Math.random() < 0.25) ex.printStackTrace(); - return ChatColor.RED + "Error: Couldn't update the config with the property."; - } - } - -} diff --git a/src/main/java/com/faris/kingkits/listeners/commands/KitCommand.java b/src/main/java/com/faris/kingkits/listeners/commands/KitCommand.java deleted file mode 100644 index a18e80b..0000000 --- a/src/main/java/com/faris/kingkits/listeners/commands/KitCommand.java +++ /dev/null @@ -1,139 +0,0 @@ -package com.faris.kingkits.listeners.commands; - -import com.faris.kingkits.KingKits; -import com.faris.kingkits.Kit; -import com.faris.kingkits.guis.GuiKingKits; -import com.faris.kingkits.guis.GuiPreviewKit; -import com.faris.kingkits.helpers.Lang; -import com.faris.kingkits.helpers.Utils; -import com.faris.kingkits.hooks.PvPKits; -import com.faris.kingkits.listeners.KingCommand; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -public class KitCommand extends KingCommand { - - public KitCommand(KingKits instance) { - super(instance); - } - - @SuppressWarnings("deprecation") - @Override - protected boolean onCommand(CommandSender sender, String command, String[] args) { - if (command.equalsIgnoreCase("pvpkit")) { - if (sender.hasPermission(this.getPlugin().permissions.kitUseCommand)) { - if (this.getPlugin().cmdValues.pvpKits) { - if (this.isConsole(sender) || this.getPlugin().configValues.pvpWorlds.contains("All") || this.getPlugin().configValues.pvpWorlds.contains(((Player) sender).getWorld().getName())) { - if (args.length == 0) { - if (sender.hasPermission(this.getPlugin().permissions.kitList)) { - if (this.isConsole(sender) || (!this.getPlugin().configValues.kitListMode.equalsIgnoreCase("Gui") && !this.getPlugin().configValues.kitListMode.equalsIgnoreCase("Menu"))) { - List kitList = new ArrayList(this.getPlugin().kitList.keySet()); - Lang.sendMessage(sender, Lang.GEN_KIT_LIST_TITLE, String.valueOf(kitList.size())); - if (!kitList.isEmpty()) { - if (this.getPlugin().configValues.sortAlphabetically) - Collections.sort(kitList, Utils.ALPHABETICAL_ORDER); - for (int kitPos = 0; kitPos < kitList.size(); kitPos++) { - String kitName = kitList.get(kitPos).split(" ")[0]; - if (sender.hasPermission("kingkits.kits." + kitName.toLowerCase())) { - sender.sendMessage(r("&6" + (kitPos + 1) + ". " + kitName)); - } else { - if (this.getPlugin().configValues.kitListPermissions) - sender.sendMessage(r("&4" + (kitPos + 1) + ". " + kitName)); - } - } - } else { - Lang.sendMessage(sender, Lang.GEN_NO_KITS); - } - } else { - PvPKits.showKitMenu((Player) sender); - } - } else { - Lang.sendMessage(sender, Lang.COMMAND_KIT_LIST_NO_PERMISSION); - } - } else if (args.length == 1) { - if (!this.isConsole(sender)) { - Player player = (Player) sender; - String kitName = args[0]; - List kitList = this.getPlugin().getKitList(); - List kitListLC = Utils.toLowerCaseList(kitList); - if (kitListLC.contains(kitName.toLowerCase())) - kitName = kitList.get(kitListLC.indexOf(kitName.toLowerCase())); - try { - final Kit kit = PvPKits.getKitByName(kitName); - if (kit != null && kit.hasCooldown() && !player.hasPermission(this.getPlugin().permissions.kitBypassCooldown)) { - if (this.getPlugin().getCooldownConfig().contains(player.getName() + "." + kit.getRealName())) { - long currentCooldown = this.getPlugin().getCooldown(player.getName(), kit.getRealName()); - if (System.currentTimeMillis() - currentCooldown >= kit.getCooldown() * 1000) { - this.getPlugin().getCooldownConfig().set(player.getName() + "." + kit.getRealName(), null); - this.getPlugin().saveCooldownConfig(); - } else { - Lang.sendMessage(player, Lang.KIT_DELAY, String.valueOf((kit.getCooldown() - ((System.currentTimeMillis() - currentCooldown) / 1000)))); - return true; - } - } - } - if (this.getPlugin().configValues.showKitPreview && !player.hasPermission("kingkits.kits." + kitName.toLowerCase())) { - if (!GuiKingKits.guiKitMenuMap.containsKey(player.getName()) && !GuiKingKits.guiPreviewKitMap.containsKey(player.getName())) { - if (this.getPlugin().getKitsConfig().contains(kitName)) { - GuiPreviewKit guiPreviewKit = new GuiPreviewKit(player, kitName); - guiPreviewKit.openMenu(); - } else { - SetKit.setKingKit(player, kitName, true); - } - } else { - SetKit.setKingKit(player, kitName, true); - } - } else { - SetKit.setKingKit(player, kitName, true); - } - } catch (Exception ex) { - ex.printStackTrace(); - } - } else { - Lang.sendMessage(sender, Lang.COMMAND_GEN_IN_GAME); - } - } else if (args.length == 2) { - if (sender.hasPermission(this.getPlugin().permissions.kitUseOtherCommand)) { - String strTarget = args[1]; - Player target = sender.getServer().getPlayer(strTarget); - if (target != null && target.isOnline()) { - String kitName = args[0]; - List kitList = this.getPlugin().getKitList(); - List kitListLC = Utils.toLowerCaseList(kitList); - if (kitListLC.contains(kitName.toLowerCase())) - kitName = kitList.get(kitListLC.indexOf(kitName.toLowerCase())); - try { - SetKit.setKit(target, kitName, false); - } catch (Exception ex) { - ex.printStackTrace(); - Lang.sendMessage(sender, Lang.COMMAND_GEN_ERROR); - return true; - } - Lang.sendMessage(sender, Lang.COMMAND_KIT_OTHER_PLAYER, target.getName()); - } else { - Lang.sendMessage(sender, Lang.COMMAND_GEN_NOT_ONLINE, strTarget); - } - } else { - this.sendNoAccess(sender); - } - } else { - Lang.sendMessage(sender, Lang.COMMAND_GEN_USAGE, command.toLowerCase() + " [| ]"); - } - } else { - Lang.sendMessage(sender, Lang.COMMAND_GEN_WORLD); - } - } else { - Lang.sendMessage(sender, Lang.COMMAND_GEN_DISABLED); - } - } else { - this.sendNoAccess(sender); - } - return true; - } - return false; - } -} diff --git a/src/main/java/com/faris/kingkits/listeners/commands/RefillCommand.java b/src/main/java/com/faris/kingkits/listeners/commands/RefillCommand.java deleted file mode 100644 index 297f4a8..0000000 --- a/src/main/java/com/faris/kingkits/listeners/commands/RefillCommand.java +++ /dev/null @@ -1,195 +0,0 @@ -package com.faris.kingkits.listeners.commands; - -import com.faris.kingkits.KingKits; -import com.faris.kingkits.helpers.Lang; -import com.faris.kingkits.listeners.PlayerCommand; -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; - -public class RefillCommand extends PlayerCommand { - - public RefillCommand(KingKits instance) { - super(instance); - } - - @Override - protected boolean onCommand(Player p, String command, String[] args) { - if (command.equalsIgnoreCase("refill") || command.equalsIgnoreCase("soup")) { - try { - if (p.hasPermission(this.getPlugin().permissions.refillSoupSingle) || p.hasPermission(this.getPlugin().permissions.refillSoupAll)) { - if (this.getPlugin().cmdValues.refillKits) { - if (this.getPlugin().configValues.pvpWorlds.contains("All") || this.getPlugin().configValues.pvpWorlds.contains(p.getWorld().getName())) { - if (this.getPlugin().configValues.quickSoupKitOnly) { - if (!this.getPlugin().usingKits.containsKey(p.getName())) { - Lang.sendMessage(p, Lang.GEN_NO_KIT_SELECTED); - return true; - } - } - if (args.length == 0) { - if (p.hasPermission(this.getPlugin().permissions.refillSoupSingle)) { - if (p.getInventory().getItemInHand() != null) { - if (p.getInventory().getItemInHand().getType() == Material.BOWL) { - int invContentsSize = 0; - ItemStack[] itemContents = p.getInventory().getContents(); - for (ItemStack itemContent : itemContents) { - if (itemContent != null) { - if (itemContent.getType() != Material.AIR) invContentsSize++; - } - } - if (invContentsSize < p.getInventory().getSize()) { - ItemStack itemInHand = p.getInventory().getItemInHand(); - int amount = itemInHand.getAmount(); - if (amount <= 1) { - p.getInventory().setItemInHand(new ItemStack(Material.MUSHROOM_SOUP, 1)); - } else { - itemInHand.setAmount(amount - 1); - p.getInventory().setItemInHand(itemInHand); - p.getInventory().addItem(new ItemStack(Material.MUSHROOM_SOUP, 1)); - } - if (this.getPlugin().configValues.vaultValues.useEconomy && this.getPlugin().configValues.vaultValues.useCostPerRefill) { - try { - net.milkbowl.vault.economy.Economy economy = (net.milkbowl.vault.economy.Economy) this.getPlugin().vault.getEconomy(); - if (economy.hasAccount(p)) { - double cost = this.getPlugin().configValues.vaultValues.costPerRefill; - if (economy.getBalance(p) >= cost) { - economy.withdrawPlayer(p, cost); - if (cost != 0) - p.sendMessage(this.getPlugin().getEconomyMessage(cost)); - } else { - Lang.sendMessage(p, Lang.COMMAND_REFILL_NOT_ENOUGH_MONEY); - return true; - } - } else { - Lang.sendMessage(p, Lang.COMMAND_REFILL_NOT_ENOUGH_MONEY); - return true; - } - } catch (Exception ex) { - } - } - } else { - Lang.sendMessage(p, Lang.COMMAND_REFILL_FULL_INV); - } - } else { - Lang.sendMessage(p, Lang.COMMAND_REFILL_BOWL); - } - } else { - Lang.sendMessage(p, Lang.COMMAND_REFILL_BOWL); - } - } else { - this.sendNoAccess(p); - } - } else if (args.length == 1) { - if (args[0].equalsIgnoreCase("all")) { - if (p.hasPermission(this.getPlugin().permissions.refillSoupAll)) { - if (p.getInventory().getItemInHand() != null) { - if (p.getInventory().getItemInHand().getType() == Material.BOWL) { - int invContentsSize = 0; - ItemStack[] inventoryContents = p.getInventory().getContents(); - for (ItemStack itemContent : inventoryContents) { - if (itemContent != null) { - if (itemContent.getType() != Material.AIR) invContentsSize++; - } - } - if (invContentsSize < p.getInventory().getSize()) { - int bowlAmount = p.getInventory().getItemInHand().getAmount(); - int invSize = 0; - int bowlsGiven = 0; - ItemStack[] itemContents = p.getInventory().getContents(); - int invMaxSize = p.getInventory().getSize(); - for (int i = 0; i < itemContents.length; i++) { - if (itemContents[i] != null) { - if (itemContents[i].getType() != Material.AIR) invSize++; - } - } - for (int i = 0; i < bowlAmount; i++) { - if (invSize < invMaxSize) { - invSize++; - bowlsGiven++; - } - } - if (this.getPlugin().configValues.vaultValues.useEconomy && this.getPlugin().configValues.vaultValues.useCostPerRefill) { - try { - net.milkbowl.vault.economy.Economy economy = (net.milkbowl.vault.economy.Economy) this.getPlugin().vault.getEconomy(); - if (economy.hasAccount(p)) { - double cost = this.getPlugin().configValues.vaultValues.costPerRefill * bowlsGiven; - if (economy.getBalance(p) >= cost) { - economy.withdrawPlayer(p, cost); - if (cost != 0) - p.sendMessage(this.getPlugin().getEconomyMessage(cost)); - } else { - Lang.sendMessage(p, Lang.COMMAND_REFILL_NOT_ENOUGH_MONEY); - return true; - } - } else { - Lang.sendMessage(p, Lang.COMMAND_REFILL_NOT_ENOUGH_MONEY); - return true; - } - } catch (Exception ex) { - } - } - for (int i = 0; i < bowlsGiven; i++) { - p.getInventory().addItem(new ItemStack(Material.MUSHROOM_SOUP, 1)); - } - if (p.getInventory().getItemInHand().getAmount() - bowlsGiven > 0) - p.getInventory().setItemInHand(new ItemStack(Material.BOWL, p.getInventory().getItemInHand().getAmount() - bowlsGiven)); - else p.getInventory().setItemInHand(new ItemStack(Material.AIR)); - } else { - if (p.getInventory().getItemInHand().getAmount() == 1) { - if (this.getPlugin().configValues.vaultValues.useEconomy && this.getPlugin().configValues.vaultValues.useCostPerRefill) { - try { - net.milkbowl.vault.economy.Economy economy = (net.milkbowl.vault.economy.Economy) this.getPlugin().vault.getEconomy(); - if (economy.hasAccount(p)) { - double cost = this.getPlugin().configValues.vaultValues.costPerRefill; - if (economy.getBalance(p) >= cost) { - economy.withdrawPlayer(p, cost); - if (cost != 0) - p.sendMessage(this.getPlugin().getEconomyMessage(cost)); - } else { - Lang.sendMessage(p, Lang.COMMAND_REFILL_NOT_ENOUGH_MONEY); - return true; - } - } else { - Lang.sendMessage(p, Lang.COMMAND_REFILL_NOT_ENOUGH_MONEY); - return true; - } - } catch (Exception ex) { - } - p.getInventory().setItemInHand(new ItemStack(Material.MUSHROOM_SOUP)); - } - } - } - } else { - Lang.sendMessage(p, Lang.COMMAND_REFILL_BOWL); - } - } else { - Lang.sendMessage(p, Lang.COMMAND_REFILL_BOWL); - } - } else { - this.sendNoAccess(p); - } - } else { - Lang.sendMessage(p, Lang.COMMAND_GEN_USAGE, command.toLowerCase() + " []"); - } - } else { - Lang.sendMessage(p, Lang.COMMAND_GEN_USAGE, command.toLowerCase() + " []"); - } - } else { - Lang.sendMessage(p, Lang.COMMAND_GEN_WORLD); - } - } else { - Lang.sendMessage(p, Lang.COMMAND_GEN_DISABLED); - } - } else { - this.sendNoAccess(p); - } - } catch (Exception ex) { - ex.printStackTrace(); - Lang.sendMessage(p, Lang.COMMAND_GEN_ERROR); - } - return true; - } - return false; - } - -} diff --git a/src/main/java/com/faris/kingkits/listeners/commands/RenameKitCommand.java b/src/main/java/com/faris/kingkits/listeners/commands/RenameKitCommand.java deleted file mode 100644 index 45b7dd7..0000000 --- a/src/main/java/com/faris/kingkits/listeners/commands/RenameKitCommand.java +++ /dev/null @@ -1,94 +0,0 @@ -package com.faris.kingkits.listeners.commands; - -import com.faris.kingkits.KingKits; -import com.faris.kingkits.Kit; -import com.faris.kingkits.helpers.Lang; -import com.faris.kingkits.helpers.Utils; -import com.faris.kingkits.listeners.PlayerCommand; -import org.bukkit.entity.Player; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class RenameKitCommand extends PlayerCommand { - - public RenameKitCommand(KingKits pluginInstance) { - super(pluginInstance); - } - - @Override - protected boolean onCommand(Player p, String command, String[] args) { - if (command.equalsIgnoreCase("renamekit")) { - try { - if (p.hasPermission(this.getPlugin().permissions.kitRenameCommand)) { - if (this.getPlugin().cmdValues.renameKits) { - if (this.getPlugin().configValues.pvpWorlds.contains("All") || this.getPlugin().configValues.pvpWorlds.contains(p.getWorld().getName())) { - if (args.length == 0) { - Lang.sendMessage(p, Lang.COMMAND_GEN_USAGE, command.toLowerCase() + " [ ]"); - Lang.sendMessage(p, Lang.COMMAND_RENAME_KIT_DESCRIPTION); - } else if (args.length == 2) { - String strKit = args[0]; - String strNewKit = args[1]; - List currentKits = this.getPlugin().getKitList(); - List currentKitsLC = Utils.toLowerCaseList(currentKits); - if (currentKitsLC.contains(strKit.toLowerCase())) - strKit = currentKits.get(currentKitsLC.indexOf(strKit.toLowerCase())); - if (!this.getPlugin().getKitsConfig().contains(strNewKit) && !currentKitsLC.contains(strNewKit.toLowerCase())) { - if (!this.containsIllegalCharacters(strNewKit)) { - final Kit kit = this.getPlugin().kitList.get(strKit); - if (kit != null) { - this.getPlugin().getKitsConfig().set(strKit, null); - kit.setName(strNewKit); - kit.setRealName(strNewKit); - this.getPlugin().getKitsConfig().set(strNewKit, kit.serialize()); - this.getPlugin().saveKitsConfig(); - - Map newKits = new HashMap(); - for (Map.Entry entrySet : this.getPlugin().usingKits.entrySet()) { - if (entrySet.getValue() != null && entrySet.getValue().equals(strKit)) - newKits.put(entrySet.getKey(), strNewKit); - } - this.getPlugin().usingKits.putAll(newKits); - - newKits = new HashMap(); - for (Map.Entry entrySet : this.getPlugin().playerKits.entrySet()) { - if (entrySet.getValue() != null && entrySet.getValue().equals(strKit)) - newKits.put(entrySet.getKey(), strNewKit); - } - this.getPlugin().playerKits.putAll(newKits); - - this.getPlugin().kitList.remove(strKit); - this.getPlugin().kitList.put(strNewKit, kit); - - Lang.sendMessage(p, Lang.COMMAND_RENAME_RENAMED, strKit, strNewKit); - } else { - Lang.sendMessage(p, Lang.KIT_NONEXISTENT, strKit); - } - } else { - Lang.sendMessage(p, Lang.COMMAND_RENAME_ILLEGAL_CHARACTERS); - } - } else { - Lang.sendMessage(p, Lang.COMMAND_RENAME_ALREADY_EXISTS, strNewKit); - } - } else { - Lang.sendMessage(p, Lang.COMMAND_GEN_USAGE, command.toLowerCase() + " [ ]"); - } - } else { - Lang.sendMessage(p, Lang.COMMAND_GEN_WORLD); - } - } else { - Lang.sendMessage(p, Lang.COMMAND_GEN_DISABLED); - } - } else { - this.sendNoAccess(p); - } - } catch (Exception ex) { - Lang.sendMessage(p, Lang.COMMAND_GEN_ERROR); - } - return true; - } - return false; - } - -} diff --git a/src/main/java/com/faris/kingkits/listeners/commands/RenameUserKitCommand.java b/src/main/java/com/faris/kingkits/listeners/commands/RenameUserKitCommand.java deleted file mode 100644 index 2d68035..0000000 --- a/src/main/java/com/faris/kingkits/listeners/commands/RenameUserKitCommand.java +++ /dev/null @@ -1,109 +0,0 @@ -package com.faris.kingkits.listeners.commands; - -import com.faris.kingkits.KingKits; -import com.faris.kingkits.Kit; -import com.faris.kingkits.helpers.Lang; -import com.faris.kingkits.helpers.Utils; -import com.faris.kingkits.hooks.PvPKits; -import com.faris.kingkits.listeners.PlayerCommand; -import org.bukkit.entity.Player; - -import java.util.ArrayList; -import java.util.List; - -public class RenameUserKitCommand extends PlayerCommand { - - public RenameUserKitCommand(KingKits pluginInstance) { - super(pluginInstance); - } - - @Override - protected boolean onCommand(Player p, String command, String[] args) { - if (command.equalsIgnoreCase("renameukit")) { - try { - if (p.hasPermission(this.getPlugin().permissions.kitURenameCommand)) { - if (this.getPlugin().cmdValues.renameUKits) { - if (this.getPlugin().configValues.pvpWorlds.contains("All") || this.getPlugin().configValues.pvpWorlds.contains(p.getWorld().getName())) { - if (args.length == 0) { - Lang.sendMessage(p, Lang.COMMAND_GEN_USAGE, command.toLowerCase() + " [ ]"); - Lang.sendMessage(p, Lang.COMMAND_RENAME_KIT_DESCRIPTION); - } else if (args.length == 2) { - String strKit = args[0]; - String strNewKit = args[1]; - List currentKits = this.getPlugin().getKitList(p.getName()); - List currentKitsLC = Utils.toLowerCaseList(currentKits); - if (currentKitsLC.contains(strKit.toLowerCase())) - strKit = currentKits.get(currentKitsLC.indexOf(strKit.toLowerCase())); - if (!this.getPlugin().getUserKitsConfig().contains(p.getName() + "." + strNewKit) && !currentKitsLC.contains(strNewKit.toLowerCase())) { - if (!this.containsIllegalCharacters(strNewKit)) { - if (PvPKits.isUserKit(strKit, p.getName())) { - final Kit kit = PvPKits.getKitByName(strKit, p.getName()); - strKit = kit.getRealName(); - kit.setName(strNewKit); - kit.setRealName(strNewKit); - this.getPlugin().getUserKitsConfig().set(p.getName() + "." + strKit, null); - this.getPlugin().getUserKitsConfig().set(p.getName() + "." + strNewKit, kit.serialize()); - this.getPlugin().saveUserKitsConfig(); - - if (this.getPlugin().userKitList.containsKey(p.getName())) { - List kitList = this.getPlugin().userKitList.get(p.getName()); - if (kitList == null) kitList = new ArrayList(); - int deleteIndex = -1; - for (int i = 0; i < kitList.size(); i++) { - Kit targetKit = kitList.get(i); - if (targetKit != null && targetKit.getRealName().toLowerCase().equals(strKit)) { - deleteIndex = i; - break; - } - } - if (deleteIndex != -1) { - kitList.remove(deleteIndex); - if (kitList.isEmpty()) { - this.getPlugin().userKitList.remove(p.getName()); - this.getPlugin().getUserKitsConfig().set(p.getName(), null); - this.getPlugin().saveUserKitsConfig(); - } else { - this.getPlugin().userKitList.put(p.getName(), kitList); - } - } - } - List kitList = this.getPlugin().userKitList.get(p.getName()); - if (kitList == null) kitList = new ArrayList(); - if (!kitList.contains(kit)) kitList.add(kit); - this.getPlugin().userKitList.put(p.getName(), kitList); - - if (this.getPlugin().usingKits.containsKey(p.getName()) && this.getPlugin().usingKits.get(p.getName()).equalsIgnoreCase(strKit)) - this.getPlugin().usingKits.put(p.getName(), strNewKit); - if (this.getPlugin().playerKits.containsKey(p.getName()) && this.getPlugin().playerKits.get(p.getName()).equalsIgnoreCase(strKit)) - this.getPlugin().playerKits.put(p.getName(), strNewKit); - - Lang.sendMessage(p, Lang.COMMAND_RENAME_RENAMED, strKit, strNewKit); - } else { - Lang.sendMessage(p, Lang.KIT_NONEXISTENT, strKit); - } - } else { - Lang.sendMessage(p, Lang.COMMAND_RENAME_ILLEGAL_CHARACTERS); - } - } else { - Lang.sendMessage(p, Lang.COMMAND_RENAME_ALREADY_EXISTS, strNewKit); - } - } else { - Lang.sendMessage(p, Lang.COMMAND_GEN_USAGE, command.toLowerCase() + " [ ]"); - } - } else { - Lang.sendMessage(p, Lang.COMMAND_GEN_WORLD); - } - } else { - Lang.sendMessage(p, Lang.COMMAND_GEN_DISABLED); - } - } else { - this.sendNoAccess(p); - } - } catch (Exception ex) { - Lang.sendMessage(p, Lang.COMMAND_GEN_ERROR); - } - return true; - } - return false; - } -} diff --git a/src/main/java/com/faris/kingkits/listeners/commands/SetKit.java b/src/main/java/com/faris/kingkits/listeners/commands/SetKit.java deleted file mode 100644 index b069a7b..0000000 --- a/src/main/java/com/faris/kingkits/listeners/commands/SetKit.java +++ /dev/null @@ -1,195 +0,0 @@ -package com.faris.kingkits.listeners.commands; - -import com.faris.kingkits.KingKits; -import com.faris.kingkits.Kit; -import com.faris.kingkits.helpers.Lang; -import com.faris.kingkits.helpers.Utils; -import com.faris.kingkits.hooks.PvPKits; -import com.faris.kingkits.listeners.event.custom.PlayerKitEvent; -import org.bukkit.ChatColor; -import org.bukkit.Effect; -import org.bukkit.GameMode; -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import org.bukkit.potion.PotionEffect; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -public class SetKit { - - public static void setKingKit(Player player, String kitName, boolean sendMessages) throws Exception { - final Kit kit = setKit(player, sendMessages, kitName); - if (kit != null) { - KingKits pl = KingKits.getInstance(); - if (kit.hasCooldown() && !player.hasPermission(pl.permissions.kitBypassCooldown)) { - final String playerName = player.getName(); - final String newKitName = kit.getRealName(); - pl.getCooldownConfig().set(playerName + "." + newKitName, System.currentTimeMillis()); - pl.saveCooldownConfig(); - } - } - } - - - public static boolean setKit(Player player, String kitName, boolean sendMessages) throws Exception { - return setKit(player, sendMessages, kitName) != null; - } - - @SuppressWarnings("deprecation") - public static Kit setKit(Player player, boolean sendMessages, String kitName) throws Exception { - if (player == null || kitName == null) return null; - KingKits plugin = KingKits.getInstance(); - if (plugin.configValues.pvpWorlds.contains("All") || plugin.configValues.pvpWorlds.contains(player.getWorld().getName())) { - Kit newKit = PvPKits.getKitByName(Utils.stripColour(kitName), player.getName()); - if (newKit != null) { - kitName = newKit.getRealName(); - if (newKit.isUserKit() || player.hasPermission("kingkits.kits." + newKit.getRealName().toLowerCase())) { - if (plugin.configValues.oneKitPerLife) { - if (plugin.configValues.opBypass) { - if (!player.isOp()) { - if (plugin.playerKits.containsKey(player.getName())) { - if (sendMessages) Lang.sendMessage(player, Lang.KIT_ALREADY_CHOSEN); - return null; - } - } - } else { - if (plugin.usingKits.containsKey(player.getName())) { - if (sendMessages) Lang.sendMessage(player, Lang.KIT_ALREADY_CHOSEN); - return null; - } - } - } - String oldKit = plugin.playerKits.containsKey(player.getName()) ? plugin.playerKits.get(player.getName()) : ""; - PlayerKitEvent playerKitEvent = new PlayerKitEvent(player, kitName, oldKit, newKit.getItemsWithSlot(), newKit.getArmour(), newKit.getPotionEffects()); - playerKitEvent.setCommands(newKit.getCommands()); - player.getServer().getPluginManager().callEvent(playerKitEvent); - if (!playerKitEvent.isCancelled()) { - if (plugin.configValues.vaultValues.useEconomy && plugin.configValues.vaultValues.useCostPerKit) { - try { - net.milkbowl.vault.economy.Economy economy = (net.milkbowl.vault.economy.Economy) plugin.vault.getEconomy(); - double kitCost = newKit.getCost(); - if (kitCost > 0D) { - if (economy.hasAccount(player.getName())) { - if (economy.getBalance(player.getName()) >= kitCost) { - economy.withdrawPlayer(player.getName(), kitCost); - player.sendMessage(ChatColor.GREEN + plugin.getEconomyMessage(kitCost)); - } else { - if (sendMessages) Lang.sendMessage(player, Lang.KIT_NOT_ENOUGH_MONEY); - return null; - } - } else { - if (sendMessages) Lang.sendMessage(player, Lang.KIT_NOT_ENOUGH_MONEY); - return null; - } - } - } catch (Exception ex) { - } - } - - if (plugin.configValues.replaceItems) { - player.getInventory().clear(); - player.getInventory().setArmorContents(null); - } - player.setGameMode(GameMode.SURVIVAL); - for (PotionEffect potionEffect : player.getActivePotionEffects()) - player.removePotionEffect(potionEffect.getType()); - if (plugin.configValues.replaceItems) { - Map kitItems = playerKitEvent.getKitContentsWithSlots(); - for (Map.Entry kitItem : kitItems.entrySet()) { - try { - if (kitItem.getValue() != null && kitItem.getValue().getType() != Material.AIR) { - int slot = kitItem.getKey(); - if (slot >= 0 && slot < player.getInventory().getSize()) { - player.getInventory().setItem(slot, kitItem.getValue()); - } - } - } catch (Exception ex) { - continue; - } - } - } else { - List kitItems = playerKitEvent.getKitContents(); - for (int i = 0; i < kitItems.size(); i++) { - try { - ItemStack kitItem = kitItems.get(i); - if (kitItem != null && kitItem.getType() != Material.AIR) - player.getInventory().addItem(kitItem); - } catch (Exception ex) { - continue; - } - } - } - List armourItems = playerKitEvent.getKitArmour(); - List leftOverArmour = new ArrayList(); - for (ItemStack armourItem : armourItems) { - if (armourItem != null) { - String strArmourType = armourItem.getType().toString().toLowerCase(); - if (strArmourType.endsWith("helmet") && (plugin.configValues.replaceItems ? true : Utils.isItemNull(player.getInventory().getHelmet()))) - player.getInventory().setHelmet(armourItem); - else if (strArmourType.endsWith("chestplate") && (plugin.configValues.replaceItems ? true : Utils.isItemNull(player.getInventory().getChestplate()))) - player.getInventory().setChestplate(armourItem); - else if ((strArmourType.endsWith("leggings") || strArmourType.endsWith("pants")) && (plugin.configValues.replaceItems ? true : Utils.isItemNull(player.getInventory().getLeggings()))) - player.getInventory().setLeggings(armourItem); - else if (strArmourType.endsWith("boots") && (plugin.configValues.replaceItems ? true : Utils.isItemNull(player.getInventory().getBoots()))) - player.getInventory().setBoots(armourItem); - else if ((plugin.configValues.replaceItems || (!strArmourType.endsWith("helmet") && !strArmourType.endsWith("chestplate") && !strArmourType.endsWith("leggings") && !strArmourType.endsWith("pants") && !strArmourType.endsWith("boots"))) && player.getInventory().getHelmet() == null) - leftOverArmour.add(armourItem); - else player.getInventory().addItem(armourItem); - } - } - if (!leftOverArmour.isEmpty()) { - player.getInventory().setHelmet(leftOverArmour.get(0)); - for (int i = 1; i < leftOverArmour.size(); i++) - player.getInventory().addItem(leftOverArmour.get(i)); - } - player.setMaxHealth(newKit.getMaxHealth()); - player.addPotionEffects(playerKitEvent.getPotionEffects()); - - plugin.playerKits.remove(player.getName()); - plugin.usingKits.remove(player.getName()); - if (plugin.configValues.opBypass) { - if (!player.isOp()) plugin.playerKits.put(player.getName(), newKit.getRealName()); - } else { - plugin.playerKits.put(player.getName(), newKit.getRealName()); - } - plugin.usingKits.put(player.getName(), newKit.getRealName()); - if (plugin.configValues.commandToRun.length() > 0) { - String cmdToRun = plugin.configValues.commandToRun; - cmdToRun = cmdToRun.replace("", kitName); - cmdToRun = cmdToRun.replace("", player.getName()).replace("", player.getDisplayName()); - player.getServer().dispatchCommand(player.getServer().getConsoleSender(), cmdToRun); - } - for (String cmdToRun : playerKitEvent.getCommands()) { - cmdToRun = cmdToRun.replace("", kitName); - cmdToRun = cmdToRun.replace("", player.getName()).replace("", player.getDisplayName()); - player.getServer().dispatchCommand(player.getServer().getConsoleSender(), cmdToRun); - } - if (plugin.configValues.customMessages != "" && plugin.configValues.customMessages != "''") - player.sendMessage(r(plugin.configValues.customMessages).replace("", player.getName()).replace("", player.getDisplayName()).replace("", kitName)); - if (plugin.configValues.kitParticleEffects) - player.playEffect(player.getLocation().add(0, 1, 0), Effect.ENDER_SIGNAL, (byte) 0); - - player.updateInventory(); - return newKit; - } else { - for (PotionEffect potionEffect : player.getActivePotionEffects()) - player.removePotionEffect(potionEffect.getType()); - } - } else { - if (sendMessages) Lang.sendMessage(player, Lang.KIT_NO_PERMISSION, kitName); - } - } else { - if (sendMessages) Lang.sendMessage(player, Lang.KIT_NONEXISTENT, kitName); - } - } - return null; - } - - private static String r(String val) { - return Utils.replaceChatColour(val); - } - -} diff --git a/src/main/java/com/faris/kingkits/listeners/event/EventListener.java b/src/main/java/com/faris/kingkits/listeners/event/EventListener.java deleted file mode 100644 index ebdb1f1..0000000 --- a/src/main/java/com/faris/kingkits/listeners/event/EventListener.java +++ /dev/null @@ -1,1103 +0,0 @@ -package com.faris.kingkits.listeners.event; - -import com.faris.kingkits.KingKits; -import com.faris.kingkits.Kit; -import com.faris.kingkits.guis.GuiKingKits; -import com.faris.kingkits.guis.GuiKitMenu; -import com.faris.kingkits.guis.GuiPreviewKit; -import com.faris.kingkits.helpers.Lang; -import com.faris.kingkits.helpers.Utils; -import com.faris.kingkits.hooks.PvPKits; -import com.faris.kingkits.listeners.commands.SetKit; -import com.faris.kingkits.listeners.event.custom.PlayerKilledEvent; -import com.faris.kingkits.sql.KingKitsSQL; -import org.bukkit.ChatColor; -import org.bukkit.GameMode; -import org.bukkit.Material; -import org.bukkit.block.BlockState; -import org.bukkit.block.Sign; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.block.Action; -import org.bukkit.event.block.BlockBreakEvent; -import org.bukkit.event.block.BlockPlaceEvent; -import org.bukkit.event.block.SignChangeEvent; -import org.bukkit.event.entity.EntityDamageByEntityEvent; -import org.bukkit.event.entity.EntityShootBowEvent; -import org.bukkit.event.entity.FoodLevelChangeEvent; -import org.bukkit.event.entity.PlayerDeathEvent; -import org.bukkit.event.player.*; -import org.bukkit.inventory.ItemStack; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; -import org.bukkit.scoreboard.DisplaySlot; -import org.bukkit.scoreboard.Objective; -import org.bukkit.scoreboard.Scoreboard; - -import java.util.List; -import java.util.Map; - -public class EventListener implements Listener { - private final KingKits plugin; - - /** - * Create an instance EventListener * - */ - public EventListener(KingKits instance) { - this.plugin = instance; - } - - /** - * Register custom kill event * - */ - @EventHandler(priority = EventPriority.HIGHEST) - public void registerKillEvent(PlayerDeathEvent event) { - try { - if (event.getEntity() != null) { - if (event.getEntity().getKiller() != null) { - if (!event.getEntity().getName().equals(event.getEntity().getKiller().getName())) - event.getEntity().getServer().getPluginManager().callEvent(new PlayerKilledEvent(event.getEntity().getKiller(), event.getEntity())); - } - } - } catch (Exception ex) { - } - } - - @EventHandler(priority = EventPriority.LOW) - public void onPlayerJoin(PlayerJoinEvent event) { - try { - // List kits on join - try { - if (this.getPlugin().configValues.listKitsOnJoin) { - if (event.getPlayer() != null) { - if (this.getPlugin().configValues.pvpWorlds.contains("All") || this.getPlugin().configValues.pvpWorlds.contains(event.getPlayer().getWorld().getName())) { - this.listKitsOnJoin(event.getPlayer()); - } - } - } - } catch (Exception ex) { - ex.printStackTrace(); - } - - // Kit menu - try { - if (this.getPlugin().configValues.kitMenuOnJoin) { - final Player player = event.getPlayer(); - player.getServer().getScheduler().runTaskLater(this.getPlugin(), new Runnable() { - @SuppressWarnings("deprecation") - public void run() { - if (player != null && player.isOnline()) { - if (!GuiKingKits.guiKitMenuMap.containsKey(player.getName()) && !GuiKingKits.guiPreviewKitMap.containsKey(player.getName())) { - PvPKits.showKitMenu(player, false); - } - } - } - }, 20L); - } - } catch (Exception ex) { - ex.printStackTrace(); - } - - // Scoreboard - try { - if (event.getPlayer().getScoreboard() != null) { - Objective scoreboardObj = event.getPlayer().getScoreboard().getObjective("KingKits"); - if (scoreboardObj != null) { - Scoreboard playerBoard = event.getPlayer().getScoreboard(); - playerBoard.resetScores(ChatColor.GREEN + "Score:"); - playerBoard.resetScores(ChatColor.GREEN + "Killstreak:"); - event.getPlayer().getScoreboard().resetScores(ChatColor.GREEN + "Score:"); - event.getPlayer().getScoreboard().resetScores(ChatColor.GREEN + "Killstreak:"); - playerBoard.clearSlot(DisplaySlot.SIDEBAR); - event.getPlayer().setScoreboard(playerBoard); - } - } - } catch (Exception ex) { - ex.printStackTrace(); - } - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - @EventHandler - public void onPlayerLeave(PlayerQuitEvent event) { - try { - // Scoreboard - try { - Scoreboard pScoreboard = event.getPlayer().getScoreboard(); - if (pScoreboard != null) { - if (pScoreboard.getObjective("KingKits") != null) { - Scoreboard playerBoard = event.getPlayer().getScoreboard(); - playerBoard.resetScores(ChatColor.GREEN + "Score:"); - playerBoard.resetScores(ChatColor.GREEN + "Killstreak:"); - event.getPlayer().getScoreboard().resetScores(ChatColor.GREEN + "Score:"); - event.getPlayer().getScoreboard().resetScores(ChatColor.GREEN + "Killstreak:"); - playerBoard.clearSlot(DisplaySlot.SIDEBAR); - event.getPlayer().setScoreboard(playerBoard); - } - } - } catch (Exception ex) { - ex.printStackTrace(); - } - - // Remove kits - try { - Player player = event.getPlayer(); - if (this.getPlugin().configValues.removeItemsOnLeave) { - if (this.getPlugin().playerKits.containsKey(player.getName()) || this.getPlugin().usingKits.containsKey(player.getName())) { - player.getInventory().clear(); - player.getInventory().setArmorContents(null); - } - } - if (this.getPlugin().playerKits.containsKey(player.getName())) - this.getPlugin().playerKits.remove(player.getName()); - if (this.getPlugin().usingKits.containsKey(player.getName())) { - this.getPlugin().usingKits.remove(player.getName()); - player.setMaxHealth(20D); - } - if (GuiKingKits.guiKitMenuMap.containsKey(event.getPlayer().getName())) { - GuiKitMenu guiKitMenu = GuiKingKits.guiKitMenuMap.get(event.getPlayer().getName()); - guiKitMenu.closeMenu(true, true); - } - if (GuiKingKits.guiPreviewKitMap.containsKey(event.getPlayer().getName())) { - GuiPreviewKit guiPreviewKit = GuiKingKits.guiPreviewKitMap.get(event.getPlayer().getName()); - guiPreviewKit.closeMenu(true, true); - } - event.getPlayer().updateInventory(); - } catch (Exception ex) { - ex.printStackTrace(); - } - - // Remove potion effects - try { - if (this.getPlugin().configValues.removePotionEffectsOnLeave) { - if (event.getPlayer().getWorld() != null) { - if (this.getPlugin().configValues.pvpWorlds.contains("All") || this.getPlugin().configValues.pvpWorlds.contains(event.getPlayer().getWorld().getName())) { - for (PotionEffect potionEffectOnPlayer : event.getPlayer().getActivePotionEffects()) { - PotionEffectType potionEffectType = potionEffectOnPlayer.getType(); - event.getPlayer().removePotionEffect(potionEffectType); - } - } - } else { - for (PotionEffect potionEffectOnPlayer : event.getPlayer().getActivePotionEffects()) { - event.getPlayer().removePotionEffect(potionEffectOnPlayer.getType()); - } - } - } - } catch (Exception ex) { - ex.printStackTrace(); - } - - // Remove compass target - try { - if (this.getPlugin().configValues.rightClickCompass) { - if (this.getPlugin().compassTargets.containsValue(event.getPlayer())) { - Player tracker = null; - for (Map.Entry e : this.getPlugin().compassTargets.entrySet()) { - Player key = e.getKey(); - Player value = e.getValue(); - if (key != null) { - if (value != null) { - if (key.isOnline()) { - if (value.isOnline()) { - if (event.getPlayer().getName().equalsIgnoreCase(value.getName())) - tracker = key.getPlayer(); - } - } - } - } - } - if (tracker != null) this.getPlugin().compassTargets.remove(tracker); - } - if (this.getPlugin().compassTargets.containsKey(event.getPlayer())) - this.getPlugin().compassTargets.remove(event.getPlayer()); - } - } catch (Exception ex) { - ex.printStackTrace(); - } - - // Remove killstreak - try { - this.getPlugin().playerKillstreaks.remove(event.getPlayer().getName()); - } catch (Exception ex) { - } - } catch (Exception ex) { - } - } - - @EventHandler - public void onPlayerInteract(PlayerInteractEvent event) { - // Quicksoup - try { - if (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK) { - if (event.getItem() != null) { - if (event.getItem().getType() == Material.MUSHROOM_SOUP) { - if (this.getPlugin().configValues.quickSoup) { - if (event.getPlayer().hasPermission(this.getPlugin().permissions.quickSoup) || (this.getPlugin().configValues.opBypass && event.getPlayer().isOp())) { - if (this.getPlugin().configValues.pvpWorlds.contains("All") || this.getPlugin().configValues.pvpWorlds.contains(event.getPlayer().getWorld().getName())) { - Player player = event.getPlayer(); - int soupAmount = player.getInventory().getItemInHand().getAmount(); - if (soupAmount > 0) { - boolean valid = true; - if (player.getHealth() < player.getMaxHealth()) { - if (player.getHealth() + (this.getPlugin().configValues.quickSoupHeal * 2) > player.getMaxHealth()) - player.setHealth(player.getMaxHealth()); - else player.setHealth(player.getHealth() + (this.getPlugin().configValues.quickSoupHeal * 2)); - } else if (player.getFoodLevel() < 20) { - if (player.getFoodLevel() + 6 > 20) player.setFoodLevel(20); - else player.setFoodLevel(player.getFoodLevel() + 6); - } else { - valid = false; - } - if (valid) { - if (soupAmount == 1) { - player.getInventory().setItemInHand(new ItemStack(Material.BOWL, 1)); - } else { - int newAmount = soupAmount - 1; - ItemStack newItem = player.getInventory().getItemInHand(); - newItem.setAmount(newAmount); - player.getInventory().setItemInHand(newItem); - player.getInventory().addItem(new ItemStack(Material.BOWL, 1)); - } - event.setCancelled(true); - } - } - } - } - } - } - } - } - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - @EventHandler(ignoreCancelled = true) - public void onPlayerInteractIgnoreCancelled(PlayerInteractEvent event) { - try { - // No tool damage - try { - if (event.getItem() != null) { - if (this.getPlugin().usingKits.containsKey(event.getPlayer().getName())) { - if (this.isTool(event.getItem().getType()) || event.getItem().getType() == Material.FISHING_ROD || event.getItem().getType() == Material.FLINT_AND_STEEL) { - boolean repair = false; - if (this.getPlugin().configValues.disableItemBreaking) { - repair = true; - } else { - Kit kit = PvPKits.getKitByName(this.getPlugin().usingKits.get(event.getPlayer().getName())); - if (kit != null && !kit.canItemsBreak()) { - repair = true; - } - } - if (repair) event.getItem().setDurability((short) 0); - } - } - } - } catch (Exception ex) { - ex.printStackTrace(); - } - - // Right clicking a sign - try { - if (event.getAction() == Action.RIGHT_CLICK_BLOCK) { - if (event.getPlayer().getWorld() != null) { - if (this.getPlugin().configValues.pvpWorlds.contains("All") || this.getPlugin().configValues.pvpWorlds.contains(event.getPlayer().getWorld().getName())) { - Player player = event.getPlayer(); - BlockState block = event.getClickedBlock().getState(); - if ((block instanceof Sign)) { - Sign sign = (Sign) block; - String signLine0 = sign.getLine(0); - if (signLine0.equalsIgnoreCase((this.getPlugin().configValues.strKitSignValid.startsWith("&0") ? this.getPlugin().configValues.strKitSignValid.replaceFirst("&0", "") : this.getPlugin().configValues.strKitSignValid))) { - if (player.hasPermission(this.getPlugin().permissions.kitUseSign)) { - String line1 = sign.getLine(1); - if (line1 != null) { - if (!line1.equalsIgnoreCase("")) { - List kitList = this.getPlugin().getKitList(); - List kitListLC = Utils.toLowerCaseList(kitList); - String kitName = kitList.get(kitListLC.indexOf(line1.toLowerCase())); - try { - final Kit kit = PvPKits.getKitByName(kitName); - boolean validCooldown = true; - if (kit != null && kit.hasCooldown() && !player.hasPermission(this.getPlugin().permissions.kitBypassCooldown)) { - if (this.getPlugin().getCooldownConfig().contains(player.getName() + "." + kit.getRealName())) { - long currentCooldown = this.getPlugin().getCooldown(player.getName(), kit.getRealName()); - if (System.currentTimeMillis() - currentCooldown >= kit.getCooldown() * 1000) { - this.getPlugin().getCooldownConfig().set(player.getName() + "." + kit.getRealName(), null); - this.getPlugin().saveCooldownConfig(); - } else { - Lang.sendMessage(player, Lang.KIT_DELAY, String.valueOf((kit.getCooldown() - ((System.currentTimeMillis() - currentCooldown) / 1000)))); - validCooldown = false; - } - } - } - if (validCooldown) SetKit.setKingKit(player, kitName, true); - } catch (Exception ex) { - ex.printStackTrace(); - Lang.sendMessage(player, Lang.COMMAND_GEN_ERROR); - } - } else { - Lang.sendMessage(player, Lang.SIGN_GENERAL_INCORRECTLY_SETUP); - sign.setLine(0, this.getPlugin().configValues.strKitSignInvalid); - sign.update(true); - } - } else { - Lang.sendMessage(player, Lang.SIGN_GENERAL_INCORRECTLY_SETUP); - sign.setLine(0, this.getPlugin().configValues.strKitSignInvalid); - sign.update(true); - } - } else { - Lang.sendMessage(player, Lang.SIGN_USE_NO_PERMISSION); - } - event.setCancelled(true); - } else if (signLine0.equalsIgnoreCase(this.getPlugin().configValues.strKitListSignValid.startsWith("&0") ? this.getPlugin().configValues.strKitListSignValid.replaceFirst("&0", "") : this.getPlugin().configValues.strKitListSignValid)) { - if (player.hasPermission(this.getPlugin().permissions.kitListSign)) { - if (!this.getPlugin().configValues.kitListMode.equalsIgnoreCase("Gui") && !this.getPlugin().configValues.kitListMode.equalsIgnoreCase("Menu")) { - List kitList = this.getPlugin().getKitList(); - Lang.sendMessage(player, Lang.GEN_KIT_LIST_TITLE, String.valueOf(kitList.size())); - if (!kitList.isEmpty()) { - for (int kitPos = 0; kitPos < kitList.size(); kitPos++) { - String kitName = kitList.get(kitPos).split(" ")[0]; - if (player.hasPermission("kingkits.kits." + kitName.toLowerCase())) { - player.sendMessage(this.r("&6" + (kitPos + 1) + ". " + kitName)); - } else { - if (this.getPlugin().configValues.kitListPermissions) - player.sendMessage(this.r("&4" + (kitPos + 1) + ". " + kitName)); - } - } - } else { - Lang.sendMessage(player, Lang.GEN_NO_KITS); - } - } else { - PvPKits.showKitMenu(player); - } - } else { - Lang.sendMessage(player, Lang.SIGN_USE_NO_PERMISSION); - } - event.setCancelled(true); - } - } - } - } - } - } catch (Exception ex) { - ex.printStackTrace(); - } - } catch (Exception ex) { - } - } - - @EventHandler - public void onSignChange(SignChangeEvent event) { - try { - // Creating a sign - try { - if (this.getPlugin().configValues.pvpWorlds.contains("All") || this.getPlugin().configValues.pvpWorlds.contains(event.getPlayer().getWorld().getName())) { - Player p = event.getPlayer(); - String signType = event.getLine(0); - if (signType.equalsIgnoreCase(this.getPlugin().configValues.strKitSign)) { - if (p.hasPermission(this.getPlugin().permissions.kitCreateSign)) { - if (!event.getLine(1).isEmpty()) { - event.setLine(0, this.getPlugin().configValues.strKitSignValid); - } else { - event.setLine(0, this.getPlugin().configValues.strKitSignInvalid); - Lang.sendMessage(p, Lang.SIGN_CREATE_SECOND_LINE); - } - } else { - Lang.sendMessage(p, Lang.SIGN_CREATE_NO_PERMISSION, "create"); - event.setLine(0, ""); - event.setLine(1, ""); - event.setLine(2, ""); - event.setLine(3, ""); - } - } else if (signType.equalsIgnoreCase(this.getPlugin().configValues.strKitListSign)) { - if (p.hasPermission(this.getPlugin().permissions.kitListSign)) { - event.setLine(0, this.getPlugin().configValues.strKitListSignValid); - } else { - Lang.sendMessage(p, Lang.SIGN_CREATE_NO_PERMISSION, "list"); - event.setLine(0, ""); - event.setLine(1, ""); - event.setLine(2, ""); - event.setLine(3, ""); - } - } - } - } catch (Exception ex) { - ex.printStackTrace(); - } - } catch (Exception ex) { - } - } - - @EventHandler - public void onPlayerDeath(PlayerDeathEvent event) { - try { - boolean inPvPWorld = this.getPlugin().configValues.pvpWorlds.contains("All") || this.getPlugin().configValues.pvpWorlds.contains(event.getEntity().getWorld().getName()); - - // Scores - try { - if (this.getPlugin().configValues.scores) { - if (inPvPWorld) { - final Player killer = event.getEntity().getKiller(); - if (killer != null && !event.getEntity().getName().equals(killer.getName())) { - try { - if (!this.getPlugin().playerScores.containsKey(killer.getUniqueId())) - this.getPlugin().playerScores.put(killer.getUniqueId(), 0); - int currentScore = (Integer) this.getPlugin().playerScores.get(killer.getUniqueId()); - int newScore = currentScore + this.getPlugin().configValues.scoreIncrement; - if (newScore > this.getPlugin().configValues.maxScore) - newScore = this.getPlugin().configValues.maxScore; - this.getPlugin().playerScores.put(killer.getUniqueId(), newScore); - this.getPlugin().getScoresConfig().set("Scores." + killer.getUniqueId(), (long) newScore); - this.getPlugin().saveScoresConfig(); - - if (KingKitsSQL.sqlEnabled) { - final int kScore = newScore; - killer.getServer().getScheduler().runTaskAsynchronously(this.getPlugin(), new Runnable() { - @Override - public void run() { - KingKitsSQL.setScore(killer, kScore); - } - }); - } - } catch (Exception ex) { - } - } - } - } - } catch (Exception ex) { - ex.printStackTrace(); - } - - // Core - try { - Player player = event.getEntity(); - boolean hadKit = false; - if (this.getPlugin().playerKits.containsKey(player.getName())) { - this.getPlugin().playerKits.remove(player.getName()); - hadKit = true; - } - if (this.getPlugin().usingKits.containsKey(player.getName())) { - this.getPlugin().usingKits.remove(player.getName()); - hadKit = true; - } - if (inPvPWorld && !this.getPlugin().configValues.dropItemsOnDeath) - event.getDrops().clear(); - if (hadKit) { - player.setMaxHealth(20D); - player.getInventory().clear(); - player.getInventory().setArmorContents(null); - player.updateInventory(); - - for (PotionEffect activeEffect : player.getActivePotionEffects()) - player.removePotionEffect(activeEffect.getType()); - } - } catch (Exception ex) { - ex.printStackTrace(); - } - - // Disable death messages - try { - if (this.getPlugin().configValues.disableDeathMessages) { - if (inPvPWorld) event.setDeathMessage(""); - } - } catch (Exception ex) { - } - - // Remove money. - if (event.getEntity().getKiller() != null) { - try { - if (this.getPlugin().configValues.vaultValues.useEconomy && this.getPlugin().configValues.vaultValues.useMoneyPerDeath) { - if (!event.getEntity().getName().equalsIgnoreCase(event.getEntity().getKiller().getName())) { - if (this.getPlugin().configValues.pvpWorlds.contains("All") || this.getPlugin().configValues.pvpWorlds.contains(event.getEntity().getKiller().getWorld().getName())) { - net.milkbowl.vault.economy.Economy economy = (net.milkbowl.vault.economy.Economy) this.getPlugin().vault.getEconomy(); - economy.withdrawPlayer(event.getEntity(), this.getPlugin().configValues.vaultValues.moneyPerDeath); - event.getEntity().sendMessage(this.getPlugin().getMPDMessage(event.getEntity(), this.getPlugin().configValues.vaultValues.moneyPerDeath)); - } - } - } - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - // Killstreaks - if (this.getPlugin().configValues.killstreaks && this.getPlugin().playerKillstreaks.containsKey(event.getEntity().getName())) - this.getPlugin().playerKillstreaks.remove(event.getEntity().getName()); - } catch (Exception ex) { - } - } - - @SuppressWarnings("deprecation") - @EventHandler - public void onPlayerDropItem(PlayerDropItemEvent event) { - try { - // Ban dropping items - try { - if (event.getItemDrop() != null) { - if (event.getPlayer().getWorld() != null) { - if (!this.getPlugin().configValues.dropItems) { - if (this.getPlugin().configValues.pvpWorlds.contains("All") || this.getPlugin().configValues.pvpWorlds.contains(event.getPlayer().getWorld().getName())) { - if (this.getPlugin().configValues.opBypass) { - if (!event.getPlayer().isOp()) { - if (this.getPlugin().playerKits.containsKey(event.getPlayer().getName())) { - if (this.getPlugin().configValues.dropAnimations.contains(event.getItemDrop().getItemStack().getType().getId())) { - event.getItemDrop().remove(); - } else { - Lang.sendMessage(event.getPlayer(), Lang.GEN_ITEM_DROP); - event.setCancelled(true); - } - } - } - } else { - if (this.getPlugin().usingKits.containsKey(event.getPlayer().getName())) { - if (this.getPlugin().configValues.dropAnimations.contains(event.getItemDrop().getItemStack().getType().getId())) { - event.getItemDrop().remove(); - } else { - Lang.sendMessage(event.getPlayer(), Lang.GEN_ITEM_DROP); - event.setCancelled(true); - } - } - } - } - } - } - } - } catch (Exception ex) { - ex.printStackTrace(); - } - } catch (Exception ex) { - } - } - - @EventHandler - public void onPlayerPickupItem(PlayerPickupItemEvent event) { - try { - // Ban picking items - try { - if (event.getItem() != null) { - if (event.getPlayer().getWorld() != null) { - if (!this.getPlugin().configValues.allowPickingUpItems) { - if (this.getPlugin().configValues.pvpWorlds.contains("All") || this.getPlugin().configValues.pvpWorlds.contains(event.getPlayer().getWorld().getName())) { - if (this.getPlugin().configValues.opBypass) { - if (!event.getPlayer().isOp()) { - if (this.getPlugin().playerKits.containsKey(event.getPlayer().getName())) { - event.setCancelled(true); - } - } - } else { - if (this.getPlugin().usingKits.containsKey(event.getPlayer().getName())) { - event.setCancelled(true); - } - } - } - } - } - } - } catch (Exception ex) { - ex.printStackTrace(); - } - } catch (Exception ex) { - } - } - - @EventHandler(ignoreCancelled = true) - public void onPlayerChat(AsyncPlayerChatEvent event) { - try { - // Score chat prefix - try { - if (this.getPlugin().configValues.scores) { - if (this.getPlugin().configValues.pvpWorlds.contains("All") || this.getPlugin().configValues.pvpWorlds.contains(event.getPlayer().getWorld().getName())) { - Player player = event.getPlayer(); - if (!this.getPlugin().playerScores.containsKey(player.getUniqueId())) { - this.getPlugin().playerScores.put(player.getUniqueId(), 0); - this.getPlugin().getScoresConfig().set("Scores." + player.getUniqueId(), 0); - this.getPlugin().saveScoresConfig(); - } - event.setFormat(Utils.replaceChatColour(this.getPlugin().configValues.scoreFormat).replace("", String.valueOf(this.getPlugin().playerScores.get(player.getUniqueId()))) + ChatColor.WHITE + " " + event.getFormat()); - } - } - } catch (Exception ex) { - ex.printStackTrace(); - } - } catch (Exception ex) { - } - } - - @EventHandler - public void onPlayerInteractCompass(PlayerInteractEvent event) { - try { - if (this.getPlugin().configValues.rightClickCompass) { - if (this.getPlugin().configValues.pvpWorlds.contains("All") || this.getPlugin().configValues.pvpWorlds.contains(event.getPlayer().getWorld().getName())) { - if (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK) { - if (event.getPlayer().getInventory().getItemInHand() != null) { - if (event.getPlayer().getInventory().getItemInHand().getType() == Material.COMPASS) { - if (event.getPlayer().hasPermission(this.getPlugin().permissions.rightClickCompass) || event.getPlayer().isOp()) { - Player nearestPlayer = null; - double distance = -1D; - for (Player target : event.getPlayer().getServer().getOnlinePlayers()) { - if (!target.getName().equalsIgnoreCase(event.getPlayer().getName())) { - if (event.getPlayer().getLocation().getWorld().getName().equalsIgnoreCase(target.getLocation().getWorld().getName())) { - if (distance == -1D) { - distance = event.getPlayer().getLocation().distance(target.getLocation()); - nearestPlayer = target; - } else { - if (event.getPlayer().getLocation().distance(target.getLocation()) < distance) { - distance = event.getPlayer().getLocation().distance(target.getLocation()); - nearestPlayer = target; - } - } - } - } - } - if (nearestPlayer != null) { - event.getPlayer().setCompassTarget(nearestPlayer.getLocation()); - Lang.sendMessage(event.getPlayer(), Lang.COMPASS_POINTING_PLAYER, nearestPlayer.getName()); - if (this.getPlugin().compassTargets.containsKey(event.getPlayer())) - this.getPlugin().compassTargets.remove(event.getPlayer()); - this.getPlugin().compassTargets.put(event.getPlayer().getPlayer(), nearestPlayer.getPlayer()); - } else { - event.getPlayer().setCompassTarget(event.getPlayer().getWorld().getSpawnLocation()); - Lang.sendMessage(event.getPlayer(), Lang.COMPASS_POINTING_SPAWN); - } - } - } - } - } - } - } - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - @EventHandler(ignoreCancelled = true) - public void onPlayerMove(PlayerMoveEvent event) { - try { - // Compass tracking updater - try { - if (this.getPlugin().configValues.rightClickCompass) { - if (this.getPlugin().compassTargets.containsValue(event.getPlayer())) { - Player tracker = null; - for (Map.Entry compassTargetsEntry : this.getPlugin().compassTargets.entrySet()) { - Player key = compassTargetsEntry.getKey(); - Player value = compassTargetsEntry.getValue(); - if (key != null) { - if (value != null) { - if (key.isOnline()) { - if (value.isOnline()) { - if (event.getPlayer().getName().equalsIgnoreCase(value.getName())) - tracker = key.getPlayer(); - } - } - } - } - } - if (tracker != null) tracker.setCompassTarget(event.getPlayer().getLocation()); - } - } - } catch (Exception ex) { - ex.printStackTrace(); - } - } catch (Exception ex) { - } - } - - @EventHandler(ignoreCancelled = true) - public void onBlockBreak(BlockBreakEvent event) { - try { - // Disable block breaking - try { - if (this.getPlugin().configValues.banBlockBreakingAndPlacing) { - if (this.getPlugin().configValues.pvpWorlds.contains("All") || this.getPlugin().configValues.pvpWorlds.contains(event.getPlayer().getWorld().getName())) { - if (this.getPlugin().configValues.opBypass) { - if (!event.getPlayer().isOp()) event.setCancelled(true); - } else { - event.setCancelled(true); - } - } - } - } catch (Exception ex) { - ex.printStackTrace(); - } - - // Disable item breaking - try { - if (event.getPlayer().getGameMode() == GameMode.SURVIVAL) { - String playerKit = this.getPlugin().usingKits.get(event.getPlayer().getName()); - if (playerKit != null) { - boolean repair = false; - if (this.getPlugin().configValues.disableItemBreaking) { - repair = true; - } else { - Kit kit = PvPKits.getKitByName(playerKit); - if (kit != null && !kit.canItemsBreak()) { - repair = true; - } - } - if (repair) { - final Player player = event.getPlayer(); - if (player.getItemInHand() != null && (this.isTool(player.getItemInHand().getType()) || player.getItemInHand().getType() == Material.FISHING_ROD || player.getItemInHand().getType() == Material.FLINT_AND_STEEL)) { - player.getServer().getScheduler().runTask(this.getPlugin(), new Runnable() { - @Override - public void run() { - if (player != null && player.isOnline() && player.getItemInHand() != null && (isTool(player.getItemInHand().getType()) || player.getItemInHand().getType() == Material.FISHING_ROD || player.getItemInHand().getType() == Material.FLINT_AND_STEEL)) { - ItemStack item = player.getItemInHand(); - item.setDurability((short) 0); - player.setItemInHand(item); - player.updateInventory(); - } - } - }); - } - } - } - } - } catch (Exception ex) { - ex.printStackTrace(); - } - } catch (Exception ex) { - } - } - - @EventHandler(ignoreCancelled = true) - public void onBlockPlace(BlockPlaceEvent event) { - try { - // Disable block placing - try { - if (this.getPlugin().configValues.banBlockBreakingAndPlacing) { - if (this.getPlugin().configValues.pvpWorlds.contains("All") || this.getPlugin().configValues.pvpWorlds.contains(event.getPlayer().getWorld().getName())) { - if (this.getPlugin().configValues.opBypass) { - if (!event.getPlayer().isOp()) event.setCancelled(true); - } else { - event.setCancelled(true); - } - } - } - } catch (Exception ex) { - ex.printStackTrace(); - } - } catch (Exception ex) { - } - } - - @EventHandler - public void onFoodLevelChange(FoodLevelChangeEvent event) { - try { - // Lock hunger bar - try { - if (this.getPlugin().configValues.lockHunger) { - if (event.getEntity() instanceof Player) { - Player player = (Player) event.getEntity(); - if (this.getPlugin().configValues.pvpWorlds.contains("All") || this.getPlugin().configValues.pvpWorlds.contains(player.getWorld().getName())) - event.setFoodLevel(this.getPlugin().configValues.hungerLock); - } - } - } catch (Exception ex) { - ex.printStackTrace(); - } - } catch (Exception ex) { - } - } - - @EventHandler - public void onPlayerKill(PlayerKilledEvent event) { - try { - // Give killer money - try { - Player killer = event.getPlayer(); - if (this.getPlugin().configValues.vaultValues.useEconomy && this.getPlugin().configValues.vaultValues.useMoneyPerKill) { - if (this.getPlugin().configValues.pvpWorlds.contains("All") || this.getPlugin().configValues.pvpWorlds.contains(killer.getWorld().getName())) { - net.milkbowl.vault.economy.Economy economy = (net.milkbowl.vault.economy.Economy) this.getPlugin().vault.getEconomy(); - if (!economy.hasAccount(killer)) economy.createPlayerAccount(killer); - economy.depositPlayer(killer, this.getPlugin().configValues.vaultValues.moneyPerKill); - killer.sendMessage(this.getPlugin().getMPKMessage(event.getDead(), this.getPlugin().configValues.vaultValues.moneyPerKill)); - } - } - } catch (Exception ex) { - ex.printStackTrace(); - } - - // Update their killstreak - try { - if (this.getPlugin().configValues.killstreaks) { - if (this.getPlugin().configValues.pvpWorlds.contains("All") || this.getPlugin().configValues.pvpWorlds.contains(event.getPlayer().getWorld().getName())) { - if (!this.getPlugin().playerKillstreaks.containsKey(event.getPlayer().getName())) - this.getPlugin().playerKillstreaks.put(event.getPlayer().getName(), 0L); - - long currentKillstreak = this.getPlugin().playerKillstreaks.get(event.getPlayer().getName()); - if (currentKillstreak + 1L > Long.MAX_VALUE - 1) - this.getPlugin().playerKillstreaks.put(event.getPlayer().getName(), 0L); - else - this.getPlugin().playerKillstreaks.put(event.getPlayer().getName(), this.getPlugin().playerKillstreaks.get(event.getPlayer().getName()) + 1L); - - currentKillstreak = this.getPlugin().playerKillstreaks.get(event.getPlayer().getName()); - if (this.getPlugin().getKillstreaksConfig().contains("Killstreak " + currentKillstreak)) { - List killstreakCommands = this.getPlugin().getKillstreaksConfig().getStringList("Killstreak " + currentKillstreak); - for (String killstreakCommand : killstreakCommands) - event.getPlayer().getServer().dispatchCommand(event.getPlayer().getServer().getConsoleSender(), killstreakCommand.replace("", event.getPlayer().getName()).replace("", event.getPlayer().getDisplayName()).replace("", "" + currentKillstreak)); - } - if (PvPKits.hasKit(event.getPlayer())) { - Kit playerKit = PvPKits.getKitByName(PvPKits.getKit(event.getPlayer())); - if (playerKit != null) { - if (playerKit.getKillstreaks().containsKey(currentKillstreak)) { - List killstreakCommands = playerKit.getKillstreaks().get(currentKillstreak); - for (String killstreakCommand : killstreakCommands) - event.getPlayer().getServer().dispatchCommand(event.getPlayer().getServer().getConsoleSender(), killstreakCommand.replace("", event.getPlayer().getName()).replace("", event.getPlayer().getDisplayName()).replace("", "" + currentKillstreak)); - } - } - } - } - } - } catch (Exception ex) { - ex.printStackTrace(); - } - } catch (Exception ex) { - } - } - - @EventHandler(priority = EventPriority.HIGHEST) - public void onPlayerChangeWorld(PlayerChangedWorldEvent event) { - try { - // Remove kit - try { - if (!this.getPlugin().configValues.pvpWorlds.contains("All") && !this.getPlugin().configValues.pvpWorlds.contains(event.getPlayer().getWorld().getName())) { - if (this.getPlugin().playerKits.containsKey(event.getPlayer().getName())) - this.getPlugin().playerKits.remove(event.getPlayer().getName()); - if (this.getPlugin().usingKits.containsKey(event.getPlayer().getName())) { - this.getPlugin().usingKits.remove(event.getPlayer().getName()); - event.getPlayer().setMaxHealth(20D); - if (!this.getPlugin().getServer().getPluginManager().isPluginEnabled(this.getPlugin().configValues.multiInvsPlugin) && !this.getPlugin().configValues.multiInvs) { - event.getPlayer().getInventory().clear(); - event.getPlayer().getInventory().setArmorContents(null); - event.getPlayer().updateInventory(); - } - for (PotionEffect potionEffectOnPlayer : event.getPlayer().getActivePotionEffects()) - event.getPlayer().removePotionEffect(potionEffectOnPlayer.getType()); - } - } else if (this.getPlugin().configValues.pvpWorlds.contains("All") || (!this.getPlugin().configValues.pvpWorlds.contains(event.getFrom().getName()) && this.getPlugin().configValues.pvpWorlds.contains(event.getPlayer().getWorld().getName()))) { - if (!this.getPlugin().getServer().getPluginManager().isPluginEnabled(this.getPlugin().configValues.multiInvsPlugin) && !this.getPlugin().configValues.multiInvs) { - event.getPlayer().getInventory().clear(); - event.getPlayer().getInventory().setArmorContents(null); - event.getPlayer().updateInventory(); - } - for (PotionEffect potionEffectOnPlayer : event.getPlayer().getActivePotionEffects()) - event.getPlayer().removePotionEffect(potionEffectOnPlayer.getType()); - if (this.getPlugin().configValues.listKitsOnJoin) this.listKitsOnJoin(event.getPlayer()); - } - } catch (Exception ex) { - ex.printStackTrace(); - } - } catch (Exception ex) { - } - } - - @EventHandler(ignoreCancelled = true) - public void onPlayerChangeGamemode(PlayerGameModeChangeEvent event) { - try { - // Disable gamemode changing - try { - if (this.getPlugin().configValues.disableGamemode) { - if (event.getNewGameMode() == GameMode.CREATIVE) { - if (!(this.getPlugin().configValues.opBypass && event.getPlayer().isOp())) { - if (this.getPlugin().configValues.pvpWorlds.contains("All") || this.getPlugin().configValues.pvpWorlds.contains(event.getPlayer().getWorld().getName())) - event.setCancelled(true); - } - } - } - } catch (Exception ex) { - ex.printStackTrace(); - } - } catch (Exception ex) { - } - } - - @EventHandler(ignoreCancelled = true) - public void onEntityDamageByEntityEvent(EntityDamageByEntityEvent event) { - try { - // Weapons unbreakable - try { - if (event.getDamager() instanceof Player) { - final Player player = (Player) event.getDamager(); - if (player.getGameMode() == GameMode.SURVIVAL) { - if (player.getItemInHand() != null && this.getPlugin().usingKits.containsKey(player.getName())) { - boolean repair = false; - if ((this.isTool(player.getItemInHand().getType()) || player.getItemInHand().getType() == Material.FISHING_ROD || player.getItemInHand().getType() == Material.FLINT_AND_STEEL)) { - if (this.getPlugin().configValues.disableItemBreaking) { - repair = true; - } else { - Kit kit = PvPKits.getKitByName(this.getPlugin().usingKits.get(player.getName())); - if (kit != null && !kit.canItemsBreak()) { - repair = true; - } - } - } - if (repair) { - player.getServer().getScheduler().runTask(this.getPlugin(), new Runnable() { - @Override - public void run() { - if (player != null && player.isOnline() && getPlugin().usingKits.containsKey(player.getName()) && player.getItemInHand() != null && (isTool(player.getItemInHand().getType()) || player.getItemInHand().getType() == Material.FISHING_ROD || player.getItemInHand().getType() == Material.FLINT_AND_STEEL)) { - ItemStack item = player.getItemInHand(); - item.setDurability((short) 0); - player.setItemInHand(item); - player.updateInventory(); - } - } - }); - } - } - } - } - if (event.getEntity() instanceof Player) { - Player player = (Player) event.getEntity(); - if (player.getGameMode() == GameMode.SURVIVAL) { - if (this.getPlugin().usingKits.containsKey(player.getName())) { - boolean repair = false; - if (this.getPlugin().configValues.disableItemBreaking) { - repair = true; - } else { - Kit kit = PvPKits.getKitByName(this.getPlugin().usingKits.get(player.getName())); - if (kit != null && !kit.canItemsBreak()) { - repair = true; - } - } - if (repair) { - ItemStack[] armour = player.getInventory().getArmorContents(); - for (ItemStack i : armour) - if (i != null && isArmour(i.getType())) i.setDurability((short) 0); - player.getInventory().setArmorContents(armour); - player.updateInventory(); - } - } - } - } - } catch (Exception ex) { - ex.printStackTrace(); - } - } catch (Exception ex) { - } - } - - @EventHandler(ignoreCancelled = true) - public void onBowShoot(EntityShootBowEvent event) { - try { - // Unbreakable bow - try { - if (event.getEntity() instanceof Player) { - Player player = (Player) event.getEntity(); - if (this.getPlugin().usingKits.containsKey(player.getName())) { - boolean repair = false; - if (this.getPlugin().configValues.disableItemBreaking) { - repair = true; - } else { - Kit kit = PvPKits.getKitByName(this.getPlugin().usingKits.get(player.getName())); - if (kit != null && !kit.canItemsBreak()) { - repair = true; - } - } - if (repair) - event.getBow().setDurability((short) 0); - } - } - } catch (Exception ex) { - ex.printStackTrace(); - } - } catch (Exception ex) { - } - } - - @EventHandler(priority = EventPriority.HIGH) - public void onPlayerRunCommand(PlayerCommandPreprocessEvent event) { - try { - // Kit command alias - try { - if (!event.isCancelled()) { - String strCommand = event.getMessage().contains(" ") ? event.getMessage().split(" ")[0].substring(1) : event.getMessage().substring(1); - Kit targetKit = PvPKits.getKitByNameCaseInsensitive(strCommand); - if (targetKit != null && !targetKit.isUserKit() && targetKit.hasAlias()) { - event.setCancelled(true); - event.getPlayer().performCommand("pvpkit " + targetKit.getName()); - } - } - } catch (Exception ex) { - ex.printStackTrace(); - } - } catch (Exception ex) { - } - } - - /** - * Gets the plugin instance * - */ - private KingKits getPlugin() { - return this.plugin; - } - - private void listKitsOnJoin(final Player p) { - p.getServer().getScheduler().runTaskLater(this.getPlugin(), new Runnable() { - public void run() { - if (p != null && p.isOnline()) { - List kitList = getPlugin().getKitList(); - StringBuilder sbKits = new StringBuilder(); - for (int kitPos = 0; kitPos < kitList.size(); kitPos++) { - String kit = kitList.get(kitPos); - ChatColor col = ChatColor.GREEN; - boolean ignoreKit = false; - if (!p.hasPermission("kingkits.kits." + kit.toLowerCase())) { - if (!getPlugin().configValues.kitListPermissionsJoin) ignoreKit = true; - else col = ChatColor.DARK_RED; - } - if (!ignoreKit) { - if (kitPos == kitList.size() - 1) sbKits.append(col).append(kit); - else sbKits.append(col).append(kit).append(", "); - } else { - if (kitPos == kitList.size() - 1) - sbKits = new StringBuilder().append(replaceLast(sbKits.toString(), ",", "")); - } - } - if (sbKits.toString().trim().isEmpty()) - sbKits = new StringBuilder().append(Lang.GEN_NO_KITS_AVAILABLE.getMessage()); - Lang.sendMessage(p, Lang.GEN_KIT_LIST, sbKits.toString()); - } - } - }, 25L); - } - - /** - * Returns if a material is an armour piece - */ - private boolean isArmour(Material material) { - return material.name().endsWith("HELMET") || material.name().endsWith("CHESTPLATE") || material.name().endsWith("LEGGINGS") || material.name().endsWith("BOOTS"); - } - - /** - * Returns if a material is a tool/sword * - */ - private boolean isTool(Material material) { - return material.name().endsWith("SWORD") || material.name().endsWith("PICKAXE") || material.name().endsWith("AXE") || material.name().endsWith("SPADE") || material.name().endsWith("SHOVEL") || material.name().endsWith("HOE"); - } - - /** - * Replaces the last occurrence of a string in a string * - */ - private String replaceLast(String text, String original, String replacement) { - String message = text; - if (message.contains(original)) { - StringBuilder stringBuilder = new StringBuilder(text); - stringBuilder.replace(text.lastIndexOf(original), text.lastIndexOf(original) + 1, replacement); - message = stringBuilder.toString(); - } - return message; - } - - /** - * Returns a string with the real colours * - */ - private String r(String message) { - return Utils.replaceChatColour(message); - } - -} diff --git a/src/main/java/com/faris/kingkits/listeners/event/custom/KingKitsReloadEvent.java b/src/main/java/com/faris/kingkits/listeners/event/custom/KingKitsReloadEvent.java deleted file mode 100644 index 0d4cecb..0000000 --- a/src/main/java/com/faris/kingkits/listeners/event/custom/KingKitsReloadEvent.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.faris.kingkits.listeners.event.custom; - -import org.bukkit.command.CommandSender; -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; - -public class KingKitsReloadEvent extends Event { - private static final HandlerList handlers = new HandlerList(); - - private CommandSender theSender = null; - - private Exception failedException = null; - - /** - * Create a new KingKitsReloadEvent instance. - * - * @param sender - The CommandSender that is reloading the configuration. - */ - public KingKitsReloadEvent(CommandSender sender) { - this.theSender = sender; - } - - /** - * Create a new KingKitsReloadEvent instance. - * - * @param sender - The CommandSender that is reloading the configuration. - * @param failedException - If the reload has not been successful, this will hold the error thrown instance. If successful, this will be null. - */ - public KingKitsReloadEvent(CommandSender sender, Exception failedException) { - this.theSender = sender; - this.failedException = failedException; - } - - /** - * Get the error exception. - * @return The Exception if failed to reload, if succeeded, this will return null. - */ - public Exception getException() { - return this.failedException; - } - - /** - * Returns the player * - */ - public CommandSender getSender() { - return this.theSender; - } - - public HandlerList getHandlers() { - return handlers; - } - - /** - * Check whether or not the reload has been successful. - * @return True if the reload has not been successful, false if it has been successful. - */ - public boolean hasFailed() { - return this.failedException != null; - } - - public static HandlerList getHandlerList() { - return handlers; - } - -} diff --git a/src/main/java/com/faris/kingkits/listeners/event/custom/PlayerCreateKitEvent.java b/src/main/java/com/faris/kingkits/listeners/event/custom/PlayerCreateKitEvent.java deleted file mode 100644 index 35c3971..0000000 --- a/src/main/java/com/faris/kingkits/listeners/event/custom/PlayerCreateKitEvent.java +++ /dev/null @@ -1,131 +0,0 @@ -package com.faris.kingkits.listeners.event.custom; - -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.bukkit.event.player.PlayerEvent; -import org.bukkit.inventory.ItemStack; - -import java.util.*; - -public class PlayerCreateKitEvent extends PlayerEvent implements Cancellable { - private static final HandlerList handlers = new HandlerList(); - - private String kitName = ""; - private Map kitContents = new HashMap(); - private List armourContents = new ArrayList(); - - private boolean isCancelled = false; - private boolean isUserKit = false; - - /** - * Create a new PlayerCreateKitEvent instance. - * - * @param player - The player. - * @param kitName - The new kit. - * @param newKitItems - The kit items. - * @param isUserKit - Whether the kit is a private user kit or not. - */ - public PlayerCreateKitEvent(Player player, String kitName, final List newKitItems, List armourContents, boolean isUserKit) { - this(player, kitName, new HashMap() { - { - for (int i = 0; i < newKitItems.size(); i++) { - this.put(i, newKitItems.get(i)); - } - } - }, armourContents, isUserKit); - - } - - /** - * Create a new PlayerCreateKitEvent instance. - * - * @param player - The player. - * @param kitName - The new kit. - * @param newKitItems - The kit items. - * @param isUserKit - Whether the kit is a private user kit or not. - */ - public PlayerCreateKitEvent(Player player, String kitName, Map newKitItems, List armourContents, boolean isUserKit) { - super(player); - this.kitName = kitName; - this.kitContents = newKitItems; - this.armourContents = armourContents; - this.isUserKit = isUserKit; - } - - /** - * Returns the kit's name * - */ - public String getKit() { - return this.kitName; - } - - /** - * Returns an unmodifiable List of armour in the new kit * - */ - public List getKitArmour() { - return Collections.unmodifiableList(this.armourContents); - } - - /** - * Returns an unmodifiable List of items in the new kit * - */ - public List getKitContents() { - return new ArrayList(this.kitContents.values()); - } - - public Map getKitContentsWithSlots() { - return Collections.unmodifiableMap(this.kitContents); - } - - public boolean isUserKit() { - return this.isUserKit; - } - - /** - * Set the item contents of the new kit * - */ - public void setArmourContents(List armourContents) { - if (armourContents != null) this.armourContents = armourContents; - } - - /** - * Set the item contents of the new kit * - */ - public void setKitContents(List kitContents) { - if (kitContents != null) { - this.kitContents = new HashMap(); - for (int i = 0; i < kitContents.size(); i++) { - ItemStack kitContent = kitContents.get(i); - this.kitContents.put(i, kitContent == null ? new ItemStack(Material.AIR) : kitContent); - } - } - } - - /** - * Set the item contents of the new kit * - */ - public void setKitContents(Map kitContents) { - if (kitContents != null) this.kitContents = kitContents; - } - - public HandlerList getHandlers() { - return handlers; - } - - public static HandlerList getHandlerList() { - return handlers; - } - - @Override - public boolean isCancelled() { - return this.isCancelled; - } - - @Override - public void setCancelled(boolean flag) { - this.isCancelled = flag; - } - -} diff --git a/src/main/java/com/faris/kingkits/listeners/event/custom/PlayerKitEvent.java b/src/main/java/com/faris/kingkits/listeners/event/custom/PlayerKitEvent.java deleted file mode 100644 index ce5cd70..0000000 --- a/src/main/java/com/faris/kingkits/listeners/event/custom/PlayerKitEvent.java +++ /dev/null @@ -1,187 +0,0 @@ -package com.faris.kingkits.listeners.event.custom; - -import org.bukkit.entity.Player; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.bukkit.event.player.PlayerEvent; -import org.bukkit.inventory.ItemStack; -import org.bukkit.potion.PotionEffect; - -import java.util.*; - -public class PlayerKitEvent extends PlayerEvent implements Cancellable { - private static final HandlerList handlers = new HandlerList(); - - private String kitName = ""; - private String oldKit = ""; - private Map kitContents = new HashMap(); - private List armourItems = new ArrayList(); - private List potionEffects = new ArrayList(); - private List kitCommands = new ArrayList(); - - private boolean isCancelled = false; - - /** - * Create a new PlayerKitEvent instance. - * - * @param player - The player. - * @param kitName - The new kit. - */ - public PlayerKitEvent(Player player, String kitName) { - super(player); - this.kitName = kitName; - } - - /** - * Create a new PlayerKitEvent instance. - * - * @param player - The player. - * @param kitName - The new kit. - * @param oldKit - The previous kit the player was. - */ - public PlayerKitEvent(Player player, String kitName, String oldKit) { - super(player); - this.kitName = kitName; - this.oldKit = oldKit; - } - - /** - * Create a new PlayerKitEvent instance. - * - * @param player - The player. - * @param kitName - The new kit. - * @param oldKit - The previous kit the player was. - * @param newKitItems - The kit items. - * @param armourItems - The kit's armour items. - */ - public PlayerKitEvent(Player player, String kitName, String oldKit, Map newKitItems, List armourItems) { - super(player); - this.kitName = kitName; - this.oldKit = oldKit; - this.kitContents = newKitItems; - this.armourItems = armourItems; - } - - /** - * Create a new PlayerKitEvent instance. - * - * @param player - The player. - * @param kitName - The new kit. - * @param oldKit - The previous kit the player was. - * @param newKitItems - The kit items. - * @param armourItems - The kit's armour items. - */ - public PlayerKitEvent(Player player, String kitName, String oldKit, Map newKitItems, List armourItems, List potionEffects) { - super(player); - this.kitName = kitName; - this.oldKit = oldKit; - this.kitContents = newKitItems; - this.armourItems = armourItems; - this.potionEffects = potionEffects; - } - - /** - * @return An unmodifiable List of all the kit-specific-commands run. - */ - public List getCommands() { - return Collections.unmodifiableList(this.kitCommands); - } - - /** - * @return The kit's name. - */ - public String getKit() { - return this.kitName; - } - - /** - * @return An unmodifiable List of the armour items in the kit. - */ - public List getKitArmour() { - return Collections.unmodifiableList(this.armourItems); - } - - /** - * @return An unmodifiable List of items in the kit. - */ - public List getKitContents() { - return new ArrayList(this.kitContents.values()); - } - - /** - * @return An unmodifiable Map of items in the kit with their slots. - */ - public Map getKitContentsWithSlots() { - return Collections.unmodifiableMap(this.kitContents); - } - - /** - * @return An unmodifiable List of all the potion effects. - */ - public List getPotionEffects() { - return Collections.unmodifiableList(this.potionEffects); - } - - /** - * @return The player's old kit name. - */ - public String getOldKit() { - return this.oldKit; - } - - public void setCommands(List commands) { - this.kitCommands = commands != null ? commands : new ArrayList(); - } - - /** - * Set the armour contents in the kit * - */ - public void setKitArmour(List armourContents) { - this.armourItems = armourContents != null ? armourContents : new ArrayList(); - } - - /** - * Set the item contents of the kit * - */ - public void setKitContents(List kitContents) { - this.kitContents = new HashMap(); - if (kitContents != null) { - for (int i = 0; i < kitContents.size(); i++) { - ItemStack kitContent = kitContents.get(i); - if (kitContent != null) this.kitContents.put(i, kitContent); - } - } - } - - /** - * Set the item contents of the kit * - */ - public void setKitContents(Map kitContents) { - this.kitContents = kitContents != null ? kitContents : new HashMap(); - } - - /** - * Set the potion effects gained when using the kit * - */ - public void setPotionEffects(List potionEffects) { - this.potionEffects = potionEffects != null ? potionEffects : new ArrayList(); - } - - public HandlerList getHandlers() { - return handlers; - } - - public static HandlerList getHandlerList() { - return handlers; - } - - @Override - public boolean isCancelled() { - return this.isCancelled; - } - - @Override - public void setCancelled(boolean flag) { - this.isCancelled = flag; - } -} diff --git a/src/main/java/com/faris/kingkits/sql/KingKitsSQL.java b/src/main/java/com/faris/kingkits/sql/KingKitsSQL.java deleted file mode 100644 index 478a0e9..0000000 --- a/src/main/java/com/faris/kingkits/sql/KingKitsSQL.java +++ /dev/null @@ -1,122 +0,0 @@ -package com.faris.kingkits.sql; - -import org.bukkit.entity.Player; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.PreparedStatement; -import java.sql.ResultSet; - -/** - * @author KingFaris10 - */ -public class KingKitsSQL { - private static Connection connection; - public static boolean sqlEnabled = false; - - private static String sqlHost = null, sqlUsername = null, sqlPassword = null, sqlDatabase = null, sqlTablePrefix = "kk_"; - private static int sqlPort = -1; - - public KingKitsSQL(String sqlHost, int sqlPort, String sqlUsername, String sqlPassword, String sqlDatabase, String sqlTablePrefix) { - KingKitsSQL.sqlHost = sqlHost; - KingKitsSQL.sqlPort = sqlPort; - KingKitsSQL.sqlUsername = sqlUsername; - KingKitsSQL.sqlPassword = sqlPassword; - KingKitsSQL.sqlDatabase = sqlDatabase; - KingKitsSQL.sqlTablePrefix = sqlTablePrefix; - } - - public void onDisable() { - try { - if (connection != null && !connection.isClosed()) connection.close(); - } catch (Exception ex) { - ex.printStackTrace(); - } - connection = null; - } - - public static boolean isInitialised() { - return sqlHost != null && sqlPort != -1 && sqlDatabase != null && sqlUsername != null && sqlPassword != null; - } - - public static boolean isOpen() { - try { - return connection != null && !connection.isClosed(); - } catch (Exception ex) { - ex.printStackTrace(); - return connection != null; - } - } - - public synchronized static void openConnection() { - try { - if (isInitialised() && sqlEnabled) - connection = DriverManager.getConnection("jdbc:mysql://" + sqlHost + ":" + sqlPort + "/" + sqlDatabase, sqlUsername, sqlPassword); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - public synchronized static void closeConnection() { - try { - if (connection != null) connection.close(); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - private synchronized static void createDefaultTable(String table) throws Exception { - try { - PreparedStatement createSql = connection.prepareStatement("CREATE TABLE IF NOT EXISTS " + sqlDatabase + "." + table + " (uuid varchar(36), score int(11));"); - createSql.execute(); - createSql.close(); - } catch (Exception ex) { - throw ex; - } - } - - private synchronized static boolean tableContainsPlayer(Player player, String table) { - try { - if (isInitialised() && player != null) { - PreparedStatement searchSql = connection.prepareStatement("SELECT * FROM `" + table + "` WHERE uuid=?;"); - searchSql.setString(1, player.getUniqueId().toString()); - - ResultSet searchResult = searchSql.executeQuery(); - boolean containsPlayer = searchResult.next(); - searchSql.close(); - searchResult.close(); - - return containsPlayer; - } - } catch (Exception ex) { - ex.printStackTrace(); - } - return false; - } - - public static void setScore(Player player, int score) { - if (sqlEnabled && isInitialised() && player != null) { - try { - openConnection(); - createDefaultTable((sqlTablePrefix + "score")); - if (tableContainsPlayer(player, (sqlTablePrefix + "score"))) { - PreparedStatement scoreSql = connection.prepareStatement("UPDATE `" + (sqlTablePrefix + "score") + "` SET score=? WHERE uuid=?;"); - scoreSql.setInt(1, score); - scoreSql.setString(2, player.getUniqueId().toString()); - scoreSql.executeUpdate(); - scoreSql.close(); - } else { - PreparedStatement scoreSql = connection.prepareStatement("INSERT INTO `" + (sqlTablePrefix + "score") + "` values(?," + score + ");"); - scoreSql.setString(1, player.getUniqueId().toString()); - scoreSql.execute(); - scoreSql.close(); - } - } catch (Exception ex) { - ex.printStackTrace(); - } finally { - closeConnection(); - } - } - } - -} diff --git a/src/main/java/com/faris/kingkits/updater/BukkitUpdater.java b/src/main/java/com/faris/kingkits/updater/BukkitUpdater.java index 263f542..e0df341 100644 --- a/src/main/java/com/faris/kingkits/updater/BukkitUpdater.java +++ b/src/main/java/com/faris/kingkits/updater/BukkitUpdater.java @@ -1,8 +1,8 @@ package com.faris.kingkits.updater; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.plugin.Plugin; -import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.configuration.file.*; +import org.bukkit.plugin.*; +import org.bukkit.scheduler.*; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; @@ -18,16 +18,6 @@ /** * Check dev.bukkit.org to find updates for a given plugin, and download the updates if needed. - *

- * VERY, VERY IMPORTANT: Because there are no standards for adding auto-update toggles in your plugin's config, this system provides NO CHECK WITH YOUR CONFIG to make sure the user has allowed auto-updating. - *
- * It is a BUKKIT POLICY that you include a boolean value in your config that prevents the auto-updater from running AT ALL. - *
- * If you fail to include this option in your config, your plugin will be REJECTED when you attempt to submit it to dev.bukkit.org. - *

- * An example of a good configuration option would be something similar to 'auto-update: true' - if this value is set to false you may NOT run the auto-updater. - *
- * If you are unsure about these rules, please read the plugin submission guidelines: http://goo.gl/8iU5l * * @author Gravity * @version 2.3 @@ -37,730 +27,730 @@ public class BukkitUpdater { /* Constants */ - // Remote file's title - private static final String TITLE_VALUE = "name"; - // Remote file's download link - private static final String LINK_VALUE = "downloadUrl"; - // Remote file's release type - private static final String TYPE_VALUE = "releaseType"; - // Remote file's build version - private static final String VERSION_VALUE = "gameVersion"; - // Path to GET - private static final String QUERY = "/servermods/files?projectIds="; - // Slugs will be appended to this to get to the project's RSS feed - private static final String HOST = "https://api.curseforge.com"; - // User-agent when querying Curse - private static final String USER_AGENT = "Updater (by Gravity)"; - // Used for locating version numbers in file names - private static final String DELIMETER = "^v|[\\s_-]v"; - // If the version number contains one of these, don't update. - private static final String[] NO_UPDATE_TAG = {"-DEV", "-PRE", "-SNAPSHOT"}; - // If the file name contains one of these, don't update. - private static final String[] NO_UPDATE_NAME = {"Special"}; - // Used for downloading files - private static final int BYTE_SIZE = 1024; - // Config key for api key - private static final String API_KEY_CONFIG_KEY = "api-key"; - // Config key for disabling Updater - private static final String DISABLE_CONFIG_KEY = "disable"; - // Default api key value in config - private static final String API_KEY_DEFAULT = "PUT_API_KEY_HERE"; - // Default disable value in config - private static final boolean DISABLE_DEFAULT = false; + // Remote file's title + private static final String TITLE_VALUE = "name"; + // Remote file's download link + private static final String LINK_VALUE = "downloadUrl"; + // Remote file's release type + private static final String TYPE_VALUE = "releaseType"; + // Remote file's build version + private static final String VERSION_VALUE = "gameVersion"; + // Path to GET + private static final String QUERY = "/servermods/files?projectIds="; + // Slugs will be appended to this to get to the project's RSS feed + private static final String HOST = "https://api.curseforge.com"; + // User-agent when querying Curse + private static final String USER_AGENT = "Updater (by Gravity)"; + // Used for locating version numbers in file names + private static final String DELIMETER = "^v|[\\s_-]v"; + // If the version number contains one of these, don't update. + private static final String[] NO_UPDATE_TAG = {"-DEV", "-PRE", "-SNAPSHOT"}; + // If the file name contains one of these, don't update. + private static final String[] NO_UPDATE_NAME = {"Special"}; + // Used for downloading files + private static final int BYTE_SIZE = 1024; + // Config key for api key + private static final String API_KEY_CONFIG_KEY = "api-key"; + // Config key for disabling Updater + private static final String DISABLE_CONFIG_KEY = "disable"; + // Default api key value in config + private static final String API_KEY_DEFAULT = "PUT_API_KEY_HERE"; + // Default disable value in config + private static final boolean DISABLE_DEFAULT = false; /* User-provided variables */ - // Plugin running Updater - private final Plugin plugin; - // Type of update check to run - private final UpdateType type; - // Whether to announce file downloads - private final boolean announce; - // The plugin file (jar) - private final File file; - // The folder that downloads will be placed in - private final File updateFolder; - // The provided callback (if any) - private final UpdateCallback callback; - // Project's Curse ID - private int id = -1; - // BukkitDev ServerMods API key - private String apiKey = null; + // Plugin running Updater + private final Plugin plugin; + // Type of update check to run + private final UpdateType type; + // Whether to announce file downloads + private final boolean announce; + // The plugin file (jar) + private final File file; + // The folder that downloads will be placed in + private final File updateFolder; + // The provided callback (if any) + private final UpdateCallback callback; + // Project's Curse ID + private int id = -1; + // BukkitDev ServerMods API key + private String apiKey = null; /* Collected from Curse API */ - private String versionName; - private String versionLink; - private String versionType; - private String versionGameVersion; + private String versionName; + private String versionLink; + private String versionType; + private String versionGameVersion; /* Update process variables */ - // Connection to RSS - private URL url; - // Updater thread - private Thread thread; - // Used for determining the outcome of the update process - private BukkitUpdater.UpdateResult result = BukkitUpdater.UpdateResult.SUCCESS; - - /** - * Gives the developer the result of the update process. Can be obtained by called {@link #getResult()} - */ - public enum UpdateResult { - /** - * The updater found an update, and has readied it to be loaded the next time the server restarts/reloads. - */ - SUCCESS, - /** - * The updater did not find an update, and nothing was downloaded. - */ - NO_UPDATE, - /** - * The server administrator has disabled the updating system. - */ - DISABLED, - /** - * The updater found an update, but was unable to download it. - */ - FAIL_DOWNLOAD, - /** - * For some reason, the updater was unable to contact dev.bukkit.org to download the file. - */ - FAIL_DBO, - /** - * When running the version check, the file on DBO did not contain a recognizable version. - */ - FAIL_NOVERSION, - /** - * The id provided by the plugin running the updater was invalid and doesn't exist on DBO. - */ - FAIL_BADID, - /** - * The server administrator has improperly configured their API key in the configuration. - */ - FAIL_APIKEY, - /** - * The updater found an update, but because of the UpdateType being set to NO_DOWNLOAD, it wasn't downloaded. - */ - UPDATE_AVAILABLE - } - - /** - * Allows the developer to specify the type of update that will be run. - */ - public enum UpdateType { - /** - * Run a version check, and then if the file is out of date, download the newest version. - */ - DEFAULT, - /** - * Don't run a version check, just find the latest update and download it. - */ - NO_VERSION_CHECK, - /** - * Get information about the version and the download size, but don't actually download anything. - */ - NO_DOWNLOAD - } - - /** - * Represents the various release types of a file on BukkitDev. - */ - public enum ReleaseType { - /** - * An "alpha" file. - */ - ALPHA, - /** - * A "beta" file. - */ - BETA, - /** - * A "release" file. - */ - RELEASE - } - - /** - * Initialize the updater. - * - * @param plugin The plugin that is checking for an update. - * @param id The dev.bukkit.org id of the project. - * @param file The file that the plugin is running from, get this by doing this.getFile() from within your main class. - * @param type Specify the type of update this will be. See {@link UpdateType} - * @param announce True if the program should announce the progress of new updates in console. - */ - public BukkitUpdater(Plugin plugin, int id, File file, UpdateType type, boolean announce) { - this(plugin, id, file, type, null, announce); - } - - /** - * Initialize the updater with the provided callback. - * - * @param plugin The plugin that is checking for an update. - * @param id The dev.bukkit.org id of the project. - * @param file The file that the plugin is running from, get this by doing this.getFile() from within your main class. - * @param type Specify the type of update this will be. See {@link UpdateType} - * @param callback The callback instance to notify when the Updater has finished - */ - public BukkitUpdater(Plugin plugin, int id, File file, UpdateType type, UpdateCallback callback) { - this(plugin, id, file, type, callback, false); - } - - /** - * Initialize the updater with the provided callback. - * - * @param plugin The plugin that is checking for an update. - * @param id The dev.bukkit.org id of the project. - * @param file The file that the plugin is running from, get this by doing this.getFile() from within your main class. - * @param type Specify the type of update this will be. See {@link UpdateType} - * @param callback The callback instance to notify when the Updater has finished - * @param announce True if the program should announce the progress of new updates in console. - */ - public BukkitUpdater(Plugin plugin, int id, File file, UpdateType type, UpdateCallback callback, boolean announce) { - this.plugin = plugin; - this.type = type; - this.announce = announce; - this.file = file; - this.id = id; - this.updateFolder = this.plugin.getServer().getUpdateFolderFile(); - this.callback = callback; - - final File pluginFile = this.plugin.getDataFolder().getParentFile(); - final File updaterFile = new File(pluginFile, "Updater"); - final File updaterConfigFile = new File(updaterFile, "config.yml"); - - YamlConfiguration config = new YamlConfiguration(); - config.options().header("This configuration file affects all plugins using the Updater system (version 2+ - http://forums.bukkit.org/threads/96681/ )" + '\n' - + "If you wish to use your API key, read http://wiki.bukkit.org/ServerMods_API and place it below." + '\n' - + "Some updating systems will not adhere to the disabled value, but these may be turned off in their plugin's configuration."); - config.addDefault(API_KEY_CONFIG_KEY, API_KEY_DEFAULT); - config.addDefault(DISABLE_CONFIG_KEY, DISABLE_DEFAULT); - - if (!updaterFile.exists()) { - this.fileIOOrError(updaterFile, updaterFile.mkdir(), true); - } - - boolean createFile = !updaterConfigFile.exists(); - try { - if (createFile) { - this.fileIOOrError(updaterConfigFile, updaterConfigFile.createNewFile(), true); - config.options().copyDefaults(true); - config.save(updaterConfigFile); - } else { - config.load(updaterConfigFile); - } - } catch (final Exception e) { - final String message; - if (createFile) { - message = "The updater could not create configuration at " + updaterFile.getAbsolutePath(); - } else { - message = "The updater could not load configuration at " + updaterFile.getAbsolutePath(); - } - this.plugin.getLogger().log(Level.SEVERE, message, e); - } - - if (config.getBoolean(DISABLE_CONFIG_KEY)) { - this.result = UpdateResult.DISABLED; - return; - } - - String key = config.getString(API_KEY_CONFIG_KEY); - if (API_KEY_DEFAULT.equalsIgnoreCase(key) || "".equals(key)) { - key = null; - } - - this.apiKey = key; - - try { - this.url = new URL(BukkitUpdater.HOST + BukkitUpdater.QUERY + this.id); - } catch (final MalformedURLException e) { - this.plugin.getLogger().log(Level.SEVERE, "The project ID provided for updating, " + this.id + " is invalid.", e); - this.result = UpdateResult.FAIL_BADID; - } - - if (this.result != UpdateResult.FAIL_BADID) { - this.thread = new Thread(new UpdateRunnable()); - this.thread.start(); - } else { - runUpdater(); - } - } - - /** - * Get the result of the update process. - * - * @return result of the update process. - * @see UpdateResult - */ - public BukkitUpdater.UpdateResult getResult() { - this.waitForThread(); - return this.result; - } - - /** - * Get the latest version's release type. - * - * @return latest version's release type. - * @see ReleaseType - */ - public ReleaseType getLatestType() { - this.waitForThread(); - if (this.versionType != null) { - for (ReleaseType type : ReleaseType.values()) { - if (this.versionType.equalsIgnoreCase(type.name())) { - return type; - } - } - } - return null; - } - - /** - * Get the latest version's game version (such as "CB 1.2.5-R1.0"). - * - * @return latest version's game version. - */ - public String getLatestGameVersion() { - this.waitForThread(); - return this.versionGameVersion; - } - - /** - * Get the latest version's name (such as "Project v1.0"). - * - * @return latest version's name. - */ - public String getLatestName() { - this.waitForThread(); - return this.versionName; - } - - /** - * Get the latest version's direct file link. - * - * @return latest version's file link. - */ - public String getLatestFileLink() { - this.waitForThread(); - return this.versionLink; - } - - /** - * As the result of Updater output depends on the thread's completion, it is necessary to wait for the thread to finish - * before allowing anyone to check the result. - */ - private void waitForThread() { - if ((this.thread != null) && this.thread.isAlive()) { - try { - this.thread.join(); - } catch (final InterruptedException e) { - this.plugin.getLogger().log(Level.SEVERE, null, e); - } - } - } - - /** - * Save an update from dev.bukkit.org into the server's update folder. - * - * @param file the name of the file to save it as. - */ - private void saveFile(String file) { - final File folder = this.updateFolder; - - deleteOldFiles(); - if (!folder.exists()) { - this.fileIOOrError(folder, folder.mkdir(), true); - } - downloadFile(); - - // Check to see if it's a zip file, if it is, unzip it. - final File dFile = new File(folder.getAbsolutePath(), file); - if (dFile.getName().endsWith(".zip")) { - // Unzip - this.unzip(dFile.getAbsolutePath()); - } - if (this.announce) { - this.plugin.getLogger().info("Finished updating."); - } - } - - /** - * Download a file and save it to the specified folder. - */ - private void downloadFile() { - BufferedInputStream in = null; - FileOutputStream fout = null; - try { - URL fileUrl = new URL(this.versionLink); - final int fileLength = fileUrl.openConnection().getContentLength(); - in = new BufferedInputStream(fileUrl.openStream()); - fout = new FileOutputStream(new File(this.updateFolder, file.getName())); - - final byte[] data = new byte[BukkitUpdater.BYTE_SIZE]; - int count; - if (this.announce) { - this.plugin.getLogger().info("About to download a new update: " + this.versionName); - } - long downloaded = 0; - while ((count = in.read(data, 0, BukkitUpdater.BYTE_SIZE)) != -1) { - downloaded += count; - fout.write(data, 0, count); - final int percent = (int) ((downloaded * 100) / fileLength); - if (this.announce && ((percent % 10) == 0)) { - this.plugin.getLogger().info("Downloading update: " + percent + "% of " + fileLength + " bytes."); - } - } - } catch (Exception ex) { - this.plugin.getLogger().log(Level.WARNING, "The auto-updater tried to download a new update, but was unsuccessful.", ex); - this.result = BukkitUpdater.UpdateResult.FAIL_DOWNLOAD; - } finally { - try { - if (in != null) { - in.close(); - } - } catch (final IOException ex) { - this.plugin.getLogger().log(Level.SEVERE, null, ex); - } - try { - if (fout != null) { - fout.close(); - } - } catch (final IOException ex) { - this.plugin.getLogger().log(Level.SEVERE, null, ex); - } - } - } - - /** - * Remove possibly leftover files from the update folder. - */ - private void deleteOldFiles() { - //Just a quick check to make sure we didn't leave any files from last time... - File[] list = listFilesOrError(this.updateFolder); - for (final File xFile : list) { - if (xFile.getName().endsWith(".zip")) { - this.fileIOOrError(xFile, xFile.mkdir(), true); - } - } - } - - /** - * Part of Zip-File-Extractor, modified by Gravity for use with Updater. - * - * @param file the location of the file to extract. - */ - private void unzip(String file) { - final File fSourceZip = new File(file); - try { - final String zipPath = file.substring(0, file.length() - 4); - ZipFile zipFile = new ZipFile(fSourceZip); - Enumeration e = zipFile.entries(); - while (e.hasMoreElements()) { - ZipEntry entry = e.nextElement(); - File destinationFilePath = new File(zipPath, entry.getName()); - this.fileIOOrError(destinationFilePath.getParentFile(), destinationFilePath.getParentFile().mkdirs(), true); - if (!entry.isDirectory()) { - final BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry)); - int b; - final byte[] buffer = new byte[BukkitUpdater.BYTE_SIZE]; - final FileOutputStream fos = new FileOutputStream(destinationFilePath); - final BufferedOutputStream bos = new BufferedOutputStream(fos, BukkitUpdater.BYTE_SIZE); - while ((b = bis.read(buffer, 0, BukkitUpdater.BYTE_SIZE)) != -1) { - bos.write(buffer, 0, b); - } - bos.flush(); - bos.close(); - bis.close(); - final String name = destinationFilePath.getName(); - if (name.endsWith(".jar") && this.pluginExists(name)) { - File output = new File(this.updateFolder, name); - this.fileIOOrError(output, destinationFilePath.renameTo(output), true); - } - } - } - zipFile.close(); - - // Move any plugin data folders that were included to the right place, Bukkit won't do this for us. - moveNewZipFiles(zipPath); - - } catch (final IOException e) { - this.plugin.getLogger().log(Level.SEVERE, "The auto-updater tried to unzip a new update file, but was unsuccessful.", e); - this.result = BukkitUpdater.UpdateResult.FAIL_DOWNLOAD; - } finally { - this.fileIOOrError(fSourceZip, fSourceZip.delete(), false); - } - } - - /** - * Find any new files extracted from an update into the plugin's data directory. - * - * @param zipPath path of extracted files. - */ - private void moveNewZipFiles(String zipPath) { - File[] list = listFilesOrError(new File(zipPath)); - for (final File dFile : list) { - if (dFile.isDirectory() && this.pluginExists(dFile.getName())) { - // Current dir - final File oFile = new File(this.plugin.getDataFolder().getParent(), dFile.getName()); - // List of existing files in the new dir - final File[] dList = listFilesOrError(dFile); - // List of existing files in the current dir - final File[] oList = listFilesOrError(oFile); - for (File cFile : dList) { - // Loop through all the files in the new dir - boolean found = false; - for (final File xFile : oList) { - // Loop through all the contents in the current dir to see if it exists - if (xFile.getName().equals(cFile.getName())) { - found = true; - break; - } - } - if (!found) { - // Move the new file into the current dir - File output = new File(oFile, cFile.getName()); - this.fileIOOrError(output, cFile.renameTo(output), true); - } else { - // This file already exists, so we don't need it anymore. - this.fileIOOrError(cFile, cFile.delete(), false); - } - } - } - this.fileIOOrError(dFile, dFile.delete(), false); - } - File zip = new File(zipPath); - this.fileIOOrError(zip, zip.delete(), false); - } - - /** - * Check if the name of a jar is one of the plugins currently installed, used for extracting the correct files out of a zip. - * - * @param name a name to check for inside the plugins folder. - * @return true if a file inside the plugins folder is named this. - */ - private boolean pluginExists(String name) { - File[] plugins = listFilesOrError(new File("plugins")); - for (final File file : plugins) { - if (file.getName().equals(name)) { - return true; - } - } - return false; - } - - /** - * Check to see if the program should continue by evaluating whether the plugin is already updated, or shouldn't be updated. - * - * @return true if the version was located and is not the same as the remote's newest. - */ - private boolean versionCheck() { - final String title = this.versionName; - if (this.type != UpdateType.NO_VERSION_CHECK) { - final String localVersion = this.plugin.getDescription().getVersion(); - if (title.split(DELIMETER).length == 2) { - // Get the newest file's version number - final String remoteVersion = title.split(DELIMETER)[1].split(" ")[0]; - - if (this.hasTag(localVersion) || this.hasName(title) || !this.shouldUpdate(localVersion, remoteVersion)) { - // We already have the latest version, or this build is tagged for no-update - this.result = BukkitUpdater.UpdateResult.NO_UPDATE; - return false; - } - } else { - // The file's name did not contain the string 'vVersion' - final String authorInfo = this.plugin.getDescription().getAuthors().isEmpty() ? "" : " (" + this.plugin.getDescription().getAuthors().get(0) + ")"; - this.plugin.getLogger().warning("The author of this plugin" + authorInfo + " has misconfigured their Auto Update system"); - this.plugin.getLogger().warning("File versions should follow the format 'PluginName vVERSION'"); - this.plugin.getLogger().warning("Please notify the author of this error."); - this.result = BukkitUpdater.UpdateResult.FAIL_NOVERSION; - return false; - } - } - return true; - } - - /** - * If you wish to run mathematical versioning checks, edit this method. - *

- * With default behavior, Updater will NOT verify that a remote version available on BukkitDev - * which is not this version is indeed an "update". - * If a version is present on BukkitDev that is not the version that is currently running, - * Updater will assume that it is a newer version. - * This is because there is no standard versioning scheme, and creating a calculation that can - * determine whether a new update is actually an update is sometimes extremely complicated. - *

- *

- * Updater will call this method from {@link #versionCheck()} before deciding whether - * the remote version is actually an update. - * If you have a specific versioning scheme with which a mathematical determination can - * be reliably made to decide whether one version is higher than another, you may - * revise this method, using the local and remote version parameters, to execute the - * appropriate check. - *

- *

- * Returning a value of false will tell the update process that this is NOT a new version. - * Without revision, this method will always consider a remote version at all different from - * that of the local version a new update. - *

- * - * @param localVersion the current version - * @param remoteVersion the remote version - * @return true if Updater should consider the remote version an update, false if not. - */ - public boolean shouldUpdate(String localVersion, String remoteVersion) { - return !localVersion.equalsIgnoreCase(remoteVersion); - } - - /** - * Evaluate whether the plugin name is marked showing that it should not be updated by this program. - * - * @param name a version number to check for tags in. - * @return true if updating should be disabled. - */ - private boolean hasName(String name) { - for (final String string : BukkitUpdater.NO_UPDATE_NAME) { - if (name.contains(string)) { - return true; - } - } - return false; - } - - /** - * Evaluate whether the version number is marked showing that it should not be updated by this program. - * - * @param version a version number to check for tags in. - * @return true if updating should be disabled. - */ - private boolean hasTag(String version) { - for (final String string : BukkitUpdater.NO_UPDATE_TAG) { - if (version.contains(string)) { - return true; - } - } - return false; - } - - /** - * Make a connection to the BukkitDev API and request the newest file's details. - * - * @return true if successful. - */ - private boolean read() { - try { - final URLConnection conn = this.url.openConnection(); - conn.setConnectTimeout(5000); - - if (this.apiKey != null) { - conn.addRequestProperty("X-API-Key", this.apiKey); - } - conn.addRequestProperty("User-Agent", BukkitUpdater.USER_AGENT); - - conn.setDoOutput(true); - - final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); - final String response = reader.readLine(); - - final JSONArray array = (JSONArray) JSONValue.parse(response); - - if (array.isEmpty()) { - this.plugin.getLogger().warning("The updater could not find any files for the project id " + this.id); - this.result = UpdateResult.FAIL_BADID; - return false; - } - - JSONObject latestUpdate = (JSONObject) array.get(array.size() - 1); - this.versionName = (String) latestUpdate.get(BukkitUpdater.TITLE_VALUE); - this.versionLink = (String) latestUpdate.get(BukkitUpdater.LINK_VALUE); - this.versionType = (String) latestUpdate.get(BukkitUpdater.TYPE_VALUE); - this.versionGameVersion = (String) latestUpdate.get(BukkitUpdater.VERSION_VALUE); - - return true; - } catch (final IOException e) { - if (e.getMessage().contains("HTTP response code: 403")) { - this.plugin.getLogger().severe("dev.bukkit.org rejected the API key provided in plugins/Updater/config.yml"); - this.plugin.getLogger().severe("Please double-check your configuration to ensure it is correct."); - this.result = UpdateResult.FAIL_APIKEY; - } else { - this.plugin.getLogger().severe("The updater could not contact dev.bukkit.org for updating."); - this.plugin.getLogger().severe("If you have not recently modified your configuration and this is the first time you are seeing this message, the site may be experiencing temporary downtime."); - this.result = UpdateResult.FAIL_DBO; - } - this.plugin.getLogger().log(Level.SEVERE, null, e); - return false; - } - } - - /** - * Perform a file operation and log any errors if it fails. - * - * @param file file operation is performed on. - * @param result result of file operation. - * @param create true if a file is being created, false if deleted. - */ - private void fileIOOrError(File file, boolean result, boolean create) { - if (!result) { - this.plugin.getLogger().severe("The updater could not " + (create ? "create" : "delete") + " file at: " + file.getAbsolutePath()); - } - } - - private File[] listFilesOrError(File folder) { - File[] contents = folder.listFiles(); - if (contents == null) { - this.plugin.getLogger().severe("The updater could not access files at: " + this.updateFolder.getAbsolutePath()); - return new File[0]; - } else { - return contents; - } - } - - /** - * Called on main thread when the Updater has finished working, regardless - * of result. - */ - public interface UpdateCallback { - /** - * Called when the updater has finished working. - * - * @param updater The updater instance - */ - void onFinish(BukkitUpdater updater); - } - - private class UpdateRunnable implements Runnable { - @Override - public void run() { - runUpdater(); - } - } - - private void runUpdater() { - if (this.url != null && (this.read() && this.versionCheck())) { - // Obtain the results of the project's file feed - if ((this.versionLink != null) && (this.type != UpdateType.NO_DOWNLOAD)) { - String name = this.file.getName(); - // If it's a zip file, it shouldn't be downloaded as the plugin's name - if (this.versionLink.endsWith(".zip")) { - name = this.versionLink.substring(this.versionLink.lastIndexOf("/") + 1); - } - this.saveFile(name); - } else { - this.result = UpdateResult.UPDATE_AVAILABLE; - } - } - - if (this.callback != null) { - new BukkitRunnable() { - @Override - public void run() { - runCallback(); - } - }.runTask(this.plugin); - } - } - - private void runCallback() { - this.callback.onFinish(this); - } + // Connection to RSS + private URL url; + // Updater thread + private Thread thread; + // Used for determining the outcome of the update process + private BukkitUpdater.UpdateResult result = BukkitUpdater.UpdateResult.SUCCESS; + + /** + * Gives the developer the result of the update process. Can be obtained by called {@link #getResult()} + */ + public enum UpdateResult { + /** + * The updater found an update, and has readied it to be loaded the next time the server restarts/reloads. + */ + SUCCESS, + /** + * The updater did not find an update, and nothing was downloaded. + */ + NO_UPDATE, + /** + * The server administrator has disabled the updating system. + */ + DISABLED, + /** + * The updater found an update, but was unable to download it. + */ + FAIL_DOWNLOAD, + /** + * For some reason, the updater was unable to contact dev.bukkit.org to download the file. + */ + FAIL_DBO, + /** + * When running the version check, the file on DBO did not contain a recognizable version. + */ + FAIL_NOVERSION, + /** + * The id provided by the plugin running the updater was invalid and doesn't exist on DBO. + */ + FAIL_BADID, + /** + * The server administrator has improperly configured their API key in the configuration. + */ + FAIL_APIKEY, + /** + * The updater found an update, but because of the UpdateType being set to NO_DOWNLOAD, it wasn't downloaded. + */ + UPDATE_AVAILABLE + } + + /** + * Allows the developer to specify the type of update that will be run. + */ + public enum UpdateType { + /** + * Run a version check, and then if the file is out of date, download the newest version. + */ + DEFAULT, + /** + * Don't run a version check, just find the latest update and download it. + */ + NO_VERSION_CHECK, + /** + * Get information about the version and the download size, but don't actually download anything. + */ + NO_DOWNLOAD + } + + /** + * Represents the various release types of a file on BukkitDev. + */ + public enum ReleaseType { + /** + * An "alpha" file. + */ + ALPHA, + /** + * A "beta" file. + */ + BETA, + /** + * A "release" file. + */ + RELEASE + } + + /** + * Initialize the updater. + * + * @param plugin The plugin that is checking for an update. + * @param id The dev.bukkit.org id of the project. + * @param file The file that the plugin is running from, get this by doing this.getFile() from within your main class. + * @param type Specify the type of update this will be. See {@link UpdateType} + * @param announce True if the program should announce the progress of new updates in console. + */ + public BukkitUpdater(Plugin plugin, int id, File file, UpdateType type, boolean announce) { + this(plugin, id, file, type, null, announce); + } + + /** + * Initialize the updater with the provided callback. + * + * @param plugin The plugin that is checking for an update. + * @param id The dev.bukkit.org id of the project. + * @param file The file that the plugin is running from, get this by doing this.getFile() from within your main class. + * @param type Specify the type of update this will be. See {@link UpdateType} + * @param callback The callback instance to notify when the Updater has finished + */ + public BukkitUpdater(Plugin plugin, int id, File file, UpdateType type, UpdateCallback callback) { + this(plugin, id, file, type, callback, false); + } + + /** + * Initialize the updater with the provided callback. + * + * @param plugin The plugin that is checking for an update. + * @param id The dev.bukkit.org id of the project. + * @param file The file that the plugin is running from, get this by doing this.getFile() from within your main class. + * @param type Specify the type of update this will be. See {@link UpdateType} + * @param callback The callback instance to notify when the Updater has finished + * @param announce True if the program should announce the progress of new updates in console. + */ + public BukkitUpdater(Plugin plugin, int id, File file, UpdateType type, UpdateCallback callback, boolean announce) { + this.plugin = plugin; + this.type = type; + this.announce = announce; + this.file = file; + this.id = id; + this.updateFolder = this.plugin.getServer().getUpdateFolderFile(); + this.callback = callback; + + final File pluginFile = this.plugin.getDataFolder().getParentFile(); + final File updaterFile = new File(pluginFile, "Updater"); + final File updaterConfigFile = new File(updaterFile, "config.yml"); + + YamlConfiguration config = new YamlConfiguration(); + config.options().header("This configuration file affects all plugins using the Updater system (version 2+ - http://forums.bukkit.org/threads/96681/ )" + '\n' + + "If you wish to use your API key, read http://wiki.bukkit.org/ServerMods_API and place it below." + '\n' + + "Some updating systems will not adhere to the disabled value, but these may be turned off in their plugin's configuration."); + config.addDefault(API_KEY_CONFIG_KEY, API_KEY_DEFAULT); + config.addDefault(DISABLE_CONFIG_KEY, DISABLE_DEFAULT); + + if (!updaterFile.exists()) { + this.fileIOOrError(updaterFile, updaterFile.mkdir(), true); + } + + boolean createFile = !updaterConfigFile.exists(); + try { + if (createFile) { + this.fileIOOrError(updaterConfigFile, updaterConfigFile.createNewFile(), true); + config.options().copyDefaults(true); + config.save(updaterConfigFile); + } else { + config.load(updaterConfigFile); + } + } catch (final Exception e) { + final String message; + if (createFile) { + message = "The updater could not create configuration at " + updaterFile.getAbsolutePath(); + } else { + message = "The updater could not load configuration at " + updaterFile.getAbsolutePath(); + } + this.plugin.getLogger().log(Level.SEVERE, message, e); + } + + if (config.getBoolean(DISABLE_CONFIG_KEY)) { + this.result = UpdateResult.DISABLED; + return; + } + + String key = config.getString(API_KEY_CONFIG_KEY); + if (API_KEY_DEFAULT.equalsIgnoreCase(key) || "".equals(key)) { + key = null; + } + + this.apiKey = key; + + try { + this.url = new URL(BukkitUpdater.HOST + BukkitUpdater.QUERY + this.id); + } catch (final MalformedURLException e) { + this.plugin.getLogger().log(Level.SEVERE, "The project ID provided for updating, " + this.id + " is invalid.", e); + this.result = UpdateResult.FAIL_BADID; + } + + if (this.result != UpdateResult.FAIL_BADID) { + this.thread = new Thread(new UpdateRunnable()); + this.thread.start(); + } else { + runUpdater(); + } + } + + /** + * Get the result of the update process. + * + * @return result of the update process. + * @see UpdateResult + */ + public BukkitUpdater.UpdateResult getResult() { + this.waitForThread(); + return this.result; + } + + /** + * Get the latest version's release type. + * + * @return latest version's release type. + * @see ReleaseType + */ + public ReleaseType getLatestType() { + this.waitForThread(); + if (this.versionType != null) { + for (ReleaseType type : ReleaseType.values()) { + if (this.versionType.equalsIgnoreCase(type.name())) { + return type; + } + } + } + return null; + } + + /** + * Get the latest version's game version (such as "CB 1.2.5-R1.0"). + * + * @return latest version's game version. + */ + public String getLatestGameVersion() { + this.waitForThread(); + return this.versionGameVersion; + } + + /** + * Get the latest version's name (such as "Project v1.0"). + * + * @return latest version's name. + */ + public String getLatestName() { + this.waitForThread(); + return this.versionName; + } + + /** + * Get the latest version's direct file link. + * + * @return latest version's file link. + */ + public String getLatestFileLink() { + this.waitForThread(); + return this.versionLink; + } + + /** + * As the result of Updater output depends on the thread's completion, it is necessary to wait for the thread to finish + * before allowing anyone to check the result. + */ + private void waitForThread() { + if ((this.thread != null) && this.thread.isAlive()) { + try { + this.thread.join(); + } catch (final InterruptedException e) { + this.plugin.getLogger().log(Level.SEVERE, null, e); + } + } + } + + /** + * Save an update from dev.bukkit.org into the server's update folder. + * + * @param file the name of the file to save it as. + */ + private void saveFile(String file) { + final File folder = this.updateFolder; + + deleteOldFiles(); + if (!folder.exists()) { + this.fileIOOrError(folder, folder.mkdir(), true); + } + downloadFile(); + + // Check to see if it's a zip file, if it is, unzip it. + final File dFile = new File(folder.getAbsolutePath(), file); + if (dFile.getName().endsWith(".zip")) { + // Unzip + this.unzip(dFile.getAbsolutePath()); + } + if (this.announce) { + this.plugin.getLogger().info("Finished updating."); + } + } + + /** + * Download a file and save it to the specified folder. + */ + private void downloadFile() { + BufferedInputStream in = null; + FileOutputStream fout = null; + try { + URL fileUrl = new URL(this.versionLink); + final int fileLength = fileUrl.openConnection().getContentLength(); + in = new BufferedInputStream(fileUrl.openStream()); + fout = new FileOutputStream(new File(this.updateFolder, file.getName())); + + final byte[] data = new byte[BukkitUpdater.BYTE_SIZE]; + int count; + if (this.announce) { + this.plugin.getLogger().info("About to download a new update: " + this.versionName); + } + long downloaded = 0; + while ((count = in.read(data, 0, BukkitUpdater.BYTE_SIZE)) != -1) { + downloaded += count; + fout.write(data, 0, count); + final int percent = (int) ((downloaded * 100) / fileLength); + if (this.announce && ((percent % 10) == 0)) { + this.plugin.getLogger().info("Downloading update: " + percent + "% of " + fileLength + " bytes."); + } + } + } catch (Exception ex) { + this.plugin.getLogger().log(Level.WARNING, "The auto-updater tried to download a new update, but was unsuccessful.", ex); + this.result = BukkitUpdater.UpdateResult.FAIL_DOWNLOAD; + } finally { + try { + if (in != null) { + in.close(); + } + } catch (final IOException ex) { + this.plugin.getLogger().log(Level.SEVERE, null, ex); + } + try { + if (fout != null) { + fout.close(); + } + } catch (final IOException ex) { + this.plugin.getLogger().log(Level.SEVERE, null, ex); + } + } + } + + /** + * Remove possibly leftover files from the update folder. + */ + private void deleteOldFiles() { + //Just a quick check to make sure we didn't leave any files from last time... + File[] list = listFilesOrError(this.updateFolder); + for (final File xFile : list) { + if (xFile.getName().endsWith(".zip")) { + this.fileIOOrError(xFile, xFile.mkdir(), true); + } + } + } + + /** + * Part of Zip-File-Extractor, modified by Gravity for use with Updater. + * + * @param file the location of the file to extract. + */ + private void unzip(String file) { + final File fSourceZip = new File(file); + try { + final String zipPath = file.substring(0, file.length() - 4); + ZipFile zipFile = new ZipFile(fSourceZip); + Enumeration e = zipFile.entries(); + while (e.hasMoreElements()) { + ZipEntry entry = e.nextElement(); + File destinationFilePath = new File(zipPath, entry.getName()); + this.fileIOOrError(destinationFilePath.getParentFile(), destinationFilePath.getParentFile().mkdirs(), true); + if (!entry.isDirectory()) { + final BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry)); + int b; + final byte[] buffer = new byte[BukkitUpdater.BYTE_SIZE]; + final FileOutputStream fos = new FileOutputStream(destinationFilePath); + final BufferedOutputStream bos = new BufferedOutputStream(fos, BukkitUpdater.BYTE_SIZE); + while ((b = bis.read(buffer, 0, BukkitUpdater.BYTE_SIZE)) != -1) { + bos.write(buffer, 0, b); + } + bos.flush(); + bos.close(); + bis.close(); + final String name = destinationFilePath.getName(); + if (name.endsWith(".jar") && this.pluginExists(name)) { + File output = new File(this.updateFolder, name); + this.fileIOOrError(output, destinationFilePath.renameTo(output), true); + } + } + } + zipFile.close(); + + // Move any plugin data folders that were included to the right place, Bukkit won't do this for us. + moveNewZipFiles(zipPath); + + } catch (final IOException e) { + this.plugin.getLogger().log(Level.SEVERE, "The auto-updater tried to unzip a new update file, but was unsuccessful.", e); + this.result = BukkitUpdater.UpdateResult.FAIL_DOWNLOAD; + } finally { + this.fileIOOrError(fSourceZip, fSourceZip.delete(), false); + } + } + + /** + * Find any new files extracted from an update into the plugin's data directory. + * + * @param zipPath path of extracted files. + */ + private void moveNewZipFiles(String zipPath) { + File[] list = listFilesOrError(new File(zipPath)); + for (final File dFile : list) { + if (dFile.isDirectory() && this.pluginExists(dFile.getName())) { + // Current dir + final File oFile = new File(this.plugin.getDataFolder().getParent(), dFile.getName()); + // List of existing files in the new dir + final File[] dList = listFilesOrError(dFile); + // List of existing files in the current dir + final File[] oList = listFilesOrError(oFile); + for (File cFile : dList) { + // Loop through all the files in the new dir + boolean found = false; + for (final File xFile : oList) { + // Loop through all the contents in the current dir to see if it exists + if (xFile.getName().equals(cFile.getName())) { + found = true; + break; + } + } + if (!found) { + // Move the new file into the current dir + File output = new File(oFile, cFile.getName()); + this.fileIOOrError(output, cFile.renameTo(output), true); + } else { + // This file already exists, so we don't need it anymore. + this.fileIOOrError(cFile, cFile.delete(), false); + } + } + } + this.fileIOOrError(dFile, dFile.delete(), false); + } + File zip = new File(zipPath); + this.fileIOOrError(zip, zip.delete(), false); + } + + /** + * Check if the name of a jar is one of the plugins currently installed, used for extracting the correct files out of a zip. + * + * @param name a name to check for inside the plugins folder. + * @return true if a file inside the plugins folder is named this. + */ + private boolean pluginExists(String name) { + File[] plugins = listFilesOrError(new File("plugins")); + for (final File file : plugins) { + if (file.getName().equals(name)) { + return true; + } + } + return false; + } + + /** + * Check to see if the program should continue by evaluating whether the plugin is already updated, or shouldn't be updated. + * + * @return true if the version was located and is not the same as the remote's newest. + */ + private boolean versionCheck() { + final String title = this.versionName; + if (this.type != UpdateType.NO_VERSION_CHECK) { + final String localVersion = this.plugin.getDescription().getVersion(); + if (title.split(DELIMETER).length == 2) { + // Get the newest file's version number + final String remoteVersion = title.split(DELIMETER)[1].split(" ")[0]; + + if (this.hasTag(localVersion) || this.hasName(title) || !this.shouldUpdate(localVersion, remoteVersion)) { + // We already have the latest version, or this build is tagged for no-update + this.result = BukkitUpdater.UpdateResult.NO_UPDATE; + return false; + } + } else { + // The file's name did not contain the string 'vVersion' + final String authorInfo = this.plugin.getDescription().getAuthors().isEmpty() ? "" : " (" + this.plugin.getDescription().getAuthors().get(0) + ")"; + this.plugin.getLogger().warning("The author of this plugin" + authorInfo + " has misconfigured their Auto Update system"); + this.plugin.getLogger().warning("File versions should follow the format 'PluginName vVERSION'"); + this.plugin.getLogger().warning("Please notify the author of this error."); + this.result = BukkitUpdater.UpdateResult.FAIL_NOVERSION; + return false; + } + } + return true; + } + + /** + * If you wish to run mathematical versioning checks, edit this method. + *

+ * With default behavior, Updater will NOT verify that a remote version available on BukkitDev + * which is not this version is indeed an "update". + * If a version is present on BukkitDev that is not the version that is currently running, + * Updater will assume that it is a newer version. + * This is because there is no standard versioning scheme, and creating a calculation that can + * determine whether a new update is actually an update is sometimes extremely complicated. + *

+ *

+ * Updater will call this method from {@link #versionCheck()} before deciding whether + * the remote version is actually an update. + * If you have a specific versioning scheme with which a mathematical determination can + * be reliably made to decide whether one version is higher than another, you may + * revise this method, using the local and remote version parameters, to execute the + * appropriate check. + *

+ *

+ * Returning a value of false will tell the update process that this is NOT a new version. + * Without revision, this method will always consider a remote version at all different from + * that of the local version a new update. + *

+ * + * @param localVersion the current version + * @param remoteVersion the remote version + * @return true if Updater should consider the remote version an update, false if not. + */ + public boolean shouldUpdate(String localVersion, String remoteVersion) { + return !localVersion.equalsIgnoreCase(remoteVersion); + } + + /** + * Evaluate whether the plugin name is marked showing that it should not be updated by this program. + * + * @param name a version number to check for tags in. + * @return true if updating should be disabled. + */ + private boolean hasName(String name) { + for (final String string : BukkitUpdater.NO_UPDATE_NAME) { + if (name.contains(string)) { + return true; + } + } + return false; + } + + /** + * Evaluate whether the version number is marked showing that it should not be updated by this program. + * + * @param version a version number to check for tags in. + * @return true if updating should be disabled. + */ + private boolean hasTag(String version) { + for (final String string : BukkitUpdater.NO_UPDATE_TAG) { + if (version.contains(string)) { + return true; + } + } + return false; + } + + /** + * Make a connection to the BukkitDev API and request the newest file's details. + * + * @return true if successful. + */ + private boolean read() { + try { + final URLConnection conn = this.url.openConnection(); + conn.setConnectTimeout(5000); + + if (this.apiKey != null) { + conn.addRequestProperty("X-API-Key", this.apiKey); + } + conn.addRequestProperty("User-Agent", BukkitUpdater.USER_AGENT); + + conn.setDoOutput(true); + + final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); + final String response = reader.readLine(); + + final JSONArray array = (JSONArray) JSONValue.parse(response); + + if (array.isEmpty()) { + this.plugin.getLogger().warning("The updater could not find any files for the project id " + this.id); + this.result = UpdateResult.FAIL_BADID; + return false; + } + + JSONObject latestUpdate = (JSONObject) array.get(array.size() - 1); + this.versionName = (String) latestUpdate.get(BukkitUpdater.TITLE_VALUE); + this.versionLink = (String) latestUpdate.get(BukkitUpdater.LINK_VALUE); + this.versionType = (String) latestUpdate.get(BukkitUpdater.TYPE_VALUE); + this.versionGameVersion = (String) latestUpdate.get(BukkitUpdater.VERSION_VALUE); + + return true; + } catch (final IOException e) { + if (e.getMessage().contains("HTTP response code: 403")) { + this.plugin.getLogger().severe("dev.bukkit.org rejected the API key provided in plugins/Updater/config.yml"); + this.plugin.getLogger().severe("Please double-check your configuration to ensure it is correct."); + this.result = UpdateResult.FAIL_APIKEY; + } else { + this.plugin.getLogger().severe("The updater could not contact dev.bukkit.org for updating."); + this.plugin.getLogger().severe("If you have not recently modified your configuration and this is the first time you are seeing this message, the site may be experiencing temporary downtime."); + this.result = UpdateResult.FAIL_DBO; + } + this.plugin.getLogger().log(Level.SEVERE, null, e); + return false; + } + } + + /** + * Perform a file operation and log any errors if it fails. + * + * @param file file operation is performed on. + * @param result result of file operation. + * @param create true if a file is being created, false if deleted. + */ + private void fileIOOrError(File file, boolean result, boolean create) { + if (!result) { + this.plugin.getLogger().severe("The updater could not " + (create ? "create" : "delete") + " file at: " + file.getAbsolutePath()); + } + } + + private File[] listFilesOrError(File folder) { + File[] contents = folder.listFiles(); + if (contents == null) { + this.plugin.getLogger().severe("The updater could not access files at: " + this.updateFolder.getAbsolutePath()); + return new File[0]; + } else { + return contents; + } + } + + /** + * Called on main thread when the Updater has finished working, regardless + * of result. + */ + public interface UpdateCallback { + /** + * Called when the updater has finished working. + * + * @param updater The updater instance + */ + void onFinish(BukkitUpdater updater); + } + + private class UpdateRunnable implements Runnable { + @Override + public void run() { + runUpdater(); + } + } + + private void runUpdater() { + if (this.url != null && (this.read() && this.versionCheck())) { + // Obtain the results of the project's file feed + if ((this.versionLink != null) && (this.type != UpdateType.NO_DOWNLOAD)) { + String name = this.file.getName(); + // If it's a zip file, it shouldn't be downloaded as the plugin's name + if (this.versionLink.endsWith(".zip")) { + name = this.versionLink.substring(this.versionLink.lastIndexOf("/") + 1); + } + this.saveFile(name); + } else { + this.result = UpdateResult.UPDATE_AVAILABLE; + } + } + + if (this.callback != null) { + new BukkitRunnable() { + @Override + public void run() { + runCallback(); + } + }.runTask(this.plugin); + } + } + + private void runCallback() { + this.callback.onFinish(this); + } } \ No newline at end of file diff --git a/src/main/java/com/faris/kingkits/updater/SpigotUpdater.java b/src/main/java/com/faris/kingkits/updater/SpigotUpdater.java index aeec11f..c1e3176 100644 --- a/src/main/java/com/faris/kingkits/updater/SpigotUpdater.java +++ b/src/main/java/com/faris/kingkits/updater/SpigotUpdater.java @@ -1,6 +1,6 @@ package com.faris.kingkits.updater; -import org.bukkit.plugin.java.JavaPlugin; +import org.bukkit.plugin.java.*; import java.io.BufferedReader; import java.io.IOException; @@ -15,97 +15,97 @@ */ public class SpigotUpdater { - private JavaPlugin plugin; - private final String API_KEY = "98BE0FE67F88AB82B4C197FAF1DC3B69206EFDCC4D3B80FC83A00037510B99B4"; - private final String REQUEST_METHOD = "POST"; - private String RESOURCE_ID = ""; - private final String HOST = "http://www.spigotmc.org"; - private final String QUERY = "/api/general.php"; - private String WRITE_STRING; - - private String version; - private String oldVersion; - - private SpigotUpdater.UpdateResult result = SpigotUpdater.UpdateResult.DISABLED; - - private HttpURLConnection connection; - - public enum UpdateResult { - NO_UPDATE, - DISABLED, - FAIL_SPIGOT, - FAIL_NO_VERSION, - BAD_RESOURCE_ID, - UPDATE_AVAILABLE - } - - public SpigotUpdater(JavaPlugin plugin, Integer resourceId, boolean disabled) { - RESOURCE_ID = resourceId + ""; - this.plugin = plugin; - this.oldVersion = this.plugin.getDescription().getVersion(); - - if (disabled) { - this.result = UpdateResult.DISABLED; - return; - } - - try { - this.connection = (HttpURLConnection) new URL(HOST + QUERY).openConnection(); - } catch (IOException e) { - this.result = UpdateResult.FAIL_SPIGOT; - return; - } - - WRITE_STRING = "key=" + API_KEY + "&resource=" + RESOURCE_ID; - this.run(); - } - - private void run() { - this.connection.setDoOutput(true); - try { - this.connection.setRequestMethod(REQUEST_METHOD); - this.connection.getOutputStream().write(WRITE_STRING.getBytes("UTF-8")); - } catch (ProtocolException e1) { - this.result = UpdateResult.FAIL_SPIGOT; - } catch (UnsupportedEncodingException e) { - this.result = UpdateResult.FAIL_SPIGOT; - } catch (IOException e) { - this.result = UpdateResult.FAIL_SPIGOT; - } - String version; - try { - version = new BufferedReader(new InputStreamReader(this.connection.getInputStream())).readLine(); - } catch (Exception e) { - this.result = UpdateResult.BAD_RESOURCE_ID; - return; - } - if (version.length() <= 7) { - this.version = version; - version.replace("[^A-Za-z]", "").replace("|", ""); - this.versionCheck(); - return; - } - this.result = UpdateResult.BAD_RESOURCE_ID; - } - - private void versionCheck() { - if (this.shouldUpdate(this.oldVersion, this.version)) { - this.result = UpdateResult.UPDATE_AVAILABLE; - } else { - this.result = UpdateResult.NO_UPDATE; - } - } - - public boolean shouldUpdate(String localVersion, String remoteVersion) { - return !localVersion.equalsIgnoreCase(remoteVersion); - } - - public UpdateResult getResult() { - return this.result; - } - - public String getVersion() { - return this.version; - } + private JavaPlugin plugin; + private final String API_KEY = "98BE0FE67F88AB82B4C197FAF1DC3B69206EFDCC4D3B80FC83A00037510B99B4"; + private final String REQUEST_METHOD = "POST"; + private String RESOURCE_ID = ""; + private final String HOST = "http://www.spigotmc.org"; + private final String QUERY = "/api/general.php"; + private String WRITE_STRING; + + private String version; + private String oldVersion; + + private SpigotUpdater.UpdateResult result = SpigotUpdater.UpdateResult.DISABLED; + + private HttpURLConnection connection; + + public enum UpdateResult { + NO_UPDATE, + DISABLED, + FAIL_SPIGOT, + FAIL_NO_VERSION, + BAD_RESOURCE_ID, + UPDATE_AVAILABLE + } + + public SpigotUpdater(JavaPlugin plugin, Integer resourceId, boolean disabled) { + RESOURCE_ID = resourceId + ""; + this.plugin = plugin; + this.oldVersion = this.plugin.getDescription().getVersion(); + + if (disabled) { + this.result = UpdateResult.DISABLED; + return; + } + + try { + this.connection = (HttpURLConnection) new URL(HOST + QUERY).openConnection(); + } catch (IOException e) { + this.result = UpdateResult.FAIL_SPIGOT; + return; + } + + WRITE_STRING = "key=" + API_KEY + "&resource=" + RESOURCE_ID; + this.run(); + } + + private void run() { + this.connection.setDoOutput(true); + try { + this.connection.setRequestMethod(REQUEST_METHOD); + this.connection.getOutputStream().write(WRITE_STRING.getBytes("UTF-8")); + } catch (ProtocolException e1) { + this.result = UpdateResult.FAIL_SPIGOT; + } catch (UnsupportedEncodingException e) { + this.result = UpdateResult.FAIL_SPIGOT; + } catch (IOException e) { + this.result = UpdateResult.FAIL_SPIGOT; + } + String version; + try { + version = new BufferedReader(new InputStreamReader(this.connection.getInputStream())).readLine(); + } catch (Exception e) { + this.result = UpdateResult.BAD_RESOURCE_ID; + return; + } + if (version.length() <= 7) { + this.version = version; + version.replace("[^A-Za-z]", "").replace("|", ""); + this.versionCheck(); + return; + } + this.result = UpdateResult.BAD_RESOURCE_ID; + } + + private void versionCheck() { + if (this.shouldUpdate(this.oldVersion, this.version)) { + this.result = UpdateResult.UPDATE_AVAILABLE; + } else { + this.result = UpdateResult.NO_UPDATE; + } + } + + public boolean shouldUpdate(String localVersion, String remoteVersion) { + return !localVersion.equalsIgnoreCase(remoteVersion); + } + + public UpdateResult getResult() { + return this.result; + } + + public String getVersion() { + return this.version; + } } diff --git a/src/main/java/com/faris/kingkits/values/CommandValues.java b/src/main/java/com/faris/kingkits/values/CommandValues.java deleted file mode 100644 index 5b1a871..0000000 --- a/src/main/java/com/faris/kingkits/values/CommandValues.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.faris.kingkits.values; - -public class CommandValues { - public boolean pvpKits = true; - public boolean createKits = true; - public boolean deleteKits = true; - public boolean renameKits = true; - public boolean createUKits = true; - public boolean deleteUKits = true; - public boolean renameUKits = true; - public boolean refillKits = true; -} diff --git a/src/main/java/com/faris/kingkits/values/ConfigValues.java b/src/main/java/com/faris/kingkits/values/ConfigValues.java deleted file mode 100644 index 94fd2fc..0000000 --- a/src/main/java/com/faris/kingkits/values/ConfigValues.java +++ /dev/null @@ -1,107 +0,0 @@ -package com.faris.kingkits.values; - -import org.bukkit.Material; - -import java.util.Arrays; -import java.util.List; - -public class ConfigValues { - // Booleans - public boolean checkForUpdates = true; - public boolean automaticUpdates = false; - - public boolean opBypass = true; - - public boolean listKitsOnJoin = true; - public boolean kitListPermissionsJoin = false; - public boolean sortAlphabetically = true; - - public boolean kitListPermissions = true; - - public boolean dropItemsOnDeath = false; - public boolean dropItems = false; - @SuppressWarnings("deprecation") - public List dropAnimations = Arrays.asList(Material.BOWL.getId()); - public boolean allowPickingUpItems = true; - - public boolean clearInvsOnReload = true; - - public boolean oneKitPerLife = false; - - public boolean removeItemsOnLeave = true; - public boolean removePotionEffectsOnLeave = true; - public boolean removeItemsOnCreateKit = true; - - public boolean rightClickCompass = true; - - public boolean quickSoup = true; - public boolean quickSoupKitOnly = true; - public double quickSoupHeal = 2.5; - - public boolean banBlockBreakingAndPlacing = false; - - public boolean disableDeathMessages = false; - - public boolean lockHunger = true; - public int hungerLock = 20; - - public boolean disableGamemode = false; - - public boolean killstreaks = false; - - public boolean disableItemBreaking = true; - - public boolean kitMenuOnJoin = false; - - public boolean kitParticleEffects = false; - - public boolean showKitPreview = false; - - public boolean kitCooldown = false; - - public boolean replaceItems = true; - - // GUI - public String guiTitle = "PvP Kits"; - public int guiSize = 36; - - // Scores - public boolean scores = false; - public String scoreFormat = "&6[&a&6]"; - public int scoreIncrement = 2; - public int maxScore = Integer.MAX_VALUE; - - // Vault - public VaultValues vaultValues = new VaultValues(); - - public class VaultValues { - public boolean useEconomy = false; - - public boolean useCostPerKit = false; - public boolean useCostPerRefill = false; - public double costPerRefill = 2.5D; - - public boolean useMoneyPerKill = false; - public double moneyPerKill = 5D; - public boolean useMoneyPerDeath = false; - public double moneyPerDeath = 5D; - } - - // Strings - public String commandToRun = ""; - - public List pvpWorlds = Arrays.asList("All"); - public String multiInvsPlugin = "Multiverse-Inventories"; - public boolean multiInvs = false; - - public String customMessages = ""; - - public String kitListMode = "Text"; - - public String strKitSign = "[Kit]"; - public String strKitListSign = "[KList]"; - public String strKitSignValid = "[Kit]"; - public String strKitSignInvalid = "[Kit]"; - public String strKitListSignValid = "[KList]"; - -} diff --git a/src/main/java/org/mcstats/Metrics.java b/src/main/java/org/mcstats/Metrics.java index 0844cf6..60eeb74 100644 --- a/src/main/java/org/mcstats/Metrics.java +++ b/src/main/java/org/mcstats/Metrics.java @@ -27,13 +27,12 @@ */ package org.mcstats; -import com.faris.kingkits.helpers.Utils; -import org.bukkit.Bukkit; -import org.bukkit.configuration.InvalidConfigurationException; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.PluginDescriptionFile; -import org.bukkit.scheduler.BukkitTask; +import com.faris.kingkits.helper.Utilities; +import org.bukkit.*; +import org.bukkit.configuration.*; +import org.bukkit.configuration.file.*; +import org.bukkit.plugin.*; +import org.bukkit.scheduler.*; import java.io.*; import java.net.Proxy; @@ -46,704 +45,689 @@ public class Metrics { - /** - * The current revision number - */ - private final static int REVISION = 7; - - /** - * The base url of the metrics domain - */ - private static final String BASE_URL = "http://report.mcstats.org"; - - /** - * The url used to report a server's status - */ - private static final String REPORT_URL = "/plugin/%s"; - - /** - * Interval of time to ping (in minutes) - */ - private static final int PING_INTERVAL = 15; - - /** - * The plugin this metrics submits for - */ - private final Plugin plugin; - - /** - * All of the custom graphs to submit to metrics - */ - private final Set graphs = Collections.synchronizedSet(new HashSet()); - - /** - * The plugin configuration file - */ - private final YamlConfiguration configuration; - - /** - * The plugin configuration file - */ - private final File configurationFile; - - /** - * Unique server id - */ - private final String guid; - - /** - * Debug mode - */ - private final boolean debug; - - /** - * Lock for synchronization - */ - private final Object optOutLock = new Object(); - - /** - * The scheduled task - */ - private volatile BukkitTask task = null; - - public Metrics(final Plugin plugin) throws IOException { - if (plugin == null) { - throw new IllegalArgumentException("Plugin cannot be null"); - } - - this.plugin = plugin; - - // load the config - configurationFile = getConfigFile(); - configuration = YamlConfiguration.loadConfiguration(configurationFile); - - // add some defaults - configuration.addDefault("opt-out", false); - configuration.addDefault("guid", UUID.randomUUID().toString()); - configuration.addDefault("debug", false); - - // Do we need to create the file? - if (configuration.get("guid", null) == null) { - configuration.options().header("http://mcstats.org").copyDefaults(true); - configuration.save(configurationFile); - } - - // Load the guid then - guid = configuration.getString("guid"); - debug = configuration.getBoolean("debug", false); - } - - /** - * Construct and create a Graph that can be used to separate specific plotters to their own graphs on the metrics - * website. Plotters can be added to the graph object returned. - * - * @param name The name of the graph - * @return Graph object created. Will never return NULL under normal circumstances unless bad parameters are given - */ - public Graph createGraph(final String name) { - if (name == null) { - throw new IllegalArgumentException("Graph name cannot be null"); - } - - // Construct the graph object - final Graph graph = new Graph(name); - - // Now we can add our graph - graphs.add(graph); - - // and return back - return graph; - } - - /** - * Add a Graph object to BukkitMetrics that represents data for the plugin that should be sent to the backend - * - * @param graph The name of the graph - */ - public void addGraph(final Graph graph) { - if (graph == null) { - throw new IllegalArgumentException("Graph cannot be null"); - } - - graphs.add(graph); - } - - /** - * Start measuring statistics. This will immediately create an async repeating task as the plugin and send the - * initial data to the metrics backend, and then after that it will post in increments of PING_INTERVAL * 1200 - * ticks. - * - * @return True if statistics measuring is running, otherwise false. - */ - public boolean start() { - synchronized (optOutLock) { - // Did we opt out? - if (isOptOut()) { - return false; - } - - // Is metrics already running? - if (task != null) { - return true; - } - - // Begin hitting the server with glorious data - task = plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, new Runnable() { - - private boolean firstPost = true; - - public void run() { - try { - // This has to be synchronized or it can collide with the disable method. - synchronized (optOutLock) { - // Disable Task, if it is running and the server owner decided to opt-out - if (isOptOut() && task != null) { - task.cancel(); - task = null; - // Tell all plotters to stop gathering information. - for (Graph graph : graphs) { - graph.onOptOut(); - } - } - } - - // We use the inverse of firstPost because if it is the first time we are posting, - // it is not a interval ping, so it evaluates to FALSE - // Each time thereafter it will evaluate to TRUE, i.e PING! - postPlugin(!firstPost); - - // After the first post we set firstPost to false - // Each post thereafter will be a ping - firstPost = false; - } catch (IOException e) { - if (debug) { - Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage()); - } - } - } - }, 0, PING_INTERVAL * 1200); - - return true; - } - } - - /** - * Has the server owner denied plugin metrics? - * - * @return true if metrics should be opted out of it - */ - public boolean isOptOut() { - synchronized (optOutLock) { - try { - // Reload the metrics file - configuration.load(getConfigFile()); - } catch (IOException ex) { - if (debug) { - Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); - } - return true; - } catch (InvalidConfigurationException ex) { - if (debug) { - Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); - } - return true; - } - return configuration.getBoolean("opt-out", false); - } - } - - /** - * Enables metrics for the server by setting "opt-out" to false in the config file and starting the metrics task. - * - * @throws java.io.IOException - */ - public void enable() throws IOException { - // This has to be synchronized or it can collide with the check in the task. - synchronized (optOutLock) { - // Check if the server owner has already set opt-out, if not, set it. - if (isOptOut()) { - configuration.set("opt-out", false); - configuration.save(configurationFile); - } - - // Enable Task, if it is not running - if (task == null) { - start(); - } - } - } - - /** - * Disables metrics for the server by setting "opt-out" to true in the config file and canceling the metrics task. - * - * @throws java.io.IOException - */ - public void disable() throws IOException { - // This has to be synchronized or it can collide with the check in the task. - synchronized (optOutLock) { - // Check if the server owner has already set opt-out, if not, set it. - if (!isOptOut()) { - configuration.set("opt-out", true); - configuration.save(configurationFile); - } - - // Disable Task, if it is running - if (task != null) { - task.cancel(); - task = null; - } - } - } - - /** - * Gets the File object of the config file that should be used to store data such as the GUID and opt-out status - * - * @return the File object for the config file - */ - public File getConfigFile() { - // I believe the easiest way to get the base folder (e.g craftbukkit set via -P) for plugins to use - // is to abuse the plugin object we already have - // plugin.getDataFolder() => base/plugins/PluginA/ - // pluginsFolder => base/plugins/ - // The base is not necessarily relative to the startup directory. - File pluginsFolder = plugin.getDataFolder().getParentFile(); - - // return => base/plugins/PluginMetrics/config.yml - return new File(new File(pluginsFolder, "PluginMetrics"), "config.yml"); - } - - /** - * Generic method that posts a plugin to the metrics website - */ - private void postPlugin(final boolean isPing) throws IOException { - // Server software specific section - PluginDescriptionFile description = plugin.getDescription(); - String pluginName = description.getName(); - boolean onlineMode = Bukkit.getServer().getOnlineMode(); // TRUE if online mode is enabled - String pluginVersion = description.getVersion(); - String serverVersion = Bukkit.getVersion(); - int playersOnline = Utils.getOnlinePlayers().size(); - - // END server software specific section -- all code below does not use any code outside of this class / Java - - // Construct the post data - StringBuilder json = new StringBuilder(1024); - json.append('{'); - - // The plugin's description file containg all of the plugin data such as name, version, author, etc - appendJSONPair(json, "guid", guid); - appendJSONPair(json, "plugin_version", pluginVersion); - appendJSONPair(json, "server_version", serverVersion); - appendJSONPair(json, "players_online", Integer.toString(playersOnline)); - - // New data as of R6 - String osname = System.getProperty("os.name"); - String osarch = System.getProperty("os.arch"); - String osversion = System.getProperty("os.version"); - String java_version = System.getProperty("java.version"); - int coreCount = Runtime.getRuntime().availableProcessors(); - - // normalize os arch .. amd64 -> x86_64 - if (osarch.equals("amd64")) { - osarch = "x86_64"; - } - - appendJSONPair(json, "osname", osname); - appendJSONPair(json, "osarch", osarch); - appendJSONPair(json, "osversion", osversion); - appendJSONPair(json, "cores", Integer.toString(coreCount)); - appendJSONPair(json, "auth_mode", onlineMode ? "1" : "0"); - appendJSONPair(json, "java_version", java_version); - - // If we're pinging, append it - if (isPing) { - appendJSONPair(json, "ping", "1"); - } - - if (graphs.size() > 0) { - synchronized (graphs) { - json.append(','); - json.append('"'); - json.append("graphs"); - json.append('"'); - json.append(':'); - json.append('{'); - - boolean firstGraph = true; - - final Iterator iter = graphs.iterator(); - - while (iter.hasNext()) { - Graph graph = iter.next(); - - StringBuilder graphJson = new StringBuilder(); - graphJson.append('{'); - - for (Plotter plotter : graph.getPlotters()) { - appendJSONPair(graphJson, plotter.getColumnName(), Integer.toString(plotter.getValue())); - } - - graphJson.append('}'); - - if (!firstGraph) { - json.append(','); - } - - json.append(escapeJSON(graph.getName())); - json.append(':'); - json.append(graphJson); - - firstGraph = false; - } - - json.append('}'); - } - } - - // close json - json.append('}'); - - // Create the url - URL url = new URL(BASE_URL + String.format(REPORT_URL, urlEncode(pluginName))); - - // Connect to the website - URLConnection connection; - - // Mineshafter creates a socks proxy, so we can safely bypass it - // It does not reroute POST requests so we need to go around it - if (isMineshafterPresent()) { - connection = url.openConnection(Proxy.NO_PROXY); - } else { - connection = url.openConnection(); - } - - - byte[] uncompressed = json.toString().getBytes(); - byte[] compressed = gzip(json.toString()); - - // Headers - connection.addRequestProperty("User-Agent", "MCStats/" + REVISION); - connection.addRequestProperty("Content-Type", "application/json"); - connection.addRequestProperty("Content-Encoding", "gzip"); - connection.addRequestProperty("Content-Length", Integer.toString(compressed.length)); - connection.addRequestProperty("Accept", "application/json"); - connection.addRequestProperty("Connection", "close"); - - connection.setDoOutput(true); - - if (debug) { - System.out.println("[Metrics] Prepared request for " + pluginName + " uncompressed=" + uncompressed.length + " compressed=" + compressed.length); - } - - // Write the data - OutputStream os = connection.getOutputStream(); - os.write(compressed); - os.flush(); - - // Now read the response - final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); - String response = reader.readLine(); - - // close resources - os.close(); - reader.close(); - - if (response == null || response.startsWith("ERR") || response.startsWith("7")) { - if (response == null) { - response = "null"; - } else if (response.startsWith("7")) { - response = response.substring(response.startsWith("7,") ? 2 : 1); - } - - throw new IOException(response); - } else { - // Is this the first update this hour? - if (response.equals("1") || response.contains("This is your first update this hour")) { - synchronized (graphs) { - final Iterator iter = graphs.iterator(); - - while (iter.hasNext()) { - final Graph graph = iter.next(); - - for (Plotter plotter : graph.getPlotters()) { - plotter.reset(); - } - } - } - } - } - } - - /** - * GZip compress a string of bytes - * - * @param input - * @return - */ - public static byte[] gzip(String input) { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - GZIPOutputStream gzos = null; - - try { - gzos = new GZIPOutputStream(baos); - gzos.write(input.getBytes("UTF-8")); - } catch (IOException e) { - e.printStackTrace(); - } finally { - if (gzos != null) try { - gzos.close(); - } catch (IOException ignore) { - } - } - - return baos.toByteArray(); - } - - /** - * Check if mineshafter is present. If it is, we need to bypass it to send POST requests - * - * @return true if mineshafter is installed on the server - */ - private boolean isMineshafterPresent() { - try { - Class.forName("mineshafter.MineServer"); - return true; - } catch (Exception e) { - return false; - } - } - - /** - * Appends a json encoded key/value pair to the given string builder. - * - * @param json - * @param key - * @param value - * @throws UnsupportedEncodingException - */ - private static void appendJSONPair(StringBuilder json, String key, String value) throws UnsupportedEncodingException { - boolean isValueNumeric = false; - - try { - if (value.equals("0") || !value.endsWith("0")) { - Double.parseDouble(value); - isValueNumeric = true; - } - } catch (NumberFormatException e) { - isValueNumeric = false; - } - - if (json.charAt(json.length() - 1) != '{') { - json.append(','); - } - - json.append(escapeJSON(key)); - json.append(':'); - - if (isValueNumeric) { - json.append(value); - } else { - json.append(escapeJSON(value)); - } - } - - /** - * Escape a string to create a valid JSON string - * - * @param text - * @return - */ - private static String escapeJSON(String text) { - StringBuilder builder = new StringBuilder(); - - builder.append('"'); - for (int index = 0; index < text.length(); index++) { - char chr = text.charAt(index); - - switch (chr) { - case '"': - case '\\': - builder.append('\\'); - builder.append(chr); - break; - case '\b': - builder.append("\\b"); - break; - case '\t': - builder.append("\\t"); - break; - case '\n': - builder.append("\\n"); - break; - case '\r': - builder.append("\\r"); - break; - default: - if (chr < ' ') { - String t = "000" + Integer.toHexString(chr); - builder.append("\\u" + t.substring(t.length() - 4)); - } else { - builder.append(chr); - } - break; - } - } - builder.append('"'); - - return builder.toString(); - } - - /** - * Encode text as UTF-8 - * - * @param text the text to encode - * @return the encoded text, as UTF-8 - */ - private static String urlEncode(final String text) throws UnsupportedEncodingException { - return URLEncoder.encode(text, "UTF-8"); - } - - /** - * Represents a custom graph on the website - */ - public static class Graph { - - /** - * The graph's name, alphanumeric and spaces only :) If it does not comply to the above when submitted, it is - * rejected - */ - private final String name; - - /** - * The set of plotters that are contained within this graph - */ - private final Set plotters = new LinkedHashSet(); - - private Graph(final String name) { - this.name = name; - } - - /** - * Gets the graph's name - * - * @return the Graph's name - */ - public String getName() { - return name; - } - - /** - * Add a plotter to the graph, which will be used to plot entries - * - * @param plotter the plotter to add to the graph - */ - public void addPlotter(final Plotter plotter) { - plotters.add(plotter); - } - - /** - * Remove a plotter from the graph - * - * @param plotter the plotter to remove from the graph - */ - public void removePlotter(final Plotter plotter) { - plotters.remove(plotter); - } - - /** - * Gets an unmodifiable set of the plotter objects in the graph - * - * @return an unmodifiable {@link java.util.Set} of the plotter objects - */ - public Set getPlotters() { - return Collections.unmodifiableSet(plotters); - } - - @Override - public int hashCode() { - return name.hashCode(); - } - - @Override - public boolean equals(final Object object) { - if (!(object instanceof Graph)) { - return false; - } - - final Graph graph = (Graph) object; - return graph.name.equals(name); - } - - /** - * Called when the server owner decides to opt-out of BukkitMetrics while the server is running. - */ - protected void onOptOut() { - } - } - - /** - * Interface used to collect custom data for a plugin - */ - public static abstract class Plotter { - - /** - * The plot's name - */ - private final String name; - - /** - * Construct a plotter with the default plot name - */ - public Plotter() { - this("Default"); - } - - /** - * Construct a plotter with a specific plot name - * - * @param name the name of the plotter to use, which will show up on the website - */ - public Plotter(final String name) { - this.name = name; - } - - /** - * Get the current value for the plotted point. Since this function defers to an external function it may or may - * not return immediately thus cannot be guaranteed to be thread friendly or safe. This function can be called - * from any thread so care should be taken when accessing resources that need to be synchronized. - * - * @return the current value for the point to be plotted. - */ - public abstract int getValue(); - - /** - * Get the column name for the plotted point - * - * @return the plotted point's column name - */ - public String getColumnName() { - return name; - } - - /** - * Called after the website graphs have been updated - */ - public void reset() { - } - - @Override - public int hashCode() { - return getColumnName().hashCode(); - } - - @Override - public boolean equals(final Object object) { - if (!(object instanceof Plotter)) { - return false; - } - - final Plotter plotter = (Plotter) object; - return plotter.name.equals(name) && plotter.getValue() == getValue(); - } - } + /** + * The current revision number + */ + private final static int REVISION = 7; + + /** + * The base url of the metrics domain + */ + private static final String BASE_URL = "http://report.mcstats.org"; + + /** + * The url used to report a server's status + */ + private static final String REPORT_URL = "/plugin/%s"; + + /** + * Interval of time to ping (in minutes) + */ + private static final int PING_INTERVAL = 15; + + /** + * The plugin this metrics submits for + */ + private final Plugin plugin; + + /** + * All of the custom graphs to submit to metrics + */ + private final Set graphs = Collections.synchronizedSet(new HashSet()); + + /** + * The plugin configuration file + */ + private final YamlConfiguration configuration; + + /** + * The plugin configuration file + */ + private final File configurationFile; + + /** + * Unique server id + */ + private final String guid; + + /** + * Debug mode + */ + private final boolean debug; + + /** + * Lock for synchronization + */ + private final Object optOutLock = new Object(); + + /** + * The scheduled task + */ + private volatile BukkitTask task = null; + + public Metrics(final Plugin plugin) throws IOException { + if (plugin == null) { + throw new IllegalArgumentException("Plugin cannot be null"); + } + + this.plugin = plugin; + + // load the config + configurationFile = getConfigFile(); + configuration = YamlConfiguration.loadConfiguration(configurationFile); + + // add some defaults + configuration.addDefault("opt-out", false); + configuration.addDefault("guid", UUID.randomUUID().toString()); + configuration.addDefault("debug", false); + + // Do we need to create the file? + if (configuration.get("guid", null) == null) { + configuration.options().header("http://mcstats.org").copyDefaults(true); + configuration.save(configurationFile); + } + + // Load the guid then + guid = configuration.getString("guid"); + debug = configuration.getBoolean("debug", false); + } + + /** + * Construct and create a Graph that can be used to separate specific plotters to their own graphs on the metrics + * website. Plotters can be added to the graph object returned. + * + * @param name The name of the graph + * @return Graph object created. Will never return NULL under normal circumstances unless bad parameters are given + */ + public Graph createGraph(final String name) { + if (name == null) { + throw new IllegalArgumentException("Graph name cannot be null"); + } + + // Construct the graph object + final Graph graph = new Graph(name); + + // Now we can add our graph + graphs.add(graph); + + // and return back + return graph; + } + + /** + * Add a Graph object to BukkitMetrics that represents data for the plugin that should be sent to the backend + * + * @param graph The name of the graph + */ + public void addGraph(final Graph graph) { + if (graph == null) { + throw new IllegalArgumentException("Graph cannot be null"); + } + + graphs.add(graph); + } + + /** + * Start measuring statistics. This will immediately create an async repeating task as the plugin and send the + * initial data to the metrics backend, and then after that it will post in increments of PING_INTERVAL * 1200 + * ticks. + * + * @return True if statistics measuring is running, otherwise false. + */ + public boolean start() { + synchronized (optOutLock) { + // Did we opt out? + if (isOptOut()) { + return false; + } + + // Is metrics already running? + if (task != null) { + return true; + } + + // Begin hitting the server with glorious data + task = plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, new Runnable() { + + private boolean firstPost = true; + + public void run() { + try { + // This has to be synchronized or it can collide with the disable method. + synchronized (optOutLock) { + // Disable Task, if it is running and the server owner decided to opt-out + if (isOptOut() && task != null) { + task.cancel(); + task = null; + // Tell all plotters to stop gathering information. + for (Graph graph : graphs) { + graph.onOptOut(); + } + } + } + + // We use the inverse of firstPost because if it is the first time we are posting, + // it is not a interval ping, so it evaluates to FALSE + // Each time thereafter it will evaluate to TRUE, i.e PING! + postPlugin(!firstPost); + + // After the first post we set firstPost to false + // Each post thereafter will be a ping + firstPost = false; + } catch (IOException e) { + if (debug) { + Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage()); + } + } + } + }, 0, PING_INTERVAL * 1200); + + return true; + } + } + + /** + * Has the server owner denied plugin metrics? + * + * @return true if metrics should be opted out of it + */ + public boolean isOptOut() { + synchronized (optOutLock) { + try { + // Reload the metrics file + configuration.load(getConfigFile()); + } catch (IOException ex) { + if (debug) { + Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); + } + return true; + } catch (InvalidConfigurationException ex) { + if (debug) { + Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); + } + return true; + } + return configuration.getBoolean("opt-out", false); + } + } + + /** + * Enables metrics for the server by setting "opt-out" to false in the config file and starting the metrics task. + */ + public void enable() throws IOException { + // This has to be synchronized or it can collide with the check in the task. + synchronized (optOutLock) { + // Check if the server owner has already set opt-out, if not, set it. + if (isOptOut()) { + configuration.set("opt-out", false); + configuration.save(configurationFile); + } + + // Enable Task, if it is not running + if (task == null) { + start(); + } + } + } + + /** + * Disables metrics for the server by setting "opt-out" to true in the config file and canceling the metrics task. + */ + public void disable() throws IOException { + // This has to be synchronized or it can collide with the check in the task. + synchronized (optOutLock) { + // Check if the server owner has already set opt-out, if not, set it. + if (!isOptOut()) { + configuration.set("opt-out", true); + configuration.save(configurationFile); + } + + // Disable Task, if it is running + if (task != null) { + task.cancel(); + task = null; + } + } + } + + /** + * Gets the File object of the config file that should be used to store data such as the GUID and opt-out status + * + * @return the File object for the config file + */ + public File getConfigFile() { + // I believe the easiest way to get the base folder (e.g craftbukkit set via -P) for plugins to use + // is to abuse the plugin object we already have + // plugin.getDataFolder() => base/plugins/PluginA/ + // pluginsFolder => base/plugins/ + // The base is not necessarily relative to the startup directory. + File pluginsFolder = plugin.getDataFolder().getParentFile(); + + // return => base/plugins/PluginMetrics/config.yml + return new File(new File(pluginsFolder, "PluginMetrics"), "config.yml"); + } + + /** + * Generic method that posts a plugin to the metrics website + */ + private void postPlugin(final boolean isPing) throws IOException { + // Server software specific section + PluginDescriptionFile description = plugin.getDescription(); + String pluginName = description.getName(); + boolean onlineMode = Bukkit.getServer().getOnlineMode(); // TRUE if online mode is enabled + String pluginVersion = description.getVersion(); + String serverVersion = Bukkit.getVersion(); + int playersOnline = Utilities.getOnlinePlayers().size(); + + // END server software specific section -- all code below does not use any code outside of this class / Java + + // Construct the post data + StringBuilder json = new StringBuilder(1024); + json.append('{'); + + // The plugin's description file containg all of the plugin data such as name, version, author, etc + appendJSONPair(json, "guid", guid); + appendJSONPair(json, "plugin_version", pluginVersion); + appendJSONPair(json, "server_version", serverVersion); + appendJSONPair(json, "players_online", Integer.toString(playersOnline)); + + // New data as of R6 + String osname = System.getProperty("os.name"); + String osarch = System.getProperty("os.arch"); + String osversion = System.getProperty("os.version"); + String java_version = System.getProperty("java.version"); + int coreCount = Runtime.getRuntime().availableProcessors(); + + // normalize os arch .. amd64 -> x86_64 + if (osarch.equals("amd64")) { + osarch = "x86_64"; + } + + appendJSONPair(json, "osname", osname); + appendJSONPair(json, "osarch", osarch); + appendJSONPair(json, "osversion", osversion); + appendJSONPair(json, "cores", Integer.toString(coreCount)); + appendJSONPair(json, "auth_mode", onlineMode ? "1" : "0"); + appendJSONPair(json, "java_version", java_version); + + // If we're pinging, append it + if (isPing) { + appendJSONPair(json, "ping", "1"); + } + + if (graphs.size() > 0) { + synchronized (graphs) { + json.append(','); + json.append('"'); + json.append("graphs"); + json.append('"'); + json.append(':'); + json.append('{'); + + boolean firstGraph = true; + + final Iterator iter = graphs.iterator(); + + while (iter.hasNext()) { + Graph graph = iter.next(); + + StringBuilder graphJson = new StringBuilder(); + graphJson.append('{'); + + for (Plotter plotter : graph.getPlotters()) { + appendJSONPair(graphJson, plotter.getColumnName(), Integer.toString(plotter.getValue())); + } + + graphJson.append('}'); + + if (!firstGraph) { + json.append(','); + } + + json.append(escapeJSON(graph.getName())); + json.append(':'); + json.append(graphJson); + + firstGraph = false; + } + + json.append('}'); + } + } + + // close json + json.append('}'); + + // Create the url + URL url = new URL(BASE_URL + String.format(REPORT_URL, urlEncode(pluginName))); + + // Connect to the website + URLConnection connection; + + // Mineshafter creates a socks proxy, so we can safely bypass it + // It does not reroute POST requests so we need to go around it + if (isMineshafterPresent()) { + connection = url.openConnection(Proxy.NO_PROXY); + } else { + connection = url.openConnection(); + } + + + byte[] uncompressed = json.toString().getBytes(); + byte[] compressed = gzip(json.toString()); + + // Headers + connection.addRequestProperty("User-Agent", "MCStats/" + REVISION); + connection.addRequestProperty("Content-Type", "application/json"); + connection.addRequestProperty("Content-Encoding", "gzip"); + connection.addRequestProperty("Content-Length", Integer.toString(compressed.length)); + connection.addRequestProperty("Accept", "application/json"); + connection.addRequestProperty("Connection", "close"); + + connection.setDoOutput(true); + + if (debug) { + System.out.println("[Metrics] Prepared request for " + pluginName + " uncompressed=" + uncompressed.length + " compressed=" + compressed.length); + } + + // Write the data + OutputStream os = connection.getOutputStream(); + os.write(compressed); + os.flush(); + + // Now read the response + final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); + String response = reader.readLine(); + + // close resources + os.close(); + reader.close(); + + if (response == null || response.startsWith("ERR") || response.startsWith("7")) { + if (response == null) { + response = "null"; + } else if (response.startsWith("7")) { + response = response.substring(response.startsWith("7,") ? 2 : 1); + } + + throw new IOException(response); + } else { + // Is this the first update this hour? + if (response.equals("1") || response.contains("This is your first update this hour")) { + synchronized (graphs) { + final Iterator iter = graphs.iterator(); + + while (iter.hasNext()) { + final Graph graph = iter.next(); + + for (Plotter plotter : graph.getPlotters()) { + plotter.reset(); + } + } + } + } + } + } + + /** + * GZip compress a string of bytes + */ + public static byte[] gzip(String input) { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + GZIPOutputStream gzos = null; + + try { + gzos = new GZIPOutputStream(baos); + gzos.write(input.getBytes("UTF-8")); + } catch (IOException e) { + e.printStackTrace(); + } finally { + if (gzos != null) try { + gzos.close(); + } catch (IOException ignore) { + } + } + + return baos.toByteArray(); + } + + /** + * Check if mineshafter is present. If it is, we need to bypass it to send POST requests + * + * @return true if mineshafter is installed on the server + */ + private boolean isMineshafterPresent() { + try { + Class.forName("mineshafter.MineServer"); + return true; + } catch (Exception e) { + return false; + } + } + + /** + * Appends a json encoded key/value pair to the given string builder. + */ + private static void appendJSONPair(StringBuilder json, String key, String value) throws UnsupportedEncodingException { + boolean isValueNumeric = false; + + try { + if (value.equals("0") || !value.endsWith("0")) { + Double.parseDouble(value); + isValueNumeric = true; + } + } catch (NumberFormatException e) { + isValueNumeric = false; + } + + if (json.charAt(json.length() - 1) != '{') { + json.append(','); + } + + json.append(escapeJSON(key)); + json.append(':'); + + if (isValueNumeric) { + json.append(value); + } else { + json.append(escapeJSON(value)); + } + } + + /** + * Escape a string to create a valid JSON string + */ + private static String escapeJSON(String text) { + StringBuilder builder = new StringBuilder(); + + builder.append('"'); + for (int index = 0; index < text.length(); index++) { + char chr = text.charAt(index); + + switch (chr) { + case '"': + case '\\': + builder.append('\\'); + builder.append(chr); + break; + case '\b': + builder.append("\\b"); + break; + case '\t': + builder.append("\\t"); + break; + case '\n': + builder.append("\\n"); + break; + case '\r': + builder.append("\\r"); + break; + default: + if (chr < ' ') { + String t = "000" + Integer.toHexString(chr); + builder.append("\\u" + t.substring(t.length() - 4)); + } else { + builder.append(chr); + } + break; + } + } + builder.append('"'); + + return builder.toString(); + } + + /** + * Encode text as UTF-8 + * + * @param text the text to encode + * @return the encoded text, as UTF-8 + */ + private static String urlEncode(final String text) throws UnsupportedEncodingException { + return URLEncoder.encode(text, "UTF-8"); + } + + /** + * Represents a custom graph on the website + */ + public static class Graph { + + /** + * The graph's name, alphanumeric and spaces only :) If it does not comply to the above when submitted, it is + * rejected + */ + private final String name; + + /** + * The set of plotters that are contained within this graph + */ + private final Set plotters = new LinkedHashSet(); + + private Graph(final String name) { + this.name = name; + } + + /** + * Gets the graph's name + * + * @return the Graph's name + */ + public String getName() { + return name; + } + + /** + * Add a plotter to the graph, which will be used to plot entries + * + * @param plotter the plotter to add to the graph + */ + public void addPlotter(final Plotter plotter) { + plotters.add(plotter); + } + + /** + * Remove a plotter from the graph + * + * @param plotter the plotter to remove from the graph + */ + public void removePlotter(final Plotter plotter) { + plotters.remove(plotter); + } + + /** + * Gets an unmodifiable set of the plotter objects in the graph + * + * @return an unmodifiable {@link java.util.Set} of the plotter objects + */ + public Set getPlotters() { + return Collections.unmodifiableSet(plotters); + } + + @Override + public int hashCode() { + return name.hashCode(); + } + + @Override + public boolean equals(final Object object) { + if (!(object instanceof Graph)) { + return false; + } + + final Graph graph = (Graph) object; + return graph.name.equals(name); + } + + /** + * Called when the server owner decides to opt-out of BukkitMetrics while the server is running. + */ + protected void onOptOut() { + } + } + + /** + * Interface used to collect custom data for a plugin + */ + public static abstract class Plotter { + + /** + * The plot's name + */ + private final String name; + + /** + * Construct a plotter with the default plot name + */ + public Plotter() { + this("Default"); + } + + /** + * Construct a plotter with a specific plot name + * + * @param name the name of the plotter to use, which will show up on the website + */ + public Plotter(final String name) { + this.name = name; + } + + /** + * Get the current value for the plotted point. Since this function defers to an external function it may or may + * not return immediately thus cannot be guaranteed to be thread friendly or safe. This function can be called + * from any thread so care should be taken when accessing resources that need to be synchronized. + * + * @return the current value for the point to be plotted. + */ + public abstract int getValue(); + + /** + * Get the column name for the plotted point + * + * @return the plotted point's column name + */ + public String getColumnName() { + return name; + } + + /** + * Called after the website graphs have been updated + */ + public void reset() { + } + + @Override + public int hashCode() { + return getColumnName().hashCode(); + } + + @Override + public boolean equals(final Object object) { + if (!(object instanceof Plotter)) { + return false; + } + + final Plotter plotter = (Plotter) object; + return plotter.name.equals(name) && plotter.getValue() == getValue(); + } + } } \ No newline at end of file