diff --git a/pom.xml b/pom.xml index 19715b6..5c2a3e8 100644 --- a/pom.xml +++ b/pom.xml @@ -1,67 +1,82 @@ - - 4.0.0 - cz.boosik - boosCooldowns - 3.8.5 - boosCooldowns - jar - http://maven.apache.org - - UTF-8 - UTF-8 - - - - maven2-repository.dev.java.net - Java.net Repository for Maven - http://download.java.net/maven/2/ - default - - - - - bukkit-repo - http://repo.bukkit.org/content/groups/public/ - - - vault-repo - http://nexus.theyeticave.net/content/repositories/pub_releases - - - - - org.bukkit - bukkit - LATEST - - - net.milkbowl.vault - Vault - LATEST - - - - boosCooldowns - ${basedir}/src/main/java/ - - - . - true - ${basedir}/src/main/resources/ - - plugin.yml - - - - - - maven-compiler-plugin - 3.1 - - 1.7 - 1.7 - - - - - + + 4.0.0 + cz.boosik + boosCooldowns + 3.9.5 + boosCooldowns + jar + http://maven.apache.org + + UTF-8 + UTF-8 + 1.8 + R0.1 + v1_8_R1 + + + + maven2-repository.dev.java.net + Java.net Repository for Maven + http://download.java.net/maven/2/ + default + + + bukkit-plugins + http://repo.bukkit.org/content/groups/public/ + + + + + bukkit-repo + http://repo.bukkit.org/content/groups/public/ + + + vault-repo + http://nexus.theyeticave.net/content/repositories/pub_releases + + + spigot-repo + http://repo.md-5.net/content/repositories/snapshots/ + + + + + org.bukkit + bukkit + ${minecraft.version}-${bukkit.version}-SNAPSHOT + provided + true + + + net.milkbowl.vault + Vault + LATEST + + + + boosCooldowns + ${basedir}/src/main/java/ + + + . + true + ${basedir}/src/main/resources/ + + plugin.yml + config.yml + + + + + + maven-compiler-plugin + 3.1 + + 1.7 + 1.7 + + + + + diff --git a/src/main/java/cz/boosik/boosCooldown/BoosConfigManager.java b/src/main/java/cz/boosik/boosCooldown/BoosConfigManager.java index d0d0d53..c8f2330 100644 --- a/src/main/java/cz/boosik/boosCooldown/BoosConfigManager.java +++ b/src/main/java/cz/boosik/boosCooldown/BoosConfigManager.java @@ -1,943 +1,896 @@ -package cz.boosik.boosCooldown; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.Arrays; -import java.util.List; -import java.util.Set; -import java.util.UUID; - -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.InvalidConfigurationException; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.entity.Player; - -/** - * T��da zaji��uj�c� ve�ker� metody, kter� se staraj� o konfiguraci pluginu a o - * datab�zi. - * - * @author Jakub Kol�� - * - */ -public class BoosConfigManager { - - private static YamlConfiguration conf; - private static YamlConfiguration confusers; - private static File confFile; - private static File confusersFile; - - /** - * Metoda zaji��uj�c� smaz�n� ve�ker�ch aktivn�ch cooldown a warmup �asova�� - * v�ech hr���. - */ - static void clear() { - ConfigurationSection userSection = confusers - .getConfigurationSection("users"); - if (userSection == null) - return; - for (String user : userSection.getKeys(false)) { - // clear cooldown - ConfigurationSection cooldown = confusers - .getConfigurationSection("users." + user + ".cooldown"); - if (cooldown != null) { - for (String key : cooldown.getKeys(false)) { - confusers.set("users." + user + ".cooldown." + key, null); - } - } - confusers.set("users." + user + ".cooldown", null); - - // clear warmup - ConfigurationSection warmup = confusers - .getConfigurationSection("users." + user + ".warmup"); - if (warmup != null) { - for (String key : warmup.getKeys(false)) { - confusers.set("users." + user + ".warmup." + key, null); - } - } - confusers.set("users." + user + ".warmup", null); - - confusers.set("users." + user, null); - } - saveConfusers(); - loadConfusers(); - } - - /** - * Metoda vyma�e ve�ker� hodnoty specifick�ho hr��e ve specifick� sekci - * datab�ze. - * - * @param co - * sekce datab�ze (warmup, cooldown, uses) - * @param uuid - * jm�no hr��e pro kret�ho se m� vymazat ��st datab�ze - */ - public static void clearSomething(String co, UUID uuid) { - ConfigurationSection userSection = confusers - .getConfigurationSection("users." + uuid + "." + co); - if (userSection == null) - return; - confusers.set("users." + uuid + "." + co, null); - saveConfusers(); - loadConfusers(); - } - - /** - * Metoda vyma�e hodnoty specifick�ho p��kazu, specifick�ho hr��e ve - * specifick� sekci datab�ze. - * - * @param co - * sekce datab�ze (warmup, cooldown, uses) - * @param uuid - * jm�no hr��e pro kret�ho se m� vymazat ��st datab�ze - * @param command - * p��kaz pro kter� se maj� vymazat hodnoty - */ - static void clearSomething(String co, UUID uuid, String command) { - int pre2 = command.toLowerCase().hashCode(); - confusers.set("users." + uuid + "." + co + "." + pre2, 0); - saveConfusers(); - loadConfusers(); - } - - /** - * @param message - * @return - */ - static String getAlias(String message) { - return conf.getString("commands.aliases." + message); - } - - /** - * @return - */ - static Set getAliases() { - Set aliases = conf.getConfigurationSection("commands.aliases") - .getKeys(false); - return aliases; - } - - /** - * @return - */ - static Set getAliasesKeys() { - Set aliases = conf.getConfigurationSection("commands.aliases") - .getKeys(true); - return aliases; - } - - /** - * @return - */ - static boolean getBlockInteractDuringWarmup() { - return conf.getBoolean("options.options.block_interact_during_warmup", - false); - } - - /** - * @return - */ - public static String getCancelWarmupByGameModeChangeMessage() { - return conf.getString( - "options.messages.warmup_cancelled_by_gamemode_change", - "&6Warm-ups have been cancelled due to changing gamemode.&f"); - } - - /** - * @return - */ - static boolean getCancelWarmUpOnDamage() { - return conf - .getBoolean("options.options.cancel_warmup_on_damage", false); - } - - /** - * @return - */ - static boolean getCancelWarmUpOnGameModeChange() { - return conf.getBoolean( - "options.options.cancel_warmup_on_gamemode_change", false); - } - - /** - * @return - */ - static boolean getCancelWarmupOnMove() { - return conf.getBoolean("options.options.cancel_warmup_on_move", false); - } - - /** - * @return - */ - static boolean getCancelWarmupOnSneak() { - return conf.getBoolean("options.options.cancel_warmup_on_sneak", false); - } - - /** - * @return - */ - public static String getCancelWarmupOnSneakMessage() { - return conf.getString("options.messages.warmup_cancelled_by_sneak", - "&6Warm-ups have been cancelled due to sneaking.&f"); - } - - /** - * @return - */ - static boolean getCancelWarmupOnSprint() { - return conf - .getBoolean("options.options.cancel_warmup_on_sprint", false); - } - - /** - * @return - */ - public static String getCancelWarmupOnSprintMessage() { - return conf.getString("options.messages.warmup_cancelled_by_sprint", - "&6Warm-ups have been cancelled due to sprinting.&f"); - } - - /** - * @return - */ - public static String getCannotCreateSignMessage() { - return conf.getString("options.messages.cannot_create_sign", - "&6You are not allowed to create this kind of signs!&f"); - } - - /** - * @return - */ - public static String getCannotUseSignMessage() { - return conf.getString("options.messages.cannot_use_sign", - "&6You are not allowed to use this sign!&f"); - } - - /** - * @return - */ - public static boolean getCleanCooldownsOnDeath() { - return conf.getBoolean("options.options.clear_cooldowns_on_death", - false); - } - - /** - * @return - */ - public static boolean getCleanUsesOnDeath() { - return conf.getBoolean("options.options.clear_uses_on_death", false); - } - - /** - * @return - */ - static boolean getClearOnRestart() { - return conf.getBoolean("options.options.clear_on_restart", false); - } - - /** - * @return - */ - static String getCommandBlockedMessage() { - return conf.getString("options.messages.limit_achieved", - "&6You cannot use this command anymore!&f"); - } - - /** - * @param player - * @return - */ - static String getCommandGroup(Player player) { - String cmdGroup = "default"; - for (String group : getCommandGroups()) { - if (player.hasPermission("booscooldowns." + group)) { - cmdGroup = group; - } - } - return cmdGroup; - } - - /** - * @return - */ - static Set getCommandGroups() { - Set groups = conf.getConfigurationSection("commands.groups") - .getKeys(false); - return groups; - } - - /** - * @return - */ - static boolean getCommandLogging() { - return conf.getBoolean("options.options.command_logging", false); - } - - /** - * @param player - * @return - */ - static Set getCommands(Player player) { - String group = getCommandGroup(player); - Set commands = conf.getConfigurationSection( - "commands.groups." + group).getKeys(false); - return commands; - } - - /** - * @param regexCommand - * @param player - * @return - */ - // static String[] getCommandValues(String regexCommand, Player player) { - // String[] values; - // String line = ""; - // String group = getCommandGroup(player); - // line = conf.getString("commands.groups." + group + "." + regexCommand, - // line); - // values = line.split(","); - // return values; - // } - - /** - * @return - */ - static YamlConfiguration getConfusers() { - return confusers; - } - - /** - * @param regexCommand - * @param player - * @return - */ - static int getCoolDown(String regexCommand, Player player) { - int coolDown; - String group = getCommandGroup(player); - coolDown = conf.getInt("commands.groups." + group + "." + regexCommand - + ".cooldown", 0); - return coolDown; - } - - /** - * @return - */ - static boolean getCooldownEnabled() { - return conf.getBoolean("options.options.cooldowns_enabled", true); - } - - /** - * @return - */ - static String getCoolDownMessage() { - return conf - .getString( - "options.messages.cooling_down", - "&6Wait&e &seconds& seconds&6 before you can use command&e &command& &6again.&f"); - } - - /** - * @param player - * @return - */ - static Set getCooldowns(Player player) { - String cool = getCommandGroup(player); - Set cooldowns = conf.getConfigurationSection( - "commands.groups." + cool).getKeys(false); - return cooldowns; - } - - /** - * @return - */ - static String getInsufficientFundsMessage() { - return conf - .getString( - "options.messages.insufficient_funds", - "&6You have insufficient funds!&e &command& &6costs &e%s &6but you only have &e%s"); - } - - /** - * @return - */ - public static String getInteractBlockedMessage() { - return conf.getString( - "options.messages.interact_blocked_during_warmup", - "&6You can't do this when command is warming-up!&f"); - } - - /** - * @param regexCommand - * @param player - * @return - */ - static String getItemCostItem(String regexCommand, Player player) { - String item = ""; - String temp; - String[] command; - String group = getCommandGroup(player); - temp = conf.getString("commands.groups." + group + "." + regexCommand - + ".itemcost", ""); - command = temp.split(","); - if (command.length == 2) { - item = command[0]; - } - return item; - } - - /** - * @param regexCommand - * @param player - * @return - */ - static int getItemCostCount(String regexCommand, Player player) { - int count = 0; - String temp; - String[] command; - String group = getCommandGroup(player); - temp = conf.getString("commands.groups." + group + "." + regexCommand - + ".itemcost", ""); - command = temp.split(","); - if (command.length == 2) { - count = Integer.valueOf(command[1]); - } - return count; - } - - /** - * @param regexCommand - * @param player - * @return - */ - static int getLimit(String regexCommand, Player player) { - int limit; - String group = getCommandGroup(player); - limit = conf.getInt("commands.groups." + group + "." + regexCommand - + ".limit", -1); - return limit; - } - - /** - * @return - */ - static boolean getLimitEnabled() { - return conf.getBoolean("options.options.limits_enabled", true); - } - - /** - * @return - */ - static String getLimitListMessage() { - return conf - .getString( - "options.messages.limit_list", - "&6Limit for command &e&command&&6 is &e&limit&&6. You can still use it &e×&&6 times.&f"); - } - - /** - * @return - */ - static boolean getLimitsEnabled() { - return conf.getBoolean("options.options.limits_enabled", true); - } - - /** - * @param pre - * @return - */ - static String getLink(String pre) { - String link = null; - pre = pre.toLowerCase(); - link = conf.getString("commands.links.link." + pre, link); - return link; - } - - /** - * @param link - * @return - */ - static List getLinkList(String link) { - List linkGroup; - link = link.toLowerCase(); - linkGroup = conf.getStringList("commands.links.linkGroups." + link); - return linkGroup; - } - - /** - * @param regexCommand - * @param player - * @return - */ - static String getMessage(String regexCommand, Player player) { - String message = ""; - String group = getCommandGroup(player); - message = conf.getString("commands.groups." + group + "." - + regexCommand + ".message", ""); - return message; - } - - /** - * @return - */ - static String getPaidErrorMessage() { - return conf.getString("options.messages.paid_error", - "An error has occured: %s"); - } - - /** - * @return - */ - static String getPaidForCommandMessage() { - return conf.getString("options.messages.paid_for_command", - "Price of &command& was %s and you now have %s"); - } - - /** - * @param regexCommand - * @param player - * @return - */ - static String getPotionEffect(String regexCommand, Player player) { - String effect = ""; - String temp; - String[] command; - String group = getCommandGroup(player); - temp = conf.getString("commands.groups." + group + "." + regexCommand - + ".potion", ""); - command = temp.split(","); - if (command.length == 2) { - effect = command[0]; - } - return effect; - } - - /** - * @param regexCommand - * @param player - * @return - */ - static int getPotionEffectStrength(String regexCommand, Player player) { - int effect = 0; - String temp; - String[] command; - String group = getCommandGroup(player); - temp = conf.getString("commands.groups." + group + "." + regexCommand - + ".potion", ""); - command = temp.split(","); - if (command.length == 2) { - effect = Integer.valueOf(command[1]); - } - return effect; - } - - /** - * @param regexCommand - * @param player - * @return - */ - static double getPrice(String regexCommand, Player player) { - double price; - String group = getCommandGroup(player); - price = conf.getDouble("commands.groups." + group + "." + regexCommand - + ".price", 0.0); - return price; - } - - /** - * @return - */ - static boolean getPriceEnabled() { - return conf.getBoolean("options.options.prices_enabled", true); - } - - /** - * @return - */ - static int getSaveInterval() { - return conf.getInt("options.options.save_interval_in_minutes", 15); - } - - /** - * @return - */ - static boolean getSignCommands() { - return conf.getBoolean("options.options.command_signs", false); - } - - /** - * @return - */ - public static boolean getStartCooldownsOnDeath() { - return conf.getBoolean("options.options.start_cooldowns_on_death", - false); - } - - /** - * @return - */ - static String getUnitHoursMessage() { - return conf.getString("options.units.hours", "hours"); - } - - /** - * @return - */ - static String getUnitMinutesMessage() { - return conf.getString("options.units.minutes", "minutes"); - } - - /** - * @return - */ - static String getUnitSecondsMessage() { - return conf.getString("options.units.seconds", "seconds"); - } - - /** - * @param regexCommand - * @param player - * @return - */ - static int getWarmUp(String regexCommand, Player player) { - int warmUp; - String group = getCommandGroup(player); - warmUp = conf.getInt("commands.groups." + group + "." + regexCommand - + ".warmup", 0); - return warmUp; - } - - /** - * @return - */ - static String getWarmUpAlreadyStartedMessage() { - return conf.getString("options.messages.warmup_already_started", - "&6Warm-Up process for&e &command& &6has already started.&f"); - } - - /** - * @return - */ - public static String getWarmUpCancelledByDamageMessage() { - return conf.getString("options.messages.warmup_cancelled_by_damage", - "&6Warm-ups have been cancelled due to receiving damage.&f"); - } - - /** - * @return - */ - public static String getWarmUpCancelledByMoveMessage() { - return conf.getString("options.messages.warmup_cancelled_by_move", - "&6Warm-ups have been cancelled due to moving.&f"); - } - - /** - * @return - */ - static boolean getWarmupEnabled() { - return conf.getBoolean("options.options.warmups_enabled", true); - } - - /** - * @return - */ - static String getWarmUpMessage() { - return conf - .getString("options.messages.warming_up", - "&6Wait&e &seconds& seconds&6 before command&e &command& &6has warmed up.&f"); - } - - /** - * Metoda na�te konfigura�n� soubor z disku do pam�ti. - */ - static void load() { - try { - conf.load(confFile); - } catch (FileNotFoundException e) { - e.printStackTrace(); - BoosCoolDown.getLog().severe( - "[boosCooldowns] Configuration file not found!"); - } catch (IOException e) { - e.printStackTrace(); - BoosCoolDown.getLog().severe( - "[boosCooldowns] Could not read configuration file!"); - } catch (InvalidConfigurationException e) { - e.printStackTrace(); - BoosCoolDown.getLog().severe( - "[boosCooldowns] Configuration file is invalid!"); - } - } - - /** - * Metoda na�te soubor datab�ze z disku do pam�ti. - */ - static void loadConfusers() { - try { - confusers.load(confusersFile); - } catch (FileNotFoundException e) { - e.printStackTrace(); - BoosCoolDown.getLog().severe( - "[boosCooldowns] Storage file not found!"); - } catch (IOException e) { - e.printStackTrace(); - BoosCoolDown.getLog().severe( - "[boosCooldowns] Could not read storage file!"); - } catch (InvalidConfigurationException e) { - e.printStackTrace(); - BoosCoolDown.getLog().severe( - "[boosCooldowns] Storage file is invalid!"); - } - } - - /** - * Metoda znovu na�te konfigura�n� soubor z disku do pam�ti. - */ - static void reload() { - conf = new YamlConfiguration(); - load(); - } - - /** - * Metoda ulo�� soubor datab�ze z pam�ti na disk. - */ - static void saveConfusers() { - try { - confFile.createNewFile(); - confusers.save(confusersFile); - } catch (IOException e) { - e.printStackTrace(); - BoosCoolDown.getLog().severe( - "[boosCooldowns] Could not save storage file!"); - } - } - - /** - * Metoda p�id�v� z�znamy do konfigura�n�ho souboru, kter� pot� ulo�� na - * disk a znovu jej na�te z disku do pam�ti. - * - * @param coSetnout - * n�zev skupiny pro kterou se m� p�idat z�znam do konfigura�n�ho - * souboru - * @param co - * p��kaz, pro kter� se m� p�idat hodnota do konfigura�n�ho - * souboru - * @param hodnota - * hodnota kter� se m� p�idat pro specifikovan� p��kaz - */ - static void setAddToConfigFile(String group, String command, String what, - String value) { - group = group.toLowerCase(); - command = command.toLowerCase(); - int value2; - try { - value2 = Integer.parseInt(value); - reload(); - conf.set("commands.groups." + group + "." + command + "." + what, - value2); - } catch (NumberFormatException e1) { - reload(); - conf.set("commands.groups." + group + "." + command + "." + what, - value); - } - try { - conf.save(confFile); - } catch (IOException e) { - BoosCoolDown.getLog().severe( - "[boosCooldowns] Could not save configuration file!"); - - } - reload(); - } - - /** - * Metoda vytv��ej�ci konfigura�n� a datab�zov� sobour, pokud tyto soubory - * ji� neexistuj�. Pokud soubory ji� existuj�, jsou na�teny z disku do - * pam�ti. - * - * @param boosCoolDown - */ - @SuppressWarnings("static-access") - BoosConfigManager(BoosCoolDown boosCoolDown) { - confFile = new File(boosCoolDown.getDataFolder(), "config.yml"); - if (confFile.exists()) { - conf = new YamlConfiguration(); - load(); - } else { - this.confFile = new File(boosCoolDown.getDataFolder(), "config.yml"); - this.conf = new YamlConfiguration(); - conf.options().copyDefaults(true); - conf.addDefault("options.options.warmups_enabled", true); - conf.addDefault("options.options.cooldowns_enabled", true); - conf.addDefault("options.options.prices_enabled", true); - conf.addDefault("options.options.item_cost_enabled", true); - conf.addDefault("options.options.xp_cost_enabled", true); - conf.addDefault("options.options.limits_enabled", true); - conf.addDefault( - "options.options.auto_save_enabled_CAN_CAUSE_BIG_LAGS", - false); - conf.addDefault("options.options.save_interval_in_minutes", 15); - conf.addDefault("options.options.cancel_warmup_on_damage", false); - conf.addDefault("options.options.cancel_warmup_on_move", false); - conf.addDefault("options.options.cancel_warmup_on_sneak", false); - conf.addDefault("options.options.cancel_warmup_on_sprint", false); - conf.addDefault("options.options.cancel_warmup_on_gamemode_change", - false); - conf.addDefault("options.options.block_interact_during_warmup", - false); - conf.addDefault("options.options.clear_on_restart", false); - conf.addDefault("options.options.clear_uses_on_death", false); - conf.addDefault("options.options.clear_cooldowns_on_death", false); - conf.addDefault("options.options.start_cooldowns_on_death", false); - conf.addDefault("options.options.command_logging", false); - conf.addDefault("options.options.command_signs", false); - conf.addDefault("options.units.seconds", "seconds"); - conf.addDefault("options.units.minutes", "minutes"); - conf.addDefault("options.units.hours", "hours"); - conf.addDefault("options.messages.warmup_cancelled_by_damage", - "&6Warm-ups have been cancelled due to receiving damage.&f"); - conf.addDefault("options.messages.warmup_cancelled_by_move", - "&6Warm-ups have been cancelled due to moving.&f"); - conf.addDefault("options.messages.warmup_cancelled_by_sprint", - "&6Warm-ups have been cancelled due to sprinting.&f"); - conf.addDefault("options.messages.warmup_cancelled_by_sneak", - "&6Warm-ups have been cancelled due to sneaking.&f"); - conf.addDefault( - "options.messages.warmup_cancelled_by_gamemode_change", - "&6Warm-ups have been cancelled due to changing gamemode.&f"); - conf.addDefault("options.messages.cooling_down", - "&6Wait&e &seconds& &unit&&6 before you can use command&e &command& &6again.&f"); - conf.addDefault("options.messages.warming_up", - "&6Wait&e &seconds& &unit&&6 before command&e &command& &6has warmed up.&f"); - conf.addDefault("options.messages.warmup_already_started", - "&6Warm-Up process for&e &command& &6has already started.&f"); - conf.addDefault("options.messages.paid_error", - "&6An error has occured:&e %s"); - conf.addDefault( - "options.messages.insufficient_funds", - "&6You have insufficient funds!&e &command& &6costs &e%s &6but you only have &e%s"); - conf.addDefault("options.messages.paid_for_command", - "&6Price of&e &command& &6was&e %s &6and you now have&e %s"); - conf.addDefault("options.messages.paid_items_for_command", - "&6Price of&e &command& &6was &e%s"); - conf.addDefault("options.messages.paid_xp_for_command", - "&6Price of&e &command& &6was &e%s levels"); - conf.addDefault("options.messages.insufficient_items", - "&6You have not enough items!&e &command& &6needs &e%s"); - conf.addDefault("options.messages.insufficient_xp", - "&6You have not enough XP!&e &command& &6needs &e%s"); - conf.addDefault("options.messages.limit_achieved", - "&6You cannot use this command anymore!&f"); - conf.addDefault( - "options.messages.limit_list", - "&6Limit for command &e&command&&6 is &e&limit&&6. You can still use it &e×&&6 times.&f"); - conf.addDefault("options.messages.interact_blocked_during_warmup", - "&6You can't do this when command is warming-up!&f"); - conf.addDefault("options.messages.cannot_create_sign", - "&6You are not allowed to create this kind of signs!&f"); - conf.addDefault("options.messages.cannot_use_sign", - "&6You are not allowed to use this sign!&f"); - } - if (confFile.exists()) { - load(); - } - try { - conf.addDefault( - "commands.groups.default./command parameter.cooldown", 2); - conf.addDefault( - "commands.groups.default./commandwithparameters *.cooldown", - 5); - conf.addDefault("commands.groups.default./anothercommand.cooldown", - 2); - conf.addDefault( - "commands.groups.default./yetanothercommand.warmup", 5); - conf.addDefault("commands.groups.default./yetanothercommand.price", - 10.0); - conf.addDefault("commands.groups.default./yetanothercommand.limit", - 5); - conf.addDefault( - "commands.groups.default./yetanothercommand.potion", - "WEAKNESS,3"); - conf.addDefault("commands.groups.default./test.message", - "You just used /test!"); - conf.addDefault("commands.groups.default./test.itemcost", - "STONE,10"); - conf.addDefault("commands.groups.default./test.xpcost", 6); - conf.addDefault("commands.groups.default.*.warmup", 1); - conf.addDefault("commands.groups.default.*.cooldown", 1); - conf.addDefault("commands.groups.default.*.price", 0.0); - conf.addDefault("commands.groups.default.*.limit", -1); - conf.addDefault("commands.groups.vip./command *.warmup", 5); - conf.addDefault("commands.links.link./lol", "default"); - conf.addDefault("commands.links.link./example", "default"); - conf.addDefault("commands.links.link./command", "default"); - conf.addDefault("commands.links.link./yourCommandHere", - "yourNameHere"); - String[] def = { "/lol", "/example" }; - conf.addDefault("commands.links.linkGroups.default", - Arrays.asList(def)); - String[] def2 = { "/yourCommandHere", "/someCommand", - "/otherCommand" }; - conf.addDefault("commands.links.linkGroups.yourNameHere", - Arrays.asList(def2)); - conf.addDefault("commands.aliases./newcommand", "/originalcommand"); - conf.addDefault("commands.aliases./new spawn command", - "/original spawn command"); - conf.save(confFile); - } catch (IOException e) { - e.printStackTrace(); - } - confusersFile = new File(boosCoolDown.getDataFolder(), "users.yml"); - confusers = new YamlConfiguration(); - if (confusersFile.exists()) { - loadConfusers(); - } else { - try { - confusersFile.createNewFile(); - } catch (IOException e) { - e.printStackTrace(); - BoosCoolDown.getLog().severe( - "[boosCooldowns] Could not save storage file!"); - } - } - } - - static boolean getAutoSave() { - return conf.getBoolean( - "options.options.auto_save_enabled_CAN_CAUSE_BIG_LAGS", false); - } - - public static String getPaidItemsForCommandMessage() { - return conf.getString("options.messages.paid_items_for_command", - "&6Price of&e &command& &6was &e%s"); - } - - public static String getInsufficientItemsMessage() { - return conf.getString("options.messages.insufficient_items", - "&6You have not enough items!&e &command& &6needs &e%s"); - } - - public static boolean getItemCostEnabled() { - return conf.getBoolean("options.options.item_cost_enabled", true); - } - - public static String getPaidXPForCommandMessage() { - return conf.getString("options.messages.paid_xp_for_command", - "&6Price of&e &command& &6was &e%s"); - } - - public static int getXpPrice(String regexCommand, Player player) { - int price; - String group = getCommandGroup(player); - price = conf.getInt("commands.groups." + group + "." + regexCommand - + ".xpcost", 0); - return price; - } - - public static boolean getXpPriceEnabled() { - return conf.getBoolean("options.options.xp_cost_enabled", true); - } - - public static String getInsufficientXpMessage() { - return conf.getString("options.messages.insufficient_xp", - "&6You have not enough XP!&e &command& &6needs &e%s"); - } -} +package cz.boosik.boosCooldown; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.Arrays; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; + +/** + * T��da zaji��uj�c� ve�ker� metody, kter� se staraj� o konfiguraci pluginu a o + * datab�zi. + * + * @author Jakub Kol�� + * + */ +public class BoosConfigManager { + + private static YamlConfiguration conf; + private static YamlConfiguration confusers; + private static File confFile; + private static File confusersFile; + + /** + * Metoda zaji��uj�c� smaz�n� ve�ker�ch aktivn�ch cooldown a warmup �asova�� + * v�ech hr���. + */ + static void clear() { + ConfigurationSection userSection = confusers + .getConfigurationSection("users"); + if (userSection == null) + return; + for (String user : userSection.getKeys(false)) { + // clear cooldown + ConfigurationSection cooldown = confusers + .getConfigurationSection("users." + user + ".cooldown"); + if (cooldown != null) { + for (String key : cooldown.getKeys(false)) { + confusers.set("users." + user + ".cooldown." + key, null); + } + } + confusers.set("users." + user + ".cooldown", null); + + // clear warmup + ConfigurationSection warmup = confusers + .getConfigurationSection("users." + user + ".warmup"); + if (warmup != null) { + for (String key : warmup.getKeys(false)) { + confusers.set("users." + user + ".warmup." + key, null); + } + } + confusers.set("users." + user + ".warmup", null); + + confusers.set("users." + user, null); + } + saveConfusers(); + loadConfusers(); + } + + /** + * Metoda vyma�e ve�ker� hodnoty specifick�ho hr��e ve specifick� sekci + * datab�ze. + * + * @param co + * sekce datab�ze (warmup, cooldown, uses) + * @param uuid + * jm�no hr��e pro kret�ho se m� vymazat ��st datab�ze + */ + public static void clearSomething(String co, UUID uuid) { + ConfigurationSection userSection = confusers + .getConfigurationSection("users." + uuid + "." + co); + if (userSection == null) + return; + confusers.set("users." + uuid + "." + co, null); + saveConfusers(); + loadConfusers(); + } + + /** + * Metoda vyma�e hodnoty specifick�ho p��kazu, specifick�ho hr��e ve + * specifick� sekci datab�ze. + * + * @param co + * sekce datab�ze (warmup, cooldown, uses) + * @param uuid + * jm�no hr��e pro kret�ho se m� vymazat ��st datab�ze + * @param command + * p��kaz pro kter� se maj� vymazat hodnoty + */ + static void clearSomething(String co, UUID uuid, String command) { + int pre2 = command.toLowerCase().hashCode(); + confusers.set("users." + uuid + "." + co + "." + pre2, 0); + saveConfusers(); + loadConfusers(); + } + + /** + * @param message + * @return + */ + static String getAlias(String message) { + return conf.getString("commands.aliases." + message); + } + + /** + * @return + */ + static Set getAliases() { + Set aliases = conf.getConfigurationSection("commands.aliases") + .getKeys(false); + return aliases; + } + + /** + * @return + */ + static Set getAliasesKeys() { + Set aliases = conf.getConfigurationSection("commands.aliases") + .getKeys(true); + return aliases; + } + + /** + * @return + */ + static boolean getBlockInteractDuringWarmup() { + return conf.getBoolean("options.options.block_interact_during_warmup", + false); + } + + /** + * @return + */ + public static String getCancelWarmupByGameModeChangeMessage() { + return conf.getString( + "options.messages.warmup_cancelled_by_gamemode_change", + "&6Warm-ups have been cancelled due to changing gamemode.&f"); + } + + /** + * @return + */ + static boolean getCancelWarmUpOnDamage() { + return conf + .getBoolean("options.options.cancel_warmup_on_damage", false); + } + + /** + * @return + */ + static boolean getCancelWarmUpOnGameModeChange() { + return conf.getBoolean( + "options.options.cancel_warmup_on_gamemode_change", false); + } + + /** + * @return + */ + static boolean getCancelWarmupOnMove() { + return conf.getBoolean("options.options.cancel_warmup_on_move", false); + } + + /** + * @return + */ + static boolean getCancelWarmupOnSneak() { + return conf.getBoolean("options.options.cancel_warmup_on_sneak", false); + } + + /** + * @return + */ + public static String getCancelWarmupOnSneakMessage() { + return conf.getString("options.messages.warmup_cancelled_by_sneak", + "&6Warm-ups have been cancelled due to sneaking.&f"); + } + + /** + * @return + */ + static boolean getCancelWarmupOnSprint() { + return conf + .getBoolean("options.options.cancel_warmup_on_sprint", false); + } + + /** + * @return + */ + public static String getCancelWarmupOnSprintMessage() { + return conf.getString("options.messages.warmup_cancelled_by_sprint", + "&6Warm-ups have been cancelled due to sprinting.&f"); + } + + /** + * @return + */ + public static String getCannotCreateSignMessage() { + return conf.getString("options.messages.cannot_create_sign", + "&6You are not allowed to create this kind of signs!&f"); + } + + /** + * @return + */ + public static String getCannotUseSignMessage() { + return conf.getString("options.messages.cannot_use_sign", + "&6You are not allowed to use this sign!&f"); + } + + /** + * @return + */ + public static boolean getCleanCooldownsOnDeath() { + return conf.getBoolean("options.options.clear_cooldowns_on_death", + false); + } + + /** + * @return + */ + public static boolean getCleanUsesOnDeath() { + return conf.getBoolean("options.options.clear_uses_on_death", false); + } + + /** + * @return + */ + static boolean getClearOnRestart() { + return conf.getBoolean("options.options.clear_on_restart", false); + } + + /** + * @return + */ + static String getCommandBlockedMessage() { + return conf.getString("options.messages.limit_achieved", + "&6You cannot use this command anymore!&f"); + } + + /** + * @param player + * @return + */ + static String getCommandGroup(Player player) { + String cmdGroup = "default"; + for (String group : getCommandGroups()) { + if (player.hasPermission("booscooldowns." + group)) { + cmdGroup = group; + } + } + return cmdGroup; + } + + /** + * @return + */ + static Set getCommandGroups() { + Set groups = conf.getConfigurationSection("commands.groups") + .getKeys(false); + return groups; + } + + /** + * @return + */ + static boolean getCommandLogging() { + return conf.getBoolean("options.options.command_logging", false); + } + + /** + * @param player + * @return + */ + static Set getCommands(Player player) { + String group = getCommandGroup(player); + Set commands = conf.getConfigurationSection( + "commands.groups." + group).getKeys(false); + return commands; + } + + /** + * @param regexCommand + * @param player + * @return + */ + // static String[] getCommandValues(String regexCommand, Player player) { + // String[] values; + // String line = ""; + // String group = getCommandGroup(player); + // line = conf.getString("commands.groups." + group + "." + regexCommand, + // line); + // values = line.split(","); + // return values; + // } + + /** + * @return + */ + static YamlConfiguration getConfusers() { + return confusers; + } + + /** + * @param regexCommand + * @param player + * @return + */ + static int getCoolDown(String regexCommand, Player player) { + int coolDown; + String coolDownString = ""; + String group = getCommandGroup(player); + coolDownString = conf.getString("commands.groups." + group + "." + + regexCommand + ".cooldown", "0"); + coolDown = parseTime(coolDownString); + return coolDown; + } + + /** + * @return + */ + static boolean getCooldownEnabled() { + return conf.getBoolean("options.options.cooldowns_enabled", true); + } + + /** + * @return + */ + static String getCoolDownMessage() { + return conf + .getString( + "options.messages.cooling_down", + "&6Wait&e &seconds& seconds&6 before you can use command&e &command& &6again.&f"); + } + + /** + * @param player + * @return + */ + static Set getCooldowns(Player player) { + String cool = getCommandGroup(player); + Set cooldowns = conf.getConfigurationSection( + "commands.groups." + cool).getKeys(false); + return cooldowns; + } + + /** + * @return + */ + static String getInsufficientFundsMessage() { + return conf + .getString( + "options.messages.insufficient_funds", + "&6You have insufficient funds!&e &command& &6costs &e%s &6but you only have &e%s"); + } + + /** + * @return + */ + public static String getInteractBlockedMessage() { + return conf.getString( + "options.messages.interact_blocked_during_warmup", + "&6You can't do this when command is warming-up!&f"); + } + + /** + * @param regexCommand + * @param player + * @return + */ + static String getItemCostItem(String regexCommand, Player player) { + String item = ""; + String temp; + String[] command; + String group = getCommandGroup(player); + temp = conf.getString("commands.groups." + group + "." + regexCommand + + ".itemcost", ""); + command = temp.split(","); + if (command.length == 2) { + item = command[0]; + } + return item; + } + + /** + * @param regexCommand + * @param player + * @return + */ + static int getItemCostCount(String regexCommand, Player player) { + int count = 0; + String temp; + String[] command; + String group = getCommandGroup(player); + temp = conf.getString("commands.groups." + group + "." + regexCommand + + ".itemcost", ""); + command = temp.split(","); + if (command.length == 2) { + count = Integer.valueOf(command[1]); + } + return count; + } + + /** + * @param regexCommand + * @param player + * @return + */ + static int getLimit(String regexCommand, Player player) { + int limit; + String group = getCommandGroup(player); + limit = conf.getInt("commands.groups." + group + "." + regexCommand + + ".limit", -1); + return limit; + } + + /** + * @return + */ + static boolean getLimitEnabled() { + return conf.getBoolean("options.options.limits_enabled", true); + } + + /** + * @return + */ + static String getLimitListMessage() { + return conf + .getString( + "options.messages.limit_list", + "&6Limit for command &e&command&&6 is &e&limit&&6. You can still use it &e×&&6 times.&f"); + } + + /** + * @return + */ + static boolean getLimitsEnabled() { + return conf.getBoolean("options.options.limits_enabled", true); + } + + static Set getAllPlayers() { + ConfigurationSection users = confusers.getConfigurationSection("users"); + Set list = users.getKeys(false); + return list; + } + + static List getSharedCooldowns(String pre, Player player) { + List sharedCooldowns; + String group = getCommandGroup(player); + sharedCooldowns = conf.getStringList("commands.groups." + group + "." + + pre + ".shared_cooldown"); + return sharedCooldowns; + } + + /** + * @param regexCommand + * @param player + * @return + */ + static String getMessage(String regexCommand, Player player) { + String message = ""; + String group = getCommandGroup(player); + message = conf.getString("commands.groups." + group + "." + + regexCommand + ".message", ""); + return message; + } + + /** + * @return + */ + static String getPaidErrorMessage() { + return conf.getString("options.messages.paid_error", + "An error has occured: %s"); + } + + /** + * @return + */ + static String getPaidForCommandMessage() { + return conf.getString("options.messages.paid_for_command", + "Price of &command& was %s and you now have %s"); + } + + /** + * @param regexCommand + * @param player + * @return + */ + static String getPotionEffect(String regexCommand, Player player) { + String effect = ""; + String temp; + String[] command; + String group = getCommandGroup(player); + temp = conf.getString("commands.groups." + group + "." + regexCommand + + ".potion", ""); + command = temp.split(","); + if (command.length == 2) { + effect = command[0]; + } + return effect; + } + + /** + * @param regexCommand + * @param player + * @return + */ + static int getPotionEffectStrength(String regexCommand, Player player) { + int effect = 0; + String temp; + String[] command; + String group = getCommandGroup(player); + temp = conf.getString("commands.groups." + group + "." + regexCommand + + ".potion", ""); + command = temp.split(","); + if (command.length == 2) { + effect = Integer.valueOf(command[1]); + } + return effect; + } + + /** + * @param regexCommand + * @param player + * @return + */ + static double getPrice(String regexCommand, Player player) { + double price; + String group = getCommandGroup(player); + price = conf.getDouble("commands.groups." + group + "." + regexCommand + + ".price", 0.0); + return price; + } + + /** + * @return + */ + static boolean getPriceEnabled() { + return conf.getBoolean("options.options.prices_enabled", true); + } + + /** + * @return + */ + static int getSaveInterval() { + return conf.getInt("options.options.save_interval_in_minutes", 15); + } + + /** + * @return + */ + static boolean getSignCommands() { + return conf.getBoolean("options.options.command_signs", false); + } + + /** + * @return + */ + public static boolean getStartCooldownsOnDeath() { + return conf.getBoolean("options.options.start_cooldowns_on_death", + false); + } + + /** + * @return + */ + static String getUnitHoursMessage() { + return conf.getString("options.units.hours", "hours"); + } + + /** + * @return + */ + static String getUnitMinutesMessage() { + return conf.getString("options.units.minutes", "minutes"); + } + + /** + * @return + */ + static String getUnitSecondsMessage() { + return conf.getString("options.units.seconds", "seconds"); + } + + /** + * @param regexCommand + * @param player + * @return + */ + static int getWarmUp(String regexCommand, Player player) { + int warmUp; + String warmUpString = ""; + String group = getCommandGroup(player); + warmUpString = conf.getString("commands.groups." + group + "." + + regexCommand + ".warmup", "0"); + warmUp = parseTime(warmUpString); + return warmUp; + } + + /** + * @return + */ + static String getWarmUpAlreadyStartedMessage() { + return conf.getString("options.messages.warmup_already_started", + "&6Warm-Up process for&e &command& &6has already started.&f"); + } + + /** + * @return + */ + public static String getWarmUpCancelledByDamageMessage() { + return conf.getString("options.messages.warmup_cancelled_by_damage", + "&6Warm-ups have been cancelled due to receiving damage.&f"); + } + + /** + * @return + */ + public static String getWarmUpCancelledByMoveMessage() { + return conf.getString("options.messages.warmup_cancelled_by_move", + "&6Warm-ups have been cancelled due to moving.&f"); + } + + /** + * @return + */ + static boolean getWarmupEnabled() { + return conf.getBoolean("options.options.warmups_enabled", true); + } + + /** + * @return + */ + static String getWarmUpMessage() { + return conf + .getString("options.messages.warming_up", + "&6Wait&e &seconds& seconds&6 before command&e &command& &6has warmed up.&f"); + } + + /** + * Metoda na�te konfigura�n� soubor z disku do pam�ti. + */ + static void load() { + try { + conf.load(confFile); + } catch (FileNotFoundException e) { + e.printStackTrace(); + BoosCoolDown.getLog().severe( + "[boosCooldowns] Configuration file not found!"); + } catch (IOException e) { + e.printStackTrace(); + BoosCoolDown.getLog().severe( + "[boosCooldowns] Could not read configuration file!"); + } catch (InvalidConfigurationException e) { + e.printStackTrace(); + BoosCoolDown.getLog().severe( + "[boosCooldowns] Configuration file is invalid!"); + } + } + + /** + * Metoda na�te soubor datab�ze z disku do pam�ti. + */ + static void loadConfusers() { + try { + confusers.load(confusersFile); + } catch (FileNotFoundException e) { + e.printStackTrace(); + BoosCoolDown.getLog().severe( + "[boosCooldowns] Storage file not found!"); + } catch (IOException e) { + e.printStackTrace(); + BoosCoolDown.getLog().severe( + "[boosCooldowns] Could not read storage file!"); + } catch (InvalidConfigurationException e) { + e.printStackTrace(); + BoosCoolDown.getLog().severe( + "[boosCooldowns] Storage file is invalid!"); + } + } + + /** + * Metoda znovu na�te konfigura�n� soubor z disku do pam�ti. + */ + static void reload() { + conf = new YamlConfiguration(); + load(); + } + + /** + * Metoda ulo�� soubor datab�ze z pam�ti na disk. + */ + static void saveConfusers() { + try { + confFile.createNewFile(); + confusers.save(confusersFile); + } catch (IOException e) { + e.printStackTrace(); + BoosCoolDown.getLog().severe( + "[boosCooldowns] Could not save storage file!"); + } + } + + /** + * Metoda p�id�v� z�znamy do konfigura�n�ho souboru, kter� pot� ulo�� na + * disk a znovu jej na�te z disku do pam�ti. + * + * @param coSetnout + * n�zev skupiny pro kterou se m� p�idat z�znam do konfigura�n�ho + * souboru + * @param co + * p��kaz, pro kter� se m� p�idat hodnota do konfigura�n�ho + * souboru + * @param hodnota + * hodnota kter� se m� p�idat pro specifikovan� p��kaz + */ + static void setAddToConfigFile(String group, String command, String what, + String value) { + group = group.toLowerCase(); + command = command.toLowerCase(); + int value2; + try { + value2 = Integer.parseInt(value); + reload(); + conf.set("commands.groups." + group + "." + command + "." + what, + value2); + } catch (NumberFormatException e1) { + reload(); + conf.set("commands.groups." + group + "." + command + "." + what, + value); + } + try { + conf.save(confFile); + } catch (IOException e) { + BoosCoolDown.getLog().severe( + "[boosCooldowns] Could not save configuration file!"); + + } + reload(); + } + + /** + * Metoda vytv��ej�ci konfigura�n� a datab�zov� sobour, pokud tyto soubory + * ji� neexistuj�. Pokud soubory ji� existuj�, jsou na�teny z disku do + * pam�ti. + * + * @param boosCoolDown + */ + @SuppressWarnings("static-access") + BoosConfigManager(BoosCoolDown boosCoolDown) { + confFile = new File(boosCoolDown.getDataFolder(), "config.yml"); + if (confFile.exists()) { + conf = new YamlConfiguration(); + load(); + } else { + this.confFile = new File(boosCoolDown.getDataFolder(), "config.yml"); + this.conf = new YamlConfiguration(); + } + if (confFile.exists()) { + load(); + } + confusersFile = new File(boosCoolDown.getDataFolder(), "users.yml"); + confusers = new YamlConfiguration(); + if (confusersFile.exists()) { + loadConfusers(); + } else { + try { + confusersFile.createNewFile(); + } catch (IOException e) { + e.printStackTrace(); + BoosCoolDown.getLog().severe( + "[boosCooldowns] Could not save storage file!"); + } + } + } + + static boolean getAutoSave() { + return conf.getBoolean( + "options.options.auto_save_enabled_CAN_CAUSE_BIG_LAGS", false); + } + + static String getPaidItemsForCommandMessage() { + return conf.getString("options.messages.paid_items_for_command", + "&6Price of&e &command& &6was &e%s"); + } + + static String getInsufficientItemsMessage() { + return conf.getString("options.messages.insufficient_items", + "&6You have not enough items!&e &command& &6needs &e%s"); + } + + static boolean getItemCostEnabled() { + return conf.getBoolean("options.options.item_cost_enabled", true); + } + + static String getPaidXPForCommandMessage() { + return conf.getString("options.messages.paid_xp_for_command", + "&6Price of&e &command& &6was &e%s"); + } + + static int getXpPrice(String regexCommand, Player player) { + int price; + String group = getCommandGroup(player); + price = conf.getInt("commands.groups." + group + "." + regexCommand + + ".xpcost", 0); + return price; + } + + static boolean getXpPriceEnabled() { + return conf.getBoolean("options.options.xp_cost_enabled", true); + } + + static String getInsufficientXpMessage() { + return conf.getString("options.messages.insufficient_xp", + "&6You have not enough XP!&e &command& &6needs &e%s"); + } + + static String getInvalidCommandSyntaxMessage(Player player) { + return conf + .getString("options.messages.invalid_command_syntax", + "&6You are not allowed to use command syntax /:!"); + } + + static long getLimitResetDelay(String regexCommand, Player player) { + long limitreset; + String limitResetString = ""; + String group = getCommandGroup(player); + limitResetString = conf.getString("commands.groups." + group + "." + + regexCommand + ".limit_reset_delay", "0"); + limitreset = parseTime(limitResetString); + return limitreset; + } + + static String getLimitResetMessage() { + return conf + .getString( + "options.messages.limit_reset", + "&6Wait&e &seconds& &unit&&6 before your limit for command&e &command& &6is reset.&f"); + } + + static void clearSomething2(String co, String uuid, int hashedCommand) { + confusers.set("users." + uuid + "." + co + "." + hashedCommand, 0); + } + + static long getLimitResetDelayGlobal(String command) { + long delay = 0; + String delayString = ""; + delayString = conf.getString( + "global." + command + ".limit_reset_delay", "0"); + delay = parseTime(delayString); + return delay; + } + + static Set getLimitResetCommandsGlobal() { + return conf.getConfigurationSection("global").getKeys(false); + } + + static int parseTime(String time) { + String[] timeString = time.split(" ", 2); + if (timeString[0].equals("cancel")){ + return -65535; + } + int timeNumber = Integer.valueOf(timeString[0]); + int timeMultiplier = 1; + if (timeString.length > 1) { + String timeUnit = timeString[1]; + if (timeUnit.equals("minute") || timeUnit.equals("minutes")) { + timeMultiplier = 60; + } else if (timeUnit.equals("hour") || timeUnit.equals("hours")) { + timeMultiplier = 60 * 60; + } else if (timeUnit.equals("day") || timeUnit.equals("days")) { + timeMultiplier = 60 * 60 * 24; + } else if (timeUnit.equals("week") || timeUnit.equals("weeks")) { + timeMultiplier = 60 * 60 * 24 * 7; + } else if (timeUnit.equals("month") || timeUnit.equals("months")) { + timeMultiplier = 60 * 60 * 24 * 30; + } else { + timeMultiplier = 1; + } + } + return timeNumber * timeMultiplier; + } + + public static String getLimitResetNowMessage() { + return conf + .getString( + "options.messages.limit_reset_now", + "&6Reseting limits for command&e &command& &6now.&f"); + } +} diff --git a/src/main/java/cz/boosik/boosCooldown/BoosCoolDown.java b/src/main/java/cz/boosik/boosCooldown/BoosCoolDown.java index 1aea82e..d93af5f 100644 --- a/src/main/java/cz/boosik/boosCooldown/BoosCoolDown.java +++ b/src/main/java/cz/boosik/boosCooldown/BoosCoolDown.java @@ -1,430 +1,560 @@ -package cz.boosik.boosCooldown; - -import java.io.IOException; -import java.util.Set; -import java.util.UUID; -import java.util.logging.Logger; - -import net.milkbowl.vault.Vault; -import net.milkbowl.vault.economy.Economy; - -import org.bukkit.Bukkit; -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.PluginDescriptionFile; -import org.bukkit.plugin.PluginManager; -import org.bukkit.plugin.RegisteredServiceProvider; -import org.bukkit.plugin.java.JavaPlugin; -import org.bukkit.scheduler.BukkitScheduler; -import org.mcstats.MetricsLite; - -import util.boosChat; -import cz.boosik.boosCooldown.Listeners.BoosEntityDamageListener; -import cz.boosik.boosCooldown.Listeners.BoosPlayerDeathListener; -import cz.boosik.boosCooldown.Listeners.BoosPlayerGameModeChangeListener; -import cz.boosik.boosCooldown.Listeners.BoosPlayerInteractListener; -import cz.boosik.boosCooldown.Listeners.BoosPlayerMoveListener; -import cz.boosik.boosCooldown.Listeners.BoosPlayerToggleSneakListener; -import cz.boosik.boosCooldown.Listeners.BoosPlayerToggleSprintListener; -import cz.boosik.boosCooldown.Listeners.BoosSignChangeListener; -import cz.boosik.boosCooldown.Listeners.BoosSignInteractListener; - -/** - * Hlavn� t��da pluginu. T��da je potomkem JavaPlugin a implementuje Runnable. - * Tato t��da se star� o ve�ker� inicializace p�i spu�t�n� a ukon�en� pluginu. - * Toto zahrnuje zji�t�n�, zda je k dispozici plugin Vault a ekonomick� plugin, - * registraci poslucha�� a tak� se star� o funkce v�ech kontroln�ch a - * konfigura�n�ch p��kaz�. Periodicky tak� ukl�d� soubor datab�ze v intervalu - * nastaven�m v konfiguraci. - * - * @author Jakub Kol�� - * - */ -public class BoosCoolDown extends JavaPlugin implements Runnable { - private static final Logger log = Logger.getLogger("Minecraft"); - private static PluginDescriptionFile pdfFile; - private static Economy economy = null; - private static boolean usingVault = false; - private PluginManager pm; - - /** - * Metoda odes�l� zpr�vy o pou�it� p��kaz� do konzole serveru. - * - * @param player - * jm�no hr��e kter� vykonal p��kaz - * @param command - * vykonan� p��kaz - */ - public static void commandLogger(String player, String command) { - log.info("[" + "boosLogger" + "] " + player + " used command " - + command); - } - - /** - * @return - */ - public static Economy getEconomy() { - return economy; - } - - /** - * @return - */ - public static Logger getLog() { - return log; - } - - /** - * Metoda zji��uje na z�klad� opr�vn�n� jestli je plugin aktivn� pro dan�ho - * hr��e nebo ne. - * - * @param player - * specifikovan� hr�� - * @return - */ - static boolean isPluginOnForPlayer(Player player) { - boolean on; - if (player.hasPermission("booscooldowns.exception")) { - on = false; - } else if (player.isOp()) { - on = false; - } else { - on = true; - } - return on; - } - - /** - * Metoda zji��uje jestli je dostupn� plugin Vault a na z�klad� toho vol� - * metodu pro nastaven� ekonomick�ho pluginu a informuje o tom u�ivatele - * pomoc� konzole serveru. - */ - private void initializeVault() { - Plugin x = pm.getPlugin("Vault"); - if (x != null & x instanceof Vault) { - log.info("[" + pdfFile.getName() + "]" - + " found [Vault] searching for economy plugin."); - usingVault = true; - if (setupEconomy()) { - log.info("[" + pdfFile.getName() + "]" + " found [" - + economy.getName() - + "] plugin, enabling prices support."); - } else { - log.info("[" - + pdfFile.getName() - + "]" - + " economy plugin not found, disabling prices support."); - } - } else { - log.info("[" + pdfFile.getName() + "]" - + " [Vault] not found disabling economy support."); - usingVault = false; - } - } - - /* - * (non-Javadoc) - * - * @see - * org.bukkit.plugin.java.JavaPlugin#onCommand(org.bukkit.command.CommandSender - * , org.bukkit.command.Command, java.lang.String, java.lang.String[]) - */ - @SuppressWarnings("deprecation") - @Override - public boolean onCommand(CommandSender sender, Command c, - String commandLabel, String[] args) { - String command = c.getName().toLowerCase(); - if (command.equalsIgnoreCase("booscooldowns")) { - if (args.length == 1) { - if (sender.hasPermission("booscooldowns.reload") - && args[0].equalsIgnoreCase("reload")) { - reload(); - boosChat.sendMessageToCommandSender(sender, - "&6[" + pdfFile.getName() + "]&e" - + " config reloaded"); - return true; - } - if (sender.hasPermission("booscooldowns.list.limits") - && args[0].equalsIgnoreCase("limits")) { - try { - Player send = (Player) sender; - Set commands = BoosConfigManager - .getCommands(send); - for (String comm : commands) { - int lim = BoosConfigManager.getLimit(comm, send); - BoosLimitManager.getLimitListMessages(send, comm, - lim); - } - } catch (ClassCastException e) { - log.warning("You cannot use this command from console!"); - } - return true; - } - } - if (args.length == 2) { - String jmeno = args[1]; - Player player = Bukkit.getPlayerExact(jmeno); - UUID uuid = player.getUniqueId(); - if (sender.hasPermission("booscooldowns.clearcooldowns") - && args[0].equalsIgnoreCase("clearcooldowns")) { - String co = "cooldown"; - BoosConfigManager.clearSomething(co, uuid); - boosChat.sendMessageToCommandSender(sender, - "&6[" + pdfFile.getName() + "]&e" - + " cooldowns of player " + jmeno - + " cleared"); - return true; - } else if (sender.hasPermission("booscooldowns.clearuses") - && command.equalsIgnoreCase("booscooldowns") - && args[0].equalsIgnoreCase("clearuses")) { - String co = "uses"; - BoosConfigManager.clearSomething(co, uuid); - boosChat.sendMessageToCommandSender(sender, - "&6[" + pdfFile.getName() + "]&e" - + " uses of player " + jmeno + " cleared"); - return true; - } else if (sender.hasPermission("booscooldowns.clearwarmups") - && command.equalsIgnoreCase("booscooldowns") - && args[0].equalsIgnoreCase("clearwarmups")) { - String co = "warmup"; - BoosConfigManager.clearSomething(co, uuid); - boosChat.sendMessageToCommandSender(sender, - "&6[" + pdfFile.getName() + "]&e" - + " warmups of player " + jmeno - + " cleared"); - return true; - } - } - if (args.length == 3) { - String jmeno = args[1]; - Player player = Bukkit.getPlayerExact(jmeno); - UUID uuid = player.getUniqueId(); - String command2 = args[2].trim(); - if (sender.hasPermission("booscooldowns.clearcooldowns") - && args[0].equalsIgnoreCase("clearcooldowns")) { - String co = "cooldown"; - BoosConfigManager.clearSomething(co, uuid, command2); - boosChat.sendMessageToCommandSender(sender, - "&6[" + pdfFile.getName() + "]&e" - + " cooldown for command " + command2 - + " of player " + uuid + " cleared"); - return true; - } else if (sender.hasPermission("booscooldowns.clearuses") - && args[0].equalsIgnoreCase("clearuses")) { - String co = "uses"; - BoosConfigManager.clearSomething(co, uuid, command2); - boosChat.sendMessageToCommandSender(sender, - "&6[" + pdfFile.getName() + "]&e" - + " uses for command " + command2 - + " of player " + jmeno + " cleared"); - return true; - } else if (sender.hasPermission("booscooldowns.clearwarmups") - && args[0].equalsIgnoreCase("clearwarmups")) { - String co = "warmup"; - BoosConfigManager.clearSomething(co, uuid, command2); - boosChat.sendMessageToCommandSender(sender, - "&6[" + pdfFile.getName() + "]&e" - + " warmups for command " + command2 - + " of player " + jmeno + " cleared"); - return true; - - } - } - if (args.length == 4) { - if (sender.hasPermission("booscooldowns.set") - && args[0].equalsIgnoreCase("set")) { - String what = args[1]; - String comm = args[2]; - String value = args[3]; - String group = "default"; - if (comm.startsWith("/") || comm.equals("*")) { - if (comm.contains("_")) { - comm = comm.replace("_", " "); - } - BoosConfigManager.setAddToConfigFile(group, comm, what, - value); - boosChat.sendMessageToCommandSender(sender, "&6[" - + pdfFile.getName() + "]&e " + what - + " for command" + comm + " in group " + group - + " is now set to " + value); - return true; - } else { - boosChat.sendMessageToCommandSender(sender, "&6[" - + pdfFile.getName() + "]&e" - + " Command has to start with \"/\"."); - return true; - } - } - - } - if (args.length == 5) { - if (sender.hasPermission("booscooldowns.set") - && args[0].equalsIgnoreCase("set")) { - String what = args[1]; - String comm = args[2]; - String value = args[3]; - String group = args[4]; - if (comm.startsWith("/") || comm.equals("*")) { - if (comm.contains("_")) { - comm = comm.replace("_", " "); - } - BoosConfigManager.setAddToConfigFile(group, comm, what, - value); - boosChat.sendMessageToCommandSender(sender, "&6[" - + pdfFile.getName() + "]&e " + what - + " for command" + comm + " in group " + group - + " is now set to " + value); - return true; - } else { - boosChat.sendMessageToCommandSender(sender, "&6[" - + pdfFile.getName() + "]&e" - + " Command has to start with \"/\"."); - return true; - } - } - - } else { - boosChat.sendMessageToCommandSender(sender, - "&6[" + pdfFile.getName() + "]&e" - + " Invalid command or access denied!"); - } - } - return false; - - } - - /* - * (non-Javadoc) - * - * @see org.bukkit.plugin.java.JavaPlugin#onDisable() - */ - @Override - public void onDisable() { - if (BoosConfigManager.getClearOnRestart() == true) { - BoosConfigManager.clear(); - log.info("[" + pdfFile.getName() + "]" + " cooldowns cleared!"); - } else { - BoosConfigManager.saveConfusers(); - log.info("[" + pdfFile.getName() + "]" + " cooldowns saved!"); - } - log.info("[" + pdfFile.getName() + "]" + " version " - + pdfFile.getVersion() + " disabled!"); - } - - /* - * (non-Javadoc) - * - * @see org.bukkit.plugin.java.JavaPlugin#onEnable() - */ - @Override - public void onEnable() { - pdfFile = this.getDescription(); - PluginDescriptionFile pdfFile = this.getDescription(); - log.info("[" + pdfFile.getName() + "]" + " version " - + pdfFile.getVersion() + " by " + pdfFile.getAuthors() - + " is enabled!"); - new BoosConfigManager(this); - BoosConfigManager.load(); - BoosConfigManager.loadConfusers(); - pm = getServer().getPluginManager(); - registerListeners(); - initializeVault(); - BukkitScheduler scheduler = this.getServer().getScheduler(); - if (BoosConfigManager.getAutoSave()) { - scheduler.scheduleSyncRepeatingTask(this, this, - BoosConfigManager.getSaveInterval() * 1200, - BoosConfigManager.getSaveInterval() * 1200); - } - if (BoosConfigManager.getClearOnRestart()) { - BoosConfigManager.clear(); - } - try { - MetricsLite metrics = new MetricsLite(this); - metrics.start(); - } catch (IOException e) { - // Failed to submit the stats :-( - } - - } - - /** - * Metoda registruje poslucha�e v PluginManageru na z�klad� konfigurace - * pluginu. Registroj� se v�dy jen nezbytn� poslucha�i. Poslucha�i pro - * vypnut� funkce nejsou registrov�ni. - */ - private void registerListeners() { - HandlerList.unregisterAll(this); - pm.registerEvents(new BoosCoolDownListener(this), this); - if (BoosConfigManager.getCancelWarmUpOnDamage()) { - pm.registerEvents(new BoosEntityDamageListener(), this); - } - if (BoosConfigManager.getCleanCooldownsOnDeath() - || BoosConfigManager.getCleanUsesOnDeath() - || BoosConfigManager.getStartCooldownsOnDeath()) { - pm.registerEvents(new BoosPlayerDeathListener(), this); - } - if (BoosConfigManager.getCancelWarmUpOnGameModeChange()) { - pm.registerEvents(new BoosPlayerGameModeChangeListener(), this); - } - if (BoosConfigManager.getBlockInteractDuringWarmup()) { - pm.registerEvents(new BoosPlayerInteractListener(), this); - } - if (BoosConfigManager.getCancelWarmupOnMove()) { - pm.registerEvents(new BoosPlayerMoveListener(), this); - } - if (BoosConfigManager.getCancelWarmupOnSneak()) { - pm.registerEvents(new BoosPlayerToggleSneakListener(), this); - } - if (BoosConfigManager.getCancelWarmupOnSprint()) { - pm.registerEvents(new BoosPlayerToggleSprintListener(), this); - } - if (BoosConfigManager.getSignCommands()) { - pm.registerEvents(new BoosSignChangeListener(), this); - pm.registerEvents(new BoosSignInteractListener(this), this); - } - } - - /** - * Metoda vol� metodu pro znovuna�ten� konfigura�n�ho souboru a metodu pro - * registraci poslucha��. - */ - private void reload() { - BoosConfigManager.reload(); - registerListeners(); - } - - /* - * (non-Javadoc) - * - * @see java.lang.Runnable#run() - */ - @Override - public void run() { - BoosConfigManager.saveConfusers(); - BoosConfigManager.loadConfusers(); - log.info("[boosCooldowns] Config saved!"); - } - - /** - * Metoda vrac� hodnotu true, pokud je na serveru dostupn� Ekonomick� plugin - * kompatibiln� s pluginem Vault. - * - * @return true pokud je dostupn� ekonomick� plugin kompatibiln� s pluginem - * Vault, jinak vrac� hodnotu false - */ - private boolean setupEconomy() { - if (usingVault) { - RegisteredServiceProvider economyProvider = getServer() - .getServicesManager().getRegistration( - net.milkbowl.vault.economy.Economy.class); - if (economyProvider != null) { - economy = economyProvider.getProvider(); - } - return (economy != null); - } - return false; - } -} +package cz.boosik.boosCooldown; + +import java.io.IOException; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.Set; +import java.util.UUID; +import java.util.logging.Logger; + +import net.milkbowl.vault.Vault; +import net.milkbowl.vault.economy.Economy; + +import org.bukkit.Bukkit; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.PluginDescriptionFile; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.RegisteredServiceProvider; +import org.bukkit.plugin.java.JavaPlugin; +import org.bukkit.scheduler.BukkitScheduler; +import org.mcstats.MetricsLite; + +import util.boosChat; +import cz.boosik.boosCooldown.Listeners.BoosEntityDamageListener; +import cz.boosik.boosCooldown.Listeners.BoosPlayerDeathListener; +import cz.boosik.boosCooldown.Listeners.BoosPlayerGameModeChangeListener; +import cz.boosik.boosCooldown.Listeners.BoosPlayerInteractListener; +import cz.boosik.boosCooldown.Listeners.BoosPlayerMoveListener; +import cz.boosik.boosCooldown.Listeners.BoosPlayerToggleSneakListener; +import cz.boosik.boosCooldown.Listeners.BoosPlayerToggleSprintListener; +import cz.boosik.boosCooldown.Listeners.BoosSignChangeListener; +import cz.boosik.boosCooldown.Listeners.BoosSignInteractListener; + +/** + * Hlavn� t��da pluginu. T��da je potomkem JavaPlugin a implementuje Runnable. + * Tato t��da se star� o ve�ker� inicializace p�i spu�t�n� a ukon�en� pluginu. + * Toto zahrnuje zji�t�n�, zda je k dispozici plugin Vault a ekonomick� plugin, + * registraci poslucha�� a tak� se star� o funkce v�ech kontroln�ch a + * konfigura�n�ch p��kaz�. Periodicky tak� ukl�d� soubor datab�ze v intervalu + * nastaven�m v konfiguraci. + * + * @author Jakub Kol�� + * + */ +public class BoosCoolDown extends JavaPlugin implements Runnable { + private static final Logger log = Logger.getLogger("Minecraft"); + private static PluginDescriptionFile pdfFile; + private static Economy economy = null; + private static boolean usingVault = false; + private PluginManager pm; + private static BoosCoolDown instance = null; + + /** + * Metoda odes�l� zpr�vy o pou�it� p��kaz� do konzole serveru. + * + * @param player + * jm�no hr��e kter� vykonal p��kaz + * @param command + * vykonan� p��kaz + */ + public static void commandLogger(String player, String command) { + log.info("[" + "boosLogger" + "] " + player + " used command " + + command); + } + + /** + * @return + */ + public static Economy getEconomy() { + return economy; + } + + /** + * @return + */ + public static Logger getLog() { + return log; + } + + /** + * Metoda zji��uje na z�klad� opr�vn�n� jestli je plugin aktivn� pro dan�ho + * hr��e nebo ne. + * + * @param player + * specifikovan� hr�� + * @return + */ + static boolean isPluginOnForPlayer(Player player) { + boolean on; + if (player.hasPermission("booscooldowns.exception")) { + on = false; + } else if (player.isOp()) { + on = false; + } else { + on = true; + } + return on; + } + + /** + * Metoda zji��uje jestli je dostupn� plugin Vault a na z�klad� toho vol� + * metodu pro nastaven� ekonomick�ho pluginu a informuje o tom u�ivatele + * pomoc� konzole serveru. + */ + private void initializeVault() { + Plugin x = pm.getPlugin("Vault"); + if (x != null & x instanceof Vault) { + log.info("[" + pdfFile.getName() + "]" + + " found [Vault] searching for economy plugin."); + usingVault = true; + if (setupEconomy()) { + log.info("[" + pdfFile.getName() + "]" + " found [" + + economy.getName() + + "] plugin, enabling prices support."); + } else { + log.info("[" + + pdfFile.getName() + + "]" + + " economy plugin not found, disabling prices support."); + } + } else { + log.info("[" + pdfFile.getName() + "]" + + " [Vault] not found disabling economy support."); + usingVault = false; + } + } + + /* + * (non-Javadoc) + * + * @see + * org.bukkit.plugin.java.JavaPlugin#onCommand(org.bukkit.command.CommandSender + * , org.bukkit.command.Command, java.lang.String, java.lang.String[]) + */ + @SuppressWarnings("deprecation") + @Override + public boolean onCommand(CommandSender sender, Command c, + String commandLabel, String[] args) { + String command = c.getName().toLowerCase(); + if (command.equalsIgnoreCase("booscooldowns")) { + if (args.length == 1) { + if (sender.hasPermission("booscooldowns.reload") + && args[0].equalsIgnoreCase("reload")) { + reload(); + boosChat.sendMessageToCommandSender(sender, + "&6[" + pdfFile.getName() + "]&e" + + " config reloaded"); + return true; + } + if (sender.hasPermission("booscooldowns.list.limits") + && args[0].equalsIgnoreCase("limits")) { + try { + Player send = (Player) sender; + Set commands = BoosConfigManager + .getCommands(send); + for (String comm : commands) { + int lim = BoosConfigManager.getLimit(comm, send); + BoosLimitManager.getLimitListMessages(send, comm, + lim); + } + } catch (ClassCastException e) { + log.warning("You cannot use this command from console!"); + } + return true; + } + else if (sender.hasPermission("booscooldowns.globalreset") + && args[0].equalsIgnoreCase("startglobalreset")) { + BoosLimitManager.setGlobalLimitResetDate(); + startLimitResetTimersGlobal(); + return true; + } + } + else if (args.length == 2) { + String jmeno = args[1]; + Player player = Bukkit.getPlayerExact(jmeno); + UUID uuid = player.getUniqueId(); + if (sender.hasPermission("booscooldowns.clearcooldowns") + && args[0].equalsIgnoreCase("clearcooldowns")) { + String co = "cooldown"; + BoosConfigManager.clearSomething(co, uuid); + boosChat.sendMessageToCommandSender(sender, + "&6[" + pdfFile.getName() + "]&e" + + " cooldowns of player " + jmeno + + " cleared"); + return true; + } else if (sender.hasPermission("booscooldowns.clearuses") + && command.equalsIgnoreCase("booscooldowns") + && args[0].equalsIgnoreCase("clearuses")) { + String co = "uses"; + BoosConfigManager.clearSomething(co, uuid); + boosChat.sendMessageToCommandSender(sender, + "&6[" + pdfFile.getName() + "]&e" + + " uses of player " + jmeno + " cleared"); + return true; + } else if (sender.hasPermission("booscooldowns.clearwarmups") + && command.equalsIgnoreCase("booscooldowns") + && args[0].equalsIgnoreCase("clearwarmups")) { + String co = "warmup"; + BoosConfigManager.clearSomething(co, uuid); + boosChat.sendMessageToCommandSender(sender, + "&6[" + pdfFile.getName() + "]&e" + + " warmups of player " + jmeno + + " cleared"); + return true; + } + } + else if (args.length == 3) { + String jmeno = args[1]; + Player player = Bukkit.getPlayerExact(jmeno); + UUID uuid = player.getUniqueId(); + String command2 = args[2].trim(); + if (sender.hasPermission("booscooldowns.clearcooldowns") + && args[0].equalsIgnoreCase("clearcooldowns")) { + String co = "cooldown"; + BoosConfigManager.clearSomething(co, uuid, command2); + boosChat.sendMessageToCommandSender(sender, + "&6[" + pdfFile.getName() + "]&e" + + " cooldown for command " + command2 + + " of player " + uuid + " cleared"); + return true; + } else if (sender.hasPermission("booscooldowns.clearuses") + && args[0].equalsIgnoreCase("clearuses")) { + String co = "uses"; + BoosConfigManager.clearSomething(co, uuid, command2); + boosChat.sendMessageToCommandSender(sender, + "&6[" + pdfFile.getName() + "]&e" + + " uses for command " + command2 + + " of player " + jmeno + " cleared"); + return true; + } else if (sender.hasPermission("booscooldowns.clearwarmups") + && args[0].equalsIgnoreCase("clearwarmups")) { + String co = "warmup"; + BoosConfigManager.clearSomething(co, uuid, command2); + boosChat.sendMessageToCommandSender(sender, + "&6[" + pdfFile.getName() + "]&e" + + " warmups for command " + command2 + + " of player " + jmeno + " cleared"); + return true; + + } + } + else if (args.length == 4) { + if (sender.hasPermission("booscooldowns.set") + && args[0].equalsIgnoreCase("set")) { + String what = args[1]; + String comm = args[2]; + String value = args[3]; + String group = "default"; + if (comm.startsWith("/") || comm.equals("*")) { + if (comm.contains("_")) { + comm = comm.replace("_", " "); + } + BoosConfigManager.setAddToConfigFile(group, comm, what, + value); + boosChat.sendMessageToCommandSender(sender, "&6[" + + pdfFile.getName() + "]&e " + what + + " for command" + comm + " in group " + group + + " is now set to " + value); + return true; + } else { + boosChat.sendMessageToCommandSender(sender, "&6[" + + pdfFile.getName() + "]&e" + + " Command has to start with \"/\"."); + return true; + } + } + + } + else if (args.length == 5) { + if (sender.hasPermission("booscooldowns.set") + && args[0].equalsIgnoreCase("set")) { + String what = args[1]; + String comm = args[2]; + String value = args[3]; + String group = args[4]; + if (comm.startsWith("/") || comm.equals("*")) { + if (comm.contains("_")) { + comm = comm.replace("_", " "); + } + BoosConfigManager.setAddToConfigFile(group, comm, what, + value); + boosChat.sendMessageToCommandSender(sender, "&6[" + + pdfFile.getName() + "]&e " + what + + " for command" + comm + " in group " + group + + " is now set to " + value); + return true; + } else { + boosChat.sendMessageToCommandSender(sender, "&6[" + + pdfFile.getName() + "]&e" + + " Command has to start with \"/\"."); + return true; + } + } + + } else { +// boosChat.sendMessageToCommandSender(sender, +// "&6[" + pdfFile.getName() + "]&e" +// + " Invalid command or access denied!"); + return false; + } + } + return false; + + } + + /* + * (non-Javadoc) + * + * @see org.bukkit.plugin.java.JavaPlugin#onDisable() + */ + @Override + public void onDisable() { + if (BoosConfigManager.getClearOnRestart()) { + BoosConfigManager.clear(); + log.info("[" + pdfFile.getName() + "]" + " cooldowns cleared!"); + } else { + BoosConfigManager.saveConfusers(); + log.info("[" + pdfFile.getName() + "]" + " cooldowns saved!"); + } + log.info("[" + pdfFile.getName() + "]" + " version " + + pdfFile.getVersion() + " disabled!"); + } + + /* + * (non-Javadoc) + * + * @see org.bukkit.plugin.java.JavaPlugin#onEnable() + */ + @Override + public void onEnable() { + pdfFile = this.getDescription(); + PluginDescriptionFile pdfFile = this.getDescription(); + log.info("[" + pdfFile.getName() + "]" + " version " + + pdfFile.getVersion() + " by " + pdfFile.getAuthors() + + " is enabled!"); + this.saveDefaultConfig(); + new BoosConfigManager(this); + BoosConfigManager.load(); + BoosConfigManager.loadConfusers(); + pm = getServer().getPluginManager(); + registerListeners(); + initializeVault(); + BukkitScheduler scheduler = this.getServer().getScheduler(); + startLimitResetTimersGlobal(); + if (BoosConfigManager.getAutoSave()) { + scheduler.scheduleSyncRepeatingTask(this, this, + BoosConfigManager.getSaveInterval() * 1200, + BoosConfigManager.getSaveInterval() * 1200); + } + + if (BoosConfigManager.getClearOnRestart()) { + BoosConfigManager.clear(); + } + try { + MetricsLite metrics = new MetricsLite(this); + metrics.start(); + } catch (IOException e) { + // Failed to submit the stats :-( + } + + } + + static void startLimitResetTimersGlobal() { + YamlConfiguration confusers = BoosConfigManager.getConfusers(); + ConfigurationSection global = confusers + .getConfigurationSection("global"); + if (global != null) { + Set globalKeys = global.getKeys(false); + BukkitScheduler scheduler = Bukkit.getScheduler(); + for (String key : globalKeys) { + String confTime = confusers.getString("global." + key + + ".reset"); + long limitResetDelay = BoosConfigManager + .getLimitResetDelayGlobal(key); + Date endDate = getTime(confTime); + Date startDate = getCurrTime(); + Calendar calcurrTime = Calendar.getInstance(); + calcurrTime.setTime(startDate); + Calendar callastTime = Calendar.getInstance(); + callastTime.setTime(endDate); + long time = secondsBetween(calcurrTime, callastTime, + limitResetDelay); + if (limitResetDelay != -65535) { + if (time <= 0) { + time = 1; + } + BoosCoolDown.getLog().info( + "[boosCooldowns] Starting timer for " + time + + " seconds to reset limits for command " + + key); + scheduler.scheduleSyncDelayedTask(Bukkit.getPluginManager() + .getPlugin("boosCooldowns"), + new BoosGlobalLimitResetRunnable(key), time * 20); + } else { + BoosCoolDown.getLog().info( + "[boosCooldowns] Stoping timer to reset limits for command " + + key); + } + } + } + } + + static void startLimitResetTimerGlobal(String key) { + YamlConfiguration confusers = BoosConfigManager.getConfusers(); + BukkitScheduler scheduler = Bukkit.getScheduler(); + String confTime = confusers.getString("global." + key + ".reset"); + long limitResetDelay = BoosConfigManager.getLimitResetDelayGlobal(key); + Date endDate = getTime(confTime); + Date startDate = getCurrTime(); + Calendar calcurrTime = Calendar.getInstance(); + calcurrTime.setTime(startDate); + Calendar callastTime = Calendar.getInstance(); + callastTime.setTime(endDate); + long time = secondsBetween(calcurrTime, callastTime, limitResetDelay); + if (limitResetDelay != -65535) { + if (time <= 0) { + time = 1; + } + BoosCoolDown.getLog().info( + "[boosCooldowns] Starting timer for " + time + + " seconds to reset limits for command " + key); + scheduler.scheduleSyncDelayedTask(Bukkit.getPluginManager() + .getPlugin("boosCooldowns"), + new BoosGlobalLimitResetRunnable(key), time * 20); + } else { + BoosCoolDown.getLog().info( + "[boosCooldowns] Stoping timer to reset limits for command " + + key); + } + } + + static long secondsBetween(Calendar startDate, Calendar endDate, + long limitResetDelay) { + long secondsBetween = 0; + secondsBetween = ((endDate.getTimeInMillis() - startDate + .getTimeInMillis()) / 1000) + limitResetDelay; + return secondsBetween; + } + + static Date getCurrTime() { + String currTime = ""; + Calendar cal = Calendar.getInstance(); + SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); + currTime = sdf.format(cal.getTime()); + Date time = null; + try { + time = sdf.parse(currTime); + return time; + } catch (ParseException e) { + return null; + } + } + + static Date getTime(String confTime) { + if (confTime != null && !confTime.equals("")) { + SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); + Date lastDate = null; + + try { + lastDate = sdf.parse(confTime); + return lastDate; + } catch (ParseException e) { + return null; + } + } + return null; + } + + /** + * Metoda registruje poslucha�e v PluginManageru na z�klad� konfigurace + * pluginu. Registroj� se v�dy jen nezbytn� poslucha�i. Poslucha�i pro + * vypnut� funkce nejsou registrov�ni. + */ + private void registerListeners() { + HandlerList.unregisterAll(this); + pm.registerEvents(new BoosCoolDownListener(this), this); + if (BoosConfigManager.getCancelWarmUpOnDamage()) { + pm.registerEvents(new BoosEntityDamageListener(), this); + } + if (BoosConfigManager.getCleanCooldownsOnDeath() + || BoosConfigManager.getCleanUsesOnDeath() + || BoosConfigManager.getStartCooldownsOnDeath()) { + pm.registerEvents(new BoosPlayerDeathListener(), this); + } + if (BoosConfigManager.getCancelWarmUpOnGameModeChange()) { + pm.registerEvents(new BoosPlayerGameModeChangeListener(), this); + } + if (BoosConfigManager.getBlockInteractDuringWarmup()) { + pm.registerEvents(new BoosPlayerInteractListener(), this); + } + if (BoosConfigManager.getCancelWarmupOnMove()) { + pm.registerEvents(new BoosPlayerMoveListener(), this); + } + if (BoosConfigManager.getCancelWarmupOnSneak()) { + pm.registerEvents(new BoosPlayerToggleSneakListener(), this); + } + if (BoosConfigManager.getCancelWarmupOnSprint()) { + pm.registerEvents(new BoosPlayerToggleSprintListener(), this); + } + if (BoosConfigManager.getSignCommands()) { + pm.registerEvents(new BoosSignChangeListener(), this); + pm.registerEvents(new BoosSignInteractListener(this), this); + } + } + + /** + * Metoda vol� metodu pro znovuna�ten� konfigura�n�ho souboru a metodu pro + * registraci poslucha��. + */ + private void reload() { + BoosConfigManager.reload(); + registerListeners(); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Runnable#run() + */ + @Override + public void run() { + BoosConfigManager.saveConfusers(); + BoosConfigManager.loadConfusers(); + log.info("[boosCooldowns] Config saved!"); + } + + /** + * Metoda vrac� hodnotu true, pokud je na serveru dostupn� Ekonomick� plugin + * kompatibiln� s pluginem Vault. + * + * @return true pokud je dostupn� ekonomick� plugin kompatibiln� s pluginem + * Vault, jinak vrac� hodnotu false + */ + private boolean setupEconomy() { + if (usingVault) { + RegisteredServiceProvider economyProvider = getServer() + .getServicesManager().getRegistration( + net.milkbowl.vault.economy.Economy.class); + if (economyProvider != null) { + economy = economyProvider.getProvider(); + } + return (economy != null); + } + return false; + } + + public static BoosCoolDown getInstance() { + if (instance == null) { + instance = new BoosCoolDown(); + } + return instance; + } +} diff --git a/src/main/java/cz/boosik/boosCooldown/BoosCoolDownListener.java b/src/main/java/cz/boosik/boosCooldown/BoosCoolDownListener.java index 8c0d1b0..03b57ef 100644 --- a/src/main/java/cz/boosik/boosCooldown/BoosCoolDownListener.java +++ b/src/main/java/cz/boosik/boosCooldown/BoosCoolDownListener.java @@ -1,295 +1,295 @@ -package cz.boosik.boosCooldown; - -import java.util.Set; - -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.player.PlayerCommandPreprocessEvent; - -import util.boosChat; - -/** - * Hlavn� poslucha�, kter� naslouch� ud�losti pou�it� p��kazu hr��em. - * Kontroluje, jestli jsou pro p��kaz nastaveny omezen� a na z�klad� tohoto - * spou�t� �asova�e a vol� metody spojen� s poplatky a limity. - * - * @author Jakub Kol�� - * - */ -public class BoosCoolDownListener implements Listener { - private static BoosCoolDown plugin; - - /** - * @param instance - */ - public BoosCoolDownListener(BoosCoolDown instance) { - plugin = instance; - } - - /** - * Metoda zkontroluje pomoc� vol�n� dal��ch metod, jestli p�ikaz kter� hr�� - * pou�il je n�jak�m zp�sobem omezen� a na z�klad� toho je bu� ud�lost - * pou�it� p��kazu stornov�na, nebo ne. - * - * @param event - * ud�lost PlayerCommandPreprocessEvent - * @param player - * hr�� kter� spustil tuto ud�lost - * @param regexCommad - * p��kaz z konfigura�n�ho souboru, kter� vyhovuje origin�ln�mu - * p��kazu - * @param originalCommand - * origin�ln� p��kaz kter� hr�� pou�il - * @param warmupTime - * warmup doba nastaven� pro regexCommand - * @param cooldownTime - * cooldown doba nastaven� pro regexCommand - * @param price - * cena nastaven� pro regexCommand - * @param limit - * limit nastaven� pro regexCommand - */ - private void checkRestrictions(PlayerCommandPreprocessEvent event, - Player player, String regexCommad, String originalCommand, - int warmupTime, int cooldownTime, double price, String item, - int count, int limit, int xpPrice) { - boolean blocked = BoosLimitManager.blocked(player, regexCommad, - originalCommand, limit); - if (!blocked) { - if (warmupTime > 0) { - if (!player.hasPermission("booscooldowns.nowarmup") - && !player.hasPermission("booscooldowns.nowarmup." - + originalCommand)) { - start(event, player, regexCommad, originalCommand, - warmupTime, cooldownTime); - } - } else if (BoosPriceManager.has(player, price) - & BoosItemCostManager.has(player, item, count) - & BoosXpCostManager.has(player, xpPrice)) { - if (BoosCoolDownManager.coolDown(player, regexCommad, - originalCommand, cooldownTime)) { - event.setCancelled(true); - } - } - if (BoosPriceManager.has(player, price) - & BoosItemCostManager.has(player, item, count) - & BoosXpCostManager.has(player, xpPrice)) { - if (!event.isCancelled()) { - BoosPriceManager.payForCommand(event, player, regexCommad, - originalCommand, price); - } - if (!event.isCancelled()) { - BoosItemCostManager.payItemForCommand(event, player, - regexCommad, originalCommand, item, count); - } - if (!event.isCancelled()) { - BoosXpCostManager.payXPForCommand(event, player, - regexCommad, originalCommand, xpPrice); - } - } else { - if (!BoosPriceManager.has(player, price) - & !BoosWarmUpManager.isWarmUpProcess(player, - regexCommad)) { - String unit; - String msg = ""; - if (price == 1) { - unit = BoosCoolDown.getEconomy().currencyNameSingular(); - } else { - unit = BoosCoolDown.getEconomy().currencyNamePlural(); - } - msg = String.format( - BoosConfigManager.getInsufficientFundsMessage(), - (price + " " + unit), - BoosCoolDown.getEconomy().format( - BoosCoolDown.getEconomy() - .getBalance(player))); - msg = msg.replaceAll("&command&", originalCommand); - boosChat.sendMessageToPlayer(player, msg); - } - if (!BoosItemCostManager.has(player, item, count) - & !BoosWarmUpManager.isWarmUpProcess(player, - regexCommad)) { - String msg = ""; - msg = String.format( - BoosConfigManager.getInsufficientItemsMessage(), - (count + " " + item)); - msg = msg.replaceAll("&command&", originalCommand); - boosChat.sendMessageToPlayer(player, msg); - } - if (!BoosXpCostManager.has(player, xpPrice) - & !BoosWarmUpManager.isWarmUpProcess(player, - regexCommad)) { - String msg = ""; - msg = String.format( - BoosConfigManager.getInsufficientXpMessage(), - (xpPrice)); - msg = msg.replaceAll("&command&", originalCommand); - boosChat.sendMessageToPlayer(player, msg); - } - event.setCancelled(true); - } - if (!event.isCancelled()) { - String msg = String.format(BoosConfigManager.getMessage( - regexCommad, player)); - if (!msg.equals("")) { - boosChat.sendMessageToPlayer(player, msg); - } - } - } else { - event.setCancelled(true); - String msg = String.format(BoosConfigManager - .getCommandBlockedMessage()); - boosChat.sendMessageToPlayer(player, msg); - } - if (!event.isCancelled()) { - BoosLimitManager.setUses(player, regexCommad, originalCommand); - if (BoosConfigManager.getCommandLogging()) { - BoosCoolDown.commandLogger(player.getName(), originalCommand); - } - } - } - - /** - * Poslucha�, kter� naslouch� ud�losti pou�it� p��kazu a spou�t� se je�t� - * p�ed t�m, ne� je vykon�n efekt tohto p��kazu. Metoda zji��uje, jestli - * p��kaz nen� alias jin�ho p��kazu a tak� jestli se p��kaz kter� hr�� - * pou�il shoduje s p��kazem nastaven�m v konfiguraci. Pokud se shoduje, pak - * jsou na�teny informace o warmup dob�, cooldown dob�, poplatku a limitu. - * Tyto hodnoty jsou pot� p�ed�ny metod� checkRestrictions();. - * - * @param event - * ud�lost PlayerCommandPreprocessEvent - */ - @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) - private void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) { - Player player = event.getPlayer(); - String originalCommand = event.getMessage().replace("\\", "\\\\"); - originalCommand = originalCommand.replace("$", "S"); - originalCommand = originalCommand.trim().replaceAll(" +", " "); - String regexCommad = ""; - Set aliases = null; - try { - aliases = BoosConfigManager.getAliases(); - } catch (Exception e1) { - BoosCoolDown - .getLog() - .warning( - "Aliases section in config.yml is missing! Please delete your config.yml, restart server and set it again!"); - } - Set commands = BoosConfigManager.getCommands(player); - boolean on = true; - String item = ""; - int count = 0; - int warmupTime = 0; - double price = 0; - int limit = -1; - int cooldownTime = 0; - int xpPrice = 0; - on = BoosCoolDown.isPluginOnForPlayer(player); - try { - if (aliases.contains(originalCommand)) { - originalCommand = BoosConfigManager.getAlias(originalCommand); - if (originalCommand.contains("$player")) { - originalCommand.replaceAll("$player", player.getName()); - } - if (originalCommand.contains("$world")) { - originalCommand.replaceAll("$world", player.getWorld() - .getName()); - } - event.setMessage(originalCommand); - } - } catch (Exception e) { - BoosCoolDown - .getLog() - .warning( - "Aliases section in config.yml is missing! Please delete your config.yml, restart server and set it again!"); - } - if (on) { - for (String group : commands) { - String group2 = group.replace("*", ".+"); - if (originalCommand.matches("(?i)"+group2)) { - regexCommad = group; - if (BoosConfigManager.getWarmupEnabled()) { - warmupTime = BoosConfigManager.getWarmUp(regexCommad, - player); - } - if (BoosConfigManager.getCooldownEnabled()) { - cooldownTime = BoosConfigManager.getCoolDown( - regexCommad, player); - } - if (BoosConfigManager.getPriceEnabled()) { - price = BoosConfigManager.getPrice(regexCommad, player); - } - if (BoosConfigManager.getXpPriceEnabled()) { - xpPrice = BoosConfigManager.getXpPrice(regexCommad, - player); - } - if (BoosConfigManager.getItemCostEnabled()) { - item = BoosConfigManager.getItemCostItem(regexCommad, - player); - count = BoosConfigManager.getItemCostCount(regexCommad, - player); - } - if (BoosConfigManager.getLimitEnabled()) { - limit = BoosConfigManager.getLimit(regexCommad, player); - } - break; - } - } - try { - this.checkRestrictions(event, player, regexCommad, originalCommand, - warmupTime, cooldownTime, price, item, count, limit, - xpPrice); - } catch (Exception e) { - BoosCoolDown.getLog().warning("[boosCooldowns] Looks like you have deleted some important part of config file (like default group or aliases section. To get rid of this message, you have to restore it."); - return; - } - } - } - - /** - * Metoda spou�t� warmup a cooldown �asova�e, p��padn� je ukon�uje, pokud - * ji� tyto �asova�e skon�ili. - * - * @param event - * ud�lost PlayerCommandPreprocessEvent - * @param player - * hr�� kter� spustil tuto ud�lost - * @param regexCommad - * p��kaz z konfigura�n�ho souboru, kter� vyhovuje origin�ln�mu - * p��kazu - * @param originalCommand - * origin�ln� p��kaz kter� hr�� pou�il - * @param warmupTime - * warmup doba nastaven� pro regexCommand - * @param cooldownTime - * cooldown doba nastaven� pro regexCommand - */ - private void start(PlayerCommandPreprocessEvent event, Player player, - String regexCommad, String originalCommand, int warmupTime, - int cooldownTime) { - if (!BoosWarmUpManager.checkWarmUpOK(player, regexCommad)) { - if (BoosCoolDownManager.checkCoolDownOK(player, regexCommad, - originalCommand, cooldownTime)) { - BoosWarmUpManager.startWarmUp(plugin, player, regexCommad, - originalCommand, warmupTime); - event.setCancelled(true); - return; - } else { - event.setCancelled(true); - return; - } - } else { - if (BoosCoolDownManager.coolDown(player, regexCommad, - originalCommand, cooldownTime)) { - event.setCancelled(true); - return; - } else { - BoosWarmUpManager.removeWarmUpOK(player, regexCommad); - return; - } - } - } +package cz.boosik.boosCooldown; + +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerCommandPreprocessEvent; + +import util.boosChat; + +/** + * Hlavn� poslucha�, kter� naslouch� ud�losti pou�it� p��kazu hr��em. + * Kontroluje, jestli jsou pro p��kaz nastaveny omezen� a na z�klad� tohoto + * spou�t� �asova�e a vol� metody spojen� s poplatky a limity. + * + * @author Jakub Kol�� + * + */ +public class BoosCoolDownListener implements Listener { + private static BoosCoolDown plugin; + + /** + * @param instance + */ + public BoosCoolDownListener(BoosCoolDown instance) { + plugin = instance; + } + + /** + * Metoda zkontroluje pomoc� vol�n� dal��ch metod, jestli p�ikaz kter� hr�� + * pou�il je n�jak�m zp�sobem omezen� a na z�klad� toho je bu� ud�lost + * pou�it� p��kazu stornov�na, nebo ne. + * + * @param event + * ud�lost PlayerCommandPreprocessEvent + * @param player + * hr�� kter� spustil tuto ud�lost + * @param regexCommad + * p��kaz z konfigura�n�ho souboru, kter� vyhovuje origin�ln�mu + * p��kazu + * @param originalCommand + * origin�ln� p��kaz kter� hr�� pou�il + * @param warmupTime + * warmup doba nastaven� pro regexCommand + * @param cooldownTime + * cooldown doba nastaven� pro regexCommand + * @param price + * cena nastaven� pro regexCommand + * @param limit + * limit nastaven� pro regexCommand + */ + private void checkRestrictions(PlayerCommandPreprocessEvent event, + Player player, String regexCommad, String originalCommand, + int warmupTime, int cooldownTime, double price, String item, + int count, int limit, int xpPrice) { + boolean blocked = BoosLimitManager.blocked(player, regexCommad, + originalCommand, limit); + if (!blocked) { + if (warmupTime > 0) { + if (!player.hasPermission("booscooldowns.nowarmup") + && !player.hasPermission("booscooldowns.nowarmup." + + originalCommand)) { + start(event, player, regexCommad, originalCommand, + warmupTime, cooldownTime); + } + } else if (BoosPriceManager.has(player, price) + & BoosItemCostManager.has(player, item, count) + & BoosXpCostManager.has(player, xpPrice)) { + if (BoosCoolDownManager.coolDown(player, regexCommad, + originalCommand, cooldownTime)) { + event.setCancelled(true); + } + } + if (BoosPriceManager.has(player, price) + & BoosItemCostManager.has(player, item, count) + & BoosXpCostManager.has(player, xpPrice)) { + if (!event.isCancelled()) { + BoosPriceManager.payForCommand(event, player, regexCommad, + originalCommand, price); + } + if (!event.isCancelled()) { + BoosItemCostManager.payItemForCommand(event, player, + regexCommad, originalCommand, item, count); + } + if (!event.isCancelled()) { + BoosXpCostManager.payXPForCommand(event, player, + regexCommad, originalCommand, xpPrice); + } + } else { + if (!BoosPriceManager.has(player, price) + & !BoosWarmUpManager.isWarmUpProcess(player, + regexCommad)) { + String unit; + String msg = ""; + if (price == 1) { + unit = BoosCoolDown.getEconomy().currencyNameSingular(); + } else { + unit = BoosCoolDown.getEconomy().currencyNamePlural(); + } + msg = String.format( + BoosConfigManager.getInsufficientFundsMessage(), + (price + " " + unit), + BoosCoolDown.getEconomy().format( + BoosCoolDown.getEconomy() + .getBalance(player))); + msg = msg.replaceAll("&command&", originalCommand); + boosChat.sendMessageToPlayer(player, msg); + } + if (!BoosItemCostManager.has(player, item, count) + & !BoosWarmUpManager.isWarmUpProcess(player, + regexCommad)) { + String msg = ""; + msg = String.format( + BoosConfigManager.getInsufficientItemsMessage(), + (count + " " + item)); + msg = msg.replaceAll("&command&", originalCommand); + boosChat.sendMessageToPlayer(player, msg); + } + if (!BoosXpCostManager.has(player, xpPrice) + & !BoosWarmUpManager.isWarmUpProcess(player, + regexCommad)) { + String msg = ""; + msg = String.format( + BoosConfigManager.getInsufficientXpMessage(), + (xpPrice)); + msg = msg.replaceAll("&command&", originalCommand); + boosChat.sendMessageToPlayer(player, msg); + } + event.setCancelled(true); + } + if (!event.isCancelled()) { + String msg = String.format(BoosConfigManager.getMessage( + regexCommad, player)); + if (!msg.equals("")) { + boosChat.sendMessageToPlayer(player, msg); + } + } + } else { + event.setCancelled(true); + } + if (!event.isCancelled()) { + BoosLimitManager.setUses(player, regexCommad); + if (BoosConfigManager.getCommandLogging()) { + BoosCoolDown.commandLogger(player.getName(), originalCommand); + } + } + } + + /** + * Poslucha�, kter� naslouch� ud�losti pou�it� p��kazu a spou�t� se je�t� + * p�ed t�m, ne� je vykon�n efekt tohto p��kazu. Metoda zji��uje, jestli + * p��kaz nen� alias jin�ho p��kazu a tak� jestli se p��kaz kter� hr�� + * pou�il shoduje s p��kazem nastaven�m v konfiguraci. Pokud se shoduje, pak + * jsou na�teny informace o warmup dob�, cooldown dob�, poplatku a limitu. + * Tyto hodnoty jsou pot� p�ed�ny metod� checkRestrictions();. + * + * @param event + * ud�lost PlayerCommandPreprocessEvent + */ + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + private void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) { + Player player = event.getPlayer(); + if (event.getMessage().contains(":")) { + Pattern p = Pattern.compile("^/([a-zA-Z0-9_]+):"); + Matcher m = p.matcher(event.getMessage()); + if (m.find()) { + { + boosChat.sendMessageToPlayer(player, BoosConfigManager + .getInvalidCommandSyntaxMessage(player)); + event.setCancelled(true); + return; + } + } + } + String originalCommand = event.getMessage().replace("\\", "\\\\"); + originalCommand = originalCommand.replace("$", "S"); + originalCommand = originalCommand.trim().replaceAll(" +", " "); + String regexCommad = ""; + Set aliases = null; + try { + aliases = BoosConfigManager.getAliases(); + } catch (Exception e1) { + BoosCoolDown + .getLog() + .warning( + "Aliases section in config.yml is missing! Please delete your config.yml, restart server and set it again!"); + } + Set commands = BoosConfigManager.getCommands(player); + boolean on = true; + String item = ""; + int count = 0; + int warmupTime = 0; + double price = 0; + int limit = -1; + int cooldownTime = 0; + int xpPrice = 0; + on = BoosCoolDown.isPluginOnForPlayer(player); + originalCommand = BoosAliasManager.checkCommandAlias(originalCommand, + aliases, player); + event.setMessage(originalCommand); + if (on) { + for (String group : commands) { + String group2 = group.replace("*", ".+"); + if (originalCommand.matches("(?i)" + group2)) { + regexCommad = group; + if (BoosConfigManager.getWarmupEnabled()) { + warmupTime = BoosConfigManager.getWarmUp(regexCommad, + player); + } + if (BoosConfigManager.getCooldownEnabled()) { + cooldownTime = BoosConfigManager.getCoolDown( + regexCommad, player); + } + if (BoosConfigManager.getPriceEnabled()) { + price = BoosConfigManager.getPrice(regexCommad, player); + } + if (BoosConfigManager.getXpPriceEnabled()) { + xpPrice = BoosConfigManager.getXpPrice(regexCommad, + player); + } + if (BoosConfigManager.getItemCostEnabled()) { + item = BoosConfigManager.getItemCostItem(regexCommad, + player); + count = BoosConfigManager.getItemCostCount(regexCommad, + player); + } + if (BoosConfigManager.getLimitEnabled()) { + limit = BoosConfigManager.getLimit(regexCommad, player); + } + break; + } + } + this.checkRestrictions(event, player, regexCommad, originalCommand, + warmupTime, cooldownTime, price, item, count, limit, + xpPrice); + try { + } catch (Exception e) { + BoosCoolDown + .getLog() + .warning( + "[boosCooldowns] Looks like you have deleted some important part of config file (like default group or aliases section. To get rid of this message, you have to restore it."); + return; + } + } + } + + /** + * Metoda spou�t� warmup a cooldown �asova�e, p��padn� je ukon�uje, pokud + * ji� tyto �asova�e skon�ili. + * + * @param event + * ud�lost PlayerCommandPreprocessEvent + * @param player + * hr�� kter� spustil tuto ud�lost + * @param regexCommad + * p��kaz z konfigura�n�ho souboru, kter� vyhovuje origin�ln�mu + * p��kazu + * @param originalCommand + * origin�ln� p��kaz kter� hr�� pou�il + * @param warmupTime + * warmup doba nastaven� pro regexCommand + * @param cooldownTime + * cooldown doba nastaven� pro regexCommand + */ + private void start(PlayerCommandPreprocessEvent event, Player player, + String regexCommad, String originalCommand, int warmupTime, + int cooldownTime) { + if (!BoosWarmUpManager.checkWarmUpOK(player, regexCommad)) { + if (BoosCoolDownManager.checkCoolDownOK(player, regexCommad, + originalCommand, cooldownTime)) { + BoosWarmUpManager.startWarmUp(plugin, player, regexCommad, + originalCommand, warmupTime); + event.setCancelled(true); + return; + } else { + event.setCancelled(true); + return; + } + } else { + if (BoosCoolDownManager.coolDown(player, regexCommad, + originalCommand, cooldownTime)) { + event.setCancelled(true); + return; + } else { + BoosWarmUpManager.removeWarmUpOK(player, regexCommad); + return; + } + } + } } \ No newline at end of file diff --git a/src/main/java/cz/boosik/boosCooldown/BoosCoolDownManager.java b/src/main/java/cz/boosik/boosCooldown/BoosCoolDownManager.java index ec37db9..96f6558 100644 --- a/src/main/java/cz/boosik/boosCooldown/BoosCoolDownManager.java +++ b/src/main/java/cz/boosik/boosCooldown/BoosCoolDownManager.java @@ -1,304 +1,300 @@ -package cz.boosik.boosCooldown; - -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.Date; -import java.util.List; - -import org.bukkit.entity.Player; - -import util.boosChat; - -/** - * T��da obsahuje ve�ker� metody pot�ebn� k ��zen� cooldown �asova��. Spou�t�n�, - * ukon�ov�n�, zji��ov�n� zda je cooldown �asova� ji� aktivn�. - * - * @author Jakub Kol�� - * - */ -public class BoosCoolDownManager { - /** - * Metoda ukon�uje specifikovan� cooldown �asova� pro specifikovan�ho hr��e. - * - * @param player - * specifick� hr�� - * @param regexCommand - * p��kaz z konfigurace vyhovuj�c� origin�ln�mu p��kazu - */ - static void cancelCooldown(Player player, String regexCommand) { - int pre2 = regexCommand.toLowerCase().hashCode(); - BoosConfigManager.getConfusers().set( - "users." + player.getUniqueId() + ".cooldown." + pre2, null); - } - - /** - * Metoda vrac� hodnotu boolean na z�klad� toho, jestli m� specifikovan� - * p��kaz aktivn� cooldown �asova�. - * - * @param player - * specifikovan� hr�� - * @param regexCommand - * p��kaz z konfigurace vyhovuj�c� origin�ln�mu p��kazu - * @param originalCommand - * origin�ln� p��kaz pou�it� hr��em - * @param coolDownSeconds - * cooldown doba v sekund�ch, nastaven� pro regexCommand v - * konfiguraci - * @return true pokud je p��kaz na cooldown �asova�i, jinak false - */ - static boolean cd(Player player, String regexCommand, - String originalCommand, int coolDownSeconds) { - Date lastTime = getTime(player, regexCommand); - String link = BoosConfigManager.getLink(regexCommand); - if (lastTime == null) { - if (link == null) { - setTime(player, regexCommand); - } else { - List linkGroup = BoosConfigManager.getLinkList(link); - for (String a : linkGroup) { - setTime(player, a); - } - } - return false; - } else { - Calendar calcurrTime = Calendar.getInstance(); - calcurrTime.setTime(getCurrTime()); - Calendar callastTime = Calendar.getInstance(); - callastTime.setTime(lastTime); - long secondsBetween = secondsBetween(callastTime, calcurrTime); - long waitSeconds = coolDownSeconds - secondsBetween; - long waitMinutes = Math.round(waitSeconds / 60) + 1; - long waitHours = Math.round(waitMinutes / 60) + 1; - if (secondsBetween > coolDownSeconds) { - if (link == null) { - setTime(player, regexCommand); - } else { - List linkGroup = BoosConfigManager - .getLinkList(link); - for (String a : linkGroup) { - setTime(player, a); - } - } - return false; - } else { - String msg = BoosConfigManager.getCoolDownMessage(); - msg = msg.replaceAll("&command&", originalCommand); - if (waitSeconds >= 60 && 3600 >= waitSeconds) { - msg = msg.replaceAll("&seconds&", - Long.toString(waitMinutes)); - msg = msg.replaceAll("&unit&", - BoosConfigManager.getUnitMinutesMessage()); - } else if (waitMinutes >= 60) { - msg = msg.replaceAll("&seconds&", Long.toString(waitHours)); - msg = msg.replaceAll("&unit&", - BoosConfigManager.getUnitHoursMessage()); - } else { - String secs = Long.toString(waitSeconds); - if (secs.equals("0")) { - secs = "1"; - } - msg = msg.replaceAll("&seconds&", secs); - msg = msg.replaceAll("&unit&", - BoosConfigManager.getUnitSecondsMessage()); - } - boosChat.sendMessageToPlayer(player, msg); - return true; - } - } - } - - /** - * Metoda kontroluje, jestli hr�� nedisponuje opr�vn�n�mi, kter� obch�zej� - * cooldown �asova�e. Pokud t�mito opr�vn�n�mi hr�� disponuje, pak metoda - * vrac� false. Pokud hr�� nedisponuje t�mito opr�vn�n�mi, vrac� hodnotu - * vr�cenou metodou cd();. - * - * @param player - * specifikovan� hr�� - * @param regexCommand - * p��kaz z konfigurace vyhovuj�c� origin�ln�mu p��kazu - * @param originalCommand - * origin�ln� p��kaz pou�it� hr��em - * @param time - * cooldown doba v sekund�ch, nastaven� pro regexCommand v - * konfiguraci - * @return false pokud hr�� disponuje opr�vn�n�mi, jinak hodnotu vr�cenou - * metodou cd();. - */ - static boolean coolDown(Player player, String regexCommand, - String originalCommand, int time) { - regexCommand = regexCommand.toLowerCase(); - if (time > 0 - && !player.hasPermission("booscooldowns.nocooldown") - && !player.hasPermission("booscooldowns.nocooldown." - + originalCommand)) { - return cd(player, regexCommand, originalCommand, time); - } - return false; - } - - /** - * Metoda vrac� sou�asn� p�esn� datum a �as. - * - * @return sou�asn� �as a datum - */ - static Date getCurrTime() { - String currTime = ""; - Calendar cal = Calendar.getInstance(); - SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); - currTime = sdf.format(cal.getTime()); - Date time = null; - - try { - time = sdf.parse(currTime); - return time; - } catch (ParseException e) { - return null; - } - } - - /** - * Metoda vrac� datum a �as, kdy hr�� naposledy pou�il dan� p��kaz. - * - * @param player - * specifikovan� hr�� - * @param regexCommand - * p��kaz z konfigurace vyhovuj�c� origin�ln�mu p��kazu - * @return datum a �as kdy hr�� naposledy pou�il dan� p��kaz - */ - static Date getTime(Player player, String regexCommand) { - int pre2 = regexCommand.toLowerCase().hashCode(); - String confTime = ""; - confTime = BoosConfigManager.getConfusers().getString( - "users." + player.getName().toLowerCase().hashCode() - + ".cooldown." + pre2, null); - - if (confTime != null && !confTime.equals("")) { - SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); - Date lastDate = null; - - try { - lastDate = sdf.parse(confTime); - return lastDate; - } catch (ParseException e) { - return null; - } - } - return null; - } - - /** - * Metoda vrac� hodnotu boolean na z�klad� toho, jestli m� specifikovan� - * p��kaz aktivn� cooldown �asova�. - * - * @param player - * specifikovan� hr�� - * @param regexCommand - * p��kaz z konfigurace vyhovuj�c� origin�ln�mu p��kazu - * @param originalCommand - * origin�ln� p��kaz pou�it� hr��em - * @param time - * cooldown doba v sekund�ch, nastaven� pro regexCommand v - * konfiguraci - * @return false pokud m� p��kaz aktivn� cooldown �asova�, jinak false - */ - static boolean checkCoolDownOK(Player player, String regexCommand, - String originalCommand, int time) { - regexCommand = regexCommand.toLowerCase(); - if (time > 0) { - Date lastTime = getTime(player, regexCommand); - if (lastTime == null) { - return true; - } else { - Calendar calcurrTime = Calendar.getInstance(); - calcurrTime.setTime(getCurrTime()); - Calendar callastTime = Calendar.getInstance(); - callastTime.setTime(lastTime); - long secondsBetween = secondsBetween(callastTime, calcurrTime); - long waitSeconds = time - secondsBetween; - long waitMinutes = Math.round(waitSeconds / 60) + 1; - long waitHours = Math.round(waitMinutes / 60) + 1; - if (secondsBetween > time) { - return true; - } else { - String msg = BoosConfigManager.getCoolDownMessage(); - msg = msg.replaceAll("&command&", originalCommand); - if (waitSeconds >= 60 && 3600 >= waitSeconds) { - msg = msg.replaceAll("&seconds&", - Long.toString(waitMinutes)); - msg = msg.replaceAll("&unit&", - BoosConfigManager.getUnitMinutesMessage()); - } else if (waitMinutes >= 60) { - msg = msg.replaceAll("&seconds&", - Long.toString(waitHours)); - msg = msg.replaceAll("&unit&", - BoosConfigManager.getUnitHoursMessage()); - } else { - msg = msg.replaceAll("&seconds&", - Long.toString(waitSeconds)); - msg = msg.replaceAll("&unit&", - BoosConfigManager.getUnitSecondsMessage()); - } - boosChat.sendMessageToPlayer(player, msg); - return false; - } - } - } - return true; - } - - /** - * Metoda vrac� hodnotu rozd�lu v sekund�ch mezi dv�mi hodnotami datumu a - * �asu. - * - * @param startDate - * @param endDate - * @return rozd�l v sekund�ch mezi startDate a endDate - */ - static long secondsBetween(Calendar startDate, Calendar endDate) { - long secondsBetween = 0; - - while (startDate.before(endDate)) { - startDate.add(Calendar.SECOND, 1); - secondsBetween++; - } - return secondsBetween; - } - - /** - * Metoda ukl�d� do datab�ze datum a �as kdy hr�� naposledy pou�il dan� - * p��kaz. - * - * @param player - * specifick� hr�� - * @param regexCommand - * p��kaz z konfigurace vyhovuj�c� origin�ln�mu p��kazu - */ - static void setTime(Player player, String regexCommand) { - int pre2 = regexCommand.toLowerCase().hashCode(); - String currTime = ""; - Calendar cal = Calendar.getInstance(); - SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); - currTime = sdf.format(cal.getTime()); - BoosConfigManager.getConfusers().set( - "users." + player.getName().toLowerCase().hashCode() - + ".cooldown." + pre2, currTime); - } - - /** - * Metoda spou�t� ve�ker� cooldown �asova�e pro specifick�ho hr��e. - * - * @param player - * specifick� hr�� - * @param message - */ - public static void startAllCooldowns(Player player, String message) { - for (String a : BoosConfigManager.getCooldowns(player)) { - int cooldownTime = BoosConfigManager.getCoolDown(a, player); - coolDown(player, a, message, cooldownTime); - } - - } - -} +package cz.boosik.boosCooldown; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.List; + +import org.bukkit.entity.Player; + +import util.boosChat; + +/** + * T��da obsahuje ve�ker� metody pot�ebn� k ��zen� cooldown �asova��. Spou�t�n�, + * ukon�ov�n�, zji��ov�n� zda je cooldown �asova� ji� aktivn�. + * + * @author Jakub Kol�� + * + */ +public class BoosCoolDownManager { + /** + * Metoda ukon�uje specifikovan� cooldown �asova� pro specifikovan�ho hr��e. + * + * @param player + * specifick� hr�� + * @param regexCommand + * p��kaz z konfigurace vyhovuj�c� origin�ln�mu p��kazu + */ + static void cancelCooldown(Player player, String regexCommand) { + int pre2 = regexCommand.toLowerCase().hashCode(); + BoosConfigManager.getConfusers().set( + "users." + player.getUniqueId() + ".cooldown." + pre2, null); + } + + /** + * Metoda vrac� hodnotu boolean na z�klad� toho, jestli m� specifikovan� + * p��kaz aktivn� cooldown �asova�. + * + * @param player + * specifikovan� hr�� + * @param regexCommand + * p��kaz z konfigurace vyhovuj�c� origin�ln�mu p��kazu + * @param originalCommand + * origin�ln� p��kaz pou�it� hr��em + * @param coolDownSeconds + * cooldown doba v sekund�ch, nastaven� pro regexCommand v + * konfiguraci + * @return true pokud je p��kaz na cooldown �asova�i, jinak false + */ + static boolean cd(Player player, String regexCommand, + String originalCommand, int coolDownSeconds) { + Date lastTime = getTime(player, regexCommand); + List linkGroup = BoosConfigManager.getSharedCooldowns( + regexCommand, player); + if (lastTime == null) { + if (linkGroup.isEmpty()) { + setTime(player, regexCommand); + } else { + setTime(player, regexCommand); + for (String a : linkGroup) { + setTime(player, a); + } + } + return false; + } else { + Calendar calcurrTime = Calendar.getInstance(); + calcurrTime.setTime(getCurrTime()); + Calendar callastTime = Calendar.getInstance(); + callastTime.setTime(lastTime); + long secondsBetween = secondsBetween(callastTime, calcurrTime); + long waitSeconds = coolDownSeconds - secondsBetween; + long waitMinutes = (long) Math.ceil(waitSeconds / 60.0); + long waitHours = (long) Math.ceil(waitMinutes / 60.0); + if (secondsBetween > coolDownSeconds) { + if (linkGroup.isEmpty()) { + setTime(player, regexCommand); + } else { + setTime(player, regexCommand); + for (String a : linkGroup) { + setTime(player, a); + } + } + return false; + } else { + String msg = BoosConfigManager.getCoolDownMessage(); + msg = msg.replaceAll("&command&", originalCommand); + if (waitSeconds >= 60 && 3600 >= waitSeconds) { + msg = msg.replaceAll("&seconds&", + Long.toString(waitMinutes)); + msg = msg.replaceAll("&unit&", + BoosConfigManager.getUnitMinutesMessage()); + } else if (waitMinutes >= 60) { + msg = msg.replaceAll("&seconds&", Long.toString(waitHours)); + msg = msg.replaceAll("&unit&", + BoosConfigManager.getUnitHoursMessage()); + } else { + String secs = Long.toString(waitSeconds); + if (secs.equals("0")) { + secs = "1"; + } + msg = msg.replaceAll("&seconds&", secs); + msg = msg.replaceAll("&unit&", + BoosConfigManager.getUnitSecondsMessage()); + } + boosChat.sendMessageToPlayer(player, msg); + return true; + } + } + } + + /** + * Metoda kontroluje, jestli hr�� nedisponuje opr�vn�n�mi, kter� obch�zej� + * cooldown �asova�e. Pokud t�mito opr�vn�n�mi hr�� disponuje, pak metoda + * vrac� false. Pokud hr�� nedisponuje t�mito opr�vn�n�mi, vrac� hodnotu + * vr�cenou metodou cd();. + * + * @param player + * specifikovan� hr�� + * @param regexCommand + * p��kaz z konfigurace vyhovuj�c� origin�ln�mu p��kazu + * @param originalCommand + * origin�ln� p��kaz pou�it� hr��em + * @param time + * cooldown doba v sekund�ch, nastaven� pro regexCommand v + * konfiguraci + * @return false pokud hr�� disponuje opr�vn�n�mi, jinak hodnotu vr�cenou + * metodou cd();. + */ + static boolean coolDown(Player player, String regexCommand, + String originalCommand, int time) { + regexCommand = regexCommand.toLowerCase(); + if (time > 0 + && !player.hasPermission("booscooldowns.nocooldown") + && !player.hasPermission("booscooldowns.nocooldown." + + originalCommand)) { + return cd(player, regexCommand, originalCommand, time); + } + return false; + } + + /** + * Metoda vrac� sou�asn� p�esn� datum a �as. + * + * @return sou�asn� �as a datum + */ + static Date getCurrTime() { + String currTime = ""; + Calendar cal = Calendar.getInstance(); + SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); + currTime = sdf.format(cal.getTime()); + Date time = null; + + try { + time = sdf.parse(currTime); + return time; + } catch (ParseException e) { + return null; + } + } + + /** + * Metoda vrac� datum a �as, kdy hr�� naposledy pou�il dan� p��kaz. + * + * @param player + * specifikovan� hr�� + * @param regexCommand + * p��kaz z konfigurace vyhovuj�c� origin�ln�mu p��kazu + * @return datum a �as kdy hr�� naposledy pou�il dan� p��kaz + */ + static Date getTime(Player player, String regexCommand) { + int pre2 = regexCommand.toLowerCase().hashCode(); + String confTime = ""; + confTime = BoosConfigManager.getConfusers().getString( + "users." + player.getUniqueId() + ".cooldown." + pre2, null); + + if (confTime != null && !confTime.equals("")) { + SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); + Date lastDate = null; + + try { + lastDate = sdf.parse(confTime); + return lastDate; + } catch (ParseException e) { + return null; + } + } + return null; + } + + /** + * Metoda vrac� hodnotu boolean na z�klad� toho, jestli m� specifikovan� + * p��kaz aktivn� cooldown �asova�. + * + * @param player + * specifikovan� hr�� + * @param regexCommand + * p��kaz z konfigurace vyhovuj�c� origin�ln�mu p��kazu + * @param originalCommand + * origin�ln� p��kaz pou�it� hr��em + * @param time + * cooldown doba v sekund�ch, nastaven� pro regexCommand v + * konfiguraci + * @return false pokud m� p��kaz aktivn� cooldown �asova�, jinak false + */ + static boolean checkCoolDownOK(Player player, String regexCommand, + String originalCommand, int time) { + regexCommand = regexCommand.toLowerCase(); + if (time > 0) { + Date lastTime = getTime(player, regexCommand); + if (lastTime == null) { + return true; + } else { + Calendar calcurrTime = Calendar.getInstance(); + calcurrTime.setTime(getCurrTime()); + Calendar callastTime = Calendar.getInstance(); + callastTime.setTime(lastTime); + long secondsBetween = secondsBetween(callastTime, calcurrTime); + long waitSeconds = time - secondsBetween; + long waitMinutes = (long) Math.ceil(waitSeconds / 60.0); + long waitHours = (long) Math.ceil(waitMinutes / 60.0); + if (secondsBetween > time) { + return true; + } else { + String msg = BoosConfigManager.getCoolDownMessage(); + msg = msg.replaceAll("&command&", originalCommand); + if (waitSeconds >= 60 && 3600 >= waitSeconds) { + msg = msg.replaceAll("&seconds&", + Long.toString(waitMinutes)); + msg = msg.replaceAll("&unit&", + BoosConfigManager.getUnitMinutesMessage()); + } else if (waitMinutes >= 60) { + msg = msg.replaceAll("&seconds&", + Long.toString(waitHours)); + msg = msg.replaceAll("&unit&", + BoosConfigManager.getUnitHoursMessage()); + } else { + msg = msg.replaceAll("&seconds&", + Long.toString(waitSeconds)); + msg = msg.replaceAll("&unit&", + BoosConfigManager.getUnitSecondsMessage()); + } + boosChat.sendMessageToPlayer(player, msg); + return false; + } + } + } + return true; + } + + /** + * Metoda vrac� hodnotu rozd�lu v sekund�ch mezi dv�mi hodnotami datumu a + * �asu. + * + * @param startDate + * @param endDate + * @return rozd�l v sekund�ch mezi startDate a endDate + */ + static long secondsBetween(Calendar startDate, Calendar endDate) { + long secondsBetween = 0; + secondsBetween = (endDate.getTimeInMillis() - startDate + .getTimeInMillis()) / 1000; + return secondsBetween; + } + + /** + * Metoda ukl�d� do datab�ze datum a �as kdy hr�� naposledy pou�il dan� + * p��kaz. + * + * @param player + * specifick� hr�� + * @param regexCommand + * p��kaz z konfigurace vyhovuj�c� origin�ln�mu p��kazu + */ + static void setTime(Player player, String regexCommand) { + int pre2 = regexCommand.toLowerCase().hashCode(); + String currTime = ""; + Calendar cal = Calendar.getInstance(); + SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); + currTime = sdf.format(cal.getTime()); + BoosConfigManager.getConfusers() + .set("users." + player.getUniqueId() + ".cooldown." + pre2, + currTime); + } + + /** + * Metoda spou�t� ve�ker� cooldown �asova�e pro specifick�ho hr��e. + * + * @param player + * specifick� hr�� + * @param message + */ + public static void startAllCooldowns(Player player, String message) { + for (String a : BoosConfigManager.getCooldowns(player)) { + int cooldownTime = BoosConfigManager.getCoolDown(a, player); + coolDown(player, a, message, cooldownTime); + } + + } + +} diff --git a/src/main/java/cz/boosik/boosCooldown/BoosLimitManager.java b/src/main/java/cz/boosik/boosCooldown/BoosLimitManager.java index 8fddd5e..30db179 100644 --- a/src/main/java/cz/boosik/boosCooldown/BoosLimitManager.java +++ b/src/main/java/cz/boosik/boosCooldown/BoosLimitManager.java @@ -1,132 +1,362 @@ -package cz.boosik.boosCooldown; - -import org.bukkit.entity.Player; - -import util.boosChat; - -/** - * T��da obsahuje ve�ker� metody pot�ebn� k ��zen� limit�. - * - * @author Jakub Kol�� - * - */ -public class BoosLimitManager { - /** - * Metoda kontroluje zda je mo�n� pou��t p��kaz, nebo zda je p��kaz ji� - * zablokovan�. - * - * @param player - * specifick� hr�� - * @param regexCommand - * p��kaz z konfigura�n�ho souboru, kter� vyhovuje origin�ln�mu - * p��kazu - * @param originalCommand - * origin�ln� p��kaz pou�it� hr��em - * @param limit - * limit nastaven� pro regexCommand - * @return false pokud p��kaz je mo�n� pou��t, true pokud p��kaz nen� mo�n� - * pou��t - */ - static boolean blocked(Player player, String regexCommand, - String originalCommand, int limit) { - int uses = getUses(player, regexCommand); - if (player.hasPermission("booscooldowns.nolimit") - || player.hasPermission("booscooldowns.nolimit." - + originalCommand)) { - } else { - if (limit == -1) { - return false; - } else if (limit <= uses) { - return true; - } - } - return false; - } - - /** - * Metoda vrac� hodnotu, kter� je ur�ena t�m, kolikr�t ji� hr�� pou�il - * specifikovan� p��kaz. - * - * @param player - * specifick� hr�� - * @param regexCommand - * p��kaz z konfigura�n�ho souboru, kter� vyhovuje origin�ln�mu - * p��kazu - * @return hodnota p�edstavuj�ci po�et pou�it� specifikovan�ho p��kazu - */ - static int getUses(Player player, String regexCommand) { - int regexCommand2 = regexCommand.toLowerCase().hashCode(); - int uses = 0; - uses = BoosConfigManager.getConfusers().getInt( - "users." + player.getUniqueId() + ".uses." + regexCommand2, - uses); - return uses; - } - - /** - * Metoda nastavuje po�et pou�it� p��kazu o jedna v�t�� po ka�d�m pou�it� - * p��kazu hr��em. Nasteven� hodnoty prob�h� jen pro p��kazy, kter� jsou - * definov�ny v konfiguraci. - * - * @param player - * specifick� hr�� - * @param regexCommand - * p��kaz z konfigura�n�ho souboru, kter� vyhovuje origin�ln�mu - * p��kazu - * @param originalCommand - * origin�ln� p��kaz pou�it� hr��em - */ - static void setUses(Player player, String regexCommand, - String originalCommand) { - if (BoosConfigManager.getLimitsEnabled()) { - if (BoosConfigManager.getCommands(player).contains(regexCommand)) { - int regexCommand2 = regexCommand.toLowerCase().hashCode(); - int uses = getUses(player, regexCommand); - uses = uses + 1; - try { - BoosConfigManager.getConfusers().set( - "users." - + player.getName().toLowerCase().hashCode() - + ".uses." + regexCommand2, uses); - } catch (IllegalArgumentException e) { - BoosCoolDown - .getLog() - .warning( - "Player " - + player.getName() - + " used empty command and caused this error!"); - } - } else { - return; - } - } - } - - /** - * Metoda odes�l� hr��i zpr�vu o limitovan�m p��kazu, hodnotu tohoto limitu - * a kolikr�t je je�t� mo�n� limitovan� p��kaz pou��t. - * - * @param send - * hr�� kter�mu bude odesl�n seznam - * @param comm - * p��kaz o kter�m si hr�� vy��dal informace - * @param lim - * hodnota limitu na p��kazu - */ - static void getLimitListMessages(Player send, String comm, int lim) { - if (lim != -1) { - int uses = getUses(send, comm); - String message = BoosConfigManager.getLimitListMessage(); - int num = lim - uses; - if (num < 0) { - num = 0; - } - message = BoosConfigManager.getLimitListMessage(); - message = message.replaceAll("&command&", comm); - message = message.replaceAll("&limit&", String.valueOf(lim)); - message = message.replaceAll("×&", String.valueOf(num)); - boosChat.sendMessageToPlayer(send, message); - } - } - -} +package cz.boosik.boosCooldown; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.Set; +import org.bukkit.entity.Player; + +import util.boosChat; + +/** + * T��da obsahuje ve�ker� metody pot�ebn� k ��zen� limit�. + * + * @author Jakub Kol�� + * + */ +public class BoosLimitManager { + /** + * Metoda kontroluje zda je mo�n� pou��t p��kaz, nebo zda je p��kaz ji� + * zablokovan�. + * + * @param player + * specifick� hr�� + * @param regexCommand + * p��kaz z konfigura�n�ho souboru, kter� vyhovuje origin�ln�mu + * p��kazu + * @param originalCommand + * origin�ln� p��kaz pou�it� hr��em + * @param limit + * limit nastaven� pro regexCommand + * @return false pokud p��kaz je mo�n� pou��t, true pokud p��kaz nen� mo�n� + * pou��t + */ + static boolean blocked(Player player, String regexCommand, + String originalCommand, int limit) { + Date time = getTime(player, regexCommand); + Date confTime = getTime(regexCommand); + Calendar calcurrTime = Calendar.getInstance(); + calcurrTime.setTime(getCurrTime()); + Calendar callastTime = Calendar.getInstance(); + Calendar callastTimeGlobal = Calendar.getInstance(); + int uses = getUses(player, regexCommand); + long limitResetDelay = BoosConfigManager.getLimitResetDelay( + regexCommand, player); + long limitResetDelayGlobal = BoosConfigManager + .getLimitResetDelayGlobal(regexCommand); + if (time != null) { + callastTime.setTime(time); + } else { + setTime(player, regexCommand); + } + if (limit - uses == 1) { + setTime(player, regexCommand); + time = getTime(player, regexCommand); + callastTime.setTime(time); + } + if (limitResetDelay > 0) { + if (secondsBetween(callastTime, calcurrTime, limitResetDelay) <= 0) { + if (uses != 0) { + BoosConfigManager.clearSomething("uses", + player.getUniqueId(), regexCommand); + uses = getUses(player, regexCommand); + } + } + } + + if (player.hasPermission("booscooldowns.nolimit") + || player.hasPermission("booscooldowns.nolimit." + + originalCommand)) { + } else { + if (limit == -1) { + return false; + } else if (limit <= uses) { + if (limitResetDelay > 0) { + long secondsBetween = secondsBetween(callastTime, + calcurrTime, limitResetDelay); + long waitSeconds = secondsBetween; + long waitMinutes = Math.round(waitSeconds / 60) + 1; + long waitHours = Math.round(waitMinutes / 60) + 1; + String msg = BoosConfigManager.getLimitResetMessage(); + msg = msg.replaceAll("&command&", originalCommand); + if (waitSeconds >= 60 && 3600 >= waitSeconds) { + msg = msg.replaceAll("&seconds&", + Long.toString(waitMinutes)); + msg = msg.replaceAll("&unit&", + BoosConfigManager.getUnitMinutesMessage()); + } else if (waitMinutes >= 60) { + msg = msg.replaceAll("&seconds&", + Long.toString(waitHours)); + msg = msg.replaceAll("&unit&", + BoosConfigManager.getUnitHoursMessage()); + } else { + msg = msg.replaceAll("&seconds&", + Long.toString(waitSeconds)); + msg = msg.replaceAll("&unit&", + BoosConfigManager.getUnitSecondsMessage()); + } + boosChat.sendMessageToPlayer(player, msg); + } else if (limitResetDelayGlobal > 0) { + if (confTime != null) { + callastTimeGlobal.setTime(confTime); + long secondsBetween = secondsBetween(callastTimeGlobal, + calcurrTime, limitResetDelayGlobal); + long waitSeconds = secondsBetween; + long waitMinutes = (long) Math.ceil(waitSeconds / 60.0); + long waitHours = (long) Math.ceil(waitMinutes / 60.0); + String msg = BoosConfigManager.getLimitResetMessage(); + msg = msg.replaceAll("&command&", originalCommand); + if (waitSeconds >= 60 && 3600 >= waitSeconds) { + msg = msg.replaceAll("&seconds&", + Long.toString(waitMinutes)); + msg = msg.replaceAll("&unit&", + BoosConfigManager.getUnitMinutesMessage()); + } else if (waitMinutes >= 60) { + msg = msg.replaceAll("&seconds&", + Long.toString(waitHours)); + msg = msg.replaceAll("&unit&", + BoosConfigManager.getUnitHoursMessage()); + } else { + msg = msg.replaceAll("&seconds&", + Long.toString(waitSeconds)); + msg = msg.replaceAll("&unit&", + BoosConfigManager.getUnitSecondsMessage()); + } + boosChat.sendMessageToPlayer(player, msg); + } + } else { + String msg = String.format(BoosConfigManager + .getCommandBlockedMessage()); + boosChat.sendMessageToPlayer(player, msg); + } + return true; + } + } + return false; + } + + /** + * Metoda vrac� hodnotu, kter� je ur�ena t�m, kolikr�t ji� hr�� pou�il + * specifikovan� p��kaz. + * + * @param player + * specifick� hr�� + * @param regexCommand + * p��kaz z konfigura�n�ho souboru, kter� vyhovuje origin�ln�mu + * p��kazu + * @return hodnota p�edstavuj�ci po�et pou�it� specifikovan�ho p��kazu + */ + static int getUses(Player player, String regexCommand) { + int regexCommand2 = regexCommand.toLowerCase().hashCode(); + int uses = 0; + uses = BoosConfigManager.getConfusers().getInt( + "users." + player.getUniqueId() + ".uses." + regexCommand2, + uses); + return uses; + } + + /** + * Metoda nastavuje po�et pou�it� p��kazu o jedna v�t�� po ka�d�m pou�it� + * p��kazu hr��em. Nasteven� hodnoty prob�h� jen pro p��kazy, kter� jsou + * definov�ny v konfiguraci. + * + * @param player + * specifick� hr�� + * @param regexCommand + * p��kaz z konfigura�n�ho souboru, kter� vyhovuje origin�ln�mu + * p��kazu + * @param originalCommand + * origin�ln� p��kaz pou�it� hr��em + */ + static void setUses(Player player, String regexCommand) { + if (BoosConfigManager.getLimitsEnabled()) { + if (BoosConfigManager.getCommands(player).contains(regexCommand)) { + int regexCommand2 = regexCommand.toLowerCase().hashCode(); + int uses = getUses(player, regexCommand); + uses = uses + 1; + try { + BoosConfigManager.getConfusers().set( + "users." + player.getUniqueId() + ".uses." + + regexCommand2, uses); + } catch (IllegalArgumentException e) { + BoosCoolDown + .getLog() + .warning( + "Player " + + player.getName() + + " used empty command and caused this error!"); + } + } else { + return; + } + } + } + + /** + * Metoda odes�l� hr��i zpr�vu o limitovan�m p��kazu, hodnotu tohoto limitu + * a kolikr�t je je�t� mo�n� limitovan� p��kaz pou��t. + * + * @param send + * hr�� kter�mu bude odesl�n seznam + * @param comm + * p��kaz o kter�m si hr�� vy��dal informace + * @param lim + * hodnota limitu na p��kazu + */ + static void getLimitListMessages(Player send, String comm, int lim) { + if (lim != -1) { + int uses = getUses(send, comm); + String message = BoosConfigManager.getLimitListMessage(); + int num = lim - uses; + if (num < 0) { + num = 0; + } + message = BoosConfigManager.getLimitListMessage(); + message = message.replaceAll("&command&", comm); + message = message.replaceAll("&limit&", String.valueOf(lim)); + message = message.replaceAll("×&", String.valueOf(num)); + boosChat.sendMessageToPlayer(send, message); + } + } + + /** + * Metoda vrac� sou�asn� p�esn� datum a �as. + * + * @return sou�asn� �as a datum + */ + static Date getCurrTime() { + String currTime = ""; + Calendar cal = Calendar.getInstance(); + SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); + currTime = sdf.format(cal.getTime()); + Date time = null; + + try { + time = sdf.parse(currTime); + return time; + } catch (ParseException e) { + return null; + } + } + + /** + * Metoda vrac� datum a �as, kdy hr�� naposledy pou�il dan� p��kaz. + * + * @param player + * specifikovan� hr�� + * @param regexCommand + * p��kaz z konfigurace vyhovuj�c� origin�ln�mu p��kazu + * @return datum a �as kdy hr�� naposledy pou�il dan� p��kaz + */ + static Date getTime(Player player, String regexCommand) { + int pre2 = regexCommand.toLowerCase().hashCode(); + String confTime = ""; + confTime = BoosConfigManager.getConfusers().getString( + "users." + player.getUniqueId() + ".lastused." + pre2, null); + + if (confTime != null && !confTime.equals("")) { + SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); + Date lastDate = null; + + try { + lastDate = sdf.parse(confTime); + return lastDate; + } catch (ParseException e) { + return null; + } + } + return null; + } + + static Date getTime(String regexCommand) { + String confTime = ""; + confTime = BoosConfigManager.getConfusers().getString( + "global." + regexCommand + ".reset", null); + + if (confTime != null && !confTime.equals("")) { + SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); + Date lastDate = null; + + try { + lastDate = sdf.parse(confTime); + return lastDate; + } catch (ParseException e) { + return null; + } + } + return null; + } + + /** + * Metoda ukl�d� do datab�ze datum a �as kdy hr�� naposledy pou�il dan� + * p��kaz. + * + * @param player + * specifick� hr�� + * @param regexCommand + * p��kaz z konfigurace vyhovuj�c� origin�ln�mu p��kazu + */ + static void setTime(Player player, String regexCommand) { + int pre2 = regexCommand.toLowerCase().hashCode(); + String currTime = ""; + Calendar cal = Calendar.getInstance(); + SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); + currTime = sdf.format(cal.getTime()); + BoosConfigManager.getConfusers() + .set("users." + player.getUniqueId() + ".lastused." + pre2, + currTime); + } + + /** + * Metoda vrac� hodnotu rozd�lu v sekund�ch mezi dv�mi hodnotami datumu a + * �asu. + * + * @param startDate + * @param endDate + * @return rozd�l v sekund�ch mezi startDate a endDate + */ + static long secondsBetween(Calendar startDate, Calendar endDate, + long limitResetDelay) { + long secondsBetween = 0; + secondsBetween = ((startDate.getTimeInMillis() - endDate + .getTimeInMillis()) / 1000) + limitResetDelay; + return secondsBetween; + } + + static void clearAllLimits(int hashedCommand) { + Set players = BoosConfigManager.getAllPlayers(); + for (String player : players) { + BoosConfigManager.clearSomething2("uses", player, hashedCommand); + } + BoosConfigManager.saveConfusers(); + BoosConfigManager.loadConfusers(); + } + + static void setGlobalLimitResetDate() { + for (String command : BoosConfigManager.getLimitResetCommandsGlobal()) { + if (BoosConfigManager.getLimitResetDelayGlobal(command) == -65535) { + BoosConfigManager.getConfusers().set("global." + command, null); + } else { + setTime(command); + } + } + BoosConfigManager.saveConfusers(); + BoosConfigManager.loadConfusers(); + } + + static void setGlobalLimitResetDate(String command) { + setTime(command); + BoosConfigManager.saveConfusers(); + BoosConfigManager.loadConfusers(); + } + + static void setTime(String command) { + String currTime = ""; + Calendar cal = Calendar.getInstance(); + SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); + currTime = sdf.format(cal.getTime()); + BoosConfigManager.getConfusers().set("global." + command + ".reset", + currTime); + } +} diff --git a/src/main/java/cz/boosik/boosCooldown/BoosWarmUpManager.java b/src/main/java/cz/boosik/boosCooldown/BoosWarmUpManager.java index 5f6454a..c869d0b 100644 --- a/src/main/java/cz/boosik/boosCooldown/BoosWarmUpManager.java +++ b/src/main/java/cz/boosik/boosCooldown/BoosWarmUpManager.java @@ -1,283 +1,283 @@ -package cz.boosik.boosCooldown; - -import java.util.Iterator; -import java.util.Timer; -import java.util.concurrent.ConcurrentHashMap; - -import org.bukkit.Location; -import org.bukkit.entity.Player; -import org.bukkit.potion.PotionEffectType; - -import util.boosChat; - -/** - * T��da obsahuje ve�ker� metody pot�ebn� k ��zen� warmup �asova��. Spou�t�n�, - * ukon�ov�n� a zji��ov�n� zda je warmup �asova� ji� aktivn�. - * - * @author Jakub Kol�� - * - */ -public class BoosWarmUpManager { - - private static ConcurrentHashMap playercommands = new ConcurrentHashMap(); - private static ConcurrentHashMap playerloc = new ConcurrentHashMap(); - private static ConcurrentHashMap playerworld = new ConcurrentHashMap(); - - private static Timer scheduler; - - /** - * Metoda aplikuje na hr��e magick� efekt na dobu ur�enou parametrem - * warmUpSeconds. - * - * @param player - * specifick� hr�� - * @param regexCommand - * p��kaz z konfigura�n�ho souboru, kter� vyhovuje origin�ln�mu - * p��kazu - * @param warmUpSeconds - * doba warmup v sekund�ch, nastaven� pro regexCommand v - * konfiguraci - */ - static void applyPotionEffect(Player player, String regexCommand, - int warmUpSeconds) { - String potion = BoosConfigManager.getPotionEffect(regexCommand, player); - if (potion.equals("")) { - return; - } - int potionStrength = BoosConfigManager.getPotionEffectStrength( - regexCommand, player); - if (potionStrength == 0) { - return; - } - PotionEffectType effect = PotionEffectType.getByName(potion); - player.addPotionEffect( - effect.createEffect(warmUpSeconds * 40, potionStrength - 1), - true); - } - - /** - * Metoda stornuje ve�ker� prob�haj�c� warmup �asova�e specifick�ho hr��e. - * - * @param player - * specifick� hr�� - */ - public static void cancelWarmUps(Player player) { - Iterator iter = playercommands.keySet().iterator(); - while (iter.hasNext()) { - if (iter.next().startsWith(player.getUniqueId() + "@")) { - killTimer(player); - iter.remove(); - } - } - } - - /** - * Metoda pro specifick�ho hr��e vyma�e ulo�enou pozici a sv�t. - * - * @param player - * specifick� hr�� - */ - public static void clearLocWorld(Player player) { - BoosWarmUpManager.playerloc.remove(player); - BoosWarmUpManager.playerworld.remove(player); - } - - /** - * Metoda vrac� boolean hodnotu v z�vislosti na tom jestli specifikovan� - * hr�� m� aktivn� warmup �asova�e nebo ne. - * - * @param player - * specifick� hr�� - * @return true pokud hr�� m� aktivn� warmup �asova�e, jinak false - */ - public static boolean hasWarmUps(Player player) { - for (String key : playercommands.keySet()) { - if (key.startsWith(player.getUniqueId() + "@")) { - return true; - } - } - return false; - } - - /** - * Metoda zji��uje, jestli je dan� warmup �asova� ozna�en� jako ji� prob�hl� - * nebo ne. - * - * @param player - * specifick� hr�� - * @param regexCommand - * p��kaz z konfigura�n�ho souboru, kter� vyhovuje origin�ln�mu - * p��kazu - * @return true pokud je warmup �asova� ozna�en jako ji� prob�hl�, jinak - * false - */ - static boolean checkWarmUpOK(Player player, String regexCommand) { - int pre2 = regexCommand.toLowerCase().hashCode(); - int ok = 0; - ok = BoosConfigManager.getConfusers().getInt( - "users." + player.getUniqueId() + ".warmup." + pre2, ok); - if (ok == 1) { - return true; - } - return false; - } - - /** - * Metoda vrac� boolean hodnotu na z�klad� toho jestli je pro specifikovan� - * p��kaz specifikovan�ho hr��e aktivn� warmup �asova�. - * - * @param player - * specifick� hr�� - * @param regexCommand - * p��kaz z konfigura�n�ho souboru, kter� vyhovuje origin�ln�mu - * p��kazu - * @return true pokud je warmup �asova� aktivn�, jinak false - */ - static boolean isWarmUpProcess(Player player, String regexCommand) { - regexCommand = regexCommand.toLowerCase(); - if (playercommands.containsKey(player.getUniqueId() + "@" - + regexCommand)) { - return true; - } - return false; - } - - /** - * Metoda odstran� v�echny �asova�e specifikovan�ho hr��e - * - * @param player - * specifick� hr�� - */ - static void killTimer(Player player) { - for (String key : playercommands.keySet()) { - if (key.startsWith(player.getUniqueId() + "@")) { - playercommands.get(key).cancel(); - } - } - } - - /** - * Metoda odstran� �asova�e na specifikovan�m p��kazu specifikovan�ho hr��e - * - * @param player - * specifick� hr�� - * @param regexCommand - * p��kaz z konfigura�n�ho souboru, kter� vyhovuje origin�ln�mu - * p��kazu - */ - static void removeWarmUp(Player player, String regexCommand) { - int pre2 = regexCommand.toLowerCase().hashCode(); - BoosConfigManager.getConfusers().set( - "users." + player.getUniqueId() + ".warmup." + pre2, null); - } - - /** - * Metoda odstran� ukon�en� �asova�e na specifikovan�m p��kazu - * specifikovan�ho hr��e - * - * @param player - * specifick� hr�� - * @param regexCommand - * p��kaz z konfigura�n�ho souboru, kter� vyhovuje origin�ln�mu - * p��kazu - */ - static void removeWarmUpOK(Player player, String regexCommand) { - int pre2 = regexCommand.toLowerCase().hashCode(); - BoosConfigManager.getConfusers().set( - "users." + player.getUniqueId() + ".warmup." + pre2, null); - } - - /** - * Metoda odstra�uje dan� �et�zec z Hashmapy - * - * @param tag - * �et�zec, kter� se m� odstranit z Hasmapy - */ - static void removeWarmUpProcess(String tag) { - BoosWarmUpManager.playercommands.remove(tag); - } - - /** - * Metoda ozna�uje warmup �asova� specifikovan�ho p��kazu specifikovan�ho - * hr��e jako ji� ukon�en�. - * - * @param player - * specifick� hr�� - * @param regexCommand - * p��kaz z konfigura�n�ho souboru, kter� vyhovuje origin�ln�mu - * p��kazu - */ - static void setWarmUpOK(Player player, String regexCommand) { - int pre2 = regexCommand.toLowerCase().hashCode(); - BoosConfigManager.getConfusers().set( - "users." + player.getUniqueId() + ".warmup." + pre2, 1); - } - - /** - * Metoda spou�t� warmup �asova� na z�klad� parametr� pomoc� Timer(). Pokud - * je ji� warmup aktivn�, ode�le hr��i zpr�vu kter� ho o tom informuje. - * - * @param bCoolDown - * instance t��dy BoosCooldown - * @param player - * specifick� hr�� - * @param regexCommand - * p��kaz z konfigura�n�ho souboru, kter� vyhovuje origin�ln�mu - * p��kazu - * @param originalCommand - * origin�ln� p��kaz pou�it� hr��em - * @param warmUpSeconds - * warmup doba nastaven� pro p��kaz v sekund�ch - */ - static void startWarmUp(BoosCoolDown bCoolDown, Player player, - String regexCommand, String originalCommand, int warmUpSeconds) { - regexCommand = regexCommand.toLowerCase(); - long warmUpMinutes = Math.round(warmUpSeconds / 60); - long warmUpHours = Math.round(warmUpMinutes / 60); - if (!isWarmUpProcess(player, regexCommand)) { - BoosWarmUpManager.removeWarmUpOK(player, regexCommand); - String msg = BoosConfigManager.getWarmUpMessage(); - msg = msg.replaceAll("&command&", originalCommand); - if (warmUpSeconds >= 60 && 3600 >= warmUpSeconds) { - msg = msg.replaceAll("&seconds&", Long.toString(warmUpMinutes)); - msg = msg.replaceAll("&unit&", - BoosConfigManager.getUnitMinutesMessage()); - } else if (warmUpMinutes >= 60) { - msg = msg.replaceAll("&seconds&", Long.toString(warmUpHours)); - msg = msg.replaceAll("&unit&", - BoosConfigManager.getUnitHoursMessage()); - } else { - msg = msg.replaceAll("&seconds&", Long.toString(warmUpSeconds)); - msg = msg.replaceAll("&unit&", - BoosConfigManager.getUnitSecondsMessage()); - } - boosChat.sendMessageToPlayer(player, msg); - - scheduler = new Timer(); - BoosWarmUpTimer scheduleMe = new BoosWarmUpTimer(bCoolDown, - scheduler, player, regexCommand, originalCommand); - playercommands.put(player.getUniqueId() + "@" + regexCommand, - scheduleMe); - scheduler.schedule(scheduleMe, warmUpSeconds * 1000); - applyPotionEffect(player, regexCommand, warmUpSeconds); - } else { - String msg = BoosConfigManager.getWarmUpAlreadyStartedMessage(); - msg = msg.replaceAll("&command&", originalCommand); - boosChat.sendMessageToPlayer(player, msg); - } - } - - /** - * @return - */ - public static ConcurrentHashMap getPlayerworld() { - return playerworld; - } - - /** - * @return - */ - public static ConcurrentHashMap getPlayerloc() { - return playerloc; - } -} +package cz.boosik.boosCooldown; + +import java.util.Iterator; +import java.util.Timer; +import java.util.concurrent.ConcurrentHashMap; + +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffectType; + +import util.boosChat; + +/** + * T��da obsahuje ve�ker� metody pot�ebn� k ��zen� warmup �asova��. Spou�t�n�, + * ukon�ov�n� a zji��ov�n� zda je warmup �asova� ji� aktivn�. + * + * @author Jakub Kol�� + * + */ +public class BoosWarmUpManager { + + private static ConcurrentHashMap playercommands = new ConcurrentHashMap(); + private static ConcurrentHashMap playerloc = new ConcurrentHashMap(); + private static ConcurrentHashMap playerworld = new ConcurrentHashMap(); + + private static Timer scheduler; + + /** + * Metoda aplikuje na hr��e magick� efekt na dobu ur�enou parametrem + * warmUpSeconds. + * + * @param player + * specifick� hr�� + * @param regexCommand + * p��kaz z konfigura�n�ho souboru, kter� vyhovuje origin�ln�mu + * p��kazu + * @param warmUpSeconds + * doba warmup v sekund�ch, nastaven� pro regexCommand v + * konfiguraci + */ + static void applyPotionEffect(Player player, String regexCommand, + int warmUpSeconds) { + String potion = BoosConfigManager.getPotionEffect(regexCommand, player); + if (potion.equals("")) { + return; + } + int potionStrength = BoosConfigManager.getPotionEffectStrength( + regexCommand, player); + if (potionStrength == 0) { + return; + } + PotionEffectType effect = PotionEffectType.getByName(potion); + player.addPotionEffect( + effect.createEffect(warmUpSeconds * 40, potionStrength - 1), + true); + } + + /** + * Metoda stornuje ve�ker� prob�haj�c� warmup �asova�e specifick�ho hr��e. + * + * @param player + * specifick� hr�� + */ + public static void cancelWarmUps(Player player) { + Iterator iter = playercommands.keySet().iterator(); + while (iter.hasNext()) { + if (iter.next().startsWith(player.getUniqueId() + "@")) { + killTimer(player); + iter.remove(); + } + } + } + + /** + * Metoda pro specifick�ho hr��e vyma�e ulo�enou pozici a sv�t. + * + * @param player + * specifick� hr�� + */ + public static void clearLocWorld(Player player) { + BoosWarmUpManager.playerloc.remove(player); + BoosWarmUpManager.playerworld.remove(player); + } + + /** + * Metoda vrac� boolean hodnotu v z�vislosti na tom jestli specifikovan� + * hr�� m� aktivn� warmup �asova�e nebo ne. + * + * @param player + * specifick� hr�� + * @return true pokud hr�� m� aktivn� warmup �asova�e, jinak false + */ + public static boolean hasWarmUps(Player player) { + for (String key : playercommands.keySet()) { + if (key.startsWith(player.getUniqueId() + "@")) { + return true; + } + } + return false; + } + + /** + * Metoda zji��uje, jestli je dan� warmup �asova� ozna�en� jako ji� prob�hl� + * nebo ne. + * + * @param player + * specifick� hr�� + * @param regexCommand + * p��kaz z konfigura�n�ho souboru, kter� vyhovuje origin�ln�mu + * p��kazu + * @return true pokud je warmup �asova� ozna�en jako ji� prob�hl�, jinak + * false + */ + static boolean checkWarmUpOK(Player player, String regexCommand) { + int pre2 = regexCommand.toLowerCase().hashCode(); + int ok = 0; + ok = BoosConfigManager.getConfusers().getInt( + "users." + player.getUniqueId() + ".warmup." + pre2, ok); + if (ok == 1) { + return true; + } + return false; + } + + /** + * Metoda vrac� boolean hodnotu na z�klad� toho jestli je pro specifikovan� + * p��kaz specifikovan�ho hr��e aktivn� warmup �asova�. + * + * @param player + * specifick� hr�� + * @param regexCommand + * p��kaz z konfigura�n�ho souboru, kter� vyhovuje origin�ln�mu + * p��kazu + * @return true pokud je warmup �asova� aktivn�, jinak false + */ + static boolean isWarmUpProcess(Player player, String regexCommand) { + regexCommand = regexCommand.toLowerCase(); + if (playercommands.containsKey(player.getUniqueId() + "@" + + regexCommand)) { + return true; + } + return false; + } + + /** + * Metoda odstran� v�echny �asova�e specifikovan�ho hr��e + * + * @param player + * specifick� hr�� + */ + static void killTimer(Player player) { + for (String key : playercommands.keySet()) { + if (key.startsWith(player.getUniqueId() + "@")) { + playercommands.get(key).cancel(); + } + } + } + + /** + * Metoda odstran� �asova�e na specifikovan�m p��kazu specifikovan�ho hr��e + * + * @param player + * specifick� hr�� + * @param regexCommand + * p��kaz z konfigura�n�ho souboru, kter� vyhovuje origin�ln�mu + * p��kazu + */ + static void removeWarmUp(Player player, String regexCommand) { + int pre2 = regexCommand.toLowerCase().hashCode(); + BoosConfigManager.getConfusers().set( + "users." + player.getUniqueId() + ".warmup." + pre2, null); + } + + /** + * Metoda odstran� ukon�en� �asova�e na specifikovan�m p��kazu + * specifikovan�ho hr��e + * + * @param player + * specifick� hr�� + * @param regexCommand + * p��kaz z konfigura�n�ho souboru, kter� vyhovuje origin�ln�mu + * p��kazu + */ + static void removeWarmUpOK(Player player, String regexCommand) { + int pre2 = regexCommand.toLowerCase().hashCode(); + BoosConfigManager.getConfusers().set( + "users." + player.getUniqueId() + ".warmup." + pre2, null); + } + + /** + * Metoda odstra�uje dan� �et�zec z Hashmapy + * + * @param tag + * �et�zec, kter� se m� odstranit z Hasmapy + */ + static void removeWarmUpProcess(String tag) { + BoosWarmUpManager.playercommands.remove(tag); + } + + /** + * Metoda ozna�uje warmup �asova� specifikovan�ho p��kazu specifikovan�ho + * hr��e jako ji� ukon�en�. + * + * @param player + * specifick� hr�� + * @param regexCommand + * p��kaz z konfigura�n�ho souboru, kter� vyhovuje origin�ln�mu + * p��kazu + */ + static void setWarmUpOK(Player player, String regexCommand) { + int pre2 = regexCommand.toLowerCase().hashCode(); + BoosConfigManager.getConfusers().set( + "users." + player.getUniqueId() + ".warmup." + pre2, 1); + } + + /** + * Metoda spou�t� warmup �asova� na z�klad� parametr� pomoc� Timer(). Pokud + * je ji� warmup aktivn�, ode�le hr��i zpr�vu kter� ho o tom informuje. + * + * @param bCoolDown + * instance t��dy BoosCooldown + * @param player + * specifick� hr�� + * @param regexCommand + * p��kaz z konfigura�n�ho souboru, kter� vyhovuje origin�ln�mu + * p��kazu + * @param originalCommand + * origin�ln� p��kaz pou�it� hr��em + * @param warmUpSeconds + * warmup doba nastaven� pro p��kaz v sekund�ch + */ + static void startWarmUp(BoosCoolDown bCoolDown, Player player, + String regexCommand, String originalCommand, int warmUpSeconds) { + regexCommand = regexCommand.toLowerCase(); + long warmUpMinutes = (long) Math.ceil(warmUpSeconds / 60.0); + long warmUpHours = (long) Math.ceil(warmUpMinutes / 60.0); + if (!isWarmUpProcess(player, regexCommand)) { + BoosWarmUpManager.removeWarmUpOK(player, regexCommand); + String msg = BoosConfigManager.getWarmUpMessage(); + msg = msg.replaceAll("&command&", originalCommand); + if (warmUpSeconds >= 60 && 3600 >= warmUpSeconds) { + msg = msg.replaceAll("&seconds&", Long.toString(warmUpMinutes)); + msg = msg.replaceAll("&unit&", + BoosConfigManager.getUnitMinutesMessage()); + } else if (warmUpMinutes >= 60) { + msg = msg.replaceAll("&seconds&", Long.toString(warmUpHours)); + msg = msg.replaceAll("&unit&", + BoosConfigManager.getUnitHoursMessage()); + } else { + msg = msg.replaceAll("&seconds&", Long.toString(warmUpSeconds)); + msg = msg.replaceAll("&unit&", + BoosConfigManager.getUnitSecondsMessage()); + } + boosChat.sendMessageToPlayer(player, msg); + + scheduler = new Timer(); + BoosWarmUpTimer scheduleMe = new BoosWarmUpTimer(bCoolDown, + scheduler, player, regexCommand, originalCommand); + playercommands.put(player.getUniqueId() + "@" + regexCommand, + scheduleMe); + scheduler.schedule(scheduleMe, warmUpSeconds * 1000); + applyPotionEffect(player, regexCommand, warmUpSeconds); + } else { + String msg = BoosConfigManager.getWarmUpAlreadyStartedMessage(); + msg = msg.replaceAll("&command&", originalCommand); + boosChat.sendMessageToPlayer(player, msg); + } + } + + /** + * @return + */ + public static ConcurrentHashMap getPlayerworld() { + return playerworld; + } + + /** + * @return + */ + public static ConcurrentHashMap getPlayerloc() { + return playerloc; + } +} diff --git a/src/main/java/org/mcstats/MetricsLite.java b/src/main/java/org/mcstats/MetricsLite.java index a55e838..097f468 100644 --- a/src/main/java/org/mcstats/MetricsLite.java +++ b/src/main/java/org/mcstats/MetricsLite.java @@ -1,556 +1,559 @@ -/* - * Copyright 2011-2013 Tyler Blair. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, are - * permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * The views and conclusions contained in the software and documentation are those of the - * authors and contributors and should not be interpreted as representing official policies, - * either expressed or implied, of anybody else. - */ - -package org.mcstats; - -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 cz.boosik.boosCooldown.BoosCoolDown; - -import java.io.BufferedReader; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.UnsupportedEncodingException; -import java.net.Proxy; -import java.net.URL; -import java.net.URLConnection; -import java.net.URLEncoder; -import java.util.UUID; -import java.util.logging.Level; -import java.util.zip.GZIPOutputStream; - -public class MetricsLite { - - /** - * 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 final static int PING_INTERVAL = 15; - - /** - * The plugin this metrics submits for - */ - private final Plugin plugin; - - /** - * 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(); - - /** - * Id of the scheduled task - */ - private volatile BukkitTask task = null; - - public MetricsLite(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); - } - - /** - * 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; - } - } - - // 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(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 = 0; - try { - playersOnline = Bukkit.getServer().getOnlinePlayers().size(); - } catch (Exception e) { - BoosCoolDown.getLog().warning("[boosCooldowns] This error was caused because you are using old CraftBukkit version. Please update to 1.7.10 (1.7.9-R0.3)."); - } - - // 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"); - } - - // 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); - } - } - - /** - * 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"); - } - +/* + * Copyright 2011-2013 Tyler Blair. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and contributors and should not be interpreted as representing official policies, + * either expressed or implied, of anybody else. + */ + +package org.mcstats; + +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 cz.boosik.boosCooldown.BoosCoolDown; + +import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.UnsupportedEncodingException; +import java.net.Proxy; +import java.net.URL; +import java.net.URLConnection; +import java.net.URLEncoder; +import java.util.UUID; +import java.util.logging.Level; +import java.util.zip.GZIPOutputStream; + +public class MetricsLite { + + /** + * 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 final static int PING_INTERVAL = 15; + + /** + * The plugin this metrics submits for + */ + private final Plugin plugin; + + /** + * 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(); + + /** + * Id of the scheduled task + */ + private volatile BukkitTask task = null; + + public MetricsLite(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); + } + + /** + * 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; + } + } + + // 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(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 = 0; + try { + playersOnline = Bukkit.getServer().getOnlinePlayers().size(); + } catch (Exception e) { + BoosCoolDown + .getLog() + .warning( + "[boosCooldowns] This error was caused because you are using old CraftBukkit version. Please update to 1.7.10 (1.7.9-R0.3)."); + } + + // 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"); + } + + // 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); + } + } + + /** + * 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"); + } + } \ No newline at end of file diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index c14fa3c..3cf0e93 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -1,110 +1,110 @@ -name: boosCooldowns -main: cz.boosik.boosCooldown.BoosCoolDown -version: 3.8.5 -authors: [LordBoos (ingame name boosik)] -softdepend: [Vault] -description: > - Shortcuts -commands: - booscooldowns: - description: Reload command. - usage: Use /booscooldowns reload, clearcooldowns , clearwarmups or clearuses - aliases: bcd -permissions: - booscooldowns.exception: - description: Player wont be affected by plugin at all (no warmups, no cooldowns, no prices, no limits, no aliases). - default: false - booscooldowns.norestriction: - description: Player wont be affected by restrictions but will be affected by aliases(no warmups, no cooldowns, no prices, no limits). - default: false - children: - booscooldowns.noprice: true - booscooldowns.nocooldown: true - booscooldowns.nowarmup: true - booscooldowns.nolimit: true - booscooldowns.noitemcost: true - booscooldowns.noxpcost: true - booscooldowns.nocancel.move: - description: Players warmups will not be canceled by moving, even if it's turned on. - default: false - booscooldowns.nocancel.damage: - description: Players warmups will not be canceled by damage, even if it's turned on. - default: false - booscooldowns.nocancel.sneak: - description: Players warmups will not be canceled by sneaking, even if it's turned on. - default: false - booscooldowns.nocancel.sprint: - description: Players warmups will not be canceled by sprinting, even if it's turned on. - default: false - booscooldowns.nocancel.gamemodechange: - description: Players warmups will not be canceled by changing gamemode, even if it's turned on. - default: false - booscooldowns.dontblock.interact: - description: Players interaction will not be blocked during warmup, even if it's turned on. - default: false - booscooldowns.noprice: - description: Players commands will always be free of charge. - default: false - booscooldowns.noprice./command: - description: Command "/command" will not be affected by price for users with this permission. - default: false - booscooldowns.noitemcost: - description: Players commands will always be free of charge (items). - default: false - booscooldowns.noitemcost./command: - description: Command "/command" will not be affected by item cost for users with this permission. - default: false - booscooldowns.noxpcost: - description: Players commands will always be free of charge (XP). - default: false - booscooldowns.noxpcost./command: - description: Command "/command" will not be affected by xp cost for users with this permission. - default: false - booscooldowns.nocooldown: - description: Player wont be affected by cooldowns. - default: false - booscooldowns.nocooldown./command: - description: Command "/command" will not be affected by cooldown for users with this permission. - default: false - booscooldowns.nowarmup: - description: Player wont be affected by warmups. - default: false - booscooldowns.nowarmup./command: - description: Command "/command" will not be affected by warmup for users with this permission. - default: false - booscooldowns.nolimit: - description: Player wont be affected by limiting. - default: false - booscooldowns.start.cooldowns.death.exception: - description: Player's cooldowns wont be started on death. - default: false - booscooldowns.nolimit./command: - description: Command "/command" will not be affected by limits for users with this permission. - default: false - booscooldowns.reload: - description: Player can use "/booscooldowns reload" to reload config file. - default: op - booscooldowns.clear.uses.death: - description: Players uses (limit-uses=how many times playr can still use command) are cleared on death (must be enabled in config file too!). - default: false - booscooldowns.clear.cooldowns.death: - description: Players cooldowns are cleared on death (must be enabled in config file too!). - default: false - booscooldowns.list.limits: - description: Player can use "/booscooldowns limits" to see limits and how many times he can still use commands. - default: true - booscooldowns.set: - description: Users with this can use "/booscooldowns set" command. - default: op - booscooldowns.signs.player.use: - description: Player can use boosCooldowns signs (marked as player on second line). - default: false - booscooldowns.signs.server.use: - description: Player can use boosCooldowns signs (marked as server on second line). - default: false - booscooldowns.signs.player.place: - description: Player can place/create boosCooldowns signs (marked as player on second line). - default: false - booscooldowns.signs.server.place: - description: Player can place/create boosCooldowns signs (marked as server on second line). !!WARNING!! With this permission, player can create sign with commands that are run as if used from console! +name: boosCooldowns +main: cz.boosik.boosCooldown.BoosCoolDown +version: 3.9.5 +authors: [LordBoos (ingame name boosik)] +softdepend: [Vault] +description: > + Shortcuts +commands: + booscooldowns: + description: Reload command. + usage: §6[boosCooldowns] §eInvalid command or access denied! + aliases: bcd +permissions: + booscooldowns.exception: + description: Player wont be affected by plugin at all (no warmups, no cooldowns, no prices, no limits, no aliases). + default: false + booscooldowns.norestriction: + description: Player wont be affected by restrictions but will be affected by aliases(no warmups, no cooldowns, no prices, no limits). + default: false + children: + booscooldowns.noprice: true + booscooldowns.nocooldown: true + booscooldowns.nowarmup: true + booscooldowns.nolimit: true + booscooldowns.noitemcost: true + booscooldowns.noxpcost: true + booscooldowns.nocancel.move: + description: Players warmups will not be canceled by moving, even if it's turned on. + default: false + booscooldowns.nocancel.damage: + description: Players warmups will not be canceled by damage, even if it's turned on. + default: false + booscooldowns.nocancel.sneak: + description: Players warmups will not be canceled by sneaking, even if it's turned on. + default: false + booscooldowns.nocancel.sprint: + description: Players warmups will not be canceled by sprinting, even if it's turned on. + default: false + booscooldowns.nocancel.gamemodechange: + description: Players warmups will not be canceled by changing gamemode, even if it's turned on. + default: false + booscooldowns.dontblock.interact: + description: Players interaction will not be blocked during warmup, even if it's turned on. + default: false + booscooldowns.noprice: + description: Players commands will always be free of charge. + default: false + booscooldowns.noprice./command: + description: Command "/command" will not be affected by price for users with this permission. + default: false + booscooldowns.noitemcost: + description: Players commands will always be free of charge (items). + default: false + booscooldowns.noitemcost./command: + description: Command "/command" will not be affected by item cost for users with this permission. + default: false + booscooldowns.noxpcost: + description: Players commands will always be free of charge (XP). + default: false + booscooldowns.noxpcost./command: + description: Command "/command" will not be affected by xp cost for users with this permission. + default: false + booscooldowns.nocooldown: + description: Player wont be affected by cooldowns. + default: false + booscooldowns.nocooldown./command: + description: Command "/command" will not be affected by cooldown for users with this permission. + default: false + booscooldowns.nowarmup: + description: Player wont be affected by warmups. + default: false + booscooldowns.nowarmup./command: + description: Command "/command" will not be affected by warmup for users with this permission. + default: false + booscooldowns.nolimit: + description: Player wont be affected by limiting. + default: false + booscooldowns.start.cooldowns.death.exception: + description: Player's cooldowns wont be started on death. + default: false + booscooldowns.nolimit./command: + description: Command "/command" will not be affected by limits for users with this permission. + default: false + booscooldowns.reload: + description: Player can use "/booscooldowns reload" to reload config file. + default: op + booscooldowns.clear.uses.death: + description: Players uses (limit-uses=how many times playr can still use command) are cleared on death (must be enabled in config file too!). + default: false + booscooldowns.clear.cooldowns.death: + description: Players cooldowns are cleared on death (must be enabled in config file too!). + default: false + booscooldowns.list.limits: + description: Player can use "/booscooldowns limits" to see limits and how many times he can still use commands. + default: true + booscooldowns.set: + description: Users with this can use "/booscooldowns set" command. + default: op + booscooldowns.signs.player.use: + description: Player can use boosCooldowns signs (marked as player on second line). + default: false + booscooldowns.signs.server.use: + description: Player can use boosCooldowns signs (marked as server on second line). + default: false + booscooldowns.signs.player.place: + description: Player can place/create boosCooldowns signs (marked as player on second line). + default: false + booscooldowns.signs.server.place: + description: Player can place/create boosCooldowns signs (marked as server on second line). !!WARNING!! With this permission, player can create sign with commands that are run as if used from console! default: false \ No newline at end of file