diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..753c9ee --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +/target/ +.classpath +.DS_Store +.project +.settings/org.eclipse.core.resources.prefs +*.prefs diff --git a/CompatNoCheatPlus/.gitignore b/CompatNoCheatPlus/.gitignore deleted file mode 100644 index bb592db..0000000 --- a/CompatNoCheatPlus/.gitignore +++ /dev/null @@ -1,8 +0,0 @@ -/.settings -/.classpath -/.project -/jar_desc.jardesc -/target -/bin -/.gitignore -/local-maven/ diff --git a/CompatNoCheatPlus/pom.xml b/CompatNoCheatPlus/pom.xml deleted file mode 100644 index b3be648..0000000 --- a/CompatNoCheatPlus/pom.xml +++ /dev/null @@ -1,121 +0,0 @@ - - 4.0.0 - CompatNoCheatPlus - CompatNoCheatPlus - 6.6.6-SNAPSHOT - CompatNoCheatPlus - - - - - scm:git:git@github.com:asofold/${project.name}.git - scm:git:git://github.com/asofold/${project.name}.git - https://github.com/asofold/${project.name} - - - - - - spigot-repo - http://hub.spigotmc.org/nexus/content/repositories/snapshots - - - md_5-snapshots - http://repo.md-5.net/content/repositories/snapshots/ - - - md_5-releases - http://repo.md-5.net/content/repositories/releases/ - - - cititensnpcs - http://repo.citizensnpcs.co/ - - - drtshock-repo - http://ci.drtshock.net/plugin/repository/everything/ - - - - - - - org.bukkit - bukkit - 1.8.8-R0.1-SNAPSHOT - provided - - - com.gmail.nossr50.mcMMO - mcMMO - 1.5.04-SNAPSHOT - provided - - - fr.neatmonster - nocheatplus - 3.16.1-SNAPSHOT - provided - - - net.citizensnpcs - citizensapi - 2.0.16-SNAPSHOT - provided - - - - - - clean package - ${basedir}/src - - - . - true - ${basedir} - - plugin.yml - LICENSE.txt - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 2.5.1 - - 1.6 - 1.6 - - - - org.apache.maven.plugins - maven-jar-plugin - 2.4 - - cncp - - false - false - - false - false - - - - - - - - - - - - - UTF-8 - ? - ? - - \ No newline at end of file diff --git a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/hooks/generic/HookBlockBreak.java b/CompatNoCheatPlus/src/me/asofold/bpl/cncp/hooks/generic/HookBlockBreak.java deleted file mode 100644 index e0267b7..0000000 --- a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/hooks/generic/HookBlockBreak.java +++ /dev/null @@ -1,68 +0,0 @@ -package me.asofold.bpl.cncp.hooks.generic; - -import java.util.Arrays; - -import me.asofold.bpl.cncp.CompatNoCheatPlus; -import me.asofold.bpl.cncp.config.compatlayer.CompatConfig; - -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.block.BlockBreakEvent; - -import fr.neatmonster.nocheatplus.checks.CheckType; -import fr.neatmonster.nocheatplus.components.registry.order.RegistrationOrder.RegisterMethodWithOrder; - -/** - * Wrap block break events to exempt players from checks by comparison of event class names. - * @author mc_dev - * - */ -public class HookBlockBreak extends ClassExemptionHook implements Listener { - - public HookBlockBreak() { - super("block-break."); - defaultClasses.addAll(Arrays.asList(new String[]{ - // MachinaCraft - "ArtificialBlockBreakEvent", - // mcMMO - "FakeBlockBreakEvent", - // MagicSpells - "MagicSpellsBlockBreakEvent" - })); - } - - @Override - public String getHookName() { - return "BlockBreak(default)"; - } - - @Override - public String getHookVersion() { - return "1.1"; - } - - @Override - public Listener[] getListeners() { - return new Listener[]{this}; - } - - @Override - public void applyConfig(CompatConfig cfg, String prefix) { - super.applyConfig(cfg, prefix); - if (classes.isEmpty()) enabled = false; - } - - @EventHandler(priority = EventPriority.LOWEST) - @RegisterMethodWithOrder(tag = CompatNoCheatPlus.tagEarlyFeature, beforeTag = CompatNoCheatPlus.beforeTagEarlyFeature) - public final void onBlockBreakLowest(final BlockBreakEvent event){ - checkExempt(event.getPlayer(), event.getClass(), CheckType.BLOCKBREAK); - } - - @EventHandler(priority = EventPriority.MONITOR) - @RegisterMethodWithOrder(tag = CompatNoCheatPlus.tagLateFeature, afterTag = CompatNoCheatPlus.afterTagLateFeature) - public final void onBlockBreakMonitor(final BlockBreakEvent event){ - checkUnexempt(event.getPlayer(), event.getClass(), CheckType.BLOCKBREAK); - } - -} diff --git a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/hooks/generic/HookBlockPlace.java b/CompatNoCheatPlus/src/me/asofold/bpl/cncp/hooks/generic/HookBlockPlace.java deleted file mode 100644 index ced74b5..0000000 --- a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/hooks/generic/HookBlockPlace.java +++ /dev/null @@ -1,66 +0,0 @@ -package me.asofold.bpl.cncp.hooks.generic; - -import java.util.Arrays; - -import me.asofold.bpl.cncp.CompatNoCheatPlus; -import me.asofold.bpl.cncp.config.compatlayer.CompatConfig; - -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.block.BlockPlaceEvent; - -import fr.neatmonster.nocheatplus.checks.CheckType; -import fr.neatmonster.nocheatplus.components.registry.order.RegistrationOrder.RegisterMethodWithOrder; - -/** - * Wrap block place events to exempt players from checks by comparison of event class names. - * @author mc_dev - * - */ -public class HookBlockPlace extends ClassExemptionHook implements Listener{ - - public HookBlockPlace() { - super("block-place."); - defaultClasses.addAll(Arrays.asList(new String[]{ - // MachinaCraft - "ArtificialBlockPlaceEvent", - // MagicSpells - "MagicSpellsBlockPlaceEvent" - })); - } - - @Override - public String getHookName() { - return "BlockPlace(default)"; - } - - @Override - public String getHookVersion() { - return "1.0"; - } - - @Override - public Listener[] getListeners() { - return new Listener[]{this}; - } - - @Override - public void applyConfig(CompatConfig cfg, String prefix) { - super.applyConfig(cfg, prefix); - if (classes.isEmpty()) enabled = false; - } - - @EventHandler(priority = EventPriority.LOWEST) - @RegisterMethodWithOrder(tag = CompatNoCheatPlus.tagEarlyFeature, beforeTag = CompatNoCheatPlus.beforeTagEarlyFeature) - public final void onBlockPlaceLowest(final BlockPlaceEvent event){ - checkExempt(event.getPlayer(), event.getClass(), CheckType.BLOCKPLACE); - } - - @EventHandler(priority = EventPriority.MONITOR) - @RegisterMethodWithOrder(tag = CompatNoCheatPlus.tagLateFeature, afterTag = CompatNoCheatPlus.afterTagLateFeature) - public final void onBlockPlaceMonitor(final BlockPlaceEvent event){ - checkUnexempt(event.getPlayer(), event.getClass(), CheckType.BLOCKPLACE); - } - -} diff --git a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/hooks/generic/HookEntityDamageByEntity.java b/CompatNoCheatPlus/src/me/asofold/bpl/cncp/hooks/generic/HookEntityDamageByEntity.java deleted file mode 100644 index 00658db..0000000 --- a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/hooks/generic/HookEntityDamageByEntity.java +++ /dev/null @@ -1,70 +0,0 @@ -package me.asofold.bpl.cncp.hooks.generic; - -import java.util.Arrays; - -import me.asofold.bpl.cncp.CompatNoCheatPlus; -import me.asofold.bpl.cncp.config.compatlayer.CompatConfig; - -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityDamageByEntityEvent; - -import fr.neatmonster.nocheatplus.checks.CheckType; -import fr.neatmonster.nocheatplus.components.registry.order.RegistrationOrder.RegisterMethodWithOrder; - -public class HookEntityDamageByEntity extends ClassExemptionHook implements -Listener { - - public HookEntityDamageByEntity() { - super("entity-damage-by-entity."); - defaultClasses.addAll(Arrays.asList(new String[] { - // CrackShot - "WeaponDamageEntityEvent", - // MagicSpells - "MagicSpellsEntityDamageByEntityEvent" })); - } - - @Override - public String getHookName() { - return "EntityDamageByEntity(default)"; - } - - @Override - public String getHookVersion() { - return "0.0"; - } - - @Override - public Listener[] getListeners() { - return new Listener[] { this }; - } - - @Override - public void applyConfig(CompatConfig cfg, String prefix) { - super.applyConfig(cfg, prefix); - if (classes.isEmpty()) - enabled = false; - } - - @EventHandler(priority = EventPriority.LOWEST) - @RegisterMethodWithOrder(tag = CompatNoCheatPlus.tagEarlyFeature, beforeTag = CompatNoCheatPlus.beforeTagEarlyFeature) - public final void onDamageLowest(final EntityDamageByEntityEvent event) { - final Entity damager = event.getDamager(); - if (damager instanceof Player) { - checkExempt((Player) damager, event.getClass(), CheckType.FIGHT); - } - } - - @EventHandler(priority = EventPriority.MONITOR) - @RegisterMethodWithOrder(tag = CompatNoCheatPlus.tagLateFeature, afterTag = CompatNoCheatPlus.afterTagLateFeature) - public final void onDamageMonitor(final EntityDamageByEntityEvent event) { - final Entity damager = event.getDamager(); - if (damager instanceof Player) { - checkUnexempt((Player) damager, event.getClass(), CheckType.FIGHT); - } - } - -} diff --git a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/hooks/generic/HookInstaBreak.java b/CompatNoCheatPlus/src/me/asofold/bpl/cncp/hooks/generic/HookInstaBreak.java deleted file mode 100644 index d3105b4..0000000 --- a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/hooks/generic/HookInstaBreak.java +++ /dev/null @@ -1,176 +0,0 @@ -package me.asofold.bpl.cncp.hooks.generic; - -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; - -import me.asofold.bpl.cncp.CompatNoCheatPlus; -import me.asofold.bpl.cncp.config.compatlayer.CompatConfig; -import me.asofold.bpl.cncp.config.compatlayer.CompatConfigFactory; -import me.asofold.bpl.cncp.config.compatlayer.ConfigUtil; -import me.asofold.bpl.cncp.hooks.AbstractHook; - -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.block.BlockBreakEvent; -import org.bukkit.event.block.BlockDamageEvent; - -import fr.neatmonster.nocheatplus.checks.CheckType; -import fr.neatmonster.nocheatplus.components.registry.order.RegistrationOrder.RegisterMethodWithOrder; -import fr.neatmonster.nocheatplus.utilities.TickTask; - -public class HookInstaBreak extends AbstractHook implements ConfigurableHook, Listener { - - public static interface InstaExemption{ - public void addExemptNext(CheckType[] types); - public Set getExemptNext(); - } - - public static class StackEntry{ - public final CheckType[] checkTypes; - public final int tick; - public final Player player; - public boolean used = false; - public StackEntry(final Player player , final CheckType[] checkTypes){ - this.player = player; - this.checkTypes = checkTypes; - tick = TickTask.getTick(); - } - public boolean isOutdated(final int tick){ - return tick != this.tick; - } - } - - protected static InstaExemption runtime = null; - - public static void addExemptNext(final CheckType[] types){ - runtime.addExemptNext(types); - } - - protected final ExemptionManager exMan = new ExemptionManager(); - - protected boolean enabled = true; - - protected final List stack = new LinkedList(); - - @Override - public String getHookName() { - return "InstaBreak(default)"; - } - - @Override - public String getHookVersion() { - return "1.0"; - } - - @Override - public void applyConfig(CompatConfig cfg, String prefix) { - enabled = cfg.getBoolean(prefix + "insta-break.enabled", true); - } - - @Override - public boolean updateConfig(CompatConfig cfg, String prefix) { - CompatConfig defaults = CompatConfigFactory.getConfig(null); - defaults.set(prefix + "insta-break.enabled", true); - return ConfigUtil.forceDefaults(defaults, cfg); - } - - @Override - public boolean isEnabled() { - return enabled; - } - - @Override - public CheckType[] getCheckTypes() { - return null; - } - - @Override - public Listener[] getListeners() { - runtime = new InstaExemption() { - protected final Set types = new HashSet(); - @Override - public final void addExemptNext(final CheckType[] types) { - for (int i = 0; i < types.length; i++){ - this.types.add(types[i]); - } - } - @Override - public Set getExemptNext() { - return types; - } - }; - return new Listener[]{this}; - } - - protected CheckType[] fetchTypes(){ - final Set types = runtime.getExemptNext(); - final CheckType[] a = new CheckType[types.size()]; - if (!types.isEmpty()) types.toArray(a); - types.clear(); - return a; - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = false) - @RegisterMethodWithOrder(tag = CompatNoCheatPlus.tagLateFeature, afterTag = CompatNoCheatPlus.afterTagLateFeature) - public void onBlockDamage(final BlockDamageEvent event){ - checkStack(); - if (!event.isCancelled() && event.getInstaBreak()){ - stack.add(new StackEntry(event.getPlayer(), fetchTypes())); - } - else{ - runtime.getExemptNext().clear(); - } - } - - @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = false) - @RegisterMethodWithOrder(tag = CompatNoCheatPlus.tagEarlyFeature, beforeTag = CompatNoCheatPlus.beforeTagEarlyFeature) - public void onBlockBreakLowest(final BlockBreakEvent event){ - checkStack(); - if (!stack.isEmpty()){ - final Player player = event.getPlayer(); - final StackEntry entry = stack.get(stack.size() - 1); - if (player.equals(entry.player)) addExemption(entry); - } - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = false) - @RegisterMethodWithOrder(tag = CompatNoCheatPlus.tagLateFeature, afterTag = CompatNoCheatPlus.afterTagLateFeature) - public void onBlockBreakMONITOR(final BlockBreakEvent event){ - if (!stack.isEmpty()){ - final Player player = event.getPlayer(); - final StackEntry entry = stack.get(stack.size() - 1); - if (player.equals(entry.player)) removeExemption(stack.remove(stack.size() - 1)); - } - } - - public void addExemption(final StackEntry entry){ - entry.used = true; - for (int i = 0; i < entry.checkTypes.length; i++){ - exMan.addExemption(entry.player, entry.checkTypes[i]); - } - } - - public void removeExemption(final StackEntry entry){ - if (!entry.used) return; - for (int i = 0; i < entry.checkTypes.length; i++){ - exMan.removeExemption(entry.player, entry.checkTypes[i]); - } - } - - public void checkStack(){ - if (stack.isEmpty()) return; - Iterator it = stack.iterator(); - final int tick = TickTask.getTick(); - while (it.hasNext()){ - final StackEntry entry = it.next(); - if (entry.isOutdated(tick)) it.remove(); - if (entry.used) removeExemption(entry); - } - } - -} diff --git a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/hooks/generic/HookPlayerInteract.java b/CompatNoCheatPlus/src/me/asofold/bpl/cncp/hooks/generic/HookPlayerInteract.java deleted file mode 100644 index 62b3ccd..0000000 --- a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/hooks/generic/HookPlayerInteract.java +++ /dev/null @@ -1,62 +0,0 @@ -package me.asofold.bpl.cncp.hooks.generic; - -import fr.neatmonster.nocheatplus.checks.CheckType; -import fr.neatmonster.nocheatplus.components.registry.order.RegistrationOrder.RegisterMethodWithOrder; -import me.asofold.bpl.cncp.CompatNoCheatPlus; -import me.asofold.bpl.cncp.config.compatlayer.CompatConfig; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.player.PlayerInteractEvent; - -import java.util.Arrays; - -/** - * Wrap player interact events to exempt players from checks by comparison of event class names. - * Uses mc_dev's format for exemption based upon class names. - * - */ -public class HookPlayerInteract extends ClassExemptionHook implements Listener{ - - public HookPlayerInteract() { - super("player-interact."); - defaultClasses.addAll(Arrays.asList(new String[]{ - // MagicSpells - "MagicSpellsPlayerInteractEvent" - })); - } - - @Override - public String getHookName() { - return "Interact(default)"; - } - - @Override - public String getHookVersion() { - return "1.0"; - } - - @Override - public Listener[] getListeners() { - return new Listener[]{this}; - } - - @Override - public void applyConfig(CompatConfig cfg, String prefix) { - super.applyConfig(cfg, prefix); - if (classes.isEmpty()) enabled = false; - } - - @EventHandler(priority = EventPriority.LOWEST) - @RegisterMethodWithOrder(tag = CompatNoCheatPlus.tagEarlyFeature, beforeTag = CompatNoCheatPlus.beforeTagEarlyFeature) - public final void onPlayerInteractLowest(final PlayerInteractEvent event){ - checkExempt(event.getPlayer(), event.getClass(), CheckType.BLOCKINTERACT); - } - - @EventHandler(priority = EventPriority.MONITOR) - @RegisterMethodWithOrder(tag = CompatNoCheatPlus.tagLateFeature, afterTag = CompatNoCheatPlus.afterTagLateFeature) - public final void onPlayerInteractMonitor(final PlayerInteractEvent event){ - checkUnexempt(event.getPlayer(), event.getClass(), CheckType.BLOCKINTERACT); - } - -} diff --git a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/hooks/generic/HookSetSpeed.java b/CompatNoCheatPlus/src/me/asofold/bpl/cncp/hooks/generic/HookSetSpeed.java deleted file mode 100644 index c3e034e..0000000 --- a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/hooks/generic/HookSetSpeed.java +++ /dev/null @@ -1,109 +0,0 @@ -package me.asofold.bpl.cncp.hooks.generic; - -import me.asofold.bpl.cncp.CompatNoCheatPlus; -import me.asofold.bpl.cncp.config.compatlayer.CompatConfig; -import me.asofold.bpl.cncp.config.compatlayer.CompatConfigFactory; -import me.asofold.bpl.cncp.config.compatlayer.ConfigUtil; -import me.asofold.bpl.cncp.hooks.AbstractHook; - -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.player.PlayerJoinEvent; - -import fr.neatmonster.nocheatplus.checks.CheckType; -import fr.neatmonster.nocheatplus.components.registry.order.RegistrationOrder.RegisterMethodWithOrder; - -public class HookSetSpeed extends AbstractHook implements Listener, ConfigurableHook{ - - private static final float defaultFlySpeed = 0.1f; - private static final float defaultWalkSpeed = 0.2f; - - protected float flySpeed = defaultFlySpeed; - protected float walkSpeed = defaultWalkSpeed; - - protected boolean enabled = false; - - // private String allowFlightPerm = "cncp.allow-flight"; - - public HookSetSpeed() throws SecurityException, NoSuchMethodException{ - Player.class.getDeclaredMethod("setFlySpeed", float.class); - } - - public void init(){ - for (final Player player : Bukkit.getOnlinePlayers()){ - setSpeed(player); - } - } - - @Override - public String getHookName() { - return "SetSpeed(default)"; - } - - @Override - public String getHookVersion() { - return "2.2"; - } - - @Override - public CheckType[] getCheckTypes() { - return new CheckType[0]; - } - - @Override - public Listener[] getListeners() { - try{ - // Initialize here, at the end of enable. - init(); - } - catch (Throwable t){} - return new Listener[]{this} ; - } - - public final void setSpeed(final Player player){ - // if (allowFlightPerm.equals("") || player.hasPermission(allowFlightPerm)) player.setAllowFlight(true); - player.setWalkSpeed(walkSpeed); - player.setFlySpeed(flySpeed); - } - - @EventHandler(priority=EventPriority.LOWEST) - @RegisterMethodWithOrder(tag = CompatNoCheatPlus.tagEarlyFeature, beforeTag = CompatNoCheatPlus.beforeTagEarlyFeature) - public final void onPlayerJoin(final PlayerJoinEvent event){ - setSpeed(event.getPlayer()); - } - - @Override - public void applyConfig(CompatConfig cfg, String prefix) { - enabled = cfg.getBoolean(prefix + "set-speed.enabled", false); - flySpeed = cfg.getDouble(prefix + "set-speed.fly-speed", (double) defaultFlySpeed).floatValue(); - walkSpeed = cfg.getDouble(prefix + "set-speed.walk-speed", (double) defaultWalkSpeed).floatValue(); - // allowFlightPerm = cfg.getString(prefix + "set-speed.allow-flight-permission", ref.allowFlightPerm); - } - - @Override - public boolean updateConfig(CompatConfig cfg, String prefix) { - CompatConfig defaults = CompatConfigFactory.getConfig(null); - defaults.set(prefix + "set-speed.enabled", false); - defaults.set(prefix + "set-speed.fly-speed", defaultFlySpeed); - defaults.set(prefix + "set-speed.walk-speed", defaultWalkSpeed); - // cfg.set(prefix + "set-speed.allow-flight-permission", ref.allowFlightPerm); - return ConfigUtil.forceDefaults(defaults, cfg); - } - - @Override - public boolean isEnabled() { - return enabled; - } - - // public String getAllowFlightPerm() { - // return allowFlightPerm; - // } - - // public void setAllowFlightPerm(String allowFlightPerm) { - // this.allowFlightPerm = allowFlightPerm; - // } - -} diff --git a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/hooks/mcmmo/HookmcMMO.java b/CompatNoCheatPlus/src/me/asofold/bpl/cncp/hooks/mcmmo/HookmcMMO.java deleted file mode 100644 index 25a342b..0000000 --- a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/hooks/mcmmo/HookmcMMO.java +++ /dev/null @@ -1,186 +0,0 @@ -package me.asofold.bpl.cncp.hooks.mcmmo; - -import me.asofold.bpl.cncp.CompatNoCheatPlus; -import me.asofold.bpl.cncp.config.compatlayer.CompatConfig; -import me.asofold.bpl.cncp.config.compatlayer.CompatConfigFactory; -import me.asofold.bpl.cncp.config.compatlayer.ConfigUtil; -import me.asofold.bpl.cncp.hooks.AbstractHook; -import me.asofold.bpl.cncp.hooks.generic.ConfigurableHook; -import me.asofold.bpl.cncp.utils.PluginGetter; - -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; - -import com.gmail.nossr50.mcMMO; -import com.gmail.nossr50.events.fake.FakeBlockBreakEvent; -import com.gmail.nossr50.events.fake.FakeBlockDamageEvent; -import com.gmail.nossr50.events.fake.FakeEntityDamageByEntityEvent; - -import fr.neatmonster.nocheatplus.checks.CheckType; -import fr.neatmonster.nocheatplus.components.registry.order.RegistrationOrder.RegisterMethodWithOrder; -import fr.neatmonster.nocheatplus.hooks.NCPHook; - -public final class HookmcMMO extends AbstractHook implements Listener, ConfigurableHook { - - /** - * To let the listener access this. - * @author mc_dev - * - */ - public static interface HookFacade{ - public void damageLowest(Player player); - public void damageMonitor(Player player); - public void blockDamageLowest(Player player); - public void blockDamageMonitor(Player player); - /** - * If to cancel the event. - * @param player - * @return - */ - public boolean blockBreakLowest(Player player); - public void blockBreakMontitor(Player player); - } - - protected HookFacade ncpHook = null; - - protected boolean enabled = true; - - protected String configPrefix = "mcmmo."; - - protected boolean useInstaBreakHook = true; - - - public HookmcMMO(){ - assertPluginPresent("mcMMO"); - } - - - protected final PluginGetter fetch = new PluginGetter("mcMMO"); - - protected int blocksPerSecond = 30; - - - - @Override - public String getHookName() { - return "mcMMO(default)"; - } - - @Override - public String getHookVersion() { - return "2.1"; - } - - @Override - public CheckType[] getCheckTypes() { - return new CheckType[]{ - CheckType.BLOCKBREAK_FASTBREAK, CheckType.BLOCKBREAK_NOSWING, // old ones - - // CheckType.BLOCKBREAK_DIRECTION, CheckType.BLOCKBREAK_FREQUENCY, - // CheckType.BLOCKBREAK_WRONGBLOCK, CheckType.BLOCKBREAK_REACH, - // - // CheckType.FIGHT_ANGLE, CheckType.FIGHT_SPEED, // old ones - // - // CheckType.FIGHT_DIRECTION, CheckType.FIGHT_NOSWING, - // CheckType.FIGHT_REACH, - }; - } - - @Override - public Listener[] getListeners() { - fetch.fetchPlugin(); - return new Listener[]{this, fetch}; - } - - @Override - public NCPHook getNCPHook() { - if (ncpHook == null){ - ncpHook = new HookFacadeImpl(useInstaBreakHook, blocksPerSecond); - } - return (NCPHook) ncpHook; - } - - /////////////////////////// - // Damage (fight) - ////////////////////////// - - @EventHandler(priority=EventPriority.LOWEST) - @RegisterMethodWithOrder(tag = CompatNoCheatPlus.tagEarlyFeature, beforeTag = CompatNoCheatPlus.beforeTagEarlyFeature) - public final void onDamageLowest(final FakeEntityDamageByEntityEvent event){ - final Entity entity = event.getDamager(); - if (entity instanceof Player) - ncpHook.damageLowest((Player) entity); - } - - @EventHandler(priority=EventPriority.MONITOR) - @RegisterMethodWithOrder(tag = CompatNoCheatPlus.tagLateFeature, afterTag = CompatNoCheatPlus.afterTagLateFeature) - public final void onDamageMonitor(final FakeEntityDamageByEntityEvent event){ - final Entity entity = event.getDamager(); - if (entity instanceof Player) - ncpHook.damageMonitor((Player) entity); - } - - /////////////////////////// - // Block damage - ////////////////////////// - - @EventHandler(priority=EventPriority.LOWEST) - @RegisterMethodWithOrder(tag = CompatNoCheatPlus.tagEarlyFeature, beforeTag = CompatNoCheatPlus.beforeTagEarlyFeature) - public final void onBlockDamageLowest(final FakeBlockDamageEvent event){ - ncpHook.blockDamageLowest(event.getPlayer()); - } - - @EventHandler(priority=EventPriority.LOWEST) - @RegisterMethodWithOrder(tag = CompatNoCheatPlus.tagEarlyFeature, beforeTag = CompatNoCheatPlus.beforeTagEarlyFeature) - public final void onBlockDamageMonitor(final FakeBlockDamageEvent event){ - ncpHook.blockDamageMonitor(event.getPlayer()); - } - - /////////////////////////// - // Block break - ////////////////////////// - - @EventHandler(priority=EventPriority.LOWEST) - @RegisterMethodWithOrder(tag = CompatNoCheatPlus.tagEarlyFeature, beforeTag = CompatNoCheatPlus.beforeTagEarlyFeature) - public final void onBlockBreakLowest(final FakeBlockBreakEvent event){ - if (ncpHook.blockBreakLowest(event.getPlayer())){ - event.setCancelled(true); - // System.out.println("Cancelled for frequency."); - } - } - - @EventHandler(priority=EventPriority.MONITOR) - @RegisterMethodWithOrder(tag = CompatNoCheatPlus.tagLateFeature, afterTag = CompatNoCheatPlus.afterTagLateFeature) - public final void onBlockBreakLMonitor(final FakeBlockBreakEvent event){ - ncpHook.blockBreakMontitor(event.getPlayer()); - } - - ///////////////////////////////// - // Config - ///////////////////////////////// - - @Override - public void applyConfig(CompatConfig cfg, String prefix) { - enabled = cfg.getBoolean(prefix + configPrefix + "enabled", true); - useInstaBreakHook = cfg.getBoolean(prefix + configPrefix + "use-insta-break-hook", true); - blocksPerSecond = cfg.getInt(prefix + configPrefix + "clickspersecond", 20); - } - - @Override - public boolean updateConfig(CompatConfig cfg, String prefix) { - CompatConfig defaults = CompatConfigFactory.getConfig(null); - defaults.set(prefix + configPrefix + "enabled", true); - defaults.set(prefix + configPrefix + "use-insta-break-hook", true); - defaults.set(prefix + configPrefix + "clickspersecond", 20); - return ConfigUtil.forceDefaults(defaults, cfg); - } - - @Override - public boolean isEnabled() { - return enabled; - } - -} diff --git a/CompatNoCheatPlus/LICENSE.txt b/LICENSE.txt similarity index 97% rename from CompatNoCheatPlus/LICENSE.txt rename to LICENSE.txt index 3d90694..20d40b6 100644 --- a/CompatNoCheatPlus/LICENSE.txt +++ b/LICENSE.txt @@ -1,674 +1,674 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - 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 . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + 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 . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read . \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..19ecdf4 --- /dev/null +++ b/README.md @@ -0,0 +1,4 @@ + +CompatNoCheatPlus +--------- +CompatNoCheatPlus (cncp) provides compatibility between the anti cheat plugin NoCheatPlus and other plugins that add game mechanics different to the vanilla game behavior, such as mcMMO or plugins that add npcs such as Citizens and protocol hack like Geyser for cross-platform to play with. diff --git a/bungee.yml b/bungee.yml new file mode 100644 index 0000000..3bd2381 --- /dev/null +++ b/bungee.yml @@ -0,0 +1,4 @@ +name: CompatNoCheatPlus +main: me.asofold.bpl.cncp.bungee.CompatNoCheatPlus +version: ${project.version}-${buildDescription} +author: asofold, xaw3ep \ No newline at end of file diff --git a/CompatNoCheatPlus/cncp_lists.txt b/cncp_lists.txt similarity index 96% rename from CompatNoCheatPlus/cncp_lists.txt rename to cncp_lists.txt index 4e4235e..ab4bd3a 100644 --- a/CompatNoCheatPlus/cncp_lists.txt +++ b/cncp_lists.txt @@ -1,72 +1,72 @@ -CompatNoCheatPlus lists file -------------------------------------------------------- - -Compatibility hooks for NoCheatPlus! - -LICENSE -------------------------- -LICENSE.txt (Same as NoCheatPlus). - - -STACK ---------- -?(add) more intricate load order stuff ? [best would be to force managelisteners with ncp] - -*** -!(add) reload command - -? another sequence number (for standard events) - -*** ADD MORE GENERIC HOOKS - -!add check type and permission hooks, also for worldguard regions. - -Citizens2 / Player class: make configurable (hidden) Or do internally: List of checks to use , exclude moving if possible. - -Generic abstract class for the mcMMO style cancelling of next x events + ticks alive etc - -add stats hook ? - -add a good mechanism for adding external configurable hooks (read automatically from the cncp config). - - -!(add) Use some exemption mechanism for npcs (generic player class hook + citizens). -!consider remove: clearing the VL ? => probably not, needs redesign to also monitor block break. + only clear the necessary bits (not frequency) - -! try: insta break: keep exemption (unless cancelled) for next block break event (!). -> maybe ncp - - -? HookInstaBreak : add static method to sset check types to exempt from for next break ? - -cncp: check at least for logs / leaves for skill specific block types - - -hookiinstabreak: let hooks fail completely if listeners are failing to register ? - - -*** CLEANUP THIS, BETTER METHODS, INTEGRATE SOME INTO NCP MAYBE - -* Auto detection of unknown events + log on disable + info command. -? analysis tools like event-Mirror ? - -* More generic hooks, clean methods! - -! Strip down mcMMO hook to add a new one / integrate into instabreak -! Clean up hooks, use TickTask and "next" to confine fuzzy unexemption to a minimum. - --------------------------- - -support for instant spells ? [internalName or name ? <- guess: name] - -? register listeners with NCP directly? also use annotations ? - -! Smarter way to enable / disable PlayerClassHoook (disable by default for now). -! if SpoutPlugin is present: add blocks to ignorepassable automatically / adjust flags ? [generic block setup] - -? add info command: show all hooks and so on. - - -add class-name inspection methods (!). - -set-speed: per world options ? [per world config concept] -set-speed: add option to set speed to default speed on player quit/kick +CompatNoCheatPlus lists file +------------------------------------------------------- + +Compatibility hooks for NoCheatPlus! + +LICENSE +------------------------- +LICENSE.txt (Same as NoCheatPlus). + + +STACK +--------- +?(add) more intricate load order stuff ? [best would be to force managelisteners with ncp] + +*** +!(add) reload command + +? another sequence number (for standard events) + +*** ADD MORE GENERIC HOOKS + +!add check type and permission hooks, also for worldguard regions. + +Citizens2 / Player class: make configurable (hidden) Or do internally: List of checks to use , exclude moving if possible. + +Generic abstract class for the mcMMO style cancelling of next x events + ticks alive etc + +add stats hook ? + +add a good mechanism for adding external configurable hooks (read automatically from the cncp config). + + +!(add) Use some exemption mechanism for npcs (generic player class hook + citizens). +!consider remove: clearing the VL ? => probably not, needs redesign to also monitor block break. + only clear the necessary bits (not frequency) + +! try: insta break: keep exemption (unless cancelled) for next block break event (!). -> maybe ncp + + +? HookInstaBreak : add static method to sset check types to exempt from for next break ? + +cncp: check at least for logs / leaves for skill specific block types + + +hookiinstabreak: let hooks fail completely if listeners are failing to register ? + + +*** CLEANUP THIS, BETTER METHODS, INTEGRATE SOME INTO NCP MAYBE + +* Auto detection of unknown events + log on disable + info command. +? analysis tools like event-Mirror ? + +* More generic hooks, clean methods! + +! Strip down mcMMO hook to add a new one / integrate into instabreak +! Clean up hooks, use TickTask and "next" to confine fuzzy unexemption to a minimum. + +-------------------------- + +support for instant spells ? [internalName or name ? <- guess: name] + +? register listeners with NCP directly? also use annotations ? + +! Smarter way to enable / disable PlayerClassHoook (disable by default for now). +! if SpoutPlugin is present: add blocks to ignorepassable automatically / adjust flags ? [generic block setup] + +? add info command: show all hooks and so on. + + +add class-name inspection methods (!). + +set-speed: per world options ? [per world config concept] +set-speed: add option to set speed to default speed on player quit/kick diff --git a/libs/CMIAPI7.6.2.0.jar b/libs/CMIAPI7.6.2.0.jar new file mode 100644 index 0000000..d5cd1a6 Binary files /dev/null and b/libs/CMIAPI7.6.2.0.jar differ diff --git a/libs/GravityTubes.jar b/libs/GravityTubes.jar new file mode 100644 index 0000000..a11bf3b Binary files /dev/null and b/libs/GravityTubes.jar differ diff --git a/libs/mcMMO-2.1.158.jar b/libs/mcMMO-2.1.158.jar new file mode 100644 index 0000000..02ece6b Binary files /dev/null and b/libs/mcMMO-2.1.158.jar differ diff --git a/CompatNoCheatPlus/plugin.yml b/plugin.yml similarity index 79% rename from CompatNoCheatPlus/plugin.yml rename to plugin.yml index 130b68a..264443a 100644 --- a/CompatNoCheatPlus/plugin.yml +++ b/plugin.yml @@ -1,19 +1,21 @@ -name: CompatNoCheatPlus -main: me.asofold.bpl.cncp.CompatNoCheatPlus -version: ${project.version}-s${BUILD_SERIES}-b${BUILD_NUMBER} -dev-url: http://dev.bukkit.org/server-mods/compatnocheatplus-cncp/ - -depend: -- NoCheatPlus -softdepend: -- mcMMO -- Citizens -- MagicSpells - -commands: - compatnocheatplus: - description: 'Show general version information of cncp and dependencies.' - usage: '/' - permission: 'cncp.cmd.info' - aliases: - - cncp +name: CompatNoCheatPlus +main: me.asofold.bpl.cncp.CompatNoCheatPlus +version: ${project.version}-${buildDescription} +dev-url: http://dev.bukkit.org/server-mods/compatnocheatplus-cncp/ +api-version: 1.13 +folia-supported: true + +loadbefore: +- NoCheatPlus +softdepend: +- mcMMO +- Citizens +- MagicSpells + +commands: + compatnocheatplus: + description: 'Show general version information of cncp and dependencies.' + usage: '/' + permission: 'cncp.cmd.info' + aliases: + - cncp diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..b60cf00 --- /dev/null +++ b/pom.xml @@ -0,0 +1,187 @@ + + 4.0.0 + CompatNoCheatPlus + CompatNoCheatPlus + 6.6.7-SNAPSHOT + CompatNoCheatPlus + + + + + scm:git:git@github.com:asofold/${project.name}.git + scm:git:git://github.com/asofold/${project.name}.git + https://github.com/asofold/${project.name} + + + + + + opencollab-snapshot-repo + https://repo.opencollab.dev/maven-snapshots/ + + false + + + true + + + + jitpack.io + https://jitpack.io + + + viaversion-repo + https://repo.viaversion.com + + + bungeecord-repo + https://oss.sonatype.org/content/repositories/snapshots + + + + + + + org.spigotmc + spigot + 1.8.8-R0.1-SNAPSHOT + provided + + + com.gmail.nossr50.mcMMO + mcMMO + 2.1.158 + system + ${basedir}/libs/mcMMO-2.1.158.jar + + + net.citizensnpcs + citizensapi + 2.0.26-SNAPSHOT + provided + + + com.benzoft.gravitytubes + gravitytubes + 1.0 + system + ${basedir}/libs/GravityTubes.jar + + + com.Zrips.CMI + CMI + 1.0 + system + ${basedir}/libs/CMIAPI7.6.2.0.jar + + + com.github.updated-nocheatplus.nocheatplus + nocheatplus + -SNAPSHOT + + + org.geysermc + connector + 1.4.2-SNAPSHOT + provided + + + org.geysermc.floodgate + api + 2.0-SNAPSHOT + provided + + + net.md-5 + bungeecord-api + 1.19-R0.1-SNAPSHOT + + + com.viaversion + viaversion-api + LATEST + + + net.md-5 + bungeecord-event + 1.19-R0.1-SNAPSHOT + + + + + + + timestamp + + + !env.BUILD_NUMBER + + + + ${maven.build.timestamp} + + + + dynamic_build_number + + + env.BUILD_NUMBER + + + + b${env.BUILD_NUMBER} + + + + + + + clean package + ${basedir}/src + + + . + true + ${basedir} + + plugin.yml + LICENSE.txt + bungee.yml + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.5.1 + + 1.8 + 1.8 + + + + org.apache.maven.plugins + maven-jar-plugin + 2.4 + + cncp + + false + false + + false + false + + + + + + + + + + UTF-8 + yyyy_MM_dd-HH_mm + + diff --git a/src/me/asofold/bpl/cncp/ClientVersion/ClientVersionListener.java b/src/me/asofold/bpl/cncp/ClientVersion/ClientVersionListener.java new file mode 100644 index 0000000..e9acd49 --- /dev/null +++ b/src/me/asofold/bpl/cncp/ClientVersion/ClientVersionListener.java @@ -0,0 +1,50 @@ +package me.asofold.bpl.cncp.ClientVersion; + +import java.lang.reflect.Method; + +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.plugin.Plugin; + +import com.viaversion.viaversion.api.Via; +import fr.neatmonster.nocheatplus.compat.Folia; +import fr.neatmonster.nocheatplus.players.DataManager; +import fr.neatmonster.nocheatplus.players.IPlayerData; +import fr.neatmonster.nocheatplus.utilities.ReflectionUtil; +import me.asofold.bpl.cncp.CompatNoCheatPlus; + +public class ClientVersionListener implements Listener { + + private Plugin ViaVersion = Bukkit.getPluginManager().getPlugin("ViaVersion"); + private Plugin ProtocolSupport = Bukkit.getPluginManager().getPlugin("ProtocolSupport"); + private final Class ProtocolSupportAPIClass = ReflectionUtil.getClass("protocolsupport.api.ProtocolSupportAPI"); + private final Class ProtocolVersionClass = ReflectionUtil.getClass("protocolsupport.api.ProtocolVersion"); + private final Method getProtocolVersion = ProtocolSupportAPIClass == null ? null : ReflectionUtil.getMethod(ProtocolSupportAPIClass, "getProtocolVersion", Player.class); + + @SuppressWarnings("unchecked") + @EventHandler(priority = EventPriority.MONITOR) + public void onPlayerJoin(PlayerJoinEvent event) { + final Player player = event.getPlayer(); + Folia.runSyncDelayedTask(CompatNoCheatPlus.getInstance(), (arg) -> { + final IPlayerData pData = DataManager.getPlayerData(player); + if (pData != null) { + if (ViaVersion != null && ViaVersion.isEnabled()) { + // Give precedence to ViaVersion + pData.setClientVersionID(Via.getAPI().getPlayerVersion(player)); + } + else if (ProtocolSupport != null && getProtocolVersion != null && ProtocolSupport.isEnabled()) { + // Fallback to PS (reflectively, due to PS not having a valid mvn repo) + Object protocolVersion = ReflectionUtil.invokeMethod(getProtocolVersion, null, player); + Method getId = ReflectionUtil.getMethodNoArgs(ProtocolVersionClass, "getId", int.class); + int version = (int) ReflectionUtil.invokeMethodNoArgs(getId, protocolVersion); + pData.setClientVersionID(version); + } + // (Client version stays unknown (-1)) + } + }, 20); // Wait 20 ticks before setting client data + } +} diff --git a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/CompatNoCheatPlus.java b/src/me/asofold/bpl/cncp/CompatNoCheatPlus.java similarity index 62% rename from CompatNoCheatPlus/src/me/asofold/bpl/cncp/CompatNoCheatPlus.java rename to src/me/asofold/bpl/cncp/CompatNoCheatPlus.java index bbea373..1cc2fc9 100644 --- a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/CompatNoCheatPlus.java +++ b/src/me/asofold/bpl/cncp/CompatNoCheatPlus.java @@ -1,423 +1,503 @@ -package me.asofold.bpl.cncp; - -import java.io.File; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; -import java.util.logging.Level; - -import org.bukkit.Bukkit; -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; -import org.bukkit.event.Listener; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.PluginDescriptionFile; -import org.bukkit.plugin.PluginManager; -import org.bukkit.plugin.java.JavaPlugin; - -import fr.neatmonster.nocheatplus.NCPAPIProvider; -import fr.neatmonster.nocheatplus.components.registry.feature.IDisableListener; -import fr.neatmonster.nocheatplus.components.registry.order.RegistrationOrder; -import fr.neatmonster.nocheatplus.hooks.NCPHook; -import fr.neatmonster.nocheatplus.hooks.NCPHookManager; -import me.asofold.bpl.cncp.config.Settings; -import me.asofold.bpl.cncp.config.compatlayer.CompatConfig; -import me.asofold.bpl.cncp.config.compatlayer.NewConfig; -import me.asofold.bpl.cncp.hooks.Hook; -import me.asofold.bpl.cncp.hooks.generic.ConfigurableHook; -import me.asofold.bpl.cncp.hooks.generic.HookBlockBreak; -import me.asofold.bpl.cncp.hooks.generic.HookBlockPlace; -import me.asofold.bpl.cncp.hooks.generic.HookEntityDamageByEntity; -import me.asofold.bpl.cncp.hooks.generic.HookInstaBreak; -import me.asofold.bpl.cncp.hooks.generic.HookPlayerClass; -import me.asofold.bpl.cncp.hooks.generic.HookPlayerInteract; -import me.asofold.bpl.cncp.utils.TickTask2; - -/** - * Quick attempt to provide compatibility to NoCheatPlus (by NeatMonster) for - * some other plugins that change the vanilla game mechanichs, for instance by - * fast block breaking. - * - * @author asofold - * - */ -public class CompatNoCheatPlus extends JavaPlugin { - - //TODO: Adjust, once NCP has order everywhere (generic + ncp-specific?). - - public static final String tagEarlyFeature = "cncp.feature.early"; - public static final String beforeTagEarlyFeature = ".*nocheatplus.*|.*NoCheatPlus.*"; - - public static final String tagLateFeature = "cncp.feature.late"; - public static final String afterTagLateFeature = "cncp.system.early.*|.*nocheatplus.*|.*NoCheatPlus.*)"; - - public static final String tagEarlySystem = "cncp.system.early"; - public static final String beforeTagEarlySystem = beforeTagEarlyFeature; // ... - - public static final RegistrationOrder defaultOrderSystemEarly = new RegistrationOrder( - tagEarlySystem, - beforeTagEarlySystem, - null); - - public static final RegistrationOrder defaultOrderFeatureEarly = new RegistrationOrder( - tagEarlyFeature, - beforeTagEarlyFeature, - "cncp.system.early.*"); - - public static final RegistrationOrder defaultOrderFeatureLate = new RegistrationOrder( - tagLateFeature, - null, - afterTagLateFeature); - - private final Settings settings = new Settings(); - - /** Hooks registered with cncp */ - private static final Set registeredHooks = new HashSet(); - - private final List builtinHooks = new LinkedList(); - - /** - * Flag if plugin is enabled. - */ - private static boolean enabled = false; - - /** - * Static method to enable a plugin (might also be useful for hooks). - * @param plgName - * @return - */ - public static boolean enablePlugin(String plgName) { - PluginManager pm = Bukkit.getPluginManager(); - Plugin plugin = pm.getPlugin(plgName); - if (plugin == null) return false; - if (pm.isPluginEnabled(plugin)) return true; - pm.enablePlugin(plugin); - return true; - } - - /** - * Static method to disable a plugin (might also be useful for hooks). - * @param plgName - * @return - */ - public static boolean disablePlugin(String plgName){ - PluginManager pm = Bukkit.getPluginManager(); - Plugin plugin = pm.getPlugin(plgName); - if (plugin == null) return false; - if (!pm.isPluginEnabled(plugin)) return true; - pm.disablePlugin(plugin); - return true; - } - - /** - * Get the plugin instance. - * @return - */ - public static CompatNoCheatPlus getInstance(){ - return CompatNoCheatPlus.getPlugin(CompatNoCheatPlus.class); - } - - /** - * API to add a hook. Adds the hook AND registers listeners if enabled. Also respects the configuration for preventing hooks.
- * If you want to not register the listeners use NCPHookManager. - * @param hook - * @return - */ - public static boolean addHook(Hook hook){ - if (Settings.preventAddHooks.contains(hook.getHookName())){ - Bukkit.getLogger().info("[cncp] Prevented adding hook: "+hook.getHookName() + " / " + hook.getHookVersion()); - return false; - } - registeredHooks.add(hook); - if (enabled) registerListeners(hook); - boolean added = checkAddNCPHook(hook); // Add if plugin is present, otherwise queue for adding. - Bukkit.getLogger().info("[cncp] Registered hook"+(added?"":"(NCPHook might get added later)")+": "+hook.getHookName() + " / " + hook.getHookVersion()); - return true; - } - - /** - * If already added to NCP - * @param hook - * @return - */ - private static boolean checkAddNCPHook(Hook hook) { - PluginManager pm = Bukkit.getPluginManager(); - Plugin plugin = pm.getPlugin("NoCheatPlus"); - if (plugin == null || !pm.isPluginEnabled(plugin)) - return false; - NCPHook ncpHook = hook.getNCPHook(); - if (ncpHook != null) - NCPHookManager.addHook(hook.getCheckTypes(), ncpHook); - return true; - } - - /** - * Conveniently register the listeners, do not use if you add/added the hook with addHook. - * @param hook - * @return - */ - public static boolean registerListeners(Hook hook) { - if (!enabled) { - return false; - } - Listener[] listeners = hook.getListeners(); - if (listeners != null){ - // attempt to register events: - Plugin plg = CompatNoCheatPlus.getPlugin(CompatNoCheatPlus.class); - if (plg == null) { - return false; - } - for (Listener listener : listeners) { - NCPAPIProvider.getNoCheatPlusAPI().getEventRegistry().register(listener, - defaultOrderFeatureEarly, plg); - } - } - return true; - } - - // ---- - - /** - * Called before loading settings, adds available hooks into a list, so they will be able to read config. - */ - private void setupBuiltinHooks() { - builtinHooks.clear(); - // Might-fail hooks: - // Set speed - try{ - builtinHooks.add(new me.asofold.bpl.cncp.hooks.generic.HookSetSpeed()); - } - catch (Throwable t){} - // Citizens 2 - try{ - builtinHooks.add(new me.asofold.bpl.cncp.hooks.citizens2.HookCitizens2()); - } - catch (Throwable t){} - // mcMMO - try{ - builtinHooks.add(new me.asofold.bpl.cncp.hooks.mcmmo.HookmcMMO()); - } - catch (Throwable t){} - // // MagicSpells - // try{ - // builtinHooks.add(new me.asofold.bpl.cncp.hooks.magicspells.HookMagicSpells()); - // } - // catch (Throwable t){} - // Simple generic hooks - for (Hook hook : new Hook[]{ - new HookPlayerClass(), - new HookBlockBreak(), - new HookBlockPlace(), - new HookInstaBreak(), - new HookEntityDamageByEntity(), - new HookPlayerInteract() - }){ - builtinHooks.add(hook); - } - } - - /** - * Add standard hooks if enabled. - */ - private void addAvailableHooks() { - - // Add built in hooks: - for (Hook hook : builtinHooks){ - boolean add = true; - if (hook instanceof ConfigurableHook){ - if (!((ConfigurableHook)hook).isEnabled()) add = false; - } - if (add){ - try{ - addHook(hook); - } - catch (Throwable t){} - } - } - } - - @Override - public void onEnable() { - enabled = false; // make sure - // (no cleanup) - - // Settings: - settings.clear(); - setupBuiltinHooks(); - loadSettings(); - // Register own listener: - //NCPAPIProvider.getNoCheatPlusAPI().getEventRegistry().register(this, defaultOrderSystemEarly, this); - super.onEnable(); - - // Add Hooks: - addAvailableHooks(); // add before enable is set to not yet register listeners. - enabled = true; - - // register all listeners: - for (Hook hook : registeredHooks){ - registerListeners(hook); - } - - // Register to remove hooks when NCP is disabling. - NCPAPIProvider.getNoCheatPlusAPI().addComponent(new IDisableListener(){ - @Override - public void onDisable() { - // Remove all registered cncp hooks: - unregisterNCPHooks(); - } - }); - if (!registeredHooks.isEmpty()) { - registerHooks(); - } - - // Start ticktask 2 - // TODO: Replace by using TickTask ? Needs order (depend is used now)? - getServer().getScheduler().scheduleSyncRepeatingTask(this, new TickTask2(), 1, 1); - - // Finished. - getLogger().info(getDescription().getFullName() + " is enabled. Some hooks might get registered with NoCheatPlus later on."); - } - - public boolean loadSettings() { - // Read and apply config to settings: - File file = new File(getDataFolder() , "cncp.yml"); - CompatConfig cfg = new NewConfig(file); - cfg.load(); - boolean changed = false; - // General settings: - if (Settings.addDefaults(cfg)) { - changed = true; - } - settings.fromConfig(cfg); - // Settings for builtin hooks: - for (Hook hook : builtinHooks){ - if (hook instanceof ConfigurableHook){ - try{ - ConfigurableHook cfgHook = (ConfigurableHook) hook; - if (cfgHook.updateConfig(cfg, "hooks.")) changed = true; - cfgHook.applyConfig(cfg, "hooks."); - } - catch (Throwable t){ - getLogger().severe("[cncp] Hook failed to process config ("+hook.getHookName() +" / " + hook.getHookVersion()+"): " + t.getClass().getSimpleName() + ": "+t.getMessage()); - t.printStackTrace(); - } - } - } - // save back config if changed: - if (changed) { - cfg.save(); - } - - return true; - } - - @Override - public void onDisable() { - unregisterNCPHooks(); // Just in case. - enabled = false; - super.onDisable(); - } - - protected int unregisterNCPHooks() { - // TODO: Clear list here !? Currently done externally... - int n = 0; - for (Hook hook : registeredHooks) { - String hookDescr = null; - try { - NCPHook ncpHook = hook.getNCPHook(); - if (ncpHook != null){ - hookDescr = ncpHook.getHookName() + ": " + ncpHook.getHookVersion(); - NCPHookManager.removeHook(ncpHook); - n ++; - } - } catch (Throwable e) - { - if (hookDescr != null) { - // Some error with removing a hook. - getLogger().log(Level.WARNING, "Failed to unregister hook: " + hookDescr, e); - } - } - } - getLogger().info("[cncp] Removed "+n+" registered hooks from NoCheatPlus."); - registeredHooks.clear(); - return n; - } - - private int registerHooks() { - int n = 0; - for (Hook hook : registeredHooks){ - // TODO: try catch - NCPHook ncpHook = hook.getNCPHook(); - if (ncpHook == null) continue; - NCPHookManager.addHook(hook.getCheckTypes(), ncpHook); - n ++; - } - getLogger().info("[cncp] Added "+n+" registered hooks to NoCheatPlus."); - return n; - } - - /* (non-Javadoc) - * @see org.bukkit.plugin.java.JavaPlugin#onCommand(org.bukkit.command.CommandSender, org.bukkit.command.Command, java.lang.String, java.lang.String[]) - */ - @Override - public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { - // Permission has already been checked. - sendInfo(sender); - return true; - } - - /** - * Send general version and hooks info. - * @param sender - */ - private void sendInfo(CommandSender sender) { - List infos = new LinkedList(); - infos.add("---- Version infomation ----"); - // Server - infos.add("#### Server ####"); - infos.add(getServer().getVersion()); - // Core plugins (NCP + cncp) - infos.add("#### Core plugins ####"); - infos.add(getDescription().getFullName()); - String temp = getOtherVersion("NoCheatPlus"); - infos.add(temp.isEmpty() ? "NoCheatPlus is missing or not yet enabled." : temp); - infos.add("#### Typical plugin dependencies ####"); - for (String pluginName : new String[]{ - "mcMMO", "Citizens", "MachinaCraft", "MagicSpells", - // TODO: extend - }){ - temp = getOtherVersion(pluginName); - if (!temp.isEmpty()) infos.add(temp); - } - // Hooks - infos.add("#### Registered hooks (cncp) ###"); - for (final Hook hook : registeredHooks){ - temp = hook.getHookName() + ": " + hook.getHookVersion(); - if (hook instanceof ConfigurableHook){ - temp += ((ConfigurableHook) hook).isEnabled() ? " (enabled)" : " (disabled)"; - } - infos.add(temp); - } - // TODO: Registered hooks (ncp) ? - infos.add("#### Registered hooks (ncp) ####"); - for (final NCPHook hook : NCPHookManager.getAllHooks()){ - infos.add(hook.getHookName() + ": " + hook.getHookVersion()); - } - final String[] a = new String[infos.size()]; - infos.toArray(a); - sender.sendMessage(a); - } - - /** - * - * @param pluginName Empty string or "name: version". - */ - private String getOtherVersion(String pluginName){ - Plugin plg = getServer().getPluginManager().getPlugin(pluginName); - if (plg == null) return ""; - PluginDescriptionFile pdf = plg.getDescription(); - return pdf.getFullName(); - } - -} +package me.asofold.bpl.cncp; + +import java.io.File; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.bukkit.Bukkit; +import org.bukkit.Server; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.server.PluginEnableEvent; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.PluginDescriptionFile; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.java.JavaPlugin; +import org.bukkit.scheduler.BukkitScheduler; +import fr.neatmonster.nocheatplus.NCPAPIProvider; +import fr.neatmonster.nocheatplus.compat.Folia; +import fr.neatmonster.nocheatplus.components.registry.feature.IDisableListener; +import fr.neatmonster.nocheatplus.hooks.NCPHook; +import fr.neatmonster.nocheatplus.hooks.NCPHookManager; +import me.asofold.bpl.cncp.bedrock.BedrockPlayerListener; +import me.asofold.bpl.cncp.ClientVersion.ClientVersionListener; +import me.asofold.bpl.cncp.config.Settings; +import me.asofold.bpl.cncp.config.compatlayer.CompatConfig; +import me.asofold.bpl.cncp.config.compatlayer.NewConfig; +import me.asofold.bpl.cncp.hooks.Hook; +import me.asofold.bpl.cncp.hooks.generic.ConfigurableHook; +import me.asofold.bpl.cncp.hooks.generic.HookBlockBreak; +import me.asofold.bpl.cncp.hooks.generic.HookBlockPlace; +import me.asofold.bpl.cncp.hooks.generic.HookEntityDamageByEntity; +import me.asofold.bpl.cncp.hooks.generic.HookInstaBreak; +import me.asofold.bpl.cncp.hooks.generic.HookPlayerClass; +import me.asofold.bpl.cncp.hooks.generic.HookPlayerInteract; +import me.asofold.bpl.cncp.utils.TickTask2; +import me.asofold.bpl.cncp.utils.Utils; + +/** + * Quick attempt to provide compatibility to NoCheatPlus (by NeatMonster) for some other plugins that change the vanilla game mechanichs, for instance by fast block breaking. + * @author mc_dev + * + */ +public class CompatNoCheatPlus extends JavaPlugin implements Listener { + + private static CompatNoCheatPlus instance = null; + + private final Settings settings = new Settings(); + + private boolean bungee; + + /** Hooks registered with cncp */ + private static final Set registeredHooks = new HashSet(); + + private final List builtinHooks = new LinkedList(); + + /** + * Flag if plugin is enabled. + */ + private static boolean enabled = false; + + /** + * Experimental: static method to enable this plugin, only enables if it is not already enabled. + * @return + */ + public static boolean enableCncp(){ + if (enabled) return true; + return enablePlugin("CompatNoCheatPlus"); + } + + /** + * Static method to enable a plugin (might also be useful for hooks). + * @param plgName + * @return + */ + public static boolean enablePlugin(String plgName) { + PluginManager pm = Bukkit.getPluginManager(); + Plugin plugin = pm.getPlugin(plgName); + if (plugin == null) return false; + if (pm.isPluginEnabled(plugin)) return true; + pm.enablePlugin(plugin); + return true; + } + + /** + * Static method to disable a plugin (might also be useful for hooks). + * @param plgName + * @return + */ + public static boolean disablePlugin(String plgName){ + PluginManager pm = Bukkit.getPluginManager(); + Plugin plugin = pm.getPlugin(plgName); + if (plugin == null) return false; + if (!pm.isPluginEnabled(plugin)) return true; + pm.disablePlugin(plugin); + return true; + } + + /** + * Get the plugin instance. + * @return + */ + public static CompatNoCheatPlus getInstance(){ + return instance; + } + + /** + * API to add a hook. Adds the hook AND registers listeners if enabled. Also respects the configuration for preventing hooks.
+ * If you want to not register the listeners use NCPHookManager. + * @param hook + * @return + */ + public static boolean addHook(Hook hook){ + if (Settings.preventAddHooks.contains(hook.getHookName())){ + Bukkit.getLogger().info("[CompatNoCheatPlus] Prevented adding hook: "+hook.getHookName() + " / " + hook.getHookVersion()); + return false; + } + registeredHooks.add(hook); + if (enabled) registerListeners(hook); + boolean added = checkAddNCPHook(hook); // Add if plugin is present, otherwise queue for adding. + Bukkit.getLogger().info("[CompatNoCheatPlus] Registered hook"+(added?"":"(NCPHook might get added later)")+": "+hook.getHookName() + " / " + hook.getHookVersion()); + return true; + } + + /** + * If already added to NCP + * @param hook + * @return + */ + private static boolean checkAddNCPHook(Hook hook) { + PluginManager pm = Bukkit.getPluginManager(); + Plugin plugin = pm.getPlugin("NoCheatPlus"); + if (plugin == null || !pm.isPluginEnabled(plugin)) + return false; + NCPHook ncpHook = hook.getNCPHook(); + if (ncpHook != null) + NCPHookManager.addHook(hook.getCheckTypes(), ncpHook); + return true; + } + + /** + * Conveniently register the listeners, do not use if you add/added the hook with addHook. + * @param hook + * @return + */ + public static boolean registerListeners(Hook hook) { + if (!enabled) return false; + Listener[] listeners = hook.getListeners(); + if (listeners != null){ + // attempt to register events: + PluginManager pm = Bukkit.getPluginManager(); + Plugin plg = pm.getPlugin("CompatNoCheatPlus"); + if (plg == null) return false; + for (Listener listener : listeners) { + pm.registerEvents(listener, plg); + } + } + return true; + } + + /** + * Called before loading settings, adds available hooks into a list, so they will be able to read config. + */ + private void setupBuiltinHooks() { + builtinHooks.clear(); + // Might-fail hooks: + // Set speed + try { + builtinHooks.add(new me.asofold.bpl.cncp.hooks.generic.HookSetSpeed()); + } + catch (Throwable t) {} + // Citizens 2 + try { + builtinHooks.add(new me.asofold.bpl.cncp.hooks.citizens2.HookCitizens2()); + } + catch (Throwable t) {} + // mcMMO + try { + builtinHooks.add(new me.asofold.bpl.cncp.hooks.mcmmo.HookmcMMO()); + } + catch (Throwable t) {} + // GravityTubes + try { + builtinHooks.add(new me.asofold.bpl.cncp.hooks.GravityTubes.HookGravityTubes()); + } + catch (Throwable t) {} + // CMI + try { + builtinHooks.add(new me.asofold.bpl.cncp.hooks.CMI.HookCMI()); + } + catch (Throwable t){} +// // MagicSpells +// try{ +// builtinHooks.add(new me.asofold.bpl.cncp.hooks.magicspells.HookMagicSpells()); +// } +// catch (Throwable t){} + // Simple generic hooks + for (Hook hook : new Hook[]{ + new HookPlayerClass(), + new HookBlockBreak(), + new HookBlockPlace(), + new HookInstaBreak(), + new HookEntityDamageByEntity(), + new HookPlayerInteract() + }){ + builtinHooks.add(hook); + } + } + + /** + * Add standard hooks if enabled. + */ + private void addAvailableHooks() { + + // Add built in hooks: + for (Hook hook : builtinHooks){ + boolean add = true; + if (hook instanceof ConfigurableHook){ + if (!((ConfigurableHook)hook).isEnabled()) add = false; + } + if (add){ + try{ + addHook(hook); + } + catch (Throwable t){} + } + } + } + + @Override + public void onEnable() { + enabled = false; // make sure + instance = this; + // (no cleanup) + + // Settings: + settings.clear(); + setupBuiltinHooks(); + loadSettings(); + // Register own listener: + final PluginManager pm = getServer().getPluginManager(); + pm.registerEvents(this, this); + pm.registerEvents(new BedrockPlayerListener(), this); + pm.registerEvents(new ClientVersionListener(), this); + getServer().getMessenger().registerIncomingPluginChannel(this, "cncp:geyser", new BedrockPlayerListener()); + try { + bungee = getServer().spigot().getConfig().getBoolean("settings.bungeecord"); + + // sometimes not work, try the hard way + if (!bungee) { + bungee = YamlConfiguration.loadConfiguration(new File("spigot.yml")).getBoolean("settings.bungeecord"); + } + } catch (Throwable t) { + bungee = false; + } + super.onEnable(); + + // Add Hooks: + addAvailableHooks(); // add before enable is set to not yet register listeners. + enabled = true; + + // register all listeners: + for (Hook hook : registeredHooks){ + registerListeners(hook); + } + + // Start ticktask 2 + Folia.runSyncRepatingTask(this, (arg) -> new TickTask2().run(), 1, 1); + + // Check for the NoCheatPlus plugin. + Plugin plugin = pm.getPlugin("NoCheatPlus"); + if (plugin == null) { + getLogger().severe("[CompatNoCheatPlus] The NoCheatPlus plugin is not present."); + } + else if (plugin.isEnabled()) { + getLogger().severe("[CompatNoCheatPlus] The NoCheatPlus plugin already is enabled, this might break several hooks."); + } + + // Finished. + getLogger().info(getDescription().getFullName() + " is enabled. Some hooks might get registered with NoCheatPlus later on."); + } + + public boolean loadSettings() { + final Set oldForceEnableLater = new LinkedHashSet(); + oldForceEnableLater.addAll(settings.forceEnableLater); + // Read and apply config to settings: + File file = new File(getDataFolder() , "cncp.yml"); + CompatConfig cfg = new NewConfig(file); + cfg.load(); + boolean changed = false; + // General settings: + if (Settings.addDefaults(cfg)) changed = true; + settings.fromConfig(cfg); + // Settings for builtin hooks: + for (Hook hook : builtinHooks){ + if (hook instanceof ConfigurableHook){ + try{ + ConfigurableHook cfgHook = (ConfigurableHook) hook; + if (cfgHook.updateConfig(cfg, "hooks.")) changed = true; + cfgHook.applyConfig(cfg, "hooks."); + } + catch (Throwable t){ + getLogger().severe("[CompatNoCheatPlus] Hook failed to process config ("+hook.getHookName() +" / " + hook.getHookVersion()+"): " + t.getClass().getSimpleName() + ": "+t.getMessage()); + t.printStackTrace(); + } + } + } + // save back config if changed: + if (changed) cfg.save(); + + + + // Re-enable plugins that were not yet on the list: + Server server = getServer(); + Logger logger = server.getLogger(); + for (String plgName : settings.loadPlugins){ + try{ + if (CompatNoCheatPlus.enablePlugin(plgName)){ + System.out.println("[CompatNoCheatPlus] Ensured that the following plugin is enabled: " + plgName); + } + } + catch (Throwable t){ + logger.severe("[CompatNoCheatPlus] Failed to enable the plugin: " + plgName); + logger.severe(Utils.toString(t)); + } + } + BukkitScheduler sched = server.getScheduler(); + for (String plgName : settings.forceEnableLater){ + if (!oldForceEnableLater.remove(plgName)) oldForceEnableLater.add(plgName); + } + if (!oldForceEnableLater.isEmpty()){ + System.out.println("[CompatNoCheatPlus] Schedule task to re-enable plugins later..."); + sched.scheduleSyncDelayedTask(this, new Runnable() { + @Override + public void run() { + // (Later maybe re-enabling this plugin could be added.) + // TODO: log levels ! + for (String plgName : oldForceEnableLater){ + try{ + if (disablePlugin(plgName)){ + if (enablePlugin(plgName)) System.out.println("[CompatNoCheatPlus] Re-enabled plugin: " + plgName); + else System.out.println("[CompatNoCheatPlus] Could not re-enable plugin: "+plgName); + } + else{ + System.out.println("[CompatNoCheatPlus] Could not disable plugin (already disabled?): "+plgName); + } + } + catch (Throwable t){ + // TODO: maybe log ? + } + } + } + }); + } + + return true; + } + + @Override + public void onDisable() { + unregisterNCPHooks(); // Just in case. + enabled = false; + instance = null; // Set last. + getServer().getMessenger().unregisterIncomingPluginChannel(this, "cncp:geyser"); + super.onDisable(); + } + + protected int unregisterNCPHooks() { + // TODO: Clear list here !? Currently done externally... + int n = 0; + for (Hook hook : registeredHooks) { + String hookDescr = null; + try { + NCPHook ncpHook = hook.getNCPHook(); + if (ncpHook != null){ + hookDescr = ncpHook.getHookName() + ": " + ncpHook.getHookVersion(); + NCPHookManager.removeHook(ncpHook); + n ++; + } + } catch (Throwable e) + { + if (hookDescr != null) { + // Some error with removing a hook. + getLogger().log(Level.WARNING, "Failed to unregister hook: " + hookDescr, e); + } + } + } + getLogger().info("[CompatNoCheatPlus] Removed "+n+" registered hooks from NoCheatPlus."); + registeredHooks.clear(); + return n; + } + + private int registerHooks() { + int n = 0; + for (Hook hook : registeredHooks){ + // TODO: try catch + NCPHook ncpHook = hook.getNCPHook(); + if (ncpHook == null) continue; + NCPHookManager.addHook(hook.getCheckTypes(), ncpHook); + n ++; + } + getLogger().info("[CompatNoCheatPlus] Added "+n+" registered hooks to NoCheatPlus."); + return n; + } + + @EventHandler(priority = EventPriority.NORMAL) + void onPluginEnable(PluginEnableEvent event){ + Plugin plugin = event.getPlugin(); + if (!plugin.getName().equals("NoCheatPlus")) { + return; + } + // Register to remove hooks when NCP is disabling. + NCPAPIProvider.getNoCheatPlusAPI().addComponent(new IDisableListener(){ + @Override + public void onDisable() { + // Remove all registered cncp hooks: + unregisterNCPHooks(); + } + }); + if (registeredHooks.isEmpty()) { + return; + } + registerHooks(); + } + + /* (non-Javadoc) + * @see org.bukkit.plugin.java.JavaPlugin#onCommand(org.bukkit.command.CommandSender, org.bukkit.command.Command, java.lang.String, java.lang.String[]) + */ + @Override + public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { + // Permission has already been checked. + sendInfo(sender); + return true; + } + + /** + * Send general version and hooks info. + * @param sender + */ + private void sendInfo(CommandSender sender) { + List infos = new LinkedList(); + infos.add("---- Version infomation ----"); + // Server + infos.add("#### Server ####"); + infos.add(getServer().getVersion()); + // Core plugins (NCP + cncp) + infos.add("#### Core plugins ####"); + infos.add(getDescription().getFullName()); + String temp = getOtherVersion("NoCheatPlus"); + infos.add(temp.isEmpty() ? "NoCheatPlus is missing or not yet enabled." : temp); + infos.add("#### Typical plugin dependencies ####"); + for (String pluginName : new String[]{ + "mcMMO", "Citizens", "MachinaCraft", "MagicSpells", "ViaVersion", "ProtocolSupport", "GravityTubes", "Geyser-Spigot", "floodgate", "CMI", "Geyser-BungeeCord" + }){ + temp = getOtherVersion(pluginName); + if (!temp.isEmpty()) infos.add(temp); + } + // Hooks + infos.add("#### Registered hooks (cncp) ###"); + for (final Hook hook : registeredHooks){ + temp = hook.getHookName() + ": " + hook.getHookVersion(); + if (hook instanceof ConfigurableHook){ + temp += ((ConfigurableHook) hook).isEnabled() ? " (enabled)" : " (disabled)"; + } + infos.add(temp); + } + // TODO: Registered hooks (ncp) ? + infos.add("#### Registered hooks (ncp) ####"); + for (final NCPHook hook : NCPHookManager.getAllHooks()){ + infos.add(hook.getHookName() + ": " + hook.getHookVersion()); + } + final String[] a = new String[infos.size()]; + infos.toArray(a); + sender.sendMessage(a); + } + + /** + * + * @param pluginName Empty string or "name: version". + */ + private String getOtherVersion(String pluginName){ + Plugin plg = getServer().getPluginManager().getPlugin(pluginName); + if (plg == null) return ""; + PluginDescriptionFile pdf = plg.getDescription(); + return pdf.getFullName(); + } + + public Settings getSettings() { + return settings; + } + + public boolean isBungeeEnabled() { + return bungee; + } +} diff --git a/src/me/asofold/bpl/cncp/bedrock/BedrockPlayerListener.java b/src/me/asofold/bpl/cncp/bedrock/BedrockPlayerListener.java new file mode 100644 index 0000000..1550730 --- /dev/null +++ b/src/me/asofold/bpl/cncp/bedrock/BedrockPlayerListener.java @@ -0,0 +1,72 @@ +package me.asofold.bpl.cncp.bedrock; + +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.messaging.PluginMessageListener; +import org.geysermc.connector.GeyserConnector; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.floodgate.api.FloodgateApi; +import com.google.common.io.ByteArrayDataInput; +import com.google.common.io.ByteStreams; + +import fr.neatmonster.nocheatplus.checks.CheckType; +import fr.neatmonster.nocheatplus.players.DataManager; +import fr.neatmonster.nocheatplus.players.IPlayerData; +import me.asofold.bpl.cncp.CompatNoCheatPlus; +import me.asofold.bpl.cncp.config.Settings; + +public class BedrockPlayerListener implements Listener, PluginMessageListener { + + private Plugin floodgate = Bukkit.getPluginManager().getPlugin("floodgate"); + private Plugin geyser = Bukkit.getPluginManager().getPlugin("Geyser-Spigot"); + private final Settings settings = CompatNoCheatPlus.getInstance().getSettings(); + + @EventHandler(priority = EventPriority.MONITOR) + public void onPlayerJoin(PlayerJoinEvent event) { + final Player player = event.getPlayer(); + if (floodgate != null && floodgate.isEnabled()) { + if (FloodgateApi.getInstance().isFloodgatePlayer(player.getUniqueId())) { + processExemption(player); + } + } + else if (geyser != null && geyser.isEnabled()) { + try { + GeyserSession session = GeyserConnector.getInstance().getPlayerByUuid(player.getUniqueId()); + if (session != null) processExemption(player); + } + catch (NullPointerException e) {} + } + } + + private void processExemption(final Player player) { + final IPlayerData pData = DataManager.getPlayerData(player); + if (pData != null) { + for (CheckType check : settings.extemptChecks) pData.exempt(check); + pData.setBedrockPlayer(true); + } + } + + private void processExemption(final String playername) { + final IPlayerData pData = DataManager.getPlayerData(playername); + if (pData != null) { + for (CheckType check : settings.extemptChecks) pData.exempt(check); + pData.setBedrockPlayer(true); + } + } + + @Override + public void onPluginMessageReceived(String channel, Player player, byte[] data) { + if (CompatNoCheatPlus.getInstance().isBungeeEnabled() && channel.equals("cncp:geyser")) { + geyser = null; + floodgate = null; + ByteArrayDataInput input = ByteStreams.newDataInput(data); + String playerName = input.readUTF(); + processExemption(playerName); + } + } +} diff --git a/src/me/asofold/bpl/cncp/bungee/CompatNoCheatPlus.java b/src/me/asofold/bpl/cncp/bungee/CompatNoCheatPlus.java new file mode 100644 index 0000000..549057f --- /dev/null +++ b/src/me/asofold/bpl/cncp/bungee/CompatNoCheatPlus.java @@ -0,0 +1,86 @@ +package me.asofold.bpl.cncp.bungee; +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.util.concurrent.TimeUnit; + +import org.geysermc.connector.GeyserConnector; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.floodgate.api.FloodgateApi; + +import net.md_5.bungee.api.ProxyServer; +import net.md_5.bungee.api.connection.ProxiedPlayer; +import net.md_5.bungee.api.connection.Server; +import net.md_5.bungee.api.event.PluginMessageEvent; +import net.md_5.bungee.api.event.ServerSwitchEvent; +import net.md_5.bungee.api.plugin.Listener; +import net.md_5.bungee.api.plugin.Plugin; +import net.md_5.bungee.event.EventHandler; + +public class CompatNoCheatPlus extends Plugin implements Listener { + private boolean floodgate; + private boolean geyser; + + @Override + public void onEnable() { + geyser = checkGeyser(); + floodgate = checkFloodgate(); + getLogger().info("Registering listeners"); + getProxy().getPluginManager().registerListener(this, this); + getProxy().registerChannel("cncp:geyser"); + getLogger().info("cncp Bungee mode with Geyser : " + geyser + ", Floodgate : " + floodgate); + } + + @EventHandler + public void onMessageReceive(PluginMessageEvent event) { + if (event.getTag().equalsIgnoreCase("cncp:geyser")) { + // Message sent from client, cancel it + if (event.getSender() instanceof ProxiedPlayer) { + event.setCancelled(true); + } + } + } + + private boolean checkFloodgate() { + return ProxyServer.getInstance().getPluginManager().getPlugin("floodgate") != null; + } + + private boolean checkGeyser() { + return ProxyServer.getInstance().getPluginManager().getPlugin("Geyser-BungeeCord") != null; + } + + @SuppressWarnings("deprecation") + private boolean isBedrockPlayer(ProxiedPlayer player) { + if (floodgate) { + return FloodgateApi.getInstance().isFloodgatePlayer(player.getUniqueId()); + } + if (geyser) { + try { + GeyserSession session = GeyserConnector.getInstance().getPlayerByUuid(player.getUniqueId()); + return session != null; + } catch (NullPointerException e) { + return false; + } + } + return false; + } + + @EventHandler + public void onChangeServer(ServerSwitchEvent event) { + ProxiedPlayer player = event.getPlayer(); + Server server = player.getServer(); + + if (!isBedrockPlayer(player)) return; + + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + DataOutputStream dataOutputStream = new DataOutputStream(outputStream); + try { + dataOutputStream.writeUTF(player.getName()); + } catch (IOException e) { + e.printStackTrace(); + } + getProxy().getScheduler().schedule(this, () -> { + server.sendData("cncp:geyser", outputStream.toByteArray()); + }, 1L, TimeUnit.SECONDS); + } +} diff --git a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/config/Settings.java b/src/me/asofold/bpl/cncp/config/Settings.java similarity index 55% rename from CompatNoCheatPlus/src/me/asofold/bpl/cncp/config/Settings.java rename to src/me/asofold/bpl/cncp/config/Settings.java index 8449c00..f886657 100644 --- a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/config/Settings.java +++ b/src/me/asofold/bpl/cncp/config/Settings.java @@ -1,67 +1,92 @@ -package me.asofold.bpl.cncp.config; - -import java.util.HashSet; -import java.util.LinkedList; -import java.util.Set; - -import org.bukkit.Bukkit; - -import me.asofold.bpl.cncp.config.compatlayer.CompatConfig; -import me.asofold.bpl.cncp.config.compatlayer.ConfigUtil; -import me.asofold.bpl.cncp.config.compatlayer.NewConfig; - -public class Settings { - public static final int configVersion = 3; - - public static Set preventAddHooks = new HashSet(); - - public static CompatConfig getDefaultConfig(){ - CompatConfig cfg = new NewConfig(null); - cfg.set("plugins.force-enable-later", new LinkedList()); // ConfigUtil.asList(new String[]{ "NoCheatPlus" })); - cfg.set("plugins.ensure-enable", new LinkedList()); // ConfigUtil.asList(new String[]{ "WorldGuard" })); - cfg.set("hooks.prevent-add", new LinkedList()); - cfg.set("configversion", configVersion); - return cfg; - } - - public static boolean addDefaults(CompatConfig cfg){ - boolean changed = false; - if (cfg.getInt("configversion", 0) == 0){ - cfg.remove("plugins"); - cfg.set("configversion", configVersion); - changed = true; - } - if (cfg.getInt("configversion", 0) <= 1){ - if (cfg.getDouble("hooks.set-speed.fly-speed", 0.1) != 0.1){ - changed = true; - cfg.set("hooks.set-speed.fly-speed", 0.1); - Bukkit.getLogger().warning("[cncp] Reset fly-speed for the set-speed hook to 0.1 (default) as a safety measure."); - } - if (cfg.getDouble("hooks.set-speed.walk-speed", 0.2) != 0.2){ - changed = true; - cfg.set("hooks.set-speed.walk-speed", 0.2); - Bukkit.getLogger().warning("[cncp] Reset walk-speed for the set-speed hook to 0.2 (default) as a safety measure."); - } - } - if (ConfigUtil.forceDefaults(getDefaultConfig(), cfg)) changed = true; - if (cfg.getInt("configversion", 0) != configVersion){ - cfg.set("configversion", configVersion); - changed = true; - } - return changed; - } - - public boolean fromConfig(CompatConfig cfg){ - // Settings ref = new Settings(); - - - // General - ConfigUtil.readStringSetFromList(cfg, "hooks.prevent-add", preventAddHooks, true, true, false); - return true; - } - - public void clear() { - // TODO: clear something !? - } - -} +package me.asofold.bpl.cncp.config; + +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.LinkedList; +import java.util.Set; + +import org.bukkit.Bukkit; + +import fr.neatmonster.nocheatplus.checks.CheckType; +import me.asofold.bpl.cncp.config.compatlayer.CompatConfig; +import me.asofold.bpl.cncp.config.compatlayer.ConfigUtil; +import me.asofold.bpl.cncp.config.compatlayer.NewConfig; + +public class Settings { + public static final int configVersion = 2; + + public Set forceEnableLater = new LinkedHashSet(); + public Set loadPlugins = new LinkedHashSet(); + public Set extemptChecks = new LinkedHashSet(); + + public static Set preventAddHooks = new HashSet(); + + public static CompatConfig getDefaultConfig(){ + CompatConfig cfg = new NewConfig(null); + cfg.set("plugins.force-enable-later", new LinkedList()); // ConfigUtil.asList(new String[]{ "NoCheatPlus" })); + cfg.set("plugins.ensure-enable", new LinkedList()); // ConfigUtil.asList(new String[]{ "WorldGuard" })); + cfg.set("plugins.bedrock-extempt-checks", ConfigUtil.asList(new String[]{ + "ALL", + "BLOCKINTERACT_VISIBLE", + "BLOCKINTERACT_DIRECTION", + "BLOCKINTERACT_REACH", + "BLOCKBREAK_DIRECTION", + "BLOCKBREAK_NOSWING", + "BLOCKBREAK_REACH", + "BLOCKPLACE_NOSWING", + "BLOCKPLACE_DIRECTION", + "BLOCKPLACE_REACH", + "BLOCKPLACE_SCAFFOLD", + "FIGHT_DIRECTION", + })); + cfg.set("hooks.prevent-add", new LinkedList()); + cfg.set("configversion", configVersion); + return cfg; + } + + public static boolean addDefaults(CompatConfig cfg){ + boolean changed = false; + if (cfg.getInt("configversion", 0) == 0){ + cfg.remove("plugins"); + cfg.set("configversion", configVersion); + changed = true; + } + if (cfg.getInt("configversion", 0) <= 1){ + if (cfg.getDouble("hooks.set-speed.fly-speed", 0.1) != 0.1){ + changed = true; + cfg.set("hooks.set-speed.fly-speed", 0.1); + Bukkit.getLogger().warning("[CompatNoCheatPlus] Reset fly-speed for the set-speed hook to 0.1 (default) as a safety measure."); + } + if (cfg.getDouble("hooks.set-speed.walk-speed", 0.2) != 0.2){ + changed = true; + cfg.set("hooks.set-speed.walk-speed", 0.2); + Bukkit.getLogger().warning("[CompatNoCheatPlus] Reset walk-speed for the set-speed hook to 0.2 (default) as a safety measure."); + } + } + if (ConfigUtil.forceDefaults(getDefaultConfig(), cfg)) changed = true; + if (cfg.getInt("configversion", 0) != configVersion){ + cfg.set("configversion", configVersion); + changed = true; + } + return changed; + } + + public boolean fromConfig(CompatConfig cfg){ +// Settings ref = new Settings(); + + // plugins to force enabling after this plugin. + ConfigUtil.readStringSetFromList(cfg, "plugins.force-enable-later", forceEnableLater, true, true, false); + ConfigUtil.readStringSetFromList(cfg, "plugins.ensure-enable", loadPlugins, true, true, false); + + ConfigUtil.readCheckTypeSetFromList(cfg, "plugins.bedrock-extempt-checks", extemptChecks, true, true, true); + + // General + ConfigUtil.readStringSetFromList(cfg, "hooks.prevent-add", preventAddHooks, true, true, false); + return true; + } + + public void clear() { + forceEnableLater.clear(); + } + +} diff --git a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/config/compatlayer/AbstractConfig.java b/src/me/asofold/bpl/cncp/config/compatlayer/AbstractConfig.java similarity index 95% rename from CompatNoCheatPlus/src/me/asofold/bpl/cncp/config/compatlayer/AbstractConfig.java rename to src/me/asofold/bpl/cncp/config/compatlayer/AbstractConfig.java index 235496e..ac360b1 100644 --- a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/config/compatlayer/AbstractConfig.java +++ b/src/me/asofold/bpl/cncp/config/compatlayer/AbstractConfig.java @@ -1,213 +1,213 @@ -package me.asofold.bpl.cncp.config.compatlayer; - -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; - - -/** - * Some generic checks and stuff using getString, hasEntry, getStringList, ... - * @author mc_dev - * - */ -public abstract class AbstractConfig implements CompatConfig { - - protected char sep = '.'; - - @Override - public Boolean getBoolean(String path, Boolean defaultValue) { - String val = getString(path, null); - if ( val == null ) return defaultValue; - try{ - // return Boolean.parseBoolean(val); - String t = val.trim().toLowerCase(); - if ( t.equals("true")) return true; - else if ( t.equals("false")) return false; - else return defaultValue; - } catch( NumberFormatException exc){ - return defaultValue; - } - } - - @Override - public Double getDouble(String path, Double defaultValue) { - String val = getString(path, null); - if ( val == null ) return defaultValue; - try{ - return Double.parseDouble(val); - } catch( NumberFormatException exc){ - return defaultValue; - } - } - - @Override - public Long getLong(String path, Long defaultValue) { - String val = getString(path, null); - if ( val == null ) return defaultValue; - try{ - return Long.parseLong(val); - } catch( NumberFormatException exc){ - return defaultValue; - } - } - - @Override - public Integer getInt(String path, Integer defaultValue) { - String val = getString(path, null); - if ( val == null ) return defaultValue; - try{ - return Integer.parseInt(val); - } catch( NumberFormatException exc){ - return defaultValue; - } - } - - @Override - public List getIntList(String path, List defaultValue){ - if ( !hasEntry(path) ) return defaultValue; - List strings = getStringList(path, null); - if ( strings == null ) return defaultValue; - List out = new LinkedList(); - for ( String s : strings){ - try{ - out.add(Integer.parseInt(s)); - } catch(NumberFormatException exc){ - // ignore - } - } - return out; - } - - @Override - public List getDoubleList(String path, List defaultValue) { - if ( !hasEntry(path) ) return defaultValue; - List strings = getStringList(path, null); - if ( strings == null ) return defaultValue; - List out = new LinkedList(); - for ( String s : strings){ - try{ - out.add(Double.parseDouble(s)); - } catch(NumberFormatException exc){ - // ignore - } - } - return out; - } - - @Override - public Set getStringKeys(String path, boolean deep) { - if (deep) return getStringKeysDeep(path); - Set keys = new HashSet(); - keys.addAll(getStringKeys(path)); - return keys; - - } - - @Override - public Set getStringKeysDeep(String path) { - // NOTE: pretty inefficient, but aimed at seldomly read sections. - Map values = getValuesDeep(); - Set out = new HashSet(); - final int len = path.length(); - for (String key : values.keySet()){ - if (!key.startsWith(path)) continue; - else if (key.length() == len) continue; - else if (key.charAt(len) == sep) out.add(key); - } - return out; - } - - @Override - public Object get(String path, Object defaultValue) { - return getProperty(path, defaultValue); - } - - @Override - public void set(String path, Object value) { - setProperty(path, value); - } - - @Override - public void remove(String path) { - removeProperty(path); - } - - @Override - public Boolean getBoolean(String path) { - return getBoolean(path, null); - } - - @Override - public Double getDouble(String path) { - return getDouble(path, null); - } - - @Override - public List getDoubleList(String path) { - return getDoubleList(path, null); - } - - @Override - public Integer getInt(String path) { - return getInt(path, null); - } - - @Override - public List getIntList(String path) { - return getIntList(path, null); - } - - @Override - public Integer getInteger(String path) { - return getInt(path, null); - } - - @Override - public List getIntegerList(String path) { - return getIntList(path, null); - } - - @Override - public String getString(String path) { - return getString(path, null); - } - - @Override - public List getStringList(String path) { - return getStringList(path, null); - } - - @Override - public Object get(String path) { - return getProperty(path, null); - } - - @Override - public Object getProperty(String path) { - return getProperty(path, null); - } - - @Override - public boolean contains(String path) { - return hasEntry(path); - } - - @Override - public Integer getInteger(String path, Integer defaultValue) { - return getInt(path, defaultValue); - } - - @Override - public List getIntegerList(String path, List defaultValue) { - return getIntList(path, defaultValue); - } - - @Override - public Long getLong(String path) { - return getLong(path, null); - } - - -} +package me.asofold.bpl.cncp.config.compatlayer; + +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; + + +/** + * Some generic checks and stuff using getString, hasEntry, getStringList, ... + * @author mc_dev + * + */ +public abstract class AbstractConfig implements CompatConfig { + + protected char sep = '.'; + + @Override + public Boolean getBoolean(String path, Boolean defaultValue) { + String val = getString(path, null); + if ( val == null ) return defaultValue; + try{ + // return Boolean.parseBoolean(val); + String t = val.trim().toLowerCase(); + if ( t.equals("true")) return true; + else if ( t.equals("false")) return false; + else return defaultValue; + } catch( NumberFormatException exc){ + return defaultValue; + } + } + + @Override + public Double getDouble(String path, Double defaultValue) { + String val = getString(path, null); + if ( val == null ) return defaultValue; + try{ + return Double.parseDouble(val); + } catch( NumberFormatException exc){ + return defaultValue; + } + } + + @Override + public Long getLong(String path, Long defaultValue) { + String val = getString(path, null); + if ( val == null ) return defaultValue; + try{ + return Long.parseLong(val); + } catch( NumberFormatException exc){ + return defaultValue; + } + } + + @Override + public Integer getInt(String path, Integer defaultValue) { + String val = getString(path, null); + if ( val == null ) return defaultValue; + try{ + return Integer.parseInt(val); + } catch( NumberFormatException exc){ + return defaultValue; + } + } + + @Override + public List getIntList(String path, List defaultValue){ + if ( !hasEntry(path) ) return defaultValue; + List strings = getStringList(path, null); + if ( strings == null ) return defaultValue; + List out = new LinkedList(); + for ( String s : strings){ + try{ + out.add(Integer.parseInt(s)); + } catch(NumberFormatException exc){ + // ignore + } + } + return out; + } + + @Override + public List getDoubleList(String path, List defaultValue) { + if ( !hasEntry(path) ) return defaultValue; + List strings = getStringList(path, null); + if ( strings == null ) return defaultValue; + List out = new LinkedList(); + for ( String s : strings){ + try{ + out.add(Double.parseDouble(s)); + } catch(NumberFormatException exc){ + // ignore + } + } + return out; + } + + @Override + public Set getStringKeys(String path, boolean deep) { + if (deep) return getStringKeysDeep(path); + Set keys = new HashSet(); + keys.addAll(getStringKeys(path)); + return keys; + + } + + @Override + public Set getStringKeysDeep(String path) { + // NOTE: pretty inefficient, but aimed at seldomly read sections. + Map values = getValuesDeep(); + Set out = new HashSet(); + final int len = path.length(); + for (String key : values.keySet()){ + if (!key.startsWith(path)) continue; + else if (key.length() == len) continue; + else if (key.charAt(len) == sep) out.add(key); + } + return out; + } + + @Override + public Object get(String path, Object defaultValue) { + return getProperty(path, defaultValue); + } + + @Override + public void set(String path, Object value) { + setProperty(path, value); + } + + @Override + public void remove(String path) { + removeProperty(path); + } + + @Override + public Boolean getBoolean(String path) { + return getBoolean(path, null); + } + + @Override + public Double getDouble(String path) { + return getDouble(path, null); + } + + @Override + public List getDoubleList(String path) { + return getDoubleList(path, null); + } + + @Override + public Integer getInt(String path) { + return getInt(path, null); + } + + @Override + public List getIntList(String path) { + return getIntList(path, null); + } + + @Override + public Integer getInteger(String path) { + return getInt(path, null); + } + + @Override + public List getIntegerList(String path) { + return getIntList(path, null); + } + + @Override + public String getString(String path) { + return getString(path, null); + } + + @Override + public List getStringList(String path) { + return getStringList(path, null); + } + + @Override + public Object get(String path) { + return getProperty(path, null); + } + + @Override + public Object getProperty(String path) { + return getProperty(path, null); + } + + @Override + public boolean contains(String path) { + return hasEntry(path); + } + + @Override + public Integer getInteger(String path, Integer defaultValue) { + return getInt(path, defaultValue); + } + + @Override + public List getIntegerList(String path, List defaultValue) { + return getIntList(path, defaultValue); + } + + @Override + public Long getLong(String path) { + return getLong(path, null); + } + + +} diff --git a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/config/compatlayer/AbstractNewConfig.java b/src/me/asofold/bpl/cncp/config/compatlayer/AbstractNewConfig.java similarity index 96% rename from CompatNoCheatPlus/src/me/asofold/bpl/cncp/config/compatlayer/AbstractNewConfig.java rename to src/me/asofold/bpl/cncp/config/compatlayer/AbstractNewConfig.java index 9df9923..7c1a927 100644 --- a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/config/compatlayer/AbstractNewConfig.java +++ b/src/me/asofold/bpl/cncp/config/compatlayer/AbstractNewConfig.java @@ -1,237 +1,237 @@ -package me.asofold.bpl.cncp.config.compatlayer; - -import java.io.File; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.bukkit.configuration.Configuration; -import org.bukkit.configuration.ConfigurationOptions; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.MemoryConfiguration; - -public abstract class AbstractNewConfig extends AbstractConfig { - File file = null; - MemoryConfiguration config = null; - - public AbstractNewConfig(File file){ - setFile(file); - } - - public void setFile(File file) { - this.file = file; - this.config = new MemoryConfiguration(); - setOptions(config); - } - - @Override - public boolean hasEntry(String path) { - return config.contains(path) || (config.get(path) != null); - } - - - - - @Override - public String getString(String path, String defaultValue) { - if (!hasEntry(path)) return defaultValue; - return config.getString(path, defaultValue); - } - - - - @Override - public List getStringKeys(String path) { - // TODO policy: only strings or all keys as strings ? - List out = new LinkedList(); - List keys = getKeys(path); - if ( keys == null ) return out; - for ( Object obj : keys){ - if ( obj instanceof String ) out.add((String) obj); - else{ - try{ - out.add(obj.toString()); - } catch ( Throwable t){ - // ignore. - } - } - } - return out; - } - - @Override - public List getKeys(String path) { - List out = new LinkedList(); - Set keys; - if ( path == null) keys = config.getKeys(false); - else{ - ConfigurationSection sec = config.getConfigurationSection(path); - if (sec == null) return out; - keys = sec.getKeys(false); - } - if ( keys == null) return out; - out.addAll(keys); - return out; - } - - @Override - public List getKeys() { - return getKeys(null); - } - - @Override - public Object getProperty(String path, Object defaultValue) { - Object obj = config.get(path); - if ( obj == null ) return defaultValue; - else return obj; - } - - @Override - public List getStringKeys() { - return getStringKeys(null); - } - - @Override - public void setProperty(String path, Object obj) { - config.set(path, obj); - } - - @Override - public List getStringList(String path, List defaultValue) { - if ( !hasEntry(path)) return defaultValue; - List out = new LinkedList(); - List entries = config.getStringList(path); - if ( entries == null ) return defaultValue; - for ( String entry : entries){ - if ( entry instanceof String) out.add(entry); - else{ - try{ - out.add(entry.toString()); - } catch (Throwable t){ - // ignore - } - } - } - return out; - } - - @Override - public void removeProperty(String path) { - if (path.startsWith(".")) path = path.substring(1); - // VERY EXPENSIVE - MemoryConfiguration temp = new MemoryConfiguration(); - setOptions(temp); - Map values = config.getValues(true); - if (values.containsKey(path)) values.remove(path); - else{ - final String altPath = "."+path; - if (values.containsKey(altPath)) values.remove(altPath); - } - for ( String _p : values.keySet()){ - Object v = values.get(_p); - if (v == null) continue; - else if (v instanceof ConfigurationSection) continue; - String p; - if (_p.startsWith(".")) p = _p.substring(1); - else p = _p; - if (p.startsWith(path)) continue; - temp.set(p, v); - } - config = temp; - } - - - @Override - public Boolean getBoolean(String path, Boolean defaultValue) { - if (!config.contains(path)) return defaultValue; - String val = config.getString(path, null); - if (val != null){ - if (val.equalsIgnoreCase("true")) return true; - else if (val.equalsIgnoreCase("false")) return false; - else return defaultValue; - } - Boolean res = defaultValue; - if ( val == null ){ - if ( defaultValue == null) defaultValue = false; - res = config.getBoolean(path, defaultValue); - } - return res; - } - - - - - @Override - public Double getDouble(String path, Double defaultValue) { - if (!config.contains(path)) return defaultValue; - Double res = super.getDouble(path, null); - if ( res == null ) res = config.getDouble(path, ConfigUtil.canaryDouble); - if ( res == ConfigUtil.canaryDouble) return defaultValue; - return res; - } - - - - - @Override - public Long getLong(String path, Long defaultValue) { - if (!config.contains(path)) return defaultValue; - Long res = super.getLong(path, null); - if ( res == null ) res = config.getLong(path, ConfigUtil.canaryLong); - if ( res == ConfigUtil.canaryLong) return defaultValue; - return res; - } - - - - - @Override - public Integer getInt(String path, Integer defaultValue) { - if (!config.contains(path)) return defaultValue; - Integer res = super.getInt(path, null); - if ( res == null ) res = config.getInt(path, ConfigUtil.canaryInt); - if ( res == ConfigUtil.canaryInt) return defaultValue; - return res; - } - - - - - @Override - public List getIntList(String path, List defaultValue) { - // TODO Auto-generated method stub - return super.getIntList(path, defaultValue); - } - - - - - @Override - public List getDoubleList(String path, List defaultValue) { - // TODO Auto-generated method stub - return super.getDoubleList(path, defaultValue); - } - - - void addAll(Configuration source, Configuration target){ - Map all = source.getValues(true); - for ( String path: all.keySet()){ - target.set(path, source.get(path)); - } - } - - void setOptions(Configuration cfg){ - ConfigurationOptions opt = cfg.options(); - opt.pathSeparator(this.sep); - //opt.copyDefaults(true); - } - - @Override - public boolean setPathSeparatorChar(char sep) { - this.sep = sep; - setOptions(config); - return true; - } - -} +package me.asofold.bpl.cncp.config.compatlayer; + +import java.io.File; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.bukkit.configuration.Configuration; +import org.bukkit.configuration.ConfigurationOptions; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.MemoryConfiguration; + +public abstract class AbstractNewConfig extends AbstractConfig { + File file = null; + MemoryConfiguration config = null; + + public AbstractNewConfig(File file){ + setFile(file); + } + + public void setFile(File file) { + this.file = file; + this.config = new MemoryConfiguration(); + setOptions(config); + } + + @Override + public boolean hasEntry(String path) { + return config.contains(path) || (config.get(path) != null); + } + + + + + @Override + public String getString(String path, String defaultValue) { + if (!hasEntry(path)) return defaultValue; + return config.getString(path, defaultValue); + } + + + + @Override + public List getStringKeys(String path) { + // TODO policy: only strings or all keys as strings ? + List out = new LinkedList(); + List keys = getKeys(path); + if ( keys == null ) return out; + for ( Object obj : keys){ + if ( obj instanceof String ) out.add((String) obj); + else{ + try{ + out.add(obj.toString()); + } catch ( Throwable t){ + // ignore. + } + } + } + return out; + } + + @Override + public List getKeys(String path) { + List out = new LinkedList(); + Set keys; + if ( path == null) keys = config.getKeys(false); + else{ + ConfigurationSection sec = config.getConfigurationSection(path); + if (sec == null) return out; + keys = sec.getKeys(false); + } + if ( keys == null) return out; + out.addAll(keys); + return out; + } + + @Override + public List getKeys() { + return getKeys(null); + } + + @Override + public Object getProperty(String path, Object defaultValue) { + Object obj = config.get(path); + if ( obj == null ) return defaultValue; + else return obj; + } + + @Override + public List getStringKeys() { + return getStringKeys(null); + } + + @Override + public void setProperty(String path, Object obj) { + config.set(path, obj); + } + + @Override + public List getStringList(String path, List defaultValue) { + if ( !hasEntry(path)) return defaultValue; + List out = new LinkedList(); + List entries = config.getStringList(path); + if ( entries == null ) return defaultValue; + for ( String entry : entries){ + if ( entry instanceof String) out.add(entry); + else{ + try{ + out.add(entry.toString()); + } catch (Throwable t){ + // ignore + } + } + } + return out; + } + + @Override + public void removeProperty(String path) { + if (path.startsWith(".")) path = path.substring(1); + // VERY EXPENSIVE + MemoryConfiguration temp = new MemoryConfiguration(); + setOptions(temp); + Map values = config.getValues(true); + if (values.containsKey(path)) values.remove(path); + else{ + final String altPath = "."+path; + if (values.containsKey(altPath)) values.remove(altPath); + } + for ( String _p : values.keySet()){ + Object v = values.get(_p); + if (v == null) continue; + else if (v instanceof ConfigurationSection) continue; + String p; + if (_p.startsWith(".")) p = _p.substring(1); + else p = _p; + if (p.startsWith(path)) continue; + temp.set(p, v); + } + config = temp; + } + + + @Override + public Boolean getBoolean(String path, Boolean defaultValue) { + if (!config.contains(path)) return defaultValue; + String val = config.getString(path, null); + if (val != null){ + if (val.equalsIgnoreCase("true")) return true; + else if (val.equalsIgnoreCase("false")) return false; + else return defaultValue; + } + Boolean res = defaultValue; + if ( val == null ){ + if ( defaultValue == null) defaultValue = false; + res = config.getBoolean(path, defaultValue); + } + return res; + } + + + + + @Override + public Double getDouble(String path, Double defaultValue) { + if (!config.contains(path)) return defaultValue; + Double res = super.getDouble(path, null); + if ( res == null ) res = config.getDouble(path, ConfigUtil.canaryDouble); + if ( res == ConfigUtil.canaryDouble) return defaultValue; + return res; + } + + + + + @Override + public Long getLong(String path, Long defaultValue) { + if (!config.contains(path)) return defaultValue; + Long res = super.getLong(path, null); + if ( res == null ) res = config.getLong(path, ConfigUtil.canaryLong); + if ( res == ConfigUtil.canaryLong) return defaultValue; + return res; + } + + + + + @Override + public Integer getInt(String path, Integer defaultValue) { + if (!config.contains(path)) return defaultValue; + Integer res = super.getInt(path, null); + if ( res == null ) res = config.getInt(path, ConfigUtil.canaryInt); + if ( res == ConfigUtil.canaryInt) return defaultValue; + return res; + } + + + + + @Override + public List getIntList(String path, List defaultValue) { + // TODO Auto-generated method stub + return super.getIntList(path, defaultValue); + } + + + + + @Override + public List getDoubleList(String path, List defaultValue) { + // TODO Auto-generated method stub + return super.getDoubleList(path, defaultValue); + } + + + void addAll(Configuration source, Configuration target){ + Map all = source.getValues(true); + for ( String path: all.keySet()){ + target.set(path, source.get(path)); + } + } + + void setOptions(Configuration cfg){ + ConfigurationOptions opt = cfg.options(); + opt.pathSeparator(this.sep); + //opt.copyDefaults(true); + } + + @Override + public boolean setPathSeparatorChar(char sep) { + this.sep = sep; + setOptions(config); + return true; + } + +} diff --git a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/config/compatlayer/CompatConfig.java b/src/me/asofold/bpl/cncp/config/compatlayer/CompatConfig.java similarity index 96% rename from CompatNoCheatPlus/src/me/asofold/bpl/cncp/config/compatlayer/CompatConfig.java rename to src/me/asofold/bpl/cncp/config/compatlayer/CompatConfig.java index 9b36c5f..4474c1a 100644 --- a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/config/compatlayer/CompatConfig.java +++ b/src/me/asofold/bpl/cncp/config/compatlayer/CompatConfig.java @@ -1,155 +1,155 @@ -package me.asofold.bpl.cncp.config.compatlayer; - - -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * CONVENTIONS: - * - Return strings if objects can be made strings. - * - No exceptions, rather leave elements out of lists. - * - Lists of length 0 and null can not always be distinguished (?->extra safe wrapper ?) - * - All contents are treated alike, even if given as a string (!): true and 'true', 1 and '1' - * @author mc_dev - * - */ -public interface CompatConfig { - - // Boolean - /** - * Only accepts true and false , 'true' and 'false'. - * @param path - * @param defaultValue - * @return - */ - public Boolean getBoolean(String path, Boolean defaultValue); - public Boolean getBoolean(String path); - - // Long - public Long getLong(String path); - public Long getLong(String path, Long defaultValue); - - // Double - public Double getDouble(String path); - public Double getDouble(String path, Double defaultValue); - public List getDoubleList(String path); - public List getDoubleList(String path , List defaultValue); - - // Integer (abbreviation) - public Integer getInt(String path); - public Integer getInt(String path, Integer defaultValue); - public List getIntList(String path); - public List getIntList(String path, List defaultValue); - // Integer (full name) - public Integer getInteger(String path); - public Integer getInteger(String path, Integer defaultValue); - public List getIntegerList(String path); - public List getIntegerList(String path, List defaultValue); - - // String - public String getString(String path); - public String getString(String path, String defaultValue); - public List getStringList(String path); - public List getStringList(String path, List defaultValue); - - // Generic methods: - public Object get(String path); - public Object get(String path, Object defaultValue); - public Object getProperty(String path); - public Object getProperty(String path, Object defaultValue); - public void set(String path, Object value); - public void setProperty(String path, Object value); - - /** - * Remove a path (would also remove sub sections, unless for path naming problems). - * @param path - */ - public void remove(String path); - - /** - * Works same as remove(path): removes properties and sections alike. - * @param path - */ - public void removeProperty(String path); - - // Contains/has - public boolean hasEntry(String path); - public boolean contains(String path); - - // Keys (Object): [possibly deprecated] - /** - * @deprecated Seems not to be supported anymore by new configuration, use getStringKeys(String path); - * @param path - * @return - */ - public List getKeys(String path); - /** - * @deprecated Seems not to be supported anymore by new configuration, use getStringKeys(); - * @return - */ - public List getKeys(); - - // Keys (String): - /** - * - * @return never null - */ - public List getStringKeys(); - - public List getStringKeys(String path); - - /** - * Get all keys from the section (deep or shallow). - * @param path - * @param deep - * @return Never null. - */ - public Set getStringKeys(String path, boolean deep); - - /** - * convenience method. - * @param path - * @return never null - * - */ - public Set getStringKeysDeep(String path); - - // Values: - /** - * Equivalent to new config: values(true) - * @return - */ - public Map getValuesDeep(); - - // Technical / IO: - /** - * False if not supported. - * @param sep - * @return - */ - public boolean setPathSeparatorChar(char sep); - - public void load(); - - public boolean save(); - - /** - * Clear all contents. - */ - public void clear(); - - /** - * Return a YAML-String representation of the contents, null if not supported. - * @return null if not supported. - */ - public String getYAMLString(); - - /** - * Add all entries from the YAML-String representation to the configuration, forget or clear all previous entries. - * @return - */ - public boolean fromYamlString(String input); - - -} +package me.asofold.bpl.cncp.config.compatlayer; + + +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * CONVENTIONS: + * - Return strings if objects can be made strings. + * - No exceptions, rather leave elements out of lists. + * - Lists of length 0 and null can not always be distinguished (?->extra safe wrapper ?) + * - All contents are treated alike, even if given as a string (!): true and 'true', 1 and '1' + * @author mc_dev + * + */ +public interface CompatConfig { + + // Boolean + /** + * Only accepts true and false , 'true' and 'false'. + * @param path + * @param defaultValue + * @return + */ + public Boolean getBoolean(String path, Boolean defaultValue); + public Boolean getBoolean(String path); + + // Long + public Long getLong(String path); + public Long getLong(String path, Long defaultValue); + + // Double + public Double getDouble(String path); + public Double getDouble(String path, Double defaultValue); + public List getDoubleList(String path); + public List getDoubleList(String path , List defaultValue); + + // Integer (abbreviation) + public Integer getInt(String path); + public Integer getInt(String path, Integer defaultValue); + public List getIntList(String path); + public List getIntList(String path, List defaultValue); + // Integer (full name) + public Integer getInteger(String path); + public Integer getInteger(String path, Integer defaultValue); + public List getIntegerList(String path); + public List getIntegerList(String path, List defaultValue); + + // String + public String getString(String path); + public String getString(String path, String defaultValue); + public List getStringList(String path); + public List getStringList(String path, List defaultValue); + + // Generic methods: + public Object get(String path); + public Object get(String path, Object defaultValue); + public Object getProperty(String path); + public Object getProperty(String path, Object defaultValue); + public void set(String path, Object value); + public void setProperty(String path, Object value); + + /** + * Remove a path (would also remove sub sections, unless for path naming problems). + * @param path + */ + public void remove(String path); + + /** + * Works same as remove(path): removes properties and sections alike. + * @param path + */ + public void removeProperty(String path); + + // Contains/has + public boolean hasEntry(String path); + public boolean contains(String path); + + // Keys (Object): [possibly deprecated] + /** + * @deprecated Seems not to be supported anymore by new configuration, use getStringKeys(String path); + * @param path + * @return + */ + public List getKeys(String path); + /** + * @deprecated Seems not to be supported anymore by new configuration, use getStringKeys(); + * @return + */ + public List getKeys(); + + // Keys (String): + /** + * + * @return never null + */ + public List getStringKeys(); + + public List getStringKeys(String path); + + /** + * Get all keys from the section (deep or shallow). + * @param path + * @param deep + * @return Never null. + */ + public Set getStringKeys(String path, boolean deep); + + /** + * convenience method. + * @param path + * @return never null + * + */ + public Set getStringKeysDeep(String path); + + // Values: + /** + * Equivalent to new config: values(true) + * @return + */ + public Map getValuesDeep(); + + // Technical / IO: + /** + * False if not supported. + * @param sep + * @return + */ + public boolean setPathSeparatorChar(char sep); + + public void load(); + + public boolean save(); + + /** + * Clear all contents. + */ + public void clear(); + + /** + * Return a YAML-String representation of the contents, null if not supported. + * @return null if not supported. + */ + public String getYAMLString(); + + /** + * Add all entries from the YAML-String representation to the configuration, forget or clear all previous entries. + * @return + */ + public boolean fromYamlString(String input); + + +} diff --git a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/config/compatlayer/CompatConfigFactory.java b/src/me/asofold/bpl/cncp/config/compatlayer/CompatConfigFactory.java similarity index 95% rename from CompatNoCheatPlus/src/me/asofold/bpl/cncp/config/compatlayer/CompatConfigFactory.java rename to src/me/asofold/bpl/cncp/config/compatlayer/CompatConfigFactory.java index 78920b2..59b4f45 100644 --- a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/config/compatlayer/CompatConfigFactory.java +++ b/src/me/asofold/bpl/cncp/config/compatlayer/CompatConfigFactory.java @@ -1,56 +1,56 @@ -package me.asofold.bpl.cncp.config.compatlayer; - -import java.io.File; - -public class CompatConfigFactory { - - public static final String version = "0.8.1"; - - /** - * Attempt to get a working file configuration.
- * This is not fit for fast processing.
- * Use getDBConfig to use this with a database.
- * @param file May be null (then memory is used). - * @return null if fails. - */ - public static final CompatConfig getConfig(File file){ - CompatConfig out = null; - // TODO: add more (latest API) -// try{ -// return new OldConfig(file); -// } catch (Throwable t){ -// } - try{ - return new NewConfig(file); - } catch (Throwable t){ - - } - return out; - } - -// public static final CompatConfig getOldConfig(File file){ -// return new OldConfig(file); -// } - - public static final CompatConfig getNewConfig(File file){ - return new NewConfig(file); - } - -// /** -// * Get a ebeans based database config (!). -// * @param file -// * @return -// */ -// public static final CompatConfig getDBConfig(EbeanServer server, String dbKey){ -// try{ -// return new SnakeDBConfig(server, dbKey); -// } catch (Throwable t){ -// -// } -// return new DBConfig(server, dbKey); -// } - - - // TODO: add setup helpers (!) - // TODO: add conversion helpers (!) -} +package me.asofold.bpl.cncp.config.compatlayer; + +import java.io.File; + +public class CompatConfigFactory { + + public static final String version = "0.8.1"; + + /** + * Attempt to get a working file configuration.
+ * This is not fit for fast processing.
+ * Use getDBConfig to use this with a database.
+ * @param file May be null (then memory is used). + * @return null if fails. + */ + public static final CompatConfig getConfig(File file){ + CompatConfig out = null; + // TODO: add more (latest API) +// try{ +// return new OldConfig(file); +// } catch (Throwable t){ +// } + try{ + return new NewConfig(file); + } catch (Throwable t){ + + } + return out; + } + +// public static final CompatConfig getOldConfig(File file){ +// return new OldConfig(file); +// } + + public static final CompatConfig getNewConfig(File file){ + return new NewConfig(file); + } + +// /** +// * Get a ebeans based database config (!). +// * @param file +// * @return +// */ +// public static final CompatConfig getDBConfig(EbeanServer server, String dbKey){ +// try{ +// return new SnakeDBConfig(server, dbKey); +// } catch (Throwable t){ +// +// } +// return new DBConfig(server, dbKey); +// } + + + // TODO: add setup helpers (!) + // TODO: add conversion helpers (!) +} diff --git a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/config/compatlayer/ConfigUtil.java b/src/me/asofold/bpl/cncp/config/compatlayer/ConfigUtil.java similarity index 82% rename from CompatNoCheatPlus/src/me/asofold/bpl/cncp/config/compatlayer/ConfigUtil.java rename to src/me/asofold/bpl/cncp/config/compatlayer/ConfigUtil.java index 02ab06a..02ef4ab 100644 --- a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/config/compatlayer/ConfigUtil.java +++ b/src/me/asofold/bpl/cncp/config/compatlayer/ConfigUtil.java @@ -1,196 +1,224 @@ -package me.asofold.bpl.cncp.config.compatlayer; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Set; - -public class ConfigUtil { - - public static final int canaryInt = Integer.MIN_VALUE +7; - public static final long canaryLong = Long.MIN_VALUE + 7L; - public static final double canaryDouble = -Double.MAX_VALUE + 1.2593; - - public static String stringPath( String path){ - return stringPath(path, '.'); - } - - public static String stringPath( String path , char sep ){ - String useSep = (sep=='.')?"\\.":""+sep; - String[] split = path.split(useSep); - StringBuilder builder = new StringBuilder(); - builder.append(stringPart(split[0])); - for (int i = 1; i all = defaults.getValuesDeep(); - boolean changed = false; - for ( String path : all.keySet()){ - if ( !config.hasEntry(path)){ - config.setProperty(path, defaults.getProperty(path, null)); - changed = true; - } - } - return changed; - } - - /** - * Add StringList entries to a set. - * @param cfg - * @param path - * @param set - * @param clear If to clear the set. - * @param trim - * @param lowerCase - */ - public static void readStringSetFromList(CompatConfig cfg, String path, Set set, boolean clear, boolean trim, boolean lowerCase){ - if (clear) set.clear(); - List tempList = cfg.getStringList(path , null); - if (tempList != null){ - for (String entry : tempList){ - if (trim) entry = entry.trim(); - if (lowerCase) entry = entry.toLowerCase(); - set.add(entry); - } - } - } - - /** - * Return an ArrayList. - * @param input - * @return - */ - public static final List asList(final T[] input){ - final List out = new ArrayList(input.length); - for (int i = 0; i < input.length; i++){ - out.add(input[i]); - } - return out; - } - - /** - * Return an ArrayList. - * @param input - * @return - */ - public static final List asList(final int[] input){ - final List out = new ArrayList(input.length); - for (int i = 0; i < input.length; i++){ - out.add(input[i]); - } - return out; - } - - /** - * Return an ArrayList. - * @param input - * @return - */ - public static final List asList(final long[] input){ - final List out = new ArrayList(input.length); - for (int i = 0; i < input.length; i++){ - out.add(input[i]); - } - return out; - } - - /** - * Return an ArrayList. - * @param input - * @return - */ - public static final List asList(final double[] input){ - final List out = new ArrayList(input.length); - for (int i = 0; i < input.length; i++){ - out.add(input[i]); - } - return out; - } - - /** - * Return an ArrayList. - * @param input - * @return - */ - public static final List asList(final float[] input){ - final List out = new ArrayList(input.length); - for (int i = 0; i < input.length; i++){ - out.add(input[i]); - } - return out; - } - - /** - * Return an ArrayList. - * @param input - * @return - */ - public static final List asList(final boolean[] input){ - final List out = new ArrayList(input.length); - for (int i = 0; i < input.length; i++){ - out.add(input[i]); - } - return out; - } - -} +package me.asofold.bpl.cncp.config.compatlayer; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import fr.neatmonster.nocheatplus.checks.CheckType; + +public class ConfigUtil { + + public static final int canaryInt = Integer.MIN_VALUE +7; + public static final long canaryLong = Long.MIN_VALUE + 7L; + public static final double canaryDouble = -Double.MAX_VALUE + 1.2593; + + public static String stringPath( String path){ + return stringPath(path, '.'); + } + + public static String stringPath( String path , char sep ){ + String useSep = (sep=='.')?"\\.":""+sep; + String[] split = path.split(useSep); + StringBuilder builder = new StringBuilder(); + builder.append(stringPart(split[0])); + for (int i = 1; i all = defaults.getValuesDeep(); + boolean changed = false; + for ( String path : all.keySet()){ + if ( !config.hasEntry(path)){ + config.setProperty(path, defaults.getProperty(path, null)); + changed = true; + } + } + return changed; + } + + /** + * Add StringList entries to a set. + * @param cfg + * @param path + * @param set + * @param clear If to clear the set. + * @param trim + * @param lowerCase + */ + public static void readStringSetFromList(CompatConfig cfg, String path, Set set, boolean clear, boolean trim, boolean lowerCase){ + if (clear) set.clear(); + List tempList = cfg.getStringList(path , null); + if (tempList != null){ + for (String entry : tempList){ + if (trim) entry = entry.trim(); + if (lowerCase) entry = entry.toLowerCase(); + set.add(entry); + } + } + } + + /** + * Add StringList entries to a set. + * @param cfg + * @param path + * @param set + * @param clear If to clear the set. + * @param trim + * @param upperCase + */ + public static void readCheckTypeSetFromList(CompatConfig cfg, String path, Set set, boolean clear, boolean trim, boolean upperCase){ + if (clear) set.clear(); + List tempList = cfg.getStringList(path , null); + if (tempList != null){ + for (String entry : tempList) { + if (trim) entry = entry.trim(); + if (upperCase) entry = entry.toUpperCase(); + try { + final CheckType checkType = CheckType.valueOf(entry); + set.add(checkType); + } catch (Exception e) { + System.out.println("[CompatNoCheatPlus] Unknown check " + entry + ". Skipping."); + } + } + } + } + + /** + * Return an ArrayList. + * @param input + * @return + */ + public static final List asList(final T[] input){ + final List out = new ArrayList(input.length); + for (int i = 0; i < input.length; i++){ + out.add(input[i]); + } + return out; + } + + /** + * Return an ArrayList. + * @param input + * @return + */ + public static final List asList(final int[] input){ + final List out = new ArrayList(input.length); + for (int i = 0; i < input.length; i++){ + out.add(input[i]); + } + return out; + } + + /** + * Return an ArrayList. + * @param input + * @return + */ + public static final List asList(final long[] input){ + final List out = new ArrayList(input.length); + for (int i = 0; i < input.length; i++){ + out.add(input[i]); + } + return out; + } + + /** + * Return an ArrayList. + * @param input + * @return + */ + public static final List asList(final double[] input){ + final List out = new ArrayList(input.length); + for (int i = 0; i < input.length; i++){ + out.add(input[i]); + } + return out; + } + + /** + * Return an ArrayList. + * @param input + * @return + */ + public static final List asList(final float[] input){ + final List out = new ArrayList(input.length); + for (int i = 0; i < input.length; i++){ + out.add(input[i]); + } + return out; + } + + /** + * Return an ArrayList. + * @param input + * @return + */ + public static final List asList(final boolean[] input){ + final List out = new ArrayList(input.length); + for (int i = 0; i < input.length; i++){ + out.add(input[i]); + } + return out; + } + +} diff --git a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/config/compatlayer/NewConfig.java b/src/me/asofold/bpl/cncp/config/compatlayer/NewConfig.java similarity index 94% rename from CompatNoCheatPlus/src/me/asofold/bpl/cncp/config/compatlayer/NewConfig.java rename to src/me/asofold/bpl/cncp/config/compatlayer/NewConfig.java index c942e0a..eb68d45 100644 --- a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/config/compatlayer/NewConfig.java +++ b/src/me/asofold/bpl/cncp/config/compatlayer/NewConfig.java @@ -1,78 +1,78 @@ -package me.asofold.bpl.cncp.config.compatlayer; - -import java.io.File; -import java.util.Map; - -import org.bukkit.configuration.InvalidConfigurationException; -import org.bukkit.configuration.MemoryConfiguration; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.configuration.file.YamlConfiguration; - -public class NewConfig extends AbstractNewConfig{ - - - public NewConfig(File file) { - super(file); - } - - - @Override - public void load(){ - config = new MemoryConfiguration(); - setOptions(config); - FileConfiguration cfg = YamlConfiguration.loadConfiguration(file); - setOptions(cfg); - addAll(cfg, config); - } - - - @Override - public boolean save(){ - YamlConfiguration cfg = new YamlConfiguration(); - setOptions(cfg); - addAll(config, cfg); - try{ - cfg.save(file); - return true; - } catch (Throwable t){ - return false; - } - } - - - @Override - public Map getValuesDeep() { - return config.getValues(true); - } - - - @Override - public void clear() { - setFile(file); - } - - - @Override - public String getYAMLString() { - final YamlConfiguration temp = new YamlConfiguration(); - addAll(config, temp); - return temp.saveToString(); - } - - - @Override - public boolean fromYamlString(String input) { - final YamlConfiguration temp = new YamlConfiguration(); - try { - clear(); - temp.loadFromString(input); - addAll(temp, config); - return true; - } catch (InvalidConfigurationException e) { - e.printStackTrace(); - return false; - } - } - - -} +package me.asofold.bpl.cncp.config.compatlayer; + +import java.io.File; +import java.util.Map; + +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.MemoryConfiguration; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; + +public class NewConfig extends AbstractNewConfig{ + + + public NewConfig(File file) { + super(file); + } + + + @Override + public void load(){ + config = new MemoryConfiguration(); + setOptions(config); + FileConfiguration cfg = YamlConfiguration.loadConfiguration(file); + setOptions(cfg); + addAll(cfg, config); + } + + + @Override + public boolean save(){ + YamlConfiguration cfg = new YamlConfiguration(); + setOptions(cfg); + addAll(config, cfg); + try{ + cfg.save(file); + return true; + } catch (Throwable t){ + return false; + } + } + + + @Override + public Map getValuesDeep() { + return config.getValues(true); + } + + + @Override + public void clear() { + setFile(file); + } + + + @Override + public String getYAMLString() { + final YamlConfiguration temp = new YamlConfiguration(); + addAll(config, temp); + return temp.saveToString(); + } + + + @Override + public boolean fromYamlString(String input) { + final YamlConfiguration temp = new YamlConfiguration(); + try { + clear(); + temp.loadFromString(input); + addAll(temp, config); + return true; + } catch (InvalidConfigurationException e) { + e.printStackTrace(); + return false; + } + } + + +} diff --git a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/hooks/AbstractConfigurableHook.java b/src/me/asofold/bpl/cncp/hooks/AbstractConfigurableHook.java similarity index 96% rename from CompatNoCheatPlus/src/me/asofold/bpl/cncp/hooks/AbstractConfigurableHook.java rename to src/me/asofold/bpl/cncp/hooks/AbstractConfigurableHook.java index 81e2b83..2ce8cf7 100644 --- a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/hooks/AbstractConfigurableHook.java +++ b/src/me/asofold/bpl/cncp/hooks/AbstractConfigurableHook.java @@ -1,56 +1,56 @@ -package me.asofold.bpl.cncp.hooks; - -import me.asofold.bpl.cncp.config.compatlayer.CompatConfig; -import me.asofold.bpl.cncp.config.compatlayer.CompatConfigFactory; -import me.asofold.bpl.cncp.config.compatlayer.ConfigUtil; -import me.asofold.bpl.cncp.hooks.generic.ConfigurableHook; - -/** - * Reads an enabled flag from the config (true by default). The prefix given will be something like "hooks.", so add your hook name to the path like:
- * prefix + "myhook.extra-config" - * @author mc_dev - * - */ -public class AbstractConfigurableHook extends AbstractHook implements - ConfigurableHook { - - protected final String configPrefix; - protected final String hookName, hookVersion; - - protected boolean enabled = true; - - public AbstractConfigurableHook(String hookName, String hookVersion, String configPrefix){ - this.configPrefix = configPrefix; - this.hookName = hookName; - this.hookVersion = hookVersion; - } - - @Override - public String getHookName() { - return hookName; - } - - @Override - public String getHookVersion() { - return hookVersion; - } - - @Override - public void applyConfig(CompatConfig cfg, String prefix) { - enabled = cfg.getBoolean(prefix + configPrefix + "enabled", true); - } - - @Override - public boolean updateConfig(CompatConfig cfg, String prefix) { - CompatConfig defaults = CompatConfigFactory.getConfig(null); - defaults.set(prefix + configPrefix + "enabled", true); - return ConfigUtil.forceDefaults(defaults, cfg); - } - - @Override - public boolean isEnabled() { - return enabled; - } - - -} +package me.asofold.bpl.cncp.hooks; + +import me.asofold.bpl.cncp.config.compatlayer.CompatConfig; +import me.asofold.bpl.cncp.config.compatlayer.CompatConfigFactory; +import me.asofold.bpl.cncp.config.compatlayer.ConfigUtil; +import me.asofold.bpl.cncp.hooks.generic.ConfigurableHook; + +/** + * Reads an enabled flag from the config (true by default). The prefix given will be something like "hooks.", so add your hook name to the path like:
+ * prefix + "myhook.extra-config" + * @author mc_dev + * + */ +public class AbstractConfigurableHook extends AbstractHook implements + ConfigurableHook { + + protected final String configPrefix; + protected final String hookName, hookVersion; + + protected boolean enabled = true; + + public AbstractConfigurableHook(String hookName, String hookVersion, String configPrefix){ + this.configPrefix = configPrefix; + this.hookName = hookName; + this.hookVersion = hookVersion; + } + + @Override + public String getHookName() { + return hookName; + } + + @Override + public String getHookVersion() { + return hookVersion; + } + + @Override + public void applyConfig(CompatConfig cfg, String prefix) { + enabled = cfg.getBoolean(prefix + configPrefix + "enabled", true); + } + + @Override + public boolean updateConfig(CompatConfig cfg, String prefix) { + CompatConfig defaults = CompatConfigFactory.getConfig(null); + defaults.set(prefix + configPrefix + "enabled", true); + return ConfigUtil.forceDefaults(defaults, cfg); + } + + @Override + public boolean isEnabled() { + return enabled; + } + + +} diff --git a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/hooks/AbstractHook.java b/src/me/asofold/bpl/cncp/hooks/AbstractHook.java similarity index 95% rename from CompatNoCheatPlus/src/me/asofold/bpl/cncp/hooks/AbstractHook.java rename to src/me/asofold/bpl/cncp/hooks/AbstractHook.java index 47c54e1..0d19e43 100644 --- a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/hooks/AbstractHook.java +++ b/src/me/asofold/bpl/cncp/hooks/AbstractHook.java @@ -1,46 +1,46 @@ -package me.asofold.bpl.cncp.hooks; - -import org.bukkit.Bukkit; -import org.bukkit.event.Listener; - -import fr.neatmonster.nocheatplus.checks.CheckType; -import fr.neatmonster.nocheatplus.hooks.NCPHook; - -/** - * Extend this to make sure that future changes will not break your hooks.
- * Probable changes:
- * - Adding onReload method. - * @author mc_dev - * - */ -public abstract class AbstractHook implements Hook{ - - @Override - public CheckType[] getCheckTypes() { - // Handle all CheckEvents (improbable). - return null; - } - - @Override - public Listener[] getListeners() { - // No listeners to register with cncp. - return null; - } - - - - @Override - public NCPHook getNCPHook() { - // No hooks to add to NCP. - return null; - } - - /** - * Throw a runtime exception if the plugin is not present. - * @param pluginName - */ - protected void assertPluginPresent(String pluginName){ - if (Bukkit.getPluginManager().getPlugin(pluginName) == null) throw new RuntimeException("Assertion, " + getHookName() + ": Plugin " + pluginName + " is not present."); - } - -} +package me.asofold.bpl.cncp.hooks; + +import org.bukkit.Bukkit; +import org.bukkit.event.Listener; + +import fr.neatmonster.nocheatplus.checks.CheckType; +import fr.neatmonster.nocheatplus.hooks.NCPHook; + +/** + * Extend this to make sure that future changes will not break your hooks.
+ * Probable changes:
+ * - Adding onReload method. + * @author mc_dev + * + */ +public abstract class AbstractHook implements Hook{ + + @Override + public CheckType[] getCheckTypes() { + // Handle all CheckEvents (improbable). + return null; + } + + @Override + public Listener[] getListeners() { + // No listeners to register with cncp. + return null; + } + + + + @Override + public NCPHook getNCPHook() { + // No hooks to add to NCP. + return null; + } + + /** + * Throw a runtime exception if the plugin is not present. + * @param pluginName + */ + protected void assertPluginPresent(String pluginName){ + if (Bukkit.getPluginManager().getPlugin(pluginName) == null) throw new RuntimeException("Assertion, " + getHookName() + ": Plugin " + pluginName + " is not present."); + } + +} diff --git a/src/me/asofold/bpl/cncp/hooks/CMI/HookCMI.java b/src/me/asofold/bpl/cncp/hooks/CMI/HookCMI.java new file mode 100644 index 0000000..02060b8 --- /dev/null +++ b/src/me/asofold/bpl/cncp/hooks/CMI/HookCMI.java @@ -0,0 +1,142 @@ +package me.asofold.bpl.cncp.hooks.CMI; + +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockPlaceEvent; +import com.Zrips.CMI.CMI; +import fr.neatmonster.nocheatplus.checks.CheckType; +import fr.neatmonster.nocheatplus.checks.access.IViolationInfo; +import fr.neatmonster.nocheatplus.hooks.NCPHook; +import me.asofold.bpl.cncp.CompatNoCheatPlus; +import me.asofold.bpl.cncp.config.compatlayer.CompatConfig; +import me.asofold.bpl.cncp.config.compatlayer.CompatConfigFactory; +import me.asofold.bpl.cncp.config.compatlayer.ConfigUtil; +import me.asofold.bpl.cncp.hooks.AbstractHook; +import me.asofold.bpl.cncp.hooks.generic.ConfigurableHook; +import me.asofold.bpl.cncp.hooks.generic.ExemptionManager; +import me.asofold.bpl.cncp.utils.TickTask2; + +public class HookCMI extends AbstractHook implements Listener, ConfigurableHook { + + protected Object ncpHook = null; + + protected boolean enabled = true; + + protected String configPrefix = "cmi."; + + protected final ExemptionManager exMan = new ExemptionManager(); + + protected final CheckType[] exemptBreakMany = new CheckType[]{ + CheckType.BLOCKBREAK, CheckType.COMBINED_IMPROBABLE, + }; + + protected final CheckType[] exemptPlaceMany = new CheckType[]{ + CheckType.BLOCKPLACE, CheckType.COMBINED_IMPROBABLE, + }; + + public HookCMI(){ + assertPluginPresent("CMI"); + } + + @Override + public String getHookName() { + return "CMI(default)"; + } + + @Override + public String getHookVersion() { + return "1.0"; + } + + @Override + public Listener[] getListeners() { + return new Listener[]{ + this + }; + } + + @Override + public NCPHook getNCPHook() { + if (ncpHook == null){ + ncpHook = new NCPHook() { + @Override + public String getHookName() { + return "CMI(cncp)"; + } + + @Override + public String getHookVersion() { + return "1.0"; + } + + @Override + public boolean onCheckFailure(CheckType checkType, Player player, IViolationInfo info) { + return false; + } + }; + } + return (NCPHook) ncpHook; + } + + @EventHandler(priority=EventPriority.MONITOR) + //@RegisterMethodWithOrder(tag = CompatNoCheatPlus.tagLateFeature, afterTag = CompatNoCheatPlus.afterTagLateFeature) + public final void onMirrorBreakMonitor(final BlockBreakEvent event){ + removeExemption(event.getPlayer(), exemptBreakMany); + } + + @EventHandler(priority=EventPriority.LOWEST) + //@RegisterMethodWithOrder(tag = CompatNoCheatPlus.tagEarlyFeature, beforeTag = CompatNoCheatPlus.beforeTagEarlyFeature) + public final void onMirrorBreakLowest(final BlockBreakEvent event){ + if (CMI.getInstance().getMirrorManager().isMirroring(event.getPlayer())) { + addExemption(event.getPlayer(), exemptBreakMany); + } + } + + @EventHandler(priority=EventPriority.MONITOR) + //@RegisterMethodWithOrder(tag = CompatNoCheatPlus.tagLateFeature, afterTag = CompatNoCheatPlus.afterTagLateFeature) + public final void onMirrorPlaceMonitor(final BlockPlaceEvent event){ + removeExemption(event.getPlayer(), exemptPlaceMany); + } + + @EventHandler(priority=EventPriority.LOWEST) + //@RegisterMethodWithOrder(tag = CompatNoCheatPlus.tagEarlyFeature, beforeTag = CompatNoCheatPlus.beforeTagEarlyFeature) + public final void onMirrorPlaceLowest(final BlockPlaceEvent event){ + if (CMI.getInstance().getMirrorManager().isMirroring(event.getPlayer())) { + addExemption(event.getPlayer(), exemptPlaceMany); + } + } + + public void addExemption(final Player player, final CheckType[] types){ + for (final CheckType type : types){ + exMan.addExemption(player, type); + TickTask2.addUnexemptions(player, types); + } + } + + public void removeExemption(final Player player, final CheckType[] types){ + for (final CheckType type : types){ + exMan.removeExemption(player, type); + } + } + + @Override + public void applyConfig(CompatConfig cfg, String prefix) { + enabled = cfg.getBoolean(prefix + configPrefix + "enabled", true); + } + + @Override + public boolean updateConfig(CompatConfig cfg, String prefix) { + CompatConfig defaults = CompatConfigFactory.getConfig(null); + defaults.set(prefix + configPrefix + "enabled", true); + return ConfigUtil.forceDefaults(defaults, cfg); + } + + @Override + public boolean isEnabled() { + return enabled; + } + +} diff --git a/src/me/asofold/bpl/cncp/hooks/GravityTubes/HookFacadeImpl.java b/src/me/asofold/bpl/cncp/hooks/GravityTubes/HookFacadeImpl.java new file mode 100644 index 0000000..ff0af1f --- /dev/null +++ b/src/me/asofold/bpl/cncp/hooks/GravityTubes/HookFacadeImpl.java @@ -0,0 +1,82 @@ +package me.asofold.bpl.cncp.hooks.GravityTubes; + +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.permissions.Permissible; + +import com.benzoft.gravitytubes.GTPerm; +import com.benzoft.gravitytubes.GravityTube; +import com.benzoft.gravitytubes.files.ConfigFile; +import com.benzoft.gravitytubes.files.GravityTubesFile; + +import fr.neatmonster.nocheatplus.checks.CheckType; +import fr.neatmonster.nocheatplus.checks.access.IViolationInfo; +import fr.neatmonster.nocheatplus.checks.moving.MovingData; +import fr.neatmonster.nocheatplus.hooks.NCPHook; +import fr.neatmonster.nocheatplus.players.DataManager; +import fr.neatmonster.nocheatplus.players.IPlayerData; +import fr.neatmonster.nocheatplus.utilities.location.TrigUtil; +import me.asofold.bpl.cncp.hooks.GravityTubes.HookGravityTubes.HookFacade; + +public class HookFacadeImpl implements HookFacade, NCPHook { + + public HookFacadeImpl(){} + + @Override + public String getHookName() { + return "GravityTubes(cncp)"; + } + + @Override + public String getHookVersion() { + return "1.1"; + } + + @Override + public final boolean onCheckFailure(final CheckType checkType, final Player player, final IViolationInfo info) { + //if (checkType == CheckType.MOVING_CREATIVEFLY && !ConfigFile.getInstance().isSneakToFall() ) + if (player.getGameMode() == GameMode.SPECTATOR) return false; + if ((checkType == CheckType.MOVING_CREATIVEFLY || checkType == CheckType.MOVING_SURVIVALFLY) && GTPerm.USE.checkPermission((Permissible)player)) { + final GravityTube tube = GravityTubesFile.getInstance().getTubes().stream().filter(gravityTube -> isInTube(gravityTube, player, true, true)).findFirst().orElse(null); + if (tube != null) { + return true; + } + } + return false; + } + + private boolean isInTube(GravityTube tube, Player p, boolean longerH, boolean extendxz) { + final int tubePower = tube.getPower(); + int power = tubePower > 171 ? 4 : tubePower > 80 ? 3 : tubePower > 25 ? 2 : 1; + final Location pLoc = p.getLocation(); + final Location tLoc = tube.getSourceLocation(); + final boolean b1 = p.getWorld().equals(tLoc.getWorld()) && pLoc.getY() >= tLoc.getBlockY() && pLoc.getY() <= tLoc.getBlockY() + tube.getHeight() + (longerH ? power : 0); + if (!extendxz) + return b1 && pLoc.getBlockX() == tLoc.getBlockX() && pLoc.getBlockZ() == tLoc.getBlockZ(); + return b1 && isTubeNearby(pLoc.getBlockX(), pLoc.getBlockZ(), tLoc.getBlockX(), tLoc.getBlockZ()); + } + + private boolean isTubeNearby(int x1, int z1, int x2, int z2) { + return TrigUtil.distance(x1,z1,x2,z2) < 1.5; + } + + @Override + public void onMoveLowest(PlayerMoveEvent event) { + final Player p = event.getPlayer(); + if (p.getGameMode() == GameMode.SPECTATOR) return; + final double hDist = TrigUtil.xzDistance(event.getFrom(), event.getTo()); + final double vDist = event.getFrom().getY() - event.getTo().getY(); + if (GTPerm.USE.checkPermission((Permissible)p) + && vDist > 0 && hDist < 0.35 + && ConfigFile.getInstance().isDisableFallDamage() && p.isSneaking()) { + final GravityTube tube = GravityTubesFile.getInstance().getTubes().stream().filter(gravityTube -> isInTube(gravityTube, p, false, false)).findFirst().orElse(null); + final IPlayerData pData = DataManager.getPlayerData(p); + if (tube != null && pData != null) { + final MovingData mData = pData.getGenericInstance(MovingData.class); + mData.clearNoFallData(); + } + } + } +} diff --git a/src/me/asofold/bpl/cncp/hooks/GravityTubes/HookGravityTubes.java b/src/me/asofold/bpl/cncp/hooks/GravityTubes/HookGravityTubes.java new file mode 100644 index 0000000..80172b9 --- /dev/null +++ b/src/me/asofold/bpl/cncp/hooks/GravityTubes/HookGravityTubes.java @@ -0,0 +1,77 @@ +package me.asofold.bpl.cncp.hooks.GravityTubes; + +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerMoveEvent; +import fr.neatmonster.nocheatplus.hooks.NCPHook; +import me.asofold.bpl.cncp.config.compatlayer.CompatConfig; +import me.asofold.bpl.cncp.config.compatlayer.CompatConfigFactory; +import me.asofold.bpl.cncp.config.compatlayer.ConfigUtil; +import me.asofold.bpl.cncp.hooks.AbstractHook; +import me.asofold.bpl.cncp.hooks.generic.ConfigurableHook; + +public class HookGravityTubes extends AbstractHook implements Listener, ConfigurableHook { + + public static interface HookFacade{ + public void onMoveLowest(PlayerMoveEvent event); + } + + protected HookFacade ncpHook = null; + + protected boolean enabled = true; + + protected String configPrefix = "gravitytubes."; + + public HookGravityTubes(){ + assertPluginPresent("GravityTubes"); + } + + @Override + public String getHookName() { + return "GravityTubes(default)"; + } + + @Override + public String getHookVersion() { + return "1.0"; + } + + @Override + public Listener[] getListeners() { + return new Listener[]{ + this + }; + } + + @Override + public NCPHook getNCPHook() { + if (ncpHook == null){ + ncpHook = new HookFacadeImpl(); + } + return (NCPHook) ncpHook; + } + + @EventHandler(priority=EventPriority.LOWEST) + //@RegisterMethodWithOrder(tag = CompatNoCheatPlus.tagEarlyFeature, beforeTag = CompatNoCheatPlus.beforeTagEarlyFeature) + public final void onMoveLowest(final PlayerMoveEvent event){ + ncpHook.onMoveLowest(event); + } + + @Override + public void applyConfig(CompatConfig cfg, String prefix) { + enabled = cfg.getBoolean(prefix + configPrefix + "enabled", true); + } + + @Override + public boolean updateConfig(CompatConfig cfg, String prefix) { + CompatConfig defaults = CompatConfigFactory.getConfig(null); + defaults.set(prefix + configPrefix + "enabled", true); + return ConfigUtil.forceDefaults(defaults, cfg); + } + + @Override + public boolean isEnabled() { + return enabled; + } +} diff --git a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/hooks/Hook.java b/src/me/asofold/bpl/cncp/hooks/Hook.java similarity index 95% rename from CompatNoCheatPlus/src/me/asofold/bpl/cncp/hooks/Hook.java rename to src/me/asofold/bpl/cncp/hooks/Hook.java index 2401e6c..f845f36 100644 --- a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/hooks/Hook.java +++ b/src/me/asofold/bpl/cncp/hooks/Hook.java @@ -1,48 +1,48 @@ -package me.asofold.bpl.cncp.hooks; - -import org.bukkit.event.Listener; - -import fr.neatmonster.nocheatplus.checks.CheckType; -import fr.neatmonster.nocheatplus.hooks.NCPHook; - -/** - * Interface for hooking into another plugin.
- * NOTE: You also have to implement the methods described in NCPHook.
- * If you do not use listeners or don't want the prevent-hooks configuration feature - * to take effect, you can also register directly with NCPHookManager. - * - * @author mc_dev - * - */ -public interface Hook{ - - /** - * - * @return - */ - public String getHookName(); - - /** - * - * @return - */ - public String getHookVersion(); - - /** - * The check types to register for, see NCPHookManager for reference, you can use ALL, - */ - public CheckType[] getCheckTypes(); - - /** - * Get listener instances to be registered with cncp. - * @return null if unused. - */ - public Listener[] getListeners(); - - /** - * Get the hook to be registered with NCP, the registration will take place after NoCheatPlus has been enabled. - * @return Should always return the same hook or null if not used. - */ - public NCPHook getNCPHook(); - -} +package me.asofold.bpl.cncp.hooks; + +import org.bukkit.event.Listener; + +import fr.neatmonster.nocheatplus.checks.CheckType; +import fr.neatmonster.nocheatplus.hooks.NCPHook; + +/** + * Interface for hooking into another plugin.
+ * NOTE: You also have to implement the methods described in NCPHook.
+ * If you do not use listeners or don't want the prevent-hooks configuration feature + * to take effect, you can also register directly with NCPHookManager. + * + * @author mc_dev + * + */ +public interface Hook{ + + /** + * + * @return + */ + public String getHookName(); + + /** + * + * @return + */ + public String getHookVersion(); + + /** + * The check types to register for, see NCPHookManager for reference, you can use ALL, + */ + public CheckType[] getCheckTypes(); + + /** + * Get listener instances to be registered with cncp. + * @return null if unused. + */ + public Listener[] getListeners(); + + /** + * Get the hook to be registered with NCP, the registration will take place after NoCheatPlus has been enabled. + * @return Should always return the same hook or null if not used. + */ + public NCPHook getNCPHook(); + +} diff --git a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/hooks/citizens2/HookCitizens2.java b/src/me/asofold/bpl/cncp/hooks/citizens2/HookCitizens2.java similarity index 96% rename from CompatNoCheatPlus/src/me/asofold/bpl/cncp/hooks/citizens2/HookCitizens2.java rename to src/me/asofold/bpl/cncp/hooks/citizens2/HookCitizens2.java index 3dac7dd..4ef1fc7 100644 --- a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/hooks/citizens2/HookCitizens2.java +++ b/src/me/asofold/bpl/cncp/hooks/citizens2/HookCitizens2.java @@ -1,79 +1,79 @@ -package me.asofold.bpl.cncp.hooks.citizens2; - -import me.asofold.bpl.cncp.config.compatlayer.CompatConfig; -import me.asofold.bpl.cncp.config.compatlayer.CompatConfigFactory; -import me.asofold.bpl.cncp.config.compatlayer.ConfigUtil; -import me.asofold.bpl.cncp.hooks.AbstractHook; -import me.asofold.bpl.cncp.hooks.generic.ConfigurableHook; -import net.citizensnpcs.api.CitizensAPI; - -import org.bukkit.entity.Player; - -import fr.neatmonster.nocheatplus.checks.CheckType; -import fr.neatmonster.nocheatplus.checks.access.IViolationInfo; -import fr.neatmonster.nocheatplus.hooks.NCPHook; - -public class HookCitizens2 extends AbstractHook implements ConfigurableHook{ - - protected Object ncpHook = null; - - protected boolean enabled = true; - - protected String configPrefix = "citizens2."; - - public HookCitizens2(){ - assertPluginPresent("Citizens"); - CitizensAPI.getNPCRegistry(); // to let it fail for old versions. - } - - @Override - public String getHookName() { - return "Citizens2(default)"; - } - - @Override - public String getHookVersion() { - return "2.2"; - } - - @Override - public NCPHook getNCPHook() { - if (ncpHook == null){ - ncpHook = new NCPHook() { - @Override - public final boolean onCheckFailure(final CheckType checkType, final Player player, IViolationInfo info) { - return CitizensAPI.getNPCRegistry().isNPC(player); - } - - @Override - public final String getHookVersion() { - return "2.0"; - } - - @Override - public final String getHookName() { - return "Citizens2(cncp)"; - } - }; - } - return (NCPHook) ncpHook; - } - - @Override - public void applyConfig(CompatConfig cfg, String prefix) { - enabled = cfg.getBoolean(prefix + configPrefix + "enabled", true); - } - - @Override - public boolean updateConfig(CompatConfig cfg, String prefix) { - CompatConfig defaults = CompatConfigFactory.getConfig(null); - defaults.set(prefix + configPrefix + "enabled", true); - return ConfigUtil.forceDefaults(defaults, cfg); - } - - @Override - public boolean isEnabled() { - return enabled; - } - -} +package me.asofold.bpl.cncp.hooks.citizens2; + +import me.asofold.bpl.cncp.config.compatlayer.CompatConfig; +import me.asofold.bpl.cncp.config.compatlayer.CompatConfigFactory; +import me.asofold.bpl.cncp.config.compatlayer.ConfigUtil; +import me.asofold.bpl.cncp.hooks.AbstractHook; +import me.asofold.bpl.cncp.hooks.generic.ConfigurableHook; +import net.citizensnpcs.api.CitizensAPI; + +import org.bukkit.entity.Player; + +import fr.neatmonster.nocheatplus.checks.CheckType; +import fr.neatmonster.nocheatplus.checks.access.IViolationInfo; +import fr.neatmonster.nocheatplus.hooks.NCPHook; + +public class HookCitizens2 extends AbstractHook implements ConfigurableHook{ + + protected Object ncpHook = null; + + protected boolean enabled = true; + + protected String configPrefix = "citizens2."; + + public HookCitizens2(){ + assertPluginPresent("Citizens"); + CitizensAPI.getNPCRegistry(); // to let it fail for old versions. + } + + @Override + public String getHookName() { + return "Citizens2(default)"; + } + + @Override + public String getHookVersion() { + return "2.2"; + } + + @Override + public NCPHook getNCPHook() { + if (ncpHook == null){ + ncpHook = new NCPHook() { + @Override + public final boolean onCheckFailure(final CheckType checkType, final Player player, IViolationInfo info) { + return CitizensAPI.getNPCRegistry().isNPC(player); + } + + @Override + public final String getHookVersion() { + return "2.0"; + } + + @Override + public final String getHookName() { + return "Citizens2(cncp)"; + } + }; + } + return (NCPHook) ncpHook; + } + + @Override + public void applyConfig(CompatConfig cfg, String prefix) { + enabled = cfg.getBoolean(prefix + configPrefix + "enabled", true); + } + + @Override + public boolean updateConfig(CompatConfig cfg, String prefix) { + CompatConfig defaults = CompatConfigFactory.getConfig(null); + defaults.set(prefix + configPrefix + "enabled", true); + return ConfigUtil.forceDefaults(defaults, cfg); + } + + @Override + public boolean isEnabled() { + return enabled; + } + +} diff --git a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/hooks/generic/ClassExemptionHook.java b/src/me/asofold/bpl/cncp/hooks/generic/ClassExemptionHook.java similarity index 96% rename from CompatNoCheatPlus/src/me/asofold/bpl/cncp/hooks/generic/ClassExemptionHook.java rename to src/me/asofold/bpl/cncp/hooks/generic/ClassExemptionHook.java index fe49e08..44cfce2 100644 --- a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/hooks/generic/ClassExemptionHook.java +++ b/src/me/asofold/bpl/cncp/hooks/generic/ClassExemptionHook.java @@ -1,85 +1,85 @@ -package me.asofold.bpl.cncp.hooks.generic; - -import java.util.Collection; -import java.util.LinkedHashSet; -import java.util.LinkedList; -import java.util.List; - -import me.asofold.bpl.cncp.config.compatlayer.CompatConfig; -import me.asofold.bpl.cncp.config.compatlayer.CompatConfigFactory; -import me.asofold.bpl.cncp.config.compatlayer.ConfigUtil; -import me.asofold.bpl.cncp.hooks.AbstractHook; - -import org.bukkit.entity.Player; - -import fr.neatmonster.nocheatplus.checks.CheckType; - -/** - * Exempting players by class names for some class. - * @author mc_dev - * - */ -public abstract class ClassExemptionHook extends AbstractHook implements ConfigurableHook{ - - protected final ExemptionManager man = new ExemptionManager(); - - protected final List defaultClasses = new LinkedList(); - protected final LinkedHashSet classes = new LinkedHashSet(); - - protected boolean defaultEnabled = true; - protected boolean enabled = true; - - protected final String configPrefix; - - public ClassExemptionHook(String configPrefix){ - this.configPrefix = configPrefix; - } - - public void setClasses(final Collection classes){ - this.classes.clear(); - this.classes.addAll(classes); - } - - /** - * Check if a player is to be exempted and exempt for the check type. - * @param player - * @param clazz - * @param checkType - * @return If exempted. - */ - public boolean checkExempt(final Player player, final Class clazz, final CheckType checkType){ - if (!classes.contains(clazz.getSimpleName())) return false; - return man.addExemption(player, checkType); - } - - /** - * - * @param player - * @param checkType - * @return If the player is still exempted. - */ - public boolean checkUnexempt(final Player player, final Class clazz, final CheckType checkType){ - if (!classes.contains(clazz.getSimpleName())) return false; - return man.removeExemption(player, checkType); - } - - @Override - public void applyConfig(CompatConfig cfg, String prefix) { - enabled = cfg.getBoolean(prefix + configPrefix + "enabled", defaultEnabled); - ConfigUtil.readStringSetFromList(cfg, prefix + configPrefix + "exempt-names", classes, true, true, false); - } - - @Override - public boolean updateConfig(CompatConfig cfg, String prefix) { - CompatConfig defaults = CompatConfigFactory.getConfig(null); - defaults.set(prefix + configPrefix + "enabled", defaultEnabled); - defaults.set(prefix + configPrefix + "exempt-names", defaultClasses); - return ConfigUtil.forceDefaults(defaults, cfg); - } - - @Override - public boolean isEnabled() { - return enabled; - } - -} +package me.asofold.bpl.cncp.hooks.generic; + +import java.util.Collection; +import java.util.LinkedHashSet; +import java.util.LinkedList; +import java.util.List; + +import me.asofold.bpl.cncp.config.compatlayer.CompatConfig; +import me.asofold.bpl.cncp.config.compatlayer.CompatConfigFactory; +import me.asofold.bpl.cncp.config.compatlayer.ConfigUtil; +import me.asofold.bpl.cncp.hooks.AbstractHook; + +import org.bukkit.entity.Player; + +import fr.neatmonster.nocheatplus.checks.CheckType; + +/** + * Exempting players by class names for some class. + * @author mc_dev + * + */ +public abstract class ClassExemptionHook extends AbstractHook implements ConfigurableHook{ + + protected final ExemptionManager man = new ExemptionManager(); + + protected final List defaultClasses = new LinkedList(); + protected final LinkedHashSet classes = new LinkedHashSet(); + + protected boolean defaultEnabled = true; + protected boolean enabled = true; + + protected final String configPrefix; + + public ClassExemptionHook(String configPrefix){ + this.configPrefix = configPrefix; + } + + public void setClasses(final Collection classes){ + this.classes.clear(); + this.classes.addAll(classes); + } + + /** + * Check if a player is to be exempted and exempt for the check type. + * @param player + * @param clazz + * @param checkType + * @return If exempted. + */ + public boolean checkExempt(final Player player, final Class clazz, final CheckType checkType){ + if (!classes.contains(clazz.getSimpleName())) return false; + return man.addExemption(player, checkType); + } + + /** + * + * @param player + * @param checkType + * @return If the player is still exempted. + */ + public boolean checkUnexempt(final Player player, final Class clazz, final CheckType checkType){ + if (!classes.contains(clazz.getSimpleName())) return false; + return man.removeExemption(player, checkType); + } + + @Override + public void applyConfig(CompatConfig cfg, String prefix) { + enabled = cfg.getBoolean(prefix + configPrefix + "enabled", defaultEnabled); + ConfigUtil.readStringSetFromList(cfg, prefix + configPrefix + "exempt-names", classes, true, true, false); + } + + @Override + public boolean updateConfig(CompatConfig cfg, String prefix) { + CompatConfig defaults = CompatConfigFactory.getConfig(null); + defaults.set(prefix + configPrefix + "enabled", defaultEnabled); + defaults.set(prefix + configPrefix + "exempt-names", defaultClasses); + return ConfigUtil.forceDefaults(defaults, cfg); + } + + @Override + public boolean isEnabled() { + return enabled; + } + +} diff --git a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/hooks/generic/ConfigurableHook.java b/src/me/asofold/bpl/cncp/hooks/generic/ConfigurableHook.java similarity index 95% rename from CompatNoCheatPlus/src/me/asofold/bpl/cncp/hooks/generic/ConfigurableHook.java rename to src/me/asofold/bpl/cncp/hooks/generic/ConfigurableHook.java index f3a37a9..7c2f265 100644 --- a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/hooks/generic/ConfigurableHook.java +++ b/src/me/asofold/bpl/cncp/hooks/generic/ConfigurableHook.java @@ -1,32 +1,32 @@ -package me.asofold.bpl.cncp.hooks.generic; - -import me.asofold.bpl.cncp.config.compatlayer.CompatConfig; - -/** - * A hook that is using configuration. - * @author mc_dev - * - */ -public interface ConfigurableHook { - - /** - * Adjust internals to the given configuration. - * @param cfg - * @param prefix - */ - public void applyConfig(CompatConfig cfg, String prefix); - - /** - * Update the given configuration with defaults where / if necessary (no blunt overwrite, it is a users config). - * @param cfg - * @param prefix - * @return If the configuration was changed. - */ - public boolean updateConfig(CompatConfig cfg, String prefix); - - /** - * If the hook is enabled by configuration or not. - * @return - */ - public boolean isEnabled(); -} +package me.asofold.bpl.cncp.hooks.generic; + +import me.asofold.bpl.cncp.config.compatlayer.CompatConfig; + +/** + * A hook that is using configuration. + * @author mc_dev + * + */ +public interface ConfigurableHook { + + /** + * Adjust internals to the given configuration. + * @param cfg + * @param prefix + */ + public void applyConfig(CompatConfig cfg, String prefix); + + /** + * Update the given configuration with defaults where / if necessary (no blunt overwrite, it is a users config). + * @param cfg + * @param prefix + * @return If the configuration was changed. + */ + public boolean updateConfig(CompatConfig cfg, String prefix); + + /** + * If the hook is enabled by configuration or not. + * @return + */ + public boolean isEnabled(); +} diff --git a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/hooks/generic/ExemptionManager.java b/src/me/asofold/bpl/cncp/hooks/generic/ExemptionManager.java similarity index 96% rename from CompatNoCheatPlus/src/me/asofold/bpl/cncp/hooks/generic/ExemptionManager.java rename to src/me/asofold/bpl/cncp/hooks/generic/ExemptionManager.java index 8c6db20..7d89841 100644 --- a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/hooks/generic/ExemptionManager.java +++ b/src/me/asofold/bpl/cncp/hooks/generic/ExemptionManager.java @@ -1,224 +1,224 @@ -package me.asofold.bpl.cncp.hooks.generic; - -import java.util.HashMap; -import java.util.Map; - -import org.bukkit.entity.Player; - -import fr.neatmonster.nocheatplus.checks.CheckType; -import fr.neatmonster.nocheatplus.hooks.NCPExemptionManager; - -/** - * Auxiliary methods and data structure to handle simple sort of exemption.
- * NOTE: Not thread safe. - * - * @deprecated: Buggy / outdated concept - should not rely on nested stuff, use TickTask2 to unexempt timely if in doubt. - * - * @author mc_dev - * - */ -public class ExemptionManager{ - - public static enum Status{ - EXEMPTED, - NOT_EXEMPTED, - NEEDS_EXEMPTION, - NEEDS_UNEXEMPTION, - } - - public static class ExemptionInfo{ - public static class CheckEntry{ - public int skip = 0; - public int exempt = 0; - } - /** Counts per type, for players being exempted already, to prevent unexempting. */ - public final Map entries = new HashMap(); - /** - * If empty, it can get removed. - * @return - */ - public boolean isEmpty(){ - return entries.isEmpty(); - } - /** - * - * @param type - * @param isExempted If the player is currently exempted, to be filled in with NCPHookManager.isExempted(player, type) - * @return EXEMPTED or NEEDS_EXEMPTION. The latter means the player has to be exempted. - */ - public Status increase(final CheckType type, final boolean isExempted){ - final CheckEntry entry = entries.get(type); - if (entry == null){ - final CheckEntry newEntry = new CheckEntry(); - entries.put(type, newEntry); - if (isExempted){ - newEntry.skip = 1; - return Status.EXEMPTED; - } - else{ - newEntry.exempt = 1; - return Status.NEEDS_EXEMPTION; - } - } - if (entry.skip > 0){ - if (isExempted){ - entry.skip ++; - return Status.EXEMPTED; - } - else{ - entry.exempt = entry.skip + 1; - entry.skip = 0; - return Status.NEEDS_EXEMPTION; - } - - } - else{ - // entry.exempt > 0 - entry.exempt ++; - return isExempted ? Status.EXEMPTED : Status.NEEDS_EXEMPTION; - } - } - - /** - * - * @param type - * @param isExempted If the player is currently exempted, to be filled in with NCPHookManager.isExempted(player, type) - * @return Status, if NEEDS_EXEMPTION the player has to be exempted. If NEEDS_UNEXEMPTION, the player has to be unexempted. - */ - public Status decrease(final CheckType type, final boolean isExempted){ - final CheckEntry info = entries.get(type); - if (info == null) return isExempted ? Status.EXEMPTED : Status.NOT_EXEMPTED; - if (info.skip > 0){ - info.skip --; - if (info.skip == 0){ - entries.remove(type); - return isExempted ? Status.EXEMPTED : Status.NOT_EXEMPTED; - } - else if (isExempted) return Status.EXEMPTED; - else{ - info.exempt = info.skip; - info.skip = 0; - return Status.NEEDS_EXEMPTION; - } - } - else{ - info.exempt --; - if (info.exempt == 0){ - entries.remove(type); - return isExempted ? Status.NEEDS_UNEXEMPTION : Status.NOT_EXEMPTED; - } - else{ - return isExempted ? Status.EXEMPTED : Status.NEEDS_EXEMPTION; - } - } - } - } - - /** Exact player name -> ExemptionInfo */ - protected final Map exemptions; - - - public ExemptionManager(){ - this(30, 0.75f); - } - - /** - * - * @param initialCapacity For the exemption HashMap. - * @param loadFactor For the exemption HashMap. - */ - public ExemptionManager(int initialCapacity, float loadFactor) { - exemptions = new HashMap(initialCapacity, loadFactor); - } - - /** - * Add exemption count and exempt, if necessary. - * @param player - * @param type - * @return If the player was exempted already. - */ - public boolean addExemption(final Player player, final CheckType type){ - final Status status = addExemption(player.getName(), type, NCPExemptionManager.isExempted(player, type)); - if (status == Status.NEEDS_EXEMPTION) NCPExemptionManager.exemptPermanently(player, type); -// System.out.println("add: " + type.toString() + " -> " + status); - return status == Status.EXEMPTED; - } - - /** - * Increment exemption count. - * @param name - * @return If exemption is needed (NEEDS_EXEMPTION). - */ - public Status addExemption(final String name, final CheckType type, boolean isExempted){ - final ExemptionInfo info = exemptions.get(name); - final Status status; - if (info == null){ - final ExemptionInfo newInfo = new ExemptionInfo(); - status = newInfo.increase(type, isExempted); - exemptions.put(name, newInfo); - } - else{ - status = info.increase(type, isExempted); - } - - return status; - } - - /** - * Decrement exemption count, exempt or unexempt if necessary. - * @param player - * @param type - * @return If the player is still exempted. - */ - public boolean removeExemption(final Player player, final CheckType type){ - final Status status = removeExemption(player.getName(), type, NCPExemptionManager.isExempted(player, type)); - if (status == Status.NEEDS_EXEMPTION) NCPExemptionManager.exemptPermanently(player, type); - else if (status == Status.NEEDS_UNEXEMPTION) NCPExemptionManager.unexempt(player, type); -// System.out.println("remove: " + type.toString() + " -> " + status); - return status == Status.EXEMPTED || status == Status.NEEDS_EXEMPTION; - } - - /** - * Decrement exemption count. - * @param name - * @return Status, NEEDS_EXEMPTION and NEEDS_UNEXEMPTION make it necessary to call NCP API. - */ - public Status removeExemption(final String name, final CheckType type, boolean isExempted){ - final ExemptionInfo info = exemptions.get(name); - if (info == null) return isExempted ? Status.EXEMPTED : Status.NOT_EXEMPTED; - final Status status = info.decrease(type, isExempted); - if (info.isEmpty()) exemptions.remove(name); - return status; - } - - /** - * Check if the player should be exempted right now according to stored info. - * @param name - * @param type - * @return - */ - public boolean shouldBeExempted(final String name, final CheckType type){ - final ExemptionInfo info = exemptions.get(name); - if (info == null) return false; - return !info.isEmpty(); - } - - /** - * Hides the API access from listeners potentially. - * @param player - * @param checkType - */ - public void exempt(final Player player, final CheckType checkType){ - NCPExemptionManager.exemptPermanently(player, checkType); - } - - /** - * Hides the API access from listeners potentially. - * @param player - * @param checkType - */ - public void unexempt(final Player player, final CheckType checkType){ - NCPExemptionManager.unexempt(player, checkType); - } - -} +package me.asofold.bpl.cncp.hooks.generic; + +import java.util.HashMap; +import java.util.Map; + +import org.bukkit.entity.Player; + +import fr.neatmonster.nocheatplus.checks.CheckType; +import fr.neatmonster.nocheatplus.hooks.NCPExemptionManager; + +/** + * Auxiliary methods and data structure to handle simple sort of exemption.
+ * NOTE: Not thread safe. + * + * @deprecated: Buggy / outdated concept - should not rely on nested stuff, use TickTask2 to unexempt timely if in doubt. + * + * @author mc_dev + * + */ +public class ExemptionManager{ + + public static enum Status{ + EXEMPTED, + NOT_EXEMPTED, + NEEDS_EXEMPTION, + NEEDS_UNEXEMPTION, + } + + public static class ExemptionInfo{ + public static class CheckEntry{ + public int skip = 0; + public int exempt = 0; + } + /** Counts per type, for players being exempted already, to prevent unexempting. */ + public final Map entries = new HashMap(); + /** + * If empty, it can get removed. + * @return + */ + public boolean isEmpty(){ + return entries.isEmpty(); + } + /** + * + * @param type + * @param isExempted If the player is currently exempted, to be filled in with NCPHookManager.isExempted(player, type) + * @return EXEMPTED or NEEDS_EXEMPTION. The latter means the player has to be exempted. + */ + public Status increase(final CheckType type, final boolean isExempted){ + final CheckEntry entry = entries.get(type); + if (entry == null){ + final CheckEntry newEntry = new CheckEntry(); + entries.put(type, newEntry); + if (isExempted){ + newEntry.skip = 1; + return Status.EXEMPTED; + } + else{ + newEntry.exempt = 1; + return Status.NEEDS_EXEMPTION; + } + } + if (entry.skip > 0){ + if (isExempted){ + entry.skip ++; + return Status.EXEMPTED; + } + else{ + entry.exempt = entry.skip + 1; + entry.skip = 0; + return Status.NEEDS_EXEMPTION; + } + + } + else{ + // entry.exempt > 0 + entry.exempt ++; + return isExempted ? Status.EXEMPTED : Status.NEEDS_EXEMPTION; + } + } + + /** + * + * @param type + * @param isExempted If the player is currently exempted, to be filled in with NCPHookManager.isExempted(player, type) + * @return Status, if NEEDS_EXEMPTION the player has to be exempted. If NEEDS_UNEXEMPTION, the player has to be unexempted. + */ + public Status decrease(final CheckType type, final boolean isExempted){ + final CheckEntry info = entries.get(type); + if (info == null) return isExempted ? Status.EXEMPTED : Status.NOT_EXEMPTED; + if (info.skip > 0){ + info.skip --; + if (info.skip == 0){ + entries.remove(type); + return isExempted ? Status.EXEMPTED : Status.NOT_EXEMPTED; + } + else if (isExempted) return Status.EXEMPTED; + else{ + info.exempt = info.skip; + info.skip = 0; + return Status.NEEDS_EXEMPTION; + } + } + else{ + info.exempt --; + if (info.exempt == 0){ + entries.remove(type); + return isExempted ? Status.NEEDS_UNEXEMPTION : Status.NOT_EXEMPTED; + } + else{ + return isExempted ? Status.EXEMPTED : Status.NEEDS_EXEMPTION; + } + } + } + } + + /** Exact player name -> ExemptionInfo */ + protected final Map exemptions; + + + public ExemptionManager(){ + this(30, 0.75f); + } + + /** + * + * @param initialCapacity For the exemption HashMap. + * @param loadFactor For the exemption HashMap. + */ + public ExemptionManager(int initialCapacity, float loadFactor) { + exemptions = new HashMap(initialCapacity, loadFactor); + } + + /** + * Add exemption count and exempt, if necessary. + * @param player + * @param type + * @return If the player was exempted already. + */ + public boolean addExemption(final Player player, final CheckType type){ + final Status status = addExemption(player.getName(), type, NCPExemptionManager.isExempted(player, type)); + if (status == Status.NEEDS_EXEMPTION) NCPExemptionManager.exemptPermanently(player, type); +// System.out.println("add: " + type.toString() + " -> " + status); + return status == Status.EXEMPTED; + } + + /** + * Increment exemption count. + * @param name + * @return If exemption is needed (NEEDS_EXEMPTION). + */ + public Status addExemption(final String name, final CheckType type, boolean isExempted){ + final ExemptionInfo info = exemptions.get(name); + final Status status; + if (info == null){ + final ExemptionInfo newInfo = new ExemptionInfo(); + status = newInfo.increase(type, isExempted); + exemptions.put(name, newInfo); + } + else{ + status = info.increase(type, isExempted); + } + + return status; + } + + /** + * Decrement exemption count, exempt or unexempt if necessary. + * @param player + * @param type + * @return If the player is still exempted. + */ + public boolean removeExemption(final Player player, final CheckType type){ + final Status status = removeExemption(player.getName(), type, NCPExemptionManager.isExempted(player, type)); + if (status == Status.NEEDS_EXEMPTION) NCPExemptionManager.exemptPermanently(player, type); + else if (status == Status.NEEDS_UNEXEMPTION) NCPExemptionManager.unexempt(player, type); +// System.out.println("remove: " + type.toString() + " -> " + status); + return status == Status.EXEMPTED || status == Status.NEEDS_EXEMPTION; + } + + /** + * Decrement exemption count. + * @param name + * @return Status, NEEDS_EXEMPTION and NEEDS_UNEXEMPTION make it necessary to call NCP API. + */ + public Status removeExemption(final String name, final CheckType type, boolean isExempted){ + final ExemptionInfo info = exemptions.get(name); + if (info == null) return isExempted ? Status.EXEMPTED : Status.NOT_EXEMPTED; + final Status status = info.decrease(type, isExempted); + if (info.isEmpty()) exemptions.remove(name); + return status; + } + + /** + * Check if the player should be exempted right now according to stored info. + * @param name + * @param type + * @return + */ + public boolean shouldBeExempted(final String name, final CheckType type){ + final ExemptionInfo info = exemptions.get(name); + if (info == null) return false; + return !info.isEmpty(); + } + + /** + * Hides the API access from listeners potentially. + * @param player + * @param checkType + */ + public void exempt(final Player player, final CheckType checkType){ + NCPExemptionManager.exemptPermanently(player, checkType); + } + + /** + * Hides the API access from listeners potentially. + * @param player + * @param checkType + */ + public void unexempt(final Player player, final CheckType checkType){ + NCPExemptionManager.unexempt(player, checkType); + } + +} diff --git a/src/me/asofold/bpl/cncp/hooks/generic/HookBlockBreak.java b/src/me/asofold/bpl/cncp/hooks/generic/HookBlockBreak.java new file mode 100644 index 0000000..ac2dff0 --- /dev/null +++ b/src/me/asofold/bpl/cncp/hooks/generic/HookBlockBreak.java @@ -0,0 +1,64 @@ +package me.asofold.bpl.cncp.hooks.generic; + +import java.util.Arrays; + +import me.asofold.bpl.cncp.config.compatlayer.CompatConfig; + +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockBreakEvent; + +import fr.neatmonster.nocheatplus.checks.CheckType; + +/** + * Wrap block break events to exempt players from checks by comparison of event class names. + * @author mc_dev + * + */ +public class HookBlockBreak extends ClassExemptionHook implements Listener { + + public HookBlockBreak() { + super("block-break."); + defaultClasses.addAll(Arrays.asList(new String[]{ + // MachinaCraft + "ArtificialBlockBreakEvent", + // mcMMO + "FakeBlockBreakEvent", + // MagicSpells + "MagicSpellsBlockBreakEvent" + })); + } + + @Override + public String getHookName() { + return "BlockBreak(default)"; + } + + @Override + public String getHookVersion() { + return "1.1"; + } + + @Override + public Listener[] getListeners() { + return new Listener[]{this}; + } + + @Override + public void applyConfig(CompatConfig cfg, String prefix) { + super.applyConfig(cfg, prefix); + if (classes.isEmpty()) enabled = false; + } + + @EventHandler(priority = EventPriority.LOWEST) + final void onBlockBreakLowest(final BlockBreakEvent event){ + checkExempt(event.getPlayer(), event.getClass(), CheckType.BLOCKBREAK); + } + + @EventHandler(priority = EventPriority.MONITOR) + final void onBlockBreakMonitor(final BlockBreakEvent event){ + checkUnexempt(event.getPlayer(), event.getClass(), CheckType.BLOCKBREAK); + } + +} diff --git a/src/me/asofold/bpl/cncp/hooks/generic/HookBlockPlace.java b/src/me/asofold/bpl/cncp/hooks/generic/HookBlockPlace.java new file mode 100644 index 0000000..8d65e20 --- /dev/null +++ b/src/me/asofold/bpl/cncp/hooks/generic/HookBlockPlace.java @@ -0,0 +1,62 @@ +package me.asofold.bpl.cncp.hooks.generic; + +import java.util.Arrays; + +import me.asofold.bpl.cncp.config.compatlayer.CompatConfig; + +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockPlaceEvent; + +import fr.neatmonster.nocheatplus.checks.CheckType; + +/** + * Wrap block place events to exempt players from checks by comparison of event class names. + * @author mc_dev + * + */ +public class HookBlockPlace extends ClassExemptionHook implements Listener{ + + public HookBlockPlace() { + super("block-place."); + defaultClasses.addAll(Arrays.asList(new String[]{ + // MachinaCraft + "ArtificialBlockPlaceEvent", + // MagicSpells + "MagicSpellsBlockPlaceEvent" + })); + } + + @Override + public String getHookName() { + return "BlockPlace(default)"; + } + + @Override + public String getHookVersion() { + return "1.0"; + } + + @Override + public Listener[] getListeners() { + return new Listener[]{this}; + } + + @Override + public void applyConfig(CompatConfig cfg, String prefix) { + super.applyConfig(cfg, prefix); + if (classes.isEmpty()) enabled = false; + } + + @EventHandler(priority = EventPriority.LOWEST) + final void onBlockPlaceLowest(final BlockPlaceEvent event){ + checkExempt(event.getPlayer(), event.getClass(), CheckType.BLOCKPLACE); + } + + @EventHandler(priority = EventPriority.MONITOR) + final void onBlockPlaceMonitor(final BlockPlaceEvent event){ + checkUnexempt(event.getPlayer(), event.getClass(), CheckType.BLOCKPLACE); + } + +} diff --git a/src/me/asofold/bpl/cncp/hooks/generic/HookEntityDamageByEntity.java b/src/me/asofold/bpl/cncp/hooks/generic/HookEntityDamageByEntity.java new file mode 100644 index 0000000..42cc657 --- /dev/null +++ b/src/me/asofold/bpl/cncp/hooks/generic/HookEntityDamageByEntity.java @@ -0,0 +1,66 @@ +package me.asofold.bpl.cncp.hooks.generic; + +import java.util.Arrays; + +import me.asofold.bpl.cncp.config.compatlayer.CompatConfig; + +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +import fr.neatmonster.nocheatplus.checks.CheckType; + +public class HookEntityDamageByEntity extends ClassExemptionHook implements + Listener { + + public HookEntityDamageByEntity() { + super("entity-damage-by-entity."); + defaultClasses.addAll(Arrays.asList(new String[] { + // CrackShot + "WeaponDamageEntityEvent", + // MagicSpells + "MagicSpellsEntityDamageByEntityEvent" })); + } + + @Override + public String getHookName() { + return "EntityDamageByEntity(default)"; + } + + @Override + public String getHookVersion() { + return "0.0"; + } + + @Override + public Listener[] getListeners() { + return new Listener[] { this }; + } + + @Override + public void applyConfig(CompatConfig cfg, String prefix) { + super.applyConfig(cfg, prefix); + if (classes.isEmpty()) + enabled = false; + } + + @EventHandler(priority = EventPriority.LOWEST) + final void onDamageLowest(final EntityDamageByEntityEvent event) { + final Entity damager = event.getDamager(); + if (damager instanceof Player) { + checkExempt((Player) damager, event.getClass(), CheckType.FIGHT); + } + } + + @EventHandler(priority = EventPriority.MONITOR) + final void onDamageMonitor(final EntityDamageByEntityEvent event) { + final Entity damager = event.getDamager(); + if (damager instanceof Player) { + checkUnexempt((Player) damager, event.getClass(), CheckType.FIGHT); + } + } + +} diff --git a/src/me/asofold/bpl/cncp/hooks/generic/HookInstaBreak.java b/src/me/asofold/bpl/cncp/hooks/generic/HookInstaBreak.java new file mode 100644 index 0000000..74f6798 --- /dev/null +++ b/src/me/asofold/bpl/cncp/hooks/generic/HookInstaBreak.java @@ -0,0 +1,171 @@ +package me.asofold.bpl.cncp.hooks.generic; + +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; + +import me.asofold.bpl.cncp.config.compatlayer.CompatConfig; +import me.asofold.bpl.cncp.config.compatlayer.CompatConfigFactory; +import me.asofold.bpl.cncp.config.compatlayer.ConfigUtil; +import me.asofold.bpl.cncp.hooks.AbstractHook; + +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockDamageEvent; + +import fr.neatmonster.nocheatplus.checks.CheckType; +import fr.neatmonster.nocheatplus.utilities.TickTask; + +public class HookInstaBreak extends AbstractHook implements ConfigurableHook, Listener { + + public static interface InstaExemption{ + public void addExemptNext(CheckType[] types); + public Set getExemptNext(); + } + + public static class StackEntry{ + public final CheckType[] checkTypes; + public final int tick; + public final Player player; + public boolean used = false; + public StackEntry(final Player player , final CheckType[] checkTypes){ + this.player = player; + this.checkTypes = checkTypes; + tick = TickTask.getTick(); + } + public boolean isOutdated(final int tick){ + return tick != this.tick; + } + } + + protected static InstaExemption runtime = null; + + public static void addExemptNext(final CheckType[] types){ + runtime.addExemptNext(types); + } + + protected final ExemptionManager exMan = new ExemptionManager(); + + protected boolean enabled = true; + + protected final List stack = new LinkedList(); + + @Override + public String getHookName() { + return "InstaBreak(default)"; + } + + @Override + public String getHookVersion() { + return "1.0"; + } + + @Override + public void applyConfig(CompatConfig cfg, String prefix) { + enabled = cfg.getBoolean(prefix + "insta-break.enabled", true); + } + + @Override + public boolean updateConfig(CompatConfig cfg, String prefix) { + CompatConfig defaults = CompatConfigFactory.getConfig(null); + defaults.set(prefix + "insta-break.enabled", true); + return ConfigUtil.forceDefaults(defaults, cfg); + } + + @Override + public boolean isEnabled() { + return enabled; + } + + @Override + public CheckType[] getCheckTypes() { + return null; + } + + @Override + public Listener[] getListeners() { + runtime = new InstaExemption() { + protected final Set types = new HashSet(); + @Override + public final void addExemptNext(final CheckType[] types) { + for (int i = 0; i < types.length; i++){ + this.types.add(types[i]); + } + } + @Override + public Set getExemptNext() { + return types; + } + }; + return new Listener[]{this}; + } + + protected CheckType[] fetchTypes(){ + final Set types = runtime.getExemptNext(); + final CheckType[] a = new CheckType[types.size()]; + if (!types.isEmpty()) types.toArray(a); + types.clear(); + return a; + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = false) + public void onBlockDamage(final BlockDamageEvent event){ + checkStack(); + if (!event.isCancelled() && event.getInstaBreak()){ + stack.add(new StackEntry(event.getPlayer(), fetchTypes())); + } + else{ + runtime.getExemptNext().clear(); + } + } + + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = false) + public void onBlockBreakLowest(final BlockBreakEvent event){ + checkStack(); + if (!stack.isEmpty()){ + final Player player = event.getPlayer(); + final StackEntry entry = stack.get(stack.size() - 1); + if (player.equals(entry.player)) addExemption(entry); + } + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = false) + public void onBlockBreakMONITOR(final BlockBreakEvent event){ + if (!stack.isEmpty()){ + final Player player = event.getPlayer(); + final StackEntry entry = stack.get(stack.size() - 1); + if (player.equals(entry.player)) removeExemption(stack.remove(stack.size() - 1)); + } + } + + public void addExemption(final StackEntry entry){ + entry.used = true; + for (int i = 0; i < entry.checkTypes.length; i++){ + exMan.addExemption(entry.player, entry.checkTypes[i]); + } + } + + public void removeExemption(final StackEntry entry){ + if (!entry.used) return; + for (int i = 0; i < entry.checkTypes.length; i++){ + exMan.removeExemption(entry.player, entry.checkTypes[i]); + } + } + + public void checkStack(){ + if (stack.isEmpty()) return; + Iterator it = stack.iterator(); + final int tick = TickTask.getTick(); + while (it.hasNext()){ + final StackEntry entry = it.next(); + if (entry.isOutdated(tick)) it.remove(); + if (entry.used) removeExemption(entry); + } + } + +} diff --git a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/hooks/generic/HookPlayerClass.java b/src/me/asofold/bpl/cncp/hooks/generic/HookPlayerClass.java similarity index 96% rename from CompatNoCheatPlus/src/me/asofold/bpl/cncp/hooks/generic/HookPlayerClass.java rename to src/me/asofold/bpl/cncp/hooks/generic/HookPlayerClass.java index 6ad57e4..cbaa45b 100644 --- a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/hooks/generic/HookPlayerClass.java +++ b/src/me/asofold/bpl/cncp/hooks/generic/HookPlayerClass.java @@ -1,121 +1,121 @@ -package me.asofold.bpl.cncp.hooks.generic; - -import java.util.Arrays; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.Set; - -import me.asofold.bpl.cncp.config.compatlayer.CompatConfig; -import me.asofold.bpl.cncp.config.compatlayer.CompatConfigFactory; -import me.asofold.bpl.cncp.config.compatlayer.ConfigUtil; -import me.asofold.bpl.cncp.hooks.AbstractHook; - -import org.bukkit.entity.Player; - -import fr.neatmonster.nocheatplus.checks.CheckType; -import fr.neatmonster.nocheatplus.checks.access.IViolationInfo; -import fr.neatmonster.nocheatplus.hooks.NCPHook; - -public final class HookPlayerClass extends AbstractHook implements ConfigurableHook { - - private static final boolean defaultEnabled = false; - - protected final Set classNames = new HashSet(); - - protected boolean exemptAll = true; - - protected boolean checkSuperClass = true; - - protected Object ncpHook = null; - - protected boolean enabled = defaultEnabled; - - /** - * Normal class name. - */ - protected Set playerClassNames = new HashSet(); - - public HookPlayerClass(){ - // TODO: Might need cleanup. - this.playerClassNames.addAll(Arrays.asList(new String[]{"CraftPlayer", "SpoutCraftPlayer", "SpoutPlayer", "SpoutClientPlayer", "SpoutPlayerSnapshot"})); - } - - @Override - public final String getHookName() { - return "PlayerClass(default)"; - } - - @Override - public final String getHookVersion() { - return "2.3"; - } - - @Override - public NCPHook getNCPHook() { - if (ncpHook == null){ - ncpHook = new NCPHook() { - @Override - public final boolean onCheckFailure(final CheckType checkType, final Player player, final IViolationInfo info) { - if (exemptAll && !playerClassNames.contains(player.getClass().getSimpleName())) return true; - else { - if (classNames.isEmpty()) return false; - final Class clazz = player.getClass(); - final String name = clazz.getSimpleName(); - if (classNames.contains(name)) return true; - else if (checkSuperClass){ - while (true){ - final Class superClass = clazz.getSuperclass(); - if (superClass == null) return false; - else{ - final String superName = superClass.getSimpleName(); - if (superName.equals("Object")) return false; - else if (classNames.contains(superName)){ - return true; - } - } - } - } - } - return false; // ECLIPSE - } - - @Override - public String getHookVersion() { - return "3.1"; - } - - @Override - public String getHookName() { - return "PlayerClass(cncp)"; - } - }; - } - return (NCPHook) ncpHook; - } - - @Override - public void applyConfig(CompatConfig cfg, String prefix) { - enabled = cfg.getBoolean(prefix + "player-class.enabled", defaultEnabled); - ConfigUtil.readStringSetFromList(cfg, prefix + "player-class.exempt-names", classNames, true, true, false); - exemptAll = cfg.getBoolean(prefix + "player-class.exempt-all", true); - ConfigUtil.readStringSetFromList(cfg, prefix + "player-class.class-names", playerClassNames, true, true, false); - checkSuperClass = cfg.getBoolean(prefix + "player-class.super-class", true); - } - - @Override - public boolean updateConfig(CompatConfig cfg, String prefix) { - CompatConfig defaults = CompatConfigFactory.getConfig(null); - defaults.set(prefix + "player-class.enabled", defaultEnabled); - defaults.set(prefix + "player-class.exempt-names", new LinkedList()); - defaults.set(prefix + "player-class.exempt-all", true); - defaults.set(prefix + "player-class.class-names", new LinkedList(playerClassNames)); - defaults.set(prefix + "player-class.super-class", true); - return ConfigUtil.forceDefaults(defaults, cfg); - } - - @Override - public boolean isEnabled() { - return enabled; - } - -} +package me.asofold.bpl.cncp.hooks.generic; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.Set; + +import me.asofold.bpl.cncp.config.compatlayer.CompatConfig; +import me.asofold.bpl.cncp.config.compatlayer.CompatConfigFactory; +import me.asofold.bpl.cncp.config.compatlayer.ConfigUtil; +import me.asofold.bpl.cncp.hooks.AbstractHook; + +import org.bukkit.entity.Player; + +import fr.neatmonster.nocheatplus.checks.CheckType; +import fr.neatmonster.nocheatplus.checks.access.IViolationInfo; +import fr.neatmonster.nocheatplus.hooks.NCPHook; + +public final class HookPlayerClass extends AbstractHook implements ConfigurableHook { + + private static final boolean defaultEnabled = false; + + protected final Set classNames = new HashSet(); + + protected boolean exemptAll = true; + + protected boolean checkSuperClass = true; + + protected Object ncpHook = null; + + protected boolean enabled = defaultEnabled; + + /** + * Normal class name. + */ + protected Set playerClassNames = new HashSet(); + + public HookPlayerClass(){ + // TODO: Might need cleanup. + this.playerClassNames.addAll(Arrays.asList(new String[]{"CraftPlayer", "SpoutCraftPlayer", "SpoutPlayer", "SpoutClientPlayer", "SpoutPlayerSnapshot"})); + } + + @Override + public final String getHookName() { + return "PlayerClass(default)"; + } + + @Override + public final String getHookVersion() { + return "2.3"; + } + + @Override + public NCPHook getNCPHook() { + if (ncpHook == null){ + ncpHook = new NCPHook() { + @Override + public final boolean onCheckFailure(final CheckType checkType, final Player player, final IViolationInfo info) { + if (exemptAll && !playerClassNames.contains(player.getClass().getSimpleName())) return true; + else { + if (classNames.isEmpty()) return false; + final Class clazz = player.getClass(); + final String name = clazz.getSimpleName(); + if (classNames.contains(name)) return true; + else if (checkSuperClass){ + while (true){ + final Class superClass = clazz.getSuperclass(); + if (superClass == null) return false; + else{ + final String superName = superClass.getSimpleName(); + if (superName.equals("Object")) return false; + else if (classNames.contains(superName)){ + return true; + } + } + } + } + } + return false; // ECLIPSE + } + + @Override + public String getHookVersion() { + return "3.1"; + } + + @Override + public String getHookName() { + return "PlayerClass(cncp)"; + } + }; + } + return (NCPHook) ncpHook; + } + + @Override + public void applyConfig(CompatConfig cfg, String prefix) { + enabled = cfg.getBoolean(prefix + "player-class.enabled", defaultEnabled); + ConfigUtil.readStringSetFromList(cfg, prefix + "player-class.exempt-names", classNames, true, true, false); + exemptAll = cfg.getBoolean(prefix + "player-class.exempt-all", true); + ConfigUtil.readStringSetFromList(cfg, prefix + "player-class.class-names", playerClassNames, true, true, false); + checkSuperClass = cfg.getBoolean(prefix + "player-class.super-class", true); + } + + @Override + public boolean updateConfig(CompatConfig cfg, String prefix) { + CompatConfig defaults = CompatConfigFactory.getConfig(null); + defaults.set(prefix + "player-class.enabled", defaultEnabled); + defaults.set(prefix + "player-class.exempt-names", new LinkedList()); + defaults.set(prefix + "player-class.exempt-all", true); + defaults.set(prefix + "player-class.class-names", new LinkedList(playerClassNames)); + defaults.set(prefix + "player-class.super-class", true); + return ConfigUtil.forceDefaults(defaults, cfg); + } + + @Override + public boolean isEnabled() { + return enabled; + } + +} diff --git a/src/me/asofold/bpl/cncp/hooks/generic/HookPlayerInteract.java b/src/me/asofold/bpl/cncp/hooks/generic/HookPlayerInteract.java new file mode 100644 index 0000000..b9ebc73 --- /dev/null +++ b/src/me/asofold/bpl/cncp/hooks/generic/HookPlayerInteract.java @@ -0,0 +1,58 @@ +package me.asofold.bpl.cncp.hooks.generic; + +import fr.neatmonster.nocheatplus.checks.CheckType; +import me.asofold.bpl.cncp.config.compatlayer.CompatConfig; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerInteractEvent; + +import java.util.Arrays; + +/** + * Wrap player interact events to exempt players from checks by comparison of event class names. + * Uses mc_dev's format for exemption based upon class names. + * + */ +public class HookPlayerInteract extends ClassExemptionHook implements Listener{ + + public HookPlayerInteract() { + super("player-interact."); + defaultClasses.addAll(Arrays.asList(new String[]{ + // MagicSpells + "MagicSpellsPlayerInteractEvent" + })); + } + + @Override + public String getHookName() { + return "Interact(default)"; + } + + @Override + public String getHookVersion() { + return "1.0"; + } + + @Override + public Listener[] getListeners() { + return new Listener[]{this}; + } + + @Override + public void applyConfig(CompatConfig cfg, String prefix) { + super.applyConfig(cfg, prefix); + if (classes.isEmpty()) enabled = false; + } + + @EventHandler(priority = EventPriority.LOWEST) + final void onPlayerInteractLowest(final PlayerInteractEvent event){ + checkExempt(event.getPlayer(), event.getClass(), CheckType.BLOCKINTERACT); + } + + @EventHandler(priority = EventPriority.MONITOR) + final void onPlayerInteractMonitor(final PlayerInteractEvent event){ + checkUnexempt(event.getPlayer(), event.getClass(), CheckType.BLOCKINTERACT); + } + +} diff --git a/src/me/asofold/bpl/cncp/hooks/generic/HookSetSpeed.java b/src/me/asofold/bpl/cncp/hooks/generic/HookSetSpeed.java new file mode 100644 index 0000000..db03a90 --- /dev/null +++ b/src/me/asofold/bpl/cncp/hooks/generic/HookSetSpeed.java @@ -0,0 +1,106 @@ +package me.asofold.bpl.cncp.hooks.generic; + +import me.asofold.bpl.cncp.config.compatlayer.CompatConfig; +import me.asofold.bpl.cncp.config.compatlayer.CompatConfigFactory; +import me.asofold.bpl.cncp.config.compatlayer.ConfigUtil; +import me.asofold.bpl.cncp.hooks.AbstractHook; + +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerJoinEvent; + +import fr.neatmonster.nocheatplus.checks.CheckType; + +public class HookSetSpeed extends AbstractHook implements Listener, ConfigurableHook{ + + private static final float defaultFlySpeed = 0.1f; + private static final float defaultWalkSpeed = 0.2f; + + protected float flySpeed = defaultFlySpeed; + protected float walkSpeed = defaultWalkSpeed; + + protected boolean enabled = false; + +// private String allowFlightPerm = "cncp.allow-flight"; + + public HookSetSpeed() throws SecurityException, NoSuchMethodException{ + Player.class.getDeclaredMethod("setFlySpeed", float.class); + } + + public void init(){ + for (final Player player : Bukkit.getOnlinePlayers()){ + setSpeed(player); + } + } + + @Override + public String getHookName() { + return "SetSpeed(default)"; + } + + @Override + public String getHookVersion() { + return "2.2"; + } + + @Override + public CheckType[] getCheckTypes() { + return new CheckType[0]; + } + + @Override + public Listener[] getListeners() { + try{ + // Initialize here, at the end of enable. + init(); + } + catch (Throwable t){} + return new Listener[]{this} ; + } + + public final void setSpeed(final Player player){ +// if (allowFlightPerm.equals("") || player.hasPermission(allowFlightPerm)) player.setAllowFlight(true); + player.setWalkSpeed(walkSpeed); + player.setFlySpeed(flySpeed); + } + + @EventHandler(priority=EventPriority.LOWEST) + public final void onPlayerJoin(final PlayerJoinEvent event){ + setSpeed(event.getPlayer()); + } + + @Override + public void applyConfig(CompatConfig cfg, String prefix) { + enabled = cfg.getBoolean(prefix + "set-speed.enabled", false); + flySpeed = cfg.getDouble(prefix + "set-speed.fly-speed", (double) defaultFlySpeed).floatValue(); + walkSpeed = cfg.getDouble(prefix + "set-speed.walk-speed", (double) defaultWalkSpeed).floatValue(); +// allowFlightPerm = cfg.getString(prefix + "set-speed.allow-flight-permission", ref.allowFlightPerm); + } + + @Override + public boolean updateConfig(CompatConfig cfg, String prefix) { + CompatConfig defaults = CompatConfigFactory.getConfig(null); + defaults.set(prefix + "set-speed.enabled", false); + defaults.set(prefix + "set-speed.fly-speed", defaultFlySpeed); + defaults.set(prefix + "set-speed.walk-speed", defaultWalkSpeed); +// cfg.set(prefix + "set-speed.allow-flight-permission", ref.allowFlightPerm); + return ConfigUtil.forceDefaults(defaults, cfg); + } + + @Override + public boolean isEnabled() { + return enabled; + } + +// public String getAllowFlightPerm() { +// return allowFlightPerm; +// } + +// public void setAllowFlightPerm(String allowFlightPerm) { +// this.allowFlightPerm = allowFlightPerm; +// } + +} diff --git a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/hooks/magicspells/HookMagicSpells.java b/src/me/asofold/bpl/cncp/hooks/magicspells/HookMagicSpells.java similarity index 92% rename from CompatNoCheatPlus/src/me/asofold/bpl/cncp/hooks/magicspells/HookMagicSpells.java rename to src/me/asofold/bpl/cncp/hooks/magicspells/HookMagicSpells.java index 8231f69..986ee17 100644 --- a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/hooks/magicspells/HookMagicSpells.java +++ b/src/me/asofold/bpl/cncp/hooks/magicspells/HookMagicSpells.java @@ -1,121 +1,121 @@ -package me.asofold.bpl.cncp.hooks.magicspells; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import me.asofold.bpl.cncp.config.compatlayer.CompatConfig; -import me.asofold.bpl.cncp.config.compatlayer.CompatConfigFactory; -import me.asofold.bpl.cncp.config.compatlayer.ConfigUtil; -import me.asofold.bpl.cncp.hooks.AbstractConfigurableHook; - -import org.bukkit.Bukkit; -import org.bukkit.event.Listener; - -import fr.neatmonster.nocheatplus.checks.CheckType; - -public class HookMagicSpells extends AbstractConfigurableHook implements Listener{ - - protected final Map spellMap = new HashMap(); - - public HookMagicSpells(){ - super("MagicSpells(default)", "1.0", "magicspells."); - assertPluginPresent("MagicSpells"); - } - - @Override - public Listener[] getListeners() { - return new Listener[]{ - this - }; - } - -// @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) -// public void onSpellCast(final SpellCastEvent event){ -// if (event.getSpellCastState() != SpellCastState.NORMAL) return; -// exempt(event.getCaster(), event.getSpell()); -// } -// -// @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) -// public void onSpellCasted(final SpellCastedEvent event){ -// unexempt(event.getCaster(), event.getSpell()); -// } -// -// private void exempt(final Player player, final Spell spell) { -// final CheckType[] types = getCheckTypes(spell); -// if (types == null) return; -// for (final CheckType type : types){ -// NCPExemptionManager.exemptPermanently(player, type); -// // Safety fall-back: -// // TODO: Might interfere with "slow" effects of spells ? [might add config for this.] -// TickTask2.addUnexemptions(player, types); -// } -// } -// -// private void unexempt(final Player player, final Spell spell) { -// final CheckType[] types = getCheckTypes(spell); -// if (types == null) return; -// for (final CheckType type : types){ -// NCPExemptionManager.unexempt(player, type); -// } -// } -// -// protected CheckType[] getCheckTypes(final Spell spell){ -// return spellMap.get(spell.getName()); -// } - - /* (non-Javadoc) - * @see me.asofold.bpl.cncp.hooks.AbstractConfigurableHook#applyConfig(me.asofold.bpl.cncp.config.compatlayer.CompatConfig, java.lang.String) - */ - @Override - public void applyConfig(CompatConfig cfg, String prefix) { - super.applyConfig(cfg, prefix); - prefix += this.configPrefix; - List keys = cfg.getStringKeys(prefix + "exempt-spells"); - for (String key : keys){ - String fullKey = ConfigUtil.bestPath(cfg, prefix + "exempt-spells." + key); - String types = cfg.getString(fullKey); - if (types == null) continue; - String[] split = types.split(","); - Set checkTypes = new HashSet(); - for (String input : split){ - input = input.trim().toUpperCase().replace('-', '_').replace(' ', '_').replace('.', '_'); - CheckType type = null; - try{ - type = CheckType.valueOf(input); - } - catch(Throwable t){ - } - if (type == null){ - Bukkit.getLogger().warning("[cncp] HookMagicSpells: Bad check type at " + fullKey + ": " + input); - } - else checkTypes.add(type); - } - if (checkTypes.isEmpty()){ - Bukkit.getLogger().warning("[cncp] HookMagicSpells: No CheckType entries at: " + fullKey); - } - else{ - CheckType[] a = new CheckType[checkTypes.size()]; - checkTypes.toArray(a); - spellMap.put(key, a); - } - } - } - - /* (non-Javadoc) - * @see me.asofold.bpl.cncp.hooks.AbstractConfigurableHook#updateConfig(me.asofold.bpl.cncp.config.compatlayer.CompatConfig, java.lang.String) - */ - @Override - public boolean updateConfig(CompatConfig cfg, String prefix) { - super.updateConfig(cfg, prefix); - CompatConfig defaults = CompatConfigFactory.getConfig(null); - prefix += this.configPrefix; - // TODO: Write default section. - defaults.set(prefix + "NOTE", "MagicSpells support is experimental, only instant spells can be added here."); - defaults.set(prefix + "exempt-spells.NameOfExampleSpell", "COMBINED_MUNCHHAUSEN, UNKNOWN, BLOCKPLACE_NOSWING"); - return ConfigUtil.forceDefaults(defaults, cfg); - } - -} +package me.asofold.bpl.cncp.hooks.magicspells; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import me.asofold.bpl.cncp.config.compatlayer.CompatConfig; +import me.asofold.bpl.cncp.config.compatlayer.CompatConfigFactory; +import me.asofold.bpl.cncp.config.compatlayer.ConfigUtil; +import me.asofold.bpl.cncp.hooks.AbstractConfigurableHook; + +import org.bukkit.Bukkit; +import org.bukkit.event.Listener; + +import fr.neatmonster.nocheatplus.checks.CheckType; + +public class HookMagicSpells extends AbstractConfigurableHook implements Listener{ + + protected final Map spellMap = new HashMap(); + + public HookMagicSpells(){ + super("MagicSpells(default)", "1.0", "magicspells."); + assertPluginPresent("MagicSpells"); + } + + @Override + public Listener[] getListeners() { + return new Listener[]{ + this + }; + } + +// @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) +// public void onSpellCast(final SpellCastEvent event){ +// if (event.getSpellCastState() != SpellCastState.NORMAL) return; +// exempt(event.getCaster(), event.getSpell()); +// } +// +// @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) +// public void onSpellCasted(final SpellCastedEvent event){ +// unexempt(event.getCaster(), event.getSpell()); +// } +// +// private void exempt(final Player player, final Spell spell) { +// final CheckType[] types = getCheckTypes(spell); +// if (types == null) return; +// for (final CheckType type : types){ +// NCPExemptionManager.exemptPermanently(player, type); +// // Safety fall-back: +// // TODO: Might interfere with "slow" effects of spells ? [might add config for this.] +// TickTask2.addUnexemptions(player, types); +// } +// } +// +// private void unexempt(final Player player, final Spell spell) { +// final CheckType[] types = getCheckTypes(spell); +// if (types == null) return; +// for (final CheckType type : types){ +// NCPExemptionManager.unexempt(player, type); +// } +// } +// +// protected CheckType[] getCheckTypes(final Spell spell){ +// return spellMap.get(spell.getName()); +// } + + /* (non-Javadoc) + * @see me.asofold.bpl.cncp.hooks.AbstractConfigurableHook#applyConfig(me.asofold.bpl.cncp.config.compatlayer.CompatConfig, java.lang.String) + */ + @Override + public void applyConfig(CompatConfig cfg, String prefix) { + super.applyConfig(cfg, prefix); + prefix += this.configPrefix; + List keys = cfg.getStringKeys(prefix + "exempt-spells"); + for (String key : keys){ + String fullKey = ConfigUtil.bestPath(cfg, prefix + "exempt-spells." + key); + String types = cfg.getString(fullKey); + if (types == null) continue; + String[] split = types.split(","); + Set checkTypes = new HashSet(); + for (String input : split){ + input = input.trim().toUpperCase().replace('-', '_').replace(' ', '_').replace('.', '_'); + CheckType type = null; + try{ + type = CheckType.valueOf(input); + } + catch(Throwable t){ + } + if (type == null){ + Bukkit.getLogger().warning("[CompatNoCheatPlus] HookMagicSpells: Bad check type at " + fullKey + ": " + input); + } + else checkTypes.add(type); + } + if (checkTypes.isEmpty()){ + Bukkit.getLogger().warning("[CompatNoCheatPlus] HookMagicSpells: No CheckType entries at: " + fullKey); + } + else{ + CheckType[] a = new CheckType[checkTypes.size()]; + checkTypes.toArray(a); + spellMap.put(key, a); + } + } + } + + /* (non-Javadoc) + * @see me.asofold.bpl.cncp.hooks.AbstractConfigurableHook#updateConfig(me.asofold.bpl.cncp.config.compatlayer.CompatConfig, java.lang.String) + */ + @Override + public boolean updateConfig(CompatConfig cfg, String prefix) { + super.updateConfig(cfg, prefix); + CompatConfig defaults = CompatConfigFactory.getConfig(null); + prefix += this.configPrefix; + // TODO: Write default section. + defaults.set(prefix + "NOTE", "MagicSpells support is experimental, only instant spells can be added here."); + defaults.set(prefix + "exempt-spells.NameOfExampleSpell", "COMBINED_MUNCHHAUSEN, UNKNOWN, BLOCKPLACE_NOSWING"); + return ConfigUtil.forceDefaults(defaults, cfg); + } + +} diff --git a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/hooks/mcmmo/HookFacadeImpl.java b/src/me/asofold/bpl/cncp/hooks/mcmmo/HookFacadeImpl.java similarity index 91% rename from CompatNoCheatPlus/src/me/asofold/bpl/cncp/hooks/mcmmo/HookFacadeImpl.java rename to src/me/asofold/bpl/cncp/hooks/mcmmo/HookFacadeImpl.java index f9611b0..f1cee5c 100644 --- a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/hooks/mcmmo/HookFacadeImpl.java +++ b/src/me/asofold/bpl/cncp/hooks/mcmmo/HookFacadeImpl.java @@ -1,256 +1,253 @@ -package me.asofold.bpl.cncp.hooks.mcmmo; - -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; - -import fr.neatmonster.nocheatplus.checks.CheckType; -import fr.neatmonster.nocheatplus.checks.access.IViolationInfo; -import fr.neatmonster.nocheatplus.hooks.NCPHook; -import fr.neatmonster.nocheatplus.players.DataManager; -import fr.neatmonster.nocheatplus.utilities.map.BlockProperties; -import fr.neatmonster.nocheatplus.utilities.map.BlockProperties.ToolProps; -import fr.neatmonster.nocheatplus.utilities.map.BlockProperties.ToolType; -import me.asofold.bpl.cncp.CompatNoCheatPlus; -import me.asofold.bpl.cncp.hooks.generic.ExemptionManager; -import me.asofold.bpl.cncp.hooks.generic.HookInstaBreak; -import me.asofold.bpl.cncp.hooks.mcmmo.HookmcMMO.HookFacade; -import me.asofold.bpl.cncp.utils.ActionFrequency; -import me.asofold.bpl.cncp.utils.TickTask2; - -@SuppressWarnings("deprecation") -public class HookFacadeImpl implements HookFacade, NCPHook { - - - protected final ExemptionManager exMan = new ExemptionManager(); - - /** Normal click per block skills. */ - protected final CheckType[] exemptBreakNormal = new CheckType[]{ - CheckType.BLOCKBREAK_FASTBREAK, CheckType.BLOCKBREAK_FREQUENCY, - CheckType.BLOCKBREAK_NOSWING, - CheckType.BLOCKBREAK_WRONGBLOCK, // Not optimal but ok. - }; - - - protected final CheckType[] exemptBreakMany = new CheckType[]{ - CheckType.BLOCKBREAK, CheckType.COMBINED_IMPROBABLE, - }; - - /** Fighting damage of effects such as bleeding or area (potentially). */ - protected final CheckType[] exemptFightEffect = new CheckType[]{ - CheckType.FIGHT_SPEED, CheckType.FIGHT_DIRECTION, - CheckType.FIGHT_ANGLE, CheckType.FIGHT_NOSWING, - CheckType.FIGHT_REACH, CheckType.COMBINED_IMPROBABLE, - }; - - // Presets for after failure exemption. - protected final Map cancelChecksBlockBreak = new HashMap(); - // protected final Map cancelChecksBlockDamage = new HashMap(); - // protected final Map cancelChecksDamage = new HashMap(); - - protected boolean useInstaBreakHook; - protected int clicksPerSecond; - protected String cancel = null; - protected long cancelTicks = 0; - - protected final Map cancelChecks = new HashMap(); - - /** - * Last block breaking time - */ - protected final Map lastBreak = new HashMap(50); - - /** Counter for nested events to cancel break counting. */ - protected int breakCancel = 0; - - protected int lastBreakAddCount = 0; - protected long lastBreakCleanup = 0; - - public HookFacadeImpl(boolean useInstaBreakHook, int clicksPerSecond){ - this.useInstaBreakHook = useInstaBreakHook; - this.clicksPerSecond = clicksPerSecond; - cancelChecksBlockBreak.put(CheckType.BLOCKBREAK_NOSWING, 1); - cancelChecksBlockBreak.put(CheckType.BLOCKBREAK_FASTBREAK, 1); - // - // cancelChecksBlockDamage.put(CheckType.BLOCKBREAK_FASTBREAK, 1); - // - // cancelChecksDamage.put(CheckType.FIGHT_ANGLE, 1); - // cancelChecksDamage.put(CheckType.FIGHT_SPEED, 1); - } - - @Override - public String getHookName() { - return "mcMMO(cncp)"; - } - - @Override - public String getHookVersion() { - return "2.3"; - } - - @Override - public final boolean onCheckFailure(final CheckType checkType, final Player player, final IViolationInfo info) { - // System.out.println(player.getName() + " -> " + checkType + "---------------------------"); - // Somewhat generic canceling mechanism (within the same tick). - // Might later fail, if block break event gets scheduled after block damage having set insta break, instead of letting them follow directly. - if (cancel == null){ - return false; - } - - final String name = player.getName(); - if (cancel.equals(name)){ - - if (player.getTicksLived() != cancelTicks){ - cancel = null; - } - else{ - final Integer n = cancelChecks.get(checkType); - if (n == null){ - return false; - } - else if (n > 0){ - if (n == 1) cancelChecks.remove(checkType); - else cancelChecks.put(checkType, n - 1); - } - return true; - } - } - return false; - } - - private final void setPlayer(final Player player, Map cancelChecks){ - cancel = player.getName(); - cancelTicks = player.getTicksLived(); - this.cancelChecks.clear(); - this.cancelChecks.putAll(cancelChecks); - } - - public ToolProps getToolProps(final ItemStack stack){ - if (stack == null) return BlockProperties.noTool; - else return BlockProperties.getToolProps(stack); - } - - public void addExemption(final Player player, final CheckType[] types){ - for (final CheckType type : types){ - exMan.addExemption(player, type); - TickTask2.addUnexemptions(player, types); - } - } - - public void removeExemption(final Player player, final CheckType[] types){ - for (final CheckType type : types){ - exMan.removeExemption(player, type); - } - } - - @Override - public final void damageLowest(final Player player) { - // System.out.println("damage lowest"); - // setPlayer(player, cancelChecksDamage); - addExemption(player, exemptFightEffect); - } - - @Override - public final void blockDamageLowest(final Player player) { - // System.out.println("block damage lowest"); - // setPlayer(player, cancelChecksBlockDamage); - if (getToolProps(player.getItemInHand()).toolType == ToolType.AXE) addExemption(player, exemptBreakMany); - else addExemption(player, exemptBreakNormal); - } - - @Override - public final boolean blockBreakLowest(final Player player) { - // System.out.println("block break lowest"); - final boolean isAxe = getToolProps(player.getItemInHand()).toolType == ToolType.AXE; - if (breakCancel > 0){ - breakCancel ++; - return true; - } - final String name = player.getName(); - ActionFrequency freq = lastBreak.get(name); - final long now = System.currentTimeMillis(); - if (freq == null){ - freq = new ActionFrequency(3, 333); - freq.add(now, 1f); - lastBreak.put(name, freq); - lastBreakAddCount ++; - if (lastBreakAddCount > 100){ - lastBreakAddCount = 0; - cleanupLastBreaks(); - } - } - else if (!isAxe){ - freq.add(now, 1f); - if (freq.score(1f) > (float) clicksPerSecond){ - breakCancel ++; - return true; - } - } - - addExemption(player, exemptBreakNormal); - if (useInstaBreakHook){ - HookInstaBreak.addExemptNext(exemptBreakNormal); - TickTask2.addUnexemptions(player, exemptBreakNormal); - } - else if (!isAxe){ - setPlayer(player, cancelChecksBlockBreak); - Bukkit.getScheduler().scheduleSyncDelayedTask(CompatNoCheatPlus.getInstance(), new Runnable() { - @Override - public void run() { - DataManager.removeData(player.getName(), CheckType.BLOCKBREAK_FASTBREAK); - } - }); - } - return false; - } - - protected void cleanupLastBreaks() { - final long ts = System.currentTimeMillis(); - if (ts - lastBreakCleanup < 30000 && ts > lastBreakCleanup) return; - lastBreakCleanup = ts; - final List rem = new LinkedList(); - if (ts >= lastBreakCleanup){ - for (final Entry entry : lastBreak.entrySet()){ - if (entry.getValue().score(1f) == 0f) rem.add(entry.getKey()); - } - } - else{ - rem.addAll(lastBreak.keySet()); - } - for (final String key :rem){ - lastBreak.remove(key); - } - } - - @Override - public void damageMonitor(Player player) { - // System.out.println("damage monitor"); - removeExemption(player, exemptFightEffect); - } - - @Override - public void blockDamageMonitor(Player player) { - // System.out.println("block damage monitor"); - if (getToolProps(player.getItemInHand()).toolType == ToolType.AXE) addExemption(player, exemptBreakMany); - else removeExemption(player, exemptBreakNormal); - } - - @Override - public void blockBreakMontitor(Player player) { - if (breakCancel > 0){ - breakCancel --; - return; - } - // System.out.println("block break monitor"); - removeExemption(player, exemptBreakNormal); - } - - - -} +package me.asofold.bpl.cncp.hooks.mcmmo; + +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import fr.neatmonster.nocheatplus.checks.CheckType; +import fr.neatmonster.nocheatplus.checks.access.IViolationInfo; +import fr.neatmonster.nocheatplus.compat.Bridge1_9; +import fr.neatmonster.nocheatplus.compat.Folia; +import fr.neatmonster.nocheatplus.hooks.NCPHook; +import fr.neatmonster.nocheatplus.players.DataManager; +import fr.neatmonster.nocheatplus.utilities.map.BlockProperties; +import fr.neatmonster.nocheatplus.utilities.map.BlockProperties.ToolProps; +import fr.neatmonster.nocheatplus.utilities.map.BlockProperties.ToolType; +import me.asofold.bpl.cncp.CompatNoCheatPlus; +import me.asofold.bpl.cncp.hooks.generic.ExemptionManager; +import me.asofold.bpl.cncp.hooks.generic.HookInstaBreak; +import me.asofold.bpl.cncp.hooks.mcmmo.HookmcMMO.HookFacade; +import me.asofold.bpl.cncp.utils.ActionFrequency; +import me.asofold.bpl.cncp.utils.TickTask2; + +@SuppressWarnings("deprecation") +public class HookFacadeImpl implements HookFacade, NCPHook { + + + protected final ExemptionManager exMan = new ExemptionManager(); + + /** Normal click per block skills. */ + protected final CheckType[] exemptBreakNormal = new CheckType[]{ + CheckType.BLOCKBREAK_FASTBREAK, CheckType.BLOCKBREAK_FREQUENCY, + CheckType.BLOCKBREAK_NOSWING, + CheckType.BLOCKBREAK_WRONGBLOCK, // Not optimal but ok. + }; + + + protected final CheckType[] exemptBreakMany = new CheckType[]{ + CheckType.BLOCKBREAK, CheckType.COMBINED_IMPROBABLE, + }; + + /** Fighting damage of effects such as bleeding or area (potentially). */ + protected final CheckType[] exemptFightEffect = new CheckType[]{ + CheckType.FIGHT_SPEED, CheckType.FIGHT_DIRECTION, + CheckType.FIGHT_ANGLE, CheckType.FIGHT_NOSWING, + CheckType.FIGHT_REACH, CheckType.COMBINED_IMPROBABLE, + }; + + // Presets for after failure exemption. + protected final Map cancelChecksBlockBreak = new HashMap(); + // protected final Map cancelChecksBlockDamage = new HashMap(); + // protected final Map cancelChecksDamage = new HashMap(); + + protected boolean useInstaBreakHook; + protected int clicksPerSecond; + protected String cancel = null; + protected long cancelTicks = 0; + + protected final Map cancelChecks = new HashMap(); + + /** + * Last block breaking time + */ + protected final Map lastBreak = new HashMap(50); + + /** Counter for nested events to cancel break counting. */ + protected int breakCancel = 0; + + protected int lastBreakAddCount = 0; + protected long lastBreakCleanup = 0; + + public HookFacadeImpl(boolean useInstaBreakHook, int clicksPerSecond){ + this.useInstaBreakHook = useInstaBreakHook; + this.clicksPerSecond = clicksPerSecond; + cancelChecksBlockBreak.put(CheckType.BLOCKBREAK_NOSWING, 1); + cancelChecksBlockBreak.put(CheckType.BLOCKBREAK_FASTBREAK, 1); + // + // cancelChecksBlockDamage.put(CheckType.BLOCKBREAK_FASTBREAK, 1); + // + // cancelChecksDamage.put(CheckType.FIGHT_ANGLE, 1); + // cancelChecksDamage.put(CheckType.FIGHT_SPEED, 1); + } + + @Override + public String getHookName() { + return "mcMMO(cncp)"; + } + + @Override + public String getHookVersion() { + return "2.3"; + } + + @Override + public final boolean onCheckFailure(final CheckType checkType, final Player player, final IViolationInfo info) { + // System.out.println(player.getName() + " -> " + checkType + "---------------------------"); + // Somewhat generic canceling mechanism (within the same tick). + // Might later fail, if block break event gets scheduled after block damage having set insta break, instead of letting them follow directly. + if (cancel == null){ + return false; + } + + final String name = player.getName(); + if (cancel.equals(name)){ + + if (player.getTicksLived() != cancelTicks){ + cancel = null; + } + else{ + final Integer n = cancelChecks.get(checkType); + if (n == null){ + return false; + } + else if (n > 0){ + if (n == 1) cancelChecks.remove(checkType); + else cancelChecks.put(checkType, n - 1); + } + return true; + } + } + return false; + } + + private final void setPlayer(final Player player, Map cancelChecks){ + cancel = player.getName(); + cancelTicks = player.getTicksLived(); + this.cancelChecks.clear(); + this.cancelChecks.putAll(cancelChecks); + } + + public ToolProps getToolProps(final ItemStack stack){ + if (stack == null) return BlockProperties.noTool; + else return BlockProperties.getToolProps(stack); + } + + public void addExemption(final Player player, final CheckType[] types){ + for (final CheckType type : types){ + exMan.addExemption(player, type); + TickTask2.addUnexemptions(player, types); + } + } + + public void removeExemption(final Player player, final CheckType[] types){ + for (final CheckType type : types){ + exMan.removeExemption(player, type); + } + } + + @Override + public final void damageLowest(final Player player) { + // System.out.println("damage lowest"); + // setPlayer(player, cancelChecksDamage); + addExemption(player, exemptFightEffect); + } + + @Override + public final void blockDamageLowest(final Player player) { + // System.out.println("block damage lowest"); + // setPlayer(player, cancelChecksBlockDamage); + if (getToolProps(Bridge1_9.getItemInMainHand(player)).toolType == ToolType.AXE) addExemption(player, exemptBreakMany); + else addExemption(player, exemptBreakNormal); + } + + @Override + public final boolean blockBreakLowest(final Player player) { + // System.out.println("block break lowest"); + final boolean isAxe = getToolProps(Bridge1_9.getItemInMainHand(player)).toolType == ToolType.AXE; + if (breakCancel > 0){ + breakCancel ++; + return true; + } + final String name = player.getName(); + ActionFrequency freq = lastBreak.get(name); + final long now = System.currentTimeMillis(); + if (freq == null){ + freq = new ActionFrequency(3, 333); + freq.add(now, 1f); + lastBreak.put(name, freq); + lastBreakAddCount ++; + if (lastBreakAddCount > 100){ + lastBreakAddCount = 0; + cleanupLastBreaks(); + } + } + else if (!isAxe){ + freq.add(now, 1f); + if (freq.score(1f) > (float) clicksPerSecond){ + breakCancel ++; + return true; + } + } + + addExemption(player, exemptBreakNormal); + if (useInstaBreakHook){ + HookInstaBreak.addExemptNext(exemptBreakNormal); + TickTask2.addUnexemptions(player, exemptBreakNormal); + } + else if (!isAxe){ + setPlayer(player, cancelChecksBlockBreak); + Folia.runSyncTask(CompatNoCheatPlus.getInstance(), (arg) -> DataManager.removeData(player.getName(), CheckType.BLOCKBREAK_FASTBREAK)); + } + return false; + } + + protected void cleanupLastBreaks() { + final long ts = System.currentTimeMillis(); + if (ts - lastBreakCleanup < 30000 && ts > lastBreakCleanup) return; + lastBreakCleanup = ts; + final List rem = new LinkedList(); + if (ts >= lastBreakCleanup){ + for (final Entry entry : lastBreak.entrySet()){ + if (entry.getValue().score(1f) == 0f) rem.add(entry.getKey()); + } + } + else{ + rem.addAll(lastBreak.keySet()); + } + for (final String key :rem){ + lastBreak.remove(key); + } + } + + @Override + public void damageMonitor(Player player) { + // System.out.println("damage monitor"); + removeExemption(player, exemptFightEffect); + } + + @Override + public void blockDamageMonitor(Player player) { + // System.out.println("block damage monitor"); + if (getToolProps(player.getItemInHand()).toolType == ToolType.AXE) addExemption(player, exemptBreakMany); + else removeExemption(player, exemptBreakNormal); + } + + @Override + public void blockBreakMontitor(Player player) { + if (breakCancel > 0){ + breakCancel --; + return; + } + // System.out.println("block break monitor"); + removeExemption(player, exemptBreakNormal); + } + + + +} diff --git a/src/me/asofold/bpl/cncp/hooks/mcmmo/HookmcMMO.java b/src/me/asofold/bpl/cncp/hooks/mcmmo/HookmcMMO.java new file mode 100644 index 0000000..ffd7f07 --- /dev/null +++ b/src/me/asofold/bpl/cncp/hooks/mcmmo/HookmcMMO.java @@ -0,0 +1,178 @@ +package me.asofold.bpl.cncp.hooks.mcmmo; + +import me.asofold.bpl.cncp.config.compatlayer.CompatConfig; +import me.asofold.bpl.cncp.config.compatlayer.CompatConfigFactory; +import me.asofold.bpl.cncp.config.compatlayer.ConfigUtil; +import me.asofold.bpl.cncp.hooks.AbstractHook; +import me.asofold.bpl.cncp.hooks.generic.ConfigurableHook; +import me.asofold.bpl.cncp.utils.PluginGetter; + +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; + +import com.gmail.nossr50.mcMMO; +import com.gmail.nossr50.events.fake.FakeBlockBreakEvent; +import com.gmail.nossr50.events.fake.FakeBlockDamageEvent; +import com.gmail.nossr50.events.fake.FakeEntityDamageByEntityEvent; + +import fr.neatmonster.nocheatplus.checks.CheckType; +import fr.neatmonster.nocheatplus.hooks.NCPHook; + +public final class HookmcMMO extends AbstractHook implements Listener, ConfigurableHook { + + /** + * To let the listener access this. + * @author mc_dev + * + */ + public static interface HookFacade{ + public void damageLowest(Player player); + public void damageMonitor(Player player); + public void blockDamageLowest(Player player); + public void blockDamageMonitor(Player player); + /** + * If to cancel the event. + * @param player + * @return + */ + public boolean blockBreakLowest(Player player); + public void blockBreakMontitor(Player player); + } + + protected HookFacade ncpHook = null; + + protected boolean enabled = true; + + protected String configPrefix = "mcmmo."; + + protected boolean useInstaBreakHook = true; + + + public HookmcMMO(){ + assertPluginPresent("mcMMO"); + } + + + protected final PluginGetter fetch = new PluginGetter("mcMMO"); + + protected int blocksPerSecond = 30; + + + + @Override + public String getHookName() { + return "mcMMO(default)"; + } + + @Override + public String getHookVersion() { + return "2.1"; + } + + @Override + public CheckType[] getCheckTypes() { + return new CheckType[]{ + CheckType.BLOCKBREAK_FASTBREAK, CheckType.BLOCKBREAK_NOSWING, // old ones + +// CheckType.BLOCKBREAK_DIRECTION, CheckType.BLOCKBREAK_FREQUENCY, +// CheckType.BLOCKBREAK_WRONGBLOCK, CheckType.BLOCKBREAK_REACH, +// +// CheckType.FIGHT_ANGLE, CheckType.FIGHT_SPEED, // old ones +// +// CheckType.FIGHT_DIRECTION, CheckType.FIGHT_NOSWING, +// CheckType.FIGHT_REACH, + }; + } + + @Override + public Listener[] getListeners() { + fetch.fetchPlugin(); + return new Listener[]{this, fetch}; + } + + @Override + public NCPHook getNCPHook() { + if (ncpHook == null){ + ncpHook = new HookFacadeImpl(useInstaBreakHook, blocksPerSecond); + } + return (NCPHook) ncpHook; + } + + /////////////////////////// + // Damage (fight) + ////////////////////////// + + @EventHandler(priority=EventPriority.LOWEST) + final void onDamageLowest(final FakeEntityDamageByEntityEvent event){ + final Entity entity = event.getDamager(); + if (entity instanceof Player) + ncpHook.damageLowest((Player) entity); + } + + @EventHandler(priority=EventPriority.MONITOR) + final void onDamageMonitor(final FakeEntityDamageByEntityEvent event){ + final Entity entity = event.getDamager(); + if (entity instanceof Player) + ncpHook.damageMonitor((Player) entity); + } + + /////////////////////////// + // Block damage + ////////////////////////// + + @EventHandler(priority=EventPriority.LOWEST) + final void onBlockDamageLowest(final FakeBlockDamageEvent event){ + ncpHook.blockDamageLowest(event.getPlayer()); + } + + @EventHandler(priority=EventPriority.LOWEST) + final void onBlockDamageMonitor(final FakeBlockDamageEvent event){ + ncpHook.blockDamageMonitor(event.getPlayer()); + } + + /////////////////////////// + // Block break + ////////////////////////// + + @EventHandler(priority=EventPriority.LOWEST) + final void onBlockBreakLowest(final FakeBlockBreakEvent event){ + if (ncpHook.blockBreakLowest(event.getPlayer())){ + event.setCancelled(true); +// System.out.println("Cancelled for frequency."); + } + } + + @EventHandler(priority=EventPriority.MONITOR) + final void onBlockBreakLMonitor(final FakeBlockBreakEvent event){ + ncpHook.blockBreakMontitor(event.getPlayer()); + } + + ///////////////////////////////// + // Config + ///////////////////////////////// + + @Override + public void applyConfig(CompatConfig cfg, String prefix) { + enabled = cfg.getBoolean(prefix + configPrefix + "enabled", true); + useInstaBreakHook = cfg.getBoolean(prefix + configPrefix + "use-insta-break-hook", true); + blocksPerSecond = cfg.getInt(prefix + configPrefix + "clickspersecond", 20); + } + + @Override + public boolean updateConfig(CompatConfig cfg, String prefix) { + CompatConfig defaults = CompatConfigFactory.getConfig(null); + defaults.set(prefix + configPrefix + "enabled", true); + defaults.set(prefix + configPrefix + "use-insta-break-hook", true); + defaults.set(prefix + configPrefix + "clickspersecond", 20); + return ConfigUtil.forceDefaults(defaults, cfg); + } + + @Override + public boolean isEnabled() { + return enabled; + } + +} diff --git a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/utils/ActionFrequency.java b/src/me/asofold/bpl/cncp/utils/ActionFrequency.java similarity index 96% rename from CompatNoCheatPlus/src/me/asofold/bpl/cncp/utils/ActionFrequency.java rename to src/me/asofold/bpl/cncp/utils/ActionFrequency.java index 8f45212..e81fe24 100644 --- a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/utils/ActionFrequency.java +++ b/src/me/asofold/bpl/cncp/utils/ActionFrequency.java @@ -1,290 +1,290 @@ -package me.asofold.bpl.cncp.utils; - -/** - * Keep track of frequency of some action, - * put weights into buckets, which represent intervals of time.
- * (Taken from NoCheatPlus.) - * @author mc_dev - * - */ -public class ActionFrequency { - - /** Reference time for the transition from the first to the second bucket. */ - private long time = 0; - /** - * Time of last update (add). Should be the "time of the last event" for the - * usual case. - */ - private long lastUpdate = 0; - private final boolean noAutoReset; - - /** - * Buckets to fill weights in, each represents an interval of durBucket duration, - * index 0 is the latest, highest index is the oldest. - * Weights will get filled into the next buckets with time passed. - */ - private final float[] buckets; - - /** Duration in milliseconds that one bucket covers. */ - private final long durBucket; - - /** - * This constructor will set noAutoReset to false, optimized for short term - * accounting. - * - * @param nBuckets - * @param durBucket - */ - public ActionFrequency(final int nBuckets, final long durBucket) { - this(nBuckets, durBucket, false); - } - - /** - * - * @param nBuckets - * @param durBucket - * @param noAutoReset - * Set to true, to prevent auto-resetting with - * "time ran backwards". Setting this to true is recommended if - * larger time frames are monitored, to prevent data loss. - */ - public ActionFrequency(final int nBuckets, final long durBucket, final boolean noAutoReset) { - this.buckets = new float[nBuckets]; - this.durBucket = durBucket; - this.noAutoReset = noAutoReset; - } - - /** - * Update and add (updates reference and update time). - * @param now - * @param amount - */ - public final void add(final long now, final float amount) { - update(now); - buckets[0] += amount; - } - - /** - * Unchecked addition of amount to the first bucket. - * @param amount - */ - public final void add(final float amount) { - buckets[0] += amount; - } - - /** - * Update without adding, also updates reference and update time. Detects - * time running backwards. - * - * @param now - */ - public final void update(final long now) { - final long diff = now - time; - if (now < lastUpdate) { - // Time ran backwards. - if (noAutoReset) { - // Only update time and lastUpdate. - time = lastUpdate = now; - } else { - // Clear all. - clear(now); - return; - } - } - else if (diff >= durBucket * buckets.length) { - // Clear (beyond range). - clear(now); - return; - } - else if (diff < durBucket) { - // No changes (first bucket). - } - else { - final int shift = (int) ((float) diff / (float) durBucket); - // Update buckets. - for (int i = 0; i < buckets.length - shift; i++) { - buckets[buckets.length - (i + 1)] = buckets[buckets.length - (i + 1 + shift)]; - } - for (int i = 0; i < shift; i++) { - buckets[i] = 0; - } - // Set time according to bucket duration (!). - time += durBucket * shift; - } - // Ensure lastUpdate is set. - lastUpdate = now; - } - - /** - * Clear all counts, reset reference and update time. - * @param now - */ - public final void clear(final long now) { - for (int i = 0; i < buckets.length; i++) { - buckets[i] = 0f; - } - time = lastUpdate = now; - } - - /** - * @deprecated Use instead: score(float). - * @param factor - * @return - */ - public final float getScore(final float factor) { - return score(factor); - } - - /** - * @deprecated Use instead: score(float). - * @param factor - * @return - */ - public final float getScore(final int bucket) { - return bucketScore(bucket); - } - - /** - * Get a weighted sum score, weight for bucket i: w(i) = factor^i. - * @param factor - * @return - */ - public final float score(final float factor) { - return sliceScore(0, buckets.length, factor); - } - - /** - * Get score of a certain bucket. At own risk. - * @param bucket - * @return - */ - public final float bucketScore(final int bucket) { - return buckets[bucket]; - } - - /** - * Get score of first end buckets, with factor. - * @param end Number of buckets including start. The end is not included. - * @param factor - * @return - */ - public final float leadingScore(final int end, float factor) { - return sliceScore(0, end, factor); - } - - /** - * Get score from start on, with factor. - * @param start This is included. - * @param factor - * @return - */ - public final float trailingScore(final int start, float factor) { - return sliceScore(start, buckets.length, factor); - } - - /** - * Get score from start on, until before end, with factor. - * @param start This is included. - * @param end This is not included. - * @param factor - * @return - */ - public final float sliceScore(final int start, final int end, float factor) { - float score = buckets[start]; - float cf = factor; - for (int i = start + 1; i < end; i++) { - score += buckets[i] * cf; - cf *= factor; - } - return score; - } - - /** - * Set the value for a buckt. - * @param n - * @param value - */ - public final void setBucket(final int n, final float value) { - buckets[n] = value; - } - - /** - * Set the reference time and last update time. - * @param time - */ - public final void setTime(final long time) { - this.time = time; - this.lastUpdate = time; - } - - /** - * Get the reference time for the transition from the first to the second bucket. - * @return - */ - public final long lastAccess() { // TODO: Should rename this. - return time; - } - - /** - * Get the last time when update was called (adding). - * @return - */ - public final long lastUpdate() { - return lastUpdate; - } - - /** - * Get the number of buckets. - * @return - */ - public final int numberOfBuckets() { - return buckets.length; - } - - /** - * Get the duration of a bucket in milliseconds. - * @return - */ - public final long bucketDuration() { - return durBucket; - } - - /** - * Serialize to a String line. - * @return - */ - public final String toLine() { - // TODO: Backwards-compatible lastUpdate ? - final StringBuilder buffer = new StringBuilder(50); - buffer.append(buckets.length + ","+durBucket+","+time); - for (int i = 0; i < buckets.length; i++) { - buffer.append("," + buckets[i]); - } - return buffer.toString(); - } - - /** - * Deserialize from a string. - * @param line - * @return - */ - public static ActionFrequency fromLine(final String line) { - // TODO: Backwards-compatible lastUpdate ? - String[] split = line.split(","); - if (split.length < 3) throw new RuntimeException("Bad argument length."); // TODO - final int n = Integer.parseInt(split[0]); - final long durBucket = Long.parseLong(split[1]); - final long time = Long.parseLong(split[2]); - final float[] buckets = new float[split.length -3]; - if (split.length - 3 != buckets.length) throw new RuntimeException("Bad argument length."); // TODO - for (int i = 3; i < split.length; i ++) { - buckets[i - 3] = Float.parseFloat(split[i]); - } - ActionFrequency freq = new ActionFrequency(n, durBucket); - freq.setTime(time); - for (int i = 0; i < buckets.length; i ++) { - freq.setBucket(i, buckets[i]); - } - return freq; - } -} +package me.asofold.bpl.cncp.utils; + +/** + * Keep track of frequency of some action, + * put weights into buckets, which represent intervals of time.
+ * (Taken from NoCheatPlus.) + * @author mc_dev + * + */ +public class ActionFrequency { + + /** Reference time for the transition from the first to the second bucket. */ + private long time = 0; + /** + * Time of last update (add). Should be the "time of the last event" for the + * usual case. + */ + private long lastUpdate = 0; + private final boolean noAutoReset; + + /** + * Buckets to fill weights in, each represents an interval of durBucket duration, + * index 0 is the latest, highest index is the oldest. + * Weights will get filled into the next buckets with time passed. + */ + private final float[] buckets; + + /** Duration in milliseconds that one bucket covers. */ + private final long durBucket; + + /** + * This constructor will set noAutoReset to false, optimized for short term + * accounting. + * + * @param nBuckets + * @param durBucket + */ + public ActionFrequency(final int nBuckets, final long durBucket) { + this(nBuckets, durBucket, false); + } + + /** + * + * @param nBuckets + * @param durBucket + * @param noAutoReset + * Set to true, to prevent auto-resetting with + * "time ran backwards". Setting this to true is recommended if + * larger time frames are monitored, to prevent data loss. + */ + public ActionFrequency(final int nBuckets, final long durBucket, final boolean noAutoReset) { + this.buckets = new float[nBuckets]; + this.durBucket = durBucket; + this.noAutoReset = noAutoReset; + } + + /** + * Update and add (updates reference and update time). + * @param now + * @param amount + */ + public final void add(final long now, final float amount) { + update(now); + buckets[0] += amount; + } + + /** + * Unchecked addition of amount to the first bucket. + * @param amount + */ + public final void add(final float amount) { + buckets[0] += amount; + } + + /** + * Update without adding, also updates reference and update time. Detects + * time running backwards. + * + * @param now + */ + public final void update(final long now) { + final long diff = now - time; + if (now < lastUpdate) { + // Time ran backwards. + if (noAutoReset) { + // Only update time and lastUpdate. + time = lastUpdate = now; + } else { + // Clear all. + clear(now); + return; + } + } + else if (diff >= durBucket * buckets.length) { + // Clear (beyond range). + clear(now); + return; + } + else if (diff < durBucket) { + // No changes (first bucket). + } + else { + final int shift = (int) ((float) diff / (float) durBucket); + // Update buckets. + for (int i = 0; i < buckets.length - shift; i++) { + buckets[buckets.length - (i + 1)] = buckets[buckets.length - (i + 1 + shift)]; + } + for (int i = 0; i < shift; i++) { + buckets[i] = 0; + } + // Set time according to bucket duration (!). + time += durBucket * shift; + } + // Ensure lastUpdate is set. + lastUpdate = now; + } + + /** + * Clear all counts, reset reference and update time. + * @param now + */ + public final void clear(final long now) { + for (int i = 0; i < buckets.length; i++) { + buckets[i] = 0f; + } + time = lastUpdate = now; + } + + /** + * @deprecated Use instead: score(float). + * @param factor + * @return + */ + public final float getScore(final float factor) { + return score(factor); + } + + /** + * @deprecated Use instead: score(float). + * @param factor + * @return + */ + public final float getScore(final int bucket) { + return bucketScore(bucket); + } + + /** + * Get a weighted sum score, weight for bucket i: w(i) = factor^i. + * @param factor + * @return + */ + public final float score(final float factor) { + return sliceScore(0, buckets.length, factor); + } + + /** + * Get score of a certain bucket. At own risk. + * @param bucket + * @return + */ + public final float bucketScore(final int bucket) { + return buckets[bucket]; + } + + /** + * Get score of first end buckets, with factor. + * @param end Number of buckets including start. The end is not included. + * @param factor + * @return + */ + public final float leadingScore(final int end, float factor) { + return sliceScore(0, end, factor); + } + + /** + * Get score from start on, with factor. + * @param start This is included. + * @param factor + * @return + */ + public final float trailingScore(final int start, float factor) { + return sliceScore(start, buckets.length, factor); + } + + /** + * Get score from start on, until before end, with factor. + * @param start This is included. + * @param end This is not included. + * @param factor + * @return + */ + public final float sliceScore(final int start, final int end, float factor) { + float score = buckets[start]; + float cf = factor; + for (int i = start + 1; i < end; i++) { + score += buckets[i] * cf; + cf *= factor; + } + return score; + } + + /** + * Set the value for a buckt. + * @param n + * @param value + */ + public final void setBucket(final int n, final float value) { + buckets[n] = value; + } + + /** + * Set the reference time and last update time. + * @param time + */ + public final void setTime(final long time) { + this.time = time; + this.lastUpdate = time; + } + + /** + * Get the reference time for the transition from the first to the second bucket. + * @return + */ + public final long lastAccess() { // TODO: Should rename this. + return time; + } + + /** + * Get the last time when update was called (adding). + * @return + */ + public final long lastUpdate() { + return lastUpdate; + } + + /** + * Get the number of buckets. + * @return + */ + public final int numberOfBuckets() { + return buckets.length; + } + + /** + * Get the duration of a bucket in milliseconds. + * @return + */ + public final long bucketDuration() { + return durBucket; + } + + /** + * Serialize to a String line. + * @return + */ + public final String toLine() { + // TODO: Backwards-compatible lastUpdate ? + final StringBuilder buffer = new StringBuilder(50); + buffer.append(buckets.length + ","+durBucket+","+time); + for (int i = 0; i < buckets.length; i++) { + buffer.append("," + buckets[i]); + } + return buffer.toString(); + } + + /** + * Deserialize from a string. + * @param line + * @return + */ + public static ActionFrequency fromLine(final String line) { + // TODO: Backwards-compatible lastUpdate ? + String[] split = line.split(","); + if (split.length < 3) throw new RuntimeException("Bad argument length."); // TODO + final int n = Integer.parseInt(split[0]); + final long durBucket = Long.parseLong(split[1]); + final long time = Long.parseLong(split[2]); + final float[] buckets = new float[split.length -3]; + if (split.length - 3 != buckets.length) throw new RuntimeException("Bad argument length."); // TODO + for (int i = 3; i < split.length; i ++) { + buckets[i - 3] = Float.parseFloat(split[i]); + } + ActionFrequency freq = new ActionFrequency(n, durBucket); + freq.setTime(time); + for (int i = 0; i < buckets.length; i ++) { + freq.setBucket(i, buckets[i]); + } + return freq; + } +} diff --git a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/utils/PluginGetter.java b/src/me/asofold/bpl/cncp/utils/PluginGetter.java similarity index 96% rename from CompatNoCheatPlus/src/me/asofold/bpl/cncp/utils/PluginGetter.java rename to src/me/asofold/bpl/cncp/utils/PluginGetter.java index 2942dbc..bac6ec9 100644 --- a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/utils/PluginGetter.java +++ b/src/me/asofold/bpl/cncp/utils/PluginGetter.java @@ -1,50 +1,50 @@ -package me.asofold.bpl.cncp.utils; - -import org.bukkit.Bukkit; -import org.bukkit.event.Listener; -import org.bukkit.event.server.PluginEnableEvent; -import org.bukkit.plugin.Plugin; - -/** - * Simple plugin fetching. - * @author mc_dev - * - * @param - */ -public final class PluginGetter implements Listener{ - private T plugin = null; - private final String pluginName; - public PluginGetter(final String pluginName){ - this.pluginName = pluginName; - fetchPlugin(); - } - - /** - * Fetch from Bukkit and set , might set to null, though. - */ - @SuppressWarnings("unchecked") - public final void fetchPlugin() { - final Plugin ref = Bukkit.getPluginManager().getPlugin(pluginName); - plugin = (T) ref; - } - - @SuppressWarnings("unchecked") - final void onPluginEnable(final PluginEnableEvent event){ - final Plugin ref = event.getPlugin(); - if (plugin.getName().equals(pluginName)) plugin = (T) ref; - } - - /** - * For convenience with chaining: getX = new PluginGetter("X").registerEvents(this); - * @param other - * @return - */ - public final PluginGetter registerEvents(final Plugin other){ - Bukkit.getPluginManager().registerEvents(this, plugin); - return this; - } - - public final T getPlugin(){ - return plugin; - } -} +package me.asofold.bpl.cncp.utils; + +import org.bukkit.Bukkit; +import org.bukkit.event.Listener; +import org.bukkit.event.server.PluginEnableEvent; +import org.bukkit.plugin.Plugin; + +/** + * Simple plugin fetching. + * @author mc_dev + * + * @param + */ +public final class PluginGetter implements Listener{ + private T plugin = null; + private final String pluginName; + public PluginGetter(final String pluginName){ + this.pluginName = pluginName; + fetchPlugin(); + } + + /** + * Fetch from Bukkit and set , might set to null, though. + */ + @SuppressWarnings("unchecked") + public final void fetchPlugin() { + final Plugin ref = Bukkit.getPluginManager().getPlugin(pluginName); + plugin = (T) ref; + } + + @SuppressWarnings("unchecked") + final void onPluginEnable(final PluginEnableEvent event){ + final Plugin ref = event.getPlugin(); + if (plugin.getName().equals(pluginName)) plugin = (T) ref; + } + + /** + * For convenience with chaining: getX = new PluginGetter("X").registerEvents(this); + * @param other + * @return + */ + public final PluginGetter registerEvents(final Plugin other){ + Bukkit.getPluginManager().registerEvents(this, plugin); + return this; + } + + public final T getPlugin(){ + return plugin; + } +} diff --git a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/utils/TickTask2.java b/src/me/asofold/bpl/cncp/utils/TickTask2.java similarity index 96% rename from CompatNoCheatPlus/src/me/asofold/bpl/cncp/utils/TickTask2.java rename to src/me/asofold/bpl/cncp/utils/TickTask2.java index bcf3656..f93d06f 100644 --- a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/utils/TickTask2.java +++ b/src/me/asofold/bpl/cncp/utils/TickTask2.java @@ -1,48 +1,48 @@ -package me.asofold.bpl.cncp.utils; - -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - -import org.bukkit.entity.Player; - -import fr.neatmonster.nocheatplus.checks.CheckType; -import fr.neatmonster.nocheatplus.hooks.NCPExemptionManager; - -public class TickTask2 implements Runnable { - - - protected static Map> exemptions = new LinkedHashMap>(40); - - /** - * Quick fix, meant for sync access (!). - * @param player - * @param checkTypes - */ - public static void addUnexemptions(final Player player, final CheckType[] checkTypes){ - for (int i = 0; i < checkTypes.length; i ++){ - final CheckType type = checkTypes[i]; - Set set = exemptions.get(type); - if (set == null){ - set = new HashSet(); - exemptions.put(type, set); - } - set.add(player); - } - } - - @Override - public void run() { - for (final Entry> entry : exemptions.entrySet()){ - final Set set = entry.getValue(); - final CheckType type = entry.getKey(); - for (final Player player : set){ - NCPExemptionManager.unexempt(player, type); - } - } - exemptions.clear(); - } - -} +package me.asofold.bpl.cncp.utils; + +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +import org.bukkit.entity.Player; + +import fr.neatmonster.nocheatplus.checks.CheckType; +import fr.neatmonster.nocheatplus.hooks.NCPExemptionManager; + +public class TickTask2 implements Runnable { + + + protected static Map> exemptions = new LinkedHashMap>(40); + + /** + * Quick fix, meant for sync access (!). + * @param player + * @param checkTypes + */ + public static void addUnexemptions(final Player player, final CheckType[] checkTypes){ + for (int i = 0; i < checkTypes.length; i ++){ + final CheckType type = checkTypes[i]; + Set set = exemptions.get(type); + if (set == null){ + set = new HashSet(); + exemptions.put(type, set); + } + set.add(player); + } + } + + @Override + public void run() { + for (final Entry> entry : exemptions.entrySet()){ + final Set set = entry.getValue(); + final CheckType type = entry.getKey(); + for (final Player player : set){ + NCPExemptionManager.unexempt(player, type); + } + } + exemptions.clear(); + } + +} diff --git a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/utils/Utils.java b/src/me/asofold/bpl/cncp/utils/Utils.java similarity index 95% rename from CompatNoCheatPlus/src/me/asofold/bpl/cncp/utils/Utils.java rename to src/me/asofold/bpl/cncp/utils/Utils.java index f42bb57..140663d 100644 --- a/CompatNoCheatPlus/src/me/asofold/bpl/cncp/utils/Utils.java +++ b/src/me/asofold/bpl/cncp/utils/Utils.java @@ -1,16 +1,16 @@ -package me.asofold.bpl.cncp.utils; - -import java.io.PrintWriter; -import java.io.StringWriter; -import java.io.Writer; - -public class Utils { - - public static final String toString(final Throwable t) { - final Writer buf = new StringWriter(500); - final PrintWriter writer = new PrintWriter(buf); - t.printStackTrace(writer); - return buf.toString(); - } - -} +package me.asofold.bpl.cncp.utils; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.io.Writer; + +public class Utils { + + public static final String toString(final Throwable t) { + final Writer buf = new StringWriter(500); + final PrintWriter writer = new PrintWriter(buf); + t.printStackTrace(writer); + return buf.toString(); + } + +}