Improvements

1) Refactoring
2) Fixed entity names (issue #26)
3) Customized messages on per-permission basis
This commit is contained in:
t3hk0d3 2012-06-07 18:37:58 +04:00
parent 7892227261
commit 46464c38d0
8 changed files with 429 additions and 227 deletions

View File

@ -18,7 +18,6 @@
*/
package ru.tehkode.modifyworld;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.configuration.ConfigurationSection;
@ -26,7 +25,8 @@ import org.bukkit.entity.*;
import org.bukkit.event.Listener;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.Plugin;
import ru.tehkode.permissions.PermissionManager;
import ru.tehkode.permissions.PermissionGroup;
import ru.tehkode.permissions.PermissionUser;
import ru.tehkode.permissions.bukkit.PermissionsEx;
/**
@ -35,61 +35,48 @@ import ru.tehkode.permissions.bukkit.PermissionsEx;
*/
public abstract class ModifyworldListener implements Listener {
public final static String PERMISSION_DENIED = "Sorry, you don't have enough permissions";
protected String permissionDenied = PERMISSION_DENIED;
protected PermissionManager permissionsManager;
protected PlayerInformer informer;
protected ConfigurationSection config;
protected boolean informPlayers = false;
protected boolean useMaterialNames = true;
protected boolean checkMetadata = false;
protected boolean checkItemUse = false;
protected boolean enableWhitelist = false;
public ModifyworldListener(Plugin plugin, ConfigurationSection config) {
this.permissionsManager = PermissionsEx.getPermissionManager();
public ModifyworldListener(Plugin plugin, ConfigurationSection config, PlayerInformer informer) {
this.informer = informer;
this.config = config;
this.registerEvents(plugin);
this.informPlayers = config.getBoolean("informPlayers", informPlayers);
this.permissionDenied = config.getString("messages.permissionDenied", this.permissionDenied);
this.useMaterialNames = config.getBoolean("use-material-names", useMaterialNames);
this.checkMetadata = config.getBoolean("check-metadata", checkMetadata);
this.checkItemUse = config.getBoolean("item-use-check", checkItemUse);
this.enableWhitelist = config.getBoolean("whitelist", enableWhitelist);
}
protected void informPlayer(Player player, String message) {
if (this.informPlayers) {
player.sendMessage(ChatColor.RED + message);
}
}
private String getEntityName(Entity entity) {
protected void informPlayerAboutDenial(Player player) {
this.informPlayer(player, this.permissionDenied);
}
protected String getEntityName(Entity entity) {
if (entity instanceof ComplexEntityPart) {
return getEntityName(((ComplexEntityPart)entity).getParent());
return getEntityName(((ComplexEntityPart) entity).getParent());
}
String entityName = entity.getType().toString().toLowerCase().replace("_", "");
if (entity instanceof Item) {
entityName = getItemPermission(((Item) entity).getItemStack());
}
if (entity instanceof Player) {
return "player." + ((Player) entity).getName();
} else if (entity instanceof Tameable) {
Tameable animal = (Tameable) entity;
return "animal." + entityName+ (animal.isTamed() ? "." + ((Player) animal.getOwner()).getName() : "");
return "animal." + entityName + (animal.isTamed() ? "." + ((Player) animal.getOwner()).getName() : "");
}
EntityCategory category = EntityCategory.fromEntity(entity);
if (category == null) {
@ -100,32 +87,84 @@ public abstract class ModifyworldListener implements Listener {
}
// Functional programming fuck yeah
protected String getMaterialPermission(Material type) {
private String getMaterialPermission(Material type) {
return this.useMaterialNames ? type.name().toLowerCase().replace("_", "") : Integer.toString(type.getId());
}
protected String getMaterialPermission(Material type, byte metadata) {
return this.getMaterialPermission(type) + (metadata > 0 ? ":" + metadata : "");
}
protected String getItemPermission(ItemStack item) {
return this.getMaterialPermission(item.getType(), item.getData().getData());
}
protected String getBlockPermission(Block block) {
return this.getMaterialPermission(block.getType(), block.getData());
private String getMaterialPermission(Material type, byte metadata) {
return getMaterialPermission(type) + (metadata > 0 ? ":" + metadata : "");
}
protected boolean canInteractWithMaterial(Player player, String basePermission, Material type) {
return player.hasPermission(basePermission + this.getMaterialPermission(type));
private String getBlockPermission(Block block) {
return getMaterialPermission(block.getType(), block.getData());
}
protected boolean canInteractWithItem(Player player, String basePermission, ItemStack item) {
return player.hasPermission(basePermission + this.getMaterialPermission(item.getType(), item.getData().getData()));
public String getItemPermission(ItemStack item) {
return getMaterialPermission(item.getType(), item.getData().getData());
}
protected boolean canInteractWithBlock(Player player, String basePermission, Block block) {
return player.hasPermission(basePermission + this.getMaterialPermission(block.getType(), block.getData()));
/*
protected boolean permissionDenied(Player player, String basePermission, Entity entity) {
if (entity instanceof Player && PermissionsEx.isAvailable()) {
PermissionUser entityUser = PermissionsEx.getUser((Player)entity);
for (PermissionGroup group : entityUser.getGroups()) {
if (permissionDenied(player, basePermission, "group", group.getName())) {
return true;
}
}
return permissionDenied(player, basePermission, "player", entityUser.getName());
}
return permissionDenied(player, basePermission, entity);
}
*/
protected boolean permissionDenied(Player player, String basePermission, Object... arguments) {
String permission = assemblePermission(basePermission, arguments);
boolean isDenied = !player.hasPermission(permission);
if (isDenied) {
this.informer.informPlayer(player, permission, arguments);
}
return isDenied;
}
protected boolean _permissionDenied(Player player, String permission, Object... arguments) {
return !player.hasPermission(assemblePermission(permission, arguments));
}
protected String assemblePermission(String permission, Object... arguments) {
StringBuilder builder = new StringBuilder(permission);
if (arguments != null) {
for (Object obj : arguments) {
if (obj == null) {
continue;
}
builder.append('.');
builder.append(getObjectPermission(obj));
}
}
return builder.toString();
}
protected String getObjectPermission(Object obj) {
if (obj instanceof Entity) {
return (getEntityName((Entity) obj));
} else if (obj instanceof ItemStack) {
return (getItemPermission((ItemStack) obj));
} else if (obj instanceof Material) {
return (getMaterialPermission((Material) obj));
} else if (obj instanceof Block) {
return (getBlockPermission((Block) obj));
}
return (obj.toString());
}
private void registerEvents(Plugin plugin) {

View File

@ -0,0 +1,172 @@
package ru.tehkode.modifyworld;
import java.util.HashMap;
import java.util.Map;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.ComplexEntityPart;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Item;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import ru.tehkode.permissions.PermissionUser;
import ru.tehkode.permissions.bukkit.PermissionsEx;
public class PlayerInformer {
public final static String PERMISSION_DENIED = "Sorry, you don't have enough permissions";
public final static String WHITELIST_MESSAGE = "You are not allowed to join this server. Goodbye!";
public final static String PROHIBITED_ITEM = "Prohibited item \"%s\" has been removed from your inventory.";
public final static String DEFAULT_MESSAGE_FORMAT = "&f[&2Modifyworld&f]&4 %s";
// Default message format
protected String messageFormat = DEFAULT_MESSAGE_FORMAT;
protected Map<String, String> messages = new HashMap<String, String>();
// Flags
protected boolean enabled = false;
protected boolean individualMessages = false;
protected String defaultMessage = PERMISSION_DENIED;
public PlayerInformer(ConfigurationSection config) {
this.enabled = config.getBoolean("inform-players", enabled);
this.loadConfig(config.getConfigurationSection("messages"));
}
private void loadConfig(ConfigurationSection config) {
this.defaultMessage = config.getString("default-message", this.defaultMessage);
this.messageFormat = config.getString("message-format", this.messageFormat);
this.individualMessages = config.getBoolean("individual-messages", this.individualMessages);
this.importMessages(config);
for (String permission : config.getKeys(true)) {
if (!config.isString(permission)) {
continue;
}
setMessage(permission, config.getString(permission.replace("/", ".")));
}
}
public void setMessage(String permission, String message) {
messages.put(permission, message);
}
public String getMessage(String permission) {
if (messages.containsKey(permission)) {
return messages.get(permission);
}
String perm = permission;
int index;
while ((index = perm.lastIndexOf(".")) != -1) {
perm = perm.substring(0, index);
if (messages.containsKey(perm)) {
String message = messages.get(perm);
messages.put(permission, message);
return message;
}
}
return this.defaultMessage;
}
public String getMessage(Player player, String permission) {
if (PermissionsEx.isAvailable()) {
PermissionUser user = PermissionsEx.getUser(player);
String message;
String perm = permission;
int index;
while ((index = perm.lastIndexOf(".")) != -1) {
perm = perm.substring(0, index);
message = user.getOption("permission-denied-" + perm, player.getWorld().getName(), null);
if (message == null) {
continue;
}
return message;
}
message = user.getOption("permission-denied", player.getWorld().getName(), null);
if (message != null) {
return message;
}
}
return getMessage(permission);
}
public void informPlayer(Player player, String permission, Object... args) {
if (!enabled) {
return;
}
String message = getMessage(player, permission).replace("$permission", permission);
for (int i = 0; i < args.length; i++) {
message = message.replace("$" + (i + 1), describeObject(args[i]));
}
if (message != null && !message.isEmpty()) {
player.sendMessage(String.format(messageFormat, message).replaceAll("&([a-z0-9])", "\u00A7$1"));
}
}
protected String describeObject(Object obj) {
if (obj instanceof ComplexEntityPart) { // Complex entities
return describeObject(((ComplexEntityPart) obj).getParent());
} else if (obj instanceof Item) { // Dropped items
return describeMaterial(((Item) obj).getItemStack().getType());
} else if (obj instanceof ItemStack) { // Items
return describeMaterial(((ItemStack) obj).getType());
} else if (obj instanceof Entity) { // Entities
return ((Entity) obj).getType().toString().toLowerCase().replace("_", " ");
} else if (obj instanceof Block) { // Blocks
return describeMaterial(((Block) obj).getType());
} else if (obj instanceof Material) { // Just material
return describeMaterial((Material) obj);
}
return obj.toString();
}
private String describeMaterial(Material material) {
// TODO: implement data id
if (material == Material.INK_SACK) {
return "dye";
}
return material.toString().toLowerCase().replace("_", " ");
}
// For backward compatibility
private void importMessages(ConfigurationSection config) {
// This should NOT be refactored, because it would be stupid :D
if (config.isString("whitelistMessage")) {
setMessage("modifyworld.login", config.getString("whitelistMessage"));
config.set("whitelistMessage", null);
}
if (config.isString("prohibitedItem")) {
setMessage("modifyworld.items.have", config.getString("prohibitedItem"));
config.set("prohibitedItem", null);
}
if (config.isString("permissionDenied")) {
setMessage("modifyworld", config.getString("permissionDenied"));
config.set("permissionDenied", null);
}
}
}

View File

@ -18,16 +18,19 @@
*/
package ru.tehkode.modifyworld.bukkit;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import org.bukkit.configuration.Configuration;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import ru.tehkode.modifyworld.ModifyworldListener;
import ru.tehkode.modifyworld.PlayerInformer;
import ru.tehkode.modifyworld.handlers.*;
import ru.tehkode.permissions.bukkit.PermissionsEx;
@ -36,8 +39,7 @@ import ru.tehkode.permissions.bukkit.PermissionsEx;
* @author t3hk0d3
*/
public class Modifyworld extends JavaPlugin {
protected final static Logger logger = Logger.getLogger("Minecraft");
protected final static Class<? extends ModifyworldListener>[] LISTENERS = new Class[]{
PlayerListener.class,
EntityListener.class,
@ -45,76 +47,109 @@ public class Modifyworld extends JavaPlugin {
VehicleListener.class
};
protected List<ModifyworldListener> listeners = new ArrayList<ModifyworldListener>();
public Modifyworld() {
protected PlayerInformer informer;
protected File configFile;
protected FileConfiguration config;
@Override
public void onLoad() {
configFile = new File(this.getDataFolder(), "config.yml");
}
@Override
public void onEnable() {
// At first check PEX existance
if (!PermissionsEx.isAvailable()) {
logger.severe("[Modifyworld] PermissionsEx not found, disabling");
this.getLogger().severe("PermissionsEx not found, disabling");
this.getPluginLoader().disablePlugin(this);
return;
}
FileConfiguration config = this.getConfig();
if (!config.isBoolean("enable")) { // Migrate
this.config = this.getConfig();
if (!config.isConfigurationSection("messages")) {
this.getLogger().severe("Deploying default config");
this.initializeConfiguration(config);
}
if (config.getBoolean("enable", false)) {
this.registerListeners();
logger.info("[Modifyworld] Modifyworld enabled!");
} else {
logger.info("[Modifyworld] Modifyworld disabled. Check config.yml!");
this.getPluginLoader().disablePlugin(this);
}
this.informer = new PlayerInformer(config);
this.registerListeners();
this.getLogger().info("Modifyworld enabled!");
this.saveConfig();
}
@Override
public void onDisable() {
this.listeners.clear();
logger.info("[Modifyworld] Modifyworld disabled!");
}
protected void initializeConfiguration(FileConfiguration config) {
// At migrate and setup defaults
PermissionsEx pex = (PermissionsEx) this.getServer().getPluginManager().getPlugin("PermissionsEx");
Configuration pexConfig = pex.getConfig();
this.config = null;
this.getLogger().info("Modifyworld successfully disabled!");
}
protected void initializeConfiguration(FileConfiguration config) {
// Flags
config.set("enable", pexConfig.get("permissions.modifyworld.enabled", false));
config.set("itemRestrictions", pexConfig.getBoolean("permissions.modifyworld.itemRestrictions", false));
config.set("informPlayers", pexConfig.getBoolean("permissions.informplayers.modifyworld", false));
config.set("whitelist", pexConfig.getBoolean("permissions.modifyworld.whitelist", false));
config.set("use-material-names", pexConfig.getBoolean("permissions.modifyworld.use-material-names", true));
config.set("drop-restricted-item", pexConfig.getBoolean("permissions.modifyworld.drop-restricted-item", false));
config.set("item-use-check", pexConfig.getBoolean("permissions.modifyworld.item-use-check", false));
config.set("item-restrictions", false);
config.set("inform-players", false);
config.set("whitelist", false);
config.set("use-material-names", true);
config.set("drop-restricted-item", false);
config.set("item-use-check", false);
// Messages
config.set("messages.whitelistMessage", pexConfig.getString("permissions.modifyworld.whitelistMessage", PlayerListener.WHITELIST_MESSAGE));
config.set("messages.prohibitedItem", PlayerListener.PROHIBITED_ITEM);
config.set("messages.permissionDenied", ModifyworldListener.PERMISSION_DENIED);
config.set("messages/message-format", PlayerInformer.DEFAULT_MESSAGE_FORMAT);
config.set("messages/default-message", PlayerInformer.PERMISSION_DENIED);
// Predefined messages
config.set("messages/modifyworld.login", PlayerInformer.WHITELIST_MESSAGE);
config.set("messages/modifyworld.items.have", PlayerInformer.PROHIBITED_ITEM);
}
protected void registerListeners() {
for (Class listenerClass : LISTENERS) {
try {
Constructor constructor = listenerClass.getConstructor(Plugin.class, ConfigurationSection.class);
ModifyworldListener listener = (ModifyworldListener) constructor.newInstance(this, this.getConfig());
Constructor constructor = listenerClass.getConstructor(Plugin.class, ConfigurationSection.class, PlayerInformer.class);
ModifyworldListener listener = (ModifyworldListener) constructor.newInstance(this, this.getConfig(), this.informer);
this.listeners.add(listener);
} catch (Throwable e) {
logger.warning("[Modifyworld] Failed to initialize \"" + listenerClass.getName() + "\" listener");
this.getLogger().warning("Failed to initialize \"" + listenerClass.getName() + "\" listener");
e.printStackTrace();
}
}
}
@Override
public FileConfiguration getConfig() {
if (this.config == null) {
this.loadConfig();
}
return this.config;
}
@Override
public void saveConfig() {
try {
this.config.save(configFile);
} catch (IOException e) {
this.getLogger().severe("Failed to save configuration file: " + e.getMessage());
}
}
protected void loadConfig() {
this.config = new YamlConfiguration();
config.options().pathSeparator('/');
this.getLogger().info("Loading configuration - " + this.configFile.getAbsolutePath());
try {
config.load(configFile);
} catch (FileNotFoundException e) {
this.getLogger().severe("Configuration file not found - deploying default one");
} catch (Exception e) {
this.getLogger().severe("Failed to load configuration file: " + e.getMessage());
}
}
}

View File

@ -29,6 +29,7 @@ import org.bukkit.event.painting.PaintingBreakEvent;
import org.bukkit.event.painting.PaintingPlaceEvent;
import org.bukkit.plugin.Plugin;
import ru.tehkode.modifyworld.ModifyworldListener;
import ru.tehkode.modifyworld.PlayerInformer;
/**
*
@ -36,22 +37,20 @@ import ru.tehkode.modifyworld.ModifyworldListener;
*/
public class BlockListener extends ModifyworldListener {
public BlockListener(Plugin plugin, ConfigurationSection config) {
super(plugin, config);
public BlockListener(Plugin plugin, ConfigurationSection config, PlayerInformer informer) {
super(plugin, config, informer);
}
@EventHandler(priority = EventPriority.LOW)
public void onBlockBreak(BlockBreakEvent event) {
if (!canInteractWithBlock(event.getPlayer(), "modifyworld.blocks.destroy.", event.getBlock())) {
informPlayerAboutDenial(event.getPlayer());
if (permissionDenied(event.getPlayer(), "modifyworld.blocks.destroy.", event.getBlock())) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOW)
public void onBlockPlace(BlockPlaceEvent event) {
if (!canInteractWithBlock(event.getPlayer(), "modifyworld.blocks.place.", event.getBlock())) {
informPlayerAboutDenial(event.getPlayer());
if (permissionDenied(event.getPlayer(), "modifyworld.blocks.place.", event.getBlock())) {
event.setCancelled(true);
}
}
@ -64,17 +63,14 @@ public class BlockListener extends ModifyworldListener {
PaintingBreakByEntityEvent pbee = (PaintingBreakByEntityEvent) event;
if (pbee.getRemover() instanceof Player
&& !canInteractWithMaterial((Player) pbee.getRemover(), "modifyworld.blocks.destroy.", Material.PAINTING)) {
informPlayerAboutDenial((Player) pbee.getRemover());
&& permissionDenied((Player) pbee.getRemover(), "modifyworld.blocks.destroy.", Material.PAINTING)) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOW)
public void onPaintingPlace(PaintingPlaceEvent event) {
if (!canInteractWithMaterial(event.getPlayer(), "modifyworld.blocks.place.", Material.PAINTING)) {
informPlayerAboutDenial(event.getPlayer());
if (permissionDenied(event.getPlayer(), "modifyworld.blocks.place.", Material.PAINTING)) {
event.setCancelled(true);
}
}

View File

@ -18,7 +18,6 @@
*/
package ru.tehkode.modifyworld.handlers;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
@ -26,8 +25,7 @@ import org.bukkit.event.entity.*;
import org.bukkit.plugin.Plugin;
import org.bukkit.configuration.ConfigurationSection;
import ru.tehkode.modifyworld.ModifyworldListener;
import ru.tehkode.permissions.PermissionGroup;
import ru.tehkode.permissions.PermissionUser;
import ru.tehkode.modifyworld.PlayerInformer;
/**
*
@ -35,8 +33,8 @@ import ru.tehkode.permissions.PermissionUser;
*/
public class EntityListener extends ModifyworldListener {
public EntityListener(Plugin plugin, ConfigurationSection config) {
super(plugin, config);
public EntityListener(Plugin plugin, ConfigurationSection config, PlayerInformer informer) {
super(plugin, config, informer);
}
@EventHandler(priority = EventPriority.LOW)
@ -47,8 +45,7 @@ public class EntityListener extends ModifyworldListener {
Player player;
if (edbe.getDamager() instanceof Player) { // Prevent from damaging by player
player = (Player) edbe.getDamager();
if (!canMessWithEntity(player, "modifyworld.damage.deal.", event.getEntity())) {
informPlayerAboutDenial(player);
if (permissionDenied(player, "modifyworld.damage.deal", event.getEntity())) {
cancelDamageEvent(player, event);
return;
}
@ -57,7 +54,7 @@ public class EntityListener extends ModifyworldListener {
if (edbe.getEntity() instanceof Player) {
player = (Player) edbe.getEntity();
if (edbe.getDamager() != null) { // Prevent from taking damage by entity
if (!canMessWithEntity(player, "modifyworld.damage.take.", edbe.getDamager())) {
if (_permissionDenied(player, "modifyworld.damage.take", edbe.getDamager())) {
cancelDamageEvent(player, event);
return;
}
@ -67,9 +64,7 @@ public class EntityListener extends ModifyworldListener {
} else if (event.getEntity() instanceof Player) { // player are been damaged by enviroment
Player player = (Player) event.getEntity();
String cause = event.getCause().name().toLowerCase().replace("_", "");
if (!player.hasPermission("modifyworld.damage.take." + cause)) {
if (_permissionDenied(player, "modifyworld.damage.take", event.getCause().name().toLowerCase().replace("_", ""))) {
cancelDamageEvent(player, event);
return;
}
@ -89,9 +84,8 @@ public class EntityListener extends ModifyworldListener {
Player player = (Player) event.getOwner();
if (!player.hasPermission("modifyworld.tame." + getEntityName(event.getEntity()))) {
if (permissionDenied(player, "modifyworld.tame", event.getEntity())) {
event.setCancelled(true);
informPlayerAboutDenial(player);
}
}
@ -99,29 +93,11 @@ public class EntityListener extends ModifyworldListener {
public void onEntityTarget(EntityTargetEvent event) {
if (event.getTarget() instanceof Player) {
Player player = (Player) event.getTarget();
if (!player.hasPermission("modifyworld.mobtarget." + getEntityName(event.getEntity()))) {
if (_permissionDenied(player, "modifyworld.mobtarget", event.getEntity())) {
event.setCancelled(true);
}
}
}
protected boolean canMessWithEntity(Player player, String basePermission, Entity entity) {
if (entity instanceof Player) {
PermissionUser entityUser = permissionsManager.getUser(((Player) entity).getName());
if (entityUser == null) {
return false;
}
for (PermissionGroup group : entityUser.getGroups()) {
if (player.hasPermission(basePermission + "group." + group.getName())) {
return true;
}
}
return player.hasPermission(basePermission + "player." + entityUser.getName());
}
return player.hasPermission(basePermission + getEntityName(entity));
}
}

View File

@ -19,8 +19,6 @@
package ru.tehkode.modifyworld.handlers;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player;
@ -35,8 +33,9 @@ import org.bukkit.event.player.*;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.Plugin;
import org.bukkit.util.Vector;
import ru.tehkode.modifyworld.ModifyworldListener;
import ru.tehkode.permissions.PermissionUser;
import ru.tehkode.modifyworld.PlayerInformer;
/**
*
@ -44,19 +43,13 @@ import ru.tehkode.permissions.PermissionUser;
*/
public class PlayerListener extends ModifyworldListener {
public final static String WHITELIST_MESSAGE = "You are not allowed to join this server. Goodbye!";
public final static String PROHIBITED_ITEM = "You have prohibited item \"%s\".";
protected boolean checkInventory = false;
protected boolean dropRestrictedItem = false;
protected String whitelistKickMessage = WHITELIST_MESSAGE;
protected String prohibitedItemMessage = PROHIBITED_ITEM;
public PlayerListener(Plugin plugin, ConfigurationSection config) {
super(plugin, config);
public PlayerListener(Plugin plugin, ConfigurationSection config, PlayerInformer informer) {
super(plugin, config, informer);
this.whitelistKickMessage = config.getString("messages.whitelistMessage", this.whitelistKickMessage);
this.prohibitedItemMessage = config.getString("messages.prohibitedItem", this.prohibitedItemMessage);
this.checkInventory = config.getBoolean("itemRestrictions", this.checkInventory);
this.checkInventory = config.getBoolean("item-restrictions", this.checkInventory);
this.dropRestrictedItem = config.getBoolean("drop-restricted-item", this.dropRestrictedItem);
}
@ -65,7 +58,7 @@ public class PlayerListener extends ModifyworldListener {
public void onPlayerSneak(PlayerToggleSneakEvent event) {
Player player = event.getPlayer();
if (event.isSneaking() && !player.hasPermission("modifyworld.sneak")) {
if (event.isSneaking() && _permissionDenied(player, "modifyworld.sneak")) {
event.setCancelled(true);
event.getPlayer().setSneaking(false);
}
@ -75,29 +68,12 @@ public class PlayerListener extends ModifyworldListener {
public void onPlayerSprint(PlayerToggleSprintEvent event) {
Player player = event.getPlayer();
if (event.isSprinting() && !player.hasPermission("modifyworld.sprint")) {
if (event.isSprinting() && _permissionDenied(player, "modifyworld.sprint")) {
event.setCancelled(true);
event.getPlayer().setSprinting(false);
}
}
@EventHandler(priority = EventPriority.LOW)
public void onPlayerPreLogin(PlayerPreLoginEvent event) {
if (!enableWhitelist) {
return;
}
PermissionUser user = this.permissionsManager.getUser(event.getName());
String worldName = Bukkit.getServer().getWorlds().get(0).getName();
if (user != null && !user.has("modifyworld.login", worldName)) {
String whiteListMessage = user.getOption("kick-message", worldName, this.whitelistKickMessage);
event.disallow(PlayerPreLoginEvent.Result.KICK_WHITELIST, whiteListMessage);
Logger.getLogger("Minecraft").info("Player \"" + user.getName() + "\" were kicked by Modifyworld - lack of modifyworld.login permission");
}
}
@EventHandler(priority = EventPriority.LOW)
public void onPlayerLogin(PlayerLoginEvent event) {
@ -105,22 +81,18 @@ public class PlayerListener extends ModifyworldListener {
return;
}
PermissionUser user = this.permissionsManager.getUser(event.getPlayer());
String worldName = Bukkit.getServer().getWorlds().get(0).getName();
if (user != null && !user.has("modifyworld.login", worldName)) {
String whiteListMessage = user.getOption("kick-message", worldName, this.whitelistKickMessage);
event.disallow(PlayerLoginEvent.Result.KICK_WHITELIST, whiteListMessage);
Logger.getLogger("Minecraft").info("Player \"" + user.getName() + "\" were kicked by Modifyworld - lack of modifyworld.login permission");
Player player = event.getPlayer();
if (_permissionDenied(player, "modifyworld.login")) {
// String whiteListMessage = user.getOption("kick-message", worldName, this.whitelistKickMessage);
event.disallow(PlayerLoginEvent.Result.KICK_WHITELIST, informer.getMessage(player, "modifyworld.login"));
Logger.getLogger("Minecraft").info("Player \"" + player.getName() + "\" were kicked by Modifyworld - lack of 'modifyworld.login' permission");
}
}
@EventHandler(priority = EventPriority.LOW)
public void onPlayerBedEnter(PlayerBedEnterEvent event) {
if (!event.getPlayer().hasPermission("modifyworld.usebeds")) {
informPlayer(event.getPlayer(), ChatColor.RED + "Sorry, you don't have enough permissions");
if (permissionDenied(event.getPlayer(), "modifyworld.usebeds")) {
event.setCancelled(true);
}
}
@ -128,8 +100,7 @@ public class PlayerListener extends ModifyworldListener {
@EventHandler(priority = EventPriority.LOW)
public void onPlayerBucketEmpty(PlayerBucketEmptyEvent event) {
String bucketName = event.getBucket().toString().toLowerCase().replace("_bucket", ""); // WATER_BUCKET -> water
if (!event.getPlayer().hasPermission("modifyworld.bucket.empty." + bucketName)) {
informPlayerAboutDenial(event.getPlayer());
if (permissionDenied(event.getPlayer(), "modifyworld.bucket.empty", bucketName)) {
event.setCancelled(true);
}
}
@ -137,31 +108,29 @@ public class PlayerListener extends ModifyworldListener {
@EventHandler(priority = EventPriority.LOW)
public void onPlayerBucketFill(PlayerBucketFillEvent event) {
String materialName = event.getBlockClicked().getType().toString().toLowerCase().replace("stationary_", ""); // STATIONARY_WATER -> water
if (!event.getPlayer().hasPermission("modifyworld.bucket.fill." + materialName)) {
informPlayerAboutDenial(event.getPlayer());
if (permissionDenied(event.getPlayer(), "modifyworld.bucket.fill", materialName)) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOW)
public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) {
if (event.getMessage().startsWith("/tell") && !event.getPlayer().hasPermission("modifyworld.chat.private")) {
informPlayerAboutDenial(event.getPlayer());
if (event.getMessage().startsWith("/tell") && permissionDenied(event.getPlayer(), "modifyworld.chat.private")) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOW)
public void onPlayerChat(PlayerChatEvent event) {
if (!event.getPlayer().hasPermission("modifyworld.chat")) {
informPlayerAboutDenial(event.getPlayer());
if (permissionDenied(event.getPlayer(), "modifyworld.chat")) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOW)
public void onPlayerPickupItem(PlayerPickupItemEvent event) {
if (!canInteractWithItem(event.getPlayer(), "modifyworld.items.pickup.", event.getItem().getItemStack())) {
// No inform to avoid spam
if (_permissionDenied(event.getPlayer(), "modifyworld.items.pickup", event.getItem().getItemStack())) {
event.setCancelled(true);
}
@ -170,19 +139,13 @@ public class PlayerListener extends ModifyworldListener {
@EventHandler(priority = EventPriority.LOW)
public void onPlayerDropItem(PlayerDropItemEvent event) {
if (!canInteractWithItem(event.getPlayer(), "modifyworld.items.drop.", event.getItemDrop().getItemStack())) {
informPlayerAboutDenial(event.getPlayer());
if (permissionDenied(event.getPlayer(), "modifyworld.items.drop", event.getItemDrop().getItemStack())) {
event.setCancelled(true);
}
this.checkPlayerInventory(event.getPlayer());
}
@EventHandler(priority = EventPriority.LOW)
public void onInventoryOpen(PlayerInventoryEvent event) {
this.checkPlayerInventory(event.getPlayer());
}
@EventHandler(priority = EventPriority.LOW)
public void onItemHeldChange(PlayerItemHeldEvent event) {
this.checkPlayerInventory(event.getPlayer());
@ -191,17 +154,15 @@ public class PlayerListener extends ModifyworldListener {
@EventHandler(priority = EventPriority.LOW)
public void onPlayerInteractEntity(PlayerInteractEntityEvent event) {
if (this.checkItemUse) {
if (!event.getPlayer().hasPermission("modifyworld.items.use." + getItemPermission(event.getPlayer().getItemInHand()) + ".on.entity." + getEntityName(event.getRightClicked()))) {
if (permissionDenied(event.getPlayer(), "modifyworld.items.use", event.getPlayer().getItemInHand(), "on.entity", event.getRightClicked())) {
event.setCancelled(true);
informPlayerAboutDenial(event.getPlayer());
}
return;
}
if (!event.isCancelled() && !event.getPlayer().hasPermission("modifyworld.interact." + getEntityName(event.getRightClicked()))) {
if (!event.isCancelled() && permissionDenied(event.getPlayer(), "modifyworld.interact", event.getRightClicked())) {
event.setCancelled(true);
informPlayerAboutDenial(event.getPlayer());
}
}
@ -212,64 +173,62 @@ public class PlayerListener extends ModifyworldListener {
if (action == Action.RIGHT_CLICK_AIR || action == Action.RIGHT_CLICK_BLOCK) { // item restriction check
this.checkPlayerInventory(event.getPlayer());
}
Player player = event.getPlayer();
if (action == Action.RIGHT_CLICK_AIR) { //RIGHT_CLICK_AIR is cancelled by default.
switch (player.getItemInHand().getType()) {
case POTION: //Only check splash potions.
if ((player.getItemInHand().getDurability() & 0x4000) != 0x4000) break;
if ((player.getItemInHand().getDurability() & 0x4000) != 0x4000) {
break;
}
case EGG:
case SNOW_BALL:
case EXP_BOTTLE:
if (!canInteractWithItem(player, "modifyworld.items.throw.", player.getItemInHand())) {
informPlayerAboutDenial(player);
if (permissionDenied(player, "modifyworld.items.throw", player.getItemInHand())) {
event.setUseItemInHand(Result.DENY);
//Denying a potion works fine, but the client needs to be updated because it already reduced the item.
if (player.getItemInHand().getType() == Material.POTION)
if (player.getItemInHand().getType() == Material.POTION) {
event.getPlayer().updateInventory();
}
}
return;
}
}
if (action != Action.LEFT_CLICK_BLOCK && action != Action.RIGHT_CLICK_BLOCK && action != Action.PHYSICAL) {
return;
}
if (this.checkItemUse && action != Action.PHYSICAL) {
if (!player.hasPermission("modifyworld.items.use." + getItemPermission(player.getItemInHand()) + ".on.block." + getBlockPermission(event.getClickedBlock()))) {
if (permissionDenied(event.getPlayer(), "modifyworld.items.use", player.getItemInHand(), "on.block", event.getClickedBlock())) {
event.setCancelled(true);
informPlayerAboutDenial(player);
}
return;
}
if (!event.isCancelled() && !canInteractWithBlock(player, "modifyworld.blocks.interact.", event.getClickedBlock())) {
informPlayerAboutDenial(player);
if (!event.isCancelled() && permissionDenied(player, "modifyworld.blocks.interact", event.getClickedBlock())) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOW)
public void onItemEnchant(EnchantItemEvent event) {
if (!canInteractWithItem(event.getEnchanter(), "modifyworld.items.enchant.", event.getItem())){
if (permissionDenied(event.getEnchanter(), "modifyworld.items.enchant", event.getItem())) {
event.setCancelled(true);
informPlayerAboutDenial(event.getEnchanter());
}
}
@EventHandler(priority = EventPriority.LOW)
public void onItemCraft(CraftItemEvent event) {
Player player = (Player)event.getWhoClicked();
if (!canInteractWithItem(player, "modifyworld.items.craft.", event.getRecipe().getResult())){
Player player = (Player) event.getWhoClicked();
if (permissionDenied(player, "modifyworld.items.craft", event.getRecipe().getResult())) {
event.setCancelled(true);
informPlayerAboutDenial(player);
}
}
@EventHandler(priority = EventPriority.LOW)
public void onFoodLevelChange(FoodLevelChangeEvent event) {
Player player = event.getEntity() instanceof Player ? (Player) event.getEntity() : null;
@ -278,7 +237,7 @@ public class PlayerListener extends ModifyworldListener {
return;
}
if (!player.hasPermission("modifyworld.digestion")) {
if (_permissionDenied(player, "modifyworld.digestion")) {
event.setCancelled(true);
}
}
@ -290,14 +249,12 @@ public class PlayerListener extends ModifyworldListener {
Inventory inventory = player.getInventory();
for (ItemStack stack : inventory.getContents()) {
if (stack != null && !canInteractWithItem(player, "modifyworld.items.have.", stack)) {
if (stack != null && permissionDenied(player, "modifyworld.items.have", stack)) {
inventory.remove(stack);
if (this.dropRestrictedItem) {
player.getWorld().dropItemNaturally(player.getLocation(), stack);
}
informPlayer(player, String.format(this.prohibitedItemMessage, stack.getType().name()));
}
}
}

View File

@ -27,6 +27,7 @@ import org.bukkit.event.vehicle.VehicleEnterEvent;
import org.bukkit.event.vehicle.VehicleEntityCollisionEvent;
import org.bukkit.plugin.Plugin;
import ru.tehkode.modifyworld.ModifyworldListener;
import ru.tehkode.modifyworld.PlayerInformer;
/**
*
@ -34,8 +35,8 @@ import ru.tehkode.modifyworld.ModifyworldListener;
*/
public class VehicleListener extends ModifyworldListener {
public VehicleListener(Plugin plugin, ConfigurationSection config) {
super(plugin, config);
public VehicleListener(Plugin plugin, ConfigurationSection config, PlayerInformer informer) {
super(plugin, config, informer);
}
@EventHandler(priority = EventPriority.LOW)
@ -45,8 +46,7 @@ public class VehicleListener extends ModifyworldListener {
}
Player player = (Player) event.getAttacker();
if (!player.hasPermission("modifyworld.vehicle.destroy")) {
informPlayerAboutDenial(player);
if (permissionDenied(player, "modifyworld.vehicle.destroy", event.getVehicle())) {
event.setCancelled(true);
}
}
@ -58,8 +58,7 @@ public class VehicleListener extends ModifyworldListener {
}
Player player = (Player) event.getEntered();
if (!player.hasPermission("modifyworld.vehicle.enter")) {
informPlayerAboutDenial(player);
if (permissionDenied(player, "modifyworld.vehicle.enter", event.getVehicle())) {
event.setCancelled(true);
}
}
@ -71,7 +70,7 @@ public class VehicleListener extends ModifyworldListener {
}
Player player = (Player) event.getEntity();
if (!player.hasPermission("modifyworld.vehicle.collide")) {
if (_permissionDenied(player, "modifyworld.vehicle.collide", event.getVehicle())) {
event.setCancelled(true);
event.setCollisionCancelled(true);
event.setPickupCancelled(true);

View File

@ -0,0 +1,28 @@
item-restrictions: false
inform-players: false
whitelist: false
use-material-names: true
drop-restricted-item: false
item-use-check: false
messages:
message-format: '&f[&2Modifyworld&f]&4 %s'
default-message: Sorry, you don't have enough permissions - $permission
modifyworld.items.use: Stop, &a$1&4 won't fit into &a$3
modifyworld.login: You are not allowed to join this server. Goodbye!
modifyworld.blocks.interact: You are too jelly for &2$1
modifyworld.blocks.place: This is wrong place for &a$1
modifyworld.blocks.destroy: '&a$1&4 is tough for you'
modifyworld.damage.deal: Your level is too low for &5$1
modifyworld.chat: Your mouth is too dry
modifyworld.chat.private: Listener is deaf :(
modifyworld.items.have: Prohibited item &a$1&4 has been removed from your inventory.
modifyworld.items.drop: This is indecent to scatter &a$1&4 around
modifyworld.items.craft: Sorry, but &a$1&4 is too complicated
modifyworld.items.enchant: Sorry, &a$1&4 is too dangerous
modifyworld.vehicle.enter.boat: You are too heavy for this &a$1
modifyworld.vehicle.enter.minecart: Sorry, but &a$1&4 is too small
modifyworld.vehicle.destroy: This &a$1&4 is legal property of &bUnited States of America
modifyworld.tame: This &a$1&4 is too ferocious
modifyworld.bucket.fill: This bucket is holey
modifyworld.bucket.empty: You suddenly realized you still need &a$1
modifyworld.usebeds: You can't sleep yet, there are monsters nearby