From 8e92077bb6012bde6da051900887756b34805e4a Mon Sep 17 00:00:00 2001 From: Rammelkast Date: Wed, 15 Aug 2018 20:28:52 +0200 Subject: [PATCH] More small changes --- .../anticheatreloaded/check/CheckType.java | 3 +- .../{ElytraFly.java => ElytraCheck.java} | 25 +- .../check/movement/FlightCheck.java | 6 +- .../event/PlayerListener.java | 26 +- .../event/VehicleListener.java | 17 +- .../manage/CheckManager.java | 4 +- .../manage/PacketManager.java | 58 - .../anticheatreloaded/metrics/Metrics.java | 1809 ++++++++--------- .../anticheatreloaded/util/BlockHardness.java | 252 +-- .../anticheatreloaded/util/Distance.java | 54 +- .../anticheatreloaded/util/FileFormatter.java | 16 +- .../anticheatreloaded/util/Group.java | 105 +- .../anticheatreloaded/util/NMS_1_9_PLUS.java | 16 +- .../anticheatreloaded/util/NPC_1_12.java | 63 +- .../anticheatreloaded/util/NameGenerator.java | 32 +- .../anticheatreloaded/util/NameUtil.java | 56 - .../anticheatreloaded/util/Permission.java | 99 +- .../anticheatreloaded/util/ToolHardness.java | 33 +- .../anticheatreloaded/util/User.java | 706 +++---- .../anticheatreloaded/util/Utilities.java | 999 ++++----- .../anticheatreloaded/util/VersionUtil.java | 39 +- .../anticheatreloaded/util/rule/Rule.java | 2 +- src/main/resources/plugin.yml | 5 +- 23 files changed, 2026 insertions(+), 2399 deletions(-) rename src/main/java/com/rammelkast/anticheatreloaded/check/movement/{ElytraFly.java => ElytraCheck.java} (52%) delete mode 100644 src/main/java/com/rammelkast/anticheatreloaded/manage/PacketManager.java delete mode 100644 src/main/java/com/rammelkast/anticheatreloaded/util/NameUtil.java diff --git a/src/main/java/com/rammelkast/anticheatreloaded/check/CheckType.java b/src/main/java/com/rammelkast/anticheatreloaded/check/CheckType.java index 84a8ad5..d20e996 100644 --- a/src/main/java/com/rammelkast/anticheatreloaded/check/CheckType.java +++ b/src/main/java/com/rammelkast/anticheatreloaded/check/CheckType.java @@ -39,7 +39,8 @@ public enum CheckType { ZOMBE_FLY(Permission.CHECK_ZOMBE_FLY), ZOMBE_NOCLIP(Permission.CHECK_ZOMBE_NOCLIP), ZOMBE_CHEAT(Permission.CHECK_ZOMBE_CHEAT), - FLY(Permission.CHECK_FLY), + FLIGHT(Permission.CHECK_FLIGHT), + ELYTRA(Permission.CHECK_FLIGHT), WATER_WALK(Permission.CHECK_WATERWALK), NO_SWING(Permission.CHECK_NOSWING), FAST_BREAK(Permission.CHECK_FASTBREAK), diff --git a/src/main/java/com/rammelkast/anticheatreloaded/check/movement/ElytraFly.java b/src/main/java/com/rammelkast/anticheatreloaded/check/movement/ElytraCheck.java similarity index 52% rename from src/main/java/com/rammelkast/anticheatreloaded/check/movement/ElytraFly.java rename to src/main/java/com/rammelkast/anticheatreloaded/check/movement/ElytraCheck.java index 807942f..afe6daf 100644 --- a/src/main/java/com/rammelkast/anticheatreloaded/check/movement/ElytraFly.java +++ b/src/main/java/com/rammelkast/anticheatreloaded/check/movement/ElytraCheck.java @@ -19,20 +19,39 @@ package com.rammelkast.anticheatreloaded.check.movement; +import org.bukkit.Material; +import org.bukkit.block.BlockFace; import org.bukkit.entity.Player; +import com.rammelkast.anticheatreloaded.AntiCheatReloaded; import com.rammelkast.anticheatreloaded.check.CheckResult; import com.rammelkast.anticheatreloaded.util.Distance; +import com.rammelkast.anticheatreloaded.util.Utilities; /** * TODO */ -public class ElytraFly { +public class ElytraCheck { private static final CheckResult PASS = new CheckResult(CheckResult.Result.PASSED); - + public static CheckResult runCheck(Player player, Distance distance) { + if (distance.getYDifference() > AntiCheatReloaded.getManager().getBackend().getMagic().TELEPORT_MIN()) { + // This was a teleport, so skip check. + return PASS; + } + if (!FlightCheck.isMovingExempt(player) && !Utilities.isHoveringOverWater(player.getLocation(), 1) + && Utilities.cantStandAtExp(player.getLocation()) + && Utilities.blockIsnt(player.getLocation().getBlock().getRelative(BlockFace.DOWN), + new Material[] { Material.FENCE, Material.FENCE_GATE, Material.COBBLE_WALL, + Material.ACACIA_FENCE, Material.ACACIA_FENCE_GATE, Material.BIRCH_FENCE, + Material.BIRCH_FENCE_GATE, Material.DARK_OAK_FENCE, Material.DARK_OAK_FENCE_GATE, + Material.IRON_FENCE, Material.JUNGLE_FENCE, Material.JUNGLE_FENCE_GATE, + Material.NETHER_FENCE, Material.SPRUCE_FENCE, Material.SPRUCE_FENCE_GATE, Material.IRON_BARDING })) { + + } + return PASS; } - + } diff --git a/src/main/java/com/rammelkast/anticheatreloaded/check/movement/FlightCheck.java b/src/main/java/com/rammelkast/anticheatreloaded/check/movement/FlightCheck.java index 7388564..13694f6 100644 --- a/src/main/java/com/rammelkast/anticheatreloaded/check/movement/FlightCheck.java +++ b/src/main/java/com/rammelkast/anticheatreloaded/check/movement/FlightCheck.java @@ -56,7 +56,11 @@ public class FlightCheck { if (!isMovingExempt(player) && !Utilities.isHoveringOverWater(player.getLocation(), 1) && Utilities.cantStandAtExp(player.getLocation()) && Utilities.blockIsnt(player.getLocation().getBlock().getRelative(BlockFace.DOWN), - new Material[] { Material.FENCE, Material.FENCE_GATE, Material.COBBLE_WALL })) { + new Material[] { Material.FENCE, Material.FENCE_GATE, Material.COBBLE_WALL, + Material.ACACIA_FENCE, Material.ACACIA_FENCE_GATE, Material.BIRCH_FENCE, + Material.BIRCH_FENCE_GATE, Material.DARK_OAK_FENCE, Material.DARK_OAK_FENCE_GATE, + Material.IRON_FENCE, Material.JUNGLE_FENCE, Material.JUNGLE_FENCE_GATE, + Material.NETHER_FENCE, Material.SPRUCE_FENCE, Material.SPRUCE_FENCE_GATE, Material.IRON_BARDING })) { if (!blocksOverFlight.containsKey(uuid)) { blocksOverFlight.put(uuid, 0D); diff --git a/src/main/java/com/rammelkast/anticheatreloaded/event/PlayerListener.java b/src/main/java/com/rammelkast/anticheatreloaded/event/PlayerListener.java index 281ce77..16b932e 100644 --- a/src/main/java/com/rammelkast/anticheatreloaded/event/PlayerListener.java +++ b/src/main/java/com/rammelkast/anticheatreloaded/event/PlayerListener.java @@ -56,7 +56,7 @@ import com.rammelkast.anticheatreloaded.AntiCheatReloaded; import com.rammelkast.anticheatreloaded.check.CheckResult; import com.rammelkast.anticheatreloaded.check.CheckType; import com.rammelkast.anticheatreloaded.check.combat.KillAuraCheck; -import com.rammelkast.anticheatreloaded.check.movement.ElytraFly; +import com.rammelkast.anticheatreloaded.check.movement.ElytraCheck; import com.rammelkast.anticheatreloaded.check.movement.FlightCheck; import com.rammelkast.anticheatreloaded.check.movement.GlideCheck; import com.rammelkast.anticheatreloaded.check.movement.SpeedCheck; @@ -153,7 +153,7 @@ public class PlayerListener extends EventListener { @EventHandler public void onPlayerVelocity(PlayerVelocityEvent event) { Player player = event.getPlayer(); - if (getCheckManager().willCheck(player, CheckType.FLY)) { + if (getCheckManager().willCheck(player, CheckType.FLIGHT)) { if (getBackend().justVelocity(player) && getBackend().extendVelocityTime(player)) { event.setCancelled(!silentMode()); return; @@ -332,26 +332,26 @@ public class PlayerListener extends EventListener { log(result.getMessage(), player, CheckType.SPRINT); } } - if (getCheckManager().willCheckQuick(player, CheckType.FLY) && !VersionUtil.isFlying(player)) { + if (getCheckManager().willCheckQuick(player, CheckType.FLIGHT) && !VersionUtil.isFlying(player)) { CheckResult result = FlightCheck.runCheck(player, distance); if (result.failed()) { if (!silentMode()) { event.setTo(user.getGoodLocation(from.clone())); } - log(result.getMessage(), player, CheckType.FLY); + log(result.getMessage(), player, CheckType.FLIGHT); } } - if (getCheckManager().willCheckQuick(player, CheckType.FLY) && !VersionUtil.isFlying(player)) { + if (getCheckManager().willCheckQuick(player, CheckType.FLIGHT) && !VersionUtil.isFlying(player)) { CheckResult result = GlideCheck.runCheck(player, distance); if (result.failed()) { // NO TELEPORT NEEDED HERE, HANDLED BY CHECK ITSELF - log(result.getMessage(), player, CheckType.FLY); + log(result.getMessage(), player, CheckType.FLIGHT); } } - if (getCheckManager().willCheckQuick(player, CheckType.FLY)) { - CheckResult result = ElytraFly.runCheck(player, distance); + if (getCheckManager().willCheckQuick(player, CheckType.ELYTRA)) { + CheckResult result = ElytraCheck.runCheck(player, distance); if (result.failed()) { - log(result.getMessage(), player, CheckType.FLY); + log(result.getMessage(), player, CheckType.ELYTRA); } } if (getCheckManager().willCheckQuick(player, CheckType.VCLIP) && event.getFrom().getY() > event.getTo().getY()) { @@ -370,7 +370,7 @@ public class PlayerListener extends EventListener { log(result.getMessage(), player, CheckType.VCLIP); } } - if (getCheckManager().willCheckQuick(player, CheckType.NOFALL) && getCheckManager().willCheck(player, CheckType.FLY) && !Utilities.isClimbableBlock(player.getLocation().getBlock()) && event.getFrom().getY() > event.getTo().getY()) { + if (getCheckManager().willCheckQuick(player, CheckType.NOFALL) && getCheckManager().willCheck(player, CheckType.FLIGHT) && !Utilities.isClimbableBlock(player.getLocation().getBlock()) && event.getFrom().getY() > event.getTo().getY()) { CheckResult result = getBackend().checkNoFall(player, y); if (result.failed()) { if (!silentMode()) { @@ -385,7 +385,7 @@ public class PlayerListener extends EventListener { if (event.getTo() != event.getFrom()) { double x = distance.getXDifference(); double z = distance.getZDifference(); - if (getCheckManager().willCheckQuick(player, CheckType.SPEED) && getCheckManager().willCheck(player, CheckType.FLY)) { + if (getCheckManager().willCheckQuick(player, CheckType.SPEED) && getCheckManager().willCheck(player, CheckType.FLIGHT)) { if (event.getFrom().getY() < event.getTo().getY()) { CheckResult result = getBackend().checkYSpeed(player, y); if (result.failed()) { @@ -462,7 +462,7 @@ public class PlayerListener extends EventListener { return; } - if (getCheckManager().willCheck(player, CheckType.FLY) && !player.isFlying()) { + if (getCheckManager().willCheck(player, CheckType.FLIGHT) && !player.isFlying()) { CheckResult result1 = YAxisCheck.runCheck(player, new Distance(from, to)); CheckResult result2 = getBackend().checkAscension(player, from.getY(), to.getY()); String log = result1.failed() ? result1.getMessage() : result2.failed() ? result2.getMessage() : ""; @@ -470,7 +470,7 @@ public class PlayerListener extends EventListener { if (!silentMode()) { event.setTo(user.getGoodLocation(from.clone())); } - log(log, player, CheckType.FLY); + log(log, player, CheckType.FLIGHT); } } } diff --git a/src/main/java/com/rammelkast/anticheatreloaded/event/VehicleListener.java b/src/main/java/com/rammelkast/anticheatreloaded/event/VehicleListener.java index 86ad8fb..77966ff 100644 --- a/src/main/java/com/rammelkast/anticheatreloaded/event/VehicleListener.java +++ b/src/main/java/com/rammelkast/anticheatreloaded/event/VehicleListener.java @@ -19,6 +19,7 @@ package com.rammelkast.anticheatreloaded.event; +import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.vehicle.VehicleDestroyEvent; @@ -48,13 +49,21 @@ public class VehicleListener extends EventListener { } - @Deprecated @EventHandler(ignoreCancelled = true) public void onVehicleDestroy(VehicleDestroyEvent event) { // TODO fix deprecations - if (event.getVehicle().getPassenger() != null && event.getVehicle().getPassenger() instanceof Player) { - getBackend().logEnterExit((Player) event.getVehicle().getPassenger()); - } + //if (event.getVehicle().getPassenger() != null && event.getVehicle().getPassenger() instanceof Player) { + // getBackend().logEnterExit((Player) event.getVehicle().getPassenger()); + //} + + // TODO this should work, untested though. + if (!event.getVehicle().getPassengers().isEmpty()) { + for (Entity entity: event.getVehicle().getPassengers()) { + if (entity instanceof Player) { + getBackend().logEnterExit((Player) entity); + } + } + } AntiCheatReloaded.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); } diff --git a/src/main/java/com/rammelkast/anticheatreloaded/manage/CheckManager.java b/src/main/java/com/rammelkast/anticheatreloaded/manage/CheckManager.java index ecf9107..8bf45c0 100644 --- a/src/main/java/com/rammelkast/anticheatreloaded/manage/CheckManager.java +++ b/src/main/java/com/rammelkast/anticheatreloaded/manage/CheckManager.java @@ -25,6 +25,7 @@ import org.bukkit.entity.Player; import com.rammelkast.anticheatreloaded.AntiCheatReloaded; import com.rammelkast.anticheatreloaded.check.CheckType; import com.rammelkast.anticheatreloaded.config.Configuration; +import com.rammelkast.anticheatreloaded.util.VersionUtil; import java.util.ArrayList; import java.util.HashMap; @@ -177,8 +178,7 @@ public class CheckManager { && !type.checkPermission(player) && !isOpExempt(player); AntiCheatReloaded.debugLog("Check " + type + (check ? " run " : " not run ") + "on " + player.getName()); - // TODO temp fix - if ((type == CheckType.FLY || type == CheckType.SPEED) && player.isFlying()) + if ((type == CheckType.FLIGHT || type == CheckType.SPEED) && VersionUtil.isFlying(player)) return false; return check; } diff --git a/src/main/java/com/rammelkast/anticheatreloaded/manage/PacketManager.java b/src/main/java/com/rammelkast/anticheatreloaded/manage/PacketManager.java deleted file mode 100644 index 07b0722..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/manage/PacketManager.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team | http://gravitydevelopment.net - * Copyright (c) 2016-2018 Rammelkast | https://rammelkast.com - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded.manage; - -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.ProtocolManager; -import com.comphenix.protocol.events.ListenerPriority; -import com.comphenix.protocol.events.PacketAdapter; -import com.comphenix.protocol.events.PacketContainer; -import com.comphenix.protocol.events.PacketEvent; -import com.rammelkast.anticheatreloaded.AntiCheatReloaded; - -public class PacketManager { - - private ProtocolManager protocolManager; - private AntiCheatReloaded plugin; - private AntiCheatManager manager; - - public PacketManager(ProtocolManager protocolManager, AntiCheatReloaded plugin, AntiCheatManager manager) { - this.protocolManager = protocolManager; - this.plugin = plugin; - this.manager = manager; - addListeners(); - } - - private void addListeners() { - // Arm Animation - protocolManager.addPacketListener(new PacketAdapter(plugin, - ListenerPriority.NORMAL, - PacketType.Play.Client.ARM_ANIMATION) { - - @Override - public void onPacketReceiving(PacketEvent event) { - if (event.getPacketType() == PacketType.Play.Client.ARM_ANIMATION) { - PacketContainer packet = event.getPacket(); - //System.out.println("Arm animation from "+packet.getIntegers().read(0)); - } - } - }); - } -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/metrics/Metrics.java b/src/main/java/com/rammelkast/anticheatreloaded/metrics/Metrics.java index b28f4c7..741a214 100644 --- a/src/main/java/com/rammelkast/anticheatreloaded/metrics/Metrics.java +++ b/src/main/java/com/rammelkast/anticheatreloaded/metrics/Metrics.java @@ -48,988 +48,829 @@ import org.json.simple.JSONObject; //bStats.org/ to learn more about bStats! public class Metrics { - // The version of this bStats class - public static final int B_STATS_VERSION = 1; - - // The url to which the data is sent - private static final String URL = "https://bStats.org/submitData"; - - // Should failed requests be logged? - private static boolean logFailedRequests; - - // The uuid of the server - private static String serverUUID; - - // The plugin - private final JavaPlugin plugin; - - // A list with all custom charts - private final List charts = new ArrayList<>(); - - /** - * Class constructor. - * - * @param plugin The plugin which stats should be submitted. - */ - public Metrics(JavaPlugin plugin) { - if (plugin == null) { - throw new IllegalArgumentException("Plugin cannot be null!"); - } - this.plugin = plugin; - - // Get the config file - File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats"); - File configFile = new File(bStatsFolder, "config.yml"); - YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); - - // Check if the config file exists - if (!config.isSet("serverUuid")) { - - // Add default values - config.addDefault("enabled", true); - // Every server gets it's unique random id. - config.addDefault("serverUuid", UUID.randomUUID().toString()); - // Should failed request be logged? - config.addDefault("logFailedRequests", false); - - // Inform the server owners about bStats - config.options().header( - "bStats collects some data for plugin authors like how many servers are using their plugins.\n" + - "To honor their work, you should not disable it.\n" + - "This has nearly no effect on the server performance!\n" + - "Check out https://bStats.org/ to learn more :)" - ).copyDefaults(true); - try { - config.save(configFile); - } catch (IOException ignored) { } - } - - // Load the data - serverUUID = config.getString("serverUuid"); - logFailedRequests = config.getBoolean("logFailedRequests", false); - if (config.getBoolean("enabled", true)) { - boolean found = false; - // Search for all other bStats Metrics classes to see if we are the first one - for (Class service : Bukkit.getServicesManager().getKnownServices()) { - try { - service.getField("B_STATS_VERSION"); // Our identifier :) - found = true; // We aren't the first - break; - } catch (NoSuchFieldException ignored) { } - } - // Register our service - Bukkit.getServicesManager().register(Metrics.class, this, plugin, ServicePriority.Normal); - if (!found) { - // We are the first! - startSubmitting(); - } - } - } - - /** - * Adds a custom chart. - * - * @param chart The chart to add. - */ - public void addCustomChart(CustomChart chart) { - if (chart == null) { - throw new IllegalArgumentException("Chart cannot be null!"); - } - charts.add(chart); - } - - /** - * Starts the Scheduler which submits our data every 30 minutes. - */ - private void startSubmitting() { - final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags - timer.scheduleAtFixedRate(new TimerTask() { - @Override - public void run() { - if (!plugin.isEnabled()) { // Plugin was disabled - timer.cancel(); - return; - } - // Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler - // Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;) - Bukkit.getScheduler().runTask(plugin, new Runnable() { - @Override - public void run() { - submitData(); - } - }); - } - }, 1000*60*5, 1000*60*30); - // Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start - // WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted! - // WARNING: Just don't do it! - } - - /** - * Gets the plugin specific data. - * This method is called using Reflection. - * - * @return The plugin specific data. - */ - public JSONObject getPluginData() { - JSONObject data = new JSONObject(); - - String pluginName = plugin.getDescription().getName(); - String pluginVersion = plugin.getDescription().getVersion(); - - data.put("pluginName", pluginName); // Append the name of the plugin - data.put("pluginVersion", pluginVersion); // Append the version of the plugin - JSONArray customCharts = new JSONArray(); - for (CustomChart customChart : charts) { - // Add the data of the custom charts - JSONObject chart = customChart.getRequestJsonObject(); - if (chart == null) { // If the chart is null, we skip it - continue; - } - customCharts.add(chart); - } - data.put("customCharts", customCharts); - - return data; - } - - /** - * Gets the server specific data. - * - * @return The server specific data. - */ - private JSONObject getServerData() { - // Minecraft specific data - int playerAmount = Bukkit.getOnlinePlayers().size(); - int onlineMode = Bukkit.getOnlineMode() ? 1 : 0; - String bukkitVersion = org.bukkit.Bukkit.getVersion(); - bukkitVersion = bukkitVersion.substring(bukkitVersion.indexOf("MC: ") + 4, bukkitVersion.length() - 1); - - // OS/Java specific data - String javaVersion = System.getProperty("java.version"); - String osName = System.getProperty("os.name"); - String osArch = System.getProperty("os.arch"); - String osVersion = System.getProperty("os.version"); - int coreCount = Runtime.getRuntime().availableProcessors(); - - JSONObject data = new JSONObject(); - - data.put("serverUUID", serverUUID); - - data.put("playerAmount", playerAmount); - data.put("onlineMode", onlineMode); - data.put("bukkitVersion", bukkitVersion); - - data.put("javaVersion", javaVersion); - data.put("osName", osName); - data.put("osArch", osArch); - data.put("osVersion", osVersion); - data.put("coreCount", coreCount); - - return data; - } - - /** - * Collects the data and sends it afterwards. - */ - private void submitData() { - final JSONObject data = getServerData(); - - JSONArray pluginData = new JSONArray(); - // Search for all other bStats Metrics classes to get their plugin data - for (Class service : Bukkit.getServicesManager().getKnownServices()) { - try { - service.getField("B_STATS_VERSION"); // Our identifier :) - } catch (NoSuchFieldException ignored) { - continue; // Continue "searching" - } - // Found one! - try { - pluginData.add(service.getMethod("getPluginData").invoke(Bukkit.getServicesManager().load(service))); - } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { } - } - - data.put("plugins", pluginData); - - // Create a new thread for the connection to the bStats server - new Thread(new Runnable() { - @Override - public void run() { - try { - // Send the data - sendData(data); - } catch (Exception e) { - // Something went wrong! :( - if (logFailedRequests) { - plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e); - } - } - } - }).start(); - - } - - /** - * Sends the data to the bStats server. - * - * @param data The data to send. - * @throws Exception If the request failed. - */ - private static void sendData(JSONObject data) throws Exception { - if (data == null) { - throw new IllegalArgumentException("Data cannot be null!"); - } - if (Bukkit.isPrimaryThread()) { - throw new IllegalAccessException("This method must not be called from the main thread!"); - } - HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection(); - - // Compress the data to save bandwidth - byte[] compressedData = compress(data.toString()); - - // Add headers - connection.setRequestMethod("POST"); - connection.addRequestProperty("Accept", "application/json"); - connection.addRequestProperty("Connection", "close"); - connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request - connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); - connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format - connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION); - - // Send data - connection.setDoOutput(true); - DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); - outputStream.write(compressedData); - outputStream.flush(); - outputStream.close(); - - connection.getInputStream().close(); // We don't care about the response - Just send our data :) - } - - /** - * Gzips the given String. - * - * @param str The string to gzip. - * @return The gzipped String. - * @throws IOException If the compression failed. - */ - private static byte[] compress(final String str) throws IOException { - if (str == null) { - return null; - } - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - GZIPOutputStream gzip = new GZIPOutputStream(outputStream); - gzip.write(str.getBytes("UTF-8")); - gzip.close(); - return outputStream.toByteArray(); - } - - /** - * Represents a custom chart. - */ - public static abstract class CustomChart { - - // The id of the chart - protected final String chartId; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - */ - public CustomChart(String chartId) { - if (chartId == null || chartId.isEmpty()) { - throw new IllegalArgumentException("ChartId cannot be null or empty!"); - } - this.chartId = chartId; - } - - protected JSONObject getRequestJsonObject() { - JSONObject chart = new JSONObject(); - chart.put("chartId", chartId); - try { - JSONObject data = getChartData(); - if (data == null) { - // If the data is null we don't send the chart. - return null; - } - chart.put("data", data); - } catch (Throwable t) { - if (logFailedRequests) { - Bukkit.getLogger().log(Level.WARNING, "Failed to get data for custom chart with id " + chartId, t); - } - return null; - } - return chart; - } - - protected abstract JSONObject getChartData(); - - } - - /** - * Represents a custom simple pie. - */ - public static abstract class SimplePie extends CustomChart { - - /** - * Class constructor. - * - * @param chartId The id of the chart. - */ - public SimplePie(String chartId) { - super(chartId); - } - - /** - * Gets the value of the pie. - * - * @return The value of the pie. - */ - public abstract String getValue(); - - @Override - protected JSONObject getChartData() { - JSONObject data = new JSONObject(); - String value = getValue(); - if (value == null || value.isEmpty()) { - // Null = skip the chart - return null; - } - data.put("value", value); - return data; - } - } - - /** - * Represents a custom advanced pie. - */ - public static abstract class AdvancedPie extends CustomChart { - - /** - * Class constructor. - * - * @param chartId The id of the chart. - */ - public AdvancedPie(String chartId) { - super(chartId); - } - - /** - * Gets the values of the pie. - * - * @param valueMap Just an empty map. The only reason it exists is to make your life easier. - * You don't have to create a map yourself! - * @return The values of the pie. - */ - public abstract HashMap getValues(HashMap valueMap); - - @Override - protected JSONObject getChartData() { - JSONObject data = new JSONObject(); - JSONObject values = new JSONObject(); - HashMap map = getValues(new HashMap()); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean allSkipped = true; - for (Map.Entry entry : map.entrySet()) { - if (entry.getValue() == 0) { - continue; // Skip this invalid - } - allSkipped = false; - values.put(entry.getKey(), entry.getValue()); - } - if (allSkipped) { - // Null = skip the chart - return null; - } - data.put("values", values); - return data; - } - } - - /** - * Represents a custom single line chart. - */ - public static abstract class SingleLineChart extends CustomChart { - - /** - * Class constructor. - * - * @param chartId The id of the chart. - */ - public SingleLineChart(String chartId) { - super(chartId); - } - - /** - * Gets the value of the chart. - * - * @return The value of the chart. - */ - public abstract int getValue(); - - @Override - protected JSONObject getChartData() { - JSONObject data = new JSONObject(); - int value = getValue(); - if (value == 0) { - // Null = skip the chart - return null; - } - data.put("value", value); - return data; - } - - } - - /** - * Represents a custom multi line chart. - */ - public static abstract class MultiLineChart extends CustomChart { - - /** - * Class constructor. - * - * @param chartId The id of the chart. - */ - public MultiLineChart(String chartId) { - super(chartId); - } - - /** - * Gets the values of the chart. - * - * @param valueMap Just an empty map. The only reason it exists is to make your life easier. - * You don't have to create a map yourself! - * @return The values of the chart. - */ - public abstract HashMap getValues(HashMap valueMap); - - @Override - protected JSONObject getChartData() { - JSONObject data = new JSONObject(); - JSONObject values = new JSONObject(); - HashMap map = getValues(new HashMap()); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean allSkipped = true; - for (Map.Entry entry : map.entrySet()) { - if (entry.getValue() == 0) { - continue; // Skip this invalid - } - allSkipped = false; - values.put(entry.getKey(), entry.getValue()); - } - if (allSkipped) { - // Null = skip the chart - return null; - } - data.put("values", values); - return data; - } - - } - - /** - * Represents a custom simple bar chart. - */ - public static abstract class SimpleBarChart extends CustomChart { - - /** - * Class constructor. - * - * @param chartId The id of the chart. - */ - public SimpleBarChart(String chartId) { - super(chartId); - } - - /** - * Gets the value of the chart. - * - * @param valueMap Just an empty map. The only reason it exists is to make your life easier. - * You don't have to create a map yourself! - * @return The value of the chart. - */ - public abstract HashMap getValues(HashMap valueMap); - - @Override - protected JSONObject getChartData() { - JSONObject data = new JSONObject(); - JSONObject values = new JSONObject(); - HashMap map = getValues(new HashMap()); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - for (Map.Entry entry : map.entrySet()) { - JSONArray categoryValues = new JSONArray(); - categoryValues.add(entry.getValue()); - values.put(entry.getKey(), categoryValues); - } - data.put("values", values); - return data; - } - - } - - /** - * Represents a custom advanced bar chart. - */ - public static abstract class AdvancedBarChart extends CustomChart { - - /** - * Class constructor. - * - * @param chartId The id of the chart. - */ - public AdvancedBarChart(String chartId) { - super(chartId); - } - - /** - * Gets the value of the chart. - * - * @param valueMap Just an empty map. The only reason it exists is to make your life easier. - * You don't have to create a map yourself! - * @return The value of the chart. - */ - public abstract HashMap getValues(HashMap valueMap); - - @Override - protected JSONObject getChartData() { - JSONObject data = new JSONObject(); - JSONObject values = new JSONObject(); - HashMap map = getValues(new HashMap()); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean allSkipped = true; - for (Map.Entry entry : map.entrySet()) { - if (entry.getValue().length == 0) { - continue; // Skip this invalid - } - allSkipped = false; - JSONArray categoryValues = new JSONArray(); - for (int categoryValue : entry.getValue()) { - categoryValues.add(categoryValue); - } - values.put(entry.getKey(), categoryValues); - } - if (allSkipped) { - // Null = skip the chart - return null; - } - data.put("values", values); - return data; - } - - } - - /** - * Represents a custom simple map chart. - */ - public static abstract class SimpleMapChart extends CustomChart { - - /** - * Class constructor. - * - * @param chartId The id of the chart. - */ - public SimpleMapChart(String chartId) { - super(chartId); - } - - /** - * Gets the value of the chart. - * - * @return The value of the chart. - */ - public abstract Country getValue(); - - @Override - protected JSONObject getChartData() { - JSONObject data = new JSONObject(); - Country value = getValue(); - - if (value == null) { - // Null = skip the chart - return null; - } - data.put("value", value.getCountryIsoTag()); - return data; - } - - } - - /** - * Represents a custom advanced map chart. - */ - public static abstract class AdvancedMapChart extends CustomChart { - - /** - * Class constructor. - * - * @param chartId The id of the chart. - */ - public AdvancedMapChart(String chartId) { - super(chartId); - } - - /** - * Gets the value of the chart. - * - * @param valueMap Just an empty map. The only reason it exists is to make your life easier. - * You don't have to create a map yourself! - * @return The value of the chart. - */ - public abstract HashMap getValues(HashMap valueMap); - - @Override - protected JSONObject getChartData() { - JSONObject data = new JSONObject(); - JSONObject values = new JSONObject(); - HashMap map = getValues(new HashMap()); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean allSkipped = true; - for (Map.Entry entry : map.entrySet()) { - if (entry.getValue() == 0) { - continue; // Skip this invalid - } - allSkipped = false; - values.put(entry.getKey().getCountryIsoTag(), entry.getValue()); - } - if (allSkipped) { - // Null = skip the chart - return null; - } - data.put("values", values); - return data; - } - - } - - /** - * A enum which is used for custom maps. - */ - public enum Country { - - /** - * bStats will use the country of the server. - */ - AUTO_DETECT("AUTO", "Auto Detected"), - - ANDORRA("AD", "Andorra"), - UNITED_ARAB_EMIRATES("AE", "United Arab Emirates"), - AFGHANISTAN("AF", "Afghanistan"), - ANTIGUA_AND_BARBUDA("AG", "Antigua and Barbuda"), - ANGUILLA("AI", "Anguilla"), - ALBANIA("AL", "Albania"), - ARMENIA("AM", "Armenia"), - NETHERLANDS_ANTILLES("AN", "Netherlands Antilles"), - ANGOLA("AO", "Angola"), - ANTARCTICA("AQ", "Antarctica"), - ARGENTINA("AR", "Argentina"), - AMERICAN_SAMOA("AS", "American Samoa"), - AUSTRIA("AT", "Austria"), - AUSTRALIA("AU", "Australia"), - ARUBA("AW", "Aruba"), - ÅLAND_ISLANDS("AX", "Åland Islands"), - AZERBAIJAN("AZ", "Azerbaijan"), - BOSNIA_AND_HERZEGOVINA("BA", "Bosnia and Herzegovina"), - BARBADOS("BB", "Barbados"), - BANGLADESH("BD", "Bangladesh"), - BELGIUM("BE", "Belgium"), - BURKINA_FASO("BF", "Burkina Faso"), - BULGARIA("BG", "Bulgaria"), - BAHRAIN("BH", "Bahrain"), - BURUNDI("BI", "Burundi"), - BENIN("BJ", "Benin"), - SAINT_BARTHÉLEMY("BL", "Saint Barthélemy"), - BERMUDA("BM", "Bermuda"), - BRUNEI("BN", "Brunei"), - BOLIVIA("BO", "Bolivia"), - BONAIRE_SINT_EUSTATIUS_AND_SABA("BQ", "Bonaire, Sint Eustatius and Saba"), - BRAZIL("BR", "Brazil"), - BAHAMAS("BS", "Bahamas"), - BHUTAN("BT", "Bhutan"), - BOUVET_ISLAND("BV", "Bouvet Island"), - BOTSWANA("BW", "Botswana"), - BELARUS("BY", "Belarus"), - BELIZE("BZ", "Belize"), - CANADA("CA", "Canada"), - COCOS_ISLANDS("CC", "Cocos Islands"), - THE_DEMOCRATIC_REPUBLIC_OF_CONGO("CD", "The Democratic Republic Of Congo"), - CENTRAL_AFRICAN_REPUBLIC("CF", "Central African Republic"), - CONGO("CG", "Congo"), - SWITZERLAND("CH", "Switzerland"), - CÔTE_D_IVOIRE("CI", "Côte d'Ivoire"), - COOK_ISLANDS("CK", "Cook Islands"), - CHILE("CL", "Chile"), - CAMEROON("CM", "Cameroon"), - CHINA("CN", "China"), - COLOMBIA("CO", "Colombia"), - COSTA_RICA("CR", "Costa Rica"), - CUBA("CU", "Cuba"), - CAPE_VERDE("CV", "Cape Verde"), - CURAÇAO("CW", "Curaçao"), - CHRISTMAS_ISLAND("CX", "Christmas Island"), - CYPRUS("CY", "Cyprus"), - CZECH_REPUBLIC("CZ", "Czech Republic"), - GERMANY("DE", "Germany"), - DJIBOUTI("DJ", "Djibouti"), - DENMARK("DK", "Denmark"), - DOMINICA("DM", "Dominica"), - DOMINICAN_REPUBLIC("DO", "Dominican Republic"), - ALGERIA("DZ", "Algeria"), - ECUADOR("EC", "Ecuador"), - ESTONIA("EE", "Estonia"), - EGYPT("EG", "Egypt"), - WESTERN_SAHARA("EH", "Western Sahara"), - ERITREA("ER", "Eritrea"), - SPAIN("ES", "Spain"), - ETHIOPIA("ET", "Ethiopia"), - FINLAND("FI", "Finland"), - FIJI("FJ", "Fiji"), - FALKLAND_ISLANDS("FK", "Falkland Islands"), - MICRONESIA("FM", "Micronesia"), - FAROE_ISLANDS("FO", "Faroe Islands"), - FRANCE("FR", "France"), - GABON("GA", "Gabon"), - UNITED_KINGDOM("GB", "United Kingdom"), - GRENADA("GD", "Grenada"), - GEORGIA("GE", "Georgia"), - FRENCH_GUIANA("GF", "French Guiana"), - GUERNSEY("GG", "Guernsey"), - GHANA("GH", "Ghana"), - GIBRALTAR("GI", "Gibraltar"), - GREENLAND("GL", "Greenland"), - GAMBIA("GM", "Gambia"), - GUINEA("GN", "Guinea"), - GUADELOUPE("GP", "Guadeloupe"), - EQUATORIAL_GUINEA("GQ", "Equatorial Guinea"), - GREECE("GR", "Greece"), - SOUTH_GEORGIA_AND_THE_SOUTH_SANDWICH_ISLANDS("GS", "South Georgia And The South Sandwich Islands"), - GUATEMALA("GT", "Guatemala"), - GUAM("GU", "Guam"), - GUINEA_BISSAU("GW", "Guinea-Bissau"), - GUYANA("GY", "Guyana"), - HONG_KONG("HK", "Hong Kong"), - HEARD_ISLAND_AND_MCDONALD_ISLANDS("HM", "Heard Island And McDonald Islands"), - HONDURAS("HN", "Honduras"), - CROATIA("HR", "Croatia"), - HAITI("HT", "Haiti"), - HUNGARY("HU", "Hungary"), - INDONESIA("ID", "Indonesia"), - IRELAND("IE", "Ireland"), - ISRAEL("IL", "Israel"), - ISLE_OF_MAN("IM", "Isle Of Man"), - INDIA("IN", "India"), - BRITISH_INDIAN_OCEAN_TERRITORY("IO", "British Indian Ocean Territory"), - IRAQ("IQ", "Iraq"), - IRAN("IR", "Iran"), - ICELAND("IS", "Iceland"), - ITALY("IT", "Italy"), - JERSEY("JE", "Jersey"), - JAMAICA("JM", "Jamaica"), - JORDAN("JO", "Jordan"), - JAPAN("JP", "Japan"), - KENYA("KE", "Kenya"), - KYRGYZSTAN("KG", "Kyrgyzstan"), - CAMBODIA("KH", "Cambodia"), - KIRIBATI("KI", "Kiribati"), - COMOROS("KM", "Comoros"), - SAINT_KITTS_AND_NEVIS("KN", "Saint Kitts And Nevis"), - NORTH_KOREA("KP", "North Korea"), - SOUTH_KOREA("KR", "South Korea"), - KUWAIT("KW", "Kuwait"), - CAYMAN_ISLANDS("KY", "Cayman Islands"), - KAZAKHSTAN("KZ", "Kazakhstan"), - LAOS("LA", "Laos"), - LEBANON("LB", "Lebanon"), - SAINT_LUCIA("LC", "Saint Lucia"), - LIECHTENSTEIN("LI", "Liechtenstein"), - SRI_LANKA("LK", "Sri Lanka"), - LIBERIA("LR", "Liberia"), - LESOTHO("LS", "Lesotho"), - LITHUANIA("LT", "Lithuania"), - LUXEMBOURG("LU", "Luxembourg"), - LATVIA("LV", "Latvia"), - LIBYA("LY", "Libya"), - MOROCCO("MA", "Morocco"), - MONACO("MC", "Monaco"), - MOLDOVA("MD", "Moldova"), - MONTENEGRO("ME", "Montenegro"), - SAINT_MARTIN("MF", "Saint Martin"), - MADAGASCAR("MG", "Madagascar"), - MARSHALL_ISLANDS("MH", "Marshall Islands"), - MACEDONIA("MK", "Macedonia"), - MALI("ML", "Mali"), - MYANMAR("MM", "Myanmar"), - MONGOLIA("MN", "Mongolia"), - MACAO("MO", "Macao"), - NORTHERN_MARIANA_ISLANDS("MP", "Northern Mariana Islands"), - MARTINIQUE("MQ", "Martinique"), - MAURITANIA("MR", "Mauritania"), - MONTSERRAT("MS", "Montserrat"), - MALTA("MT", "Malta"), - MAURITIUS("MU", "Mauritius"), - MALDIVES("MV", "Maldives"), - MALAWI("MW", "Malawi"), - MEXICO("MX", "Mexico"), - MALAYSIA("MY", "Malaysia"), - MOZAMBIQUE("MZ", "Mozambique"), - NAMIBIA("NA", "Namibia"), - NEW_CALEDONIA("NC", "New Caledonia"), - NIGER("NE", "Niger"), - NORFOLK_ISLAND("NF", "Norfolk Island"), - NIGERIA("NG", "Nigeria"), - NICARAGUA("NI", "Nicaragua"), - NETHERLANDS("NL", "Netherlands"), - NORWAY("NO", "Norway"), - NEPAL("NP", "Nepal"), - NAURU("NR", "Nauru"), - NIUE("NU", "Niue"), - NEW_ZEALAND("NZ", "New Zealand"), - OMAN("OM", "Oman"), - PANAMA("PA", "Panama"), - PERU("PE", "Peru"), - FRENCH_POLYNESIA("PF", "French Polynesia"), - PAPUA_NEW_GUINEA("PG", "Papua New Guinea"), - PHILIPPINES("PH", "Philippines"), - PAKISTAN("PK", "Pakistan"), - POLAND("PL", "Poland"), - SAINT_PIERRE_AND_MIQUELON("PM", "Saint Pierre And Miquelon"), - PITCAIRN("PN", "Pitcairn"), - PUERTO_RICO("PR", "Puerto Rico"), - PALESTINE("PS", "Palestine"), - PORTUGAL("PT", "Portugal"), - PALAU("PW", "Palau"), - PARAGUAY("PY", "Paraguay"), - QATAR("QA", "Qatar"), - REUNION("RE", "Reunion"), - ROMANIA("RO", "Romania"), - SERBIA("RS", "Serbia"), - RUSSIA("RU", "Russia"), - RWANDA("RW", "Rwanda"), - SAUDI_ARABIA("SA", "Saudi Arabia"), - SOLOMON_ISLANDS("SB", "Solomon Islands"), - SEYCHELLES("SC", "Seychelles"), - SUDAN("SD", "Sudan"), - SWEDEN("SE", "Sweden"), - SINGAPORE("SG", "Singapore"), - SAINT_HELENA("SH", "Saint Helena"), - SLOVENIA("SI", "Slovenia"), - SVALBARD_AND_JAN_MAYEN("SJ", "Svalbard And Jan Mayen"), - SLOVAKIA("SK", "Slovakia"), - SIERRA_LEONE("SL", "Sierra Leone"), - SAN_MARINO("SM", "San Marino"), - SENEGAL("SN", "Senegal"), - SOMALIA("SO", "Somalia"), - SURINAME("SR", "Suriname"), - SOUTH_SUDAN("SS", "South Sudan"), - SAO_TOME_AND_PRINCIPE("ST", "Sao Tome And Principe"), - EL_SALVADOR("SV", "El Salvador"), - SINT_MAARTEN_DUTCH_PART("SX", "Sint Maarten (Dutch part)"), - SYRIA("SY", "Syria"), - SWAZILAND("SZ", "Swaziland"), - TURKS_AND_CAICOS_ISLANDS("TC", "Turks And Caicos Islands"), - CHAD("TD", "Chad"), - FRENCH_SOUTHERN_TERRITORIES("TF", "French Southern Territories"), - TOGO("TG", "Togo"), - THAILAND("TH", "Thailand"), - TAJIKISTAN("TJ", "Tajikistan"), - TOKELAU("TK", "Tokelau"), - TIMOR_LESTE("TL", "Timor-Leste"), - TURKMENISTAN("TM", "Turkmenistan"), - TUNISIA("TN", "Tunisia"), - TONGA("TO", "Tonga"), - TURKEY("TR", "Turkey"), - TRINIDAD_AND_TOBAGO("TT", "Trinidad and Tobago"), - TUVALU("TV", "Tuvalu"), - TAIWAN("TW", "Taiwan"), - TANZANIA("TZ", "Tanzania"), - UKRAINE("UA", "Ukraine"), - UGANDA("UG", "Uganda"), - UNITED_STATES_MINOR_OUTLYING_ISLANDS("UM", "United States Minor Outlying Islands"), - UNITED_STATES("US", "United States"), - URUGUAY("UY", "Uruguay"), - UZBEKISTAN("UZ", "Uzbekistan"), - VATICAN("VA", "Vatican"), - SAINT_VINCENT_AND_THE_GRENADINES("VC", "Saint Vincent And The Grenadines"), - VENEZUELA("VE", "Venezuela"), - BRITISH_VIRGIN_ISLANDS("VG", "British Virgin Islands"), - U_S__VIRGIN_ISLANDS("VI", "U.S. Virgin Islands"), - VIETNAM("VN", "Vietnam"), - VANUATU("VU", "Vanuatu"), - WALLIS_AND_FUTUNA("WF", "Wallis And Futuna"), - SAMOA("WS", "Samoa"), - YEMEN("YE", "Yemen"), - MAYOTTE("YT", "Mayotte"), - SOUTH_AFRICA("ZA", "South Africa"), - ZAMBIA("ZM", "Zambia"), - ZIMBABWE("ZW", "Zimbabwe"); - - private String isoTag; - private String name; - - Country(String isoTag, String name) { - this.isoTag = isoTag; - this.name = name; - } - - /** - * Gets the name of the country. - * - * @return The name of the country. - */ - public String getCountryName() { - return name; - } - - /** - * Gets the iso tag of the country. - * - * @return The iso tag of the country. - */ - public String getCountryIsoTag() { - return isoTag; - } - - /** - * Gets a country by it's iso tag. - * - * @param isoTag The iso tag of the county. - * @return The country with the given iso tag or null if unknown. - */ - public static Country byIsoTag(String isoTag) { - for (Country country : Country.values()) { - if (country.getCountryIsoTag().equals(isoTag)) { - return country; - } - } - return null; - } - - /** - * Gets a country by a locale. - * - * @param locale The locale. - * @return The country from the giben locale or null if unknown country or - * if the locale does not contain a country. - */ - public static Country byLocale(Locale locale) { - return byIsoTag(locale.getCountry()); - } - - } + // The version of this bStats class + public static final int B_STATS_VERSION = 1; + + // The url to which the data is sent + private static final String URL = "https://bStats.org/submitData"; + + // Should failed requests be logged? + private static boolean logFailedRequests; + + // The uuid of the server + private static String serverUUID; + + // The plugin + private final JavaPlugin plugin; + + // A list with all custom charts + private final List charts = new ArrayList<>(); + + /** + * Class constructor. + * + * @param plugin The plugin which stats should be submitted. + */ + public Metrics(JavaPlugin plugin) { + if (plugin == null) { + throw new IllegalArgumentException("Plugin cannot be null!"); + } + this.plugin = plugin; + + // Get the config file + File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats"); + File configFile = new File(bStatsFolder, "config.yml"); + YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); + + // Check if the config file exists + if (!config.isSet("serverUuid")) { + + // Add default values + config.addDefault("enabled", true); + // Every server gets it's unique random id. + config.addDefault("serverUuid", UUID.randomUUID().toString()); + // Should failed request be logged? + config.addDefault("logFailedRequests", false); + + // Inform the server owners about bStats + config.options().header( + "bStats collects some data for plugin authors like how many servers are using their plugins.\n" + + "To honor their work, you should not disable it.\n" + + "This has nearly no effect on the server performance!\n" + + "Check out https://bStats.org/ to learn more :)") + .copyDefaults(true); + try { + config.save(configFile); + } catch (IOException ignored) { + } + } + + // Load the data + serverUUID = config.getString("serverUuid"); + logFailedRequests = config.getBoolean("logFailedRequests", false); + if (config.getBoolean("enabled", true)) { + boolean found = false; + // Search for all other bStats Metrics classes to see if we are the first one + for (Class service : Bukkit.getServicesManager().getKnownServices()) { + try { + service.getField("B_STATS_VERSION"); // Our identifier :) + found = true; // We aren't the first + break; + } catch (NoSuchFieldException ignored) { + } + } + // Register our service + Bukkit.getServicesManager().register(Metrics.class, this, plugin, ServicePriority.Normal); + if (!found) { + // We are the first! + startSubmitting(); + } + } + } + + /** + * Adds a custom chart. + * + * @param chart The chart to add. + */ + public void addCustomChart(CustomChart chart) { + if (chart == null) { + throw new IllegalArgumentException("Chart cannot be null!"); + } + charts.add(chart); + } + + /** + * Starts the Scheduler which submits our data every 30 minutes. + */ + private void startSubmitting() { + final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags + timer.scheduleAtFixedRate(new TimerTask() { + @Override + public void run() { + if (!plugin.isEnabled()) { // Plugin was disabled + timer.cancel(); + return; + } + // Nevertheless we want our code to run in the Bukkit main thread, so we have to + // use the Bukkit scheduler + // Don't be afraid! The connection to the bStats server is still async, only the + // stats collection is sync ;) + Bukkit.getScheduler().runTask(plugin, new Runnable() { + @Override + public void run() { + submitData(); + } + }); + } + }, 1000 * 60 * 5, 1000 * 60 * 30); + // Submit the data every 30 minutes, first time after 5 minutes to give other + // plugins enough time to start + // WARNING: Changing the frequency has no effect but your plugin WILL be + // blocked/deleted! + // WARNING: Just don't do it! + } + + /** + * Gets the plugin specific data. This method is called using Reflection. + * + * @return The plugin specific data. + */ + public JSONObject getPluginData() { + JSONObject data = new JSONObject(); + + String pluginName = plugin.getDescription().getName(); + String pluginVersion = plugin.getDescription().getVersion(); + + data.put("pluginName", pluginName); // Append the name of the plugin + data.put("pluginVersion", pluginVersion); // Append the version of the plugin + JSONArray customCharts = new JSONArray(); + for (CustomChart customChart : charts) { + // Add the data of the custom charts + JSONObject chart = customChart.getRequestJsonObject(); + if (chart == null) { // If the chart is null, we skip it + continue; + } + customCharts.add(chart); + } + data.put("customCharts", customCharts); + + return data; + } + + /** + * Gets the server specific data. + * + * @return The server specific data. + */ + private JSONObject getServerData() { + // Minecraft specific data + int playerAmount = Bukkit.getOnlinePlayers().size(); + int onlineMode = Bukkit.getOnlineMode() ? 1 : 0; + String bukkitVersion = org.bukkit.Bukkit.getVersion(); + bukkitVersion = bukkitVersion.substring(bukkitVersion.indexOf("MC: ") + 4, bukkitVersion.length() - 1); + + // OS/Java specific data + String javaVersion = System.getProperty("java.version"); + String osName = System.getProperty("os.name"); + String osArch = System.getProperty("os.arch"); + String osVersion = System.getProperty("os.version"); + int coreCount = Runtime.getRuntime().availableProcessors(); + + JSONObject data = new JSONObject(); + + data.put("serverUUID", serverUUID); + + data.put("playerAmount", playerAmount); + data.put("onlineMode", onlineMode); + data.put("bukkitVersion", bukkitVersion); + + data.put("javaVersion", javaVersion); + data.put("osName", osName); + data.put("osArch", osArch); + data.put("osVersion", osVersion); + data.put("coreCount", coreCount); + + return data; + } + + /** + * Collects the data and sends it afterwards. + */ + private void submitData() { + final JSONObject data = getServerData(); + + JSONArray pluginData = new JSONArray(); + // Search for all other bStats Metrics classes to get their plugin data + for (Class service : Bukkit.getServicesManager().getKnownServices()) { + try { + service.getField("B_STATS_VERSION"); // Our identifier :) + } catch (NoSuchFieldException ignored) { + continue; // Continue "searching" + } + // Found one! + try { + pluginData.add(service.getMethod("getPluginData").invoke(Bukkit.getServicesManager().load(service))); + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { + } + } + + data.put("plugins", pluginData); + + // Create a new thread for the connection to the bStats server + new Thread(new Runnable() { + @Override + public void run() { + try { + // Send the data + sendData(data); + } catch (Exception e) { + // Something went wrong! :( + if (logFailedRequests) { + plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), + e); + } + } + } + }).start(); + + } + + /** + * Sends the data to the bStats server. + * + * @param data The data to send. + * @throws Exception If the request failed. + */ + private static void sendData(JSONObject data) throws Exception { + if (data == null) { + throw new IllegalArgumentException("Data cannot be null!"); + } + if (Bukkit.isPrimaryThread()) { + throw new IllegalAccessException("This method must not be called from the main thread!"); + } + HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection(); + + // Compress the data to save bandwidth + byte[] compressedData = compress(data.toString()); + + // Add headers + connection.setRequestMethod("POST"); + connection.addRequestProperty("Accept", "application/json"); + connection.addRequestProperty("Connection", "close"); + connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request + connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); + connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format + connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION); + + // Send data + connection.setDoOutput(true); + DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); + outputStream.write(compressedData); + outputStream.flush(); + outputStream.close(); + + connection.getInputStream().close(); // We don't care about the response - Just send our data :) + } + + /** + * Gzips the given String. + * + * @param str The string to gzip. + * @return The gzipped String. + * @throws IOException If the compression failed. + */ + private static byte[] compress(final String str) throws IOException { + if (str == null) { + return null; + } + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + GZIPOutputStream gzip = new GZIPOutputStream(outputStream); + gzip.write(str.getBytes("UTF-8")); + gzip.close(); + return outputStream.toByteArray(); + } + + /** + * Represents a custom chart. + */ + public static abstract class CustomChart { + + // The id of the chart + protected final String chartId; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + */ + public CustomChart(String chartId) { + if (chartId == null || chartId.isEmpty()) { + throw new IllegalArgumentException("ChartId cannot be null or empty!"); + } + this.chartId = chartId; + } + + protected JSONObject getRequestJsonObject() { + JSONObject chart = new JSONObject(); + chart.put("chartId", chartId); + try { + JSONObject data = getChartData(); + if (data == null) { + // If the data is null we don't send the chart. + return null; + } + chart.put("data", data); + } catch (Throwable t) { + if (logFailedRequests) { + Bukkit.getLogger().log(Level.WARNING, "Failed to get data for custom chart with id " + chartId, t); + } + return null; + } + return chart; + } + + protected abstract JSONObject getChartData(); + + } + + /** + * Represents a custom simple pie. + */ + public static abstract class SimplePie extends CustomChart { + + /** + * Class constructor. + * + * @param chartId The id of the chart. + */ + public SimplePie(String chartId) { + super(chartId); + } + + /** + * Gets the value of the pie. + * + * @return The value of the pie. + */ + public abstract String getValue(); + + @Override + protected JSONObject getChartData() { + JSONObject data = new JSONObject(); + String value = getValue(); + if (value == null || value.isEmpty()) { + // Null = skip the chart + return null; + } + data.put("value", value); + return data; + } + } + + /** + * Represents a custom advanced pie. + */ + public static abstract class AdvancedPie extends CustomChart { + + /** + * Class constructor. + * + * @param chartId The id of the chart. + */ + public AdvancedPie(String chartId) { + super(chartId); + } + + /** + * Gets the values of the pie. + * + * @param valueMap Just an empty map. The only reason it exists is to make your + * life easier. You don't have to create a map yourself! + * @return The values of the pie. + */ + public abstract HashMap getValues(HashMap valueMap); + + @Override + protected JSONObject getChartData() { + JSONObject data = new JSONObject(); + JSONObject values = new JSONObject(); + HashMap map = getValues(new HashMap()); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() == 0) { + continue; // Skip this invalid + } + allSkipped = false; + values.put(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + data.put("values", values); + return data; + } + } + + /** + * Represents a custom single line chart. + */ + public static abstract class SingleLineChart extends CustomChart { + + /** + * Class constructor. + * + * @param chartId The id of the chart. + */ + public SingleLineChart(String chartId) { + super(chartId); + } + + /** + * Gets the value of the chart. + * + * @return The value of the chart. + */ + public abstract int getValue(); + + @Override + protected JSONObject getChartData() { + JSONObject data = new JSONObject(); + int value = getValue(); + if (value == 0) { + // Null = skip the chart + return null; + } + data.put("value", value); + return data; + } + + } + + /** + * Represents a custom multi line chart. + */ + public static abstract class MultiLineChart extends CustomChart { + + /** + * Class constructor. + * + * @param chartId The id of the chart. + */ + public MultiLineChart(String chartId) { + super(chartId); + } + + /** + * Gets the values of the chart. + * + * @param valueMap Just an empty map. The only reason it exists is to make your + * life easier. You don't have to create a map yourself! + * @return The values of the chart. + */ + public abstract HashMap getValues(HashMap valueMap); + + @Override + protected JSONObject getChartData() { + JSONObject data = new JSONObject(); + JSONObject values = new JSONObject(); + HashMap map = getValues(new HashMap()); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() == 0) { + continue; // Skip this invalid + } + allSkipped = false; + values.put(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + data.put("values", values); + return data; + } + + } + + /** + * Represents a custom simple bar chart. + */ + public static abstract class SimpleBarChart extends CustomChart { + + /** + * Class constructor. + * + * @param chartId The id of the chart. + */ + public SimpleBarChart(String chartId) { + super(chartId); + } + + /** + * Gets the value of the chart. + * + * @param valueMap Just an empty map. The only reason it exists is to make your + * life easier. You don't have to create a map yourself! + * @return The value of the chart. + */ + public abstract HashMap getValues(HashMap valueMap); + + @Override + protected JSONObject getChartData() { + JSONObject data = new JSONObject(); + JSONObject values = new JSONObject(); + HashMap map = getValues(new HashMap()); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + for (Map.Entry entry : map.entrySet()) { + JSONArray categoryValues = new JSONArray(); + categoryValues.add(entry.getValue()); + values.put(entry.getKey(), categoryValues); + } + data.put("values", values); + return data; + } + + } + + /** + * Represents a custom advanced bar chart. + */ + public static abstract class AdvancedBarChart extends CustomChart { + + /** + * Class constructor. + * + * @param chartId The id of the chart. + */ + public AdvancedBarChart(String chartId) { + super(chartId); + } + + /** + * Gets the value of the chart. + * + * @param valueMap Just an empty map. The only reason it exists is to make your + * life easier. You don't have to create a map yourself! + * @return The value of the chart. + */ + public abstract HashMap getValues(HashMap valueMap); + + @Override + protected JSONObject getChartData() { + JSONObject data = new JSONObject(); + JSONObject values = new JSONObject(); + HashMap map = getValues(new HashMap()); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue().length == 0) { + continue; // Skip this invalid + } + allSkipped = false; + JSONArray categoryValues = new JSONArray(); + for (int categoryValue : entry.getValue()) { + categoryValues.add(categoryValue); + } + values.put(entry.getKey(), categoryValues); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + data.put("values", values); + return data; + } + + } + + /** + * Represents a custom simple map chart. + */ + public static abstract class SimpleMapChart extends CustomChart { + + /** + * Class constructor. + * + * @param chartId The id of the chart. + */ + public SimpleMapChart(String chartId) { + super(chartId); + } + + /** + * Gets the value of the chart. + * + * @return The value of the chart. + */ + public abstract Country getValue(); + + @Override + protected JSONObject getChartData() { + JSONObject data = new JSONObject(); + Country value = getValue(); + + if (value == null) { + // Null = skip the chart + return null; + } + data.put("value", value.getCountryIsoTag()); + return data; + } + + } + + /** + * Represents a custom advanced map chart. + */ + public static abstract class AdvancedMapChart extends CustomChart { + + /** + * Class constructor. + * + * @param chartId The id of the chart. + */ + public AdvancedMapChart(String chartId) { + super(chartId); + } + + /** + * Gets the value of the chart. + * + * @param valueMap Just an empty map. The only reason it exists is to make your + * life easier. You don't have to create a map yourself! + * @return The value of the chart. + */ + public abstract HashMap getValues(HashMap valueMap); + + @Override + protected JSONObject getChartData() { + JSONObject data = new JSONObject(); + JSONObject values = new JSONObject(); + HashMap map = getValues(new HashMap()); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() == 0) { + continue; // Skip this invalid + } + allSkipped = false; + values.put(entry.getKey().getCountryIsoTag(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + data.put("values", values); + return data; + } + + } + + /** + * A enum which is used for custom maps. + */ + public enum Country { + + /** + * bStats will use the country of the server. + */ + AUTO_DETECT("AUTO", "Auto Detected"), + + ANDORRA("AD", "Andorra"), UNITED_ARAB_EMIRATES("AE", "United Arab Emirates"), AFGHANISTAN("AF", "Afghanistan"), + ANTIGUA_AND_BARBUDA("AG", "Antigua and Barbuda"), ANGUILLA("AI", "Anguilla"), ALBANIA("AL", "Albania"), + ARMENIA("AM", "Armenia"), NETHERLANDS_ANTILLES("AN", "Netherlands Antilles"), ANGOLA("AO", "Angola"), + ANTARCTICA("AQ", "Antarctica"), ARGENTINA("AR", "Argentina"), AMERICAN_SAMOA("AS", "American Samoa"), + AUSTRIA("AT", "Austria"), AUSTRALIA("AU", "Australia"), ARUBA("AW", "Aruba"), + ÅLAND_ISLANDS("AX", "Åland Islands"), AZERBAIJAN("AZ", "Azerbaijan"), + BOSNIA_AND_HERZEGOVINA("BA", "Bosnia and Herzegovina"), BARBADOS("BB", "Barbados"), + BANGLADESH("BD", "Bangladesh"), BELGIUM("BE", "Belgium"), BURKINA_FASO("BF", "Burkina Faso"), + BULGARIA("BG", "Bulgaria"), BAHRAIN("BH", "Bahrain"), BURUNDI("BI", "Burundi"), BENIN("BJ", "Benin"), + SAINT_BARTHÉLEMY("BL", "Saint Barthélemy"), BERMUDA("BM", "Bermuda"), BRUNEI("BN", "Brunei"), + BOLIVIA("BO", "Bolivia"), BONAIRE_SINT_EUSTATIUS_AND_SABA("BQ", "Bonaire, Sint Eustatius and Saba"), + BRAZIL("BR", "Brazil"), BAHAMAS("BS", "Bahamas"), BHUTAN("BT", "Bhutan"), BOUVET_ISLAND("BV", "Bouvet Island"), + BOTSWANA("BW", "Botswana"), BELARUS("BY", "Belarus"), BELIZE("BZ", "Belize"), CANADA("CA", "Canada"), + COCOS_ISLANDS("CC", "Cocos Islands"), + THE_DEMOCRATIC_REPUBLIC_OF_CONGO("CD", "The Democratic Republic Of Congo"), + CENTRAL_AFRICAN_REPUBLIC("CF", "Central African Republic"), CONGO("CG", "Congo"), + SWITZERLAND("CH", "Switzerland"), CÔTE_D_IVOIRE("CI", "Côte d'Ivoire"), COOK_ISLANDS("CK", "Cook Islands"), + CHILE("CL", "Chile"), CAMEROON("CM", "Cameroon"), CHINA("CN", "China"), COLOMBIA("CO", "Colombia"), + COSTA_RICA("CR", "Costa Rica"), CUBA("CU", "Cuba"), CAPE_VERDE("CV", "Cape Verde"), CURAÇAO("CW", "Curaçao"), + CHRISTMAS_ISLAND("CX", "Christmas Island"), CYPRUS("CY", "Cyprus"), CZECH_REPUBLIC("CZ", "Czech Republic"), + GERMANY("DE", "Germany"), DJIBOUTI("DJ", "Djibouti"), DENMARK("DK", "Denmark"), DOMINICA("DM", "Dominica"), + DOMINICAN_REPUBLIC("DO", "Dominican Republic"), ALGERIA("DZ", "Algeria"), ECUADOR("EC", "Ecuador"), + ESTONIA("EE", "Estonia"), EGYPT("EG", "Egypt"), WESTERN_SAHARA("EH", "Western Sahara"), + ERITREA("ER", "Eritrea"), SPAIN("ES", "Spain"), ETHIOPIA("ET", "Ethiopia"), FINLAND("FI", "Finland"), + FIJI("FJ", "Fiji"), FALKLAND_ISLANDS("FK", "Falkland Islands"), MICRONESIA("FM", "Micronesia"), + FAROE_ISLANDS("FO", "Faroe Islands"), FRANCE("FR", "France"), GABON("GA", "Gabon"), + UNITED_KINGDOM("GB", "United Kingdom"), GRENADA("GD", "Grenada"), GEORGIA("GE", "Georgia"), + FRENCH_GUIANA("GF", "French Guiana"), GUERNSEY("GG", "Guernsey"), GHANA("GH", "Ghana"), + GIBRALTAR("GI", "Gibraltar"), GREENLAND("GL", "Greenland"), GAMBIA("GM", "Gambia"), GUINEA("GN", "Guinea"), + GUADELOUPE("GP", "Guadeloupe"), EQUATORIAL_GUINEA("GQ", "Equatorial Guinea"), GREECE("GR", "Greece"), + SOUTH_GEORGIA_AND_THE_SOUTH_SANDWICH_ISLANDS("GS", "South Georgia And The South Sandwich Islands"), + GUATEMALA("GT", "Guatemala"), GUAM("GU", "Guam"), GUINEA_BISSAU("GW", "Guinea-Bissau"), GUYANA("GY", "Guyana"), + HONG_KONG("HK", "Hong Kong"), HEARD_ISLAND_AND_MCDONALD_ISLANDS("HM", "Heard Island And McDonald Islands"), + HONDURAS("HN", "Honduras"), CROATIA("HR", "Croatia"), HAITI("HT", "Haiti"), HUNGARY("HU", "Hungary"), + INDONESIA("ID", "Indonesia"), IRELAND("IE", "Ireland"), ISRAEL("IL", "Israel"), + ISLE_OF_MAN("IM", "Isle Of Man"), INDIA("IN", "India"), + BRITISH_INDIAN_OCEAN_TERRITORY("IO", "British Indian Ocean Territory"), IRAQ("IQ", "Iraq"), IRAN("IR", "Iran"), + ICELAND("IS", "Iceland"), ITALY("IT", "Italy"), JERSEY("JE", "Jersey"), JAMAICA("JM", "Jamaica"), + JORDAN("JO", "Jordan"), JAPAN("JP", "Japan"), KENYA("KE", "Kenya"), KYRGYZSTAN("KG", "Kyrgyzstan"), + CAMBODIA("KH", "Cambodia"), KIRIBATI("KI", "Kiribati"), COMOROS("KM", "Comoros"), + SAINT_KITTS_AND_NEVIS("KN", "Saint Kitts And Nevis"), NORTH_KOREA("KP", "North Korea"), + SOUTH_KOREA("KR", "South Korea"), KUWAIT("KW", "Kuwait"), CAYMAN_ISLANDS("KY", "Cayman Islands"), + KAZAKHSTAN("KZ", "Kazakhstan"), LAOS("LA", "Laos"), LEBANON("LB", "Lebanon"), SAINT_LUCIA("LC", "Saint Lucia"), + LIECHTENSTEIN("LI", "Liechtenstein"), SRI_LANKA("LK", "Sri Lanka"), LIBERIA("LR", "Liberia"), + LESOTHO("LS", "Lesotho"), LITHUANIA("LT", "Lithuania"), LUXEMBOURG("LU", "Luxembourg"), LATVIA("LV", "Latvia"), + LIBYA("LY", "Libya"), MOROCCO("MA", "Morocco"), MONACO("MC", "Monaco"), MOLDOVA("MD", "Moldova"), + MONTENEGRO("ME", "Montenegro"), SAINT_MARTIN("MF", "Saint Martin"), MADAGASCAR("MG", "Madagascar"), + MARSHALL_ISLANDS("MH", "Marshall Islands"), MACEDONIA("MK", "Macedonia"), MALI("ML", "Mali"), + MYANMAR("MM", "Myanmar"), MONGOLIA("MN", "Mongolia"), MACAO("MO", "Macao"), + NORTHERN_MARIANA_ISLANDS("MP", "Northern Mariana Islands"), MARTINIQUE("MQ", "Martinique"), + MAURITANIA("MR", "Mauritania"), MONTSERRAT("MS", "Montserrat"), MALTA("MT", "Malta"), + MAURITIUS("MU", "Mauritius"), MALDIVES("MV", "Maldives"), MALAWI("MW", "Malawi"), MEXICO("MX", "Mexico"), + MALAYSIA("MY", "Malaysia"), MOZAMBIQUE("MZ", "Mozambique"), NAMIBIA("NA", "Namibia"), + NEW_CALEDONIA("NC", "New Caledonia"), NIGER("NE", "Niger"), NORFOLK_ISLAND("NF", "Norfolk Island"), + NIGERIA("NG", "Nigeria"), NICARAGUA("NI", "Nicaragua"), NETHERLANDS("NL", "Netherlands"), + NORWAY("NO", "Norway"), NEPAL("NP", "Nepal"), NAURU("NR", "Nauru"), NIUE("NU", "Niue"), + NEW_ZEALAND("NZ", "New Zealand"), OMAN("OM", "Oman"), PANAMA("PA", "Panama"), PERU("PE", "Peru"), + FRENCH_POLYNESIA("PF", "French Polynesia"), PAPUA_NEW_GUINEA("PG", "Papua New Guinea"), + PHILIPPINES("PH", "Philippines"), PAKISTAN("PK", "Pakistan"), POLAND("PL", "Poland"), + SAINT_PIERRE_AND_MIQUELON("PM", "Saint Pierre And Miquelon"), PITCAIRN("PN", "Pitcairn"), + PUERTO_RICO("PR", "Puerto Rico"), PALESTINE("PS", "Palestine"), PORTUGAL("PT", "Portugal"), + PALAU("PW", "Palau"), PARAGUAY("PY", "Paraguay"), QATAR("QA", "Qatar"), REUNION("RE", "Reunion"), + ROMANIA("RO", "Romania"), SERBIA("RS", "Serbia"), RUSSIA("RU", "Russia"), RWANDA("RW", "Rwanda"), + SAUDI_ARABIA("SA", "Saudi Arabia"), SOLOMON_ISLANDS("SB", "Solomon Islands"), SEYCHELLES("SC", "Seychelles"), + SUDAN("SD", "Sudan"), SWEDEN("SE", "Sweden"), SINGAPORE("SG", "Singapore"), SAINT_HELENA("SH", "Saint Helena"), + SLOVENIA("SI", "Slovenia"), SVALBARD_AND_JAN_MAYEN("SJ", "Svalbard And Jan Mayen"), SLOVAKIA("SK", "Slovakia"), + SIERRA_LEONE("SL", "Sierra Leone"), SAN_MARINO("SM", "San Marino"), SENEGAL("SN", "Senegal"), + SOMALIA("SO", "Somalia"), SURINAME("SR", "Suriname"), SOUTH_SUDAN("SS", "South Sudan"), + SAO_TOME_AND_PRINCIPE("ST", "Sao Tome And Principe"), EL_SALVADOR("SV", "El Salvador"), + SINT_MAARTEN_DUTCH_PART("SX", "Sint Maarten (Dutch part)"), SYRIA("SY", "Syria"), SWAZILAND("SZ", "Swaziland"), + TURKS_AND_CAICOS_ISLANDS("TC", "Turks And Caicos Islands"), CHAD("TD", "Chad"), + FRENCH_SOUTHERN_TERRITORIES("TF", "French Southern Territories"), TOGO("TG", "Togo"), + THAILAND("TH", "Thailand"), TAJIKISTAN("TJ", "Tajikistan"), TOKELAU("TK", "Tokelau"), + TIMOR_LESTE("TL", "Timor-Leste"), TURKMENISTAN("TM", "Turkmenistan"), TUNISIA("TN", "Tunisia"), + TONGA("TO", "Tonga"), TURKEY("TR", "Turkey"), TRINIDAD_AND_TOBAGO("TT", "Trinidad and Tobago"), + TUVALU("TV", "Tuvalu"), TAIWAN("TW", "Taiwan"), TANZANIA("TZ", "Tanzania"), UKRAINE("UA", "Ukraine"), + UGANDA("UG", "Uganda"), UNITED_STATES_MINOR_OUTLYING_ISLANDS("UM", "United States Minor Outlying Islands"), + UNITED_STATES("US", "United States"), URUGUAY("UY", "Uruguay"), UZBEKISTAN("UZ", "Uzbekistan"), + VATICAN("VA", "Vatican"), SAINT_VINCENT_AND_THE_GRENADINES("VC", "Saint Vincent And The Grenadines"), + VENEZUELA("VE", "Venezuela"), BRITISH_VIRGIN_ISLANDS("VG", "British Virgin Islands"), + U_S__VIRGIN_ISLANDS("VI", "U.S. Virgin Islands"), VIETNAM("VN", "Vietnam"), VANUATU("VU", "Vanuatu"), + WALLIS_AND_FUTUNA("WF", "Wallis And Futuna"), SAMOA("WS", "Samoa"), YEMEN("YE", "Yemen"), + MAYOTTE("YT", "Mayotte"), SOUTH_AFRICA("ZA", "South Africa"), ZAMBIA("ZM", "Zambia"), + ZIMBABWE("ZW", "Zimbabwe"); + + private String isoTag; + private String name; + + Country(String isoTag, String name) { + this.isoTag = isoTag; + this.name = name; + } + + /** + * Gets the name of the country. + * + * @return The name of the country. + */ + public String getCountryName() { + return name; + } + + /** + * Gets the iso tag of the country. + * + * @return The iso tag of the country. + */ + public String getCountryIsoTag() { + return isoTag; + } + + /** + * Gets a country by it's iso tag. + * + * @param isoTag The iso tag of the county. + * @return The country with the given iso tag or null if unknown. + */ + public static Country byIsoTag(String isoTag) { + for (Country country : Country.values()) { + if (country.getCountryIsoTag().equals(isoTag)) { + return country; + } + } + return null; + } + + /** + * Gets a country by a locale. + * + * @param locale The locale. + * @return The country from the giben locale or null if unknown + * country or if the locale does not contain a country. + */ + public static Country byLocale(Locale locale) { + return byIsoTag(locale.getCountry()); + } + + } } \ No newline at end of file diff --git a/src/main/java/com/rammelkast/anticheatreloaded/util/BlockHardness.java b/src/main/java/com/rammelkast/anticheatreloaded/util/BlockHardness.java index d0c6a57..1b6ceb4 100644 --- a/src/main/java/com/rammelkast/anticheatreloaded/util/BlockHardness.java +++ b/src/main/java/com/rammelkast/anticheatreloaded/util/BlockHardness.java @@ -22,205 +22,65 @@ package com.rammelkast.anticheatreloaded.util; import org.bukkit.Material; public enum BlockHardness { - STONE(1.50D), - GRASS(0.60D), - DIRT(0.50D), - COBBLESTONE(2.00D), - WOOD(2.00D), - SAPLING(0.00D), - WATER(100.00D), - STATIONARY_WATER(100.00D), - LAVA(0.00D), - STATIONARY_LAVA(100.00D), - SAND(0.50D), - GRAVEL(0.60D), - GOLD_ORE(3.00D), - IRON_ORE(3.00D), - COAL_ORE(3.00D), - LOG(2.00D), - LOG_2(2.00D), - LEAVES(0.20D), - LEAVES_2(0.20D), - SPONGE(0.60D), - GLASS(0.30D), - LAPIS_ORE(3.00D), - LAPIS_BLOCK(3.00D), - DISPENSER(3.50D), - DROPPER(3.50D), - SANDSTONE(0.80D), - NOTE_BLOCK(0.80D), - BED(0.20D), - RAILS(0.70D), - DETECTOR_RAIL(0.70D), - POWERED_RAIL(0.70D), - ACTIVATOR_RAIL(0.70D), - WEB(4.00D), - LONG_GRASS(0.00D), - DOUBLE_PLANT(0.00D), - DEAD_BUSH(0.00D), - WOOL(0.80D), - YELLOW_FLOWER(0.00D), - RED_ROSE(0.00D), - BROWN_MUSHROOM(0.00D), - RED_MUSHROOM(0.00D), - GOLD_BLOCK(3.00D), - IRON_BLOCK(5.00D), - DOUBLE_STEP(2.00D), - STEP(2.00D), - BRICK(2.00D), - TNT(0.00D), - BOOKSHELF(1.50D), - MOSSY_COBBLESTONE(2.00D), - OBSIDIAN(50.00D), - TORCH(0.00D), - FIRE(0.00D), - MOB_SPAWNER(5.00D), - CHEST(2.50D), - TRAPPED_CHEST(2.50D), - REDSTONE_WIRE(0.00D), - DIAMOND_ORE(3.00D), - DIAMOND_BLOCK(5.00D), - WORKBENCH(2.50D), - SOIL(0.60D), - FURNACE(3.50D), - BURNING_FURNACE(3.50D), - WOODEN_DOOR(3.00D), - LADDER(0.40D), - LEVER(0.50D), - IRON_DOOR_BLOCK(5.00D), - HOPPER(2.00D), - STONE_PLATE(0.50D), - WOOD_PLATE(0.50D), - GOLD_PLATE(0.50D), - IRON_PLATE(0.50D), - QUARTZ_BLOCK(0.80D), - QUARTZ_ORE(3.00D), - REDSTONE_BLOCK(5.00D), - REDSTONE_ORE(3.00D), - GLOWING_REDSTONE_ORE(3.00D), - REDSTONE_TORCH_OFF(0.00D), - REDSTONE_TORCH_ON(0.00D), - REDSTONE_COMPARATOR_OFF(0.00D), - REDSTONE_COMPARATOR_ON(0.00D), - DAYLIGHT_DETECTOR(0.20D), - STONE_BUTTON(0.50D), - SNOW(0.10D), - ICE(0.50D), - PACKED_ICE(0.50D), - SNOW_BLOCK(0.20D), - CACTUS(0.40D), - CLAY(0.60D), - HARD_CLAY(1.25D), - STAINED_CLAY(1.25D), - SUGAR_CANE_BLOCK(0.00D), - JUKEBOX(2.00D), - FENCE(2.00D), - NETHERRACK(0.40D), - SOUL_SAND(0.50D), - GLOWSTONE(0.30D), - PORTAL(-1.00D), - CAKE_BLOCK(0.50D), - LOCKED_CHEST(0.00D), - TRAP_DOOR(3.00D), - MONSTER_EGGS(0.750D), - SMOOTH_BRICK(1.50D), - IRON_FENCE(5.00D), - THIN_GLASS(0.30D), - STAINED_GLASS(0.30D), - STAINED_GLASS_PANE(0.30D), - PUMPKIN_STEM(0.00D), - MELON_STEM(0.00D), - VINE(0.20D), - FENCE_GATE(2.00D), - MYCEL(0.60D), - WATER_LILY(0.00D), - NETHER_BRICK(2.00D), - NETHER_FENCE(2.00D), - ENCHANTMENT_TABLE(5.00D), - BREWING_STAND(0.50D), - CAULDRON(2.00D), - ENDER_PORTAL(-1.00D), - ENDER_PORTAL_FRAME(-1.00D), - DRAGON_EGG(3.00D), - REDSTONE_LAMP_OFF(0.30D), - REDSTONE_LAMP_ON(0.30D), - WOOD_DOUBLE_STEP(2.00D), - WOOD_STEP(2.00D), - COCOA(0.20D), - EMERALD_ORE(3.00D), - ENDER_CHEST(22.50D), - EMERALD_BLOCK(5.00D), - FLOWER_POT(0.00D), - WOOD_BUTTON(0.50D), - ANVIL(5.00D), - HUGE_MUSHROOM_1(0.20D), - HUGE_MUSHROOM_2(0.20D), - BED_BLOCK(0.20D), - WOOD_STAIRS(2.00D), - COBBLESTONE_STAIRS(2.00D), - BRICK_STAIRS(2.00D), - SMOOTH_STAIRS(1.50D), - NETHER_BRICK_STAIRS(2.00D), - SPRUCE_WOOD_STAIRS(2.00D), - BIRCH_WOOD_STAIRS(2.00D), - JUNGLE_WOOD_STAIRS(2.00D), - DARK_OAK_STAIRS(2.00D), - ACACIA_STAIRS(2.00D), - QUARTZ_STAIRS(0.80D), - SANDSTONE_STAIRS(0.80D), - COMMAND(0.00D), - BEACON(3.00D), - COBBLE_WALL(2.00D), - CROPS(0.00D), - CARROT(0.00D), - POTATO(0.00D), - SKULL(1.00D), - NETHER_WARTS(0.00D), - SIGN_POST(1.00D), - WALL_SIGN(1.00D), - PUMPKIN(1.00D), - JACK_O_LANTERN(1.00D), - DIODE_BLOCK_ON(0.00D), - DIODE_BLOCK_OFF(0.00D), - MELON_BLOCK(1.00D), - ENDER_STONE(3.00D), - TRIPWIRE(0.00D), - TRIPWIRE_HOOK(0.00D), - HAY_BLOCK(0.50D), - CARPET(0.10D), - COAL_BLOCK(5.00D), - PISTON_BASE(0.70D), - PISTON_EXTENSION(0.70D), - PISTON_MOVING_PIECE(0.70D), - PISTON_STICKY_BASE(0.70D); + STONE(1.50D), GRASS(0.60D), DIRT(0.50D), COBBLESTONE(2.00D), WOOD(2.00D), SAPLING(0.00D), WATER(100.00D), + STATIONARY_WATER(100.00D), LAVA(0.00D), STATIONARY_LAVA(100.00D), SAND(0.50D), GRAVEL(0.60D), GOLD_ORE(3.00D), + IRON_ORE(3.00D), COAL_ORE(3.00D), LOG(2.00D), LOG_2(2.00D), LEAVES(0.20D), LEAVES_2(0.20D), SPONGE(0.60D), + GLASS(0.30D), LAPIS_ORE(3.00D), LAPIS_BLOCK(3.00D), DISPENSER(3.50D), DROPPER(3.50D), SANDSTONE(0.80D), + NOTE_BLOCK(0.80D), BED(0.20D), RAILS(0.70D), DETECTOR_RAIL(0.70D), POWERED_RAIL(0.70D), ACTIVATOR_RAIL(0.70D), + WEB(4.00D), LONG_GRASS(0.00D), DOUBLE_PLANT(0.00D), DEAD_BUSH(0.00D), WOOL(0.80D), YELLOW_FLOWER(0.00D), + RED_ROSE(0.00D), BROWN_MUSHROOM(0.00D), RED_MUSHROOM(0.00D), GOLD_BLOCK(3.00D), IRON_BLOCK(5.00D), + DOUBLE_STEP(2.00D), STEP(2.00D), BRICK(2.00D), TNT(0.00D), BOOKSHELF(1.50D), MOSSY_COBBLESTONE(2.00D), + OBSIDIAN(50.00D), TORCH(0.00D), FIRE(0.00D), MOB_SPAWNER(5.00D), CHEST(2.50D), TRAPPED_CHEST(2.50D), + REDSTONE_WIRE(0.00D), DIAMOND_ORE(3.00D), DIAMOND_BLOCK(5.00D), WORKBENCH(2.50D), SOIL(0.60D), FURNACE(3.50D), + BURNING_FURNACE(3.50D), WOODEN_DOOR(3.00D), LADDER(0.40D), LEVER(0.50D), IRON_DOOR_BLOCK(5.00D), HOPPER(2.00D), + STONE_PLATE(0.50D), WOOD_PLATE(0.50D), GOLD_PLATE(0.50D), IRON_PLATE(0.50D), QUARTZ_BLOCK(0.80D), QUARTZ_ORE(3.00D), + REDSTONE_BLOCK(5.00D), REDSTONE_ORE(3.00D), GLOWING_REDSTONE_ORE(3.00D), REDSTONE_TORCH_OFF(0.00D), + REDSTONE_TORCH_ON(0.00D), REDSTONE_COMPARATOR_OFF(0.00D), REDSTONE_COMPARATOR_ON(0.00D), DAYLIGHT_DETECTOR(0.20D), + STONE_BUTTON(0.50D), SNOW(0.10D), ICE(0.50D), PACKED_ICE(0.50D), SNOW_BLOCK(0.20D), CACTUS(0.40D), CLAY(0.60D), + HARD_CLAY(1.25D), STAINED_CLAY(1.25D), SUGAR_CANE_BLOCK(0.00D), JUKEBOX(2.00D), FENCE(2.00D), NETHERRACK(0.40D), + SOUL_SAND(0.50D), GLOWSTONE(0.30D), PORTAL(-1.00D), CAKE_BLOCK(0.50D), LOCKED_CHEST(0.00D), TRAP_DOOR(3.00D), + MONSTER_EGGS(0.750D), SMOOTH_BRICK(1.50D), IRON_FENCE(5.00D), THIN_GLASS(0.30D), STAINED_GLASS(0.30D), + STAINED_GLASS_PANE(0.30D), PUMPKIN_STEM(0.00D), MELON_STEM(0.00D), VINE(0.20D), FENCE_GATE(2.00D), MYCEL(0.60D), + WATER_LILY(0.00D), NETHER_BRICK(2.00D), NETHER_FENCE(2.00D), ENCHANTMENT_TABLE(5.00D), BREWING_STAND(0.50D), + CAULDRON(2.00D), ENDER_PORTAL(-1.00D), ENDER_PORTAL_FRAME(-1.00D), DRAGON_EGG(3.00D), REDSTONE_LAMP_OFF(0.30D), + REDSTONE_LAMP_ON(0.30D), WOOD_DOUBLE_STEP(2.00D), WOOD_STEP(2.00D), COCOA(0.20D), EMERALD_ORE(3.00D), + ENDER_CHEST(22.50D), EMERALD_BLOCK(5.00D), FLOWER_POT(0.00D), WOOD_BUTTON(0.50D), ANVIL(5.00D), + HUGE_MUSHROOM_1(0.20D), HUGE_MUSHROOM_2(0.20D), BED_BLOCK(0.20D), WOOD_STAIRS(2.00D), COBBLESTONE_STAIRS(2.00D), + BRICK_STAIRS(2.00D), SMOOTH_STAIRS(1.50D), NETHER_BRICK_STAIRS(2.00D), SPRUCE_WOOD_STAIRS(2.00D), + BIRCH_WOOD_STAIRS(2.00D), JUNGLE_WOOD_STAIRS(2.00D), DARK_OAK_STAIRS(2.00D), ACACIA_STAIRS(2.00D), + QUARTZ_STAIRS(0.80D), SANDSTONE_STAIRS(0.80D), COMMAND(0.00D), BEACON(3.00D), COBBLE_WALL(2.00D), CROPS(0.00D), + CARROT(0.00D), POTATO(0.00D), SKULL(1.00D), NETHER_WARTS(0.00D), SIGN_POST(1.00D), WALL_SIGN(1.00D), PUMPKIN(1.00D), + JACK_O_LANTERN(1.00D), DIODE_BLOCK_ON(0.00D), DIODE_BLOCK_OFF(0.00D), MELON_BLOCK(1.00D), ENDER_STONE(3.00D), + TRIPWIRE(0.00D), TRIPWIRE_HOOK(0.00D), HAY_BLOCK(0.50D), CARPET(0.10D), COAL_BLOCK(5.00D), PISTON_BASE(0.70D), + PISTON_EXTENSION(0.70D), PISTON_MOVING_PIECE(0.70D), PISTON_STICKY_BASE(0.70D); - Material mat; - double hardness; + Material mat; + double hardness; - BlockHardness(double hard) { - mat = Material.getMaterial(name()); - hardness = hard; - } + BlockHardness(double hard) { + mat = Material.getMaterial(name()); + hardness = hard; + } - public static double getBlockHardness(Material m) { - try { - BlockHardness h = getHardness(m); - return h == null ? 0D : h.hardness; - }catch(Exception e) { - return 0D; - } - } + public static double getBlockHardness(Material m) { + try { + BlockHardness h = getHardness(m); + return h == null ? 0D : h.hardness; + } catch (Exception e) { + return 0D; + } + } - public static boolean hasBlockHardness(Material m) { - return getHardness(m) != null; - } + public static boolean hasBlockHardness(Material m) { + return getHardness(m) != null; + } - public static BlockHardness getHardness(Material m) { - for (BlockHardness e : BlockHardness.values()) { - if (e.mat.equals(m)) { - return e; - } - } - return null; - } + public static BlockHardness getHardness(Material m) { + for (BlockHardness e : BlockHardness.values()) { + if (e.mat.equals(m)) { + return e; + } + } + return null; + } } diff --git a/src/main/java/com/rammelkast/anticheatreloaded/util/Distance.java b/src/main/java/com/rammelkast/anticheatreloaded/util/Distance.java index 03e788a..dd7ea31 100644 --- a/src/main/java/com/rammelkast/anticheatreloaded/util/Distance.java +++ b/src/main/java/com/rammelkast/anticheatreloaded/util/Distance.java @@ -22,39 +22,39 @@ package com.rammelkast.anticheatreloaded.util; import org.bukkit.Location; public class Distance { - private final double l1Y; - private final double l2Y; + private final double l1Y; + private final double l2Y; - private final double XDiff; - private final double YDiff; - private final double ZDiff; + private final double XDiff; + private final double YDiff; + private final double ZDiff; - public Distance(Location from, Location to) { - l1Y = to.getY(); - l2Y = from.getY(); + public Distance(Location from, Location to) { + l1Y = to.getY(); + l2Y = from.getY(); - XDiff = Math.abs(to.getX() - from.getX()); - ZDiff = Math.abs(to.getZ() - from.getZ()); - YDiff = Math.abs(l1Y - l2Y); - } + XDiff = Math.abs(to.getX() - from.getX()); + ZDiff = Math.abs(to.getZ() - from.getZ()); + YDiff = Math.abs(l1Y - l2Y); + } - public double fromY() { - return l2Y; - } + public double fromY() { + return l2Y; + } - public double toY() { - return l1Y; - } + public double toY() { + return l1Y; + } - public double getXDifference() { - return XDiff; - } + public double getXDifference() { + return XDiff; + } - public double getZDifference() { - return ZDiff; - } + public double getZDifference() { + return ZDiff; + } - public double getYDifference() { - return YDiff; - } + public double getYDifference() { + return YDiff; + } } diff --git a/src/main/java/com/rammelkast/anticheatreloaded/util/FileFormatter.java b/src/main/java/com/rammelkast/anticheatreloaded/util/FileFormatter.java index 37f3d4e..78bd59f 100644 --- a/src/main/java/com/rammelkast/anticheatreloaded/util/FileFormatter.java +++ b/src/main/java/com/rammelkast/anticheatreloaded/util/FileFormatter.java @@ -26,12 +26,14 @@ import java.util.logging.Formatter; import java.util.logging.LogRecord; public class FileFormatter extends Formatter { - private static final DateFormat FORMAT = new SimpleDateFormat("h:mm:ss"); - private static final String LINE_SEP = System.getProperty("line.separator"); + private static final DateFormat FORMAT = new SimpleDateFormat("h:mm:ss"); + private static final String LINE_SEP = System.getProperty("line.separator"); - @Override - 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); - return output.toString(); - } + @Override + 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); + return output.toString(); + } } diff --git a/src/main/java/com/rammelkast/anticheatreloaded/util/Group.java b/src/main/java/com/rammelkast/anticheatreloaded/util/Group.java index 5dd6ebe..11fefef 100644 --- a/src/main/java/com/rammelkast/anticheatreloaded/util/Group.java +++ b/src/main/java/com/rammelkast/anticheatreloaded/util/Group.java @@ -29,62 +29,67 @@ import java.util.List; public class Group { - private String name; - private int level; - private ChatColor color = ChatColor.RED; - private List actions = new ArrayList(); + private String name; + private int level; + private ChatColor color = ChatColor.RED; + private List actions = new ArrayList(); - public Group(String name, int level, String color, List actions) { + public Group(String name, int level, String color, List actions) { - this.name = name; - this.level = level; - this.actions = actions; + this.name = name; + this.level = level; + this.actions = actions; - ChatColor c = ChatColor.valueOf(color); - if (c == null) { - AntiCheatReloaded.getPlugin().getLogger().warning("Event '" + name + "' was initialized with the color '" + color + "' which is invalid."); - AntiCheatReloaded.getPlugin().getLogger().warning("This event will not run properly. See http://jd.bukkit.org/apidocs/org/bukkit/ChatColor.html#enum_constant_summary for a list of valid colors"); - } else { - this.color = c; - } - } - public String getName() { - return name; - } + ChatColor c = ChatColor.valueOf(color); + if (c == null) { + AntiCheatReloaded.getPlugin().getLogger() + .warning("Event '" + name + "' was initialized with the color '" + color + "' which is invalid."); + AntiCheatReloaded.getPlugin().getLogger().warning( + "This event will not run properly. See http://jd.bukkit.org/apidocs/org/bukkit/ChatColor.html#enum_constant_summary for a list of valid colors"); + } else { + this.color = c; + } + } - public int getLevel() { - return level; - } + public String getName() { + return name; + } - public ChatColor getColor() { - return color; - } + public int getLevel() { + return level; + } - public List getActions() { - return actions; - } + public ChatColor getColor() { + return color; + } - public static Group load(String string) { - try { - if (string.split(" : ").length == 4) { - String name = string.split(" : ")[0]; - int level = Integer.parseInt(string.split(" : ")[1]); - String color = string.split(" : ")[2]; - List actions = Arrays.asList(string.split(" : ")[3].split(",")); - return new Group(name, level, color, actions); - } else { - throw new Exception(); - } - } catch (Exception ex) { - AntiCheatReloaded.getPlugin().getLogger().warning("An event was initialized with an invalid string: '" + string + "'"); - AntiCheatReloaded.getPlugin().getLogger().warning("The proper format is: 'name : threshold : color : action' such as 'High : 50 : RED : KICK'"); - AntiCheatReloaded.getPlugin().getLogger().warning("This event will NOT run. (" + ex.getMessage() + ")"); - return null; - } - } + public List getActions() { + return actions; + } - @Override - public String toString() { - return name + " : " + level + " : " + color.name() + " : " + Utilities.listToCommaString(actions); - } + public static Group load(String string) { + try { + if (string.split(" : ").length == 4) { + String name = string.split(" : ")[0]; + int level = Integer.parseInt(string.split(" : ")[1]); + String color = string.split(" : ")[2]; + List actions = Arrays.asList(string.split(" : ")[3].split(",")); + return new Group(name, level, color, actions); + } else { + throw new Exception(); + } + } catch (Exception ex) { + AntiCheatReloaded.getPlugin().getLogger() + .warning("An event was initialized with an invalid string: '" + string + "'"); + AntiCheatReloaded.getPlugin().getLogger().warning( + "The proper format is: 'name : threshold : color : action' such as 'High : 50 : RED : KICK'"); + AntiCheatReloaded.getPlugin().getLogger().warning("This event will NOT run. (" + ex.getMessage() + ")"); + return null; + } + } + + @Override + public String toString() { + return name + " : " + level + " : " + color.name() + " : " + Utilities.listToCommaString(actions); + } } diff --git a/src/main/java/com/rammelkast/anticheatreloaded/util/NMS_1_9_PLUS.java b/src/main/java/com/rammelkast/anticheatreloaded/util/NMS_1_9_PLUS.java index b1e04fb..179d43a 100644 --- a/src/main/java/com/rammelkast/anticheatreloaded/util/NMS_1_9_PLUS.java +++ b/src/main/java/com/rammelkast/anticheatreloaded/util/NMS_1_9_PLUS.java @@ -29,18 +29,18 @@ import org.bukkit.potion.PotionEffectType; public class NMS_1_9_PLUS { - static final EnumSet MOVE_UP_BLOCKS_1_9 = EnumSet.of(Material.ACACIA_STAIRS, - Material.BIRCH_WOOD_STAIRS, Material.BRICK_STAIRS, Material.COBBLESTONE_STAIRS, Material.DARK_OAK_STAIRS, - Material.JUNGLE_WOOD_STAIRS, Material.NETHER_BRICK_STAIRS, Material.QUARTZ_STAIRS, - Material.RED_SANDSTONE_STAIRS, Material.SANDSTONE_STAIRS, Material.SMOOTH_STAIRS, - Material.SPRUCE_WOOD_STAIRS, Material.WOOD_STAIRS, Material.PURPUR_STAIRS); - + static final EnumSet MOVE_UP_BLOCKS_1_9 = EnumSet.of(Material.ACACIA_STAIRS, Material.BIRCH_WOOD_STAIRS, + Material.BRICK_STAIRS, Material.COBBLESTONE_STAIRS, Material.DARK_OAK_STAIRS, Material.JUNGLE_WOOD_STAIRS, + Material.NETHER_BRICK_STAIRS, Material.QUARTZ_STAIRS, Material.RED_SANDSTONE_STAIRS, + Material.SANDSTONE_STAIRS, Material.SMOOTH_STAIRS, Material.SPRUCE_WOOD_STAIRS, Material.WOOD_STAIRS, + Material.PURPUR_STAIRS); + static final PotionEffectType LEVITATION = PotionEffectType.LEVITATION; - + static final Enchantment FROST_WALKER = Enchantment.FROST_WALKER; public static ItemStack getItemInHand(Player player) { return player.getInventory().getItemInMainHand(); } - + } diff --git a/src/main/java/com/rammelkast/anticheatreloaded/util/NPC_1_12.java b/src/main/java/com/rammelkast/anticheatreloaded/util/NPC_1_12.java index 89895b4..64a8a32 100644 --- a/src/main/java/com/rammelkast/anticheatreloaded/util/NPC_1_12.java +++ b/src/main/java/com/rammelkast/anticheatreloaded/util/NPC_1_12.java @@ -64,7 +64,7 @@ public class NPC_1_12 { public int getID() { return this.entityId; } - + public NPC_1_12(Player owner) { this.owner = owner.getUniqueId(); this.name = NameGenerator.generateName(); @@ -85,15 +85,21 @@ public class NPC_1_12 { this.location.getZ(), 0.0f, 0.0f); this.npc.collides = false; this.npc.setInvisible(true); - this.npc.setEquipment(EnumItemSlot.CHEST, AntiCheatReloaded.getRandom().nextBoolean() ? CraftItemStack.asNMSCopy(new ItemStack(Material.DIAMOND_CHESTPLATE)) : CraftItemStack.asNMSCopy(new ItemStack(Material.CHAINMAIL_CHESTPLATE))); - this.npc.setEquipment(EnumItemSlot.FEET, AntiCheatReloaded.getRandom().nextBoolean() ? CraftItemStack.asNMSCopy(new ItemStack(Material.CHAINMAIL_BOOTS)) : CraftItemStack.asNMSCopy(new ItemStack(Material.DIAMOND_BOOTS))); + this.npc.setEquipment(EnumItemSlot.CHEST, + AntiCheatReloaded.getRandom().nextBoolean() + ? CraftItemStack.asNMSCopy(new ItemStack(Material.DIAMOND_CHESTPLATE)) + : CraftItemStack.asNMSCopy(new ItemStack(Material.CHAINMAIL_CHESTPLATE))); + this.npc.setEquipment(EnumItemSlot.FEET, + AntiCheatReloaded.getRandom().nextBoolean() + ? CraftItemStack.asNMSCopy(new ItemStack(Material.CHAINMAIL_BOOTS)) + : CraftItemStack.asNMSCopy(new ItemStack(Material.DIAMOND_BOOTS))); this.entityId = this.npc.getId(); final PlayerConnection connection = ((CraftPlayer) this.getOwner()).getHandle().playerConnection; connection.sendPacket(new PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.ADD_PLAYER, new EntityPlayer[] { this.npc })); connection.sendPacket(new PacketPlayOutNamedEntitySpawn((EntityHuman) this.npc)); } - + public boolean up = true; public void move(PlayerMoveEvent e) { @@ -106,11 +112,14 @@ public class NPC_1_12 { vec.setZ(-3 * vec.getZ()); Location back = eyelocation.add(vec); this.location = back; // TODO - this.npc.setPositionRotation(back.getX(), back.getY(), back.getZ(), (float)new Random().nextFloat() * 20, (float)new Random().nextFloat() * 20); - ((CraftPlayer) this.getOwner()).getHandle().playerConnection.sendPacket(new PacketPlayOutEntityTeleport(npc)); + this.npc.setPositionRotation(back.getX(), back.getY(), back.getZ(), + (float) new Random().nextFloat() * 20, (float) new Random().nextFloat() * 20); + ((CraftPlayer) this.getOwner()).getHandle().playerConnection + .sendPacket(new PacketPlayOutEntityTeleport(npc)); if (new Random().nextInt(50) == 25 && this.npc.isInvisible()) { this.npc.setInvisible(false); - ((CraftPlayer) this.getOwner()).getHandle().playerConnection.sendPacket(new PacketPlayOutEntityMetadata(entityId, npc.getDataWatcher(), false)); + ((CraftPlayer) this.getOwner()).getHandle().playerConnection + .sendPacket(new PacketPlayOutEntityMetadata(entityId, npc.getDataWatcher(), false)); new BukkitRunnable() { @Override public void run() { @@ -118,11 +127,12 @@ public class NPC_1_12 { return; } npc.setInvisible(true); - ((CraftPlayer) getOwner()).getHandle().playerConnection.sendPacket(new PacketPlayOutEntityMetadata(entityId, npc.getDataWatcher(), false)); + ((CraftPlayer) getOwner()).getHandle().playerConnection + .sendPacket(new PacketPlayOutEntityMetadata(entityId, npc.getDataWatcher(), false)); } }.runTaskLater(AntiCheatReloaded.getPlugin(), 4); } - }else { + } else { Location eyelocation = e.getPlayer().getEyeLocation(); Vector vec = e.getPlayer().getLocation().getDirection(); vec.setX(-3 * vec.getX()); @@ -130,8 +140,10 @@ public class NPC_1_12 { vec.setZ(-3 * vec.getZ()); Location back = eyelocation.add(vec); this.location = back; // TODO - this.npc.setPositionRotation(back.getX(), back.getY(), back.getZ(), (float)new Random().nextFloat() * 20, (float)new Random().nextFloat() * 20); - ((CraftPlayer) this.getOwner()).getHandle().playerConnection.sendPacket(new PacketPlayOutEntityTeleport(npc)); + this.npc.setPositionRotation(back.getX(), back.getY(), back.getZ(), + (float) new Random().nextFloat() * 20, (float) new Random().nextFloat() * 20); + ((CraftPlayer) this.getOwner()).getHandle().playerConnection + .sendPacket(new PacketPlayOutEntityTeleport(npc)); } } else if (e.getTo().getPitch() >= 22) { Location eyelocation = e.getPlayer().getEyeLocation(); @@ -141,8 +153,10 @@ public class NPC_1_12 { vec.setZ(-3 * vec.getZ()); Location back = eyelocation.add(vec); this.location = back; // TODO - this.npc.setPositionRotation(back.getX(), back.getY(), back.getZ(), (float)new Random().nextFloat() * 20, (float)new Random().nextFloat() * 20); - ((CraftPlayer) this.getOwner()).getHandle().playerConnection.sendPacket(new PacketPlayOutEntityTeleport(npc)); + this.npc.setPositionRotation(back.getX(), back.getY(), back.getZ(), (float) new Random().nextFloat() * 20, + (float) new Random().nextFloat() * 20); + ((CraftPlayer) this.getOwner()).getHandle().playerConnection + .sendPacket(new PacketPlayOutEntityTeleport(npc)); } else { Location eyelocation = e.getPlayer().getEyeLocation(); Vector vec = e.getPlayer().getLocation().getDirection(); @@ -156,12 +170,14 @@ public class NPC_1_12 { vec.setZ(-1.95 * vec.getZ()); Location back = eyelocation.add(vec); this.location = back; // TODO - this.npc.setPositionRotation(back.getX(), back.getY(), back.getZ(), (float)new Random().nextFloat() * 20, (float)new Random().nextFloat() * 20); + this.npc.setPositionRotation(back.getX(), back.getY(), back.getZ(), (float) new Random().nextFloat() * 20, + (float) new Random().nextFloat() * 20); ((CraftPlayer) this.getOwner()).getHandle().playerConnection .sendPacket(new PacketPlayOutEntityTeleport(npc)); if (new Random().nextInt(1000) == 500 && this.npc.isInvisible()) { this.npc.setInvisible(false); - ((CraftPlayer) this.getOwner()).getHandle().playerConnection.sendPacket(new PacketPlayOutEntityMetadata(entityId, npc.getDataWatcher(), false)); + ((CraftPlayer) this.getOwner()).getHandle().playerConnection + .sendPacket(new PacketPlayOutEntityMetadata(entityId, npc.getDataWatcher(), false)); new BukkitRunnable() { @Override public void run() { @@ -169,7 +185,8 @@ public class NPC_1_12 { return; } npc.setInvisible(true); - ((CraftPlayer) getOwner()).getHandle().playerConnection.sendPacket(new PacketPlayOutEntityMetadata(entityId, npc.getDataWatcher(), false)); + ((CraftPlayer) getOwner()).getHandle().playerConnection + .sendPacket(new PacketPlayOutEntityMetadata(entityId, npc.getDataWatcher(), false)); } }.runTaskLater(AntiCheatReloaded.getPlugin(), 6); } @@ -186,7 +203,8 @@ public class NPC_1_12 { } if (new Random().nextBoolean() && this.npc.isInvisible()) { this.npc.setInvisible(false); - ((CraftPlayer) this.getOwner()).getHandle().playerConnection.sendPacket(new PacketPlayOutEntityMetadata(entityId, npc.getDataWatcher(), false)); + ((CraftPlayer) this.getOwner()).getHandle().playerConnection + .sendPacket(new PacketPlayOutEntityMetadata(entityId, npc.getDataWatcher(), false)); new BukkitRunnable() { @Override public void run() { @@ -194,19 +212,21 @@ public class NPC_1_12 { return; } npc.setInvisible(true); - ((CraftPlayer) getOwner()).getHandle().playerConnection.sendPacket(new PacketPlayOutEntityMetadata(entityId, npc.getDataWatcher(), false)); + ((CraftPlayer) getOwner()).getHandle().playerConnection + .sendPacket(new PacketPlayOutEntityMetadata(entityId, npc.getDataWatcher(), false)); } }.runTaskLater(AntiCheatReloaded.getPlugin(), 6 + new Random().nextInt(7)); } } - + public void damage() { if (this.npc == null || this.getOwner() == null) { return; } if (new Random().nextBoolean() && this.npc.isInvisible()) { this.npc.setInvisible(false); - ((CraftPlayer) this.getOwner()).getHandle().playerConnection.sendPacket(new PacketPlayOutEntityMetadata(entityId, npc.getDataWatcher(), false)); + ((CraftPlayer) this.getOwner()).getHandle().playerConnection + .sendPacket(new PacketPlayOutEntityMetadata(entityId, npc.getDataWatcher(), false)); new BukkitRunnable() { @Override public void run() { @@ -214,7 +234,8 @@ public class NPC_1_12 { return; } npc.setInvisible(true); - ((CraftPlayer) getOwner()).getHandle().playerConnection.sendPacket(new PacketPlayOutEntityMetadata(entityId, npc.getDataWatcher(), false)); + ((CraftPlayer) getOwner()).getHandle().playerConnection + .sendPacket(new PacketPlayOutEntityMetadata(entityId, npc.getDataWatcher(), false)); } }.runTaskLater(AntiCheatReloaded.getPlugin(), 6 + new Random().nextInt(8)); } diff --git a/src/main/java/com/rammelkast/anticheatreloaded/util/NameGenerator.java b/src/main/java/com/rammelkast/anticheatreloaded/util/NameGenerator.java index 5880188..1d71f3a 100644 --- a/src/main/java/com/rammelkast/anticheatreloaded/util/NameGenerator.java +++ b/src/main/java/com/rammelkast/anticheatreloaded/util/NameGenerator.java @@ -25,32 +25,12 @@ import java.util.Random; public class NameGenerator { - private static final List BEGIN = Arrays.asList(new String[]{ - "Pixel", - "Pro", - "NoHax", - "Just", - "That", - "New", - "Ultra", - "Killer", - "Swift", - "Yolo", - "Rammel" - }); + private static final List BEGIN = Arrays.asList(new String[] { "Pixel", "Pro", "NoHax", "Just", "That", + "New", "Ultra", "Killer", "Swift", "Anarchy", "Yolo", "Rammel" }); + + private static final List END = Arrays.asList(new String[] { "Gamer", "PvP", "JustYolo", "Gaming", + "Minecraft", "Games", "Bawz", "Tech", "Noob", "Extra", "kast", "" + new Random().nextInt(100) }); - private static final List END = Arrays.asList(new String[]{ - "Gamer", - "PvP", - "JustYolo", - "Gaming", - "Minecraft", - "Games", - "Bawz", - "kast", - "" + new Random().nextInt(100) - }); - public static String generateName() { Random r = new Random(); String begin = BEGIN.get(r.nextInt(BEGIN.size() - 1)); @@ -60,5 +40,5 @@ public class NameGenerator { else return begin + end; } - + } diff --git a/src/main/java/com/rammelkast/anticheatreloaded/util/NameUtil.java b/src/main/java/com/rammelkast/anticheatreloaded/util/NameUtil.java deleted file mode 100644 index f9812a6..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/util/NameUtil.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team | http://gravitydevelopment.net - * Copyright (c) 2016-2018 Rammelkast | https://rammelkast.com - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded.util; - -import java.util.Random; - -public class NameUtil { - - private static String[] firstParts = new String[] { - "Gamer", - "Pixel", - "Derp", - "Random", - "That", - "NoHaxJust", - "Derp", - "Fun", - "Luigi" - }; - - private static String[] secondParts = new String[] { - "01", - "Boy", - "Guy", - "Mario", - "Plain", - "Simple", - "NotHacking", - "Random", - "11", - "06" - }; - - private static Random theRandom = new Random(); - - public static String getRandomName() { - return firstParts[theRandom.nextInt(firstParts.length - 1)] + secondParts[theRandom.nextInt(secondParts.length - 1)]; - } -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/util/Permission.java b/src/main/java/com/rammelkast/anticheatreloaded/util/Permission.java index 594886f..f3a2554 100644 --- a/src/main/java/com/rammelkast/anticheatreloaded/util/Permission.java +++ b/src/main/java/com/rammelkast/anticheatreloaded/util/Permission.java @@ -22,77 +22,46 @@ package com.rammelkast.anticheatreloaded.util; import org.bukkit.command.CommandSender; public enum Permission { - /* Check Nodes */ - CHECK_ZOMBE_FLY, - CHECK_ZOMBE_NOCLIP, - CHECK_ZOMBE_CHEAT, - CHECK_FLY, - CHECK_WATERWALK, - CHECK_NOSWING, - CHECK_FASTBREAK, - CHECK_FASTPLACE, - CHECK_CHATSPAM, - CHECK_COMMANDSPAM, - CHECK_SPRINT, - CHECK_SNEAK, - CHECK_SPEED, - CHECK_VCLIP, - CHECK_SPIDER, - CHECK_NOFALL, - CHECK_FASTBOW, - CHECK_FASTEAT, - CHECK_FASTHEAL, - CHECK_FORCEFIELD, - CHECK_LONGREACH, - CHECK_FASTPROJECTILE, - CHECK_ITEMSPAM, - CHECK_VISUAL, - CHECK_FASTINVENTORY, - CHECK_AUTOTOOL, + /* Check Nodes */ + CHECK_ZOMBE_FLY, CHECK_ZOMBE_NOCLIP, CHECK_ZOMBE_CHEAT, CHECK_FLIGHT, CHECK_ELYTRA, CHECK_WATERWALK, CHECK_NOSWING, CHECK_FASTBREAK, + CHECK_FASTPLACE, CHECK_CHATSPAM, CHECK_COMMANDSPAM, CHECK_SPRINT, CHECK_SNEAK, CHECK_SPEED, CHECK_VCLIP, + CHECK_SPIDER, CHECK_NOFALL, CHECK_FASTBOW, CHECK_FASTEAT, CHECK_FASTHEAL, CHECK_FORCEFIELD, CHECK_LONGREACH, + CHECK_FASTPROJECTILE, CHECK_ITEMSPAM, CHECK_VISUAL, CHECK_FASTINVENTORY, CHECK_AUTOTOOL, - /* System Nodes */ - SYSTEM_LOG, - SYSTEM_RESET, - SYSTEM_SPY, - SYSTEM_HELP, - SYSTEM_UPDATE, - SYSTEM_REPORT, - SYSTEM_ALERT, - SYSTEM_NOTICE, - SYSTEM_CALIBRATE, - SYSTEM_CHECK, - SYSTEM_DEBUG, - SYSTEM_RELOAD, CHECK_KILLAURA, CHECK_BLINK, VELOCITY, CRITICALS; + /* System Nodes */ + SYSTEM_LOG, SYSTEM_RESET, SYSTEM_SPY, SYSTEM_HELP, SYSTEM_UPDATE, SYSTEM_REPORT, SYSTEM_ALERT, SYSTEM_NOTICE, + SYSTEM_CALIBRATE, SYSTEM_CHECK, SYSTEM_DEBUG, SYSTEM_RELOAD, CHECK_KILLAURA, CHECK_BLINK, VELOCITY, CRITICALS; - private static final String PERMISSION_ALL = "anticheat.*"; - private static final String PERMISSION_SPAM = "anticheat.check.spam"; + private static final String PERMISSION_ALL = "anticheat.*"; + private static final String PERMISSION_SPAM = "anticheat.check.spam"; - public static boolean getCommandExempt(CommandSender cs, String commandLabel) { - // Check permission, base, and all will have already been checked - return cs.hasPermission(CHECK_COMMANDSPAM.toString() + commandLabel); - } + public static boolean getCommandExempt(CommandSender cs, String commandLabel) { + // Check permission, base, and all will have already been checked + return cs.hasPermission(CHECK_COMMANDSPAM.toString() + commandLabel); + } - public boolean get(CommandSender cs) { - if ((this == CHECK_CHATSPAM || this == CHECK_COMMANDSPAM) && cs.hasPermission(PERMISSION_SPAM)) return true; - return cs.hasPermission(toString()) || cs.hasPermission(getBase()) || cs.hasPermission(PERMISSION_ALL); - } + public boolean get(CommandSender cs) { + if ((this == CHECK_CHATSPAM || this == CHECK_COMMANDSPAM) && cs.hasPermission(PERMISSION_SPAM)) + return true; + return cs.hasPermission(toString()) || cs.hasPermission(getBase()) || cs.hasPermission(PERMISSION_ALL); + } - public String getBase() { - return "anticheat." + this.name().toLowerCase().split("_")[0] + ".*"; - } + public String getBase() { + return "anticheat." + this.name().toLowerCase().split("_")[0] + ".*"; + } - public String whichPermission(CommandSender cs) { - for (String s : new String[]{PERMISSION_ALL, getBase(), toString()}) { - if (cs.hasPermission(s)) { - return s; - } - } - return null; - } + public String whichPermission(CommandSender cs) { + for (String s : new String[] { PERMISSION_ALL, getBase(), toString() }) { + if (cs.hasPermission(s)) { + return s; + } + } + return null; + } - @Override - public String toString() { - return "anticheat." + this.name().toLowerCase().replace("_", "."); - } + @Override + public String toString() { + return "anticheat." + this.name().toLowerCase().replace("_", "."); + } } diff --git a/src/main/java/com/rammelkast/anticheatreloaded/util/ToolHardness.java b/src/main/java/com/rammelkast/anticheatreloaded/util/ToolHardness.java index 12622c7..1ec092b 100644 --- a/src/main/java/com/rammelkast/anticheatreloaded/util/ToolHardness.java +++ b/src/main/java/com/rammelkast/anticheatreloaded/util/ToolHardness.java @@ -23,27 +23,22 @@ import org.bukkit.Material; public enum ToolHardness { - // NOTHING(null, 1.5) - WOOD(0.75D), - STONE(0.40D), - IRON(0.25D), - DIAMOND(0.20D), - SHEARS(0.55D), - GOLD(0.15D); + // NOTHING(null, 1.5) + WOOD(0.75D), STONE(0.40D), IRON(0.25D), DIAMOND(0.20D), SHEARS(0.55D), GOLD(0.15D); - double hardness; + double hardness; - ToolHardness(double hard) { - hardness = hard; - } + ToolHardness(double hard) { + hardness = hard; + } - public static double getToolHardness(Material tool) { - for (ToolHardness e : ToolHardness.values()) { - if (tool.name().contains(e.name())) { - return e.hardness; - } - } + public static double getToolHardness(Material tool) { + for (ToolHardness e : ToolHardness.values()) { + if (tool.name().contains(e.name())) { + return e.hardness; + } + } - return 1.50D; - } + return 1.50D; + } } diff --git a/src/main/java/com/rammelkast/anticheatreloaded/util/User.java b/src/main/java/com/rammelkast/anticheatreloaded/util/User.java index f16acbc..518b5cf 100644 --- a/src/main/java/com/rammelkast/anticheatreloaded/util/User.java +++ b/src/main/java/com/rammelkast/anticheatreloaded/util/User.java @@ -36,397 +36,401 @@ import java.util.List; import java.util.UUID; public class User { - private final UUID uuid; - private final String name; - private final int id; - private int level = 0; - private Location goodLocation; - private List inventorySnapshot = null; - private Configuration config = AntiCheatReloaded.getManager().getConfiguration(); - private int toX, toY, toZ; - private String[] messages = new String[2]; - private Long[] messageTimes = new Long[2]; - private String[] commands = new String[2]; - private Long[] commandTimes = new Long[2]; + private final UUID uuid; + private final String name; + private final int id; + private int level = 0; + private Location goodLocation; + private List inventorySnapshot = null; + private Configuration config = AntiCheatReloaded.getManager().getConfiguration(); + private int toX, toY, toZ; + private String[] messages = new String[2]; + private Long[] messageTimes = new Long[2]; + private String[] commands = new String[2]; + private Long[] commandTimes = new Long[2]; - private boolean isWaitingOnLevelSync; - private Timestamp levelSyncTimestamp; + private boolean isWaitingOnLevelSync; + private Timestamp levelSyncTimestamp; - /** - * Initialize an AntiCheat user - * - * @param uuid Player's UUID - */ - public User(UUID uuid) { - this.uuid = uuid; - this.name = getPlayer() != null && getPlayer().isOnline() ? getPlayer().getName() : ""; - this.id = getPlayer() != null && getPlayer().isOnline() ? getPlayer().getEntityId() : -1; - } + /** + * Initialize an AntiCheat user + * + * @param uuid Player's UUID + */ + public User(UUID uuid) { + this.uuid = uuid; + this.name = getPlayer() != null && getPlayer().isOnline() ? getPlayer().getName() : ""; + this.id = getPlayer() != null && getPlayer().isOnline() ? getPlayer().getEntityId() : -1; + } - /** - * Initialize an AntiCheat user - * - * @param name Player's name - */ -/* public User(String name) { - this.uuid = Bukkit.getPlayer(name).getUniqueId(); - this.name = name; - this.id = getPlayer() != null && getPlayer().isOnline() ? getPlayer().getEntityId() : -1; - } -*/ - /** - * Get the player's UUID - * - * @return Player UUID - */ - public UUID getUUID() { - return uuid; - } + /** + * Initialize an AntiCheat user + * + * @param name Player's name + */ + /* + * public User(String name) { this.uuid = Bukkit.getPlayer(name).getUniqueId(); + * this.name = name; this.id = getPlayer() != null && getPlayer().isOnline() ? + * getPlayer().getEntityId() : -1; } + */ + /** + * Get the player's UUID + * + * @return Player UUID + */ + public UUID getUUID() { + return uuid; + } - /** - * Get the player's name - * - * @return Player name - */ - public String getName() { - return name; - } + /** + * Get the player's name + * + * @return Player name + */ + public String getName() { + return name; + } - /** - * Get the player's entity ID - * - * @return Entity id - */ - public int getId() { - return id; - } + /** + * Get the player's entity ID + * + * @return Entity id + */ + public int getId() { + return id; + } - /** - * Get the Bukkit player - * - * @return Player - */ - public Player getPlayer() { - return Bukkit.getPlayer(uuid); - } + /** + * Get the Bukkit player + * + * @return Player + */ + public Player getPlayer() { + return Bukkit.getPlayer(uuid); + } - /** - * Get the user's level value - * - * @return level - */ - public int getLevel() { - return level; - } + /** + * Get the user's level value + * + * @return level + */ + public int getLevel() { + return level; + } - /** - * Get the user's group - * - * @return group - */ - public Group getGroup() { - List groups = config.getGroups().getGroups(); - for (int i = 0; i < groups.size(); i++) { - if (i == 0 && level < groups.get(i).getLevel()) break; - else if (i == groups.size() - 1) return groups.get(i); - else if (level >= groups.get(i).getLevel() && level < groups.get(i + 1).getLevel()) return groups.get(i); - } - return null; - } + /** + * Get the user's group + * + * @return group + */ + public Group getGroup() { + List groups = config.getGroups().getGroups(); + for (int i = 0; i < groups.size(); i++) { + if (i == 0 && level < groups.get(i).getLevel()) + break; + else if (i == groups.size() - 1) + return groups.get(i); + else if (level >= groups.get(i).getLevel() && level < groups.get(i + 1).getLevel()) + return groups.get(i); + } + return null; + } - /** - * Increase the player's level (from failing a check) - * - * @param type The check failed - * @return true if the level was increased - */ - public boolean increaseLevel(CheckType type) { - if (getPlayer() != null && getPlayer().isOnline()) { - if (silentMode() && type.getUses(uuid) % 4 != 0) { - // Prevent silent mode from increasing the level way too fast - return false; - } else { - if (level < config.getGroups().getHighestLevel()) { - level++; + /** + * Increase the player's level (from failing a check) + * + * @param type The check failed + * @return true if the level was increased + */ + public boolean increaseLevel(CheckType type) { + if (getPlayer() != null && getPlayer().isOnline()) { + if (silentMode() && type.getUses(uuid) % 4 != 0) { + // Prevent silent mode from increasing the level way too fast + return false; + } else { + if (level < config.getGroups().getHighestLevel()) { + level++; - // Check levels - for (Group l : getLevels()) { - if (l.getLevel() == level) { - AntiCheatReloaded.getManager().getUserManager().alert(this, l, type); - if (l.getLevel() == config.getGroups().getHighestLevel()) { - level = l.getLevel() - 10; - } - } - } + // Check levels + for (Group l : getLevels()) { + if (l.getLevel() == level) { + AntiCheatReloaded.getManager().getUserManager().alert(this, l, type); + if (l.getLevel() == config.getGroups().getHighestLevel()) { + level = l.getLevel() - 10; + } + } + } - // Execute rules - for (Rule rule : config.getRules().getRules()) { - rule.check(this, type); - } - return true; - } - return false; - } - } else { - return false; - } - } + // Execute rules + for (Rule rule : config.getRules().getRules()) { + rule.check(this, type); + } + return true; + } + return false; + } + } else { + return false; + } + } - /** - * Decrease the player's level by one value - */ - public void decreaseLevel() { - level = level != 0 ? level - 1 : 0; - } + /** + * Decrease the player's level by one value + */ + public void decreaseLevel() { + level = level != 0 ? level - 1 : 0; + } - /** - * Set the users level to a specific value. Must be 0 < level < config-defined highest level - * - * @param level level to set - * @return true if the level was valid and set properly - */ - public boolean setLevel(int level) { - isWaitingOnLevelSync = false; - if (level >= 0) { - if (level <= config.getGroups().getHighestLevel()) { - this.level = level; - return true; - } else { - this.level = config.getGroups().getHighestLevel(); - return false; - } - } else { - return false; - } - } + /** + * Set the users level to a specific value. Must be 0 < level < config-defined + * highest level + * + * @param level level to set + * @return true if the level was valid and set properly + */ + public boolean setLevel(int level) { + isWaitingOnLevelSync = false; + if (level >= 0) { + if (level <= config.getGroups().getHighestLevel()) { + this.level = level; + return true; + } else { + this.level = config.getGroups().getHighestLevel(); + return false; + } + } else { + return false; + } + } - /** - * Reset the user's level to zero and clear all check failures - */ - public void resetLevel() { - level = 0; - for (CheckType type : CheckType.values()) { - type.clearUse(uuid); - } - } + /** + * Reset the user's level to zero and clear all check failures + */ + public void resetLevel() { + level = 0; + for (CheckType type : CheckType.values()) { + type.clearUse(uuid); + } + } - /** - * Get the last known valid location of the player for use in resetting - * - * @param location default value to be returned if no known good location exists - * @return last known valid location - */ - public Location getGoodLocation(Location location) { - if (goodLocation == null) { - return location; - } + /** + * Get the last known valid location of the player for use in resetting + * + * @param location default value to be returned if no known good location exists + * @return last known valid location + */ + public Location getGoodLocation(Location location) { + if (goodLocation == null) { + return location; + } - return goodLocation; - } + return goodLocation; + } - /** - * Set the last known valid location of the player - * - * @param location location to be set - * @return true if the location was valid and set properly - */ - public boolean setGoodLocation(Location location) { - if (Utilities.cantStandAtExp(location) || (location.getBlock().isLiquid() && !Utilities.isFullyInWater(location))) { - return false; - } + /** + * Set the last known valid location of the player + * + * @param location location to be set + * @return true if the location was valid and set properly + */ + public boolean setGoodLocation(Location location) { + if (Utilities.cantStandAtExp(location) + || (location.getBlock().isLiquid() && !Utilities.isFullyInWater(location))) { + return false; + } - goodLocation = location; - return true; - } + goodLocation = location; + return true; + } - /** - * Store a copy of the player's inventory, for use in resetting - * - * @param is ItemStack list to store - */ - public void setInventorySnapshot(ItemStack[] is) { - inventorySnapshot = new ArrayList(); - for (int i = 0; i < is.length; i++) { - if (is[i] != null) { - inventorySnapshot.add(is[i].clone()); - } - } - } + /** + * Store a copy of the player's inventory, for use in resetting + * + * @param is ItemStack list to store + */ + public void setInventorySnapshot(ItemStack[] is) { + inventorySnapshot = new ArrayList(); + for (int i = 0; i < is.length; i++) { + if (is[i] != null) { + inventorySnapshot.add(is[i].clone()); + } + } + } - /** - * Remove the current inventory snapshot - */ - public void removeInventorySnapshot() { - inventorySnapshot = null; - } + /** + * Remove the current inventory snapshot + */ + public void removeInventorySnapshot() { + inventorySnapshot = null; + } - /** - * Restore the player's inventory with the current inventory snapshot - * - * @param inventory Player's inventory - */ - public void restoreInventory(Inventory inventory) { - if (inventorySnapshot != null) { - inventory.clear(); - for (ItemStack is : inventorySnapshot) { - if (is != null) { - inventory.addItem(is); - } - } - } - } + /** + * Restore the player's inventory with the current inventory snapshot + * + * @param inventory Player's inventory + */ + public void restoreInventory(Inventory inventory) { + if (inventorySnapshot != null) { + inventory.clear(); + for (ItemStack is : inventorySnapshot) { + if (is != null) { + inventory.addItem(is); + } + } + } + } - /** - * Set the player's to location - * - * @param x X value - * @param y Y value - * @param z Z value - */ - public void setTo(double x, double y, double z) { - toX = (int) x; - toY = (int) y; - toZ = (int) z; - } + /** + * Set the player's to location + * + * @param x X value + * @param y Y value + * @param z Z value + */ + public void setTo(double x, double y, double z) { + toX = (int) x; + toY = (int) y; + toZ = (int) z; + } - /** - * Check if a given to value is the same as the stored value - * - * @param x X value - * @param y Y value - * @param z Z value - * @return true if coordinates are all equal - */ - public boolean checkTo(double x, double y, double z) { - return (int) x == toX && (int) y == toY && (int) z == toZ; - } + /** + * Check if a given to value is the same as the stored value + * + * @param x X value + * @param y Y value + * @param z Z value + * @return true if coordinates are all equal + */ + public boolean checkTo(double x, double y, double z) { + return (int) x == toX && (int) y == toY && (int) z == toZ; + } - /** - * Log a player's chat message - * - * @param message Message to log - */ - public void addMessage(String message) { - addToSpamLog(message, messages, messageTimes); - } + /** + * Log a player's chat message + * + * @param message Message to log + */ + public void addMessage(String message) { + addToSpamLog(message, messages, messageTimes); + } - /** - * Log a player's command - * - * @param command Command to log - */ - public void addCommand(String command) { - addToSpamLog(command, commands, commandTimes); - } + /** + * Log a player's command + * + * @param command Command to log + */ + public void addCommand(String command) { + addToSpamLog(command, commands, commandTimes); + } - private void addToSpamLog(String string, String[] messages, Long[] times) { - messages[1] = messages[0]; - messages[0] = string; + private void addToSpamLog(String string, String[] messages, Long[] times) { + messages[1] = messages[0]; + messages[0] = string; - times[1] = times[0]; - times[0] = System.currentTimeMillis(); - } + times[1] = times[0]; + times[0] = System.currentTimeMillis(); + } - /** - * Get a stored chat message - * - * @param index Index of the chat in storage - * @return the message - */ - public String getMessage(int index) { - return messages[index]; - } + /** + * Get a stored chat message + * + * @param index Index of the chat in storage + * @return the message + */ + public String getMessage(int index) { + return messages[index]; + } - /** - * Get a stored command - * - * @param index Index of the command in storage - * @return the command - */ - public String getCommand(int index) { - return commands[index]; - } + /** + * Get a stored command + * + * @param index Index of the command in storage + * @return the command + */ + public String getCommand(int index) { + return commands[index]; + } - /** - * Get the time a message in storage was sent - * - * @param index Index of the chat in storage - * @return time the message was sent - */ - public Long getMessageTime(int index) { - return messageTimes[index]; - } + /** + * Get the time a message in storage was sent + * + * @param index Index of the chat in storage + * @return time the message was sent + */ + public Long getMessageTime(int index) { + return messageTimes[index]; + } - /** - * Get the time a command in storage was sent - * - * @param index Index of the command in storage - * @return time the command was sent - */ - public Long getCommandTime(int index) { - return commandTimes[index]; - } + /** + * Get the time a command in storage was sent + * + * @param index Index of the command in storage + * @return time the command was sent + */ + public Long getCommandTime(int index) { + return commandTimes[index]; + } - /** - * Clear all stored messages - */ - public void clearMessages() { - messages = new String[2]; - messageTimes = new Long[2]; - } + /** + * Clear all stored messages + */ + public void clearMessages() { + messages = new String[2]; + messageTimes = new Long[2]; + } - /** - * Clear all stored commands - */ - public void clearCommands() { - commands = new String[2]; - commandTimes = new Long[2]; - } + /** + * Clear all stored commands + */ + public void clearCommands() { + commands = new String[2]; + commandTimes = new Long[2]; + } - /** - * Get the time the very last stored message was sent - * - * @return the last message's time - */ - public Long getLastMessageTime() { - return getMessageTime(0) == null ? -1 : getMessageTime(0); - } + /** + * Get the time the very last stored message was sent + * + * @return the last message's time + */ + public Long getLastMessageTime() { + return getMessageTime(0) == null ? -1 : getMessageTime(0); + } - /** - * Get the time the very last stored command was sent - * - * @return the last command's time - */ - public Long getLastCommandTime() { - return getCommandTime(0) == null ? -1 : getCommandTime(0); - } + /** + * Get the time the very last stored command was sent + * + * @return the last command's time + */ + public Long getLastCommandTime() { + return getCommandTime(0) == null ? -1 : getCommandTime(0); + } - private List getLevels() { - return config.getGroups().getGroups(); - } + private List getLevels() { + return config.getGroups().getGroups(); + } - private boolean silentMode() { - return config.getConfig().silentMode.getValue(); - } + private boolean silentMode() { + return config.getConfig().silentMode.getValue(); + } - public void setIsWaitingOnLevelSync(boolean b) { - this.isWaitingOnLevelSync = b; - } + public void setIsWaitingOnLevelSync(boolean b) { + this.isWaitingOnLevelSync = b; + } - public boolean isWaitingOnLevelSync() { - return isWaitingOnLevelSync; - } + public boolean isWaitingOnLevelSync() { + return isWaitingOnLevelSync; + } - public void setLevelSyncTimestamp(Timestamp timestamp) { - levelSyncTimestamp = timestamp; - } + public void setLevelSyncTimestamp(Timestamp timestamp) { + levelSyncTimestamp = timestamp; + } - public Timestamp getLevelSyncTimestamp() { - return levelSyncTimestamp; - } + public Timestamp getLevelSyncTimestamp() { + return levelSyncTimestamp; + } - @Override - public String toString() { - return "User {name = " + getName() + ", level = " + level + "}"; - } + @Override + public String toString() { + return "User {name = " + getName() + ", level = " + level + "}"; + } } diff --git a/src/main/java/com/rammelkast/anticheatreloaded/util/Utilities.java b/src/main/java/com/rammelkast/anticheatreloaded/util/Utilities.java index 01e7d78..9b9b48f 100644 --- a/src/main/java/com/rammelkast/anticheatreloaded/util/Utilities.java +++ b/src/main/java/com/rammelkast/anticheatreloaded/util/Utilities.java @@ -39,539 +39,566 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; public final class Utilities { - private static final List INSTANT_BREAK = new ArrayList(); - private static final List FOOD = new ArrayList(); - private static final List INTERACTABLE = new ArrayList(); - private static final Map COMBO = new HashMap(); + private static final List INSTANT_BREAK = new ArrayList(); + private static final List FOOD = new ArrayList(); + private static final List INTERACTABLE = new ArrayList(); + private static final Map COMBO = new HashMap(); - public static final String SPY_METADATA = "ac-spydata"; + public static final String SPY_METADATA = "ac-spydata"; - /** - * Send a hack level alert to players and console - * - * @param message List of strings to send as the alert - */ - public static void alert(List message) { - for (Player player : Bukkit.getOnlinePlayers()) { - if (Permission.SYSTEM_ALERT.get(player)) { - for (String msg : message) { - player.sendMessage(msg); - } - } - } - for (String msg : message) { - AntiCheatReloaded.getManager().log(msg); - } - } - - /** - * Check if only the block beneath them is standable (includes water + lava) - * @param block the block to check (under) - * @return true if they cannot stand there - */ - public static boolean cantStandAtSingle(Block block) - { - // TODO: Implement Better to reduce false positives (done? lets test...) - Block otherBlock = block.getLocation().add(0, -0.5, 0).getBlock(); - boolean center = otherBlock.getType() == Material.AIR; - return center; - } + /** + * Send a hack level alert to players and console + * + * @param message List of strings to send as the alert + */ + public static void alert(List message) { + for (Player player : Bukkit.getOnlinePlayers()) { + if (Permission.SYSTEM_ALERT.get(player)) { + for (String msg : message) { + player.sendMessage(msg); + } + } + } + for (String msg : message) { + AntiCheatReloaded.getManager().log(msg); + } + } - /** - * Determine whether a player cannot stand on or around the given block - * - * @param block the block to check - * @return true if the player should be unable to stand here - */ - public static boolean cantStandAt(Block block) { - return !canStand(block) && cantStandClose(block) && cantStandFar(block); - } + /** + * Check if only the block beneath them is standable (includes water + lava) + * + * @param block the block to check (under) + * @return true if they cannot stand there + */ + public static boolean cantStandAtSingle(Block block) { + // TODO: Implement Better to reduce false positives (done? lets test...) + Block otherBlock = block.getLocation().add(0, -0.5, 0).getBlock(); + boolean center = otherBlock.getType() == Material.AIR; + return center; + } - /** - * Determine whether a player should be unable to stand at a given location - * - * @param location the location to check - * @return true if the player should be unable to stand here - */ - public static boolean cantStandAtExp(Location location) { - return cantStandAt(new Location(location.getWorld(), fixXAxis(location.getX()), location.getY() - 0.01D, location.getBlockZ()).getBlock()); - } + /** + * Determine whether a player cannot stand on or around the given block + * + * @param block the block to check + * @return true if the player should be unable to stand here + */ + public static boolean cantStandAt(Block block) { + return !canStand(block) && cantStandClose(block) && cantStandFar(block); + } - /** - * Determine whether cannot stand on the block's immediately surroundings (North, East, South, West) - * - * @param block the block to check - * @return true if a player cannot stand in the immediate vicinity - */ - 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)); - } + /** + * Determine whether a player should be unable to stand at a given location + * + * @param location the location to check + * @return true if the player should be unable to stand here + */ + public static boolean cantStandAtExp(Location location) { + return cantStandAt(new Location(location.getWorld(), fixXAxis(location.getX()), location.getY() - 0.01D, + location.getBlockZ()).getBlock()); + } - /** - * Determine whether cannot stand on the block's outer surroundings - * - * @param block the block to check - * @return true if a player cannot stand in areas further away from the 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)); - } + /** + * Determine whether cannot stand on the block's immediately surroundings + * (North, East, South, West) + * + * @param block the block to check + * @return true if a player cannot stand in the immediate vicinity + */ + 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)); + } - /** - * Determine whether a player can stand on the given block - * - * @param block the block to check - * @return true if the player can stand here - */ - public static boolean canStand(Block block) { - return !(block.isLiquid() || block.getType() == Material.AIR); - } + /** + * Determine whether cannot stand on the block's outer surroundings + * + * @param block the block to check + * @return true if a player cannot stand in areas further away from the 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)); + } - /** - * Determine whether a player is fully submerged in water - * - * @param player the player's location - * @return true if the player is fully in the water - */ - public static boolean isFullyInWater(Location player) { - double touchedX = fixXAxis(player.getX()); + /** + * Determine whether a player can stand on the given block + * + * @param block the block to check + * @return true if the player can stand here + */ + public static boolean canStand(Block block) { + return !(block.isLiquid() || block.getType() == Material.AIR); + } - // 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 :) - 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; - } + /** + * Determine whether a player is fully submerged in water + * + * @param player the player's location + * @return true if the player is fully in the water + */ + public static boolean isFullyInWater(Location player) { + double touchedX = fixXAxis(player.getX()); - 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(); - } + // 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 :) + 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; + } - /** - * Fixes a player's X position to determine the block they are on, even if they're on the edge - * - * @param x player's x position - * @return fixed x position - */ - public static double fixXAxis(double x) { - /* For Z axis, just use Math.round(xaxis); */ - double touchedX = x; - double rem = touchedX - Math.round(touchedX) + 0.01D; - if (rem < 0.30D) { - touchedX = NumberConversions.floor(x) - 1; - } - return touchedX; - } + 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(); + } - /** - * Determine if the player is hovering over water with the given limit - * - * @param player the player's location - * @param blocks max blocks to check - * @return true if the player is hovering over water - */ - public static boolean isHoveringOverWater(Location player, int blocks) { - for (int i = player.getBlockY(); i > player.getBlockY() - blocks; i--) { - Block newloc = (new Location(player.getWorld(), player.getBlockX(), i, player.getBlockZ())).getBlock(); - if (newloc.getType() != Material.AIR) { - return newloc.isLiquid(); - } - } + /** + * Fixes a player's X position to determine the block they are on, even if + * they're on the edge + * + * @param x player's x position + * @return fixed x position + */ + public static double fixXAxis(double x) { + /* For Z axis, just use Math.round(xaxis); */ + double touchedX = x; + double rem = touchedX - Math.round(touchedX) + 0.01D; + if (rem < 0.30D) { + touchedX = NumberConversions.floor(x) - 1; + } + return touchedX; + } - return false; - } + /** + * Determine if the player is hovering over water with the given limit + * + * @param player the player's location + * @param blocks max blocks to check + * @return true if the player is hovering over water + */ + public static boolean isHoveringOverWater(Location player, int blocks) { + for (int i = player.getBlockY(); i > player.getBlockY() - blocks; i--) { + Block newloc = (new Location(player.getWorld(), player.getBlockX(), i, player.getBlockZ())).getBlock(); + if (newloc.getType() != Material.AIR) { + return newloc.isLiquid(); + } + } - /** - * Determine if the player is hovering over water with a hard limit of 25 blocks - * - * @param player the player's location - * @return true if the player is hovering over water - */ - public static boolean isHoveringOverWater(Location player) { - return isHoveringOverWater(player, 25); - } + return false; + } - /** - * Determine whether a material will break instantly when hit - * - * @param m the material to check - * @return true if the material is instant break - */ - public static boolean isInstantBreak(Material m) { - return INSTANT_BREAK.contains(m); - } + /** + * Determine if the player is hovering over water with a hard limit of 25 blocks + * + * @param player the player's location + * @return true if the player is hovering over water + */ + public static boolean isHoveringOverWater(Location player) { + return isHoveringOverWater(player, 25); + } - /** - * Determine whether a material is edible - * - * @param m the material to check - * @return true if the material is food - */ - public static boolean isFood(Material m) { - return FOOD.contains(m); - } + /** + * Determine whether a material will break instantly when hit + * + * @param m the material to check + * @return true if the material is instant break + */ + public static boolean isInstantBreak(Material m) { + return INSTANT_BREAK.contains(m); + } - /** - * Determine whether a block is a slab - * - * @param block block to check - * @return true if slab - */ - public static boolean isSlab(Block block) { - Material type = block.getType(); - switch (type) { - case STEP: - case DOUBLE_STEP: - case WOOD_STEP: - case WOOD_DOUBLE_STEP: - return true; - default: - return false; - } - } + /** + * Determine whether a material is edible + * + * @param m the material to check + * @return true if the material is food + */ + public static boolean isFood(Material m) { + return FOOD.contains(m); + } - /** - * Determine whether a block is a stair - * - * @param block block to check - * @return true if stair - */ - public static boolean isStair(Block block) { - Material type = block.getType(); - switch (type) { - case WOOD_STAIRS: - case SPRUCE_WOOD_STAIRS: - case SMOOTH_STAIRS: - case SANDSTONE_STAIRS: - case QUARTZ_STAIRS: - case JUNGLE_WOOD_STAIRS: - case NETHER_BRICK_STAIRS: - case BIRCH_WOOD_STAIRS: - case COBBLESTONE_STAIRS: - return true; - default: - return false; - } - } + /** + * Determine whether a block is a slab + * + * @param block block to check + * @return true if slab + */ + public static boolean isSlab(Block block) { + Material type = block.getType(); + switch (type) { + case STEP: + case DOUBLE_STEP: + case WOOD_STEP: + case WOOD_DOUBLE_STEP: + return true; + default: + return false; + } + } - /** - * Determine whether a player can interact with this material - * - * @param m material to check - * @return true if interactable - */ - public static boolean isInteractable(Material m) { - return INTERACTABLE.contains(m); - } + /** + * Determine whether a block is a stair + * + * @param block block to check + * @return true if stair + */ + public static boolean isStair(Block block) { + Material type = block.getType(); + switch (type) { + case WOOD_STAIRS: + case SPRUCE_WOOD_STAIRS: + case SMOOTH_STAIRS: + case SANDSTONE_STAIRS: + case QUARTZ_STAIRS: + case JUNGLE_WOOD_STAIRS: + case NETHER_BRICK_STAIRS: + case BIRCH_WOOD_STAIRS: + case COBBLESTONE_STAIRS: + return true; + default: + return false; + } + } - /** - * Determine whether a player is sprinting or flying - * - * @param player player to check - * @return true if sprinting or flying - */ - public static boolean sprintFly(Player player) { - return player.isSprinting() || player.isFlying(); - } + /** + * Determine whether a player can interact with this material + * + * @param m material to check + * @return true if interactable + */ + public static boolean isInteractable(Material m) { + return INTERACTABLE.contains(m); + } - /** - * Determine whether a player is standing on a lily pad - * - * @param player player to check - * @return true if on lily pad - */ - public static boolean isOnLilyPad(Player player) { - Block block = player.getLocation().getBlock(); - Material lily = Material.WATER_LILY; - // TODO: Can we fix X this? - 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; - } + /** + * Determine whether a player is sprinting or flying + * + * @param player player to check + * @return true if sprinting or flying + */ + public static boolean sprintFly(Player player) { + return player.isSprinting() || player.isFlying(); + } - /** - * Determine whether a player is fully submersed in liquid - * - * @param player player to check - * @return true if submersed - */ - public static boolean isSubmersed(Player player) { - return player.getLocation().getBlock().isLiquid() && player.getLocation().getBlock().getRelative(BlockFace.UP).isLiquid(); - } + /** + * Determine whether a player is standing on a lily pad + * + * @param player player to check + * @return true if on lily pad + */ + public static boolean isOnLilyPad(Player player) { + Block block = player.getLocation().getBlock(); + Material lily = Material.WATER_LILY; + // TODO: Can we fix X this? + 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; + } - /** - * Determine whether a player is in water - * - * @param player player to check - * @return true if in water - */ - 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(); - } + /** + * Determine whether a player is fully submersed in liquid + * + * @param player player to check + * @return true if submersed + */ + public static boolean isSubmersed(Player player) { + return player.getLocation().getBlock().isLiquid() + && player.getLocation().getBlock().getRelative(BlockFace.UP).isLiquid(); + } - /** - * Determine whether a player is in a web - * - * @param player player to check - * @return true if in web - */ - public static boolean isInWeb(Player player) { - return player.getLocation().getBlock().getType() == Material.WEB || player.getLocation().getBlock().getRelative(BlockFace.DOWN).getType() == Material.WEB || player.getLocation().getBlock().getRelative(BlockFace.UP).getType() == Material.WEB; - } + /** + * Determine whether a player is in water + * + * @param player player to check + * @return true if in water + */ + 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(); + } - /** - * Determine whether a block is climbable - * - * @param block block to check - * @return true if climbable - */ - public static boolean isClimbableBlock(Block block) { - return block.getType() == Material.VINE || block.getType() == Material.LADDER || block.getType() == Material.WATER || block.getType() == Material.STATIONARY_WATER; - } + /** + * Determine whether a player is in a web + * + * @param player player to check + * @return true if in web + */ + public static boolean isInWeb(Player player) { + return player.getLocation().getBlock().getType() == Material.WEB + || player.getLocation().getBlock().getRelative(BlockFace.DOWN).getType() == Material.WEB + || player.getLocation().getBlock().getRelative(BlockFace.UP).getType() == Material.WEB; + } - /** - * Determine whether a player is on a vine (can be free hanging) - * - * @param player to check - * @return true if on vine - */ - public static boolean isOnVine(Player player) { - return player.getLocation().getBlock().getType() == Material.VINE; - } + /** + * Determine whether a block is climbable + * + * @param block block to check + * @return true if climbable + */ + public static boolean isClimbableBlock(Block block) { + return block.getType() == Material.VINE || block.getType() == Material.LADDER + || block.getType() == Material.WATER || block.getType() == Material.STATIONARY_WATER; + } - /** - * Determine whether a String can be cast to an Integer - * - * @param string text to check - * @return true if int - */ - public static boolean isInt(String string) { - try { - Integer.parseInt(string); - return true; - } catch (Exception ex) { - return false; - } - } + /** + * Determine whether a player is on a vine (can be free hanging) + * + * @param player to check + * @return true if on vine + */ + public static boolean isOnVine(Player player) { + return player.getLocation().getBlock().getType() == Material.VINE; + } - /** - * Determine whether a String can be cast to a Double - * - * @param string text to check - * @return true if double - */ - public static boolean isDouble(String string) { - try { - Double.parseDouble(string); - return true; - } catch (Exception ex) { - return false; - } - } + /** + * Determine whether a String can be cast to an Integer + * + * @param string text to check + * @return true if int + */ + public static boolean isInt(String string) { + try { + Integer.parseInt(string); + return true; + } catch (Exception ex) { + return false; + } + } - /** - * Calculate the time in milliseconds that it should take to break the given block with the given tool - * - * @param tool tool to check - * @param block block to check - * @return time in milliseconds to break - */ - public static long calcSurvivalFastBreak(ItemStack tool, Material block) { - if (isInstantBreak(block) || (tool.getType() == Material.SHEARS && block == Material.LEAVES)) { - return 0; - } - double bhardness = BlockHardness.getBlockHardness(block); - double thardness = ToolHardness.getToolHardness(tool.getType()); - long enchantlvl = (long) tool.getEnchantmentLevel(Enchantment.DIG_SPEED); + /** + * Determine whether a String can be cast to a Double + * + * @param string text to check + * @return true if double + */ + public static boolean isDouble(String string) { + try { + Double.parseDouble(string); + return true; + } catch (Exception ex) { + return false; + } + } - long result = Math.round((bhardness * thardness) * 0.10 * 10000); + /** + * Calculate the time in milliseconds that it should take to break the given + * block with the given tool + * + * @param tool tool to check + * @param block block to check + * @return time in milliseconds to break + */ + public static long calcSurvivalFastBreak(ItemStack tool, Material block) { + if (isInstantBreak(block) || (tool.getType() == Material.SHEARS && block == Material.LEAVES)) { + return 0; + } + double bhardness = BlockHardness.getBlockHardness(block); + double thardness = ToolHardness.getToolHardness(tool.getType()); + long enchantlvl = (long) tool.getEnchantmentLevel(Enchantment.DIG_SPEED); - if (enchantlvl > 0) { - result /= enchantlvl * enchantlvl + 1L; - } + long result = Math.round((bhardness * thardness) * 0.10 * 10000); - result = result > 25000 ? 25000 : result < 0 ? 0 : result; + if (enchantlvl > 0) { + result /= enchantlvl * enchantlvl + 1L; + } - if (isQuickCombo(tool, block)) { - result = result / 2; - } + result = result > 25000 ? 25000 : result < 0 ? 0 : result; - return result; - } + if (isQuickCombo(tool, block)) { + result = result / 2; + } - /** - * Determine whether the given tool is a combination that makes the breaking of this block faster - * - * @param tool tool to check - * @param block block to check - * @return true if quick combo - */ - private static boolean isQuickCombo(ItemStack tool, Material block) { - for (Material t : COMBO.keySet()) { - if (tool.getType() == t && COMBO.get(t) == block) { - return true; - } - } - return false; - } + return result; + } - /** - * Determine if a block ISN'T one of the specified types - * - * @param block block to check - * @param materials array of possible materials - * @return true if the block isn't any of the materials - */ - public static boolean blockIsnt(Block block, Material[] materials) { - Material type = block.getType(); - for (Material m : materials) { - if (m == type) { - return false; - } - } - return false; - } + /** + * Determine whether the given tool is a combination that makes the breaking of + * this block faster + * + * @param tool tool to check + * @param block block to check + * @return true if quick combo + */ + private static boolean isQuickCombo(ItemStack tool, Material block) { + for (Material t : COMBO.keySet()) { + if (tool.getType() == t && COMBO.get(t) == block) { + return true; + } + } + return false; + } - /** - * Parse a COMMAND[] input to a set of commands to execute - * - * @param command input string - * @return parsed commands - */ - public static String[] getCommands(String command) { - return command.replaceAll("COMMAND\\[", "").replaceAll("]", "").split(";"); - } + /** + * Determine if a block ISN'T one of the specified types + * + * @param block block to check + * @param materials array of possible materials + * @return true if the block isn't any of the materials + */ + public static boolean blockIsnt(Block block, Material[] materials) { + Material type = block.getType(); + for (Material m : materials) { + if (m == type) { + return false; + } + } + return false; + } - /** - * Remove all whitespace from the given string to ready it for parsing - * - * @param string the string to parse - * @return string with whitespace removed - */ - public static String removeWhitespace(String string) { - return string.replaceAll(" ", ""); - } + /** + * Parse a COMMAND[] input to a set of commands to execute + * + * @param command input string + * @return parsed commands + */ + public static String[] getCommands(String command) { + return command.replaceAll("COMMAND\\[", "").replaceAll("]", "").split(";"); + } - /** - * Determine if a player has the given enchantment on their armor - * - * @param player player to check - * @param e enchantment to check - * @return true if the armor has this enchantment - */ - public static boolean hasArmorEnchantment(Player player, Enchantment e) { - for (ItemStack is : player.getInventory().getArmorContents()) { - if (is != null && is.containsEnchantment(e)) { - return true; - } - } - return false; - } + /** + * Remove all whitespace from the given string to ready it for parsing + * + * @param string the string to parse + * @return string with whitespace removed + */ + public static String removeWhitespace(String string) { + return string.replaceAll(" ", ""); + } - /** - * Create a list with the given string for execution - * - * @param string the string to parse - * @return ArrayList with string - */ - public static ArrayList stringToList(final String string) { - return new ArrayList() {{ add(string); }}; - } + /** + * Determine if a player has the given enchantment on their armor + * + * @param player player to check + * @param e enchantment to check + * @return true if the armor has this enchantment + */ + public static boolean hasArmorEnchantment(Player player, Enchantment e) { + for (ItemStack is : player.getInventory().getArmorContents()) { + if (is != null && is.containsEnchantment(e)) { + return true; + } + } + return false; + } - /** - * Create a comma-delimited string from a list - * - * @param list the list to parse - * @return the list in a string format - */ - public static String listToCommaString(List list) { - StringBuilder b = new StringBuilder(); - for (int i = 0; i < list.size(); i++) { - b.append(list.get(i)); - if (i < list.size() - 1) { - b.append(","); - } - } - return b.toString(); - } + /** + * Create a list with the given string for execution + * + * @param string the string to parse + * @return ArrayList with string + */ + public static ArrayList stringToList(final String string) { + return new ArrayList() { + { + add(string); + } + }; + } - /** - * Parse a string in the format of "XdXhXmXs" to seconds - * @param string The string to parse - * @return seconds - */ - public static long lifeToSeconds(String string) { - if (string.equals("0") || string.equals("")) return 0; - String[] lifeMatch = new String[]{ "d", "h", "m", "s" }; - int[] lifeInterval = new int[]{ 86400, 3600, 60, 1 }; - long seconds = 0L; + /** + * Create a comma-delimited string from a list + * + * @param list the list to parse + * @return the list in a string format + */ + public static String listToCommaString(List list) { + StringBuilder b = new StringBuilder(); + for (int i = 0; i < list.size(); i++) { + b.append(list.get(i)); + if (i < list.size() - 1) { + b.append(","); + } + } + return b.toString(); + } - for (int i=0;i SUPPORTED_VERSIONS = Arrays.asList(new String[] { - "v1_8", - "v1_9", - "v1_10", - "v1_11", - "v1_12" - }); - + private static final List SUPPORTED_VERSIONS = Arrays + .asList(new String[] { "v1_8", "v1_9", "v1_10", "v1_11", "v1_12" }); + public static String getVersion() { - return Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3]; + return Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3]; } - + public static boolean isSupported() { for (String versionId : SUPPORTED_VERSIONS) { if (getVersion().startsWith(versionId)) { @@ -50,15 +45,16 @@ public class VersionUtil { } return false; } - + private static final EnumSet MOVE_UP_BLOCKS_1_8 = EnumSet.of(Material.ACACIA_STAIRS, Material.BIRCH_WOOD_STAIRS, Material.BRICK_STAIRS, Material.COBBLESTONE_STAIRS, Material.DARK_OAK_STAIRS, Material.JUNGLE_WOOD_STAIRS, Material.NETHER_BRICK_STAIRS, Material.QUARTZ_STAIRS, Material.RED_SANDSTONE_STAIRS, Material.SANDSTONE_STAIRS, Material.SMOOTH_STAIRS, Material.SPRUCE_WOOD_STAIRS, Material.WOOD_STAIRS); - + public static boolean isFlying(Player p) { - if (getVersion().startsWith("v1_9") || getVersion().startsWith("v1_10") || getVersion().startsWith("v1_11") || getVersion().startsWith("v1_12")) { + if (getVersion().startsWith("v1_9") || getVersion().startsWith("v1_10") || getVersion().startsWith("v1_11") + || getVersion().startsWith("v1_12")) { return p.isFlying() || p.isGliding() || p.hasPotionEffect(NMS_1_9_PLUS.LEVITATION); } else { return p.isFlying(); @@ -66,7 +62,8 @@ public class VersionUtil { } public static EnumSet getMoveUpBlocks() { - if (getVersion().startsWith("v1_9") || getVersion().startsWith("v1_10") || getVersion().startsWith("v1_11") || getVersion().startsWith("v1_12")) { + if (getVersion().startsWith("v1_9") || getVersion().startsWith("v1_10") || getVersion().startsWith("v1_11") + || getVersion().startsWith("v1_12")) { return NMS_1_9_PLUS.MOVE_UP_BLOCKS_1_9; } else { return MOVE_UP_BLOCKS_1_8; @@ -74,7 +71,8 @@ public class VersionUtil { } public static boolean isNewYSpeed() { - if (getVersion().startsWith("v1_9") || getVersion().startsWith("v1_10") || getVersion().startsWith("v1_11") || getVersion().startsWith("v1_12")) { + if (getVersion().startsWith("v1_9") || getVersion().startsWith("v1_10") || getVersion().startsWith("v1_11") + || getVersion().startsWith("v1_12")) { return true; } else { return false; @@ -82,7 +80,8 @@ public class VersionUtil { } public static long getHealTime() { - if (getVersion().startsWith("v1_9") || getVersion().startsWith("v1_10") || getVersion().startsWith("v1_11") || getVersion().startsWith("v1_12")) { + if (getVersion().startsWith("v1_9") || getVersion().startsWith("v1_10") || getVersion().startsWith("v1_11") + || getVersion().startsWith("v1_12")) { return 495; } else { return 1995; @@ -90,7 +89,8 @@ public class VersionUtil { } public static boolean isFrostWalk(Player player) { - if (getVersion().startsWith("v1_9") || getVersion().startsWith("v1_10") || getVersion().startsWith("v1_11") || getVersion().startsWith("v1_12")) { + if (getVersion().startsWith("v1_9") || getVersion().startsWith("v1_10") || getVersion().startsWith("v1_11") + || getVersion().startsWith("v1_12")) { if (player.getInventory().getBoots() == null) { return false; } @@ -101,11 +101,12 @@ public class VersionUtil { } public static ItemStack getItemInHand(Player player) { - if (getVersion().startsWith("v1_9") || getVersion().startsWith("v1_10") || getVersion().startsWith("v1_11") || getVersion().startsWith("v1_12")) { + if (getVersion().startsWith("v1_9") || getVersion().startsWith("v1_10") || getVersion().startsWith("v1_11") + || getVersion().startsWith("v1_12")) { return NMS_1_9_PLUS.getItemInHand(player); } else { return player.getItemInHand(); } } - + } diff --git a/src/main/java/com/rammelkast/anticheatreloaded/util/rule/Rule.java b/src/main/java/com/rammelkast/anticheatreloaded/util/rule/Rule.java index d9d4011..aeaed32 100644 --- a/src/main/java/com/rammelkast/anticheatreloaded/util/rule/Rule.java +++ b/src/main/java/com/rammelkast/anticheatreloaded/util/rule/Rule.java @@ -88,7 +88,7 @@ public class Rule { private Type type; public enum Type { - CONDITIONAL(".*[?]*.*:.*", "net.gravitydevelopment.anticheat.util.rule.ConditionalRule"); + CONDITIONAL(".*[?]*.*:.*", "com.rammelkast.anticheatreloaded.util.rule.ConditionalRule"); private String regex; private String c; diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 09cffdd..5f2eafd 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -60,9 +60,12 @@ permissions: anticheat.check.zombe.cheat: description: Allow players to use zombe cheat hack default: false - anticheat.check.fly: + anticheat.check.flight: description: Allow players to fly default: false + anticheat.check.elytra: + description: Allow players to fly when using elytra + default: false anticheat.check.waterwalk: description: Allow players to walk on water default: false