Implement Rules. Adds #154

This commit is contained in:
h31ix committed 2013-02-24 22:38:18 -05:00
1 parent 5db99578ff
commit 2ceb16dcd2
10 files changed
+435 -102

No files matched your search

@@ -25,6 +25,7 @@ import java.util.List;
import java.util.logging.Logger;
import net.h31ix.anticheat.Anticheat;
import net.h31ix.anticheat.manage.AnticheatManager;
import net.h31ix.anticheat.util.rule.Rule;
import net.h31ix.anticheat.util.yaml.CommentedConfiguration;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
@@ -61,8 +62,10 @@ public class Configuration {
private static Language language;
private List<String> exemptWorlds = new ArrayList<String>();
private List<Level> levels = new ArrayList<Level>();
private List<Rule> rules = new ArrayList<Rule>();
private Magic magicInstance;
private int highestLevel;
private boolean updateEvents = false;
public Configuration(AnticheatManager instance) {
micromanage = instance;
@@ -153,9 +156,18 @@ public class Configuration {
}
public int getHighestLevel() {
// TODO: setup
return highestLevel = -99;
}
public List<Rule> getRules() {
return rules;
}
public void setUpdateEvents() {
updateEvents = true;
}
public void updateEvents() {
// Update the old event system to events.yml
CommentedConfiguration config = CommentedConfiguration.loadConfig(configFile);
@@ -178,6 +190,7 @@ public class Configuration {
levels.add(customLevel);
writeEvents();
updateEvents = false;
}
private void writeEvents() {
@@ -198,6 +211,10 @@ public class Configuration {
levels = new ArrayList<Level>();
for(String string : events.getStringList("levels")) {
Level level = Level.load(string);
if(level == null) {
continue;
}
levels.add(level);
highestLevel = level.getValue() > highestLevel ? level.getValue() : highestLevel;
}
@@ -217,10 +234,31 @@ public class Configuration {
}
}
}
rules = new ArrayList<Rule>();
List<String> tempRules = events.getStringList("rules");
for(int i=0;i<tempRules.size();i++) {
String string = tempRules.get(i);
// Old default. Isn't valid anymore.
if (string.equals("Check:SPIDER > 0 ? Level=20 : none")) {
tempRules.set(i, "Check_SPIDER < 0 ? Player.KICK : null");
events.set("rules", tempRules);
continue;
} else if (string.equals("Check_SPIDER < 0 ? Player.KICK : null")) {
// New default rule, won't ever run so we shouldn't load it; only used as example
continue;
}
Rule rule = Rule.load(string);
if(rule != null) {
rules.add(rule);
} else {
Anticheat.getPlugin().getLogger().warning("Couldn't load rule '"+string+"' from config. Improper formatting used.");
}
}
}
public final void load() {
boolean secondLoad = config != null;
config = CommentedConfiguration.loadConfig(configFile);
level = YamlConfiguration.loadConfiguration(levelFile);
magic = YamlConfiguration.loadConfiguration(magicFile);
@@ -275,10 +313,13 @@ public class Configuration {
exemptWorlds = config.getStringList("Disable in");
if(secondLoad) {
readEvents();
if(updateEvents) {
updateEvents();
}
readEvents();
// End pulling values from config
save();
magicInstance = new Magic(getMagic(), this, CommentedConfiguration.loadConfiguration(micromanage.getPlugin().getResource("magic.yml")));
if(micromanage.getBackend() != null) { // If this is first run, backend may not be setup yet
@@ -80,7 +80,7 @@ public class Level {
public static Level load(String string) {
try {
string = string.trim();
string = Utilities.removeWhitespace(string);
String name = string.split(":")[0];
int level = Integer.parseInt(string.split(":")[1]);
if(string.split(":").length == 3) {
@@ -90,8 +90,8 @@ public class Level {
return new Level(name, level);
}
} catch (Exception ex) {
Anticheat.getPlugin().getLogger().warning("An event was intialized with an invalid string: '"+string+"'");
Anticheat.getPlugin().getLogger().warning("The proper format is: 'name: threshold, color' such as 'high: 50, RED'");
Anticheat.getPlugin().getLogger().warning("An event was initialized with an invalid string: '"+string+"'");
Anticheat.getPlugin().getLogger().warning("The proper format is: 'name: threshold : color' such as 'High : 50 : RED'");
Anticheat.getPlugin().getLogger().warning("This event will NOT run. ("+ex.getMessage()+")");
return null;
}
@@ -405,6 +405,16 @@ public final class Utilities {
return command.replaceAll("COMMAND\\[", "").replaceAll("]", "").split(";");
}
/**
* 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(" ", "");
}
/**
* Determine if a player has the given enchantment on their armor
*
@@ -0,0 +1,94 @@
/*
* 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.h31ix.anticheat.util.rule;
import net.h31ix.anticheat.manage.CheckType;
import net.h31ix.anticheat.manage.User;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.util.SortedMap;
/**
* The conditional rule follows the same syntax as the traditional CS conditional operator.<br />
* (CONDITION) ? (TRUE RESULT) : (FALSE RESULT)<br />
* Where CONDITION is a statement that will be evaluated as either <b>TRUE</b> or <b>FALSE</b>
* and the results are actions to be taken for either outcome.
* <br /><br />
*
* Should you need additional actions, the system will recursively parse the following values and handle appropriately.
* <br />
* For instance, (CONDITION) ? (TRUE RESULT) : (CONDITION) ? (TRUE RESULT) : (FALSE RESULT) is a valid rule
* <br /><br />
*
* An example of a valid Conditional Rule:<br />
* Check_SPIDER > 0 ? Player.KICK : null<br />
* <i>The above statement would read 'If the spider check has been failed over zero times, kick the player. Otherwise, do nothing.'</i>
*
* To see syntax for variables and functions that you may use, see {@link net.h31ix.anticheat.util.rule.Rule}
*/
public class ConditionalRule extends Rule {
private static ScriptEngineManager factory = new ScriptEngineManager();
private static ScriptEngine engine = factory.getEngineByName("js");
private static final String TRUE_DELIMITER = "\\?";
private static final String FALSE_DELIMITER = ":";
private static final Type TYPE = Type.CONDITIONAL;
public ConditionalRule(String string) {
super(string, TYPE);
}
@Override
public boolean check(User user, CheckType type) {
try {
// Load all variables
SortedMap<String, Object> map = getVariables(user, type);
for(String key : map.keySet()) {
engine.put(key, map.get(key));
}
boolean value = (Boolean)engine.eval(getString().split(TRUE_DELIMITER)[0]);
// Yo dawg I heard you like conditionals...
String next = value ? getString().split(TRUE_DELIMITER)[1].split(FALSE_DELIMITER)[0] : getString().split(TRUE_DELIMITER)[1].split(FALSE_DELIMITER)[1];
execute(next, user, type);
return value;
} catch (ScriptException e) {
e.printStackTrace();
}
return true;
}
private void execute(String string, User user, CheckType type) {
// If we're told to do nothing
if(string.equalsIgnoreCase("null") || string.equalsIgnoreCase("none")) return;
// If this string is a new conditional statement
if(TYPE.matches(string)) {
new ConditionalRule(string).check(user, type);
} else if(isVariableSet(string)) {
setVariable(string.split("=")[0], string.split("=")[1], user);
} else if(isFunction(string)) {
doFunction(string, type, user);
}
}
}
@@ -0,0 +1,175 @@
/*
* 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.h31ix.anticheat.util.rule;
import net.h31ix.anticheat.Anticheat;
import net.h31ix.anticheat.manage.CheckType;
import net.h31ix.anticheat.manage.User;
import net.h31ix.anticheat.util.Utilities;
import java.lang.reflect.Constructor;
import java.util.*;
/**
* A rule is a scriptable function used to customize the functions of AntiCheat<br />
* Rules are executed whenever a user's level rises.<br /><br />
*
* There are various variables you can use to interact with AntiCheat through your rules<br />
* Variables are denoted with the type followed by a _ followed by the variable name.<br />
* For instance, a variable coming from a user who has used FLY 5 times and is checked by a rule containing 'Check_FLY' will produce a value of 5.
* <br /><br />
*
* <b>Types of variables:</b><br />
* - Check: Contains all valid checks as listed in {@link net.h31ix.anticheat.manage.CheckType}, and will return the number of times this user has failed the given check<br />
* - Player: Contains LEVEL, the player's current level and CHECK, the check that was just failed
* <br /><br />
*
* There are also functions you can use to execute an action within AntiCheat<br />
* Functions are denoted with the type followed by a period followed by the function name.<br />
* For instance, a rule containing Player.KICK will result in the user being kicked.<br />
* <br /><br />
*
* <b>Types of functions:</b><br />
* - Player: RESET, KICK, BAN, COMMAND[command] OR COMMAND[command1;command2]
* <i>- when using commands <b>&player</b> will be replaced by the player name, <b>&world</b> will be replaced by the player's world,
* and <b>&check</b> will be replaced by the check that caused this rule to be run</i><br />
* <br /><br />
*
* The Rule class itself is not an functional rule setup,
* it is inherited and made functional by different implementations of the rule parser.<br />
* The only current Rule implementation is the {@link net.h31ix.anticheat.util.rule.ConditionalRule}
*
*/
public class Rule {
private static String string;
private static final String VARIABLE_SET_REGEX = ".*(_).*=.*";
private static final String FUNCTION_REGEX = ".*\\..*";
private Type type;
public enum Type {
CONDITIONAL(".*[?]*.*:.*", "net.h31ix.anticheat.util.rule.ConditionalRule");
private String regex;
private String c;
private Type(String regex, String c) {
this.regex = regex;
this.c = c;
}
public boolean matches(String s) {
return s.matches(regex);
}
public String getInstance() {
return c;
}
}
public Rule(String string, Type type) {
this.string = string = Utilities.removeWhitespace(string).toLowerCase();
this.type = type;
}
/**
* Check if the rule passed or failed
*
* @param user the user to check
* @return true if the rule has passed, false if failed
*/
public boolean check(User user, CheckType type) {
// Default value
return true;
}
/**
* Load a rule by its string value
*
* @param string the string value to load
* @return an instance of Rule if an implementation exists to handle this rule, null if none are found
*/
public static Rule load(String string) {
for(Type type : Type.values()) {
if(type.matches(string)) {
try {
Class c = Class.forName(type.getInstance());
Constructor con = c.getConstructor(String.class);
return (Rule)con.newInstance(string);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
return null;
}
/**
* Get the type of rule this is
*
* @return a {@link net.h31ix.anticheat.util.rule.Rule.Type}
*/
public Type getType() {
return type;
}
protected String getString() {
return string;
}
protected SortedMap<String, Object> getVariables(User user, CheckType type) {
SortedMap<String, Object> map = new TreeMap<String, Object>();
map.put("player_check", type.name().toLowerCase());
map.put("player_level", user.getLevel());
for(CheckType t : CheckType.values()) {
map.put("check_"+t.name().toLowerCase(), t.getUses(user.getName()));
}
return map;
}
protected void setVariable(String variable, String value, User user) {
// Only variable that can be set for now, may change in the future
// others wouldn't make any sense to set
if(variable.equals("player_level") && Utilities.isInt(value)) {
user.setLevel(Integer.parseInt(value));
}
}
protected void doFunction(String text, CheckType type, User user) {
if(text.toLowerCase().startsWith("player")) {
text = text.split("\\.")[1];
List<String> action = new ArrayList<String>();
action.add(text);
Anticheat.getManager().getUserManager().execute(user, action, type);
}
}
protected boolean isFunction(String string) {
return string.matches(FUNCTION_REGEX);
}
protected boolean isVariableSet(String string) {
return string.matches(VARIABLE_SET_REGEX);
}
@Override
public String toString() {
return type+"{"+string+"}";
}
}