Run through new formatter.

This commit is contained in:
SuPaH sPii committed 2012-12-22 00:28:37 -06:00
1 parent b48e97a799
commit 170f4dd946
34 files changed
+1311 -2825

No files matched your search

+55 -111
View File
@@ -43,8 +43,7 @@ import org.bukkit.entity.Player;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
public class Anticheat extends JavaPlugin public class Anticheat extends JavaPlugin {
{
private static AnticheatManager manager; private static AnticheatManager manager;
private static List<Listener> eventList = new ArrayList<Listener>(); private static List<Listener> eventList = new ArrayList<Listener>();
private static boolean update = false; private static boolean update = false;
@@ -55,8 +54,7 @@ public class Anticheat extends JavaPlugin
public static final String SPY_METADATA = "ac-spydata"; public static final String SPY_METADATA = "ac-spydata";
@Override @Override
public void onEnable() public void onEnable() {
{
manager = new AnticheatManager(this, getLogger()); manager = new AnticheatManager(this, getLogger());
eventList.add(new PlayerListener()); eventList.add(new PlayerListener());
eventList.add(new BlockListener()); eventList.add(new BlockListener());
@@ -73,12 +71,9 @@ public class Anticheat extends JavaPlugin
setupMetrics(); setupMetrics();
restoreLevels(); restoreLevels();
// Test for compatibility for 1.4.5-R1.0 // Test for compatibility for 1.4.5-R1.0
try try {
{
Material.AIR.isSolid(); Material.AIR.isSolid();
} } catch (NoSuchMethodError error) {
catch(NoSuchMethodError error)
{
getLogger().severe("You are using an outdated version of CraftBukkit that does not contain the API required for AntiCheat to run properly."); getLogger().severe("You are using an outdated version of CraftBukkit that does not contain the API required for AntiCheat to run properly.");
getLogger().severe("Please update to CraftBukkit 1.4.5-R1.0 or higher by visiting dl.bukkit.org and hitting the green download button."); getLogger().severe("Please update to CraftBukkit 1.4.5-R1.0 or higher by visiting dl.bukkit.org and hitting the green download button.");
getLogger().severe("AntiCheat will now be disabled, and will not protect your server until it is updated."); getLogger().severe("AntiCheat will now be disabled, and will not protect your server until it is updated.");
@@ -86,18 +81,15 @@ public class Anticheat extends JavaPlugin
return; return;
} }
// End test // End test
if (verbose) if (verbose) {
{
getLogger().log(Level.INFO, "Finished loading."); getLogger().log(Level.INFO, "Finished loading.");
} }
} }
@Override @Override
public void onDisable() public void onDisable() {
{
AnticheatManager.close(); AnticheatManager.close();
for(User user : manager.getUserManager().getUsers()) for (User user : manager.getUserManager().getUsers()) {
{
config.saveLevel(user.getName(), user.getLevel()); config.saveLevel(user.getName(), user.getLevel());
} }
config.saveLevels(); config.saveLevels();
@@ -105,52 +97,38 @@ public class Anticheat extends JavaPlugin
cleanup(); cleanup();
} }
private void save(InputStream in, File file) private void save(InputStream in, File file) {
{ if (!file.exists()) {
if (!file.exists())
{
file.getParentFile().mkdirs(); file.getParentFile().mkdirs();
try try {
{
OutputStream out = new FileOutputStream(file); OutputStream out = new FileOutputStream(file);
byte[] buf = new byte[1024]; byte[] buf = new byte[1024];
int len; int len;
while((len=in.read(buf))>0) while ((len = in.read(buf)) > 0) {
{ out.write(buf, 0, len);
out.write(buf,0,len);
} }
out.close(); out.close();
in.close(); in.close();
} } catch (Exception e) {
catch (Exception e)
{
getLogger().severe("Unable to save files. Is the directory writeable?"); getLogger().severe("Unable to save files. Is the directory writeable?");
} }
if (verbose) if (verbose) {
{ getLogger().log(Level.INFO, file.getName() + " created.");
getLogger().log(Level.INFO, file.getName()+" created.");
} }
} }
} }
private void setupXray() private void setupXray() {
{
final XRayTracker xtracker = manager.getXRayTracker(); final XRayTracker xtracker = manager.getXRayTracker();
if (config.logXRay()) if (config.logXRay()) {
{
eventList.add(new XRayListener()); eventList.add(new XRayListener());
if (config.alertXRay()) if (config.alertXRay()) {
{ getServer().getScheduler().scheduleAsyncRepeatingTask(this, new Runnable() {
getServer().getScheduler().scheduleAsyncRepeatingTask(this, new Runnable()
{
@Override @Override
public void run() public void run() {
{ for (Player player : getServer().getOnlinePlayers()) {
for (Player player : getServer().getOnlinePlayers())
{
String name = player.getName(); String name = player.getName();
if (!xtracker.hasAlerted(name) && xtracker.sufficientData(name) && xtracker.hasAbnormal(name)) if (!xtracker.hasAlerted(name) && xtracker.sufficientData(name) && xtracker.hasAbnormal(name)) {
{
List<String> alert = new ArrayList<String>(); List<String> alert = new ArrayList<String>();
alert.add(ChatColor.YELLOW + "[ALERT] " + ChatColor.WHITE + name + ChatColor.YELLOW + " might be using xray."); alert.add(ChatColor.YELLOW + "[ALERT] " + ChatColor.WHITE + name + ChatColor.YELLOW + " might be using xray.");
alert.add(ChatColor.YELLOW + "[ALERT] Please check their xray stats using " + ChatColor.WHITE + "/anticheat xray " + name + ChatColor.YELLOW + "."); alert.add(ChatColor.YELLOW + "[ALERT] Please check their xray stats using " + ChatColor.WHITE + "/anticheat xray " + name + ChatColor.YELLOW + ".");
@@ -160,152 +138,118 @@ public class Anticheat extends JavaPlugin
} }
} }
}, XRAY_TIME, XRAY_TIME); }, XRAY_TIME, XRAY_TIME);
if (verbose) if (verbose) {
{
getLogger().log(Level.INFO, "Scheduled the XRay checker."); getLogger().log(Level.INFO, "Scheduled the XRay checker.");
} }
} }
} }
} }
private void setupEvents() private void setupEvents() {
{ for (Listener listener : eventList) {
for (Listener listener : eventList)
{
getServer().getPluginManager().registerEvents(listener, this); getServer().getPluginManager().registerEvents(listener, this);
if (verbose) if (verbose) {
{
getLogger().log(Level.INFO, "Registered events for ".concat(listener.toString().split("@")[0].split(".anticheat.")[1])); getLogger().log(Level.INFO, "Registered events for ".concat(listener.toString().split("@")[0].split(".anticheat.")[1]));
} }
} }
} }
private void setupCommands() private void setupCommands() {
{
getCommand("anticheat").setExecutor(new CommandHandler()); getCommand("anticheat").setExecutor(new CommandHandler());
if (verbose) if (verbose) {
{
getLogger().log(Level.INFO, "Registered commands."); getLogger().log(Level.INFO, "Registered commands.");
} }
} }
private void setupUpdater() private void setupUpdater() {
{ if (config.autoUpdate()) {
if (config.autoUpdate()) if (verbose) {
{
if (verbose)
{
getLogger().log(Level.INFO, "Checking for a new update..."); getLogger().log(Level.INFO, "Checking for a new update...");
} }
Updater updater = new Updater(this, "anticheat", this.getFile(), Updater.UpdateType.DEFAULT, false); Updater updater = new Updater(this, "anticheat", this.getFile(), Updater.UpdateType.DEFAULT, false);
update = updater.getResult() != Updater.UpdateResult.NO_UPDATE; update = updater.getResult() != Updater.UpdateResult.NO_UPDATE;
if (verbose) if (verbose) {
{ getLogger().log(Level.INFO, "Update avaliable: " + update);
getLogger().log(Level.INFO, "Update avaliable: "+update);
} }
} }
} }
private void setupMetrics() private void setupMetrics() {
{ try {
try
{
metrics = new Metrics(this); metrics = new Metrics(this);
final EventListener listener = new EventListener(); final EventListener listener = new EventListener();
Graph hacksGraph = metrics.createGraph("Hacks blocked"); Graph hacksGraph = metrics.createGraph("Hacks blocked");
for (final CheckType type : CheckType.values()) for (final CheckType type : CheckType.values()) {
{ hacksGraph.addPlotter(new Metrics.Plotter(CheckType.getName(type)) {
hacksGraph.addPlotter(new Metrics.Plotter(CheckType.getName(type))
{
@Override @Override
public int getValue() public int getValue() {
{
return EventListener.getCheats(type); return EventListener.getCheats(type);
} }
}); });
listener.resetCheck(type); listener.resetCheck(type);
} }
Graph apiGraph = metrics.createGraph("API Usage"); Graph apiGraph = metrics.createGraph("API Usage");
apiGraph.addPlotter(new Metrics.Plotter("Checks disabled") apiGraph.addPlotter(new Metrics.Plotter("Checks disabled") {
{
@Override @Override
public int getValue() public int getValue() {
{
return manager.getCheckManager().getDisabled(); return manager.getCheckManager().getDisabled();
} }
}); });
apiGraph.addPlotter(new Metrics.Plotter("Players exempted") apiGraph.addPlotter(new Metrics.Plotter("Players exempted") {
{
@Override @Override
public int getValue() public int getValue() {
{
return manager.getCheckManager().getExempt(); return manager.getCheckManager().getExempt();
} }
}); });
metrics.start(); metrics.start();
if (verbose) if (verbose) {
{
getLogger().log(Level.INFO, "Metrics started."); getLogger().log(Level.INFO, "Metrics started.");
} }
} } catch (IOException ex) {}
catch (IOException ex)
{
}
} }
private void setupConfig() private void setupConfig() {
{
config = manager.getConfiguration(); config = manager.getConfiguration();
checkConfigs(); checkConfigs();
verbose = config.verboseStartup(); verbose = config.verboseStartup();
if (verbose) if (verbose) {
{
getLogger().log(Level.INFO, "Setup the config."); getLogger().log(Level.INFO, "Setup the config.");
} }
} }
private void restoreLevels() private void restoreLevels() {
{ for (Player player : getServer().getOnlinePlayers()) {
for (Player player : getServer().getOnlinePlayers())
{
String name = player.getName(); String name = player.getName();
manager.getUserManager().addUser(new User(player.getName(), config.getLevel(name))); manager.getUserManager().addUser(new User(player.getName(), config.getLevel(name)));
if (verbose) if (verbose) {
{
getLogger().log(Level.INFO, "Data for " + player.getName() + " re-applied from flatfile"); getLogger().log(Level.INFO, "Data for " + player.getName() + " re-applied from flatfile");
} }
} }
} }
public void checkConfigs() public void checkConfigs() {
{
save(getResource("config.yml"), new File(getDataFolder() + "/config.yml")); save(getResource("config.yml"), new File(getDataFolder() + "/config.yml"));
save(getResource("lang.yml"), new File(getDataFolder() + "/lang.yml")); save(getResource("lang.yml"), new File(getDataFolder() + "/lang.yml"));
save(getResource("magic.yml"), new File(getDataFolder() + "/magic.yml")); save(getResource("magic.yml"), new File(getDataFolder() + "/magic.yml"));
} }
public static Anticheat getPlugin() public static Anticheat getPlugin() {
{
return manager.getPlugin(); return manager.getPlugin();
} }
public static AnticheatManager getManager() public static AnticheatManager getManager() {
{
return manager; return manager;
} }
public static boolean isUpdated() public static boolean isUpdated() {
{
return !update; return !update;
} }
public static String getVersion() public static String getVersion() {
{
return manager.getPlugin().getDescription().getVersion(); return manager.getPlugin().getDescription().getVersion();
} }
private void cleanup() private void cleanup() {
{
eventList = null; eventList = null;
manager = null; manager = null;
config = null; config = null;
@@ -35,8 +35,7 @@ import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.metadata.FixedMetadataValue; import org.bukkit.metadata.FixedMetadataValue;
public class CommandHandler implements CommandExecutor public class CommandHandler implements CommandExecutor {
{
private static final Configuration CONFIG = Anticheat.getManager().getConfiguration(); private static final Configuration CONFIG = Anticheat.getManager().getConfiguration();
private static final UserManager USER_MANAGER = Anticheat.getManager().getUserManager(); private static final UserManager USER_MANAGER = Anticheat.getManager().getUserManager();
private static final XRayTracker XRAY_TRACKER = Anticheat.getManager().getXRayTracker(); private static final XRayTracker XRAY_TRACKER = Anticheat.getManager().getXRayTracker();
@@ -54,160 +53,105 @@ public class CommandHandler implements CommandExecutor
private static final String PERMISSIONS_ERROR = RED + "Insufficient Permissions."; private static final String PERMISSIONS_ERROR = RED + "Insufficient Permissions.";
private static final String MENU_END = "-----------------------------------------------------"; private static final String MENU_END = "-----------------------------------------------------";
public void handleLog(CommandSender cs, String[] args) public void handleLog(CommandSender cs, String[] args) {
{ if (Permission.SYSTEM_LOG.get(cs)) {
if (Permission.SYSTEM_LOG.get(cs)) if (args[1].equalsIgnoreCase("enable")) {
{ if (!CONFIG.logConsole()) {
if (args[1].equalsIgnoreCase("enable"))
{
if (!CONFIG.logConsole())
{
CONFIG.setLog(true); CONFIG.setLog(true);
cs.sendMessage(GREEN + "Console logging enabled."); cs.sendMessage(GREEN + "Console logging enabled.");
} } else {
else
{
cs.sendMessage(GREEN + "Console logging is already enabled!"); cs.sendMessage(GREEN + "Console logging is already enabled!");
} }
} } else if (args[1].equalsIgnoreCase("disable")) {
else if (args[1].equalsIgnoreCase("disable")) if (CONFIG.logConsole()) {
{
if (CONFIG.logConsole())
{
CONFIG.setLog(false); CONFIG.setLog(false);
cs.sendMessage(GREEN + "Console logging disabled."); cs.sendMessage(GREEN + "Console logging disabled.");
} } else {
else
{
cs.sendMessage(GREEN + "Console logging is already disabled!"); cs.sendMessage(GREEN + "Console logging is already disabled!");
} }
} } else {
else
{
cs.sendMessage(RED + "Usage: /anticheat log [enable/disable]"); cs.sendMessage(RED + "Usage: /anticheat log [enable/disable]");
} }
} } else {
else
{
cs.sendMessage(PERMISSIONS_ERROR); cs.sendMessage(PERMISSIONS_ERROR);
} }
} }
public void handleDebug(CommandSender cs) public void handleDebug(CommandSender cs) {
{ if (Permission.SYSTEM_REPORT.get(cs)) {
if (Permission.SYSTEM_REPORT.get(cs))
{
PastebinReport report = new PastebinReport(cs); PastebinReport report = new PastebinReport(cs);
cs.sendMessage(GREEN + "Debug information posted to: " + WHITE + report.getURL()); cs.sendMessage(GREEN + "Debug information posted to: " + WHITE + report.getURL());
cs.sendMessage(GREEN + "Please include this link when making bug reports."); cs.sendMessage(GREEN + "Please include this link when making bug reports.");
} } else {
else
{
cs.sendMessage(PERMISSIONS_ERROR); cs.sendMessage(PERMISSIONS_ERROR);
} }
} }
public void handleXRay(CommandSender cs, String[] args) public void handleXRay(CommandSender cs, String[] args) {
{ if (Permission.SYSTEM_XRAY.get(cs)) {
if (Permission.SYSTEM_XRAY.get(cs)) if (CONFIG.logXRay()) {
{
if (CONFIG.logXRay())
{
List<Player> list = SERVER.matchPlayer(args[1]); List<Player> list = SERVER.matchPlayer(args[1]);
if (list.size() == 1) if (list.size() == 1) {
{
Player player = list.get(0); Player player = list.get(0);
if (XRAY_TRACKER.sufficientData(player.getName())) if (XRAY_TRACKER.sufficientData(player.getName())) {
{
XRAY_TRACKER.sendStats(cs, player.getName()); XRAY_TRACKER.sendStats(cs, player.getName());
} } else {
else
{
cs.sendMessage(RED + "Insufficient data collected from " + WHITE + args[1] + RED + "."); cs.sendMessage(RED + "Insufficient data collected from " + WHITE + args[1] + RED + ".");
cs.sendMessage(RED + "Please wait until more info is collected before predictions are calculated."); cs.sendMessage(RED + "Please wait until more info is collected before predictions are calculated.");
} }
} } else if (list.size() > 1) {
else if (list.size() > 1)
{
cs.sendMessage(RED + "Multiple players found by name: " + WHITE + args[1] + RED + "."); cs.sendMessage(RED + "Multiple players found by name: " + WHITE + args[1] + RED + ".");
} } else if (XRAY_TRACKER.sufficientData(args[1])) {
else if (XRAY_TRACKER.sufficientData(args[1]))
{
XRAY_TRACKER.sendStats(cs, args[1]); XRAY_TRACKER.sendStats(cs, args[1]);
} } else {
else
{
cs.sendMessage(RED + "Insufficient data collected from " + WHITE + args[1] + RED + "."); cs.sendMessage(RED + "Insufficient data collected from " + WHITE + args[1] + RED + ".");
cs.sendMessage(RED + "Please wait until more info is collected before predictions are calculated."); cs.sendMessage(RED + "Please wait until more info is collected before predictions are calculated.");
} }
} } else {
else
{
cs.sendMessage(RED + "XRay logging is off in the config."); cs.sendMessage(RED + "XRay logging is off in the config.");
} }
} } else {
else
{
cs.sendMessage(PERMISSIONS_ERROR); cs.sendMessage(PERMISSIONS_ERROR);
} }
} }
public void handleReset(CommandSender cs, String[] args) public void handleReset(CommandSender cs, String[] args) {
{ if (Permission.SYSTEM_RESET.get(cs)) {
if (Permission.SYSTEM_RESET.get(cs))
{
List<Player> list = SERVER.matchPlayer(args[1]); List<Player> list = SERVER.matchPlayer(args[1]);
if (list.size() == 1) if (list.size() == 1) {
{
Player player = list.get(0); Player player = list.get(0);
if (USER_MANAGER.safeGetLevel(player.getName()) == 0) if (USER_MANAGER.safeGetLevel(player.getName()) == 0) {
{
cs.sendMessage(player.getName() + RED + " is already in Low Level!"); cs.sendMessage(player.getName() + RED + " is already in Low Level!");
} } else {
else
{
USER_MANAGER.safeReset(player.getName()); USER_MANAGER.safeReset(player.getName());
cs.sendMessage(player.getName() + GREEN + " has been reset to Low Level."); cs.sendMessage(player.getName() + GREEN + " has been reset to Low Level.");
} }
XRAY_TRACKER.reset(player.getName()); XRAY_TRACKER.reset(player.getName());
cs.sendMessage(player.getName() + GREEN + "'s XRay stats have been reset."); cs.sendMessage(player.getName() + GREEN + "'s XRay stats have been reset.");
} } else if (list.size() > 1) {
else if (list.size() > 1)
{
cs.sendMessage(RED + "Multiple players found by name: " + WHITE + args[1] + RED + "."); cs.sendMessage(RED + "Multiple players found by name: " + WHITE + args[1] + RED + ".");
} } else {
else
{
cs.sendMessage(RED + "Player: " + WHITE + args[1] + RED + " not found."); cs.sendMessage(RED + "Player: " + WHITE + args[1] + RED + " not found.");
} }
} } else {
else
{
cs.sendMessage(PERMISSIONS_ERROR); cs.sendMessage(PERMISSIONS_ERROR);
} }
} }
public void handleSpy(CommandSender cs, String[] args) public void handleSpy(CommandSender cs, String[] args) {
{ if (cs instanceof Player) {
if (cs instanceof Player) if (Permission.SYSTEM_SPY.get(cs)) {
{
if (Permission.SYSTEM_SPY.get(cs))
{
Player sender = (Player) cs; Player sender = (Player) cs;
if (!args[1].equalsIgnoreCase("off")) if (!args[1].equalsIgnoreCase("off")) {
{
List<Player> list = SERVER.matchPlayer(args[1]); List<Player> list = SERVER.matchPlayer(args[1]);
if (list.size() == 1) if (list.size() == 1) {
{
Player player = list.get(0); Player player = list.get(0);
for (Player p : cs.getServer().getOnlinePlayers()) for (Player p : cs.getServer().getOnlinePlayers()) {
{ if (!Permission.SYSTEM_SPY.get(p)) {
if (!Permission.SYSTEM_SPY.get(p))
{
p.hidePlayer(sender); p.hidePlayer(sender);
} }
} }
if(!sender.hasMetadata(Anticheat.SPY_METADATA)) // Maintain ORIGINAL location and other data if (!sender.hasMetadata(Anticheat.SPY_METADATA)) // Maintain ORIGINAL location and other data
{ {
SpyState state = new SpyState(sender.getAllowFlight(), sender.isFlying(), sender.getLocation()); SpyState state = new SpyState(sender.getAllowFlight(), sender.isFlying(), sender.getLocation());
sender.setMetadata(Anticheat.SPY_METADATA, new FixedMetadataValue(Anticheat.getPlugin(), state)); sender.setMetadata(Anticheat.SPY_METADATA, new FixedMetadataValue(Anticheat.getPlugin(), state));
@@ -217,52 +161,36 @@ public class CommandHandler implements CommandExecutor
sender.teleport(player); sender.teleport(player);
sender.sendMessage(GREEN + "You have been teleported to " + player.getName() + " and made invisible."); sender.sendMessage(GREEN + "You have been teleported to " + player.getName() + " and made invisible.");
sender.sendMessage(GREEN + "To stop spying, type " + WHITE + " /AntiCheat spy off"); sender.sendMessage(GREEN + "To stop spying, type " + WHITE + " /AntiCheat spy off");
} } else if (list.size() > 1) {
else if (list.size() > 1)
{
cs.sendMessage(RED + "Multiple players found by name: " + WHITE + args[1] + RED + "."); cs.sendMessage(RED + "Multiple players found by name: " + WHITE + args[1] + RED + ".");
} } else {
else
{
cs.sendMessage(RED + "Player: " + WHITE + args[1] + RED + " not found."); cs.sendMessage(RED + "Player: " + WHITE + args[1] + RED + " not found.");
} }
} } else {
else if (sender.hasMetadata(Anticheat.SPY_METADATA)) {
{
if (sender.hasMetadata(Anticheat.SPY_METADATA))
{
SpyState state = ((SpyState) sender.getMetadata(Anticheat.SPY_METADATA).get(0).value()); SpyState state = ((SpyState) sender.getMetadata(Anticheat.SPY_METADATA).get(0).value());
sender.setAllowFlight(state.getAllowFlight()); sender.setAllowFlight(state.getAllowFlight());
sender.setFlying(state.getFlying()); sender.setFlying(state.getFlying());
sender.teleport(state.getLocation()); sender.teleport(state.getLocation());
sender.removeMetadata(Anticheat.SPY_METADATA, Anticheat.getPlugin()); sender.removeMetadata(Anticheat.SPY_METADATA, Anticheat.getPlugin());
for (Player p : cs.getServer().getOnlinePlayers()) for (Player p : cs.getServer().getOnlinePlayers()) {
{
p.showPlayer(sender); p.showPlayer(sender);
} }
sender.sendMessage(GREEN + "Done spying! Brought you back to where you started!"); sender.sendMessage(GREEN + "Done spying! Brought you back to where you started!");
} } else {
else
{
sender.sendMessage(RED + "You were not spying."); sender.sendMessage(RED + "You were not spying.");
} }
} }
} } else {
else
{
cs.sendMessage(PERMISSIONS_ERROR); cs.sendMessage(PERMISSIONS_ERROR);
} }
} } else {
else
{
cs.sendMessage(RED + "Sorry, but you can't spy on a player from the console."); cs.sendMessage(RED + "Sorry, but you can't spy on a player from the console.");
} }
} }
public void handleHelp(CommandSender cs) public void handleHelp(CommandSender cs) {
{ if (Permission.SYSTEM_HELP.get(cs)) {
if (Permission.SYSTEM_HELP.get(cs))
{
String base = "/AntiCheat "; String base = "/AntiCheat ";
cs.sendMessage("----------------------[" + GREEN + "AntiCheat" + WHITE + "]----------------------"); cs.sendMessage("----------------------[" + GREEN + "AntiCheat" + WHITE + "]----------------------");
cs.sendMessage(base + GREEN + "log [Enable/Disable]" + WHITE + " - toggle logging"); cs.sendMessage(base + GREEN + "log [Enable/Disable]" + WHITE + " - toggle logging");
@@ -276,399 +204,266 @@ public class CommandHandler implements CommandExecutor
cs.sendMessage(base + GREEN + "debug" + WHITE + " - post debug information"); cs.sendMessage(base + GREEN + "debug" + WHITE + " - post debug information");
cs.sendMessage(base + GREEN + "update" + WHITE + " - check update status"); cs.sendMessage(base + GREEN + "update" + WHITE + " - check update status");
cs.sendMessage(MENU_END); cs.sendMessage(MENU_END);
} } else {
else
{
cs.sendMessage(PERMISSIONS_ERROR); cs.sendMessage(PERMISSIONS_ERROR);
} }
} }
public void handleUpdate(CommandSender cs) public void handleUpdate(CommandSender cs) {
{ if (Permission.SYSTEM_UPDATE.get(cs)) {
if (Permission.SYSTEM_UPDATE.get(cs))
{
cs.sendMessage("Running " + GREEN + "AntiCheat " + WHITE + "v" + GREEN + Anticheat.getVersion()); cs.sendMessage("Running " + GREEN + "AntiCheat " + WHITE + "v" + GREEN + Anticheat.getVersion());
cs.sendMessage(MENU_END); cs.sendMessage(MENU_END);
if (!Anticheat.isUpdated()) if (!Anticheat.isUpdated()) {
{
cs.sendMessage(GRAY + "There " + GREEN + "IS" + GRAY + " a newer version avaliable."); cs.sendMessage(GRAY + "There " + GREEN + "IS" + GRAY + " a newer version avaliable.");
if (CONFIG.autoUpdate()) if (CONFIG.autoUpdate()) {
{
cs.sendMessage(GRAY + "It will be installed automatically for you on next launch."); cs.sendMessage(GRAY + "It will be installed automatically for you on next launch.");
} } else {
else
{
cs.sendMessage(GRAY + "Due to your config settings, we " + RED + "can not" + GRAY + " auto update."); cs.sendMessage(GRAY + "Due to your config settings, we " + RED + "can not" + GRAY + " auto update.");
cs.sendMessage(GRAY + "Please visit http://dev.bukkit.org/server-mods/anticheat/"); cs.sendMessage(GRAY + "Please visit http://dev.bukkit.org/server-mods/anticheat/");
} }
} } else {
else
{
cs.sendMessage(GRAY + "AntiCheat is " + GREEN + "UP TO DATE!"); cs.sendMessage(GRAY + "AntiCheat is " + GREEN + "UP TO DATE!");
} }
} } else {
else
{
cs.sendMessage(PERMISSIONS_ERROR); cs.sendMessage(PERMISSIONS_ERROR);
} }
} }
public void handleCalibrate(CommandSender cs) public void handleCalibrate(CommandSender cs) {
{ if (cs instanceof Player) {
if(cs instanceof Player) if (Permission.SYSTEM_CALIBRATE.get(cs)) {
{ Calibrator c = new Calibrator((Player) cs);
if (Permission.SYSTEM_CALIBRATE.get(cs))
{
Calibrator c = new Calibrator((Player)cs);
SERVER.getPluginManager().registerEvents(c, Anticheat.getPlugin()); SERVER.getPluginManager().registerEvents(c, Anticheat.getPlugin());
c.calibrate(); c.calibrate();
} } else {
else
{
cs.sendMessage(PERMISSIONS_ERROR); cs.sendMessage(PERMISSIONS_ERROR);
} }
} } else {
else
{
cs.sendMessage(RED + "Sorry, but you cannot calibrate from console."); cs.sendMessage(RED + "Sorry, but you cannot calibrate from console.");
} }
} }
public void handleReport(CommandSender cs, String[] args) public void handleReport(CommandSender cs, String[] args) {
{ if (Permission.SYSTEM_REPORT.get(cs)) {
if (Permission.SYSTEM_REPORT.get(cs))
{
getPlayers(); getPlayers();
if(args.length > 1) if (args.length > 1) {
{
String group = args[1]; String group = args[1];
if(group.equalsIgnoreCase("low")) if (group.equalsIgnoreCase("low")) {
{
int num = getReportPageNum(args); int num = getReportPageNum(args);
if (num > 0) if (num > 0) {
{
sendReport(cs, low, "Low", GREEN, num); sendReport(cs, low, "Low", GREEN, num);
} } else {
else
{
cs.sendMessage(RED + "Not a valid page number: " + WHITE + args[2]); cs.sendMessage(RED + "Not a valid page number: " + WHITE + args[2]);
} }
} } else if (group.equalsIgnoreCase("medium")) {
else if(group.equalsIgnoreCase("medium"))
{
int num = getReportPageNum(args); int num = getReportPageNum(args);
if (num > 0) if (num > 0) {
{
sendReport(cs, med, "Medium", YELLOW, num); sendReport(cs, med, "Medium", YELLOW, num);
} } else {
else
{
cs.sendMessage(RED + "Not a valid page number: " + WHITE + args[2]); cs.sendMessage(RED + "Not a valid page number: " + WHITE + args[2]);
} }
} }
if(group.equalsIgnoreCase("high")) if (group.equalsIgnoreCase("high")) {
{
int num = getReportPageNum(args); int num = getReportPageNum(args);
if (num > 0) if (num > 0) {
{
sendReport(cs, high, "High", RED, num); sendReport(cs, high, "High", RED, num);
} } else {
else
{
cs.sendMessage(RED + "Not a valid page number: " + WHITE + args[2]); cs.sendMessage(RED + "Not a valid page number: " + WHITE + args[2]);
} }
} }
} }
} } else {
else
{
cs.sendMessage(PERMISSIONS_ERROR); cs.sendMessage(PERMISSIONS_ERROR);
} }
} }
public int getReportPageNum(String [] args) public int getReportPageNum(String[] args) {
{ if (args.length == 2) {
if (args.length == 2)
{
return 1; return 1;
} } else if (Utilities.isInt(args[2])) {
else if (Utilities.isInt(args[2]))
{
return Integer.parseInt(args[2]); return Integer.parseInt(args[2]);
} } else {
else
{
return -1; return -1;
} }
} }
public void sendReport(CommandSender cs, List<String> players, String group, ChatColor color, int page) public void sendReport(CommandSender cs, List<String> players, String group, ChatColor color, int page) {
{ int pages = (int) Math.ceil(((float) players.size()) / 7);
int pages = (int)Math.ceil(((float)players.size())/7); if (page <= pages && page > 0) {
if(page <= pages && page > 0) cs.sendMessage("--------------------[" + GREEN + "REPORT[" + page + "/" + pages + "]" + WHITE + "]---------------------");
{
cs.sendMessage("--------------------[" + GREEN + "REPORT[" + page + "/"+pages+"]" + WHITE + "]---------------------");
cs.sendMessage(GRAY + "Group: " + color + group); cs.sendMessage(GRAY + "Group: " + color + group);
for (int x = 0; x < 7; x++) for (int x = 0; x < 7; x++) {
{ int index = ((page - 1) * 6) + (x + ((page - 1) * 1));
int index = ((page-1)*6)+(x+((page-1)*1)); if (index < players.size()) {
if(index < players.size())
{
String player = players.get(index); String player = players.get(index);
cs.sendMessage(GRAY + player); cs.sendMessage(GRAY + player);
} }
} }
cs.sendMessage(MENU_END); cs.sendMessage(MENU_END);
} } else {
else if (pages == 0) {
{
if(pages == 0)
{
cs.sendMessage("--------------------[" + GREEN + "REPORT[1/1]" + WHITE + "]---------------------"); cs.sendMessage("--------------------[" + GREEN + "REPORT[1/1]" + WHITE + "]---------------------");
cs.sendMessage(GRAY + "Group: " + color + group); cs.sendMessage(GRAY + "Group: " + color + group);
cs.sendMessage(GRAY + "There are no users in this group."); cs.sendMessage(GRAY + "There are no users in this group.");
cs.sendMessage(MENU_END); cs.sendMessage(MENU_END);
} } else {
else cs.sendMessage(RED + "Page not found. Requested " + WHITE + page + RED + ", Max " + WHITE + pages);
{
cs.sendMessage(RED+"Page not found. Requested "+WHITE+page+RED+", Max "+WHITE+pages);
} }
} }
} }
public void handlePlayerReport(CommandSender cs, String[] args) public void handlePlayerReport(CommandSender cs, String[] args) {
{ if (Permission.SYSTEM_REPORT.get(cs)) {
if (Permission.SYSTEM_REPORT.get(cs))
{
User user = Anticheat.getManager().getUserManager().getUser(args[1]); User user = Anticheat.getManager().getUserManager().getUser(args[1]);
boolean cont = false; boolean cont = false;
if (user == null) if (user == null) {
{ if ((user = Anticheat.getManager().getUserManager().loadUserFromFile(args[1])) == null) {
if((user = Anticheat.getManager().getUserManager().loadUserFromFile(args[1])) == null)
{
cs.sendMessage(RED + "Player: " + WHITE + args[1] + RED + " not found."); cs.sendMessage(RED + "Player: " + WHITE + args[1] + RED + " not found.");
} } else {
else
{
cont = true; cont = true;
} }
} } else {
else
{
cont = true; cont = true;
} }
if (cont) if (cont) {
{
List<CheckType> l = new ArrayList<CheckType>(); List<CheckType> l = new ArrayList<CheckType>();
for(CheckType type : CheckType.values()) for (CheckType type : CheckType.values()) {
{ if (type.getUses(user.getName()) > 0) {
if(type.getUses(user.getName()) > 0)
{
l.add(type); l.add(type);
} }
} }
if (args.length == 2) if (args.length == 2) {
{
sendPlayerReport(cs, l, user, 1); sendPlayerReport(cs, l, user, 1);
} } else if (Utilities.isInt(args[2])) {
else if (Utilities.isInt(args[2]))
{
int num = Integer.parseInt(args[2]); int num = Integer.parseInt(args[2]);
sendPlayerReport(cs, l, user, num); sendPlayerReport(cs, l, user, num);
} } else {
else
{
cs.sendMessage(RED + "Not a valid page number: " + WHITE + args[2]); cs.sendMessage(RED + "Not a valid page number: " + WHITE + args[2]);
} }
} }
} } else {
else
{
cs.sendMessage(PERMISSIONS_ERROR); cs.sendMessage(PERMISSIONS_ERROR);
} }
} }
public void sendPlayerReport(CommandSender cs, List<CheckType> types, User user, int page) public void sendPlayerReport(CommandSender cs, List<CheckType> types, User user, int page) {
{
String name = user.getName(); String name = user.getName();
int pages = (int)Math.ceil(((float)types.size())/6); int pages = (int) Math.ceil(((float) types.size()) / 6);
int level = user.getLevel(); int level = user.getLevel();
String levelString = GREEN + "Low"; String levelString = GREEN + "Low";
if (level >= CONFIG.highThreshold()) if (level >= CONFIG.highThreshold()) {
{
levelString = RED + "High"; levelString = RED + "High";
} } else if (level >= CONFIG.medThreshold()) {
else if (level >= CONFIG.medThreshold())
{
levelString = YELLOW + "Medium"; levelString = YELLOW + "Medium";
} }
if(page <= pages && page > 0) if (page <= pages && page > 0) {
{ cs.sendMessage("--------------------[" + GREEN + "REPORT[" + page + "/" + pages + "]" + WHITE + "]---------------------");
cs.sendMessage("--------------------[" + GREEN + "REPORT[" + page + "/"+pages+"]" + WHITE + "]---------------------");
cs.sendMessage(GRAY + "Player: " + WHITE + name); cs.sendMessage(GRAY + "Player: " + WHITE + name);
cs.sendMessage(GRAY + "Level: " + levelString); cs.sendMessage(GRAY + "Level: " + levelString);
for (int x = 0; x < 6; x++) for (int x = 0; x < 6; x++) {
{ int index = ((page - 1) * 5) + (x + ((page - 1) * 1));
int index = ((page-1)*5)+(x+((page-1)*1)); if (index < types.size()) {
if(index < types.size())
{
int use = types.get(index).getUses(name); int use = types.get(index).getUses(name);
ChatColor color = WHITE; ChatColor color = WHITE;
if (use >= 20) if (use >= 20) {
{
color = YELLOW; color = YELLOW;
} } else if (use > 50) {
else if (use > 50)
{
color = RED; color = RED;
} }
cs.sendMessage(GRAY + CheckType.getName(types.get(index)) + ": " + color + use); cs.sendMessage(GRAY + CheckType.getName(types.get(index)) + ": " + color + use);
} }
} }
cs.sendMessage(MENU_END); cs.sendMessage(MENU_END);
} } else {
else if (pages == 0) {
{
if(pages == 0)
{
cs.sendMessage("--------------------[" + GREEN + "REPORT[1/1]" + WHITE + "]---------------------"); cs.sendMessage("--------------------[" + GREEN + "REPORT[1/1]" + WHITE + "]---------------------");
cs.sendMessage(GRAY + "Player: " + WHITE + name); cs.sendMessage(GRAY + "Player: " + WHITE + name);
cs.sendMessage(GRAY + "Level: " + levelString); cs.sendMessage(GRAY + "Level: " + levelString);
cs.sendMessage(GRAY + "This user has not failed any checks."); cs.sendMessage(GRAY + "This user has not failed any checks.");
cs.sendMessage(MENU_END); cs.sendMessage(MENU_END);
} } else {
else cs.sendMessage(RED + "Page not found. Requested " + WHITE + page + RED + ", Max " + WHITE + pages);
{
cs.sendMessage(RED+"Page not found. Requested "+WHITE+page+RED+", Max "+WHITE+pages);
} }
} }
} }
public void handleReload(CommandSender cs) public void handleReload(CommandSender cs) {
{ if (Permission.SYSTEM_RELOAD.get(cs)) {
if (Permission.SYSTEM_RELOAD.get(cs))
{
CONFIG.load(); CONFIG.load();
cs.sendMessage(GREEN + "AntiCheat configuration reloaded."); cs.sendMessage(GREEN + "AntiCheat configuration reloaded.");
} } else {
else
{
cs.sendMessage(PERMISSIONS_ERROR); cs.sendMessage(PERMISSIONS_ERROR);
} }
} }
@Override @Override
public boolean onCommand(CommandSender cs, Command cmd, String alias, String[] args) public boolean onCommand(CommandSender cs, Command cmd, String alias, String[] args) {
{ if (args.length == 3) {
if (args.length == 3) if (args[0].equalsIgnoreCase("report")) {
{ if (args[1].equalsIgnoreCase("low") || args[1].equalsIgnoreCase("medium") || args[1].equalsIgnoreCase("high")) {
if (args[0].equalsIgnoreCase("report"))
{
if(args[1].equalsIgnoreCase("low") || args[1].equalsIgnoreCase("medium") || args[1].equalsIgnoreCase("high"))
{
handleReport(cs, args); handleReport(cs, args);
} } else {
else
{
handlePlayerReport(cs, args); handlePlayerReport(cs, args);
} }
} }
} } else if (args.length == 2) {
else if (args.length == 2) if (args[0].equalsIgnoreCase("log")) {
{
if (args[0].equalsIgnoreCase("log"))
{
handleLog(cs, args); handleLog(cs, args);
} } else if (args[0].equalsIgnoreCase("xray")) {
else if (args[0].equalsIgnoreCase("xray"))
{
handleXRay(cs, args); handleXRay(cs, args);
} } else if (args[0].equalsIgnoreCase("reset")) {
else if (args[0].equalsIgnoreCase("reset"))
{
handleReset(cs, args); handleReset(cs, args);
} } else if (args[0].equalsIgnoreCase("spy")) {
else if (args[0].equalsIgnoreCase("spy"))
{
handleSpy(cs, args); handleSpy(cs, args);
} } else if (args[0].equalsIgnoreCase("report")) {
else if (args[0].equalsIgnoreCase("report")) if (args[1].equalsIgnoreCase("low") || args[1].equalsIgnoreCase("medium") || args[1].equalsIgnoreCase("high")) {
{
if(args[1].equalsIgnoreCase("low") || args[1].equalsIgnoreCase("medium") || args[1].equalsIgnoreCase("high"))
{
handleReport(cs, args); handleReport(cs, args);
} } else {
else
{
handlePlayerReport(cs, args); handlePlayerReport(cs, args);
} }
} } else {
else
{
cs.sendMessage(RED + "Unrecognized command."); cs.sendMessage(RED + "Unrecognized command.");
} }
} } else if (args.length == 1) {
else if (args.length == 1) if (args[0].equalsIgnoreCase("help")) {
{
if (args[0].equalsIgnoreCase("help"))
{
handleHelp(cs); handleHelp(cs);
} } else if (args[0].equalsIgnoreCase("debug")) {
else if (args[0].equalsIgnoreCase("debug"))
{
handleDebug(cs); handleDebug(cs);
} } else if (args[0].equalsIgnoreCase("report")) {
else if (args[0].equalsIgnoreCase("report")) cs.sendMessage(ChatColor.GREEN + "To see the report of a specific user, type their name, like so:");
{ cs.sendMessage(ChatColor.WHITE + "/anticheat report [user]");
cs.sendMessage(ChatColor.GREEN+"To see the report of a specific user, type their name, like so:"); cs.sendMessage(ChatColor.GRAY + " - This will allow you to see the checks that user has failed.");
cs.sendMessage(ChatColor.WHITE+"/anticheat report [user]"); cs.sendMessage(ChatColor.GREEN + "To see the report of an AntiCheat group, type it's name, like so:");
cs.sendMessage(ChatColor.GRAY+" - This will allow you to see the checks that user has failed."); cs.sendMessage(ChatColor.WHITE + "/anticheat report [low/medium/high]");
cs.sendMessage(ChatColor.GREEN+"To see the report of an AntiCheat group, type it's name, like so:"); cs.sendMessage(ChatColor.GRAY + " - This will allow you to see which players are good, and which could be hacking.");
cs.sendMessage(ChatColor.WHITE+"/anticheat report [low/medium/high]"); } else if (args[0].equalsIgnoreCase("reload")) {
cs.sendMessage(ChatColor.GRAY+" - This will allow you to see which players are good, and which could be hacking.");
}
else if (args[0].equalsIgnoreCase("reload"))
{
handleReload(cs); handleReload(cs);
} } else if (args[0].equalsIgnoreCase("update")) {
else if (args[0].equalsIgnoreCase("update"))
{
handleUpdate(cs); handleUpdate(cs);
} }
/**else if (args[0].equalsIgnoreCase("calibrate")) /**
{ * else if (args[0].equalsIgnoreCase("calibrate")) { handleCalibrate(cs); }
handleCalibrate(cs); */
}*/ else {
else
{
cs.sendMessage(RED + "Unrecognized command."); cs.sendMessage(RED + "Unrecognized command.");
} }
} } else {
else
{
cs.sendMessage(RED + "Unrecognized command. Try " + ChatColor.WHITE + "/anticheat help"); cs.sendMessage(RED + "Unrecognized command. Try " + ChatColor.WHITE + "/anticheat help");
} }
return true; return true;
} }
public void getPlayers() public void getPlayers() {
{
high.clear(); high.clear();
med.clear(); med.clear();
low.clear(); low.clear();
for (Player player : SERVER.getOnlinePlayers()) for (Player player : SERVER.getOnlinePlayers()) {
{
int level = USER_MANAGER.safeGetLevel(player.getName()); int level = USER_MANAGER.safeGetLevel(player.getName());
if (level <= MED_THRESHOLD) if (level <= MED_THRESHOLD) {
{
low.add(player.getName()); low.add(player.getName());
} } else if (level <= HIGH_THRESHOLD) {
else if (level <= HIGH_THRESHOLD)
{
med.add(player.getName()); med.add(player.getName());
} } else {
else
{
high.add(player.getName()); high.add(player.getName());
} }
} }
@@ -28,116 +28,92 @@ import org.bukkit.entity.Player;
* Developer's interface for all things AntiCheat. * Developer's interface for all things AntiCheat.
*/ */
public class AnticheatAPI public class AnticheatAPI {
{
private static CheckManager chk = Anticheat.getManager().getCheckManager(); private static CheckManager chk = Anticheat.getManager().getCheckManager();
private static UserManager umr = Anticheat.getManager().getUserManager(); private static UserManager umr = Anticheat.getManager().getUserManager();
private static XRayTracker xtracker = Anticheat.getManager().getXRayTracker(); private static XRayTracker xtracker = Anticheat.getManager().getXRayTracker();
//CheckManager API // CheckManager API
/** /**
* Start running a certain check * Start running a certain check
* *
* @param type * @param type Check to start watching for
* Check to start watching for
*/ */
public static void activateCheck(CheckType type) public static void activateCheck(CheckType type) {
{
chk.activateCheck(type); chk.activateCheck(type);
} }
/** /**
* Stop running a certain check * Stop running a certain check
* *
* @param type * @param type Check to stop watching for
* Check to stop watching for
*/ */
public static void deactivateCheck(CheckType type) public static void deactivateCheck(CheckType type) {
{
chk.deactivateCheck(type); chk.deactivateCheck(type);
} }
/** /**
* Find out if a check is currently being watched for * Find out if a check is currently being watched for
* *
* @param type * @param type Type to check
* Type to check
* @return true if plugin is watching for this check * @return true if plugin is watching for this check
*/ */
public static boolean isActive(CheckType type) public static boolean isActive(CheckType type) {
{
return chk.isActive(type); return chk.isActive(type);
} }
/** /**
* Allow a player to skip a certain check * Allow a player to skip a certain check
* *
* @param player * @param player Player to stop watching
* Player to stop watching * @param type Check to stop watching for
* @param type
* Check to stop watching for
*/ */
public static void exemptPlayer(Player player, CheckType type) public static void exemptPlayer(Player player, CheckType type) {
{
chk.exemptPlayer(player, type); chk.exemptPlayer(player, type);
} }
/** /**
* Stop allowing a player to skip a certain check * Stop allowing a player to skip a certain check
* *
* @param player * @param player Player to start watching
* Player to start watching * @param type Check to start watching for
* @param type
* Check to start watching for
*/ */
public static void unexemptPlayer(Player player, CheckType type) public static void unexemptPlayer(Player player, CheckType type) {
{
chk.unexemptPlayer(player, type); chk.unexemptPlayer(player, type);
} }
/** /**
* Find out if a player is currently exempt from a certain check * Find out if a player is currently exempt from a certain check
* *
* @param player * @param player Player to check
* Player to check * @param type Type to check
* @param type
* Type to check
* @return true if plugin is ignoring this check on this player * @return true if plugin is ignoring this check on this player
*/ */
public static boolean isExempt(Player player, CheckType type) public static boolean isExempt(Player player, CheckType type) {
{
return chk.isExempt(player, type); return chk.isExempt(player, type);
} }
/** /**
* Find out if a check will occur for a player. This checks if they are * Find out if a check will occur for a player. This checks if they are being tracked, the check is active, the player isn't exempt from the check, and the player doesn't have override permission.
* being tracked, the check is active, the player isn't exempt from the
* check, and the player doesn't have override permission.
* *
* @param player * @param player Player to check
* Player to check * @param type Type to check
* @param type * @return true if plugin will check this player, and that all things allow it to happen.
* Type to check
* @return true if plugin will check this player, and that all things allow
* it to happen.
*/ */
public boolean willCheck(Player player, CheckType type) public boolean willCheck(Player player, CheckType type) {
{
return chk.willCheck(player, type); return chk.willCheck(player, type);
} }
//PlayerManager API // PlayerManager API
/** /**
* Get a player's integer hack level * Get a player's integer hack level
* *
* @param player * @param player Player to check
* Player to check
* @return player's hack level * @return player's hack level
*/ */
public static int getLevel(Player player) public static int getLevel(Player player) {
{
return umr.safeGetLevel(player.getName()); return umr.safeGetLevel(player.getName());
} }
@@ -145,44 +121,35 @@ public class AnticheatAPI
/** /**
* Set a player's hack level (Min = 0, Max = 50) * Set a player's hack level (Min = 0, Max = 50)
* *
* @param player * @param player Player to set
* Player to set * @param level Level to set to
* @param level
* Level to set to
*/ */
public static void setLevel(Player player, int level) public static void setLevel(Player player, int level) {
{
umr.safeSetLevel(player.getName(), level); umr.safeSetLevel(player.getName(), level);
} }
//XrayTracker API // XrayTracker API
/** /**
* Find out if a player is detected as using xray hacks (on any ore) * Find out if a player is detected as using xray hacks (on any ore)
* *
* @param player * @param player Player to check
* Player to check
* @return true if the player has any xray anomalies. * @return true if the player has any xray anomalies.
*/ */
public static boolean isXrayer(Player player) public static boolean isXrayer(Player player) {
{
String name = player.getName(); String name = player.getName();
if (xtracker.sufficientData(name) && xtracker.hasAbnormal(name)) if (xtracker.sufficientData(name) && xtracker.hasAbnormal(name)) { return true; }
{
return true;
}
return false; return false;
} }
//Advanced Users Only API. // Advanced Users Only API.
/** /**
* Get access to all the other managers, advanced users ONLY * Get access to all the other managers, advanced users ONLY
* *
* @return the AntiCheat Manager * @return the AntiCheat Manager
*/ */
public static AnticheatManager getManager() public static AnticheatManager getManager() {
{
return Anticheat.getManager(); return Anticheat.getManager();
} }
} }
@@ -25,7 +25,6 @@ import net.h31ix.anticheat.manage.CheckType;
import net.h31ix.anticheat.util.Configuration; import net.h31ix.anticheat.util.Configuration;
import net.h31ix.anticheat.util.Distance; import net.h31ix.anticheat.util.Distance;
import net.h31ix.anticheat.util.Utilities; import net.h31ix.anticheat.util.Utilities;
import org.bukkit.block.Block; import org.bukkit.block.Block;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
@@ -34,41 +33,32 @@ import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockDamageEvent; import org.bukkit.event.block.BlockDamageEvent;
import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.block.BlockPlaceEvent;
public class BlockListener extends EventListener public class BlockListener extends EventListener {
{
private final Backend backend = getBackend(); private final Backend backend = getBackend();
private final CheckManager checkManager = getCheckManager(); private final CheckManager checkManager = getCheckManager();
private final Configuration config = Anticheat.getManager().getConfiguration(); private final Configuration config = Anticheat.getManager().getConfiguration();
@EventHandler(priority = EventPriority.MONITOR) @EventHandler(priority = EventPriority.MONITOR)
public void onBlockDamage(BlockDamageEvent event) public void onBlockDamage(BlockDamageEvent event) {
{
Player player = event.getPlayer(); Player player = event.getPlayer();
if (event.getInstaBreak() && Utilities.isInstantBreak(event.getBlock().getType())) if (event.getInstaBreak() && Utilities.isInstantBreak(event.getBlock().getType())) {
{
backend.logInstantBreak(player); backend.logInstantBreak(player);
} }
if (checkManager.willCheck(player, CheckType.AUTOTOOL) && backend.justSwitchedTool(player)) if (checkManager.willCheck(player, CheckType.AUTOTOOL) && backend.justSwitchedTool(player)) {
{
event.setCancelled(!config.silentMode()); event.setCancelled(!config.silentMode());
log("tried to switch their tool too fast.", player, CheckType.AUTOTOOL); log("tried to switch their tool too fast.", player, CheckType.AUTOTOOL);
} }
} }
@EventHandler(ignoreCancelled = true) @EventHandler(ignoreCancelled = true)
public void onBlockPlace(BlockPlaceEvent event) public void onBlockPlace(BlockPlaceEvent event) {
{
final Player player = event.getPlayer(); final Player player = event.getPlayer();
Block block = event.getBlock(); Block block = event.getBlock();
if (player != null && checkManager.willCheck(player, CheckType.FAST_PLACE)) if (player != null && checkManager.willCheck(player, CheckType.FAST_PLACE)) {
{ if (backend.checkFastPlace(player)) {
if (backend.checkFastPlace(player))
{
event.setCancelled(!config.silentMode()); event.setCancelled(!config.silentMode());
log("tried to place a block of " + block.getType().name() + " too fast.", player, CheckType.FAST_PLACE); log("tried to place a block of " + block.getType().name() + " too fast.", player, CheckType.FAST_PLACE);
} } else {
else
{
decrease(player); decrease(player);
backend.logBlockPlace(player); backend.logBlockPlace(player);
} }
@@ -76,38 +66,31 @@ public class BlockListener extends EventListener
} }
@EventHandler(ignoreCancelled = true) @EventHandler(ignoreCancelled = true)
public void onBlockBreak(BlockBreakEvent event) public void onBlockBreak(BlockBreakEvent event) {
{
final Player player = event.getPlayer(); final Player player = event.getPlayer();
final Block block = event.getBlock(); final Block block = event.getBlock();
boolean noHack = true; boolean noHack = true;
if (player != null) if (player != null) {
{ if (checkManager.willCheck(player, CheckType.FAST_BREAK) && !backend.isInstantBreakExempt(player) && backend.checkFastBreak(player, block)) {
if (checkManager.willCheck(player, CheckType.FAST_BREAK) && !backend.isInstantBreakExempt(player) && backend.checkFastBreak(player, block))
{
event.setCancelled(!config.silentMode()); event.setCancelled(!config.silentMode());
log("tried to break a block of " + block.getType().name() + " too fast.", player, CheckType.FAST_BREAK); log("tried to break a block of " + block.getType().name() + " too fast.", player, CheckType.FAST_BREAK);
noHack = false; noHack = false;
} }
if (checkManager.willCheck(player, CheckType.NO_SWING) && backend.checkSwing(player, block)) if (checkManager.willCheck(player, CheckType.NO_SWING) && backend.checkSwing(player, block)) {
{
event.setCancelled(!config.silentMode()); event.setCancelled(!config.silentMode());
log("tried to break a block of " + block.getType().name() + " without swinging their arm.", player, CheckType.NO_SWING); log("tried to break a block of " + block.getType().name() + " without swinging their arm.", player, CheckType.NO_SWING);
noHack = false; noHack = false;
} }
if (checkManager.willCheck(player, CheckType.LONG_REACH)) if (checkManager.willCheck(player, CheckType.LONG_REACH)) {
{
Distance distance = new Distance(player.getLocation(), block.getLocation()); Distance distance = new Distance(player.getLocation(), block.getLocation());
if (backend.checkLongReachBlock(player, distance.getXDifference(), distance.getYDifference(), distance.getZDifference())) if (backend.checkLongReachBlock(player, distance.getXDifference(), distance.getYDifference(), distance.getZDifference())) {
{
event.setCancelled(!config.silentMode()); event.setCancelled(!config.silentMode());
log("tried to break a block of " + block.getType().name() + " that was too far away.", player, CheckType.LONG_REACH); log("tried to break a block of " + block.getType().name() + " that was too far away.", player, CheckType.LONG_REACH);
noHack = false; noHack = false;
} }
} }
} }
if (noHack) if (noHack) {
{
decrease(player); decrease(player);
} }
backend.logBlockBreak(player); backend.logBlockBreak(player);
@@ -33,27 +33,20 @@ import org.bukkit.event.EventHandler;
import org.bukkit.event.entity.*; import org.bukkit.event.entity.*;
import org.bukkit.event.entity.EntityRegainHealthEvent.RegainReason; import org.bukkit.event.entity.EntityRegainHealthEvent.RegainReason;
public class EntityListener extends EventListener public class EntityListener extends EventListener {
{
private final Backend backend = getBackend(); private final Backend backend = getBackend();
private final CheckManager checkManager = getCheckManager(); private final CheckManager checkManager = getCheckManager();
private final Configuration config = Anticheat.getManager().getConfiguration(); private final Configuration config = Anticheat.getManager().getConfiguration();
@EventHandler @EventHandler
public void onEntityShootBow(EntityShootBowEvent event) public void onEntityShootBow(EntityShootBowEvent event) {
{ if (event.getEntity() instanceof Player) {
if (event.getEntity() instanceof Player)
{
Player player = (Player) event.getEntity(); Player player = (Player) event.getEntity();
if (checkManager.willCheck(player, CheckType.FAST_BOW)) if (checkManager.willCheck(player, CheckType.FAST_BOW)) {
{ if (backend.checkFastBow(player, event.getForce())) {
if (backend.checkFastBow(player, event.getForce()))
{
event.setCancelled(!config.silentMode()); event.setCancelled(!config.silentMode());
log("tried to fire a bow too fast.", player, CheckType.FAST_BOW); log("tried to fire a bow too fast.", player, CheckType.FAST_BOW);
} } else {
else
{
decrease(player); decrease(player);
} }
} }
@@ -61,20 +54,14 @@ public class EntityListener extends EventListener
} }
@EventHandler @EventHandler
public void onEntityRegainHealth(EntityRegainHealthEvent event) public void onEntityRegainHealth(EntityRegainHealthEvent event) {
{ if (event.getEntity() instanceof Player && event.getRegainReason() == RegainReason.SATIATED) {
if (event.getEntity() instanceof Player && event.getRegainReason() == RegainReason.SATIATED)
{
Player player = (Player) event.getEntity(); Player player = (Player) event.getEntity();
if (checkManager.willCheck(player, CheckType.FAST_HEAL)) if (checkManager.willCheck(player, CheckType.FAST_HEAL)) {
{ if (backend.justHealed(player)) {
if (backend.justHealed(player))
{
event.setCancelled(!config.silentMode()); event.setCancelled(!config.silentMode());
log("tried to heal too fast.", player, CheckType.FAST_HEAL); log("tried to heal too fast.", player, CheckType.FAST_HEAL);
} } else {
else
{
decrease(player); decrease(player);
backend.logHeal(player); backend.logHeal(player);
} }
@@ -83,20 +70,15 @@ public class EntityListener extends EventListener
} }
@EventHandler @EventHandler
public void onFoodLevelChange(FoodLevelChangeEvent event) public void onFoodLevelChange(FoodLevelChangeEvent event) {
{ if (event.getEntity() instanceof Player) {
if (event.getEntity() instanceof Player)
{
Player player = (Player) event.getEntity(); Player player = (Player) event.getEntity();
if(player.getFoodLevel() < event.getFoodLevel() && checkManager.willCheck(player, CheckType.FAST_EAT)) // Make sure it's them actually gaining a food level if (player.getFoodLevel() < event.getFoodLevel() && checkManager.willCheck(player, CheckType.FAST_EAT)) // Make sure it's them actually gaining a food level
{
if (backend.justStartedEating(player))
{ {
if (backend.justStartedEating(player)) {
event.setCancelled(!config.silentMode()); event.setCancelled(!config.silentMode());
log("tried to eat too fast.", player, CheckType.FAST_EAT); log("tried to eat too fast.", player, CheckType.FAST_EAT);
} } else {
else
{
decrease(player); decrease(player);
} }
} }
@@ -104,83 +86,64 @@ public class EntityListener extends EventListener
} }
@EventHandler(ignoreCancelled = true) @EventHandler(ignoreCancelled = true)
public void onEntityDamage(EntityDamageEvent event) public void onEntityDamage(EntityDamageEvent event) {
{
boolean noHack = true; boolean noHack = true;
if (event instanceof EntityDamageByEntityEvent) if (event instanceof EntityDamageByEntityEvent) {
{
EntityDamageByEntityEvent e = (EntityDamageByEntityEvent) event; EntityDamageByEntityEvent e = (EntityDamageByEntityEvent) event;
if (event.getEntity() instanceof Player) if (event.getEntity() instanceof Player) {
{
Player player = (Player) event.getEntity(); Player player = (Player) event.getEntity();
// Keep players from shooting an arrow at themselves in order to fly // Keep players from shooting an arrow at themselves in order to fly
if(e.getDamager() instanceof Arrow) if (e.getDamager() instanceof Arrow) {
{ Arrow arrow = (Arrow) e.getDamager();
Arrow arrow = (Arrow)e.getDamager(); if (arrow.getShooter() instanceof Player && event.getEntity() == arrow.getShooter()) {
if(arrow.getShooter() instanceof Player && event.getEntity() == arrow.getShooter())
{
event.setCancelled(true); event.setCancelled(true);
} }
} }
if (e.getDamager() instanceof Player) if (e.getDamager() instanceof Player) {
{
Player p = (Player) e.getDamager(); Player p = (Player) e.getDamager();
backend.logDamage(p, 1); backend.logDamage(p, 1);
int value = p.getInventory().getItemInHand().containsEnchantment(Enchantment.KNOCKBACK) ? 2 : 1; int value = p.getInventory().getItemInHand().containsEnchantment(Enchantment.KNOCKBACK) ? 2 : 1;
backend.logDamage(player, value); backend.logDamage(player, value);
if (checkManager.willCheck(p, CheckType.LONG_REACH)) if (checkManager.willCheck(p, CheckType.LONG_REACH)) {
{
Distance distance = new Distance(player.getLocation(), p.getLocation()); Distance distance = new Distance(player.getLocation(), p.getLocation());
if (backend.checkLongReachDamage(distance.getXDifference(), distance.getYDifference(), distance.getZDifference())) if (backend.checkLongReachDamage(distance.getXDifference(), distance.getYDifference(), distance.getZDifference())) {
{
event.setCancelled(!config.silentMode()); event.setCancelled(!config.silentMode());
log("tried to damage a player too far away from them.", p, CheckType.LONG_REACH); log("tried to damage a player too far away from them.", p, CheckType.LONG_REACH);
noHack = false; noHack = false;
} }
} }
} } else {
else if (e.getDamager() instanceof TNTPrimed || e.getDamager() instanceof Creeper) {
{
if (e.getDamager() instanceof TNTPrimed || e.getDamager() instanceof Creeper)
{
backend.logDamage(player, 3); backend.logDamage(player, 3);
} } else {
else
{
backend.logDamage(player, 1); backend.logDamage(player, 1);
} }
} }
} }
if (e.getDamager() instanceof Player) if (e.getDamager() instanceof Player) {
{
Player player = (Player) e.getDamager(); Player player = (Player) e.getDamager();
backend.logDamage(player, 1); backend.logDamage(player, 1);
if (checkManager.willCheck(player, CheckType.AUTOTOOL) && backend.justSwitchedTool(player)) if (checkManager.willCheck(player, CheckType.AUTOTOOL) && backend.justSwitchedTool(player)) {
{
event.setCancelled(!config.silentMode()); event.setCancelled(!config.silentMode());
log("tried to switch their tool too fast.", player, CheckType.AUTOTOOL); log("tried to switch their tool too fast.", player, CheckType.AUTOTOOL);
noHack = false; noHack = false;
} }
if (checkManager.willCheck(player, CheckType.FORCEFIELD) && backend.justSprinted(player)) if (checkManager.willCheck(player, CheckType.FORCEFIELD) && backend.justSprinted(player)) {
{
event.setCancelled(!config.silentMode()); event.setCancelled(!config.silentMode());
log("tried to sprint & damage too fast.", player, CheckType.FORCEFIELD); log("tried to sprint & damage too fast.", player, CheckType.FORCEFIELD);
noHack = false; noHack = false;
} }
if (checkManager.willCheck(player, CheckType.NO_SWING) && !backend.justAnimated(player)) if (checkManager.willCheck(player, CheckType.NO_SWING) && !backend.justAnimated(player)) {
{
event.setCancelled(!config.silentMode()); event.setCancelled(!config.silentMode());
log("tried to damage an entity without swinging their arm.", player, CheckType.NO_SWING); log("tried to damage an entity without swinging their arm.", player, CheckType.NO_SWING);
noHack = false; noHack = false;
} }
if (checkManager.willCheck(player, CheckType.FORCEFIELD) && !backend.checkSight(player, e.getEntity())) if (checkManager.willCheck(player, CheckType.FORCEFIELD) && !backend.checkSight(player, e.getEntity())) {
{
event.setCancelled(!config.silentMode()); event.setCancelled(!config.silentMode());
log("tried to damage an entity that they couldn't see.", player, CheckType.FORCEFIELD); log("tried to damage an entity that they couldn't see.", player, CheckType.FORCEFIELD);
noHack = false; noHack = false;
} }
if (noHack) if (noHack) {
{
decrease(player); decrease(player);
} }
} }
@@ -26,8 +26,7 @@ import net.h31ix.anticheat.manage.*;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
public class EventListener implements Listener public class EventListener implements Listener {
{
private static final Map<CheckType, Integer> USAGE_LIST = new EnumMap<CheckType, Integer>(CheckType.class); private static final Map<CheckType, Integer> USAGE_LIST = new EnumMap<CheckType, Integer>(CheckType.class);
private static final Map<String, Integer> DECREASE_LIST = new HashMap<String, Integer>(); private static final Map<String, Integer> DECREASE_LIST = new HashMap<String, Integer>();
private static final CheckManager CHECK_MANAGER = Anticheat.getManager().getCheckManager(); private static final CheckManager CHECK_MANAGER = Anticheat.getManager().getCheckManager();
@@ -35,58 +34,46 @@ public class EventListener implements Listener
private static final Anticheat PLUGIN = Anticheat.getManager().getPlugin(); private static final Anticheat PLUGIN = Anticheat.getManager().getPlugin();
private static final UserManager USER_MANAGER = Anticheat.getManager().getUserManager(); private static final UserManager USER_MANAGER = Anticheat.getManager().getUserManager();
public static void log(String message, Player player, CheckType type) public static void log(String message, Player player, CheckType type) {
{
User user = getUserManager().getUser(player.getName()); User user = getUserManager().getUser(player.getName());
if (user.increaseLevel(type)) if (user.increaseLevel(type)) {
{
Anticheat.getManager().log(user.getName() + " " + message); Anticheat.getManager().log(user.getName() + " " + message);
} }
removeDecrease(user); removeDecrease(user);
logCheat(type, user); logCheat(type, user);
} }
private static void logCheat(CheckType type, User user) private static void logCheat(CheckType type, User user) {
{
USAGE_LIST.put(type, getCheats(type) + 1); USAGE_LIST.put(type, getCheats(type) + 1);
type.logUse(user.getName()); type.logUse(user.getName());
// Ignore plugins that are creating NPCs with no names (why the hell) // Ignore plugins that are creating NPCs with no names (why the hell)
if(user.getName() != null) if (user.getName() != null) {
{ if (Anticheat.getManager().getConfiguration().getFileLogLevel() == 2 && type.getUses(user.getName()) % 10 == 0) {
if (Anticheat.getManager().getConfiguration().getFileLogLevel() == 2 && type.getUses(user.getName()) % 10 == 0)
{
Anticheat.getManager().fileLog(user.getName() + " has triggered multiple " + type + " checks."); Anticheat.getManager().fileLog(user.getName() + " has triggered multiple " + type + " checks.");
} }
} }
} }
public void resetCheck(CheckType type) public void resetCheck(CheckType type) {
{
USAGE_LIST.put(type, 0); USAGE_LIST.put(type, 0);
} }
public static int getCheats(CheckType type) public static int getCheats(CheckType type) {
{
int x = 0; int x = 0;
if (USAGE_LIST.get(type) != null) if (USAGE_LIST.get(type) != null) {
{
x = USAGE_LIST.get(type); x = USAGE_LIST.get(type);
} }
return x; return x;
} }
private static void removeDecrease(User user) private static void removeDecrease(User user) {
{
int x = 0; int x = 0;
// Ignore plugins that are creating NPCs with no names // Ignore plugins that are creating NPCs with no names
if(user.getName() != null) if (user.getName() != null) {
{ if (DECREASE_LIST.get(user.getName()) != null) {
if (DECREASE_LIST.get(user.getName()) != null)
{
x = DECREASE_LIST.get(user.getName()); x = DECREASE_LIST.get(user.getName());
x -= 2; x -= 2;
if (x < 0) if (x < 0) {
{
x = 0; x = 0;
} }
} }
@@ -94,49 +81,40 @@ public class EventListener implements Listener
} }
} }
public static void decrease(Player player) public static void decrease(Player player) {
{
User user = getUserManager().getUser(player.getName()); User user = getUserManager().getUser(player.getName());
// Ignore plugins that are creating NPCs with no names // Ignore plugins that are creating NPCs with no names
if(user.getName() != null) if (user.getName() != null) {
{
int x = 0; int x = 0;
if (DECREASE_LIST.get(user.getName()) != null) if (DECREASE_LIST.get(user.getName()) != null) {
{
x = DECREASE_LIST.get(user.getName()); x = DECREASE_LIST.get(user.getName());
} }
x += 1; x += 1;
DECREASE_LIST.put(user.getName(), x); DECREASE_LIST.put(user.getName(), x);
if (x >= 10) if (x >= 10) {
{
user.decreaseLevel(); user.decreaseLevel();
DECREASE_LIST.put(user.getName(), 0); DECREASE_LIST.put(user.getName(), 0);
} }
} }
} }
public static CheckManager getCheckManager() public static CheckManager getCheckManager() {
{
return CHECK_MANAGER; return CHECK_MANAGER;
} }
public static AnticheatManager getManager() public static AnticheatManager getManager() {
{
return Anticheat.getManager(); return Anticheat.getManager();
} }
public static Backend getBackend() public static Backend getBackend() {
{
return BACKEND; return BACKEND;
} }
public static UserManager getUserManager() public static UserManager getUserManager() {
{
return USER_MANAGER; return USER_MANAGER;
} }
public static Anticheat getPlugin() public static Anticheat getPlugin() {
{
return PLUGIN; return PLUGIN;
} }
} }
@@ -27,31 +27,24 @@ import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryClickEvent;
public class InventoryListener extends EventListener{ public class InventoryListener extends EventListener {
private final Backend backend = getBackend(); private final Backend backend = getBackend();
private final CheckManager checkManager = getCheckManager(); private final CheckManager checkManager = getCheckManager();
private final Configuration config = Anticheat.getManager().getConfiguration(); private final Configuration config = Anticheat.getManager().getConfiguration();
@EventHandler @EventHandler
public void onInventoryClick(InventoryClickEvent event) public void onInventoryClick(InventoryClickEvent event) {
{ if (event.getWhoClicked() instanceof Player) {
if (event.getWhoClicked() instanceof Player)
{
Player player = (Player) event.getWhoClicked(); Player player = (Player) event.getWhoClicked();
if(checkManager.willCheck(player, CheckType.FAST_INVENTORY)) if (checkManager.willCheck(player, CheckType.FAST_INVENTORY)) {
{ if (backend.checkInventoryClicks(player)) {
if(backend.checkInventoryClicks(player)) if (!config.silentMode()) {
{
if(!config.silentMode())
{
event.setCancelled(!config.silentMode()); event.setCancelled(!config.silentMode());
player.setHealth(0); player.setHealth(0);
} }
log("tried to use their inventory too fast", player, CheckType.FAST_INVENTORY); log("tried to use their inventory too fast", player, CheckType.FAST_INVENTORY);
} } else {
else
{
decrease(player); decrease(player);
} }
} }
@@ -42,21 +42,17 @@ import org.bukkit.event.player.*;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import org.bukkit.inventory.PlayerInventory; import org.bukkit.inventory.PlayerInventory;
public class PlayerListener extends EventListener public class PlayerListener extends EventListener {
{
private final Backend backend = getBackend(); private final Backend backend = getBackend();
private final CheckManager checkManager = getCheckManager(); private final CheckManager checkManager = getCheckManager();
private final Configuration config = Anticheat.getManager().getConfiguration(); private final Configuration config = Anticheat.getManager().getConfiguration();
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) {
{
Player player = event.getPlayer(); Player player = event.getPlayer();
if (checkManager.willCheck(player, CheckType.SPAM) && config.commandSpam()) if (checkManager.willCheck(player, CheckType.SPAM) && config.commandSpam()) {
{
backend.logChat(player); backend.logChat(player);
if (backend.checkSpam(player, event.getMessage())) if (backend.checkSpam(player, event.getMessage())) {
{
event.setCancelled(!config.silentMode()); event.setCancelled(!config.silentMode());
player.sendMessage(ChatColor.RED + "Please do not spam."); player.sendMessage(ChatColor.RED + "Please do not spam.");
} }
@@ -64,37 +60,27 @@ public class PlayerListener extends EventListener
} }
@EventHandler @EventHandler
public void onPlayerToggleFlight(PlayerToggleFlightEvent event) public void onPlayerToggleFlight(PlayerToggleFlightEvent event) {
{ if (!event.isFlying()) {
if (!event.isFlying())
{
backend.logEnterExit(event.getPlayer()); backend.logEnterExit(event.getPlayer());
} }
} }
@EventHandler @EventHandler
public void onPlayerGameModeChange(PlayerGameModeChangeEvent event) public void onPlayerGameModeChange(PlayerGameModeChangeEvent event) {
{ if (event.getNewGameMode() != GameMode.CREATIVE) {
if (event.getNewGameMode() != GameMode.CREATIVE)
{
backend.logEnterExit(event.getPlayer()); backend.logEnterExit(event.getPlayer());
} }
} }
@EventHandler @EventHandler
public void onProjectileLaunch(ProjectileLaunchEvent event) public void onProjectileLaunch(ProjectileLaunchEvent event) {
{ if (event.getEntity().getShooter() instanceof Player) {
if (event.getEntity().getShooter() instanceof Player)
{
Player player = (Player) event.getEntity().getShooter(); Player player = (Player) event.getEntity().getShooter();
if (event.getEntity() instanceof Arrow) if (event.getEntity() instanceof Arrow) { return; }
{
return;
}
if (checkManager.willCheck(player, CheckType.FAST_PROJECTILE) && backend.checkProjectile(player)) if (checkManager.willCheck(player, CheckType.FAST_PROJECTILE) && backend.checkProjectile(player)) {
{
event.setCancelled(!config.silentMode()); event.setCancelled(!config.silentMode());
log("tried to fire projectiles too fast.", player, CheckType.FAST_PROJECTILE); log("tried to fire projectiles too fast.", player, CheckType.FAST_PROJECTILE);
} }
@@ -102,37 +88,30 @@ public class PlayerListener extends EventListener
} }
@EventHandler @EventHandler
public void onPlayerTeleport(PlayerTeleportEvent event) public void onPlayerTeleport(PlayerTeleportEvent event) {
{ if (event.getCause() == TeleportCause.ENDER_PEARL || event.getCause() == TeleportCause.PLUGIN) {
if (event.getCause() == TeleportCause.ENDER_PEARL || event.getCause() == TeleportCause.PLUGIN)
{
backend.logTeleport(event.getPlayer()); backend.logTeleport(event.getPlayer());
} }
} }
@EventHandler @EventHandler
public void onPlayerChangeWorlds(PlayerChangedWorldEvent event) public void onPlayerChangeWorlds(PlayerChangedWorldEvent event) {
{
backend.logTeleport(event.getPlayer()); backend.logTeleport(event.getPlayer());
} }
@EventHandler @EventHandler
public void onPlayerToggleSneak(PlayerToggleSneakEvent event) public void onPlayerToggleSneak(PlayerToggleSneakEvent event) {
{ if (event.isSneaking()) {
if (event.isSneaking())
{
backend.logToggleSneak(event.getPlayer()); backend.logToggleSneak(event.getPlayer());
} }
} }
@EventHandler @EventHandler
public void onPlayerVelocity(PlayerVelocityEvent event) public void onPlayerVelocity(PlayerVelocityEvent event) {
{
Player player = event.getPlayer(); Player player = event.getPlayer();
if (checkManager.willCheck(player, CheckType.FLY) && checkManager.willCheck(player, CheckType.ZOMBE_FLY)) //@h31ix: Change if necessary. I'm not sure what perms should go here :3 if (checkManager.willCheck(player, CheckType.FLY) && checkManager.willCheck(player, CheckType.ZOMBE_FLY)) // @h31ix: Change if necessary. I'm not sure what perms should go here :3
{
if (backend.justVelocity(player) && backend.extendVelocityTime(player))
{ {
if (backend.justVelocity(player) && backend.extendVelocityTime(player)) {
event.setCancelled(!config.silentMode()); event.setCancelled(!config.silentMode());
return; // don't log it lol. return; // don't log it lol.
} }
@@ -141,18 +120,14 @@ public class PlayerListener extends EventListener
} }
@EventHandler(ignoreCancelled = true) @EventHandler(ignoreCancelled = true)
public void onPlayerChat(AsyncPlayerChatEvent event) public void onPlayerChat(AsyncPlayerChatEvent event) {
{
Player player = event.getPlayer(); Player player = event.getPlayer();
if (checkManager.willCheck(player, CheckType.SPAM) && config.chatSpam()) if (checkManager.willCheck(player, CheckType.SPAM) && config.chatSpam()) {
{
backend.logChat(player); backend.logChat(player);
if (backend.checkSpam(player, event.getMessage())) if (backend.checkSpam(player, event.getMessage())) {
{
boolean b = !config.silentMode(); boolean b = !config.silentMode();
event.setCancelled(b); event.setCancelled(b);
if (b) if (b) {
{
player.sendMessage(ChatColor.RED + config.getLang().getChatWarning()); player.sendMessage(ChatColor.RED + config.getLang().getChatWarning());
} }
} }
@@ -160,123 +135,95 @@ public class PlayerListener extends EventListener
} }
@EventHandler @EventHandler
public void onPlayerKick(PlayerKickEvent event) public void onPlayerKick(PlayerKickEvent event) {
{
backend.clearChatLevel(event.getPlayer()); backend.clearChatLevel(event.getPlayer());
backend.garbageClean(event.getPlayer()); backend.garbageClean(event.getPlayer());
} }
@EventHandler @EventHandler
public void onPlayerQuit(PlayerQuitEvent event) public void onPlayerQuit(PlayerQuitEvent event) {
{
backend.garbageClean(event.getPlayer()); backend.garbageClean(event.getPlayer());
} }
@EventHandler @EventHandler
public void onPlayerToggleSprint(PlayerToggleSprintEvent event) public void onPlayerToggleSprint(PlayerToggleSprintEvent event) {
{
Player player = event.getPlayer(); Player player = event.getPlayer();
if (checkManager.willCheck(player, CheckType.SPRINT)) if (checkManager.willCheck(player, CheckType.SPRINT)) {
{ if (backend.checkSprintHungry(event)) {
if (backend.checkSprintHungry(event))
{
event.setCancelled(!config.silentMode()); event.setCancelled(!config.silentMode());
log("tried to sprint while hungry.", player, CheckType.SPRINT); log("tried to sprint while hungry.", player, CheckType.SPRINT);
} } else {
else
{
decrease(player); decrease(player);
} }
} }
} }
@EventHandler @EventHandler
public void onPlayerInteract(PlayerInteractEvent event) public void onPlayerInteract(PlayerInteractEvent event) {
{
Player player = event.getPlayer(); Player player = event.getPlayer();
PlayerInventory inv = player.getInventory(); PlayerInventory inv = player.getInventory();
if (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK) if (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK) {
{
Material m = inv.getItemInHand().getType(); Material m = inv.getItemInHand().getType();
if (m == Material.BOW) if (m == Material.BOW) {
{
backend.logBowWindUp(player); backend.logBowWindUp(player);
} } else if (Utilities.isFood(m)) {
else if (Utilities.isFood(m))
{
backend.logEatingStart(player); backend.logEatingStart(player);
} }
} }
Block block = event.getClickedBlock(); Block block = event.getClickedBlock();
if (block != null) if (block != null) {
{
Distance distance = new Distance(player.getLocation(), block.getLocation()); Distance distance = new Distance(player.getLocation(), block.getLocation());
backend.checkLongReachBlock(player, distance.getXDifference(), distance.getYDifference(), distance.getZDifference()); backend.checkLongReachBlock(player, distance.getXDifference(), distance.getYDifference(), distance.getZDifference());
} }
} }
@EventHandler(ignoreCancelled = true) @EventHandler(ignoreCancelled = true)
public void onPlayerDropItem(PlayerDropItemEvent event) public void onPlayerDropItem(PlayerDropItemEvent event) {
{
Player player = event.getPlayer(); Player player = event.getPlayer();
if (checkManager.willCheck(player, CheckType.ITEM_SPAM) && backend.checkFastDrop(player)) if (checkManager.willCheck(player, CheckType.ITEM_SPAM) && backend.checkFastDrop(player)) {
{
event.setCancelled(!config.silentMode()); event.setCancelled(!config.silentMode());
} }
} }
@EventHandler(ignoreCancelled = true) @EventHandler(ignoreCancelled = true)
public void onPlayerEnterBed(PlayerBedEnterEvent event) public void onPlayerEnterBed(PlayerBedEnterEvent event) {
{
backend.logEnterExit(event.getPlayer()); backend.logEnterExit(event.getPlayer());
} }
@EventHandler(ignoreCancelled = true) @EventHandler(ignoreCancelled = true)
public void onPlayerExitBed(PlayerBedLeaveEvent event) public void onPlayerExitBed(PlayerBedLeaveEvent event) {
{
backend.logEnterExit(event.getPlayer()); backend.logEnterExit(event.getPlayer());
} }
@EventHandler @EventHandler
public void onPlayerAnimation(PlayerAnimationEvent event) public void onPlayerAnimation(PlayerAnimationEvent event) {
{
Player player = event.getPlayer(); Player player = event.getPlayer();
backend.logAnimation(player); backend.logAnimation(player);
} }
@EventHandler @EventHandler
public void onPlayerJoin(PlayerJoinEvent event) public void onPlayerJoin(PlayerJoinEvent event) {
{
Player player = event.getPlayer(); Player player = event.getPlayer();
String section = "\u00a7"; String section = "\u00a7";
if (checkManager.willCheck(player, CheckType.ZOMBE_FLY)) if (checkManager.willCheck(player, CheckType.ZOMBE_FLY)) {
{
player.sendMessage(section + "f " + section + "f " + section + "1 " + section + "0 " + section + "2 " + section + "4"); player.sendMessage(section + "f " + section + "f " + section + "1 " + section + "0 " + section + "2 " + section + "4");
} }
if (checkManager.willCheck(player, CheckType.ZOMBE_CHEAT)) if (checkManager.willCheck(player, CheckType.ZOMBE_CHEAT)) {
{
player.sendMessage(section + "f " + section + "f " + section + "2 " + section + "0 " + section + "4 " + section + "8"); player.sendMessage(section + "f " + section + "f " + section + "2 " + section + "0 " + section + "4 " + section + "8");
} }
if (checkManager.willCheck(player, CheckType.ZOMBE_NOCLIP)) if (checkManager.willCheck(player, CheckType.ZOMBE_NOCLIP)) {
{
player.sendMessage(section + "f " + section + "f " + section + "4 " + section + "0 " + section + "9 " + section + "6"); player.sendMessage(section + "f " + section + "f " + section + "4 " + section + "0 " + section + "9 " + section + "6");
} }
backend.logJoin(player); backend.logJoin(player);
if (getUserManager().getUser(player.getName()) == null) if (getUserManager().getUser(player.getName()) == null) {
{
getUserManager().addUser(new User(player.getName())); getUserManager().addUser(new User(player.getName()));
} } else {
else
{
getUserManager().addUserFromFile(player.getName()); getUserManager().addUserFromFile(player.getName());
} }
if (player.hasMetadata(Anticheat.SPY_METADATA)) if (player.hasMetadata(Anticheat.SPY_METADATA)) {
{ for (Player p : player.getServer().getOnlinePlayers()) {
for (Player p : player.getServer().getOnlinePlayers()) if (!Permission.SYSTEM_SPY.get(p)) {
{
if (!Permission.SYSTEM_SPY.get(p))
{
p.hidePlayer(player); p.hidePlayer(player);
} }
} }
@@ -284,63 +231,48 @@ public class PlayerListener extends EventListener
} }
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void checkExploit(PlayerMoveEvent event) public void checkExploit(PlayerMoveEvent event) {
{
Player player = event.getPlayer(); Player player = event.getPlayer();
Location from = event.getFrom(); Location from = event.getFrom();
Location to = event.getTo(); Location to = event.getTo();
Distance distance = new Distance(from, to); Distance distance = new Distance(from, to);
double y = distance.getYDifference(); double y = distance.getYDifference();
backend.logAscension(player, from.getY(), to.getY()); backend.logAscension(player, from.getY(), to.getY());
if (checkManager.willCheck(player, CheckType.SPEED) && backend.checkFreeze(player, from.getY(), to.getY())) if (checkManager.willCheck(player, CheckType.SPEED) && backend.checkFreeze(player, from.getY(), to.getY())) {
{
log("tried to freeze in mid-air.", player, CheckType.SPEED); log("tried to freeze in mid-air.", player, CheckType.SPEED);
player.kickPlayer("Freezing client"); player.kickPlayer("Freezing client");
} }
if (checkManager.willCheck(player, CheckType.SPRINT)) if (checkManager.willCheck(player, CheckType.SPRINT)) {
{ if (backend.checkSprintStill(player, from, to)) {
if (backend.checkSprintStill(player, from, to))
{
event.setCancelled(!config.silentMode()); event.setCancelled(!config.silentMode());
log("tried to sprint while standing still.", player, CheckType.SPRINT); log("tried to sprint while standing still.", player, CheckType.SPRINT);
} }
} }
if (checkManager.willCheck(player, CheckType.FLY) && !player.isFlying() && checkManager.willCheck(player, CheckType.ZOMBE_FLY) && backend.checkFlight(player, distance)) if (checkManager.willCheck(player, CheckType.FLY) && !player.isFlying() && checkManager.willCheck(player, CheckType.ZOMBE_FLY) && backend.checkFlight(player, distance)) {
{ if (!config.silentMode()) {
if (!config.silentMode())
{
event.setTo(Anticheat.getManager().getUserManager().getUser(player.getName()).getGoodLocation(from.clone())); event.setTo(Anticheat.getManager().getUserManager().getUser(player.getName()).getGoodLocation(from.clone()));
} }
log("tried to fly.", player, CheckType.FLY); log("tried to fly.", player, CheckType.FLY);
} }
if (checkManager.willCheck(player, CheckType.FLY) && !player.isFlying() && checkManager.willCheck(player, CheckType.ZOMBE_FLY) && (backend.checkYAxis(player, distance) || backend.checkAscension(player, from.getY(), to.getY()))) if (checkManager.willCheck(player, CheckType.FLY) && !player.isFlying() && checkManager.willCheck(player, CheckType.ZOMBE_FLY) && (backend.checkYAxis(player, distance) || backend.checkAscension(player, from.getY(), to.getY()))) {
{ if (!config.silentMode()) {
if (!config.silentMode())
{
event.setTo(Anticheat.getManager().getUserManager().getUser(player.getName()).getGoodLocation(from.clone())); event.setTo(Anticheat.getManager().getUserManager().getUser(player.getName()).getGoodLocation(from.clone()));
} }
log("tried to fly on y-axis", player, CheckType.FLY); log("tried to fly on y-axis", player, CheckType.FLY);
} }
if (checkManager.willCheck(player, CheckType.VCLIP) && checkManager.willCheck(player, CheckType.ZOMBE_FLY) && checkManager.willCheck(player, CheckType.FLY) && event.getFrom().getY() > event.getTo().getY()) if (checkManager.willCheck(player, CheckType.VCLIP) && checkManager.willCheck(player, CheckType.ZOMBE_FLY) && checkManager.willCheck(player, CheckType.FLY) && event.getFrom().getY() > event.getTo().getY()) {
{
int result = backend.checkVClip(player, new Distance(event.getFrom(), event.getTo())); int result = backend.checkVClip(player, new Distance(event.getFrom(), event.getTo()));
if (result > 0) if (result > 0) {
{ if (!config.silentMode()) {
if (!config.silentMode())
{
// You come back up, and you suddenly feel sick from trying to stick yourself through the blocks.. // You come back up, and you suddenly feel sick from trying to stick yourself through the blocks..
Location newloc = new Location(player.getWorld(), event.getFrom().getX(), event.getFrom().getY() + result, event.getFrom().getZ()); Location newloc = new Location(player.getWorld(), event.getFrom().getX(), event.getFrom().getY() + result, event.getFrom().getZ());
if (result > 3) if (result > 3) {
{
result = 3; // prevents players from using AC as a way to teleport to sky islands. result = 3; // prevents players from using AC as a way to teleport to sky islands.
} }
if (newloc.getBlock().getTypeId() == 0) if (newloc.getBlock().getTypeId() == 0) {
{
event.setTo(newloc); event.setTo(newloc);
} } else {
else
{
event.setTo(Anticheat.getManager().getUserManager().getUser(player.getName()).getGoodLocation(from.clone())); event.setTo(Anticheat.getManager().getUserManager().getUser(player.getName()).getGoodLocation(from.clone()));
} }
player.damage(3); player.damage(3);
@@ -348,10 +280,8 @@ public class PlayerListener extends EventListener
log("tried to move down through a block.", player, CheckType.VCLIP); log("tried to move down through a block.", player, CheckType.VCLIP);
} }
} }
if (checkManager.willCheck(player, CheckType.NOFALL) && checkManager.willCheck(player, CheckType.ZOMBE_FLY) && checkManager.willCheck(player, CheckType.FLY) && !Utilities.isClimbableBlock(player.getLocation().getBlock()) && event.getFrom().getY() > event.getTo().getY() && backend.checkNoFall(player, y)) if (checkManager.willCheck(player, CheckType.NOFALL) && checkManager.willCheck(player, CheckType.ZOMBE_FLY) && checkManager.willCheck(player, CheckType.FLY) && !Utilities.isClimbableBlock(player.getLocation().getBlock()) && event.getFrom().getY() > event.getTo().getY() && backend.checkNoFall(player, y)) {
{ if (!config.silentMode()) {
if (!config.silentMode())
{
event.setTo(Anticheat.getManager().getUserManager().getUser(player.getName()).getGoodLocation(from.clone())); event.setTo(Anticheat.getManager().getUserManager().getUser(player.getName()).getGoodLocation(from.clone()));
player.damage(2); // I added this in here so the player(s) would still receive damage. player.damage(2); // I added this in here so the player(s) would still receive damage.
} }
@@ -360,80 +290,64 @@ public class PlayerListener extends EventListener
} }
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void checkSpeed(PlayerMoveEvent event) public void checkSpeed(PlayerMoveEvent event) {
{
Player player = event.getPlayer(); Player player = event.getPlayer();
Location from = event.getFrom(); Location from = event.getFrom();
Location to = event.getTo(); Location to = event.getTo();
boolean changed = false; boolean changed = false;
if (event.getTo() != event.getFrom()) if (event.getTo() != event.getFrom()) {
{
Distance distance = new Distance(from, to); Distance distance = new Distance(from, to);
double x = distance.getXDifference(); double x = distance.getXDifference();
double y = distance.getYDifference(); double y = distance.getYDifference();
double z = distance.getZDifference(); double z = distance.getZDifference();
if (checkManager.willCheck(player, CheckType.SPEED) && checkManager.willCheck(player, CheckType.ZOMBE_FLY) && checkManager.willCheck(player, CheckType.FLY)) if (checkManager.willCheck(player, CheckType.SPEED) && checkManager.willCheck(player, CheckType.ZOMBE_FLY) && checkManager.willCheck(player, CheckType.FLY)) {
{ if (event.getFrom().getY() < event.getTo().getY() && backend.checkYSpeed(player, y)) {
if (event.getFrom().getY() < event.getTo().getY() && backend.checkYSpeed(player, y)) if (!config.silentMode()) {
{
if (!config.silentMode())
{
event.setTo(Anticheat.getManager().getUserManager().getUser(player.getName()).getGoodLocation(from.clone())); event.setTo(Anticheat.getManager().getUserManager().getUser(player.getName()).getGoodLocation(from.clone()));
} }
log("tried to ascend too fast.", player, CheckType.SPEED); log("tried to ascend too fast.", player, CheckType.SPEED);
changed = true; changed = true;
} }
if (backend.checkXZSpeed(player, x, z)) if (backend.checkXZSpeed(player, x, z)) {
{ if (!config.silentMode()) {
if (!config.silentMode())
{
event.setTo(Anticheat.getManager().getUserManager().getUser(player.getName()).getGoodLocation(from.clone())); event.setTo(Anticheat.getManager().getUserManager().getUser(player.getName()).getGoodLocation(from.clone()));
} }
log("tried to move too fast.", player, CheckType.SPEED); log("tried to move too fast.", player, CheckType.SPEED);
changed = true; changed = true;
} }
if ((event.getFrom().getX() != event.getTo().getX() || event.getFrom().getZ() != event.getTo().getZ()) && backend.checkTimer(player)) if ((event.getFrom().getX() != event.getTo().getX() || event.getFrom().getZ() != event.getTo().getZ()) && backend.checkTimer(player)) {
{ if (!config.silentMode()) {
if (!config.silentMode())
{
event.setTo(Anticheat.getManager().getUserManager().getUser(player.getName()).getGoodLocation(from.clone())); event.setTo(Anticheat.getManager().getUserManager().getUser(player.getName()).getGoodLocation(from.clone()));
} }
log("tried to alter their timer.", player, CheckType.SPEED); log("tried to alter their timer.", player, CheckType.SPEED);
changed = true; changed = true;
} }
} }
if (checkManager.willCheck(player, CheckType.WATER_WALK) && backend.checkWaterWalk(player, x, y, z)) if (checkManager.willCheck(player, CheckType.WATER_WALK) && backend.checkWaterWalk(player, x, y, z)) {
{ if (!config.silentMode()) {
if (!config.silentMode())
{
player.teleport(Anticheat.getManager().getUserManager().getUser(player.getName()).getGoodLocation(player.getLocation().add(0, -1, 0))); player.teleport(Anticheat.getManager().getUserManager().getUser(player.getName()).getGoodLocation(player.getLocation().add(0, -1, 0)));
} }
log("tried to walk on water.", player, CheckType.WATER_WALK); log("tried to walk on water.", player, CheckType.WATER_WALK);
changed = true; changed = true;
} }
if (checkManager.willCheck(player, CheckType.SNEAK) && backend.checkSneak(player, x, z)) if (checkManager.willCheck(player, CheckType.SNEAK) && backend.checkSneak(player, x, z)) {
{ if (!config.silentMode()) {
if (!config.silentMode())
{
event.setTo(Anticheat.getManager().getUserManager().getUser(player.getName()).getGoodLocation(from.clone())); event.setTo(Anticheat.getManager().getUserManager().getUser(player.getName()).getGoodLocation(from.clone()));
player.setSneaking(false); player.setSneaking(false);
} }
log("tried to sneak too fast.", player, CheckType.SNEAK); log("tried to sneak too fast.", player, CheckType.SNEAK);
changed = true; changed = true;
} }
if (checkManager.willCheck(player, CheckType.SPIDER) && backend.checkSpider(player, y)) if (checkManager.willCheck(player, CheckType.SPIDER) && backend.checkSpider(player, y)) {
{ if (!config.silentMode()) {
if (!config.silentMode())
{
event.setTo(Anticheat.getManager().getUserManager().getUser(player.getName()).getGoodLocation(from.clone())); event.setTo(Anticheat.getManager().getUserManager().getUser(player.getName()).getGoodLocation(from.clone()));
} }
log("tried to climb a wall.", player, CheckType.SPIDER); log("tried to climb a wall.", player, CheckType.SPIDER);
changed = true; changed = true;
} }
if (!changed) if (!changed) {
{
Anticheat.getManager().getUserManager().getUser(player.getName()).setGoodLocation(event.getFrom()); Anticheat.getManager().getUserManager().getUser(player.getName()).setGoodLocation(event.getFrom());
} }
} }
@@ -24,24 +24,19 @@ import org.bukkit.event.EventHandler;
import org.bukkit.event.vehicle.VehicleEnterEvent; import org.bukkit.event.vehicle.VehicleEnterEvent;
import org.bukkit.event.vehicle.VehicleExitEvent; import org.bukkit.event.vehicle.VehicleExitEvent;
public class VehicleListener extends EventListener public class VehicleListener extends EventListener {
{
private final Backend backend = getBackend(); private final Backend backend = getBackend();
@EventHandler(ignoreCancelled = true) @EventHandler(ignoreCancelled = true)
public void onVehicleEnter(VehicleEnterEvent event) public void onVehicleEnter(VehicleEnterEvent event) {
{ if (event.getEntered() instanceof Player) {
if (event.getEntered() instanceof Player)
{
backend.logEnterExit((Player) event.getEntered()); backend.logEnterExit((Player) event.getEntered());
} }
} }
@EventHandler(ignoreCancelled = true) @EventHandler(ignoreCancelled = true)
public void onVehicleExit(VehicleExitEvent event) public void onVehicleExit(VehicleExitEvent event) {
{ if (event.getExited() instanceof Player) {
if (event.getExited() instanceof Player)
{
backend.logEnterExit((Player) event.getExited()); backend.logEnterExit((Player) event.getExited());
} }
} }
@@ -37,8 +37,7 @@ import org.bukkit.ChatColor;
* The internal hub for all managers. * The internal hub for all managers.
*/ */
public class AnticheatManager public class AnticheatManager {
{
private Anticheat plugin = null; private Anticheat plugin = null;
private Configuration configuration; private Configuration configuration;
private XRayTracker xrayTracker = null; private XRayTracker xrayTracker = null;
@@ -50,8 +49,7 @@ public class AnticheatManager
private static Handler fileHandler; private static Handler fileHandler;
private static final int LOG_LEVEL_HIGH = 3; private static final int LOG_LEVEL_HIGH = 3;
public AnticheatManager(Anticheat instance, Logger logger) public AnticheatManager(Anticheat instance, Logger logger) {
{
plugin = instance; plugin = instance;
// now load all the others!!!!! // now load all the others!!!!!
fileLogger = Logger.getLogger("net.h31ix.anticheat.Anticheat"); fileLogger = Logger.getLogger("net.h31ix.anticheat.Anticheat");
@@ -60,98 +58,77 @@ public class AnticheatManager
userManager = new UserManager(configuration); userManager = new UserManager(configuration);
checkManager = new CheckManager(this); checkManager = new CheckManager(this);
backend = new Backend(this); backend = new Backend(this);
try try {
{
File file = new File(plugin.getDataFolder() + "/log"); File file = new File(plugin.getDataFolder() + "/log");
if (!file.exists()) if (!file.exists()) {
{
file.mkdir(); file.mkdir();
} }
fileHandler = new FileHandler(plugin.getDataFolder() + "/log/anticheat.log", true); fileHandler = new FileHandler(plugin.getDataFolder() + "/log/anticheat.log", true);
fileHandler.setFormatter(new FileFormatter()); fileHandler.setFormatter(new FileFormatter());
} } catch (Exception ex) {
catch (Exception ex)
{
logger.log(Level.SEVERE, null, ex); logger.log(Level.SEVERE, null, ex);
} }
fileLogger.setUseParentHandlers(false); fileLogger.setUseParentHandlers(false);
fileLogger.addHandler(fileHandler); fileLogger.addHandler(fileHandler);
} }
public void log(String message) public void log(String message) {
{
log(message, 0); log(message, 0);
} }
public void log(String message, int i) public void log(String message, int i) {
{ if (getConfiguration().logConsole()) {
if (getConfiguration().logConsole()) Bukkit.getConsoleSender().sendMessage(ChatColor.RED + message);
{
Bukkit.getConsoleSender().sendMessage(ChatColor.RED+message);
} }
if(i == 0 && getConfiguration().getFileLogLevel() == LOG_LEVEL_HIGH) // Not an alert, normal log message if (i == 0 && getConfiguration().getFileLogLevel() == LOG_LEVEL_HIGH) // Not an alert, normal log message
{ {
fileLog(message); fileLog(message);
} } else if (getConfiguration().getFileLogLevel() != 0)// alert
else if(getConfiguration().getFileLogLevel() != 0)// alert
{ {
fileLog(message); fileLog(message);
} }
logs.add(ChatColor.stripColor(message)); logs.add(ChatColor.stripColor(message));
} }
public void fileLog(String message) public void fileLog(String message) {
{
fileLogger.info(message); fileLogger.info(message);
} }
public List<String> getLastLogs() public List<String> getLastLogs() {
{
List<String> log = new CopyOnWriteArrayList<String>(); List<String> log = new CopyOnWriteArrayList<String>();
if (logs.size() < 30) if (logs.size() < 30) { return logs; }
{ for (int i = logs.size() - 1; i >= 0; i--) {
return logs;
}
for(int i = logs.size()-1; i >= 0; i--)
{
log.add(logs.get(i)); log.add(logs.get(i));
} }
logs.clear(); logs.clear();
return log; return log;
} }
public Anticheat getPlugin() public Anticheat getPlugin() {
{
return plugin; return plugin;
} }
public Configuration getConfiguration() public Configuration getConfiguration() {
{
return configuration; return configuration;
} }
public XRayTracker getXRayTracker() public XRayTracker getXRayTracker() {
{
return xrayTracker; return xrayTracker;
} }
public UserManager getUserManager() public UserManager getUserManager() {
{
return userManager; return userManager;
} }
public CheckManager getCheckManager() public CheckManager getCheckManager() {
{
return checkManager; return checkManager;
} }
public Backend getBackend() public Backend getBackend() {
{
return backend; return backend;
} }
public static void close() public static void close() {
{
fileHandler.close(); fileHandler.close();
} }
} }
File diff suppressed because it is too large. Load diff
@@ -27,53 +27,42 @@ import org.bukkit.entity.Player;
/** /**
* <p> * <p>
* The manager that AntiCheat will check with to see if it should watch certain * The manager that AntiCheat will check with to see if it should watch certain checks and certain players.
* checks and certain players.
*/ */
public class CheckManager public class CheckManager {
{
private AnticheatManager manager = null; private AnticheatManager manager = null;
private static List<CheckType> checkIgnoreList = new ArrayList<CheckType>(); private static List<CheckType> checkIgnoreList = new ArrayList<CheckType>();
private static Map<String, List<CheckType>> exemptList = new HashMap<String, List<CheckType>>(); private static Map<String, List<CheckType>> exemptList = new HashMap<String, List<CheckType>>();
private static int disabled = 0; private static int disabled = 0;
private static int exempt = 0; private static int exempt = 0;
public CheckManager(AnticheatManager instance) public CheckManager(AnticheatManager instance) {
{
manager = instance; manager = instance;
} }
public void activateCheck(CheckType type) public void activateCheck(CheckType type) {
{ if (isActive(type)) {
if (isActive(type))
{
manager.log("The " + type.toString() + " check was activated."); manager.log("The " + type.toString() + " check was activated.");
checkIgnoreList.remove(type); checkIgnoreList.remove(type);
} }
} }
public void deactivateCheck(CheckType type) public void deactivateCheck(CheckType type) {
{ if (!isActive(type)) {
if (!isActive(type))
{
manager.log("The " + type.toString() + " check was deactivated."); manager.log("The " + type.toString() + " check was deactivated.");
checkIgnoreList.add(type); checkIgnoreList.add(type);
disabled++; disabled++;
} }
} }
public boolean isActive(CheckType type) public boolean isActive(CheckType type) {
{
return !checkIgnoreList.contains(type); return !checkIgnoreList.contains(type);
} }
public void exemptPlayer(Player player, CheckType type) public void exemptPlayer(Player player, CheckType type) {
{ if (!isExempt(player, type)) {
if (!isExempt(player, type)) if (!exemptList.containsKey(player.getName())) {
{
if(!exemptList.containsKey(player.getName()))
{
exemptList.put(player.getName(), new ArrayList<CheckType>()); exemptList.put(player.getName(), new ArrayList<CheckType>());
} }
manager.log(player.getName() + " was exempted from the " + type.toString() + " check."); manager.log(player.getName() + " was exempted from the " + type.toString() + " check.");
@@ -82,52 +71,40 @@ public class CheckManager
} }
} }
public void unexemptPlayer(Player player, CheckType type) public void unexemptPlayer(Player player, CheckType type) {
{ if (isExempt(player, type)) {
if (isExempt(player, type))
{
manager.log(player.getName() + " was re-added to the " + type.toString() + " check."); manager.log(player.getName() + " was re-added to the " + type.toString() + " check.");
exemptList.get(player.getName()).remove(type); exemptList.get(player.getName()).remove(type);
} }
} }
public boolean isExempt(Player player, CheckType type) public boolean isExempt(Player player, CheckType type) {
{
return exemptList.containsKey(player.getName()) ? exemptList.get(player.getName()).contains(type) : false; return exemptList.containsKey(player.getName()) ? exemptList.get(player.getName()).contains(type) : false;
} }
public boolean isOpExempt(Player player) public boolean isOpExempt(Player player) {
{
return (this.manager.getConfiguration().opExempt() && player.isOp()); return (this.manager.getConfiguration().opExempt() && player.isOp());
} }
public boolean willCheck(Player player, CheckType type) public boolean willCheck(Player player, CheckType type) {
{
return isActive(type) && manager.getConfiguration().checkInWorld(player.getWorld()) && !isExempt(player, type) && !type.checkPermission(player) && isOnline(player) && !isOpExempt(player); return isActive(type) && manager.getConfiguration().checkInWorld(player.getWorld()) && !isExempt(player, type) && !type.checkPermission(player) && isOnline(player) && !isOpExempt(player);
} }
public boolean isOnline(Player player) public boolean isOnline(Player player) {
{
// Check if the player is on the user list, e.g. is not an NPC // Check if the player is on the user list, e.g. is not an NPC
for(Player p : Bukkit.getOnlinePlayers()) for (Player p : Bukkit.getOnlinePlayers()) {
{ if (p.getName().equals(player.getName())) { return true; }
if(p.getName().equals(player.getName()))
{
return true;
}
} }
return false; return false;
} }
public int getExempt() public int getExempt() {
{
int x = exempt; int x = exempt;
exempt = 0; exempt = 0;
return x; return x;
} }
public int getDisabled() public int getDisabled() {
{
int x = disabled; int x = disabled;
disabled = 0; disabled = 0;
return x; return x;
@@ -28,8 +28,7 @@ import org.bukkit.entity.Player;
* All the types of checks and their corresponding permission nodes. * All the types of checks and their corresponding permission nodes.
*/ */
public enum CheckType public enum CheckType {
{
ZOMBE_FLY(Permission.CHECK_ZOMBE_FLY), ZOMBE_FLY(Permission.CHECK_ZOMBE_FLY),
ZOMBE_NOCLIP(Permission.CHECK_ZOMBE_NOCLIP), ZOMBE_NOCLIP(Permission.CHECK_ZOMBE_NOCLIP),
ZOMBE_CHEAT(Permission.CHECK_ZOMBE_CHEAT), ZOMBE_CHEAT(Permission.CHECK_ZOMBE_CHEAT),
@@ -59,34 +58,28 @@ public enum CheckType
private final Permission permission; private final Permission permission;
private final Map<String, Integer> level = new HashMap<String, Integer>(); private final Map<String, Integer> level = new HashMap<String, Integer>();
private CheckType(Permission perm) private CheckType(Permission perm) {
{
this.permission = perm; this.permission = perm;
} }
public boolean checkPermission(Player player) public boolean checkPermission(Player player) {
{
return permission.get(player); return permission.get(player);
} }
public void logUse(String name) public void logUse(String name) {
{
int amount = level.get(name) == null ? 1 : level.get(name) + 1; int amount = level.get(name) == null ? 1 : level.get(name) + 1;
level.put(name, amount); level.put(name, amount);
} }
public void clearUse(String name) public void clearUse(String name) {
{
level.put(name, 0); level.put(name, 0);
} }
public int getUses(String name) public int getUses(String name) {
{
return level.get(name) != null ? level.get(name) : 0; return level.get(name) != null ? level.get(name) : 0;
} }
public static String getName(CheckType type) public static String getName(CheckType type) {
{
char[] chars = type.toString().replaceAll("_", " ").toLowerCase().toCharArray(); char[] chars = type.toString().replaceAll("_", " ").toLowerCase().toCharArray();
chars[0] = Character.toUpperCase(chars[0]); chars[0] = Character.toUpperCase(chars[0]);
return new String(chars); return new String(chars);
@@ -21,13 +21,11 @@ package net.h31ix.anticheat.manage;
import net.h31ix.anticheat.Anticheat; import net.h31ix.anticheat.Anticheat;
import net.h31ix.anticheat.util.Configuration; import net.h31ix.anticheat.util.Configuration;
import net.h31ix.anticheat.util.Utilities; import net.h31ix.anticheat.util.Utilities;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
public class User public class User {
{
private final String name; private final String name;
private int level = 0; private int level = 0;
private int high; private int high;
@@ -35,121 +33,88 @@ public class User
private Location goodLocation; private Location goodLocation;
private boolean silentMode; private boolean silentMode;
public User(String name) public User(String name) {
{
this.name = name; this.name = name;
getConfigInfo(); getConfigInfo();
} }
public User(String name, int level) public User(String name, int level) {
{
this.name = name; this.name = name;
this.level = level; this.level = level;
getConfigInfo(); getConfigInfo();
} }
private void getConfigInfo() private void getConfigInfo() {
{
Configuration config = Anticheat.getManager().getConfiguration(); Configuration config = Anticheat.getManager().getConfiguration();
silentMode = config.silentMode(); silentMode = config.silentMode();
med = config.medThreshold(); med = config.medThreshold();
high = config.highThreshold(); high = config.highThreshold();
} }
public String getName() public String getName() {
{
return name; return name;
} }
public Player getPlayer() public Player getPlayer() {
{
return Bukkit.getPlayer(name); return Bukkit.getPlayer(name);
} }
public int getLevel() public int getLevel() {
{
return level; return level;
} }
public boolean increaseLevel(CheckType type) public boolean increaseLevel(CheckType type) {
{ if (getPlayer() != null && getPlayer().isOnline()) {
if(getPlayer() != null && getPlayer().isOnline()) if (silentMode && type.getUses(name) % 4 != 0) {
{
if(silentMode && type.getUses(name) % 4 != 0)
{
// Prevent silent mode from increasing the level way too fast // Prevent silent mode from increasing the level way too fast
return false; return false;
} } else {
else
{
level++; level++;
if(level == med) if (level == med) {
{
Anticheat.getManager().getUserManager().alertMed(this, type); Anticheat.getManager().getUserManager().alertMed(this, type);
} } else if (level == high) {
else if(level == high)
{
Anticheat.getManager().getUserManager().alertHigh(this, type); Anticheat.getManager().getUserManager().alertHigh(this, type);
// Prevent the player from going over the high limit // Prevent the player from going over the high limit
level = high-10; level = high - 10;
} }
return true; return true;
} }
} } else {
else
{
return false; return false;
} }
} }
public void decreaseLevel() public void decreaseLevel() {
{ level = level != 0 ? level - 1 : 0;
level = level != 0 ? level-1 : 0;
} }
public void setLevel(int level) public void setLevel(int level) {
{ if (level > 0 && level <= high) {
if(level > 0 && level <= high)
{
this.level = level; this.level = level;
} }
} }
public void resetLevel() public void resetLevel() {
{
level = 0; level = 0;
for (CheckType type : CheckType.values()) for (CheckType type : CheckType.values()) {
{
type.clearUse(name); type.clearUse(name);
} }
} }
public Location getGoodLocation(Location e) public Location getGoodLocation(Location e) {
{ if (goodLocation == null) { return e; }
if(goodLocation == null)
{
return e;
}
return goodLocation; return goodLocation;
} }
public boolean hasGoodLocation() public boolean hasGoodLocation() {
{
return goodLocation != null; return goodLocation != null;
} }
public void setGoodLocation(Location e) public void setGoodLocation(Location e) {
{ if (Utilities.cantStandAtExp(e)) { return; }
if(Utilities.cantStandAtExp(e))
{
return;
}
if(e.getBlock().isLiquid() && !Utilities.isFullyInWater(e)) if (e.getBlock().isLiquid() && !Utilities.isFullyInWater(e)) { return; }
{
return;
}
goodLocation = e; goodLocation = e;
} }
@@ -26,8 +26,7 @@ import net.h31ix.anticheat.util.Utilities;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
public class UserManager public class UserManager {
{
private List<User> users = new ArrayList<User>(); private List<User> users = new ArrayList<User>();
private static Configuration config; private static Configuration config;
private static Language lang; private static Language lang;
@@ -36,104 +35,77 @@ public class UserManager
private static final ChatColor YELLOW = ChatColor.YELLOW; private static final ChatColor YELLOW = ChatColor.YELLOW;
private static final ChatColor RED = ChatColor.RED; private static final ChatColor RED = ChatColor.RED;
public UserManager(Configuration conf) public UserManager(Configuration conf) {
{
config = conf; config = conf;
lang = conf.getLang(); lang = conf.getLang();
} }
public User getUser(String name) public User getUser(String name) {
{ for (User user : users) {
for(User user : users) if (user.getName().equalsIgnoreCase(name)) { return user; }
{
if(user.getName().equalsIgnoreCase(name))
{
return user;
}
} }
// Otherwise try to load them // Otherwise try to load them
return loadUserFromFile(name); return loadUserFromFile(name);
} }
public List<User> getUsers() public List<User> getUsers() {
{
return users; return users;
} }
public void addUser(User user) public void addUser(User user) {
{
users.add(user); users.add(user);
} }
public void remove(User user) public void remove(User user) {
{
config.saveLevel(user.getName(), user.getLevel()); config.saveLevel(user.getName(), user.getLevel());
users.remove(user); users.remove(user);
} }
public int safeGetLevel(String name) public int safeGetLevel(String name) {
{
User user = getUser(name); User user = getUser(name);
if(user == null) if (user == null) {
{
return 0; return 0;
} } else {
else
{
return user.getLevel(); return user.getLevel();
} }
} }
public void safeSetLevel(String name, int level) public void safeSetLevel(String name, int level) {
{
User user = getUser(name); User user = getUser(name);
if(user != null) if (user != null) {
{
user.setLevel(level); user.setLevel(level);
} }
} }
public void safeReset(String name) public void safeReset(String name) {
{
User user = getUser(name); User user = getUser(name);
if(user != null) if (user != null) {
{
user.resetLevel(); user.resetLevel();
} }
} }
public boolean addUserFromFile(String name) public boolean addUserFromFile(String name) {
{
User user = loadUserFromFile(name); User user = loadUserFromFile(name);
if(user != null) if (user != null) {
{
users.add(user); users.add(user);
return true; return true;
} } else {
else
{
return false; return false;
} }
} }
public User loadUserFromFile(String name) public User loadUserFromFile(String name) {
{
int level = config.getLevel(name); int level = config.getLevel(name);
if(level == -1) if (level == -1) {
{
return null; return null;
} } else {
else
{
return new User(name, level); return new User(name, level);
} }
} }
public void alertMed(User user, CheckType type) public void alertMed(User user, CheckType type) {
{
List<String> messageArray = lang.getMediumAlert(); List<String> messageArray = lang.getMediumAlert();
for(int i=0;i<messageArray.size();i++) for (int i = 0; i < messageArray.size(); i++) {
{
String message = messageArray.get(i); String message = messageArray.get(i);
message = message.replaceAll("&player", GOLD + user.getName() + GRAY); message = message.replaceAll("&player", GOLD + user.getName() + GRAY);
message = message.replaceAll("&check", GOLD + CheckType.getName(type) + GRAY); message = message.replaceAll("&check", GOLD + CheckType.getName(type) + GRAY);
@@ -144,11 +116,9 @@ public class UserManager
execute(user, config.mediumEvent()); execute(user, config.mediumEvent());
} }
public void alertHigh(User user, CheckType type) public void alertHigh(User user, CheckType type) {
{
List<String> messageArray = lang.getHighAlert(); List<String> messageArray = lang.getHighAlert();
for(int i=0;i<messageArray.size();i++) for (int i = 0; i < messageArray.size(); i++) {
{
String message = messageArray.get(i); String message = messageArray.get(i);
message = message.replaceAll("&player", GOLD + user.getName() + GRAY); message = message.replaceAll("&player", GOLD + user.getName() + GRAY);
message = message.replaceAll("&check", GOLD + CheckType.getName(type) + GRAY); message = message.replaceAll("&check", GOLD + CheckType.getName(type) + GRAY);
@@ -159,38 +129,27 @@ public class UserManager
execute(user, config.highEvent()); execute(user, config.highEvent());
} }
public void execute(User user, String event) public void execute(User user, String event) {
{
final String name = user.getName(); final String name = user.getName();
if (event.startsWith("COMMAND[")) if (event.startsWith("COMMAND[")) {
{
String command = event.replaceAll("COMMAND\\[", "").replaceAll("]", "").replaceAll("&player", name).replaceAll("&world", user.getPlayer().getWorld().getName()); String command = event.replaceAll("COMMAND\\[", "").replaceAll("]", "").replaceAll("&player", name).replaceAll("&world", user.getPlayer().getWorld().getName());
Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), command); Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), command);
} } else if (event.equalsIgnoreCase("KICK")) {
else if (event.equalsIgnoreCase("KICK"))
{
user.getPlayer().kickPlayer(RED + lang.getKickReason()); user.getPlayer().kickPlayer(RED + lang.getKickReason());
String msg = RED + lang.getKickBroadcast().replaceAll("&player", name); String msg = RED + lang.getKickBroadcast().replaceAll("&player", name);
if(!msg.equals("")) if (!msg.equals("")) {
{
Bukkit.broadcastMessage(msg); Bukkit.broadcastMessage(msg);
} }
} } else if (event.equalsIgnoreCase("WARN")) {
else if (event.equalsIgnoreCase("WARN"))
{
List<String> message = lang.getWarning(); List<String> message = lang.getWarning();
for (String string : message) for (String string : message) {
{
user.getPlayer().sendMessage(RED + string); user.getPlayer().sendMessage(RED + string);
} }
} } else if (event.equalsIgnoreCase("BAN")) {
else if (event.equalsIgnoreCase("BAN"))
{
user.getPlayer().setBanned(true); user.getPlayer().setBanned(true);
user.getPlayer().kickPlayer(RED + lang.getBanReason()); user.getPlayer().kickPlayer(RED + lang.getBanReason());
String msg = RED + lang.getBanBroadcast().replaceAll("&player", name); String msg = RED + lang.getBanBroadcast().replaceAll("&player", name);
if(!msg.equals("")) if (!msg.equals("")) {
{
Bukkit.broadcastMessage(msg); Bukkit.broadcastMessage(msg);
} }
} }
@@ -41,8 +41,7 @@ import org.bukkit.plugin.PluginDescriptionFile;
/** /**
* <p> * <p>
* The metrics class obtains data about a plugin and submits statistics about it * The metrics class obtains data about a plugin and submits statistics about it to the metrics backend.
* to the metrics backend.
* </p> * </p>
* <p> * <p>
* Public methods provided by this class: * Public methods provided by this class:
@@ -53,8 +52,7 @@ import org.bukkit.plugin.PluginDescriptionFile;
* void start(); <br/> * void start(); <br/>
* </code> * </code>
*/ */
public class Metrics public class Metrics {
{
/** /**
* The current revision number * The current revision number
@@ -77,8 +75,7 @@ public class Metrics
private static final String CONFIG_FILE = "plugins/PluginMetrics/config.yml"; private static final String CONFIG_FILE = "plugins/PluginMetrics/config.yml";
/** /**
* The separator to use for custom data. This MUST NOT change unless you are * The separator to use for custom data. This MUST NOT change unless you are hosting your own version of metrics and want to change it.
* hosting your own version of metrics and want to change it.
*/ */
private static final String CUSTOM_DATA_SEPARATOR = "~~"; private static final String CUSTOM_DATA_SEPARATOR = "~~";
@@ -98,8 +95,7 @@ public class Metrics
private final Set<Graph> graphs = Collections.synchronizedSet(new HashSet<Graph>()); private final Set<Graph> graphs = Collections.synchronizedSet(new HashSet<Graph>());
/** /**
* The default graph, used for addCustomData when you don't want a specific * The default graph, used for addCustomData when you don't want a specific graph
* graph
*/ */
private final Graph defaultGraph = new Graph("Default"); private final Graph defaultGraph = new Graph("Default");
@@ -113,12 +109,8 @@ public class Metrics
*/ */
private final String guid; private final String guid;
public Metrics(Plugin plugin) throws IOException public Metrics(Plugin plugin) throws IOException {
{ if (plugin == null) { throw new IllegalArgumentException("Plugin cannot be null"); }
if (plugin == null)
{
throw new IllegalArgumentException("Plugin cannot be null");
}
this.plugin = plugin; this.plugin = plugin;
@@ -131,8 +123,7 @@ public class Metrics
configuration.addDefault("guid", UUID.randomUUID().toString()); configuration.addDefault("guid", UUID.randomUUID().toString());
// Do we need to create the file? // Do we need to create the file?
if (configuration.get("guid", null) == null) if (configuration.get("guid", null) == null) {
{
configuration.options().header("http://metrics.griefcraft.com").copyDefaults(true); configuration.options().header("http://metrics.griefcraft.com").copyDefaults(true);
configuration.save(file); configuration.save(file);
} }
@@ -142,20 +133,13 @@ public class Metrics
} }
/** /**
* Construct and create a Graph that can be used to separate specific * Construct and create a Graph that can be used to separate specific plotters to their own graphs on the metrics website. Plotters can be added to the graph object returned.
* plotters to their own graphs on the metrics website. Plotters can be
* added to the graph object returned.
* *
* @param name * @param name
* @return Graph object created. Will never return NULL under normal * @return Graph object created. Will never return NULL under normal circumstances unless bad parameters are given
* circumstances unless bad parameters are given
*/ */
public Graph createGraph(String name) public Graph createGraph(String name) {
{ if (name == null) { throw new IllegalArgumentException("Graph name cannot be null"); }
if (name == null)
{
throw new IllegalArgumentException("Graph name cannot be null");
}
// Construct the graph object // Construct the graph object
Graph graph = new Graph(name); Graph graph = new Graph(name);
@@ -172,12 +156,8 @@ public class Metrics
* *
* @param plotter * @param plotter
*/ */
public void addCustomData(Plotter plotter) public void addCustomData(Plotter plotter) {
{ if (plotter == null) { throw new IllegalArgumentException("Plotter cannot be null"); }
if (plotter == null)
{
throw new IllegalArgumentException("Plotter cannot be null");
}
// Add the plotter to the graph o/ // Add the plotter to the graph o/
defaultGraph.addPlotter(plotter); defaultGraph.addPlotter(plotter);
@@ -187,29 +167,19 @@ public class Metrics
} }
/** /**
* Start measuring statistics. This will immediately create an async * Start measuring statistics. This will immediately create an async repeating task as the plugin and send the initial data to the metrics backend, and then after that it will post in increments of PING_INTERVAL * 1200 ticks.
* repeating task as the plugin and send the initial data to the metrics
* backend, and then after that it will post in increments of PING_INTERVAL
* * 1200 ticks.
*/ */
public void start() public void start() {
{
// Did we opt out? // Did we opt out?
if (configuration.getBoolean("opt-out", false)) if (configuration.getBoolean("opt-out", false)) { return; }
{
return;
}
// Begin hitting the server with glorious data // Begin hitting the server with glorious data
plugin.getServer().getScheduler().scheduleAsyncRepeatingTask(plugin, new Runnable() plugin.getServer().getScheduler().scheduleAsyncRepeatingTask(plugin, new Runnable() {
{
private boolean firstPost = true; private boolean firstPost = true;
@Override @Override
public void run() public void run() {
{ try {
try
{
// We use the inverse of firstPost because if it is the first time we are posting, // We use the inverse of firstPost because if it is the first time we are posting,
// it is not a interval ping, so it evaluates to FALSE // it is not a interval ping, so it evaluates to FALSE
// Each time thereafter it will evaluate to TRUE, i.e PING! // Each time thereafter it will evaluate to TRUE, i.e PING!
@@ -218,9 +188,7 @@ public class Metrics
// After the first post we set firstPost to false // After the first post we set firstPost to false
// Each post thereafter will be a ping // Each post thereafter will be a ping
firstPost = false; firstPost = false;
} } catch (IOException e) {
catch (IOException e)
{
System.err.println("[Metrics] " + e.getMessage()); System.err.println("[Metrics] " + e.getMessage());
} }
} }
@@ -230,8 +198,7 @@ public class Metrics
/** /**
* Generic method that posts a plugin to the metrics website * Generic method that posts a plugin to the metrics website
*/ */
private void postPlugin(boolean isPing) throws IOException private void postPlugin(boolean isPing) throws IOException {
{
// The plugin's description file containg all of the plugin data such as name, version, author, etc // The plugin's description file containg all of the plugin data such as name, version, author, etc
PluginDescriptionFile description = plugin.getDescription(); PluginDescriptionFile description = plugin.getDescription();
@@ -239,27 +206,23 @@ public class Metrics
String data = encode("guid") + '=' + encode(guid) + encodeDataPair("version", description.getVersion().split("-b")[0]) + encodeDataPair("server", Bukkit.getVersion()) + encodeDataPair("players", Integer.toString(Bukkit.getServer().getOnlinePlayers().length)) + encodeDataPair("revision", String.valueOf(REVISION)); String data = encode("guid") + '=' + encode(guid) + encodeDataPair("version", description.getVersion().split("-b")[0]) + encodeDataPair("server", Bukkit.getVersion()) + encodeDataPair("players", Integer.toString(Bukkit.getServer().getOnlinePlayers().length)) + encodeDataPair("revision", String.valueOf(REVISION));
// If we're pinging, append it // If we're pinging, append it
if (isPing) if (isPing) {
{
data += encodeDataPair("ping", "true"); data += encodeDataPair("ping", "true");
} }
// Acquire a lock on the graphs, which lets us make the assumption we also lock everything // Acquire a lock on the graphs, which lets us make the assumption we also lock everything
// inside of the graph (e.g plotters) // inside of the graph (e.g plotters)
synchronized (graphs) synchronized (graphs) {
{
Iterator<Graph> iter = graphs.iterator(); Iterator<Graph> iter = graphs.iterator();
while (iter.hasNext()) while (iter.hasNext()) {
{
Graph graph = iter.next(); Graph graph = iter.next();
// Because we have a lock on the graphs set already, it is reasonable to assume // Because we have a lock on the graphs set already, it is reasonable to assume
// that our lock transcends down to the individual plotters in the graphs also. // that our lock transcends down to the individual plotters in the graphs also.
// Because our methods are private, no one but us can reasonably access this list // Because our methods are private, no one but us can reasonably access this list
// without reflection so this is a safe assumption without adding more code. // without reflection so this is a safe assumption without adding more code.
for (Plotter plotter : graph.getPlotters()) for (Plotter plotter : graph.getPlotters()) {
{
// The key name to send to the metrics server // The key name to send to the metrics server
// The format is C-GRAPHNAME-PLOTTERNAME where separator - is defined at the top // The format is C-GRAPHNAME-PLOTTERNAME where separator - is defined at the top
// Legacy (R4) submitters use the format Custom%s, or CustomPLOTTERNAME // Legacy (R4) submitters use the format Custom%s, or CustomPLOTTERNAME
@@ -283,12 +246,9 @@ public class Metrics
// Mineshafter creates a socks proxy, so we can safely bypass it // Mineshafter creates a socks proxy, so we can safely bypass it
// It does not reroute POST requests so we need to go around it // It does not reroute POST requests so we need to go around it
if (isMineshafterPresent()) if (isMineshafterPresent()) {
{
connection = url.openConnection(Proxy.NO_PROXY); connection = url.openConnection(Proxy.NO_PROXY);
} } else {
else
{
connection = url.openConnection(); connection = url.openConnection();
} }
@@ -307,57 +267,44 @@ public class Metrics
writer.close(); writer.close();
reader.close(); reader.close();
if (response.startsWith("ERR")) if (response.startsWith("ERR")) {
{ throw new IOException(response); // Throw the exception
throw new IOException(response); //Throw the exception } else {
}
else
{
// Is this the first update this hour? // Is this the first update this hour?
if (response.contains("OK This is your first update this hour")) if (response.contains("OK This is your first update this hour")) {
{ synchronized (graphs) {
synchronized (graphs)
{
Iterator<Graph> iter = graphs.iterator(); Iterator<Graph> iter = graphs.iterator();
while (iter.hasNext()) while (iter.hasNext()) {
{
Graph graph = iter.next(); Graph graph = iter.next();
for (Plotter plotter : graph.getPlotters()) for (Plotter plotter : graph.getPlotters()) {
{
plotter.reset(); plotter.reset();
} }
} }
} }
} }
} }
//if (response.startsWith("OK")) - We should get "OK" followed by an optional description if everything goes right // if (response.startsWith("OK")) - We should get "OK" followed by an optional description if everything goes right
} }
/** /**
* Check if mineshafter is present. If it is, we need to bypass it to send * Check if mineshafter is present. If it is, we need to bypass it to send POST requests
* POST requests
* *
* @return * @return
*/ */
private boolean isMineshafterPresent() private boolean isMineshafterPresent() {
{ try {
try
{
Class.forName("mineshafter.MineServer"); Class.forName("mineshafter.MineServer");
return true; return true;
} } catch (Exception e) {
catch (Exception e)
{
return false; return false;
} }
} }
/** /**
* <p> * <p>
* Encode a key/value data pair to be used in a HTTP post request. This * Encode a key/value data pair to be used in a HTTP post request. This INCLUDES a & so the first key/value pair MUST be included manually, e.g:
* INCLUDES a & so the first key/value pair MUST be included manually, e.g:
* </p> * </p>
* <code> * <code>
* String httpData = encode("guid") + '=' + encode("1234") + encodeDataPair("authors") + ".."; * String httpData = encode("guid") + '=' + encode("1234") + encodeDataPair("authors") + "..";
@@ -367,8 +314,7 @@ public class Metrics
* @param value * @param value
* @return * @return
*/ */
private static String encodeDataPair(String key, String value) throws UnsupportedEncodingException private static String encodeDataPair(String key, String value) throws UnsupportedEncodingException {
{
return '&' + encode(key) + '=' + encode(value); return '&' + encode(key) + '=' + encode(value);
} }
@@ -378,20 +324,17 @@ public class Metrics
* @param text * @param text
* @return * @return
*/ */
private static String encode(String text) throws UnsupportedEncodingException private static String encode(String text) throws UnsupportedEncodingException {
{
return URLEncoder.encode(text, "UTF-8"); return URLEncoder.encode(text, "UTF-8");
} }
/** /**
* Represents a custom graph on the website * Represents a custom graph on the website
*/ */
public static class Graph public static class Graph {
{
/** /**
* The graph's name, alphanumeric and spaces only :) If it does not * The graph's name, alphanumeric and spaces only :) If it does not comply to the above when submitted, it is rejected
* comply to the above when submitted, it is rejected
*/ */
private final String name; private final String name;
@@ -400,8 +343,7 @@ public class Metrics
*/ */
private final Set<Plotter> plotters = new LinkedHashSet<Plotter>(); private final Set<Plotter> plotters = new LinkedHashSet<Plotter>();
private Graph(String name) private Graph(String name) {
{
this.name = name; this.name = name;
} }
@@ -410,8 +352,7 @@ public class Metrics
* *
* @return * @return
*/ */
public String getName() public String getName() {
{
return name; return name;
} }
@@ -420,8 +361,7 @@ public class Metrics
* *
* @param plotter * @param plotter
*/ */
public void addPlotter(Plotter plotter) public void addPlotter(Plotter plotter) {
{
plotters.add(plotter); plotters.add(plotter);
} }
@@ -430,8 +370,7 @@ public class Metrics
* *
* @param plotter * @param plotter
*/ */
public void removePlotter(Plotter plotter) public void removePlotter(Plotter plotter) {
{
plotters.remove(plotter); plotters.remove(plotter);
} }
@@ -440,24 +379,18 @@ public class Metrics
* *
* @return * @return
*/ */
public Set<Plotter> getPlotters() public Set<Plotter> getPlotters() {
{
return Collections.unmodifiableSet(plotters); return Collections.unmodifiableSet(plotters);
} }
@Override @Override
public int hashCode() public int hashCode() {
{
return name.hashCode(); return name.hashCode();
} }
@Override @Override
public boolean equals(Object object) public boolean equals(Object object) {
{ if (!(object instanceof Graph)) { return false; }
if (!(object instanceof Graph))
{
return false;
}
Graph graph = (Graph) object; Graph graph = (Graph) object;
return graph.name.equals(name); return graph.name.equals(name);
@@ -468,8 +401,7 @@ public class Metrics
/** /**
* Interface used to collect custom data for a plugin * Interface used to collect custom data for a plugin
*/ */
public static abstract class Plotter public static abstract class Plotter {
{
/** /**
* The plot's name * The plot's name
@@ -479,8 +411,7 @@ public class Metrics
/** /**
* Construct a plotter with the default plot name * Construct a plotter with the default plot name
*/ */
public Plotter() public Plotter() {
{
this("Default"); this("Default");
} }
@@ -489,8 +420,7 @@ public class Metrics
* *
* @param name * @param name
*/ */
public Plotter(String name) public Plotter(String name) {
{
this.name = name; this.name = name;
} }
@@ -506,31 +436,24 @@ public class Metrics
* *
* @return the plotted point's column name * @return the plotted point's column name
*/ */
public String getColumnName() public String getColumnName() {
{
return name; return name;
} }
/** /**
* Called after the website graphs have been updated * Called after the website graphs have been updated
*/ */
public void reset() public void reset() {
{
} }
@Override @Override
public int hashCode() public int hashCode() {
{
return getColumnName().hashCode() + getValue(); return getColumnName().hashCode() + getValue();
} }
@Override @Override
public boolean equals(Object object) public boolean equals(Object object) {
{ if (!(object instanceof Plotter)) { return false; }
if (!(object instanceof Plotter))
{
return false;
}
Plotter plotter = (Plotter) object; Plotter plotter = (Plotter) object;
return plotter.name.equals(name) && plotter.getValue() == getValue(); return plotter.name.equals(name) && plotter.getValue() == getValue();
@@ -35,29 +35,19 @@ import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.Plugin; import org.bukkit.plugin.Plugin;
/** /**
* Check dev.bukkit.org to find updates for a given plugin, and download the * Check dev.bukkit.org to find updates for a given plugin, and download the updates if needed.
* updates if needed.
* <p> * <p>
* <strong>VERY, VERY IMPORTANT</strong>: Because there are no standards for * <strong>VERY, VERY IMPORTANT</strong>: Because there are no standards for adding auto-update toggles in your plugin's config, this system provides NO CHECK WITH YOUR CONFIG to make sure the user has allowed auto-updating. <br>
* adding auto-update toggles in your plugin's config, this system provides NO * It is a <strong>BUKKIT POLICY</strong> that you include a boolean value in your config that prevents the auto-updater from running <strong>AT ALL</strong>. <br>
* CHECK WITH YOUR CONFIG to make sure the user has allowed auto-updating. <br> * If you fail to include this option in your config, your plugin will be <strong>REJECTED</strong> when you attempt to submit it to dev.bukkit.org.
* It is a <strong>BUKKIT POLICY</strong> that you include a boolean value in
* your config that prevents the auto-updater from running <strong>AT
* ALL</strong>. <br>
* If you fail to include this option in your config, your plugin will be
* <strong>REJECTED</strong> when you attempt to submit it to dev.bukkit.org.
* <p> * <p>
* An example of a good configuration option would be something similar to * An example of a good configuration option would be something similar to 'auto-update: true' - if this value is set to false you may NOT run the auto-updater. <br>
* 'auto-update: true' - if this value is set to false you may NOT run the * If you are unsure about these rules, please read the plugin submission guidelines: http://goo.gl/8iU5l
* auto-updater. <br>
* If you are unsure about these rules, please read the plugin submission
* guidelines: http://goo.gl/8iU5l
* *
* @author H31IX * @author H31IX
*/ */
public class Updater public class Updater {
{
private Plugin plugin; private Plugin plugin;
private UpdateType type; private UpdateType type;
private String versionTitle; private String versionTitle;
@@ -80,14 +70,11 @@ public class Updater
private static final String ITEM = "item"; private static final String ITEM = "item";
/** /**
* Gives the dev the result of the update process. Can be obtained by called * Gives the dev the result of the update process. Can be obtained by called getResult().
* getResult().
*/ */
public enum UpdateResult public enum UpdateResult {
{
/** /**
* The updater found an update, and has readied it to be loaded the next * The updater found an update, and has readied it to be loaded the next time the server restarts/reloads.
* time the server restarts/reloads.
*/ */
SUCCESS(1), SUCCESS(1),
/** /**
@@ -99,23 +86,19 @@ public class Updater
*/ */
FAIL_DOWNLOAD(3), FAIL_DOWNLOAD(3),
/** /**
* For some reason, the updater was unable to contact dev.bukkit.org to * For some reason, the updater was unable to contact dev.bukkit.org to download the file.
* download the file.
*/ */
FAIL_DBO(4), FAIL_DBO(4),
/** /**
* When running the version check, the file on DBO did not contain the a * When running the version check, the file on DBO did not contain the a version in the format 'vVersion' such as 'v1.0'.
* version in the format 'vVersion' such as 'v1.0'.
*/ */
FAIL_NOVERSION(5), FAIL_NOVERSION(5),
/** /**
* The slug provided by the plugin running the updater was invalid and * The slug provided by the plugin running the updater was invalid and doesn't exist on DBO.
* doesn't exist on DBO.
*/ */
FAIL_BADSLUG(6), FAIL_BADSLUG(6),
/** /**
* The updater found an update, but because of the UpdateType being set * The updater found an update, but because of the UpdateType being set to NO_DOWNLOAD, it wasn't downloaded.
* to NO_DOWNLOAD, it wasn't downloaded.
*/ */
UPDATE_AVAILABLE(7), UPDATE_AVAILABLE(7),
/** /**
@@ -126,25 +109,20 @@ public class Updater
private static final Map<Integer, Updater.UpdateResult> valueList = new HashMap<Integer, Updater.UpdateResult>(); private static final Map<Integer, Updater.UpdateResult> valueList = new HashMap<Integer, Updater.UpdateResult>();
private final int value; private final int value;
private UpdateResult(int value) private UpdateResult(int value) {
{
this.value = value; this.value = value;
} }
public int getValue() public int getValue() {
{
return this.value; return this.value;
} }
public static Updater.UpdateResult getResult(int value) public static Updater.UpdateResult getResult(int value) {
{
return valueList.get(value); return valueList.get(value);
} }
static static {
{ for (Updater.UpdateResult result : Updater.UpdateResult.values()) {
for (Updater.UpdateResult result : Updater.UpdateResult.values())
{
valueList.put(result.value, result); valueList.put(result.value, result);
} }
} }
@@ -153,46 +131,37 @@ public class Updater
/** /**
* Allows the dev to specify the type of update that will be run. * Allows the dev to specify the type of update that will be run.
*/ */
public enum UpdateType public enum UpdateType {
{
/** /**
* Run a version check, and then if the file is out of date, download * Run a version check, and then if the file is out of date, download the newest version.
* the newest version.
*/ */
DEFAULT(1), DEFAULT(1),
/** /**
* Don't run a version check, just find the latest update and download * Don't run a version check, just find the latest update and download it.
* it.
*/ */
NO_VERSION_CHECK(2), NO_VERSION_CHECK(2),
/** /**
* Get information about the version and the download size, but don't * Get information about the version and the download size, but don't actually download anything.
* actually download anything.
*/ */
NO_DOWNLOAD(3); NO_DOWNLOAD(3);
private static final Map<Integer, Updater.UpdateType> valueList = new HashMap<Integer, Updater.UpdateType>(); private static final Map<Integer, Updater.UpdateType> valueList = new HashMap<Integer, Updater.UpdateType>();
private final int value; private final int value;
private UpdateType(int value) private UpdateType(int value) {
{
this.value = value; this.value = value;
} }
public int getValue() public int getValue() {
{
return this.value; return this.value;
} }
public static Updater.UpdateType getResult(int value) public static Updater.UpdateType getResult(int value) {
{
return valueList.get(value); return valueList.get(value);
} }
static static {
{ for (Updater.UpdateType result : Updater.UpdateType.values()) {
for (Updater.UpdateType result : Updater.UpdateType.values())
{
valueList.put(result.value, result); valueList.put(result.value, result);
} }
} }
@@ -201,67 +170,45 @@ public class Updater
/** /**
* Initialize the updater * Initialize the updater
* *
* @param plugin * @param plugin The plugin that is checking for an update.
* The plugin that is checking for an update. * @param slug The dev.bukkit.org slug of the project (http://dev.bukkit.org/server-mods/SLUG_IS_HERE)
* @param slug * @param file The file that the plugin is running from, get this by doing this.getFile() from within your main class.
* The dev.bukkit.org slug of the project * @param type Specify the type of update this will be. See {@link UpdateType}
* (http://dev.bukkit.org/server-mods/SLUG_IS_HERE) * @param announce True if the program should announce the progress of new updates in console
* @param file
* The file that the plugin is running from, get this by doing
* this.getFile() from within your main class.
* @param type
* Specify the type of update this will be. See
* {@link UpdateType}
* @param announce
* True if the program should announce the progress of new
* updates in console
*/ */
public Updater(Plugin plugin, String slug, File file, UpdateType type, boolean announce) public Updater(Plugin plugin, String slug, File file, UpdateType type, boolean announce) {
{
this.plugin = plugin; this.plugin = plugin;
this.type = type; this.type = type;
this.announce = announce; this.announce = announce;
try try {
{
// Obtain the results of the project's file feed // Obtain the results of the project's file feed
url = new URL(DBOUrl + slug + "/files.rss"); url = new URL(DBOUrl + slug + "/files.rss");
if (url != null) if (url != null) {
{
// Obtain the results of the project's file feed // Obtain the results of the project's file feed
readFeed(); readFeed();
if (versionCheck(versionTitle)) if (versionCheck(versionTitle)) {
{
String fileLink = getFile(versionLink); String fileLink = getFile(versionLink);
if (fileLink != null && type != UpdateType.NO_DOWNLOAD) if (fileLink != null && type != UpdateType.NO_DOWNLOAD) {
{
String name = file.getName(); String name = file.getName();
// If it's a zip file, it shouldn't be downloaded as the plugin's name // If it's a zip file, it shouldn't be downloaded as the plugin's name
if (fileLink.endsWith(".zip")) if (fileLink.endsWith(".zip")) {
{
String[] split = fileLink.split("/"); String[] split = fileLink.split("/");
name = split[split.length - 1]; name = split[split.length - 1];
} }
saveFile(new File("plugins/" + updateFolder), name, fileLink); saveFile(new File("plugins/" + updateFolder), name, fileLink);
} } else {
else
{
result = UpdateResult.UPDATE_AVAILABLE; result = UpdateResult.UPDATE_AVAILABLE;
} }
} }
} }
} } catch (MalformedURLException ex) {
catch (MalformedURLException ex)
{
// The slug doesn't exist // The slug doesn't exist
plugin.getLogger().warning("The author of this plugin has misconfigured their Auto Update system"); plugin.getLogger().warning("The author of this plugin has misconfigured their Auto Update system");
plugin.getLogger().warning("The project slug added ('" + slug + "') is invalid, and does not exist on dev.bukkit.org"); plugin.getLogger().warning("The project slug added ('" + slug + "') is invalid, and does not exist on dev.bukkit.org");
result = Updater.UpdateResult.FAIL_BADSLUG; // Bad slug! Bad! result = Updater.UpdateResult.FAIL_BADSLUG; // Bad slug! Bad!
} } catch (RuntimeException ex) {
catch (RuntimeException ex)
{
// Something went wrong with the updater and can't check for updates. // Something went wrong with the updater and can't check for updates.
if (result == Updater.UpdateResult.SUCCESS) if (result == Updater.UpdateResult.SUCCESS) {
{
plugin.getLogger().warning("An error had occured and Auto Update was unable to check for updates"); plugin.getLogger().warning("An error had occured and Auto Update was unable to check for updates");
plugin.getLogger().warning("Here is a stacktrace of what happened: "); plugin.getLogger().warning("Here is a stacktrace of what happened: ");
ex.printStackTrace(); ex.printStackTrace();
@@ -273,41 +220,34 @@ public class Updater
/** /**
* Get the result of the update process. * Get the result of the update process.
*/ */
public Updater.UpdateResult getResult() public Updater.UpdateResult getResult() {
{
return result; return result;
} }
/** /**
* Get the total bytes of the file (can only be used after running a version * Get the total bytes of the file (can only be used after running a version check or a normal run).
* check or a normal run).
*/ */
public long getFileSize() public long getFileSize() {
{
return totalSize; return totalSize;
} }
/** /**
* Get the version string latest file avaliable online. * Get the version string latest file avaliable online.
*/ */
public String getLatestVersionString() public String getLatestVersionString() {
{
return versionTitle; return versionTitle;
} }
/** /**
* Save an update from dev.bukkit.org into the server's update folder. * Save an update from dev.bukkit.org into the server's update folder.
*/ */
private void saveFile(File folder, String file, String u) private void saveFile(File folder, String file, String u) {
{ if (!folder.exists()) {
if (!folder.exists())
{
folder.mkdir(); folder.mkdir();
} }
BufferedInputStream in = null; BufferedInputStream in = null;
FileOutputStream fout = null; FileOutputStream fout = null;
try try {
{
// Download the file // Download the file
URL url = new URL(u); URL url = new URL(u);
int fileLength = url.openConnection().getContentLength(); int fileLength = url.openConnection().getContentLength();
@@ -316,98 +256,73 @@ public class Updater
byte[] data = new byte[BYTE_SIZE]; byte[] data = new byte[BYTE_SIZE];
int count; int count;
if (announce) if (announce) plugin.getLogger().info("About to download a new update: " + versionTitle);
plugin.getLogger().info("About to download a new update: " + versionTitle);
long downloaded = 0; long downloaded = 0;
while ((count = in.read(data, 0, BYTE_SIZE)) != -1) while ((count = in.read(data, 0, BYTE_SIZE)) != -1) {
{
downloaded += count; downloaded += count;
fout.write(data, 0, count); fout.write(data, 0, count);
int percent = (int) (downloaded * 100 / fileLength); int percent = (int) (downloaded * 100 / fileLength);
if (announce & (percent % 10 == 0)) if (announce & (percent % 10 == 0)) {
{
plugin.getLogger().info("Downloading update: " + percent + "% of " + fileLength + " bytes."); plugin.getLogger().info("Downloading update: " + percent + "% of " + fileLength + " bytes.");
} }
} }
//Just a quick check to make sure we didn't leave any files from last time... // Just a quick check to make sure we didn't leave any files from last time...
for (File xFile : new File("plugins/" + updateFolder).listFiles()) for (File xFile : new File("plugins/" + updateFolder).listFiles()) {
{ if (xFile.getName().endsWith(".zip")) {
if (xFile.getName().endsWith(".zip"))
{
xFile.delete(); xFile.delete();
} }
} }
// Check to see if it's a zip file, if it is, unzip it. // Check to see if it's a zip file, if it is, unzip it.
File dFile = new File(folder.getAbsolutePath() + "/" + file); File dFile = new File(folder.getAbsolutePath() + "/" + file);
if (dFile.getName().endsWith(".zip")) if (dFile.getName().endsWith(".zip")) {
{
// Unzip // Unzip
unzip(dFile.getCanonicalPath()); unzip(dFile.getCanonicalPath());
} }
if (announce) if (announce) plugin.getLogger().info("Finished updating.");
plugin.getLogger().info("Finished updating."); } catch (Exception ex) {
}
catch (Exception ex)
{
plugin.getLogger().warning("The auto-updater tried to download a new update, but was unsuccessful."); plugin.getLogger().warning("The auto-updater tried to download a new update, but was unsuccessful.");
result = Updater.UpdateResult.FAIL_DOWNLOAD; result = Updater.UpdateResult.FAIL_DOWNLOAD;
} } finally {
finally try {
{ if (in != null) {
try
{
if (in != null)
{
in.close(); in.close();
} }
if (fout != null) if (fout != null) {
{
fout.close(); fout.close();
} }
} } catch (Exception ex) {}
catch (Exception ex)
{
}
} }
} }
/** /**
* Part of Zip-File-Extractor, modified by H31IX for use with Bukkit * Part of Zip-File-Extractor, modified by H31IX for use with Bukkit
*/ */
private void unzip(String file) private void unzip(String file) {
{ try {
try
{
File fSourceZip = new File(file); File fSourceZip = new File(file);
String zipPath = file.substring(0, file.length() - 4); String zipPath = file.substring(0, file.length() - 4);
ZipFile zipFile = new ZipFile(fSourceZip); ZipFile zipFile = new ZipFile(fSourceZip);
Enumeration e = zipFile.entries(); Enumeration e = zipFile.entries();
while (e.hasMoreElements()) while (e.hasMoreElements()) {
{
ZipEntry entry = (ZipEntry) e.nextElement(); ZipEntry entry = (ZipEntry) e.nextElement();
File destinationFilePath = new File(zipPath, entry.getName()); File destinationFilePath = new File(zipPath, entry.getName());
destinationFilePath.getParentFile().mkdirs(); destinationFilePath.getParentFile().mkdirs();
if (entry.isDirectory()) if (entry.isDirectory()) {
{
continue; continue;
} } else {
else
{
BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry)); BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));
int b; int b;
byte buffer[] = new byte[BYTE_SIZE]; byte buffer[] = new byte[BYTE_SIZE];
FileOutputStream fos = new FileOutputStream(destinationFilePath); FileOutputStream fos = new FileOutputStream(destinationFilePath);
BufferedOutputStream bos = new BufferedOutputStream(fos, BYTE_SIZE); BufferedOutputStream bos = new BufferedOutputStream(fos, BYTE_SIZE);
while ((b = bis.read(buffer, 0, BYTE_SIZE)) != -1) while ((b = bis.read(buffer, 0, BYTE_SIZE)) != -1) {
{
bos.write(buffer, 0, b); bos.write(buffer, 0, b);
} }
bos.flush(); bos.flush();
bos.close(); bos.close();
bis.close(); bis.close();
String name = destinationFilePath.getName(); String name = destinationFilePath.getName();
if (name.endsWith(".jar") && pluginFile(name)) if (name.endsWith(".jar") && pluginFile(name)) {
{
destinationFilePath.renameTo(new File("plugins/" + updateFolder + "/" + name)); destinationFilePath.renameTo(new File("plugins/" + updateFolder + "/" + name));
} }
} }
@@ -418,12 +333,9 @@ public class Updater
zipFile.close(); zipFile.close();
zipFile = null; zipFile = null;
// Move any plugin data folders that were included to the right place, Bukkit won't do this for us. // Move any plugin data folders that were included to the right place, Bukkit won't do this for us.
for (File dFile : new File(zipPath).listFiles()) for (File dFile : new File(zipPath).listFiles()) {
{ if (dFile.isDirectory()) {
if (dFile.isDirectory()) if (pluginFile(dFile.getName())) {
{
if (pluginFile(dFile.getName()))
{
File oFile = new File("plugins/" + dFile.getName()); // Get current dir File oFile = new File("plugins/" + dFile.getName()); // Get current dir
File[] contents = oFile.listFiles(); // List of existing files in the current dir File[] contents = oFile.listFiles(); // List of existing files in the current dir
for (File cFile : dFile.listFiles()) // Loop through all the files in the new dir for (File cFile : dFile.listFiles()) // Loop through all the files in the new dir
@@ -431,19 +343,15 @@ public class Updater
boolean found = false; boolean found = false;
for (File xFile : contents) // Loop through contents to see if it exists for (File xFile : contents) // Loop through contents to see if it exists
{ {
if (xFile.getName().equals(cFile.getName())) if (xFile.getName().equals(cFile.getName())) {
{
found = true; found = true;
break; break;
} }
} }
if (!found) if (!found) {
{
// Move the new file into the current dir // Move the new file into the current dir
cFile.renameTo(new File(oFile.getCanonicalFile() + "/" + cFile.getName())); cFile.renameTo(new File(oFile.getCanonicalFile() + "/" + cFile.getName()));
} } else {
else
{
// This file already exists, so we don't need it anymore. // This file already exists, so we don't need it anymore.
cFile.delete(); cFile.delete();
} }
@@ -454,9 +362,7 @@ public class Updater
} }
new File(zipPath).delete(); new File(zipPath).delete();
fSourceZip.delete(); fSourceZip.delete();
} } catch (IOException ex) {
catch (IOException ex)
{
ex.printStackTrace(); ex.printStackTrace();
plugin.getLogger().warning("The auto-updater tried to unzip a new update file, but was unsuccessful."); plugin.getLogger().warning("The auto-updater tried to unzip a new update file, but was unsuccessful.");
result = Updater.UpdateResult.FAIL_DOWNLOAD; result = Updater.UpdateResult.FAIL_DOWNLOAD;
@@ -465,17 +371,11 @@ public class Updater
} }
/** /**
* Check if the name of a jar is one of the plugins currently installed, * Check if the name of a jar is one of the plugins currently installed, used for extracting the correct files out of a zip.
* used for extracting the correct files out of a zip.
*/ */
public boolean pluginFile(String name) public boolean pluginFile(String name) {
{ for (File file : new File("plugins").listFiles()) {
for (File file : new File("plugins").listFiles()) if (file.getName().equals(name)) { return true; }
{
if (file.getName().equals(name))
{
return true;
}
} }
return false; return false;
} }
@@ -483,11 +383,9 @@ public class Updater
/** /**
* Obtain the direct download file url from the file's page. * Obtain the direct download file url from the file's page.
*/ */
private String getFile(String link) private String getFile(String link) {
{
String download = null; String download = null;
try try {
{
// Open a connection to the page // Open a connection to the page
URL url = new URL(link); URL url = new URL(link);
URLConnection urlConn = url.openConnection(); URLConnection urlConn = url.openConnection();
@@ -496,22 +394,17 @@ public class Updater
int counter = 0; int counter = 0;
String line; String line;
while ((line = buff.readLine()) != null) while ((line = buff.readLine()) != null) {
{
counter++; counter++;
// Search for the download link // Search for the download link
if (line.contains("<li class=\"user-action user-action-download\">")) if (line.contains("<li class=\"user-action user-action-download\">")) {
{
// Get the raw link // Get the raw link
download = line.split("<a href=\"")[1].split("\">Download</a>")[0]; download = line.split("<a href=\"")[1].split("\">Download</a>")[0];
} }
// Search for size // Search for size
else if (line.contains("<dt>Size</dt>")) else if (line.contains("<dt>Size</dt>")) {
{
sizeLine = counter + 1; sizeLine = counter + 1;
} } else if (counter == sizeLine) {
else if (counter == sizeLine)
{
String size = line.replaceAll("<dd>", "").replaceAll("</dd>", ""); String size = line.replaceAll("<dd>", "").replaceAll("</dd>", "");
multiplier = size.contains("MiB") ? 1048576 : 1024; multiplier = size.contains("MiB") ? 1048576 : 1024;
size = size.replace(" KiB", "").replace(" MiB", ""); size = size.replace(" KiB", "").replace(" MiB", "");
@@ -522,9 +415,7 @@ public class Updater
inStream = null; inStream = null;
buff.close(); buff.close();
buff = null; buff = null;
} } catch (Exception ex) {
catch (Exception ex)
{
ex.printStackTrace(); ex.printStackTrace();
plugin.getLogger().warning("The auto-updater tried to contact dev.bukkit.org, but was unsuccessful."); plugin.getLogger().warning("The auto-updater tried to contact dev.bukkit.org, but was unsuccessful.");
result = Updater.UpdateResult.FAIL_DBO; result = Updater.UpdateResult.FAIL_DBO;
@@ -534,26 +425,19 @@ public class Updater
} }
/** /**
* Check to see if the program should continue by evaluation whether the * Check to see if the program should continue by evaluation whether the plugin is already updated, or shouldn't be updated
* plugin is already updated, or shouldn't be updated
*/ */
private boolean versionCheck(String title) private boolean versionCheck(String title) {
{ if (type != UpdateType.NO_VERSION_CHECK) {
if (type != UpdateType.NO_VERSION_CHECK)
{
String version = plugin.getDescription().getVersion(); String version = plugin.getDescription().getVersion();
if (title.split("v").length == 2) if (title.split("v").length == 2) {
{
String remoteVersion = title.split("v")[1].split(" ")[0]; // Get the newest file's version number String remoteVersion = title.split("v")[1].split(" ")[0]; // Get the newest file's version number
if (hasTag(version, remoteVersion) || version.equalsIgnoreCase(remoteVersion)) if (hasTag(version, remoteVersion) || version.equalsIgnoreCase(remoteVersion)) {
{
// We already have the latest version, or this build is tagged for no-update // We already have the latest version, or this build is tagged for no-update
result = Updater.UpdateResult.NO_UPDATE; result = Updater.UpdateResult.NO_UPDATE;
return false; return false;
} }
} } else {
else
{
// The file's name did not contain the string 'vVersion' // The file's name did not contain the string 'vVersion'
plugin.getLogger().warning("The author of this plugin has misconfigured their Auto Update system"); plugin.getLogger().warning("The author of this plugin has misconfigured their Auto Update system");
plugin.getLogger().warning("Files uploaded to BukkitDev should contain the version number, seperated from the name by a 'v', such as PluginName v1.0"); plugin.getLogger().warning("Files uploaded to BukkitDev should contain the version number, seperated from the name by a 'v', such as PluginName v1.0");
@@ -566,22 +450,15 @@ public class Updater
} }
/** /**
* Evaluate whether the version number is marked showing that it should not * Evaluate whether the version number is marked showing that it should not be updated by this program
* be updated by this program
*/ */
private boolean hasTag(String version, String remoteVersion) private boolean hasTag(String version, String remoteVersion) {
{ for (String string : noUpdateTag) {
for (String string : noUpdateTag) if (version.contains(string)) {
{ if (version.replaceAll(string, "").equals(remoteVersion)) {
if (version.contains(string))
{
if (version.replaceAll(string, "").equals(remoteVersion))
{
// The build has a tag, but the version was upgraded to release so we should do an update anyway // The build has a tag, but the version was upgraded to release so we should do an update anyway
return false; return false;
} } else {
else
{
return true; return true;
} }
} }
@@ -593,10 +470,8 @@ public class Updater
* Part of RSS Reader by Vogella, modified by H31IX for use with Bukkit * Part of RSS Reader by Vogella, modified by H31IX for use with Bukkit
*/ */
@SuppressWarnings({ "deprecation", "restriction" }) @SuppressWarnings({ "deprecation", "restriction" })
private void readFeed() private void readFeed() {
{ try {
try
{
// Set header values intial to the empty string // Set header values intial to the empty string
String title = ""; String title = "";
String link = ""; String link = "";
@@ -606,28 +481,21 @@ public class Updater
InputStream in = read(); InputStream in = read();
XMLEventReader eventReader = inputFactory.createXMLEventReader(in); XMLEventReader eventReader = inputFactory.createXMLEventReader(in);
// Read the XML document // Read the XML document
while (eventReader.hasNext()) while (eventReader.hasNext()) {
{
XMLEvent event = eventReader.nextEvent(); XMLEvent event = eventReader.nextEvent();
if (event.isStartElement()) if (event.isStartElement()) {
{ if (event.asStartElement().getName().getLocalPart().equals(TITLE)) {
if (event.asStartElement().getName().getLocalPart().equals(TITLE))
{
event = eventReader.nextEvent(); event = eventReader.nextEvent();
title = event.asCharacters().getData(); title = event.asCharacters().getData();
continue; continue;
} }
if (event.asStartElement().getName().getLocalPart().equals(LINK)) if (event.asStartElement().getName().getLocalPart().equals(LINK)) {
{
event = eventReader.nextEvent(); event = eventReader.nextEvent();
link = event.asCharacters().getData(); link = event.asCharacters().getData();
continue; continue;
} }
} } else if (event.isEndElement()) {
else if (event.isEndElement()) if (event.asEndElement().getName().getLocalPart().equals(ITEM)) {
{
if (event.asEndElement().getName().getLocalPart().equals(ITEM))
{
// Store the title and link of the first entry we get - the first file on the list is all we need // Store the title and link of the first entry we get - the first file on the list is all we need
versionTitle = title; versionTitle = title;
versionLink = link; versionLink = link;
@@ -636,9 +504,7 @@ public class Updater
} }
} }
} }
} } catch (XMLStreamException e) {
catch (XMLStreamException e)
{
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
@@ -646,14 +512,10 @@ public class Updater
/** /**
* Open the RSS feed * Open the RSS feed
*/ */
private InputStream read() private InputStream read() {
{ try {
try
{
return url.openStream(); return url.openStream();
} } catch (IOException e) {
catch (IOException e)
{
e.printStackTrace(); e.printStackTrace();
plugin.getLogger().warning("The auto-updater tried to contact dev.bukkit.org, but was unsuccessful."); plugin.getLogger().warning("The auto-updater tried to contact dev.bukkit.org, but was unsuccessful.");
result = Updater.UpdateResult.FAIL_DBO; result = Updater.UpdateResult.FAIL_DBO;
@@ -2,8 +2,7 @@ package net.h31ix.anticheat.util;
import org.bukkit.Material; import org.bukkit.Material;
public enum BlockHardness public enum BlockHardness {
{
STONE(Material.STONE, 1.50D), STONE(Material.STONE, 1.50D),
GRASS(Material.GRASS, 0.60D), GRASS(Material.GRASS, 0.60D),
DIRT(Material.DIRT, 0.50D), DIRT(Material.DIRT, 0.50D),
@@ -118,18 +117,14 @@ public enum BlockHardness
Material mat; Material mat;
double hardness; double hardness;
BlockHardness(Material m, double hard) BlockHardness(Material m, double hard) {
{
mat = m; mat = m;
hardness = hard; hardness = hard;
} }
public static double getBlockHardness(Material m) public static double getBlockHardness(Material m) {
{ for (BlockHardness e : BlockHardness.values()) {
for (BlockHardness e : BlockHardness.values()) if (e.mat.equals(m)) return e.hardness;
{
if (e.mat.equals(m))
return e.hardness;
} }
return 1.0D; return 1.0D;
@@ -14,17 +14,16 @@ import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
public class Calibrator implements Listener public class Calibrator implements Listener {
{
private final Player player; private final Player player;
private int step = 0; private int step = 0;
private static final int TOTAL = 30; private static final int TOTAL = 30;
private long lastLong; private long lastLong;
private int lastInt; private int lastInt;
private int lastDouble; private int lastDouble;
private long [] longs = new long[10]; private long[] longs = new long[10];
private double [] doubles = new double[10]; private double[] doubles = new double[10];
private int [] ints = new int[10]; private int[] ints = new int[10];
private int times = 0; private int times = 0;
// Value-specific calculations // Value-specific calculations
@@ -34,17 +33,14 @@ public class Calibrator implements Listener
private double blockBreakMax; private double blockBreakMax;
private double blockPlaceMax; private double blockPlaceMax;
public Calibrator(Player player) public Calibrator(Player player) {
{
this.player = player; this.player = player;
player.sendMessage(ChatColor.GREEN+"----You have entered calibration mode.----"); player.sendMessage(ChatColor.GREEN + "----You have entered calibration mode.----");
// Wait for listener to be registered and calibrate method called. // Wait for listener to be registered and calibrate method called.
} }
public void calibrate() public void calibrate() {
{ switch (step) {
switch(step)
{
case 0: case 0:
sendStep(); sendStep();
player.getInventory().setItemInHand(new ItemStack(Material.BOW)); player.getInventory().setItemInHand(new ItemStack(Material.BOW));
@@ -55,59 +51,42 @@ public class Calibrator implements Listener
player.getInventory().clear(); player.getInventory().clear();
player.getInventory().setItemInHand(new ItemStack(Material.DIRT, 64)); player.getInventory().setItemInHand(new ItemStack(Material.DIRT, 64));
player.sendMessage("Drop items as fast as possible."); player.sendMessage("Drop items as fast as possible.");
/*case 0: /*
sendStep(); * case 0: sendStep(); player.sendMessage("Spam the left mouse button as fast as possible."); break; case 2: player.setGameMode(GameMode.CREATIVE); player.sendMessage("Break blocks from as far away as you can possibly get from them."); break; case 3:
player.sendMessage("Spam the left mouse button as fast as possible."); * player.sendMessage("Place blocks from as far away as you can possibly get from them."); break;
break; */
case 2:
player.setGameMode(GameMode.CREATIVE);
player.sendMessage("Break blocks from as far away as you can possibly get from them.");
break;
case 3:
player.sendMessage("Place blocks from as far away as you can possibly get from them.");
break;*/
} }
} }
private int getLongCount() private int getLongCount() {
{
int fill = 0; int fill = 0;
for(long l : longs) for (long l : longs) {
{ if (l != 0) {
if(l != 0)
{
fill++; fill++;
} }
} }
return fill; return fill;
} }
private int getDoubleCount() private int getDoubleCount() {
{
int fill = 0; int fill = 0;
for(double d : doubles) for (double d : doubles) {
{ if (d != 0) {
if(d != 0)
{
fill++; fill++;
} }
} }
return fill; return fill;
} }
private void clear() private void clear() {
{ for (int i = 0; i < longs.length; i++) {
for(int i =0;i<longs.length;i++)
{
longs[i] = 0; longs[i] = 0;
} }
for(int i =0;i<ints.length;i++) for (int i = 0; i < ints.length; i++) {
{
ints[i] = 0; ints[i] = 0;
} }
for(int i =0;i<doubles.length;i++) for (int i = 0; i < doubles.length; i++) {
{
doubles[i] = 0; doubles[i] = 0;
} }
lastInt = 0; lastInt = 0;
@@ -117,38 +96,29 @@ public class Calibrator implements Listener
} }
private void sendStep() private void sendStep() {
{
step++; step++;
player.sendMessage(ChatColor.GREEN+"Step "+step+"/"+TOTAL); player.sendMessage(ChatColor.GREEN + "Step " + step + "/" + TOTAL);
} }
// Find the average time it takes to do a task // Find the average time it takes to do a task
private long getAvgLong() private long getAvgLong() {
{
int count = getLongCount(); int count = getLongCount();
if(count < 10) if (count < 10) {
{ if (lastLong == 0) {
if(lastLong == 0) lastLong = System.currentTimeMillis();
{ } else {
longs[count] = System.currentTimeMillis() - lastLong;
lastLong = System.currentTimeMillis(); lastLong = System.currentTimeMillis();
} }
else } else {
{
longs[count] = System.currentTimeMillis()-lastLong;
lastLong = System.currentTimeMillis();
}
}
else
{
long avg = 0; long avg = 0;
for(long l : longs) for (long l : longs) {
{ avg += l;
avg+=l;
} }
clear(); clear();
avg/=10; avg /= 10;
player.sendMessage(ChatColor.AQUA+"Done. Average calculated at "+ChatColor.WHITE+avg); player.sendMessage(ChatColor.AQUA + "Done. Average calculated at " + ChatColor.WHITE + avg);
sendStep(); sendStep();
calibrate(); calibrate();
return avg; return avg;
@@ -157,25 +127,19 @@ public class Calibrator implements Listener
} }
// Find the maximum time it takes to do a task // Find the maximum time it takes to do a task
private double getMaxDouble(double length) private double getMaxDouble(double length) {
{
int count = getDoubleCount(); int count = getDoubleCount();
if(count < 10) if (count < 10) {
{
doubles[count] = length; doubles[count] = length;
} } else {
else
{
double max = 0; double max = 0;
for(double d : doubles) for (double d : doubles) {
{ if (max == 0 || d > max) {
if(max == 0 || d > max)
{
max = d; max = d;
} }
} }
clear(); clear();
player.sendMessage(ChatColor.AQUA+"Done. Maximum calculated at "+ChatColor.WHITE+max); player.sendMessage(ChatColor.AQUA + "Done. Maximum calculated at " + ChatColor.WHITE + max);
sendStep(); sendStep();
calibrate(); calibrate();
return max; return max;
@@ -184,26 +148,19 @@ public class Calibrator implements Listener
} }
// Get the absolute time it takes to do something X times // Get the absolute time it takes to do something X times
private long getAbsoluteLong() private long getAbsoluteLong() {
{
int count = getLongCount(); int count = getLongCount();
if(count < 10) if (count < 10) {
{ if (lastLong == 0) {
if(lastLong == 0)
{
lastLong = System.currentTimeMillis(); lastLong = System.currentTimeMillis();
} } else {
else
{
longs[count] = System.currentTimeMillis(); longs[count] = System.currentTimeMillis();
lastLong = System.currentTimeMillis(); lastLong = System.currentTimeMillis();
} }
} } else {
else long val = longs[9] - longs[0];
{
long val = longs[9]-longs[0];
clear(); clear();
player.sendMessage(ChatColor.AQUA+"Done. Value calculated at "+ChatColor.WHITE+val); player.sendMessage(ChatColor.AQUA + "Done. Value calculated at " + ChatColor.WHITE + val);
sendStep(); sendStep();
calibrate(); calibrate();
return val; return val;
@@ -212,19 +169,14 @@ public class Calibrator implements Listener
} }
// Begin event listeners // Begin event listeners
@EventHandler @EventHandler
public void onPlayerDropItem(PlayerDropItemEvent event) public void onPlayerDropItem(PlayerDropItemEvent event) {
{ if (event.getPlayer() == player) {
if(event.getPlayer() == player) if (step == 2) {
{
if(step == 2)
{
long v = getAbsoluteLong(); long v = getAbsoluteLong();
if(v != -1) if (v != -1) {
{
dropItemTime = v; dropItemTime = v;
} }
} }
@@ -232,15 +184,11 @@ public class Calibrator implements Listener
} }
@EventHandler @EventHandler
public void onEntityShootBow(EntityShootBowEvent event) public void onEntityShootBow(EntityShootBowEvent event) {
{ if (event.getEntity() instanceof Player && ((Player) event.getEntity()) == player) {
if(event.getEntity() instanceof Player && ((Player)event.getEntity()) == player) if (step == 1) {
{
if(step == 1)
{
long v = getAbsoluteLong(); long v = getAbsoluteLong();
if(v != -1) if (v != -1) {
{
projectileTime = v; projectileTime = v;
} }
} }
@@ -248,37 +196,27 @@ public class Calibrator implements Listener
} }
@EventHandler @EventHandler
public void onPlayerInteract(PlayerInteractEvent event) public void onPlayerInteract(PlayerInteractEvent event) {
{ if (event.getPlayer() == player) {
if(event.getPlayer() == player) if (step == -1) {
{
if(step == -1)
{
long v = getAvgLong(); long v = getAvgLong();
if(v != -1) if (v != -1) {
{
punchAvg = v; punchAvg = v;
} }
} } else if (step == 1) {
else if(step == 1)
{
} }
} }
} }
@EventHandler @EventHandler
public void onBlockBreak(BlockBreakEvent event) public void onBlockBreak(BlockBreakEvent event) {
{ if (event.getPlayer() == player) {
if(event.getPlayer() == player) if (step == -1) {
{ double lengthX = Math.abs(event.getBlock().getX() - event.getPlayer().getLocation().getX());
if(step == -1) double lengthZ = Math.abs(event.getBlock().getZ() - event.getPlayer().getLocation().getZ());
{
double lengthX = Math.abs(event.getBlock().getX()-event.getPlayer().getLocation().getX());
double lengthZ = Math.abs(event.getBlock().getZ()-event.getPlayer().getLocation().getZ());
double v = getMaxDouble(lengthX >= lengthZ ? lengthX : lengthZ); double v = getMaxDouble(lengthX >= lengthZ ? lengthX : lengthZ);
if(v != -1) if (v != -1) {
{
blockBreakMax = v; blockBreakMax = v;
} }
} }
@@ -286,17 +224,13 @@ public class Calibrator implements Listener
} }
@EventHandler @EventHandler
public void onBlockPlace(BlockPlaceEvent event) public void onBlockPlace(BlockPlaceEvent event) {
{ if (event.getPlayer() == player) {
if(event.getPlayer() == player) if (step == -1) {
{ double lengthX = Math.abs(event.getBlock().getX() - event.getPlayer().getLocation().getX());
if(step == -1) double lengthZ = Math.abs(event.getBlock().getZ() - event.getPlayer().getLocation().getZ());
{
double lengthX = Math.abs(event.getBlock().getX()-event.getPlayer().getLocation().getX());
double lengthZ = Math.abs(event.getBlock().getZ()-event.getPlayer().getLocation().getZ());
double v = getMaxDouble(lengthX >= lengthZ ? lengthX : lengthZ); double v = getMaxDouble(lengthX >= lengthZ ? lengthX : lengthZ);
if(v != -1) if (v != -1) {
{
blockPlaceMax = v; blockPlaceMax = v;
} }
} }
@@ -31,8 +31,7 @@ import org.bukkit.World;
import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConfiguration;
public class Configuration public class Configuration {
{
private AnticheatManager micromanage = null; private AnticheatManager micromanage = null;
private File configFile = null; private File configFile = null;
private File levelFile = null; private File levelFile = null;
@@ -62,8 +61,7 @@ public class Configuration
private static Language language; private static Language language;
private List<String> exemptWorlds = new ArrayList<String>(); private List<String> exemptWorlds = new ArrayList<String>();
public Configuration(AnticheatManager instance) public Configuration(AnticheatManager instance) {
{
micromanage = instance; micromanage = instance;
configFile = new File(micromanage.getPlugin().getDataFolder() + "/config.yml"); configFile = new File(micromanage.getPlugin().getDataFolder() + "/config.yml");
levelFile = new File(micromanage.getPlugin().getDataFolder() + "/data/level.yml"); levelFile = new File(micromanage.getPlugin().getDataFolder() + "/data/level.yml");
@@ -72,115 +70,91 @@ public class Configuration
load(); load();
} }
private void save() private void save() {
{ try {
try
{
config.save(configFile); config.save(configFile);
} } catch (IOException ex) {
catch (IOException ex)
{
Logger.getLogger(Configuration.class.getName()).log(Level.SEVERE, null, ex); Logger.getLogger(Configuration.class.getName()).log(Level.SEVERE, null, ex);
} }
} }
public boolean logConsole() public boolean logConsole() {
{
return logConsole; return logConsole;
} }
public boolean logXRay() public boolean logXRay() {
{
return logXRay; return logXRay;
} }
public boolean alertXRay() public boolean alertXRay() {
{
return alertXRay; return alertXRay;
} }
public boolean autoUpdate() public boolean autoUpdate() {
{
return autoUpdate; return autoUpdate;
} }
public boolean verboseStartup() public boolean verboseStartup() {
{
return verboseStartup; return verboseStartup;
} }
public boolean chatSpam() public boolean chatSpam() {
{
return chatSpam; return chatSpam;
} }
public boolean commandSpam() public boolean commandSpam() {
{
return commandSpam; return commandSpam;
} }
public String updateFolder() public String updateFolder() {
{
return updateFolder; return updateFolder;
} }
public boolean silentMode() public boolean silentMode() {
{
return silentMode; return silentMode;
} }
public boolean opExempt() public boolean opExempt() {
{
return opExempt; return opExempt;
} }
public boolean trackCreativeXRay() public boolean trackCreativeXRay() {
{
return trackCreativeXRay; return trackCreativeXRay;
} }
public int medThreshold() public int medThreshold() {
{
return medThreshold; return medThreshold;
} }
public int highThreshold() public int highThreshold() {
{
return highThreshold; return highThreshold;
} }
public String mediumEvent() public String mediumEvent() {
{
return eventMed; return eventMed;
} }
public String highEvent() public String highEvent() {
{
return eventHigh; return eventHigh;
} }
public String chatActionKick() public String chatActionKick() {
{
return chatActionKick; return chatActionKick;
} }
public String chatActionBan() public String chatActionBan() {
{
return chatActionBan; return chatActionBan;
} }
public int getFileLogLevel() public int getFileLogLevel() {
{
return fileLogLevel; return fileLogLevel;
} }
public Language getLang() public Language getLang() {
{
return language; return language;
} }
public final void load() public final void load() {
{
micromanage.getPlugin().checkConfigs(); micromanage.getPlugin().checkConfigs();
config = CommentedConfiguration.loadConfig(configFile); config = CommentedConfiguration.loadConfig(configFile);
level = YamlConfiguration.loadConfiguration(levelFile); level = YamlConfiguration.loadConfiguration(levelFile);
@@ -190,9 +164,9 @@ public class Configuration
// Begin pulling values from config. // Begin pulling values from config.
logConsole = getBoolean("System.Log to console", false); logConsole = getBoolean("System.Log to console", false);
logXRay = getBoolean ("XRay.Log xray stats", true); logXRay = getBoolean("XRay.Log xray stats", true);
autoUpdate = getBoolean ("System.Auto update", true); autoUpdate = getBoolean("System.Auto update", true);
verboseStartup = getBoolean ("System.Verbose startup", false); verboseStartup = getBoolean("System.Verbose startup", false);
alertXRay = getBoolean("XRay.Alert when xray is found", false); alertXRay = getBoolean("XRay.Alert when xray is found", false);
fileLogLevel = getInt("System.File log level", 1); fileLogLevel = getInt("System.File log level", 1);
silentMode = getBoolean("System.Silent mode", false); silentMode = getBoolean("System.Silent mode", false);
@@ -207,12 +181,10 @@ public class Configuration
chatSpam = getBoolean("Chat.Block chat spam", true); chatSpam = getBoolean("Chat.Block chat spam", true);
commandSpam = getBoolean("Chat.Block command spam", false); commandSpam = getBoolean("Chat.Block command spam", false);
// Cleanup old values // Cleanup old values
if(config.getString("System.Block command spam") != null) if (config.getString("System.Block command spam") != null) {
{
config.set("System.Block command spam", null); config.set("System.Block command spam", null);
} }
if(config.getString("System.Block chat spam") != null) if (config.getString("System.Block chat spam") != null) {
{
config.set("System.Block chat spam", null); config.set("System.Block chat spam", null);
} }
@@ -221,25 +193,20 @@ public class Configuration
list.add("example-world"); list.add("example-world");
list.add("example-world-2"); list.add("example-world-2");
if (config.getList("Enable in") != null) if (config.getList("Enable in") != null) {
{
List<String> list2 = config.getStringList("Enable in"); List<String> list2 = config.getStringList("Enable in");
List<String> list3 = new ArrayList<String>(); List<String> list3 = new ArrayList<String>();
for(World world : micromanage.getPlugin().getServer().getWorlds()) for (World world : micromanage.getPlugin().getServer().getWorlds()) {
{ if (!list2.contains(world.getName())) {
if(!list2.contains(world.getName()))
{
list3.add(world.getName()); list3.add(world.getName());
} }
} }
if(!list3.isEmpty()) if (!list3.isEmpty()) {
{
list = list3; list = list3;
} }
config.set("Enable in", null); config.set("Enable in", null);
} }
if (config.getList("Disable in") == null) if (config.getList("Disable in") == null) {
{
config.set("Disable in", list); config.set("Disable in", list);
} }
@@ -248,119 +215,87 @@ public class Configuration
save(); save();
} }
private boolean getBoolean(String entry, boolean d) private boolean getBoolean(String entry, boolean d) {
{ if (config.getString(entry) == null) {
if (config.getString(entry) == null)
{
config.set(entry, d); config.set(entry, d);
return d; return d;
} } else {
else
{
return config.getBoolean(entry); return config.getBoolean(entry);
} }
} }
private int getInt(String entry, int d) private int getInt(String entry, int d) {
{ if (config.getString(entry) == null) {
if (config.getString(entry) == null)
{
config.set(entry, d); config.set(entry, d);
return d; return d;
} } else {
else
{
return config.getInt(entry); return config.getInt(entry);
} }
} }
private String getString(String entry, String d) private String getString(String entry, String d) {
{ if (config.getString(entry) == null) {
if (config.getString(entry) == null)
{
config.set(entry, d); config.set(entry, d);
return d; return d;
} } else {
else
{
return config.getString(entry); return config.getString(entry);
} }
} }
public void setLog(boolean b) public void setLog(boolean b) {
{
config.set("System.Log to console", b); config.set("System.Log to console", b);
this.logConsole = b; this.logConsole = b;
try try {
{
config.save(configFile); config.save(configFile);
} } catch (IOException ex) {
catch (IOException ex)
{
Logger.getLogger(Configuration.class.getName()).log(Level.SEVERE, null, ex); Logger.getLogger(Configuration.class.getName()).log(Level.SEVERE, null, ex);
} }
} }
public List<String> getWorldsExempt() public List<String> getWorldsExempt() {
{
return exemptWorlds; return exemptWorlds;
} }
public File getConfigFile() public File getConfigFile() {
{
return configFile; return configFile;
} }
public File getLevelFile() public File getLevelFile() {
{
return levelFile; return levelFile;
} }
public FileConfiguration getMagic() public FileConfiguration getMagic() {
{
return magic; return magic;
} }
public boolean checkInWorld(World world) public boolean checkInWorld(World world) {
{
return !exemptWorlds.contains(world.getName()); return !exemptWorlds.contains(world.getName());
} }
public int getLevel(String player) public int getLevel(String player) {
{
int x = -1; int x = -1;
if (level.getString(player) != null) if (level.getString(player) != null) {
{
x = level.getInt(player); x = level.getInt(player);
} }
return x; return x;
} }
public void saveLevel(String user, int x) public void saveLevel(String user, int x) {
{
level.set(user, x); level.set(user, x);
} }
public void saveLevels() public void saveLevels() {
{ try {
try
{
level.save(levelFile); level.save(levelFile);
} } catch (IOException ex) {
catch (IOException ex)
{
Logger.getLogger(Configuration.class.getName()).log(Level.SEVERE, null, ex); Logger.getLogger(Configuration.class.getName()).log(Level.SEVERE, null, ex);
} }
} }
public void saveMagic(FileConfiguration newMagic) public void saveMagic(FileConfiguration newMagic) {
{ try {
try
{
newMagic.save(magicFile); newMagic.save(magicFile);
} } catch (IOException ex) {
catch (IOException ex)
{
Logger.getLogger(Configuration.class.getName()).log(Level.SEVERE, null, ex); Logger.getLogger(Configuration.class.getName()).log(Level.SEVERE, null, ex);
} }
} }
@@ -21,12 +21,10 @@ package net.h31ix.anticheat.util;
import java.util.logging.Formatter; import java.util.logging.Formatter;
import java.util.logging.LogRecord; import java.util.logging.LogRecord;
public class ConsoleFormatter extends Formatter public class ConsoleFormatter extends Formatter {
{
@Override @Override
public String format(LogRecord record) public String format(LogRecord record) {
{
StringBuilder output = new StringBuilder().append(record.getMessage()).append(' '); StringBuilder output = new StringBuilder().append(record.getMessage()).append(' ');
return output.toString(); return output.toString();
} }
@@ -20,38 +20,31 @@ package net.h31ix.anticheat.util;
import org.bukkit.Location; import org.bukkit.Location;
public class Distance public class Distance {
{
private final Location l1, l2; private final Location l1, l2;
public Distance(Location from, Location to) public Distance(Location from, Location to) {
{
l1 = to; l1 = to;
l2 = from; l2 = from;
} }
public double fromY() public double fromY() {
{
return l2.getY(); return l2.getY();
} }
public double toY() public double toY() {
{
return l1.getY(); return l1.getY();
} }
public double getXDifference() public double getXDifference() {
{
return Math.abs(l1.getX() - l2.getX()); return Math.abs(l1.getX() - l2.getX());
} }
public double getZDifference() public double getZDifference() {
{
return Math.abs(l1.getZ() - l2.getZ()); return Math.abs(l1.getZ() - l2.getZ());
} }
public double getYDifference() public double getYDifference() {
{
return Math.abs(l1.getY() - l2.getY()); return Math.abs(l1.getY() - l2.getY());
} }
} }
@@ -24,14 +24,12 @@ import java.util.Date;
import java.util.logging.Formatter; import java.util.logging.Formatter;
import java.util.logging.LogRecord; import java.util.logging.LogRecord;
public class FileFormatter extends Formatter public class FileFormatter extends Formatter {
{
private static final DateFormat FORMAT = new SimpleDateFormat("h:mm:ss"); private static final DateFormat FORMAT = new SimpleDateFormat("h:mm:ss");
private static final String LINE_SEP = System.getProperty("line.separator"); private static final String LINE_SEP = System.getProperty("line.separator");
@Override @Override
public String format(LogRecord record) public String format(LogRecord record) {
{
StringBuilder output = new StringBuilder().append("[").append(record.getLevel()).append('|').append(FORMAT.format(new Date(record.getMillis()))).append("]: ").append(record.getMessage()).append(' ').append(LINE_SEP); StringBuilder output = new StringBuilder().append("[").append(record.getLevel()).append('|').append(FORMAT.format(new Date(record.getMillis()))).append("]: ").append(record.getMessage()).append(' ').append(LINE_SEP);
return output.toString(); return output.toString();
} }
@@ -28,8 +28,7 @@ import java.util.logging.Logger;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.FileConfiguration;
public class Language public class Language {
{
private static String[] medAlert = null; private static String[] medAlert = null;
private static String[] highAlert = null; private static String[] highAlert = null;
private static String[] warning = null; private static String[] warning = null;
@@ -47,25 +46,22 @@ public class Language
private static final ChatColor GRAY = ChatColor.GRAY; private static final ChatColor GRAY = ChatColor.GRAY;
private FileConfiguration file; private FileConfiguration file;
public Language(FileConfiguration file, File f) public Language(FileConfiguration file, File f) {
{
this.file = file; this.file = file;
String [] temp = file.getList("alert.medium_alert").toArray(new String[file.getList("alert.medium_alert").size()]); String[] temp = file.getList("alert.medium_alert").toArray(new String[file.getList("alert.medium_alert").size()]);
medAlert = new String [temp.length+2]; medAlert = new String[temp.length + 2];
medAlert[0] = GOLD + "----------------------[" + GRAY + "AntiCheat" + GOLD + "]----------------------"; medAlert[0] = GOLD + "----------------------[" + GRAY + "AntiCheat" + GOLD + "]----------------------";
for(int i=0;i<temp.length;i++) for (int i = 0; i < temp.length; i++) {
{ medAlert[i + 1] = GRAY + temp[i];
medAlert[i+1] = GRAY + temp[i];
} }
medAlert[medAlert.length-1] = GOLD + "-----------------------------------------------------"; medAlert[medAlert.length - 1] = GOLD + "-----------------------------------------------------";
temp = file.getList("alert.high_alert").toArray(new String[file.getList("alert.high_alert").size()]); temp = file.getList("alert.high_alert").toArray(new String[file.getList("alert.high_alert").size()]);
highAlert = new String [temp.length+2]; highAlert = new String[temp.length + 2];
highAlert[0] = GOLD + "----------------------[" + GRAY + "AntiCheat" + GOLD + "]----------------------"; highAlert[0] = GOLD + "----------------------[" + GRAY + "AntiCheat" + GOLD + "]----------------------";
for(int i=0;i<temp.length;i++) for (int i = 0; i < temp.length; i++) {
{ highAlert[i + 1] = GRAY + temp[i];
highAlert[i+1] = GRAY + temp[i];
} }
highAlert[highAlert.length-1] = GOLD + "-----------------------------------------------------"; highAlert[highAlert.length - 1] = GOLD + "-----------------------------------------------------";
warning = file.getList("warning.player_warning").toArray(new String[file.getList("warning.player_warning").size()]); warning = file.getList("warning.player_warning").toArray(new String[file.getList("warning.player_warning").size()]);
banReason = getString("ban.ban_reason", "Banned by AntiCheat"); banReason = getString("ban.ban_reason", "Banned by AntiCheat");
@@ -77,85 +73,66 @@ public class Language
chatBanReason = getString("chat.ban_reason", "Banned for spamming"); chatBanReason = getString("chat.ban_reason", "Banned for spamming");
chatKickBroadcast = getString("chat.kick_broadcast", "[AntiCheat] &player was kicked for spamming"); chatKickBroadcast = getString("chat.kick_broadcast", "[AntiCheat] &player was kicked for spamming");
chatBanBroadcast = getString("chat.ban_broadcast", "[AntiCheat] &player was banned for spamming"); chatBanBroadcast = getString("chat.ban_broadcast", "[AntiCheat] &player was banned for spamming");
try try {
{
file.save(f); file.save(f);
} } catch (IOException ex) {
catch (IOException ex)
{
Logger.getLogger(Language.class.getName()).log(Level.SEVERE, null, ex); Logger.getLogger(Language.class.getName()).log(Level.SEVERE, null, ex);
} }
} }
public List<String> getMediumAlert() public List<String> getMediumAlert() {
{
return new ArrayList<String>(Arrays.asList(medAlert)); return new ArrayList<String>(Arrays.asList(medAlert));
} }
public List<String> getHighAlert() public List<String> getHighAlert() {
{
return new ArrayList<String>(Arrays.asList(highAlert)); return new ArrayList<String>(Arrays.asList(highAlert));
} }
public List<String> getWarning() public List<String> getWarning() {
{
return new ArrayList<String>(Arrays.asList(warning)); return new ArrayList<String>(Arrays.asList(warning));
} }
public String getBanReason() public String getBanReason() {
{
return banReason; return banReason;
} }
public String getBanBroadcast() public String getBanBroadcast() {
{
return banBroadcast; return banBroadcast;
} }
public String getKickReason() public String getKickReason() {
{
return kickReason; return kickReason;
} }
public String getKickBroadcast() public String getKickBroadcast() {
{
return kickBroadcast; return kickBroadcast;
} }
public String getChatKickReason() public String getChatKickReason() {
{
return chatKickReason; return chatKickReason;
} }
public String getChatKickBroadcast() public String getChatKickBroadcast() {
{
return chatKickBroadcast; return chatKickBroadcast;
} }
public String getChatBanReason() public String getChatBanReason() {
{
return chatBanReason; return chatBanReason;
} }
public String getChatBanBroadcast() public String getChatBanBroadcast() {
{
return chatBanBroadcast; return chatBanBroadcast;
} }
public String getChatWarning() public String getChatWarning() {
{
return chatWarning; return chatWarning;
} }
private String getString(String entry, String d) private String getString(String entry, String d) {
{ if (file.getString(entry) == null) {
if (file.getString(entry) == null)
{
file.set(entry, d); file.set(entry, d);
return d; return d;
} } else {
else
{
return file.getString(entry); return file.getString(entry);
} }
} }
@@ -23,27 +23,20 @@ import org.bukkit.configuration.file.FileConfiguration;
/** /**
* Magic number class. Modifications to values in magic.yml will be accepted here. * Magic number class. Modifications to values in magic.yml will be accepted here.
* <p> * <p>
* Note that although each value is documented, changing it may have unintended side-effects. For instance, setting something to 0 that the plugin then uses as a dividend will result in an error. * Note that although each value is documented, changing it may have unintended side-effects. For instance, setting something to 0 that the plugin then uses as a dividend will result in an error. <br>
* <br>
* Also realize that the smaller a value is, the less you should change it; it's probably small for a reason. The larger a value is, the safer it is to probably change it. * Also realize that the smaller a value is, the less you should change it; it's probably small for a reason. The larger a value is, the safer it is to probably change it.
* <p> * <p>
* <b>How to read the value documentation:</b> * <b>How to read the value documentation:</b> <br>
* <br> * First, you will see a description of the value. Then, you will see a type: <br>
* First, you will see a description of the value. Then, you will see a type: * <b>Type SYSTEM:</b> This is a 'long' value, measured in milliseconds, used to compare past and future events with the current system time. Remember, 1000 ms = 1 second. <br>
* <br> * <b>Type INTEGER:</b> This is a regular number. It's typically used as something trivial, such as how many times X event can occur. <br>
* <b>Type SYSTEM:</b> This is a 'long' value, measured in milliseconds, used to compare past and future events with the current system time. Remember, 1000 ms = 1 second.
* <br>
* <b>Type INTEGER:</b> This is a regular number. It's typically used as something trivial, such as how many times X event can occur.
* <br>
* <b>Type DOUBLE:</b> This is a number that has a decimal in it. It's typically used to evaluate speed or distance. * <b>Type DOUBLE:</b> This is a number that has a decimal in it. It's typically used to evaluate speed or distance.
* <p> * <p>
* After the type, you may see a recommendation labeled as '+Leniency'. This means 'In order to add leniency to this value, do X' * After the type, you may see a recommendation labeled as '+Leniency'. This means 'In order to add leniency to this value, do X' <br>
* <br>
* The suggestion for adding leniency will either be to INCREASE or DECREASE the variable. Doing what it suggests will cause the system to not judge the people being checked so vigorously. * The suggestion for adding leniency will either be to INCREASE or DECREASE the variable. Doing what it suggests will cause the system to not judge the people being checked so vigorously.
*/ */
public class Magic public class Magic {
{
/** /**
* Time to exempt a player from moving because of entering/exiting a vehicle; Type=system, +Leniency=Increase. * Time to exempt a player from moving because of entering/exiting a vehicle; Type=system, +Leniency=Increase.
*/ */
@@ -341,8 +334,7 @@ public class Magic
private FileConfiguration magic; private FileConfiguration magic;
private Configuration config; private Configuration config;
public Magic(FileConfiguration magic, Configuration config, FileConfiguration defaults) public Magic(FileConfiguration magic, Configuration config, FileConfiguration defaults) {
{
this.magic = magic; this.magic = magic;
this.config = config; this.config = config;
this.defaults = defaults; this.defaults = defaults;
@@ -424,14 +416,10 @@ public class Magic
TIMER_TIMEMIN = getLong("TIMER_TIMEMIN"); TIMER_TIMEMIN = getLong("TIMER_TIMEMIN");
} }
private int getInt(String path) private int getInt(String path) {
{ if (magic.contains(path)) {
if(magic.contains(path))
{
return magic.getInt(path); return magic.getInt(path);
} } else {
else
{
int i = defaults.getInt(path); int i = defaults.getInt(path);
magic.set(path, i); magic.set(path, i);
config.saveMagic(magic); config.saveMagic(magic);
@@ -439,14 +427,10 @@ public class Magic
} }
} }
private double getDouble(String path) private double getDouble(String path) {
{ if (magic.contains(path)) {
if(magic.contains(path))
{
return magic.getDouble(path); return magic.getDouble(path);
} } else {
else
{
double i = defaults.getDouble(path); double i = defaults.getDouble(path);
magic.set(path, i); magic.set(path, i);
config.saveMagic(magic); config.saveMagic(magic);
@@ -454,14 +438,10 @@ public class Magic
} }
} }
private long getLong(String path) private long getLong(String path) {
{ if (magic.contains(path)) {
if(magic.contains(path))
{
return magic.getLong(path); return magic.getLong(path);
} } else {
else
{
long i = defaults.getLong(path); long i = defaults.getLong(path);
magic.set(path, i); magic.set(path, i);
config.saveMagic(magic); config.saveMagic(magic);
@@ -30,66 +30,49 @@ import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
public class PastebinReport public class PastebinReport {
{
private StringBuilder report = new StringBuilder(); private StringBuilder report = new StringBuilder();
private String url = ""; private String url = "";
private Date date = new Date(); private Date date = new Date();
private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd kk:mm Z"); private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd kk:mm Z");
public PastebinReport(CommandSender cs) public PastebinReport(CommandSender cs) {
{
Player player = null; Player player = null;
try try {
{
player = (Player) cs; player = (Player) cs;
} } catch (Exception e) {
catch (Exception e)
{
cs.sendMessage(ChatColor.RED + "We were unable to detect a player when making this report. Skipping permstester"); cs.sendMessage(ChatColor.RED + "We were unable to detect a player when making this report. Skipping permstester");
} }
createReport(player); createReport(player);
try try {
{
writeReport(); writeReport();
} } catch (IOException e) {}
catch (IOException e)
{
}
postReport(); postReport();
} }
public String getURL() public String getURL() {
{
return url; return url;
} }
private void appendPermissionsTester(Player player) private void appendPermissionsTester(Player player) {
{ if (player == null) { return; }
if (player == null)
{
return;
}
// alrighty then noobs. // alrighty then noobs.
for(Permission node : Permission.values()) for (Permission node : Permission.values()) {
{
report.append(player.getName() + ": " + node.toString() + " " + node.get(player) + '\n'); report.append(player.getName() + ": " + node.toString() + " " + node.get(player) + '\n');
} }
} }
private void createReport(Player player) private void createReport(Player player) {
{
report.append("------------ AntiCheat Report - " + format.format(date) + " ------------" + '\n'); report.append("------------ AntiCheat Report - " + format.format(date) + " ------------" + '\n');
report.append("Version: " + Anticheat.getVersion() + '\n'); report.append("Version: " + Anticheat.getVersion() + '\n');
report.append("CraftBukkit: " + Bukkit.getVersion() + '\n'); report.append("CraftBukkit: " + Bukkit.getVersion() + '\n');
report.append("Plugin Count: " + Bukkit.getPluginManager().getPlugins().length + '\n'); report.append("Plugin Count: " + Bukkit.getPluginManager().getPlugins().length + '\n');
appendSystemInfo(); appendSystemInfo();
report.append("------------Last 30 logs------------" + '\n'); report.append("------------Last 30 logs------------" + '\n');
for (String log : Anticheat.getManager().getLastLogs()) for (String log : Anticheat.getManager().getLastLogs()) {
{
report.append("[AntiCheat] " + log + '\n'); report.append("[AntiCheat] " + log + '\n');
} }
report.append("------------Permission Tester------------" + '\n'); report.append("------------Permission Tester------------" + '\n');
@@ -97,8 +80,7 @@ public class PastebinReport
report.append("-----------End Of Report------------"); report.append("-----------End Of Report------------");
} }
private void appendSystemInfo() private void appendSystemInfo() {
{
Runtime runtime = Runtime.getRuntime(); Runtime runtime = Runtime.getRuntime();
report.append("Java: " + System.getProperty("java.vendor") + " " + System.getProperty("java.version") + '\n'); report.append("Java: " + System.getProperty("java.vendor") + " " + System.getProperty("java.version") + '\n');
report.append("OS: " + System.getProperty("os.name") + " " + System.getProperty("os.version") + '\n'); report.append("OS: " + System.getProperty("os.name") + " " + System.getProperty("os.version") + '\n');
@@ -109,8 +91,7 @@ public class PastebinReport
report.append("Players: " + Bukkit.getOnlinePlayers().length + "/" + Bukkit.getMaxPlayers() + '\n'); report.append("Players: " + Bukkit.getOnlinePlayers().length + "/" + Bukkit.getMaxPlayers() + '\n');
} }
private void writeReport() throws IOException private void writeReport() throws IOException {
{
File f = new File(Anticheat.getPlugin().getDataFolder() + "/report.txt"); File f = new File(Anticheat.getPlugin().getDataFolder() + "/report.txt");
FileWriter r = new FileWriter(f); FileWriter r = new FileWriter(f);
BufferedWriter writer = new BufferedWriter(r); BufferedWriter writer = new BufferedWriter(r);
@@ -118,10 +99,8 @@ public class PastebinReport
writer.close(); writer.close();
} }
private void postReport() private void postReport() {
{ try {
try
{
URL urls = new URL("http://pastebin.com/api/api_post.php"); URL urls = new URL("http://pastebin.com/api/api_post.php");
HttpURLConnection conn = (HttpURLConnection) urls.openConnection(); HttpURLConnection conn = (HttpURLConnection) urls.openConnection();
conn.setConnectTimeout(5000); conn.setConnectTimeout(5000);
@@ -136,14 +115,12 @@ public class PastebinReport
out.flush(); out.flush();
out.close(); out.close();
if (conn.getResponseCode() == 200) if (conn.getResponseCode() == 200) {
{
InputStream receive = conn.getInputStream(); InputStream receive = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(receive)); BufferedReader reader = new BufferedReader(new InputStreamReader(receive));
String line; String line;
StringBuffer response = new StringBuffer(); StringBuffer response = new StringBuffer();
while ((line = reader.readLine()) != null) while ((line = reader.readLine()) != null) {
{
response.append(line); response.append(line);
response.append("\r\n"); response.append("\r\n");
} }
@@ -151,22 +128,15 @@ public class PastebinReport
String result = response.toString().trim(); String result = response.toString().trim();
if (!result.contains("http://")) if (!result.contains("http://")) {
{
url = "Failed to post. Check report.txt"; url = "Failed to post. Check report.txt";
} } else {
else
{
url = result.trim(); url = result.trim();
} }
} } else {
else
{
url = "Failed to post. Check report.txt"; url = "Failed to post. Check report.txt";
} }
} } catch (Exception e) {
catch (Exception e)
{
url = "Failed to post. Check report.txt"; url = "Failed to post. Check report.txt";
} }
} }
@@ -20,8 +20,7 @@ package net.h31ix.anticheat.util;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
public enum Permission public enum Permission {
{
/* Check Nodes */ /* Check Nodes */
CHECK_ZOMBE_FLY, CHECK_ZOMBE_FLY,
CHECK_ZOMBE_NOCLIP, CHECK_ZOMBE_NOCLIP,
@@ -62,14 +61,12 @@ public enum Permission
SYSTEM_CALIBRATE, SYSTEM_CALIBRATE,
SYSTEM_RELOAD; SYSTEM_RELOAD;
public boolean get(CommandSender cs) public boolean get(CommandSender cs) {
{
return cs.hasPermission(toString()); return cs.hasPermission(toString());
} }
@Override @Override
public String toString() public String toString() {
{
return "anticheat." + this.name().toLowerCase().replace("_", "."); return "anticheat." + this.name().toLowerCase().replace("_", ".");
} }
@@ -20,31 +20,26 @@ package net.h31ix.anticheat.util;
import org.bukkit.Location; import org.bukkit.Location;
public class SpyState public class SpyState {
{
private boolean allowFlight; private boolean allowFlight;
private boolean flying; private boolean flying;
private Location location; private Location location;
public SpyState(boolean allowFlight, boolean flying, Location location) public SpyState(boolean allowFlight, boolean flying, Location location) {
{
this.allowFlight = allowFlight; this.allowFlight = allowFlight;
this.flying = flying; this.flying = flying;
this.location = location; this.location = location;
} }
public boolean getAllowFlight() public boolean getAllowFlight() {
{
return this.allowFlight; return this.allowFlight;
} }
public boolean getFlying() public boolean getFlying() {
{
return this.flying; return this.flying;
} }
public Location getLocation() public Location getLocation() {
{
return this.location; return this.location;
} }
} }
@@ -2,10 +2,9 @@ package net.h31ix.anticheat.util;
import org.bukkit.Material; import org.bukkit.Material;
public enum ToolHardness public enum ToolHardness {
{
//NOTHING(null, 1.5) // NOTHING(null, 1.5)
WOOD(0.75D), WOOD(0.75D),
STONE(0.40D), STONE(0.40D),
IRON(0.25D), IRON(0.25D),
@@ -15,19 +14,13 @@ public enum ToolHardness
double hardness; double hardness;
ToolHardness(double hard) ToolHardness(double hard) {
{
hardness = hard; hardness = hard;
} }
public static double getToolHardness(Material tool) public static double getToolHardness(Material tool) {
{ for (ToolHardness e : ToolHardness.values()) {
for (ToolHardness e : ToolHardness.values()) if (tool.name().contains(e.name())) { return e.hardness; }
{
if (tool.name().contains(e.name()))
{
return e.hardness;
}
} }
return 1.50D; return 1.50D;
@@ -31,8 +31,7 @@ import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.util.NumberConversions; import org.bukkit.util.NumberConversions;
public final class Utilities public final class Utilities {
{
private static final List<Material> INSTANT_BREAK = new ArrayList<Material>(); private static final List<Material> INSTANT_BREAK = new ArrayList<Material>();
private static final List<Material> FOOD = new ArrayList<Material>(); private static final List<Material> FOOD = new ArrayList<Material>();
private static final List<Material> INTERACTABLE = new ArrayList<Material>(); private static final List<Material> INTERACTABLE = new ArrayList<Material>();
@@ -42,182 +41,142 @@ public final class Utilities
private static final List<Material> SHOVELS = new ArrayList<Material>(); private static final List<Material> SHOVELS = new ArrayList<Material>();
private static final List<Material> ANY = new ArrayList<Material>(); private static final List<Material> ANY = new ArrayList<Material>();
public static void alert(List<String> message) public static void alert(List<String> message) {
{ for (Player player : Bukkit.getOnlinePlayers()) {
for (Player player : Bukkit.getOnlinePlayers()) if (Permission.SYSTEM_ALERT.get(player)) {
{ for (String msg : message) {
if (Permission.SYSTEM_ALERT.get(player))
{
for (String msg : message)
{
player.sendMessage(msg); player.sendMessage(msg);
} }
} }
} }
if (Anticheat.getManager().getConfiguration().logConsole()) if (Anticheat.getManager().getConfiguration().logConsole()) {
{ for (String msg : message) {
for (String msg : message)
{
Anticheat.getManager().log(msg); Anticheat.getManager().log(msg);
} }
} }
if (Anticheat.getManager().getConfiguration().getFileLogLevel() != 0) if (Anticheat.getManager().getConfiguration().getFileLogLevel() != 0) {
{ for (String msg : message) {
for (String msg : message)
{
Anticheat.getManager().log(msg, 1); Anticheat.getManager().log(msg, 1);
} }
} }
} }
public static boolean cantStandAt(Block block) public static boolean cantStandAt(Block block) {
{
return !canStand(block) && cantStandClose(block) && cantStandFar(block); return !canStand(block) && cantStandClose(block) && cantStandFar(block);
} }
public static boolean cantStandAtExp(Location block) public static boolean cantStandAtExp(Location block) {
{
// This is a experimental check for checking whether you can't stand at or whatever. // This is a experimental check for checking whether you can't stand at or whatever.
Block nblock = new Location(block.getWorld(), fixXAxis(block.getX()), block.getY() - 0.01D, block.getBlockZ()).getBlock(); Block nblock = new Location(block.getWorld(), fixXAxis(block.getX()), block.getY() - 0.01D, block.getBlockZ()).getBlock();
return cantStandAt(nblock); return cantStandAt(nblock);
} }
public static boolean cantStandClose(Block block) public static boolean cantStandClose(Block block) {
{
return !canStand(block.getRelative(BlockFace.NORTH)) && !canStand(block.getRelative(BlockFace.EAST)) && !canStand(block.getRelative(BlockFace.SOUTH)) && !canStand(block.getRelative(BlockFace.WEST)); return !canStand(block.getRelative(BlockFace.NORTH)) && !canStand(block.getRelative(BlockFace.EAST)) && !canStand(block.getRelative(BlockFace.SOUTH)) && !canStand(block.getRelative(BlockFace.WEST));
} }
public static boolean cantStandFar(Block block) public static boolean cantStandFar(Block block) {
{
return !canStand(block.getRelative(BlockFace.NORTH_WEST)) && !canStand(block.getRelative(BlockFace.NORTH_EAST)) && !canStand(block.getRelative(BlockFace.SOUTH_WEST)) && !canStand(block.getRelative(BlockFace.SOUTH_EAST)); return !canStand(block.getRelative(BlockFace.NORTH_WEST)) && !canStand(block.getRelative(BlockFace.NORTH_EAST)) && !canStand(block.getRelative(BlockFace.SOUTH_WEST)) && !canStand(block.getRelative(BlockFace.SOUTH_EAST));
} }
public static boolean canStand(Block block) public static boolean canStand(Block block) {
{
return !(block.isLiquid() || block.getType() == Material.AIR); return !(block.isLiquid() || block.getType() == Material.AIR);
} }
public static boolean isFullyInWater(Location player) public static boolean isFullyInWater(Location player) {
{
double touchedX = fixXAxis(player.getX()); double touchedX = fixXAxis(player.getX());
// Yes, this doesn't make sense, but it's supposed to fix some false positives in water walk. // Yes, this doesn't make sense, but it's supposed to fix some false positives in water walk.
// Think of it as 2 negatives = a positive :) // Think of it as 2 negatives = a positive :)
if(!(new Location(player.getWorld(), touchedX, player.getY(), player.getBlockZ()).getBlock()).isLiquid() && !(new Location(player.getWorld(), touchedX, Math.round(player.getY()), player.getBlockZ()).getBlock()).isLiquid()) if (!(new Location(player.getWorld(), touchedX, player.getY(), player.getBlockZ()).getBlock()).isLiquid() && !(new Location(player.getWorld(), touchedX, Math.round(player.getY()), player.getBlockZ()).getBlock()).isLiquid()) { return true; }
{
return true;
}
return (new Location(player.getWorld(), touchedX, player.getY(), player.getBlockZ()).getBlock()).isLiquid() && (new Location(player.getWorld(), touchedX, Math.round(player.getY()), player.getBlockZ()).getBlock()).isLiquid(); return (new Location(player.getWorld(), touchedX, player.getY(), player.getBlockZ()).getBlock()).isLiquid() && (new Location(player.getWorld(), touchedX, Math.round(player.getY()), player.getBlockZ()).getBlock()).isLiquid();
} }
public static double fixXAxis(double x) public static double fixXAxis(double x) {
{
/* Really really really useful function for those who are on the edges of blocks */ /* Really really really useful function for those who are on the edges of blocks */
/* For Z axis, just use Math.round(xaxis); */ /* For Z axis, just use Math.round(xaxis); */
double touchedX = x; double touchedX = x;
double rem = touchedX - Math.round(touchedX) + 0.01D; double rem = touchedX - Math.round(touchedX) + 0.01D;
if (rem < 0.30D) if (rem < 0.30D) {
{
touchedX = NumberConversions.floor(x) - 1; touchedX = NumberConversions.floor(x) - 1;
} }
return touchedX; return touchedX;
} }
public static boolean isHoveringOverWater(Location player, int blocks) public static boolean isHoveringOverWater(Location player, int blocks) {
{ for (int i = player.getBlockY(); i > player.getBlockY() - blocks; i--) {
for(int i = player.getBlockY(); i > player.getBlockY() - blocks; i--)
{
Block newloc = (new Location(player.getWorld(), player.getBlockX(), i, player.getBlockZ())).getBlock(); Block newloc = (new Location(player.getWorld(), player.getBlockX(), i, player.getBlockZ())).getBlock();
if(newloc.getTypeId() != 0 && newloc.isLiquid()) if (newloc.getTypeId() != 0 && newloc.isLiquid())
return true; return true;
else if (newloc.getTypeId() != 0) else if (newloc.getTypeId() != 0) return false;
return false;
} }
return false; return false;
} }
public static boolean isHoveringOverWater(Location player) public static boolean isHoveringOverWater(Location player) {
{
return isHoveringOverWater(player, 25); return isHoveringOverWater(player, 25);
} }
public static boolean isInstantBreak(Material m) public static boolean isInstantBreak(Material m) {
{
return INSTANT_BREAK.contains(m); return INSTANT_BREAK.contains(m);
} }
public static boolean isFood(Material m) public static boolean isFood(Material m) {
{
return FOOD.contains(m); return FOOD.contains(m);
} }
public static boolean isSlab(Block block) public static boolean isSlab(Block block) {
{
int id = block.getTypeId(); int id = block.getTypeId();
return id == 43 || id == 44 || id == 125 || id == 126; return id == 43 || id == 44 || id == 125 || id == 126;
} }
public static boolean isStair(Block block) public static boolean isStair(Block block) {
{
int id = block.getTypeId(); int id = block.getTypeId();
return id == 53 || id == 67 || id == 108 || id == 109 || id == 114 || id == 128 || id == 134 || id == 135 || id == 136; return id == 53 || id == 67 || id == 108 || id == 109 || id == 114 || id == 128 || id == 134 || id == 135 || id == 136;
} }
public static boolean isInteractable(Material m) public static boolean isInteractable(Material m) {
{
return INTERACTABLE.contains(m); return INTERACTABLE.contains(m);
} }
public static boolean sprintFly(Player player) public static boolean sprintFly(Player player) {
{
return player.isSprinting() || player.isFlying(); return player.isSprinting() || player.isFlying();
} }
public static boolean isOnLilyPad(Player player) public static boolean isOnLilyPad(Player player) {
{
Block block = player.getLocation().getBlock(); Block block = player.getLocation().getBlock();
Material lily = Material.WATER_LILY; Material lily = Material.WATER_LILY;
return block.getType() == lily || block.getRelative(BlockFace.NORTH).getType() == lily || block.getRelative(BlockFace.SOUTH).getType() == lily || block.getRelative(BlockFace.EAST).getType() == lily || block.getRelative(BlockFace.WEST).getType() == lily; return block.getType() == lily || block.getRelative(BlockFace.NORTH).getType() == lily || block.getRelative(BlockFace.SOUTH).getType() == lily || block.getRelative(BlockFace.EAST).getType() == lily || block.getRelative(BlockFace.WEST).getType() == lily;
} }
public static boolean isSubmersed(Player player) public static boolean isSubmersed(Player player) {
{
return player.getLocation().getBlock().isLiquid() && player.getLocation().getBlock().getRelative(BlockFace.UP).isLiquid(); return player.getLocation().getBlock().isLiquid() && player.getLocation().getBlock().getRelative(BlockFace.UP).isLiquid();
} }
public static boolean isInWater(Player player) public static boolean isInWater(Player player) {
{
return player.getLocation().getBlock().isLiquid() || player.getLocation().getBlock().getRelative(BlockFace.DOWN).isLiquid() || player.getLocation().getBlock().getRelative(BlockFace.UP).isLiquid(); return player.getLocation().getBlock().isLiquid() || player.getLocation().getBlock().getRelative(BlockFace.DOWN).isLiquid() || player.getLocation().getBlock().getRelative(BlockFace.UP).isLiquid();
} }
public static boolean isClimbableBlock(Block block) public static boolean isClimbableBlock(Block block) {
{
return block.getType() == Material.VINE || block.getType() == Material.LADDER; return block.getType() == Material.VINE || block.getType() == Material.LADDER;
} }
public static boolean isOnVine(Player player) public static boolean isOnVine(Player player) {
{
return player.getLocation().getBlock().getType() == Material.VINE; return player.getLocation().getBlock().getType() == Material.VINE;
} }
public static boolean isInt(String string) public static boolean isInt(String string) {
{
boolean x = false; boolean x = false;
try try {
{
Integer.parseInt(string); Integer.parseInt(string);
x = true; x = true;
} } catch (Exception ex) {}
catch (Exception ex)
{
}
return x; return x;
} }
public static long calcSurvivalFastBreak(ItemStack tool, Material block) public static long calcSurvivalFastBreak(ItemStack tool, Material block) {
{
double bhardness = BlockHardness.getBlockHardness(block); double bhardness = BlockHardness.getBlockHardness(block);
double thardness = ToolHardness.getToolHardness(tool.getType()); double thardness = ToolHardness.getToolHardness(tool.getType());
@@ -226,14 +185,12 @@ public final class Utilities
if (result > 25000) if (result > 25000)
result = 25000; result = 25000;
else if (result < 0) else if (result < 0) result = 0;
result = 0;
return result; return result;
} }
static static {
{
INSTANT_BREAK.add(Material.RED_MUSHROOM); INSTANT_BREAK.add(Material.RED_MUSHROOM);
INSTANT_BREAK.add(Material.RED_ROSE); INSTANT_BREAK.add(Material.RED_ROSE);
INSTANT_BREAK.add(Material.BROWN_MUSHROOM); INSTANT_BREAK.add(Material.BROWN_MUSHROOM);
@@ -33,8 +33,7 @@ import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.representer.Representer; import org.yaml.snakeyaml.representer.Representer;
public class CommentedConfiguration extends YamlConfiguration public class CommentedConfiguration extends YamlConfiguration {
{
private Map<String, String> comments = new HashMap<String, String>(); private Map<String, String> comments = new HashMap<String, String>();
private final DumperOptions yamlOptions = new DumperOptions(); private final DumperOptions yamlOptions = new DumperOptions();
@@ -42,8 +41,7 @@ public class CommentedConfiguration extends YamlConfiguration
private final Yaml yaml = new Yaml(new YamlConstructor(), yamlRepresenter, yamlOptions); private final Yaml yaml = new Yaml(new YamlConstructor(), yamlRepresenter, yamlOptions);
private String lastLine = null; private String lastLine = null;
public CommentedConfiguration() public CommentedConfiguration() {
{
// Val 1 = line comment should be under // Val 1 = line comment should be under
// Val 2 = comment // Val 2 = comment
comments.put("XRay:", " # Should AntiCheat use calculations to try and find xrayers?"); comments.put("XRay:", " # Should AntiCheat use calculations to try and find xrayers?");
@@ -80,18 +78,18 @@ public class CommentedConfiguration extends YamlConfiguration
dump = ""; dump = "";
} else { } else {
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
String [] lines = dump.split("\n"); String[] lines = dump.split("\n");
int i =0; int i = 0;
while(i < lines.length) { while (i < lines.length) {
if(containsLine(lines[i])) { if (containsLine(lines[i])) {
builder.append(lines[i]); builder.append(lines[i]);
builder.append("\n"); builder.append("\n");
builder.append(getComment(lines[i])); builder.append(getComment(lines[i]));
builder.append("\n"); builder.append("\n");
lastLine = getComment(getComment(lines[i])); lastLine = getComment(getComment(lines[i]));
i++; i++;
} else if(containsLine(lastLine)) { } else if (containsLine(lastLine)) {
builder.append(getComment(lastLine)); builder.append(getComment(lastLine));
builder.append("\n"); builder.append("\n");
lastLine = getComment(lastLine); lastLine = getComment(lastLine);
@@ -101,31 +99,24 @@ public class CommentedConfiguration extends YamlConfiguration
i++; i++;
} }
} }
dump = "# AntiCheat configuration file\n# Please report any bugs: http://dev.bukkit.org/server-mods/anticheat/\n"+builder.toString(); dump = "# AntiCheat configuration file\n# Please report any bugs: http://dev.bukkit.org/server-mods/anticheat/\n" + builder.toString();
} }
return dump; return dump;
} }
private boolean containsLine(String line) private boolean containsLine(String line) {
{ if (line != null) {
if(line != null) for (String string : comments.keySet()) {
{ if (string.replaceAll(" ", "").split(":")[0].equalsIgnoreCase(line.replaceAll(" ", "").split(":")[0])) { return true; }
for(String string : comments.keySet()) {
if(string.replaceAll(" ", "").split(":")[0].equalsIgnoreCase(line.replaceAll(" ", "").split(":")[0])) {
return true;
}
} }
} }
return false; return false;
} }
private String getComment(String line) private String getComment(String line) {
{ for (String string : comments.keySet()) {
for(String string : comments.keySet()) { if (string.replaceAll(" ", "").split(":")[0].equalsIgnoreCase(line.replaceAll(" ", "").split(":")[0])) { return comments.get(string); }
if(string.replaceAll(" ", "").split(":")[0].equalsIgnoreCase(line.replaceAll(" ", "").split(":")[0])) {
return comments.get(string);
}
} }
return null; return null;
} }
@@ -135,11 +126,10 @@ public class CommentedConfiguration extends YamlConfiguration
CommentedConfiguration config = new CommentedConfiguration(); CommentedConfiguration config = new CommentedConfiguration();
try { try {
config.load(file); config.load(file);
} catch (FileNotFoundException ex) { } catch (FileNotFoundException ex) {} catch (IOException ex) {
} catch (IOException ex) {
Bukkit.getLogger().log(Level.SEVERE, "Cannot load " + file, ex); Bukkit.getLogger().log(Level.SEVERE, "Cannot load " + file, ex);
} catch (InvalidConfigurationException ex) { } catch (InvalidConfigurationException ex) {
Bukkit.getLogger().log(Level.SEVERE, "Cannot load " + file , ex); Bukkit.getLogger().log(Level.SEVERE, "Cannot load " + file, ex);
} }
return config; return config;
@@ -29,52 +29,32 @@ import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockBreakEvent;
public class XRayListener implements Listener public class XRayListener implements Listener {
{
private XRayTracker tracker = Anticheat.getManager().getXRayTracker(); private XRayTracker tracker = Anticheat.getManager().getXRayTracker();
private Configuration config = Anticheat.getManager().getConfiguration(); private Configuration config = Anticheat.getManager().getConfiguration();
private CheckManager checkManager = Anticheat.getManager().getCheckManager(); private CheckManager checkManager = Anticheat.getManager().getCheckManager();
@EventHandler @EventHandler
public void onBlockBreak(BlockBreakEvent event) public void onBlockBreak(BlockBreakEvent event) {
{ if (config.logXRay()) {
if (config.logXRay())
{
Player p = event.getPlayer(); Player p = event.getPlayer();
if(p.getGameMode() == GameMode.CREATIVE && !config.trackCreativeXRay()) if (p.getGameMode() == GameMode.CREATIVE && !config.trackCreativeXRay()) { return; }
{
return;
}
String player = p.getName(); String player = p.getName();
if (checkManager.willCheck(p, CheckType.XRAY)) if (checkManager.willCheck(p, CheckType.XRAY)) {
{
Material m = event.getBlock().getType(); Material m = event.getBlock().getType();
if (m == Material.DIAMOND_ORE) if (m == Material.DIAMOND_ORE) {
{
tracker.addDiamond(player); tracker.addDiamond(player);
} } else if (m == Material.IRON_ORE) {
else if (m == Material.IRON_ORE)
{
tracker.addIron(player); tracker.addIron(player);
} } else if (m == Material.GOLD_ORE) {
else if (m == Material.GOLD_ORE)
{
tracker.addGold(player); tracker.addGold(player);
} } else if (m == Material.LAPIS_ORE) {
else if (m == Material.LAPIS_ORE)
{
tracker.addLapis(player); tracker.addLapis(player);
} } else if (m == Material.REDSTONE_ORE) {
else if (m == Material.REDSTONE_ORE)
{
tracker.addRedstone(player); tracker.addRedstone(player);
} } else if (m == Material.GOLD_ORE) {
else if (m == Material.GOLD_ORE)
{
tracker.addGold(player); tracker.addGold(player);
} } else {
else
{
tracker.addBlock(player); tracker.addBlock(player);
} }
tracker.addTotal(player); tracker.addTotal(player);
@@ -20,8 +20,7 @@ package net.h31ix.anticheat.xray;
import java.util.Map; import java.util.Map;
public class XRayStats public class XRayStats {
{
private static final int DIVISOR = 100; private static final int DIVISOR = 100;
private double t = 1; private double t = 1;
private double d = 0; private double d = 0;
@@ -31,70 +30,55 @@ public class XRayStats
private double r = 0; private double r = 0;
private double o = 0; private double o = 0;
public XRayStats(String player, Map<String, Integer> diamond, Map<String, Integer> gold, Map<String, Integer> iron, Map<String, Integer> lapis, Map<String, Integer> redstone, Map<String, Integer> other, Map<String, Integer> total) public XRayStats(String player, Map<String, Integer> diamond, Map<String, Integer> gold, Map<String, Integer> iron, Map<String, Integer> lapis, Map<String, Integer> redstone, Map<String, Integer> other, Map<String, Integer> total) {
{ if (total.get(player) != null) {
if (total.get(player) != null)
{
t = total.get(player); t = total.get(player);
} }
if (diamond.get(player) != null) if (diamond.get(player) != null) {
{
d = (diamond.get(player) / t) * DIVISOR; d = (diamond.get(player) / t) * DIVISOR;
} }
if (gold.get(player) != null) if (gold.get(player) != null) {
{
g = (gold.get(player) / t) * DIVISOR; g = (gold.get(player) / t) * DIVISOR;
} }
if (iron.get(player) != null) if (iron.get(player) != null) {
{
i = (iron.get(player) / t) * DIVISOR; i = (iron.get(player) / t) * DIVISOR;
} }
if (lapis.get(player) != null) if (lapis.get(player) != null) {
{
l = (lapis.get(player) / t) * DIVISOR; l = (lapis.get(player) / t) * DIVISOR;
} }
if (redstone.get(player) != null) if (redstone.get(player) != null) {
{
r = (redstone.get(player) / t) * DIVISOR; r = (redstone.get(player) / t) * DIVISOR;
} }
if (other.get(player) != null) if (other.get(player) != null) {
{
o = (other.get(player) / t) * DIVISOR; o = (other.get(player) / t) * DIVISOR;
} }
} }
public double getTotal() public double getTotal() {
{
return t; return t;
} }
public double getDiamond() public double getDiamond() {
{
return d; return d;
} }
public double getGold() public double getGold() {
{
return g; return g;
} }
public double getIron() public double getIron() {
{
return i; return i;
} }
public double getLapis() public double getLapis() {
{
return l; return l;
} }
public double getRedstone() public double getRedstone() {
{
return r; return r;
} }
public double getOther() public double getOther() {
{
return o; return o;
} }
} }
@@ -25,8 +25,7 @@ import java.util.Map;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
public class XRayTracker public class XRayTracker {
{
private Map<String, Integer> diamond = new HashMap<String, Integer>(); private Map<String, Integer> diamond = new HashMap<String, Integer>();
private Map<String, Integer> gold = new HashMap<String, Integer>(); private Map<String, Integer> gold = new HashMap<String, Integer>();
private Map<String, Integer> iron = new HashMap<String, Integer>(); private Map<String, Integer> iron = new HashMap<String, Integer>();
@@ -43,54 +42,44 @@ public class XRayTracker
private static final int POWER = 10; private static final int POWER = 10;
private static final int MIN_BLOCK_COUNT = 100; private static final int MIN_BLOCK_COUNT = 100;
public XRayTracker() public XRayTracker() {
{
} }
public boolean sufficientData(String player) public boolean sufficientData(String player) {
{
return totalblock.get(player) != null && totalblock.get(player) >= MIN_BLOCK_COUNT; return totalblock.get(player) != null && totalblock.get(player) >= MIN_BLOCK_COUNT;
} }
public void calculate(CommandSender cs, String player, double x, double b, String type) public void calculate(CommandSender cs, String player, double x, double b, String type) {
{
ChatColor color = WHITE; ChatColor color = WHITE;
if (x >= b / RATIO_DIVISOR) if (x >= b / RATIO_DIVISOR) {
{
color = RED; color = RED;
} }
cs.sendMessage(GRAY + "Percent " + type + " ore: " + color + round(x) + "%"); cs.sendMessage(GRAY + "Percent " + type + " ore: " + color + round(x) + "%");
} }
public boolean calculate(String player, double x, double b) public boolean calculate(String player, double x, double b) {
{
return x >= b / RATIO_DIVISOR; return x >= b / RATIO_DIVISOR;
} }
public boolean hasAbnormal(String player) public boolean hasAbnormal(String player) {
{
XRayStats stats = new XRayStats(player, diamond, gold, iron, lapis, redstone, block, totalblock); XRayStats stats = new XRayStats(player, diamond, gold, iron, lapis, redstone, block, totalblock);
double total = stats.getOther(); double total = stats.getOther();
return calculate(player, stats.getDiamond(), total) || calculate(player, stats.getGold(), total) || calculate(player, stats.getIron(), total) || calculate(player, stats.getLapis(), total) || calculate(player, stats.getRedstone(), total); return calculate(player, stats.getDiamond(), total) || calculate(player, stats.getGold(), total) || calculate(player, stats.getIron(), total) || calculate(player, stats.getLapis(), total) || calculate(player, stats.getRedstone(), total);
} }
public boolean hasAlerted(String player) public boolean hasAlerted(String player) {
{
return alerted.contains(player); return alerted.contains(player);
} }
public void logAlert(String player) public void logAlert(String player) {
{
alerted.add(player); alerted.add(player);
} }
public void sendStats(CommandSender cs, String player) public void sendStats(CommandSender cs, String player) {
{
getStats(cs, player); getStats(cs, player);
} }
public void getStats(CommandSender cs, String player) public void getStats(CommandSender cs, String player) {
{
XRayStats stats = new XRayStats(player, diamond, gold, iron, lapis, redstone, block, totalblock); XRayStats stats = new XRayStats(player, diamond, gold, iron, lapis, redstone, block, totalblock);
double total = stats.getOther(); double total = stats.getOther();
cs.sendMessage("--------------------[" + GREEN + "X-Ray Stats" + WHITE + "]---------------------"); cs.sendMessage("--------------------[" + GREEN + "X-Ray Stats" + WHITE + "]---------------------");
@@ -105,56 +94,44 @@ public class XRayTracker
cs.sendMessage("-----------------------------------------------------"); cs.sendMessage("-----------------------------------------------------");
} }
public void addDiamond(String player) public void addDiamond(String player) {
{
addOre(player, diamond); addOre(player, diamond);
} }
public void addGold(String player) public void addGold(String player) {
{
addOre(player, gold); addOre(player, gold);
} }
public void addIron(String player) public void addIron(String player) {
{
addOre(player, iron); addOre(player, iron);
} }
public void addLapis(String player) public void addLapis(String player) {
{
addOre(player, lapis); addOre(player, lapis);
} }
public void addRedstone(String player) public void addRedstone(String player) {
{
addOre(player, redstone); addOre(player, redstone);
} }
public void addBlock(String player) public void addBlock(String player) {
{
addOre(player, block); addOre(player, block);
} }
public void addTotal(String player) public void addTotal(String player) {
{
addOre(player, totalblock); addOre(player, totalblock);
} }
private void addOre(String player, Map<String, Integer> map) private void addOre(String player, Map<String, Integer> map) {
{ if (map.get(player) == null || map.get(player) == 0) {
if (map.get(player) == null || map.get(player) == 0)
{
map.put(player, 1); map.put(player, 1);
} } else {
else
{
int playerLevel = map.get(player); int playerLevel = map.get(player);
map.put(player, playerLevel + 1); map.put(player, playerLevel + 1);
} }
} }
private float round(double num) private float round(double num) {
{
double number = num; double number = num;
float p = (float) Math.pow(POWER, 1); float p = (float) Math.pow(POWER, 1);
number *= p; number *= p;
@@ -162,8 +139,7 @@ public class XRayTracker
return (float) tmp / p; return (float) tmp / p;
} }
public void reset(String player) public void reset(String player) {
{
totalblock.put(player, 1); totalblock.put(player, 1);
diamond.put(player, 0); diamond.put(player, 0);
iron.put(player, 0); iron.put(player, 0);