Refactor package to new namespace

This commit is contained in:
h31ix committed 2013-10-13 21:47:19 -04:00
1 parent 089759dbad
commit fd1e5232e0
55 files changed
+5632 -5624

No files matched your search

@@ -0,0 +1,185 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net
*
* 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 <http://www.gnu.org/licenses/>.
*/
package net.gravitydevelopment.anticheat.manage;
import net.gravitydevelopment.anticheat.AntiCheat;
import net.gravitydevelopment.anticheat.config.Configuration;
import net.gravitydevelopment.anticheat.util.FileFormatter;
import net.gravitydevelopment.anticheat.xray.XRayTracker;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.plugin.RegisteredListener;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* The internal hub for all managers.
*/
public class AnticheatManager {
private static AntiCheat plugin = null;
private static Configuration configuration;
private static XRayTracker xrayTracker = null;
private static UserManager userManager = null;
private static CheckManager checkManager = null;
private static Backend backend = null;
private final Logger fileLogger;
private static Map<String, RegisteredListener[]> eventchains = new ConcurrentHashMap<String, RegisteredListener[]>();
private static Map<String, Long> eventcache = new ConcurrentHashMap<String, Long>();
private static List<String> logs = new CopyOnWriteArrayList<String>();
private static Handler fileHandler;
private static final int LOG_LEVEL_HIGH = 3;
public AnticheatManager(AntiCheat instance, Logger logger) {
plugin = instance;
// now load all the others!!!!!
fileLogger = Logger.getLogger("net.gravitydevelopment.anticheat.AntiCheat");
configuration = new Configuration(plugin);
xrayTracker = new XRayTracker();
userManager = new UserManager(configuration);
checkManager = new CheckManager(this, configuration);
backend = new Backend(this);
try {
File file = new File(plugin.getDataFolder(), "log");
if (!file.exists()) {
file.mkdir();
}
fileHandler = new FileHandler(plugin.getDataFolder() + "/log/anticheat.log", true);
fileHandler.setFormatter(new FileFormatter());
} catch (Exception ex) {
logger.log(Level.SEVERE, null, ex);
}
fileLogger.setUseParentHandlers(false);
fileLogger.addHandler(fileHandler);
}
public void log(String message) {
log(message, 0);
}
public void log(String message, int i) {
if (i != 1 && getConfiguration().getConfig().logToConsole.getValue()) {
Bukkit.getConsoleSender().sendMessage("[AntiCheat] " + ChatColor.RED + message);
}
if (i == 0 && getConfiguration().getConfig().fileLogLevel.getValue() == LOG_LEVEL_HIGH) // Not an alert, normal log message
{
fileLog(message);
} else if (getConfiguration().getConfig().fileLogLevel.getValue() != 0) { // alert
fileLog(message);
}
logs.add(ChatColor.stripColor(message));
}
public void fileLog(String message) {
fileLogger.info(message);
}
public List<String> getLastLogs() {
List<String> log = new CopyOnWriteArrayList<String>();
if (logs.size() < 30) {
return logs;
}
for (int i = logs.size() - 1; i >= 0; i--) {
log.add(logs.get(i));
}
logs.clear();
return log;
}
public void addEvent(String e, RegisteredListener[] arr) {
if (!configuration.getConfig().eventChains.getValue())
return;
if (!eventcache.containsKey(e) || eventcache.get(e) > 30000L) {
eventchains.put(e, arr);
eventcache.put(e, System.currentTimeMillis());
}
}
public String getEventChainReport() {
String gen = "";
if (!configuration.getConfig().eventChains.getValue()) {
return "Event Chains is disabled by the configuration." + '\n';
}
if (eventchains.entrySet().size() == 0) {
return "No event chains found." + '\n';
}
for (Entry<String, RegisteredListener[]> e : eventchains.entrySet()) {
String toadd = "";
String ename = e.getKey();
toadd += ename + ":" + '\n';
RegisteredListener[] reg = e.getValue();
for (RegisteredListener plug : reg) {
String pluginname = plug.getPlugin().getName();
if (pluginname.equals("AntiCheat"))
pluginname = "self";
toadd += "- " + pluginname + '\n';
}
gen += toadd + '\n';
}
return gen;
}
public AntiCheat getPlugin() {
return plugin;
}
public Configuration getConfiguration() {
return configuration;
}
public XRayTracker getXRayTracker() {
return xrayTracker;
}
public UserManager getUserManager() {
return userManager;
}
public CheckManager getCheckManager() {
return checkManager;
}
public Backend getBackend() {
return backend;
}
public static void close() {
fileHandler.close();
if (configuration.getConfig().enterprise.getValue()) {
configuration.getEnterprise().database.shutdown();
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,211 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net
*
* 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 <http://www.gnu.org/licenses/>.
*/
package net.gravitydevelopment.anticheat.manage;
import net.gravitydevelopment.anticheat.AntiCheat;
import net.gravitydevelopment.anticheat.config.Configuration;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* <p/>
* The manager that AntiCheat will check with to see if it should watch certain checks and certain players.
*/
public class CheckManager {
private AnticheatManager manager = null;
private Configuration config;
private static List<CheckType> checkIgnoreList = new ArrayList<CheckType>();
private static Map<String, List<CheckType>> exemptList = new HashMap<String, List<CheckType>>();
private static int disabled = 0;
private static int exempt = 0;
public CheckManager(AnticheatManager instance, Configuration config) {
manager = instance;
this.config = config;
}
/**
* Turn a check on
*
* @param type The CheckType to enable
*/
public void activateCheck(CheckType type) {
if (isActive(type)) {
manager.log("The " + type.toString() + " check was activated.");
checkIgnoreList.remove(type);
}
}
/**
* Turn a check off
*
* @param type The CheckType to disable
*/
public void deactivateCheck(CheckType type) {
if (!isActive(type)) {
manager.log("The " + type.toString() + " check was deactivated.");
checkIgnoreList.add(type);
disabled++;
}
}
/**
* Determine whether a check is enabled
*
* @param type The CheckType to check
* @return true if the check is active
*/
public boolean isActive(CheckType type) {
return !checkIgnoreList.contains(type);
}
/**
* Exempt a player from a check
*
* @param player The player
* @param type The check
*/
public void exemptPlayer(Player player, CheckType type) {
if (!isExempt(player, type)) {
if (!exemptList.containsKey(player.getName())) {
exemptList.put(player.getName(), new ArrayList<CheckType>());
}
manager.log(player.getName() + " was exempted from the " + type.toString() + " check.");
exemptList.get(player.getName()).add(type);
exempt++;
}
}
/**
* Unexempt a player from a check
*
* @param player The player
* @param type The check
*/
public void unexemptPlayer(Player player, CheckType type) {
if (isExempt(player, type)) {
manager.log(player.getName() + " was re-added to the " + type.toString() + " check.");
exemptList.get(player.getName()).remove(type);
}
}
/**
* Determine whether a player is exempt from a check
*
* @param player The player
* @param type The check
*/
public boolean isExempt(Player player, CheckType type) {
return exemptList.containsKey(player.getName()) ? exemptList.get(player.getName()).contains(type) : false;
}
/**
* Determine whether a player is exempt from all checks from op status
*
* @param player The player
*/
public boolean isOpExempt(Player player) {
return (this.manager.getConfiguration().getConfig().exemptOp.getValue() && player.isOp());
}
/**
* Determine whether a player should be checked in their world
*
* @param player The player
* @return true if the player's world is enabled
*/
public boolean checkInWorld(Player player) {
return !config.getConfig().exemptedWorlds.getValue().contains(player.getWorld().getName());
}
/**
* Run a quick version of the "willCheck" method, using the other non-check-specific methods beforehand
*
* @param player The player to check
* @param type The check being run
* @return true if the check should run
*/
public boolean willCheckQuick(Player player, CheckType type) {
return
isActive(type)
&& !isExempt(player, type)
&& !type.checkPermission(player);
}
/**
* Determine whether a check should run on a player
*
* @param player The player to check
* @param type The check being run
* @return true if the check should run
*/
public boolean willCheck(Player player, CheckType type) {
boolean check = isActive(type)
&& checkInWorld(player)
&& !isExempt(player, type)
&& !type.checkPermission(player)
&& !isOpExempt(player);
AntiCheat.debugLog("Check " + type + (check ? " run " : " not run ") + "on " + player.getName());
return check;
}
/**
* Determine whether a player is actually online; not an NPC
*
* @param player Player to check
* @return true if the player is a real person
*/
public boolean isOnline(Player player) {
// Check if the player is on the user list, e.g. is not an NPC
for (Player p : Bukkit.getOnlinePlayers()) {
if (p.getName().equals(player.getName())) {
return true;
}
}
return false;
}
/**
* Get the number of exempt players
*
* @return exempt players
*/
public int getExempt() {
int x = exempt;
exempt = 0;
return x;
}
/**
* Get the number of disabled checks
*
* @return disabled checks
*/
public int getDisabled() {
int x = disabled;
disabled = 0;
return x;
}
}
@@ -0,0 +1,125 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net
*
* 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 <http://www.gnu.org/licenses/>.
*/
package net.gravitydevelopment.anticheat.manage;
import net.gravitydevelopment.anticheat.api.CheckFailEvent;
import net.gravitydevelopment.anticheat.util.Permission;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import java.util.HashMap;
import java.util.Map;
/**
* <p/>
* All the types of checks and their corresponding permission nodes.
*/
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),
WATER_WALK(Permission.CHECK_WATERWALK),
NO_SWING(Permission.CHECK_NOSWING),
FAST_BREAK(Permission.CHECK_FASTBREAK),
FAST_PLACE(Permission.CHECK_FASTPLACE),
SPAM(Permission.CHECK_SPAM),
SPRINT(Permission.CHECK_SPRINT),
SNEAK(Permission.CHECK_SNEAK),
SPEED(Permission.CHECK_SPEED),
VCLIP(Permission.CHECK_VCLIP),
SPIDER(Permission.CHECK_SPIDER),
NOFALL(Permission.CHECK_NOFALL),
FAST_BOW(Permission.CHECK_FASTBOW),
FAST_EAT(Permission.CHECK_FASTEAT),
FAST_HEAL(Permission.CHECK_FASTHEAL),
FORCEFIELD(Permission.CHECK_FORCEFIELD),
XRAY(Permission.CHECK_XRAY),
LONG_REACH(Permission.CHECK_LONGREACH),
FAST_PROJECTILE(Permission.CHECK_FASTPROJECTILE),
ITEM_SPAM(Permission.CHECK_ITEMSPAM),
FAST_INVENTORY(Permission.CHECK_FASTINVENTORY),
FAST_ANIMATION(Permission.CHECK_FASTANIMATION),
AUTOTOOL(Permission.CHECK_AUTOTOOL);
private final Permission permission;
private final Map<String, Integer> level = new HashMap<String, Integer>();
/**
* Initialize a CheckType
*
* @param perm Permission that applies to this check
*/
private CheckType(Permission perm) {
this.permission = perm;
}
/**
* Determine whether a player has permission to bypass this check
*
* @param player Player to check
* @return true if the player can bypass
*/
public boolean checkPermission(Player player) {
return permission.get(player);
}
/**
* Log the failure of this check
*
* @param user User who failed the check
*/
public void logUse(User user) {
int amount = level.get(user.getName()) == null ? 1 : level.get(user.getName()) + 1;
level.put(user.getName(), amount);
Bukkit.getServer().getPluginManager().callEvent(new CheckFailEvent(user, this));
}
/**
* Clear failure history of this check for a user
*
* @param name User's name to clear
*/
public void clearUse(String name) {
level.put(name, 0);
}
/**
* Get how many times a user has failed this check
*
* @param name User's name
* @return number of times failed
*/
public int getUses(String name) {
return level.get(name) != null ? level.get(name) : 0;
}
/**
* Get the reference name of a check
*
* @param type Type of check
* @return reference name
*/
public static String getName(CheckType type) {
char[] chars = type.toString().replaceAll("_", " ").toLowerCase().toCharArray();
chars[0] = Character.toUpperCase(chars[0]);
return new String(chars);
}
}
@@ -0,0 +1,37 @@
package net.gravitydevelopment.anticheat.manage;
import com.comphenix.protocol.Packets;
import com.comphenix.protocol.ProtocolManager;
import com.comphenix.protocol.events.*;
import net.gravitydevelopment.anticheat.AntiCheat;
public class PacketManager {
private ProtocolManager protocolManager;
private AntiCheat plugin;
private AnticheatManager manager;
public PacketManager(ProtocolManager protocolManager, AntiCheat plugin, AnticheatManager manager) {
this.protocolManager = protocolManager;
this.plugin = plugin;
this.manager = manager;
addListeners();
}
private void addListeners() {
// Arm Animation
protocolManager.addPacketListener(new PacketAdapter(plugin,
ConnectionSide.CLIENT_SIDE,
ListenerPriority.NORMAL,
Packets.Client.ARM_ANIMATION) {
@Override
public void onPacketReceiving(PacketEvent event) {
if (event.getPacketID() == Packets.Client.ARM_ANIMATION) {
PacketContainer packet = event.getPacket();
//System.out.println("Arm animation from "+packet.getIntegers().read(0));
}
}
});
}
}
@@ -0,0 +1,346 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net
*
* 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 <http://www.gnu.org/licenses/>.
*/
package net.gravitydevelopment.anticheat.manage;
import net.gravitydevelopment.anticheat.AntiCheat;
import net.gravitydevelopment.anticheat.config.Configuration;
import net.gravitydevelopment.anticheat.util.Level;
import net.gravitydevelopment.anticheat.util.Utilities;
import net.gravitydevelopment.anticheat.util.rule.Rule;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
public class User {
private final String name;
private final int id;
private int level = 0;
private Location goodLocation;
private List<ItemStack> inventorySnapshot = null;
private Configuration config = AntiCheat.getManager().getConfiguration();
private int toX, toY, toZ;
private String[] messages = new String[2];
private Long[] messageTimes = new Long[2];
private boolean isWaitingOnLevelSync;
private Timestamp levelSyncTimestamp;
/**
* Initialize an AntiCheat user
*
* @param name Player's name
*/
public User(String name) {
this.name = name;
this.id = getPlayer() != null && getPlayer().isOnline() ? getPlayer().getEntityId() : -1;
}
/**
* 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 Bukkit player
*
* @return Player
*/
public Player getPlayer() {
return Bukkit.getPlayer(name);
}
/**
* Get the user's level value
*
* @return level
*/
public int getLevel() {
return level;
}
public Level getNamedLevel() {
List<Level> levels = config.getEvents().getLevels();
for (int i = 0; i < levels.size(); i++) {
if (i == 0 && level < levels.get(i).getValue()) break;
else if (i == levels.size() - 1) return levels.get(i);
else if (level >= levels.get(i).getValue() && level < levels.get(i + 1).getValue()) return levels.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(name) % 4 != 0) {
// Prevent silent mode from increasing the level way too fast
return false;
} else {
if (level < config.getEvents().getHighestLevel()) {
level++;
// Check levels
for (Level l : getLevels()) {
if (l.getValue() == level) {
AntiCheat.getManager().getUserManager().alert(this, l, type);
if (l.getValue() == config.getEvents().getHighestLevel()) {
level = l.getValue() - 10;
}
}
}
// 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;
}
/**
* 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.getEvents().getHighestLevel()) {
this.level = level;
return true;
} else {
this.level = config.getEvents().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(name);
}
}
/**
* 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;
}
/**
* 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;
}
/**
* 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<ItemStack>();
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;
}
/**
* 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;
}
/**
* 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) {
messages[1] = messages[0];
messages[0] = message;
messageTimes[1] = messageTimes[0];
messageTimes[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 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];
}
/**
* Clear all stored messages
*/
public void clearMessages() {
messages = new String[2];
messageTimes = 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);
}
private List<Level> getLevels() {
return config.getEvents().getLevels();
}
private boolean silentMode() {
return config.getConfig().silentMode.getValue();
}
public void setIsWaitingOnLevelSync(boolean b) {
this.isWaitingOnLevelSync = b;
}
public boolean isWaitingOnLevelSync() {
return isWaitingOnLevelSync;
}
public void setLevelSyncTimestamp(Timestamp timestamp) {
levelSyncTimestamp = timestamp;
}
public Timestamp getLevelSyncTimestamp() {
return levelSyncTimestamp;
}
}
@@ -0,0 +1,229 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net
*
* 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 <http://www.gnu.org/licenses/>.
*/
package net.gravitydevelopment.anticheat.manage;
import net.gravitydevelopment.anticheat.AntiCheat;
import net.gravitydevelopment.anticheat.config.Configuration;
import net.gravitydevelopment.anticheat.util.Level;
import net.gravitydevelopment.anticheat.util.Utilities;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import java.util.ArrayList;
import java.util.List;
public class UserManager {
private List<User> users = new ArrayList<User>();
private static Configuration config;
private static final ChatColor GRAY = ChatColor.GRAY;
private static final ChatColor GOLD = ChatColor.GOLD;
private static final ChatColor YELLOW = ChatColor.YELLOW;
private static final ChatColor RED = ChatColor.RED;
private static List<String> alert;
/**
* Initialize the user manager with a given configuration
*
* @param conf Configuration to use
*/
public UserManager(Configuration conf) {
config = conf;
alert = config.getLang().alert.getValue();
}
/**
* Get a user with the given name
*
* @param name Name
* @return User with name
*/
public User getUser(String name) {
for (User user : users) {
if (user.getName().equalsIgnoreCase(name)) {
return user;
}
}
// Otherwise try to load them
User user = new User(name);
user.setIsWaitingOnLevelSync(true);
config.getLevels().loadLevelToUser(user);
return user;
}
/**
* Get all users
*
* @return List of users
*/
public List<User> getUsers() {
return users;
}
/**
* Add a user to the list
*
* @param user User to add
*/
public void addUser(User user) {
users.add(user);
}
/**
* Remove a user from the list
*
* @param user User to remove
*/
public void remove(User user) {
users.remove(user);
}
/**
* Save a user's level
*
* @param user User to save
*/
public void saveLevel(User user) {
config.getLevels().saveLevelFromUser(user);
}
/**
* Get a user's level, or 0 if the player isn't found
*
* @param name Name of the player
* @return player level
*/
public int safeGetLevel(String name) {
User user = getUser(name);
if (user == null) {
return 0;
} else {
return user.getLevel();
}
}
/**
* Set a user's level
*
* @param name Name of the player
* @param level Level to set
*/
public void safeSetLevel(String name, int level) {
User user = getUser(name);
if (user != null) {
user.setLevel(level);
}
}
/**
* Reset a user
*
* @param name Name of the user
*/
public void safeReset(String name) {
User user = getUser(name);
if (user != null) {
user.resetLevel();
}
}
/**
* Fire an alert
*
* @param user The user to alert
* @param level The user's level
* @param type The CheckType that triggered the alert
*/
public void alert(User user, Level level, CheckType type) {
ArrayList<String> messageArray = new ArrayList<String>();
for (int i = 0; i < alert.size(); i++) {
String message = alert.get(i);
if (!message.equals("")) {
message = message.replaceAll("&player", GOLD + user.getName() + GRAY);
message = message.replaceAll("&check", GOLD + CheckType.getName(type) + GRAY);
message = message.replaceAll("&level", level.getColor() + level.getName() + GRAY);
messageArray.add(message);
}
}
Utilities.alert(messageArray);
execute(user, level.getActions(), type);
}
/**
* Execute configuration actions for an alert
*
* @param user The user
* @param actions The list of actions to execute
* @param type The CheckType that triggered the alert
*/
public void execute(User user, List<String> actions, CheckType type) {
execute(user, actions, type, config.getLang().kickReason.getValue(), config.getLang().playerWarning.getValue(), config.getLang().banReason.getValue());
}
/**
* Execute configuration actions for an alert
*
* @param user The user
* @param actions The list of actions to execute
* @param type The CheckType that triggered the alert
* @param kickReason The config's kick reason
* @param warning The config's warning format
* @param banReason The config's ban reason
*/
public void execute(final User user, final List<String> actions, final CheckType type, final String kickReason, final List<String> warning, final String banReason) {
// Execute synchronously for thread safety when called from AsyncPlayerChatEvent
Bukkit.getScheduler().scheduleSyncDelayedTask(AntiCheat.getPlugin(), new Runnable() {
@Override
public void run() {
final String name = user.getName();
for (String event : actions) {
event = event.replaceAll("&player", name).replaceAll("&world", user.getPlayer().getWorld().getName()).replaceAll("&check", type.name());
if (event.startsWith("COMMAND[")) {
for (String cmd : Utilities.getCommands(event)) {
Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), cmd);
}
} else if (event.equalsIgnoreCase("KICK")) {
user.getPlayer().kickPlayer(RED + kickReason);
String msg = RED + config.getLang().kickBroadcast.getValue().replaceAll("&player", name);
if (!msg.equals("")) {
Bukkit.broadcastMessage(msg);
}
} else if (event.equalsIgnoreCase("WARN")) {
List<String> message = warning;
for (String string : message) {
if (!string.equals("")) {
user.getPlayer().sendMessage(RED + string);
}
}
} else if (event.equalsIgnoreCase("BAN")) {
user.getPlayer().setBanned(true);
user.getPlayer().kickPlayer(RED + banReason);
String msg = RED + config.getLang().banBroadcast.getValue().replaceAll("&player", name);
if (!msg.equals("")) {
Bukkit.broadcastMessage(msg);
}
} else if (event.equalsIgnoreCase("RESET")) {
user.resetLevel();
}
}
}
});
}
}