Archived
0

Code cleanup batch 1

This commit is contained in:
David Panić
2018-11-10 22:42:49 +01:00
parent fe80557b8a
commit 0b1c2c69fd
13 changed files with 1046 additions and 1206 deletions

View File

@@ -22,25 +22,21 @@ import com.redstoner.modules.Module;
@Commands(CommandHolderType.File) @Commands(CommandHolderType.File)
@AutoRegisterListener @AutoRegisterListener
@Version(major = 4, minor = 1, revision = 0, compatible = 4) @Version(major = 4, minor = 1, revision = 0, compatible = 4)
public class Abot implements Module, Listener public class Abot implements Module, Listener {
{
private File answerFile = new File(Main.plugin.getDataFolder(), "abot.json"); private File answerFile = new File(Main.plugin.getDataFolder(), "abot.json");
JSONArray answers; JSONArray answers;
@EventHandler @EventHandler
public void onPlayerChat(AsyncPlayerChatEvent event) public void onPlayerChat(AsyncPlayerChatEvent event) {
{ for (Object rawObject : answers) {
for (Object rawObject : answers)
{
JSONObject entry = (JSONObject) rawObject; JSONObject entry = (JSONObject) rawObject;
JSONArray regexes = (JSONArray) entry.get("regex"); JSONArray regexes = (JSONArray) entry.get("regex");
for (Object regex : regexes)
{ for (Object regex : regexes) {
if (event.getMessage().toLowerCase().matches((String) regex)) if (event.getMessage().toLowerCase().matches((String) regex)) {
{
Object hideperm = entry.get("hide-perm"); Object hideperm = entry.get("hide-perm");
if (hideperm == null || !event.getPlayer().hasPermission((String) hideperm))
{ if (hideperm == null || !event.getPlayer().hasPermission((String) hideperm)) {
event.setCancelled(true); event.setCancelled(true);
getLogger().message(event.getPlayer(), (String) entry.get("message")); getLogger().message(event.getPlayer(), (String) entry.get("message"));
return; return;
@@ -51,17 +47,15 @@ public class Abot implements Module, Listener
} }
@Command(hook = "abot_reload") @Command(hook = "abot_reload")
public void loadAnswers(CommandSender sender) public void loadAnswers(CommandSender sender) {
{
answers = JsonManager.getArray(answerFile); answers = JsonManager.getArray(answerFile);
if (answers == null) if (answers == null) answers = new JSONArray();
answers = new JSONArray();
getLogger().message(sender, "Loaded the abot.json file!"); getLogger().message(sender, "Loaded the abot.json file!");
} }
@Override @Override
public boolean onEnable() public boolean onEnable() {
{
loadAnswers(Bukkit.getConsoleSender()); loadAnswers(Bukkit.getConsoleSender());
return true; return true;
} }

View File

@@ -25,190 +25,185 @@ import com.redstoner.modules.Module;
import net.nemez.chatapi.ChatAPI; import net.nemez.chatapi.ChatAPI;
/** AdminChat module. Allows staff to chat to other staff using /ac \<message\> as well as a one char prefix or a toggle. /**
* AdminChat module. Allows staff to chat to other staff using /ac \<message\>
* as well as a one char prefix or a toggle.
* *
* @author Pepich */ * @author Pepich
*/
@Commands(CommandHolderType.File) @Commands(CommandHolderType.File)
@AutoRegisterListener @AutoRegisterListener
@Version(major = 4, minor = 1, revision = 0, compatible = 4) @Version(major = 4, minor = 1, revision = 0, compatible = 4)
public class Adminchat implements Module, Listener public class Adminchat implements Module, Listener {
{
private static final char defaultKey = ','; private static final char defaultKey = ',';
private static final File keysLocation = new File(Main.plugin.getDataFolder(), "adminchat_keys.json"); private static final File keysLocation = new File(Main.plugin.getDataFolder(), "adminchat_keys.json");
private ArrayList<UUID> actoggled; private ArrayList<UUID> actoggled;
private static JSONObject keys; private static JSONObject keys;
private static final BroadcastFilter AC_PERM_BROADCAST_FILTER = new BroadcastFilter() {
@Override
public boolean sendTo(CommandSender recipient) {
return recipient.hasPermission("utils.ac");
}
};
@Override @Override
public boolean onEnable() public boolean onEnable() {
{
keys = JsonManager.getObject(keysLocation); keys = JsonManager.getObject(keysLocation);
if (keys == null)
{ if (keys == null) {
keys = new JSONObject(); keys = new JSONObject();
saveKeys(); saveKeys();
} }
actoggled = new ArrayList<>(); actoggled = new ArrayList<>();
return true; return true;
} }
@Command(hook = "ac_msg") @Command(hook = "ac_msg")
public boolean acSay(CommandSender sender, String message) public boolean acSay(CommandSender sender, String message) {
{
String name; String name;
if (sender instanceof Player)
name = ((Player) sender).getDisplayName(); if (sender instanceof Player) name = ((Player) sender).getDisplayName();
else else name = sender.getName();
name = sender.getName();
Utils.broadcast("§8[§cAC§8] §9" + name + "§8: §b", ChatAPI.colorify(sender, message), new BroadcastFilter() Utils.broadcast("§8[§cAC§8] §9" + name + "§8: §b", ChatAPI.colorify(sender, message), AC_PERM_BROADCAST_FILTER);
{
@Override
public boolean sendTo(CommandSender recipient)
{
return recipient.hasPermission("utils.ac");
}
});
return true; return true;
} }
@Command(hook = "acn_msg") @Command(hook = "acn_msg")
public boolean acnSay(CommandSender sender, String name, String message) public boolean acnSay(CommandSender sender, String name, String message) {
{ Utils.broadcast("§8[§cAC§8] §9" + name + "§8: §b", ChatAPI.colorify(sender, message), AC_PERM_BROADCAST_FILTER);
Utils.broadcast("§8[§cAC§8] §9" + name + "§8: §b", ChatAPI.colorify(sender, message), new BroadcastFilter()
{
@Override
public boolean sendTo(CommandSender recipient)
{
return recipient.hasPermission("utils.ac");
}
});
return true; return true;
} }
/** Let's a Player toggle their ac-toglge status to allow for automatically sending chat messages to adminchat. /**
* Lets a Player toggle their AC toggle status to allow automatically sending
* chat messages to admin chat.
* *
* @param sender the issuer of the command. * @param sender the issuer of the command.
* @param _void ignored. * @param _void ignored.
* @return true. */ * @return true.
*/
@Command(hook = "act") @Command(hook = "act")
public boolean acToggleCommand(CommandSender sender) public boolean acToggleCommand(CommandSender sender) {
{ if (actoggled.contains(((Player) sender).getUniqueId())) {
if (actoggled.contains(((Player) sender).getUniqueId()))
{
actoggled.remove(((Player) sender).getUniqueId()); actoggled.remove(((Player) sender).getUniqueId());
getLogger().message(sender, "ACT now §cdisabled"); getLogger().message(sender, "ACT now §cdisabled");
} } else {
else
{
actoggled.add(((Player) sender).getUniqueId()); actoggled.add(((Player) sender).getUniqueId());
getLogger().message(sender, "ACT now §aenabled"); getLogger().message(sender, "ACT now §aenabled");
} }
return true; return true;
} }
/** Let's a Player toggle their ac-toglge status to allow for automatically sending chat messages to adminchat. /**
* Lets a Player toggle their AC toggle status to allow automatically sending
* chat messages to admin chat.
* *
* @param sender the issuer of the command. * @param sender the issuer of the command.
* @return true. */ * @return true.
*/
@Command(hook = "act_on") @Command(hook = "act_on")
public boolean acToggleOnCommand(CommandSender sender) public boolean acToggleOnCommand(CommandSender sender) {
{ if (!actoggled.contains(((Player) sender).getUniqueId())) {
if (!actoggled.contains(((Player) sender).getUniqueId()))
{
actoggled.add(((Player) sender).getUniqueId()); actoggled.add(((Player) sender).getUniqueId());
getLogger().message(sender, "ACT now §aenabled"); getLogger().message(sender, "ACT now §aenabled");
} } else {
else
getLogger().message(sender, "ACT was already enabled"); getLogger().message(sender, "ACT was already enabled");
}
return true; return true;
} }
/** Let's a Player toggle their ac-toglge status to allow for automatically sending chat messages to adminchat. /**
* Lets a Player toggle their AC toggle status to allow automatically sending chat messages to admin chat.
* *
* @param sender the issuer of the command. * @param sender the issuer of the command.
* @return true. */ * @return true.
*/
@Command(hook = "act_off") @Command(hook = "act_off")
public boolean acToggleOffCommand(CommandSender sender) public boolean acToggleOffCommand(CommandSender sender) {
{ if (actoggled.contains(((Player) sender).getUniqueId())) {
if (actoggled.contains(((Player) sender).getUniqueId()))
{
actoggled.remove(((Player) sender).getUniqueId()); actoggled.remove(((Player) sender).getUniqueId());
getLogger().message(sender, "ACT now §cdisabled"); getLogger().message(sender, "ACT now §cdisabled");
} } else {
else
{
getLogger().message(sender, "ACT was already disabled"); getLogger().message(sender, "ACT was already disabled");
} }
return true; return true;
} }
/** Deals with chat events to allow for ackeys and actoggle. /**
* Deals with chat events to allow for ackeys and actoggle.
* *
* @param event the chat event containing the player and the message. */ * @param event the chat event containing the player and the message.
*/
@EventHandler @EventHandler
public void onPlayerChat(AsyncPlayerChatEvent event) public void onPlayerChat(AsyncPlayerChatEvent event) {
{
Player player = event.getPlayer(); Player player = event.getPlayer();
if (!player.hasPermission("utils.ac"))
return; if (!player.hasPermission("utils.ac")) return;
if (event.getMessage().startsWith(getKey(player)))
{ if (event.getMessage().startsWith(getKey(player))) {
event.setCancelled(true); event.setCancelled(true);
acSay(event.getPlayer(), event.getMessage().replaceFirst(Pattern.quote(getKey(player)), "")); acSay(event.getPlayer(), event.getMessage().replaceFirst(Pattern.quote(getKey(player)), ""));
} } else if (actoggled.contains(event.getPlayer().getUniqueId())) {
else if (actoggled.contains(event.getPlayer().getUniqueId()))
{
event.setCancelled(true); event.setCancelled(true);
acSay(event.getPlayer(), event.getMessage()); acSay(event.getPlayer(), event.getMessage());
} }
} }
/** Sets the ackey of a Player. /**
* Sets the ackey of a Player.
* *
* @param sender the issuer of the command. * @param sender the issuer of the command.
* @param key the key to be set. Set to NULL or "" to get your current key. * @param key the key to be set. Set to NULL or "" to get your current key.
* @return true. */ * @return true.
*/
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Command(hook = "setackey") @Command(hook = "setackey")
public boolean setAcKey(CommandSender sender, String key) public boolean setAcKey(CommandSender sender, String key) {
{ if (key.length() > 1) {
if (key.length() > 1) getLogger().message(sender, true, "Could not set your key to §6" + key + " §7, it can be at most one char.");
{
getLogger().message(sender, true,
"Could not set your key to §6" + key + " §7, it can be at most one char.");
return true; return true;
} }
if (key == null || key.length() == 0)
{ if (key == null || key.length() == 0) {
getAcKey(sender); getAcKey(sender);
return true; return true;
} }
getLogger().message(sender, "Set your key to §6" + key); getLogger().message(sender, "Set your key to §6" + key);
keys.put(((Player) sender).getUniqueId().toString(), key + ""); keys.put(((Player) sender).getUniqueId().toString(), key + "");
saveKeys(); saveKeys();
return true; return true;
} }
/** This method will find the AdminChat key of any player. /**
* This method will find the AdminChat key of any player.
* *
* @param player the player to get the key from. * @param player the player to get the key from.
* @return the key. */ * @return the key.
public static String getKey(Player player) */
{ public static String getKey(Player player) {
String key = (String) keys.get(player.getUniqueId().toString()); String key = (String) keys.get(player.getUniqueId().toString());
return (key == null ? "" + defaultKey : key); return (key == null ? "" + defaultKey : key);
} }
/** Prints a Players ackey to their chat. /**
* Prints a Player's ackey to their chat.
* *
* @param sender the issuer of the command. */ * @param sender the issuer of the command.
public void getAcKey(CommandSender sender) */
{ public void getAcKey(CommandSender sender) {
getLogger().message(sender, "Your current ackey is §6" + getKey((Player) sender)); getLogger().message(sender, "Your current ackey is §6" + getKey((Player) sender));
} }
/** Saves the keys. */ /** Saves the keys. */
private void saveKeys() private void saveKeys() {
{
JsonManager.save(keys, keysLocation); JsonManager.save(keys, keysLocation);
} }
} }

View File

@@ -1,5 +1,7 @@
package com.redstoner.modules.afk; package com.redstoner.modules.afk;
import java.lang.reflect.InvocationTargetException;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@@ -31,17 +33,15 @@ import com.redstoner.modules.datamanager.DataManager;
@Commands(CommandHolderType.File) @Commands(CommandHolderType.File)
@AutoRegisterListener @AutoRegisterListener
@Version(major = 4, minor = 0, revision = 6, compatible = 5) @Version(major = 4, minor = 0, revision = 6, compatible = 5)
public class AFK implements Module, Listener public class AFK implements Module, Listener {
{
private CustomListener listener; private CustomListener listener;
boolean move = true, look = false;
@Override @Override
public void firstLoad() public void firstLoad() {
{ String[] choices = new String[] { "listen", "ignore" };
Module.super.firstLoad();
DataManager.setConfig("indicator", "&7[AFK]"); DataManager.setConfig("indicator", "&7[AFK]");
String[] choices = new String[] {"listen", "ignore"};
DataManager.setConfig("move", "listen", choices); DataManager.setConfig("move", "listen", choices);
DataManager.setConfig("look", "ignore", choices); DataManager.setConfig("look", "ignore", choices);
DataManager.setConfig("chat", "listen", choices); DataManager.setConfig("chat", "listen", choices);
@@ -50,186 +50,151 @@ public class AFK implements Module, Listener
} }
@Override @Override
public void migrate(Version old) public void migrate(Version old) {
{ if (old.major() == 4 && old.minor() == 0 && old.revision() == 3) {
Module.super.migrate(old); String[] choices = new String[] { "listen", "ignore" };
if ((old.major() == 4) && (old.minor() == 0) && (old.revision() == 3))
{
String[] choices = new String[] {"listen", "ignore"};
DataManager.setConfig("look", "ignore", choices); DataManager.setConfig("look", "ignore", choices);
} }
} }
@Override @Override
public void postEnable() public void postEnable() {
{
Module.super.postEnable();
listener = new CustomListener(); listener = new CustomListener();
update_afk_listeners(Bukkit.getConsoleSender()); update_afk_listeners(Bukkit.getConsoleSender());
} }
@Override @Override
public void onDisable() public void onDisable() {
{
Module.super.onDisable();
HandlerList.unregisterAll(listener); HandlerList.unregisterAll(listener);
} }
@Command(hook = "afk") @Command(hook = "afk")
public boolean afk(CommandSender sender) public boolean afk(CommandSender sender) {
{
return afk(sender, false, ""); return afk(sender, false, "");
} }
@Command(hook = "afks") @Command(hook = "afks")
public boolean afk(CommandSender sender, boolean silent) public boolean afk(CommandSender sender, boolean silent) {
{
return afk(sender, silent, ""); return afk(sender, silent, "");
} }
@Command(hook = "afk2") @Command(hook = "afk2")
public boolean afk(CommandSender sender, boolean silent, String reason) public boolean afk(CommandSender sender, boolean silent, String reason) {
{ if (AFKUtil.isafk(sender)) {
if (isafk(sender)) AFKUtil.unafk(sender, silent);
{ } else {
unafk(sender, silent);
}
else
{
DataManager.setData(sender, "afk_time", System.currentTimeMillis()); DataManager.setData(sender, "afk_time", System.currentTimeMillis());
DataManager.setData(sender, "afk_reason", reason); DataManager.setData(sender, "afk_reason", reason);
DataManager.setState(sender, "afk_silent", silent); DataManager.setState(sender, "afk_silent", silent);
DataManager.setState(sender, "afk", true); DataManager.setState(sender, "afk", true);
if (!silent)
Utils.broadcast("§7 * ", Utils.getName(sender) + "§7 is now AFK", null); if (!silent) Utils.broadcast("§7 * ", Utils.getName(sender) + "§7 is now AFK", null);
} }
return true; return true;
} }
public void unafk(CommandSender sender, boolean silent) private void registerCustomListenerEvent(Class<? extends Event> event) {
{ Bukkit.getPluginManager().registerEvent(event, listener, EventPriority.MONITOR, listener, Main.plugin);
DataManager.setState(sender, "afk", false);
if (!silent)
Utils.broadcast("§7 * ", Utils.getName(sender) + "§7 is no longer AFK", null);
} }
public boolean isafk(CommandSender sender) /*
{ * This is perfectly valid code. Copied from the source code of the Event class:
return DataManager.getState(sender, "afk"); * "All events require a static method named getHandlerList()"
*/
private void unregisterCustomListenerEvent(Class<? extends Event> clazz) {
try {
HandlerList list = (HandlerList) clazz.getMethod("getHandlerList").invoke(null);
list.unregister(listener);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) {
e.printStackTrace();
}
} }
public boolean isVanished(Player player) private boolean getListenSetting(String name, String def) {
{ return DataManager.getConfigOrDefault(name, def).equals("listen");
return DataManager.getState(player, "vanished"); }
private void updateCustomListener(boolean listen, Class<? extends Event> clazz) {
if (listen) registerCustomListenerEvent(PlayerInteractEvent.class);
else unregisterCustomListenerEvent(PlayerInteractEvent.class);
} }
@Command(hook = "update_afk_listeners") @Command(hook = "update_afk_listeners")
public boolean update_afk_listeners(CommandSender sender) public boolean update_afk_listeners(CommandSender sender) {
{ Utils.broadcast(null, "Updating afk listeners...", new BroadcastFilter() {
Utils.broadcast(null, "Updating afk listeners...", new BroadcastFilter()
{
@Override @Override
public boolean sendTo(CommandSender recipient) public boolean sendTo(CommandSender recipient) {
{
return recipient.hasPermission("utils.afk.admin"); return recipient.hasPermission("utils.afk.admin");
} }
}); });
move = DataManager.getConfigOrDefault("move", "listen").equals("listen");
look = DataManager.getConfigOrDefault("look", "ignore").equals("listen"); updateCustomListener(getListenSetting("move", "listen") || getListenSetting("look", "ignore"), PlayerMoveEvent.class);
if (move || look) updateCustomListener(getListenSetting("chat", "listen"), AsyncPlayerChatEvent.class);
Bukkit.getPluginManager().registerEvent(PlayerMoveEvent.class, listener, EventPriority.MONITOR, listener, updateCustomListener(getListenSetting("interact", "listen"), PlayerInteractEvent.class);
Main.plugin); updateCustomListener(getListenSetting("command", "ignore"), PlayerCommandPreprocessEvent.class);
else
PlayerMoveEvent.getHandlerList().unregister(listener);
if (DataManager.getConfigOrDefault("chat", "listen").equals("listen"))
Bukkit.getPluginManager().registerEvent(PlayerInteractEvent.class, listener, EventPriority.MONITOR,
listener, Main.plugin);
else
PlayerInteractEvent.getHandlerList().unregister(listener);
if (DataManager.getConfigOrDefault("interact", "listen").equals("listen"))
Bukkit.getPluginManager().registerEvent(AsyncPlayerChatEvent.class, listener, EventPriority.MONITOR,
listener, Main.plugin);
else
AsyncPlayerChatEvent.getHandlerList().unregister(listener);
if (DataManager.getConfigOrDefault("command", "ignore").equals("listen"))
Bukkit.getPluginManager().registerEvent(PlayerCommandPreprocessEvent.class, listener, EventPriority.MONITOR,
listener, Main.plugin);
else
PlayerCommandPreprocessEvent.getHandlerList().unregister(listener);
return true; return true;
} }
@EventHandler @EventHandler
public void onLeave(PlayerQuitEvent event) public void onLeave(PlayerQuitEvent event) {
{
DataManager.setState(event.getPlayer(), "afk", false); DataManager.setState(event.getPlayer(), "afk", false);
} }
} }
class CustomListener implements Listener, EventExecutor class CustomListener implements Listener, EventExecutor {
{
private boolean move = true, look = false; private boolean move = true, look = false;
@Override @Override
public void execute(Listener listener, Event event) throws EventException public void execute(Listener listener, Event event) throws EventException {
{ if (event instanceof PlayerEvent) {
if (event instanceof PlayerEvent) if (event instanceof PlayerMoveEvent) {
{
if (event instanceof PlayerMoveEvent)
{
PlayerMoveEvent pevent = (PlayerMoveEvent) event; PlayerMoveEvent pevent = (PlayerMoveEvent) event;
double distance = pevent.getFrom().distance(pevent.getTo()); double distance = pevent.getFrom().distance(pevent.getTo());
boolean moved = distance > 0; boolean moved = distance > 0;
boolean looked = (pevent.getFrom().getPitch() != pevent.getTo().getPitch()) boolean looked = (pevent.getFrom().getPitch() != pevent.getTo().getPitch()) || (pevent.getFrom().getYaw() != pevent.getTo().getYaw());
|| (pevent.getFrom().getYaw() != pevent.getTo().getYaw());
if ((move && moved) || (look && looked)) if ((move && moved) || (look && looked)) {
{
Player player = pevent.getPlayer(); Player player = pevent.getPlayer();
if (isafk(player))
if (!isVanished(player)) if (AFKUtil.isafk(player) && !AFKUtil.isVanished(player)) AFKUtil.unafk(player, AFKUtil.isSilent(player));
unafk(player);
} }
} } else {
else
{
PlayerEvent pevent = (PlayerEvent) event; PlayerEvent pevent = (PlayerEvent) event;
Player player = pevent.getPlayer(); Player player = pevent.getPlayer();
if (isafk(player))
if (!isVanished(player)) if (AFKUtil.isafk(player) && !AFKUtil.isVanished(player)) AFKUtil.unafk(player, AFKUtil.isSilent(player));
unafk(player);
} }
} }
} }
public void unafk(CommandSender sender) public void listenMove(boolean move) {
{
DataManager.setState(sender, "afk", false);
if ( !isSilent(sender) )
Utils.broadcast("§7 * ", Utils.getName(sender) + "§7 is no longer AFK", null);
}
public boolean isafk(CommandSender sender)
{
return DataManager.getState(sender, "afk");
}
public boolean isSilent(CommandSender sender)
{
return DataManager.getState(sender, "afk_silent");
}
public boolean isVanished(Player player)
{
return DataManager.getState(player, "vanished");
}
public void listenMove(boolean move)
{
this.move = move; this.move = move;
} }
public void listenLook(boolean look) public void listenLook(boolean look) {
{
this.look = look; this.look = look;
} }
} }
class AFKUtil {
protected static void unafk(CommandSender sender, boolean silent) {
DataManager.setState(sender, "afk", false);
if (!silent) Utils.broadcast("§7 * ", Utils.getName(sender) + "§7 is no longer AFK", null);
}
protected static boolean isafk(CommandSender sender) {
return DataManager.getState(sender, "afk");
}
protected static boolean isVanished(Player player) {
return DataManager.getState(player, "vanished");
}
protected static boolean isSilent(CommandSender sender) {
return DataManager.getState(sender, "afk_silent");
}
}

View File

@@ -23,185 +23,181 @@ import com.redstoner.misc.Main;
import com.redstoner.misc.Utils; import com.redstoner.misc.Utils;
import com.redstoner.modules.Module; import com.redstoner.modules.Module;
/** BuildTeamChat module. Allows the build team to chat privately using /bc \<message\> as well as a one char prefix or a toggle. /**
* BuildTeamChat module. Allows the build team to chat privately using /bc
* \<message\> as well as a one char prefix or a toggle.
* *
* @author Pepich */ * @author Pepich
*/
@Commands(CommandHolderType.File) @Commands(CommandHolderType.File)
@AutoRegisterListener @AutoRegisterListener
@Version(major = 4, minor = 1, revision = 0, compatible = 4) @Version(major = 4, minor = 1, revision = 0, compatible = 4)
public class BuildChat implements Module, Listener public class BuildChat implements Module, Listener {
{
private static final char defaultKey = ';'; private static final char defaultKey = ';';
private static final File keysLocation = new File(Main.plugin.getDataFolder(), "buildchat_keys.json"); private static final File keysLocation = new File(Main.plugin.getDataFolder(), "buildchat_keys.json");
private ArrayList<UUID> bctoggled; private ArrayList<UUID> bctoggled;
private static JSONObject keys; private static JSONObject keys;
private static final BroadcastFilter BC_PERM_BROADCAST_FILTER = new BroadcastFilter() {
@Override
public boolean sendTo(CommandSender recipient) {
return recipient.hasPermission("utils.bc");
}
};
@Override @Override
public boolean onEnable() public boolean onEnable() {
{
keys = JsonManager.getObject(keysLocation); keys = JsonManager.getObject(keysLocation);
if (keys == null)
{ if (keys == null) {
keys = new JSONObject(); keys = new JSONObject();
saveKeys(); saveKeys();
} }
bctoggled = new ArrayList<>(); bctoggled = new ArrayList<>();
return true; return true;
} }
@Command(hook = "bc_msg") @Command(hook = "bc_msg")
public boolean bcSay(CommandSender sender, String message) public boolean bcSay(CommandSender sender, String message) {
{
String name; String name;
if (sender instanceof Player)
name = ((Player) sender).getDisplayName(); if (sender instanceof Player) name = ((Player) sender).getDisplayName();
else else name = sender.getName();
name = sender.getName();
Utils.broadcast("§8[§cBC§8] §9" + name + "§8: §b", message, new BroadcastFilter() Utils.broadcast("§8[§cBC§8] §9" + name + "§8: §b", message, BC_PERM_BROADCAST_FILTER);
{
@Override
public boolean sendTo(CommandSender recipient)
{
return recipient.hasPermission("utils.bc");
}
});
return true; return true;
} }
@Command(hook = "bcn_msg") @Command(hook = "bcn_msg")
public boolean bcnSay(CommandSender sender, String name, String message) public boolean bcnSay(CommandSender sender, String name, String message) {
{ Utils.broadcast("§8[§cBC§8] §9" + name + "§8: §b", message, BC_PERM_BROADCAST_FILTER);
Utils.broadcast("§8[§cBC§8] §9" + name + "§8: §b", message, new BroadcastFilter()
{
@Override
public boolean sendTo(CommandSender recipient)
{
return recipient.hasPermission("utils.bc");
}
});
return true; return true;
} }
/** Let's a Player toggle their auto-cg status to allow for automatically sending chat messages to their chatgroup. /**
* Lets a Player toggle their auto-cg status to allow for automatically sending
* chat messages to their chatgroup.
* *
* @param sender the issuer of the command. * @param sender the issuer of the command.
* @param _void ignored. * @param _void ignored.
* @return true. */ * @return true.
*/
@Command(hook = "bct") @Command(hook = "bct")
public boolean bcToggleCommand(CommandSender sender) public boolean bcToggleCommand(CommandSender sender) {
{ if (bctoggled.contains(((Player) sender).getUniqueId())) {
if (bctoggled.contains(((Player) sender).getUniqueId()))
{
bctoggled.remove(((Player) sender).getUniqueId()); bctoggled.remove(((Player) sender).getUniqueId());
getLogger().message(sender, "BCT now §cdisabled"); getLogger().message(sender, "BCT now §cdisabled");
} } else {
else
{
bctoggled.add(((Player) sender).getUniqueId()); bctoggled.add(((Player) sender).getUniqueId());
getLogger().message(sender, "BCT now §aenabled"); getLogger().message(sender, "BCT now §aenabled");
} }
return true; return true;
} }
/** Let's a Player toggle their auto-cg status to allow for automatically sending chat messages to their chatgroup. /**
* Lets a Player toggle their auto-cg status to allow for automatically sending
* chat messages to their chatgroup.
* *
* @param sender the issuer of the command. * @param sender the issuer of the command.
* @return true. */ * @return true.
*/
@Command(hook = "bct_on") @Command(hook = "bct_on")
public boolean bcToggleOnCommand(CommandSender sender) public boolean bcToggleOnCommand(CommandSender sender) {
{ if (!bctoggled.contains(((Player) sender).getUniqueId())) {
if (!bctoggled.contains(((Player) sender).getUniqueId()))
{
bctoggled.add(((Player) sender).getUniqueId()); bctoggled.add(((Player) sender).getUniqueId());
getLogger().message(sender, "BCT now §aenabled"); getLogger().message(sender, "BCT now §aenabled");
} } else getLogger().message(sender, "BCT was already enabled");
else
getLogger().message(sender, "BCT was already enabled");
return true; return true;
} }
/** Let's a Player toggle their auto-cg status to allow for automatically sending chat messages to their chatgroup. /**
* Let's a Player toggle their auto-cg status to allow for automatically sending
* chat messages to their chatgroup.
* *
* @param sender the issuer of the command. * @param sender the issuer of the command.
* @return true. */ * @return true.
*/
@Command(hook = "bct_off") @Command(hook = "bct_off")
public boolean bcToggleOffCommand(CommandSender sender) public boolean bcToggleOffCommand(CommandSender sender) {
{ if (bctoggled.remove(((Player) sender).getUniqueId())) getLogger().message(sender, "BCT now §cdisabled");
if (bctoggled.remove(((Player) sender).getUniqueId())) else getLogger().message(sender, "BCT was already disabled");
getLogger().message(sender, "BCT now §cdisabled");
else
getLogger().message(sender, "BCT was already disabled");
return true; return true;
} }
/** Deals with chat events to allow for bckeys and bctoggle. /**
* Deals with chat events to allow for bckeys and bctoggle.
* *
* @param event the chat event containing the player and the message. */ * @param event the chat event containing the player and the message.
*/
@EventHandler @EventHandler
public void onPlayerChat(AsyncPlayerChatEvent event) public void onPlayerChat(AsyncPlayerChatEvent event) {
{
Player player = event.getPlayer(); Player player = event.getPlayer();
if (!player.hasPermission("utils.bc"))
return; if (!player.hasPermission("utils.bc")) return;
if (event.getMessage().startsWith(getKey(player)))
{ if (event.getMessage().startsWith(getKey(player))) {
event.setCancelled(true); event.setCancelled(true);
bcSay(event.getPlayer(), event.getMessage().replaceFirst(Pattern.quote(getKey(player)), "")); bcSay(event.getPlayer(), event.getMessage().replaceFirst(Pattern.quote(getKey(player)), ""));
} } else if (bctoggled.contains(event.getPlayer().getUniqueId())) {
else if (bctoggled.contains(event.getPlayer().getUniqueId()))
{
event.setCancelled(true); event.setCancelled(true);
bcSay(event.getPlayer(), event.getMessage()); bcSay(event.getPlayer(), event.getMessage());
} }
} }
/** Sets the bckey of a Player. /**
* Sets the bckey of a Player.
* *
* @param sender the issuer of the command. * @param sender the issuer of the command.
* @param key the key to be set. Set to NULL or "" to get your current key. * @param key the key to be set. Set to NULL or "" to get your current key.
* @return true. */ * @return true.
*/
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Command(hook = "setbckey") @Command(hook = "setbckey")
public boolean setBcKey(CommandSender sender, String key) public boolean setBcKey(CommandSender sender, String key) {
{ if (key.length() > 1) {
if (key.length() > 1) getLogger().message(sender, true, "Could not set your key to §6" + key + " §7, it can be at most one char.");
{
getLogger().message(sender, true,
"Could not set your key to §6" + key + " §7, it can be at most one char.");
return true; return true;
} }
if (key == null || key.length() == 0)
{ if (key == null || key.length() == 0) {
getBcKey(sender); getBcKey(sender);
return true; return true;
} }
getLogger().message(sender, "Set your key to §6" + key); getLogger().message(sender, "Set your key to §6" + key);
keys.put(((Player) sender).getUniqueId().toString(), key + ""); keys.put(((Player) sender).getUniqueId().toString(), key + "");
saveKeys(); saveKeys();
return true; return true;
} }
/** This method will find the ChatgGroup key of any player. /**
* This method will find the ChatgGroup key of any player.
* *
* @param player the player to get the key from. * @param player the player to get the key from.
* @return the key. */ * @return the key.
public static String getKey(Player player) */
{ public static String getKey(Player player) {
String key = (String) keys.get(player.getUniqueId().toString()); String key = (String) keys.get(player.getUniqueId().toString());
return (key == null ? "" + defaultKey : key); return (key == null ? "" + defaultKey : key);
} }
/** Prints a Players bckey to their chat. /**
* Prints a Players bckey to their chat.
* *
* @param sender the issuer of the command. */ * @param sender the issuer of the command.
public void getBcKey(CommandSender sender) */
{ public void getBcKey(CommandSender sender) {
getLogger().message(sender, "Your current bckey is §6" + getKey((Player) sender)); getLogger().message(sender, "Your current bckey is §6" + getKey((Player) sender));
} }
/** Saves the keys. */ /** Saves the keys. */
private void saveKeys() private void saveKeys() {
{
JsonManager.save(keys, keysLocation); JsonManager.save(keys, keysLocation);
} }
} }

View File

@@ -12,44 +12,41 @@ import com.redstoner.modules.Module;
@Commands(CommandHolderType.File) @Commands(CommandHolderType.File)
@Version(major = 4, minor = 0, revision = 0, compatible = 4) @Version(major = 4, minor = 0, revision = 0, compatible = 4)
public class BuildTeam implements Module public class BuildTeam implements Module {
{
@Command(hook = "teleport") @Command(hook = "teleport")
public boolean teleport(CommandSender sender, String target_name) public boolean teleport(CommandSender sender, String target_name) {
{
final Player player = (Player) sender; final Player player = (Player) sender;
final Player target = Bukkit.getPlayer(target_name); final Player target = Bukkit.getPlayer(target_name);
if (target == null || !player.hasPermission("utils.buildteam.teleport")
|| !target.getLocation().getWorld().getName().equals("BuildTeam")) if (target == null || !player.hasPermission("utils.buildteam.teleport") || !target.getLocation().getWorld().getName().equals("BuildTeam")) {
{
player.performCommand("essentials:tp " + target_name); player.performCommand("essentials:tp " + target_name);
return true; return true;
} }
player.teleport(target); player.teleport(target);
getLogger().message(sender, "Teleported you to &e" + target.getDisplayName() + "&7!"); getLogger().message(sender, "Teleported you to &e" + target.getDisplayName() + "&7!");
return true; return true;
} }
@Command(hook = "team_add") @Command(hook = "team_add")
public boolean add(CommandSender sender, String target_name) public boolean add(CommandSender sender, String target_name) {
{ if (!target_name.matches("^\\w{2,16}$")) {
if (!target_name.matches("^\\w{2,16}$"))
{
getLogger().message(sender, true, "This doesn't look like a valid playername!"); getLogger().message(sender, true, "This doesn't look like a valid playername!");
return true; return true;
} }
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "pex user " + target_name + " group add +buildteam"); Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "pex user " + target_name + " group add +buildteam");
return true; return true;
} }
@Command(hook = "team_remove") @Command(hook = "team_remove")
public boolean remove(CommandSender sender, String target_name) public boolean remove(CommandSender sender, String target_name) {
{ if (!target_name.matches("^\\w{2,16}$")) {
if (!target_name.matches("^\\w{2,16}$"))
{
getLogger().message(sender, true, "This doesn't look like a valid playername!"); getLogger().message(sender, true, "This doesn't look like a valid playername!");
return true; return true;
} }
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "pex user " + target_name + " group remove +buildteam"); Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "pex user " + target_name + " group remove +buildteam");
return true; return true;
} }

View File

@@ -33,13 +33,11 @@ import net.nemez.chatapi.ChatAPI;
@Commands(CommandHolderType.File) @Commands(CommandHolderType.File)
@AutoRegisterListener @AutoRegisterListener
@Version(major = 4, minor = 1, revision = 1, compatible = 4) @Version(major = 4, minor = 1, revision = 1, compatible = 4)
public class Chat implements Module, Listener public class Chat implements Module, Listener {
{
private final Map<String, String> defaults = new HashMap<>(); private final Map<String, String> defaults = new HashMap<>();
private Set<UUID> chatonly = new HashSet<>(); private Set<UUID> chatonly = new HashSet<>();
public Chat() public Chat() {
{
defaults.put("chat", " %n§7%c →§r %m"); defaults.put("chat", " %n§7%c →§r %m");
defaults.put("me", " §7- %n§7%c ⇦ %m"); defaults.put("me", " §7- %n§7%c ⇦ %m");
defaults.put("action", " §7- %n§7%c ⇦ %m"); defaults.put("action", " §7- %n§7%c ⇦ %m");
@@ -50,9 +48,7 @@ public class Chat implements Module, Listener
} }
@Override @Override
public void firstLoad() public void firstLoad() {
{
Module.super.firstLoad();
DataManager.setConfig("chat", defaults.get("chat")); DataManager.setConfig("chat", defaults.get("chat"));
DataManager.setConfig("me", defaults.get("me")); DataManager.setConfig("me", defaults.get("me"));
DataManager.setConfig("action", defaults.get("action")); DataManager.setConfig("action", defaults.get("action"));
@@ -62,183 +58,162 @@ public class Chat implements Module, Listener
DataManager.setConfig("%c", defaults.get("%c")); DataManager.setConfig("%c", defaults.get("%c"));
} }
@EventHandler(priority = EventPriority.MONITOR) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPlayerChat(AsyncPlayerChatEvent event) public void onPlayerChat(AsyncPlayerChatEvent event) {
{
if (event.isCancelled())
return;
Player player = event.getPlayer(); Player player = event.getPlayer();
String message = event.getMessage(); String message = event.getMessage();
event.setCancelled(true); event.setCancelled(true);
broadcastFormatted("chat", player, message, event); broadcastFormatted("chat", player, message, event);
} }
@EventHandler @EventHandler
public void onLeave(PlayerQuitEvent event) public void onLeave(PlayerQuitEvent event) {
{
chatonly.remove(event.getPlayer().getUniqueId()); chatonly.remove(event.getPlayer().getUniqueId());
} }
@Command(hook = "me") @Command(hook = "me")
public boolean me(CommandSender sender, String message) public boolean me(CommandSender sender, String message) {
{
broadcastFormatted("me", sender, message); broadcastFormatted("me", sender, message);
return true; return true;
} }
@Command(hook = "chat") @Command(hook = "chat")
public boolean chat(CommandSender sender, String message) public boolean chat(CommandSender sender, String message) {
{
broadcastFormatted("chat", sender, message); broadcastFormatted("chat", sender, message);
return true; return true;
} }
@Command(hook = "chatn") @Command(hook = "chatn")
public boolean chatn(CommandSender sender, String name, String message) public boolean chatn(CommandSender sender, String name, String message) {
{
broadcastFormatted("chat", sender, message, name); broadcastFormatted("chat", sender, message, name);
return true; return true;
} }
@Command(hook = "action") @Command(hook = "action")
public boolean action(CommandSender sender, String message) public boolean action(CommandSender sender, String message) {
{
broadcastFormatted("action", sender, message); broadcastFormatted("action", sender, message);
return true; return true;
} }
@Command(hook = "say") @Command(hook = "say")
public boolean say(CommandSender sender, String message) public boolean say(CommandSender sender, String message) {
{
String name; String name;
if (sender instanceof Player)
name = ((Player) sender).getName(); if (sender instanceof Player) name = ((Player) sender).getName();
else else name = "§9CONSOLE";
name = "§9CONSOLE";
broadcastFormatted("say", sender, message, name); broadcastFormatted("say", sender, message, name);
return true; return true;
} }
@Command(hook = "sayn") @Command(hook = "sayn")
public boolean say(CommandSender sender, String name, String message) public boolean say(CommandSender sender, String name, String message) {
{
broadcastFormatted("say", sender, message, name); broadcastFormatted("say", sender, message, name);
return true; return true;
} }
@Command(hook = "shrug") @Command(hook = "shrug")
public boolean shrug(CommandSender sender, String message) public boolean shrug(CommandSender sender, String message) {
{
broadcastFormatted("shrug", sender, message); broadcastFormatted("shrug", sender, message);
return true; return true;
} }
@Command(hook = "shrugnoarg") @Command(hook = "shrugnoarg")
public boolean shrug(CommandSender sender) public boolean shrug(CommandSender sender) {
{
broadcastFormatted("shrug", sender, ""); broadcastFormatted("shrug", sender, "");
return true; return true;
} }
@Command(hook = "print") @Command(hook = "print")
public boolean print(CommandSender sender, String message) public boolean print(CommandSender sender, String message) {
{
broadcastFormatted("print", sender, message); broadcastFormatted("print", sender, message);
return true; return true;
} }
@Command(hook = "mute") @Command(hook = "mute")
public boolean mute(CommandSender sender, String player) public boolean mute(CommandSender sender, String player) {
{
Player p = Bukkit.getPlayer(player); Player p = Bukkit.getPlayer(player);
if (p == null)
{ if (p == null) {
getLogger().message(sender, true, "That player couldn't be found!"); getLogger().message(sender, true, "That player couldn't be found!");
return true; return true;
} }
DataManager.setData(p, "muted", true); DataManager.setData(p, "muted", true);
getLogger().message(sender, "Muted player &e" + Utils.getName(p) + "&7!"); getLogger().message(sender, "Muted player &e" + Utils.getName(p) + "&7!");
getLogger().message(p, "You have been &cmuted&7!"); getLogger().message(p, "You have been &cmuted&7!");
return true; return true;
} }
@Command(hook = "unmute") @Command(hook = "unmute")
public boolean unmute(CommandSender sender, String player) public boolean unmute(CommandSender sender, String player) {
{
Player p = Bukkit.getPlayer(player); Player p = Bukkit.getPlayer(player);
if (p == null)
{ if (p == null) {
getLogger().message(sender, true, "That player couldn't be found!"); getLogger().message(sender, true, "That player couldn't be found!");
return true; return true;
} }
DataManager.setData(p, "muted", false); DataManager.setData(p, "muted", false);
getLogger().message(sender, "Unmuted player &e" + Utils.getName(p) + "&7!"); getLogger().message(sender, "Unmuted player &e" + Utils.getName(p) + "&7!");
getLogger().message(p, "You have been &aunmuted&7!"); getLogger().message(p, "You have been &aunmuted&7!");
return true; return true;
} }
@Command(hook = "chatonly") @Command(hook = "chatonly")
public void chatonly(CommandSender sender) public void chatonly(CommandSender sender) {
{
UUID uuid = ((Player) sender).getUniqueId(); UUID uuid = ((Player) sender).getUniqueId();
if (chatonly.contains(uuid)) { if (chatonly.contains(uuid)) {
chatonly.remove(uuid); chatonly.remove(uuid);
getLogger().message(sender, "You are no longer tagged with being only able to chat."); getLogger().message(sender, "You are no longer tagged with being only able to chat.");
} } else {
else {
chatonly.add(uuid); chatonly.add(uuid);
getLogger().message(sender, "You are now tagged with being only able to chat."); getLogger().message(sender, "You are now tagged with being only able to chat.");
} }
} }
public boolean broadcastFormatted(String format, CommandSender sender, String message) public boolean broadcastFormatted(String format, CommandSender sender, String message) {
{
return broadcastFormatted(format, sender, message, Utils.getName(sender), null); return broadcastFormatted(format, sender, message, Utils.getName(sender), null);
} }
public boolean broadcastFormatted(String format, CommandSender sender, String message, String name) public boolean broadcastFormatted(String format, CommandSender sender, String message, String name) {
{
return broadcastFormatted(format, sender, message, name, null); return broadcastFormatted(format, sender, message, name, null);
} }
public boolean broadcastFormatted(String format, CommandSender sender, String message, AsyncPlayerChatEvent event) public boolean broadcastFormatted(String format, CommandSender sender, String message, AsyncPlayerChatEvent event) {
{
return broadcastFormatted(format, sender, message, Utils.getName(sender), event); return broadcastFormatted(format, sender, message, Utils.getName(sender), event);
} }
public boolean broadcastFormatted(String format, CommandSender sender, String message, String name, public boolean broadcastFormatted(String format, CommandSender sender, String message, String name, AsyncPlayerChatEvent event) {
AsyncPlayerChatEvent event) boolean isChatOnly = sender instanceof Player && chatonly.contains(((Player) sender).getUniqueId());
{
boolean isChatOnly = sender instanceof Player && chatonly.contains(((Player)sender).getUniqueId()); if ((boolean) DataManager.getOrDefault(sender, "muted", false)) {
if ((boolean) DataManager.getOrDefault(sender, "muted", false))
{
getLogger().message(sender, true, "You have been muted!"); getLogger().message(sender, true, "You have been muted!");
getLogger().info(" &7User &e" + Utils.getName(sender) + " &7tried to &e" + format + " &7(&e" + message getLogger().info(" &7User &e" + Utils.getName(sender) + " &7tried to &e" + format + " &7(&e" + message + "&7) while being &cmuted&7.");
+ "&7) while being &cmuted&7.");
return false; return false;
} }
String raw = (String) DataManager.getConfigOrDefault(format, defaults.get(format)); String raw = (String) DataManager.getConfigOrDefault(format, defaults.get(format));
String formatted = raw.replace("%n", name).replace("%m", message).replace("%c", isChatOnly? (String) DataManager.getConfigOrDefault("%c", defaults.get("%c")) : ""); String formatted = raw.replace("%n", name).replace("%m", message).replace("%c", isChatOnly ? (String) DataManager.getConfigOrDefault("%c", defaults.get("%c")) : "");
Utils.broadcast("", ChatAPI.colorify(sender, formatted), Utils.broadcast("", ChatAPI.colorify(sender, formatted), wrap(ModuleLoader.exists("Ignore") ? Ignore.getIgnoredBy(sender) : null, event));
wrap(ModuleLoader.exists("Ignore") ? Ignore.getIgnoredBy(sender) : null, event));
return true; return true;
} }
public BroadcastFilter wrap(BroadcastFilter filter, AsyncPlayerChatEvent event) public BroadcastFilter wrap(BroadcastFilter filter, AsyncPlayerChatEvent event) {
{ if (event == null) return filter;
if (event == null) else return new BroadcastFilter() {
return filter; @Override
else public boolean sendTo(CommandSender recipient) {
return new BroadcastFilter() if (recipient instanceof ConsoleCommandSender || filter == null) return true;
{ return filter.sendTo(recipient) && event.getRecipients().contains(recipient);
@Override }
public boolean sendTo(CommandSender recipient) };
{
if (recipient instanceof ConsoleCommandSender || filter == null)
return true;
return filter.sendTo(recipient) && event.getRecipients().contains(recipient);
}
};
} }
} }

View File

@@ -3,6 +3,7 @@ package com.redstoner.modules.chatalias;
import java.io.File; import java.io.File;
import java.util.Set; import java.util.Set;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
@@ -27,309 +28,299 @@ import com.redstoner.misc.JsonManager;
import com.redstoner.misc.Main; import com.redstoner.misc.Main;
import com.redstoner.modules.Module; import com.redstoner.modules.Module;
import io.netty.util.internal.ThreadLocalRandom;
import net.nemez.chatapi.ChatAPI; import net.nemez.chatapi.ChatAPI;
import net.nemez.chatapi.click.Message; import net.nemez.chatapi.click.Message;
@Commands(CommandHolderType.File) @Commands(CommandHolderType.File)
@AutoRegisterListener @AutoRegisterListener
@Version(major = 4, minor = 1, revision = 0, compatible = 4) @Version(major = 4, minor = 1, revision = 0, compatible = 4)
public class Chatalias implements Module, Listener public class Chatalias implements Module, Listener {
{ private final String[] commands = new String[] { "e?r", "e?m .+?", "e?t", "e?w", "e?msg .+?", "e?message .+?", "e?whisper .+?", "e?me", "cgsay", "ac", "bc",
private final String[] commands = new String[] {"e?r", "e?m .+?", "e?t", "e?w", "e?msg .+?", "e?message .+?", "say", "sayn .+?", "chat", "shrug", "action", "speak", "chatn", "speakn" };
"e?whisper .+?", "e?me", "cgsay", "ac", "bc", "say", "sayn .+?", "chat", "shrug", "action", "speak", "chatn", "speakn"};
private JSONObject aliases = new JSONObject(); private JSONObject aliases = new JSONObject();
@Override @Override
public boolean onEnable() public boolean onEnable() {
{ for (Player p : Bukkit.getOnlinePlayers()) {
for (Player p : Bukkit.getOnlinePlayers())
{
loadAliases(p.getUniqueId()); loadAliases(p.getUniqueId());
} }
return true; return true;
} }
@Override @Override
public void onDisable() public void onDisable() {
{ for (Object key : aliases.keySet()) {
for (Object key : aliases.keySet())
{
UUID uuid = UUID.fromString((String) key); UUID uuid = UUID.fromString((String) key);
saveAliases(uuid); saveAliases(uuid);
} }
} }
@EventHandler @EventHandler
public void onPlayerJoin(PlayerJoinEvent event) public void onPlayerJoin(PlayerJoinEvent event) {
{
loadAliases(event.getPlayer().getUniqueId()); loadAliases(event.getPlayer().getUniqueId());
} }
@EventHandler @EventHandler
public void onPlayerLeave(PlayerQuitEvent event) public void onPlayerLeave(PlayerQuitEvent event) {
{
aliases.remove(event.getPlayer().getUniqueId().toString()); aliases.remove(event.getPlayer().getUniqueId().toString());
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@EventHandler(priority = EventPriority.LOWEST) @EventHandler(priority = EventPriority.LOWEST)
public void onPlayerChat(AsyncPlayerChatEvent event) public void onPlayerChat(AsyncPlayerChatEvent event) {
{
Player player = event.getPlayer(); Player player = event.getPlayer();
UUID uuid = player.getUniqueId(); UUID uuid = player.getUniqueId();
if (!aliases.containsKey(uuid.toString()))
{ if (!aliases.containsKey(uuid.toString())) {
loadAliases(player.getUniqueId()); loadAliases(player.getUniqueId());
if (!aliases.containsKey(uuid.toString()))
return; if (!aliases.containsKey(uuid.toString())) return;
} }
JSONObject playerAliases = (JSONObject) aliases.get(uuid.toString()); JSONObject playerAliases = (JSONObject) aliases.get(uuid.toString());
boolean changed = false; boolean changed = false;
for (Object key : playerAliases.keySet())
{ for (Object key : playerAliases.keySet()) {
String keyword = (String) key; String keyword = (String) key;
String replacement = (String) playerAliases.get(key); String replacement = (String) playerAliases.get(key);
if (keyword.startsWith("RND;")) { if (keyword.startsWith("RND;")) {
keyword = keyword.replace("RND;", ""); keyword = keyword.replace("RND;", "");
String[] results = replacement.split(" \\|\\| "); String[] results = replacement.split(" \\|\\| ");
for (String str : results) { for (String str : results) {
System.out.println(str); System.out.println(str);
} }
int rand = ThreadLocalRandom.current().nextInt(0, results.length); int rand = ThreadLocalRandom.current().nextInt(0, results.length);
replacement = results[rand]; replacement = results[rand];
} }
if (keyword.startsWith("R: ")) {
if (keyword.startsWith("R: "))
{
keyword = keyword.replace("R: ", ""); keyword = keyword.replace("R: ", "");
event.setMessage(event.getMessage().replaceAll(keyword, replacement)); event.setMessage(event.getMessage().replaceAll(keyword, replacement));
} } else {
else if (keyword.startsWith("N: ")) keyword = keyword.replace("N: ", "");
{ else {
if (keyword.startsWith("N: "))
keyword = keyword.replace("N: ", "");
else
{
changed = true; changed = true;
playerAliases.put("N: " + key, replacement); playerAliases.put("N: " + key, replacement);
} }
event.setMessage(event.getMessage().replace(keyword, replacement)); event.setMessage(event.getMessage().replace(keyword, replacement));
} }
int maxLength; int maxLength;
try
{ try {
maxLength = Integer.valueOf(getPermissionContent(player, "utils.alias.length.")); maxLength = Integer.valueOf(getPermissionContent(player, "utils.alias.length."));
} } catch (NumberFormatException e) {
catch (NumberFormatException e)
{
maxLength = 255; maxLength = 255;
} }
if (event.getMessage().length() > maxLength)
{ if (event.getMessage().length() > maxLength) {
getLogger().message(player, true, "The generated message is too long!"); getLogger().message(player, true, "The generated message is too long!");
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
} }
event.setMessage(ChatAPI.colorify(event.getPlayer(), event.getMessage())); event.setMessage(ChatAPI.colorify(event.getPlayer(), event.getMessage()));
if (changed)
saveAliases(uuid); if (changed) saveAliases(uuid);
} }
@EventHandler(priority = EventPriority.LOWEST) @EventHandler(priority = EventPriority.LOWEST)
public void onPlayerCommand(PlayerCommandPreprocessEvent event) public void onPlayerCommand(PlayerCommandPreprocessEvent event) {
{ if (event.isCancelled()) return;
if (event.isCancelled())
return;
boolean listening = false; boolean listening = false;
String command = ""; String command = "";
for (String s : commands)
{ for (String s : commands) {
command = "^\\/(.*:)?" + s + " "; command = "^\\/(.*:)?" + s + " ";
if (event.getMessage().matches(command + ".*"))
{ if (event.getMessage().matches(command + ".*")) {
listening = true; listening = true;
break; break;
} }
} }
if (!listening)
return; if (!listening) return;
Player player = event.getPlayer(); Player player = event.getPlayer();
UUID uuid = player.getUniqueId(); UUID uuid = player.getUniqueId();
JSONObject playerAliases = (JSONObject) aliases.get(uuid.toString()); JSONObject playerAliases = (JSONObject) aliases.get(uuid.toString());
String temp = event.getMessage().replaceAll(command, ""); String temp = event.getMessage().replaceAll(command, "");
command = event.getMessage().replaceAll(Pattern.quote(temp) + "$", ""); command = event.getMessage().replaceAll(Pattern.quote(temp) + "$", "");
event.setMessage(event.getMessage().replaceFirst(Pattern.quote(command), "")); event.setMessage(event.getMessage().replaceFirst(Pattern.quote(command), ""));
for (Object key : playerAliases.keySet())
{ for (Object key : playerAliases.keySet()) {
String keyword = (String) key; String keyword = (String) key;
String replacement = (String) playerAliases.get(key); String replacement = (String) playerAliases.get(key);
if (keyword.startsWith("RND;")) { if (keyword.startsWith("RND;")) {
keyword = keyword.replace("RND;", ""); keyword = keyword.replace("RND;", "");
String[] results = replacement.split(" \\|\\| "); String[] results = replacement.split(" \\|\\| ");
for (String str : results) { for (String str : results) {
System.out.println(str); System.out.println(str);
} }
int rand = ThreadLocalRandom.current().nextInt(0, results.length); int rand = ThreadLocalRandom.current().nextInt(0, results.length);
replacement = results[rand]; replacement = results[rand];
} }
if (keyword.startsWith("R: ")) if (keyword.startsWith("R: ")) {
{
keyword = keyword.replace("R: ", ""); keyword = keyword.replace("R: ", "");
event.setMessage(event.getMessage().replaceAll(keyword, replacement)); event.setMessage(event.getMessage().replaceAll(keyword, replacement));
} } else {
else if (keyword.startsWith("N: ")) keyword = keyword.replace("N: ", "");
{
if (keyword.startsWith("N: "))
keyword = keyword.replace("N: ", "");
event.setMessage(event.getMessage().replace(keyword, replacement)); event.setMessage(event.getMessage().replace(keyword, replacement));
} }
int maxLength; int maxLength;
try
{ try {
maxLength = Integer.valueOf(getPermissionContent(player, "utils.alias.length.")); maxLength = Integer.valueOf(getPermissionContent(player, "utils.alias.length."));
} } catch (NumberFormatException e) {
catch (NumberFormatException e)
{
maxLength = 255; maxLength = 255;
} }
if (event.getMessage().length() > maxLength)
{ if (event.getMessage().length() > maxLength) {
getLogger().message(player, true, "The generated message is too long!"); getLogger().message(player, true, "The generated message is too long!");
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
} }
event.setMessage(command + event.getMessage()); event.setMessage(command + event.getMessage());
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Command(hook = "addalias") @Command(hook = "addalias")
public boolean addAlias(CommandSender sender, boolean regex, boolean random, String keyword, String replacement) public boolean addAlias(CommandSender sender, boolean regex, boolean random, String keyword, String replacement) {
{ if (regex && keyword.equals(".*")) {
if (regex && keyword.equals(".*"))
{
getLogger().message(sender, true, "You may not define the wildcard regex as an alias."); getLogger().message(sender, true, "You may not define the wildcard regex as an alias.");
return true; return true;
} }
Player player = (Player) sender; Player player = (Player) sender;
UUID uuid = player.getUniqueId(); UUID uuid = player.getUniqueId();
JSONObject data = (JSONObject) aliases.get(uuid.toString()); JSONObject data = (JSONObject) aliases.get(uuid.toString());
keyword = (random ? "RND;" : "") + (regex ? "R: " : "N: ") + keyword; keyword = (random ? "RND;" : "") + (regex ? "R: " : "N: ") + keyword;
if (!data.containsKey(keyword))
{ if (!data.containsKey(keyword)) {
int maxAmount; int maxAmount;
try
{ try {
maxAmount = Integer.valueOf(getPermissionContent(player, "utils.alias.amount.")); maxAmount = Integer.valueOf(getPermissionContent(player, "utils.alias.amount."));
} } catch (NumberFormatException e) {
catch (NumberFormatException e)
{
maxAmount = 25; maxAmount = 25;
} }
if (data.size() == maxAmount)
{ if (data.size() == maxAmount) {
getLogger().message(sender, true, "You already reached your maximum of aliases!"); getLogger().message(sender, true, "You already reached your maximum of aliases!");
return true; return true;
} }
} }
data.put(keyword, replacement); data.put(keyword, replacement);
if (sender.hasPermission("essentials.chat.color"))
getLogger().message(sender, if (sender.hasPermission("essentials.chat.color")) {
"Successfully created alias " + keyword.substring(random? 7 : 3) + " §7-> " + replacement + " §7for you."); getLogger().message(sender, "Successfully created alias " + keyword.substring(random ? 7 : 3) + " §7-> " + replacement + " §7for you.");
else } else {
getLogger().message(sender, getLogger().message(sender, "Successfully created alias " + keyword.substring(random ? 7 : 3) + " §7-> " + replacement + " §7for you.");
"Successfully created alias " + keyword.substring(random? 7 : 3) + " §7-> " + replacement + " §7for you."); }
saveAliases(uuid); saveAliases(uuid);
return true; return true;
} }
@Command(hook = "delalias") @Command(hook = "delalias")
public boolean delAlias(CommandSender sender, boolean regex, boolean random, String keyword) public boolean delAlias(CommandSender sender, boolean regex, boolean random, String keyword) {
{
Player player = (Player) sender; Player player = (Player) sender;
UUID uuid = player.getUniqueId(); UUID uuid = player.getUniqueId();
JSONObject data = (JSONObject) aliases.get(uuid.toString()); JSONObject data = (JSONObject) aliases.get(uuid.toString());
keyword = (random ? "RND;" : "") + (regex ? "R: " : "N: ") + keyword; keyword = (random ? "RND;" : "") + (regex ? "R: " : "N: ") + keyword;
if (data.remove(keyword) != null)
{ if (data.remove(keyword) != null) {
getLogger().message(sender, "Successfully removed the alias!"); getLogger().message(sender, "Successfully removed the alias!");
saveAliases(uuid); saveAliases(uuid);
return true; return true;
} } else {
else
{
getLogger().message(sender, true, "That alias doesn't exist! Hint: regex/no regex does matter for this."); getLogger().message(sender, true, "That alias doesn't exist! Hint: regex/no regex does matter for this.");
return true; return true;
} }
} }
@Command(hook = "listaliases") @Command(hook = "listaliases")
public boolean listAliases(CommandSender sender) public boolean listAliases(CommandSender sender) {
{
Message m = new Message(sender, null).appendText(getLogger().getHeader()); Message m = new Message(sender, null).appendText(getLogger().getHeader());
Player player = (Player) sender; Player player = (Player) sender;
UUID uuid = player.getUniqueId(); UUID uuid = player.getUniqueId();
JSONObject data = (JSONObject) aliases.get(uuid.toString()); JSONObject data = (JSONObject) aliases.get(uuid.toString());
for (Object key : data.keySet()) { for (Object key : data.keySet()) {
String d_key = (String) key; String d_key = (String) key;
System.out.println("1" + d_key); System.out.println("1" + d_key);
d_key = d_key.replace("RND;N:", "RND:")
.replace("RND;R:", "R-RND:");
d_key = d_key.replace("RND;N:", "RND:").replace("RND;R:", "R-RND:");
m.appendText("\n" + d_key + " §7-> " + data.get(key)); m.appendText("\n" + d_key + " §7-> " + data.get(key));
} }
m.send(); m.send();
return true; return true;
} }
private String getPermissionContent(Player player, String permnode) private String getPermissionContent(Player player, String permnode) {
{
Set<PermissionAttachmentInfo> perms = player.getEffectivePermissions(); Set<PermissionAttachmentInfo> perms = player.getEffectivePermissions();
for (PermissionAttachmentInfo perm : perms)
if (perm.getPermission().toString().startsWith(permnode)) for (PermissionAttachmentInfo perm : perms) if (perm.getPermission().toString().startsWith(permnode)) return perm.getPermission().replace(permnode, "");
return perm.getPermission().replace(permnode, "");
return null; return null;
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private void loadAliases(UUID uuid) private void loadAliases(UUID uuid) {
{
JSONObject defaults = new JSONObject(); JSONObject defaults = new JSONObject();
defaults.put("dataFormat", "v1"); defaults.put("dataFormat", "v1");
JSONObject data = new JSONObject(); JSONObject data = new JSONObject();
data.put("N: ./", "/"); data.put("N: ./", "/");
defaults.put("data", data); defaults.put("data", data);
JSONObject playerAliases = JsonManager
.getObject(new File(Main.plugin.getDataFolder(), "aliases/" + uuid.toString() + ".json")); JSONObject playerAliases = JsonManager.getObject(new File(Main.plugin.getDataFolder(), "aliases/" + uuid.toString() + ".json"));
if (playerAliases == null)
{ if (playerAliases == null) {
playerAliases = defaults; playerAliases = defaults;
} }
String dataFormat = (String) playerAliases.get("dataFormat"); String dataFormat = (String) playerAliases.get("dataFormat");
if (dataFormat == null)
{ if (dataFormat == null) {
JSONObject temp = new JSONObject(); JSONObject temp = new JSONObject();
temp.put("dataFormat", "v1"); temp.put("dataFormat", "v1");
JSONObject tempAliases = new JSONObject(); JSONObject tempAliases = new JSONObject();
{
for (Object key : playerAliases.keySet()) for (Object key : playerAliases.keySet()) {
{ tempAliases.put("N: " + key, playerAliases.get(key));
tempAliases.put("N: " + key, playerAliases.get(key));
}
} }
temp.put("data", tempAliases); temp.put("data", tempAliases);
aliases.put(uuid.toString(), temp.get("data")); aliases.put(uuid.toString(), temp.get("data"));
}
else if (dataFormat.equals("v1")) } else if (dataFormat.equals("v1")) {
aliases.put(uuid.toString(), playerAliases.get("data")); aliases.put(uuid.toString(), playerAliases.get("data"));
else } else {
{
getLogger().error("Unknown data format for alias set of player " + uuid.toString()); getLogger().error("Unknown data format for alias set of player " + uuid.toString());
aliases.put(uuid.toString(), ((JSONObject) defaults.get("data")).clone()); aliases.put(uuid.toString(), ((JSONObject) defaults.get("data")).clone());
saveAliases(uuid); saveAliases(uuid);
@@ -337,11 +328,12 @@ public class Chatalias implements Module, Listener
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private void saveAliases(UUID uuid) private void saveAliases(UUID uuid) {
{
JSONObject temp = new JSONObject(); JSONObject temp = new JSONObject();
temp.put("dataFormat", "v1"); temp.put("dataFormat", "v1");
temp.put("data", aliases.get(uuid.toString())); temp.put("data", aliases.get(uuid.toString()));
JsonManager.save(temp, new File(Main.plugin.getDataFolder(), "aliases/" + uuid.toString() + ".json")); JsonManager.save(temp, new File(Main.plugin.getDataFolder(), "aliases/" + uuid.toString() + ".json"));
} }
} }

View File

@@ -29,14 +29,16 @@ import com.redstoner.modules.socialspy.Socialspy;
import net.nemez.chatapi.ChatAPI; import net.nemez.chatapi.ChatAPI;
/** The ChatGroups module. Allows people to have private sub-chats that can be accessed via a single char prefix or a toggle. /**
* The ChatGroups module. Allows people to have private sub-chats that can be
* accessed via a single char prefix or a toggle.
* *
* @author Pepich */ * @author Pepich
*/
@Commands(CommandHolderType.File) @Commands(CommandHolderType.File)
@AutoRegisterListener @AutoRegisterListener
@Version(major = 4, minor = 1, revision = 0, compatible = 4) @Version(major = 4, minor = 1, revision = 0, compatible = 4)
public class Chatgroups implements Module, Listener public class Chatgroups implements Module, Listener {
{
private static final char defaultKey = ':'; private static final char defaultKey = ':';
private static final File groupsLocation = new File(Main.plugin.getDataFolder(), "chatgroups.json"); private static final File groupsLocation = new File(Main.plugin.getDataFolder(), "chatgroups.json");
private static final File keysLocation = new File(Main.plugin.getDataFolder(), "chatgroup_keys.json"); private static final File keysLocation = new File(Main.plugin.getDataFolder(), "chatgroup_keys.json");
@@ -44,17 +46,14 @@ public class Chatgroups implements Module, Listener
private static JSONObject groups, keys; private static JSONObject groups, keys;
@Override @Override
public boolean onEnable() public boolean onEnable() {
{
groups = JsonManager.getObject(groupsLocation); groups = JsonManager.getObject(groupsLocation);
if (groups == null) if (groups == null) {
{
groups = new JSONObject(); groups = new JSONObject();
saveGroups(); saveGroups();
} }
keys = JsonManager.getObject(keysLocation); keys = JsonManager.getObject(keysLocation);
if (keys == null) if (keys == null) {
{
keys = new JSONObject(); keys = new JSONObject();
saveKeys(); saveKeys();
} }
@@ -63,50 +62,40 @@ public class Chatgroups implements Module, Listener
} }
@Override @Override
public void onDisable() public void onDisable() {
{
saveKeys(); saveKeys();
saveGroups(); saveGroups();
} }
/** Prints chatgroup info (like players in the group, groupname) to the sender. /**
* Prints chatgroup info (like players in the group, groupname) to the sender.
* *
* @param sender the issuer of the command. * @param sender the issuer of the command.
* @return true. */ * @return true.
*/
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Command(hook = "cginfo") @Command(hook = "cginfo")
public boolean cgInfo(CommandSender sender) public boolean cgInfo(CommandSender sender) {
{
String group = getGroup(sender); String group = getGroup(sender);
if (group == null) if (group == null) getLogger().message(sender, true, "You are not in a chatgroup!");
getLogger().message(sender, true, "You are not in a chatgroup!"); else {
else
{
ArrayList<String> message = new ArrayList<>(); ArrayList<String> message = new ArrayList<>();
message.add("§7Your current chatgroup is: §6" + group); message.add("§7Your current chatgroup is: §6" + group);
ArrayList<String> players = new ArrayList<>(); ArrayList<String> players = new ArrayList<>();
Iterator<String> iter = groups.keySet().iterator(); Iterator<String> iter = groups.keySet().iterator();
while (iter.hasNext()) while (iter.hasNext()) {
{
String id = iter.next(); String id = iter.next();
if (((String) groups.get(id)).equals(group)) if (((String) groups.get(id)).equals(group)) {
{ if (!id.equals("CONSOLE")) {
if (!id.equals("CONSOLE"))
{
UUID uuid = UUID.fromString(id); UUID uuid = UUID.fromString(id);
Player p = Bukkit.getPlayer(uuid); Player p = Bukkit.getPlayer(uuid);
if (p != null) if (p != null) players.add(p.getDisplayName());
players.add(p.getDisplayName()); else players.add(Bukkit.getOfflinePlayer(UUID.fromString(id)).getName());
else } else players.add(id);
players.add(Bukkit.getOfflinePlayer(UUID.fromString(id)).getName());
}
else
players.add(id);
} }
} }
StringBuilder sb = new StringBuilder("&6Other players in this group: &9"); StringBuilder sb = new StringBuilder("&6Other players in this group: &9");
for (String player : players) for (String player : players) {
{
sb.append(player); sb.append(player);
sb.append("&7, &9"); sb.append("&7, &9");
} }
@@ -117,31 +106,30 @@ public class Chatgroups implements Module, Listener
return true; return true;
} }
/** Prints a Players cgkey to their chat. /**
* Prints a Players cgkey to their chat.
* *
* @param sender the issuer of the command. */ * @param sender the issuer of the command.
public void getCgKey(CommandSender sender) */
{ public void getCgKey(CommandSender sender) {
getLogger().message(sender, "Your current cgkey is §6" + getKey((Player) sender)); getLogger().message(sender, "Your current cgkey is §6" + getKey((Player) sender));
} }
/** Sets the cgkey of a Player. /**
* Sets the cgkey of a Player.
* *
* @param sender the issuer of the command. * @param sender the issuer of the command.
* @param key the key to be set. Set to NULL or "" to get your current key. * @param key the key to be set. Set to NULL or "" to get your current key.
* @return true. */ * @return true.
*/
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Command(hook = "setcgkey") @Command(hook = "setcgkey")
public boolean setCgKey(CommandSender sender, String key) public boolean setCgKey(CommandSender sender, String key) {
{ if (key.length() > 1) {
if (key.length() > 1) getLogger().message(sender, true, "Could not set your key to §6" + key + " §7, it can be at most one char.");
{
getLogger().message(sender, true,
"Could not set your key to §6" + key + " §7, it can be at most one char.");
return true; return true;
} }
if (key == null || key.length() == 0) if (key == null || key.length() == 0) {
{
getCgKey(sender); getCgKey(sender);
return true; return true;
} }
@@ -151,67 +139,61 @@ public class Chatgroups implements Module, Listener
return true; return true;
} }
/** Let's a Player toggle their auto-cg status to allow for automatically sending chat messages to their chatgroup. /**
* Lets a Player toggle their auto-cg status to allow for automatically sending
* chat messages to their chatgroup.
* *
* @param sender the issuer of the command. * @param sender the issuer of the command.
* @return true. */ * @return true.
*/
@Command(hook = "cgtoggle") @Command(hook = "cgtoggle")
public boolean cgToggleCommand(CommandSender sender) public boolean cgToggleCommand(CommandSender sender) {
{ if (getGroup(sender) != null) if (cgtoggled.contains(((Player) sender).getUniqueId())) {
if (getGroup(sender) != null) cgtoggled.remove(((Player) sender).getUniqueId());
if (cgtoggled.contains(((Player) sender).getUniqueId())) getLogger().message(sender, "CGT now §cdisabled");
{ } else {
cgtoggled.remove(((Player) sender).getUniqueId()); cgtoggled.add(((Player) sender).getUniqueId());
getLogger().message(sender, "CGT now §cdisabled"); getLogger().message(sender, "CGT now §aenabled");
} }
else else getLogger().message(sender, true, "You are not in a chatgroup!");
{
cgtoggled.add(((Player) sender).getUniqueId());
getLogger().message(sender, "CGT now §aenabled");
}
else
getLogger().message(sender, true, "You are not in a chatgroup!");
return true; return true;
} }
/** Lets a CommandSender leave their group. /**
* Lets a CommandSender leave their group.
* *
* @param sender the command issuer. * @param sender the command issuer.
* @return true. */ * @return true.
*/
@Command(hook = "cgleave") @Command(hook = "cgleave")
public boolean cgLeave(CommandSender sender) public boolean cgLeave(CommandSender sender) {
{
String group = removeGroup(sender); String group = removeGroup(sender);
if (group == null) if (group == null) {
{
getLogger().message(sender, true, "You were not in a chatgroup!"); getLogger().message(sender, true, "You were not in a chatgroup!");
return true; return true;
} }
String name = Utils.getName(sender); String name = Utils.getName(sender);
sendToGroup(group, "&9" + name + " &7left the group!"); sendToGroup(group, "&9" + name + " &7left the group!");
getLogger().message(sender, "Successfully removed you from your group!"); getLogger().message(sender, "Successfully removed you from your group!");
if (sender instanceof Player) if (sender instanceof Player) cgtoggled.remove(((Player) sender).getUniqueId());
cgtoggled.remove(((Player) sender).getUniqueId());
return true; return true;
} }
/** Lets a CommandSender join a group. /**
* Lets a CommandSender join a group.
* *
* @param sender the command issuer. * @param sender the command issuer.
* @param name the name of the group. * @param name the name of the group.
* @return true. */ * @return true.
*/
@Command(hook = "cgjoin") @Command(hook = "cgjoin")
public boolean cgJoin(CommandSender sender, String name) public boolean cgJoin(CommandSender sender, String name) {
{
String pname = Utils.getName(sender); String pname = Utils.getName(sender);
String group = getGroup(sender); String group = getGroup(sender);
if (group != null && group.equals(name)) if (group != null && group.equals(name)) getLogger().message(sender, true, "You were already in group §6" + name);
getLogger().message(sender, true, "You were already in group §6" + name); else {
else
{
setGroup(sender, null); setGroup(sender, null);
if (group != null) if (group != null) sendToGroup(group, "&9" + pname + " &7left the group!");
sendToGroup(group, "&9" + pname + " &7left the group!");
sendToGroup(name, "&9" + pname + " &7joined the group!"); sendToGroup(name, "&9" + pname + " &7joined the group!");
setGroup(sender, name); setGroup(sender, name);
getLogger().message(sender, "Successfully joined group §6" + name); getLogger().message(sender, "Successfully joined group §6" + name);
@@ -219,182 +201,163 @@ public class Chatgroups implements Module, Listener
return true; return true;
} }
/** Sends a message to a group. /**
* Sends a message to a group.
* *
* @param sender the sender of the message - the message will be sent to the group of the sender. * @param sender the sender of the message - the message will be sent to the
* group of the sender.
* @param message the message to be sent. * @param message the message to be sent.
* @return true. */ * @return true.
*/
@Command(hook = "cgsay") @Command(hook = "cgsay")
public boolean cgSay(CommandSender sender, String message) public boolean cgSay(CommandSender sender, String message) {
{
String group = getGroup(sender); String group = getGroup(sender);
if (group != null) if (group != null) sendToGroup(sender, message);
sendToGroup(sender, message); else getLogger().message(sender, true, "You are not in a chatgroup right now!");
else
getLogger().message(sender, true, "You are not in a chatgroup right now!");
return true; return true;
} }
/** Deals with chat events to allow for cgkeys and cgtoggle. /**
* Deals with chat events to allow for cgkeys and cgtoggle.
* *
* @param event the chat event containing the player and the message. */ * @param event the chat event containing the player and the message.
*/
@EventHandler @EventHandler
public void onPlayerChat(AsyncPlayerChatEvent event) public void onPlayerChat(AsyncPlayerChatEvent event) {
{
String group = getGroup(event.getPlayer()); String group = getGroup(event.getPlayer());
Player player = event.getPlayer(); Player player = event.getPlayer();
if (group != null) if (group != null) {
{ if (event.getMessage().startsWith(getKey(player))) {
if (event.getMessage().startsWith(getKey(player)))
{
event.setCancelled(true); event.setCancelled(true);
sendToGroup(event.getPlayer(), event.getMessage().substring(1)); sendToGroup(event.getPlayer(), event.getMessage().substring(1));
} } else if (cgtoggled.contains(event.getPlayer().getUniqueId())) {
else if (cgtoggled.contains(event.getPlayer().getUniqueId()))
{
event.setCancelled(true); event.setCancelled(true);
sendToGroup(event.getPlayer(), event.getMessage()); sendToGroup(event.getPlayer(), event.getMessage());
} }
} }
} }
/** Finds the group of a CommandSender. /**
* Finds the group of a CommandSender.
* *
* @param target the CommandSender to get the group of. * @param target the CommandSender to get the group of.
* @return the group of the target or NULL if he doesn't have one. */ * @return the group of the target or NULL if he doesn't have one.
public static String getGroup(CommandSender target) */
{ public static String getGroup(CommandSender target) {
if (target instanceof Player) if (target instanceof Player) return (String) groups.get(((Player) target).getUniqueId().toString());
return (String) groups.get(((Player) target).getUniqueId().toString()); else return (String) groups.get("CONSOLE");
else
return (String) groups.get("CONSOLE");
} }
/** Sets the group of the CommandSender. /**
* Sets the group of the CommandSender.
* *
* @param target the CommandSender to set the group of. * @param target the CommandSender to set the group of.
* @param group the name of the group to join. */ * @param group the name of the group to join.
*/
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private void setGroup(CommandSender target, String group) private void setGroup(CommandSender target, String group) {
{ if (target instanceof Player) groups.put(((Player) target).getUniqueId().toString(), group);
if (target instanceof Player) else groups.put("CONSOLE", group);
groups.put(((Player) target).getUniqueId().toString(), group);
else
groups.put("CONSOLE", group);
saveGroups(); saveGroups();
} }
/** Removes a CommandSender from their chatgroup. Will also save the groups after finishing /**
* Removes a CommandSender from their chatgroup. Will also save the groups after
* finishing
* *
* @param target the CommandSender to get their group removed. */ * @param target the CommandSender to get their group removed.
private String removeGroup(CommandSender target) */
{ private String removeGroup(CommandSender target) {
String group; String group;
if (target instanceof Player) if (target instanceof Player) group = (String) groups.remove(((Player) target).getUniqueId().toString());
group = (String) groups.remove(((Player) target).getUniqueId().toString()); else group = (String) groups.remove("CONSOLE");
else
group = (String) groups.remove("CONSOLE");
saveGroups(); saveGroups();
return group; return group;
} }
/** This method will find the ChatgGroup key of any player. /**
* This method will find the ChatgGroup key of any player.
* *
* @param player the player to get the key from. * @param player the player to get the key from.
* @return the key. */ * @return the key.
public static String getKey(Player player) */
{ public static String getKey(Player player) {
String key = (String) keys.get(player.getUniqueId().toString()); String key = (String) keys.get(player.getUniqueId().toString());
return (key == null ? "" + defaultKey : key); return (key == null ? "" + defaultKey : key);
} }
/** This method sends a message to a chatgroup. /**
* This method sends a message to a chatgroup.
* *
* @param sender the sender of the message. Also defines which group the message will be sent to. * @param sender the sender of the message. Also defines which group the
* @param message the message to be sent. */ * message will be sent to.
private void sendToGroup(CommandSender sender, String message) * @param message the message to be sent.
{ */
private void sendToGroup(CommandSender sender, String message) {
String name = Utils.getName(sender); String name = Utils.getName(sender);
String group = getGroup(sender); String group = getGroup(sender);
message = ChatAPI.colorify(null, message); message = ChatAPI.colorify(null, message);
BroadcastFilter ignore = ModuleLoader.exists("Ignore")? Ignore.getIgnoredBy(sender) : null; BroadcastFilter ignore = ModuleLoader.exists("Ignore") ? Ignore.getIgnoredBy(sender) : null;
Utils.broadcast("§8[§bCG§8] §9", name + "§8: §6" + message, new BroadcastFilter() Utils.broadcast("§8[§bCG§8] §9", name + "§8: §6" + message, new BroadcastFilter() {
{
@Override @Override
public boolean sendTo(CommandSender recipient) public boolean sendTo(CommandSender recipient) {
{
String rgroup = getGroup(recipient); String rgroup = getGroup(recipient);
if ( rgroup != null && (ignore == null? true : ignore.sendTo(recipient)) ) if (rgroup != null && (ignore == null ? true : ignore.sendTo(recipient))) return rgroup.equals(group);
return rgroup.equals(group); else return false;
else
return false;
} }
}); });
if (ModuleLoader.getModule("Socialspy") != null) if (ModuleLoader.getModule("Socialspy") != null) {
{ Socialspy.spyBroadcast(sender, "§e" + group + " §a(cg)", message, "/cg", new BroadcastFilter() {
Socialspy.spyBroadcast(sender, "§e" + group + " §a(cg)", message, "/cg", new BroadcastFilter()
{
@Override @Override
public boolean sendTo(CommandSender recipient) public boolean sendTo(CommandSender recipient) {
{
return getGroup(recipient) == null || !getGroup(recipient).equals(group); return getGroup(recipient) == null || !getGroup(recipient).equals(group);
} }
}); });
} }
if (getGroup(Bukkit.getConsoleSender()) == null || !getGroup(Bukkit.getConsoleSender()).equals(group)) if (getGroup(Bukkit.getConsoleSender()) == null || !getGroup(Bukkit.getConsoleSender()).equals(group)) {
{
getLogger().info(name + " in " + group + ": " + message + " §8(hidden)"); getLogger().info(name + " in " + group + ": " + message + " §8(hidden)");
} }
} }
/** This method sends a message to a chatgroup. /**
* This method sends a message to a chatgroup.
* *
* @param sender the sender of the message. Also defines which group the message will be sent to. * @param sender the sender of the message. Also defines which group the
* @param message the message to be sent. */ * message will be sent to.
private void sendToGroup(String group, String message) * @param message the message to be sent.
{ */
private void sendToGroup(String group, String message) {
message = ChatAPI.colorify(null, message); message = ChatAPI.colorify(null, message);
Utils.broadcast(null, message, new BroadcastFilter() Utils.broadcast(null, message, new BroadcastFilter() {
{
@Override @Override
public boolean sendTo(CommandSender recipient) public boolean sendTo(CommandSender recipient) {
{
String rgroup = getGroup(recipient); String rgroup = getGroup(recipient);
if (rgroup != null) if (rgroup != null) return rgroup.equals(group);
return rgroup.equals(group); else return false;
else
return false;
} }
}); });
if (ModuleLoader.getModule("Socialspy") != null) if (ModuleLoader.getModule("Socialspy") != null) {
{ Socialspy.spyBroadcast(Bukkit.getConsoleSender(), "§e" + group + " §a(cg)", message, "/cg", new BroadcastFilter() {
Socialspy.spyBroadcast(Bukkit.getConsoleSender(), "§e" + group + " §a(cg)", message, "/cg", @Override
new BroadcastFilter() public boolean sendTo(CommandSender recipient) {
{ return getGroup(recipient) == null || !getGroup(recipient).equals(group);
@Override }
public boolean sendTo(CommandSender recipient) });
{
return getGroup(recipient) == null || !getGroup(recipient).equals(group);
}
});
} }
if (getGroup(Bukkit.getConsoleSender()) == null || !getGroup(Bukkit.getConsoleSender()).equals(group)) if (getGroup(Bukkit.getConsoleSender()) == null || !getGroup(Bukkit.getConsoleSender()).equals(group)) {
{
getLogger().info("In " + group + ": " + message + " §8(hidden)"); getLogger().info("In " + group + ": " + message + " §8(hidden)");
} }
} }
/** Saves the groups. */ /** Saves the groups. */
private void saveGroups() private void saveGroups() {
{
JsonManager.save(groups, groupsLocation); JsonManager.save(groups, groupsLocation);
} }
/** Saves the keys. */ /** Saves the keys. */
private void saveKeys() private void saveKeys() {
{
JsonManager.save(keys, keysLocation); JsonManager.save(keys, keysLocation);
} }
} }

View File

@@ -37,96 +37,79 @@ import net.nemez.chatapi.click.Message;
@Commands(CommandHolderType.File) @Commands(CommandHolderType.File)
@Version(major = 4, minor = 2, revision = 0, compatible = 4) @Version(major = 4, minor = 2, revision = 0, compatible = 4)
public class Check implements Module, Listener public class Check implements Module, Listener {
{
MysqlTable table; MysqlTable table;
@Override @Override
public boolean onEnable() public boolean onEnable() {
{
Map<Serializable, Serializable> config = JSONManager.getConfiguration("check.json"); Map<Serializable, Serializable> config = JSONManager.getConfiguration("check.json");
if (config == null || !config.containsKey("database") || !config.containsKey("table"))
{ if (config == null || !config.containsKey("database") || !config.containsKey("table")) {
getLogger().error("Could not load the Check config file, disabling!"); getLogger().error("Could not load the Check config file, disabling!");
return false; return false;
} }
try
{ try {
MysqlDatabase database = MysqlHandler.INSTANCE MysqlDatabase database = MysqlHandler.INSTANCE.getDatabase((String) config.get("database") + "?autoReconnect=true");
.getDatabase((String) config.get("database") + "?autoReconnect=true");
table = database.getTable((String) config.get("table")); table = database.getTable((String) config.get("table"));
} } catch (NullPointerException e) {
catch (NullPointerException e)
{
getLogger().error("Could not use the Check config, disabling!"); getLogger().error("Could not use the Check config, disabling!");
return false; return false;
} }
return true; return true;
} }
@Override @Override
public void postEnable() public void postEnable() {
{
CommandManager.registerCommand(getCommandString(), this, Main.plugin); CommandManager.registerCommand(getCommandString(), this, Main.plugin);
} }
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
@Command(hook = "checkCommand", async = AsyncType.ALWAYS) @Command(hook = "checkCommand", async = AsyncType.ALWAYS)
public void checkCommand(final CommandSender sender, final String player) public void checkCommand(final CommandSender sender, final String player) {
{ OfflinePlayer oPlayer = Bukkit.getPlayer(player);
OfflinePlayer oPlayer; if (oPlayer == null) oPlayer = Bukkit.getServer().getOfflinePlayer(player);
oPlayer = Bukkit.getPlayer(player);
if (oPlayer == null)
oPlayer = Bukkit.getServer().getOfflinePlayer(player);
sendData(sender, oPlayer); sendData(sender, oPlayer);
if (ModuleLoader.exists("Tag"))
Bukkit.dispatchCommand(sender, "tag check " + player); if (ModuleLoader.exists("Tag")) Bukkit.dispatchCommand(sender, "tag check " + player);
} }
public String read(URL url) public String read(URL url) {
{
String data = ""; String data = "";
try
{ try {
Scanner in = new Scanner(new InputStreamReader(url.openStream())); Scanner in = new Scanner(new InputStreamReader(url.openStream()));
while (in.hasNextLine())
{ while (in.hasNextLine()) {
data += in.nextLine(); data += in.nextLine();
} }
in.close(); in.close();
return data; return data;
} } catch (IOException e) {}
catch (IOException e)
{}
return null; return null;
} }
public String[] getIpInfo(OfflinePlayer player) public String[] getIpInfo(OfflinePlayer player) {
{
String ip = ""; String ip = "";
String[] info = new String[4]; String[] info = new String[4];
if (player.isOnline()) if (player.isOnline()) {
{
ip = player.getPlayer().getAddress().getHostString(); ip = player.getPlayer().getAddress().getHostString();
} } else {
else try {
{ ip = (String) table.get("last_ip", new MysqlConstraint("uuid", ConstraintOperator.EQUAL, player.getUniqueId().toString().replace("-", "")))[0];
try } catch (Exception e) {
{
ip = (String) table.get("last_ip", new MysqlConstraint("uuid", ConstraintOperator.EQUAL,
player.getUniqueId().toString().replace("-", "")))[0];
}
catch (Exception e)
{
return null; return null;
} }
} }
try
{ try {
URL ipinfo = new URL("https://ipapi.co/" + ip + "/json"); URL ipinfo = new URL("https://ipapi.co/" + ip + "/json");
JSONObject json = (JSONObject) new JSONParser().parse( read(ipinfo) ); JSONObject json = (JSONObject) new JSONParser().parse(read(ipinfo));
info[0] = ip; info[0] = ip;
@@ -135,90 +118,85 @@ public class Check implements Module, Listener
Object o_asn = json.get("asn"); Object o_asn = json.get("asn");
Object o_org = json.get("org"); Object o_org = json.get("org");
String country = o_country == null? "Unknown" : (String) o_country; String country = o_country == null ? "Unknown" : (String) o_country;
String region = o_region == null? "" : ", " + (String) o_region; String region = o_region == null ? "" : ", " + (String) o_region;
String asn = o_asn == null? "Unknown" : (String) o_asn; String asn = o_asn == null ? "Unknown" : (String) o_asn;
String org = o_org == null? "Unknown" : (String) o_org; String org = o_org == null ? "Unknown" : (String) o_org;
info[1] = country.equals("") ? "Unknown" : country + (region.equals(", ") ? "" : region);
info[3] = asn.equals("") ? "Unknown" : asn;
info[4] = org.equals("") ? "Unknown" : org;
info[1] = country.equals("")? "Unknown" : country + (region.equals(", ")? "" : region);
info[3] = asn.equals("")? "Unknown" : asn;
info[4] = org.equals("")? "Unknown" : org;
return info; return info;
} catch (Exception e) {
e.printStackTrace();
} }
catch (Exception e)
{e.printStackTrace();}
return null; return null;
} }
public String getFirstJoin(OfflinePlayer player) public String getFirstJoin(OfflinePlayer player) {
{
Long firstJoin = player.getFirstPlayed(); Long firstJoin = player.getFirstPlayed();
Date date = new Date(firstJoin); Date date = new Date(firstJoin);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm"); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
return format.format(date); return format.format(date);
} }
public String getLastSeen(OfflinePlayer player) public String getLastSeen(OfflinePlayer player) {
{
Long lastSeen = player.getLastPlayed(); Long lastSeen = player.getLastPlayed();
Date date = new Date(lastSeen); Date date = new Date(lastSeen);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm"); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
return format.format(date); return format.format(date);
} }
public Object[] getWebsiteData(OfflinePlayer player) public Object[] getWebsiteData(OfflinePlayer player) {
{ MysqlConstraint constraint = new MysqlConstraint("uuid", ConstraintOperator.EQUAL, player.getUniqueId().toString().replace("-", ""));
MysqlConstraint constraint = new MysqlConstraint("uuid", ConstraintOperator.EQUAL,
player.getUniqueId().toString().replace("-", "")); try {
try
{
int id = (int) table.get("id", constraint)[0]; int id = (int) table.get("id", constraint)[0];
String email = (String) table.get("email", constraint)[0]; String email = (String) table.get("email", constraint)[0];
boolean confirmed = (boolean) table.get("confirmed", constraint)[0]; boolean confirmed = (boolean) table.get("confirmed", constraint)[0];
return new Object[] {"https://redstoner.com/users/" + id, email, confirmed};
} return new Object[] { "https://redstoner.com/users/" + id, email, confirmed };
catch (Exception e) } catch (Exception e) {
{ try {
try
{
int id = (int) table.get("id", constraint)[0]; int id = (int) table.get("id", constraint)[0];
String email = (String) table.get("email", constraint)[0]; String email = (String) table.get("email", constraint)[0];
boolean confirmed = (boolean) table.get("confirmed", constraint)[0]; boolean confirmed = (boolean) table.get("confirmed", constraint)[0];
return new Object[] {"https://redstoner.com/users/" + id, email, confirmed};
}
catch (Exception e2)
{}
return new Object[] {null};
return new Object[] { "https://redstoner.com/users/" + id, email, confirmed };
} catch (Exception e2) {}
return new Object[] { null };
} }
} }
public String getAllNames(OfflinePlayer player) public String getAllNames(OfflinePlayer player) {
{
String uuid = player.getUniqueId().toString().replace("-", ""); String uuid = player.getUniqueId().toString().replace("-", "");
String nameString = ""; String nameString = "";
try
{ try {
String rawJson = read(new URL("https://api.mojang.com/user/profiles/" + uuid + "/names")); String rawJson = read(new URL("https://api.mojang.com/user/profiles/" + uuid + "/names"));
JSONArray names = (JSONArray) new JSONParser().parse(rawJson); JSONArray names = (JSONArray) new JSONParser().parse(rawJson);
for (Object obj : names)
{ for (Object obj : names) {
nameString += "&e" + ((JSONObject) obj).get("name") + "&7, "; nameString += "&e" + ((JSONObject) obj).get("name") + "&7, ";
} }
nameString = nameString.substring(0, nameString.length() - 2); nameString = nameString.substring(0, nameString.length() - 2);
return nameString; return nameString;
} } catch (Exception e) {}
catch (Exception e)
{}
return "None"; return "None";
} }
public void sendData(CommandSender sender, OfflinePlayer player) public void sendData(CommandSender sender, OfflinePlayer player) {
{ try {
try
{
// data // data
String uuid = player.getUniqueId().toString(); String uuid = player.getUniqueId().toString();
String firstJoin = getFirstJoin(player); String firstJoin = getFirstJoin(player);
String lastSeen = getLastSeen(player); String lastSeen = getLastSeen(player);
firstJoin = (firstJoin.equals("1970-01-01 01:00")) ? "&eNever" : "&7(yyyy-MM-dd hh:mm) &e" + firstJoin; firstJoin = (firstJoin.equals("1970-01-01 01:00")) ? "&eNever" : "&7(yyyy-MM-dd hh:mm) &e" + firstJoin;
@@ -234,38 +212,35 @@ public class Check implements Module, Listener
String namesUsed = getAllNames(player); String namesUsed = getAllNames(player);
// messages // messages
Message msg = new Message(sender, null) Message msg = new Message(sender, null);
.appendText("\n" + getLogger().getHeader())
.appendText("\n&7Data provided by redstoner:")
.appendText("\n&6> UUID: ").appendSuggestHover("&e" + uuid, uuid, "Click to copy!")
.appendText("\n&6> First joined: &e" + firstJoin)
.appendText("\n&6> Last Seen: &e" + lastSeen)
.appendText("\n&6> Website account: &e").appendLink(websiteUrl, websiteUrl)
.appendText("\n&6> Email: &e" + (emailNotConfirmed ? "\n&6> &cEmail NOT Confirmed!" : ""))
.appendSuggestHover("&e" + email, email, "Click to copy!")
.appendText("\n\n&7Data provided by ipapi.co:");
if (ipInfo == null) msg.appendText("\n" + getLogger().getHeader());
msg.appendText("\n&7Data provided by redstoner:");
msg.appendText("\n&6> UUID: ").appendSuggestHover("&e" + uuid, uuid, "Click to copy!");
msg.appendText("\n&6> First joined: &e" + firstJoin);
msg.appendText("\n&6> Last Seen: &e" + lastSeen);
msg.appendText("\n&6> Website account: &e").appendLink(websiteUrl, websiteUrl);
msg.appendText("\n&6> Email: &e" + (emailNotConfirmed ? "\n&6> &cEmail NOT Confirmed!" : "")).appendSuggestHover("&e" + email, email, "Click to copy!");
msg.appendText("\n\n&7Data provided by ipapi.co:");
if (ipInfo == null) {
msg.appendText("\n&6> &cData Unavailable"); msg.appendText("\n&6> &cData Unavailable");
else } else {
{
String ip = ipInfo[0]; String ip = ipInfo[0];
String region = ipInfo[1]; String region = ipInfo[1];
String asn = ipInfo[2]; String asn = ipInfo[2];
String org = ipInfo[3]; String org = ipInfo[3];
msg.appendText("\n&6> IP: ").appendSuggestHover("&e" + ip, ip, "Click to copy!") msg.appendText("\n&6> IP: ").appendSuggestHover("&e" + ip, ip, "Click to copy!");
.appendText("\n&6> Region: " + region) msg.appendText("\n&6> Region: " + region);
.appendText("\n&6> ASN: ").appendSuggestHover("&e" + asn, asn, "Click to copy!") msg.appendText("\n&6> ASN: ").appendSuggestHover("&e" + asn, asn, "Click to copy!");
.appendText("\n&6> Org: ").appendSuggestHover("&e" + org, org, "Click to copy!"); msg.appendText("\n&6> Org: ").appendSuggestHover("&e" + org, org, "Click to copy!");
} }
msg.appendText("\n\n&7Data provided by mojang:") msg.appendText("\n\n&7Data provided by mojang:");
.appendText("\n&6> All ingame names used so far: &e" + namesUsed) msg.appendText("\n&6> All ingame names used so far: &e" + namesUsed);
.send(); msg.send();
} } catch (Exception e) {
catch (Exception e)
{
getLogger().message(sender, true, "Sorry, something went wrong while fetching data"); getLogger().message(sender, true, "Sorry, something went wrong while fetching data");
e.printStackTrace(); e.printStackTrace();
} }

View File

@@ -13,32 +13,30 @@ import com.redstoner.modules.Module;
@Commands(CommandHolderType.File) @Commands(CommandHolderType.File)
@Version(major = 4, minor = 1, revision = 0, compatible = 4) @Version(major = 4, minor = 1, revision = 0, compatible = 4)
public class Clear implements Module public class Clear implements Module {
{
@Command(hook = "clear") @Command(hook = "clear")
public boolean clearInventory(CommandSender sender) public boolean clearInventory(CommandSender sender) {
{
Player player = (Player) sender; Player player = (Player) sender;
Inventory inv = player.getInventory(); Inventory inv = player.getInventory();
for (int i = 0; i < 36; i++) for (int i = 0; i < 36; i++) inv.clear(i);
inv.clear(i);
getLogger().message(sender, "Cleared your inventory!"); getLogger().message(sender, "Cleared your inventory!");
return true; return true;
} }
@Command(hook = "clearother") @Command(hook = "clearother")
public boolean clearOtherInventory(CommandSender sender, String name) public boolean clearOtherInventory(CommandSender sender, String name) {
{
Player player = Bukkit.getPlayer(name); Player player = Bukkit.getPlayer(name);
if (player == null)
getLogger().message(sender, true, "That player couldn't be found!"); if (player == null) getLogger().message(sender, true, "That player couldn't be found!");
else else {
{
Inventory inv = player.getInventory(); Inventory inv = player.getInventory();
for (int i = 0; i < 36; i++) for (int i = 0; i < 36; i++) inv.clear(i);
inv.clear(i);
getLogger().message(sender, "Cleared " + player.getDisplayName() + "&7's inventory!"); getLogger().message(sender, "Cleared " + player.getDisplayName() + "&7's inventory!");
} }
return true; return true;
} }
} }

View File

@@ -25,118 +25,108 @@ import com.redstoner.modules.Module;
@Commands(CommandHolderType.File) @Commands(CommandHolderType.File)
@AutoRegisterListener @AutoRegisterListener
@Version(major = 4, minor = 1, revision = 0, compatible = 4) @Version(major = 4, minor = 1, revision = 0, compatible = 4)
public class Cycle implements Module, Listener public class Cycle implements Module, Listener {
{
private File cycleFile = new File(Main.plugin.getDataFolder(), "cycle.json"); private File cycleFile = new File(Main.plugin.getDataFolder(), "cycle.json");
private JSONArray no_cyclers; private JSONArray no_cyclers;
@Override @Override
public boolean onEnable() public boolean onEnable() {
{
no_cyclers = JsonManager.getArray(cycleFile); no_cyclers = JsonManager.getArray(cycleFile);
if (no_cyclers == null) if (no_cyclers == null) no_cyclers = new JSONArray();
no_cyclers = new JSONArray();
return true; return true;
} }
@Override @Override
public void onDisable() public void onDisable() {
{
saveCyclers(); saveCyclers();
} }
private void saveCyclers() private void saveCyclers() {
{
JsonManager.save(no_cyclers, cycleFile); JsonManager.save(no_cyclers, cycleFile);
} }
@Command(hook = "cycle_on") @Command(hook = "cycle_on")
public boolean cycleOn(CommandSender sender) public boolean cycleOn(CommandSender sender) {
{
UUID uid = ((Player) sender).getUniqueId(); UUID uid = ((Player) sender).getUniqueId();
if (no_cyclers.remove(uid.toString()))
{ if (no_cyclers.remove(uid.toString())) {
getLogger().message(sender, "Cycle enabled!"); getLogger().message(sender, "Cycle enabled!");
saveCyclers(); saveCyclers();
} } else getLogger().message(sender, "Cycle was already enabled!");
else
getLogger().message(sender, "Cycle was already enabled!");
return true; return true;
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Command(hook = "cycle_off") @Command(hook = "cycle_off")
public boolean cycleOff(CommandSender sender) public boolean cycleOff(CommandSender sender) {
{
UUID uid = ((Player) sender).getUniqueId(); UUID uid = ((Player) sender).getUniqueId();
if (!no_cyclers.contains(uid.toString()))
{ if (!no_cyclers.contains(uid.toString())) {
getLogger().message(sender, "Cycle disabled!"); getLogger().message(sender, "Cycle disabled!");
no_cyclers.add(uid.toString()); no_cyclers.add(uid.toString());
saveCyclers(); saveCyclers();
} } else getLogger().message(sender, "Cycle was already disabled!");
else
getLogger().message(sender, "Cycle was already disabled!");
return true; return true;
} }
@EventHandler @EventHandler
public void onInventoryCycle(PlayerItemHeldEvent event) public void onInventoryCycle(PlayerItemHeldEvent event) {
{
Player player = event.getPlayer(); Player player = event.getPlayer();
UUID uid = player.getUniqueId(); UUID uid = player.getUniqueId();
if (!player.getGameMode().equals(GameMode.CREATIVE) || player.isSneaking()
|| no_cyclers.contains(uid.toString())) if (!player.getGameMode().equals(GameMode.CREATIVE) || player.isSneaking() || no_cyclers.contains(uid.toString())) return;
return;
int prev_slot = event.getPreviousSlot(); int prev_slot = event.getPreviousSlot();
int new_slot = event.getNewSlot(); int new_slot = event.getNewSlot();
if (prev_slot == 0 && new_slot == 8)
shift(player, false); if (prev_slot == 0 && new_slot == 8) shift(player, false);
else if (prev_slot == 8 && new_slot == 0) else if (prev_slot == 8 && new_slot == 0) shift(player, true);
shift(player, true);
} }
private void shift(Player player, boolean down) private void shift(Player player, boolean down) {
{
Inventory inv = player.getInventory(); Inventory inv = player.getInventory();
ItemStack[] items = inv.getStorageContents(); ItemStack[] items = inv.getStorageContents();
int shift = down ? -9 : 9; int shift = down ? -9 : 9;
shift = (shift + items.length) % items.length; shift = (shift + items.length) % items.length;
for (int i = 0; i < 4; i++)
{ for (int i = 0; i < 4; i++) {
items = join(subset(items, shift, items.length), subset(items, 0, shift)); items = join(subset(items, shift, items.length), subset(items, 0, shift));
ItemStack[] hotbar = subset(items, 0, 9); ItemStack[] hotbar = subset(items, 0, 9);
boolean found = false; boolean found = false;
for (ItemStack item : hotbar)
if (item != null) for (ItemStack item : hotbar) if (item != null) {
{ found = true;
found = true;
break;
}
if (found)
break; break;
}
if (found) break;
} }
inv.setStorageContents(items); inv.setStorageContents(items);
} }
private ItemStack[] subset(ItemStack[] items, int start, int end) private ItemStack[] subset(ItemStack[] items, int start, int end) {
{
ItemStack[] result = new ItemStack[end - start]; ItemStack[] result = new ItemStack[end - start];
for (int i = start; i < end; i++)
{ for (int i = start; i < end; i++) {
result[i - start] = items[i]; result[i - start] = items[i];
} }
return result; return result;
} }
private ItemStack[] join(ItemStack[] items1, ItemStack[] items2) private ItemStack[] join(ItemStack[] items1, ItemStack[] items2) {
{
ItemStack[] result = new ItemStack[items1.length + items2.length]; ItemStack[] result = new ItemStack[items1.length + items2.length];
for (int i = 0; i < items1.length; i++)
result[i] = items1[i]; for (int i = 0; i < items1.length; i++) result[i] = items1[i];
int offset = items1.length; int offset = items1.length;
for (int i = 0; i < items2.length; i++) for (int i = 0; i < items2.length; i++) result[i + offset] = items2[i];
result[i + offset] = items2[i];
return result; return result;
} }
} }

View File

@@ -40,264 +40,271 @@ import com.redstoner.modules.Module;
@Commands(CommandHolderType.File) @Commands(CommandHolderType.File)
@AutoRegisterListener @AutoRegisterListener
@Version(major = 4, minor = 1, revision = 0, compatible = 4) @Version(major = 4, minor = 1, revision = 0, compatible = 4)
public class DamnSpam implements Module, Listener public class DamnSpam implements Module, Listener {
{
File configFile = new File(Main.plugin.getDataFolder(), "DamnSpam.json"); File configFile = new File(Main.plugin.getDataFolder(), "DamnSpam.json");
Map<String, SpamInput> inputs; Map<String, SpamInput> inputs;
boolean changingInput = false;
List<Material> acceptedInputs; List<Material> acceptedInputs;
HashMap<Material, int[][]> attachedBlocks; HashMap<Material, int[][]> attachedBlocks;
HashMap<Player, SpamInput> players; HashMap<Player, SpamInput> players;
boolean changingInput = false;
int maxTimeout = 240; int maxTimeout = 240;
String timeoutErrorString = "The timeout must be -1 or within 0 and " + maxTimeout; String timeoutErrorString = "The timeout must be -1 or within 0 and " + maxTimeout;
private static final BlockFace[] DIRECTIONS = { BlockFace.DOWN, BlockFace.UP, BlockFace.NORTH, BlockFace.SOUTH, BlockFace.WEST, BlockFace.EAST };
private static final int[][] LEVER_ATTACHED_BLOCKS = new int[][] { { 0, 7, 8, 15 }, { 5, 6, 13, 14 }, { 4, 12 }, { 3, 11 }, { 2, 10 }, { 1, 9 } };
private static final int[][] BUTTON_ATTACHED_BLOCKS = new int[][] { { 0, 8 }, { 5, 6, 7, 13, 14, 15 }, { 4, 12 }, { 3, 11 }, { 2, 10 }, { 1, 9 } };
// @formatter:off
private static final Material[] BUTTONS = {
Material.ACACIA_BUTTON,
Material.BIRCH_BUTTON,
Material.DARK_OAK_BUTTON,
Material.JUNGLE_BUTTON,
Material.OAK_BUTTON,
Material.SPRUCE_BUTTON,
Material.STONE_BUTTON
};
// @formatter:on
@Override @Override
public boolean onEnable() public boolean onEnable() {
{
loadInputs(); loadInputs();
acceptedInputs = new ArrayList<Material>(); acceptedInputs = new ArrayList<Material>();
Collections.addAll(acceptedInputs, Material.WOOD_BUTTON, Material.STONE_BUTTON, Material.LEVER); acceptedInputs.add(Material.LEVER);
Collections.addAll(acceptedInputs, BUTTONS);
attachedBlocks = new HashMap<Material, int[][]>(); attachedBlocks = new HashMap<Material, int[][]>();
attachedBlocks.put(Material.LEVER, attachedBlocks.put(Material.LEVER, LEVER_ATTACHED_BLOCKS);
new int[][] {{0, 7, 8, 15}, {5, 6, 13, 14}, {4, 12}, {3, 11}, {2, 10}, {1, 9}});
attachedBlocks.put(Material.STONE_BUTTON, for (Material button : BUTTONS) {
new int[][] {{0, 8}, {5, 6, 7, 13, 14, 15}, {4, 12}, {3, 11}, {2, 10}, {1, 9}}); attachedBlocks.put(button, BUTTON_ATTACHED_BLOCKS);
attachedBlocks.put(Material.WOOD_BUTTON, }
new int[][] {{0, 8}, {5, 6, 7, 13, 14, 15}, {4, 12}, {3, 11}, {2, 10}, {1, 9}});
players = new HashMap<Player, SpamInput>(); players = new HashMap<Player, SpamInput>();
return true; return true;
} }
public void loadInputs() public void loadInputs() {
{
inputs = new HashMap<String, SpamInput>(); inputs = new HashMap<String, SpamInput>();
try
{ try {
FileReader reader = new FileReader(configFile); FileReader reader = new FileReader(configFile);
JSONObject json = (JSONObject) new JSONParser().parse(reader); JSONObject json = (JSONObject) new JSONParser().parse(reader);
for (Object key : json.keySet())
{ for (Object key : json.keySet()) {
JSONObject inputData = (JSONObject) json.get(key); JSONObject inputData = (JSONObject) json.get(key);
String uuid = (String) inputData.get("creator"); String uuid = (String) inputData.get("creator");
Double timeoutOn = (Double) inputData.get("timeout_on"); Double timeoutOn = (Double) inputData.get("timeout_on");
Double timeoutOff = (Double) inputData.get("timeout_off"); Double timeoutOff = (Double) inputData.get("timeout_off");
Double lastTime = (Double) inputData.get("last_time"); Double lastTime = (Double) inputData.get("last_time");
inputs.put((String) key, new SpamInput(uuid, timeoutOff, timeoutOn, lastTime)); inputs.put((String) key, new SpamInput(uuid, timeoutOff, timeoutOn, lastTime));
} }
} } catch (IOException | ParseException e) {
catch (IOException | ParseException e)
{
e.printStackTrace(); e.printStackTrace();
} }
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public void saveInputs() public void saveInputs() {
{
JSONObject json = new JSONObject(); JSONObject json = new JSONObject();
for (String key : inputs.keySet())
{ for (String key : inputs.keySet()) {
JSONObject jsonInput = new JSONObject(); JSONObject jsonInput = new JSONObject();
SpamInput input = inputs.get(key); SpamInput input = inputs.get(key);
jsonInput.put("creator", input.player); jsonInput.put("creator", input.player);
jsonInput.put("timeout_on", input.timeoutOn); jsonInput.put("timeout_on", input.timeoutOn);
jsonInput.put("timeout_off", input.timeoutOff); jsonInput.put("timeout_off", input.timeoutOff);
jsonInput.put("last_time", input.lastTime); jsonInput.put("last_time", input.lastTime);
json.put(key, jsonInput); json.put(key, jsonInput);
} }
try try {
{
PrintWriter writer = new PrintWriter(configFile); PrintWriter writer = new PrintWriter(configFile);
writer.write(json.toJSONString()); writer.write(json.toJSONString());
writer.close(); writer.close();
} } catch (FileNotFoundException e) {
catch (FileNotFoundException e)
{
e.printStackTrace(); e.printStackTrace();
} }
} }
public String locationString(Location loc) public String locationString(Location loc) {
{
return loc.getWorld().getName() + ";" + loc.getBlockX() + ";" + loc.getBlockY() + ";" + loc.getBlockZ(); return loc.getWorld().getName() + ";" + loc.getBlockX() + ";" + loc.getBlockY() + ";" + loc.getBlockZ();
} }
public boolean isAcceptableTimeout(double timeout) public boolean isAcceptableTimeout(double timeout) {
{
return (timeout > 0 && timeout <= maxTimeout) || timeout == -1; return (timeout > 0 && timeout <= maxTimeout) || timeout == -1;
} }
public boolean canBuild(Player player, Block block) public boolean canBuild(Player player, Block block) {
{
BlockBreakEvent event = new BlockBreakEvent(block, player); BlockBreakEvent event = new BlockBreakEvent(block, player);
Bukkit.getPluginManager().callEvent(event); Bukkit.getPluginManager().callEvent(event);
return !event.isCancelled(); return !event.isCancelled();
} }
@Command(hook = "damnspamSingle") @Command(hook = "damnspamSingle")
public void damnspam(CommandSender sender, double seconds) public void damnspam(CommandSender sender, double seconds) {
{
boolean destroyingInput = false; boolean destroyingInput = false;
seconds = (double) Math.round(seconds * 100) / 100; seconds = (double) Math.round(seconds * 100) / 100;
if (seconds == 0)
destroyingInput = true; if (seconds == 0) destroyingInput = true;
else if (!isAcceptableTimeout(seconds)) else if (!isAcceptableTimeout(seconds)) {
{
getLogger().message(sender, true, "The timeout must be -1 or within 0 and " + maxTimeout); getLogger().message(sender, true, "The timeout must be -1 or within 0 and " + maxTimeout);
return; return;
} }
getLogger().message(sender, "Please click the input you would like to set."); getLogger().message(sender, "Please click the input you would like to set.");
setPlayer((Player) sender, destroyingInput, seconds, seconds); setPlayer((Player) sender, destroyingInput, seconds, seconds);
} }
@Command(hook = "damnspamDouble") @Command(hook = "damnspamDouble")
public void damnspam(CommandSender sender, double secondsOff, double secondsOn) public void damnspam(CommandSender sender, double secondsOff, double secondsOn) {
{
boolean destroyingInput = false; boolean destroyingInput = false;
secondsOn = (double) Math.round(secondsOn * 100) / 100; secondsOn = (double) Math.round(secondsOn * 100) / 100;
secondsOff = (double) Math.round(secondsOff * 100) / 100; secondsOff = (double) Math.round(secondsOff * 100) / 100;
if (secondsOn == 0 && secondsOff == 0)
{ if (secondsOn == 0 && secondsOff == 0) {
destroyingInput = true; destroyingInput = true;
} } else if (!(isAcceptableTimeout(secondsOn) && isAcceptableTimeout(secondsOff))) {
else if (!(isAcceptableTimeout(secondsOn) && isAcceptableTimeout(secondsOff)))
{
getLogger().message(sender, true, "The timeout must be -1 or within 0 and " + maxTimeout); getLogger().message(sender, true, "The timeout must be -1 or within 0 and " + maxTimeout);
return; return;
} }
getLogger().message(sender, "Please click the input you would like to set."); getLogger().message(sender, "Please click the input you would like to set.");
setPlayer((Player) sender, destroyingInput, secondsOff, secondsOn); setPlayer((Player) sender, destroyingInput, secondsOff, secondsOn);
} }
public void setPlayer(Player player, boolean destroying, double timeoutOff, double timeoutOn) public void setPlayer(Player player, boolean destroying, double timeoutOff, double timeoutOn) {
{
SpamInput input = null; SpamInput input = null;
if (!destroying)
{ if (!destroying) {
input = new SpamInput(player.getUniqueId().toString(), timeoutOff, timeoutOn, 0); input = new SpamInput(player.getUniqueId().toString(), timeoutOff, timeoutOn, 0);
} }
players.put(player, input); players.put(player, input);
} }
public boolean attemptInputRegister(Player player, Block block, Cancellable event) public boolean attemptInputRegister(Player player, Block block, Cancellable event) {
{ if (players.containsKey(player)) {
if (players.containsKey(player)) if (!acceptedInputs.contains(block.getType())) {
{
if (!acceptedInputs.contains(block.getType()))
{
getLogger().message(player, true, "That block is not an acceptable input!"); getLogger().message(player, true, "That block is not an acceptable input!");
return true; return true;
} }
String typeStr = block.getType().toString().toLowerCase().replace("_", " "); String typeStr = block.getType().toString().toLowerCase().replace("_", " ");
String locationStr = locationString(block.getLocation()); String locationStr = locationString(block.getLocation());
changingInput = true; changingInput = true;
boolean buildCheck = canBuild(player, block); boolean buildCheck = canBuild(player, block);
changingInput = false; changingInput = false;
if (!buildCheck)
{ if (!buildCheck) {
getLogger().message(player, true, getLogger().message(player, true, "Something went wrong trying to change the timeout on this " + typeStr + "!");
"Something went wrong trying to change the timeout on this " + typeStr + "!");
event.setCancelled(true); event.setCancelled(true);
return true; return true;
} }
SpamInput input = players.get(player); SpamInput input = players.get(player);
if (input == null)
{ if (input == null) {
if (!inputs.containsKey(locationStr)) if (!inputs.containsKey(locationStr)) {
{ getLogger().message(player, true, "Something went wrong trying to change the timeout on this " + typeStr + "!");
getLogger().message(player, true,
"Something went wrong trying to change the timeout on this " + typeStr + "!");
event.setCancelled(true); event.setCancelled(true);
return true; return true;
} }
inputs.remove(locationStr); inputs.remove(locationStr);
getLogger().message(player, "Successfully removed the timeout for this " + typeStr); getLogger().message(player, "Successfully removed the timeout for this " + typeStr);
} } else {
else
{
inputs.put(locationStr, players.get(player)); inputs.put(locationStr, players.get(player));
getLogger().message(player, "Successfully set a timeout for this " + typeStr); getLogger().message(player, "Successfully set a timeout for this " + typeStr);
} }
event.setCancelled(true); event.setCancelled(true);
players.remove(player); players.remove(player);
saveInputs(); saveInputs();
return true; return true;
} }
return false; return false;
} }
public void checkBlockBreak(BlockBreakEvent event, Block block) public void checkBlockBreak(BlockBreakEvent event, Block block) {
{ if (!acceptedInputs.contains(block.getType())) return;
if (!acceptedInputs.contains(block.getType()))
return;
String posStr = locationString(block.getLocation()); String posStr = locationString(block.getLocation());
if (!inputs.containsKey(posStr)) if (!inputs.containsKey(posStr)) return;
return;
SpamInput input = inputs.get(posStr); SpamInput input = inputs.get(posStr);
Player sender = event.getPlayer(); Player sender = event.getPlayer();
String typeStr = block.getType().toString().toLowerCase().replace("_", " "); String typeStr = block.getType().toString().toLowerCase().replace("_", " ");
String inputStr = (block.getLocation().equals(event.getBlock()) ? "this " + typeStr String inputStr = (block.getLocation().equals(event.getBlock()) ? "this " + typeStr : "the " + typeStr + " attached to that block");
: "the " + typeStr + " attached to that block");
if (!sender.isSneaking()) if (!sender.isSneaking()) {
{
getLogger().message(sender, true, "You cannot destroy " + inputStr); getLogger().message(sender, true, "You cannot destroy " + inputStr);
getLogger().message(sender, true, "Sneak and break or set the timeout to 0 if you want to remove it."); getLogger().message(sender, true, "Sneak and break or set the timeout to 0 if you want to remove it.");
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
if (sender.hasPermission("damnspam.admin") || sender.getUniqueId().toString().equals(input.player))
{ if (sender.hasPermission("damnspam.admin") || sender.getUniqueId().toString().equals(input.player)) {
inputs.remove(posStr); inputs.remove(posStr);
saveInputs(); saveInputs();
getLogger().message(sender, "Succesfully removed " + inputStr); getLogger().message(sender, "Succesfully removed " + inputStr);
} } else {
else
{
getLogger().message(sender, true, "You are not allowed to remove " + inputStr); getLogger().message(sender, true, "You are not allowed to remove " + inputStr);
event.setCancelled(true); event.setCancelled(true);
} }
} }
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public List<Block> getAttachedBlocks(Block block) public List<Block> getAttachedBlocks(Block block) {
{
List<Block> blocks = new ArrayList<Block>(); List<Block> blocks = new ArrayList<Block>();
BlockFace[] directions = {BlockFace.DOWN, BlockFace.UP, BlockFace.NORTH, BlockFace.SOUTH, BlockFace.WEST,
BlockFace.EAST}; for (int i = 0; i < DIRECTIONS.length; i++) {
for (int i = 0; i < directions.length; i++) Block side = block.getRelative(DIRECTIONS[i]);
{
Block side = block.getRelative(directions[i]);
int[][] dvalues = attachedBlocks.get(side.getType()); int[][] dvalues = attachedBlocks.get(side.getType());
if (dvalues != null)
{ if (dvalues != null) {
boolean onSide = false; boolean onSide = false;
for (int val : dvalues[i])
{ for (int val : dvalues[i]) {
if (side.getData() == (byte) val) if (side.getData() == (byte) val) {
{
onSide = true; onSide = true;
break; break;
} }
} }
if (onSide)
blocks.add(side); if (onSide) blocks.add(side);
} }
} }
return blocks; return blocks;
} }
@EventHandler(priority = EventPriority.NORMAL) @EventHandler(priority = EventPriority.NORMAL)
public void onBreak(BlockBreakEvent event) public void onBreak(BlockBreakEvent event) {
{ if (changingInput || event.isCancelled()) return;
if (changingInput || event.isCancelled())
return;
boolean register = attemptInputRegister(event.getPlayer(), event.getBlock(), event); boolean register = attemptInputRegister(event.getPlayer(), event.getBlock(), event);
if (!register)
{ if (!register) {
Block block = event.getBlock(); Block block = event.getBlock();
checkBlockBreak(event, block); checkBlockBreak(event, block);
for (Block affected : getAttachedBlocks(block))
{ for (Block affected : getAttachedBlocks(block)) {
checkBlockBreak(event, affected); checkBlockBreak(event, affected);
} }
} }
@@ -305,43 +312,36 @@ public class DamnSpam implements Module, Listener
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
@EventHandler(priority = EventPriority.HIGHEST) @EventHandler(priority = EventPriority.HIGHEST)
public void onInteract(PlayerInteractEvent event) public void onInteract(PlayerInteractEvent event) {
{ if (event.getClickedBlock() == null) return;
if (event.getClickedBlock() == null)
return;
boolean register = attemptInputRegister(event.getPlayer(), event.getClickedBlock(), event); boolean register = attemptInputRegister(event.getPlayer(), event.getClickedBlock(), event);
if (!register && event.getAction().equals(Action.RIGHT_CLICK_BLOCK) && !event.isCancelled())
{ if (!register && event.getAction().equals(Action.RIGHT_CLICK_BLOCK) && !event.isCancelled()) {
Player sender = event.getPlayer(); Player sender = event.getPlayer();
Block block = event.getClickedBlock(); Block block = event.getClickedBlock();
String posStr = locationString(block.getLocation()); String posStr = locationString(block.getLocation());
SpamInput data = inputs.get(posStr); SpamInput data = inputs.get(posStr);
if (data != null)
{ if (data != null) {
String btype = block.getType().toString().toLowerCase().replace("_", " "); String btype = block.getType().toString().toLowerCase().replace("_", " ");
double checktime = 0; double checktime = 0;
if (btype.equals("lever") && block.getData() < 8)
checktime = data.timeoutOff; if (btype.equals("lever") && block.getData() < 8) checktime = data.timeoutOff;
else else checktime = data.timeoutOn;
checktime = data.timeoutOn;
double timeLeft = (data.lastTime + checktime) double timeLeft = (data.lastTime + checktime) - ((double) Math.round((double) System.currentTimeMillis() / 10) / 100);
- ((double) Math.round((double) System.currentTimeMillis() / 10) / 100);
timeLeft = (double) Math.round(timeLeft * 100) / 100; timeLeft = (double) Math.round(timeLeft * 100) / 100;
if (checktime == -1)
{ if (checktime == -1) {
event.setCancelled(true); event.setCancelled(true);
getLogger().message(sender, "This " + btype + " is locked permanently by /damnspam."); getLogger().message(sender, "This " + btype + " is locked permanently by /damnspam.");
} } else if (timeLeft > 0) {
else if (timeLeft > 0)
{
event.setCancelled(true); event.setCancelled(true);
getLogger().message(sender, "This " + btype + " has a damnspam timeout of " + checktime + ", with " getLogger().message(sender, "This " + btype + " has a damnspam timeout of " + checktime + ", with " + timeLeft + " left.");
+ timeLeft + " left."); } else {
}
else
{
data.lastTime = (double) Math.round((double) System.currentTimeMillis() / 10) / 100; data.lastTime = (double) Math.round((double) System.currentTimeMillis() / 10) / 100;
} }
inputs.put(posStr, data); inputs.put(posStr, data);
} }
} }

View File

@@ -2,10 +2,10 @@ package com.redstoner.modules.damnspam;
public class SpamInput { public class SpamInput {
protected String player; protected String player;
protected double timeoutOn; protected double timeoutOn;
protected double timeoutOff; protected double timeoutOff;
protected double lastTime; protected double lastTime;
protected SpamInput(String player, double timeoutOff, double timeoutOn, double lastTime) { protected SpamInput(String player, double timeoutOff, double timeoutOn, double lastTime) {
this.player = player; this.player = player;