L10nAPI - Reworking API - WIP

Removed the old localization system
Started implementation of the new one

For build reasons, removed protection listeners - they were requiring too much work to update them, and they need to be reworked due to the boilerplate code.
This commit is contained in:
Florian CUNY 2017-12-22 13:22:33 +01:00
parent 2f4136cef4
commit 29dfc313fc
16 changed files with 160 additions and 4108 deletions

View File

@ -1,9 +1,6 @@
package us.tastybento.bskyblock;
import java.util.UUID;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
@ -11,8 +8,6 @@ import org.bukkit.plugin.java.JavaPlugin;
import us.tastybento.bskyblock.api.BSModule;
import us.tastybento.bskyblock.commands.AdminCommand;
import us.tastybento.bskyblock.commands.IslandCommand;
import us.tastybento.bskyblock.config.BSBLocale;
import us.tastybento.bskyblock.config.LocaleManager;
import us.tastybento.bskyblock.config.Settings;
import us.tastybento.bskyblock.database.BSBDatabase;
import us.tastybento.bskyblock.database.managers.PlayersManager;
@ -21,11 +16,8 @@ import us.tastybento.bskyblock.generators.IslandWorld;
import us.tastybento.bskyblock.listeners.JoinLeaveListener;
import us.tastybento.bskyblock.listeners.NetherPortals;
import us.tastybento.bskyblock.listeners.PanelListener;
import us.tastybento.bskyblock.listeners.protection.IslandGuard;
import us.tastybento.bskyblock.listeners.protection.IslandGuard1_8;
import us.tastybento.bskyblock.listeners.protection.IslandGuard1_9;
import us.tastybento.bskyblock.listeners.protection.NetherEvents;
import us.tastybento.bskyblock.managers.CommandsManager;
import us.tastybento.bskyblock.managers.LocalesManager;
import us.tastybento.bskyblock.util.Util;
import us.tastybento.bskyblock.util.nms.NMSAbstraction;
@ -47,8 +39,7 @@ public class BSkyBlock extends JavaPlugin implements BSModule {
// Managers
private CommandsManager commandsManager;
protected LocaleManager localeManager;
private LocalesManager localesManager;
@Override
public void onEnable(){
@ -102,7 +93,8 @@ public class BSkyBlock extends JavaPlugin implements BSModule {
};
Settings.defaultLanguage = "en-US";
localeManager = new LocaleManager(plugin);
localesManager = new LocalesManager(plugin);
localesManager.registerLocales(plugin);
// Register Listeners
registerListeners();
@ -138,11 +130,7 @@ public class BSkyBlock extends JavaPlugin implements BSModule {
PluginManager manager = getServer().getPluginManager();
// Player join events
manager.registerEvents(new JoinLeaveListener(this), this);
manager.registerEvents(new NetherEvents(this), this);
manager.registerEvents(new NetherPortals(this), this);
manager.registerEvents(new IslandGuard(this), this);
manager.registerEvents(new IslandGuard1_8(this), this);
manager.registerEvents(new IslandGuard1_9(this), this);
manager.registerEvents(new PanelListener(this), this);
}
@ -209,22 +197,6 @@ public class BSkyBlock extends JavaPlugin implements BSModule {
return plugin;
}
/**
* @param sender
* @return Locale object for sender
*/
public BSBLocale getLocale(CommandSender sender) {
return localeManager.getLocale(sender);
}
/**
* @param uuid
* @return Locale object for UUID
*/
public BSBLocale getLocale(UUID uuid) {
return localeManager.getLocale(uuid);
}
public NMSAbstraction getNMSHandler() {
NMSAbstraction nmsHandler = null;
try {
@ -239,6 +211,10 @@ public class BSkyBlock extends JavaPlugin implements BSModule {
return commandsManager;
}
public LocalesManager getLocalesManager() {
return localesManager;
}
@Override
public String getIdentifier() {
return getDescription().getName();

View File

@ -3,6 +3,7 @@ package us.tastybento.bskyblock.api.addons;
import us.tastybento.bskyblock.BSkyBlock;
import us.tastybento.bskyblock.api.BSModule;
import us.tastybento.bskyblock.managers.CommandsManager;
import us.tastybento.bskyblock.managers.LocalesManager;
public abstract class BSAddon implements BSModule {
@ -27,6 +28,10 @@ public abstract class BSAddon implements BSModule {
return BSkyBlock.getPlugin().getCommandsManager();
}
public LocalesManager getLocalesManager() {
return BSkyBlock.getPlugin().getLocalesManager();
}
@Override
public String getIdentifier() {
return getDescription().getName();

View File

@ -153,7 +153,7 @@ public class User {
* @param variables - CharSequence target, replacement pairs
*/
public void sendMessage(String reference, String... variables) {
String message = ChatColor.getLastColors(reference) + plugin.getLocale(sender).get(ChatColor.stripColor(reference));
String message = plugin.getLocalesManager().get(sender, reference);
if (variables.length > 1) {
for (int i = 0; i < variables.length; i+=2) {
message.replace(variables[i], variables[i+1]);

View File

@ -0,0 +1,73 @@
package us.tastybento.bskyblock.api.localization;
import org.bukkit.ChatColor;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
/**
* @author Poslovitch, Tastybento
*/
public class BSLocale {
private Locale locale;
private YamlConfiguration config;
private Map<String, String> cache;
public BSLocale(String languageTag, File file) {
this.locale = Locale.forLanguageTag(languageTag);
this.config = YamlConfiguration.loadConfiguration(file);
this.cache = new HashMap<>();
}
/**
* Get text from the yml file for this locale
* @param reference - the YAML node where the text is
* @return Text for this locale reference or the reference if nothing has been found
*/
public String get(String reference) {
if (cache.containsKey(reference)) {
return cache.get(reference);
} else if (config.contains(reference)) {
cache.put(reference, ChatColor.translateAlternateColorCodes('&', config.getString(reference)));
return cache.get(reference);
}
return reference; // return reference in case nothing has been found
}
public void clearCache() {
this.cache.clear();
}
/**
* Returns the locale language
* @return the locale language
*/
public String getLanguage(){
if(locale == null) return "unknown";
return locale.getDisplayLanguage();
}
/**
* Returns the locale country
* @return the locale country
*/
public String getCountry(){
if(locale == null) return "unknown";
return locale.getDisplayCountry();
}
/**
* Returns the locale language tag (e.g: en-GB)
* @return the locale language tag
*/
public String toLanguageTag(){
return this.locale.toLanguageTag();
}
}

View File

@ -33,30 +33,30 @@ public class IslandCreateCommand extends CompositeCommand {
@Override
public boolean execute(User user, String[] args) {
if (getIslands().hasIsland(user.getUniqueId())) {
user.sendMessage(ChatColor.RED + "general.errors.already-have-island");
user.sendMessage("general.errors.already-have-island");
}
if (getPlayers().inTeam(user.getUniqueId())) {
return false;
}
createIsland(user.getPlayer());
createIsland(user);
return true;
}
/**
* Creates an island for player
*
* @param player
* @param user
*/
protected void createIsland(Player player) {
protected void createIsland(User user) {
//TODO: Add panels, make a selection.
try {
NewIsland.builder()
.player(player)
.player(user.getPlayer())
.reason(Reason.CREATE)
.build();
} catch (IOException e) {
plugin.getLogger().severe("Could not create island for player.");
player.sendMessage(ChatColor.RED + plugin.getLocale(player).get("general.errors.general"));
user.sendMessage("general.errors.general");
e.printStackTrace();
}
}

View File

@ -1,125 +0,0 @@
package us.tastybento.bskyblock.config;
import java.io.File;
import java.io.FilenameFilter;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Locale;
import java.util.UUID;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import us.tastybento.bskyblock.util.FileLister;
/**
* Handles locale functions
* @author ben
*
*/
public abstract class AbstractLocaleManager {
private Plugin plugin;
private HashMap<String, BSBLocale> locales = new HashMap<>();
final static String LOCALE_FOLDER = "locales";
public AbstractLocaleManager(Plugin plugin) {
super();
this.plugin = plugin;
this.loadLocales();
}
/**
* Returns an HashMap of locale identifier and the related object
* @return the locales
*/
public HashMap<String, BSBLocale> getLocales(){
return locales;
}
/**
* Set the available locales
* @param locales - the locales to set
*/
public void setLocales(HashMap<String, BSBLocale> locales){
this.locales = locales;
}
/**
* Returns the default locale
* @return the default locale
*/
public BSBLocale getLocale(){
return locales.get(Settings.defaultLanguage);
}
/**
* Returns the locale for the specified CommandSender
* @param sender - CommandSender to get the locale
* @return if sender is a player, the player's locale, otherwise the default locale
*/
public BSBLocale getLocale(CommandSender sender){
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
* @return the locale for this player
*/
public abstract BSBLocale getLocale(UUID player);
/**
* Loads all the locales available. If the locale folder does not exist, one will be created and
* filled with locale files from the jar.
*/
public void loadLocales() {
// Describe the filter - we only want files that are correctly named
FilenameFilter ymlFilter = new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
//plugin.getLogger().info("DEBUG: filename = " + name);
if (name.toLowerCase().startsWith("bsb_") && name.toLowerCase().endsWith(".yml")) {
// See if this is a valid locale
//Locale localeObject = new Locale(name.substring(0, 2), name.substring(3, 5));
Locale localeObject = Locale.forLanguageTag(name.substring(4, name.length() - 4));
if (localeObject == null) {
plugin.getLogger().severe("Filename '" + name + "' is an unknown locale, skipping...");
return false;
}
return true;
} else {
if (name.toLowerCase().endsWith(".yml")) {
plugin.getLogger().severe("Filename '" + name + "' is not in the correct format for a locale file - skipping...");
}
return false;
}
}
};
// Run through the files and store the locales
File localeDir = new File(plugin.getDataFolder(), LOCALE_FOLDER);
// If the folder does not exist, then make it and fill with the locale files from the jar
if (!localeDir.exists()) {
localeDir.mkdir();
FileLister lister = new FileLister(plugin);
try {
for (String name : lister.listJar(LOCALE_FOLDER)) {
plugin.saveResource(name,true);
}
} catch (Exception e) {
e.printStackTrace();
}
}
// Store all the locales available
for (String language : localeDir.list(ymlFilter)) {
try {
BSBLocale locale = new BSBLocale(plugin, language);
locales.put(locale.getLocaleId(), locale);
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
}

View File

@ -1,99 +0,0 @@
package us.tastybento.bskyblock.config;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Locale;
import java.util.ResourceBundle;
import org.bukkit.ChatColor;
import org.bukkit.plugin.Plugin;
public class BSBLocale {
final static String LOCALE_FOLDER = "locales";
private Plugin plugin;
//private String localeId;
private String languageTag;
private ResourceBundle rb;
Locale localeObject;
/**
* Provides localization
* Locale files are .yml and have the filename "bsb_[country and language tag].yml", e.g. bsb_en_GB.yml
* @param plugin
* @throws MalformedURLException
*/
public BSBLocale(Plugin plugin, String localeId) throws MalformedURLException {
this.plugin = plugin;
//this.localeId = localeId;
// Check if the folder exists
File localeDir = new File(plugin.getDataFolder(), LOCALE_FOLDER);
if (!localeDir.exists()) {
localeDir.mkdirs();
}
// Check if this file does not exist
File localeFile = new File(localeDir, localeId);
if (!localeFile.exists()) {
// Does not exist - look in JAR and save if possible
plugin.saveResource(LOCALE_FOLDER + localeId, false);
}
languageTag = localeId.substring(4, localeId.length() - 4).replace('_', '-');
URL[] urls = {localeDir.toURI().toURL()};
ClassLoader loader = new URLClassLoader(urls);
localeObject = Locale.forLanguageTag(languageTag);
rb = ResourceBundle.getBundle("bsb", localeObject, loader, YamlResourceBundle.Control.INSTANCE);
}
/**
* Get text from the yml file for this locale
* @param reference - the YAML node where the text is
* @return Text for this locale reference or the reference is nothing has been found
*/
public String get(String reference) {
// TODO: add placeholder conversion?
//plugin.getLogger().info("DEBUG: default lang = " + Settings.defaultLanguage);
//plugin.getLogger().info("DEBUG: this locale = " + languageTag);
//plugin.getLogger().info("DEBUG: reference = " + reference);
if (rb.containsKey(reference)) {
//plugin.getLogger().info("DEBUG: contains key");
return ChatColor.translateAlternateColorCodes('&', rb.getString(reference));
} else if (!Settings.defaultLanguage.equals(languageTag)){
//plugin.getLogger().info("DEBUG: try default");
// TODO: Try default lang
return reference;
}
plugin.getLogger().severe(reference + " not found in " + languageTag + " or default lang " + Settings.defaultLanguage);
return reference; // Return reference for debug purposes, like for the mods.
}
/**
* Returns the locale language
* @return the locale language
*/
public String getLanguageName(){
if(localeObject == null) return "unknown";
return localeObject.getDisplayLanguage(localeObject);
}
/**
* Returns the locale country
* @return the locale country
*/
public String getCountryName(){
if(localeObject == null) return "unknown";
return localeObject.getDisplayCountry(localeObject);
}
/**
* Returns the locale identifier (e.g: en-GB)
* @return the locale ID
*/
public String getLocaleId(){
return this.localeObject.toLanguageTag();
}
}

View File

@ -1,37 +0,0 @@
package us.tastybento.bskyblock.config;
import java.util.UUID;
import us.tastybento.bskyblock.BSkyBlock;
/**
* Handles the BSkyBlock locale
* @author ben
*
*/
public class LocaleManager extends AbstractLocaleManager {
private BSkyBlock plugin;
public LocaleManager(BSkyBlock plugin) {
super(plugin);
this.plugin = plugin;
}
@Override
/**
* Returns the locale for the specified player
* @param player - Player to get the locale
* @return the locale for this player
*/
public BSBLocale getLocale(UUID player){
//getLogger().info("DEBUG: " + player);
//getLogger().info("DEBUG: " + getPlayers() == null ? "Players is null":"Players in not null");
//getLogger().info("DEBUG: " + getPlayers().getPlayer(player));
//getLogger().info("DEBUG: " + getPlayers().getPlayer(player).getLocale());
String locale = plugin.getPlayers().getPlayer(player).getLocale();
if(locale.isEmpty() || !getLocales().containsKey(locale)) return getLocales().get(Settings.defaultLanguage);
return getLocales().get(locale);
}
}

View File

@ -1,181 +0,0 @@
/*
* https://github.com/akihyro/yaml-resource-bundle
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package us.tastybento.bskyblock.config;
import static java.util.Arrays.asList;
import static java.util.Collections.enumeration;
import static java.util.Collections.unmodifiableList;
import static java.util.stream.Collectors.toMap;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.util.AbstractMap.SimpleImmutableEntry;
import java.util.Enumeration;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Stream;
import org.yaml.snakeyaml.Yaml;
/**
* {@link ResourceBundle} for YAML format.
*/
public class YamlResourceBundle extends ResourceBundle {
/**
* Entries.
*/
private final Map<String, Object> entries;
/**
* Constructor.
*
* @param string YAML data.
*/
public YamlResourceBundle(String string) {
entries = flattenYamlTree(new Yaml().loadAs(string, Map.class));
}
/**
* Constructor.
*
* @param stream YAML data as input stream.
*/
public YamlResourceBundle(InputStream stream) {
entries = flattenYamlTree(new Yaml().loadAs(stream, Map.class));
}
/**
* Constructor.
*
* @param reader YAML data as input character stream.
*/
public YamlResourceBundle(Reader reader) {
entries = flattenYamlTree(new Yaml().loadAs(reader, Map.class));
}
/**
* Flatten yaml tree structure.
*
* @param map {@link Map} of yaml tree.
* @return {@link Map} of entries.
*/
private static Map<String, Object> flattenYamlTree(Map<?, ?> map) {
return map.entrySet().stream()
.flatMap(YamlResourceBundle::flattenYamlTree)
.collect(toMap(
e -> e.getKey(),
e -> e.getValue(),
(oldValue, newValue) -> newValue
));
}
/**
* Flatten yaml tree structure.
*
* @param entry {@link Entry} of yaml tree.
* @return {@link Stream} of entries
*/
private static Stream<Entry<String, Object>> flattenYamlTree(Entry<?, ?> entry) {
String key = entry.getKey().toString();
Object value = entry.getValue();
if (value instanceof Map) {
Map<?, ?> valueAsMap = (Map<?, ?>) value;
return valueAsMap.entrySet().stream()
.flatMap(YamlResourceBundle::flattenYamlTree)
.map(e -> new SimpleImmutableEntry<>(key + "." + e.getKey(), e.getValue()));
} else if (value instanceof List) {
List<?> valueAsList = (List<?>) value;
value = valueAsList.stream().toArray(String[]::new);
AtomicInteger index = new AtomicInteger();
return Stream.concat(
Stream.of(new SimpleImmutableEntry<>(key, value)),
valueAsList.stream()
.map(v -> new SimpleImmutableEntry<>(key + "[" + index.getAndIncrement() + "]", v))
);
}
return Stream.of(new SimpleImmutableEntry<>(key, value));
}
/** {@inheritDoc} */
@Override
protected Set<String> handleKeySet() {
return entries.keySet();
}
/** {@inheritDoc} */
@Override
public Enumeration<String> getKeys() {
return enumeration(keySet());
}
/** {@inheritDoc} */
@Override
protected Object handleGetObject(String key) {
return entries.get(key);
}
/**
* {@link ResourceBundle.Control} for YAML format.
*/
public static class Control extends ResourceBundle.Control {
/**
* Singleton instance.
*/
public static final Control INSTANCE = new Control();
/**
* Constructor.
*/
protected Control() {
}
/** {@inheritDoc} */
@Override
public List<String> getFormats(String baseName) {
return unmodifiableList(asList("yaml", "yml"));
}
/** {@inheritDoc} */
@Override
public ResourceBundle newBundle(String baseName,
Locale locale, String format, ClassLoader loader, boolean reload)
throws IllegalAccessException, InstantiationException, IOException {
if (!getFormats(baseName).contains(format)) {
return null;
}
String bundleName = toBundleName(baseName, locale);
String resourceName = toResourceName(bundleName, format);
InputStream stream = loader.getResourceAsStream(resourceName);
try {
return stream != null ? new YamlResourceBundle(stream) : null;
} finally {
if (stream != null) {
stream.close();
}
}
}
}
}

View File

@ -623,10 +623,11 @@ public class IslandsManager {
//home.getChunk().load();
player.teleport(home);
//player.sendBlockChange(home, Material.GLOWSTONE, (byte)0);
User user = User.getInstance(player);
if (number == 1) {
player.sendMessage(plugin.getLocale(player.getUniqueId()).get("island.teleport").replace("[label]", Settings.ISLANDCOMMAND));
user.sendMessage("island.teleport", "[label]", Settings.ISLANDCOMMAND);
} else {
player.sendMessage(plugin.getLocale(player.getUniqueId()).get("island.teleported").replace("[number]", String.valueOf(number)));
user.sendMessage("island.teleported", "[number]", String.valueOf(number));
}
// Exit spectator mode if in it
if (player.getGameMode().equals(GameMode.SPECTATOR)) {

View File

@ -1,206 +0,0 @@
package us.tastybento.bskyblock.listeners.protection;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.player.PlayerInteractAtEntityEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
import us.tastybento.bskyblock.BSkyBlock;
import us.tastybento.bskyblock.config.Settings;
import us.tastybento.bskyblock.database.objects.Island;
import us.tastybento.bskyblock.database.objects.Island.SettingsFlag;
import us.tastybento.bskyblock.util.Util;
/**
* @author tastybento
* Provides protection to islands - handles newer events that may not
* exist in older servers
*/
public class IslandGuard1_8 implements Listener {
private final BSkyBlock plugin;
private final static boolean DEBUG = false;
public IslandGuard1_8(final BSkyBlock plugin) {
this.plugin = plugin;
}
/**
* Checks if action is allowed for player in location for flag
* @param player
* @param location
* @param flag
* @return true if allowed
*/
private boolean actionAllowed(Player player, Location location, SettingsFlag flag) {
// This permission bypasses protection
if (player.hasPermission(Settings.PERMPREFIX + "mod.bypassprotect")) {
return true;
}
Island island = plugin.getIslands().getProtectedIslandAt(location);
if (island != null && (island.getFlag(flag) || island.getMembers().contains(player.getUniqueId()))){
return true;
}
if (island == null && Settings.defaultWorldSettings.get(flag)) {
return true;
}
return false;
}
/**
* Handle interaction with armor stands V1.8
* Note - some armor stand protection is done in IslandGuard.java, e.g. against projectiles.
*
* @param e
*/
@EventHandler(priority = EventPriority.LOW, ignoreCancelled=true)
public void onPlayerInteract(final PlayerInteractAtEntityEvent e) {
if (DEBUG) {
plugin.getLogger().info("1.8 " + e.getEventName());
}
if (!Util.inWorld(e.getPlayer())) {
return;
}
if (e.getRightClicked() != null && e.getRightClicked().getType().equals(EntityType.ARMOR_STAND)) {
if (actionAllowed(e.getPlayer(), e.getRightClicked().getLocation(), SettingsFlag.ARMOR_STAND)) {
return;
}
e.setCancelled(true);
e.getPlayer().sendMessage(plugin.getLocale(e.getPlayer().getUniqueId()).get("island.protected"));
}
}
/**
* Handle V1.8 blocks that need special treatment
* Tilling of coarse dirt into dirt
* Usually prevented because it could lead to an endless supply of dirt with gravel
*
* @param e
*/
@SuppressWarnings("deprecation")
@EventHandler(priority = EventPriority.LOW, ignoreCancelled=true)
public void onPlayerInteract(final PlayerInteractEvent e) {
if (DEBUG) {
plugin.getLogger().info("1.8 " + e.getEventName());
}
if (!e.getAction().equals(Action.RIGHT_CLICK_BLOCK)) {
return;
}
if (!Util.inWorld(e.getPlayer())) {
return;
}
// This permission bypasses protection
if (e.getPlayer().hasPermission(Settings.PERMPREFIX + "mod.bypassprotect")) {
return;
}
// Prevents tilling of coarse dirt into dirt
ItemStack inHand = e.getPlayer().getItemInHand();
if (inHand.getType() == Material.WOOD_HOE || inHand.getType() == Material.IRON_HOE || inHand.getType() == Material.GOLD_HOE
|| inHand.getType() == Material.DIAMOND_HOE || inHand.getType() == Material.STONE_HOE) {
// plugin.getLogger().info("1.8 " + "DEBUG: hoe in hand");
Block block = e.getClickedBlock();
// plugin.getLogger().info("1.8 " + "DEBUG: block is " + block.getType() +
// ":" + block.getData());
// Check if coarse dirt
if (block.getType() == Material.DIRT && block.getData() == (byte) 1) {
// plugin.getLogger().info("1.8 " + "DEBUG: hitting coarse dirt!");
e.setCancelled(true);
}
}
}
// Armor stand events
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled=true)
void placeArmorStandEvent(PlayerInteractEvent e) {
Player p = e.getPlayer();
if (DEBUG) {
plugin.getLogger().info("1.8 " + "Armor stand place " + e.getEventName());
}
if (!Util.inWorld(p)) {
return;
}
if (p.hasPermission(Settings.PERMPREFIX + "mod.bypassprotect")) {
// You can do anything if you are Op
return;
}
// Check if they are holding armor stand
for (ItemStack inHand : Util.getPlayerInHandItems(e.getPlayer())) {
if (inHand.getType().equals(Material.ARMOR_STAND)) {
// Check island
Island island = plugin.getIslands().getIslandAt(e.getPlayer().getLocation());
if (island == null && Settings.defaultWorldSettings.get(SettingsFlag.PLACE_BLOCKS)) {
return;
}
if (island !=null && (island.getMembers().contains(p.getUniqueId()) || island.getFlag(SettingsFlag.PLACE_BLOCKS))) {
//plugin.getLogger().info("1.8 " + "DEBUG: armor stand place check");
if (Settings.limitedBlocks.containsKey("ARMOR_STAND") && Settings.limitedBlocks.get("ARMOR_STAND") > -1) {
//plugin.getLogger().info("1.8 " + "DEBUG: count armor stands");
int count = island.getTileEntityCount(Material.ARMOR_STAND,e.getPlayer().getWorld());
//plugin.getLogger().info("1.8 " + "DEBUG: count is " + count + " limit is " + Settings.limitedBlocks.get("ARMOR_STAND"));
if (Settings.limitedBlocks.get("ARMOR_STAND") <= count) {
e.getPlayer().sendMessage((plugin.getLocale(e.getPlayer().getUniqueId()).get("moblimits.entity").replace("[entity]",
Util.prettifyText(Material.ARMOR_STAND.toString()))).replace("[number]", String.valueOf(Settings.limitedBlocks.get("ARMOR_STAND"))));
e.setCancelled(true);
return;
}
}
return;
}
// plugin.getLogger().info("1.8 " + "DEBUG: stand place cancelled");
e.setCancelled(true);
e.getPlayer().sendMessage(plugin.getLocale(e.getPlayer().getUniqueId()).get("island.protected"));
e.getPlayer().updateInventory();
}
}
}
@EventHandler(priority = EventPriority.LOW, ignoreCancelled=true)
public void ArmorStandDestroy(EntityDamageByEntityEvent e) {
if (DEBUG) {
plugin.getLogger().info("1.8 " + "IslandGuard New " + e.getEventName());
}
if (!(e.getEntity() instanceof LivingEntity)) {
return;
}
if (!Util.inWorld(e.getEntity())) {
return;
}
final LivingEntity livingEntity = (LivingEntity) e.getEntity();
if (!livingEntity.getType().equals(EntityType.ARMOR_STAND)) {
return;
}
if (e.getDamager() instanceof Player) {
Player p = (Player) e.getDamager();
if (p.hasPermission(Settings.PERMPREFIX + "mod.bypassprotect")) {
return;
}
// Check if on island
if (plugin.getIslands().playerIsOnIsland(p)) {
return;
}
// Check island
Island island = plugin.getIslands().getIslandAt(e.getEntity().getLocation());
if (island == null && Settings.defaultWorldSettings.get(SettingsFlag.BREAK_BLOCKS)) {
return;
}
if (island != null && island.getFlag(SettingsFlag.BREAK_BLOCKS)) {
return;
}
p.sendMessage(plugin.getLocale(p.getUniqueId()).get("island.protected"));
e.setCancelled(true);
}
}
}

View File

@ -1,474 +0,0 @@
package us.tastybento.bskyblock.listeners.protection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Animals;
import org.bukkit.entity.EnderCrystal;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.IronGolem;
import org.bukkit.entity.Monster;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.entity.Slime;
import org.bukkit.entity.Snowman;
import org.bukkit.entity.Squid;
import org.bukkit.entity.Villager;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.EntityBlockFormEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.entity.LingeringPotionSplashEvent;
import org.bukkit.event.player.PlayerInteractAtEntityEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.projectiles.ProjectileSource;
import us.tastybento.bskyblock.BSkyBlock;
import us.tastybento.bskyblock.config.Settings;
import us.tastybento.bskyblock.database.objects.Island;
import us.tastybento.bskyblock.database.objects.Island.SettingsFlag;
import us.tastybento.bskyblock.generators.IslandWorld;
import us.tastybento.bskyblock.util.Util;
/**
* @author tastybento
* Provides protection to islands - handles newer events that may not
* exist in older servers
*/
public class IslandGuard1_9 implements Listener {
private final BSkyBlock plugin;
private final static boolean DEBUG = false;
private HashMap<Integer, UUID> thrownPotions;
public IslandGuard1_9(final BSkyBlock plugin) {
this.plugin = plugin;
this.thrownPotions = new HashMap<>();
}
/**
* Handles Frost Walking on visitor's islands
* @param e
*/
@EventHandler(priority = EventPriority.LOW, ignoreCancelled=true)
public void onBlockForm(EntityBlockFormEvent e) {
if (DEBUG) {
plugin.getLogger().info("1.9 " +e.getEventName());
}
if (e.getEntity() instanceof Player && e.getNewState().getType().equals(Material.FROSTED_ICE)) {
Player player= (Player) e.getEntity();
if (!Util.inWorld(player)) {
return;
}
// This permission bypasses protection
if (player.hasPermission(Settings.PERMPREFIX + "mod.bypassprotect")) {
return;
}
// Check island
Island island = plugin.getIslands().getIslandAt(player.getLocation());
if (island == null && Settings.defaultWorldSettings.get(SettingsFlag.PLACE_BLOCKS)) {
return;
}
if (island !=null) {
if (island.getMembers().contains(player.getUniqueId()) || island.getFlag(SettingsFlag.PLACE_BLOCKS)) {
return;
}
}
// Silently cancel the event
e.setCancelled(true);
}
}
/**
* Handle interaction with end crystals 1.9
*
* @param e
*/
@EventHandler(priority = EventPriority.LOW, ignoreCancelled=true)
public void onHitEndCrystal(final PlayerInteractAtEntityEvent e) {
if (DEBUG) {
plugin.getLogger().info("1.9 " +e.getEventName());
}
if (!Util.inWorld(e.getPlayer())) {
return;
}
// This permission bypasses protection
if (e.getPlayer().hasPermission(Settings.PERMPREFIX + "mod.bypassprotect")) {
return;
}
if (e.getRightClicked() != null && e.getRightClicked().getType().equals(EntityType.ENDER_CRYSTAL)) {
// Check island
Island island = plugin.getIslands().getIslandAt(e.getRightClicked().getLocation());
if (island == null && Settings.defaultWorldSettings.get(SettingsFlag.BREAK_BLOCKS)) {
return;
}
if (island !=null) {
if (island.getMembers().contains(e.getPlayer().getUniqueId()) || island.getFlag(SettingsFlag.BREAK_BLOCKS)) {
return;
}
}
e.setCancelled(true);
e.getPlayer().sendMessage(plugin.getLocale(e.getPlayer()).get("island.protected"));
}
}
// End crystal
@SuppressWarnings("deprecation")
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled=true)
void placeEndCrystalEvent(PlayerInteractEvent e) {
Player p = e.getPlayer();
if (DEBUG) {
plugin.getLogger().info("1.9 " +"End crystal place " + e.getEventName());
}
if (!Util.inWorld(p)) {
return;
}
if (p.hasPermission(Settings.PERMPREFIX + "mod.bypassprotect")) {
// You can do anything if you are Op
return;
}
// Check if they are holding armor stand
for (ItemStack inHand : Util.getPlayerInHandItems(e.getPlayer())) {
if (inHand.getType().equals(Material.END_CRYSTAL)) {
// Check island
Island island = plugin.getIslands().getIslandAt(e.getPlayer().getLocation());
if (island == null && Settings.defaultWorldSettings.get(SettingsFlag.PLACE_BLOCKS)) {
return;
}
if (island !=null && (island.getMembers().contains(p.getUniqueId()) || island.getFlag(SettingsFlag.PLACE_BLOCKS))) {
//plugin.getLogger().info("1.9 " +"DEBUG: armor stand place check");
if (Settings.limitedBlocks.containsKey("END_CRYSTAL") && Settings.limitedBlocks.get("END_CRYSTAL") > -1) {
//plugin.getLogger().info("1.9 " +"DEBUG: count armor stands");
int count = island.getTileEntityCount(Material.END_CRYSTAL,e.getPlayer().getWorld());
//plugin.getLogger().info("1.9 " +"DEBUG: count is " + count + " limit is " + Settings.limitedBlocks.get("ARMOR_STAND"));
if (Settings.limitedBlocks.get("END_CRYSTAL") <= count) {
e.getPlayer().sendMessage((plugin.getLocale(e.getPlayer().getUniqueId()).get("moblimits.entity").replace("[entity]",
Util.prettifyText(Material.END_CRYSTAL.toString()))).replace("[number]", String.valueOf(Settings.limitedBlocks.get("END_CRYSTAL"))));
e.setCancelled(true);
return;
}
}
return;
}
// plugin.getLogger().info("1.9 " +"DEBUG: stand place cancelled");
e.setCancelled(true);
e.getPlayer().sendMessage(plugin.getLocale(e.getPlayer()).get("island.protected"));
e.getPlayer().updateInventory();
}
}
}
/**
* Handle end crystal damage by visitors
* @param e
*/
@EventHandler(priority = EventPriority.LOW, ignoreCancelled=true)
public void EndCrystalDamage(EntityDamageByEntityEvent e) {
if (DEBUG) {
plugin.getLogger().info("1.9 " +"IslandGuard 1_9 " + e.getEventName());
plugin.getLogger().info("1.9 " +"Entity is " + e.getEntityType());
}
if (e.getEntity() == null || !Util.inWorld(e.getEntity())) {
return;
}
if (!(e.getEntity() instanceof EnderCrystal)) {
if (DEBUG) {
plugin.getLogger().info("1.9 Entity is not End crystal it is " + e.getEntityType());
}
return;
}
if (DEBUG) {
plugin.getLogger().info("1.9 Damager is " + e.getDamager());
}
Player p = null;
if (e.getDamager() instanceof Player) {
p = (Player) e.getDamager();
if (DEBUG) {
plugin.getLogger().info("1.9 Damager is a player");
}
} else if (e.getDamager() instanceof Projectile) {
// Get the shooter
Projectile projectile = (Projectile)e.getDamager();
ProjectileSource shooter = projectile.getShooter();
if (shooter instanceof Player) {
p = (Player)shooter;
}
if (DEBUG) {
plugin.getLogger().info("1.9 " +"Damager is a projectile shot by " + p.getName());
}
}
if (p != null) {
if (p.hasPermission(Settings.PERMPREFIX + "mod.bypassprotect")) {
if (DEBUG) {
plugin.getLogger().info("1.9 " +"Bypassing protection");
}
return;
}
// Check if on island
if (plugin.getIslands().playerIsOnIsland(p)) {
if (DEBUG) {
plugin.getLogger().info("1.9 " +"Player is on their own island");
}
return;
}
// Check island
Island island = plugin.getIslands().getIslandAt(e.getEntity().getLocation());
if (island == null && Settings.defaultWorldSettings.get(SettingsFlag.BREAK_BLOCKS)) {
return;
}
if (island != null && island.getFlag(SettingsFlag.BREAK_BLOCKS)) {
if (DEBUG) {
plugin.getLogger().info("1.9 " +"Visitor is allowed to break blocks");
}
return;
}
p.sendMessage(plugin.getLocale(p).get("island.protected"));
e.setCancelled(true);
}
}
/**
* Handles end crystal explosions
* @param e
*/
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onExplosion(final EntityExplodeEvent e) {
if (DEBUG) {
plugin.getLogger().info("1.9 " +e.getEventName());
plugin.getLogger().info("1.9 " +"Entity exploding is " + e.getEntity());
}
if (e.getEntity() == null || !e.getEntityType().equals(EntityType.ENDER_CRYSTAL)) {
if (DEBUG) {
plugin.getLogger().info("1.9 " +"Entity is not an END CRYSTAL");
}
return;
}
if (!Util.inWorld(e.getLocation())) {
return;
}
// General settings irrespective of whether this is allowed or not
if (!Settings.allowTNTDamage) {
plugin.getLogger().info("1.9 " +"TNT block damage prevented");
e.blockList().clear();
} else {
if (!Settings.allowChestDamage) {
List<Block> toberemoved = new ArrayList<>();
// Save the chest blocks in a list
for (Block b : e.blockList()) {
switch (b.getType()) {
case CHEST:
case ENDER_CHEST:
case STORAGE_MINECART:
case TRAPPED_CHEST:
toberemoved.add(b);
break;
default:
break;
}
}
// Now delete them
for (Block b : toberemoved) {
e.blockList().remove(b);
}
}
}
// prevent at spawn
if (plugin.getIslands().isAtSpawn(e.getLocation())) {
e.blockList().clear();
e.setCancelled(true);
}
}
/**
* Handle blocks that need special treatment
* Tilling of coarse dirt into dirt using off-hand (regular hand is in 1.8)
* Usually prevented because it could lead to an endless supply of dirt with gravel
*
* @param e
*/
@SuppressWarnings("deprecation")
@EventHandler(priority = EventPriority.LOW, ignoreCancelled=true)
public void onPlayerInteract(final PlayerInteractEvent e) {
if (DEBUG) {
plugin.getLogger().info("1.9 " + e.getEventName());
}
if (!e.getAction().equals(Action.RIGHT_CLICK_BLOCK)) {
return;
}
if (!Util.inWorld(e.getPlayer())) {
return;
}
// This permission bypasses protection
if (e.getPlayer().hasPermission(Settings.PERMPREFIX + "mod.bypassprotect")) {
return;
}
// Prevents tilling of coarse dirt into dirt
ItemStack inHand = e.getPlayer().getInventory().getItemInOffHand();
if (inHand.getType() == Material.WOOD_HOE || inHand.getType() == Material.IRON_HOE || inHand.getType() == Material.GOLD_HOE
|| inHand.getType() == Material.DIAMOND_HOE || inHand.getType() == Material.STONE_HOE) {
// plugin.getLogger().info("1.8 " + "DEBUG: hoe in hand");
Block block = e.getClickedBlock();
// plugin.getLogger().info("1.8 " + "DEBUG: block is " + block.getType() +
// ":" + block.getData());
// Check if coarse dirt
if (block.getType() == Material.DIRT && block.getData() == (byte) 1) {
// plugin.getLogger().info("1.8 " + "DEBUG: hitting coarse dirt!");
e.setCancelled(true);
}
}
}
@EventHandler(priority = EventPriority.LOW, ignoreCancelled=true)
public void onLingeringPotionSplash(final LingeringPotionSplashEvent e) {
if (DEBUG) {
plugin.getLogger().info("1.9 " + e.getEventName());
plugin.getLogger().info("1.9 entity = " + e.getEntity());
plugin.getLogger().info("1.9 entity type = " + e.getEntityType());
plugin.getLogger().info("1.9 radius = " + e.getAreaEffectCloud().getRadius());
plugin.getLogger().info("1.9 id = " + e.getAreaEffectCloud().getEntityId());
plugin.getLogger().info("1.9 hit entity = " + e.getHitEntity());
}
if (!Util.inWorld(e.getEntity().getLocation())) {
return;
}
// Try to get the shooter
Projectile projectile = e.getEntity();
plugin.getLogger().info("shooter = " + projectile.getShooter());
if (projectile.getShooter() != null && projectile.getShooter() instanceof Player) {
UUID uuid = ((Player)projectile.getShooter()).getUniqueId();
// Store it and remove it when the effect is gone
thrownPotions.put(e.getAreaEffectCloud().getEntityId(), uuid);
plugin.getServer().getScheduler().runTaskLater(plugin, () -> thrownPotions.remove(e.getAreaEffectCloud().getEntityId()), e.getAreaEffectCloud().getDuration());
}
}
@EventHandler(priority = EventPriority.LOW, ignoreCancelled=true)
public void onLingeringPotionDamage(final EntityDamageByEntityEvent e) {
if (DEBUG) {
plugin.getLogger().info("1.9 lingering potion damage " + e.getEventName());
plugin.getLogger().info("1.9 lingering potion entity = " + e.getEntity());
plugin.getLogger().info("1.9 lingering potion entity type = " + e.getEntityType());
plugin.getLogger().info("1.9 lingering potion cause = " + e.getCause());
plugin.getLogger().info("1.9 lingering potion damager = " + e.getDamager());
}
if (!Util.inWorld(e.getEntity().getLocation())) {
return;
}
if (e.getEntity() == null || e.getEntity().getUniqueId() == null) {
return;
}
if (e.getCause().equals(DamageCause.ENTITY_ATTACK) && thrownPotions.containsKey(e.getDamager().getEntityId())) {
UUID attacker = thrownPotions.get(e.getDamager().getEntityId());
// Self damage
if (attacker.equals(e.getEntity().getUniqueId())) {
if (DEBUG)
plugin.getLogger().info("DEBUG: Self damage from lingering potion!");
return;
}
Island island = plugin.getIslands().getIslandAt(e.getEntity().getLocation());
boolean inNether = false;
if (e.getEntity().getWorld().equals(IslandWorld.getNetherWorld())) {
inNether = true;
}
// Monsters being hurt
if (e.getEntity() instanceof Monster || e.getEntity() instanceof Slime || e.getEntity() instanceof Squid) {
// Normal island check
if (island != null && island.getMembers().contains(attacker)) {
// Members always allowed
return;
}
if (actionAllowed(attacker, e.getEntity().getLocation(), SettingsFlag.HURT_MONSTERS)) {
return;
}
// Not allowed
e.setCancelled(true);
return;
}
// Mobs being hurt
if (e.getEntity() instanceof Animals || e.getEntity() instanceof IronGolem || e.getEntity() instanceof Snowman
|| e.getEntity() instanceof Villager) {
if (island != null && (island.getFlag(SettingsFlag.HURT_ANIMALS) || island.getMembers().contains(attacker))) {
return;
}
if (DEBUG)
plugin.getLogger().info("DEBUG: Mobs not allowed to be hurt. Blocking");
e.setCancelled(true);
return;
}
// Establish whether PVP is allowed or not.
boolean pvp = false;
if ((inNether && island != null && island.getFlag(SettingsFlag.PVP_NETHER) || (!inNether && island != null && island.getFlag(SettingsFlag.PVP_OVERWORLD)))) {
if (DEBUG) plugin.getLogger().info("DEBUG: PVP allowed");
pvp = true;
}
// Players being hurt PvP
if (e.getEntity() instanceof Player) {
if (!pvp) {
if (DEBUG) plugin.getLogger().info("DEBUG: PVP not allowed");
e.setCancelled(true);
}
}
}
}
/**
* Checks if action is allowed for player in location for flag
* @param uuid
* @param location
* @param flag
* @return true if allowed
*/
private boolean actionAllowed(UUID uuid, Location location, SettingsFlag flag) {
Player player = plugin.getServer().getPlayer(uuid);
if (player == null) {
return actionAllowed(location, flag);
}
// This permission bypasses protection
if (player.hasPermission(Settings.PERMPREFIX + "mod.bypassprotect")) {
return true;
}
Island island = plugin.getIslands().getProtectedIslandAt(location);
if (island != null && (island.getFlag(flag) || island.getMembers().contains(player.getUniqueId()))){
return true;
}
if (island == null && Settings.defaultWorldSettings.get(flag)) {
return true;
}
return false;
}
/**
* Action allowed in this location
* @param location
* @param flag
* @return true if allowed
*/
private boolean actionAllowed(Location location, SettingsFlag flag) {
Island island = plugin.getIslands().getProtectedIslandAt(location);
if (island != null && island.getFlag(flag)){
return true;
}
if (island == null && Settings.defaultWorldSettings.get(flag)) {
return true;
}
return false;
}
}

View File

@ -1,226 +0,0 @@
package us.tastybento.bskyblock.listeners.protection;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World.Environment;
import org.bukkit.block.BlockState;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Vehicle;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.entity.EntityPortalEvent;
import org.bukkit.event.player.PlayerBucketEmptyEvent;
import org.bukkit.event.world.StructureGrowEvent;
import org.bukkit.util.Vector;
import us.tastybento.bskyblock.BSkyBlock;
import us.tastybento.bskyblock.config.Settings;
import us.tastybento.bskyblock.generators.IslandWorld;
import us.tastybento.bskyblock.util.SafeSpotTeleport;
public class NetherEvents implements Listener {
private final BSkyBlock plugin;
private final static boolean DEBUG = false;
public NetherEvents(BSkyBlock plugin) {
this.plugin = plugin;
}
/**
* This handles non-player portal use
* Currently disables portal use by entities
*
* @param event
*/
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void onEntityPortal(EntityPortalEvent event) {
if (DEBUG)
plugin.getLogger().info("DEBUG: nether portal entity " + event.getFrom().getBlock().getType());
// If the nether is disabled then quit immediately
if (!Settings.netherGenerate || IslandWorld.getNetherWorld() == null) {
return;
}
if (event.getEntity() == null) {
return;
}
if (event.getFrom() != null && event.getFrom().getBlock().getType().equals(Material.ENDER_PORTAL)) {
event.setCancelled(true);
// Same action for all worlds except the end itself
if (!event.getFrom().getWorld().getEnvironment().equals(Environment.THE_END)) {
if (plugin.getServer().getWorld(Settings.worldName + "_the_end") != null) {
// The end exists
Location end_place = plugin.getServer().getWorld(Settings.worldName + "_the_end").getSpawnLocation();
event.getEntity().teleport(end_place);
if (DEBUG)
plugin.getLogger().info("DEBUG: Result teleported " + event.getEntityType() + " to " + end_place);
return;
}
}
return;
}
Location currentLocation = event.getFrom().clone();
String currentWorld = currentLocation.getWorld().getName();
// Only operate if this is Island territory
if (!currentWorld.equalsIgnoreCase(Settings.worldName) && !currentWorld.equalsIgnoreCase(Settings.worldName + "_nether")) {
return;
}
// No entities may pass with the old nether
if (!Settings.netherIslands) {
event.setCancelled(true);
return;
}
// New nether
// Entities can pass only if there are adjoining portals
Location dest = event.getFrom().toVector().toLocation(IslandWorld.getIslandWorld());
if (event.getFrom().getWorld().getEnvironment().equals(Environment.NORMAL)) {
dest = event.getFrom().toVector().toLocation(IslandWorld.getNetherWorld());
}
// Vehicles
if (event.getEntity() instanceof Vehicle) {
Vehicle vehicle = (Vehicle)event.getEntity();
vehicle.eject();
}
new SafeSpotTeleport(plugin, event.getEntity(), dest);
event.setCancelled(true);
}
// Nether portal spawn protection
/**
* Function to check proximity to nether spawn location
*
* @param player
* @return true if in the spawn area, false if not
*/
private boolean awayFromSpawn(Player player) {
Vector p = player.getLocation().toVector().multiply(new Vector(1, 0, 1));
Vector spawn = player.getWorld().getSpawnLocation().toVector().multiply(new Vector(1, 0, 1));
return spawn.distanceSquared(p) < (Settings.netherSpawnRadius * Settings.netherSpawnRadius);
}
/**
* Prevents blocks from being broken
*
* @param e
*/
@EventHandler(priority = EventPriority.LOW)
public void onBlockBreak(final BlockBreakEvent e) {
if (DEBUG)
plugin.getLogger().info("DEBUG: " + e.getEventName());
// plugin.getLogger().info("Block break");
if ((e.getPlayer().getWorld().getName().equalsIgnoreCase(Settings.worldName + "_nether") && !Settings.netherIslands)
|| e.getPlayer().getWorld().getName().equalsIgnoreCase(Settings.worldName + "_the_end")) {
if (e.getPlayer().hasPermission(Settings.PERMPREFIX + "mod.bypassprotect")) {
return;
}
if (DEBUG)
plugin.getLogger().info("Block break in island nether");
if (!awayFromSpawn(e.getPlayer()) && !e.getPlayer().isOp()) {
e.getPlayer().sendMessage(plugin.getLocale(e.getPlayer()).get("nether.spawnisprotected"));
e.setCancelled(true);
}
}
}
/**
* Prevents placing of blocks
*
* @param e
*/
@EventHandler(priority = EventPriority.LOW)
public void onPlayerBlockPlace(final BlockPlaceEvent e) {
if (DEBUG)
plugin.getLogger().info("DEBUG: " + e.getEventName());
if (!Settings.netherIslands) {
if (e.getPlayer().getWorld().getName().equalsIgnoreCase(Settings.worldName + "_nether")
|| e.getPlayer().getWorld().getName().equalsIgnoreCase(Settings.worldName + "_the_end")) {
if (e.getPlayer().hasPermission(Settings.PERMPREFIX + "mod.bypassprotect")) {
return;
}
if (!awayFromSpawn(e.getPlayer()) && !e.getPlayer().isOp()) {
e.setCancelled(true);
}
}
}
}
@EventHandler(priority = EventPriority.LOW)
public void onBucketEmpty(final PlayerBucketEmptyEvent e) {
if (DEBUG)
plugin.getLogger().info("DEBUG: " + e.getEventName());
if (!Settings.netherIslands) {
if (e.getPlayer().getWorld().getName().equalsIgnoreCase(Settings.worldName + "_nether")
|| e.getPlayer().getWorld().getName().equalsIgnoreCase(Settings.worldName + "_the_end")) {
if (e.getPlayer().hasPermission(Settings.PERMPREFIX + "mod.bypassprotect")) {
return;
}
if (!awayFromSpawn(e.getPlayer()) && !e.getPlayer().isOp()) {
e.setCancelled(true);
}
}
}
}
/**
* Prevent the Nether spawn from being blown up
*
* @param e
*/
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onExplosion(final EntityExplodeEvent e) {
if (Settings.netherIslands) {
// Not used in the new nether
return;
}
// Find out what is exploding
Entity expl = e.getEntity();
if (expl == null) {
return;
}
// Check world
if (!e.getEntity().getWorld().getName().equalsIgnoreCase(Settings.worldName + "_nether")
|| e.getEntity().getWorld().getName().equalsIgnoreCase(Settings.worldName + "_the_end")) {
return;
}
Location spawn = e.getLocation().getWorld().getSpawnLocation();
Location loc = e.getLocation();
if (spawn.distance(loc) < Settings.netherSpawnRadius) {
e.blockList().clear();
}
}
/**
* Converts trees to gravel and glowstone
*
* @param e
*/
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onTreeGrow(final StructureGrowEvent e) {
if (DEBUG)
plugin.getLogger().info("DEBUG: " + e.getEventName());
if (!Settings.netherTrees) {
return;
}
if (!Settings.netherGenerate || IslandWorld.getNetherWorld() == null) {
return;
}
// Check world
if (!e.getLocation().getWorld().equals(IslandWorld.getNetherWorld())) {
return;
}
for (BlockState b : e.getBlocks()) {
if (b.getType() == Material.LOG || b.getType() == Material.LOG_2) {
b.setType(Material.GRAVEL);
} else if (b.getType() == Material.LEAVES || b.getType() == Material.LEAVES_2) {
b.setType(Material.GLOWSTONE);
}
}
}
}

View File

@ -1,162 +0,0 @@
package us.tastybento.bskyblock.listeners.protection;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.entity.EntityPickupItemEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import us.tastybento.bskyblock.BSkyBlock;
import us.tastybento.bskyblock.config.Settings;
import us.tastybento.bskyblock.database.objects.Island;
import us.tastybento.bskyblock.database.objects.Island.SettingsFlag;
import us.tastybento.bskyblock.util.Util;
/**
* @author tastybento
* Provides protection to islands
*/
public class VisitorGuard implements Listener {
private final BSkyBlock plugin;
private static final boolean DEBUG = false;
public VisitorGuard(final BSkyBlock plugin) {
this.plugin = plugin;
}
/*
* Prevent dropping items if player dies on another island
* This option helps reduce the down side of dying due to traps, etc.
* Also handles muting of death messages
*/
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onVisitorDeath(final PlayerDeathEvent e) {
if (DEBUG) {
plugin.getLogger().info(e.getEventName());
}
if (!Util.inWorld(e.getEntity())) {
return;
}
// Mute death messages
if (Settings.muteDeathMessages) {
e.setDeathMessage(null);
}
// If visitors will keep items and their level on death. This overrides any global settings.
// If the player is not a visitor then they die and lose everything - sorry :-(
Island island = plugin.getIslands().getProtectedIslandAt(e.getEntity().getLocation());
if (island != null && !island.getMembers().contains(e.getEntity().getUniqueId()) && island.getFlag(SettingsFlag.KEEP_INVENTORY)) {
// They are a visitor
InventorySave.getInstance().savePlayerInventory(e.getEntity());
e.getDrops().clear();
e.setKeepLevel(true);
e.setDroppedExp(0);
}
}
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onVisitorSpawn(final PlayerRespawnEvent e) {
if (DEBUG) {
plugin.getLogger().info(e.getEventName());
}
// If the player died on an island and his inventory has been saved, give it him back. This will override any global settings.
if (InventorySave.isStored(e.getPlayer().getUniqueId())) {
InventorySave.getInstance().loadPlayerInventory(e.getPlayer());
InventorySave.getInstance().clearSavedInventory(e.getPlayer());
}
}
/*
* Prevent item drop by visitors
*/
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onVisitorDrop(final PlayerDropItemEvent e) {
if (DEBUG) {
plugin.getLogger().info(e.getEventName());
}
if (!Util.inWorld(e.getPlayer())) {
return;
}
Island island = plugin.getIslands().getIslandAt(e.getItemDrop().getLocation());
if ((island != null && island.getFlag(SettingsFlag.ITEM_DROP))
|| e.getPlayer().hasPermission(Settings.PERMPREFIX + "mod.bypassprotect")
|| plugin.getIslands().locationIsOnIsland(e.getPlayer(), e.getItemDrop().getLocation())) {
return;
}
e.getPlayer().sendMessage(plugin.getLocale(e.getPlayer()).get("island.protected"));
e.setCancelled(true);
}
/**
* Prevents visitors from getting damage if invinciblevisitors option is set to TRUE
* @param e
*/
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onVisitorReceiveDamage(EntityDamageEvent e){
if(!Settings.invincibleVisitor) return;
if(!(e.getEntity() instanceof Player)) return;
Player p = (Player) e.getEntity();
if (!Util.inWorld(p) || plugin.getIslands().locationIsOnIsland(p, p.getLocation())) return;
if (Settings.invincibleVisitorOptions.contains(e.getCause())) e.setCancelled(true);
else if(e.getCause().equals(DamageCause.VOID)) {
if(plugin.getPlayers().hasIsland(p.getUniqueId())) {
Location safePlace = plugin.getIslands().getSafeHomeLocation(p.getUniqueId(), 1);
if (safePlace != null) {
p.teleport(safePlace);
// Set their fall distance to zero otherwise they crash onto their island and die
p.setFallDistance(0);
e.setCancelled(true);
return;
}
}
// No island, or no safe spot on island
if (plugin.getIslands().getSpawn() != null) {
p.teleport(plugin.getIslands().getSpawnPoint());
// Set their fall distance to zero otherwise they crash onto their island and die
p.setFallDistance(0);
e.setCancelled(true);
return;
}
// No island spawn, try regular spawn
if (!p.performCommand("spawn")) {
// If this command doesn't work, let them die otherwise they may get trapped in the void forever
return;
}
// Set their fall distance to zero otherwise they crash onto their island and die
p.setFallDistance(0);
e.setCancelled(true);
}
}
/*
* Prevent item pickup by visitors
*/
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onVisitorPickup(final EntityPickupItemEvent e) {
if (DEBUG) {
plugin.getLogger().info(e.getEventName());
}
if (e.getEntity() instanceof Player) {
Player player = (Player)e.getEntity();
if (!Util.inWorld(player)) {
return;
}
Island island = plugin.getIslands().getIslandAt(e.getItem().getLocation());
if ((island != null && island.getFlag(SettingsFlag.ITEM_PICKUP))
|| player.hasPermission(Settings.PERMPREFIX + "mod.bypassprotect")
|| plugin.getIslands().locationIsOnIsland(player, e.getItem().getLocation())) {
return;
}
e.setCancelled(true);
}
}
}

View File

@ -0,0 +1,64 @@
package us.tastybento.bskyblock.managers;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import us.tastybento.bskyblock.BSkyBlock;
import us.tastybento.bskyblock.api.BSModule;
import us.tastybento.bskyblock.api.localization.BSLocale;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
* @author Poslovitch
*/
public final class LocalesManager {
private BSkyBlock plugin;
private Map<BSModule, List<BSLocale>> locales;
public LocalesManager(BSkyBlock plugin) {
this.plugin = plugin;
this.locales = new HashMap<>();
}
public String get(CommandSender sender, String reference) {
if (sender instanceof Player) {
return get(((Player)sender).getUniqueId(), reference);
}
return reference; //TODO
}
public String get(UUID uuid, String reference) {
return reference; //TODO
}
public Map<BSModule, List<BSLocale>> getLocales() {
return locales;
}
public List<BSLocale> getLocales(BSModule module) {
return locales.get(module);
}
public BSLocale getLocale(BSModule module, String languageTag) {
for (BSLocale locale : locales.get(module)) {
if (locale.toLanguageTag().equals(languageTag)) return locale;
}
return null;
}
public void registerLocales(BSModule module) {
//TODO
}
public void registerLocale(BSModule module, String languageTag) {
//TODO
}
public void registerExternalLocale(BSModule originModule, BSModule targetModule, String languageTag) {
//TODO
}
}