From 468b90be43eccdde08de367d22a9218f20a7d849 Mon Sep 17 00:00:00 2001 From: Sn0wStorm Date: Sat, 23 Apr 2016 17:45:01 +0200 Subject: [PATCH 1/3] Changes for Distilling and 1.9 --- src/com/dre/brewery/Brew.java | 4 + src/com/dre/brewery/P.java | 1658 ++++++++--------- .../{Compat1_9.java => DrinkListener1_9.java} | 2 +- .../brewery/listeners/InventoryListener.java | 100 +- .../dre/brewery/listeners/PlayerListener.java | 12 +- 5 files changed, 899 insertions(+), 877 deletions(-) rename src/com/dre/brewery/listeners/{Compat1_9.java => DrinkListener1_9.java} (94%) diff --git a/src/com/dre/brewery/Brew.java b/src/com/dre/brewery/Brew.java index eb89a14..ec7d6ae 100644 --- a/src/com/dre/brewery/Brew.java +++ b/src/com/dre/brewery/Brew.java @@ -15,6 +15,7 @@ import org.bukkit.potion.PotionEffectType; public class Brew { // represents the liquid in the brewed Potions + public static Map potions = new HashMap(); public static Boolean colorInBarrels; // color the Lore while in Barrels public static Boolean colorInBrewer; // color the Lore while in Brewer @@ -307,6 +308,7 @@ public class Brew { } // Distilling section --------------- + // distill all custom potions in the brewer public static void distillAll(BrewerInventory inv, Boolean[] contents) { int slot = 0; @@ -369,6 +371,7 @@ public class Brew { } // Ageing Section ------------------ + public void age(ItemStack item, float time, byte woodType) { if (stat) { return; @@ -452,6 +455,7 @@ public class Brew { } // Lore ----------- + // Converts to/from qualitycolored Lore public void convertLore(PotionMeta meta, Boolean toQuality) { if (currentRecipe == null) { diff --git a/src/com/dre/brewery/P.java b/src/com/dre/brewery/P.java index b95abe8..6afbb95 100644 --- a/src/com/dre/brewery/P.java +++ b/src/com/dre/brewery/P.java @@ -1,829 +1,829 @@ -package com.dre.brewery; - -import com.dre.brewery.filedata.*; -import com.dre.brewery.integration.LogBlockBarrel; -import com.dre.brewery.integration.WGBarrel; -import com.dre.brewery.integration.WGBarrelNew; -import com.dre.brewery.integration.WGBarrelOld; -import com.dre.brewery.listeners.*; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.ListIterator; -import java.util.Map; -import java.util.UUID; -import org.apache.commons.lang.math.NumberUtils; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.World; -import org.bukkit.block.Block; -import org.bukkit.command.CommandSender; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; -import org.bukkit.inventory.ItemStack; -import org.bukkit.plugin.java.JavaPlugin; - -public class P extends JavaPlugin { - public static P p; - public static String configVersion = "1.3.1"; - public static boolean debug; - public static boolean useUUID; - public static boolean use1_9; - public static boolean updateCheck; - - // Third Party Enabled - public boolean useWG; //WorldGuard - public WGBarrel wg; - public boolean useLWC; //LWC - public boolean useLB; //LogBlock - public boolean useGP; //GriefPrevention - public boolean hasVault; - - // Listeners - public BlockListener blockListener; - public PlayerListener playerListener; - public EntityListener entityListener; - public InventoryListener inventoryListener; - public WorldListener worldListener; - public Compat1_9 compat1_9; - - // Language - public String language; - public LanguageReader languageReader; - - @Override - public void onEnable() { - p = this; - - // Version check - String v = Bukkit.getBukkitVersion(); - useUUID = !v.matches(".*1\\.[0-6].*") && !v.matches(".*1\\.7\\.[0-5].*"); - use1_9 = !v.matches(".*1\\.[0-8].*"); - if (use1_9) { - log("&cExperimental support for Bukkit 1.9 enabled."); - } - - // load the Config - try { - if (!readConfig()) { - p = null; - getServer().getPluginManager().disablePlugin(this); - return; - } - } catch (Exception e) { - e.printStackTrace(); - p = null; - getServer().getPluginManager().disablePlugin(this); - return; - } - readData(); - - // Setup Metrics - setupMetrics(); - - // Listeners - blockListener = new BlockListener(); - playerListener = new PlayerListener(); - entityListener = new EntityListener(); - inventoryListener = new InventoryListener(); - worldListener = new WorldListener(); - compat1_9 = new Compat1_9(); - getCommand("Brewery").setExecutor(new CommandListener()); - - p.getServer().getPluginManager().registerEvents(blockListener, p); - p.getServer().getPluginManager().registerEvents(playerListener, p); - p.getServer().getPluginManager().registerEvents(entityListener, p); - p.getServer().getPluginManager().registerEvents(inventoryListener, p); - p.getServer().getPluginManager().registerEvents(worldListener, p); - if (use1_9) { - p.getServer().getPluginManager().registerEvents(compat1_9, p); - } - - // Heartbeat - p.getServer().getScheduler().runTaskTimer(p, new BreweryRunnable(), 650, 1200); - p.getServer().getScheduler().runTaskTimer(p, new DrunkRunnable(), 120, 120); - - if (updateCheck) { - p.getServer().getScheduler().runTaskLaterAsynchronously(p, new UpdateChecker(), 135); - } - - this.log(this.getDescription().getName() + " enabled!"); - } - - @Override - public void onDisable() { - - // Disable listeners - HandlerList.unregisterAll(this); - - // Stop shedulers - getServer().getScheduler().cancelTasks(this); - - if (p == null) { - return; - } - - // save Data to Disk - DataSave.save(true); - - // save LanguageReader - languageReader.save(); - - // delete Data from Ram - Barrel.barrels.clear(); - BCauldron.bcauldrons.clear(); - BIngredients.possibleIngredients.clear(); - BIngredients.recipes.clear(); - BIngredients.cookedNames.clear(); - BPlayer.clear(); - Brew.potions.clear(); - Wakeup.wakeups.clear(); - Words.words.clear(); - - this.log(this.getDescription().getName() + " disabled!"); - } - - public void setupMetrics() { - try { - new com.dre.brewery.integration.Metrics(this).start(); - } catch (Exception ignored) { - } - } - - public void reload(CommandSender sender) { - // clear all existent config Data - BIngredients.possibleIngredients.clear(); - BIngredients.recipes.clear(); - BIngredients.cookedNames.clear(); - Words.words.clear(); - BPlayer.drainItems.clear(); - if (useLB) { - try { - LogBlockBarrel.clear(); - } catch (Exception e) { - e.printStackTrace(); - } - } - - // load the Config - try { - if (!readConfig()) { - p = null; - getServer().getPluginManager().disablePlugin(this); - return; - } - } catch (Exception e) { - e.printStackTrace(); - p = null; - getServer().getPluginManager().disablePlugin(this); - return; - } - - // save and load LanguageReader - languageReader.save(); - languageReader = new LanguageReader(new File(p.getDataFolder(), "languages/" + language + ".yml")); - - // Reload Recipes - Boolean successful = true; - for (Brew brew : Brew.potions.values()) { - if (!brew.reloadRecipe()) { - successful = false; - } - } - if (!successful) { - msg(sender, p.languageReader.get("Error_Recipeload")); - } - } - - public void msg(CommandSender sender, String msg) { - sender.sendMessage(color("&2[Brewery] &f" + msg)); - } - - public void log(String msg) { - this.msg(Bukkit.getConsoleSender(), msg); - } - - public void debugLog(String msg) { - if (debug) { - this.msg(Bukkit.getConsoleSender(), "&2[Debug] &f" + msg); - } - } - - public void errorLog(String msg) { - Bukkit.getConsoleSender().sendMessage(ChatColor.DARK_GREEN + "[Brewery] " + ChatColor.DARK_RED + "ERROR: " + ChatColor.RED + msg); - } - - public boolean readConfig() { - File file = new File(p.getDataFolder(), "config.yml"); - if (!checkConfigs()) { - return false; - } - FileConfiguration config = YamlConfiguration.loadConfiguration(file); - - // Set the Language - language = config.getString("language", "en"); - - // Load LanguageReader - languageReader = new LanguageReader(new File(p.getDataFolder(), "languages/" + language + ".yml")); - - // Check if config is the newest version - String version = config.getString("version", null); - if (version != null) { - if (!version.equals(configVersion)) { - new ConfigUpdater(file).update(version, language); - P.p.log("Config Updated to version: " + configVersion); - config = YamlConfiguration.loadConfiguration(file); - } - } - - // If the Update Checker should be enabled - updateCheck = config.getBoolean("updateCheck", false); - - // Third-Party - useWG = config.getBoolean("useWorldGuard", true) && getServer().getPluginManager().isPluginEnabled("WorldGuard"); - if (useWG) { - try { - try { - Class.forName("com.sk89q.worldguard.bukkit.RegionContainer"); - wg = new WGBarrelNew(); - } catch (ClassNotFoundException e) { - wg = new WGBarrelOld(); - } - } catch (Throwable e) { - wg = null; - P.p.errorLog("Failed loading WorldGuard Integration! Opening Barrels will NOT work!"); - P.p.errorLog("Brewery was tested with version 5.8 to 6.0 of WorldGuard!"); - P.p.errorLog("Disable the WorldGuard support in the config and do /brew reload"); - e.printStackTrace(); - } - } - useLWC = config.getBoolean("useLWC", true) && getServer().getPluginManager().isPluginEnabled("LWC"); - useGP = config.getBoolean("useGriefPrevention", true) && getServer().getPluginManager().isPluginEnabled("GriefPrevention"); - useLB = config.getBoolean("useLogBlock", false) && getServer().getPluginManager().isPluginEnabled("LogBlock"); - hasVault = getServer().getPluginManager().isPluginEnabled("Vault"); - - // various Settings - DataSave.autosave = config.getInt("autosave", 3); - debug = config.getBoolean("debug", false); - BPlayer.pukeItem = Material.matchMaterial(config.getString("pukeItem", "SOUL_SAND")); - BPlayer.hangoverTime = config.getInt("hangoverDays", 0) * 24 * 60; - BPlayer.overdrinkKick = config.getBoolean("enableKickOnOverdrink", false); - BPlayer.enableHome = config.getBoolean("enableHome", false); - BPlayer.enableLoginDisallow = config.getBoolean("enableLoginDisallow", false); - BPlayer.enablePuke = config.getBoolean("enablePuke", false); - BPlayer.homeType = config.getString("homeType", null); - Brew.colorInBarrels = config.getBoolean("colorInBarrels", false); - Brew.colorInBrewer = config.getBoolean("colorInBrewer", false); - PlayerListener.openEverywhere = config.getBoolean("openLargeBarrelEverywhere", false); - Words.log = config.getBoolean("logRealChat", false); - Words.commands = config.getStringList("distortCommands"); - Words.doSigns = config.getBoolean("distortSignText", false); - for (String bypass : config.getStringList("distortBypass")) { - Words.ignoreText.add(bypass.split(",")); - } - - // loading recipes - ConfigurationSection configSection = config.getConfigurationSection("recipes"); - if (configSection != null) { - for (String recipeId : configSection.getKeys(false)) { - BRecipe recipe = new BRecipe(configSection, recipeId); - if (recipe.isValid()) { - BIngredients.recipes.add(recipe); - } else { - errorLog("Loading the Recipe with id: '" + recipeId + "' failed!"); - } - } - } - - // loading cooked names and possible ingredients - configSection = config.getConfigurationSection("cooked"); - if (configSection != null) { - for (String ingredient : configSection.getKeys(false)) { - Material mat = Material.matchMaterial(ingredient); - if (mat == null && hasVault) { - try { - net.milkbowl.vault.item.ItemInfo vaultItem = net.milkbowl.vault.item.Items.itemByString(ingredient); - if (vaultItem != null) { - mat = vaultItem.getType(); - } - } catch (Exception e) { - P.p.errorLog("Could not check vault for Item Name"); - e.printStackTrace(); - } - } - if (mat != null) { - BIngredients.cookedNames.put(mat, (configSection.getString(ingredient, null))); - BIngredients.possibleIngredients.add(mat); - } else { - errorLog("Unknown Material: " + ingredient); - } - } - } - - // loading drainItems - List drainList = config.getStringList("drainItems"); - if (drainList != null) { - for (String drainString : drainList) { - String[] drainSplit = drainString.split("/"); - if (drainSplit.length > 1) { - Material mat = Material.matchMaterial(drainSplit[0]); - int strength = p.parseInt(drainSplit[1]); - if (mat == null && hasVault && strength > 0) { - try { - net.milkbowl.vault.item.ItemInfo vaultItem = net.milkbowl.vault.item.Items.itemByString(drainSplit[0]); - if (vaultItem != null) { - mat = vaultItem.getType(); - } - } catch (Exception e) { - P.p.errorLog("Could not check vault for Item Name"); - e.printStackTrace(); - } - } - if (mat != null && strength > 0) { - BPlayer.drainItems.put(mat, strength); - } - } - } - } - - // telling Words the path, it will load it when needed - Words.config = config; - - return true; - } - - // load all Data - public void readData() { - File file = new File(p.getDataFolder(), "data.yml"); - if (file.exists()) { - - FileConfiguration data = YamlConfiguration.loadConfiguration(file); - - // Check if data is the newest version - String version = data.getString("Version", null); - if (version != null) { - if (!version.equals(DataSave.dataVersion)) { - P.p.log("Data File is being updated..."); - new DataUpdater(data, file).update(version); - data = YamlConfiguration.loadConfiguration(file); - P.p.log("Data Updated to version: " + DataSave.dataVersion); - } - } - - // loading Ingredients into ingMap - Map ingMap = new HashMap(); - ConfigurationSection section = data.getConfigurationSection("Ingredients"); - if (section != null) { - for (String id : section.getKeys(false)) { - ConfigurationSection matSection = section.getConfigurationSection(id + ".mats"); - if (matSection != null) { - // matSection has all the materials + amount as Integers - ArrayList ingredients = deserializeIngredients(matSection); - ingMap.put(id, new BIngredients(ingredients, section.getInt(id + ".cookedTime", 0))); - } else { - errorLog("Ingredient id: '" + id + "' incomplete in data.yml"); - } - } - } - - // loading Brew - section = data.getConfigurationSection("Brew"); - if (section != null) { - // All sections have the UID as name - for (String uid : section.getKeys(false)) { - BIngredients ingredients = getIngredients(ingMap, section.getString(uid + ".ingId")); - int quality = section.getInt(uid + ".quality", 0); - int distillRuns = section.getInt(uid + ".distillRuns", 0); - float ageTime = (float) section.getDouble(uid + ".ageTime", 0.0); - float wood = (float) section.getDouble(uid + ".wood", -1.0); - String recipe = section.getString(uid + ".recipe", null); - boolean unlabeled = section.getBoolean(uid + ".unlabeled", false); - boolean persistent = section.getBoolean(uid + ".persist", false); - boolean stat = section.getBoolean(uid + ".stat", false); - - new Brew(parseInt(uid), ingredients, quality, distillRuns, ageTime, wood, recipe, unlabeled, persistent, stat); - } - } - - // loading BPlayer - section = data.getConfigurationSection("Player"); - if (section != null) { - // keys have players name - for (String name : section.getKeys(false)) { - try { - UUID.fromString(name); - if (!useUUID) { - continue; - } - } catch (IllegalArgumentException e) { - if (useUUID) { - continue; - } - } - - int quality = section.getInt(name + ".quality"); - int drunk = section.getInt(name + ".drunk"); - int offDrunk = section.getInt(name + ".offDrunk", 0); - boolean passedOut = section.getBoolean(name + ".passedOut", false); - - new BPlayer(name, quality, drunk, offDrunk, passedOut); - } - } - - for (World world : p.getServer().getWorlds()) { - if (world.getName().startsWith("DXL_")) { - loadWorldData(getDxlName(world.getName()), world); - } else { - loadWorldData(world.getUID().toString(), world); - } - } - - } else { - errorLog("No data.yml found, will create new one!"); - } - } - - public ArrayList deserializeIngredients(ConfigurationSection matSection) { - ArrayList ingredients = new ArrayList(); - for (String mat : matSection.getKeys(false)) { - String[] matSplit = mat.split(","); - ItemStack item = new ItemStack(Material.getMaterial(matSplit[0]), matSection.getInt(mat)); - if (matSplit.length == 2) { - item.setDurability((short) P.p.parseInt(matSplit[1])); - } - ingredients.add(item); - } - return ingredients; - } - - // returns Ingredients by id from the specified ingMap - public BIngredients getIngredients(Map ingMap, String id) { - if (!ingMap.isEmpty()) { - if (ingMap.containsKey(id)) { - return ingMap.get(id); - } - } - errorLog("Ingredient id: '" + id + "' not found in data.yml"); - return new BIngredients(); - } - - // loads BIngredients from an ingredient section - public BIngredients loadIngredients(ConfigurationSection section) { - if (section != null) { - return new BIngredients(deserializeIngredients(section), 0); - } else { - errorLog("Cauldron is missing Ingredient Section"); - } - return new BIngredients(); - } - - // load Block locations of given world - public void loadWorldData(String uuid, World world) { - - File file = new File(p.getDataFolder(), "data.yml"); - if (file.exists()) { - - FileConfiguration data = YamlConfiguration.loadConfiguration(file); - - // loading BCauldron - if (data.contains("BCauldron." + uuid)) { - ConfigurationSection section = data.getConfigurationSection("BCauldron." + uuid); - for (String cauldron : section.getKeys(false)) { - // block is splitted into x/y/z - String block = section.getString(cauldron + ".block"); - if (block != null) { - String[] splitted = block.split("/"); - if (splitted.length == 3) { - - Block worldBlock = world.getBlockAt(parseInt(splitted[0]), parseInt(splitted[1]), parseInt(splitted[2])); - BIngredients ingredients = loadIngredients(section.getConfigurationSection(cauldron + ".ingredients")); - int state = section.getInt(cauldron + ".state", 1); - - new BCauldron(worldBlock, ingredients, state); - } else { - errorLog("Incomplete Block-Data in data.yml: " + section.getCurrentPath() + "." + cauldron); - } - } else { - errorLog("Missing Block-Data in data.yml: " + section.getCurrentPath() + "." + cauldron); - } - } - } - - // loading Barrel - if (data.contains("Barrel." + uuid)) { - ConfigurationSection section = data.getConfigurationSection("Barrel." + uuid); - for (String barrel : section.getKeys(false)) { - // block spigot is splitted into x/y/z - String spigot = section.getString(barrel + ".spigot"); - if (spigot != null) { - String[] splitted = spigot.split("/"); - if (splitted.length == 3) { - - // load itemStacks from invSection - ConfigurationSection invSection = section.getConfigurationSection(barrel + ".inv"); - Block block = world.getBlockAt(parseInt(splitted[0]), parseInt(splitted[1]), parseInt(splitted[2])); - float time = (float) section.getDouble(barrel + ".time", 0.0); - byte sign = (byte) section.getInt(barrel + ".sign", 0); - String[] st = section.getString(barrel + ".st", "").split(","); - String[] wo = section.getString(barrel + ".wo", "").split(","); - - if (invSection != null) { - new Barrel(block, sign, st, wo, invSection.getValues(true), time); - } else { - // Barrel has no inventory - new Barrel(block, sign, st, wo, null, time); - } - - } else { - errorLog("Incomplete Block-Data in data.yml: " + section.getCurrentPath() + "." + barrel); - } - } else { - errorLog("Missing Block-Data in data.yml: " + section.getCurrentPath() + "." + barrel); - } - } - } - - // loading Wakeup - if (data.contains("Wakeup." + uuid)) { - ConfigurationSection section = data.getConfigurationSection("Wakeup." + uuid); - for (String wakeup : section.getKeys(false)) { - // loc of wakeup is splitted into x/y/z/pitch/yaw - String loc = section.getString(wakeup); - if (loc != null) { - String[] splitted = loc.split("/"); - if (splitted.length == 5) { - - double x = NumberUtils.toDouble(splitted[0]); - double y = NumberUtils.toDouble(splitted[1]); - double z = NumberUtils.toDouble(splitted[2]); - float pitch = NumberUtils.toFloat(splitted[3]); - float yaw = NumberUtils.toFloat(splitted[4]); - Location location = new Location(world, x, y, z, yaw, pitch); - - Wakeup.wakeups.add(new Wakeup(location)); - - } else { - errorLog("Incomplete Location-Data in data.yml: " + section.getCurrentPath() + "." + wakeup); - } - } - } - } - - } - } - - private boolean checkConfigs() { - File cfg = new File(p.getDataFolder(), "config.yml"); - if (!cfg.exists()) { - errorLog("No config.yml found, creating default file! You may want to choose a config according to your language!"); - InputStream defconf = getResource("config/en/config.yml"); - if (defconf == null) { - errorLog("default config file not found, your jarfile may be corrupt. Disabling Brewery!"); - return false; - } - try { - saveFile(defconf, getDataFolder(), "config.yml"); - } catch (IOException e) { - e.printStackTrace(); - return false; - } - } - if (!cfg.exists()) { - errorLog("default config file could not be copied, your jarfile may be corrupt. Disabling Brewery!"); - return false; - } - - File configs = new File(getDataFolder(), "configs"); - if (!configs.exists()) { - String lang[] = new String[] {"de", "en", "fr"}; - for (String l : lang) { - File lfold = new File(configs, l); - try { - saveFile(getResource("config/" + l + "/config.yml"), lfold, "config.yml"); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - File languages = new File(getDataFolder(), "languages"); - if (!languages.exists()) { - String lang[] = new String[] {"de", "en", "fr", "no"}; - for (String l : lang) { - try { - saveFile(getResource("languages/" + l + ".yml"), languages, l + ".yml"); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - return true; - } - - // Utility - - public int parseInt(String string) { - return NumberUtils.toInt(string, 0); - } - - // gets the Name of a DXL World - public String getDxlName(String worldName) { - File dungeonFolder = new File(worldName); - if (dungeonFolder.isDirectory()) { - for (File file : dungeonFolder.listFiles()) { - if (!file.isDirectory()) { - if (file.getName().startsWith(".id_")) { - return file.getName().substring(1).toLowerCase(); - } - } - } - } - return worldName; - } - - // create empty World save Sections - public void createWorldSections(ConfigurationSection section) { - for (World world : p.getServer().getWorlds()) { - String worldName = world.getName(); - if (worldName.startsWith("DXL_")) { - worldName = getDxlName(worldName); - } else { - worldName = world.getUID().toString(); - } - section.createSection(worldName); - } - } - - // prints a list of Strings at the specified page - public void list(CommandSender sender, ArrayList strings, int page) { - int pages = (int) Math.ceil(strings.size() / 7F); - if (page > pages || page < 1) { - page = 1; - } - - sender.sendMessage(color("&7-------------- &f" + languageReader.get("Etc_Page") + " &6" + page + "&f/&6" + pages + " &7--------------")); - - ListIterator iter = strings.listIterator((page - 1) * 7); - - for (int i = 0; i < 7; i++) { - if (iter.hasNext()) { - sender.sendMessage(color(iter.next())); - } else { - break; - } - } - } - - // Returns true if the Block can be destroyed by the Player or something else (null) - public boolean blockDestroy(Block block, Player player) { - switch (block.getType()) { - case CAULDRON: - // will only remove when existing - BCauldron.remove(block); - return true; - case FENCE: - case NETHER_FENCE: - case ACACIA_FENCE: - case BIRCH_FENCE: - case DARK_OAK_FENCE: - case IRON_FENCE: - case JUNGLE_FENCE: - case SPRUCE_FENCE: - // remove barrel and throw potions on the ground - Barrel barrel = Barrel.getBySpigot(block); - if (barrel != null) { - if (barrel.hasPermsDestroy(player)) { - barrel.remove(null, player); - return true; - } else { - return false; - } - } - return true; - case SIGN_POST: - case WALL_SIGN: - // remove small Barrels - Barrel barrel2 = Barrel.getBySpigot(block); - if (barrel2 != null) { - if (!barrel2.isLarge()) { - if (barrel2.hasPermsDestroy(player)) { - barrel2.remove(null, player); - return true; - } else { - return false; - } - } else { - barrel2.destroySign(); - } - } - return true; - case WOOD: - case WOOD_STAIRS: - case BIRCH_WOOD_STAIRS: - case JUNGLE_WOOD_STAIRS: - case SPRUCE_WOOD_STAIRS: - case ACACIA_STAIRS: - case DARK_OAK_STAIRS: - Barrel barrel3 = Barrel.getByWood(block); - if (barrel3 != null) { - if (barrel3.hasPermsDestroy(player)) { - barrel3.remove(block, player); - } else { - return false; - } - } - default: - break; - } - return true; - } - - public String color(String msg) { - if (msg != null) { - msg = ChatColor.translateAlternateColorCodes('&', msg); - } - return msg; - } - - public static void saveFile(InputStream in, File dest, String name) throws IOException { - if (in == null) return; - if (!dest.exists()) { - dest.mkdirs(); - } - File result = new File(dest, name); - if (result.exists()) { - return; - } - - OutputStream out = new FileOutputStream(result); - byte[] buffer = new byte[1024]; - - int length; - //copy the file content in bytes - while ((length = in.read(buffer)) > 0){ - out.write(buffer, 0, length); - } - - in.close(); - out.close(); - } - - // Returns either uuid or Name of player, depending on bukkit version - public static String playerString(Player player) { - if (useUUID) { - return player.getUniqueId().toString(); - } else { - return player.getName(); - } - } - - // returns the Player if online - public static Player getPlayerfromString(String name) { - if (useUUID) { - try { - return Bukkit.getPlayer(UUID.fromString(name)); - } catch (Exception e) { - return Bukkit.getPlayerExact(name); - } - } - return Bukkit.getPlayerExact(name); - } - - // Runnables - - public class DrunkRunnable implements Runnable { - @Override - public void run() { - if (!BPlayer.isEmpty()) { - BPlayer.drunkeness(); - } - } - } - - public class BreweryRunnable implements Runnable { - @Override - public void run() { - for (BCauldron cauldron : BCauldron.bcauldrons) { - cauldron.onUpdate();// runs every min to update cooking time - } - Barrel.onUpdate();// runs every min to check and update ageing time - BPlayer.onUpdate();// updates players drunkeness - - debugLog("Update"); - - DataSave.autoSave(); - } - - } - -} +package com.dre.brewery; + +import com.dre.brewery.filedata.*; +import com.dre.brewery.integration.LogBlockBarrel; +import com.dre.brewery.integration.WGBarrel; +import com.dre.brewery.integration.WGBarrelNew; +import com.dre.brewery.integration.WGBarrelOld; +import com.dre.brewery.listeners.*; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.ListIterator; +import java.util.Map; +import java.util.UUID; +import org.apache.commons.lang.math.NumberUtils; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; +import org.bukkit.inventory.ItemStack; +import org.bukkit.plugin.java.JavaPlugin; + +public class P extends JavaPlugin { + public static P p; + public static final String configVersion = "1.3.1"; + public static boolean debug; + public static boolean useUUID; + public static boolean use1_9; + public static boolean updateCheck; + + // Third Party Enabled + public boolean useWG; //WorldGuard + public WGBarrel wg; + public boolean useLWC; //LWC + public boolean useLB; //LogBlock + public boolean useGP; //GriefPrevention + public boolean hasVault; + + // Listeners + public BlockListener blockListener; + public PlayerListener playerListener; + public EntityListener entityListener; + public InventoryListener inventoryListener; + public WorldListener worldListener; + public DrinkListener1_9 drinkListener1_9; + + // Language + public String language; + public LanguageReader languageReader; + + @Override + public void onEnable() { + p = this; + + // Version check + String v = Bukkit.getBukkitVersion(); + useUUID = !v.matches(".*1\\.[0-6].*") && !v.matches(".*1\\.7\\.[0-5].*"); + use1_9 = !v.matches(".*1\\.[0-8].*"); + if (use1_9) { + log("&cExperimental support for Bukkit 1.9 enabled."); + } + + // load the Config + try { + if (!readConfig()) { + p = null; + getServer().getPluginManager().disablePlugin(this); + return; + } + } catch (Exception e) { + e.printStackTrace(); + p = null; + getServer().getPluginManager().disablePlugin(this); + return; + } + readData(); + + // Setup Metrics + setupMetrics(); + + // Listeners + blockListener = new BlockListener(); + playerListener = new PlayerListener(); + entityListener = new EntityListener(); + inventoryListener = new InventoryListener(); + worldListener = new WorldListener(); + drinkListener1_9 = new DrinkListener1_9(); + getCommand("Brewery").setExecutor(new CommandListener()); + + p.getServer().getPluginManager().registerEvents(blockListener, p); + p.getServer().getPluginManager().registerEvents(playerListener, p); + p.getServer().getPluginManager().registerEvents(entityListener, p); + p.getServer().getPluginManager().registerEvents(inventoryListener, p); + p.getServer().getPluginManager().registerEvents(worldListener, p); + if (use1_9) { + p.getServer().getPluginManager().registerEvents(drinkListener1_9, p); + } + + // Heartbeat + p.getServer().getScheduler().runTaskTimer(p, new BreweryRunnable(), 650, 1200); + p.getServer().getScheduler().runTaskTimer(p, new DrunkRunnable(), 120, 120); + + if (updateCheck) { + p.getServer().getScheduler().runTaskLaterAsynchronously(p, new UpdateChecker(), 135); + } + + this.log(this.getDescription().getName() + " enabled!"); + } + + @Override + public void onDisable() { + + // Disable listeners + HandlerList.unregisterAll(this); + + // Stop shedulers + getServer().getScheduler().cancelTasks(this); + + if (p == null) { + return; + } + + // save Data to Disk + DataSave.save(true); + + // save LanguageReader + languageReader.save(); + + // delete Data from Ram + Barrel.barrels.clear(); + BCauldron.bcauldrons.clear(); + BIngredients.possibleIngredients.clear(); + BIngredients.recipes.clear(); + BIngredients.cookedNames.clear(); + BPlayer.clear(); + Brew.potions.clear(); + Wakeup.wakeups.clear(); + Words.words.clear(); + + this.log(this.getDescription().getName() + " disabled!"); + } + + public void setupMetrics() { + try { + new com.dre.brewery.integration.Metrics(this).start(); + } catch (Exception ignored) { + } + } + + public void reload(CommandSender sender) { + // clear all existent config Data + BIngredients.possibleIngredients.clear(); + BIngredients.recipes.clear(); + BIngredients.cookedNames.clear(); + Words.words.clear(); + BPlayer.drainItems.clear(); + if (useLB) { + try { + LogBlockBarrel.clear(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + // load the Config + try { + if (!readConfig()) { + p = null; + getServer().getPluginManager().disablePlugin(this); + return; + } + } catch (Exception e) { + e.printStackTrace(); + p = null; + getServer().getPluginManager().disablePlugin(this); + return; + } + + // save and load LanguageReader + languageReader.save(); + languageReader = new LanguageReader(new File(p.getDataFolder(), "languages/" + language + ".yml")); + + // Reload Recipes + Boolean successful = true; + for (Brew brew : Brew.potions.values()) { + if (!brew.reloadRecipe()) { + successful = false; + } + } + if (!successful) { + msg(sender, p.languageReader.get("Error_Recipeload")); + } + } + + public void msg(CommandSender sender, String msg) { + sender.sendMessage(color("&2[Brewery] &f" + msg)); + } + + public void log(String msg) { + this.msg(Bukkit.getConsoleSender(), msg); + } + + public void debugLog(String msg) { + if (debug) { + this.msg(Bukkit.getConsoleSender(), "&2[Debug] &f" + msg); + } + } + + public void errorLog(String msg) { + Bukkit.getConsoleSender().sendMessage(ChatColor.DARK_GREEN + "[Brewery] " + ChatColor.DARK_RED + "ERROR: " + ChatColor.RED + msg); + } + + public boolean readConfig() { + File file = new File(p.getDataFolder(), "config.yml"); + if (!checkConfigs()) { + return false; + } + FileConfiguration config = YamlConfiguration.loadConfiguration(file); + + // Set the Language + language = config.getString("language", "en"); + + // Load LanguageReader + languageReader = new LanguageReader(new File(p.getDataFolder(), "languages/" + language + ".yml")); + + // Check if config is the newest version + String version = config.getString("version", null); + if (version != null) { + if (!version.equals(configVersion)) { + new ConfigUpdater(file).update(version, language); + P.p.log("Config Updated to version: " + configVersion); + config = YamlConfiguration.loadConfiguration(file); + } + } + + // If the Update Checker should be enabled + updateCheck = config.getBoolean("updateCheck", false); + + // Third-Party + useWG = config.getBoolean("useWorldGuard", true) && getServer().getPluginManager().isPluginEnabled("WorldGuard"); + if (useWG) { + try { + try { + Class.forName("com.sk89q.worldguard.bukkit.RegionContainer"); + wg = new WGBarrelNew(); + } catch (ClassNotFoundException e) { + wg = new WGBarrelOld(); + } + } catch (Throwable e) { + wg = null; + P.p.errorLog("Failed loading WorldGuard Integration! Opening Barrels will NOT work!"); + P.p.errorLog("Brewery was tested with version 5.8 to 6.0 of WorldGuard!"); + P.p.errorLog("Disable the WorldGuard support in the config and do /brew reload"); + e.printStackTrace(); + } + } + useLWC = config.getBoolean("useLWC", true) && getServer().getPluginManager().isPluginEnabled("LWC"); + useGP = config.getBoolean("useGriefPrevention", true) && getServer().getPluginManager().isPluginEnabled("GriefPrevention"); + useLB = config.getBoolean("useLogBlock", false) && getServer().getPluginManager().isPluginEnabled("LogBlock"); + hasVault = getServer().getPluginManager().isPluginEnabled("Vault"); + + // various Settings + DataSave.autosave = config.getInt("autosave", 3); + debug = config.getBoolean("debug", false); + BPlayer.pukeItem = Material.matchMaterial(config.getString("pukeItem", "SOUL_SAND")); + BPlayer.hangoverTime = config.getInt("hangoverDays", 0) * 24 * 60; + BPlayer.overdrinkKick = config.getBoolean("enableKickOnOverdrink", false); + BPlayer.enableHome = config.getBoolean("enableHome", false); + BPlayer.enableLoginDisallow = config.getBoolean("enableLoginDisallow", false); + BPlayer.enablePuke = config.getBoolean("enablePuke", false); + BPlayer.homeType = config.getString("homeType", null); + Brew.colorInBarrels = config.getBoolean("colorInBarrels", false); + Brew.colorInBrewer = config.getBoolean("colorInBrewer", false); + PlayerListener.openEverywhere = config.getBoolean("openLargeBarrelEverywhere", false); + Words.log = config.getBoolean("logRealChat", false); + Words.commands = config.getStringList("distortCommands"); + Words.doSigns = config.getBoolean("distortSignText", false); + for (String bypass : config.getStringList("distortBypass")) { + Words.ignoreText.add(bypass.split(",")); + } + + // loading recipes + ConfigurationSection configSection = config.getConfigurationSection("recipes"); + if (configSection != null) { + for (String recipeId : configSection.getKeys(false)) { + BRecipe recipe = new BRecipe(configSection, recipeId); + if (recipe.isValid()) { + BIngredients.recipes.add(recipe); + } else { + errorLog("Loading the Recipe with id: '" + recipeId + "' failed!"); + } + } + } + + // loading cooked names and possible ingredients + configSection = config.getConfigurationSection("cooked"); + if (configSection != null) { + for (String ingredient : configSection.getKeys(false)) { + Material mat = Material.matchMaterial(ingredient); + if (mat == null && hasVault) { + try { + net.milkbowl.vault.item.ItemInfo vaultItem = net.milkbowl.vault.item.Items.itemByString(ingredient); + if (vaultItem != null) { + mat = vaultItem.getType(); + } + } catch (Exception e) { + P.p.errorLog("Could not check vault for Item Name"); + e.printStackTrace(); + } + } + if (mat != null) { + BIngredients.cookedNames.put(mat, (configSection.getString(ingredient, null))); + BIngredients.possibleIngredients.add(mat); + } else { + errorLog("Unknown Material: " + ingredient); + } + } + } + + // loading drainItems + List drainList = config.getStringList("drainItems"); + if (drainList != null) { + for (String drainString : drainList) { + String[] drainSplit = drainString.split("/"); + if (drainSplit.length > 1) { + Material mat = Material.matchMaterial(drainSplit[0]); + int strength = p.parseInt(drainSplit[1]); + if (mat == null && hasVault && strength > 0) { + try { + net.milkbowl.vault.item.ItemInfo vaultItem = net.milkbowl.vault.item.Items.itemByString(drainSplit[0]); + if (vaultItem != null) { + mat = vaultItem.getType(); + } + } catch (Exception e) { + P.p.errorLog("Could not check vault for Item Name"); + e.printStackTrace(); + } + } + if (mat != null && strength > 0) { + BPlayer.drainItems.put(mat, strength); + } + } + } + } + + // telling Words the path, it will load it when needed + Words.config = config; + + return true; + } + + // load all Data + public void readData() { + File file = new File(p.getDataFolder(), "data.yml"); + if (file.exists()) { + + FileConfiguration data = YamlConfiguration.loadConfiguration(file); + + // Check if data is the newest version + String version = data.getString("Version", null); + if (version != null) { + if (!version.equals(DataSave.dataVersion)) { + P.p.log("Data File is being updated..."); + new DataUpdater(data, file).update(version); + data = YamlConfiguration.loadConfiguration(file); + P.p.log("Data Updated to version: " + DataSave.dataVersion); + } + } + + // loading Ingredients into ingMap + Map ingMap = new HashMap(); + ConfigurationSection section = data.getConfigurationSection("Ingredients"); + if (section != null) { + for (String id : section.getKeys(false)) { + ConfigurationSection matSection = section.getConfigurationSection(id + ".mats"); + if (matSection != null) { + // matSection has all the materials + amount as Integers + ArrayList ingredients = deserializeIngredients(matSection); + ingMap.put(id, new BIngredients(ingredients, section.getInt(id + ".cookedTime", 0))); + } else { + errorLog("Ingredient id: '" + id + "' incomplete in data.yml"); + } + } + } + + // loading Brew + section = data.getConfigurationSection("Brew"); + if (section != null) { + // All sections have the UID as name + for (String uid : section.getKeys(false)) { + BIngredients ingredients = getIngredients(ingMap, section.getString(uid + ".ingId")); + int quality = section.getInt(uid + ".quality", 0); + int distillRuns = section.getInt(uid + ".distillRuns", 0); + float ageTime = (float) section.getDouble(uid + ".ageTime", 0.0); + float wood = (float) section.getDouble(uid + ".wood", -1.0); + String recipe = section.getString(uid + ".recipe", null); + boolean unlabeled = section.getBoolean(uid + ".unlabeled", false); + boolean persistent = section.getBoolean(uid + ".persist", false); + boolean stat = section.getBoolean(uid + ".stat", false); + + new Brew(parseInt(uid), ingredients, quality, distillRuns, ageTime, wood, recipe, unlabeled, persistent, stat); + } + } + + // loading BPlayer + section = data.getConfigurationSection("Player"); + if (section != null) { + // keys have players name + for (String name : section.getKeys(false)) { + try { + UUID.fromString(name); + if (!useUUID) { + continue; + } + } catch (IllegalArgumentException e) { + if (useUUID) { + continue; + } + } + + int quality = section.getInt(name + ".quality"); + int drunk = section.getInt(name + ".drunk"); + int offDrunk = section.getInt(name + ".offDrunk", 0); + boolean passedOut = section.getBoolean(name + ".passedOut", false); + + new BPlayer(name, quality, drunk, offDrunk, passedOut); + } + } + + for (World world : p.getServer().getWorlds()) { + if (world.getName().startsWith("DXL_")) { + loadWorldData(getDxlName(world.getName()), world); + } else { + loadWorldData(world.getUID().toString(), world); + } + } + + } else { + errorLog("No data.yml found, will create new one!"); + } + } + + public ArrayList deserializeIngredients(ConfigurationSection matSection) { + ArrayList ingredients = new ArrayList(); + for (String mat : matSection.getKeys(false)) { + String[] matSplit = mat.split(","); + ItemStack item = new ItemStack(Material.getMaterial(matSplit[0]), matSection.getInt(mat)); + if (matSplit.length == 2) { + item.setDurability((short) P.p.parseInt(matSplit[1])); + } + ingredients.add(item); + } + return ingredients; + } + + // returns Ingredients by id from the specified ingMap + public BIngredients getIngredients(Map ingMap, String id) { + if (!ingMap.isEmpty()) { + if (ingMap.containsKey(id)) { + return ingMap.get(id); + } + } + errorLog("Ingredient id: '" + id + "' not found in data.yml"); + return new BIngredients(); + } + + // loads BIngredients from an ingredient section + public BIngredients loadIngredients(ConfigurationSection section) { + if (section != null) { + return new BIngredients(deserializeIngredients(section), 0); + } else { + errorLog("Cauldron is missing Ingredient Section"); + } + return new BIngredients(); + } + + // load Block locations of given world + public void loadWorldData(String uuid, World world) { + + File file = new File(p.getDataFolder(), "data.yml"); + if (file.exists()) { + + FileConfiguration data = YamlConfiguration.loadConfiguration(file); + + // loading BCauldron + if (data.contains("BCauldron." + uuid)) { + ConfigurationSection section = data.getConfigurationSection("BCauldron." + uuid); + for (String cauldron : section.getKeys(false)) { + // block is splitted into x/y/z + String block = section.getString(cauldron + ".block"); + if (block != null) { + String[] splitted = block.split("/"); + if (splitted.length == 3) { + + Block worldBlock = world.getBlockAt(parseInt(splitted[0]), parseInt(splitted[1]), parseInt(splitted[2])); + BIngredients ingredients = loadIngredients(section.getConfigurationSection(cauldron + ".ingredients")); + int state = section.getInt(cauldron + ".state", 1); + + new BCauldron(worldBlock, ingredients, state); + } else { + errorLog("Incomplete Block-Data in data.yml: " + section.getCurrentPath() + "." + cauldron); + } + } else { + errorLog("Missing Block-Data in data.yml: " + section.getCurrentPath() + "." + cauldron); + } + } + } + + // loading Barrel + if (data.contains("Barrel." + uuid)) { + ConfigurationSection section = data.getConfigurationSection("Barrel." + uuid); + for (String barrel : section.getKeys(false)) { + // block spigot is splitted into x/y/z + String spigot = section.getString(barrel + ".spigot"); + if (spigot != null) { + String[] splitted = spigot.split("/"); + if (splitted.length == 3) { + + // load itemStacks from invSection + ConfigurationSection invSection = section.getConfigurationSection(barrel + ".inv"); + Block block = world.getBlockAt(parseInt(splitted[0]), parseInt(splitted[1]), parseInt(splitted[2])); + float time = (float) section.getDouble(barrel + ".time", 0.0); + byte sign = (byte) section.getInt(barrel + ".sign", 0); + String[] st = section.getString(barrel + ".st", "").split(","); + String[] wo = section.getString(barrel + ".wo", "").split(","); + + if (invSection != null) { + new Barrel(block, sign, st, wo, invSection.getValues(true), time); + } else { + // Barrel has no inventory + new Barrel(block, sign, st, wo, null, time); + } + + } else { + errorLog("Incomplete Block-Data in data.yml: " + section.getCurrentPath() + "." + barrel); + } + } else { + errorLog("Missing Block-Data in data.yml: " + section.getCurrentPath() + "." + barrel); + } + } + } + + // loading Wakeup + if (data.contains("Wakeup." + uuid)) { + ConfigurationSection section = data.getConfigurationSection("Wakeup." + uuid); + for (String wakeup : section.getKeys(false)) { + // loc of wakeup is splitted into x/y/z/pitch/yaw + String loc = section.getString(wakeup); + if (loc != null) { + String[] splitted = loc.split("/"); + if (splitted.length == 5) { + + double x = NumberUtils.toDouble(splitted[0]); + double y = NumberUtils.toDouble(splitted[1]); + double z = NumberUtils.toDouble(splitted[2]); + float pitch = NumberUtils.toFloat(splitted[3]); + float yaw = NumberUtils.toFloat(splitted[4]); + Location location = new Location(world, x, y, z, yaw, pitch); + + Wakeup.wakeups.add(new Wakeup(location)); + + } else { + errorLog("Incomplete Location-Data in data.yml: " + section.getCurrentPath() + "." + wakeup); + } + } + } + } + + } + } + + private boolean checkConfigs() { + File cfg = new File(p.getDataFolder(), "config.yml"); + if (!cfg.exists()) { + errorLog("No config.yml found, creating default file! You may want to choose a config according to your language!"); + InputStream defconf = getResource("config/en/config.yml"); + if (defconf == null) { + errorLog("default config file not found, your jarfile may be corrupt. Disabling Brewery!"); + return false; + } + try { + saveFile(defconf, getDataFolder(), "config.yml"); + } catch (IOException e) { + e.printStackTrace(); + return false; + } + } + if (!cfg.exists()) { + errorLog("default config file could not be copied, your jarfile may be corrupt. Disabling Brewery!"); + return false; + } + + File configs = new File(getDataFolder(), "configs"); + if (!configs.exists()) { + String lang[] = new String[] {"de", "en", "fr"}; + for (String l : lang) { + File lfold = new File(configs, l); + try { + saveFile(getResource("config/" + l + "/config.yml"), lfold, "config.yml"); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + File languages = new File(getDataFolder(), "languages"); + if (!languages.exists()) { + String lang[] = new String[] {"de", "en", "fr", "no"}; + for (String l : lang) { + try { + saveFile(getResource("languages/" + l + ".yml"), languages, l + ".yml"); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + return true; + } + + // Utility + + public int parseInt(String string) { + return NumberUtils.toInt(string, 0); + } + + // gets the Name of a DXL World + public String getDxlName(String worldName) { + File dungeonFolder = new File(worldName); + if (dungeonFolder.isDirectory()) { + for (File file : dungeonFolder.listFiles()) { + if (!file.isDirectory()) { + if (file.getName().startsWith(".id_")) { + return file.getName().substring(1).toLowerCase(); + } + } + } + } + return worldName; + } + + // create empty World save Sections + public void createWorldSections(ConfigurationSection section) { + for (World world : p.getServer().getWorlds()) { + String worldName = world.getName(); + if (worldName.startsWith("DXL_")) { + worldName = getDxlName(worldName); + } else { + worldName = world.getUID().toString(); + } + section.createSection(worldName); + } + } + + // prints a list of Strings at the specified page + public void list(CommandSender sender, ArrayList strings, int page) { + int pages = (int) Math.ceil(strings.size() / 7F); + if (page > pages || page < 1) { + page = 1; + } + + sender.sendMessage(color("&7-------------- &f" + languageReader.get("Etc_Page") + " &6" + page + "&f/&6" + pages + " &7--------------")); + + ListIterator iter = strings.listIterator((page - 1) * 7); + + for (int i = 0; i < 7; i++) { + if (iter.hasNext()) { + sender.sendMessage(color(iter.next())); + } else { + break; + } + } + } + + // Returns true if the Block can be destroyed by the Player or something else (null) + public boolean blockDestroy(Block block, Player player) { + switch (block.getType()) { + case CAULDRON: + // will only remove when existing + BCauldron.remove(block); + return true; + case FENCE: + case NETHER_FENCE: + case ACACIA_FENCE: + case BIRCH_FENCE: + case DARK_OAK_FENCE: + case IRON_FENCE: + case JUNGLE_FENCE: + case SPRUCE_FENCE: + // remove barrel and throw potions on the ground + Barrel barrel = Barrel.getBySpigot(block); + if (barrel != null) { + if (barrel.hasPermsDestroy(player)) { + barrel.remove(null, player); + return true; + } else { + return false; + } + } + return true; + case SIGN_POST: + case WALL_SIGN: + // remove small Barrels + Barrel barrel2 = Barrel.getBySpigot(block); + if (barrel2 != null) { + if (!barrel2.isLarge()) { + if (barrel2.hasPermsDestroy(player)) { + barrel2.remove(null, player); + return true; + } else { + return false; + } + } else { + barrel2.destroySign(); + } + } + return true; + case WOOD: + case WOOD_STAIRS: + case BIRCH_WOOD_STAIRS: + case JUNGLE_WOOD_STAIRS: + case SPRUCE_WOOD_STAIRS: + case ACACIA_STAIRS: + case DARK_OAK_STAIRS: + Barrel barrel3 = Barrel.getByWood(block); + if (barrel3 != null) { + if (barrel3.hasPermsDestroy(player)) { + barrel3.remove(block, player); + } else { + return false; + } + } + default: + break; + } + return true; + } + + public String color(String msg) { + if (msg != null) { + msg = ChatColor.translateAlternateColorCodes('&', msg); + } + return msg; + } + + public static void saveFile(InputStream in, File dest, String name) throws IOException { + if (in == null) return; + if (!dest.exists()) { + dest.mkdirs(); + } + File result = new File(dest, name); + if (result.exists()) { + return; + } + + OutputStream out = new FileOutputStream(result); + byte[] buffer = new byte[1024]; + + int length; + //copy the file content in bytes + while ((length = in.read(buffer)) > 0){ + out.write(buffer, 0, length); + } + + in.close(); + out.close(); + } + + // Returns either uuid or Name of player, depending on bukkit version + public static String playerString(Player player) { + if (useUUID) { + return player.getUniqueId().toString(); + } else { + return player.getName(); + } + } + + // returns the Player if online + public static Player getPlayerfromString(String name) { + if (useUUID) { + try { + return Bukkit.getPlayer(UUID.fromString(name)); + } catch (Exception e) { + return Bukkit.getPlayerExact(name); + } + } + return Bukkit.getPlayerExact(name); + } + + // Runnables + + public class DrunkRunnable implements Runnable { + @Override + public void run() { + if (!BPlayer.isEmpty()) { + BPlayer.drunkeness(); + } + } + } + + public class BreweryRunnable implements Runnable { + @Override + public void run() { + for (BCauldron cauldron : BCauldron.bcauldrons) { + cauldron.onUpdate();// runs every min to update cooking time + } + Barrel.onUpdate();// runs every min to check and update ageing time + BPlayer.onUpdate();// updates players drunkeness + + debugLog("Update"); + + DataSave.autoSave(); + } + + } + +} diff --git a/src/com/dre/brewery/listeners/Compat1_9.java b/src/com/dre/brewery/listeners/DrinkListener1_9.java similarity index 94% rename from src/com/dre/brewery/listeners/Compat1_9.java rename to src/com/dre/brewery/listeners/DrinkListener1_9.java index 9ae2b63..ce093d4 100644 --- a/src/com/dre/brewery/listeners/Compat1_9.java +++ b/src/com/dre/brewery/listeners/DrinkListener1_9.java @@ -11,7 +11,7 @@ import org.bukkit.potion.PotionData; import org.bukkit.potion.PotionType; // Workaround to remove unwanted potion effects -public class Compat1_9 implements Listener { +public class DrinkListener1_9 implements Listener { @EventHandler public void onPlayerDrink(PlayerItemConsumeEvent event) { diff --git a/src/com/dre/brewery/listeners/InventoryListener.java b/src/com/dre/brewery/listeners/InventoryListener.java index c75aed6..2437615 100644 --- a/src/com/dre/brewery/listeners/InventoryListener.java +++ b/src/com/dre/brewery/listeners/InventoryListener.java @@ -12,6 +12,7 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.inventory.BrewEvent; +import org.bukkit.event.inventory.InventoryAction; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.inventory.InventoryOpenEvent; @@ -33,23 +34,24 @@ import com.dre.brewery.integration.LogBlockBarrel; /** * Updated for 1.9 to replicate the "Brewing" process for distilling. * Because of how metadata has changed, the brewer no longer triggers as previously described. - * So, I've added some event tracking and manual forcing of the brewing "animation" if the - * set of ingredients in the brewer can be distilled. + * So, I've added some event tracking and manual forcing of the brewing "animation" if the + * set of ingredients in the brewer can be distilled. * Nothing here should interfere with vanilla brewing. - * + * * Note in testing I did discover a few ways to "hack" brewing to distill your brews alongside * potions; put fuel and at least one "valid" water bottle w/ a brewing component. You can distill * two brews this way, just remove them before the "final" distillation or you will actually * brew the potion as well. - * + * * @author ProgrammerDan (1.9 distillation update only) */ public class InventoryListener implements Listener { - + /* === Recreating manually the prior BrewEvent behavior. === */ private HashSet trackedBrewmen = new HashSet(); private HashMap trackedBrewers = new HashMap(); - + private static final int DISTILLTIME = 401; + /** * Start tracking distillation for a person when they open the brewer window. * @param event @@ -60,11 +62,11 @@ public class InventoryListener implements Listener { HumanEntity player = event.getPlayer(); Inventory inv = event.getInventory(); if (player == null || inv == null || !(inv instanceof BrewerInventory)) return; - + P.p.debugLog("Starting brew inventory tracking"); trackedBrewmen.add(player.getUniqueId()); } - + /** * Stop tracking distillation for a person when they close the brewer window. * @param event @@ -75,7 +77,7 @@ public class InventoryListener implements Listener { HumanEntity player = event.getPlayer(); Inventory inv = event.getInventory(); if (player == null || inv == null || !(inv instanceof BrewerInventory)) return; - + P.p.debugLog("Stopping brew inventory tracking"); trackedBrewmen.remove(player.getUniqueId()); } @@ -84,7 +86,7 @@ public class InventoryListener implements Listener { * Clicking can either start or stop the new brew distillation tracking. * Note that server restart will halt any ongoing brewing processes and * they will _not_ restart until a new click event. - * + * * @param event the Click event. */ @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) @@ -93,53 +95,56 @@ public class InventoryListener implements Listener { HumanEntity player = event.getWhoClicked(); Inventory inv = event.getInventory(); if (player == null || inv == null || !(inv instanceof BrewerInventory)) return; - + UUID puid = player.getUniqueId(); if (!trackedBrewmen.contains(puid)) return; - + if (InventoryType.BREWING != inv.getType()) return; - + if (event.getAction() == InventoryAction.NOTHING) return; // Ignore clicks that do nothing + BrewerInventory brewer = (BrewerInventory) inv; final Block brewery = brewer.getHolder().getBlock(); - + // If we were already tracking the brewer, cancel any ongoing event due to the click. Integer curTask = trackedBrewers.get(brewery); if (curTask != null) { Bukkit.getScheduler().cancelTask(curTask); // cancel prior } - + // Now check if we should bother to track it. trackedBrewers.put(brewery, new BukkitRunnable() { - private int brewTime = 401; + private int brewTime = DISTILLTIME; @Override public void run() { BlockState now = brewery.getState(); if (now instanceof BrewingStand) { BrewingStand stand = (BrewingStand) now; - // check if still custom - BrewerInventory brewer = stand.getInventory(); - if (isCustomAndDistill(brewer) ) { - - // Still a valid brew distillation - brewTime = brewTime - 1; // count down. - stand.setBrewingTime(brewTime); // arbitrary for now - - if (brewTime <= 1) { // Done! - BrewEvent doBrew = new BrewEvent(brewery, brewer); - Bukkit.getServer().getPluginManager().callEvent(doBrew); - if (!doBrew.isCancelled()) { // BrewEvent _wasn't_ cancelled. - this.cancel(); - trackedBrewers.remove(brewery); - stand.setBrewingTime(0); - P.p.debugLog("All done distilling"); - } else { - brewTime = 401; // go again. - P.p.debugLog("Can distill more! Continuing."); - } + if (brewTime == DISTILLTIME) { // only check at the beginning (and end) for distillables + if (!isCustomAndDistill(stand.getInventory())) { + this.cancel(); + trackedBrewers.remove(brewery); + P.p.debugLog("nothing to distill"); + return; + } + } + + brewTime--; // count down. + stand.setBrewingTime(brewTime); // arbitrary for now + + if (brewTime <= 1) { // Done! + //BrewEvent doBrew = new BrewEvent(brewery, brewer); + //Bukkit.getServer().getPluginManager().callEvent(doBrew); + + BrewerInventory brewer = stand.getInventory(); + if (!runDistill(brewer)) { + this.cancel(); + trackedBrewers.remove(brewery); + stand.setBrewingTime(0); + P.p.debugLog("All done distilling"); + } else { + brewTime = DISTILLTIME; // go again. + P.p.debugLog("Can distill more! Continuing."); } - } else { - this.cancel(); - trackedBrewers.remove(brewery); } } else { this.cancel(); @@ -149,7 +154,7 @@ public class InventoryListener implements Listener { } }.runTaskTimer(P.p, 2l, 1l).getTaskId()); } - + private boolean isCustomAndDistill(BrewerInventory brewer) { ItemStack item = brewer.getItem(3); // ingredient if (item == null || Material.GLOWSTONE_DUST != item.getType()) return false; // need dust in the top slot. @@ -171,11 +176,16 @@ public class InventoryListener implements Listener { } return false; } - + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onBrew(BrewEvent event) { + if (runDistill(event.getContents())) { + event.setCancelled(true); + } + } + + private boolean runDistill(BrewerInventory inv) { int slot = 0; - BrewerInventory inv = event.getContents(); ItemStack item; boolean custom = false; Boolean[] contents = new Boolean[3]; @@ -200,10 +210,10 @@ public class InventoryListener implements Listener { slot++; } if (custom) { - event.setCancelled(true); Brew.distillAll(inv, contents); + return true; } - + return false; } // convert to non colored Lore when taking out of Barrel/Brewer @@ -233,7 +243,7 @@ public class InventoryListener implements Listener { } } } - + // block the pickup of items where getPickupDelay is > 1000 (puke) @EventHandler(ignoreCancelled = true) public void onInventoryPickupItem(InventoryPickupItemEvent event){ diff --git a/src/com/dre/brewery/listeners/PlayerListener.java b/src/com/dre/brewery/listeners/PlayerListener.java index e8c208c..d2d4db3 100644 --- a/src/com/dre/brewery/listeners/PlayerListener.java +++ b/src/com/dre/brewery/listeners/PlayerListener.java @@ -70,6 +70,14 @@ public class PlayerListener implements Listener { BCauldron.remove(clickedBlock); } return; + + // Its possible to empty a Cauldron with a Bucket in 1.9 + } else if (P.use1_9 && materialInHand == Material.BUCKET) { + if (BCauldron.getFillLevel(clickedBlock) == 2) { + // will only remove when existing + BCauldron.remove(clickedBlock); + } + return; } // Check if fire alive below cauldron when adding ingredients @@ -202,7 +210,7 @@ public class PlayerListener implements Listener { public void onPlayerChat(AsyncPlayerChatEvent event) { Words.playerChat(event); } - + // player commands while drunk, distort chat commands @EventHandler(priority = EventPriority.LOWEST) public void onCommandPreProcess(PlayerCommandPreprocessEvent event) { @@ -257,4 +265,4 @@ public class PlayerListener implements Listener { bplayer.disconnecting(); } } -} \ No newline at end of file +} From 0f38ef008f94aa191278a4e7318a0492bdc01b5c Mon Sep 17 00:00:00 2001 From: Sn0wStorm Date: Sat, 23 Apr 2016 18:51:29 +0200 Subject: [PATCH 2/3] Fixed too much drunk-pushing in 1.9 --- src/com/dre/brewery/BPlayer.java | 11 ++++++++--- src/com/dre/brewery/Barrel.java | 4 ++-- src/com/dre/brewery/P.java | 2 +- 3 files changed, 11 insertions(+), 6 deletions(-) diff --git a/src/com/dre/brewery/BPlayer.java b/src/com/dre/brewery/BPlayer.java index c577433..c31a9ec 100644 --- a/src/com/dre/brewery/BPlayer.java +++ b/src/com/dre/brewery/BPlayer.java @@ -229,8 +229,13 @@ public class BPlayer { if (time == 0) { // push him only to the side? or any direction // like now - push.setX(Math.random() - 0.5); - push.setZ(Math.random() - 0.5); + if (P.use1_9) { // Pushing is way stronger in 1.9 + push.setX((Math.random() - 0.5) / 2.0); + push.setZ((Math.random() - 0.5) / 2.0); + } else { + push.setX(Math.random() - 0.5); + push.setZ(Math.random() - 0.5); + } player.setVelocity(push); } else if (time < 0 && time > -10) { // push him some more in the same direction @@ -574,4 +579,4 @@ public class BPlayer { return -getQuality() + 11; } -} \ No newline at end of file +} diff --git a/src/com/dre/brewery/Barrel.java b/src/com/dre/brewery/Barrel.java index 4e79dbc..689b0a9 100644 --- a/src/com/dre/brewery/Barrel.java +++ b/src/com/dre/brewery/Barrel.java @@ -129,7 +129,7 @@ public class Barrel implements InventoryHolder { } } catch (Throwable e) { P.p.errorLog("Failed to Check WorldGuard for Barrel Open Permissions!"); - P.p.errorLog("Brewery was tested with version 5.8 to 6.0 of WorldGuard!"); + P.p.errorLog("Brewery was tested with version 5.8 to 6.1 of WorldGuard!"); P.p.errorLog("Disable the WorldGuard support in the config and do /brew reload"); e.printStackTrace(); P.p.msg(player, "&cError opening Barrel, please report to an Admin!"); @@ -146,7 +146,7 @@ public class Barrel implements InventoryHolder { } } catch (Throwable e) { P.p.errorLog("Failed to Check GriefPrevention for Barrel Open Permissions!"); - P.p.errorLog("Brewery only works with the latest release of GriefPrevention (7.8)"); + P.p.errorLog("Brewery was tested with GriefPrevention 14.5.1"); P.p.errorLog("Disable the GriefPrevention support in the config and do /brew reload"); e.printStackTrace(); P.p.msg(player, "&cError opening Barrel, please report to an Admin!"); diff --git a/src/com/dre/brewery/P.java b/src/com/dre/brewery/P.java index 6afbb95..499a636 100644 --- a/src/com/dre/brewery/P.java +++ b/src/com/dre/brewery/P.java @@ -70,7 +70,7 @@ public class P extends JavaPlugin { useUUID = !v.matches(".*1\\.[0-6].*") && !v.matches(".*1\\.7\\.[0-5].*"); use1_9 = !v.matches(".*1\\.[0-8].*"); if (use1_9) { - log("&cExperimental support for Bukkit 1.9 enabled."); + log("&eExperimental support for Bukkit 1.9 enabled."); } // load the Config From 37ecf87276b93bbef1731975175de6a4f9af6e96 Mon Sep 17 00:00:00 2001 From: Sn0wStorm Date: Wed, 27 Apr 2016 21:28:42 +0200 Subject: [PATCH 3/3] Fix Potion Colors, using PotionType Workaround additional misleading effects showing in Lore by hiding all Potion Effects --- src/com/dre/brewery/BIngredients.java | 31 ++---- src/com/dre/brewery/BRecipe.java | 11 +-- src/com/dre/brewery/Brew.java | 98 +++++++++---------- .../brewery/listeners/DrinkListener1_9.java | 3 +- 4 files changed, 56 insertions(+), 87 deletions(-) diff --git a/src/com/dre/brewery/BIngredients.java b/src/com/dre/brewery/BIngredients.java index e26896c..a475a31 100644 --- a/src/com/dre/brewery/BIngredients.java +++ b/src/com/dre/brewery/BIngredients.java @@ -1,16 +1,13 @@ package com.dre.brewery; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; import org.bukkit.Material; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.PotionMeta; import org.bukkit.potion.PotionEffectType; +import java.util.*; + public class BIngredients { public static Set possibleIngredients = new HashSet(); public static ArrayList recipes = new ArrayList(); @@ -83,11 +80,7 @@ public class BIngredients { Brew.addOrReplaceEffects(potionMeta, brew.getEffects(), brew.getQuality()); cookedName = cookRecipe.getName(quality); - if (P.use1_9) { - potionMeta.setMainEffect(Brew.PotionColor.valueOf(cookRecipe.getColor()).getEffect()); - } else { - potion.setDurability(Brew.PotionColor.valueOf(cookRecipe.getColor()).getColorId(false)); - } + Brew.PotionColor.valueOf(cookRecipe.getColor()).colorBrew(potionMeta, potion, false); } else { // new base potion @@ -95,22 +88,14 @@ public class BIngredients { if (state <= 1) { cookedName = P.p.languageReader.get("Brew_ThickBrew"); - if (P.use1_9) { - potionMeta.setMainEffect(Brew.PotionColor.BLUE.getEffect()); - } else { - potion.setDurability(Brew.PotionColor.BLUE.getColorId(false)); - } + Brew.PotionColor.BLUE.colorBrew(potionMeta, potion, false); } else { for (Material ingredient : materials.keySet()) { if (cookedNames.containsKey(ingredient)) { // if more than half of the ingredients is of one kind if (materials.get(ingredient) > (getIngredientsCount() / 2)) { cookedName = cookedNames.get(ingredient); - if (P.use1_9) { - potionMeta.setMainEffect(Brew.PotionColor.CYAN.getEffect()); - } else { - potion.setDurability(Brew.PotionColor.CYAN.getColorId(true)); - } + Brew.PotionColor.CYAN.colorBrew(potionMeta, potion, true); } } } @@ -119,11 +104,7 @@ public class BIngredients { if (cookedName == null) { // if no name could be found cookedName = P.p.languageReader.get("Brew_Undefined"); - if (P.use1_9) { - potionMeta.setMainEffect(Brew.PotionColor.CYAN.getEffect()); - } else { - potion.setDurability(Brew.PotionColor.CYAN.getColorId(true)); - } + Brew.PotionColor.CYAN.colorBrew(potionMeta, potion, true); } potionMeta.setDisplayName(P.p.color("&f" + cookedName)); diff --git a/src/com/dre/brewery/BRecipe.java b/src/com/dre/brewery/BRecipe.java index d772dc9..9a7c68d 100644 --- a/src/com/dre/brewery/BRecipe.java +++ b/src/com/dre/brewery/BRecipe.java @@ -1,13 +1,14 @@ package com.dre.brewery; -import java.util.ArrayList; -import java.util.List; import org.bukkit.Material; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.PotionMeta; import org.bukkit.potion.PotionEffectType; +import java.util.ArrayList; +import java.util.List; + public class BRecipe { private String[] name; @@ -204,11 +205,7 @@ public class BRecipe { Brew brew = new Brew(uid, bIngredients, quality, distillruns, getAge(), wood, getName(5), false, false, true); - if (P.use1_9) { - potionMeta.setMainEffect(Brew.PotionColor.valueOf(getColor()).getEffect()); - } else { - potion.setDurability(Brew.PotionColor.valueOf(getColor()).getColorId(false)); - } + Brew.PotionColor.valueOf(getColor()).colorBrew(potionMeta, potion, false); potionMeta.setDisplayName(P.p.color("&f" + getName(quality))); // This effect stores the UID in its Duration potionMeta.addCustomEffect((PotionEffectType.REGENERATION).createEffect((uid * 4), 0), true); diff --git a/src/com/dre/brewery/Brew.java b/src/com/dre/brewery/Brew.java index ec7d6ae..263e096 100644 --- a/src/com/dre/brewery/Brew.java +++ b/src/com/dre/brewery/Brew.java @@ -1,16 +1,20 @@ package com.dre.brewery; +import org.bukkit.Material; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.inventory.BrewerInventory; +import org.bukkit.inventory.ItemFlag; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.PotionMeta; +import org.bukkit.potion.PotionData; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; +import org.bukkit.potion.PotionType; + import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import org.bukkit.Material; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.inventory.BrewerInventory; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.PotionMeta; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; public class Brew { @@ -238,6 +242,7 @@ public class Brew { } public boolean canDistill() { + if (stat) return false; if (currentRecipe != null) { return currentRecipe.getDistillRuns() > distillRuns; } else if (distillRuns >= 6) { @@ -292,17 +297,9 @@ public class Brew { this.stat = stat; if (currentRecipe != null && canDistill()) { if (stat) { - if (P.use1_9) { - PotionMeta potionMeta = (PotionMeta) potion.getItemMeta(); - potionMeta.setMainEffect(PotionColor.valueOf(currentRecipe.getColor()).getEffect()); - } else { - potion.setDurability(PotionColor.valueOf(currentRecipe.getColor()).getColorId(false)); - } - } else if (P.use1_9) { - PotionMeta potionMeta = (PotionMeta) potion.getItemMeta(); - potionMeta.setMainEffect(PotionColor.valueOf(currentRecipe.getColor()).getEffect()); + PotionColor.valueOf(currentRecipe.getColor()).colorBrew(((PotionMeta) potion.getItemMeta()), potion, false); } else { - potion.setDurability(PotionColor.valueOf(currentRecipe.getColor()).getColorId(true)); + PotionColor.valueOf(currentRecipe.getColor()).colorBrew(((PotionMeta) potion.getItemMeta()), potion, true); } } } @@ -338,21 +335,13 @@ public class Brew { addOrReplaceEffects(potionMeta, getEffects(), quality); potionMeta.setDisplayName(P.p.color("&f" + recipe.getName(quality))); - if (P.use1_9) { - potionMeta.setMainEffect(PotionColor.valueOf(recipe.getColor()).getEffect()); - } else { - slotItem.setDurability(PotionColor.valueOf(recipe.getColor()).getColorId(canDistill())); - } + PotionColor.valueOf(recipe.getColor()).colorBrew(potionMeta, slotItem, canDistill()); } else { quality = 0; removeEffects(potionMeta); potionMeta.setDisplayName(P.p.color("&f" + P.p.languageReader.get("Brew_DistillUndefined"))); - if (P.use1_9) { - potionMeta.setMainEffect(PotionColor.GREY.getEffect()); - } else { - slotItem.setDurability(PotionColor.GREY.getColorId(canDistill())); - } + PotionColor.GREY.colorBrew(potionMeta, slotItem, canDistill()); } // Distill Lore @@ -394,20 +383,12 @@ public class Brew { addOrReplaceEffects(potionMeta, getEffects(), quality); potionMeta.setDisplayName(P.p.color("&f" + recipe.getName(quality))); - if (P.use1_9) { - potionMeta.setMainEffect(PotionColor.valueOf(recipe.getColor()).getEffect()); - } else { - item.setDurability(PotionColor.valueOf(recipe.getColor()).getColorId(canDistill())); - } + PotionColor.valueOf(recipe.getColor()).colorBrew(potionMeta, item, canDistill()); } else { quality = 0; removeEffects(potionMeta); potionMeta.setDisplayName(P.p.color("&f" + P.p.languageReader.get("Brew_BadPotion"))); - if (P.use1_9) { - potionMeta.setMainEffect(PotionColor.GREY.getEffect()); - } else { - item.setDurability(PotionColor.GREY.getColorId(canDistill())); - } + PotionColor.GREY.colorBrew(potionMeta, item, canDistill()); } } @@ -664,25 +645,25 @@ public class Brew { } public static enum PotionColor { - PINK(1, PotionEffectType.REGENERATION), - CYAN(2, PotionEffectType.SPEED), - ORANGE(3, PotionEffectType.FIRE_RESISTANCE), - GREEN(4, PotionEffectType.POISON), - BRIGHT_RED(5, PotionEffectType.HEAL), - BLUE(6, PotionEffectType.NIGHT_VISION), - BLACK(8, PotionEffectType.WEAKNESS), - RED(9, PotionEffectType.INCREASE_DAMAGE), - GREY(10, PotionEffectType.SLOW), - WATER(11, PotionEffectType.WATER_BREATHING), - DARK_RED(12, PotionEffectType.HARM), - BRIGHT_GREY(14, PotionEffectType.INVISIBILITY); + PINK(1, PotionType.REGEN), + CYAN(2, PotionType.SPEED), + ORANGE(3, PotionType.FIRE_RESISTANCE), + GREEN(4, PotionType.POISON), + BRIGHT_RED(5, PotionType.INSTANT_HEAL), + BLUE(6, PotionType.NIGHT_VISION), + BLACK(8, PotionType.WEAKNESS), + RED(9, PotionType.STRENGTH), + GREY(10, PotionType.SLOWNESS), + WATER(11, PotionType.WATER_BREATHING), + DARK_RED(12, PotionType.INSTANT_DAMAGE), + BRIGHT_GREY(14, PotionType.INVISIBILITY); private final int colorId; - private final PotionEffectType effect; + private final PotionType type; - private PotionColor(int colorId, PotionEffectType effect) { + private PotionColor(int colorId, PotionType type) { this.colorId = colorId; - this.effect = effect; + this.type = type; } // gets the Damage Value, that sets a color on the potion @@ -694,8 +675,17 @@ public class Brew { return (short) (colorId + 32); } - public PotionEffectType getEffect() { - return effect; + public PotionType getType() { + return type; + } + + public void colorBrew(PotionMeta meta, ItemStack potion, boolean destillable) { + if (P.use1_9) { + meta.setBasePotionData(new PotionData(getType())); + meta.addItemFlags(ItemFlag.HIDE_POTION_EFFECTS); + } else { + potion.setDurability(getColorId(destillable)); + } } } diff --git a/src/com/dre/brewery/listeners/DrinkListener1_9.java b/src/com/dre/brewery/listeners/DrinkListener1_9.java index ce093d4..ddaf94e 100644 --- a/src/com/dre/brewery/listeners/DrinkListener1_9.java +++ b/src/com/dre/brewery/listeners/DrinkListener1_9.java @@ -3,6 +3,7 @@ package com.dre.brewery.listeners; import com.dre.brewery.Brew; import org.bukkit.Material; import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerItemConsumeEvent; import org.bukkit.inventory.ItemStack; @@ -13,7 +14,7 @@ import org.bukkit.potion.PotionType; // Workaround to remove unwanted potion effects public class DrinkListener1_9 implements Listener { - @EventHandler + @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) public void onPlayerDrink(PlayerItemConsumeEvent event) { ItemStack item = event.getItem(); Brew brew = Brew.get(item);