diff --git a/config.yml b/config.yml new file mode 100644 index 000000000..6d30c5b57 --- /dev/null +++ b/config.yml @@ -0,0 +1,539 @@ +############################################################################ +# Config for BSkyBlock V${version} +# +# Created and maintained by Tastybento with the help of Poslovitch +############################################################################ + +### General Settings ### +general: + # BSkyBlock uses bStats.org to get global data about the plugin to help improving it. + # bStats has nearly no effect on your server's performance and the sent data is completely + # anonymous so please consider twice if you really want to disable it. + metrics: true + + # Check for updates - this will tell Ops and the console if there is a new + # version available. It contacts dev.bukkit.org to request the latest version + # info. It does not download the latest version or change any files + check-updates: true + + # Default language for new players. + # This is the filename in the locale folder without .yml. + # If this does not exist, the default en-US will be used. + default-language: en-US + + # Use economy or not. If true, an economy plugin is required. If false, no money is used or give. + # If there is no economy plugin present anyway, money will be automatically disabled. + use-economy: true + + # Starting money - this is how much money new players will have as their + # balance at the start of an island. + starting-money: 10.0 + + # Use the control panel as the default display for /island + # /island will always create an island if one does not exist + # If the control panel is not used, then /island will teleport the player home + # Players can change this setting using /island cp on or /island cp off + # Changing this setting will only apply to new players. + use-control-panel: true + + ### Purge-related Settings ### + purge: + # Only islands below this level will be removed if they are abandoned and admins issue the purge command + max-island-level: 50 + + # Remove user data when its island gets purged. + # Helps a lot to avoid huge backups and can save some performance on startup, + # but the player settings and data will be reset. + remove-user-data: false + + ### Database-related Settings ### + database: + # FLATFILE, MYSQL, SQLITE + type: FLATFILE + + mysql: 0 #TODO + sqlite: 0 #TODO + + # How often the data will be saved to file in mins. Default is 5 minutes. + # This helps prevent issues if the server crashes. + # Data is also saved at important points in the game. + backup-period: 5 + + # Recover super flat - if the generator does not run for some reason, you can get + # super flat chunks (grass). To remove automatically, select this option. Turn off + # if there are no more because it may cause lag. + # This will regenerate any chunks with bedrock at y=0 when they are loaded + recover-super-flat: false + + # Mute death messages + mute-death-messages: false + + # Allow FTB Autonomous Activator to work (will allow a pseudo player [CoFH] to place and break blocks and hang items) + FTB-auto-activator: false + + # Allow obsidian to be scooped up with an empty bucket back into lava + # This only works if there is a single block of obsidian (no obsidian within 10 blocks) + # Recommendation is to keep this true so that newbies don't bother you or reset their + # island unnecessarily. + allow-obsidian-scooping: true + + allow-teleport: + # Allow /island teleport when falling. If set to false, all teleporting is + # disabled until death from the void or until you hit something. + # See commands that this will block too + # Using "*" (with quotes) will block ALL commands when falling + falling: true + falling-blocked-commands: + - home + + # The same as above, but this time it is when the player is swimming in acid + acid: true + acid-blocked-commands: + - home + +### World Settings ### +world: + # Name of the world - if it does not exist then it will be generated. + # It acts like a prefix for nether and end (e.g. BSkyBlock, BSkyBlock_nether, BSkyBlock_end) + world-name: BSkyBlock + + # Distance between islands in blocks - NEVER change this mid-game. + # It is the same for every dimension : Overworld, Nether and End. + # Values for a new world: + # 400 - puts players distance enough that they usually cannot see each other + # 200 - allows some expansion of the protected zone (recommended) + # 110 - for compatibility with established worlds. Cozy. + # 50 - minimum - not recommended + # IF YOU ARE UPGRADING YOU MUST USE YOUR OLD VALUE EXACTLY (E.G.: 110), OR RESET YOUR WORLD + # Value must be an even number (must end with 0, 2, 4, 6, 8) + distance: 200 + + # Default protection range (even number). Min = 0, Recommended = 100 + # Larger values will take longer to calculate the island level + # Admins can change protection sizes for players individually using /asadmin setrange + # or set this permission: askyblock.island.range. + # For optimal performance, keep protection range at least 16 blocks less than distance. + protection-range: 100 + + # Start islands at these coordinates. This is where new islands will start in the + # world. These must be a factor of your island distance, but the plugin will auto + # calculate the closest location on the grid. Islands develop around this location + # both positively and negatively in a square grid. + # If none of this makes sense, leave it at 0,0. + start-x: 0 + start-z: 0 + + # Island height - Lowest is 5. + # It is the y coordinate of the bedrock block in the schematic + island-height: 120 + + # Sea height (don't changes this mid-game unless you delete the world) + # Minimum is 0, which means you are playing Skyblock! + # If sea height is less than about 10, then players will drop right through it + # if it exists. Makes for an interesting variation on skyblock. + sea-height: 0 + + # Maximum number of islands in the world. Set to 0 for unlimited. + # If the number of islands is greater than this number, no new island will be created. + max-islands: 0 + + ### Nether-related Settings ### + nether: + # Generate Nether - if this is false, the nether world will not be made and access to + # the nether will not occur. Other plugins may still enable portal usage. + # Note: Some challenges will not be possible if there is no nether. + # Note that with a standard nether all players arrive at the same portal and entering a + # portal will return them back to their islands. + generate: true + + # Islands in Nether. Change to false for standard vanilla nether. + islands: true + + # Nether trees are made if a player grows a tree in the nether (gravel and glowstone) + # Applies to both vanilla and islands Nether + trees: true + + # Make the nether roof, if false, there is nothing up there + # Change to false if lag is a problem from the generation + # Only applies to islands Nether + roof: true + + # Nether spawn protection radius - this is the distance around the nether spawn + # that will be protected from player interaction (breaking blocks, pouring lava etc.) + # Minimum is 0 (not recommended), maximum is 100. Default is 25. + # Only applies to vanilla nether + spawn-radius: 25 + + ### Entities-related Settings ### + entities: + # Sets the limit for number of entities that can spawn in a chunk in this world. + # Note: this does not limit the number of them, just how many spawn naturally. + # Note: If set to a negative number the world will use the server-wide spawn limit instead. + spawn-per-chunk: + # Limit monsters spawn + monsters: 100 + # Limits animals spawn + animals: 15 + # Limits water animals (Squid) spawn + water-animals: 15 + + # General entity limiting + # Use this section to limit how many entities can be added to an island. + # 0 means the item will be blocked from placement completely. + # Uncomment to set the limit. The numbers are just suggested values. + # The limit is per-world, so a hopper limit of 30 means up to 30 in the overworld and + # up to 30 in the nether. + limits: + # Mobs, animals and other living entities + #BAT: 10 + #BLAZE: 10 + #BOAT: 10 + #CAVE_SPIDER: 10 + #CHICKEN: 10 + #COW: 10 + #CREEPER: 10 + #DONKEY: 10 + #ENDERMAN: 10 + #HORSE: 10 + #HUSK: 10 + #IRON_GOLEM: 10 + #LLAMA: 10 + #MAGMA_CUBE: 10 + #MULE: 10 + #MUSHROOM_COW: 10 + #OCELOT: 10 + #PIG: 10 + #PIG_ZOMBIE: 10 + #POLAR_BEAR: 10 + #RABBIT: 10 + #SHEEP: 10 + #SKELETON: 10 + #SKELETON_HORSE: 10 + #SLIME: 10 + #SNOWMAN: 10 + #SPIDER: 10 + #SQUID: 10 + #STRAY: 10 + #WITCH: 10 + #WITHER: 10 + #WITHER_SKELETON: 10 + #WOLF: 10 + #ZOMBIE: 10 + #ZOMBIE_HORSE: 10 + #ZOMBIE_VILLAGER: 10 + # These are the ONLY blocks that can be limited (because they are entities). + #BANNER: 20 + #ITEM_FRAME: 30 + #FURNACE: 10 + #CHEST: 50 + #TRAPPED_CHEST: 50 + #ENDER_CHEST: 1 + #JUKEBOX: 5 + #DISPENSER: 5 + #DROPPER: 5 + #SIGN: 10 + #MOB_SPAWNER: 10 + #NOTE_BLOCK: 5 + #ENCHANTMENT_TABLE: 5 + #BEACON: 12 + #SKULL: 50 + #DAYLIGHT_DETECTOR: 10 + HOPPER: 30 + #REDSTONE_COMPARATOR: 30 + #FLOWER_POT: 20 + #PAINTING: 5 + #ARMOR_STAND: 5 + + # Disable redstone operation on islands unless a team member is online. + # This may reduce lag but it can cause problems with visitors needing to use a redstone system. + # Default is false, because it is an experimental feature that can break a lot of redstone systems. + disable-offline-redstone: false + +### Island Settings ### +island: + # Default max team size + # Use this permission to set for specific user groups: askyblock.team.maxsize. + # Permission size cannot be less than the default below. + max-team-size: 4 + + # Default maximum number of homes a player can have. Min = 1 + # Accessed via sethome or go + # Use this permission to set for specific user groups: askyblock.island.maxhomes. + max-homes: 1 + + # Island naming + # Only players with the TODO can name their island + # It is displayed in the top ten and enter and exit announcements + # It replaces the owner's name. Players can use & for color coding if they have the TODO permission + # These set the minimum and maximum size of a name. + name: + min-length: 0 + max-length: 20 + + # How long a player must wait until they can rejoin a team island after being + # kicked in minutes. This slows the effectiveness of players repeating challenges + # by repetitively being invited to a team island. + invite-wait: 60 + + ### Join/leave/reset island related settings ### + reset: + # How many resets a player is allowed (override with /asadmin clearreset ) + # Value of -1 means unlimited, 0 means hardcore - no resets. + # Example, 2 resets means they get 2 resets or 3 islands lifetime + reset-limit: -1 + + #How long a player must wait before they can reset their island again in second + reset-wait: 300 + + # Kicked or leaving players lose resets + # Players who leave a team will lose an island reset chance + # If a player has zero resets left and leaves a team, they cannot make a new + # island by themselves and can only join a team. + # Leave this true to avoid players exploiting free islands + leavers-lose-resets: true + + # Allow kicked players to keep their inventory. + # If false, kicked player's inventory will be thrown at the island leader if the + # kicked player is online and in the island world. + kicked-keep-inventory: false + + # What the plugin should reset when the player joins or creates an island + on-join: + # Reset Money - if this is true, will reset the player's money to the starting money + # Recommendation is that this is set to true, but if you run multi-worlds + # make sure your economy handles multi-worlds too. + money: false + + # Reset inventory - if true, the player's inventory will be cleared. + # Note: if you have MultiInv running or a similar inventory control plugin, that + # plugin may still reset the inventory when the world changes. + inventory: false + + # Reset Ender Chest - if true, the player's Ender Chest will be cleared. + ender-chest: false + + # What the plugin should reset when the player leaves or is kicked from an island + on-leave: + # Reset Money - if this is true, will reset the player's money to the starting money + # Recommendation is that this is set to true, but if you run multi-worlds + # make sure your economy handles multi-worlds too. + money: false + + # Reset inventory - if true, the player's inventory will be cleared. + # Note: if you have MultiInv running or a similar inventory control plugin, that + # plugin may still reset the inventory when the world changes. + inventory: false + + # Reset Ender Chest - if true, the player's Ender Chest will be cleared. + ender-chest: false + + # Removing mobs - this kills all monsters in the vicinity. Benefit is that it helps + # players return to their island if the island has been overrun by monsters. + # Con is that it kills any mob grinders. + remove-mobs: + # Remove mobs on island when logging in. + on-login: false + + # Remove mobs when /island. + on-island: false + + # Mob white list - these mobs will NOT be removed when logging in or doing /island + whitelist: + - WITHER + - ENDERMAN + - PIG_ZOMBIE + #- ZOMBIE_VILLAGER (1.10+) + + # Make island if player teleports to the island world and does not have one + make-island-if-none: false + + # Immediately teleport player to their island (home 1 if it exists) when entering the world + immediate-teleport-on-island: false + + # Have player's respawn on their island if they die + respawn-on-island: false + + # Only allow the island leader to coop players. + # Island members wont be able to coop other players. + only-leader-can-coop: false + + # Island and Team Chat + chat: + # Team Chat + # The prefix [Team Chat] that goes in front of team chats is in the locale files + team: + # This enables player to set is so their chat goes to their team mates only + # using the /island teamchat command. + use: true + + # Log all messages sent in TeamChats to console. + log: true + + # Set this to true will include trust players in the TeamChat. + include-trust: true + + # Set this to true will include coop players in the TeamChat. + include-coop: false + + # TODO + island: + use: true + log: true + + # Ask the player to confirm the command he is using by typing it again. + # The "wait" value is the number of seconds to wait for confirmation. + require-confirmation: + kick: true + kick-wait: 10 + + leave: true + leave-wait: 10 + + reset: true + reset-wait: 10 + + # Deaths count + deaths: + # Max deaths + # If player dies more than this, it doesn't count anymore + max: 10 + + # Sum team deaths - if true, all the teams deaths are summed + # If false, only the leader's deaths counts + sum-team: false + +### Protection Settings ### +protection: + # Allow pistons to push outside of the protected area (maybe to make bridges) + allow-piston-push: true + + # Restrict Wither and other flying mobs. + # Any flying mobs that exit the island space where they were spawned will be removed. + # Includes blaze and ghast. + restrict-wither: true + + # Invincible visitors - Prevent players from killing them (intentionally or by accident) + # If they fall to the void, they get TP'd to their island. + invincible-visitors: + # Toggle the invincibility + use: true + + # This allow you to customize what kind of damage visitors should not receive + # If you want visitors to receive a listed damage, put a "#" at the start of the line + # See this for more info about options : https://hub.spigotmc.org/javadocs/bukkit/org/bukkit/event/entity/EntityDamageEvent.DamageCause.html + options: + - BLOCK_EXPLOSION + - CONTACT + - CUSTOM + - DROWNING + - ENTITY_ATTACK + - ENTITY_EXPLOSION + - FALL + - FALLING_BLOCK + - FIRE + - FIRE_TICK + - LAVA + - LIGHTNING + - MAGIC + - POISON + - PROJECTILE + - STARVATION + - SUFFOCATION + - THORNS + - WITHER + # 1.9+ only + - DRAGON_BREATH + - FLY_INTO_WALL + # 1.10+ only + - HOT_FLOOR + # 1.11+ only + - CRAMMING + + # Visitor banned commands: Visitors to islands cannot use these commands + visitor-banned-commands: + - spawner + - spawnmob + + # PVP cooldown in seconds. Players cannot toggle PVP off and on until this timeout + toggle-pvp-cooldown: 60 + + # TODO + flags: [] + +### Acid Settings ### +# Originally designed for AcidIsland, but can be used for BSkyBlock as well. +acid: + # Ops receive damage from acid (Set to true if you want Ops to play properly) + damage-op: false + + # Damage chickens in acid - true or false - chickens tend to go swimming... + damage-chickens: false + + damage: + # Water is acid + acid: + # Acid damage to player per second by being in acid if they have no armor on. + # A fully health player has 20 health points. Players will regen some health + # so the default will give players about 3 seconds to get out the acid + # 0 = no damage, 10 = default damage, 20 = instant death + player: 0 + + # Damage that monsters will experience in acid. + monster: 0 + + # Damage that animals will experience in acid. + animal: 0 + + # Destroy items in water after this many seconds. Timing is variable and may occur + # up to 2x this time. If 0, items will not be removed. Acid damage does not need to + # be on for this setting to work. i.e., it'll work with water too. + # Items fizz when they are destroyed. + item: 0 + + # Damage that rain does. + rain: 0 + + # Damage type to apply in addition to acid damage + # Types can be : SLOW, SLOW_DIGGING, CONFUSION, BLINDNESS, HUNGER, WEAKNESS and POISON + # If you just want these to act, then make the acid damage 0 above + # Note - these are potion effects and so can be cured by milk + effects: + #- confusion + + # Armor protection + protection: + # Protect players from acid rain if they have a helmet on + helmet: false + + # Protect players from all acid if they have a full set of armor on + full-armor: false + +### Schematics Settings ### +schematics: + # These are the default settings applied to the schematics + defaults: + companion: + # Default island companion. Set schematic-specific companions in the schematic configuration + # Recommended are: COW, PIG, SHEEP, CHICKEN, VILLAGER, HORSE, IRON_GOLEM, OCELOT, + # RABBIT, WOLF, LLAMA or NOTHING. Default is COW. + # If you don't want a companion to spawn, set NOTHING. + type: COW + + # List of names, picked at random that will apply to the companion + # You can add more if you like. If none are listed, the companion will not be named. + # Set schematic-specific companion names in the schematic configuration + names: + - "&9[player]'s cow" + - "&cEmergency &fFood?" + - "&aD&6a&di&6s&9y" + - "&bA&cTasty&aCow" + + # Items that will be in the chest when the player starts an island + # TODO + chest-items: + - ICE:2 + +# Config.yml version. DO NOT EDIT. This number only changes if the latest +# plugin config has been updated. If a new config is detected, it will be +# auto-saved to config.new.yml. +version: ${version} diff --git a/pom.xml b/pom.xml index 7841c87bc..73b4ee541 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ jar 0.0.1 BSkyBlock - The next generation of BSkyBlock + The next generation of ASkyBlock UTF-8 @@ -31,9 +31,9 @@ - locale + locales false - ${basedir}/locale + ${basedir}/locales *.yml @@ -83,4 +83,4 @@ http://nexus.hc.to/content/repositories/pub_releases - \ No newline at end of file + diff --git a/src/main/java/us/tastybento/bskyblock/BSkyBlock.java b/src/main/java/us/tastybento/bskyblock/BSkyBlock.java index 8838c92f8..8f9353f8e 100755 --- a/src/main/java/us/tastybento/bskyblock/BSkyBlock.java +++ b/src/main/java/us/tastybento/bskyblock/BSkyBlock.java @@ -8,6 +8,7 @@ import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; import us.tastybento.bskyblock.config.BSBLocale; +import us.tastybento.bskyblock.config.PluginConfig; import us.tastybento.bskyblock.config.Settings; import us.tastybento.bskyblock.database.BSBDatabase; import us.tastybento.bskyblock.database.IslandsManager; @@ -22,80 +23,85 @@ import us.tastybento.bskyblock.util.VaultHelper; */ public class BSkyBlock extends JavaPlugin{ private static BSkyBlock plugin; - + private HashMap locales = new HashMap(); - + // Databases private PlayersManager playersManager; private IslandsManager islandsManager; private OfflineHistoryMessages offlineHistoryMessages; - + // Metrics private Metrics metrics; - + @Override public void onEnable(){ plugin = this; - playersManager = new PlayersManager(this); - islandsManager = new IslandsManager(this); - - playersManager.load(); - islandsManager.load(); - - offlineHistoryMessages = new OfflineHistoryMessages(this); - offlineHistoryMessages.load(); - - if (Settings.useEconomy && !VaultHelper.setupEconomy()) { - getLogger().warning("Could not set up economy! - Running without an economy."); - Settings.useEconomy = false; - } + if (!VaultHelper.setupPermissions()) { getLogger().severe("Cannot link with Vault for permissions! Disabling plugin!"); getServer().getPluginManager().disablePlugin(this); return; } - // Only load metrics if set to true in config - if(Settings.metrics) metrics = new Metrics(this); - - // If metrics are loaded, register the custom data charts - if(metrics != null){ - registerCustomCharts(); - } - - // Save islands & players data asynchronously every X minutes - plugin.getServer().getScheduler().runTaskTimer(this, new Runnable() { - - @Override - public void run() { - playersManager.save(true); - islandsManager.save(true); - offlineHistoryMessages.save(true); + // Load configuration and locales. If there are no errors, load the plugin. + if(PluginConfig.loadPluginConfig(this)){ + playersManager = new PlayersManager(this); + islandsManager = new IslandsManager(this); + + playersManager.load(); + islandsManager.load(); + + offlineHistoryMessages = new OfflineHistoryMessages(this); + offlineHistoryMessages.load(); + + if (Settings.useEconomy && !VaultHelper.setupEconomy()) { + getLogger().warning("Could not set up economy! - Running without an economy."); + Settings.useEconomy = false; } - }, Settings.backupPeriod, Settings.backupPeriod); + + // Only load metrics if set to true in config + if(Settings.metrics) metrics = new Metrics(this); + + // If metrics are loaded, register the custom data charts + if(metrics != null){ + registerCustomCharts(); + } + + // Save islands & players data asynchronously every X minutes + plugin.getServer().getScheduler().runTaskTimer(this, new Runnable() { + + @Override + public void run() { + playersManager.save(true); + islandsManager.save(true); + offlineHistoryMessages.save(true); + } + }, Settings.databaseBackupPeriod, Settings.databaseBackupPeriod); + } } - + @Override public void onDisable(){ // Save data playersManager.shutdown(); islandsManager.shutdown(); offlineHistoryMessages.shutdown(); - + plugin = null; } - + private void registerCustomCharts(){ metrics.addCustomChart(new Metrics.SingleLineChart("islands_count") { - + @Override public int getValue() { return islandsManager.getCount(); } }); - + metrics.addCustomChart(new Metrics.SingleLineChart("created_islands") { - + @Override public int getValue() { int created = islandsManager.metrics_getCreatedCount(); @@ -103,24 +109,24 @@ public class BSkyBlock extends JavaPlugin{ return created; } }); - + metrics.addCustomChart(new Metrics.SimplePie("default_locale") { - + @Override public String getValue() { return Settings.defaultLanguage; } }); - + metrics.addCustomChart(new Metrics.SimplePie("database") { - + @Override public String getValue() { return BSBDatabase.getDatabase().toString(); } }); } - + /** * Returns BSkyBlock object instance * @return BSkyBlock instance @@ -128,7 +134,7 @@ public class BSkyBlock extends JavaPlugin{ public static BSkyBlock getInstance(){ return plugin; } - + /** * Returns an HashMap of locale identifier and the related object * @return the locales @@ -136,7 +142,15 @@ public class BSkyBlock extends JavaPlugin{ public HashMap getLocales(){ return locales; } - + + /** + * Set the available locales + * @param locales - the locales to set + */ + public void setLocales(HashMap locales){ + this.locales = locales; + } + /** * Returns the default locale * @return the default locale @@ -144,7 +158,7 @@ public class BSkyBlock extends JavaPlugin{ public BSBLocale getLocale(){ return locales.get(Settings.defaultLanguage); } - + /** * Returns the locale for the specified CommandSender * @param sender - CommandSender to get the locale @@ -154,7 +168,7 @@ public class BSkyBlock extends JavaPlugin{ if(sender instanceof Player) return getLocale(((Player) sender).getUniqueId()); else return getLocale(); } - + /** * Returns the locale for the specified player * @param player - Player to get the locale @@ -163,10 +177,10 @@ public class BSkyBlock extends JavaPlugin{ public BSBLocale getLocale(UUID player){ String locale = getPlayers().getPlayer(player).getLocale(); if(locale.isEmpty() || !locales.containsKey(locale)) return locales.get(Settings.defaultLanguage); - + return locales.get(locale); } - + /** * Returns the player database * @return the player database @@ -174,7 +188,7 @@ public class BSkyBlock extends JavaPlugin{ public PlayersManager getPlayers(){ return playersManager; } - + /** * Returns the island database * @return the island database diff --git a/src/main/java/us/tastybento/bskyblock/commands/BSBCommand.java b/src/main/java/us/tastybento/bskyblock/commands/BSBCommand.java index 0a4f6ef4b..818f5be90 100644 --- a/src/main/java/us/tastybento/bskyblock/commands/BSBCommand.java +++ b/src/main/java/us/tastybento/bskyblock/commands/BSBCommand.java @@ -38,7 +38,7 @@ public abstract class BSBCommand implements CommandExecutor, TabCompleter{ @Override public void onExecute(CommandSender sender, String label, String[] args) { // Generate help - String help = plugin.getLocale(sender).helpHeader + "\n"; + String help = plugin.getLocale(sender).get("help.header") + "\n"; for(String argument : arguments.keySet()){ CommandArgumentHandler cah = getArgumentHandler(argument); diff --git a/src/main/java/us/tastybento/bskyblock/commands/IslandCommand.java b/src/main/java/us/tastybento/bskyblock/commands/IslandCommand.java index 6c2596a1c..658a6d573 100755 --- a/src/main/java/us/tastybento/bskyblock/commands/IslandCommand.java +++ b/src/main/java/us/tastybento/bskyblock/commands/IslandCommand.java @@ -29,14 +29,14 @@ public class IslandCommand extends BSBCommand{ @Override public boolean canExecute(CommandSender sender, String label) { if(!(sender instanceof Player)){ - Util.sendMessage(sender, plugin.getLocale(sender).errorUseInGame); + Util.sendMessage(sender, plugin.getLocale(sender).get("general.errors.use-in-game")); return false; } Player player = (Player) sender; // Basic permission check to even use /island if(!VaultHelper.hasPerm(player, Settings.PERMPREFIX + "island.create")){ - Util.sendMessage(player, ChatColor.RED + plugin.getLocale(player).errorNoPermission); + Util.sendMessage(player, ChatColor.RED + plugin.getLocale(player).get("general.errors.no-permission")); return false; } @@ -113,8 +113,8 @@ public class IslandCommand extends BSBCommand{ @Override public String[] getHelp(CommandSender sender, String label){ // TODO check if multiple homes - if(VaultHelper.hasPerm((Player) sender, "todo")) return new String[] {"[1-x]", plugin.getLocale(sender).islandHelpGoHomes}; - return new String[] {null, plugin.getLocale(sender).islandHelpGo}; + if(VaultHelper.hasPerm((Player) sender, "todo")) return new String[] {"[1-x]", plugin.getLocale(sender).get("help.island.go-homes")}; + return new String[] {null, plugin.getLocale(sender).get("help.island.go")}; } }); @@ -140,7 +140,7 @@ public class IslandCommand extends BSBCommand{ @Override public String[] getHelp(CommandSender sender, String label){ - return new String[] {null, plugin.getLocale(sender).islandHelpSpawn}; + return new String[] {null, plugin.getLocale(sender).get("help.island.spawn")}; } }); @@ -167,7 +167,7 @@ public class IslandCommand extends BSBCommand{ @Override public String[] getHelp(CommandSender sender, String label){ - return new String[] {"[schematic]", plugin.getLocale(sender).islandHelpCreate}; + return new String[] {"[schematic]", plugin.getLocale(sender).get("help.island.create")}; } }); @@ -194,7 +194,7 @@ public class IslandCommand extends BSBCommand{ @Override public String[] getHelp(CommandSender sender, String label){ - return new String[] {"[player]", plugin.getLocale(sender).islandHelpInfo}; + return new String[] {"[player]", plugin.getLocale(sender).get("help.island.info")}; } }); @@ -221,7 +221,7 @@ public class IslandCommand extends BSBCommand{ @Override public String[] getHelp(CommandSender sender, String label){ - return new String[] {"[on/off]", plugin.getLocale(sender).islandHelpControlPanel}; + return new String[] {"[on/off]", plugin.getLocale(sender).get("help.island.control-panel")}; } }); @@ -248,7 +248,7 @@ public class IslandCommand extends BSBCommand{ @Override public String[] getHelp(CommandSender sender, String label){ - return new String[] {null, plugin.getLocale(sender).islandHelpReset}; + return new String[] {null, plugin.getLocale(sender).get("help.island.reset")}; } }); @@ -275,35 +275,7 @@ public class IslandCommand extends BSBCommand{ @Override public String[] getHelp(CommandSender sender, String label){ - return new String[] {null, plugin.getLocale(sender).islandHelpSetHome}; - } - }); - - /* /is level [player] - Calculate and display island level */ - registerArgument(new String[] {"level"}, new CommandArgumentHandler() { - - @Override - public boolean canExecute(CommandSender sender, String label, String[] args) { - // TODO Auto-generated method stub - return false; - } - - @Override - public void onExecute(CommandSender sender, String label, String[] args) { - // TODO Auto-generated method stub - - } - - @Override - public List onTabComplete(CommandSender sender, String label, String[] args) { - // TODO Auto-generated method stub - return null; - } - - @Override - public String[] getHelp(CommandSender sender, String label){ - return new String[] {null, plugin.getLocale(sender).islandHelpLevel, - "[player]", plugin.getLocale(sender).islandHelpLevelOther}; + return new String[] {null, plugin.getLocale(sender).get("help.island.sethome")}; } }); @@ -315,17 +287,17 @@ public class IslandCommand extends BSBCommand{ Player player = (Player) sender; if(!VaultHelper.hasPerm(player, Settings.PERMPREFIX + "island.name")){ - Util.sendMessage(player, ChatColor.RED + plugin.getLocale(player).errorNoPermission); + Util.sendMessage(player, ChatColor.RED + plugin.getLocale(player).get("general.errors.no-permission")); return false; } if(!plugin.getIslands().hasIsland(player.getUniqueId())){ - Util.sendMessage(player, ChatColor.RED + plugin.getLocale(player).errorNoIsland); + Util.sendMessage(player, ChatColor.RED + plugin.getLocale(player).get("general.errors.no-island")); return false; } if(!plugin.getIslands().isOwner(player.getUniqueId())){ - Util.sendMessage(player, ChatColor.RED + plugin.getLocale(player).errorNotLeader); + Util.sendMessage(player, ChatColor.RED + plugin.getLocale(player).get("general.errors.not-leader")); return false; } @@ -349,12 +321,12 @@ public class IslandCommand extends BSBCommand{ } // Check if the name isn't too short or too long - if(name.length() < Settings.minIslandNameLength){ - Util.sendMessage(player, ChatColor.RED + plugin.getLocale(player).errorTooShort.replace("[length]", String.valueOf(Settings.minIslandNameLength))); + if(name.length() < Settings.nameMinLength){ + Util.sendMessage(player, ChatColor.RED + plugin.getLocale(player).get("general.errors.too-short").replace("[length]", String.valueOf(Settings.nameMinLength))); return; } - if(name.length() > Settings.maxIslandNameLength){ - Util.sendMessage(player, ChatColor.RED + plugin.getLocale(player).errorTooLong.replace("[length]", String.valueOf(Settings.maxIslandNameLength))); + if(name.length() > Settings.nameMaxLength){ + Util.sendMessage(player, ChatColor.RED + plugin.getLocale(player).get("general.errors.too-long").replace("[length]", String.valueOf(Settings.nameMaxLength))); return; } @@ -362,7 +334,7 @@ public class IslandCommand extends BSBCommand{ if(VaultHelper.hasPerm(player, Settings.PERMPREFIX + "island.name.format")) plugin.getIslands().getIsland(player.getUniqueId()).setName(ChatColor.translateAlternateColorCodes('&', name)); else plugin.getIslands().getIsland(player.getUniqueId()).setName(name); - Util.sendMessage(player, ChatColor.GREEN + plugin.getLocale(player).generalSuccess); + Util.sendMessage(player, ChatColor.GREEN + plugin.getLocale(player).get("general.success")); } @Override @@ -372,7 +344,7 @@ public class IslandCommand extends BSBCommand{ @Override public String[] getHelp(CommandSender sender, String label){ - return new String[] {"", plugin.getLocale(sender).islandHelpName}; + return new String[] {"", plugin.getLocale(sender).get("help.island.name")}; } }); @@ -384,17 +356,17 @@ public class IslandCommand extends BSBCommand{ Player player = (Player) sender; if(!VaultHelper.hasPerm(player, Settings.PERMPREFIX + "island.name")){ - Util.sendMessage(player, ChatColor.RED + plugin.getLocale(player).errorNoPermission); + Util.sendMessage(player, ChatColor.RED + plugin.getLocale(player).get("general.errors.no-permission")); return false; } if(!plugin.getIslands().hasIsland(player.getUniqueId())){ - Util.sendMessage(player, ChatColor.RED + plugin.getLocale(player).errorNoIsland); + Util.sendMessage(player, ChatColor.RED + plugin.getLocale(player).get("general.errors.no-island")); return false; } if(!plugin.getIslands().isOwner(player.getUniqueId())){ - Util.sendMessage(player, ChatColor.RED + plugin.getLocale(player).errorNotLeader); + Util.sendMessage(player, ChatColor.RED + plugin.getLocale(player).get("general.errors.not-leader")); return false; } @@ -407,7 +379,7 @@ public class IslandCommand extends BSBCommand{ // Resets the island name plugin.getIslands().getIsland(player.getUniqueId()).setName(null); - Util.sendMessage(player, ChatColor.GREEN + plugin.getLocale(player).generalSuccess); + Util.sendMessage(player, ChatColor.GREEN + plugin.getLocale(player).get("general.success")); } @Override @@ -417,61 +389,7 @@ public class IslandCommand extends BSBCommand{ @Override public String[] getHelp(CommandSender sender, String label){ - return new String[] {null, plugin.getLocale(sender).islandHelpResetName}; - } - }); - - /* /is topten - Display top ten */ - registerArgument(new String[] {"topten", "top"}, new CommandArgumentHandler() { - - @Override - public boolean canExecute(CommandSender sender, String label, String[] args) { - // TODO Auto-generated method stub - return false; - } - - @Override - public void onExecute(CommandSender sender, String label, String[] args) { - // TODO Auto-generated method stub - - } - - @Override - public List onTabComplete(CommandSender sender, String label, String[] args) { - // TODO Auto-generated method stub - return null; - } - - @Override - public String[] getHelp(CommandSender sender, String label){ - return new String[] {null, plugin.getLocale(sender).islandHelpTopTen}; - } - }); - - /* /is value - Show the value of the block in hand */ - registerArgument(new String[] {"value"}, new CommandArgumentHandler() { - - @Override - public boolean canExecute(CommandSender sender, String label, String[] args) { - // TODO Auto-generated method stub - return false; - } - - @Override - public void onExecute(CommandSender sender, String label, String[] args) { - // TODO Auto-generated method stub - - } - - @Override - public List onTabComplete(CommandSender sender, String label, String[] args) { - // TODO Auto-generated method stub - return null; - } - - @Override - public String[] getHelp(CommandSender sender, String label){ - return new String[] {null, plugin.getLocale(sender).islandHelpValue}; + return new String[] {null, plugin.getLocale(sender).get("help.island.resetname")}; } }); @@ -498,7 +416,7 @@ public class IslandCommand extends BSBCommand{ @Override public String[] getHelp(CommandSender sender, String label){ - return new String[] {null, plugin.getLocale(sender).islandHelpLimits}; + return new String[] {null, plugin.getLocale(sender).get("help.island.limits")}; } }); @@ -525,7 +443,7 @@ public class IslandCommand extends BSBCommand{ @Override public String[] getHelp(CommandSender sender, String label){ - return new String[] {null, plugin.getLocale(sender).islandHelpTeam}; + return new String[] {null, plugin.getLocale(sender).get("help.island.team")}; } }); @@ -552,7 +470,7 @@ public class IslandCommand extends BSBCommand{ @Override public String[] getHelp(CommandSender sender, String label){ - return new String[] {"", plugin.getLocale(sender).islandHelpInvite}; + return new String[] {"", plugin.getLocale(sender).get("help.island.invite")}; } }); @@ -579,7 +497,7 @@ public class IslandCommand extends BSBCommand{ @Override public String[] getHelp(CommandSender sender, String label){ - return new String[] {"", plugin.getLocale(sender).islandHelpUninvite}; + return new String[] {"", plugin.getLocale(sender).get("help.island.uninvite")}; } }); @@ -606,7 +524,7 @@ public class IslandCommand extends BSBCommand{ @Override public String[] getHelp(CommandSender sender, String label){ - return new String[] {null, plugin.getLocale(sender).islandHelpLeave}; + return new String[] {null, plugin.getLocale(sender).get("help.island.leave")}; } }); @@ -633,7 +551,7 @@ public class IslandCommand extends BSBCommand{ @Override public String[] getHelp(CommandSender sender, String label){ - return new String[] {"", plugin.getLocale(sender).islandHelpKick}; + return new String[] {"", plugin.getLocale(sender).get("help.island.kick")}; } }); @@ -660,7 +578,7 @@ public class IslandCommand extends BSBCommand{ @Override public String[] getHelp(CommandSender sender, String label){ - return new String[] {"[player]", plugin.getLocale(sender).islandHelpAccept}; + return new String[] {"[player]", plugin.getLocale(sender).get("help.island.accept")}; } }); @@ -687,7 +605,7 @@ public class IslandCommand extends BSBCommand{ @Override public String[] getHelp(CommandSender sender, String label){ - return new String[] {"[player]", plugin.getLocale(sender).islandHelpReject}; + return new String[] {"[player]", plugin.getLocale(sender).get("help.island.reject")}; } }); @@ -714,7 +632,7 @@ public class IslandCommand extends BSBCommand{ @Override public String[] getHelp(CommandSender sender, String label){ - return new String[] {"", plugin.getLocale(sender).islandHelpMakeleader}; + return new String[] {"", plugin.getLocale(sender).get("help.island.makeleader")}; } }); @@ -741,7 +659,7 @@ public class IslandCommand extends BSBCommand{ @Override public String[] getHelp(CommandSender sender, String label){ - return new String[] {null, plugin.getLocale(sender).islandHelpTeamchat}; + return new String[] {null, plugin.getLocale(sender).get("help.island.teamchat")}; } }); @@ -768,7 +686,7 @@ public class IslandCommand extends BSBCommand{ @Override public String[] getHelp(CommandSender sender, String label){ - return new String[] {null, plugin.getLocale(sender).islandHelpBiomes}; + return new String[] {null, plugin.getLocale(sender).get("help.island.biomes")}; } }); @@ -795,7 +713,7 @@ public class IslandCommand extends BSBCommand{ @Override public String[] getHelp(CommandSender sender, String label){ - return new String[] {"", plugin.getLocale(sender).islandHelpExpel}; + return new String[] {"", plugin.getLocale(sender).get("help.island.expel")}; } }); @@ -822,7 +740,7 @@ public class IslandCommand extends BSBCommand{ @Override public String[] getHelp(CommandSender sender, String label){ - return new String[] {null, plugin.getLocale(sender).islandHelpExpelall}; + return new String[] {null, plugin.getLocale(sender).get("help.island.expelall")}; } }); @@ -849,7 +767,7 @@ public class IslandCommand extends BSBCommand{ @Override public String[] getHelp(CommandSender sender, String label){ - return new String[] {"", plugin.getLocale(sender).islandHelpBan}; + return new String[] {"", plugin.getLocale(sender).get("help.island.ban")}; } }); @@ -876,7 +794,7 @@ public class IslandCommand extends BSBCommand{ @Override public String[] getHelp(CommandSender sender, String label){ - return new String[] {"", plugin.getLocale(sender).islandHelpUnban}; + return new String[] {"", plugin.getLocale(sender).get("help.island.unban")}; } }); @@ -903,7 +821,7 @@ public class IslandCommand extends BSBCommand{ @Override public String[] getHelp(CommandSender sender, String label){ - return new String[] {null, plugin.getLocale(sender).islandHelpBanlist}; + return new String[] {null, plugin.getLocale(sender).get("help.island.banlist")}; } }); @@ -930,7 +848,7 @@ public class IslandCommand extends BSBCommand{ @Override public String[] getHelp(CommandSender sender, String label){ - return new String[] {"", plugin.getLocale(sender).islandHelpTrust}; + return new String[] {"", plugin.getLocale(sender).get("help.island.trust")}; } }); @@ -957,7 +875,7 @@ public class IslandCommand extends BSBCommand{ @Override public String[] getHelp(CommandSender sender, String label){ - return new String[] {"", plugin.getLocale(sender).islandHelpUntrust}; + return new String[] {"", plugin.getLocale(sender).get("help.island.untrust")}; } }); @@ -984,7 +902,7 @@ public class IslandCommand extends BSBCommand{ @Override public String[] getHelp(CommandSender sender, String label){ - return new String[] {null, plugin.getLocale(sender).islandHelpTrustlist}; + return new String[] {null, plugin.getLocale(sender).get("help.island.trustlist")}; } }); @@ -1011,7 +929,7 @@ public class IslandCommand extends BSBCommand{ @Override public String[] getHelp(CommandSender sender, String label){ - return new String[] {"", plugin.getLocale(sender).islandHelpCoop}; + return new String[] {"", plugin.getLocale(sender).get("help.island.coop")}; } }); @@ -1038,7 +956,7 @@ public class IslandCommand extends BSBCommand{ @Override public String[] getHelp(CommandSender sender, String label){ - return new String[] {"", plugin.getLocale(sender).islandHelpUncoop}; + return new String[] {"", plugin.getLocale(sender).get("help.island.uncoop")}; } }); @@ -1065,7 +983,7 @@ public class IslandCommand extends BSBCommand{ @Override public String[] getHelp(CommandSender sender, String label){ - return new String[] {null, plugin.getLocale(sender).islandHelpCooplist}; + return new String[] {null, plugin.getLocale(sender).get("help.island.cooplist")}; } }); @@ -1077,12 +995,12 @@ public class IslandCommand extends BSBCommand{ Player player = (Player) sender; if(!VaultHelper.hasPerm(player, Settings.PERMPREFIX + "island.lock")){ - Util.sendMessage(player, ChatColor.RED + plugin.getLocale(player).errorNoPermission); + Util.sendMessage(player, ChatColor.RED + plugin.getLocale(player).get("general.errors.no-permission")); return false; } if(!plugin.getIslands().hasIsland(player.getUniqueId())){ - Util.sendMessage(player, ChatColor.RED + plugin.getLocale(player).errorNoIsland); + Util.sendMessage(player, ChatColor.RED + plugin.getLocale(player).get("general.errors.no-island")); return false; } @@ -1097,9 +1015,9 @@ public class IslandCommand extends BSBCommand{ if(!island.isLocked()){ // TODO: Expel all visitors // TODO: send offline messages - island.setLocked(false); + island.setLocked(true); } else { - Util.sendMessage(player, ChatColor.GREEN + plugin.getLocale(player).lockUnlocking); + Util.sendMessage(player, ChatColor.GREEN + plugin.getLocale(player).get("island.lock.unlocking")); // TODO: send offline messages island.setLocked(false); } @@ -1112,7 +1030,7 @@ public class IslandCommand extends BSBCommand{ @Override public String[] getHelp(CommandSender sender, String label){ - return new String[] {null, plugin.getLocale(sender).islandHelpLock}; + return new String[] {null, plugin.getLocale(sender).get("help.island.lock")}; } }); @@ -1139,7 +1057,7 @@ public class IslandCommand extends BSBCommand{ @Override public String[] getHelp(CommandSender sender, String label){ - return new String[] {null, plugin.getLocale(sender).islandHelpSettings}; + return new String[] {null, plugin.getLocale(sender).get("help.island.settings")}; } }); @@ -1166,7 +1084,7 @@ public class IslandCommand extends BSBCommand{ @Override public String[] getHelp(CommandSender sender, String label){ - return new String[] {"", plugin.getLocale(sender).islandHelpLanguage}; + return new String[] {"", plugin.getLocale(sender).get("help.island.language")}; } }); } diff --git a/src/main/java/us/tastybento/bskyblock/commands/NotSetup.java b/src/main/java/us/tastybento/bskyblock/commands/NotSetup.java deleted file mode 100755 index 0fa5ac1d4..000000000 --- a/src/main/java/us/tastybento/bskyblock/commands/NotSetup.java +++ /dev/null @@ -1,57 +0,0 @@ -package us.tastybento.bskyblock.commands; - -import org.bukkit.ChatColor; -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; - -import us.tastybento.bskyblock.BSkyBlock; -import us.tastybento.bskyblock.util.Util; - -/** - * This class runs when the config file is not set up enough, or is unsafe. - * It provides useful information to the admin on what is wrong. - * - * @author Tastybento - */ -public class NotSetup implements CommandExecutor{ - - public enum Reason { - DISTANCE, GENERATOR, WORLD_NAME, OUTDATED; - } - - private BSkyBlock plugin; - private Reason reason; - - /** - * Handles plugin operation if a critical config-related issue happened - * - * @param reason - */ - public NotSetup(BSkyBlock plugin, Reason reason){ - this.reason = reason; - } - - @Override - public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { - Util.sendMessage(sender, ChatColor.RED + plugin.getLocale(sender).notSetupHeader); - switch (reason) { - case DISTANCE: - Util.sendMessage(sender, ChatColor.RED + plugin.getLocale(sender).notSetupDistance); - break; - case GENERATOR: - Util.sendMessage(sender, ChatColor.RED + plugin.getLocale(sender).notSetupGenerator); - if(plugin.getServer().getPluginManager().isPluginEnabled("Multiverse-Core")) Util.sendMessage(sender, ChatColor.RED + plugin.getLocale(sender).notSetupGeneratorMultiverse); - break; - case WORLD_NAME: - Util.sendMessage(sender, ChatColor.RED + plugin.getLocale(sender).notSetupWorldname); - break; - case OUTDATED: - Util.sendMessage(sender, ChatColor.RED + plugin.getLocale(sender).notSetupOutdated); - break; - default: - break; - } - return true; - } -} diff --git a/src/main/java/us/tastybento/bskyblock/config/BSBLocale.java b/src/main/java/us/tastybento/bskyblock/config/BSBLocale.java index 0609207f7..6c2488af7 100644 --- a/src/main/java/us/tastybento/bskyblock/config/BSBLocale.java +++ b/src/main/java/us/tastybento/bskyblock/config/BSBLocale.java @@ -1,16 +1,17 @@ package us.tastybento.bskyblock.config; import java.io.File; +import java.util.HashMap; import java.util.Locale; -import org.bukkit.ChatColor; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import us.tastybento.bskyblock.BSkyBlock; /** - * Contains all the texts sent to players + * Contains all the texts sent to players. + * The locale object is instantiated at server launch, but the texts are only loaded when needed. * * @author Tastybento * @author Poslovitch @@ -33,7 +34,6 @@ public class BSBLocale { this.plugin = plugin; this.localeID = localeID; getLocale(localeID); - loadLocale(); localeObject = new Locale(localeID.substring(0, 2), localeID.substring(3, 5)); } @@ -104,99 +104,15 @@ public class BSBLocale { } /* Localization */ + private HashMap localization = new HashMap(); - // Not Setup - public String notSetupHeader; - public String notSetupDistance; - public String notSetupGenerator; - public String notSetupGeneratorMultiverse; - public String notSetupWorldname; - public String notSetupOutdated; - - // General - public String generalSuccess; - - // Errors - public String errorNoPermission; - public String errorUseInGame; - public String errorNoIsland; - public String errorNotLeader; - public String errorTooShort; - public String errorTooLong; - - // Help - public String helpSyntaxColor; - public String helpCommentColor; - public String helpHeader; - public String islandHelpGo; - public String islandHelpGoHomes; - public String islandHelpSpawn; - public String islandHelpCreate; - public String islandHelpInfo; - public String islandHelpControlPanel; - public String islandHelpReset; - public String islandHelpSetHome; - public String islandHelpLevel; - public String islandHelpLevelOther; - public String islandHelpName; - public String islandHelpResetName; - public String islandHelpTopTen; - public String islandHelpValue; - public String islandHelpLimits; - public String islandHelpTeam; - public String islandHelpInvite; - public String islandHelpUninvite; - public String islandHelpLeave; - public String islandHelpKick; - public String islandHelpAccept; - public String islandHelpReject; - public String islandHelpMakeleader; - public String islandHelpTeamchat; - public String islandHelpBiomes; - public String islandHelpExpel; - public String islandHelpExpelall; - public String islandHelpBan; - public String islandHelpUnban; - public String islandHelpBanlist; - public String islandHelpTrust; - public String islandHelpUntrust; - public String islandHelpTrustlist; - public String islandHelpCoop; - public String islandHelpUncoop; - public String islandHelpCooplist; - public String islandHelpLock; - public String islandHelpSettings; - public String islandHelpLanguage; - - // Lock - public String lockLocking; - public String lockUnlocking; - - private void loadLocale(){ - // Not Setup - notSetupHeader = ChatColor.translateAlternateColorCodes('&', locale.getString("not-setup.header", "More set up is required before the plugin can start...\nEdit config.yml. Then restart server.")); - notSetupDistance = ChatColor.translateAlternateColorCodes('&', locale.getString("not-setup.distance", "Make sure you set island distance. If upgrading, set it to what it was before.")); - notSetupGenerator = ChatColor.translateAlternateColorCodes('&', - locale.getString("not-setup.generator", "The world generator for the island world is not registered." - + "\nPotential reasons are:" - + "\n 1. If you are configuring the island world as the only server world\n Make sure you have added the world to bukkit.yml" - + "\n 2. You reloaded instead of restarting the server. Reboot and try again.")); - notSetupGeneratorMultiverse = ChatColor.translateAlternateColorCodes('&', locale.getString("not-setup.generator-multiverse", " 3. Your Multiverse plugin is out of date. Upgrade to the latest version.")); - notSetupWorldname = ChatColor.translateAlternateColorCodes('&', - locale.getString("not-setup.world-name", "The world name in config.yml is different to the world name in islands.yml." - + "\nIf this is intentional, we assume you are doing a full reset." - + "\nIf so, delete islands.yml and the previous world." - + "\nIf not, correct the world name in config.yml and restart. This is probably the case if you are upgrading.")); - notSetupOutdated = ChatColor.translateAlternateColorCodes('&', - locale.getString("not-setup.config-outdated", "The config.yml file looks outdated." - + "\nMake sure you updated your configuration after upgrading." - + "\nIf this error is still happening, you probably edited the old config rather than editing the new one." - + "\nIf so, please remove the current config.yml, work on config.new.yml and rename it to config.yml.")); - - // General - generalSuccess = ChatColor.translateAlternateColorCodes('&', locale.getString("general.success", "Success!")); - - // Errors - errorNoPermission = ChatColor.translateAlternateColorCodes('&', locale.getString("general.errors.no-permission", "You don't have permission to execute this command.")); + public String get(String id){ + // If the text isn't loaded, load it. + if(!localization.containsKey(id)){ + // Save the text to the HashMap. + // If the text doesn't exist in the locale file, save it as its id, to help debug. + localization.put(id, locale.getString(id, id)); + } + return localization.get(id); } } diff --git a/src/main/java/us/tastybento/bskyblock/config/NotSetup.java b/src/main/java/us/tastybento/bskyblock/config/NotSetup.java new file mode 100644 index 000000000..eb9fbe960 --- /dev/null +++ b/src/main/java/us/tastybento/bskyblock/config/NotSetup.java @@ -0,0 +1,76 @@ +package us.tastybento.bskyblock.config; + +import java.util.List; + +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; + +import us.tastybento.bskyblock.BSkyBlock; + +/** + * This class runs when the config file is not set up enough, or is unsafe. + * It provides useful information to the admin on what is wrong. + * + * @author Tastybento + * @author Poslovitch + */ +public class NotSetup implements CommandExecutor{ + + public enum ConfigError { + DIFFERENT_WORLDNAME(0, 001), + DIFFERENT_ISLAND_DISTANCE(0, 002), + PROTECTION_RANGE_HIGHER_THAN_ISLAND_DISTANCE(1, 101), + UNKNOWN_LANGUAGE(2, 201), + NOT_EVEN_ISLAND_DISTANCE(2, 202), + NOT_EVEN_PROTECTION_RANGE(2, 203), + PURGE_ISLAND_LEVEL_TOO_LOW(3, 301), + ISLAND_DISTANCE_TOO_LOW(3, 302), + PROTECTION_RANGE_TOO_LOW(3, 303), + ISLAND_HEIGHT_TOO_LOW(3, 304), + NETHER_SPAWN_RADIUS_TOO_LOW(3, 305), + NETHER_SPAWN_RADIUS_TOO_HIGH(3, 306); + + /* + * Priority: + * 0 - CRITICAL + * 1 - HIGH + * 2 - MEDIUM + * 3 - LOW + */ + private int priority; + private int id; + + ConfigError(int priority, int id){ + this.priority = priority; + this.id = id; + } + + public static ConfigError getById(int id){ + for(ConfigError e : ConfigError.values()){ + if(e.id == id) return e; + } + return null; + } + } + + private BSkyBlock plugin; + private List errors; + + /** + * Handles plugin operation if a critical config-related issue happened + * + * @param plugin + * @param errors + */ + public NotSetup(BSkyBlock plugin, List errors){ + this.plugin = plugin; + this.errors = errors; + } + + @Override + public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { + + return true; + } +} diff --git a/src/main/java/us/tastybento/bskyblock/config/PluginConfig.java b/src/main/java/us/tastybento/bskyblock/config/PluginConfig.java index fdbdc64cf..eb8dcceab 100755 --- a/src/main/java/us/tastybento/bskyblock/config/PluginConfig.java +++ b/src/main/java/us/tastybento/bskyblock/config/PluginConfig.java @@ -1,5 +1,113 @@ package us.tastybento.bskyblock.config; -public class PluginConfig { +import java.util.HashMap; +import us.tastybento.bskyblock.BSkyBlock; +import us.tastybento.bskyblock.config.NotSetup.ConfigError; + +/** + * Loads the plugin configuration and the locales. + * Also provides + * + * @author Tastybento + * @author Poslovitch + */ +public class PluginConfig { + + /** + * Loads the plugin configuration and the locales. + * If there were errors, it setups the commands as "NotSetup" and generates a debug for admins to fix their configuration. + * @return true if there wasn't any error, otherwise false. + */ + public static boolean loadPluginConfig(BSkyBlock plugin){ + // Check if the config exists. It shouldn't happen, but the stack trace helps to know why. + try{ + plugin.getConfig(); + } catch (Exception exception){ + exception.printStackTrace(); + } + + // Initialize the errors list + HashMap errors = new HashMap(); + + //TODO config version + + // The order in this file should match the order in config.yml so that it's easy to check that everything is covered + + // ********************* General ********************* + Settings.metrics = plugin.getConfig().getBoolean("general.metrics", true); + Settings.checkUpdates = plugin.getConfig().getBoolean("general.check-updates", true); + + loadLocales(plugin); + Settings.defaultLanguage = plugin.getConfig().getString("general.default-language", "en-US"); + if(!plugin.getLocales().containsKey(Settings.defaultLanguage)) errors.put(ConfigError.UNKNOWN_LANGUAGE, Settings.defaultLanguage); + + Settings.useEconomy = plugin.getConfig().getBoolean("general.use-economy", true); + Settings.startingMoney = plugin.getConfig().getDouble("general.starting-money", 10.0); + Settings.useControlPanel = plugin.getConfig().getBoolean("general.use-control-panel", true); + + // Purge + Settings.purgeMaxIslandLevel = plugin.getConfig().getInt("general.purge.max-island-level", 50); + if(Settings.purgeMaxIslandLevel < 0) errors.put(ConfigError.PURGE_ISLAND_LEVEL_TOO_LOW, Settings.purgeMaxIslandLevel); + Settings.purgeRemoveUserData = plugin.getConfig().getBoolean("general.purge.remove-user-data", false); + + // TODO Database + + Settings.recoverSuperFlat = plugin.getConfig().getBoolean("general.recover-super-flat", false); + Settings.muteDeathMessages = plugin.getConfig().getBoolean("general.mute-death-messages", false); + Settings.ftbAutoActivator = plugin.getConfig().getBoolean("general.FTB-auto-activator", false); + Settings.allowObsidianScooping = plugin.getConfig().getBoolean("general.allow-obsidian-scooping", true); + + // Allow teleport + Settings.fallingAllowTeleport = plugin.getConfig().getBoolean("general.allow-teleport.falling", true); + Settings.fallingBlockedCommands = plugin.getConfig().getStringList("general.allow-teleport.falling-blocked-commands"); + Settings.acidAllowTeleport = plugin.getConfig().getBoolean("general.allow-teleport.acid", true); + Settings.acidBlockedCommands = plugin.getConfig().getStringList("general.allow-teleport.acid-blocked-commands"); + + // ********************* World ********************* + Settings.worldName = plugin.getConfig().getString("world.world-name", "BSkyBlock"); + //TODO check if it is the same than before + + Settings.islandDistance = plugin.getConfig().getInt("world.distance", 200); + // TODO check if it is the same than before + if(Settings.islandDistance % 2 != 0) errors.put(ConfigError.NOT_EVEN_ISLAND_DISTANCE, Settings.islandDistance); + if(Settings.islandDistance < 50) errors.put(ConfigError.ISLAND_DISTANCE_TOO_LOW, Settings.islandDistance); + + Settings.islandProtectionRange = plugin.getConfig().getInt("world.protection-range", 100); + if(Settings.islandProtectionRange % 2 != 0) errors.put(ConfigError.NOT_EVEN_PROTECTION_RANGE, Settings.islandProtectionRange); + if(Settings.islandProtectionRange < 0) errors.put(ConfigError.PROTECTION_RANGE_TOO_LOW, Settings.islandProtectionRange); + if(Settings.islandProtectionRange > Settings.islandDistance) errors.put(ConfigError.PROTECTION_RANGE_HIGHER_THAN_ISLAND_DISTANCE, Settings.islandProtectionRange); + + Settings.startX = plugin.getConfig().getInt("world.start-x", 0); + Settings.startZ = plugin.getConfig().getInt("world.start-z", 0); + Settings.islandHeight = plugin.getConfig().getInt("world.island-height", 120); + if(Settings.islandHeight < 5) errors.put(ConfigError.ISLAND_HEIGHT_TOO_LOW, Settings.islandHeight); + Settings.seaHeight = plugin.getConfig().getInt("world.sea-height", 0); + + Settings.maxIslands = plugin.getConfig().getInt("world.max-islands", 0); + + // Nether + Settings.netherGenerate = plugin.getConfig().getBoolean("world.nether.generate", true); + Settings.netherIslands = plugin.getConfig().getBoolean("world.nether.islands", true); + Settings.netherTrees = plugin.getConfig().getBoolean("world.nether.trees", true); + Settings.netherRoof = plugin.getConfig().getBoolean("world.nether.roof", true); + Settings.netherSpawnRadius = plugin.getConfig().getInt("world.nether.spawn-radius", 25); + if(!Settings.netherIslands){ + // If the nether is vanilla + if(Settings.netherSpawnRadius < 0) errors.put(ConfigError.NETHER_SPAWN_RADIUS_TOO_LOW, Settings.netherSpawnRadius); + if(Settings.netherSpawnRadius > 100) errors.put(ConfigError.NETHER_SPAWN_RADIUS_TOO_HIGH, Settings.netherSpawnRadius); + } + + // Entities + + //TODO end loading + + //TODO not setup error report + + return true; + } + + public static void loadLocales(BSkyBlock plugin){ + //TODO Imperatively load en-US locale + } } diff --git a/src/main/java/us/tastybento/bskyblock/config/Settings.java b/src/main/java/us/tastybento/bskyblock/config/Settings.java index 21b48f313..8e932052d 100755 --- a/src/main/java/us/tastybento/bskyblock/config/Settings.java +++ b/src/main/java/us/tastybento/bskyblock/config/Settings.java @@ -3,47 +3,158 @@ package us.tastybento.bskyblock.config; import java.util.HashMap; import java.util.List; +import org.bukkit.entity.EntityType; +import org.bukkit.event.entity.EntityDamageEvent.DamageCause; +import org.bukkit.inventory.ItemStack; +import org.bukkit.potion.PotionEffectType; + import us.tastybento.bskyblock.database.BSBDatabase.DatabaseType; import us.tastybento.bskyblock.database.OfflineHistoryMessages.HistoryMessageType; -import us.tastybento.bskyblock.database.objects.Island.SettingsFlag; /** * All the plugin settings are here * @author Tastybento */ public class Settings { + /* The settings variables should follow the config order */ public static final String PERMPREFIX = "askyblock."; + /* GENERAL */ + public static boolean metrics; + public static boolean checkUpdates; public static String defaultLanguage; - - public static int backupPeriod; - public static boolean useEconomy; - public static boolean useMinishop; - + public static double startingMoney; public static boolean useControlPanel; - public static int defaultResetLimit; - - public static boolean metrics; + // Purge + public static int purgeMaxIslandLevel; + public static boolean purgeRemoveUserData; + // TODO Database public static DatabaseType databaseType; + public static int databaseBackupPeriod; - public static int minIslandNameLength; - public static int maxIslandNameLength; + public static boolean recoverSuperFlat; + public static boolean muteDeathMessages; + public static boolean ftbAutoActivator; + public static boolean allowObsidianScooping; - public static HashMap defaultWorldSettings = new HashMap(); - public static HashMap defaultIslandSettings = new HashMap(); - public static HashMap defaultSpawnSettings = new HashMap(); + // Teleport + public static boolean fallingAllowTeleport; + public static List fallingBlockedCommands; + public static boolean acidAllowTeleport; + public static List acidBlockedCommands; - public static List historyMessagesTypes; - - public static int inviteWait; - - public static int maxDeaths; - + /* WORLD */ + public static String worldName; public static int islandDistance; + public static int islandProtectionRange; + public static int startX; + public static int startZ; + public static int seaHeight; + public static int islandHeight; + public static int maxIslands; - public static int protectionRange; + // Nether + public static boolean netherGenerate; + public static boolean netherIslands; + public static boolean netherTrees; + public static boolean netherRoof; + public static int netherSpawnRadius; + + // Entities + public static int spawnLimitMonsters; + public static int spawnLimitAnimals; + public static int spawnLimitWaterAnimals; + public static int breedingLimit; + public static HashMap entityLimits; + public static HashMap tileEntityLimits; + + public static boolean disableOfflineRedstone; + + /* ISLAND */ + public static int maxTeamSize; + public static int maxHomes; + public static int nameMinLength; + public static int nameMaxLength; + public static int inviteWait; + + // Reset + public static int resetLimit; + public static int resetWait; + public static boolean leaversLoseReset; + public static boolean kickedKeepInventory; + public static boolean onJoinResetMoney; + public static boolean onJoinResetInventory; + public static boolean onJoinResetEnderChest; + public static boolean onLeaveResetMoney; + public static boolean onLeaveResetInventory; + public static boolean onLeaveResetEnderChest; + + // Remove mobs + public static boolean removeMobsOnLogin; + public static boolean removeMobsOnIsland; + public static List removeMobsWhitelist; + + public static boolean makeIslandIfNone; + public static boolean immediateTeleportOnIsland; + public static boolean respawnOnIsland; + public static boolean onlyLeaderCanCoop; + + // Chats + public static boolean teamchatUse; + public static boolean teamchatLog; + public static boolean teamchatIncludeTrust; + public static boolean teamchatIncludeCoop; + //TODO island chat + + public static boolean confirmKick; + public static int confirmKickWait; + public static boolean confirmLeave; + public static int confirmLeaveWait; + public static boolean confirmReset; + public static int confirmResetWait; + + // Deaths + public static int deathsMax; + public static boolean deathsSumTeam; + + /* PROTECTION */ + public static boolean allowPistonPush; + public static boolean restrictWither; + + // Invincible visitors + public static boolean invincibleVisitor; + public static List invincibleVisitorOptions; + + public static List visitorBannedCommands; + public static int togglePvPCooldown; + + //TODO flags + + /* ACID */ + public static boolean acidDamageOp; + public static boolean acidDamageChickens; + + // Damage + public static int acidDamagePlayer; + public static int acidDamageMonster; + public static int acidDamageAnimal; + public static int acidDestroyItemTime; + public static int acidRainDamage; + public static List acidEffects; + + // Protection + public static boolean acidHelmetProtection; + public static boolean acidFullArmorProtection; + + /* SCHEMATICS */ + public static EntityType companionType; + public static List companionNames; + public static List chestItems; + + // TODO added this just to avoid compilation errors, but will be changed in the future + public static List historyMessagesTypes; } diff --git a/src/main/java/us/tastybento/bskyblock/database/IslandsManager.java b/src/main/java/us/tastybento/bskyblock/database/IslandsManager.java index 1b767676a..9bc36aa3f 100755 --- a/src/main/java/us/tastybento/bskyblock/database/IslandsManager.java +++ b/src/main/java/us/tastybento/bskyblock/database/IslandsManager.java @@ -98,7 +98,7 @@ public class IslandsManager { * @param owner UUID */ public Island createIsland(Location location, UUID owner){ - Island island = new Island(location, owner, Settings.protectionRange); + Island island = new Island(location, owner, Settings.islandProtectionRange); islands.put(location, island); if (owner != null) islandsByUUID.put(owner, island); @@ -139,33 +139,6 @@ public class IslandsManager { } } - /** - * Get the island level - * @param playerUUID - * @return Level of island, or null if unknown - */ - public Integer getIslandLevel(UUID playerUUID) { - if (islandsByUUID.containsKey(playerUUID)) - return islandsByUUID.get(playerUUID).getLevel(); - return null; - } - - /** - * Set the island level for this player - * @param playerUUID - * @param islandLevel - * @return true if successful, false if not - */ - public boolean setIslandLevel(UUID playerUUID, int islandLevel) { - if (islandsByUUID.containsKey(playerUUID)) { - islandsByUUID.get(playerUUID).setLevel(islandLevel); - // TODO - //plugin.getChatListener().setPlayerLevel(playerUUID, islandLevel); - return true; - } - return false; - } - /** * Puts a player in a team. Removes them from their old island if required. * @param playerUUID diff --git a/src/main/java/us/tastybento/bskyblock/database/objects/Island.java b/src/main/java/us/tastybento/bskyblock/database/objects/Island.java index a45d5de40..e9a796093 100755 --- a/src/main/java/us/tastybento/bskyblock/database/objects/Island.java +++ b/src/main/java/us/tastybento/bskyblock/database/objects/Island.java @@ -38,8 +38,6 @@ public class Island { private int minProtectedZ; // Protection size private int protectionRange; - // Height of island - private int y; // World the island is in private World world; @@ -67,10 +65,6 @@ public class Island { private boolean isSpawn = false; private boolean purgeProtected = false; - //// Rating //// - private int level; - private int levelHandicap; - //// Protection //// private HashMap flags = new HashMap(); @@ -296,34 +290,6 @@ public class Island { this.purgeProtected = purgeProtected; } - /** - * @return the island level - */ - public int getLevel(){ - return level; - } - - /** - * @param level - the island level to set - */ - public void setLevel(int level){ - this.level = level; - } - - /** - * @return the island level handicap - */ - public int getLevelHandicap(){ - return levelHandicap; - } - - /** - * @param levelHandicap - the island level handicap to set - */ - public void setLevelHandicap(int levelHandicap){ - this.levelHandicap = levelHandicap; - } - /** * Island Guard Settings flags * Covers island, spawn and system settings @@ -582,18 +548,18 @@ public class Island { * Resets the flags to their default as set in config.yml for this island */ public void setFlagsDefaults(){ - for(SettingsFlag flag : SettingsFlag.values()){ + /*for(SettingsFlag flag : SettingsFlag.values()){ this.flags.put(flag, Settings.defaultIslandSettings.get(flag)); - } + }*/ //TODO default flags } /** * Resets the flags to their default as set in config.yml for the spawn */ public void setSpawnFlagsDefaults(){ - for(SettingsFlag flag : SettingsFlag.values()){ + /*for(SettingsFlag flag : SettingsFlag.values()){ this.flags.put(flag, Settings.defaultSpawnSettings.get(flag)); - } + }*/ //TODO default flags } /** diff --git a/src/main/java/us/tastybento/bskyblock/database/objects/Players.java b/src/main/java/us/tastybento/bskyblock/database/objects/Players.java index d03ae5749..1571cd520 100755 --- a/src/main/java/us/tastybento/bskyblock/database/objects/Players.java +++ b/src/main/java/us/tastybento/bskyblock/database/objects/Players.java @@ -26,7 +26,6 @@ public class Players { private int deaths; private HashMap kickedList; - /** * @param uuid * Constructor - initializes the state variables @@ -36,7 +35,7 @@ public class Players { this.uuid = uuid; this.homeLocations = new HashMap(); this.playerName = ""; - this.resetsLeft = Settings.defaultResetLimit; + this.resetsLeft = Settings.resetLimit; this.locale = ""; this.useControlPanel = Settings.useControlPanel; this.kickedList = new HashMap(); @@ -186,8 +185,8 @@ public class Players { */ public void setDeaths(int deaths) { this.deaths = deaths; - if (this.deaths > Settings.maxDeaths) { - this.deaths = Settings.maxDeaths; + if (this.deaths > Settings.deathsMax) { + this.deaths = Settings.deathsMax; } } @@ -196,8 +195,8 @@ public class Players { */ public void addDeath() { this.deaths++; - if (this.deaths > Settings.maxDeaths) { - this.deaths = Settings.maxDeaths; + if (this.deaths > Settings.deathsMax) { + this.deaths = Settings.deathsMax; } } diff --git a/src/main/java/us/tastybento/bskyblock/util/Util.java b/src/main/java/us/tastybento/bskyblock/util/Util.java index 26dd439d7..213443697 100755 --- a/src/main/java/us/tastybento/bskyblock/util/Util.java +++ b/src/main/java/us/tastybento/bskyblock/util/Util.java @@ -36,7 +36,7 @@ public class Util { * @throws InvocationTargetException * @throws NoSuchMethodException */ - public static NMSAbstraction checkVersion() throws ClassNotFoundException, IllegalArgumentException, + public static NMSAbstraction getNMSHandler() throws ClassNotFoundException, IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { String serverPackageName = plugin.getServer().getClass().getPackage().getName(); @@ -44,10 +44,10 @@ public class Util { String version = serverPackageName.substring(serverPackageName.lastIndexOf('.') + 1); Class clazz; try { - clazz = Class.forName(pluginPackageName + ".nms." + version + ".NMSHandler"); + clazz = Class.forName(pluginPackageName + ".util.nms." + version + ".NMSHandler"); } catch (Exception e) { plugin.getLogger().info("No NMS Handler found for " + version + ", falling back to Bukkit API."); - clazz = Class.forName(pluginPackageName + ".nms.fallback.NMSHandler"); + clazz = Class.forName(pluginPackageName + ".util.nms.fallback.NMSHandler"); } // Check if we have a NMSAbstraction implementing class at that location. if (NMSAbstraction.class.isAssignableFrom(clazz)) { diff --git a/src/main/java/us/tastybento/bskyblock/util/placeholders/PlaceholderHandler.java b/src/main/java/us/tastybento/bskyblock/util/placeholders/PlaceholderHandler.java new file mode 100644 index 000000000..7305c2134 --- /dev/null +++ b/src/main/java/us/tastybento/bskyblock/util/placeholders/PlaceholderHandler.java @@ -0,0 +1,102 @@ +package us.tastybento.bskyblock.util.placeholders; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.bukkit.command.CommandSender; + +import us.tastybento.bskyblock.BSkyBlock; + +/** + * Handles hooks with other Placeholder APIs. + * + * @author Poslovitch + * @author Tastybento + */ +public class PlaceholderHandler { + private static final String PACKAGE = "us.tastybento.bskyblock.util.placeholders.hooks."; + /** + * List of API classes in the package specified above (except the Internal one) + */ + private static final String[] HOOKS = { + //TODO + }; + + private static List apis = new ArrayList<>(); + + /** + * Register placeholders and hooks + * @param plugin + */ + public static void register(BSkyBlock plugin){ + // Register placeholders + new Placeholders(plugin); + + // Load Internal Placeholder API + try{ + Class clazz = Class.forName(PACKAGE + "InternalPlaceholderImpl"); + PlaceholderInterface internal = (PlaceholderInterface)clazz.newInstance(); + apis.add(internal); + } catch (Exception e){ + // Should never happen. + plugin.getLogger().severe("Failed to load default placeholder API"); + e.printStackTrace(); + } + + // Load hooks + for(String hook : HOOKS){ + if(plugin.getServer().getPluginManager().isPluginEnabled(hook)){ + try{ + Class clazz = Class.forName(PACKAGE + hook + "PlaceholderImpl"); + PlaceholderInterface api = (PlaceholderInterface)clazz.newInstance(); + if(api.register(plugin)){ + plugin.getLogger().info("Hooked placeholders into " + hook); + apis.add(api); + } else { + plugin.getLogger().info("Failed to hook placeholders into " + hook); + } + } catch (Exception e){ + plugin.getLogger().info("Failed to hook placeholders into " + hook); + e.printStackTrace(); + } + } + } + } + + /** + * Unregister placeholder hooks + * @param plugin + */ + public static void unregister(BSkyBlock plugin){ + Iterator it = apis.iterator(); + while (it.hasNext()) { + PlaceholderInterface api = it.next(); + api.unregister(plugin); + it.remove(); + } + } + + /** + * Replace placeholders in the message according to the receiver + * @param receiver + * @param message + * @return updated message + */ + public static String replacePlaceholders(CommandSender receiver, String message){ + if(message == null || message.isEmpty()) return ""; + + for(PlaceholderInterface api : apis){ + message = api.replacePlaceholders(receiver, message); + } + + return message; + } + + /** + * @return tre if APIs are registered (including Internal), otherwise false + */ + public static boolean hasHooks(){ + return apis != null ? true : false; + } +} diff --git a/src/main/java/us/tastybento/bskyblock/util/placeholders/PlaceholderInterface.java b/src/main/java/us/tastybento/bskyblock/util/placeholders/PlaceholderInterface.java new file mode 100644 index 000000000..59c8a7c74 --- /dev/null +++ b/src/main/java/us/tastybento/bskyblock/util/placeholders/PlaceholderInterface.java @@ -0,0 +1,40 @@ +package us.tastybento.bskyblock.util.placeholders; + +import org.bukkit.command.CommandSender; + +import us.tastybento.bskyblock.BSkyBlock; + +/** + * Simple interface for every Placeholder API. + * + * @author Poslovitch + */ +public interface PlaceholderInterface { + + /** + * Get the name of the Placeholder API + * @return name of the placeholder plugin + */ + String getName(); + + /** + * Register the placeholder API + * @param plugin + * @return true if registered + */ + boolean register(BSkyBlock plugin); + + /** + * Unregister the placeholder API + * @param plugin + */ + void unregister(BSkyBlock plugin); + + /** + * Replace placeholders in the message according to the receiver + * @param sender + * @param message + * @return updated message + */ + String replacePlaceholders(CommandSender receiver, String message); +} \ No newline at end of file diff --git a/src/main/java/us/tastybento/bskyblock/util/placeholders/Placeholders.java b/src/main/java/us/tastybento/bskyblock/util/placeholders/Placeholders.java new file mode 100644 index 000000000..37d3c08ed --- /dev/null +++ b/src/main/java/us/tastybento/bskyblock/util/placeholders/Placeholders.java @@ -0,0 +1,63 @@ +package us.tastybento.bskyblock.util.placeholders; + +import java.util.HashSet; +import java.util.Set; + +import org.bukkit.command.CommandSender; + +import us.tastybento.bskyblock.BSkyBlock; + +/** + * Register placeholders + * + * @author Poslovitch + */ +public class Placeholders { + private static Set placeholders = new HashSet(); + + private BSkyBlock plugin; + + protected Placeholders(BSkyBlock plugin){ + this.plugin = plugin; + register(); + } + + private void register(){ + /* PLUGIN */ + new Placeholder("bsb_name"){ + @Override + public String onRequest(CommandSender receiver) { + return plugin.getDescription().getName(); + } + }; + + new Placeholder("bsb_version") { + + @Override + public String onRequest(CommandSender receiver) { + return plugin.getDescription().getVersion(); + } + }; + + //TODO: add more placeholders + } + + public static Set getPlaceholders(){ + return placeholders; + } + + public abstract class Placeholder{ + private String identifier; + + protected Placeholder(String identifier){ + this.identifier = identifier; + placeholders.add(this); + } + + public String getIdentifier(){ + return identifier; + } + + public abstract String onRequest(CommandSender receiver); + } +} diff --git a/src/main/java/us/tastybento/bskyblock/util/placeholders/hooks/InternalPlaceholderImpl.java b/src/main/java/us/tastybento/bskyblock/util/placeholders/hooks/InternalPlaceholderImpl.java new file mode 100644 index 000000000..7d6069061 --- /dev/null +++ b/src/main/java/us/tastybento/bskyblock/util/placeholders/hooks/InternalPlaceholderImpl.java @@ -0,0 +1,46 @@ +package us.tastybento.bskyblock.util.placeholders.hooks; + +import java.util.regex.Pattern; + +import org.bukkit.command.CommandSender; + +import us.tastybento.bskyblock.BSkyBlock; +import us.tastybento.bskyblock.util.placeholders.PlaceholderInterface; +import us.tastybento.bskyblock.util.placeholders.Placeholders; +import us.tastybento.bskyblock.util.placeholders.Placeholders.Placeholder; + +/** + * Built-in placeholder API + * + * @author Poslovitch + */ +public class InternalPlaceholderImpl implements PlaceholderInterface{ + + @Override + public String getName() { + return "Internal"; + } + + @Override + public boolean register(BSkyBlock plugin) { + return true; + } + + @Override + public void unregister(BSkyBlock plugin) { + // Useless : it would disable the placeholders. + } + + @Override + public String replacePlaceholders(CommandSender receiver, String message) { + if(message == null || message.isEmpty()) return ""; + + for(Placeholder placeholder : Placeholders.getPlaceholders()){ + String identifier = "{" + placeholder.getIdentifier() + "}"; + message = message.replaceAll(Pattern.quote(identifier), placeholder.onRequest(receiver)); + } + + return message; + } + +}