From 4306941b893c14444983b9f33890c265cbc682bf Mon Sep 17 00:00:00 2001 From: xGinko Date: Mon, 30 Dec 2024 23:34:17 +0100 Subject: [PATCH] speed up module loading replace deprecated XSeries calls reduce codesize where possible --- .../me/xginko/aef/AnarchyExploitFixes.java | 4 + .../java/me/xginko/aef/modules/AEFModule.java | 45 +++++-- .../bedrock/FillNetherCeilingOnChunkload.java | 7 +- .../bedrock/FillNetherFloorOnChunkload.java | 7 +- .../FillOverworldFloorOnChunkload.java | 7 +- .../PeriodicallyFillNetherCeiling.java | 21 ++-- .../bedrock/PeriodicallyFillNetherFloor.java | 17 ++- .../PeriodicallyFillOverworldFloor.java | 19 ++- .../PreventGoingBelowBedrockFloor.java | 9 +- .../modules/chat/PreventPluginScanning.java | 7 +- .../commandwhitelist/CommandWhitelist.java | 32 ++--- .../aef/modules/chunklimits/BlockLimit.java | 19 ++- .../chunklimits/CustomEntityLimit.java | 11 +- .../modules/chunklimits/DroppedItemLimit.java | 8 +- .../modules/chunklimits/ExpBottleLimit.java | 8 +- .../chunklimits/FallingBlockLimit.java | 21 ++-- .../modules/chunklimits/MinecartLimit.java | 18 ++- .../chunklimits/NonLivingEntityLimit.java | 19 ++- .../modules/chunklimits/TileEntityLimit.java | 19 ++- .../aef/modules/chunklimits/VehicleLimit.java | 20 ++- .../modules/chunklimits/VillagerLimit.java | 21 ++-- .../me/xginko/aef/modules/combat/BowBomb.java | 7 +- .../me/xginko/aef/modules/combat/Burrow.java | 19 ++- .../xginko/aef/modules/combat/MultiTask.java | 7 +- .../modules/combat/PistonCrystalDelay.java | 32 ++--- .../xginko/aef/modules/combat/PistonPush.java | 14 +-- .../aef/modules/combat/PortalGodMode.java | 24 ++-- .../aef/modules/combat/SilentSwapDelay.java | 2 +- .../modules/combat/auras/AnchorAuraDelay.java | 6 +- .../modules/combat/auras/AuraDelayModule.java | 26 ++-- .../combat/auras/CrystalAuraDelay.java | 2 +- .../modules/dupepreventions/AllayDupe.java | 8 +- .../dupepreventions/BookTitleDupe.java | 62 ++++++++-- .../ChestedEntitiesInPortals.java | 7 +- .../dupepreventions/ChestsOnEntities.java | 7 +- .../CloseEntityInventoriesOnLogout.java | 7 +- .../CloseEntityInventoryOnChunkUnload.java | 7 +- .../aef/modules/elytra/ElytraAtSpawn.java | 2 +- .../aef/modules/elytra/ElytraGlobal.java | 10 +- .../aef/modules/elytra/ElytraHelper.java | 30 +++-- .../aef/modules/elytra/ElytraOnCeiling.java | 3 +- .../aef/modules/elytra/ElytraPacketFly.java | 25 ++-- .../illegals/items/BannedItemNames.java | 18 +-- .../illegals/items/BannedMaterials.java | 12 +- .../illegals/items/IllegalItemModule.java | 8 +- .../illegals/items/IllegalPotions.java | 14 +-- .../illegals/items/InvalidStackSize.java | 17 +-- .../illegals/items/ItemAttributes.java | 13 +- .../modules/illegals/items/PlayerHeads.java | 10 +- .../aef/modules/illegals/items/SpawnEggs.java | 12 +- .../modules/illegals/items/Unbreakables.java | 23 ++-- .../items/enchantments/HigherEnchants.java | 27 ++-- .../enchantments/InapplicableEnchants.java | 13 +- .../enchantments/IncompatibleEnchants.java | 96 ++++++-------- .../illegals/items/nbt/CommandItems.java | 10 +- .../illegals/items/nbt/CustomNBTFilter.java | 12 +- .../items/nbt/NBTFilledStorageItem.java | 20 ++- .../PeriodicallyRemoveIllegalBlocks.java | 46 ++++--- .../RemoveIllegalBlocksOnChunkload.java | 36 +++--- .../placedblocks/RemoveUnnaturalSpawners.java | 21 ++-- .../lagpreventions/DisableCustomEntities.java | 71 +++++++++++ .../lagpreventions/FloodingMachines.java | 12 +- .../lagpreventions/KeepStashLoaded.java | 34 ++--- .../aef/modules/lagpreventions/LeverSpam.java | 31 +++-- .../lagpreventions/NoShulkerDrops.java | 8 +- .../lagpreventions/StashExplosions.java | 34 ++--- .../agelimits/CustomAgeLimits.java | 20 ++- .../agelimits/ProjectileAgeLimit.java | 28 ++--- .../regionalactivity/BlockFormOrGrow.java | 9 +- .../regionalactivity/BlockPhysics.java | 9 +- .../regionalactivity/EntitySpawns.java | 9 +- .../regionalactivity/EntityTargeting.java | 9 +- .../regionalactivity/Explosions.java | 9 +- .../regionalactivity/LiquidSpread.java | 11 +- .../regionalactivity/Noteblocks.java | 9 +- .../regionalactivity/Pathfinding.java | 9 +- .../regionalactivity/Pistons.java | 8 +- .../regionalactivity/Redstone.java | 9 +- .../RegionalActivityModule.java | 38 +++--- .../regionalactivity/SculkActivity.java | 21 ++-- .../regionalactivity/SculkBloom.java | 9 +- .../aef/modules/misc/AutoBedOrSpigot5988.java | 30 ++--- .../aef/modules/misc/FirstJoinMessages.java | 7 +- .../aef/modules/misc/JoinLeaveMessages.java | 9 +- .../aef/modules/misc/MaskKickMessages.java | 7 +- .../aef/modules/misc/PreventMessageKick.java | 7 +- .../xginko/aef/modules/packets/BedTrap.java | 66 +++++----- .../modules/packets/BeehiveCoordinates.java | 8 +- .../aef/modules/packets/BigMessages.java | 8 +- .../aef/modules/packets/InventoryLag.java | 26 ++-- .../aef/modules/packets/MapCursorLag.java | 27 ++-- .../aef/modules/packets/PacketModule.java | 19 +-- .../modules/packets/PurpurBeehiveCrash.java | 8 +- .../aef/modules/packets/SequenceCrash.java | 5 +- .../xginko/aef/modules/packets/SignLag.java | 30 +++-- .../aef/modules/packets/TabCompleteCrash.java | 17 ++- .../aef/modules/packets/WindowClickCrash.java | 9 +- .../xginko/aef/modules/patches/GodMode.java | 8 +- .../aef/modules/patches/ItemDataBan.java | 40 +++--- .../modules/patches/TeleportCoordExploit.java | 10 +- .../aef/modules/patches/WorldChangeCrash.java | 25 ++-- .../patches/commandsign/CommandSign.java | 8 +- .../aef/modules/preventions/NetherRoof.java | 52 ++++---- .../preventions/PreventNonSurvival.java | 8 +- .../preventions/PreventOppedPlayers.java | 9 +- .../PistonExplodePermBlockRemoval.java | 11 +- ...stonPlaceWhileRetractPermBlockRemoval.java | 7 +- .../StructureGrowPermBlockRemoval.java | 8 +- .../portals/EndPortalDestruction.java | 13 +- .../portals/PreventAllEntitiesInPortals.java | 8 +- .../portals/PreventPortalTraps.java | 16 +-- .../portals/PreventProjectilesInPortals.java | 9 +- .../PreventSpecificEntitiesInPortals.java | 23 ++-- .../withers/RateLimitWitherSkulls.java | 46 ++++--- .../withers/RemoveSkullsOnChunkload.java | 9 +- .../withers/WitherSkullDropsAtSpawn.java | 19 ++- .../withers/WitherSummonAtSpawn.java | 15 +-- .../me/xginko/aef/AnarchyExploitFixes.java | 4 + .../java/me/xginko/aef/modules/AEFModule.java | 46 +++++-- .../bedrock/FillNetherCeilingOnChunkload.java | 12 +- .../bedrock/FillNetherFloorOnChunkload.java | 14 +-- .../FillOverworldFloorOnChunkload.java | 14 +-- .../PeriodicallyFillNetherCeiling.java | 15 ++- .../bedrock/PeriodicallyFillNetherFloor.java | 13 +- .../PeriodicallyFillOverworldFloor.java | 15 ++- .../PreventGoingBelowBedrockFloor.java | 25 ++-- .../modules/chat/PreventPluginScanning.java | 12 +- .../commandwhitelist/CommandWhitelist.java | 41 +++--- .../aef/modules/chunklimits/BlockLimit.java | 19 ++- .../chunklimits/CustomEntityLimit.java | 10 +- .../modules/chunklimits/DroppedItemLimit.java | 14 +-- .../modules/chunklimits/ExpBottleLimit.java | 14 +-- .../chunklimits/FallingBlockLimit.java | 28 ++--- .../modules/chunklimits/MinecartLimit.java | 14 +-- .../chunklimits/NonLivingEntityLimit.java | 14 +-- .../modules/chunklimits/TileEntityLimit.java | 17 ++- .../aef/modules/chunklimits/VehicleLimit.java | 14 +-- .../modules/chunklimits/VillagerLimit.java | 15 ++- .../aef/modules/combat/AnchorAuraDelay.java | 101 --------------- .../aef/modules/combat/BedAuraDelay.java | 100 --------------- .../me/xginko/aef/modules/combat/BowBomb.java | 7 +- .../me/xginko/aef/modules/combat/Burrow.java | 19 ++- .../aef/modules/combat/CrystalAuraDelay.java | 100 --------------- .../xginko/aef/modules/combat/MultiTask.java | 7 +- .../modules/combat/PistonCrystalDelay.java | 32 ++--- .../xginko/aef/modules/combat/PistonPush.java | 7 +- .../aef/modules/combat/PortalGodMode.java | 32 ++--- .../aef/modules/combat/SilentSwapDelay.java | 7 +- .../modules/combat/auras/AnchorAuraDelay.java | 52 ++++++++ .../modules/combat/auras/AuraDelayModule.java | 81 ++++++++++++ .../modules/combat/auras/BedAuraDelay.java | 51 ++++++++ .../combat/auras/CrystalAuraDelay.java | 51 ++++++++ .../modules/dupepreventions/AllayDupe.java | 10 +- .../dupepreventions/BookTitleDupe.java | 65 ++++++++-- .../ChestedEntitiesInPortals.java | 12 +- .../dupepreventions/ChestsOnEntities.java | 8 +- .../CloseEntityInventoriesOnLogout.java | 8 +- .../CloseEntityInventoryOnChunkUnload.java | 8 +- .../{patches => dupepreventions}/CowDupe.java | 16 +-- .../dupepreventions/EndPortalDupe.java | 28 ++--- .../aef/modules/elytra/ElytraAtSpawn.java | 4 +- .../aef/modules/elytra/ElytraGlobal.java | 5 +- .../aef/modules/elytra/ElytraHelper.java | 41 ++++-- .../aef/modules/elytra/ElytraOnCeiling.java | 3 +- .../aef/modules/elytra/ElytraPacketFly.java | 20 +-- .../illegals/items/BannedItemNames.java | 18 +-- .../illegals/items/BannedMaterials.java | 12 +- .../illegals/items/IllegalItemModule.java | 8 +- .../illegals/items/IllegalPotions.java | 14 +-- .../illegals/items/InvalidStackSize.java | 4 +- .../modules/illegals/items/PlayerHeads.java | 10 +- .../aef/modules/illegals/items/SpawnEggs.java | 12 +- .../modules/illegals/items/Unbreakables.java | 25 ++-- .../items/datavalues/CustomDataValues.java | 16 +-- .../items/datavalues/IllegalGoldenApples.java | 19 ++- .../items/enchantments/HigherEnchants.java | 28 ++--- .../enchantments/InapplicableEnchants.java | 20 ++- .../enchantments/IncompatibleEnchants.java | 117 +++++++----------- .../illegals/items/nbt/CommandItems.java | 13 +- .../illegals/items/nbt/CustomNBTFilter.java | 15 +-- .../items/nbt/NBTFilledStorageItem.java | 12 +- .../PeriodicallyRemoveIllegalBlocks.java | 43 ++++--- .../RemoveIllegalBlocksOnChunkload.java | 32 +++-- .../placedblocks/RemoveUnnaturalSpawners.java | 17 +-- .../lagpreventions/DisableCustomEntities.java | 71 +++++++++++ .../lagpreventions/FloodingMachines.java | 10 +- .../lagpreventions/KeepStashLoaded.java | 30 +++-- .../aef/modules/lagpreventions/LeverSpam.java | 39 +++--- .../lagpreventions/NoShulkerDrops.java | 8 +- .../lagpreventions/StashExplosions.java | 38 +++--- .../agelimits/CustomAgeLimits.java | 20 ++- .../agelimits/ProjectileAgeLimit.java | 16 +-- .../regionalactivity/BlockFormOrGrow.java | 28 ++--- .../regionalactivity/BlockPhysics.java | 26 ++-- .../regionalactivity/EntitySpawns.java | 8 +- .../regionalactivity/EntityTargeting.java | 8 +- .../regionalactivity/Explosions.java | 20 +-- .../regionalactivity/LiquidSpread.java | 22 ++-- .../regionalactivity/Noteblocks.java | 18 +-- .../regionalactivity/Pathfinding.java | 8 +- .../regionalactivity/Pistons.java | 18 +-- .../regionalactivity/Redstone.java | 20 +-- .../RegionalActivityModule.java | 33 +++-- .../regionalactivity/SculkActivity.java | 20 +-- .../aef/modules/misc/FirstJoinMessages.java | 7 +- .../aef/modules/misc/JoinLeaveMessages.java | 7 +- .../aef/modules/misc/MaskKickMessages.java | 7 +- .../aef/modules/misc/PreventMessageKick.java | 7 +- .../modules/packets/BeehiveCoordinates.java | 8 +- .../aef/modules/packets/BigMessages.java | 8 +- .../modules/packets/CraftingRecipeLag.java | 33 +++-- .../aef/modules/packets/InventoryLag.java | 50 ++++---- .../aef/modules/packets/LecternCrash.java | 7 +- .../aef/modules/packets/MapCursorLag.java | 13 +- .../aef/modules/packets/NoComExploit.java | 9 +- .../aef/modules/packets/PacketModule.java | 19 +-- .../modules/packets/PurpurBeehiveCrash.java | 7 +- .../aef/modules/packets/SequenceCrash.java | 5 +- .../xginko/aef/modules/packets/SignLag.java | 30 +++-- .../aef/modules/packets/TabCompleteCrash.java | 17 ++- .../aef/modules/packets/WindowClickCrash.java | 8 +- .../xginko/aef/modules/patches/GodMode.java | 8 +- .../aef/modules/patches/ItemDataBan.java | 42 ++++--- .../modules/patches/TeleportCoordExploit.java | 14 +-- .../patches/commandsign/CommandSign.java | 12 +- .../patches/crashexploits/DispenserCrash.java | 10 +- .../crashexploits/EndGatewayCrash.java | 8 +- .../crashexploits/MultipleEnderdragons.java | 7 +- .../RedstoneOnTrapdoorCrash.java | 45 +++---- .../crashexploits/WorldChangeCrash.java | 27 ++-- .../aef/modules/preventions/BedTrap.java | 42 +++---- .../aef/modules/preventions/DisableFish.java | 63 ---------- .../aef/modules/preventions/MapSpam.java | 26 ++-- .../aef/modules/preventions/NetherRoof.java | 52 ++++---- .../preventions/PreventNonSurvival.java | 13 +- .../preventions/PreventOppedPlayers.java | 9 +- .../PistonExplodePermBlockRemoval.java | 11 +- ...stonPlaceWhileRetractPermBlockRemoval.java | 7 +- .../StructureGrowPermBlockRemoval.java | 8 +- .../portals/EndPortalDestruction.java | 13 +- .../portals/PreventAllEntitiesInPortals.java | 9 +- .../portals/PreventPortalTraps.java | 12 +- .../portals/PreventProjectilesInPortals.java | 9 +- .../PreventSpecificEntitiesInPortals.java | 26 ++-- .../withers/RateLimitWitherSkulls.java | 47 ++++--- ...ad.java => RemoveSkullsOnChunkUnload.java} | 14 +-- .../withers/WitherSkullDropsAtSpawn.java | 19 ++- .../withers/WitherSummonAtSpawn.java | 15 +-- .../commandsign/SignCommandListener.java | 3 +- .../java/me/xginko/aef/utils/BlockUtil.java | 10 +- .../me/xginko/aef/utils/CachingPermTool.java | 12 +- .../java/me/xginko/aef/utils/ItemUtil.java | 2 +- .../me/xginko/aef/utils/MaterialUtil.java | 11 +- 253 files changed, 2335 insertions(+), 2732 deletions(-) create mode 100755 AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/DisableCustomEntities.java delete mode 100644 AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/AnchorAuraDelay.java delete mode 100755 AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/BedAuraDelay.java delete mode 100755 AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/CrystalAuraDelay.java create mode 100644 AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/auras/AnchorAuraDelay.java create mode 100644 AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/auras/AuraDelayModule.java create mode 100755 AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/auras/BedAuraDelay.java create mode 100755 AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/auras/CrystalAuraDelay.java rename AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/{patches => dupepreventions}/CowDupe.java (75%) create mode 100755 AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/DisableCustomEntities.java delete mode 100755 AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/DisableFish.java rename AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/withers/{RemoveSkullsOnChunkload.java => RemoveSkullsOnChunkUnload.java} (80%) diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/AnarchyExploitFixes.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/AnarchyExploitFixes.java index 0c00f75cd..b0cfe10a8 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/AnarchyExploitFixes.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/AnarchyExploitFixes.java @@ -12,6 +12,8 @@ import me.xginko.aef.utils.tickdata.TickReporter; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.logger.slf4j.ComponentLogger; +import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.core.config.Configurator; import org.bstats.bukkit.Metrics; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; @@ -48,6 +50,8 @@ public final class AnarchyExploitFixes extends JavaPlugin { @Override public void onLoad() { PlatformUtil.load(); + // Disable reflection logging because we want to do our own, pretty logging + Configurator.setLevel(AnarchyExploitFixes.class.getPackage().getName() + ".libs.reflections.Reflections", Level.OFF); } @Override diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/AEFModule.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/AEFModule.java index 2fe006b18..a33044068 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/AEFModule.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/AEFModule.java @@ -7,8 +7,6 @@ import me.xginko.aef.utils.models.ConditionalEnableable; import me.xginko.aef.utils.models.Disableable; import me.xginko.aef.utils.models.Enableable; -import org.apache.logging.log4j.Level; -import org.apache.logging.log4j.core.config.Configurator; import org.reflections.Reflections; import org.reflections.scanners.Scanners; @@ -24,8 +22,6 @@ public abstract class AEFModule implements ConditionalEnableable, Disableable { protected static final Set ENABLED_MODULES; static { - // Disable reflection logging for this operation because its just confusing and provides no value. - Configurator.setLevel(AnarchyExploitFixes.class.getPackage().getName() + ".libs.reflections.Reflections", Level.OFF); AVAILABLE_MODULES = new Reflections(AEFModule.class.getPackage().getName()) .get(Scanners.SubTypes.of(AEFModule.class).asClass()) .stream() @@ -36,15 +32,35 @@ public abstract class AEFModule implements ConditionalEnableable, Disableable { ENABLED_MODULES = new HashSet<>(); } - protected final AnarchyExploitFixes plugin; - protected final Config config; + protected final AnarchyExploitFixes plugin = AnarchyExploitFixes.getInstance(); + protected final Config config = AnarchyExploitFixes.config(); protected final String configPath, logFormat; + protected final boolean configEnabled; public AEFModule(String configPath) { - this.plugin = AnarchyExploitFixes.getInstance(); - this.config = AnarchyExploitFixes.config(); this.configPath = configPath; - shouldEnable(); // Ensure enable option is always first + this.configEnabled = true; + + String[] paths = configPath.split("\\."); + if (paths.length <= 2) { + this.logFormat = "<" + configPath + "> {}"; + } else { + this.logFormat = "<" + paths[paths.length - 2] + "." + paths[paths.length - 1] + "> {}"; + } + } + + public AEFModule(String configPath, boolean defEnabled) { + this(configPath, defEnabled, null); + } + + public AEFModule(String configPath, boolean defEnabled, String comment) { + this.configPath = configPath; + if (comment == null || comment.isEmpty()) { + this.configEnabled = config.getBoolean(configPath + ".enable", defEnabled); + } else { + this.configEnabled = config.getBoolean(configPath + ".enable", defEnabled, comment); + } + String[] paths = configPath.split("\\."); if (paths.length <= 2) { this.logFormat = "<" + configPath + "> {}"; @@ -53,6 +69,10 @@ public AEFModule(String configPath) { } } + public boolean shouldEnable() { + return configEnabled; + } + public static void disableAll() { ENABLED_MODULES.forEach(Disableable::disable); ENABLED_MODULES.clear(); @@ -67,12 +87,11 @@ public static void reloadModules() { if (module.shouldEnable()) { if (module instanceof PacketModule && AnarchyExploitFixes.config().packets_disabled) { module.warn("Cannot enable because you disabled packets in config!"); - continue; + } else { + ENABLED_MODULES.add(module); } - - ENABLED_MODULES.add(module); } - } catch (Throwable t) { // We want to catch everything here if it fails to init + } catch (Throwable t) { AnarchyExploitFixes.prefixedLogger().warn("Failed initialising module class '{}'.", moduleClass.getSimpleName(), t); } } diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/bedrock/FillNetherCeilingOnChunkload.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/bedrock/FillNetherCeilingOnChunkload.java index fe63f28f6..5b3828fc7 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/bedrock/FillNetherCeilingOnChunkload.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/bedrock/FillNetherCeilingOnChunkload.java @@ -21,7 +21,7 @@ public class FillNetherCeilingOnChunkload extends AEFModule implements Listener private final boolean alsoCheckNewChunks, checkShouldPauseOnLowTPS; public FillNetherCeilingOnChunkload() { - super("bedrock.fill-in-bedrock.nether-ceiling.fill-on-chunkload"); + super("bedrock.fill-in-bedrock.nether-ceiling.fill-on-chunkload", false); this.alsoCheckNewChunks = config.getBoolean(configPath + ".also-check-new-chunks", false, """ Recommended to leave off. Only useful if world generation is broken."""); this.exemptedWorlds = new HashSet<>(config.getList(configPath + ".exempted-worlds", @@ -37,11 +37,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/bedrock/FillNetherFloorOnChunkload.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/bedrock/FillNetherFloorOnChunkload.java index 4d01d1fc2..44b8860fe 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/bedrock/FillNetherFloorOnChunkload.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/bedrock/FillNetherFloorOnChunkload.java @@ -21,7 +21,7 @@ public class FillNetherFloorOnChunkload extends AEFModule implements Listener { private final boolean alsoCheckNewChunks, checkShouldPauseOnLowTPS; public FillNetherFloorOnChunkload() { - super("bedrock.fill-in-bedrock.nether-floor.fill-on-chunkload"); + super("bedrock.fill-in-bedrock.nether-floor.fill-on-chunkload", false); this.alsoCheckNewChunks = config.getBoolean(configPath + ".also-check-new-chunks", false, """ Recommended to leave off. Only useful if world generation is broken."""); this.exemptedWorlds = new HashSet<>(config.getList(configPath + ".exempted-worlds", @@ -37,11 +37,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/bedrock/FillOverworldFloorOnChunkload.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/bedrock/FillOverworldFloorOnChunkload.java index 4510c0a82..dcff92035 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/bedrock/FillOverworldFloorOnChunkload.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/bedrock/FillOverworldFloorOnChunkload.java @@ -21,7 +21,7 @@ public class FillOverworldFloorOnChunkload extends AEFModule implements Listener private final boolean alsoCheckNewChunks, checkShouldPauseOnLowTPS; public FillOverworldFloorOnChunkload() { - super("bedrock.fill-in-bedrock.overworld-floor.fill-on-chunkload"); + super("bedrock.fill-in-bedrock.overworld-floor.fill-on-chunkload", false); this.alsoCheckNewChunks = config.getBoolean(configPath + ".also-check-new-chunks", false, """ Recommended to leave off. Only useful if world generation is broken."""); this.exemptedWorlds = new HashSet<>(config.getList(configPath + ".exempted-worlds", @@ -37,11 +37,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/bedrock/PeriodicallyFillNetherCeiling.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/bedrock/PeriodicallyFillNetherCeiling.java index 765c3c8cc..a29bb4907 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/bedrock/PeriodicallyFillNetherCeiling.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/bedrock/PeriodicallyFillNetherCeiling.java @@ -14,15 +14,16 @@ public class PeriodicallyFillNetherCeiling extends AEFModule implements Consumer { - private ScheduledTask scheduledTask; private final Set exemptedWorlds; private final long checkPeriod; private final double pauseTPS; private final boolean pauseOnLowTPS; - + + private ScheduledTask scheduledTask; + public PeriodicallyFillNetherCeiling() { - super("bedrock.fill-in-bedrock.nether-ceiling.periodically-check-and-fill"); - config.addComment(configPath + ".enable","Only checks loaded chunks."); + super("bedrock.fill-in-bedrock.nether-ceiling.periodically-check-and-fill", false, + "Only checks loaded chunks."); this.checkPeriod = config.getInt(configPath + ".check-period-in-seconds", 10) * 20L; this.exemptedWorlds = new HashSet<>(config.getList(configPath + ".exempted-worlds", List.of("exampleworld", "exampleworld2"), @@ -34,18 +35,16 @@ public PeriodicallyFillNetherCeiling() { @Override public void enable() { - this.scheduledTask = plugin.getServer().getGlobalRegionScheduler() + scheduledTask = plugin.getServer().getGlobalRegionScheduler() .runAtFixedRate(plugin, this, checkPeriod, checkPeriod); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { - if (scheduledTask != null) scheduledTask.cancel(); + if (scheduledTask != null) { + scheduledTask.cancel(); + scheduledTask = null; + } } @Override diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/bedrock/PeriodicallyFillNetherFloor.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/bedrock/PeriodicallyFillNetherFloor.java index 0c40895e9..8c3c6ca58 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/bedrock/PeriodicallyFillNetherFloor.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/bedrock/PeriodicallyFillNetherFloor.java @@ -14,14 +14,15 @@ public class PeriodicallyFillNetherFloor extends AEFModule implements Consumer { - private ScheduledTask scheduledTask; private final Set exemptedWorlds; private final long checkPeriod; private final double pauseTPS; private final boolean pauseOnLowTPS; + private ScheduledTask scheduledTask; + public PeriodicallyFillNetherFloor() { - super("bedrock.fill-in-bedrock.nether-floor.periodically-check-and-fill"); + super("bedrock.fill-in-bedrock.nether-floor.periodically-check-and-fill", false); config.addComment(configPath + ".enable","Only checks loaded chunks."); this.checkPeriod = config.getInt(configPath + ".check-period-in-seconds", 10) * 20L; this.exemptedWorlds = new HashSet<>(config.getList(configPath + ".exempted-worlds", @@ -34,18 +35,16 @@ public PeriodicallyFillNetherFloor() { @Override public void enable() { - this.scheduledTask = plugin.getServer().getGlobalRegionScheduler() + scheduledTask = plugin.getServer().getGlobalRegionScheduler() .runAtFixedRate(plugin, this, checkPeriod, checkPeriod); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { - if (scheduledTask != null) scheduledTask.cancel(); + if (scheduledTask != null) { + scheduledTask.cancel(); + scheduledTask = null; + } } @Override diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/bedrock/PeriodicallyFillOverworldFloor.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/bedrock/PeriodicallyFillOverworldFloor.java index 57f82b9f0..df6bd3742 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/bedrock/PeriodicallyFillOverworldFloor.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/bedrock/PeriodicallyFillOverworldFloor.java @@ -14,15 +14,16 @@ public class PeriodicallyFillOverworldFloor extends AEFModule implements Consumer { - private ScheduledTask scheduledTask; private final Set exemptedWorlds; private final long checkPeriod; private final double pauseTPS; private final boolean pauseOnLowTPS; + private ScheduledTask scheduledTask; + public PeriodicallyFillOverworldFloor() { - super("bedrock.fill-in-bedrock.overworld-floor.periodically-check-and-fill"); - config.addComment(configPath + ".enable","Only checks loaded chunks."); + super("bedrock.fill-in-bedrock.overworld-floor.periodically-check-and-fill", false, + "Only checks loaded chunks."); this.checkPeriod = config.getInt(configPath + ".check-period-in-seconds", 10) * 20L; this.exemptedWorlds = new HashSet<>(config.getList(configPath + ".exempted-worlds", List.of("exampleworld", "exampleworld2"), @@ -35,18 +36,16 @@ public PeriodicallyFillOverworldFloor() { @Override public void enable() { - this.scheduledTask = plugin.getServer().getGlobalRegionScheduler() + scheduledTask = plugin.getServer().getGlobalRegionScheduler() .runAtFixedRate(plugin, this, checkPeriod, checkPeriod); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { - if (scheduledTask != null) scheduledTask.cancel(); + if (scheduledTask != null) { + scheduledTask.cancel(); + scheduledTask = null; + } } @Override diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/bedrock/PreventGoingBelowBedrockFloor.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/bedrock/PreventGoingBelowBedrockFloor.java index d406581f8..1fb6bd776 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/bedrock/PreventGoingBelowBedrockFloor.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/bedrock/PreventGoingBelowBedrockFloor.java @@ -23,8 +23,8 @@ public class PreventGoingBelowBedrockFloor extends AEFModule implements Listener private final double damageOnMove; public PreventGoingBelowBedrockFloor() { - super("bedrock.prevent-going-below-bedrock-floor"); - config.addComment(configPath + ".enable", "Prevents players from going below the bedrock floor."); + super("bedrock.prevent-going-below-bedrock-floor", true, + "Prevents players from going below the bedrock floor."); this.vehicleEject = config.getBoolean(configPath + ".leave-vehicle", true, "Whether to make player leave their vehicle."); this.closeElytra = config.getBoolean(configPath + ".stop-elytra", true, @@ -52,11 +52,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", true); - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/chat/PreventPluginScanning.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/chat/PreventPluginScanning.java index 3fec1232c..e0b788a85 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/chat/PreventPluginScanning.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/chat/PreventPluginScanning.java @@ -16,7 +16,7 @@ public class PreventPluginScanning extends AEFModule implements Listener { public PreventPluginScanning() { - super("chat.prevent-scanning-server-plugins"); + super("chat.prevent-scanning-server-plugins", true); config.addComment(configPath + ".enable",""" Prevents hacked clients running .plugins to find out what plugins\s the server is using.\s @@ -28,11 +28,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", true); - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/chat/commandwhitelist/CommandWhitelist.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/chat/commandwhitelist/CommandWhitelist.java index 4faf7833c..ca15dd87d 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/chat/commandwhitelist/CommandWhitelist.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/chat/commandwhitelist/CommandWhitelist.java @@ -32,13 +32,14 @@ */ public class CommandWhitelist extends AEFModule implements PacketListener, Listener { - private final PacketListenerAbstract abstractListener; - private final Listener commandSendListener; private final Set allowedCommands, bannedSubCommands; private final boolean usePackets, shouldLog; + private PacketListenerAbstract packetListenerAbstract; + private Listener commandSendListener; + public CommandWhitelist() { - super("chat.command-whitelist"); + super("chat.command-whitelist", false); config.addComment(configPath + ".enable", "This will make it pretty much impossible to find your plugins as\n" + "only the commands you specify will be able to work.\n" + @@ -63,33 +64,34 @@ public CommandWhitelist() { List.of("help about", "vote List", "vote Best", "vote Total", "worldstats reload", "stats reload"),""" Add all subcommands you DON'T want your players to be able\s to access. Case sensitive!""")); - this.commandSendListener = new CWCommandSendListener(allowedCommands); - this.abstractListener = asAbstract(PacketListenerPriority.HIGHEST); } @Override public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); + commandSendListener = new CWCommandSendListener(allowedCommands); plugin.getServer().getPluginManager().registerEvents(commandSendListener, plugin); if (usePackets) { - if (config.packets_disabled) { + if (AnarchyExploitFixes.config().packets_disabled) { warn("Can't enable packet listener because packet events is disabled in config."); } else { - PacketEvents.getAPI().getEventManager().registerListener(abstractListener); + packetListenerAbstract = asAbstract(PacketListenerPriority.HIGHEST); + PacketEvents.getAPI().getEventManager().registerListener(packetListenerAbstract); } } } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); - HandlerList.unregisterAll(commandSendListener); - PacketEvents.getAPI().getEventManager().unregisterListener(abstractListener); + if (commandSendListener != null) { + HandlerList.unregisterAll(commandSendListener); + commandSendListener = null; + } + if (packetListenerAbstract != null) { + PacketEvents.getAPI().getEventManager().unregisterListener(packetListenerAbstract); + packetListenerAbstract = null; + } } @Override @@ -106,7 +108,7 @@ public void onPacketReceive(PacketReceiveEvent event) { return; } - final Player player = (Player) event.getPlayer(); + final Player player = event.getPlayer(); if (player != null && player.hasPermission(AEFPermission.BYPASS_CMD_WHITELIST.bukkit())) return; if (!allowedCommands.contains(CommandUtil.getCommandLabel(message).toLowerCase())) { diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/chunklimits/BlockLimit.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/chunklimits/BlockLimit.java index 16ffd2913..5fc0429b5 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/chunklimits/BlockLimit.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/chunklimits/BlockLimit.java @@ -20,7 +20,7 @@ public class BlockLimit extends AEFModule implements Listener { private final Map blockLimits = new EnumMap<>(Material.class); public BlockLimit() { - super("chunk-limits.block-limit"); + super("chunk-limits.block-limit", false); Map universal = new EnumMap<>(XMaterial.class); universal.put(XMaterial.ENCHANTING_TABLE, 16); @@ -146,11 +146,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); @@ -158,16 +153,16 @@ public void disable() { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) private void onBlockPlace(BlockPlaceEvent event) { - final Material placedType = event.getBlock().getType(); if ( - blockLimits.containsKey(placedType) - && exceedsPerChunkLimit(placedType, blockLimits.get(placedType), event.getBlock().getChunk()) + blockLimits.containsKey(event.getBlock().getType()) + && exceedsPerChunkLimit(event.getBlock().getType(), event.getBlock().getChunk()) ) { event.setCancelled(true); } } - private boolean exceedsPerChunkLimit(Material material, int limit, Chunk chunk) { + private boolean exceedsPerChunkLimit(Material material, Chunk chunk) { + final int materialLimit = blockLimits.get(material); final int minY = chunk.getWorld().getMinHeight(); final int maxY = chunk.getWorld().getMaxHeight(); int count = 0; @@ -176,7 +171,9 @@ private boolean exceedsPerChunkLimit(Material material, int limit, Chunk chunk) for (int y = minY; y < maxY; y++) { if (chunk.getBlock(x, y, z).getType() == material) { count++; - if (count > limit) return true; + if (count > materialLimit) { + return true; + } } } } diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/chunklimits/CustomEntityLimit.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/chunklimits/CustomEntityLimit.java index d4c90cf68..8f076bba3 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/chunklimits/CustomEntityLimit.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/chunklimits/CustomEntityLimit.java @@ -32,9 +32,9 @@ public class CustomEntityLimit extends AEFModule implements Consumer private final boolean logIsEnabled; public ExpBottleLimit() { - super("chunk-limits.exp-bottle-limit"); - config.addComment(configPath + ".enable", """ + super("chunk-limits.exp-bottle-limit", true, """ Prevent players from crashing the server or other players by\s creating a ton of THROWN_EXP_BOTTLE entities, then loading\s them at once.\s @@ -44,11 +43,6 @@ public void enable() { .runAtFixedRate(plugin, this, checkPeriod, checkPeriod); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", true); - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/chunklimits/FallingBlockLimit.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/chunklimits/FallingBlockLimit.java index 163530498..58f8f26a1 100644 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/chunklimits/FallingBlockLimit.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/chunklimits/FallingBlockLimit.java @@ -19,39 +19,40 @@ public class FallingBlockLimit extends AEFModule implements Listener { - private final ExpiringSet checkedChunks; + private final long chunkCheckDelay; private final int maxFallingGravityBlockPerChunk; private final boolean logIsEnabled; + private ExpiringSet checkedChunks; + public FallingBlockLimit() { - super("chunk-limits.falling-block-limit"); - config.addComment(configPath + ".enable", """ + super("chunk-limits.falling-block-limit", true, """ Prevent players from placing massive sand chunks, then collapsing\s them to kill the server."""); this.logIsEnabled = config.getBoolean(configPath + ".log", false); this.maxFallingGravityBlockPerChunk = config.getInt(configPath + ".max-falling-gravity-blocks-per-chunk", 60, """ Removes any falling block if there is more than x blocks actively\s falling in a chunk."""); - long chunkCheckDelay = Math.max(1, config.getInt(configPath + ".chunk-check-delay-in-ticks", 20, """ + this.chunkCheckDelay = Math.max(1, config.getInt(configPath + ".chunk-check-delay-in-ticks", 20, """ Delay in ticks until the same chunk can be checked again.\s Prevents overchecking, because physics events can be called many\s times in a short time for the same chunk.""")) * 50L; - this.checkedChunks = new ExpiringSet<>(Duration.ofMillis(chunkCheckDelay)); } @Override public void enable() { + checkedChunks = new ExpiringSet<>(Duration.ofMillis(chunkCheckDelay)); plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", true); - } - @Override public void disable() { HandlerList.unregisterAll(this); + if (checkedChunks != null) { + checkedChunks.clear(); + checkedChunks.cleanUp(); + checkedChunks = null; + } } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/chunklimits/MinecartLimit.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/chunklimits/MinecartLimit.java index 6e6d82050..8e51ba145 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/chunklimits/MinecartLimit.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/chunklimits/MinecartLimit.java @@ -20,14 +20,14 @@ public class MinecartLimit extends AEFModule implements Consumer, Listener { - private ScheduledTask scheduledTask; private final long checkPeriod; private final int maxMinecartsPerChunk; private final boolean logIsEnabled; + private ScheduledTask scheduledTask; + public MinecartLimit() { - super("chunk-limits.minecart-limit"); - config.addComment(configPath + ".enable", """ + super("chunk-limits.minecart-limit", false, """ Limit the amount of minecarts to prevent lag caused by collisions."""); this.logIsEnabled = config.getBoolean(configPath + ".log-removals", false); this.maxMinecartsPerChunk = config.getInt(configPath + ".max-minecarts-per-chunk", 25); @@ -37,19 +37,17 @@ public MinecartLimit() { @Override public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); - this.scheduledTask = plugin.getServer().getGlobalRegionScheduler() + scheduledTask = plugin.getServer().getGlobalRegionScheduler() .runAtFixedRate(plugin, this, checkPeriod, checkPeriod); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { - if (scheduledTask != null) scheduledTask.cancel(); HandlerList.unregisterAll(this); + if (scheduledTask != null) { + scheduledTask.cancel(); + scheduledTask = null; + } } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/chunklimits/NonLivingEntityLimit.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/chunklimits/NonLivingEntityLimit.java index 216e7116a..1f04fb8ce 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/chunklimits/NonLivingEntityLimit.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/chunklimits/NonLivingEntityLimit.java @@ -21,19 +21,20 @@ public class NonLivingEntityLimit extends AEFModule implements Consumer, Listener { - private ScheduledTask scheduledTask; private final long checkPeriod; private final int maxNonLivingEntities; private final boolean logIsEnabled; + private ScheduledTask scheduledTask; + public NonLivingEntityLimit() { - super("chunk-limits.entity-limits.non-living-limit"); - config.addComment(configPath + ".enable", """ + super("chunk-limits.entity-limits.non-living-limit", false, """ Limit the amount of non living entities in a chunk to prevent lag.\s Ignores dropped items."""); this.logIsEnabled = config.getBoolean(configPath + ".log-removals", true); this.maxNonLivingEntities = config.getInt(configPath + ".max-non-living-per-chunk", 100); - this.checkPeriod = config.getInt(configPath + ".check-period-in-ticks", 20); + this.checkPeriod = Math.max(1, config.getInt(configPath + ".check-period-in-ticks", 20, + "20 ticks = 1 second")); } @Override @@ -43,15 +44,13 @@ public void enable() { .runAtFixedRate(plugin, this, checkPeriod, checkPeriod); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { - if (scheduledTask != null) scheduledTask.cancel(); HandlerList.unregisterAll(this); + if (scheduledTask != null) { + scheduledTask.cancel(); + scheduledTask = null; + } } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/chunklimits/TileEntityLimit.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/chunklimits/TileEntityLimit.java index 2413ef2a4..34d142a2f 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/chunklimits/TileEntityLimit.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/chunklimits/TileEntityLimit.java @@ -15,13 +15,14 @@ public class TileEntityLimit extends AEFModule implements Consumer, Listener { - private ScheduledTask scheduledTask; private final long checkPeriod; private final int maxTileEntities; private final boolean logIsEnabled; + private ScheduledTask scheduledTask; + public TileEntityLimit() { - super("chunk-limits.entity-limits.tile-entity-limit"); + super("chunk-limits.entity-limits.tile-entity-limit", false); config.addComment(configPath + ".enable", """ Limit the amount of tile entities in a chunk to prevent lag."""); this.logIsEnabled = config.getBoolean(configPath + ".log-removals", true); @@ -36,15 +37,13 @@ public void enable() { .runAtFixedRate(plugin, this, checkPeriod, checkPeriod); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { - if (scheduledTask != null) scheduledTask.cancel(); HandlerList.unregisterAll(this); + if (scheduledTask != null) { + scheduledTask.cancel(); + scheduledTask = null; + } } @Override @@ -59,11 +58,11 @@ public void accept(ScheduledTask task) { if (tooMany <= 0) return; for (int i = 0; i < tooMany; i++) { - tileEntities[i].setType(XMaterial.AIR.parseMaterial()); + tileEntities[i].setType(XMaterial.AIR.get()); tileEntities[i].update(true, false); if (logIsEnabled) - info( "Removed tile entity at " + LocationUtil.toString(tileEntities[i].getLocation()) + + info("Removed tile entity at " + LocationUtil.toString(tileEntities[i].getLocation()) + " because reached limit of " + maxTileEntities); } }); diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/chunklimits/VehicleLimit.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/chunklimits/VehicleLimit.java index 943b791b5..2e08c70ca 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/chunklimits/VehicleLimit.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/chunklimits/VehicleLimit.java @@ -19,21 +19,21 @@ public class VehicleLimit extends AEFModule implements Consumer, Listener { - private ScheduledTask scheduledTask; private final long checkPeriod; private final int maxVehiclesPerChunk; private final boolean logIsEnabled; + private ScheduledTask scheduledTask; + public VehicleLimit() { - super("chunk-limits.vehicle-limit"); - config.addComment(configPath + ".enable", """ + super("chunk-limits.vehicle-limit", false, """ Limit the amount of vehicles to prevent some lag machines.\s ex. dispenser that spawns a lot of boats into a single location\s then hitting it, causing all boats to explode in every direction."""); this.logIsEnabled = config.getBoolean(configPath + ".log-removals", false); this.maxVehiclesPerChunk = config.getInt(configPath + ".max-vehicles-per-chunk", 25); - this.checkPeriod = config.getInt(configPath + ".check-period-in-ticks", 400, - "200 ticks = 10 seconds."); + this.checkPeriod = Math.max(1, config.getInt(configPath + ".check-period-in-ticks", 400, + "200 ticks = 10 seconds.")); } @Override @@ -43,15 +43,13 @@ public void enable() { .runAtFixedRate(plugin, this, checkPeriod, checkPeriod); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { - if (scheduledTask != null) scheduledTask.cancel(); HandlerList.unregisterAll(this); + if (scheduledTask != null) { + scheduledTask.cancel(); + scheduledTask = null; + } } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/chunklimits/VillagerLimit.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/chunklimits/VillagerLimit.java index 78b5d9c38..bfb7be4ec 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/chunklimits/VillagerLimit.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/chunklimits/VillagerLimit.java @@ -27,19 +27,20 @@ public class VillagerLimit extends AEFModule implements Consumer, Listener { - private ScheduledTask scheduledTask; private final List removalPriority; private final Set professionWhitelist; private final long checkPeriod; private final int maxVillagersPerChunk; private final boolean logIsEnabled, whitelistEnabled; + private ScheduledTask scheduledTask; + public VillagerLimit() { - super("chunk-limits.entity-limits.villager-limit"); + super("chunk-limits.entity-limits.villager-limit", false); this.maxVillagersPerChunk = Math.max(1, config.getInt(configPath + ".max-villagers-per-chunk", 25)); this.logIsEnabled = config.getBoolean(configPath + ".log-removals", false); - this.checkPeriod = Math.max(config.getInt(configPath + ".check-period-in-ticks", 600, - "Check all chunks every x ticks."), 1); + this.checkPeriod = Math.max(1, config.getInt(configPath + ".check-period-in-ticks", 600, + "Check all chunks every x ticks.")); final List defPriority = Stream.of("NONE", "NITWIT", "SHEPHERD", "FISHERMAN", "BUTCHER", "CARTOGRAPHER", "LEATHERWORKER", "FLETCHER", "MASON", "FARMER", "ARMORER", "TOOLSMITH", "WEAPONSMITH", "CLERIC", "LIBRARIAN") .filter(prof -> { @@ -94,19 +95,17 @@ public VillagerLimit() { @Override public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); - this.scheduledTask = plugin.getServer().getGlobalRegionScheduler() + scheduledTask = plugin.getServer().getGlobalRegionScheduler() .runAtFixedRate(plugin, this, checkPeriod, checkPeriod); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); - if (scheduledTask != null) scheduledTask.cancel(); + if (scheduledTask != null) { + scheduledTask.cancel(); + scheduledTask = null; + } } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/combat/BowBomb.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/combat/BowBomb.java index eb6c83ef5..e7531a8ba 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/combat/BowBomb.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/combat/BowBomb.java @@ -13,7 +13,7 @@ public class BowBomb extends AEFModule implements Listener { private final int maxBowSquaredVelocity; public BowBomb() { - super("combat.prevent-bow-bomb"); + super("combat.prevent-bow-bomb", false); this.maxBowSquaredVelocity = config.getInt(configPath + ".max-bow-squared-velocity", 15, "Fully pulled bow is ~9-10. 15 is default just to be safe."); } @@ -23,11 +23,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/combat/Burrow.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/combat/Burrow.java index cf43023b3..23f2ca1e2 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/combat/Burrow.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/combat/Burrow.java @@ -31,7 +31,7 @@ public class Burrow extends AEFModule implements Listener { private final boolean shouldTeleportUp, preventIfBlockAboveBurrow, breakAnvilInsteadOfTP, allowSlabs; public Burrow() { - super("combat.prevent-burrow"); + super("combat.prevent-burrow", false); this.damageWhenMovingInBurrow = config.getDouble(configPath + ".damage-when-moving",1.0, """ 1.0 = Half a heart of damage every time you move."""); this.shouldTeleportUp = config.getBoolean(configPath + ".teleport-above-block", true); @@ -47,7 +47,7 @@ public Burrow() { List defaults = Stream.concat(XTag.SHULKER_BOXES.getValues().stream(), Stream.of(XMaterial.AIR, XMaterial.DIRT, XMaterial.DIRT_PATH, XMaterial.SAND, XMaterial.GRAVEL)) .filter(XMaterial::isSupported) - .map(XMaterial::parseMaterial) + .map(XMaterial::get) .map(Enum::name) .toList(); this.ignoredMaterial = config.getList(configPath + ".ignored-materials", defaults) @@ -69,11 +69,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); @@ -102,12 +97,12 @@ private void onPlayerMove(PlayerMoveEvent event) { final Block burrowBlock = playerLocation.getBlock(); if (ignoredMaterial.contains(burrowBlock.getType())) return; - if (!preventIfBlockAboveBurrow && burrowBlock.getRelative(BlockFace.UP).getType() != XMaterial.AIR.parseMaterial()) { + if (!preventIfBlockAboveBurrow && burrowBlock.getRelative(BlockFace.UP).getType() != XMaterial.AIR.get()) { return; } // Beacon and Indestructibles - if (MaterialUtil.SOLID_INDESTRUCTIBLES.contains(burrowBlock.getType()) || burrowBlock.getType() == XMaterial.BEACON.parseMaterial()) { + if (MaterialUtil.SOLID_INDESTRUCTIBLES.contains(burrowBlock.getType()) || burrowBlock.getType() == XMaterial.BEACON.get()) { player.damage(damageWhenMovingInBurrow); if (shouldTeleportUp) teleportUpAndCenter(player, burrowBlock.getLocation()); return; @@ -126,7 +121,7 @@ private void onPlayerMove(PlayerMoveEvent event) { if (MaterialUtil.ANVILS.contains(burrowBlock.getType())) { player.damage(damageWhenMovingInBurrow); if (breakAnvilInsteadOfTP) { - burrowBlock.setType(XMaterial.AIR.parseMaterial()); + burrowBlock.setType(XMaterial.AIR.get()); } else { if (shouldTeleportUp) teleportUpAndCenter(player, burrowBlock.getLocation()); } @@ -134,7 +129,7 @@ private void onPlayerMove(PlayerMoveEvent event) { } // Ender chest & Blocks that are slightly lower in height - if (burrowBlock.getType() == XMaterial.ENDER_CHEST.parseMaterial() || MaterialUtil.SINK_IN_BLOCKS.contains(burrowBlock.getType())) { + if (burrowBlock.getType() == XMaterial.ENDER_CHEST.get() || MaterialUtil.SINK_IN_BLOCKS.contains(burrowBlock.getType())) { if (playerLocation.getY() - playerLocation.getBlockY() < 0.875) { player.damage(damageWhenMovingInBurrow); if (shouldTeleportUp) teleportUpAndCenter(player, burrowBlock.getLocation()); @@ -143,7 +138,7 @@ private void onPlayerMove(PlayerMoveEvent event) { } // Enchantment Table - if (burrowBlock.getType() == XMaterial.ENCHANTING_TABLE.parseMaterial()) { + if (burrowBlock.getType() == XMaterial.ENCHANTING_TABLE.get()) { if (playerLocation.getY() - playerLocation.getBlockY() < 0.75) { player.damage(damageWhenMovingInBurrow); if (shouldTeleportUp) teleportUpAndCenter(player, burrowBlock.getLocation()); diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/combat/MultiTask.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/combat/MultiTask.java index c3ee3098b..2813dcd6e 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/combat/MultiTask.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/combat/MultiTask.java @@ -15,7 +15,7 @@ public class MultiTask extends AEFModule implements Listener { public MultiTask() { - super("combat.multi-task-patch"); + super("combat.multi-task-patch", false); } @Override @@ -23,11 +23,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/combat/PistonCrystalDelay.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/combat/PistonCrystalDelay.java index 5484c096d..6c33bd0ff 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/combat/PistonCrystalDelay.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/combat/PistonCrystalDelay.java @@ -2,7 +2,6 @@ import com.cryptomorin.xseries.XEntityType; import me.xginko.aef.modules.AEFModule; -import me.xginko.aef.utils.models.ExpiringSet; import org.bukkit.Location; import org.bukkit.entity.Entity; import org.bukkit.event.EventHandler; @@ -11,42 +10,47 @@ import org.bukkit.event.Listener; import org.bukkit.event.block.BlockPistonExtendEvent; -import java.time.Duration; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.TimeUnit; public class PistonCrystalDelay extends AEFModule implements Listener { - private final ExpiringSet pistonsPushingCrystals; + private final long cooldownNanos; + + private Map extendCooldowns; public PistonCrystalDelay() { - super("combat.crystal-aura.piston-aura-delay"); - config.addComment(configPath+".enable", "Rate-limits pistons that extend into crystals."); - this.pistonsPushingCrystals = new ExpiringSet<>(Duration.ofMillis( - Math.max(1, config.getInt(configPath + ".piston-extend-delay-in-ticks", 40)) * 50L)); + super("combat.crystal-aura.piston-aura-delay", false, + "Rate-limits pistons that extend into crystals."); + this.cooldownNanos = TimeUnit.MILLISECONDS.toNanos( + Math.max(1, config.getInt(configPath + ".piston-extend-delay-in-ticks", 40)) * 50L); } @Override public void enable() { + extendCooldowns = new HashMap<>(); plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath+".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); + if (extendCooldowns != null) { + extendCooldowns.clear(); + extendCooldowns = null; + } } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) private void onPistonExtend(BlockPistonExtendEvent event) { for (Entity entity : event.getBlock().getRelative(event.getDirection()).getLocation().getNearbyEntities(1, 1, 1)) { if (entity.getType() == XEntityType.END_CRYSTAL.get()) { - if (pistonsPushingCrystals.contains(event.getBlock().getLocation())) { + if (extendCooldowns.containsKey(event.getBlock().getLocation()) + && extendCooldowns.get(event.getBlock().getLocation()) > System.nanoTime()) { event.setCancelled(true); } else { - pistonsPushingCrystals.add(event.getBlock().getLocation()); + extendCooldowns.put(event.getBlock().getLocation(), System.currentTimeMillis() + cooldownNanos); } return; } diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/combat/PistonPush.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/combat/PistonPush.java index b03c60595..0db54a92f 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/combat/PistonPush.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/combat/PistonPush.java @@ -20,11 +20,10 @@ public class PistonPush extends AEFModule implements Listener { private final Set pushDisabledTypes; public PistonPush() { - super("combat.piston-push"); - config.addComment(configPath+".enable", - "Disables pistons from extending if it would push certain configured entities.\n" + - "This can be used to prevent players from pushing other players out of burrows, by\n" + - "configuring PLAYER, or to disable piston-crystal by adding ENDER_CRYSTAL to the list."); + super("combat.piston-push", false,""" + Disables pistons from extending if it would push certain configured entities. + This can be used to prevent players from pushing other players out of burrows, by + configuring PLAYER, or to disable piston-crystal by adding ENDER_CRYSTAL to the list."""); this.pushDisabledTypes = config.getList(configPath+".piston-push-blocked-entities", Collections.singletonList("PLAYER")) .stream() .map(configuredType -> { @@ -43,11 +42,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath+".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/combat/PortalGodMode.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/combat/PortalGodMode.java index 4863b307f..7f2404f51 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/combat/PortalGodMode.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/combat/PortalGodMode.java @@ -20,12 +20,12 @@ public class PortalGodMode extends AEFModule implements Listener { - private final Cache playersWaitingForPortalTeleport; private final long delayTicks; + private Cache playersWaitingForPortalTeleport; + public PortalGodMode() { - super("combat.portal-god-mode-patch"); - config.addComment(configPath + ".enable", """ + super("combat.portal-god-mode-patch", false, """ Prevents an exploit that allows players to stand in nether portals and not\s take damage indefinitely by just never sending a TeleportConfirm packet to\s the server.\s @@ -36,23 +36,23 @@ public PortalGodMode() { the portal will be broken, making the player inside vulnerable again.\s Nether portal teleports normally happen within ~3s after enter, so 5s (100ticks)\s should be a safe value."""); - this.playersWaitingForPortalTeleport = Caffeine.newBuilder() - .expireAfterWrite(Duration.ofMillis((delayTicks * 50L) + 1000L)).build(); // Keep cached content for a second longer just in case } @Override public void enable() { + playersWaitingForPortalTeleport = Caffeine.newBuilder() + .expireAfterWrite(Duration.ofMillis((delayTicks * 50L) + 1000L)).build(); // Keep cached content for a second longer just in case plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); + if (playersWaitingForPortalTeleport != null) { + playersWaitingForPortalTeleport.asMap().clear(); + playersWaitingForPortalTeleport.cleanUp(); + playersWaitingForPortalTeleport = null; + } } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @@ -63,7 +63,7 @@ private void onEntityPortalEnter(EntityPortalEnterEvent event) { playersWaitingForPortalTeleport.put(event.getEntity().getUniqueId(), plugin.getServer().getRegionScheduler().runDelayed(plugin, event.getLocation(), breakPortal -> { - event.getLocation().getBlock().setType(XMaterial.AIR.parseMaterial(), true); + event.getLocation().getBlock().setType(XMaterial.AIR.get(), true); playersWaitingForPortalTeleport.invalidate(event.getEntity().getUniqueId()); }, delayTicks)); } @@ -85,7 +85,7 @@ private void onPlayerMove(PlayerMoveEvent event) { @Nullable ScheduledTask breakPortalTask = playersWaitingForPortalTeleport.getIfPresent(event.getPlayer().getUniqueId()); if (breakPortalTask == null) return; - if (event.getTo().getBlock().getType() != XMaterial.NETHER_PORTAL.parseMaterial()) { + if (event.getTo().getBlock().getType() != XMaterial.NETHER_PORTAL.get()) { breakPortalTask.cancel(); playersWaitingForPortalTeleport.invalidate(event.getPlayer().getUniqueId()); } diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/combat/SilentSwapDelay.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/combat/SilentSwapDelay.java index ce6cd7cdc..07df4e812 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/combat/SilentSwapDelay.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/combat/SilentSwapDelay.java @@ -27,7 +27,7 @@ public class SilentSwapDelay extends AEFModule implements Listener { private final boolean updateInventory; public SilentSwapDelay() { - super("combat.silent-swap-delay"); + super("combat.silent-swap-delay", false); this.swapItemCooldowns = new ConcurrentHashMap<>(); this.updateInventory = config.getBoolean(configPath + ".update-inventory-on-cancel", false, "Can help with desync but recommended to leave off unless you have issues."); diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/combat/auras/AnchorAuraDelay.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/combat/auras/AnchorAuraDelay.java index 10222c847..a0ddfad4e 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/combat/auras/AnchorAuraDelay.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/combat/auras/AnchorAuraDelay.java @@ -18,8 +18,8 @@ public AnchorAuraDelay() { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) private void onPlayerInteract(PlayerInteractEvent event) { if (event.getAction() != Action.RIGHT_CLICK_BLOCK) return; - if (event.getClickedBlock().getType() != XMaterial.RESPAWN_ANCHOR.parseMaterial()) return; - if (event.getItem() == null || event.getItem().getType() != XMaterial.GLOWSTONE.parseMaterial()) return; + if (event.getClickedBlock().getType() != XMaterial.RESPAWN_ANCHOR.get()) return; + if (event.getItem() == null || event.getItem().getType() != XMaterial.GLOWSTONE.get()) return; if (event.getPlayer().getWorld().isRespawnAnchorWorks()) return; for (Map.Entry entry : cooldownSettings.entrySet()) { @@ -35,7 +35,7 @@ private void onPlayerInteract(PlayerInteractEvent event) { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) private void onBlockPlace(BlockPlaceEvent event) { - if (event.getBlock().getType() != XMaterial.RESPAWN_ANCHOR.parseMaterial()) return; + if (event.getBlock().getType() != XMaterial.RESPAWN_ANCHOR.get()) return; if (event.getPlayer().getWorld().isRespawnAnchorWorks()) return; for (Map.Entry entry : cooldownSettings.entrySet()) { diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/combat/auras/AuraDelayModule.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/combat/auras/AuraDelayModule.java index 47543cc3e..a35afc960 100644 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/combat/auras/AuraDelayModule.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/combat/auras/AuraDelayModule.java @@ -19,7 +19,7 @@ public abstract class AuraDelayModule extends AEFModule implements Listener { protected static class Cooldowns { - public final Map placeCooldowns, breakCooldowns; + public Map placeCooldowns, breakCooldowns; public final long placeDelayNanos, breakDelayNanos; public Cooldowns(long placeDelayMillis, long breakDelayMillis) { @@ -28,13 +28,23 @@ public Cooldowns(long placeDelayMillis, long breakDelayMillis) { this.placeDelayNanos = TimeUnit.MILLISECONDS.toNanos(placeDelayMillis); this.breakDelayNanos = TimeUnit.MILLISECONDS.toNanos(breakDelayMillis); } + + public void clear() { + placeCooldowns.clear(); + breakCooldowns.clear(); + placeCooldowns = breakCooldowns = null; + } } protected final Map cooldownSettings = new EnumMap<>(SettingType.class); protected final boolean updateInventory; - + public AuraDelayModule(String configPath, long defPlaceDelayMillis, long defBreakDelayMillis) { - super(configPath); + this(configPath, false, defPlaceDelayMillis, defBreakDelayMillis); + } + + public AuraDelayModule(String configPath, boolean defEnabled, long defPlaceDelayMillis, long defBreakDelayMillis) { + super(configPath, defEnabled); this.updateInventory = config.getBoolean(configPath + ".update-inventory-on-cancel", false, "Can help with desync but recommended to leave off unless you have issues."); for (SettingType settingType : SettingType.values()) { @@ -54,18 +64,10 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); - cooldownSettings.forEach((settingType, cooldowns) -> { - cooldowns.placeCooldowns.clear(); - cooldowns.breakCooldowns.clear(); - }); + cooldownSettings.forEach((settingType, cooldowns) -> cooldowns.clear()); } protected boolean isOnCooldown(UUID uuid, Map cooldownMap, long delayNanos) { diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/combat/auras/CrystalAuraDelay.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/combat/auras/CrystalAuraDelay.java index e80f37b50..05d11b3dc 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/combat/auras/CrystalAuraDelay.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/combat/auras/CrystalAuraDelay.java @@ -34,7 +34,7 @@ private void onPrePlayerAttackEntity(PrePlayerAttackEntityEvent event) { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) private void onPlayerInteract(PlayerInteractEvent event) { if (event.getAction() != Action.RIGHT_CLICK_BLOCK) return; // Need to right-click a block to place a crystal - if (event.getItem() == null || event.getItem().getType() != XMaterial.END_CRYSTAL.parseMaterial()) return; + if (event.getItem() == null || event.getItem().getType() != XMaterial.END_CRYSTAL.get()) return; for (Map.Entry entry : cooldownSettings.entrySet()) { if (entry.getKey() != SettingType.GLOBAL && entry.getKey().slot != event.getHand()) continue; diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/dupepreventions/AllayDupe.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/dupepreventions/AllayDupe.java index 05548bce3..815608996 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/dupepreventions/AllayDupe.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/dupepreventions/AllayDupe.java @@ -15,8 +15,7 @@ public class AllayDupe extends AEFModule implements Listener { private final boolean dismount; public AllayDupe() { - super("dupe-preventions.allay-dupe"); - config.addComment(configPath + ".enable", """ + super("dupe-preventions.allay-dupe", false, """ Will prevent allays from entering vehicles to prevent a duplication exploit confirmed working in 1.19.4."""); this.dismount = config.getBoolean(configPath + ".dismount-premounted-allays", true); @@ -27,11 +26,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/dupepreventions/BookTitleDupe.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/dupepreventions/BookTitleDupe.java index 8dfbc52a6..689eec061 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/dupepreventions/BookTitleDupe.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/dupepreventions/BookTitleDupe.java @@ -1,25 +1,32 @@ package me.xginko.aef.modules.dupepreventions; +import com.github.retrooper.packetevents.PacketEvents; import com.github.retrooper.packetevents.event.PacketListenerPriority; import com.github.retrooper.packetevents.event.PacketReceiveEvent; +import com.github.retrooper.packetevents.manager.server.ServerVersion; +import com.github.retrooper.packetevents.netty.buffer.ByteBufHelper; import com.github.retrooper.packetevents.protocol.packettype.PacketType; -import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientEditBook; import me.xginko.aef.modules.packets.PacketModule; import me.xginko.aef.utils.PlatformUtil; +import java.nio.charset.StandardCharsets; + public class BookTitleDupe extends PacketModule { - private final int maxTitleChars; + private final int titleLimit, pageLimit, pageCharLimit; + private final boolean log, kick; public BookTitleDupe() { - super("dupe-preventions.book-title-dupe", PacketListenerPriority.HIGHEST); - config.addComment(configPath + ".enable", """ + super("dupe-preventions.book-title-dupe", true, PacketListenerPriority.HIGHEST,""" Relevant for 1.20.6 - 1.21: Will prevent players from sending book packets with a too large title, to get disconnected and their inventories restored."""); - this.maxTitleChars = config.getInt(configPath + ".max-title-charlength", 20, """ - Normal ascii like charlimit in vanilla is 15, you could need a bit more - if you want to support languages with special characters."""); + boolean modernLimits = PacketEvents.getAPI().getServerManager().getVersion().isNewerThanOrEquals(ServerVersion.V_1_21_2); + this.titleLimit = config.getInt(configPath + ".max-title-charlength", modernLimits ? 32 : 128); + this.pageLimit = config.getInt(configPath + ".max-pages", modernLimits ? 100 : 200); + this.pageCharLimit = config.getInt(configPath + ".max-page-charlength", modernLimits ? 1024 : 8192); + this.log = config.getBoolean(configPath + ".log", false); + this.kick = config.getBoolean(configPath + ".kick-player", false); } @Override @@ -31,11 +38,44 @@ public boolean shouldEnable() { public void onPacketReceive(PacketReceiveEvent event) { if (event.getPacketType() != PacketType.Play.Client.EDIT_BOOK) return; - WrapperPlayClientEditBook packet = new WrapperPlayClientEditBook(event); - if (packet.getTitle() == null) return; - - if (packet.getTitle().length() > maxTitleChars) { + if (isIllegalBookEdit(event)) { event.setCancelled(true); + onCancel(log, kick, event.getUser()); + } + } + + private boolean isIllegalBookEdit(PacketReceiveEvent event) { + int slot = ByteBufHelper.readVarInt(event.getByteBuf()); + + int pageCount = ByteBufHelper.readVarInt(event.getByteBuf()); + + if (pageCount > pageLimit) { + return true; + } + + for (int i = 0; i < pageCount; ++i) { + if (isStringTooBig(event.getByteBuf(), pageCharLimit)) { + return true; + } } + + if (ByteBufHelper.readByte(event.getByteBuf()) != 0) { + return isStringTooBig(event.getByteBuf(), titleLimit); + } + + return false; + } + + private boolean isStringTooBig(Object byteBuf, int charLimit) { + int strBufLen = ByteBufHelper.readVarInt(byteBuf); + + // Check if the received encoded string buffer length is shorter or longer than allowed + if (strBufLen < 0 || strBufLen > charLimit * 4) { + return true; + } + + // The received string length is longer than maximum allowed + return ByteBufHelper.toString(byteBuf, ByteBufHelper.readerIndex(byteBuf), strBufLen, StandardCharsets.UTF_8) + .length() > charLimit; } } diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/dupepreventions/ChestedEntitiesInPortals.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/dupepreventions/ChestedEntitiesInPortals.java index 6f66a62b1..a496477f8 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/dupepreventions/ChestedEntitiesInPortals.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/dupepreventions/ChestedEntitiesInPortals.java @@ -14,8 +14,7 @@ public class ChestedEntitiesInPortals extends AEFModule implements Listener { public ChestedEntitiesInPortals() { - super("dupe-preventions.prevent-chested-living-entities-in-portals"); - config.addComment(configPath, """ + super("dupe-preventions.prevent-chested-living-entities-in-portals", false, """ Prevents entities that can carry chests from using portals to\s block some common dupe tactics.\s CAUTION: Will remove chests and their contents from a chested\s @@ -39,9 +38,7 @@ public void disable() { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) private void onEntityPortalEvent(EntityPortalEvent event) { // Does not fire on folia due to broken API - if (!EntityUtil.isChestableHorse(event.getEntity())) return; - - if (((ChestedHorse) event.getEntity()).isCarryingChest()) { + if (EntityUtil.isChestableHorse(event.getEntity()) && ((ChestedHorse) event.getEntity()).isCarryingChest()) { event.setCancelled(true); } } diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/dupepreventions/ChestsOnEntities.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/dupepreventions/ChestsOnEntities.java index e1177a262..fa6d4d3ef 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/dupepreventions/ChestsOnEntities.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/dupepreventions/ChestsOnEntities.java @@ -12,7 +12,7 @@ public class ChestsOnEntities extends AEFModule implements Listener { public ChestsOnEntities() { - super("dupe-preventions.prevent-chests-on-living-entities"); + super("dupe-preventions.prevent-chests-on-living-entities", false); config.addComment(configPath, """ Prevent any possible dupes involving chested entities by making\s it impossible to put a chest on them.\s @@ -25,11 +25,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath, false); - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/dupepreventions/CloseEntityInventoriesOnLogout.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/dupepreventions/CloseEntityInventoriesOnLogout.java index c1010febf..485d21ea3 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/dupepreventions/CloseEntityInventoriesOnLogout.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/dupepreventions/CloseEntityInventoriesOnLogout.java @@ -14,7 +14,7 @@ public class CloseEntityInventoriesOnLogout extends AEFModule implements Listener { public CloseEntityInventoriesOnLogout() { - super("dupe-preventions.close-entity-inventories-on-player-disconnect"); + super("dupe-preventions.close-entity-inventories-on-player-disconnect", false); config.addComment(configPath, """ Closes open inventories of entities that disappeared when the\s player riding it disconnects."""); @@ -25,11 +25,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath, false); - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/dupepreventions/CloseEntityInventoryOnChunkUnload.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/dupepreventions/CloseEntityInventoryOnChunkUnload.java index c40811fe5..a0fefa25b 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/dupepreventions/CloseEntityInventoryOnChunkUnload.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/dupepreventions/CloseEntityInventoryOnChunkUnload.java @@ -14,7 +14,7 @@ public class CloseEntityInventoryOnChunkUnload extends AEFModule implements Listener { public CloseEntityInventoryOnChunkUnload() { - super("dupe-preventions.close-entity-inventories-on-chunk-unload"); + super("dupe-preventions.close-entity-inventories-on-chunk-unload", false); config.addComment(configPath, """ Closes open inventories of all entities that are in a chunk\s that will be unloaded."""); @@ -25,11 +25,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath, false); - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/elytra/ElytraAtSpawn.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/elytra/ElytraAtSpawn.java index 88398b527..832da60d7 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/elytra/ElytraAtSpawn.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/elytra/ElytraAtSpawn.java @@ -26,7 +26,7 @@ public class ElytraAtSpawn extends AEFModule implements Listener { private final boolean spawn_shouldCheckPermission, spawn_DenyElytra, spawn_DenyOnLowTPS, spawn_AlsoRemoveElytraOnLowTPS; public ElytraAtSpawn() { - super("elytra.elytra-speed.At-Spawn"); + super("elytra.elytra-speed.At-Spawn", false); config.addComment(configPath + ".enable", "Use separate values for players at spawn."); this.spawn_shouldCheckPermission = config.getBoolean(configPath + ".use-bypass-permission", false, diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/elytra/ElytraGlobal.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/elytra/ElytraGlobal.java index 678ca16a3..401e0fb94 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/elytra/ElytraGlobal.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/elytra/ElytraGlobal.java @@ -27,10 +27,7 @@ public class ElytraGlobal extends AEFModule implements Listener { global_DenyOnLowTPS, global_AlsoRemoveOnLowTPS; public ElytraGlobal() { - super("elytra.elytra-speed.Global-Settings"); - config.addComment("elytra.elytra-speed", - "NOTE: Set nocheatplus horizontal elytra settings to 500 or higher."); - config.addComment(configPath + ".enable", + super("elytra.elytra-speed.Global-Settings", false, "Global settings. If nothing else is enabled, this will be used for all environments."); this.global_shouldCheckPermission = config.getBoolean(configPath + ".use-bypass-permission", false, "Can be slow with a lot of players. Enable only if needed."); @@ -52,11 +49,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.elytra_enable_global; - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/elytra/ElytraHelper.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/elytra/ElytraHelper.java index cc8474676..252d40c3c 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/elytra/ElytraHelper.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/elytra/ElytraHelper.java @@ -32,17 +32,16 @@ public class ElytraHelper extends AEFModule implements Runnable, PacketListener, Listener { private static ElytraHelper instance; - private final Map playerDataMap; - private final PacketListenerAbstract packetListener; + private final long speed_as_ticks = config.elytra_speed_calc_period / 50L; + + private Map playerDataMap; + private PacketListenerAbstract packetListener; private ScheduledExecutorService executorService; private ScheduledFuture scheduledTask; - private final long speed_as_ticks = config.elytra_speed_calc_period / 50L; public ElytraHelper() { super("elytra.elytra-speed"); instance = this; - playerDataMap = new ConcurrentHashMap<>(); - packetListener = asAbstract(PacketListenerPriority.MONITOR); } public static ElytraHelper getInstance() { @@ -51,6 +50,8 @@ public static ElytraHelper getInstance() { @Override public void enable() { + playerDataMap = new ConcurrentHashMap<>(); + packetListener = asAbstract(PacketListenerPriority.MONITOR); plugin.getServer().getPluginManager().registerEvents(this, plugin); PacketEvents.getAPI().getEventManager().registerListener(packetListener); executorService = Executors.newScheduledThreadPool(1); @@ -66,9 +67,22 @@ public boolean shouldEnable() { @Override public void disable() { HandlerList.unregisterAll(this); - PacketEvents.getAPI().getEventManager().unregisterListener(packetListener); - if (scheduledTask != null) scheduledTask.cancel(true); - if (executorService != null) executorService.shutdown(); + if (packetListener != null) { + PacketEvents.getAPI().getEventManager().unregisterListener(packetListener); + packetListener = null; + } + if (playerDataMap != null) { + playerDataMap.clear(); + playerDataMap = null; + } + if (scheduledTask != null) { + scheduledTask.cancel(true); + scheduledTask = null; + } + if (executorService != null) { + executorService.close(); + executorService = null; + } } @Override diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/elytra/ElytraOnCeiling.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/elytra/ElytraOnCeiling.java index ecc8aea22..fc3aeb514 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/elytra/ElytraOnCeiling.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/elytra/ElytraOnCeiling.java @@ -27,8 +27,7 @@ public class ElytraOnCeiling extends AEFModule implements Listener { ceiling_DenyElytra, ceiling_EnableBursting, ceiling_DenyOnLowTPS, ceiling_AlsoRemoveOnLowTPS; public ElytraOnCeiling() { - super("elytra.elytra-speed.Nether-Ceiling"); - config.addComment(configPath + ".enable", + super("elytra.elytra-speed.Nether-Ceiling", false, "Use separate values for players above the nether ceiling."); this.ceiling_shouldCheckPermission = config.getBoolean(configPath + ".use-bypass-permission", false, "Can be slow with a lot of players. Enable only if needed."); diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/elytra/ElytraPacketFly.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/elytra/ElytraPacketFly.java index 0e4da8f4e..36443bf64 100644 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/elytra/ElytraPacketFly.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/elytra/ElytraPacketFly.java @@ -20,14 +20,15 @@ public class ElytraPacketFly extends AEFModule implements Listener { - private final Cache elytraOpenCounts; + private final long durationMillis; private final int maxElytraOpensPerTime; private final boolean notify, kickPlayer; + private Cache elytraOpenCounts; + public ElytraPacketFly() { - super("elytra.packet-elytra-fly"); - config.addComment(configPath + ".patch-packet-elytra-fly", """ - Patches the future/rusherhack/kamiblue 2b2t elytra fly exploit."""); + super("elytra.packet-elytra-fly", false, """ + Cheap patch for future/rusherhack/kamiblue 2b2t elytra fly exploit."""); this.maxElytraOpensPerTime = Math.max(1, config.getInt(configPath + ".max-elytra-opens-per-time", 25, """ The fly exploit causes the player to constantly toggle gliding.\s If too many glide toggles occur within a timeframe, they are\s @@ -35,10 +36,8 @@ public ElytraPacketFly() { Still may trigger false positives when players are jumping and\s sprinting with elytra equipped, so recommended to play around\s with the values.""")); - this.elytraOpenCounts = Caffeine.newBuilder().expireAfterWrite(Duration.ofSeconds(Math.max(1, - config.getInt(configPath + ".time-in-seconds", 8, """ - Time in seconds a elytra open count will be remembered by the plugin.""") - ))).build(); + this.durationMillis = Math.max(1, config.getInt(configPath + ".time-in-seconds", 8, """ + Time in seconds a elytra open count will be remembered by the plugin.""")); this.notify = config.getBoolean(configPath + ".notify-player-to-disable-packetfly", true, """ Configure message in lang folder."""); this.kickPlayer = config.getBoolean(configPath + ".kick-instead-of-remove-elytra", false, """ @@ -48,17 +47,17 @@ public ElytraPacketFly() { @Override public void enable() { + elytraOpenCounts = Caffeine.newBuilder().expireAfterWrite(Duration.ofMillis(durationMillis)).build(); plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".patch-packet-elytra-fly", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); + if (elytraOpenCounts != null) { + elytraOpenCounts.invalidateAll(); + elytraOpenCounts.cleanUp(); + } } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/BannedItemNames.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/BannedItemNames.java index 085b417f0..9269f4ff9 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/BannedItemNames.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/BannedItemNames.java @@ -31,13 +31,12 @@ public class BannedItemNames extends IllegalItemModule { private final boolean delete; public BannedItemNames() { - super("illegals.banned-item-names", AEFPermission.BYPASS_ILLEGAL_BANNEDNAME); - config.addComment(configPath + ".enable", - "Bypass permission: " + bypassPermission.string() + "\n" + - "Resets an item's name (or deletes the item) if it matches one of\n" + - "the configured regexes.\n" + - "Regexes can be complex. Use a tool like https://regex101.com/ or\n" + - "ChatGPT for good results."); + super("illegals.banned-item-names", false, AEFPermission.BYPASS_ILLEGAL_BANNEDNAME, + "Bypass permission: " + AEFPermission.BYPASS_ILLEGAL_BANNEDNAME.string() + "\n" + + "Resets an item's name (or deletes the item) if it matches one of\n" + + "the configured regexes.\n" + + "Regexes can be complex. Use a tool like https://regex101.com/ or\n" + + "ChatGPT for good results."); this.delete = config.getBoolean(configPath + ".delete-item", false, "Will delete the item instead of resetting the name."); this.bannedRegex = config.getList(configPath + ".regex", List.of("(?i)illegalstring")) @@ -74,11 +73,6 @@ private void onPrepareResult(PrepareResultEvent event) { } } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public @NotNull ItemLegality legalityOf(@Nullable ItemStack itemStack) { if ( diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/BannedMaterials.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/BannedMaterials.java index 838dfd9d0..612413607 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/BannedMaterials.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/BannedMaterials.java @@ -23,9 +23,8 @@ public class BannedMaterials extends IllegalItemModule { private final boolean checkStored; public BannedMaterials() { - super("illegals.ban-specific-materials", AEFPermission.BYPASS_ILLEGAL_BANNEDMATERIAL); - config.addComment(configPath + ".enable", - "Bypass permission: " + bypassPermission.string() + "\n" + + super("illegals.ban-specific-materials", false, AEFPermission.BYPASS_ILLEGAL_BANNEDMATERIAL, + "Bypass permission: " + AEFPermission.BYPASS_ILLEGAL_BANNEDMATERIAL.string() + "\n" + "Prevents usage of or deletes items with material that you do not want\n" + "your players to be able to use.\n" + "Useful if your players have blocks that shouldn't be obtainable in survival."); @@ -44,7 +43,7 @@ public BannedMaterials() { XMaterial.NETHER_PORTAL, XMaterial.LIGHT) .filter(XMaterial::isSupported) - .map(XMaterial::parseMaterial) + .map(XMaterial::get) .map(Enum::name) .collect(Collectors.toList()); this.bannedMaterials = config.getList(configPath + ".banned-materials", defaults) @@ -61,11 +60,6 @@ public BannedMaterials() { .collect(Collectors.toCollection(() -> EnumSet.noneOf(Material.class))); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public @NotNull ItemLegality legalityOf(@Nullable ItemStack itemStack) { if (itemStack == null) { diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/IllegalItemModule.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/IllegalItemModule.java index 35fbb8d67..33456994a 100644 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/IllegalItemModule.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/IllegalItemModule.java @@ -59,7 +59,11 @@ public abstract class IllegalItemModule extends AEFModule implements Listener { private final Function, @PolyNull ExpiringSet> createIfAbsent; public IllegalItemModule(String configPath, AEFPermission bypassPermission) { - super(configPath); + this(configPath, false, bypassPermission, null); + } + + public IllegalItemModule(String configPath, boolean defEnabled, AEFPermission bypassPermission, String comment) { + super(configPath, defEnabled, comment); this.bypassPermission = bypassPermission; this.optionalListeners = new HashSet<>(); @@ -175,6 +179,8 @@ public void disable() { HandlerList.unregisterAll(this); optionalListeners.forEach(HandlerList::unregisterAll); optionalListeners.clear(); + listenerCooldowns.asMap().clear(); + listenerCooldowns.cleanUp(); } public ItemLegality legalityOf(@Nullable Iterable itemStacks) { diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/IllegalPotions.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/IllegalPotions.java index 2383479cf..0f7ead35b 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/IllegalPotions.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/IllegalPotions.java @@ -15,19 +15,13 @@ public class IllegalPotions extends IllegalItemModule { private final boolean checkStored; public IllegalPotions() { - super("illegals.potions", AEFPermission.BYPASS_ILLEGAL_POTIONS); - config.addComment(configPath + ".enable", - "Bypass permission: " + bypassPermission.string() + "\n" + - "Prevents usage of or reverts items with any attribute modifiers\n" + - "or item flags."); + super("illegals.potions", false, AEFPermission.BYPASS_ILLEGAL_POTIONS, + "Bypass permission: " + AEFPermission.BYPASS_ILLEGAL_POTIONS.string() + "\n" + + "Prevents usage of or reverts items with any attribute modifiers\n" + + "or item flags."); this.checkStored = config.getBoolean(configPath + ".check-stored-items", false); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public @NotNull ItemLegality legalityOf(@Nullable ItemStack itemStack) { if (itemStack == null || !MaterialUtil.POTIONS.contains(itemStack.getType()) || !itemStack.hasItemMeta()) { diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/InvalidStackSize.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/InvalidStackSize.java index 9e8694eb0..081e8bed2 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/InvalidStackSize.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/InvalidStackSize.java @@ -1,5 +1,6 @@ package me.xginko.aef.modules.illegals.items; +import com.cryptomorin.xseries.XMaterial; import me.xginko.aef.enums.AEFPermission; import me.xginko.aef.enums.IllegalHandling; import me.xginko.aef.enums.ItemLegality; @@ -21,15 +22,14 @@ public class InvalidStackSize extends IllegalItemModule { private final boolean useWhitelist, blacklistMode, checkStored; public InvalidStackSize() { - super("illegals.illegally-stacked-items", AEFPermission.BYPASS_ILLEGAL_OVERSTACKED); - config.addComment(configPath + ".enable", - "Bypass permission: " + bypassPermission.string() + "\n" + - "Prevents usage of or reverts items with a higher or lower\n" + - "stack size than their vanilla limit."); + super("illegals.illegally-stacked-items", false, AEFPermission.BYPASS_ILLEGAL_OVERSTACKED, + "Bypass permission: " + AEFPermission.BYPASS_ILLEGAL_OVERSTACKED.string() + "\n" + + "Prevents usage of or reverts items with a higher or lower\n" + + "stack size than their vanilla limit."); this.useWhitelist = config.getBoolean(configPath + ".item-whitelist-enabled", false); this.blacklistMode = config.getBoolean(configPath + ".use-as-blacklist-instead", true); this.checkStored = config.getBoolean(configPath + ".check-stored-items", false); - this.whitelistedTypes = config.getList(configPath + ".whitelisted-items", List.of("TOTEM_OF_UNDYING")) + this.whitelistedTypes = config.getList(configPath + ".whitelisted-items", List.of(XMaterial.TOTEM_OF_UNDYING.get().name())) .stream() .map(configuredType -> { try { @@ -43,11 +43,6 @@ public InvalidStackSize() { .collect(Collectors.toCollection(() -> EnumSet.noneOf(Material.class))); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public @NotNull ItemLegality legalityOf(@Nullable ItemStack itemStack) { if (itemStack == null || itemStack.getType().isAir()) { diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/ItemAttributes.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/ItemAttributes.java index df8637b82..71c9abec2 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/ItemAttributes.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/ItemAttributes.java @@ -1,5 +1,6 @@ package me.xginko.aef.modules.illegals.items; +import com.cryptomorin.xseries.XMaterial; import me.xginko.aef.enums.AEFPermission; import me.xginko.aef.enums.IllegalHandling; import me.xginko.aef.enums.ItemLegality; @@ -23,15 +24,14 @@ public class ItemAttributes extends IllegalItemModule { private final boolean useWhitelist, blacklistMode, checkStored; public ItemAttributes() { - super("illegals.attribute-modifiers", AEFPermission.BYPASS_ILLEGAL_ATTRIBUTES); - config.addComment(configPath + ".enable", - "Bypass permission: " + bypassPermission.string() + "\n" + + super("illegals.attribute-modifiers", false, AEFPermission.BYPASS_ILLEGAL_ATTRIBUTES, + "Bypass permission: " + AEFPermission.BYPASS_ILLEGAL_ATTRIBUTES.string() + "\n" + "Prevents usage of or reverts items with any attribute modifiers\n" + "or item flags."); this.useWhitelist = config.getBoolean(configPath + ".item-whitelist-enabled", false); this.blacklistMode = config.getBoolean(configPath + ".use-as-blacklist-instead", true); this.checkStored = config.getBoolean(configPath + ".check-stored-items", false); - this.whitelistedTypes = config.getList(configPath + ".whitelisted-items", List.of("TOTEM_OF_UNDYING")) + this.whitelistedTypes = config.getList(configPath + ".whitelisted-items", List.of(XMaterial.TOTEM_OF_UNDYING.get().name())) .stream() .map(configuredType -> { try { @@ -45,11 +45,6 @@ public ItemAttributes() { .collect(Collectors.toCollection(() -> EnumSet.noneOf(Material.class))); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public @NotNull ItemLegality legalityOf(@Nullable ItemStack itemStack) { if (itemStack == null || itemStack.getType().isAir() || !itemStack.hasItemMeta()) { diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/PlayerHeads.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/PlayerHeads.java index 4fe7f19e7..c27b1abe3 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/PlayerHeads.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/PlayerHeads.java @@ -14,19 +14,13 @@ public class PlayerHeads extends IllegalItemModule { private final boolean checkStored; public PlayerHeads() { - super("illegals.ban-player-heads", AEFPermission.BYPASS_ILLEGAL_PLAYERHEAD); - config.addComment(configPath + ".enable", - "Bypass permission: " + bypassPermission.string() + "\n" + + super("illegals.ban-player-heads", false, AEFPermission.BYPASS_ILLEGAL_PLAYERHEAD, + "Bypass permission: " + AEFPermission.BYPASS_ILLEGAL_PLAYERHEAD.string() + "\n" + "Deletes or prevents usage of player heads."); this.checkStored = config.getBoolean(configPath + ".check-stored-items", false, "Will delete shulker/bundle if they contain any player heads."); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public @NotNull ItemLegality legalityOf(@Nullable ItemStack itemStack) { if (itemStack == null) { diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/SpawnEggs.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/SpawnEggs.java index 2ffeb7c01..0696ed396 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/SpawnEggs.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/SpawnEggs.java @@ -23,15 +23,14 @@ public class SpawnEggs extends IllegalItemModule { private final boolean checkStored; public SpawnEggs() { - super("illegals.ban-spawn-eggs", AEFPermission.BYPASS_ILLEGAL_SPAWNEGG); - config.addComment(configPath + ".enable", - "Bypass permission: " + bypassPermission.string() + "\n" + + super("illegals.ban-spawn-eggs", false, AEFPermission.BYPASS_ILLEGAL_SPAWNEGG, + "Bypass permission: " + AEFPermission.BYPASS_ILLEGAL_SPAWNEGG.string() + "\n" + "Deletes or prevents usage of spawn eggs."); this.checkStored = config.getBoolean(configPath + ".check-stored-items", false, """ If remove-spawn-eggs is set to true Will delete shulker/bundle\s should they contain any spawneggs."""); this.whitelistedTypes = config.getList(configPath + ".whitelisted-items", - Collections.singletonList(XMaterial.VILLAGER_SPAWN_EGG.parseMaterial().name())) + Collections.singletonList(XMaterial.VILLAGER_SPAWN_EGG.get().name())) .stream() .map(configuredType -> { try { @@ -45,11 +44,6 @@ public SpawnEggs() { .collect(Collectors.toCollection(() -> EnumSet.noneOf(Material.class))); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public @NotNull ItemLegality legalityOf(@Nullable ItemStack itemStack) { if (itemStack == null || whitelistedTypes.contains(itemStack.getType())) { diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/Unbreakables.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/Unbreakables.java index 895d40224..57bbc635c 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/Unbreakables.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/Unbreakables.java @@ -1,5 +1,6 @@ package me.xginko.aef.modules.illegals.items; +import com.cryptomorin.xseries.XMaterial; import me.xginko.aef.enums.AEFPermission; import me.xginko.aef.enums.IllegalHandling; import me.xginko.aef.enums.ItemLegality; @@ -23,19 +24,18 @@ public class Unbreakables extends IllegalItemModule { private final boolean useWhitelist, blacklistMode, checkStored; public Unbreakables() { - super("illegals.revert-unbreakables", AEFPermission.BYPASS_ILLEGAL_UNBREAKABLE); - config.addComment(configPath + ".enable", - "Bypass permission: " + bypassPermission.string() + "\n" + - "Deletes and prevents usage of unbreakable items.\n" + - "This can be anything from items with illegal damage attributes to\n" + - "Metadata/NBT tags.\n" + - "Note: Due to the limitations of the API, we can only fully prevent\n" + - "usage of these items by deleting them."); + super("illegals.revert-unbreakables", false, AEFPermission.BYPASS_ILLEGAL_UNBREAKABLE, + "Bypass permission: " + AEFPermission.BYPASS_ILLEGAL_UNBREAKABLE.string() + "\n" + + "Deletes and prevents usage of unbreakable items.\n" + + "This can be anything from items with illegal damage attributes to\n" + + "Metadata/NBT tags.\n" + + "Note: Due to the limitations of the API, we can only fully prevent\n" + + "usage of these items by deleting them."); this.useWhitelist = config.getBoolean(configPath + ".item-whitelist-enabled", false); this.blacklistMode = config.getBoolean(configPath + ".use-as-blacklist-instead", false); this.checkStored = config.getBoolean(configPath + ".check-stored-items", false, "Will delete shulkers and bundles if they contain unbreakables."); - this.whitelistedTypes = config.getList(configPath + ".whitelisted-items", List.of("DIAMOND_CHESTPLATE")) + this.whitelistedTypes = config.getList(configPath + ".whitelisted-items", List.of(XMaterial.DIAMOND_CHESTPLATE.get().name())) .stream() .map(configuredType -> { try { @@ -49,11 +49,6 @@ public Unbreakables() { .collect(Collectors.toCollection(() -> EnumSet.noneOf(Material.class))); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public @NotNull ItemLegality legalityOf(@Nullable ItemStack itemStack) { if (itemStack == null || itemStack.getType().isAir() || !itemStack.hasItemMeta()) { diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/enchantments/HigherEnchants.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/enchantments/HigherEnchants.java index d1bab08d6..abeca8278 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/enchantments/HigherEnchants.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/enchantments/HigherEnchants.java @@ -1,5 +1,7 @@ package me.xginko.aef.modules.illegals.items.enchantments; +import com.cryptomorin.xseries.XEnchantment; +import com.cryptomorin.xseries.XMaterial; import me.xginko.aef.enums.AEFPermission; import me.xginko.aef.enums.IllegalHandling; import me.xginko.aef.enums.ItemLegality; @@ -16,6 +18,7 @@ import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; @@ -25,27 +28,28 @@ public class HigherEnchants extends IllegalItemModule { private final Set whitelistedTypes; private final boolean useWhitelist, blacklistMode, checkStored, onlySomeEnchants; - @SuppressWarnings("deprecation") public HigherEnchants() { - super("illegals.enchantments.higher-enchants", AEFPermission.BYPASS_ILLEGAL_ENCHANT_HIGHER); - config.addComment(configPath + ".enable", - "Bypass permission: " + bypassPermission.string() + "\n" + + super("illegals.enchantments.higher-enchants", false, AEFPermission.BYPASS_ILLEGAL_ENCHANT_HIGHER, + "Bypass permission: " + AEFPermission.BYPASS_ILLEGAL_ENCHANT_HIGHER.string() + "\n" + "Reverts or prevents usage of ItemStacks with Enchantments higher\n" + "than the natural, in vanilla survival obtainable level (aka 32ks / 255s)."); this.checkStored = config.getBoolean(configPath + ".check-stored-items", false); this.onlySomeEnchants = config.getBoolean(configPath + ".only-specific-enchants", false); - this.specificEnchants = config.getList(configPath + ".specific-enchants", List.of("DIG_SPEED")) + this.specificEnchants = config.getList(configPath + ".specific-enchants", List.of(XEnchantment.EFFICIENCY.get().getName())) .stream() .map(configuredEnchant -> { - final Enchantment enchantment = Enchantment.getByName(configuredEnchant); - if (enchantment == null) notRecognized(Enchantment.class, configuredEnchant); - return enchantment; + Optional enchantment = XEnchantment.of(configuredEnchant); + if (enchantment.isEmpty()) { + notRecognized(Enchantment.class, configuredEnchant); + return null; + } + return enchantment.get().get(); }) .filter(Objects::nonNull) .collect(Collectors.toCollection(HashSet::new)); this.useWhitelist = config.getBoolean(configPath + ".item-whitelist-enabled", true); this.blacklistMode = config.getBoolean(configPath + ".use-as-blacklist-instead", false); - this.whitelistedTypes = config.getList(configPath + ".whitelisted-items", List.of("GOLDEN_APPLE")) + this.whitelistedTypes = config.getList(configPath + ".whitelisted-items", List.of(XMaterial.GOLDEN_APPLE.get().name())) .stream() .map(configuredType -> { try { @@ -59,11 +63,6 @@ public HigherEnchants() { .collect(Collectors.toCollection(() -> EnumSet.noneOf(Material.class))); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public @NotNull ItemLegality legalityOf(@Nullable ItemStack itemStack) { if (itemStack == null || itemStack.getType().isAir()) { diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/enchantments/InapplicableEnchants.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/enchantments/InapplicableEnchants.java index dde4d37d1..f30c4a65c 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/enchantments/InapplicableEnchants.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/enchantments/InapplicableEnchants.java @@ -1,5 +1,6 @@ package me.xginko.aef.modules.illegals.items.enchantments; +import com.cryptomorin.xseries.XMaterial; import me.xginko.aef.enums.AEFPermission; import me.xginko.aef.enums.IllegalHandling; import me.xginko.aef.enums.ItemLegality; @@ -24,16 +25,15 @@ public class InapplicableEnchants extends IllegalItemModule { private final boolean useWhitelist, blacklistMode, checkStored; public InapplicableEnchants() { - super("illegals.enchantments.inapplicable-enchants", AEFPermission.BYPASS_ILLEGAL_ENCHANT_INAPPLICABLE); - config.addComment(configPath + ".enable", - "Bypass permission: " + bypassPermission.string() + "\n" + + super("illegals.enchantments.inapplicable-enchants", false, AEFPermission.BYPASS_ILLEGAL_ENCHANT_INAPPLICABLE, + "Bypass permission: " + AEFPermission.BYPASS_ILLEGAL_ENCHANT_INAPPLICABLE.string() + "\n" + "Reverts or prevents usage of ItemStacks with Enchantments that\n" + "cannot be applied to that ItemStack in vanilla survival minecraft.\n" + "Examples: A helmet with sharpness or a block of stone with fortune."); this.checkStored = config.getBoolean(configPath + ".check-stored-items", false); this.useWhitelist = config.getBoolean(configPath + ".item-whitelist-enabled", true); this.blacklistMode = config.getBoolean(configPath + ".use-as-blacklist-instead", false); - this.whitelistedTypes = config.getList(configPath + ".whitelisted-items", List.of("GOLDEN_APPLE")) + this.whitelistedTypes = config.getList(configPath + ".whitelisted-items", List.of(XMaterial.GOLDEN_APPLE.get().name())) .stream() .map(configuredType -> { try { @@ -47,11 +47,6 @@ public InapplicableEnchants() { .collect(Collectors.toCollection(() -> EnumSet.noneOf(Material.class))); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public @NotNull ItemLegality legalityOf(@Nullable ItemStack itemStack) { if (itemStack == null || itemStack.getType().isAir()) { diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/enchantments/IncompatibleEnchants.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/enchantments/IncompatibleEnchants.java index 4a2f981e6..268ab0f43 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/enchantments/IncompatibleEnchants.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/enchantments/IncompatibleEnchants.java @@ -1,5 +1,7 @@ package me.xginko.aef.modules.illegals.items.enchantments; +import com.cryptomorin.xseries.XEnchantment; +import com.cryptomorin.xseries.XMaterial; import me.xginko.aef.enums.AEFPermission; import me.xginko.aef.enums.IllegalHandling; import me.xginko.aef.enums.ItemLegality; @@ -17,27 +19,6 @@ import java.util.Set; import java.util.stream.Collectors; -import static com.cryptomorin.xseries.XEnchantment.BANE_OF_ARTHROPODS; -import static com.cryptomorin.xseries.XEnchantment.BINDING_CURSE; -import static com.cryptomorin.xseries.XEnchantment.BLAST_PROTECTION; -import static com.cryptomorin.xseries.XEnchantment.CHANNELING; -import static com.cryptomorin.xseries.XEnchantment.DEPTH_STRIDER; -import static com.cryptomorin.xseries.XEnchantment.FIRE_PROTECTION; -import static com.cryptomorin.xseries.XEnchantment.FORTUNE; -import static com.cryptomorin.xseries.XEnchantment.FROST_WALKER; -import static com.cryptomorin.xseries.XEnchantment.INFINITY; -import static com.cryptomorin.xseries.XEnchantment.LOYALTY; -import static com.cryptomorin.xseries.XEnchantment.MENDING; -import static com.cryptomorin.xseries.XEnchantment.MULTISHOT; -import static com.cryptomorin.xseries.XEnchantment.PIERCING; -import static com.cryptomorin.xseries.XEnchantment.PROJECTILE_PROTECTION; -import static com.cryptomorin.xseries.XEnchantment.PROTECTION; -import static com.cryptomorin.xseries.XEnchantment.RIPTIDE; -import static com.cryptomorin.xseries.XEnchantment.SHARPNESS; -import static com.cryptomorin.xseries.XEnchantment.SILK_TOUCH; -import static com.cryptomorin.xseries.XEnchantment.SMITE; -import static com.cryptomorin.xseries.XEnchantment.VANISHING_CURSE; - public class IncompatibleEnchants extends IllegalItemModule { private final Set whitelistedTypes; @@ -45,20 +26,19 @@ public class IncompatibleEnchants extends IllegalItemModule { private final boolean useWhitelist, blacklistMode, checkStored; public IncompatibleEnchants() { - super("illegals.enchantments.incompatible-enchants", AEFPermission.BYPASS_ILLEGAL_ENCHANT_INCOMPATIBLE); - this.damageEnchants = new Enchantment[]{SHARPNESS.getEnchant(), SMITE.getEnchant(), BANE_OF_ARTHROPODS.getEnchant()}; - this.protectionEnchants = new Enchantment[]{PROTECTION.getEnchant(), BLAST_PROTECTION.getEnchant(), - FIRE_PROTECTION.getEnchant(), PROJECTILE_PROTECTION.getEnchant()}; - config.addComment(configPath + ".enable", - "Bypass permission: " + bypassPermission.string() + "\n" + + super("illegals.enchantments.incompatible-enchants", false, AEFPermission.BYPASS_ILLEGAL_ENCHANT_INCOMPATIBLE, + "Bypass permission: " + AEFPermission.BYPASS_ILLEGAL_ENCHANT_INCOMPATIBLE.string() + "\n" + "Reverts or prevents usage of ItemStacks with Enchantments that\n" + "cannot coexist in vanilla survival minecraft.\n" + "Examples: A bow with mending and infinity or armor with every\n" + "protection enchantment."); + this.damageEnchants = new Enchantment[]{XEnchantment.SHARPNESS.get(), XEnchantment.SMITE.get(), XEnchantment.BANE_OF_ARTHROPODS.get()}; + this.protectionEnchants = new Enchantment[]{XEnchantment.PROTECTION.get(), XEnchantment.BLAST_PROTECTION.get(), + XEnchantment.FIRE_PROTECTION.get(), XEnchantment.PROJECTILE_PROTECTION.get()}; this.checkStored = config.getBoolean(configPath + ".check-stored-items", false); this.useWhitelist = config.getBoolean(configPath + ".item-whitelist-enabled", true); this.blacklistMode = config.getBoolean(configPath + ".use-as-blacklist-instead", false); - this.whitelistedTypes = config.getList(configPath + ".whitelisted-items", Collections.singletonList("BOW")) + this.whitelistedTypes = config.getList(configPath + ".whitelisted-items", Collections.singletonList(XMaterial.BOW.get().name())) .stream() .map(configuredType -> { try { @@ -87,18 +67,18 @@ public boolean shouldEnable() { final Set enchantments = itemStack.getEnchantments().keySet(); if (!enchantments.isEmpty()) { - if (enchantments.contains(SILK_TOUCH.getEnchant()) && enchantments.contains(FORTUNE.getEnchant())) + if (enchantments.contains(XEnchantment.SILK_TOUCH.get()) && enchantments.contains(XEnchantment.FORTUNE.get())) return ItemLegality.ILLEGAL; - if (enchantments.contains(DEPTH_STRIDER.getEnchant()) && enchantments.contains(FROST_WALKER.getEnchant())) + if (enchantments.contains(XEnchantment.DEPTH_STRIDER.get()) && enchantments.contains(XEnchantment.FROST_WALKER.get())) return ItemLegality.ILLEGAL; - if (enchantments.contains(INFINITY.getEnchant()) && enchantments.contains(MENDING.getEnchant())) + if (enchantments.contains(XEnchantment.INFINITY.get()) && enchantments.contains(XEnchantment.MENDING.get())) return ItemLegality.ILLEGAL; - if (enchantments.contains(BINDING_CURSE.getEnchant()) && enchantments.contains(VANISHING_CURSE.getEnchant())) + if (enchantments.contains(XEnchantment.BINDING_CURSE.get()) && enchantments.contains(XEnchantment.VANISHING_CURSE.get())) return ItemLegality.ILLEGAL; - if (enchantments.contains(RIPTIDE.getEnchant()) - && (enchantments.contains(LOYALTY.getEnchant()) || enchantments.contains(CHANNELING.getEnchant()))) + if (enchantments.contains(XEnchantment.RIPTIDE.get()) + && (enchantments.contains(XEnchantment.LOYALTY.get()) || enchantments.contains(XEnchantment.CHANNELING.get()))) return ItemLegality.ILLEGAL; - if (enchantments.contains(MULTISHOT.getEnchant()) && enchantments.contains(PIERCING.getEnchant())) + if (enchantments.contains(XEnchantment.MULTISHOT.get()) && enchantments.contains(XEnchantment.PIERCING.get())) return ItemLegality.ILLEGAL; int dmgEnchCount = 0; @@ -142,43 +122,43 @@ public void handleItem(ItemStack itemStack, ItemLegality legality) { final Set enchantments = itemStack.getEnchantments().keySet(); - if (enchantments.contains(SILK_TOUCH.getEnchant()) && enchantments.contains(FORTUNE.getEnchant())) - itemStack.removeEnchantment(FORTUNE.getEnchant()); - if (enchantments.contains(DEPTH_STRIDER.getEnchant()) && enchantments.contains(FROST_WALKER.getEnchant())) - itemStack.removeEnchantment(FROST_WALKER.getEnchant()); - if (enchantments.contains(INFINITY.getEnchant()) && enchantments.contains(MENDING.getEnchant())) - itemStack.removeEnchantment(INFINITY.getEnchant()); - if (enchantments.contains(BINDING_CURSE.getEnchant()) && enchantments.contains(VANISHING_CURSE.getEnchant())) - itemStack.removeEnchantment(BINDING_CURSE.getEnchant()); - if (enchantments.contains(MULTISHOT.getEnchant()) && enchantments.contains(PIERCING.getEnchant())) - itemStack.removeEnchantment(MULTISHOT.getEnchant()); - if (enchantments.contains(RIPTIDE.getEnchant()) && (enchantments.contains(LOYALTY.getEnchant()) || enchantments.contains(CHANNELING.getEnchant()))) - itemStack.removeEnchantment(RIPTIDE.getEnchant()); - - if (enchantments.contains(SHARPNESS.getEnchant())) { // Prefer keeping sharpness enchantment if present + if (enchantments.contains(XEnchantment.SILK_TOUCH.get()) && enchantments.contains(XEnchantment.FORTUNE.get())) + itemStack.removeEnchantment(XEnchantment.FORTUNE.get()); + if (enchantments.contains(XEnchantment.DEPTH_STRIDER.get()) && enchantments.contains(XEnchantment.FROST_WALKER.get())) + itemStack.removeEnchantment(XEnchantment.FROST_WALKER.get()); + if (enchantments.contains(XEnchantment.INFINITY.get()) && enchantments.contains(XEnchantment.MENDING.get())) + itemStack.removeEnchantment(XEnchantment.INFINITY.get()); + if (enchantments.contains(XEnchantment.BINDING_CURSE.get()) && enchantments.contains(XEnchantment.VANISHING_CURSE.get())) + itemStack.removeEnchantment(XEnchantment.BINDING_CURSE.get()); + if (enchantments.contains(XEnchantment.MULTISHOT.get()) && enchantments.contains(XEnchantment.PIERCING.get())) + itemStack.removeEnchantment(XEnchantment.MULTISHOT.get()); + if (enchantments.contains(XEnchantment.RIPTIDE.get()) && (enchantments.contains(XEnchantment.LOYALTY.get()) || enchantments.contains(XEnchantment.CHANNELING.get()))) + itemStack.removeEnchantment(XEnchantment.RIPTIDE.get()); + + if (enchantments.contains(XEnchantment.SHARPNESS.get())) { // Prefer keeping sharpness enchantment if present for (Enchantment dmgEnchant : damageEnchants) { - if (dmgEnchant != SHARPNESS.getEnchant()) { + if (dmgEnchant != XEnchantment.SHARPNESS.get()) { itemStack.removeEnchantment(dmgEnchant); } } - } else if (enchantments.contains(BANE_OF_ARTHROPODS.getEnchant()) && enchantments.contains(SMITE.getEnchant())) { - itemStack.removeEnchantment(BANE_OF_ARTHROPODS.getEnchant()); + } else if (enchantments.contains(XEnchantment.BANE_OF_ARTHROPODS.get()) && enchantments.contains(XEnchantment.SMITE.get())) { + itemStack.removeEnchantment(XEnchantment.BANE_OF_ARTHROPODS.get()); } - if (enchantments.contains(PROTECTION.getEnchant())) { // Prefer keeping protection enchantment if present + if (enchantments.contains(XEnchantment.PROTECTION.get())) { // Prefer keeping protection enchantment if present for (Enchantment protEnchant : protectionEnchants) { - if (protEnchant != PROTECTION.getEnchant()) { + if (protEnchant != XEnchantment.PROTECTION.get()) { itemStack.removeEnchantment(protEnchant); } } - } else if (enchantments.contains(BLAST_PROTECTION.getEnchant())) { // If protection isn't present, prefer blast protection + } else if (enchantments.contains(XEnchantment.BLAST_PROTECTION.get())) { // If protection isn't present, prefer blast protection for (Enchantment protEnchant : protectionEnchants) { - if (protEnchant != BLAST_PROTECTION.getEnchant()) { + if (protEnchant != XEnchantment.BLAST_PROTECTION.get()) { itemStack.removeEnchantment(protEnchant); } } - } else if (enchantments.contains(PROJECTILE_PROTECTION.getEnchant()) && enchantments.contains(FIRE_PROTECTION.getEnchant())) { - itemStack.removeEnchantment(FIRE_PROTECTION.getEnchant()); // If protection and blast protection is not present, prefer projectile protection + } else if (enchantments.contains(XEnchantment.PROJECTILE_PROTECTION.get()) && enchantments.contains(XEnchantment.FIRE_PROTECTION.get())) { + itemStack.removeEnchantment(XEnchantment.FIRE_PROTECTION.get()); // If protection and blast protection is not present, prefer projectile protection } } } \ No newline at end of file diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/nbt/CommandItems.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/nbt/CommandItems.java index c99c3d724..2b9788321 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/nbt/CommandItems.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/nbt/CommandItems.java @@ -14,20 +14,14 @@ public class CommandItems extends IllegalItemModule { private final boolean checkStored; public CommandItems() { - super("illegals.nbt.command-items", AEFPermission.BYPASS_ILLEGAL_NBT_COMMAND_ITEM); - config.addComment(configPath + ".enable", - "Bypass permission: " + bypassPermission.string() + "\n" + + super("illegals.nbt.command-items", false, AEFPermission.BYPASS_ILLEGAL_NBT_COMMAND_ITEM, + "Bypass permission: " + AEFPermission.BYPASS_ILLEGAL_NBT_COMMAND_ITEM.string() + "\n" + "Deletes items with commands in their NBT data that run as operator.\n" + "These can only be created by players with creative access.\n" + "Most common items are books, since it allows storing multiple commands."); this.checkStored = config.getBoolean(configPath + ".check-stored-items", false); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public @NotNull ItemLegality legalityOf(@Nullable ItemStack itemStack) { if (itemStack == null || itemStack.getType().isAir()) { diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/nbt/CustomNBTFilter.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/nbt/CustomNBTFilter.java index ae0369127..26a52db0d 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/nbt/CustomNBTFilter.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/nbt/CustomNBTFilter.java @@ -24,10 +24,9 @@ public class CustomNBTFilter extends IllegalItemModule { private final boolean useWhitelist, blacklistMode, checkStored; public CustomNBTFilter() { - super("illegals.nbt.ban-custom-tags", AEFPermission.BYPASS_ILLEGAL_NBT_CUSTOM); - config.addComment(configPath + ".enable", - "Bypass permission: " + bypassPermission.string() + "\n" + - "Deletes items that have one or more of the configured tags."); + super("illegals.nbt.ban-custom-tags", false, AEFPermission.BYPASS_ILLEGAL_NBT_CUSTOM, + "Bypass permission: " + AEFPermission.BYPASS_ILLEGAL_NBT_CUSTOM.string() + "\n" + + "Deletes items that have one or more of the configured tags."); this.checkStored = config.getBoolean(configPath + ".check-stored-items", false); this.illegalTags = new HashSet<>(config.getList(configPath + ".tags", List.of("dmg"), "The exact, case sensitive value of the nbt tag.")); @@ -47,11 +46,6 @@ public CustomNBTFilter() { .collect(Collectors.toCollection(() -> EnumSet.noneOf(Material.class))); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public @NotNull ItemLegality legalityOf(@Nullable ItemStack itemStack) { if (itemStack == null || itemStack.getType().isAir()) { diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/nbt/NBTFilledStorageItem.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/nbt/NBTFilledStorageItem.java index 2f8fc47f6..7554a959b 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/nbt/NBTFilledStorageItem.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/items/nbt/NBTFilledStorageItem.java @@ -25,14 +25,13 @@ public class NBTFilledStorageItem extends IllegalItemModule { private final boolean checkStored; public NBTFilledStorageItem() { - super("illegals.nbt.impossibly-stored-items", AEFPermission.BYPASS_ILLEGAL_NBT_STOREDITEMS); - config.addComment(configPath + ".enable", - "Bypass permission: " + bypassPermission.string() + "\n" + - "Prevents usage of or deletes storage items that have been pre-filled\n" + - "with items using NBT tags. These can only be created by players with\n" + - "creative access.\n" + - "Most commonly dispensers, droppers and chests containing kit shulkers\n" + - "are created but there are more combinations possible."); + super("illegals.nbt.impossibly-stored-items", false, AEFPermission.BYPASS_ILLEGAL_NBT_STOREDITEMS, + "Bypass permission: " + AEFPermission.BYPASS_ILLEGAL_NBT_STOREDITEMS.string() + "\n" + + "Prevents usage of or deletes storage items that have been pre-filled\n" + + "with items using NBT tags. These can only be created by players with\n" + + "creative access.\n" + + "Most commonly dispensers, droppers and chests containing kit shulkers\n" + + "are created but there are more combinations possible."); this.stored_items_tag = config.getString(configPath + ".tag", "BlockEntityTag", "The exact name of the nbt tag that signals items are stored inside."); this.checkStored = config.getBoolean(configPath + ".check-stored-items", false); @@ -51,11 +50,6 @@ public NBTFilledStorageItem() { .collect(Collectors.toCollection(() -> EnumSet.noneOf(Material.class))); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public @NotNull ItemLegality legalityOf(@Nullable ItemStack itemStack) { if (itemStack == null || itemStack.getType().isAir()) { diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/placedblocks/PeriodicallyRemoveIllegalBlocks.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/placedblocks/PeriodicallyRemoveIllegalBlocks.java index 6a8cfce82..31be9fd86 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/placedblocks/PeriodicallyRemoveIllegalBlocks.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/placedblocks/PeriodicallyRemoveIllegalBlocks.java @@ -17,22 +17,36 @@ import java.util.Set; import java.util.function.Consumer; import java.util.stream.Collectors; +import java.util.stream.Stream; public class PeriodicallyRemoveIllegalBlocks extends AEFModule implements Consumer { - private ScheduledTask scheduledTask; private final Set blocksToRemove; private final Set exemptedWorlds; private final long checkPeriod; private final double pauseTPS; private final boolean checkShouldPauseOnLowTPS; + private ScheduledTask scheduledTask; + public PeriodicallyRemoveIllegalBlocks() { - super("illegals.remove-placed-blocks.periodically"); - this.blocksToRemove = config.getList(configPath + ".blocks-to-remove", - List.of("PLAYER_HEAD", "CHAIN_COMMAND_BLOCK", "COMMAND_BLOCK", "COMMAND_BLOCK_MINECART", - "REPEATING_COMMAND_BLOCK", "BEDROCK", "BARRIER"), - "Enter PLAYER_HEAD here if you want to remove placed playerheads.") + super("illegals.remove-placed-blocks.periodically", false); + List defaults = Stream.of( + XMaterial.PLAYER_HEAD, + XMaterial.PLAYER_WALL_HEAD, + XMaterial.COMMAND_BLOCK, + XMaterial.CHAIN_COMMAND_BLOCK, + XMaterial.REPEATING_COMMAND_BLOCK, + XMaterial.BEDROCK, + XMaterial.BARRIER, + XMaterial.STRUCTURE_BLOCK, + XMaterial.STRUCTURE_VOID, + XMaterial.LIGHT) + .filter(XMaterial::isSupported) + .map(XMaterial::get) + .map(Enum::name) + .toList(); + this.blocksToRemove = config.getList(configPath + ".blocks-to-remove", defaults) .stream() .map(configuredType -> { try { @@ -53,18 +67,16 @@ public PeriodicallyRemoveIllegalBlocks() { @Override public void enable() { - this.scheduledTask = plugin.getServer().getGlobalRegionScheduler() + scheduledTask = plugin.getServer().getGlobalRegionScheduler() .runAtFixedRate(plugin, this, checkPeriod, checkPeriod); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { - if (scheduledTask != null) scheduledTask.cancel(); + if (scheduledTask != null) { + scheduledTask.cancel(); + scheduledTask = null; + } } @Override @@ -90,20 +102,20 @@ public void accept(ScheduledTask task) { if (!blocksToRemove.contains(block.getType())) continue; // If is bedrock, make sure not to delete naturally generated - if (block.getType() == XMaterial.BEDROCK.parseMaterial()) { + if (block.getType() == XMaterial.BEDROCK.get()) { if (y > minY + 4) { // offset to not delete natural bedrock floor if (inNether) { // offset to not delete bedrock ceiling if (y < config.nether_ceiling_max_y - 5) - block.setType(XMaterial.AIR.parseMaterial(), false); + block.setType(XMaterial.AIR.get(), false); } else { - block.setType(XMaterial.AIR.parseMaterial(), false); + block.setType(XMaterial.AIR.get(), false); } } continue; } - block.setType(XMaterial.AIR.parseMaterial(), false); + block.setType(XMaterial.AIR.get(), false); } } } diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/placedblocks/RemoveIllegalBlocksOnChunkload.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/placedblocks/RemoveIllegalBlocksOnChunkload.java index 2c2065517..ecb0502a4 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/placedblocks/RemoveIllegalBlocksOnChunkload.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/placedblocks/RemoveIllegalBlocksOnChunkload.java @@ -19,6 +19,7 @@ import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; +import java.util.stream.Stream; public class RemoveIllegalBlocksOnChunkload extends AEFModule implements Listener { @@ -28,12 +29,24 @@ public class RemoveIllegalBlocksOnChunkload extends AEFModule implements Listene private final double pauseTPS; public RemoveIllegalBlocksOnChunkload() { - super("illegals.remove-placed-blocks.on-chunkload"); - config.addComment(configPath + ".enable", + super("illegals.remove-placed-blocks.on-chunkload", false, "Remove illegally placed blocks on chunkload."); - this.blocksToRemove = config.getList(configPath + ".blocks-to-remove", - List.of("PLAYER_HEAD", "CHAIN_COMMAND_BLOCK", "COMMAND_BLOCK", "COMMAND_BLOCK_MINECART", - "REPEATING_COMMAND_BLOCK", "BEDROCK", "BARRIER"), + List defaults = Stream.of( + XMaterial.PLAYER_HEAD, + XMaterial.PLAYER_WALL_HEAD, + XMaterial.COMMAND_BLOCK, + XMaterial.CHAIN_COMMAND_BLOCK, + XMaterial.REPEATING_COMMAND_BLOCK, + XMaterial.BEDROCK, + XMaterial.BARRIER, + XMaterial.STRUCTURE_BLOCK, + XMaterial.STRUCTURE_VOID, + XMaterial.LIGHT) + .filter(XMaterial::isSupported) + .map(XMaterial::get) + .map(Enum::name) + .toList(); + this.blocksToRemove = config.getList(configPath + ".blocks-to-remove", defaults, "Enter PLAYER_HEAD here if you want to remove placed playerheads.") .stream() .map(configuredType -> { @@ -57,11 +70,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); @@ -85,20 +93,20 @@ private void onChunkLoad(ChunkLoadEvent event) { if (!blocksToRemove.contains(block.getType())) continue; // If is bedrock, make sure not to delete naturally generated - if (block.getType() == XMaterial.BEDROCK.parseMaterial()) { + if (block.getType() == XMaterial.BEDROCK.get()) { if (y > minY + 4) { // offset to not delete natural bedrock floor if (inNether) { // offset to not delete bedrock ceiling if (y < config.nether_ceiling_max_y - 5) - block.setType(XMaterial.AIR.parseMaterial(), false); + block.setType(XMaterial.AIR.get(), false); } else { - block.setType(XMaterial.AIR.parseMaterial(), false); + block.setType(XMaterial.AIR.get(), false); } } continue; } - block.setType(XMaterial.AIR.parseMaterial(), false); + block.setType(XMaterial.AIR.get(), false); } } } diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/placedblocks/RemoveUnnaturalSpawners.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/placedblocks/RemoveUnnaturalSpawners.java index f24c3a66b..d10fb5721 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/placedblocks/RemoveUnnaturalSpawners.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/illegals/placedblocks/RemoveUnnaturalSpawners.java @@ -17,7 +17,6 @@ import java.util.EnumSet; import java.util.HashMap; -import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; @@ -30,21 +29,22 @@ public class RemoveUnnaturalSpawners extends AEFModule implements Listener { private final double pauseTPS; public RemoveUnnaturalSpawners() { - super("illegals.remove-unnatural-spawners-on-chunkload"); + super("illegals.remove-unnatural-spawners-on-chunkload", false); this.checkShouldPauseOnLowTPS = config.getBoolean(configPath + ".pause-on-low-TPS", false); this.pauseTPS = config.getDouble(configPath + ".pause-TPS", 14.0); Map defaults = new HashMap<>(); - defaults.put("world", List.of( + defaults.put("world", Set.of( XEntityType.SKELETON.get().name(), XEntityType.ZOMBIE.get().name(), XEntityType.SILVERFISH.get().name(), XEntityType.SPIDER.get().name(), - XEntityType.CAVE_SPIDER.get().name())); - defaults.put("world_nether", List.of( + XEntityType.CAVE_SPIDER.get().name(), + XEntityType.BREEZE_WIND_CHARGE.get().name())); + defaults.put("world_nether", Set.of( XEntityType.BLAZE.get().name(), XEntityType.MAGMA_CUBE.get().name())); - defaults.put("world_the_end", List.of( + defaults.put("world_the_end", Set.of( XEntityType.SKELETON.get().name(), XEntityType.SPIDER.get().name())); @@ -73,11 +73,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); @@ -97,10 +92,10 @@ private void onChunkLoad(ChunkLoadEvent event) { for (int z = 0; z < 16; z++) { for (int y = minY; y < maxY; y++) { Block block = event.getChunk().getBlock(x, y, z); - if (block.getType() == XMaterial.SPAWNER.parseMaterial() + if (block.getType() == XMaterial.SPAWNER.get() && !naturalSpawners.get(event.getWorld().getName()).contains(((CreatureSpawner) block.getState()).getSpawnedType()) ) { - block.setType(XMaterial.AIR.parseMaterial(), false); + block.setType(XMaterial.AIR.get(), false); } } } diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/DisableCustomEntities.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/DisableCustomEntities.java new file mode 100755 index 000000000..f78826e70 --- /dev/null +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/DisableCustomEntities.java @@ -0,0 +1,71 @@ +package me.xginko.aef.modules.lagpreventions; + +import com.cryptomorin.xseries.XEntityType; +import me.xginko.aef.modules.AEFModule; +import org.bukkit.entity.EntityType; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.HandlerList; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntitySpawnEvent; + +import java.util.EnumSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class DisableCustomEntities extends AEFModule implements Listener { + + private final Set disabledEntities; + + public DisableCustomEntities() { + super("lag-preventions.disable-entity-spawns", false,""" + Prevent certain entity types from spawning to combat lag. + Fish types are enabled by default on newer versions since they + can cause a ton of lag."""); + + List defaults = Stream.of( + XEntityType.COD, + XEntityType.SALMON, + XEntityType.PUFFERFISH, + XEntityType.TROPICAL_FISH, + XEntityType.BAT, + XEntityType.PHANTOM) + .filter(XEntityType::isSupported) + .map(XEntityType::get) + .map(Enum::name) + .toList(); + + this.disabledEntities = config.getList(configPath + ".types", defaults) + .stream() + .map(configuredType -> { + try { + return EntityType.valueOf(configuredType); + } catch (IllegalArgumentException exception) { + notRecognized(EntityType.class, configuredType); + return null; + } + }) + .filter(Objects::nonNull) + .collect(Collectors.toCollection(() -> EnumSet.noneOf(EntityType.class))); + } + + @Override + public void enable() { + plugin.getServer().getPluginManager().registerEvents(this, plugin); + } + + @Override + public void disable() { + HandlerList.unregisterAll(this); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + private void onEntitySpawn(EntitySpawnEvent event) { + if (disabledEntities.contains(event.getEntityType())) { + event.setCancelled(true); + } + } +} diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/FloodingMachines.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/FloodingMachines.java index 6c87044d2..ab8f7e3dd 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/FloodingMachines.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/FloodingMachines.java @@ -1,8 +1,8 @@ package me.xginko.aef.modules.lagpreventions; +import com.cryptomorin.xseries.XMaterial; import me.xginko.aef.modules.AEFModule; import me.xginko.aef.utils.BlockUtil; -import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; @@ -15,8 +15,7 @@ public class FloodingMachines extends AEFModule implements Listener { private final boolean remove; public FloodingMachines() { - super("lag-preventions.prevent-flooding-machines"); - config.addComment(configPath + ".enable", """ + super("lag-preventions.prevent-flooding-machines", false, """ Will prevent pistons from pushing waterlogged blocks.\s Stops players from using waterlogged blocks and piston flying\s machines to generate large walls of water that generate lag\s @@ -34,16 +33,11 @@ public void disable() { HandlerList.unregisterAll(this); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) private void onPistonExtend(BlockPistonExtendEvent event) { for (Block block : event.getBlocks()) { if (BlockUtil.isWaterlogged(block.getState())) { - if (remove) block.setType(Material.AIR); + if (remove) block.setType(XMaterial.AIR.get()); event.setCancelled(true); return; } diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/KeepStashLoaded.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/KeepStashLoaded.java index c4c378856..aa172c5bc 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/KeepStashLoaded.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/KeepStashLoaded.java @@ -3,6 +3,7 @@ import io.github.thatsmusic99.configurationmaster.api.ConfigSection; import io.papermc.paper.threadedregions.scheduler.ScheduledTask; import me.xginko.aef.modules.AEFModule; +import me.xginko.aef.utils.ChunkUtil; import me.xginko.aef.utils.MaterialUtil; import me.xginko.aef.utils.models.ChunkUID; import org.bukkit.Chunk; @@ -17,6 +18,7 @@ import java.util.EnumSet; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; @@ -31,16 +33,16 @@ */ public class KeepStashLoaded extends AEFModule implements Consumer, Listener { - private final Map forceLoadedChunks; - private final Map worldsAndTheirRadiuses = new HashMap<>(); + private final Map worldsAndTheirRadiuses; private final Set storageTypes; private final long minInhabitedTime, keepLoadedMillis, checkDelayTicks; private final int stashCount; private final boolean logIsEnabled, onlyTileEntities; + private Map forceLoadedChunks; + public KeepStashLoaded() { super("lag-preventions.keep-stash-chunks-loaded"); - this.forceLoadedChunks = new ConcurrentHashMap<>(); config.addComment(configPath + ".enable", """ Idea by 3b3t admin kumori (Soft1k)\s Improves lag generated by large stash chunks constantly loading and\s @@ -83,7 +85,9 @@ public KeepStashLoaded() { ConfigSection section = config.getConfigSection(configPath + ".worlds", defaults, "Radiuses around spawn in chunks (not blocks) that should not be checked.\n" + "Worlds not on this list are exempt from all checking."); - for (String world : section.getKeys(false)) { + List worlds = section.getKeys(false); + this.worldsAndTheirRadiuses = new HashMap<>(worlds.size()); + for (String world : worlds) { try { int radius = Integer.parseInt(section.getString(world)); this.worldsAndTheirRadiuses.put(world, NumberConversions.square(radius)); @@ -95,6 +99,7 @@ public KeepStashLoaded() { @Override public void enable() { + forceLoadedChunks = new ConcurrentHashMap<>(); plugin.getServer().getPluginManager().registerEvents(this, plugin); plugin.getServer().getAsyncScheduler().runAtFixedRate(plugin, this, 1L, 1L, TimeUnit.MINUTES); } @@ -102,20 +107,19 @@ public void enable() { @Override public void disable() { HandlerList.unregisterAll(this); - for (Map.Entry entry : forceLoadedChunks.entrySet()) { - entry.getKey().getChunkAsync(false).thenAccept(chunk -> { - if (chunk != null) - plugin.getServer().getGlobalRegionScheduler().execute(plugin, () -> chunk.setForceLoaded(false)); - forceLoadedChunks.remove(entry.getKey()); - }); + if (forceLoadedChunks != null) { + for (Map.Entry entry : forceLoadedChunks.entrySet()) { + entry.getKey().getChunkAsync(false).thenAccept(chunk -> { + if (chunk != null) { + ChunkUtil.setForceLoaded(chunk, false); + } + }); + } + forceLoadedChunks.clear(); + forceLoadedChunks = null; } } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void accept(ScheduledTask task) { for (Map.Entry entry : forceLoadedChunks.entrySet()) { diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/LeverSpam.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/LeverSpam.java index eafb5769a..179cfc7f3 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/LeverSpam.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/LeverSpam.java @@ -19,35 +19,42 @@ public class LeverSpam extends AEFModule implements Listener { - private final Cache leverLocationCooldowns; - private final Cache playersUsingLeversCooldowns; + private final long cacheTimeMillis; private final int leverUsageLimit; private final boolean shouldKickPlayer, sendActionBar; + private Cache leverLocationCooldowns; + private Cache playersUsingLeversCooldowns; + public LeverSpam() { - super("lag-preventions.prevent-lever-spam"); - config.addComment(configPath + ".enable", "Rate Limit levers to prevent a lag exploit."); + super("lag-preventions.prevent-lever-spam", false, + "Rate Limit levers to prevent a lag exploit."); this.sendActionBar = config.getBoolean(configPath + ".show-actionbar", true); this.shouldKickPlayer = config.getBoolean(configPath + ".kick-player", false); this.leverUsageLimit = config.getInt(configPath + ".max-lever-usages-per-time", 15); - final long cacheTimeMillis = config.getInt(configPath + ".lever-time-in-ticks", 40) * 50L; - this.leverLocationCooldowns = Caffeine.newBuilder().expireAfterWrite(Duration.ofMillis(cacheTimeMillis)).build(); - this.playersUsingLeversCooldowns = Caffeine.newBuilder().expireAfterWrite(Duration.ofMillis(cacheTimeMillis)).build(); + this.cacheTimeMillis = config.getInt(configPath + ".lever-time-in-ticks", 40) * 50L; } @Override public void enable() { + leverLocationCooldowns = Caffeine.newBuilder().expireAfterWrite(Duration.ofMillis(cacheTimeMillis)).build(); + playersUsingLeversCooldowns = Caffeine.newBuilder().expireAfterWrite(Duration.ofMillis(cacheTimeMillis)).build(); plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); + if (leverLocationCooldowns != null) { + leverLocationCooldowns.invalidateAll(); + leverLocationCooldowns.cleanUp(); + leverLocationCooldowns = null; + } + if (playersUsingLeversCooldowns != null) { + playersUsingLeversCooldowns.invalidateAll(); + playersUsingLeversCooldowns.cleanUp(); + playersUsingLeversCooldowns = null; + } } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/NoShulkerDrops.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/NoShulkerDrops.java index 5f2633ef6..c856883c0 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/NoShulkerDrops.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/NoShulkerDrops.java @@ -13,8 +13,7 @@ public class NoShulkerDrops extends AEFModule implements Listener { public NoShulkerDrops() { - super("lag-preventions.anti-shulker-drops"); - config.addComment(configPath + ".enable", """ + super("lag-preventions.anti-shulker-drops", false, """ Disables shulkers dropping stored items when blown up.\s This helps fix client- and serverside lag when done often and fast."""); } @@ -29,11 +28,6 @@ public void disable() { HandlerList.unregisterAll(this); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) private void onEntityDamage(EntityDamageEvent event) { if (event.getEntityType() != XEntityType.ITEM.get()) return; diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/StashExplosions.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/StashExplosions.java index 1144b62b6..2904cbfc8 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/StashExplosions.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/StashExplosions.java @@ -1,6 +1,7 @@ package me.xginko.aef.modules.lagpreventions; import com.cryptomorin.xseries.XEntityType; +import com.cryptomorin.xseries.XMaterial; import com.destroystokyo.paper.MaterialTags; import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; @@ -26,25 +27,24 @@ public class StashExplosions extends AEFModule implements Listener { - private final Cache containerExplosions; private final Set storageTypes; + private final long waitTimeSeconds; private final int amountAtWhichToTakeAction; private final boolean logIsEnabled; + private Cache containerExplosions; + public StashExplosions() { - super("lag-preventions.disable-item-drops-during-large-stash-explosions"); - config.addComment(configPath + ".enable", """ + super("lag-preventions.disable-item-drops-during-large-stash-explosions", false, """ Explodes containers without dropping items after a certain amount\s of exploded containers per chunk."""); this.logIsEnabled = config.getBoolean(configPath + ".log", false); this.amountAtWhichToTakeAction = config.getInt(configPath + ".min-explosions-before-drops-disable", 6, """ How many container blocks in a chunk can be blown up until items\s no longer drop from them."""); - this.containerExplosions = Caffeine.newBuilder().expireAfterWrite(Duration.ofSeconds( - Math.max(1, config.getInt(configPath + ".time-in-seconds", 3, """ - The time in seconds to wait after an explosion for another one to happen.\s - If no explosion happens within x seconds after the first one, the count resets to 0.""")) - )).build(); + this.waitTimeSeconds = Math.max(1, config.getInt(configPath + ".time-in-seconds", 3, """ + The time in seconds to wait after an explosion for another one to happen.\s + If no explosion happens within x seconds after the first one, the count resets to 0.""")); this.storageTypes = config.getList(configPath + ".container-types", MaterialUtil.INVENTORY_HOLDERS .stream() .filter(material -> !MaterialTags.SHULKER_BOXES.isTagged(material)) @@ -64,18 +64,18 @@ public StashExplosions() { @Override public void enable() { + containerExplosions = Caffeine.newBuilder().expireAfterWrite(Duration.ofSeconds(waitTimeSeconds)).build(); plugin.getServer().getPluginManager().registerEvents(this, plugin); } @Override public void disable() { HandlerList.unregisterAll(this); - containerExplosions.asMap().clear(); - } - - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); + if (containerExplosions != null) { + containerExplosions.invalidateAll(); + containerExplosions.cleanUp(); + containerExplosions = null; + } } private void handleExplosion(Chunk chunk, List affectedBlocks) { @@ -90,7 +90,7 @@ private void handleExplosion(Chunk chunk, List affectedBlocks) { affectedBlocks.removeIf(block -> { if (storageTypes.contains(block.getType())) { - block.setType(Material.AIR); + block.setType(XMaterial.AIR.get()); return true; } return false; @@ -115,7 +115,9 @@ private void onBlockExplode(BlockExplodeEvent event) { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) private void onEntityExplode(EntityExplodeEvent event) { - if (event.getEntityType().equals(XEntityType.WIND_CHARGE.get())) return; + if (event.getEntityType() == XEntityType.WIND_CHARGE.get()) return; + if (event.getEntityType() == XEntityType.BREEZE_WIND_CHARGE.get()) return; + handleExplosion(event.getEntity().getChunk(), event.blockList()); } } diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/agelimits/CustomAgeLimits.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/agelimits/CustomAgeLimits.java index 5d746c7e9..052c118c7 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/agelimits/CustomAgeLimits.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/agelimits/CustomAgeLimits.java @@ -23,14 +23,14 @@ public class CustomAgeLimits extends AEFModule implements Consumer, Listener { - private ScheduledTask scheduledTask; private final Map entityLimits = new EnumMap<>(EntityType.class); private final long checkPeriod; private final boolean logIsEnabled, forceLoadEntities; + private ScheduledTask scheduledTask; + public CustomAgeLimits() { - super("lag-preventions.entity-age-limits.custom-limits"); - config.addComment(configPath + ".enable", + super("lag-preventions.entity-age-limits.custom-limits", false, "Kill certain entities after a custom amount of ticks lived."); this.logIsEnabled = config.getBoolean(configPath + ".log-removals", false); this.checkPeriod = config.getInt(configPath + ".check-period-in-ticks", 1200, """ @@ -78,16 +78,13 @@ public void enable() { .runAtFixedRate(plugin, this, 20L, checkPeriod); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); - if (scheduledTask != null) + if (scheduledTask != null) { scheduledTask.cancel(); + scheduledTask = null; + } } @Override @@ -101,8 +98,7 @@ public void accept(ScheduledTask task) { for (Entity entity : chunk.getEntities()) { entity.getScheduler().execute(plugin, () -> { - if (entityLimits.containsKey(entity.getType()) - && entity.getTicksLived() >= entityLimits.get(entity.getType())) { + if (entityLimits.containsKey(entity.getType()) && entity.getTicksLived() > entityLimits.get(entity.getType())) { entity.remove(); if (logIsEnabled) info("Removed " + entity.getType().name() + " due to old age."); @@ -117,7 +113,7 @@ public void accept(ScheduledTask task) { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) private void onEntitiesLoad(EntitiesLoadEvent event) { for (Entity entity : event.getEntities()) { - if (entityLimits.containsKey(entity.getType()) && entity.getTicksLived() >= entityLimits.get(entity.getType())) { + if (entityLimits.containsKey(entity.getType()) && entity.getTicksLived() > entityLimits.get(entity.getType())) { entity.getScheduler().execute(plugin, entity::remove, null, 1L); if (logIsEnabled) info("Removed " + entity.getType().name() + " due to old age."); diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/agelimits/ProjectileAgeLimit.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/agelimits/ProjectileAgeLimit.java index bbf5b5603..02ce86ef8 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/agelimits/ProjectileAgeLimit.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/agelimits/ProjectileAgeLimit.java @@ -17,18 +17,18 @@ public class ProjectileAgeLimit extends AEFModule implements Consumer, Listener { - private ScheduledTask scheduledTask; private final long check_period_in_ticks; private final int max_alive_time; + private ScheduledTask scheduledTask; + public ProjectileAgeLimit() { - super("lag-preventions.entity-age-limits.projectile-limit"); - config.addComment(configPath + ".enable", - "Patches any lag exploit that abuses spawning a ton of projectile entities\n" + - "(ex. Snowball exploit)." + - "Skips over the following entities: ENDER_PEARL, FISHING_HOOK, WITHER_SKULL\n" + - "and ENDER_SIGNAL. You can configure those separately in the custom entity age\n" + - "limit section."); + super("lag-preventions.entity-age-limits.projectile-limit", false, """ + Patches any lag exploit that abuses spawning a ton of projectile entities + (ex. Snowball exploit). + Skips over the following entities: ENDER_PEARL, FISHING_HOOK, WITHER_SKULL + and ENDER_SIGNAL. You can configure those separately in the custom entity age + limit section."""); this.max_alive_time = config.getInt(configPath + ".max-alive-time-ticks", 300, "(20 ticks = 1 second) Will not touch Ender Pearls"); this.check_period_in_ticks = config.getInt(configPath + ".check-period-seconds", 20, @@ -37,20 +37,18 @@ public ProjectileAgeLimit() { @Override public void enable() { - this.scheduledTask = plugin.getServer().getGlobalRegionScheduler() + scheduledTask = plugin.getServer().getGlobalRegionScheduler() .runAtFixedRate(plugin, this, check_period_in_ticks, check_period_in_ticks); plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { - if (scheduledTask != null) scheduledTask.cancel(); HandlerList.unregisterAll(this); + if (scheduledTask != null) { + scheduledTask.cancel(); + scheduledTask = null; + } } @Override diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/BlockFormOrGrow.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/BlockFormOrGrow.java index 73d4333f1..cf97e4520 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/BlockFormOrGrow.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/BlockFormOrGrow.java @@ -13,13 +13,13 @@ public BlockFormOrGrow() { super( "block-spread", false, + true, 1500.0, 6000, 10000, 10.0, - 120.0 - ); - config.addComment(configPath+".enable", """ + 120.0, + """ Limits blocks spreading or forming based on world conditions within a\s configurable radius and timeframe to help reduce lag by cancelling burst\s activity hotspots.\s @@ -31,7 +31,8 @@ public BlockFormOrGrow() { - Obsidian / Cobblestone forming due to contact with water.\s - Concrete forming due to mixing of concrete powder and water.\s - Mushrooms spreading.\s - - Fire spreading."""); + - Fire spreading.""" + ); this.limit = config.getInt(configPath + ".block-form-event-limit", 800, "Maximum number of times a block can form or spread within the configured\n" + "timeframe before activity will be put on cooldown."); diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/BlockPhysics.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/BlockPhysics.java index c328a2d80..a58af90fa 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/BlockPhysics.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/BlockPhysics.java @@ -11,14 +11,14 @@ public class BlockPhysics extends RegionalActivityModule { public BlockPhysics() { super( "block-physics", + false, true, 1500.0, 18000, 20000, 10.0, - 120.0 - ); - this.config.addComment(configPath+".enable", """ + 120.0, + """ Limits block physics within a configurable radius and timeframe\s to help reduce lag by cancelling burst activity hotspots.\s \s @@ -29,7 +29,8 @@ The event used for this check (BlockPhysicsEvent) is a high frequency event,\s Where possible the event may also only be called for the "root" block of\s physics updates in order to limit event spam.\s Physics updates that cause other blocks to change their state may not result\s - in an event for each of those blocks (usually adjacent)."""); + in an event for each of those blocks (usually adjacent).""" + ); this.limit = config.getInt(configPath + ".block-physics-event-limit", 256000, "Maximum number of times a physics check can be performed within the configured\n" + "timeframe before they will be put on cooldown."); diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/EntitySpawns.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/EntitySpawns.java index 16b4451e8..b6efbf21b 100644 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/EntitySpawns.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/EntitySpawns.java @@ -11,14 +11,14 @@ public class EntitySpawns extends RegionalActivityModule { public EntitySpawns() { super( "entity-spawn", + false, true, 1500.0, 18000, 20000, 10.0, - 120.0 - ); - this.config.addComment(configPath+".enable", """ + 120.0, + """ Limits entity spawning activity within a configurable radius and timeframe\s to help reduce lag by cancelling high activity hotspots.\s \s @@ -26,7 +26,8 @@ public EntitySpawns() { \s - A creature gets spawned naturally, by spawner or other reasons.\s - An entity gets spawned naturally, by spawner or other reasons.\s - This does not include tile entities."""); + This does not include tile entities.""" + ); this.limit = config.getInt(configPath + ".spawn-event-limit", 6000, "Maximum number of entity spawns within configured timeframe."); } diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/EntityTargeting.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/EntityTargeting.java index bd60ab6a0..22d7d2ec1 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/EntityTargeting.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/EntityTargeting.java @@ -25,16 +25,17 @@ public class EntityTargeting extends RegionalActivityModule implements Listener public EntityTargeting() { super("entity-targeting", + false, true, 1500.0, 18000, 20000, 14.0, - 120.0 - ); - this.config.addComment(configPath+".enable", """ + 120.0, + """ Limits entities targeting other entities within a configurable radius\s - and timeframe to help reduce lag by cancelling burst activity hotspots."""); + and timeframe to help reduce lag by cancelling burst activity hotspots.""" + ); this.limit = config.getInt(configPath + ".entity-target-event-limit", 8000, """ Maximum number of times an entity can target another entity within the\s configured timeframe before the area will be put on cooldown."""); diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/Explosions.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/Explosions.java index 47aae4c07..ac9700708 100644 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/Explosions.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/Explosions.java @@ -14,13 +14,13 @@ public Explosions() { super( "explosions", false, + true, 1500.0, 6000, 10000, 10.0, - 120.0 - ); - this.config.addComment(configPath+".enable", """ + 120.0, + """ Limits explosions within a configurable radius and timeframe\s to help reduce lag by cancelling high activity hotspots.\s \s @@ -28,7 +28,8 @@ public Explosions() { \s - A block exploding.\s - An entity exploding.\s - - An entity making the decision to explode."""); + - An entity making the decision to explode.""" + ); this.limit = config.getInt(configPath + ".explode-event-limit", 500, "Maximum number of explode events within the configured timeframe\n" + "before the region will be put on cooldown."); diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/LiquidSpread.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/LiquidSpread.java index 480ba4fae..0b386a41c 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/LiquidSpread.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/LiquidSpread.java @@ -13,14 +13,14 @@ public class LiquidSpread extends RegionalActivityModule { public LiquidSpread() { super( "liquid-spread", + false, true, 1500.0, 18000, 20000, 12.0, - 100.0 - ); - this.config.addComment(configPath+".enable", """ + 100.0, + """ Limits liquid spreading within a configurable radius and timeframe\s to help reduce lag by cancelling high activity hotspots.\s \s @@ -28,7 +28,8 @@ public LiquidSpread() { \s - A lava block spreading by flowing.\s - A water block spreading by flowing.\s - - (optional) A dragon egg is teleporting from one position to another."""); + - (optional) A dragon egg is teleporting from one position to another.""" + ); this.limit = config.getInt(configPath + ".liquid-spread-event-limit", 2400, "Maximum number of times liquids are allowed to spread within the configured\n" + "timeframe before they will be put on cooldown."); @@ -37,7 +38,7 @@ public LiquidSpread() { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) private void onBlockFromTo(BlockFromToEvent event) { - if (ignoreDragonEgg && event.getBlock().getType() == XMaterial.DRAGON_EGG.parseMaterial()) return; + if (ignoreDragonEgg && event.getBlock().getType() == XMaterial.DRAGON_EGG.get()) return; if (shouldCancelActivity(event, event.getBlock().getLocation(), limit)) { event.setCancelled(true); diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/Noteblocks.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/Noteblocks.java index 7c3945916..6227502b9 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/Noteblocks.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/Noteblocks.java @@ -12,20 +12,21 @@ public Noteblocks() { super( "noteblocks", false, + true, 1500.0, 6000, 10000, 10.0, - 120.0 - ); - this.config.addComment(configPath+".enable", """ + 120.0, + """ Limits noteblocks being played within a configurable radius and timeframe\s to help reduce lag by cancelling high activity hotspots.\s \s Examples:\s \s - A noteblock is being played through player interaction.\s - - A noteblock is being played through a redstone current."""); + - A noteblock is being played through a redstone current.""" + ); this.limit = config.getInt(configPath + ".noteblock-play-limit", 2800, "Maximum number of times a noteblock can be played within the configured\n" + "timeframe before they will be put on cooldown."); diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/Pathfinding.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/Pathfinding.java index 370e00fe3..48564d62d 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/Pathfinding.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/Pathfinding.java @@ -25,16 +25,17 @@ public Pathfinding() { super( "entity-pathfinding", false, + true, 1500.0, 6000, 10000, 14.0, - 120.0 - ); - this.config.addComment(configPath+".enable", """ + 120.0, + """ Limits entities deciding to pathfind to a specific location\s within a configurable radius and timeframe to help reduce lag\s - by cancelling burst activity hotspots."""); + by cancelling burst activity hotspots.""" + ); this.limit = config.getInt(configPath + ".entity-pathfind-event-limit", 4000, """ Maximum number of times an entity can decide to start moving\s towards a location within the configured timeframe before the\s diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/Pistons.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/Pistons.java index 9b5a6b2cf..a279bedf8 100644 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/Pistons.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/Pistons.java @@ -13,20 +13,20 @@ public Pistons() { super( "pistons", false, + true, 1500.0, 6000, 10000, 10.0, - 120.0 - ); - this.config.addComment(configPath+".enable", """ + 120.0, """ Limits piston movement within a configurable radius and timeframe\s to help reduce lag by cancelling high activity hotspots.\s \s Examples:\s \s - A piston extends.\s - - A piston retracts."""); + - A piston retracts.""" + ); this.limit = config.getInt(configPath + ".piston-movement-limit", 1000, "Maximum number of piston extend and/or retracts within the\n" + "configured timeframe."); diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/Redstone.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/Redstone.java index 4d34efe38..d98181072 100644 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/Redstone.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/Redstone.java @@ -11,14 +11,14 @@ public class Redstone extends RegionalActivityModule { public Redstone() { super( "redstone", + false, true, 1500.0, 18000, 20000, 10.0, - 120.0 - ); - this.config.addComment(configPath+".enable", """ + 120.0, + """ Limits redstone activity within a configurable radius and timeframe\s to help reduce lag by cancelling high activity hotspots.\s \s @@ -26,7 +26,8 @@ public Redstone() { \s - A redstone current changes.\s - A redstone block gets powered on.\s - - A redstone block gets powered off."""); + - A redstone block gets powered off.""" + ); this.limit = config.getInt(configPath + ".redstone-event-limit", 6000, "Maximum number of redstone events within configured timeframe."); } diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/RegionalActivityModule.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/RegionalActivityModule.java index 027b34166..ccf271e28 100644 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/RegionalActivityModule.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/RegionalActivityModule.java @@ -22,16 +22,25 @@ */ public abstract class RegionalActivityModule extends AEFModule implements Listener { - protected final Cache regionDataCache; - protected final long pauseTimeMillis; + protected final long cacheTimeMillis, pauseTimeMillis; protected final double checkRadius, pauseTPS, pauseMSPT; protected final boolean logIsEnabled; + protected Cache regionDataCache; + public RegionalActivityModule( - String subConfigPath, boolean deflogEnabled, double defCheckRadius, + String subConfigPath, boolean defEnabled, boolean deflogEnabled, double defCheckRadius, int defPauseMillis, int defCacheMillis, double defPauseTPS, double defPauseMSPT ) { - super("lag-preventions.regional-activity."+subConfigPath); + this(subConfigPath, defEnabled, deflogEnabled, defCheckRadius, + defPauseMillis, defCacheMillis, defPauseTPS, defPauseMSPT, null); + } + + public RegionalActivityModule( + String subConfigPath, boolean defEnabled, boolean deflogEnabled, double defCheckRadius, + int defPauseMillis, int defCacheMillis, double defPauseTPS, double defPauseMSPT, String comment + ) { + super("lag-preventions.regional-activity."+subConfigPath, defEnabled, comment); String configPath = "lag-preventions.regional-activity."+subConfigPath; this.logIsEnabled = config.getBoolean(configPath + ".log", deflogEnabled); this.checkRadius = config.getDouble(configPath + ".check-radius-blocks", defCheckRadius, @@ -39,31 +48,30 @@ public RegionalActivityModule( this.pauseTimeMillis = config.getInt(configPath + ".pause-time-millis", defPauseMillis, "The time in milliseconds all related activity will be blocked if it exceeded\n" + "the configured limit."); - this.regionDataCache = Caffeine.newBuilder().expireAfterWrite(Duration.ofMillis( - config.getInt(configPath + ".data-keep-time-millis", defCacheMillis, - "The time in milliseconds before a region and its data will be expired\n" + - "if no activity has been detected.\n" + - "For proper functionality, needs to be at least as long as your pause time."))).build(); + this.cacheTimeMillis = Math.max(100L, config.getInt(configPath + ".data-keep-time-millis", defCacheMillis, + "The time in milliseconds before a region and its data will be expired\n" + + "if no activity has been detected.\n" + + "For proper functionality, needs to be at least as long as your pause time.")); this.pauseTPS = config.getDouble(configPath + ".pause-TPS", defPauseTPS, "The TPS at which to cancel the physics entirely."); this.pauseMSPT = config.getDouble(configPath + ".pause-MSPT", defPauseMSPT, "The MSPT at which to cancel the physics entirely."); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void enable() { + regionDataCache = Caffeine.newBuilder().expireAfterWrite(Duration.ofMillis(cacheTimeMillis)).build(); plugin.getServer().getPluginManager().registerEvents(this, plugin); } @Override public void disable() { HandlerList.unregisterAll(this); - regionDataCache.invalidateAll(); + if (regionDataCache != null) { + regionDataCache.invalidateAll(); + regionDataCache.cleanUp(); + regionDataCache = null; + } } protected @NotNull RegionalActivityModule.RegionData getRegionData(Location location) { diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/SculkActivity.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/SculkActivity.java index 0d4896f80..97274d5c1 100644 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/SculkActivity.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/SculkActivity.java @@ -21,21 +21,22 @@ public class SculkActivity extends RegionalActivityModule { public SculkActivity() { super( "sculk-sensor", + false, true, 1500.0, 18000, 20000, 10.0, - 120.0 + 120.0, + """ + Limits sculk activity within a configurable radius and timeframe + to help reduce lag by cancelling high activity hotspots. + + Examples: + + - A redstone current changes for a sculk sensor. + - A physics check is being performed for a sculk sensor.""" ); - this.config.addComment(configPath+".enable", - "Limits sculk activity within a configurable radius and timeframe\n" + - "to help reduce lag by cancelling high activity hotspots.\n" + - "\n" + - "Examples:\n" + - "\n" + - "- A redstone current changes for a sculk sensor.\n" + - "- A physics check is being performed for a sculk sensor."); this.limit = config.getInt(configPath + ".sculk-event-limit", 800, "Maximum number of sculk events within configured timeframe."); List defaults = Stream.of( @@ -43,7 +44,7 @@ public SculkActivity() { XMaterial.SCULK_SHRIEKER, XMaterial.CALIBRATED_SCULK_SENSOR) .filter(XMaterial::isSupported) - .map(XMaterial::parseMaterial) + .map(XMaterial::get) .map(Enum::name) .collect(Collectors.toList()); this.sculkBlocks = config.getList(configPath + ".sculk-blocks", defaults) diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/SculkBloom.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/SculkBloom.java index 0997ab64c..142661077 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/SculkBloom.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/SculkBloom.java @@ -12,13 +12,13 @@ public SculkBloom() { super( "sculk-bloom", false, + true, 1500.0, 6000, 10000, 10.0, - 120.0 - ); - this.config.addComment(configPath+".enable", """ + 120.0, + """ Limits sculk blooming within a configurable radius and timeframe\s to help reduce lag by cancelling high activity hotspots.\s \s @@ -26,7 +26,8 @@ public SculkBloom() { \s - An entity was killed and dropped experience within an 8-block\s radius of a SculkCatalyst.\s - - A plugin used SculkCatalyst.bloom(Block, int)"""); + - A plugin used SculkCatalyst.bloom(Block, int)""" + ); this.limit = config.getInt(configPath + ".sculk-bloom-limit", 300, "Maximum number of sculk bloom events within the configured timeframe."); } diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/misc/AutoBedOrSpigot5988.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/misc/AutoBedOrSpigot5988.java index 5799fa567..c1a442ecc 100644 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/misc/AutoBedOrSpigot5988.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/misc/AutoBedOrSpigot5988.java @@ -10,19 +10,18 @@ public class AutoBedOrSpigot5988 extends AEFModule implements Listener { public AutoBedOrSpigot5988() { - super("misc.auto-bed"); - config.addComment(configPath+ ".enable", - "Re-enables SPIGOT-5988, also known as 'auto-bed'\n"+ - "From Minecraft version 1.16 (≈June 2020) to version 1.17.1(≈October 2021)\n" + - "there was a bug (SPIGOT-5988) which did not reset the respawn point of the\n" + - "player after death, if his bed was blocked with a shulker.\n" + - "After dying a second time, the player will be back at his bed again.\n" + - "This bug persisted from the Spigot server to Paper and all its forks until\n" + - "October 2021, after which it was fixed by the Spigot development team.\n" + - "Attempts by players to reach out to Spigot to allow them to disable the patch\n" + - "that fixes the SPIGOT-5988 bug have failed.\n" + - "Demonstration of how the patch works:\n" + - "https://www.youtube.com/watch?v=3y5SbQXzMss"); + super("misc.auto-bed", false,""" + Re-enables SPIGOT-5988, also known as 'auto-bed' + From Minecraft version 1.16 (≈June 2020) to version 1.17.1(≈October 2021) + there was a bug (SPIGOT-5988) which did not reset the respawn point of the + player after death, if his bed was blocked with a shulker. + After dying a second time, the player will be back at his bed again. + This bug persisted from the Spigot server to Paper and all its forks until + October 2021, after which it was fixed by the Spigot development team. + Attempts by players to reach out to Spigot to allow them to disable the patch + that fixes the SPIGOT-5988 bug have failed. + Demonstration of how the patch works: + https://www.youtube.com/watch?v=3y5SbQXzMss"""); } @Override @@ -35,11 +34,6 @@ public void disable() { HandlerList.unregisterAll(this); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) private void onPlayerSetSpawn(com.destroystokyo.paper.event.player.PlayerSetSpawnEvent event) { if (event.getCause() == PlayerSetSpawnEvent.Cause.PLUGIN || event.getCause() == PlayerSetSpawnEvent.Cause.COMMAND) return; diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/misc/FirstJoinMessages.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/misc/FirstJoinMessages.java index fc095addf..c7a0a5e58 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/misc/FirstJoinMessages.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/misc/FirstJoinMessages.java @@ -24,7 +24,7 @@ public class FirstJoinMessages extends AEFModule implements Listener { private final boolean logFirstJoin; public FirstJoinMessages() { - super("misc.join-leave-messages.first-join-messages"); + super("misc.join-leave-messages.first-join-messages", false); this.totalPlayers = new AtomicInteger(0); this.config.addComment(configPath + ".enable", "Configure message in lang folder.\n" + @@ -42,11 +42,6 @@ public void enable() { .thenRun(() -> plugin.getServer().getPluginManager().registerEvents(this, plugin)); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/misc/JoinLeaveMessages.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/misc/JoinLeaveMessages.java index 99b18af76..7c8630901 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/misc/JoinLeaveMessages.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/misc/JoinLeaveMessages.java @@ -18,15 +18,14 @@ public class JoinLeaveMessages extends AEFModule implements Listener { - private final boolean connectionMsgsOnByDefault, showInConsole, firstJoinEnabled; + private final boolean showInConsole, firstJoinEnabled; public JoinLeaveMessages() { - super("misc.join-leave-messages"); + super("misc.join-leave-messages", false); config.addComment(configPath + ".enable", "If you want to hide yourself or someone else when logging\n" + "into the game, use these permissions:\n" + AEFPermission.SILENT_JOIN.string() + ", " + AEFPermission.SILENT_LEAVE.string()); - this.connectionMsgsOnByDefault = config.connectionMsgsAreOnByDefault; this.showInConsole = config.getBoolean(configPath + ".show-in-console", false); this.firstJoinEnabled = config.getBoolean(configPath + ".first-join-messages.enable", false); } @@ -58,7 +57,7 @@ private void onPlayerJoinEvent(PlayerJoinEvent event) { onlinePlayer.getScheduler().execute(plugin, () -> { final PersistentDataContainer dataContainer = onlinePlayer.getPersistentDataContainer(); if ( - !dataContainer.has(AEFKey.CONNECT_MSG_TOGGLE.getKey()) ? connectionMsgsOnByDefault : + !dataContainer.has(AEFKey.CONNECT_MSG_TOGGLE.getKey()) ? config.connectionMsgsAreOnByDefault : dataContainer.get(AEFKey.CONNECT_MSG_TOGGLE.getKey(), PersistentDataType.BOOLEAN) ) { onlinePlayer.sendMessage(AnarchyExploitFixes.getLang(onlinePlayer.locale()).misc_joinMessage @@ -86,7 +85,7 @@ private void onPlayerLeaveEvent(PlayerQuitEvent event) { if (onlinePlayer.getUniqueId().equals(leavingPlayer.getUniqueId())) return; final PersistentDataContainer dataContainer = onlinePlayer.getPersistentDataContainer(); if ( - !dataContainer.has(AEFKey.CONNECT_MSG_TOGGLE.getKey()) ? connectionMsgsOnByDefault : + !dataContainer.has(AEFKey.CONNECT_MSG_TOGGLE.getKey()) ? config.connectionMsgsAreOnByDefault : dataContainer.get(AEFKey.CONNECT_MSG_TOGGLE.getKey(), PersistentDataType.BOOLEAN) ) { onlinePlayer.sendMessage(AnarchyExploitFixes.getLang(onlinePlayer.locale()).misc_leaveMessage diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/misc/MaskKickMessages.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/misc/MaskKickMessages.java index a1bd32ea0..dc1bbc63e 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/misc/MaskKickMessages.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/misc/MaskKickMessages.java @@ -11,7 +11,7 @@ public class MaskKickMessages extends AEFModule implements Listener { public MaskKickMessages() { - super("misc.kicks.mask-kick-messages"); + super("misc.kicks.mask-kick-messages", false); config.addComment(configPath, "Configure mask message in lang folder."); } @@ -20,11 +20,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath, false); - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/misc/PreventMessageKick.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/misc/PreventMessageKick.java index 63ba6f974..e1882ec31 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/misc/PreventMessageKick.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/misc/PreventMessageKick.java @@ -18,7 +18,7 @@ public class PreventMessageKick extends AEFModule implements Listener { private final Set kickMessagesToListenTo; public PreventMessageKick() { - super("misc.kicks.prevent-message-kick"); + super("misc.kicks.prevent-message-kick", false); config.addComment(configPath + ".enable", "Cancels the kick for specific kick messages."); this.kickMessagesToListenTo = config.getList(configPath + ".kick-messages-to-listen-to", List.of("Kicked for spamming", "Stop spamming!")) @@ -32,11 +32,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/packets/BedTrap.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/packets/BedTrap.java index dd5079f81..08d83d2f3 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/packets/BedTrap.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/packets/BedTrap.java @@ -6,6 +6,7 @@ import com.github.retrooper.packetevents.PacketEvents; import com.github.retrooper.packetevents.event.PacketListenerPriority; import com.github.retrooper.packetevents.event.PacketReceiveEvent; +import com.github.retrooper.packetevents.protocol.ConnectionState; import com.github.retrooper.packetevents.protocol.packettype.PacketType; import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientClientStatus; import me.xginko.aef.utils.PlatformUtil; @@ -18,72 +19,82 @@ import org.bukkit.event.entity.PlayerDeathEvent; import java.time.Duration; +import java.util.Collections; import java.util.Set; import java.util.UUID; -import java.util.concurrent.CopyOnWriteArraySet; +import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; public class BedTrap extends PacketModule implements Listener { - private static final Set DEAD_PLAYERS = new CopyOnWriteArraySet<>(); - private final Cache playerDeathNearBedCount; + private final long timeInSeconds; private final int maxDeathsPerTime; private final boolean shouldLog; + private Set deadPlayers; + private Cache playerDeathNearBedCount; + public BedTrap() { - super("preventions.anti-bed-trap", PacketListenerPriority.MONITOR); - config.addComment(configPath + ".enable", """ + super("preventions.anti-bed-trap", false, PacketListenerPriority.MONITOR, """ Resets a players bed respawn they die too many times within\s a certain timeframe."""); this.maxDeathsPerTime = config.getInt(configPath + ".max-deaths-per-time", 7, """ Amount of times player can die until he is determined as bed-trapped."""); - this.playerDeathNearBedCount = Caffeine.newBuilder().expireAfterWrite(Duration.ofSeconds(Math.max(1, - config.getInt(configPath + ".time-in-seconds", 5, """ - "Time until death counter will be reset again.""")))).build(); + this.timeInSeconds = Math.max(1, config.getInt(configPath + ".time-in-seconds", 5, """ + "Time until death counter will be reset again.""")); this.shouldLog = config.getBoolean(configPath+".log", false); } @Override public void enable() { + deadPlayers = Collections.newSetFromMap(new ConcurrentHashMap<>()); + playerDeathNearBedCount = Caffeine.newBuilder().expireAfterWrite(Duration.ofSeconds(timeInSeconds)).build(); plugin.getServer().getPluginManager().registerEvents(this, plugin); - if (PlatformUtil.isFolia()) PacketEvents.getAPI().getEventManager().registerListener(asAbstract); - } - - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); + if (PlatformUtil.isFolia()) { + PacketEvents.getAPI().getEventManager().registerListener(asAbstract); + } } @Override public void disable() { HandlerList.unregisterAll(this); - if (PlatformUtil.isFolia()) PacketEvents.getAPI().getEventManager().unregisterListener(asAbstract); + if (PlatformUtil.isFolia()) { + PacketEvents.getAPI().getEventManager().unregisterListener(asAbstract); + } + if (deadPlayers != null) { + deadPlayers.clear(); + deadPlayers = null; + } + if (playerDeathNearBedCount != null) { + playerDeathNearBedCount.invalidateAll(); + playerDeathNearBedCount.cleanUp(); + playerDeathNearBedCount = null; + } } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) private void onPlayerDeath(PlayerDeathEvent event) { if (PlatformUtil.isFolia()) { - DEAD_PLAYERS.add(event.getPlayer().getUniqueId()); + deadPlayers.add(event.getPlayer().getUniqueId()); } } @SuppressWarnings("deprecation") @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) private void onPlayerPostRespawn(PlayerPostRespawnEvent event) { - Player player = event.getPlayer(); if (!event.isBedSpawn()) return; - if (playerDeathNearBedCount.get(player.getUniqueId(), k -> new AtomicInteger()).incrementAndGet() <= maxDeathsPerTime) { + if (playerDeathNearBedCount.get(event.getPlayer().getUniqueId(), k -> new AtomicInteger()).incrementAndGet() <= maxDeathsPerTime) { return; } - player.getScheduler().execute(plugin, () -> { + event.getPlayer().getScheduler().execute(plugin, () -> { try { - player.setRespawnLocation(null, true); + event.getPlayer().setRespawnLocation(null, true); } catch (NoSuchMethodError e) { - player.setBedSpawnLocation(null, true); + event.getPlayer().setBedSpawnLocation(null, true); } - if (shouldLog) info("Reset bed respawn of potentially bed-trapped player '" + player.getName() + "'"); + if (shouldLog) info("Reset bed respawn of potentially bed-trapped player '" + event.getPlayer().getName() + "'"); }, null, 1L); } @@ -94,14 +105,14 @@ private void onPlayerPostRespawn(PlayerPostRespawnEvent event) { @SuppressWarnings("deprecation") public void onPacketReceive(PacketReceiveEvent event) { if (event.isCancelled()) return; + if (event.getConnectionState() != ConnectionState.PLAY) return; if (event.getPacketType() != PacketType.Play.Client.CLIENT_STATUS) return; - WrapperPlayClientClientStatus packet = new WrapperPlayClientClientStatus(event); - if (packet.getAction() != WrapperPlayClientClientStatus.Action.PERFORM_RESPAWN) return; + if (new WrapperPlayClientClientStatus(event).getAction() != WrapperPlayClientClientStatus.Action.PERFORM_RESPAWN) return; - Player player = (Player) event.getPlayer(); + Player player = event.getPlayer(); if (player == null) return; - if (!DEAD_PLAYERS.contains(player.getUniqueId()) && !player.isDead()) { + if (!deadPlayers.contains(player.getUniqueId()) && !player.isDead()) { return; } @@ -121,8 +132,7 @@ public void onPacketReceive(PacketReceiveEvent event) { if (shouldLog) info("Reset bed respawn of potentially bed-trapped player '" + player.getName() + "'"); - - DEAD_PLAYERS.remove(player.getUniqueId()); + deadPlayers.remove(player.getUniqueId()); }, null, 20L); } } \ No newline at end of file diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/packets/BeehiveCoordinates.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/packets/BeehiveCoordinates.java index f67519012..df0e13b2d 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/packets/BeehiveCoordinates.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/packets/BeehiveCoordinates.java @@ -16,8 +16,7 @@ public class BeehiveCoordinates extends PacketModule { private final String[] entityDataTagsToRemove; public BeehiveCoordinates() { - super("patches.remove-beehive-coordinates", PacketListenerPriority.HIGHEST); - config.addComment(configPath + ".enable", """ + super("patches.remove-beehive-coordinates", true, PacketListenerPriority.HIGHEST, """ Patches an exploit that allows players to obtain another player's\s coordinates by trading them for Beehives or Beenests.\s If the traded item contains any bees, the stored bee's NBT data can\s @@ -35,11 +34,6 @@ public BeehiveCoordinates() { .toArray(new String[0]); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", true); - } - @Override public void onPacketSend(PacketSendEvent event) { if (event.isCancelled()) return; diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/packets/BigMessages.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/packets/BigMessages.java index 244e8f5e7..2c353ac08 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/packets/BigMessages.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/packets/BigMessages.java @@ -13,19 +13,13 @@ public class BigMessages extends PacketModule { private final boolean log, kick; public BigMessages() { - super("patches.message-char-limit", PacketListenerPriority.HIGHEST); - config.addComment(configPath + ".enable", """ + super("patches.message-char-limit", true, PacketListenerPriority.HIGHEST, """ Sets a character limit for command and message packets to prevent a lag exploit."""); this.charLimit = config.getInt(configPath + ".max-characters", 256); this.log = config.getBoolean(configPath + ".log", false); this.kick = config.getBoolean(configPath + ".kick-player", false); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", true); - } - @Override public void onPacketReceive(PacketReceiveEvent event) { if (event.isCancelled()) return; diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/packets/InventoryLag.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/packets/InventoryLag.java index e1e2bd18d..e8676ff8b 100644 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/packets/InventoryLag.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/packets/InventoryLag.java @@ -34,15 +34,15 @@ public class InventoryLag extends PacketModule implements Listener { - private final Cache playerDataCache; private final Set measuredPacketTypes; - private final long rateLimitBytes, lockoutBytes, lockoutMillis; + private final long playerCacheMillis, rateLimitBytes, lockoutBytes, lockoutMillis; private final int screenOpenLimit, screenOpenDelay; private final boolean closeInventory, log; + private Cache playerDataCache; + public InventoryLag() { - super("patches.inventory-lag", PacketListenerPriority.HIGHEST); - config.addComment(configPath + ".enable", """ + super("patches.inventory-lag", false, PacketListenerPriority.HIGHEST, """ Checks if a player is requesting unusual amounts of traffic from the server\s using ItemStacks.\s If a player exceeds the limit, they will be put on a cooldown, during which\s @@ -53,10 +53,9 @@ public InventoryLag() { Whether to immediately close any open inventory of the player on limit exceed\s Note: Closing has to be scheduled so it will take a bit if the server is heavily\s lagging."""); - this.playerDataCache = Caffeine.newBuilder().expireAfterWrite(Duration.ofMillis(Math.max(1L, - config.getLong(configPath + ".byte-data-keep-time-millis", 30_000, """ - The time in millis in which to check if the player exceeded the limit.\s - Needs to be at least as long as your lockout duration millis.""")))).build(); + this.playerCacheMillis = Math.max(1L, config.getLong(configPath + ".byte-data-keep-time-millis", 30_000, """ + The time in millis in which to check if the player exceeded the limit.\s + Needs to be at least as long as your lockout duration millis.""")); this.rateLimitBytes = config.getLong(configPath + ".rate-limit.bytesize-limit", 8_000_000, """ The limit in bytes the server has sent the server in the form of ItemStacks,\s before the player will be put on a rate-limit.\s @@ -88,13 +87,9 @@ public InventoryLag() { .collect(Collectors.toCollection(HashSet::new)); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void enable() { + playerDataCache = Caffeine.newBuilder().expireAfterWrite(Duration.ofMillis(playerCacheMillis)).build(); plugin.getServer().getPluginManager().registerEvents(this, plugin); PacketEvents.getAPI().getEventManager().registerListener(asAbstract); } @@ -103,6 +98,11 @@ public void enable() { public void disable() { HandlerList.unregisterAll(this); PacketEvents.getAPI().getEventManager().unregisterListener(asAbstract); + if (playerDataCache != null) { + playerDataCache.invalidateAll(); + playerDataCache.cleanUp(); + playerDataCache = null; + } } @Override diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/packets/MapCursorLag.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/packets/MapCursorLag.java index 196575a3f..a1d22ec18 100644 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/packets/MapCursorLag.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/packets/MapCursorLag.java @@ -14,29 +14,22 @@ import org.bukkit.event.HandlerList; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerInteractEntityEvent; -import org.bukkit.event.world.ChunkLoadEvent; +import org.bukkit.event.world.EntitiesLoadEvent; public class MapCursorLag extends PacketModule implements Listener { public MapCursorLag() { - super("patches.map-cursor-lag-patch", PacketListenerPriority.HIGHEST); - config.addComment(configPath + ".enable", """ + super("patches.map-cursor-lag-patch", false, PacketListenerPriority.HIGHEST, """ Patches the famous stacked map cursor lag that causes both\s client and server crashes."""); } @Override public void enable() { - if (EntityUtil.MAP_SET_TRACKING_POS_AVAILABLE) - plugin.getServer().getPluginManager().registerEvents(this, plugin); + plugin.getServer().getPluginManager().registerEvents(this, plugin); PacketEvents.getAPI().getEventManager().registerListener(asAbstract); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); @@ -52,14 +45,9 @@ public void onPacketSend(PacketSendEvent event) { } } - /* - For 1.16 and up - */ @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - private void onChunkLoad(ChunkLoadEvent event) { - if (event.isNewChunk()) return; - - for (Entity entity : event.getChunk().getEntities()) { + private void onEntitiesLoad(EntitiesLoadEvent event) { + for (Entity entity : event.getEntities()) { if (EntityUtil.ITEM_FRAMES.contains(entity.getType())) { EntityUtil.disableMapPositionCursor((ItemFrame) entity); } @@ -68,9 +56,8 @@ private void onChunkLoad(ChunkLoadEvent event) { @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) private void onInteract(PlayerInteractEntityEvent event) { - Entity rightClicked = event.getRightClicked(); - if (EntityUtil.ITEM_FRAMES.contains(rightClicked.getType())) { - EntityUtil.disableMapPositionCursor((ItemFrame) rightClicked); + if (EntityUtil.ITEM_FRAMES.contains(event.getRightClicked().getType())) { + EntityUtil.disableMapPositionCursor((ItemFrame) event.getRightClicked()); } } } diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/packets/PacketModule.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/packets/PacketModule.java index cf4275353..d9cf7d734 100644 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/packets/PacketModule.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/packets/PacketModule.java @@ -9,16 +9,19 @@ import me.xginko.aef.utils.models.ExpiringSet; import java.time.Duration; -import java.util.Set; import java.util.UUID; public abstract class PacketModule extends AEFModule implements PacketListener { protected final PacketListenerAbstract asAbstract; - private final Set loggingCooldown; + protected final ExpiringSet loggingCooldown; - public PacketModule(String configPath, PacketListenerPriority priority) { - super(configPath); + public PacketModule(String configPath, boolean enabledByDefault, PacketListenerPriority priority) { + this(configPath, enabledByDefault, priority, null); + } + + public PacketModule(String configPath, boolean enabledByDefault, PacketListenerPriority priority, String comment) { + super(configPath, enabledByDefault, comment); this.asAbstract = asAbstract(priority); // Otherwise will log for each received packet, which would be a LOT this.loggingCooldown = new ExpiringSet<>(Duration.ofMinutes(5)); @@ -35,11 +38,9 @@ public void disable() { } public void onCancel(boolean log, boolean kick, User sender) { - if (log) { - if (!loggingCooldown.contains(sender.getUUID())) { - info(sender.getName() + " failed to trigger exploit."); - loggingCooldown.add(sender.getUUID()); - } + if (log && !loggingCooldown.contains(sender.getUUID())) { + info(sender.getName() + " failed to trigger exploit."); + loggingCooldown.add(sender.getUUID()); } if (kick) { diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/packets/PurpurBeehiveCrash.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/packets/PurpurBeehiveCrash.java index 4f6967ee9..37eb55fbd 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/packets/PurpurBeehiveCrash.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/packets/PurpurBeehiveCrash.java @@ -23,8 +23,7 @@ public class PurpurBeehiveCrash extends PacketModule { private final boolean log, kick; public PurpurBeehiveCrash() { - super("patches.beehive-crash-patch", PacketListenerPriority.HIGHEST); - config.addComment(configPath + ".enable", """ + super("patches.beehive-crash-patch", PlatformUtil.isPurpur(), PacketListenerPriority.HIGHEST, """ Patches a server crash exploit exclusive to Purpur servers.\s This exploit works due to PurpurClient having a feature that\s lets clients request stored data of a clicked beehive from\s @@ -38,11 +37,6 @@ public PurpurBeehiveCrash() { this.kick = config.getBoolean(configPath + ".kick-player", false); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", PlatformUtil.isPurpur()); - } - @Override public void onPacketReceive(PacketReceiveEvent event) { if (event.isCancelled() || event.getPlayer() == null) return; diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/packets/SequenceCrash.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/packets/SequenceCrash.java index 6a4fe8a49..003316934 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/packets/SequenceCrash.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/packets/SequenceCrash.java @@ -13,8 +13,7 @@ public class SequenceCrash extends PacketModule { private final boolean log, kick; public SequenceCrash() { - super("patches.sequence-crash-patch", PacketListenerPriority.HIGHEST); - config.addComment(configPath + ".enable", """ + super("patches.sequence-crash-patch", true, PacketListenerPriority.HIGHEST, """ Patches a variety of lag/crash exploits that involves sending packets\s with invalid sequences."""); this.log = config.getBoolean(configPath + ".log", false); @@ -23,7 +22,7 @@ public SequenceCrash() { @Override public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", true) && PlatformUtil.getMinecraftVersion() >= 19; + return configEnabled && PlatformUtil.getMinecraftVersion() >= 19; } @Override diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/packets/SignLag.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/packets/SignLag.java index 805b64ab0..844990245 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/packets/SignLag.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/packets/SignLag.java @@ -1,5 +1,6 @@ package me.xginko.aef.modules.packets; +import com.github.retrooper.packetevents.PacketEvents; import com.github.retrooper.packetevents.event.PacketListenerPriority; import com.github.retrooper.packetevents.event.PacketReceiveEvent; import com.github.retrooper.packetevents.protocol.packettype.PacketType; @@ -11,19 +12,19 @@ public class SignLag extends PacketModule { - private final ExpiringSet cooldowns; + private final long cooldownMillis; private final int line_char_limit, total_char_limit; private final boolean log, kick; + private ExpiringSet cooldowns; + public SignLag() { - super("patches.sign-lag", PacketListenerPriority.HIGHEST); - config.addComment(configPath + ".enable", """ + super("patches.sign-lag", true, PacketListenerPriority.HIGHEST, """ Patches a lag exploit that involves sending specific oversized\s sign edit packets."""); - this.cooldowns = new ExpiringSet<>(Duration.ofMillis(Math.max(1, - config.getInt(configPath + ".packet-delay-in-ticks", 10, - "How many ticks a player needs to wait to be able to send\n" + - "another sign update packet (renaming or writing).")) * 50L)); + this.cooldownMillis = Math.max(1, config.getInt(configPath + ".packet-delay-in-ticks", 10, + "How many ticks a player needs to wait to be able to send\n" + + "another sign update packet (renaming or writing).")) * 50L; this.line_char_limit = config.getInt(configPath + ".line-character-limit", 80, "Vanilla limit is 384 characters per line, which can be too much."); this.total_char_limit = config.getInt(configPath + ".total-char-limit", 384, @@ -33,8 +34,19 @@ public SignLag() { } @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", true); + public void enable() { + cooldowns = new ExpiringSet<>(Duration.ofMillis(cooldownMillis)); + PacketEvents.getAPI().getEventManager().registerListener(asAbstract); + } + + @Override + public void disable() { + PacketEvents.getAPI().getEventManager().unregisterListener(asAbstract); + if (cooldowns != null) { + cooldowns.clear(); + cooldowns.cleanUp(); + cooldowns = null; + } } @Override diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/packets/TabCompleteCrash.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/packets/TabCompleteCrash.java index 399e7773f..6f422fa57 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/packets/TabCompleteCrash.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/packets/TabCompleteCrash.java @@ -6,24 +6,21 @@ import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientTabComplete; import org.bukkit.permissions.ServerOperator; +import java.util.List; + public class TabCompleteCrash extends PacketModule { - private static final String[] ABUSABLE_SEQUENCES = { "@", "[", "nbt", "=", "{", "}", "]" }; + private final String[] sequences; private final boolean log, kick; public TabCompleteCrash() { - super("patches.tab-complete-crash-patch", PacketListenerPriority.HIGHEST); - config.addComment(configPath + ".enable", """ + super("patches.tab-complete-crash-patch", true, PacketListenerPriority.HIGHEST, """ Patches two lag exploits and an instant server shutdown exploit that\s works by sending a malicious TabComplete packet that triggers a\s StackOverflowError inside the TagParser class."""); this.log = config.getBoolean(configPath + ".log", false); this.kick = config.getBoolean(configPath + ".kick-player", false); - } - - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", true); + this.sequences = config.getList("characters", List.of("@", "[", "nbt", "=", "{", "}", "]")).toArray(new String[0]); } @Override @@ -51,8 +48,8 @@ public void onPacketReceive(PacketReceiveEvent event) { if (event.getPlayer() == null || ((ServerOperator) event.getPlayer()).isOp()) return; - for (String sequence : ABUSABLE_SEQUENCES) { - if (text.indexOf(sequence) != -1) { + for (String sequence : sequences) { + if (text.contains(sequence)) { event.setCancelled(true); onCancel(log, kick, event.getUser()); return; diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/packets/WindowClickCrash.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/packets/WindowClickCrash.java index e33595b7b..bae3e3b35 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/packets/WindowClickCrash.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/packets/WindowClickCrash.java @@ -11,8 +11,7 @@ public class WindowClickCrash extends PacketModule { private final boolean log, kick; public WindowClickCrash() { - super("patches.window-click-crash-patch", PacketListenerPriority.HIGHEST); - config.addComment(configPath + ".enable", """ + super("patches.window-click-crash-patch", true, PacketListenerPriority.HIGHEST, """ Patches a variety of different lag and crash methods that work\s by sending invalid Window Click packets, causing the server to\s dump error logs until it runs out of memory."""); @@ -20,15 +19,11 @@ public WindowClickCrash() { this.kick = config.getBoolean(configPath + ".kick-player", false); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", true); - } - @Override public void onPacketReceive(PacketReceiveEvent event) { if (event.isCancelled()) return; if (event.getPacketType() != PacketType.Play.Client.CLICK_WINDOW) return; + WrapperPlayClientClickWindow packet = new WrapperPlayClientClickWindow(event); int button = packet.getButton(); diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/patches/GodMode.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/patches/GodMode.java index 3d4b0d14a..55a7e7da4 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/patches/GodMode.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/patches/GodMode.java @@ -15,8 +15,7 @@ public class GodMode extends AEFModule implements Listener { public GodMode() { - super("patches.experimental-godmode-patch"); - config.addComment(configPath, """ + super("patches.experimental-godmode-patch", false, """ Removes entities or players if they are invalid, dead or not located within a ticking chunk. Not sure if this works."""); } @@ -26,11 +25,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath, false); - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/patches/ItemDataBan.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/patches/ItemDataBan.java index 130b1502d..225d1b9fe 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/patches/ItemDataBan.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/patches/ItemDataBan.java @@ -26,13 +26,14 @@ public class ItemDataBan extends AEFModule implements Listener { - private final Cache cachedItemSizes, cachedInventorySizes; + private final long itemSizeCacheMillis, inventorySizeCacheMillis; private final int maxBookSize, maxItemSize, maxInventorySize, maxAuthorChars, maxTitleChars, maxPages; private final boolean useUTF16, kickOnBigBook; + private Cache cachedItemSizes, cachedInventorySizes; + public ItemDataBan() { - super("patches.anti-item-ban"); - this.config.addComment(configPath+".enable", """ + super("patches.anti-item-ban", false, """ More commonly known as book-ban:\s Prevents player's getting banned from items with big nbt/compound data.\s This check applies to all item data, not just books."""); @@ -50,31 +51,34 @@ public ItemDataBan() { this.maxPages = config.getInt(configPath + ".max-pages", 100); this.maxItemSize = config.getInt(configPath + ".max-item-size", 56000); this.maxInventorySize = config.getInt(configPath + ".max-inventory-size", 2050000); - this.cachedItemSizes = Caffeine.newBuilder().expireAfterWrite(Duration.ofMillis(Math.max(1, - config.getInt(configPath + ".dropped-items-size-cache-ticks", 120, """ - How long in ticks a dropped item's size should be cached after\s - checking.""")) * 50L - )).build(); - this.cachedInventorySizes = Caffeine.newBuilder().expireAfterWrite(Duration.ofMillis(Math.max(1, - config.getInt(configPath + ".player-inventory-size-cache-ticks", 20, """ - How long in ticks a player's inventory size should be cached after\s - checking.""")) * 50L - )).build(); + this.itemSizeCacheMillis = Math.max(1,config.getInt(configPath + ".dropped-items-size-cache-ticks", 120, """ + How long in ticks a dropped item's size should be cached after\s + checking.""")) * 50L; + this.inventorySizeCacheMillis = Math.max(1, config.getInt(configPath + ".player-inventory-size-cache-ticks", 20, """ + How long in ticks a player's inventory size should be cached after\s + checking.""")) * 50L; } @Override public void enable() { + cachedItemSizes = Caffeine.newBuilder().expireAfterWrite(Duration.ofMillis(itemSizeCacheMillis)).build(); + cachedInventorySizes = Caffeine.newBuilder().expireAfterWrite(Duration.ofMillis(inventorySizeCacheMillis)).build(); plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); + if (cachedItemSizes != null) { + cachedItemSizes.invalidateAll(); + cachedItemSizes.cleanUp(); + cachedItemSizes = null; + } + if (cachedInventorySizes != null) { + cachedInventorySizes.invalidateAll(); + cachedInventorySizes.cleanUp(); + cachedInventorySizes = null; + } } @SuppressWarnings("DataFlowIssue") // Legitimate because we make sure no values are null by testing .hasX() diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/patches/TeleportCoordExploit.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/patches/TeleportCoordExploit.java index fd2da8d79..1c32c98d5 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/patches/TeleportCoordExploit.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/patches/TeleportCoordExploit.java @@ -18,8 +18,7 @@ public class TeleportCoordExploit extends AEFModule implements Listener { private final int minDistanceToVanishPlayers; public TeleportCoordExploit() { - super("patches.prevent-teleport-coordinate-exploit"); - config.addComment(configPath + ".enable", """ + super("patches.prevent-teleport-coordinate-exploit", true, """ Patches coordinate exploit for teleportation commands such as /tpa, /home AS WELL as respawn exploits.\s This is done by vanishing the player for x ticks before teleporting."""); @@ -32,11 +31,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); @@ -57,7 +51,7 @@ private void tempVanish(Player player) { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) private void onTeleport(PlayerTeleportEvent event) { switch (event.getCause()) { - case ENDER_PEARL, COMMAND, PLUGIN -> { + case ENDER_PEARL, COMMAND, PLUGIN, UNKNOWN, SPECTATE -> { if (LocationUtil.getRelDistance2D(event.getFrom(), event.getTo()) >= minDistanceToVanishPlayers) { this.tempVanish(event.getPlayer()); } diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/patches/WorldChangeCrash.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/patches/WorldChangeCrash.java index db5d2fd3a..0a220b21f 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/patches/WorldChangeCrash.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/patches/WorldChangeCrash.java @@ -14,34 +14,35 @@ public class WorldChangeCrash extends AEFModule implements Listener { - private final ExpiringSet recentWorldChangers; + private final long worldChangeDelayMillis; private final boolean shouldLog; + private ExpiringSet recentWorldChangers; + public WorldChangeCrash() { - super("patches.prevent-fast-world-teleport-crash"); - config.addComment(configPath + ".enable", """ + super("patches.prevent-fast-world-teleport-crash", false, """ Prevents crash methods that involve very fast teleporting between\s different worlds in a short time."""); - this.recentWorldChangers = new ExpiringSet<>(Duration.ofMillis( - Math.max(1, config.getInt(configPath + ".teleport-delay-millis", 1000, """ - Time in milliseconds until an entity can teleport to another\s - world again.""")))); + this.worldChangeDelayMillis = Math.max(1, config.getInt(configPath + ".teleport-delay-millis", 1000, """ + Time in milliseconds until an entity can teleport to another\s + world again.""")); this.shouldLog = config.getBoolean(configPath + ".log", false); } @Override public void enable() { + recentWorldChangers = new ExpiringSet<>(Duration.ofMillis(worldChangeDelayMillis)); plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); + if (recentWorldChangers != null) { + recentWorldChangers.clear(); + recentWorldChangers.cleanUp(); + recentWorldChangers = null; + } } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/patches/commandsign/CommandSign.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/patches/commandsign/CommandSign.java index 4621b5a6c..6aadc140f 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/patches/commandsign/CommandSign.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/patches/commandsign/CommandSign.java @@ -9,8 +9,7 @@ public class CommandSign extends AEFModule { private final Listener signCommandListener; public CommandSign() { - super("patches.prevent-command-sign"); - config.addComment(configPath + ".enable", """ + super("patches.prevent-command-sign", true, """ Patch signs that have run_command NBT tags attached, allowing the\s to run a command with operator permissions on click.\s Recommended to enable if you had a rogue admin or backdoor incident."""); @@ -22,11 +21,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(signCommandListener, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", true); - } - @Override public void disable() { HandlerList.unregisterAll(signCommandListener); diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/NetherRoof.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/NetherRoof.java index 685d73503..e20cc6515 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/NetherRoof.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/NetherRoof.java @@ -8,12 +8,10 @@ import me.xginko.aef.utils.CachingPermTool; import me.xginko.aef.utils.LocationUtil; import org.bukkit.Location; -import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; -import org.bukkit.entity.Vehicle; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.HandlerList; @@ -29,8 +27,8 @@ public class NetherRoof extends AEFModule implements Listener { private final boolean safe_teleport_enabled; public NetherRoof() { - super("preventions.prevent-nether-roof"); - config.addComment(configPath + ".enable", "Prevent players from going above the nether roof."); + super("preventions.prevent-nether-roof", true, + "Prevent players from going above the nether roof."); this.safe_teleport_enabled = config.getBoolean(configPath + ".safely-teleport-players", true); } @@ -39,11 +37,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", true); - } - @Override public void disable() { HandlerList.unregisterAll(this); @@ -61,12 +54,11 @@ private void onTeleport(PlayerTeleportEvent event) { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) private void onPlayerMove(PlayerMoveEvent event) { - final Player player = event.getPlayer(); if ( - LocationUtil.isNetherCeiling(player.getLocation()) - && !CachingPermTool.hasPermission(AEFPermission.BYPASS_NETHER_ROOF, player) + LocationUtil.isNetherCeiling(event.getPlayer().getLocation()) + && !CachingPermTool.hasPermission(AEFPermission.BYPASS_NETHER_ROOF, event.getPlayer()) ) { - Location belowCeiling = getBelowCeilLocation(player.getLocation()); + Location belowCeiling = getBelowCeilLocation(event.getPlayer().getLocation()); event.setTo(belowCeiling); createSafespace(belowCeiling); } @@ -74,15 +66,14 @@ private void onPlayerMove(PlayerMoveEvent event) { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) private void onVehicleMove(VehicleMoveEvent event) { - final Vehicle vehicle = event.getVehicle(); - if (!LocationUtil.isNetherCeiling(vehicle.getLocation())) return; + if (!LocationUtil.isNetherCeiling(event.getVehicle().getLocation())) return; - for (Entity passenger : vehicle.getPassengers()) { + for (Entity passenger : event.getVehicle().getPassengers()) { if (passenger.getType() == XEntityType.PLAYER.get() && CachingPermTool.hasPermission(AEFPermission.BYPASS_NETHER_ROOF, (Player) passenger)) return; } - for (Entity passenger : vehicle.getPassengers()) { + for (Entity passenger : event.getVehicle().getPassengers()) { if (passenger.getType() == XEntityType.PLAYER.get()) { teleportFromCeiling((Player) passenger); } else { @@ -91,20 +82,19 @@ private void onVehicleMove(VehicleMoveEvent event) { } } - vehicle.remove(); + event.getVehicle().remove(); } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) private void onBlockPlace(BlockPlaceEvent event) { - final Player player = event.getPlayer(); - if (CachingPermTool.hasPermission(AEFPermission.BYPASS_NETHER_ROOF, player)) return; + if (CachingPermTool.hasPermission(AEFPermission.BYPASS_NETHER_ROOF, event.getPlayer())) return; if (LocationUtil.isNetherCeiling(event.getBlock().getLocation())) { event.setCancelled(true); } - if (LocationUtil.isNetherCeiling(player.getLocation())) { - teleportFromCeiling(player); + if (LocationUtil.isNetherCeiling(event.getPlayer().getLocation())) { + teleportFromCeiling(event.getPlayer()); } } @@ -128,30 +118,30 @@ private void createSafespace(Location location) { plugin.getServer().getRegionScheduler().execute(plugin, location, () -> { // Check block above for liquid or falling block Block blockAboveHead = location.clone().add(0, 2, 0).getBlock(); - if (isUnsafe(blockAboveHead) && blockAboveHead.getType() != XMaterial.NETHER_PORTAL.parseMaterial()) - blockAboveHead.setType(XMaterial.NETHERRACK.parseMaterial(), false); + if (isUnsafe(blockAboveHead) && blockAboveHead.getType() != XMaterial.NETHER_PORTAL.get()) + blockAboveHead.setType(XMaterial.NETHERRACK.get(), false); // Create an air pocket for the player Block blockAtPlayerLegs = location.getBlock(); - if (blockAtPlayerLegs.getType() != Material.AIR && blockAtPlayerLegs.getType() != XMaterial.NETHER_PORTAL.parseMaterial()) - blockAtPlayerLegs.setType(Material.AIR, false); + if (blockAtPlayerLegs.getType() != XMaterial.AIR.get() && blockAtPlayerLegs.getType() != XMaterial.NETHER_PORTAL.get()) + blockAtPlayerLegs.setType(XMaterial.AIR.get(), false); Block blockAtPlayerTorso = blockAtPlayerLegs.getRelative(BlockFace.UP); - if (blockAtPlayerTorso.getType() != Material.AIR && blockAtPlayerTorso.getType() != XMaterial.NETHER_PORTAL.parseMaterial()) - blockAtPlayerTorso.setType(Material.AIR, false); + if (blockAtPlayerTorso.getType() != XMaterial.AIR.get() && blockAtPlayerTorso.getType() != XMaterial.NETHER_PORTAL.get()) + blockAtPlayerTorso.setType(XMaterial.AIR.get(), false); // Check all sides of air pocket for liquids and fill with netherrack for (int i = 0; i < 2; i++) { Block airPocketBlock = blockAtPlayerLegs.getRelative(BlockFace.UP, i); for (BlockFace face : CARDINAL_FACES) { Block around = airPocketBlock.getRelative(face); - if (isUnsafe(around)) around.setType(XMaterial.NETHERRACK.parseMaterial(), false); + if (isUnsafe(around)) around.setType(XMaterial.NETHERRACK.get(), false); } } // Create block below feet if not solid Block blockBelowFeet = blockAtPlayerLegs.getRelative(BlockFace.DOWN); - if (isUnsafe(blockBelowFeet) || blockBelowFeet.getType() == XMaterial.NETHER_PORTAL.parseMaterial()) - blockBelowFeet.setType(XMaterial.NETHERRACK.parseMaterial(), true); + if (isUnsafe(blockBelowFeet) || blockBelowFeet.getType() == XMaterial.NETHER_PORTAL.get()) + blockBelowFeet.setType(XMaterial.NETHERRACK.get(), true); }); } diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/PreventNonSurvival.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/PreventNonSurvival.java index caf08aeb0..e9c4f8743 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/PreventNonSurvival.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/PreventNonSurvival.java @@ -23,8 +23,7 @@ public class PreventNonSurvival extends AEFModule implements Listener { private final boolean shouldLog; public PreventNonSurvival() { - super("preventions.prevent-non-survival-players"); - config.addComment(configPath + ".enable", """ + super("preventions.prevent-non-survival-players", false, """ Checks if player is in survival and if not, puts him back into survival.\s Useful if you had a backdoor incident."""); this.shouldLog = config.getBoolean(configPath+".log", false); @@ -37,11 +36,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/PreventOppedPlayers.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/PreventOppedPlayers.java index 3cb3ac6ef..bd7abb886 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/PreventOppedPlayers.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/PreventOppedPlayers.java @@ -22,8 +22,8 @@ public class PreventOppedPlayers extends AEFModule implements Listener { private final boolean shouldLog; public PreventOppedPlayers() { - super("preventions.prevent-opped-players"); - config.addComment(configPath + ".enable", "Useful if you suspect a backdoor has happened."); + super("preventions.prevent-opped-players", false, + "Useful if you suspect a backdoor has happened."); this.shouldLog = config.getBoolean(configPath+".log", false); this.allowedOperators = new HashSet<>(config.getList(configPath + ".whitelisted-players", List.of("Notch"))); } @@ -33,11 +33,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/blockbreak/PistonExplodePermBlockRemoval.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/blockbreak/PistonExplodePermBlockRemoval.java index 1f70fe0d3..d8a2d83a2 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/blockbreak/PistonExplodePermBlockRemoval.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/blockbreak/PistonExplodePermBlockRemoval.java @@ -1,8 +1,8 @@ package me.xginko.aef.modules.preventions.blockbreak; +import com.cryptomorin.xseries.XMaterial; import me.xginko.aef.modules.AEFModule; import me.xginko.aef.utils.MaterialUtil; -import org.bukkit.Material; import org.bukkit.block.BlockFace; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; @@ -19,7 +19,7 @@ public class PistonExplodePermBlockRemoval extends AEFModule implements Listener private final Set whitelistedWorlds; public PistonExplodePermBlockRemoval() { - super("preventions.permanent-block-breaking.by-exploding-pistons"); + super("preventions.permanent-block-breaking.by-exploding-pistons", true); this.whitelistedWorlds = new HashSet<>(config.getList(configPath + ".whitelisted-worlds", List.of("example_world_name"))); config.getBoolean(configPath + ".only-for-portals-and-gateways", false, "If enabled, will only protect portals and end gateways"); @@ -30,11 +30,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", true); - } - @Override public void disable() { HandlerList.unregisterAll(this); @@ -52,7 +47,7 @@ private void onEntityExplode(EntityExplodeEvent event) { if (MaterialUtil.INDESTRUCTIBLES.contains(block.getRelative(face).getType())) { // Schedule remove task for each piston location to ensure we are always on the correct thread plugin.getServer().getRegionScheduler().runDelayed(plugin, block.getLocation(), remove -> - block.setType(Material.AIR), 5); + block.setType(XMaterial.AIR.get()), 5); return true; // Remove piston from the list of blocks to be affected by the explosion } } diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/blockbreak/PistonPlaceWhileRetractPermBlockRemoval.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/blockbreak/PistonPlaceWhileRetractPermBlockRemoval.java index e33586bf4..60e11aa98 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/blockbreak/PistonPlaceWhileRetractPermBlockRemoval.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/blockbreak/PistonPlaceWhileRetractPermBlockRemoval.java @@ -17,7 +17,7 @@ public class PistonPlaceWhileRetractPermBlockRemoval extends AEFModule implement private final Set whitelistedWorlds; public PistonPlaceWhileRetractPermBlockRemoval() { - super("preventions.permanent-block-breaking.by-placing-piston-on-retract"); + super("preventions.permanent-block-breaking.by-placing-piston-on-retract", true); this.whitelistedWorlds = new HashSet<>(config.getList(configPath + ".whitelisted-worlds", List.of("example_world_name"))); } @@ -27,11 +27,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", true); - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/blockbreak/StructureGrowPermBlockRemoval.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/blockbreak/StructureGrowPermBlockRemoval.java index b67e207be..a10e4dc97 100644 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/blockbreak/StructureGrowPermBlockRemoval.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/blockbreak/StructureGrowPermBlockRemoval.java @@ -14,8 +14,7 @@ public class StructureGrowPermBlockRemoval extends AEFModule implements Listener { public StructureGrowPermBlockRemoval() { - super("preventions.permanent-block-breaking.by-growing-structures"); - config.addComment(configPath + ".enable", """ + super("preventions.permanent-block-breaking.by-growing-structures", true, """ Prevents removal of permanent blocks by growing structures\s like mushrooms into them."""); } @@ -25,11 +24,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", true); - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/portals/EndPortalDestruction.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/portals/EndPortalDestruction.java index f20fa5232..38ca1c944 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/portals/EndPortalDestruction.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/portals/EndPortalDestruction.java @@ -32,7 +32,7 @@ public class EndPortalDestruction extends AEFModule implements Listener { private final boolean shouldLog; public EndPortalDestruction() { - super("preventions.portals.prevent-destroying-end-portals"); + super("preventions.portals.prevent-destroying-end-portals", true); this.shouldLog = config.getBoolean(configPath + ".show-logs", true); this.endBedrockProtectRadius = config.getInt(configPath + ".end.bedrock-protection-radius-blocks", 8); this.pillars = config.getList(configPath + ".end.pillar-blocks", @@ -68,11 +68,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", true); - } - @Override public void disable() { HandlerList.unregisterAll(this); @@ -88,14 +83,14 @@ private void onBlockDispense(BlockDispenseEvent event) { private boolean isNearEndPortal(Block dispenser) { for (BlockFace face : BlockFace.values()) { - if (dispenser.getRelative(face).getType() == XMaterial.END_PORTAL.parseMaterial()) return true; + if (dispenser.getRelative(face).getType() == XMaterial.END_PORTAL.get()) return true; } return false; } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) private void onPlayerBucketEvent(PlayerBucketEmptyEvent event) { - if (event.getBlockClicked().getRelative(event.getBlockFace()).getType() == XMaterial.END_PORTAL.parseMaterial()) { + if (event.getBlockClicked().getRelative(event.getBlockFace()).getType() == XMaterial.END_PORTAL.get()) { event.setCancelled(true); if (shouldLog) info("Prevented "+event.getPlayer().getName()+" from destroying an end portal using a bucket!"); } @@ -160,6 +155,6 @@ private boolean isWithinEndProtectedRadius(Location location) { } private boolean isEndPortal(Material material) { - return material == XMaterial.END_PORTAL_FRAME.parseMaterial() || material == XMaterial.END_PORTAL.parseMaterial(); + return material == XMaterial.END_PORTAL_FRAME.get() || material == XMaterial.END_PORTAL.get(); } } diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/portals/PreventAllEntitiesInPortals.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/portals/PreventAllEntitiesInPortals.java index 0eaba2ead..7ff03aaf6 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/portals/PreventAllEntitiesInPortals.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/portals/PreventAllEntitiesInPortals.java @@ -13,8 +13,7 @@ public class PreventAllEntitiesInPortals extends AEFModule implements Listener { public PreventAllEntitiesInPortals() { - super("preventions.portals.prevent-all-entities-in-portals"); - config.addComment(configPath, """ + super("preventions.portals.prevent-all-entities-in-portals", false, """ Only enable if you must. Does not affect players. CAUTION: Will kill the entity on folia due to broken portal event."""); } @@ -24,11 +23,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath, false); - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/portals/PreventPortalTraps.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/portals/PreventPortalTraps.java index d993a11ce..959f9e39b 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/portals/PreventPortalTraps.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/portals/PreventPortalTraps.java @@ -25,8 +25,7 @@ public class PreventPortalTraps extends AEFModule implements Listener { private final long tpBackDelayTicks; public PreventPortalTraps() { - super("preventions.portals.prevent-portal-traps"); - config.addComment(configPath + ".enable", """ + super("preventions.portals.prevent-portal-traps", false, """ Teleports a player back to the original location if they have been\s standing in a portal for too long."""); int tpBackDelaySeconds = Math.max(1, config.getInt(configPath + ".wait-time-until-tp-back-in-seconds", 10)); @@ -43,11 +42,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); @@ -57,10 +51,10 @@ public void disable() { private void onPortalUse(PlayerPortalEvent event) { // Does not fire on folia due to broken API final Player player = event.getPlayer(); player.getScheduler().execute(plugin, () -> { - if (player.getLocation().getBlock().getType() == XMaterial.NETHER_PORTAL.parseMaterial()) { + if (player.getLocation().getBlock().getType() == XMaterial.NETHER_PORTAL.get()) { player.teleportAsync(event.getFrom()).thenAccept(tpHappened -> { if (tpHappened) { - player.playSound(player.getLocation(), XSound.BLOCK_PORTAL_TRAVEL.parseSound(), 1.0F, 1.0F); + player.playSound(player.getLocation(), XSound.BLOCK_PORTAL_TRAVEL.get(), 1.0F, 1.0F); } }); } @@ -80,10 +74,10 @@ private void onPortalEnter(EntityPortalEnterEvent event) { // Only portal event portalEnterLocations.put(player.getUniqueId(), from); player.getScheduler().execute(plugin, () -> { - if (player.getLocation().getBlock().getType() == XMaterial.NETHER_PORTAL.parseMaterial()) { + if (player.getLocation().getBlock().getType() == XMaterial.NETHER_PORTAL.get()) { player.teleportAsync(from).thenAccept(tpHappened -> { if (tpHappened) { - player.playSound(player.getLocation(), XSound.BLOCK_PORTAL_TRAVEL.parseSound(), 1.0F, 1.0F); + player.playSound(player.getLocation(), XSound.BLOCK_PORTAL_TRAVEL.get(), 1.0F, 1.0F); } }); } diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/portals/PreventProjectilesInPortals.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/portals/PreventProjectilesInPortals.java index 032d621ef..e14a9d268 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/portals/PreventProjectilesInPortals.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/portals/PreventProjectilesInPortals.java @@ -13,8 +13,8 @@ public class PreventProjectilesInPortals extends AEFModule implements Listener { public PreventProjectilesInPortals() { - super("preventions.portals.prevent-projectiles-in-portals"); - config.addComment(configPath, "Prevents a lag exploit. Might disable some chunk loader designs."); + super("preventions.portals.prevent-projectiles-in-portals", false, + "Prevents a lag exploit. Might disable some chunk loader designs."); } @Override @@ -22,11 +22,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath, false); - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/portals/PreventSpecificEntitiesInPortals.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/portals/PreventSpecificEntitiesInPortals.java index 4a9befc3d..7c57b825d 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/portals/PreventSpecificEntitiesInPortals.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/portals/PreventSpecificEntitiesInPortals.java @@ -16,20 +16,30 @@ import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; +import java.util.stream.Stream; public class PreventSpecificEntitiesInPortals extends AEFModule implements Listener { private final Set forbiddenTypes; public PreventSpecificEntitiesInPortals() { - super("preventions.portals.prevent-specific-types"); - config.addComment(configPath + ".enable", """ + super("preventions.portals.prevent-specific-types", true, """ Configure entities here that you suspect might be used in a dupe\s with portals.\s CAUTION: Will kill the entity on folia due to broken portal event.\s There is sadly no other efficient way."""); - this.forbiddenTypes = config.getList(configPath + ".entities", - List.of("DROPPED_ITEM", "FIREWORK", "PRIMED_TNT", "THROWN_EXP_BOTTLE", "EXPERIENCE_ORB", "ARMOR_STAND"), + List defaults = Stream.of( + XEntityType.ITEM, + XEntityType.FIREWORK_ROCKET, + XEntityType.TNT, + XEntityType.EXPERIENCE_BOTTLE, + XEntityType.EXPERIENCE_ORB, + XEntityType.ARMOR_STAND) + .filter(XEntityType::isSupported) + .map(XEntityType::get) + .map(Enum::name) + .toList(); + this.forbiddenTypes = config.getList(configPath + ".entities", defaults, "Defaults prevent common lag methods.") .stream() .map(configuredType -> { @@ -49,11 +59,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", true); - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/withers/RateLimitWitherSkulls.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/withers/RateLimitWitherSkulls.java index 51fe25dc9..ad8d9310a 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/withers/RateLimitWitherSkulls.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/withers/RateLimitWitherSkulls.java @@ -15,38 +15,50 @@ public class RateLimitWitherSkulls extends AEFModule implements Listener { - private final ExpiringSet targetingPlayers, targetingOther, notTargeting; + private final long playerCooldownMillis, otherCooldownMillis, notargetCooldownMillis; + + private ExpiringSet targetingPlayers, targetingOther, notTargeting; public RateLimitWitherSkulls() { - super("preventions.withers.rate-limit-shooting-skulls"); + super("preventions.withers.rate-limit-shooting-skulls", false); config.addComment(configPath + ".enable", """ This can help combat lag caused by a ton of wither skulls\s spawning but weakens withers."""); - this.targetingPlayers = new ExpiringSet<>(Duration.ofMillis(Math.max(1, - config.getInt(configPath + ".player-target-cooldown-in-ticks", 20, """ - Cooldown until another skull can be shot at a player.""")) * 50L)); - this.targetingOther = new ExpiringSet<>(Duration.ofMillis(Math.max(1, - config.getInt(configPath + ".other-target-cooldown-in-ticks", 40, """ - Cooldown until another skull can be shot at anything\s - else other than a player.""")) * 50L)); - this.notTargeting = new ExpiringSet<>(Duration.ofMillis(Math.max(1, - config.getInt(configPath + ".no-target-cooldown-in-ticks", 100, """ - Cooldown when wither has no target.""")) * 50L)); + this.playerCooldownMillis = Math.max(1, config.getInt(configPath + ".player-target-cooldown-in-ticks", 20, + "Cooldown until another skull will be shot at a player")) * 50L; + this.otherCooldownMillis = Math.max(1, config.getInt(configPath + ".other-target-cooldown-in-ticks", 40, + "Cooldown until another skull can be shot at anything \n" + + "else other than a player.")) * 50L; + this.notargetCooldownMillis = Math.max(1, config.getInt(configPath + ".no-target-cooldown-in-ticks", 100, + "Cooldown when wither has no target")) * 50L; } @Override public void enable() { + targetingPlayers = new ExpiringSet<>(Duration.ofMillis(playerCooldownMillis)); + targetingOther = new ExpiringSet<>(Duration.ofMillis(otherCooldownMillis)); + notTargeting = new ExpiringSet<>(Duration.ofMillis(notargetCooldownMillis)); plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); + if (targetingPlayers != null) { + targetingPlayers.clear(); + targetingPlayers.cleanUp(); + targetingPlayers = null; + } + if (targetingOther != null) { + targetingOther.clear(); + targetingOther.cleanUp(); + targetingOther = null; + } + if (notTargeting != null) { + notTargeting.clear(); + notTargeting.cleanUp(); + notTargeting = null; + } } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/withers/RemoveSkullsOnChunkload.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/withers/RemoveSkullsOnChunkload.java index 6f6c46c88..2155fd509 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/withers/RemoveSkullsOnChunkload.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/withers/RemoveSkullsOnChunkload.java @@ -2,7 +2,6 @@ import com.cryptomorin.xseries.XEntityType; import me.xginko.aef.modules.AEFModule; -import me.xginko.aef.utils.ChunkUtil; import org.bukkit.entity.Entity; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; @@ -14,8 +13,7 @@ public class RemoveSkullsOnChunkload extends AEFModule implements Listener { public RemoveSkullsOnChunkload() { - super("preventions.withers.remove-skulls-on-load"); - config.addComment(configPath, """ + super("preventions.withers.remove-skulls-on-load", true, """ Removes wither skulls when entities get loaded.\s Use if you have a ton of them at spawn and they are causing lag."""); } @@ -25,11 +23,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath, true); - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/withers/WitherSkullDropsAtSpawn.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/withers/WitherSkullDropsAtSpawn.java index f6f0d6650..2d3d11fa1 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/withers/WitherSkullDropsAtSpawn.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/withers/WitherSkullDropsAtSpawn.java @@ -1,9 +1,9 @@ package me.xginko.aef.modules.preventions.withers; +import com.cryptomorin.xseries.XEntityType; import io.github.thatsmusic99.configurationmaster.api.ConfigSection; import me.xginko.aef.modules.AEFModule; import me.xginko.aef.utils.LocationUtil; -import org.bukkit.entity.EntityType; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.HandlerList; @@ -12,15 +12,15 @@ import org.bukkit.util.NumberConversions; import java.util.HashMap; +import java.util.List; import java.util.Map; public class WitherSkullDropsAtSpawn extends AEFModule implements Listener { - private final Map worldsAndTheirRadiuses = new HashMap<>(); + private final Map worldsAndTheirRadiuses; public WitherSkullDropsAtSpawn() { - super("preventions.withers.disable-item-drops-at-spawn"); - config.addComment(configPath + ".enable", + super("preventions.withers.disable-item-drops-at-spawn", false, "Prevents wither skulls from dropping items when they hit a block\n" + "within a certain radius from 00. Can help with lag."); Map defaults = new HashMap<>(); @@ -28,7 +28,9 @@ public WitherSkullDropsAtSpawn() { defaults.put("world_nether", 5000); defaults.put("world_the_end", 5000); ConfigSection section = config.getConfigSection(configPath + ".worlds", defaults); - for (String world : section.getKeys(false)) { + List worlds = section.getKeys(false); + this.worldsAndTheirRadiuses = new HashMap<>(worlds.size()); + for (String world : worlds) { try { double radiusSquared = NumberConversions.square(Integer.parseInt(section.getString(world))); this.worldsAndTheirRadiuses.put(world, radiusSquared); @@ -43,11 +45,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); @@ -55,7 +52,7 @@ public void disable() { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) private void onEntityExplode(EntityExplodeEvent event) { - if (event.getEntityType() != EntityType.WITHER_SKULL) return; + if (event.getEntityType() != XEntityType.WITHER_SKULL.get()) return; if (!worldsAndTheirRadiuses.containsKey(event.getLocation().getWorld().getName())) return; if (LocationUtil.getSquaredDistance2DTo00(event.getLocation()) diff --git a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/withers/WitherSummonAtSpawn.java b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/withers/WitherSummonAtSpawn.java index 4a513c317..0ac380b22 100755 --- a/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/withers/WitherSummonAtSpawn.java +++ b/AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/preventions/withers/WitherSummonAtSpawn.java @@ -15,16 +15,16 @@ import org.bukkit.util.NumberConversions; import java.util.HashMap; +import java.util.List; import java.util.Map; public class WitherSummonAtSpawn extends AEFModule implements Listener { - private final Map worldsAndTheirRadiuses = new HashMap<>(); + private final Map worldsAndTheirRadiuses; private final boolean playersShouldBeInformed; public WitherSummonAtSpawn() { - super("preventions.withers.disable-summon-at-spawn"); - config.addComment(configPath + ".enable", """ + super("preventions.withers.disable-summon-at-spawn", false, """ Disables spawning withers near a configurable radius around\s spawn. Helps if players are generating endless amounts of withers\s to lag the server."""); @@ -34,7 +34,9 @@ public WitherSummonAtSpawn() { defaults.put("world_nether", 5000); defaults.put("world_the_end", 5000); ConfigSection section = config.getConfigSection(configPath + ".worlds", defaults); - for (String world : section.getKeys(false)) { + List worlds = section.getKeys(false); + this.worldsAndTheirRadiuses = new HashMap<>(worlds.size()); + for (String world : worlds) { try { Double radiusSquared = NumberConversions.square(Integer.parseInt(section.getString(world))); this.worldsAndTheirRadiuses.put(world, radiusSquared); @@ -49,11 +51,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/AnarchyExploitFixes.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/AnarchyExploitFixes.java index bcc2722b1..0432916e6 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/AnarchyExploitFixes.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/AnarchyExploitFixes.java @@ -10,6 +10,8 @@ import me.xginko.aef.utils.CachingPermTool; import me.xginko.aef.utils.PlatformUtil; import me.xginko.aef.utils.tickdata.TickReporter; +import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.core.config.Configurator; import org.bstats.bukkit.Metrics; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; @@ -49,6 +51,8 @@ public final class AnarchyExploitFixes extends JavaPlugin { @Override public void onLoad() { PlatformUtil.load(); + // Disable reflection logging because we want to do our own, pretty logging + Configurator.setLevel(AnarchyExploitFixes.class.getPackage().getName() + ".libs.reflections.Reflections", Level.OFF); } @Override diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/AEFModule.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/AEFModule.java index 2fe006b18..44d3f95e5 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/AEFModule.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/AEFModule.java @@ -7,8 +7,6 @@ import me.xginko.aef.utils.models.ConditionalEnableable; import me.xginko.aef.utils.models.Disableable; import me.xginko.aef.utils.models.Enableable; -import org.apache.logging.log4j.Level; -import org.apache.logging.log4j.core.config.Configurator; import org.reflections.Reflections; import org.reflections.scanners.Scanners; @@ -24,8 +22,6 @@ public abstract class AEFModule implements ConditionalEnableable, Disableable { protected static final Set ENABLED_MODULES; static { - // Disable reflection logging for this operation because its just confusing and provides no value. - Configurator.setLevel(AnarchyExploitFixes.class.getPackage().getName() + ".libs.reflections.Reflections", Level.OFF); AVAILABLE_MODULES = new Reflections(AEFModule.class.getPackage().getName()) .get(Scanners.SubTypes.of(AEFModule.class).asClass()) .stream() @@ -36,15 +32,16 @@ public abstract class AEFModule implements ConditionalEnableable, Disableable { ENABLED_MODULES = new HashSet<>(); } - protected final AnarchyExploitFixes plugin; - protected final Config config; + protected final AnarchyExploitFixes plugin = AnarchyExploitFixes.getInstance(); + protected final Config config = AnarchyExploitFixes.config(); + protected final String configPath, logFormat; + protected final boolean configEnabled; public AEFModule(String configPath) { - this.plugin = AnarchyExploitFixes.getInstance(); - this.config = AnarchyExploitFixes.config(); this.configPath = configPath; - shouldEnable(); // Ensure enable option is always first + this.configEnabled = true; + String[] paths = configPath.split("\\."); if (paths.length <= 2) { this.logFormat = "<" + configPath + "> {}"; @@ -53,6 +50,30 @@ public AEFModule(String configPath) { } } + public AEFModule(String configPath, boolean defEnabled) { + this(configPath, defEnabled, null); + } + + public AEFModule(String configPath, boolean defEnabled, String comment) { + this.configPath = configPath; + if (comment == null || comment.isEmpty()) { + this.configEnabled = config.getBoolean(configPath + ".enable", defEnabled); + } else { + this.configEnabled = config.getBoolean(configPath + ".enable", defEnabled, comment); + } + + String[] paths = configPath.split("\\."); + if (paths.length <= 2) { + this.logFormat = "<" + configPath + "> {}"; + } else { + this.logFormat = "<" + paths[paths.length - 2] + "." + paths[paths.length - 1] + "> {}"; + } + } + + public boolean shouldEnable() { + return configEnabled; + } + public static void disableAll() { ENABLED_MODULES.forEach(Disableable::disable); ENABLED_MODULES.clear(); @@ -67,12 +88,11 @@ public static void reloadModules() { if (module.shouldEnable()) { if (module instanceof PacketModule && AnarchyExploitFixes.config().packets_disabled) { module.warn("Cannot enable because you disabled packets in config!"); - continue; + } else { + ENABLED_MODULES.add(module); } - - ENABLED_MODULES.add(module); } - } catch (Throwable t) { // We want to catch everything here if it fails to init + } catch (Throwable t) { AnarchyExploitFixes.prefixedLogger().warn("Failed initialising module class '{}'.", moduleClass.getSimpleName(), t); } } diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/bedrock/FillNetherCeilingOnChunkload.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/bedrock/FillNetherCeilingOnChunkload.java index 66fbdf716..f0f75addf 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/bedrock/FillNetherCeilingOnChunkload.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/bedrock/FillNetherCeilingOnChunkload.java @@ -21,7 +21,7 @@ public class FillNetherCeilingOnChunkload extends AEFModule implements Listener private final boolean alsoCheckNewChunks, pauseOnLowTPS; public FillNetherCeilingOnChunkload() { - super("bedrock.fill-in-bedrock.nether-ceiling.fill-on-chunkload"); + super("bedrock.fill-in-bedrock.nether-ceiling.fill-on-chunkload", false); this.alsoCheckNewChunks = config.getBoolean(configPath + ".also-check-new-chunks", false, "Recommended to leave off. Only useful if world generation is broken."); this.exemptedWorlds = new HashSet<>(config.getList(configPath + ".exempted-worlds", @@ -38,11 +38,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); @@ -52,9 +47,8 @@ public void disable() { private void onChunkLoad(ChunkLoadEvent event) { if (ChunkUtil.isRetrievalUnsafe(event.getChunk())) return; if (!alsoCheckNewChunks && event.isNewChunk()) return; - final World world = event.getWorld(); - if (world.getEnvironment() != World.Environment.NETHER) return; - if (exemptedWorlds.contains(world.getName())) return; + if (event.getWorld().getEnvironment() != World.Environment.NETHER) return; + if (exemptedWorlds.contains(event.getWorld().getName())) return; if (!pauseOnLowTPS || AnarchyExploitFixes.tickReporter().getTPS() >= pauseTPS) { ChunkUtil.createBedrockLayer(event.getChunk(), config.nether_ceiling_max_y); diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/bedrock/FillNetherFloorOnChunkload.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/bedrock/FillNetherFloorOnChunkload.java index 3fbc6625a..197621018 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/bedrock/FillNetherFloorOnChunkload.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/bedrock/FillNetherFloorOnChunkload.java @@ -22,7 +22,7 @@ public class FillNetherFloorOnChunkload extends AEFModule implements Listener { private final boolean alsoCheckNewChunks, pauseOnLowTPS; public FillNetherFloorOnChunkload() { - super("bedrock.fill-in-bedrock.nether-floor.fill-on-chunkload"); + super("bedrock.fill-in-bedrock.nether-floor.fill-on-chunkload", false); this.alsoCheckNewChunks = config.getBoolean(configPath + ".also-check-new-chunks", false, "Recommended to leave off. Only useful if world generation is broken."); this.exemptedWorlds = new HashSet<>(config.getList(configPath + ".exempted-worlds", @@ -38,11 +38,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); @@ -52,12 +47,11 @@ public void disable() { private void onChunkLoad(ChunkLoadEvent event) { if (ChunkUtil.isRetrievalUnsafe(event.getChunk())) return; if (!alsoCheckNewChunks && event.isNewChunk()) return; - final World world = event.getWorld(); - if (world.getEnvironment() != World.Environment.NETHER) return; - if (exemptedWorlds.contains(world.getName())) return; + if (event.getWorld().getEnvironment() != World.Environment.NETHER) return; + if (exemptedWorlds.contains(event.getWorld().getName())) return; if (!pauseOnLowTPS || AnarchyExploitFixes.tickReporter().getTPS() >= pauseTPS) { - ChunkUtil.createBedrockLayer(event.getChunk(), WorldUtil.getMinWorldHeight(world)); + ChunkUtil.createBedrockLayer(event.getChunk(), WorldUtil.getMinWorldHeight(event.getWorld())); } } } diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/bedrock/FillOverworldFloorOnChunkload.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/bedrock/FillOverworldFloorOnChunkload.java index 34376d693..16ef3fa9f 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/bedrock/FillOverworldFloorOnChunkload.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/bedrock/FillOverworldFloorOnChunkload.java @@ -22,7 +22,7 @@ public class FillOverworldFloorOnChunkload extends AEFModule implements Listener private final boolean alsoCheckNewChunks, pauseOnLowTPS; public FillOverworldFloorOnChunkload() { - super("bedrock.fill-in-bedrock.overworld-floor.fill-on-chunkload"); + super("bedrock.fill-in-bedrock.overworld-floor.fill-on-chunkload", false); this.alsoCheckNewChunks = config.getBoolean(configPath + ".also-check-new-chunks", false, "Recommended to leave off. Only useful if world generation is broken."); this.exemptedWorlds = new HashSet<>(config.getList(configPath + ".exempted-worlds", @@ -38,11 +38,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); @@ -52,12 +47,11 @@ public void disable() { private void onChunkLoad(ChunkLoadEvent event) { if (ChunkUtil.isRetrievalUnsafe(event.getChunk())) return; if (!alsoCheckNewChunks && event.isNewChunk()) return; - final World world = event.getWorld(); - if (world.getEnvironment() != World.Environment.NORMAL) return; - if (exemptedWorlds.contains(world.getName())) return; + if (event.getWorld().getEnvironment() != World.Environment.NORMAL) return; + if (exemptedWorlds.contains(event.getWorld().getName())) return; if (!pauseOnLowTPS || AnarchyExploitFixes.tickReporter().getTPS() >= pauseTPS) { - ChunkUtil.createBedrockLayer(event.getChunk(), WorldUtil.getMinWorldHeight(world)); + ChunkUtil.createBedrockLayer(event.getChunk(), WorldUtil.getMinWorldHeight(event.getWorld())); } } } diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/bedrock/PeriodicallyFillNetherCeiling.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/bedrock/PeriodicallyFillNetherCeiling.java index 3f96a9de6..bdce04d4f 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/bedrock/PeriodicallyFillNetherCeiling.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/bedrock/PeriodicallyFillNetherCeiling.java @@ -17,11 +17,12 @@ public class PeriodicallyFillNetherCeiling extends AEFModule implements Runnable private final long checkPeriod; private final double pauseTPS; private final boolean checkShouldPauseOnLowTPS; + private BukkitTask bukkitTask; public PeriodicallyFillNetherCeiling() { - super("bedrock.fill-in-bedrock.nether-ceiling.periodically-check-and-fill"); - config.addComment(configPath + ".enable","Only checks loaded chunks."); + super("bedrock.fill-in-bedrock.nether-ceiling.periodically-check-and-fill", false, + "Only checks loaded chunks."); this.checkPeriod = config.getInt(configPath + ".check-period-in-seconds", 10) * 20L; this.exemptedWorlds = new HashSet<>(config.getList(configPath + ".exempted-worlds", Arrays.asList("exampleworld", "exampleworld2"), @@ -36,14 +37,12 @@ public void enable() { bukkitTask = plugin.getServer().getScheduler().runTaskTimer(plugin, this, 20L, checkPeriod); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { - if (bukkitTask != null) bukkitTask.cancel(); + if (bukkitTask != null) { + bukkitTask.cancel(); + bukkitTask = null; + } } @Override diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/bedrock/PeriodicallyFillNetherFloor.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/bedrock/PeriodicallyFillNetherFloor.java index 84fbb534d..13ad78017 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/bedrock/PeriodicallyFillNetherFloor.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/bedrock/PeriodicallyFillNetherFloor.java @@ -18,10 +18,11 @@ public class PeriodicallyFillNetherFloor extends AEFModule implements Runnable { private final long checkPeriod; private final double pauseTPS; private final boolean checkShouldPauseOnLowTPS; + private BukkitTask bukkitTask; public PeriodicallyFillNetherFloor() { - super("bedrock.fill-in-bedrock.nether-floor.periodically-check-and-fill"); + super("bedrock.fill-in-bedrock.nether-floor.periodically-check-and-fill", false); config.addComment(configPath + ".enable","Only checks loaded chunks."); this.checkPeriod = config.getInt(configPath + ".check-period-in-seconds", 10) * 20L; this.exemptedWorlds = new HashSet<>(config.getList(configPath + ".exempted-worlds", @@ -37,14 +38,12 @@ public void enable() { bukkitTask = plugin.getServer().getScheduler().runTaskTimer(plugin, this, 20L, checkPeriod); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { - if (bukkitTask != null) bukkitTask.cancel(); + if (bukkitTask != null) { + bukkitTask.cancel(); + bukkitTask = null; + } } @Override diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/bedrock/PeriodicallyFillOverworldFloor.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/bedrock/PeriodicallyFillOverworldFloor.java index 5f9999960..ce9fff976 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/bedrock/PeriodicallyFillOverworldFloor.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/bedrock/PeriodicallyFillOverworldFloor.java @@ -18,11 +18,12 @@ public class PeriodicallyFillOverworldFloor extends AEFModule implements Runnabl private final long checkPeriod; private final double pauseTPS; private final boolean checkShouldPauseOnLowTPS; + private BukkitTask bukkitTask; public PeriodicallyFillOverworldFloor() { - super("bedrock.fill-in-bedrock.overworld-floor.periodically-check-and-fill"); - config.addComment(configPath + ".enable","only checks loaded chunks"); + super("bedrock.fill-in-bedrock.overworld-floor.periodically-check-and-fill", false, + "Only checks loaded chunks"); this.checkPeriod = config.getInt(configPath + ".check-period-in-seconds", 10) * 20L; this.exemptedWorlds = new HashSet<>(config.getList(configPath + ".exempted-worlds", Arrays.asList("exampleworld", "exampleworld2"), @@ -37,14 +38,12 @@ public void enable() { bukkitTask = plugin.getServer().getScheduler().runTaskTimer(plugin, this, 20L, checkPeriod); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { - if (bukkitTask != null) bukkitTask.cancel(); + if (bukkitTask != null) { + bukkitTask.cancel(); + bukkitTask = null; + } } @Override diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/bedrock/PreventGoingBelowBedrockFloor.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/bedrock/PreventGoingBelowBedrockFloor.java index 440caf3f5..facc82d31 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/bedrock/PreventGoingBelowBedrockFloor.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/bedrock/PreventGoingBelowBedrockFloor.java @@ -5,7 +5,6 @@ import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; -import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.HandlerList; @@ -24,7 +23,7 @@ public class PreventGoingBelowBedrockFloor extends AEFModule implements Listener private final double damageOnMove; public PreventGoingBelowBedrockFloor() { - super("bedrock.prevent-going-below-bedrock-floor"); + super("bedrock.prevent-going-below-bedrock-floor", true); config.addComment(configPath + ".enable", "Prevents players from going below the bedrock floor."); this.vehicleEject = config.getBoolean(configPath + ".eject-player", true, @@ -54,11 +53,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", true); - } - @Override public void disable() { HandlerList.unregisterAll(this); @@ -66,18 +60,17 @@ public void disable() { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) private void onPlayerMove(PlayerMoveEvent event) { - final Player player = event.getPlayer(); - final World world = player.getWorld(); + final World world = event.getPlayer().getWorld(); if (exemptedWorlds.contains(world.getName())) return; - final Location playerLoc = player.getLocation(); + final Location playerLoc = event.getPlayer().getLocation(); if (playerLoc.getY() >= WorldUtil.getMinWorldHeight(world)) return; - if (vehicleEject && player.getVehicle() != null) { - player.getVehicle().eject(); + if (vehicleEject && event.getPlayer().getVehicle() != null) { + event.getPlayer().getVehicle().eject(); } - if (closeElytra && player.isGliding()) { - player.setGliding(false); + if (closeElytra && event.getPlayer().isGliding()) { + event.getPlayer().setGliding(false); } if (fillHole) { @@ -90,13 +83,13 @@ private void onPlayerMove(PlayerMoveEvent event) { // Teleport player up, so he lands on top of that bedrock Location threeBlocksUp = event.getFrom().clone().add(0, 3, 0); event.setTo(threeBlocksUp); - player.teleport(threeBlocksUp); + event.getPlayer().teleport(threeBlocksUp); } if (damageOnMove > 0) { // Deal damage when moving below bedrock. Just in case everything else fails // to prevent players from moving below bedrock. - player.damage(damageOnMove); + event.getPlayer().damage(damageOnMove); } } } diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/chat/PreventPluginScanning.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/chat/PreventPluginScanning.java index ca7672f52..97cdeb33f 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/chat/PreventPluginScanning.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/chat/PreventPluginScanning.java @@ -16,11 +16,10 @@ public class PreventPluginScanning extends AEFModule implements Listener { public PreventPluginScanning() { - super("chat.prevent-scanning-server-plugins"); - config.addComment(configPath + ".enable", + super("chat.prevent-scanning-server-plugins", true, "Prevents hacked clients running .plugins to find out what plugins\n" + - "the server is using.\n" + - "Recommended to use in combination with command whitelist."); + "the server is using.\n" + + "Recommended to use in combination with command whitelist."); } @Override @@ -28,11 +27,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", true); - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/chat/commandwhitelist/CommandWhitelist.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/chat/commandwhitelist/CommandWhitelist.java index 4754a75d5..2ba6f1372 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/chat/commandwhitelist/CommandWhitelist.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/chat/commandwhitelist/CommandWhitelist.java @@ -35,17 +35,17 @@ */ public class CommandWhitelist extends AEFModule implements PacketListener, Listener { - private final PacketListenerAbstract abstractListener; - private Listener commandSendListener; private final Set allowedCommands, bannedSubCommands; private final boolean usePackets, shouldLog; + private PacketListenerAbstract packetListenerAbstract; + private Listener commandSendListener; + public CommandWhitelist() { - super("chat.command-whitelist"); - config.addComment(configPath + ".enable", + super("chat.command-whitelist", false, "This will make it pretty much impossible to find your plugins as\n" + - "only the commands you specify will be able to work.\n" + - "Allow bypass using permission: " + AEFPermission.BYPASS_CMD_WHITELIST.string()); + "only the commands you specify will be able to work.\n" + + "Allow bypass using permission: " + AEFPermission.BYPASS_CMD_WHITELIST.string()); this.shouldLog = config.getBoolean(configPath + ".log", false, "Will show logs when a command was denied."); this.usePackets = config.getBoolean(configPath + ".use-packets", true, @@ -56,7 +56,7 @@ public CommandWhitelist() { "toggledeathmsg", "dmt", "worldstats", "stats", "tps", "msg", "whisper", "w", "m", "t", "pm", "tell", "r", "reply", "last"), "Add all commands you WANT your players to be able to access\n" + - "WITHOUT the '/'. Not case sensitive.") + "WITHOUT the '/'. Not case sensitive.") .stream() .map(String::toLowerCase) .collect(Collectors.toCollection(HashSet::new)); @@ -64,41 +64,42 @@ public CommandWhitelist() { Arrays.asList("help about", "vote List", "vote Best", "vote Total", "worldstats reload", "stats reload"), "Add all subcommands you DON'T want your players to be able\n" + "to access. Case sensitive!")); - if (CWCommandSendListener.isSupported()) // Not available by default on 1.12 - this.commandSendListener = new CWCommandSendListener(allowedCommands); - this.abstractListener = asAbstract(PacketListenerPriority.HIGHEST); } @Override public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); - if (commandSendListener != null) + if (CWCommandSendListener.isSupported()) { // Legacy versions do not have this event + commandSendListener = new CWCommandSendListener(allowedCommands); plugin.getServer().getPluginManager().registerEvents(commandSendListener, plugin); + } if (usePackets) { if (AnarchyExploitFixes.config().packets_disabled) { warn("Can't enable packet listener because packet events is disabled in config."); } else { - PacketEvents.getAPI().getEventManager().registerListener(abstractListener); + packetListenerAbstract = asAbstract(PacketListenerPriority.HIGHEST); + PacketEvents.getAPI().getEventManager().registerListener(packetListenerAbstract); } } } - @Override - public boolean shouldEnable() { - return AnarchyExploitFixes.config().getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); - if (commandSendListener != null) + if (commandSendListener != null) { HandlerList.unregisterAll(commandSendListener); - PacketEvents.getAPI().getEventManager().unregisterListener(abstractListener); + commandSendListener = null; + } + if (packetListenerAbstract != null) { + PacketEvents.getAPI().getEventManager().unregisterListener(packetListenerAbstract); + packetListenerAbstract = null; + } } @Override public void onPacketReceive(PacketReceiveEvent event) { if (event.isCancelled()) return; + if (event.getPacketType() == PacketType.Play.Client.TAB_COMPLETE) { if (CWCommandSendListener.isSupported()) return; @@ -143,7 +144,7 @@ else if (allowedCommand.startsWith(text.substring(1))) { return; } - final Player player = (Player) event.getPlayer(); + final Player player = event.getPlayer(); if (player != null && player.hasPermission(AEFPermission.BYPASS_CMD_WHITELIST.bukkit())) return; if (!allowedCommands.contains(CommandUtil.getCommandLabel(message).toLowerCase())) { diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/chunklimits/BlockLimit.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/chunklimits/BlockLimit.java index bf633d78a..d5bb97a09 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/chunklimits/BlockLimit.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/chunklimits/BlockLimit.java @@ -21,7 +21,7 @@ public class BlockLimit extends AEFModule implements Listener { private final Map blockLimits = new EnumMap<>(Material.class); public BlockLimit() { - super("chunk-limits.block-limit"); + super("chunk-limits.block-limit", false); Map universal = new EnumMap<>(XMaterial.class); universal.put(XMaterial.ENCHANTING_TABLE, 16); @@ -147,11 +147,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); @@ -159,16 +154,16 @@ public void disable() { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) private void onBlockPlace(BlockPlaceEvent event) { - final Material placedType = event.getBlock().getType(); if ( - blockLimits.containsKey(placedType) - && exceedsPerChunkLimit(placedType, blockLimits.get(placedType), event.getBlock().getChunk()) + blockLimits.containsKey(event.getBlock().getType()) + && exceedsPerChunkLimit(event.getBlock().getType(), event.getBlock().getChunk()) ) { event.setCancelled(true); } } - private boolean exceedsPerChunkLimit(Material material, int limit, Chunk chunk) { + private boolean exceedsPerChunkLimit(Material material, Chunk chunk) { + final int materialLimit = blockLimits.get(material); final int minY = WorldUtil.getMinWorldHeight(chunk.getWorld()); final int maxY = chunk.getWorld().getMaxHeight(); int count = 0; @@ -177,7 +172,9 @@ private boolean exceedsPerChunkLimit(Material material, int limit, Chunk chunk) for (int y = minY; y < maxY; y++) { if (chunk.getBlock(x, y, z).getType() == material) { count++; - if (count > limit) return true; + if (count > materialLimit) { + return true; + } } } } diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/chunklimits/CustomEntityLimit.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/chunklimits/CustomEntityLimit.java index 6c379d1ba..fdf8423b3 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/chunklimits/CustomEntityLimit.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/chunklimits/CustomEntityLimit.java @@ -30,8 +30,9 @@ public class CustomEntityLimit extends AEFModule implements Runnable, Listener { private BukkitTask bukkitTask; public CustomEntityLimit() { - super("chunk-limits.entity-limits.custom-limit"); - config.addComment(configPath + ".enable", "Limit specific entity types per chunk."); + super("chunk-limits.entity-limits.custom-limit", false, + "Limit specific entity types per chunk.\n" + + "Read over the defaults at least once before enabling."); this.logIsEnabled = config.getBoolean(configPath + ".log-removals", true); this.checkPeriod = config.getInt(configPath + ".check-period-in-ticks", 1200, "Check all loaded chunks every x ticks."); @@ -142,11 +143,6 @@ public void enable() { bukkitTask = plugin.getServer().getScheduler().runTaskTimer(plugin, this, checkPeriod, checkPeriod); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/chunklimits/DroppedItemLimit.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/chunklimits/DroppedItemLimit.java index 9d893d7f3..383430bc1 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/chunklimits/DroppedItemLimit.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/chunklimits/DroppedItemLimit.java @@ -37,12 +37,11 @@ public class DroppedItemLimit extends AEFModule implements Listener, Runnable { private BukkitTask bukkitTask; public DroppedItemLimit() { - super("chunk-limits.entity-limits.dropped-item-limit"); - config.addComment(configPath + ".enable", + super("chunk-limits.entity-limits.dropped-item-limit", false, "Limit the amount of dropped items in a chunk to combat lag.\n" + - "Be aware this does not prioritize items by value or anything,\n" + - "it just deletes whatever happens to get over the limit during\n" + - "counting."); + "Be aware this does not prioritize items by value or anything,\n" + + "it just deletes whatever happens to get over the limit during\n" + + "counting."); this.logIsEnabled = config.getBoolean(configPath + ".log-removals", true); this.maxDroppedItemsPerChunk = config.getInt(configPath + ".max-dropped-items-per-chunk", 200); this.cleanupDelay = Math.max(1, config.getInt(configPath + ".post-item-drop-check-delay", 60, @@ -82,11 +81,6 @@ public void enable() { bukkitTask = plugin.getServer().getScheduler().runTaskTimer(plugin, this, checkPeriod, checkPeriod); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/chunklimits/ExpBottleLimit.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/chunklimits/ExpBottleLimit.java index ba327ca64..3d2cffd67 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/chunklimits/ExpBottleLimit.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/chunklimits/ExpBottleLimit.java @@ -22,12 +22,11 @@ public class ExpBottleLimit extends AEFModule implements Runnable, Listener { private BukkitTask bukkitTask; public ExpBottleLimit() { - super("chunk-limits.exp-bottle-limit"); - config.addComment(configPath + ".enable", + super("chunk-limits.exp-bottle-limit", true, "Prevent players from crashing the server or other players by\n" + - "creating a ton of THROWN_EXP_BOTTLE entities, then loading\n" + - "them at once.\n" + - "Does not limit the EXP_ORBS, just the bottle entities."); + "creating a ton of THROWN_EXP_BOTTLE entities, then loading\n" + + "them at once.\n" + + "Does not limit the EXP_ORBS, just the bottle entities."); this.logIsEnabled = config.getBoolean(configPath + ".log", false); this.maxExpBottlePerChunk = config.getInt(configPath + ".max-exp-bottle-per-chunk", 25, "Max in a chunk, doesn't limit the actual xp orbs."); @@ -41,11 +40,6 @@ public void enable() { bukkitTask = plugin.getServer().getScheduler().runTaskTimer(plugin, this, checkPeriod, checkPeriod); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", true); - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/chunklimits/FallingBlockLimit.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/chunklimits/FallingBlockLimit.java index 51bd0acc4..425572937 100644 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/chunklimits/FallingBlockLimit.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/chunklimits/FallingBlockLimit.java @@ -16,16 +16,17 @@ import org.bukkit.event.entity.EntityChangeBlockEvent; import java.time.Duration; -import java.util.Set; public class FallingBlockLimit extends AEFModule implements Listener { - private final Set checkedChunks; + private final long chunkCheckDelay; private final int maxFallingGravityBlockPerChunk; private final boolean logIsEnabled; + private ExpiringSet checkedChunks; + public FallingBlockLimit() { - super("chunk-limits.falling-block-limit"); + super("chunk-limits.falling-block-limit", true); config.addComment(configPath + ".enable", "Prevent players from placing massive sand chunks, then collapsing\n" + "them to kill the server."); @@ -33,27 +34,26 @@ public FallingBlockLimit() { this.maxFallingGravityBlockPerChunk = config.getInt(configPath + ".max-falling-gravity-blocks-per-chunk", 60, "Removes any falling block if there is more than x blocks actively\n" + "falling in a chunk."); - this.checkedChunks = new ExpiringSet<>(Duration.ofMillis( - Math.max(1, config.getInt(configPath + ".chunk-check-delay-in-ticks", 20, - "Delay in ticks until the same chunk can be checked again.\n" + - "Prevents overchecking, because physics events can be called many\n" + - "times in a short time for the same chunk.")) * 50L - )); + this.chunkCheckDelay = Math.max(1, config.getInt(configPath + ".chunk-check-delay-in-ticks", 20, + "Delay in ticks until the same chunk can be checked again.\n" + + "Prevents overchecking, because physics events can be called many\n" + + "times in a short time for the same chunk.")) * 50L; } @Override public void enable() { + checkedChunks = new ExpiringSet<>(Duration.ofMillis(chunkCheckDelay)); plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", true); - } - @Override public void disable() { HandlerList.unregisterAll(this); + if (checkedChunks != null) { + checkedChunks.clear(); + checkedChunks.cleanUp(); + checkedChunks = null; + } } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/chunklimits/MinecartLimit.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/chunklimits/MinecartLimit.java index d9dbfc161..9a43db254 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/chunklimits/MinecartLimit.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/chunklimits/MinecartLimit.java @@ -20,11 +20,11 @@ public class MinecartLimit extends AEFModule implements Listener, Runnable { private final long checkPeriod; private final int maxMinecartsPerChunk; private final boolean logIsEnabled; + private BukkitTask bukkitTask; public MinecartLimit() { - super("chunk-limits.minecart-limit"); - config.addComment(configPath + ".enable", + super("chunk-limits.minecart-limit", false, "Limit the amount of minecarts to prevent lag caused by collisions."); this.logIsEnabled = config.getBoolean(configPath + ".log-removals", false); this.maxMinecartsPerChunk = config.getInt(configPath + ".max-minecarts-per-chunk", 25); @@ -38,15 +38,13 @@ public void enable() { bukkitTask = plugin.getServer().getScheduler().runTaskTimer(plugin, this, checkPeriod, checkPeriod); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); - if (bukkitTask != null) bukkitTask.cancel(); + if (bukkitTask != null) { + bukkitTask.cancel(); + bukkitTask = null; + } } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/chunklimits/NonLivingEntityLimit.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/chunklimits/NonLivingEntityLimit.java index a9f308201..428f08e12 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/chunklimits/NonLivingEntityLimit.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/chunklimits/NonLivingEntityLimit.java @@ -21,11 +21,11 @@ public class NonLivingEntityLimit extends AEFModule implements Listener, Runnabl private final long checkPeriod; private final int maxNonLivingEntities; private final boolean logIsEnabled; + private BukkitTask bukkitTask; public NonLivingEntityLimit() { - super("chunk-limits.entity-limits.non-living-limit"); - config.addComment(configPath + ".enable", + super("chunk-limits.entity-limits.non-living-limit", false, "Limit the amount of non living entities in a chunk to prevent lag.\n" + "Ignores dropped items."); this.logIsEnabled = config.getBoolean(configPath + ".log-removals", true); @@ -40,15 +40,13 @@ public void enable() { bukkitTask = plugin.getServer().getScheduler().runTaskTimer(plugin, this, checkPeriod, checkPeriod); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); - if (bukkitTask != null) bukkitTask.cancel(); + if (bukkitTask != null) { + bukkitTask.cancel(); + bukkitTask = null; + } } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/chunklimits/TileEntityLimit.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/chunklimits/TileEntityLimit.java index 9dc12c904..3127577e7 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/chunklimits/TileEntityLimit.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/chunklimits/TileEntityLimit.java @@ -16,10 +16,11 @@ public class TileEntityLimit extends AEFModule implements Runnable, Listener { private final long checkPeriod; private final int maxTileEntities; private final boolean logIsEnabled; + private BukkitTask bukkitTask; public TileEntityLimit() { - super("chunk-limits.entity-limits.tile-entity-limit"); + super("chunk-limits.entity-limits.tile-entity-limit", false); config.addComment(configPath + ".enable", "Limit the amount of tile entities in a chunk to prevent lag."); this.logIsEnabled = config.getBoolean(configPath + ".log-removals", true); @@ -33,15 +34,13 @@ public void enable() { bukkitTask = plugin.getServer().getScheduler().runTaskTimer(plugin, this, checkPeriod, checkPeriod); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); - if (bukkitTask != null) bukkitTask.cancel(); + if (bukkitTask != null) { + bukkitTask.cancel(); + bukkitTask = null; + } } @Override @@ -55,11 +54,11 @@ public void run() { if (amountToRemove <= 0) return; for (int i = 0; i < amountToRemove; i++) { - tileEntities[i].setType(XMaterial.AIR.parseMaterial()); + tileEntities[i].setType(XMaterial.AIR.get()); tileEntities[i].update(true, false); if (logIsEnabled) - info( "Removed tile entity at " + LocationUtil.toString(tileEntities[i].getLocation()) + + info("Removed tile entity at " + LocationUtil.toString(tileEntities[i].getLocation()) + " because reached limit of " + maxTileEntities); } } diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/chunklimits/VehicleLimit.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/chunklimits/VehicleLimit.java index 107faba1d..79ca7223c 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/chunklimits/VehicleLimit.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/chunklimits/VehicleLimit.java @@ -19,11 +19,11 @@ public class VehicleLimit extends AEFModule implements Listener, Runnable { private final long checkPeriod; private final int maxVehiclesPerChunk; private final boolean logIsEnabled; + private BukkitTask bukkitTask; public VehicleLimit() { - super("chunk-limits.vehicle-limit"); - config.addComment(configPath + ".enable", + super("chunk-limits.vehicle-limit", false, "Limit the amount of vehicles to prevent some lag machines.\n" + "ex. dispenser that spawns a lot of boats into a single location\n" + "then hitting it, causing all boats to explode in every direction."); @@ -39,15 +39,13 @@ public void enable() { bukkitTask = plugin.getServer().getScheduler().runTaskTimer(plugin, this, checkPeriod, checkPeriod); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); - if (bukkitTask != null) bukkitTask.cancel(); + if (bukkitTask != null) { + bukkitTask.cancel(); + bukkitTask = null; + } } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/chunklimits/VillagerLimit.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/chunklimits/VillagerLimit.java index 90fd4e8e4..b95770d0f 100644 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/chunklimits/VillagerLimit.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/chunklimits/VillagerLimit.java @@ -31,11 +31,12 @@ public class VillagerLimit extends AEFModule implements Runnable, Listener { private final long checkPeriod; private final int maxVillagersPerChunk; private final boolean logIsEnabled, whitelistEnabled; + private BukkitTask bukkitTask; public VillagerLimit() { - super("chunk-limits.entity-limits.villager-limit"); - this.maxVillagersPerChunk = Math.max(config.getInt(configPath + ".max-villagers-per-chunk", 25), 1); + super("chunk-limits.entity-limits.villager-limit", false); + this.maxVillagersPerChunk = Math.max(1, config.getInt(configPath + ".max-villagers-per-chunk", 25)); this.logIsEnabled = config.getBoolean(configPath + ".log-removals", false); this.checkPeriod = Math.max(1, config.getInt(configPath + ".check-period-in-ticks", 600, "check all chunks every x ticks.")); @@ -96,15 +97,13 @@ public void enable() { bukkitTask = plugin.getServer().getScheduler().runTaskTimer(plugin, this, checkPeriod, checkPeriod); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); - if (bukkitTask != null) bukkitTask.cancel(); + if (bukkitTask != null) { + bukkitTask.cancel(); + bukkitTask = null; + } } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/AnchorAuraDelay.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/AnchorAuraDelay.java deleted file mode 100644 index 0142d762d..000000000 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/AnchorAuraDelay.java +++ /dev/null @@ -1,101 +0,0 @@ -package me.xginko.aef.modules.combat; - -import com.cryptomorin.xseries.XMaterial; -import me.xginko.aef.modules.AEFModule; -import me.xginko.aef.utils.WorldUtil; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.HandlerList; -import org.bukkit.event.Listener; -import org.bukkit.event.block.Action; -import org.bukkit.event.block.BlockPlaceEvent; -import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.event.player.PlayerKickEvent; -import org.bukkit.event.player.PlayerQuitEvent; - -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.TimeUnit; - -public class AnchorAuraDelay extends AEFModule implements Listener { - - private final Map placeCooldowns, breakCooldowns; - private final long placeDelayNanos, breakDelayNanos; - private final boolean updateInventory; - - public AnchorAuraDelay() { - super("combat.anchor-aura-delay"); - this.breakCooldowns = new ConcurrentHashMap<>(); - this.breakDelayNanos = TimeUnit.MILLISECONDS.toNanos( - config.getLong(configPath + ".break-delay-millis", 0, "1 tick = 50 ms")); - this.placeCooldowns = new ConcurrentHashMap<>(); - this.placeDelayNanos = TimeUnit.MILLISECONDS.toNanos( - config.getLong(configPath + ".place-delay-millis", 400, "1 tick = 50 ms")); - this.updateInventory = config.getBoolean(configPath + ".update-inventory-on-cancel", false, - "Can help with desync but recommended to leave off unless you have issues."); - } - - @Override - public void enable() { - plugin.getServer().getPluginManager().registerEvents(this, plugin); - } - - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - - @Override - public void disable() { - HandlerList.unregisterAll(this); - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - private void onPlayerInteract(PlayerInteractEvent event) { - if (breakDelayNanos <= 0) return; - if (event.getAction() != Action.RIGHT_CLICK_BLOCK) return; - if (event.getClickedBlock().getType() != XMaterial.RESPAWN_ANCHOR.parseMaterial()) return; - if (event.getItem() == null || event.getItem().getType() != XMaterial.GLOWSTONE.parseMaterial()) return; - if (WorldUtil.isRespawnAnchorWorks(event.getPlayer().getWorld())) return; - - if ( - breakCooldowns.containsKey(event.getPlayer().getUniqueId()) - && breakCooldowns.get(event.getPlayer().getUniqueId()) > System.nanoTime() - ) { - event.setCancelled(true); - if (updateInventory) event.getPlayer().updateInventory(); - } else { - breakCooldowns.put(event.getPlayer().getUniqueId(), System.nanoTime() + breakDelayNanos); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - private void onBlockPlace(BlockPlaceEvent event) { - if (placeDelayNanos <= 0) return; - if (event.getBlock().getType() != XMaterial.RESPAWN_ANCHOR.parseMaterial()) return; - if (WorldUtil.isRespawnAnchorWorks(event.getPlayer().getWorld())) return; - - if ( - placeCooldowns.containsKey(event.getPlayer().getUniqueId()) - && placeCooldowns.get(event.getPlayer().getUniqueId()) > System.nanoTime() - ) { - event.setCancelled(true); - if (updateInventory) event.getPlayer().updateInventory(); - } else { - placeCooldowns.put(event.getPlayer().getUniqueId(), System.nanoTime() + placeDelayNanos); - } - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - private void onPlayerQuit(PlayerQuitEvent event) { - placeCooldowns.remove(event.getPlayer().getUniqueId()); - breakCooldowns.remove(event.getPlayer().getUniqueId()); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - private void onPlayerKick(PlayerKickEvent event) { - placeCooldowns.remove(event.getPlayer().getUniqueId()); - breakCooldowns.remove(event.getPlayer().getUniqueId()); - } -} \ No newline at end of file diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/BedAuraDelay.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/BedAuraDelay.java deleted file mode 100755 index f002632bc..000000000 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/BedAuraDelay.java +++ /dev/null @@ -1,100 +0,0 @@ -package me.xginko.aef.modules.combat; - -import me.xginko.aef.modules.AEFModule; -import me.xginko.aef.utils.MaterialUtil; -import me.xginko.aef.utils.WorldUtil; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.HandlerList; -import org.bukkit.event.Listener; -import org.bukkit.event.block.Action; -import org.bukkit.event.block.BlockPlaceEvent; -import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.event.player.PlayerKickEvent; -import org.bukkit.event.player.PlayerQuitEvent; - -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.TimeUnit; - -public class BedAuraDelay extends AEFModule implements Listener { - - private final Map breakCooldowns, placeCooldowns; - private final long breakDelayNanos, placeDelayNanos; - private final boolean updateInventory; - - public BedAuraDelay() { - super("combat.bed-aura-delay"); - this.breakCooldowns = new ConcurrentHashMap<>(); - this.breakDelayNanos = TimeUnit.MILLISECONDS.toNanos( - config.getLong(configPath + ".break-delay-millis", 0, "1 tick = 50 ms")); - this.placeCooldowns = new ConcurrentHashMap<>(); - this.placeDelayNanos = TimeUnit.MILLISECONDS.toNanos( - config.getLong(configPath + ".place-delay-millis", 250, "1 tick = 50 ms")); - this.updateInventory = config.getBoolean(configPath + ".update-inventory-on-cancel", false, - "Can help with desync but recommended to leave off unless you have issues."); - } - - @Override - public void enable() { - plugin.getServer().getPluginManager().registerEvents(this, plugin); - } - - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - - @Override - public void disable() { - HandlerList.unregisterAll(this); - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - private void onPlayerInteract(PlayerInteractEvent event) { - if (breakDelayNanos <= 0) return; - if (event.getAction() != Action.RIGHT_CLICK_BLOCK) return; - if (!MaterialUtil.BEDS.contains(event.getClickedBlock().getType())) return; - if (WorldUtil.isBedWorks(event.getClickedBlock().getWorld())) return; - - if ( - breakCooldowns.containsKey(event.getPlayer().getUniqueId()) - && breakCooldowns.get(event.getPlayer().getUniqueId()) > System.nanoTime() - ) { - event.setCancelled(true); - if (updateInventory) event.getPlayer().updateInventory(); - } else { - breakCooldowns.put(event.getPlayer().getUniqueId(), System.nanoTime() + breakDelayNanos); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - private void onBlockPlace(BlockPlaceEvent event) { - if (placeDelayNanos <= 0) return; - if (!MaterialUtil.BEDS.contains(event.getBlockPlaced().getType())) return; - if (WorldUtil.isBedWorks(event.getBlockPlaced().getWorld())) return; - - if ( - placeCooldowns.containsKey(event.getPlayer().getUniqueId()) - && placeCooldowns.get(event.getPlayer().getUniqueId()) > System.nanoTime() - ) { - event.setCancelled(true); - if (updateInventory) event.getPlayer().updateInventory(); - } else { - placeCooldowns.put(event.getPlayer().getUniqueId(), System.nanoTime() + placeDelayNanos); - } - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - private void onPlayerQuit(PlayerQuitEvent event) { - placeCooldowns.remove(event.getPlayer().getUniqueId()); - breakCooldowns.remove(event.getPlayer().getUniqueId()); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - private void onPlayerKick(PlayerKickEvent event) { - placeCooldowns.remove(event.getPlayer().getUniqueId()); - breakCooldowns.remove(event.getPlayer().getUniqueId()); - } -} diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/BowBomb.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/BowBomb.java index eb6c83ef5..e7531a8ba 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/BowBomb.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/BowBomb.java @@ -13,7 +13,7 @@ public class BowBomb extends AEFModule implements Listener { private final int maxBowSquaredVelocity; public BowBomb() { - super("combat.prevent-bow-bomb"); + super("combat.prevent-bow-bomb", false); this.maxBowSquaredVelocity = config.getInt(configPath + ".max-bow-squared-velocity", 15, "Fully pulled bow is ~9-10. 15 is default just to be safe."); } @@ -23,11 +23,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/Burrow.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/Burrow.java index 61fe7c008..156572d08 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/Burrow.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/Burrow.java @@ -33,7 +33,7 @@ public class Burrow extends AEFModule implements Listener { private final boolean shouldTeleportUp, preventIfBlockAboveBurrow, breakAnvilInsteadOfTP, allowSlabs; public Burrow() { - super("combat.prevent-burrow"); + super("combat.prevent-burrow", false); this.damageWhenMovingInBurrow = config.getDouble(configPath + ".damage-when-moving",1.0, "1.0 = Half a heart of damage every time you move."); this.shouldTeleportUp = config.getBoolean(configPath + ".teleport-above-block", true); @@ -49,7 +49,7 @@ public Burrow() { List defaults = Stream.concat(XTag.SHULKER_BOXES.getValues().stream(), Stream.of(XMaterial.AIR, XMaterial.DIRT, XMaterial.DIRT_PATH, XMaterial.SAND, XMaterial.GRAVEL)) .filter(XMaterial::isSupported) - .map(XMaterial::parseMaterial) + .map(XMaterial::get) .map(Enum::name) .collect(Collectors.toList()); this.ignoredMaterial = config.getList(configPath + ".ignored-materials", defaults) @@ -71,11 +71,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); @@ -104,12 +99,12 @@ private void onPlayerMove(PlayerMoveEvent event) { final Block burrowBlock = playerLocation.getBlock(); if (ignoredMaterial.contains(burrowBlock.getType())) return; - if (!preventIfBlockAboveBurrow && burrowBlock.getRelative(BlockFace.UP).getType() != XMaterial.AIR.parseMaterial()) { + if (!preventIfBlockAboveBurrow && burrowBlock.getRelative(BlockFace.UP).getType() != XMaterial.AIR.get()) { return; } // Beacon and Indestructibles - if (MaterialUtil.SOLID_INDESTRUCTIBLES.contains(burrowBlock.getType()) || burrowBlock.getType() == XMaterial.BEACON.parseMaterial()) { + if (MaterialUtil.SOLID_INDESTRUCTIBLES.contains(burrowBlock.getType()) || burrowBlock.getType() == XMaterial.BEACON.get()) { player.damage(damageWhenMovingInBurrow); if (shouldTeleportUp) teleportUpAndCenter(player, burrowBlock.getLocation()); return; @@ -128,7 +123,7 @@ private void onPlayerMove(PlayerMoveEvent event) { if (MaterialUtil.ANVILS.contains(burrowBlock.getType())) { player.damage(damageWhenMovingInBurrow); if (breakAnvilInsteadOfTP) { - burrowBlock.setType(XMaterial.AIR.parseMaterial()); + burrowBlock.setType(XMaterial.AIR.get()); } else { if (shouldTeleportUp) teleportUpAndCenter(player, burrowBlock.getLocation()); } @@ -136,7 +131,7 @@ private void onPlayerMove(PlayerMoveEvent event) { } // Ender chest & Blocks that are slightly lower in height - if (burrowBlock.getType() == XMaterial.ENDER_CHEST.parseMaterial() || MaterialUtil.SINK_IN_BLOCKS.contains(burrowBlock.getType())) { + if (burrowBlock.getType() == XMaterial.ENDER_CHEST.get() || MaterialUtil.SINK_IN_BLOCKS.contains(burrowBlock.getType())) { if (playerLocation.getY() - playerLocation.getBlockY() < 0.875) { player.damage(damageWhenMovingInBurrow); if (shouldTeleportUp) teleportUpAndCenter(player, burrowBlock.getLocation()); @@ -145,7 +140,7 @@ private void onPlayerMove(PlayerMoveEvent event) { } // Enchantment Table - if (burrowBlock.getType() == XMaterial.ENCHANTING_TABLE.parseMaterial()) { + if (burrowBlock.getType() == XMaterial.ENCHANTING_TABLE.get()) { if (playerLocation.getY() - playerLocation.getBlockY() < 0.75) { player.damage(damageWhenMovingInBurrow); if (shouldTeleportUp) teleportUpAndCenter(player, burrowBlock.getLocation()); diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/CrystalAuraDelay.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/CrystalAuraDelay.java deleted file mode 100755 index 20319b10a..000000000 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/CrystalAuraDelay.java +++ /dev/null @@ -1,100 +0,0 @@ -package me.xginko.aef.modules.combat; - -import com.cryptomorin.xseries.XEntityType; -import com.cryptomorin.xseries.XMaterial; -import me.xginko.aef.modules.AEFModule; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.HandlerList; -import org.bukkit.event.Listener; -import org.bukkit.event.block.Action; -import org.bukkit.event.entity.EntityDamageByEntityEvent; -import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.event.player.PlayerKickEvent; -import org.bukkit.event.player.PlayerQuitEvent; - -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.TimeUnit; - -public class CrystalAuraDelay extends AEFModule implements Listener { - - private final Map breakCooldowns, placeCooldowns; - private final long breakDelayNanos, placeDelayNanos; - private final boolean updateInventory; - - public CrystalAuraDelay() { - super("combat.crystal-aura.regular-delay"); - this.breakCooldowns = new ConcurrentHashMap<>(); - this.breakDelayNanos = TimeUnit.MILLISECONDS.toNanos( - config.getLong(configPath + ".break-delay-millis", 200, "1 tick = 50 ms")); - this.placeCooldowns = new ConcurrentHashMap<>(); - this.placeDelayNanos = TimeUnit.MILLISECONDS.toNanos( - config.getLong(configPath + ".place-delay-millis", 0, "1 tick = 50 ms")); - this.updateInventory = config.getBoolean(configPath + ".update-inventory-on-cancel", false, - "Can help with desync but recommended to leave off unless you have issues."); - } - - @Override - public void enable() { - plugin.getServer().getPluginManager().registerEvents(this, plugin); - } - - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - - @Override - public void disable() { - HandlerList.unregisterAll(this); - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - private void onEntityDamageByEntity(EntityDamageByEntityEvent event) { - if (breakDelayNanos <= 0) return; - if (event.getEntityType() != XEntityType.END_CRYSTAL.get()) return; - if (event.getDamager().getType() != XEntityType.PLAYER.get()) return; - - if ( - breakCooldowns.containsKey(event.getDamager().getUniqueId()) - && breakCooldowns.get(event.getDamager().getUniqueId()) > System.nanoTime() - ) { - event.setCancelled(true); - if (updateInventory) ((Player) event.getDamager()).updateInventory(); - } else { - breakCooldowns.put(event.getDamager().getUniqueId(), System.nanoTime() + breakDelayNanos); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - private void onPlayerInteract(PlayerInteractEvent event) { - if (placeDelayNanos <= 0) return; - if (event.getAction() != Action.RIGHT_CLICK_BLOCK) return; // Need to right-click a block to place a crystal - if (event.getItem() == null || event.getItem().getType() != XMaterial.END_CRYSTAL.parseMaterial()) return; - - if ( - placeCooldowns.containsKey(event.getPlayer().getUniqueId()) - && placeCooldowns.get(event.getPlayer().getUniqueId()) > System.nanoTime() - ) { - event.setCancelled(true); - if (updateInventory) event.getPlayer().updateInventory(); - } else { - placeCooldowns.put(event.getPlayer().getUniqueId(), System.nanoTime() + placeDelayNanos); - } - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - private void onPlayerQuit(PlayerQuitEvent event) { - placeCooldowns.remove(event.getPlayer().getUniqueId()); - breakCooldowns.remove(event.getPlayer().getUniqueId()); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - private void onPlayerKick(PlayerKickEvent event) { - placeCooldowns.remove(event.getPlayer().getUniqueId()); - breakCooldowns.remove(event.getPlayer().getUniqueId()); - } -} \ No newline at end of file diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/MultiTask.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/MultiTask.java index 3e4fa5562..7ba8e057a 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/MultiTask.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/MultiTask.java @@ -14,7 +14,7 @@ public class MultiTask extends AEFModule implements Listener { public MultiTask() { - super("combat.multi-task-patch"); + super("combat.multi-task-patch", false); } @Override @@ -22,11 +22,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/PistonCrystalDelay.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/PistonCrystalDelay.java index 20441f57a..380165ea0 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/PistonCrystalDelay.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/PistonCrystalDelay.java @@ -2,7 +2,6 @@ import com.cryptomorin.xseries.XEntityType; import me.xginko.aef.modules.AEFModule; -import me.xginko.aef.utils.models.ExpiringSet; import org.bukkit.Location; import org.bukkit.entity.Entity; import org.bukkit.event.EventHandler; @@ -11,42 +10,47 @@ import org.bukkit.event.Listener; import org.bukkit.event.block.BlockPistonExtendEvent; -import java.time.Duration; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; public class PistonCrystalDelay extends AEFModule implements Listener { - private final ExpiringSet pistonsPushingCrystals; + private final long cooldownNanos; + + private Map extendCooldowns; public PistonCrystalDelay() { - super("combat.crystal-aura.piston-aura-delay"); - config.addComment(configPath + ".enable", "Rate-limits pistons that extend into crystals"); - this.pistonsPushingCrystals = new ExpiringSet<>(Duration.ofMillis( - Math.max(config.getInt(configPath + ".piston-extend-delay-in-ticks", 40), 1) * 50L)); + super("combat.crystal-aura.piston-aura-delay", false, + "Rate-limits pistons that extend into crystals."); + this.cooldownNanos = TimeUnit.MILLISECONDS.toNanos( + Math.max(1, config.getInt(configPath + ".piston-extend-delay-in-ticks", 40)) * 50L); } @Override public void enable() { + extendCooldowns = new ConcurrentHashMap<>(); plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); + if (extendCooldowns != null) { + extendCooldowns.clear(); + extendCooldowns = null; + } } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) private void onPistonExtend(BlockPistonExtendEvent event) { for (Entity entity : event.getBlock().getRelative(event.getDirection()).getLocation().getNearbyEntities(1, 1, 1)) { if (entity.getType() == XEntityType.END_CRYSTAL.get()) { - if (pistonsPushingCrystals.contains(event.getBlock().getLocation())) { + if (extendCooldowns.containsKey(event.getBlock().getLocation()) + && extendCooldowns.get(event.getBlock().getLocation()) > System.nanoTime()) { event.setCancelled(true); } else { - pistonsPushingCrystals.add(event.getBlock().getLocation()); + extendCooldowns.put(event.getBlock().getLocation(), System.currentTimeMillis() + cooldownNanos); } return; } diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/PistonPush.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/PistonPush.java index b03c60595..b9c6537ac 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/PistonPush.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/PistonPush.java @@ -20,7 +20,7 @@ public class PistonPush extends AEFModule implements Listener { private final Set pushDisabledTypes; public PistonPush() { - super("combat.piston-push"); + super("combat.piston-push", false); config.addComment(configPath+".enable", "Disables pistons from extending if it would push certain configured entities.\n" + "This can be used to prevent players from pushing other players out of burrows, by\n" + @@ -43,11 +43,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath+".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/PortalGodMode.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/PortalGodMode.java index 873560cac..3cffb25dd 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/PortalGodMode.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/PortalGodMode.java @@ -20,39 +20,39 @@ public class PortalGodMode extends AEFModule implements Listener { - private final Cache playersWaitingForPortalTeleport; private final long delayTicks; + private Cache playersWaitingForPortalTeleport; + public PortalGodMode() { - super("combat.portal-god-mode-patch"); - config.addComment(configPath + ".enable", + super("combat.portal-god-mode-patch", false, "Prevents an exploit that allows players to stand in nether portals and not\n" + - "take damage indefinitely by just never sending a TeleportConfirm packet to\n" + - "the server.\n" + - "A similar method is used for the chorus tp exploit, which is not covered\n" + - "by this module."); + "take damage indefinitely by just never sending a TeleportConfirm packet to\n" + + "the server.\n" + + "A similar method is used for the chorus tp exploit, which is not covered\n" + + "by this module."); this.delayTicks = config.getInt(configPath + ".break-portal-delay-ticks", 100, "If the player stays inside the nether portal for this time without teleporting,\n" + "the portal will be broken, making the player inside vulnerable again.\n" + "Nether portal teleports normally happen within ~3s after enter, so 5s (100ticks)\n" + "should be a safe value."); - this.playersWaitingForPortalTeleport = Caffeine.newBuilder() - .expireAfterWrite(Duration.ofMillis((delayTicks * 50L) + 1000L)).build(); // Keep cached content for a second longer just in case } @Override public void enable() { + playersWaitingForPortalTeleport = Caffeine.newBuilder() + .expireAfterWrite(Duration.ofMillis((delayTicks * 50L) + 1000L)).build(); // Keep cached content for a second longer just in case plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); + if (playersWaitingForPortalTeleport != null) { + playersWaitingForPortalTeleport.asMap().clear(); + playersWaitingForPortalTeleport.cleanUp(); + playersWaitingForPortalTeleport = null; + } } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @@ -63,7 +63,7 @@ private void onEntityPortalEnter(EntityPortalEnterEvent event) { playersWaitingForPortalTeleport.put(event.getEntity().getUniqueId(), plugin.getServer().getScheduler().runTaskLater(plugin, () -> { - event.getLocation().getBlock().setType(XMaterial.AIR.parseMaterial(), true); + event.getLocation().getBlock().setType(XMaterial.AIR.get(), true); playersWaitingForPortalTeleport.invalidate(event.getEntity().getUniqueId()); }, delayTicks)); } @@ -85,7 +85,7 @@ private void onPlayerMove(PlayerMoveEvent event) { @Nullable BukkitTask breakPortalTask = playersWaitingForPortalTeleport.getIfPresent(event.getPlayer().getUniqueId()); if (breakPortalTask == null) return; - if (event.getTo().getBlock().getType() != XMaterial.NETHER_PORTAL.parseMaterial()) { + if (event.getTo().getBlock().getType() != XMaterial.NETHER_PORTAL.get()) { breakPortalTask.cancel(); playersWaitingForPortalTeleport.invalidate(event.getPlayer().getUniqueId()); } diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/SilentSwapDelay.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/SilentSwapDelay.java index a22fd3d40..573205ffb 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/SilentSwapDelay.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/SilentSwapDelay.java @@ -27,7 +27,7 @@ public class SilentSwapDelay extends AEFModule implements Listener { private final boolean updateInventory; public SilentSwapDelay() { - super("combat.silent-swap-delay"); + super("combat.silent-swap-delay", false); this.swapItemCooldowns = new ConcurrentHashMap<>(); this.updateInventory = config.getBoolean(configPath + ".update-inventory-on-cancel", false, "Can help with desync but recommended to leave off unless you have issues."); @@ -43,11 +43,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/auras/AnchorAuraDelay.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/auras/AnchorAuraDelay.java new file mode 100644 index 000000000..a91bee7d8 --- /dev/null +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/auras/AnchorAuraDelay.java @@ -0,0 +1,52 @@ +package me.xginko.aef.modules.combat.auras; + +import com.cryptomorin.xseries.XMaterial; +import me.xginko.aef.utils.WorldUtil; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.block.Action; +import org.bukkit.event.block.BlockPlaceEvent; +import org.bukkit.event.player.PlayerInteractEvent; + +public class AnchorAuraDelay extends AuraDelayModule { + + public AnchorAuraDelay() { + super("combat.anchor-aura-delay", 0, 400); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + private void onPlayerInteract(PlayerInteractEvent event) { + if (breakDelayNanos <= 0) return; + if (event.getAction() != Action.RIGHT_CLICK_BLOCK) return; + if (event.getClickedBlock().getType() != XMaterial.RESPAWN_ANCHOR.get()) return; + if (event.getItem() == null || event.getItem().getType() != XMaterial.GLOWSTONE.get()) return; + if (WorldUtil.isRespawnAnchorWorks(event.getPlayer().getWorld())) return; + + if ( + breakCooldowns.containsKey(event.getPlayer().getUniqueId()) + && breakCooldowns.get(event.getPlayer().getUniqueId()) > System.nanoTime() + ) { + event.setCancelled(true); + if (updateInventory) event.getPlayer().updateInventory(); + } else { + breakCooldowns.put(event.getPlayer().getUniqueId(), System.nanoTime() + breakDelayNanos); + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + private void onBlockPlace(BlockPlaceEvent event) { + if (placeDelayNanos <= 0) return; + if (event.getBlock().getType() != XMaterial.RESPAWN_ANCHOR.get()) return; + if (WorldUtil.isRespawnAnchorWorks(event.getPlayer().getWorld())) return; + + if ( + placeCooldowns.containsKey(event.getPlayer().getUniqueId()) + && placeCooldowns.get(event.getPlayer().getUniqueId()) > System.nanoTime() + ) { + event.setCancelled(true); + if (updateInventory) event.getPlayer().updateInventory(); + } else { + placeCooldowns.put(event.getPlayer().getUniqueId(), System.nanoTime() + placeDelayNanos); + } + } +} \ No newline at end of file diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/auras/AuraDelayModule.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/auras/AuraDelayModule.java new file mode 100644 index 000000000..4e83c06c2 --- /dev/null +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/auras/AuraDelayModule.java @@ -0,0 +1,81 @@ +package me.xginko.aef.modules.combat.auras; + +import me.xginko.aef.modules.AEFModule; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.HandlerList; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerKickEvent; +import org.bukkit.event.player.PlayerQuitEvent; + +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; + +public abstract class AuraDelayModule extends AEFModule implements Listener { + + protected final long placeDelayNanos, breakDelayNanos; + protected final boolean updateInventory; + + protected Map placeCooldowns, breakCooldowns; + + public AuraDelayModule(String configPath, long defPlaceDelayMillis, long defBreakDelayMillis) { + this(configPath, false, defPlaceDelayMillis, defBreakDelayMillis); + } + + public AuraDelayModule(String configPath, boolean defEnabled, long defPlaceDelayMillis, long defBreakDelayMillis) { + super(configPath, defEnabled); + this.updateInventory = config.getBoolean(configPath + ".update-inventory-on-cancel", false, + "Can help with desync but recommended to leave off unless you have issues."); + placeDelayNanos = TimeUnit.MILLISECONDS.toNanos( + config.getLong(".place-delay-millis", defPlaceDelayMillis, "1 tick = 50 ms")); + breakDelayNanos = TimeUnit.MILLISECONDS.toNanos( + config.getLong(".break-delay-millis", defBreakDelayMillis)); + } + + @Override + public void enable() { + breakCooldowns = new ConcurrentHashMap<>(); + placeCooldowns = new ConcurrentHashMap<>(); + plugin.getServer().getPluginManager().registerEvents(this, plugin); + } + + @Override + public void disable() { + HandlerList.unregisterAll(this); + if (breakCooldowns != null) { + breakCooldowns.clear(); + breakCooldowns = null; + } + if (placeCooldowns != null) { + placeCooldowns.clear(); + placeCooldowns = null; + } + } + + protected boolean isOnCooldown(UUID uuid, Map cooldownMap, long delayNanos) { + if (delayNanos <= 0) { + return false; + } + + if (cooldownMap.containsKey(uuid) && cooldownMap.get(uuid) > System.nanoTime()) { + return true; + } + + cooldownMap.put(uuid, System.nanoTime() + delayNanos); + return false; + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + private void onPlayerQuit(PlayerQuitEvent event) { + placeCooldowns.remove(event.getPlayer().getUniqueId()); + breakCooldowns.remove(event.getPlayer().getUniqueId()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + private void onPlayerKick(PlayerKickEvent event) { + placeCooldowns.remove(event.getPlayer().getUniqueId()); + breakCooldowns.remove(event.getPlayer().getUniqueId()); + } +} diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/auras/BedAuraDelay.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/auras/BedAuraDelay.java new file mode 100755 index 000000000..db33d0177 --- /dev/null +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/auras/BedAuraDelay.java @@ -0,0 +1,51 @@ +package me.xginko.aef.modules.combat.auras; + +import me.xginko.aef.utils.MaterialUtil; +import me.xginko.aef.utils.WorldUtil; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.block.Action; +import org.bukkit.event.block.BlockPlaceEvent; +import org.bukkit.event.player.PlayerInteractEvent; + +public class BedAuraDelay extends AuraDelayModule { + + public BedAuraDelay() { + super("combat.bed-aura-delay", 0, 250); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + private void onPlayerInteract(PlayerInteractEvent event) { + if (breakDelayNanos <= 0) return; + if (event.getAction() != Action.RIGHT_CLICK_BLOCK) return; + if (!MaterialUtil.BEDS.contains(event.getClickedBlock().getType())) return; + if (WorldUtil.isBedWorks(event.getClickedBlock().getWorld())) return; + + if ( + breakCooldowns.containsKey(event.getPlayer().getUniqueId()) + && breakCooldowns.get(event.getPlayer().getUniqueId()) > System.nanoTime() + ) { + event.setCancelled(true); + if (updateInventory) event.getPlayer().updateInventory(); + } else { + breakCooldowns.put(event.getPlayer().getUniqueId(), System.nanoTime() + breakDelayNanos); + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + private void onBlockPlace(BlockPlaceEvent event) { + if (placeDelayNanos <= 0) return; + if (!MaterialUtil.BEDS.contains(event.getBlockPlaced().getType())) return; + if (WorldUtil.isBedWorks(event.getBlockPlaced().getWorld())) return; + + if ( + placeCooldowns.containsKey(event.getPlayer().getUniqueId()) + && placeCooldowns.get(event.getPlayer().getUniqueId()) > System.nanoTime() + ) { + event.setCancelled(true); + if (updateInventory) event.getPlayer().updateInventory(); + } else { + placeCooldowns.put(event.getPlayer().getUniqueId(), System.nanoTime() + placeDelayNanos); + } + } +} diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/auras/CrystalAuraDelay.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/auras/CrystalAuraDelay.java new file mode 100755 index 000000000..05379e7f5 --- /dev/null +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/combat/auras/CrystalAuraDelay.java @@ -0,0 +1,51 @@ +package me.xginko.aef.modules.combat.auras; + +import com.cryptomorin.xseries.XEntityType; +import com.cryptomorin.xseries.XMaterial; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.block.Action; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.player.PlayerInteractEvent; + +public class CrystalAuraDelay extends AuraDelayModule { + + public CrystalAuraDelay() { + super("combat.crystal-aura.regular-delay", 200, 0); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + private void onEntityDamageByEntity(EntityDamageByEntityEvent event) { + if (breakDelayNanos <= 0) return; + if (event.getEntityType() != XEntityType.END_CRYSTAL.get()) return; + if (event.getDamager().getType() != XEntityType.PLAYER.get()) return; + + if ( + breakCooldowns.containsKey(event.getDamager().getUniqueId()) + && breakCooldowns.get(event.getDamager().getUniqueId()) > System.nanoTime() + ) { + event.setCancelled(true); + if (updateInventory) ((Player) event.getDamager()).updateInventory(); + } else { + breakCooldowns.put(event.getDamager().getUniqueId(), System.nanoTime() + breakDelayNanos); + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + private void onPlayerInteract(PlayerInteractEvent event) { + if (placeDelayNanos <= 0) return; + if (event.getAction() != Action.RIGHT_CLICK_BLOCK) return; // Need to right-click a block to place a crystal + if (event.getItem() == null || event.getItem().getType() != XMaterial.END_CRYSTAL.get()) return; + + if ( + placeCooldowns.containsKey(event.getPlayer().getUniqueId()) + && placeCooldowns.get(event.getPlayer().getUniqueId()) > System.nanoTime() + ) { + event.setCancelled(true); + if (updateInventory) event.getPlayer().updateInventory(); + } else { + placeCooldowns.put(event.getPlayer().getUniqueId(), System.nanoTime() + placeDelayNanos); + } + } +} \ No newline at end of file diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/dupepreventions/AllayDupe.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/dupepreventions/AllayDupe.java index 365893132..39a3f2b92 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/dupepreventions/AllayDupe.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/dupepreventions/AllayDupe.java @@ -14,10 +14,9 @@ public class AllayDupe extends AEFModule implements Listener { private final boolean dismount; public AllayDupe() { - super("dupe-preventions.allay-dupe"); - config.addComment(configPath + ".enable", + super("dupe-preventions.allay-dupe", true, "Will prevent allays from entering vehicles to prevent a duplication exploit\n" + - "confirmed working in 1.19.4."); + "confirmed working in 1.19.4."); this.dismount = config.getBoolean(configPath + ".dismount-premounted-allays", true); } @@ -26,11 +25,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/dupepreventions/BookTitleDupe.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/dupepreventions/BookTitleDupe.java index 2bfd90ac3..c7db099a8 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/dupepreventions/BookTitleDupe.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/dupepreventions/BookTitleDupe.java @@ -1,25 +1,32 @@ package me.xginko.aef.modules.dupepreventions; +import com.github.retrooper.packetevents.PacketEvents; import com.github.retrooper.packetevents.event.PacketListenerPriority; import com.github.retrooper.packetevents.event.PacketReceiveEvent; +import com.github.retrooper.packetevents.manager.server.ServerVersion; +import com.github.retrooper.packetevents.netty.buffer.ByteBufHelper; import com.github.retrooper.packetevents.protocol.packettype.PacketType; -import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientEditBook; import me.xginko.aef.modules.packets.PacketModule; import me.xginko.aef.utils.PlatformUtil; +import java.nio.charset.StandardCharsets; + public class BookTitleDupe extends PacketModule { - private final int maxTitleChars; + private final int titleLimit, pageLimit, pageCharLimit; + private final boolean log, kick; public BookTitleDupe() { - super("dupe-preventions.book-title-dupe", PacketListenerPriority.HIGHEST); - config.addComment(configPath + ".enable", + super("dupe-preventions.book-title-dupe", true, PacketListenerPriority.HIGHEST, "Relevant for 1.20.6 - 1.21:\n" + - "Will prevent players from sending book packets with a too large title,\n" + - "to get disconnected and their inventories restored."); - this.maxTitleChars = config.getInt(configPath + ".max-title-charlength", 20, - "Normal ascii like charlimit in vanilla is 15, you could need a bit more\n" + - "if you want to support languages with special characters."); + "Will prevent players from sending book packets with a too large title,\n" + + "to get disconnected and their inventories restored."); + boolean modernLimits = PacketEvents.getAPI().getServerManager().getVersion().isNewerThanOrEquals(ServerVersion.V_1_21_2); + this.titleLimit = config.getInt(configPath + ".max-title-charlength", modernLimits ? 32 : 128); + this.pageLimit = config.getInt(configPath + ".max-pages", modernLimits ? 100 : 200); + this.pageCharLimit = config.getInt(configPath + ".max-page-charlength", modernLimits ? 1024 : 8192); + this.log = config.getBoolean(configPath + ".log", false); + this.kick = config.getBoolean(configPath + ".kick-player", false); } @Override @@ -31,11 +38,43 @@ public boolean shouldEnable() { public void onPacketReceive(PacketReceiveEvent event) { if (event.getPacketType() != PacketType.Play.Client.EDIT_BOOK) return; - WrapperPlayClientEditBook packet = new WrapperPlayClientEditBook(event); - if (packet.getTitle() == null) return; - - if (packet.getTitle().length() > maxTitleChars) { + if (isIllegalBookEdit(event)) { event.setCancelled(true); + onCancel(log, kick, event.getUser()); + } + } + + private boolean isIllegalBookEdit(PacketReceiveEvent event) { + ByteBufHelper.readVarInt(event.getByteBuf()); + + int pageCount = ByteBufHelper.readVarInt(event.getByteBuf()); + if (pageCount > pageLimit) { + return true; + } + + for (int i = 0; i < pageCount; ++i) { + if (isStringTooBig(event.getByteBuf(), pageCharLimit)) { + return true; + } } + + if (ByteBufHelper.readByte(event.getByteBuf()) != 0) { + return isStringTooBig(event.getByteBuf(), titleLimit); + } + + return false; + } + + private boolean isStringTooBig(Object byteBuf, int charLimit) { + int strBufLen = ByteBufHelper.readVarInt(byteBuf); + + // Check if the received encoded string buffer length is zero or longer than maximum allowed + if (strBufLen < 0 || strBufLen > charLimit * 4) { + return true; + } + + // The received string length is longer than maximum allowed + return ByteBufHelper.toString(byteBuf, ByteBufHelper.readerIndex(byteBuf), strBufLen, StandardCharsets.UTF_8) + .length() > charLimit; } } diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/dupepreventions/ChestedEntitiesInPortals.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/dupepreventions/ChestedEntitiesInPortals.java index 018e15f21..3ebe32626 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/dupepreventions/ChestedEntitiesInPortals.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/dupepreventions/ChestedEntitiesInPortals.java @@ -12,8 +12,7 @@ public class ChestedEntitiesInPortals extends AEFModule implements Listener { public ChestedEntitiesInPortals() { - super("dupe-preventions.prevent-chested-living-entities-in-portals"); - config.addComment(configPath, + super("dupe-preventions.prevent-chested-living-entities-in-portals", false, "Prevents entities that can carry chests from using portals to\n" + "block some common dupe tactics.\n" + "CAUTION: Will remove chests and their contents from a chested\n" + @@ -25,11 +24,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath, false); - } - @Override public void disable() { HandlerList.unregisterAll(this); @@ -37,9 +31,7 @@ public void disable() { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) private void onEntityPortalEvent(EntityPortalEvent event) { - if (!EntityUtil.isChestableHorse(event.getEntity())) return; - - if (((ChestedHorse) event.getEntity()).isCarryingChest()) { + if (EntityUtil.isChestableHorse(event.getEntity()) && ((ChestedHorse) event.getEntity()).isCarryingChest()) { event.setCancelled(true); } } diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/dupepreventions/ChestsOnEntities.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/dupepreventions/ChestsOnEntities.java index af853aa1e..00264c5a7 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/dupepreventions/ChestsOnEntities.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/dupepreventions/ChestsOnEntities.java @@ -12,8 +12,7 @@ public class ChestsOnEntities extends AEFModule implements Listener { public ChestsOnEntities() { - super("dupe-preventions.prevent-chests-on-living-entities"); - config.addComment(configPath, + super("dupe-preventions.prevent-chests-on-living-entities", false, "Prevent any possible dupes involving chested entities by making\n" + "it impossible to put a chest on them.\n" + "Only do this if you have reason to believe a dupe like that exists\n" + @@ -25,11 +24,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath, false); - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/dupepreventions/CloseEntityInventoriesOnLogout.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/dupepreventions/CloseEntityInventoriesOnLogout.java index bc31b6d8b..58a7b88f5 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/dupepreventions/CloseEntityInventoriesOnLogout.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/dupepreventions/CloseEntityInventoriesOnLogout.java @@ -14,8 +14,7 @@ public class CloseEntityInventoriesOnLogout extends AEFModule implements Listener { public CloseEntityInventoriesOnLogout() { - super("dupe-preventions.close-entity-inventories-on-player-disconnect"); - config.addComment(configPath, + super("dupe-preventions.close-entity-inventories-on-player-disconnect", false, "Closes open inventories of entities that disappeared when the\n" + "player riding it disconnects."); } @@ -25,11 +24,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath, false); - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/dupepreventions/CloseEntityInventoryOnChunkUnload.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/dupepreventions/CloseEntityInventoryOnChunkUnload.java index 63890060e..beab144a2 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/dupepreventions/CloseEntityInventoryOnChunkUnload.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/dupepreventions/CloseEntityInventoryOnChunkUnload.java @@ -14,8 +14,7 @@ public class CloseEntityInventoryOnChunkUnload extends AEFModule implements Listener { public CloseEntityInventoryOnChunkUnload() { - super("dupe-preventions.close-entity-inventories-on-chunk-unload"); - config.addComment(configPath, + super("dupe-preventions.close-entity-inventories-on-chunk-unload", false, "Closes open inventories of all entities that are in a chunk\n" + "that will be unloaded."); } @@ -25,11 +24,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath, false); - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/patches/CowDupe.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/dupepreventions/CowDupe.java similarity index 75% rename from AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/patches/CowDupe.java rename to AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/dupepreventions/CowDupe.java index 74257ae56..e07c8b707 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/patches/CowDupe.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/dupepreventions/CowDupe.java @@ -1,4 +1,4 @@ -package me.xginko.aef.modules.patches; +package me.xginko.aef.modules.dupepreventions; import com.cryptomorin.xseries.XEntityType; import com.cryptomorin.xseries.XMaterial; @@ -10,13 +10,12 @@ import org.bukkit.event.player.PlayerShearEntityEvent; public class CowDupe extends AEFModule implements Listener { + /** * Yoinked from: https://github.com/F3F5/CowDupeFix */ - public CowDupe() { - super("patches.cow-dupe-patch"); - config.addComment(configPath, + super("dupe-preventions.cow-dupe-patch", false, "Patches the cow duplication exploit that allows duping cows using shears.\n" + "Only affects lower versions"); } @@ -26,11 +25,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath, false); - } - @Override public void disable() { HandlerList.unregisterAll(this); @@ -40,10 +34,10 @@ public void disable() { private void onPlayerShearEntity(PlayerShearEntityEvent event) { if (event.getEntity().getType() != XEntityType.MOOSHROOM.get()) return; - if (event.getPlayer().hasCooldown(XMaterial.SHEARS.parseMaterial())) { + if (event.getPlayer().hasCooldown(XMaterial.SHEARS.get())) { event.setCancelled(true); } else { - event.getPlayer().setCooldown(XMaterial.SHEARS.parseMaterial(), 2); + event.getPlayer().setCooldown(XMaterial.SHEARS.get(), 2); } } } diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/dupepreventions/EndPortalDupe.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/dupepreventions/EndPortalDupe.java index a2f9763cd..786dab814 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/dupepreventions/EndPortalDupe.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/dupepreventions/EndPortalDupe.java @@ -4,7 +4,6 @@ import me.xginko.aef.utils.EntityUtil; import org.bukkit.World; import org.bukkit.entity.ChestedHorse; -import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.LivingEntity; import org.bukkit.event.EventHandler; @@ -16,11 +15,10 @@ public class EndPortalDupe extends AEFModule implements Listener { public EndPortalDupe() { - super("dupe-preventions.prevent-end-portal-dupe"); - config.addComment(configPath, + super("dupe-preventions.prevent-end-portal-dupe", false, "Patches a dupe that involves pushing a chestable entity\n" + - "with low hp into an end portal, duplicating its inventory\n" + - "content on death"); + "with low hp into an end portal, duplicating its inventory\n" + + "content on death"); } @Override @@ -28,11 +26,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath, false); - } - @Override public void disable() { HandlerList.unregisterAll(this); @@ -40,17 +33,12 @@ public void disable() { @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) private void onEntityDamage(EntityDamageEvent event) { - switch (event.getCause()) { - case ENTITY_ATTACK: - case FALL: - return; - } + if (event.getCause() == EntityDamageEvent.DamageCause.ENTITY_ATTACK || event.getCause() == EntityDamageEvent.DamageCause.FALL) return; + if (event.getEntity().getWorld().getEnvironment() != World.Environment.THE_END) return; + if (event.getEntity().getType() == EntityType.PLAYER) return; + if (!EntityUtil.isLivingEntity(event.getEntity())) return; - final Entity entity = event.getEntity(); - if (entity.getType() == EntityType.PLAYER) return; - if (entity.getWorld().getEnvironment() != World.Environment.THE_END) return; - if (!EntityUtil.isLivingEntity(entity)) return; - final LivingEntity livingEntity = (LivingEntity) entity; + final LivingEntity livingEntity = (LivingEntity) event.getEntity(); if ( livingEntity.getCanPickupItems() diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/elytra/ElytraAtSpawn.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/elytra/ElytraAtSpawn.java index ae9bab2f3..3b0ad78ac 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/elytra/ElytraAtSpawn.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/elytra/ElytraAtSpawn.java @@ -23,8 +23,8 @@ public class ElytraAtSpawn extends AEFModule implements Listener { private final boolean spawn_shouldCheckPermission, spawn_DenyElytra, spawn_DenyOnLowTPS, spawn_AlsoRemoveElytraOnLowTPS; public ElytraAtSpawn() { - super("elytra.elytra-speed.At-Spawn"); - config.addComment(configPath + ".enable", "Use separate values for players at spawn."); + super("elytra.elytra-speed.At-Spawn", false, + "Use separate values for players at spawn."); this.spawn_shouldCheckPermission = config.getBoolean(configPath + ".use-bypass-permission", false, "Can be slow with a lot of players. Enable only if needed."); this.spawn_DenyElytra = config.getBoolean(configPath + ".deny-elytra-usage", false); diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/elytra/ElytraGlobal.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/elytra/ElytraGlobal.java index 11217f3bd..b0e7e8ee2 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/elytra/ElytraGlobal.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/elytra/ElytraGlobal.java @@ -25,10 +25,7 @@ public class ElytraGlobal extends AEFModule implements Listener { global_AlsoRemoveOnLowTPS; public ElytraGlobal() { - super("elytra.elytra-speed.Global-Settings"); - config.addComment("elytra.elytra-speed", - "NOTE: Set nocheatplus horizontal elytra settings to 500 or higher."); - config.addComment(configPath + ".enable", + super("elytra.elytra-speed.Global-Settings", false, "Global settings. If nothing else is enabled, this will be used for all environments."); this.global_shouldCheckPermission = config.getBoolean(configPath + ".use-bypass-permission", false, "Can be slow with a lot of players. Enable only if needed."); diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/elytra/ElytraHelper.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/elytra/ElytraHelper.java index 18364d30b..6c09b3ad3 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/elytra/ElytraHelper.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/elytra/ElytraHelper.java @@ -36,18 +36,17 @@ public class ElytraHelper extends AEFModule implements Runnable, PacketListener, Listener { private static ElytraHelper instance; - private final Map playerDataMap; - private final PacketListenerAbstract packetListener; + private final long speed_as_ticks = config.elytra_speed_calc_period_millis / 50L; + + private Map playerDataMap; + private PacketListenerAbstract packetListener; private NewChunksListener newChunksListener; private ScheduledExecutorService executorService; private ScheduledFuture scheduledTask; - private final long speed_as_ticks = config.elytra_speed_calc_period_millis / 50L; public ElytraHelper() { super("elytra.elytra-speed"); instance = this; - playerDataMap = new ConcurrentHashMap<>(); - packetListener = asAbstract(PacketListenerPriority.MONITOR); } public static ElytraHelper getInstance() { @@ -56,22 +55,42 @@ public static ElytraHelper getInstance() { @Override public void enable() { - plugin.getServer().getPluginManager().registerEvents(this, plugin); + playerDataMap = new ConcurrentHashMap<>(); + packetListener = asAbstract(PacketListenerPriority.MONITOR); PacketEvents.getAPI().getEventManager().registerListener(packetListener); + plugin.getServer().getPluginManager().registerEvents(this, plugin); executorService = Executors.newScheduledThreadPool(1); scheduledTask = executorService.scheduleAtFixedRate( this, 50L, config.elytra_speed_calc_period_millis, TimeUnit.MILLISECONDS); - if (!ChunkUtil.canGetInhabitedTime()) + if (!ChunkUtil.canGetInhabitedTime()) { newChunksListener = new NewChunksListener(); + plugin.getServer().getPluginManager().registerEvents(newChunksListener, plugin); + } } @Override public void disable() { HandlerList.unregisterAll(this); - if (newChunksListener != null) HandlerList.unregisterAll(newChunksListener); - PacketEvents.getAPI().getEventManager().unregisterListener(packetListener); - if (scheduledTask != null) scheduledTask.cancel(true); - if (executorService != null) executorService.shutdown(); + if (newChunksListener != null) { + HandlerList.unregisterAll(newChunksListener); + newChunksListener = null; + } + if (packetListener != null) { + PacketEvents.getAPI().getEventManager().unregisterListener(packetListener); + packetListener = null; + } + if (playerDataMap != null) { + playerDataMap.clear(); + playerDataMap = null; + } + if (scheduledTask != null) { + scheduledTask.cancel(true); + scheduledTask = null; + } + if (executorService != null) { + executorService.close(); + executorService = null; + } } @Override diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/elytra/ElytraOnCeiling.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/elytra/ElytraOnCeiling.java index 0e7bb902b..ccae21624 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/elytra/ElytraOnCeiling.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/elytra/ElytraOnCeiling.java @@ -25,8 +25,7 @@ public class ElytraOnCeiling extends AEFModule implements Listener { ceiling_AlsoRemoveOnLowTPS; public ElytraOnCeiling() { - super("elytra.elytra-speed.Nether-Ceiling"); - config.addComment(configPath + ".enable", + super("elytra.elytra-speed.Nether-Ceiling", false, "Use separate values for players above the nether ceiling."); this.ceiling_shouldCheckPermission = config.getBoolean(configPath + ".use-bypass-permission", false, "Can be slow with a lot of players. Enable only if needed."); diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/elytra/ElytraPacketFly.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/elytra/ElytraPacketFly.java index fea0553f1..d1cacd53e 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/elytra/ElytraPacketFly.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/elytra/ElytraPacketFly.java @@ -20,10 +20,12 @@ public class ElytraPacketFly extends AEFModule implements Listener { - private final Cache elytraOpenCounts; + private final long durationMillis; private final int maxElytraOpensPerTime; private final boolean notify, kickPlayer; + private Cache elytraOpenCounts; + public ElytraPacketFly() { super("elytra.packet-elytra-fly"); config.addComment(configPath + ".patch-packet-elytra-fly", @@ -35,10 +37,8 @@ public ElytraPacketFly() { "Still may trigger false positives when players are jumping and\n" + "sprinting with elytra equipped, so recommended to play around\n" + "with the values."); - this.elytraOpenCounts = Caffeine.newBuilder().expireAfterWrite(Duration.ofSeconds(Math.max(1, - config.getInt(configPath + ".time-in-seconds", 8, - "Time in seconds a elytra open count will be remembered by the plugin.") - ))).build(); + this.durationMillis = Math.max(1, config.getInt(configPath + ".time-in-seconds", 8, + "Time in seconds a elytra open count will be remembered by the plugin.")); this.notify = config.getBoolean(configPath + ".notify-player-to-disable-packetfly", true, "Configure message in lang folder."); this.kickPlayer = config.getBoolean(configPath + ".kick-instead-of-remove-elytra", false, @@ -48,17 +48,17 @@ public ElytraPacketFly() { @Override public void enable() { + elytraOpenCounts = Caffeine.newBuilder().expireAfterWrite(Duration.ofMillis(durationMillis)).build(); plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".patch-packet-elytra-fly", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); + if (elytraOpenCounts != null) { + elytraOpenCounts.invalidateAll(); + elytraOpenCounts.cleanUp(); + } } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/BannedItemNames.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/BannedItemNames.java index 89817925e..b1d85693a 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/BannedItemNames.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/BannedItemNames.java @@ -24,13 +24,12 @@ public class BannedItemNames extends IllegalItemModule { private final boolean delete; public BannedItemNames() { - super("illegals.banned-item-names", AEFPermission.BYPASS_ILLEGAL_BANNEDNAME); - config.addComment(configPath + ".enable", - "Bypass permission: " + bypassPermission.string() + "\n" + - "Resets an item's name (or deletes the item) if it matches one of\n" + - "the configured regexes.\n" + - "Regexes can be complex. Use a tool like https://regex101.com/ or\n" + - "ChatGPT for good results."); + super("illegals.banned-item-names", false, AEFPermission.BYPASS_ILLEGAL_BANNEDNAME, + "Bypass permission: " + AEFPermission.BYPASS_ILLEGAL_BANNEDNAME.string() + "\n" + + "Resets an item's name (or deletes the item) if it matches one of\n" + + "the configured regexes.\n" + + "Regexes can be complex. Use a tool like https://regex101.com/ or\n" + + "ChatGPT for good results."); this.delete = config.getBoolean(configPath + ".delete-item", false, "Will delete the item instead of resetting the name."); this.bannedRegex = config.getList(configPath + ".regex", Collections.singletonList("(?i)illegalstring")) @@ -52,11 +51,6 @@ public BannedItemNames() { .collect(Collectors.toCollection(() -> EnumSet.noneOf(Material.class))); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public @NotNull ItemLegality legalityOf(@Nullable ItemStack itemStack) { if ( diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/BannedMaterials.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/BannedMaterials.java index 838dfd9d0..612413607 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/BannedMaterials.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/BannedMaterials.java @@ -23,9 +23,8 @@ public class BannedMaterials extends IllegalItemModule { private final boolean checkStored; public BannedMaterials() { - super("illegals.ban-specific-materials", AEFPermission.BYPASS_ILLEGAL_BANNEDMATERIAL); - config.addComment(configPath + ".enable", - "Bypass permission: " + bypassPermission.string() + "\n" + + super("illegals.ban-specific-materials", false, AEFPermission.BYPASS_ILLEGAL_BANNEDMATERIAL, + "Bypass permission: " + AEFPermission.BYPASS_ILLEGAL_BANNEDMATERIAL.string() + "\n" + "Prevents usage of or deletes items with material that you do not want\n" + "your players to be able to use.\n" + "Useful if your players have blocks that shouldn't be obtainable in survival."); @@ -44,7 +43,7 @@ public BannedMaterials() { XMaterial.NETHER_PORTAL, XMaterial.LIGHT) .filter(XMaterial::isSupported) - .map(XMaterial::parseMaterial) + .map(XMaterial::get) .map(Enum::name) .collect(Collectors.toList()); this.bannedMaterials = config.getList(configPath + ".banned-materials", defaults) @@ -61,11 +60,6 @@ public BannedMaterials() { .collect(Collectors.toCollection(() -> EnumSet.noneOf(Material.class))); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public @NotNull ItemLegality legalityOf(@Nullable ItemStack itemStack) { if (itemStack == null) { diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/IllegalItemModule.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/IllegalItemModule.java index 6b136ea24..ec024209b 100644 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/IllegalItemModule.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/IllegalItemModule.java @@ -59,7 +59,11 @@ public abstract class IllegalItemModule extends AEFModule implements Listener { private final Function, @PolyNull ExpiringSet> createIfAbsent; public IllegalItemModule(String configPath, AEFPermission bypassPermission) { - super(configPath); + this(configPath, false, bypassPermission, null); + } + + public IllegalItemModule(String configPath, boolean defEnabled, AEFPermission bypassPermission, String comment) { + super(configPath, defEnabled, comment); this.bypassPermission = bypassPermission; this.optionalListeners = new HashSet<>(); @@ -174,6 +178,8 @@ public void disable() { HandlerList.unregisterAll(this); optionalListeners.forEach(HandlerList::unregisterAll); optionalListeners.clear(); + listenerCooldowns.asMap().clear(); + listenerCooldowns.cleanUp(); } public ItemLegality legalityOf(Iterable itemStacks) { diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/IllegalPotions.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/IllegalPotions.java index 8ebebaad4..e8da52c33 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/IllegalPotions.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/IllegalPotions.java @@ -15,19 +15,13 @@ public class IllegalPotions extends IllegalItemModule { private final boolean checkStored; public IllegalPotions() { - super("illegals.potions", AEFPermission.BYPASS_ILLEGAL_POTIONS); - config.addComment(configPath + ".enable", - "Bypass permission: " + bypassPermission.string() + "\n" + - "Prevents usage of or reverts items with any attribute modifiers\n" + - "or item flags."); + super("illegals.potions", false, AEFPermission.BYPASS_ILLEGAL_POTIONS, + "Bypass permission: " + AEFPermission.BYPASS_ILLEGAL_POTIONS.string() + "\n" + + "Prevents usage of or reverts items with any attribute modifiers\n" + + "or item flags."); this.checkStored = config.getBoolean(configPath + ".check-stored-items", false); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public @NotNull ItemLegality legalityOf(@Nullable ItemStack itemStack) { if (itemStack == null || !MaterialUtil.POTIONS.contains(itemStack.getType()) || !itemStack.hasItemMeta()) { diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/InvalidStackSize.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/InvalidStackSize.java index ca5fe7503..2caee7ffe 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/InvalidStackSize.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/InvalidStackSize.java @@ -31,7 +31,7 @@ public InvalidStackSize() { this.blacklistMode = config.getBoolean(configPath + ".use-as-blacklist-instead", true); this.checkStored = config.getBoolean(configPath + ".check-stored-items", false); this.whitelistedTypes = config.getList(configPath + ".whitelisted-items", - Collections.singletonList(XMaterial.TOTEM_OF_UNDYING.parseMaterial().name())) + Collections.singletonList(XMaterial.TOTEM_OF_UNDYING.get().name())) .stream() .map(configuredType -> { try { @@ -52,7 +52,7 @@ public boolean shouldEnable() { @Override public @NotNull ItemLegality legalityOf(@Nullable ItemStack itemStack) { - if (itemStack == null || itemStack.getType() == Material.AIR) { + if (itemStack == null || itemStack.getType() == XMaterial.AIR.get()) { return ItemLegality.LEGAL; } diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/PlayerHeads.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/PlayerHeads.java index 1fd8040af..5dc8922fd 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/PlayerHeads.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/PlayerHeads.java @@ -14,19 +14,13 @@ public class PlayerHeads extends IllegalItemModule { private final boolean checkStored; public PlayerHeads() { - super("illegals.ban-player-heads", AEFPermission.BYPASS_ILLEGAL_PLAYERHEAD); - config.addComment(configPath + ".enable", - "Bypass permission: " + bypassPermission.string() + "\n" + + super("illegals.ban-player-heads", false, AEFPermission.BYPASS_ILLEGAL_PLAYERHEAD, + "Bypass permission: " + AEFPermission.BYPASS_ILLEGAL_PLAYERHEAD.string() + "\n" + "Deletes or prevents usage of player heads."); this.checkStored = config.getBoolean(configPath + ".check-stored-items", false, "Will delete shulker/bundle if they contain any player heads."); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public @NotNull ItemLegality legalityOf(@Nullable ItemStack itemStack) { if (itemStack == null) { diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/SpawnEggs.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/SpawnEggs.java index ed2d6b419..78b1918ce 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/SpawnEggs.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/SpawnEggs.java @@ -23,15 +23,14 @@ public class SpawnEggs extends IllegalItemModule { private final boolean checkStored; public SpawnEggs() { - super("illegals.ban-spawn-eggs", AEFPermission.BYPASS_ILLEGAL_SPAWNEGG); - config.addComment(configPath + ".enable", - "Bypass permission: " + bypassPermission.string() + "\n" + + super("illegals.ban-spawn-eggs", false, AEFPermission.BYPASS_ILLEGAL_SPAWNEGG, + "Bypass permission: " + AEFPermission.BYPASS_ILLEGAL_SPAWNEGG.string() + "\n" + "Deletes or prevents usage of spawn eggs."); this.checkStored = config.getBoolean(configPath + ".check-stored-items", false, "If remove-spawn-eggs is set to true Will delete shulker/bundle\n" + "should they contain any spawneggs."); this.whitelistedTypes = config.getList(configPath + ".whitelisted-items", - Collections.singletonList(XMaterial.VILLAGER_SPAWN_EGG.parseMaterial().name())) + Collections.singletonList(XMaterial.VILLAGER_SPAWN_EGG.get().name())) .stream() .map(configuredType -> { try { @@ -45,11 +44,6 @@ public SpawnEggs() { .collect(Collectors.toCollection(() -> EnumSet.noneOf(Material.class))); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public @NotNull ItemLegality legalityOf(@Nullable ItemStack itemStack) { if (itemStack == null || whitelistedTypes.contains(itemStack.getType())) { diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/Unbreakables.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/Unbreakables.java index 787e53276..77acb370a 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/Unbreakables.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/Unbreakables.java @@ -5,6 +5,7 @@ import me.xginko.aef.enums.IllegalHandling; import me.xginko.aef.enums.ItemLegality; import me.xginko.aef.utils.ItemUtil; +import me.xginko.aef.utils.MaterialUtil; import me.xginko.aef.utils.PlatformUtil; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; @@ -24,14 +25,13 @@ public class Unbreakables extends IllegalItemModule { private final boolean skipZeroDurability, useWhitelist, blacklistMode, checkStored; public Unbreakables() { - super("illegals.revert-unbreakables", AEFPermission.BYPASS_ILLEGAL_UNBREAKABLE); - config.addComment(configPath + ".enable", - "Bypass permission: " + bypassPermission.string() + "\n" + - "Deletes and prevents usage of unbreakable items.\n" + - "This can be anything from items with illegal damage attributes to\n" + - "Metadata/NBT tags.\n" + - "Note: Due to the limitations of the API, we can only fully prevent\n" + - "usage of these items by deleting them."); + super("illegals.revert-unbreakables", false, AEFPermission.BYPASS_ILLEGAL_UNBREAKABLE, + "Bypass permission: " + AEFPermission.BYPASS_ILLEGAL_UNBREAKABLE.string() + "\n" + + "Deletes and prevents usage of unbreakable items.\n" + + "This can be anything from items with illegal damage attributes to\n" + + "Metadata/NBT tags.\n" + + "Note: Due to the limitations of the API, we can only fully prevent\n" + + "usage of these items by deleting them."); this.useWhitelist = config.getBoolean(configPath + ".item-whitelist-enabled", false); this.blacklistMode = config.getBoolean(configPath + ".use-as-blacklist-instead", false); this.checkStored = config.getBoolean(configPath + ".check-stored-items", false, @@ -40,7 +40,7 @@ public Unbreakables() { "Make sure to keep enabled on 1.16+, otherwise netherite tools\n" + "will mistakenly be set to max durability, due to some bug in paper."); this.whitelistedTypes = config.getList(configPath + ".whitelisted-items", - Collections.singletonList(XMaterial.DIAMOND_CHESTPLATE.parseMaterial().name())) + Collections.singletonList(XMaterial.DIAMOND_CHESTPLATE.get().name())) .stream() .map(configuredType -> { try { @@ -54,14 +54,9 @@ public Unbreakables() { .collect(Collectors.toCollection(() -> EnumSet.noneOf(Material.class))); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public @NotNull ItemLegality legalityOf(@Nullable ItemStack itemStack) { - if (itemStack == null || itemStack.getType() == Material.AIR) { + if (itemStack == null || MaterialUtil.AIR.contains(itemStack.getType())) { return ItemLegality.LEGAL; } diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/datavalues/CustomDataValues.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/datavalues/CustomDataValues.java index 66513f506..8c92d405d 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/datavalues/CustomDataValues.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/datavalues/CustomDataValues.java @@ -5,6 +5,7 @@ import me.xginko.aef.enums.ItemLegality; import me.xginko.aef.modules.illegals.items.IllegalItemModule; import me.xginko.aef.utils.ItemUtil; +import me.xginko.aef.utils.MaterialUtil; import me.xginko.aef.utils.PlatformUtil; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; @@ -25,12 +26,11 @@ public class CustomDataValues extends IllegalItemModule { private final boolean useWhitelist, blacklistMode, checkStored; public CustomDataValues() { - super("illegals.data-values.custom-data-values", AEFPermission.BYPASS_ILLEGAL_DATA_CUSTOM); - config.addComment(configPath + ".enable", - "1.12 Only. Bypass permission: " + bypassPermission.string() + "\n" + - "Deletes items with configured illegal MaterialData values.\n" + - "Use '/aef datavalue' ingame while holding an item to add the\n" + - "specific value here."); + super("illegals.data-values.custom-data-values", false, AEFPermission.BYPASS_ILLEGAL_DATA_CUSTOM, + "1.12 Only. Bypass permission: " + AEFPermission.BYPASS_ILLEGAL_DATA_CUSTOM.string() + "\n" + + "Deletes items with configured illegal MaterialData values.\n" + + "Use '/aef datavalue' ingame while holding an item to add the\n" + + "specific value here."); this.checkStored = config.getBoolean(configPath + ".check-stored-items", false); this.forbiddenDataValues = new HashSet<>(config.getList(configPath + ".data-values", Collections.singletonList("SuperIllegalItem(0)"))); @@ -53,12 +53,12 @@ public CustomDataValues() { @Override public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false) && PlatformUtil.getMinecraftVersion() <= 12; + return configEnabled && PlatformUtil.getMinecraftVersion() <= 12; } @Override public @NotNull ItemLegality legalityOf(@Nullable ItemStack itemStack) { - if (itemStack == null || itemStack.getType() == Material.AIR) { + if (itemStack == null || MaterialUtil.AIR.contains(itemStack.getType())) { return ItemLegality.LEGAL; } diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/datavalues/IllegalGoldenApples.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/datavalues/IllegalGoldenApples.java index 7c163c1ff..1c216d91f 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/datavalues/IllegalGoldenApples.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/datavalues/IllegalGoldenApples.java @@ -22,27 +22,26 @@ public class IllegalGoldenApples extends IllegalItemModule { private final boolean checkStored; public IllegalGoldenApples() { - super("illegals.data-values.illegal-golden-apples", AEFPermission.BYPASS_ILLEGAL_DATA_APPLE); - config.addComment(configPath + ".enable", - "1.12 Only. Bypass permission: " + bypassPermission.string() + "\n" + - "Deletes apples with illegal MaterialData values. Will use the\n" + - "API to determine what a natural value looks like."); + super("illegals.data-values.illegal-golden-apples", false, AEFPermission.BYPASS_ILLEGAL_DATA_APPLE, + "1.12 Only. Bypass permission: " + AEFPermission.BYPASS_ILLEGAL_DATA_APPLE.string() + "\n" + + "Deletes apples with illegal MaterialData values. Will use the\n" + + "API to determine what a natural value looks like."); this.checkStored = config.getBoolean(configPath + ".check-stored-items", false); if (XMaterial.GOLDEN_APPLE.isSupported()) { this.allowedAppleData.put( - XMaterial.GOLDEN_APPLE.parseMaterial(), - new MaterialData(XMaterial.GOLDEN_APPLE.parseMaterial())); + XMaterial.GOLDEN_APPLE.get(), + new MaterialData(XMaterial.GOLDEN_APPLE.get())); } if (XMaterial.ENCHANTED_GOLDEN_APPLE.isSupported()) { this.allowedAppleData.put( - XMaterial.ENCHANTED_GOLDEN_APPLE.parseMaterial(), - new MaterialData(XMaterial.ENCHANTED_GOLDEN_APPLE.parseMaterial())); + XMaterial.ENCHANTED_GOLDEN_APPLE.get(), + new MaterialData(XMaterial.ENCHANTED_GOLDEN_APPLE.get())); } } @Override public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false) && PlatformUtil.getMinecraftVersion() <= 12; + return configEnabled && PlatformUtil.getMinecraftVersion() <= 12; } @Override diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/enchantments/HigherEnchants.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/enchantments/HigherEnchants.java index 572bc019f..a39a8d6fa 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/enchantments/HigherEnchants.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/enchantments/HigherEnchants.java @@ -1,10 +1,12 @@ package me.xginko.aef.modules.illegals.items.enchantments; +import com.cryptomorin.xseries.XEnchantment; import me.xginko.aef.enums.AEFPermission; import me.xginko.aef.enums.IllegalHandling; import me.xginko.aef.enums.ItemLegality; import me.xginko.aef.modules.illegals.items.IllegalItemModule; import me.xginko.aef.utils.ItemUtil; +import me.xginko.aef.utils.MaterialUtil; import org.bukkit.Material; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemStack; @@ -16,6 +18,7 @@ import java.util.HashSet; import java.util.Map; import java.util.Objects; +import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; @@ -26,19 +29,21 @@ public class HigherEnchants extends IllegalItemModule { private final boolean useWhitelist, blacklistMode, checkStored, onlySomeEnchants; public HigherEnchants() { - super("illegals.enchantments.higher-enchants", AEFPermission.BYPASS_ILLEGAL_ENCHANT_HIGHER); - config.addComment(configPath + ".enable", - "Bypass permission: " + bypassPermission.string() + "\n" + - "Reverts or prevents usage of ItemStacks with Enchantments higher\n" + - "than the natural, in vanilla survival obtainable level (aka 32ks / 255s)."); + super("illegals.enchantments.higher-enchants", false, AEFPermission.BYPASS_ILLEGAL_ENCHANT_HIGHER, + "Bypass permission: " + AEFPermission.BYPASS_ILLEGAL_ENCHANT_HIGHER.string() + "\n" + + "Reverts or prevents usage of ItemStacks with Enchantments higher\n" + + "than the natural, in vanilla survival obtainable level (aka 32ks / 255s)."); this.checkStored = config.getBoolean(configPath + ".check-stored-items", false); this.onlySomeEnchants = config.getBoolean(configPath + ".only-specific-enchants", false); this.specificEnchants = config.getList(configPath + ".specific-enchants", Collections.singletonList("DIG_SPEED")) .stream() .map(configuredEnchant -> { - final Enchantment enchantment = Enchantment.getByName(configuredEnchant); - if (enchantment == null) notRecognized(Enchantment.class, configuredEnchant); - return enchantment; + Optional enchantment = XEnchantment.of(configuredEnchant); + if (!enchantment.isPresent()) { + notRecognized(Enchantment.class, configuredEnchant); + return null; + } + return enchantment.get().get(); }) .filter(Objects::nonNull) .collect(Collectors.toCollection(HashSet::new)); @@ -58,14 +63,9 @@ public HigherEnchants() { .collect(Collectors.toCollection(() -> EnumSet.noneOf(Material.class))); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public @NotNull ItemLegality legalityOf(@Nullable ItemStack itemStack) { - if (itemStack == null || itemStack.getType() == Material.AIR) { + if (itemStack == null || MaterialUtil.AIR.contains(itemStack.getType())) { return ItemLegality.LEGAL; } diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/enchantments/InapplicableEnchants.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/enchantments/InapplicableEnchants.java index 8509d6bde..cbf8b2caa 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/enchantments/InapplicableEnchants.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/enchantments/InapplicableEnchants.java @@ -1,11 +1,11 @@ package me.xginko.aef.modules.illegals.items.enchantments; -import me.xginko.aef.AnarchyExploitFixes; import me.xginko.aef.enums.AEFPermission; import me.xginko.aef.enums.IllegalHandling; import me.xginko.aef.enums.ItemLegality; import me.xginko.aef.modules.illegals.items.IllegalItemModule; import me.xginko.aef.utils.ItemUtil; +import me.xginko.aef.utils.MaterialUtil; import org.bukkit.Material; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemStack; @@ -25,12 +25,11 @@ public class InapplicableEnchants extends IllegalItemModule { private final boolean useWhitelist, blacklistMode, checkStored; public InapplicableEnchants() { - super("illegals.enchantments.inapplicable-enchants", AEFPermission.BYPASS_ILLEGAL_ENCHANT_INAPPLICABLE); - config.addComment(configPath + ".enable", - "Bypass permission: " + bypassPermission.string() + "\n" + - "Reverts or prevents usage of ItemStacks with Enchantments that\n" + - "cannot be applied to that ItemStack in vanilla survival minecraft.\n" + - "Examples: A helmet with sharpness or a block of stone with fortune."); + super("illegals.enchantments.inapplicable-enchants", false, AEFPermission.BYPASS_ILLEGAL_ENCHANT_INAPPLICABLE, + "Bypass permission: " + AEFPermission.BYPASS_ILLEGAL_ENCHANT_INAPPLICABLE.string() + "\n" + + "Reverts or prevents usage of ItemStacks with Enchantments that\n" + + "cannot be applied to that ItemStack in vanilla survival minecraft.\n" + + "Examples: A helmet with sharpness or a block of stone with fortune."); this.checkStored = config.getBoolean(configPath + ".check-stored-items", false); this.useWhitelist = config.getBoolean(configPath + ".item-whitelist-enabled", true); this.blacklistMode = config.getBoolean(configPath + ".use-as-blacklist-instead", false); @@ -49,14 +48,9 @@ public InapplicableEnchants() { .collect(Collectors.toCollection(() -> EnumSet.noneOf(Material.class))); } - @Override - public boolean shouldEnable() { - return AnarchyExploitFixes.config().getBoolean(configPath + ".enable", false); - } - @Override public @NotNull ItemLegality legalityOf(@Nullable ItemStack itemStack) { - if (itemStack == null || itemStack.getType() == Material.AIR) { + if (itemStack == null || MaterialUtil.AIR.contains(itemStack.getType())) { return ItemLegality.LEGAL; } diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/enchantments/IncompatibleEnchants.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/enchantments/IncompatibleEnchants.java index 947aa3501..63c3054af 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/enchantments/IncompatibleEnchants.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/enchantments/IncompatibleEnchants.java @@ -1,10 +1,12 @@ package me.xginko.aef.modules.illegals.items.enchantments; +import com.cryptomorin.xseries.XEnchantment; import me.xginko.aef.enums.AEFPermission; import me.xginko.aef.enums.IllegalHandling; import me.xginko.aef.enums.ItemLegality; import me.xginko.aef.modules.illegals.items.IllegalItemModule; import me.xginko.aef.utils.ItemUtil; +import me.xginko.aef.utils.MaterialUtil; import org.bukkit.Material; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemStack; @@ -17,27 +19,6 @@ import java.util.Set; import java.util.stream.Collectors; -import static com.cryptomorin.xseries.XEnchantment.BANE_OF_ARTHROPODS; -import static com.cryptomorin.xseries.XEnchantment.BINDING_CURSE; -import static com.cryptomorin.xseries.XEnchantment.BLAST_PROTECTION; -import static com.cryptomorin.xseries.XEnchantment.CHANNELING; -import static com.cryptomorin.xseries.XEnchantment.DEPTH_STRIDER; -import static com.cryptomorin.xseries.XEnchantment.FIRE_PROTECTION; -import static com.cryptomorin.xseries.XEnchantment.FORTUNE; -import static com.cryptomorin.xseries.XEnchantment.FROST_WALKER; -import static com.cryptomorin.xseries.XEnchantment.INFINITY; -import static com.cryptomorin.xseries.XEnchantment.LOYALTY; -import static com.cryptomorin.xseries.XEnchantment.MENDING; -import static com.cryptomorin.xseries.XEnchantment.MULTISHOT; -import static com.cryptomorin.xseries.XEnchantment.PIERCING; -import static com.cryptomorin.xseries.XEnchantment.PROJECTILE_PROTECTION; -import static com.cryptomorin.xseries.XEnchantment.PROTECTION; -import static com.cryptomorin.xseries.XEnchantment.RIPTIDE; -import static com.cryptomorin.xseries.XEnchantment.SHARPNESS; -import static com.cryptomorin.xseries.XEnchantment.SILK_TOUCH; -import static com.cryptomorin.xseries.XEnchantment.SMITE; -import static com.cryptomorin.xseries.XEnchantment.VANISHING_CURSE; - public class IncompatibleEnchants extends IllegalItemModule { private final Set whitelistedTypes; @@ -45,16 +26,15 @@ public class IncompatibleEnchants extends IllegalItemModule { private final boolean useWhitelist, blacklistMode, checkStored; public IncompatibleEnchants() { - super("illegals.enchantments.incompatible-enchants", AEFPermission.BYPASS_ILLEGAL_ENCHANT_INCOMPATIBLE); - this.damageEnchants = new Enchantment[]{SHARPNESS.getEnchant(), SMITE.getEnchant(), BANE_OF_ARTHROPODS.getEnchant()}; - this.protectionEnchants = new Enchantment[]{PROTECTION.getEnchant(), BLAST_PROTECTION.getEnchant(), - FIRE_PROTECTION.getEnchant(), PROJECTILE_PROTECTION.getEnchant()}; - config.addComment(configPath + ".enable", - "Bypass permission: " + bypassPermission.string() + "\n" + - "Reverts or prevents usage of ItemStacks with Enchantments that\n" + - "cannot coexist in vanilla survival minecraft.\n" + - "Examples: A bow with mending and infinity or armor with every\n" + - "protection enchantment."); + super("illegals.enchantments.incompatible-enchants", false, AEFPermission.BYPASS_ILLEGAL_ENCHANT_INCOMPATIBLE, + "Bypass permission: " + AEFPermission.BYPASS_ILLEGAL_ENCHANT_INCOMPATIBLE.string() + "\n" + + "Reverts or prevents usage of ItemStacks with Enchantments that\n" + + "cannot coexist in vanilla survival minecraft.\n" + + "Examples: A bow with mending and infinity or armor with every\n" + + "protection enchantment."); + this.damageEnchants = new Enchantment[]{XEnchantment.SHARPNESS.get(), XEnchantment.SMITE.get(), XEnchantment.BANE_OF_ARTHROPODS.get()}; + this.protectionEnchants = new Enchantment[]{XEnchantment.PROTECTION.get(), XEnchantment.BLAST_PROTECTION.get(), + XEnchantment.FIRE_PROTECTION.get(), XEnchantment.PROJECTILE_PROTECTION.get()}; this.checkStored = config.getBoolean(configPath + ".check-stored-items", false); this.useWhitelist = config.getBoolean(configPath + ".item-whitelist-enabled", true); this.blacklistMode = config.getBoolean(configPath + ".use-as-blacklist-instead", false); @@ -72,14 +52,9 @@ public IncompatibleEnchants() { .collect(Collectors.toCollection(() -> EnumSet.noneOf(Material.class))); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public @NotNull ItemLegality legalityOf(@Nullable ItemStack itemStack) { - if (itemStack == null || itemStack.getType() == Material.AIR) { + if (itemStack == null || MaterialUtil.AIR.contains(itemStack.getType())) { return ItemLegality.LEGAL; } @@ -87,21 +62,21 @@ public boolean shouldEnable() { final Set enchantments = itemStack.getEnchantments().keySet(); if (!enchantments.isEmpty()) { - if (enchantments.contains(SILK_TOUCH.getEnchant()) && enchantments.contains(FORTUNE.getEnchant())) + if (enchantments.contains(XEnchantment.SILK_TOUCH.get()) && enchantments.contains(XEnchantment.FORTUNE.get())) return ItemLegality.ILLEGAL; - if (enchantments.contains(DEPTH_STRIDER.getEnchant()) && enchantments.contains(FROST_WALKER.getEnchant())) + if (enchantments.contains(XEnchantment.DEPTH_STRIDER.get()) && enchantments.contains(XEnchantment.FROST_WALKER.get())) return ItemLegality.ILLEGAL; - if (enchantments.contains(INFINITY.getEnchant()) && enchantments.contains(MENDING.getEnchant())) + if (enchantments.contains(XEnchantment.INFINITY.get()) && enchantments.contains(XEnchantment.MENDING.get())) return ItemLegality.ILLEGAL; - if (enchantments.contains(BINDING_CURSE.getEnchant()) && enchantments.contains(VANISHING_CURSE.getEnchant())) + if (enchantments.contains(XEnchantment.BINDING_CURSE.get()) && enchantments.contains(XEnchantment.VANISHING_CURSE.get())) return ItemLegality.ILLEGAL; - if (RIPTIDE.isSupported()) { - if (enchantments.contains(RIPTIDE.getEnchant()) - && (enchantments.contains(LOYALTY.getEnchant()) || enchantments.contains(CHANNELING.getEnchant()))) + if (XEnchantment.RIPTIDE.isSupported()) { + if (enchantments.contains(XEnchantment.RIPTIDE.get()) + && (enchantments.contains(XEnchantment.LOYALTY.get()) || enchantments.contains(XEnchantment.CHANNELING.get()))) return ItemLegality.ILLEGAL; } - if (MULTISHOT.isSupported()) { - if (enchantments.contains(MULTISHOT.getEnchant()) && enchantments.contains(PIERCING.getEnchant())) + if (XEnchantment.MULTISHOT.isSupported()) { + if (enchantments.contains(XEnchantment.MULTISHOT.get()) && enchantments.contains(XEnchantment.PIERCING.get())) return ItemLegality.ILLEGAL; } @@ -146,48 +121,48 @@ public void handleItem(ItemStack itemStack, ItemLegality legality) { final Set enchantments = itemStack.getEnchantments().keySet(); - if (enchantments.contains(SILK_TOUCH.getEnchant()) && enchantments.contains(FORTUNE.getEnchant())) - itemStack.removeEnchantment(FORTUNE.getEnchant()); - if (enchantments.contains(DEPTH_STRIDER.getEnchant()) && enchantments.contains(FROST_WALKER.getEnchant())) - itemStack.removeEnchantment(FROST_WALKER.getEnchant()); - if (enchantments.contains(INFINITY.getEnchant()) && enchantments.contains(MENDING.getEnchant())) - itemStack.removeEnchantment(INFINITY.getEnchant()); - if (enchantments.contains(BINDING_CURSE.getEnchant()) && enchantments.contains(VANISHING_CURSE.getEnchant())) - itemStack.removeEnchantment(BINDING_CURSE.getEnchant()); - if (RIPTIDE.isSupported()) { // 1.12 doesn't have tridents - if (enchantments.contains(RIPTIDE.getEnchant()) - && (enchantments.contains(LOYALTY.getEnchant()) || enchantments.contains(CHANNELING.getEnchant()))) - itemStack.removeEnchantment(RIPTIDE.getEnchant()); + if (enchantments.contains(XEnchantment.SILK_TOUCH.get()) && enchantments.contains(XEnchantment.FORTUNE.get())) + itemStack.removeEnchantment(XEnchantment.FORTUNE.get()); + if (enchantments.contains(XEnchantment.DEPTH_STRIDER.get()) && enchantments.contains(XEnchantment.FROST_WALKER.get())) + itemStack.removeEnchantment(XEnchantment.FROST_WALKER.get()); + if (enchantments.contains(XEnchantment.INFINITY.get()) && enchantments.contains(XEnchantment.MENDING.get())) + itemStack.removeEnchantment(XEnchantment.INFINITY.get()); + if (enchantments.contains(XEnchantment.BINDING_CURSE.get()) && enchantments.contains(XEnchantment.VANISHING_CURSE.get())) + itemStack.removeEnchantment(XEnchantment.BINDING_CURSE.get()); + if (XEnchantment.RIPTIDE.isSupported()) { // 1.12 doesn't have tridents + if (enchantments.contains(XEnchantment.RIPTIDE.get()) + && (enchantments.contains(XEnchantment.LOYALTY.get()) || enchantments.contains(XEnchantment.CHANNELING.get()))) + itemStack.removeEnchantment(XEnchantment.RIPTIDE.get()); } - if (MULTISHOT.isSupported()) { // 1.12 doesn't have crossbows - if (enchantments.contains(MULTISHOT.getEnchant()) && enchantments.contains(PIERCING.getEnchant())) - itemStack.removeEnchantment(MULTISHOT.getEnchant()); + if (XEnchantment.MULTISHOT.isSupported()) { // 1.12 doesn't have crossbows + if (enchantments.contains(XEnchantment.MULTISHOT.get()) && enchantments.contains(XEnchantment.PIERCING.get())) + itemStack.removeEnchantment(XEnchantment.MULTISHOT.get()); } - if (enchantments.contains(SHARPNESS.getEnchant())) { // Prefer keeping sharpness enchantment if present + if (enchantments.contains(XEnchantment.SHARPNESS.get())) { // Prefer keeping sharpness enchantment if present for (Enchantment dmgEnchant : damageEnchants) { - if (dmgEnchant != SHARPNESS.getEnchant()) { + if (dmgEnchant != XEnchantment.SHARPNESS.get()) { itemStack.removeEnchantment(dmgEnchant); } } - } else if (enchantments.contains(BANE_OF_ARTHROPODS.getEnchant()) && enchantments.contains(SMITE.getEnchant())) { - itemStack.removeEnchantment(BANE_OF_ARTHROPODS.getEnchant()); + } else if (enchantments.contains(XEnchantment.BANE_OF_ARTHROPODS.get()) && enchantments.contains(XEnchantment.SMITE.get())) { + itemStack.removeEnchantment(XEnchantment.BANE_OF_ARTHROPODS.get()); } - if (enchantments.contains(PROTECTION.getEnchant())) { // Prefer keeping protection enchantment if present + if (enchantments.contains(XEnchantment.PROTECTION.get())) { // Prefer keeping protection enchantment if present for (Enchantment protEnchant : protectionEnchants) { - if (protEnchant != PROTECTION.getEnchant()) { + if (protEnchant != XEnchantment.PROTECTION.get()) { itemStack.removeEnchantment(protEnchant); } } - } else if (enchantments.contains(BLAST_PROTECTION.getEnchant())) { // If protection isn't present, prefer blast protection + } else if (enchantments.contains(XEnchantment.BLAST_PROTECTION.get())) { // If protection isn't present, prefer blast protection for (Enchantment protEnchant : protectionEnchants) { - if (protEnchant != BLAST_PROTECTION.getEnchant()) { + if (protEnchant != XEnchantment.BLAST_PROTECTION.get()) { itemStack.removeEnchantment(protEnchant); } } - } else if (enchantments.contains(PROJECTILE_PROTECTION.getEnchant()) && enchantments.contains(FIRE_PROTECTION.getEnchant())) { - itemStack.removeEnchantment(FIRE_PROTECTION.getEnchant()); // If protection and blast protection is not present, prefer projectile protection + } else if (enchantments.contains(XEnchantment.PROJECTILE_PROTECTION.get()) && enchantments.contains(XEnchantment.FIRE_PROTECTION.get())) { + itemStack.removeEnchantment(XEnchantment.FIRE_PROTECTION.get()); // If protection and blast protection is not present, prefer projectile protection } } } \ No newline at end of file diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/nbt/CommandItems.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/nbt/CommandItems.java index 11ac2ec1c..00bcb880d 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/nbt/CommandItems.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/nbt/CommandItems.java @@ -5,7 +5,6 @@ import me.xginko.aef.modules.illegals.items.IllegalItemModule; import me.xginko.aef.utils.ItemUtil; import me.xginko.aef.utils.MaterialUtil; -import org.bukkit.Material; import org.bukkit.inventory.ItemStack; import org.checkerframework.checker.nullness.qual.Nullable; import org.jetbrains.annotations.NotNull; @@ -15,23 +14,17 @@ public class CommandItems extends IllegalItemModule { private final boolean checkStored; public CommandItems() { - super("illegals.nbt.command-items", AEFPermission.BYPASS_ILLEGAL_NBT_COMMAND_ITEM); - config.addComment(configPath + ".enable", - "Bypass permission: " + bypassPermission.string() + "\n" + + super("illegals.nbt.command-items", false, AEFPermission.BYPASS_ILLEGAL_NBT_COMMAND_ITEM, + "Bypass permission: " + AEFPermission.BYPASS_ILLEGAL_NBT_COMMAND_ITEM.string() + "\n" + "Deletes items with commands in their NBT data that run as operator.\n" + "These can only be created by players with creative access.\n" + "Most common items are books, since it allows storing multiple commands."); this.checkStored = config.getBoolean(configPath + ".check-stored-items", false); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public @NotNull ItemLegality legalityOf(@Nullable ItemStack itemStack) { - if (itemStack == null || itemStack.getType() == Material.AIR) { + if (itemStack == null || MaterialUtil.AIR.contains(itemStack.getType())) { return ItemLegality.LEGAL; } diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/nbt/CustomNBTFilter.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/nbt/CustomNBTFilter.java index 59dde091c..0e0c7a6c8 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/nbt/CustomNBTFilter.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/nbt/CustomNBTFilter.java @@ -5,6 +5,7 @@ import me.xginko.aef.enums.ItemLegality; import me.xginko.aef.modules.illegals.items.IllegalItemModule; import me.xginko.aef.utils.ItemUtil; +import me.xginko.aef.utils.MaterialUtil; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; import org.checkerframework.checker.nullness.qual.Nullable; @@ -24,10 +25,9 @@ public class CustomNBTFilter extends IllegalItemModule { private final boolean useWhitelist, blacklistMode, checkStored; public CustomNBTFilter() { - super("illegals.nbt.ban-custom-tags", AEFPermission.BYPASS_ILLEGAL_NBT_CUSTOM); - config.addComment(configPath + ".enable", - "Bypass permission: " + bypassPermission.string() + "\n" + - "Deletes items that have one or more of the configured tags."); + super("illegals.nbt.ban-custom-tags", false, AEFPermission.BYPASS_ILLEGAL_NBT_CUSTOM, + "Bypass permission: " + AEFPermission.BYPASS_ILLEGAL_NBT_CUSTOM.string() + "\n" + + "Deletes items that have one or more of the configured tags."); this.checkStored = config.getBoolean(configPath + ".check-stored-items", false); this.illegalTags = new HashSet<>(config.getList(configPath + ".tags", Collections.singletonList("dmg"), "The exact, case sensitive value of the nbt tag.")); @@ -47,14 +47,9 @@ public CustomNBTFilter() { .collect(Collectors.toCollection(() -> EnumSet.noneOf(Material.class))); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public @NotNull ItemLegality legalityOf(@Nullable ItemStack itemStack) { - if (itemStack == null || itemStack.getType() == Material.AIR) { + if (itemStack == null || MaterialUtil.AIR.contains(itemStack.getType())) { return ItemLegality.LEGAL; } diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/nbt/NBTFilledStorageItem.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/nbt/NBTFilledStorageItem.java index bbec50758..30e04890c 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/nbt/NBTFilledStorageItem.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/items/nbt/NBTFilledStorageItem.java @@ -24,9 +24,8 @@ public class NBTFilledStorageItem extends IllegalItemModule { private final boolean checkStored; public NBTFilledStorageItem() { - super("illegals.nbt.impossibly-stored-items", AEFPermission.BYPASS_ILLEGAL_NBT_STOREDITEMS); - config.addComment(configPath + ".enable", - "Bypass permission: " + bypassPermission.string() + "\n" + + super("illegals.nbt.impossibly-stored-items", false, AEFPermission.BYPASS_ILLEGAL_NBT_STOREDITEMS, + "Bypass permission: " + AEFPermission.BYPASS_ILLEGAL_NBT_STOREDITEMS.string() + "\n" + "Prevents usage of or deletes storage items that have been pre-filled\n" + "with items using NBT tags. These can only be created by players with\n" + "creative access.\n" + @@ -50,14 +49,9 @@ public NBTFilledStorageItem() { .collect(Collectors.toCollection(() -> EnumSet.noneOf(Material.class))); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public @NotNull ItemLegality legalityOf(@Nullable ItemStack itemStack) { - if (itemStack == null || itemStack.getType() == Material.AIR) { + if (itemStack == null || MaterialUtil.AIR.contains(itemStack.getType())) { return ItemLegality.LEGAL; } diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/placedblocks/PeriodicallyRemoveIllegalBlocks.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/placedblocks/PeriodicallyRemoveIllegalBlocks.java index 6f71d7895..75648d653 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/placedblocks/PeriodicallyRemoveIllegalBlocks.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/placedblocks/PeriodicallyRemoveIllegalBlocks.java @@ -28,21 +28,25 @@ public class PeriodicallyRemoveIllegalBlocks extends AEFModule implements Runnab private final long checkPeriod; private final double pauseTPS; private final boolean checkShouldPauseOnLowTPS; + private BukkitTask bukkitTask; public PeriodicallyRemoveIllegalBlocks() { - super("illegals.remove-placed-blocks.periodically"); + super("illegals.remove-placed-blocks.periodically", false); List defaults = Stream.of( - XMaterial.CHAIN_COMMAND_BLOCK, + XMaterial.PLAYER_HEAD, + XMaterial.PLAYER_WALL_HEAD, XMaterial.COMMAND_BLOCK, - XMaterial.COMMAND_BLOCK_MINECART, + XMaterial.CHAIN_COMMAND_BLOCK, XMaterial.REPEATING_COMMAND_BLOCK, XMaterial.BEDROCK, - XMaterial.BARRIER) - .map(XMaterial::parseMaterial) - .filter(Objects::nonNull) + XMaterial.BARRIER, + XMaterial.STRUCTURE_BLOCK, + XMaterial.STRUCTURE_VOID, + XMaterial.LIGHT) + .filter(XMaterial::isSupported) + .map(XMaterial::get) .map(Enum::name) - .sorted() .collect(Collectors.toList()); this.blocksToRemove = config.getList(configPath + ".blocks-to-remove", defaults) .stream() @@ -65,17 +69,16 @@ public PeriodicallyRemoveIllegalBlocks() { @Override public void enable() { - bukkitTask = plugin.getServer().getScheduler().runTaskTimer(plugin, this, checkPeriod, checkPeriod); - } - - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); + bukkitTask = plugin.getServer().getScheduler() + .runTaskTimer(plugin, this, checkPeriod, checkPeriod); } @Override public void disable() { - if (bukkitTask != null) bukkitTask.cancel(); + if (bukkitTask != null) { + bukkitTask.cancel(); + bukkitTask = null; + } } @Override @@ -101,28 +104,28 @@ public void run() { // If is skull, check if it is player head if (MaterialUtil.PLAYER_HEADS.contains(block.getType())) { - if (MaterialUtil.isPlayerHead(block.getState())) { - block.setType(XMaterial.AIR.parseMaterial(), false); + if (MaterialUtil.isPlayerHead(block.getState())) { // Necessary additional check due to legacy limitations + block.setType(XMaterial.AIR.get(), false); } continue; } // If is bedrock, make sure not to delete naturally generated - if (block.getType() == XMaterial.BEDROCK.parseMaterial()) { + if (block.getType() == XMaterial.BEDROCK.get()) { if (y > minY + 4) { // offset to not delete natural bedrock floor if (inNether) { // offset to not delete bedrock ceiling if (y < config.nether_ceiling_max_y - 5) - block.setType(XMaterial.AIR.parseMaterial(), false); + block.setType(XMaterial.AIR.get(), false); } else { - block.setType(XMaterial.AIR.parseMaterial(), false); + block.setType(XMaterial.AIR.get(), false); } } continue; } // Everything else may be removed - block.setType(XMaterial.AIR.parseMaterial(), false); + block.setType(XMaterial.AIR.get(), false); } } } diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/placedblocks/RemoveIllegalBlocksOnChunkload.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/placedblocks/RemoveIllegalBlocksOnChunkload.java index 0c5f65f23..331245b68 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/placedblocks/RemoveIllegalBlocksOnChunkload.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/placedblocks/RemoveIllegalBlocksOnChunkload.java @@ -32,19 +32,22 @@ public class RemoveIllegalBlocksOnChunkload extends AEFModule implements Listene private final boolean checkShouldPauseOnLowTPS; public RemoveIllegalBlocksOnChunkload() { - super("illegals.remove-placed-blocks.on-chunkload"); + super("illegals.remove-placed-blocks.on-chunkload", false); config.addComment(configPath + ".enable", "Remove illegally placed blocks on chunkload."); List defaults = Stream.of( - XMaterial.CHAIN_COMMAND_BLOCK, + XMaterial.PLAYER_HEAD, + XMaterial.PLAYER_WALL_HEAD, XMaterial.COMMAND_BLOCK, - XMaterial.COMMAND_BLOCK_MINECART, + XMaterial.CHAIN_COMMAND_BLOCK, XMaterial.REPEATING_COMMAND_BLOCK, XMaterial.BEDROCK, - XMaterial.BARRIER) - .map(XMaterial::parseMaterial) - .filter(Objects::nonNull) + XMaterial.BARRIER, + XMaterial.STRUCTURE_BLOCK, + XMaterial.STRUCTURE_VOID, + XMaterial.LIGHT) + .filter(XMaterial::isSupported) + .map(XMaterial::get) .map(Enum::name) - .sorted() .collect(Collectors.toList()); this.blocksToRemove = config.getList(configPath + ".blocks-to-remove", defaults) .stream() @@ -69,11 +72,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); @@ -99,26 +97,26 @@ private void onChunkLoad(ChunkLoadEvent event) { // If is skull, check if it is player head if (MaterialUtil.PLAYER_HEADS.contains(block.getType())) { if (MaterialUtil.isPlayerHead(block.getState())) { - block.setType(XMaterial.AIR.parseMaterial(), false); + block.setType(XMaterial.AIR.get(), false); } continue; } // If is bedrock, make sure not to delete naturally generated - if (block.getType() == XMaterial.BEDROCK.parseMaterial()) { + if (block.getType() == XMaterial.BEDROCK.get()) { if (y > minY + 4) { // offset to not delete natural bedrock floor if (inNether) { // offset to not delete bedrock ceiling if (y < config.nether_ceiling_max_y - 5) - block.setType(XMaterial.AIR.parseMaterial(), false); + block.setType(XMaterial.AIR.get(), false); } else { - block.setType(XMaterial.AIR.parseMaterial(), false); + block.setType(XMaterial.AIR.get(), false); } } continue; } - block.setType(XMaterial.AIR.parseMaterial(), false); + block.setType(XMaterial.AIR.get(), false); } } } diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/placedblocks/RemoveUnnaturalSpawners.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/placedblocks/RemoveUnnaturalSpawners.java index e055717ac..fa18f561b 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/placedblocks/RemoveUnnaturalSpawners.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/illegals/placedblocks/RemoveUnnaturalSpawners.java @@ -2,6 +2,7 @@ import com.cryptomorin.xseries.XEntityType; import com.cryptomorin.xseries.XMaterial; +import com.google.common.collect.Sets; import io.github.thatsmusic99.configurationmaster.api.ConfigSection; import me.xginko.aef.AnarchyExploitFixes; import me.xginko.aef.modules.AEFModule; @@ -16,7 +17,6 @@ import org.bukkit.event.Listener; import org.bukkit.event.world.ChunkLoadEvent; -import java.util.Arrays; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; @@ -31,21 +31,22 @@ public class RemoveUnnaturalSpawners extends AEFModule implements Listener { private final boolean checkShouldPauseOnLowTPS; public RemoveUnnaturalSpawners() { - super("illegals.remove-unnatural-spawners-on-chunkload"); + super("illegals.remove-unnatural-spawners-on-chunkload", false); this.checkShouldPauseOnLowTPS = config.getBoolean(configPath + ".pause-on-low-TPS", true); this.pauseTPS = config.getDouble(configPath + ".pause-TPS", 14.0); Map defaults = new HashMap<>(); - defaults.put("world", Arrays.asList( + defaults.put("world", Sets.newHashSet( XEntityType.SKELETON.get().name(), XEntityType.ZOMBIE.get().name(), XEntityType.SILVERFISH.get().name(), XEntityType.SPIDER.get().name(), - XEntityType.CAVE_SPIDER.get().name())); - defaults.put("world_nether", Arrays.asList( + XEntityType.CAVE_SPIDER.get().name(), + XEntityType.BREEZE_WIND_CHARGE.get().name())); + defaults.put("world_nether", Sets.newHashSet( XEntityType.BLAZE.get().name(), XEntityType.MAGMA_CUBE.get().name())); - defaults.put("world_the_end", Arrays.asList( + defaults.put("world_the_end", Sets.newHashSet( XEntityType.SKELETON.get().name(), XEntityType.SPIDER.get().name())); @@ -98,10 +99,10 @@ private void onChunkLoad(ChunkLoadEvent event) { for (int z = 0; z < 16; z++) { for (int y = minY; y < maxY; y++) { Block block = event.getChunk().getBlock(x, y, z); - if (block.getType() == XMaterial.SPAWNER.parseMaterial() + if (block.getType() == XMaterial.SPAWNER.get() && !naturalSpawners.get(event.getWorld().getName()).contains(((CreatureSpawner) block.getState()).getSpawnedType()) ) { - block.setType(XMaterial.AIR.parseMaterial(), false); + block.setType(XMaterial.AIR.get(), false); } } } diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/DisableCustomEntities.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/DisableCustomEntities.java new file mode 100755 index 000000000..bfd073315 --- /dev/null +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/DisableCustomEntities.java @@ -0,0 +1,71 @@ +package me.xginko.aef.modules.lagpreventions; + +import com.cryptomorin.xseries.XEntityType; +import me.xginko.aef.modules.AEFModule; +import org.bukkit.entity.EntityType; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.HandlerList; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntitySpawnEvent; + +import java.util.EnumSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class DisableCustomEntities extends AEFModule implements Listener { + + private final Set disabledEntities; + + public DisableCustomEntities() { + super("lag-preventions.disable-entity-spawns", false, + "Prevent certain entity types from spawning to combat lag.\n" + + "Fish types are enabled by default on newer versions since they\n" + + "can cause a ton of lag."); + + List defaults = Stream.of( + XEntityType.COD, + XEntityType.SALMON, + XEntityType.PUFFERFISH, + XEntityType.TROPICAL_FISH, + XEntityType.BAT, + XEntityType.PHANTOM) + .filter(XEntityType::isSupported) + .map(XEntityType::get) + .map(Enum::name) + .collect(Collectors.toList()); + + this.disabledEntities = config.getList(configPath + ".types", defaults) + .stream() + .map(configuredType -> { + try { + return EntityType.valueOf(configuredType); + } catch (IllegalArgumentException exception) { + notRecognized(EntityType.class, configuredType); + return null; + } + }) + .filter(Objects::nonNull) + .collect(Collectors.toCollection(() -> EnumSet.noneOf(EntityType.class))); + } + + @Override + public void enable() { + plugin.getServer().getPluginManager().registerEvents(this, plugin); + } + + @Override + public void disable() { + HandlerList.unregisterAll(this); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + private void onEntitySpawn(EntitySpawnEvent event) { + if (disabledEntities.contains(event.getEntityType())) { + event.setCancelled(true); + } + } +} diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/FloodingMachines.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/FloodingMachines.java index e04eacad1..f238bb783 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/FloodingMachines.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/FloodingMachines.java @@ -1,8 +1,8 @@ package me.xginko.aef.modules.lagpreventions; +import com.cryptomorin.xseries.XMaterial; import me.xginko.aef.modules.AEFModule; import me.xginko.aef.utils.BlockUtil; -import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; @@ -15,8 +15,8 @@ public class FloodingMachines extends AEFModule implements Listener { private final boolean remove; public FloodingMachines() { - super("lag-preventions.prevent-flooding-machines"); - config.addComment(configPath + ".enable", "Will prevent pistons from pushing waterlogged blocks."); + super("lag-preventions.prevent-flooding-machines", false, + "Will prevent pistons from pushing waterlogged blocks."); this.remove = config.getBoolean(configPath + ".delete-waterlogged-blocks", true); } @@ -27,7 +27,7 @@ public void enable() { @Override public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false) && BlockUtil.isWaterloggedAvailable(); + return configEnabled && BlockUtil.isWaterloggedAvailable(); } @Override @@ -39,7 +39,7 @@ public void disable() { private void onPistonExtend(BlockPistonExtendEvent event) { for (Block block : event.getBlocks()) { if (BlockUtil.isWaterlogged(block.getState())) { - if (remove) block.setType(Material.AIR); + if (remove) block.setType(XMaterial.AIR.get()); event.setCancelled(true); return; } diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/KeepStashLoaded.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/KeepStashLoaded.java index 3fe0f2a45..fbb7c200c 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/KeepStashLoaded.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/KeepStashLoaded.java @@ -18,6 +18,7 @@ import java.util.EnumSet; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; @@ -31,16 +32,16 @@ */ public class KeepStashLoaded extends AEFModule implements Runnable, Listener { - private final Map forceLoadedChunks; - private final Map worldsAndTheirRadiuses = new HashMap<>(); + private final Map worldsAndTheirRadiuses; private final Set storageTypes; private final long keepLoadedMillis, checkDelayTicks; private final int stashCount; private final boolean logIsEnabled, onlyTileEntities; + private Map forceLoadedChunks; + public KeepStashLoaded() { super("lag-preventions.keep-stash-chunks-loaded"); - this.forceLoadedChunks = new ConcurrentHashMap<>(); config.addComment(configPath + ".enable", "Idea by 3b3t admin kumori (Soft1k)\n"+ "Improves lag generated by large stash chunks constantly loading and\n"+ @@ -83,7 +84,9 @@ public KeepStashLoaded() { ConfigSection section = config.getConfigSection(configPath + ".worlds", defaults, "Radiuses around spawn in chunks (not blocks) that should not be checked.\n" + "Worlds not on this list are exempt from all checking."); - for (String world : section.getKeys(false)) { + List worlds = section.getKeys(false); + this.worldsAndTheirRadiuses = new HashMap<>(worlds.size()); + for (String world : worlds) { try { int radius = Integer.parseInt(section.getString(world)); this.worldsAndTheirRadiuses.put(world, NumberConversions.square(radius)); @@ -95,6 +98,7 @@ public KeepStashLoaded() { @Override public void enable() { + forceLoadedChunks = new ConcurrentHashMap<>(); plugin.getServer().getPluginManager().registerEvents(this, plugin); plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, this, 1L, 20L); } @@ -102,18 +106,22 @@ public void enable() { @Override public void disable() { HandlerList.unregisterAll(this); - for (Map.Entry entry : forceLoadedChunks.entrySet()) { - entry.getKey().getChunkAsync(false).thenAccept(chunk -> { - if (chunk != null) - ChunkUtil.setForceLoaded(chunk, false); - forceLoadedChunks.remove(entry.getKey()); - }); + if (forceLoadedChunks != null) { + for (Map.Entry entry : forceLoadedChunks.entrySet()) { + entry.getKey().getChunkAsync(false).thenAccept(chunk -> { + if (chunk != null) { + ChunkUtil.setForceLoaded(chunk, false); + } + }); + } + forceLoadedChunks.clear(); + forceLoadedChunks = null; } } @Override public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false) && ChunkUtil.canSetChunksForceLoaded(); + return configEnabled && ChunkUtil.canSetChunksForceLoaded(); } @Override diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/LeverSpam.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/LeverSpam.java index bd987b781..af700ddda 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/LeverSpam.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/LeverSpam.java @@ -4,10 +4,8 @@ import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; import me.xginko.aef.AnarchyExploitFixes; -import me.xginko.aef.config.Config; import me.xginko.aef.modules.AEFModule; import org.bukkit.Location; -import org.bukkit.block.Block; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; @@ -21,47 +19,52 @@ public class LeverSpam extends AEFModule implements Listener { - private final Cache leverLocationCooldowns; - private final Cache playersUsingLeversCooldowns; + private final long cacheTimeMillis; private final int leverUsageLimit; private final boolean shouldKickPlayer, sendActionBar; + private Cache leverLocationCooldowns; + private Cache playersUsingLeversCooldowns; + public LeverSpam() { - super("lag-preventions.prevent-lever-spam"); - Config config = AnarchyExploitFixes.config(); - config.addComment(configPath + ".enable", "Rate Limit levers to prevent a lag exploit."); + super("lag-preventions.prevent-lever-spam", false, + "Rate Limit levers to prevent a lag exploit."); this.sendActionBar = config.getBoolean(configPath + ".show-actionbar", true); this.shouldKickPlayer = config.getBoolean(configPath + ".kick-player", false); this.leverUsageLimit = config.getInt(configPath + ".max-lever-usages-per-time", 15); - final long cacheTimeMillis = config.getInt(configPath + ".lever-time-in-ticks", 40) * 50L; - this.leverLocationCooldowns = Caffeine.newBuilder().expireAfterWrite(Duration.ofMillis(cacheTimeMillis)).build(); - this.playersUsingLeversCooldowns = Caffeine.newBuilder().expireAfterWrite(Duration.ofMillis(cacheTimeMillis)).build(); + this.cacheTimeMillis = config.getInt(configPath + ".lever-time-in-ticks", 40) * 50L; } @Override public void enable() { + leverLocationCooldowns = Caffeine.newBuilder().expireAfterWrite(Duration.ofMillis(cacheTimeMillis)).build(); + playersUsingLeversCooldowns = Caffeine.newBuilder().expireAfterWrite(Duration.ofMillis(cacheTimeMillis)).build(); plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); + if (leverLocationCooldowns != null) { + leverLocationCooldowns.invalidateAll(); + leverLocationCooldowns.cleanUp(); + leverLocationCooldowns = null; + } + if (playersUsingLeversCooldowns != null) { + playersUsingLeversCooldowns.invalidateAll(); + playersUsingLeversCooldowns.cleanUp(); + playersUsingLeversCooldowns = null; + } } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) private void onInteract(PlayerInteractEvent event) { if (event.getAction() != Action.RIGHT_CLICK_BLOCK) return; - Block clicked = event.getClickedBlock(); - if (clicked.getType() != XMaterial.LEVER.parseMaterial()) return; + if (event.getClickedBlock().getType() != XMaterial.LEVER.get()) return; final Player player = event.getPlayer(); - final Location leverLoc = clicked.getLocation(); + final Location leverLoc = event.getClickedBlock().getLocation(); Integer activationCount = leverLocationCooldowns.getIfPresent(leverLoc); if (activationCount == null) activationCount = 0; diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/NoShulkerDrops.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/NoShulkerDrops.java index 0615eebf7..a3d5ba45a 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/NoShulkerDrops.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/NoShulkerDrops.java @@ -13,8 +13,7 @@ public class NoShulkerDrops extends AEFModule implements Listener { public NoShulkerDrops() { - super("lag-preventions.anti-shulker-drops"); - config.addComment(configPath + ".enable", + super("lag-preventions.anti-shulker-drops", false, "Disables shulkers dropping stored items when blown up.\n" + "This helps fix client- and serverside lag when done often and fast."); } @@ -24,11 +23,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/StashExplosions.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/StashExplosions.java index db897e6a1..8e4d14aaa 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/StashExplosions.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/StashExplosions.java @@ -1,5 +1,7 @@ package me.xginko.aef.modules.lagpreventions; +import com.cryptomorin.xseries.XEntityType; +import com.cryptomorin.xseries.XMaterial; import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; import me.xginko.aef.modules.AEFModule; @@ -24,26 +26,25 @@ public class StashExplosions extends AEFModule implements Listener { - private final Cache containerExplosions; private final Set storageTypes; + private final long waitTimeSeconds; private final int amountAtWhichToTakeAction; private final boolean logIsEnabled; + private Cache containerExplosions; + public StashExplosions() { - super("lag-preventions.disable-item-drops-during-large-stash-explosions"); - config.addComment(configPath + ".enable", + super("lag-preventions.disable-item-drops-during-large-stash-explosions", false, "Explodes containers without dropping items after a certain amount\n" + - "of exploded containers per chunk."); + "of exploded containers per chunk."); this.logIsEnabled = config.getBoolean(configPath + ".log", false); this.amountAtWhichToTakeAction = config.getInt(configPath + ".min-explosions-before-drops-disable", 6, "How many container blocks in a chunk can be blown up until items \n" + - "no longer drop from them."); - this.containerExplosions = Caffeine.newBuilder().expireAfterWrite(Duration.ofSeconds( - Math.max(1, config.getInt(configPath + ".time-in-seconds", 3, - "The time in seconds to wait after an explosion for another one to happen.\n" + + "no longer drop from them."); + this.waitTimeSeconds = Math.max(1, config.getInt(configPath + ".time-in-seconds", 3, + "The time in seconds to wait after an explosion for another one to happen.\n" + "If no explosion happens within x seconds after the first one, the count\n" + - "resets to 0.")) - )).build(); + "resets to 0.")); this.storageTypes = config.getList(configPath + ".container-types", MaterialUtil.INVENTORY_HOLDERS .stream() .filter(material -> !MaterialUtil.SHULKER_BOXES.contains(material)) @@ -63,18 +64,18 @@ public StashExplosions() { @Override public void enable() { + containerExplosions = Caffeine.newBuilder().expireAfterWrite(Duration.ofSeconds(waitTimeSeconds)).build(); plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); - containerExplosions.cleanUp(); + if (containerExplosions != null) { + containerExplosions.invalidateAll(); + containerExplosions.cleanUp(); + containerExplosions = null; + } } private void handleExplosion(Chunk chunk, List affectedBlocks) { @@ -90,7 +91,7 @@ private void handleExplosion(Chunk chunk, List affectedBlocks) { affectedBlocks.removeIf(block -> { if (storageTypes.contains(block.getType())) { - block.setType(Material.AIR); + block.setType(XMaterial.AIR.get()); return true; } return false; @@ -115,6 +116,9 @@ private void onBlockExplode(BlockExplodeEvent event) { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) private void onEntityExplode(EntityExplodeEvent event) { + if (event.getEntityType() == XEntityType.WIND_CHARGE.get()) return; + if (event.getEntityType() == XEntityType.BREEZE_WIND_CHARGE.get()) return; + handleExplosion(event.getEntity().getChunk(), event.blockList()); } } diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/agelimits/CustomAgeLimits.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/agelimits/CustomAgeLimits.java index e376e327d..53847a416 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/agelimits/CustomAgeLimits.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/agelimits/CustomAgeLimits.java @@ -3,7 +3,6 @@ import com.cryptomorin.xseries.XEntityType; import io.github.thatsmusic99.configurationmaster.api.ConfigSection; import me.xginko.aef.modules.AEFModule; -import me.xginko.aef.utils.ChunkUtil; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.entity.Entity; @@ -24,11 +23,11 @@ public class CustomAgeLimits extends AEFModule implements Runnable, Listener { private final Map entityLimits = new EnumMap<>(EntityType.class); private final long checkPeriod; private final boolean logIsEnabled; + private BukkitTask bukkitTask; public CustomAgeLimits() { - super("lag-preventions.entity-age-limits.custom-limits"); - config.addComment(configPath + ".enable", + super("lag-preventions.entity-age-limits.custom-limits", false, "Kill certain entities after a custom amount of ticks lived."); this.logIsEnabled = config.getBoolean(configPath + ".log-removals", false); this.checkPeriod = config.getInt(configPath + ".check-period-in-ticks", 1200, @@ -71,22 +70,20 @@ public void enable() { bukkitTask = plugin.getServer().getScheduler().runTaskTimer(plugin, this, checkPeriod, checkPeriod); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); - if (bukkitTask != null) bukkitTask.cancel(); + if (bukkitTask != null) { + bukkitTask.cancel(); + bukkitTask = null; + } } @Override public void run() { for (World world : plugin.getServer().getWorlds()) { for (Entity entity : world.getEntities()) { - if (entityLimits.containsKey(entity.getType()) && entity.getTicksLived() >= entityLimits.get(entity.getType())) { + if (entityLimits.containsKey(entity.getType()) && entity.getTicksLived() > entityLimits.get(entity.getType())) { entity.remove(); if (logIsEnabled) info("Removed " + entity.getType().name() + " due to old age."); } @@ -97,10 +94,9 @@ public void run() { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) private void onChunkLoad(ChunkLoadEvent event) { if (event.isNewChunk()) return; - if (ChunkUtil.isRetrievalUnsafe(event.getChunk())) return; for (Entity entity : event.getChunk().getEntities()) { - if (entityLimits.containsKey(entity.getType()) && entity.getTicksLived() >= entityLimits.get(entity.getType())) { + if (entityLimits.containsKey(entity.getType()) && entity.getTicksLived() > entityLimits.get(entity.getType())) { entity.remove(); if (logIsEnabled) info("Removed " + entity.getType().name() + " due to old age."); } diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/agelimits/ProjectileAgeLimit.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/agelimits/ProjectileAgeLimit.java index 03edab823..065b6fad4 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/agelimits/ProjectileAgeLimit.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/agelimits/ProjectileAgeLimit.java @@ -1,7 +1,6 @@ package me.xginko.aef.modules.lagpreventions.agelimits; import me.xginko.aef.modules.AEFModule; -import me.xginko.aef.utils.ChunkUtil; import me.xginko.aef.utils.EntityUtil; import org.bukkit.World; import org.bukkit.entity.Entity; @@ -16,11 +15,11 @@ public class ProjectileAgeLimit extends AEFModule implements Runnable, Listener private final long checkPeriod; private final int max_alive_time; + private BukkitTask bukkitTask; public ProjectileAgeLimit() { - super("lag-preventions.entity-age-limits.projectile-limit"); - config.addComment(configPath + ".enable", + super("lag-preventions.entity-age-limits.projectile-limit", false, "Patches any lag exploit that abuses spawning a ton of projectile entities\n" + "(ex. Snowball exploit)." + "Skips over the following entities: ENDER_PEARL, FISHING_HOOK, WITHER_SKULL\n" + @@ -38,15 +37,13 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { - if (bukkitTask != null) bukkitTask.cancel(); HandlerList.unregisterAll(this); + if (bukkitTask != null) { + bukkitTask.cancel(); + bukkitTask = null; + } } @Override @@ -73,7 +70,6 @@ public void run() { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) private void onChunkLoad(ChunkLoadEvent event) { if (event.isNewChunk()) return; - if (ChunkUtil.isRetrievalUnsafe(event.getChunk())) return; for (Entity entity : event.getChunk().getEntities()) { if (EntityUtil.isProjectile(entity)) { diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/BlockFormOrGrow.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/BlockFormOrGrow.java index 9347d3a20..d0425f662 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/BlockFormOrGrow.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/BlockFormOrGrow.java @@ -13,25 +13,25 @@ public BlockFormOrGrow() { super( "block-spread", false, + true, 1500.0, 6000, 10000, 10.0, - 120.0 - ); - config.addComment(configPath+".enable", + 120.0, "Limits blocks spreading or forming based on world conditions within a\n" + - "configurable radius and timeframe to help reduce lag by cancelling burst\n" + - "activity hotspots.\n" + - "\n" + - "Examples:\n" + - "\n" + - "- Snow forming due to a snow storm.\n" + - "- Ice forming in a snowy Biome like Taiga or Tundra.\n" + - "- Obsidian / Cobblestone forming due to contact with water.\n" + - "- Concrete forming due to mixing of concrete powder and water.\n" + - "- Mushrooms spreading.\n" + - "- Fire spreading."); + "configurable radius and timeframe to help reduce lag by cancelling burst\n" + + "activity hotspots.\n" + + "\n" + + "Examples:\n" + + "\n" + + "- Snow forming due to a snow storm.\n" + + "- Ice forming in a snowy Biome like Taiga or Tundra.\n" + + "- Obsidian / Cobblestone forming due to contact with water.\n" + + "- Concrete forming due to mixing of concrete powder and water.\n" + + "- Mushrooms spreading.\n" + + "- Fire spreading." + ); this.limit = config.getInt(configPath + ".block-form-event-limit", 800, "Maximum number of times a block can form or spread within the configured\n" + "timeframe before activity will be put on cooldown."); diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/BlockPhysics.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/BlockPhysics.java index 2fa898a08..554b983cb 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/BlockPhysics.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/BlockPhysics.java @@ -11,25 +11,25 @@ public class BlockPhysics extends RegionalActivityModule { public BlockPhysics() { super( "block-physics", + false, true, 1500.0, 18000, 20000, 10.0, - 120.0 - ); - this.config.addComment(configPath+".enable", + 120.0, "Limits block physics within a configurable radius and timeframe\n" + - "to help reduce lag by cancelling burst activity hotspots.\n" + - "\n" + - "Note:\n" + - "\n" + - "The event used for this check (BlockPhysicsEvent) is a high frequency event,\n" + - "it may be called thousands of times per a second on a busy server.\n" + - "Where possible the event may also only be called for the \"root\" block of\n" + - "physics updates in order to limit event spam.\n" + - "Physics updates that cause other blocks to change their state may not result\n" + - "in an event for each of those blocks (usually adjacent)."); + "to help reduce lag by cancelling burst activity hotspots.\n" + + "\n" + + "Note:\n" + + "\n" + + "The event used for this check (BlockPhysicsEvent) is a high frequency event,\n" + + "it may be called thousands of times per a second on a busy server.\n" + + "Where possible the event may also only be called for the \"root\" block of\n" + + "physics updates in order to limit event spam.\n" + + "Physics updates that cause other blocks to change their state may not result\n" + + "in an event for each of those blocks (usually adjacent)." + ); this.limit = config.getInt(configPath + ".block-physics-event-limit", 256000, "Maximum number of times a physics check can be performed within the configured\n" + "timeframe before they will be put on cooldown."); diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/EntitySpawns.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/EntitySpawns.java index ea98637a3..668801d18 100644 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/EntitySpawns.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/EntitySpawns.java @@ -11,14 +11,13 @@ public class EntitySpawns extends RegionalActivityModule { public EntitySpawns() { super( "creature-spawn", + false, true, 1500.0, 18000, 20000, 10.0, - 120.0 - ); - this.config.addComment(configPath + ".enable", + 120.0, "Limits entity spawning activity within a configurable radius and timeframe\n" + "to help reduce lag by cancelling high activity hotspots.\n" + "\n" + @@ -26,7 +25,8 @@ public EntitySpawns() { "\n" + "- A creature gets spawned naturally, by spawner or other reasons.\n" + "- An entity gets spawned naturally, by spawner or other reasons.\n" + - "This does not include tile entities."); + "This does not include tile entities." + ); this.limit = config.getInt(configPath + ".spawn-event-limit", 6000, "Maximum number of entity spawns within configured timeframe."); } diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/EntityTargeting.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/EntityTargeting.java index 7e15a79f1..048400026 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/EntityTargeting.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/EntityTargeting.java @@ -25,16 +25,16 @@ public class EntityTargeting extends RegionalActivityModule implements Listener public EntityTargeting() { super("entity-targeting", + false, true, 1500.0, 18000, 20000, 14.0, - 120.0 - ); - this.config.addComment(configPath+".enable", + 120.0, "Limits entities targeting other entities within a configurable radius\n" + - "and timeframe to help reduce lag by cancelling burst activity hotspots."); + "and timeframe to help reduce lag by cancelling burst activity hotspots." + ); this.limit = config.getInt(configPath + ".entity-target-event-limit", 8000, "Maximum number of times an entity can target another entity within the\n" + "configured timeframe before the area will be put on cooldown."); diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/Explosions.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/Explosions.java index d9a232bdd..504cac761 100644 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/Explosions.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/Explosions.java @@ -14,21 +14,21 @@ public Explosions() { super( "explosions", false, + true, 1500.0, 6000, 10000, 10.0, - 120.0 - ); - this.config.addComment(configPath + ".enable", + 120.0, "Limits explosions within a configurable radius and timeframe\n" + - "to help reduce lag by cancelling high activity hotspots.\n" + - "\n" + - "Examples:\n" + - "\n" + - "- A block exploding.\n" + - "- An entity exploding.\n" + - "- An entity making the decision to explode.\n"); + "to help reduce lag by cancelling high activity hotspots.\n" + + "\n" + + "Examples:\n" + + "\n" + + "- A block exploding.\n" + + "- An entity exploding.\n" + + "- An entity making the decision to explode.\n" + ); this.limit = config.getInt(configPath + ".explode-event-limit", 500, "Maximum number of explode events within the configured timeframe\n" + "before the region will be put on cooldown."); diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/LiquidSpread.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/LiquidSpread.java index 37d94c326..dee91eea8 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/LiquidSpread.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/LiquidSpread.java @@ -13,22 +13,22 @@ public class LiquidSpread extends RegionalActivityModule { public LiquidSpread() { super( "liquid-spread", + false, true, 1500.0, 18000, 20000, 12.0, - 100.0 - ); - this.config.addComment(configPath+".enable", + 100.0, "Limits liquid spreading within a configurable radius and timeframe\n" + - "to help reduce lag by cancelling high activity hotspots.\n" + - "\n" + - "Examples:\n" + - "\n" + - "- A lava block spreading by flowing.\n" + - "- A water block spreading by flowing.\n" + - "- (optional) A dragon egg is teleporting from one position to another."); + "to help reduce lag by cancelling high activity hotspots.\n" + + "\n" + + "Examples:\n" + + "\n" + + "- A lava block spreading by flowing.\n" + + "- A water block spreading by flowing.\n" + + "- (optional) A dragon egg is teleporting from one position to another." + ); this.limit = config.getInt(configPath + ".liquid-spread-event-limit", 2400, "Maximum number of times liquids are allowed to spread within the configured\n" + "timeframe before they will be put on cooldown."); @@ -37,7 +37,7 @@ public LiquidSpread() { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) private void onBlockFromTo(BlockFromToEvent event) { - if (ignoreDragonEgg && event.getBlock().getType() == XMaterial.DRAGON_EGG.parseMaterial()) return; + if (ignoreDragonEgg && event.getBlock().getType() == XMaterial.DRAGON_EGG.get()) return; if (shouldCancelActivity(event, event.getBlock().getLocation(), limit)) { event.setCancelled(true); diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/Noteblocks.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/Noteblocks.java index 22c976582..b764e27c8 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/Noteblocks.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/Noteblocks.java @@ -12,20 +12,20 @@ public Noteblocks() { super( "noteblocks", false, + true, 1500.0, 6000, 10000, 10.0, - 120.0 - ); - this.config.addComment(configPath+".enable", + 120.0, "Limits noteblocks being played within a configurable radius and timeframe\n" + - "to help reduce lag by cancelling high activity hotspots.\n" + - "\n" + - "Examples:\n" + - "\n" + - "- A noteblock is being played through player interaction.\n" + - "- A noteblock is being played through a redstone current.\n"); + "to help reduce lag by cancelling high activity hotspots.\n" + + "\n" + + "Examples:\n" + + "\n" + + "- A noteblock is being played through player interaction.\n" + + "- A noteblock is being played through a redstone current.\n" + ); this.limit = config.getInt(configPath + ".noteblock-play-limit", 2800, "Maximum number of times a noteblock can be played within the configured\n" + "timeframe before they will be put on cooldown."); diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/Pathfinding.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/Pathfinding.java index 5e96bb85e..6eb18843b 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/Pathfinding.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/Pathfinding.java @@ -25,16 +25,16 @@ public Pathfinding() { super( "entity-pathfinding", false, + true, 1500.0, 6000, 10000, 14.0, - 120.0 - ); - this.config.addComment(configPath+".enable", + 120.0, "Limits entities deciding to pathfind to a specific location\n" + "within a configurable radius and timeframe to help reduce lag\n" + - "by cancelling burst activity hotspots."); + "by cancelling burst activity hotspots." + ); this.limit = config.getInt(configPath + ".entity-pathfind-event-limit", 4000, "Maximum number of times an entity can decide to start moving\n" + "towards a location within the configured timeframe before the\n" + diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/Pistons.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/Pistons.java index 7d6277102..ac749ed79 100644 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/Pistons.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/Pistons.java @@ -13,20 +13,20 @@ public Pistons() { super( "pistons", false, + true, 1500.0, 6000, 10000, 10.0, - 120.0 - ); - this.config.addComment(configPath+".enable", + 120.0, "Limits piston movement within a configurable radius and timeframe\n" + - "to help reduce lag by cancelling high activity hotspots.\n" + - "\n" + - "Examples:\n" + - "\n" + - "- A piston extends.\n" + - "- A piston retracts.\n"); + "to help reduce lag by cancelling high activity hotspots.\n" + + "\n" + + "Examples:\n" + + "\n" + + "- A piston extends.\n" + + "- A piston retracts.\n" + ); this.limit = config.getInt(configPath + ".piston-movement-limit", 1000, "Maximum number of piston extend and/or retracts within the\n" + "configured timeframe."); diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/Redstone.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/Redstone.java index e694414ec..1b820c340 100644 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/Redstone.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/Redstone.java @@ -11,22 +11,22 @@ public class Redstone extends RegionalActivityModule { public Redstone() { super( "redstone", + false, true, 1500.0, 18000, 20000, 10.0, - 120.0 - ); - this.config.addComment(configPath+".enable", + 120.0, "Limits redstone activity within a configurable radius and timeframe\n" + - "to help reduce lag by cancelling high activity hotspots.\n" + - "\n" + - "Examples:\n" + - "\n" + - "- A redstone current changes.\n" + - "- A redstone block gets powered on.\n" + - "- A redstone block gets powered off.\n"); + "to help reduce lag by cancelling high activity hotspots.\n" + + "\n" + + "Examples:\n" + + "\n" + + "- A redstone current changes.\n" + + "- A redstone block gets powered on.\n" + + "- A redstone block gets powered off.\n" + ); this.limit = config.getInt(configPath + ".redstone-event-limit", 6000, "Maximum number of redstone events within configured timeframe."); } diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/RegionalActivityModule.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/RegionalActivityModule.java index 0667e6b91..51f73e960 100644 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/RegionalActivityModule.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/RegionalActivityModule.java @@ -22,16 +22,25 @@ */ public abstract class RegionalActivityModule extends AEFModule implements Listener { - protected final Cache regionDataCache; - protected final long pauseTimeMillis; + protected final long cacheTimeMillis, pauseTimeMillis; protected final double checkRadius, pauseTPS, pauseMSPT; protected final boolean logIsEnabled; + protected Cache regionDataCache; + public RegionalActivityModule( - String subConfigPath, boolean deflogEnabled, double defCheckRadius, + String subConfigPath, boolean defEnabled, boolean deflogEnabled, double defCheckRadius, int defPauseMillis, int defCacheMillis, double defPauseTPS, double defPauseMSPT ) { - super("lag-preventions.regional-activity."+subConfigPath); + this(subConfigPath, defEnabled, deflogEnabled, defCheckRadius, + defPauseMillis, defCacheMillis, defPauseTPS, defPauseMSPT, null); + } + + public RegionalActivityModule( + String subConfigPath, boolean defEnabled, boolean deflogEnabled, double defCheckRadius, + int defPauseMillis, int defCacheMillis, double defPauseTPS, double defPauseMSPT, String comment + ) { + super("lag-preventions.regional-activity."+subConfigPath, defEnabled, comment); String configPath = "lag-preventions.regional-activity."+subConfigPath; this.logIsEnabled = config.getBoolean(configPath + ".log", deflogEnabled); this.checkRadius = config.getDouble(configPath + ".check-radius-blocks", defCheckRadius, @@ -39,6 +48,10 @@ public RegionalActivityModule( this.pauseTimeMillis = config.getInt(configPath + ".pause-time-millis", defPauseMillis, "The time in milliseconds all related activity will be blocked if it exceeded\n" + "the configured limit."); + this.cacheTimeMillis = Math.max(100L, config.getInt(configPath + ".data-keep-time-millis", defCacheMillis, + "The time in milliseconds before a region and its data will be expired\n" + + "if no activity has been detected.\n" + + "For proper functionality, needs to be at least as long as your pause time.")); this.regionDataCache = Caffeine.newBuilder().expireAfterWrite(Duration.ofMillis( config.getInt(configPath + ".data-keep-time-millis", defCacheMillis, "The time in milliseconds before a region and its data will be expired\n" + @@ -50,20 +63,20 @@ public RegionalActivityModule( "The MSPT at which to cancel the physics entirely."); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void enable() { + regionDataCache = Caffeine.newBuilder().expireAfterWrite(Duration.ofMillis(cacheTimeMillis)).build(); plugin.getServer().getPluginManager().registerEvents(this, plugin); } @Override public void disable() { HandlerList.unregisterAll(this); - regionDataCache.invalidateAll(); + if (regionDataCache != null) { + regionDataCache.invalidateAll(); + regionDataCache.cleanUp(); + regionDataCache = null; + } } @SuppressWarnings("DataFlowIssue") diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/SculkActivity.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/SculkActivity.java index 0d4896f80..8f789a005 100644 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/SculkActivity.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/lagpreventions/regionalactivity/SculkActivity.java @@ -21,21 +21,21 @@ public class SculkActivity extends RegionalActivityModule { public SculkActivity() { super( "sculk-sensor", + false, true, 1500.0, 18000, 20000, 10.0, - 120.0 - ); - this.config.addComment(configPath+".enable", + 120.0, "Limits sculk activity within a configurable radius and timeframe\n" + - "to help reduce lag by cancelling high activity hotspots.\n" + - "\n" + - "Examples:\n" + - "\n" + - "- A redstone current changes for a sculk sensor.\n" + - "- A physics check is being performed for a sculk sensor."); + "to help reduce lag by cancelling high activity hotspots.\n" + + "\n" + + "Examples:\n" + + "\n" + + "- A redstone current changes for a sculk sensor.\n" + + "- A physics check is being performed for a sculk sensor." + ); this.limit = config.getInt(configPath + ".sculk-event-limit", 800, "Maximum number of sculk events within configured timeframe."); List defaults = Stream.of( @@ -43,7 +43,7 @@ public SculkActivity() { XMaterial.SCULK_SHRIEKER, XMaterial.CALIBRATED_SCULK_SENSOR) .filter(XMaterial::isSupported) - .map(XMaterial::parseMaterial) + .map(XMaterial::get) .map(Enum::name) .collect(Collectors.toList()); this.sculkBlocks = config.getList(configPath + ".sculk-blocks", defaults) diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/misc/FirstJoinMessages.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/misc/FirstJoinMessages.java index c0b4a1645..eae4f4d7c 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/misc/FirstJoinMessages.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/misc/FirstJoinMessages.java @@ -19,7 +19,7 @@ public class FirstJoinMessages extends AEFModule implements Listener { private final boolean logFirstJoin; public FirstJoinMessages() { - super("misc.join-leave-messages.first-join-messages"); + super("misc.join-leave-messages.first-join-messages", false); this.totalPlayers = new AtomicInteger(0); this.config.addComment(configPath + ".enable", "Configure message in lang folder.\n" + @@ -37,11 +37,6 @@ public void enable() { .thenRun(() -> plugin.getServer().getPluginManager().registerEvents(this, plugin)); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/misc/JoinLeaveMessages.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/misc/JoinLeaveMessages.java index 3a8a0c21d..7e0824f6c 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/misc/JoinLeaveMessages.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/misc/JoinLeaveMessages.java @@ -16,7 +16,7 @@ public class JoinLeaveMessages extends AEFModule implements Listener { private final boolean showInConsole, firstJoinEnabled; public JoinLeaveMessages() { - super("misc.join-leave-messages"); + super("misc.join-leave-messages", false); config.addComment(configPath + ".enable", "If you want to hide yourself or someone else when logging\n" + "into the game, use these permissions:\n" + @@ -30,11 +30,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", true); - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/misc/MaskKickMessages.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/misc/MaskKickMessages.java index 93262194e..8446e4777 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/misc/MaskKickMessages.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/misc/MaskKickMessages.java @@ -11,7 +11,7 @@ public class MaskKickMessages extends AEFModule implements Listener { public MaskKickMessages() { - super("misc.kicks.mask-kick-messages"); + super("misc.kicks.mask-kick-messages", false); config.addComment(configPath, "Configure mask message in lang folder."); } @@ -20,11 +20,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath, false); - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/misc/PreventMessageKick.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/misc/PreventMessageKick.java index 24aa41e3e..2b2ce91ad 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/misc/PreventMessageKick.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/misc/PreventMessageKick.java @@ -17,7 +17,7 @@ public class PreventMessageKick extends AEFModule implements Listener { private final Set kickMessagesToListenTo; public PreventMessageKick() { - super("misc.kicks.prevent-message-kick"); + super("misc.kicks.prevent-message-kick", false); config.addComment(configPath + ".enable", "Cancels the kick for specific kick messages."); this.kickMessagesToListenTo = config.getList(configPath + ".kick-messages-to-listen-to", Arrays.asList("Kicked for spamming", "Stop spamming!")) @@ -31,11 +31,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/packets/BeehiveCoordinates.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/packets/BeehiveCoordinates.java index 2f8cfd8be..526f336dd 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/packets/BeehiveCoordinates.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/packets/BeehiveCoordinates.java @@ -16,8 +16,7 @@ public class BeehiveCoordinates extends PacketModule { private final String[] entityDataTagsToRemove; public BeehiveCoordinates() { - super("patches.remove-beehive-coordinates", PacketListenerPriority.HIGHEST); - config.addComment(configPath + ".enable", + super("patches.remove-beehive-coordinates", true, PacketListenerPriority.HIGHEST, "Patches an exploit that allows players to obtain another player's\n" + "coordinates by trading them for Beehives or Beenests.\n" + "If the traded item contains any bees, the stored bee's NBT data can\n" + @@ -35,11 +34,6 @@ public BeehiveCoordinates() { .toArray(new String[0]); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", true); - } - @Override public void onPacketSend(PacketSendEvent event) { if (event.isCancelled()) return; diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/packets/BigMessages.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/packets/BigMessages.java index 016761e5a..0a6bd14a5 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/packets/BigMessages.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/packets/BigMessages.java @@ -13,19 +13,13 @@ public class BigMessages extends PacketModule { private final boolean log, kick; public BigMessages() { - super("patches.message-char-limit", PacketListenerPriority.HIGHEST); - config.addComment(configPath + ".enable", + super("patches.message-char-limit", true, PacketListenerPriority.HIGHEST, "Sets a character limit for command and message packets to prevent a lag exploit."); this.charLimit = config.getInt(configPath + ".max-characters", 256); this.log = config.getBoolean(configPath + ".log", false); this.kick = config.getBoolean(configPath + ".kick-player", false); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", true); - } - @Override public void onPacketReceive(PacketReceiveEvent event) { if (event.isCancelled()) return; diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/packets/CraftingRecipeLag.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/packets/CraftingRecipeLag.java index ef1e3c283..ac1cf58ce 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/packets/CraftingRecipeLag.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/packets/CraftingRecipeLag.java @@ -1,5 +1,6 @@ package me.xginko.aef.modules.packets; +import com.github.retrooper.packetevents.PacketEvents; import com.github.retrooper.packetevents.event.PacketListenerPriority; import com.github.retrooper.packetevents.event.PacketReceiveEvent; import com.github.retrooper.packetevents.protocol.packettype.PacketType; @@ -10,27 +11,37 @@ public class CraftingRecipeLag extends PacketModule { - private final ExpiringSet recipeCooldowns; + private final long cooldownMillis; private final boolean log, kick; + private ExpiringSet cooldowns; + public CraftingRecipeLag() { - super("patches.prevent-crafting-recipe-lag-exploit", PacketListenerPriority.HIGHEST); - shouldEnable(); - config.addComment(configPath + ".enable", + super("patches.prevent-crafting-recipe-lag-exploit", true, PacketListenerPriority.HIGHEST, "Prevent lag or crash caused by flooding the server with\n" + "crafting recipe book requests. This can even be done by hand on\n" + "servers with low specs. Only affects versions < 1.16"); - this.recipeCooldowns = new ExpiringSet<>(Duration.ofMillis(Math.max(1, - config.getInt(configPath + ".crafting-recipe-delay-in-ticks", 5, + this.cooldownMillis = Math.max(1, config.getInt(configPath + ".crafting-recipe-delay-in-ticks", 5, "How many ticks a player needs to wait to be able to use\n" + - "the crafting recipe book again")) * 50L)); + "the crafting recipe book again")) * 50L; this.log = config.getBoolean(configPath + ".log", false); this.kick = config.getBoolean(configPath + ".kick-player", false); } @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", true); + public void enable() { + cooldowns = new ExpiringSet<>(Duration.ofMillis(cooldownMillis)); + PacketEvents.getAPI().getEventManager().registerListener(asAbstract); + } + + @Override + public void disable() { + PacketEvents.getAPI().getEventManager().unregisterListener(asAbstract); + if (cooldowns != null) { + cooldowns.clear(); + cooldowns.cleanUp(); + cooldowns = null; + } } @Override @@ -38,11 +49,11 @@ public void onPacketReceive(PacketReceiveEvent event) { if (event.isCancelled()) return; if (event.getPacketType() != PacketType.Play.Client.CRAFT_RECIPE_REQUEST) return; - if (recipeCooldowns.contains(event.getUser().getUUID())) { + if (cooldowns.contains(event.getUser().getUUID())) { event.setCancelled(true); onCancel(log, kick, event.getUser()); } else { - recipeCooldowns.add(event.getUser().getUUID()); + cooldowns.add(event.getUser().getUUID()); } } } diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/packets/InventoryLag.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/packets/InventoryLag.java index a25bc63b5..fcce29075 100644 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/packets/InventoryLag.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/packets/InventoryLag.java @@ -34,46 +34,45 @@ public class InventoryLag extends PacketModule implements Listener { - private final Cache playerDataCache; private final Set measuredPacketTypes; - private final long rateLimitBytes, lockoutBytes, lockoutMillis; + private final long playerCacheMillis, rateLimitBytes, lockoutBytes, lockoutMillis; private final int screenOpenLimit, screenOpenDelay; private final boolean closeInventory, log; + private Cache playerDataCache; + public InventoryLag() { - super("patches.inventory-lag", PacketListenerPriority.HIGHEST); - config.addComment(configPath + ".enable", + super("patches.inventory-lag", false, PacketListenerPriority.HIGHEST, "Checks if a player is requesting unusual amounts of traffic from the server\n" + - "using ItemStacks.\n" + - "If a player exceeds the limit, they will be put on a cooldown, during which\n" + - "they will be very limited in terms of ItemStack or Inventory interactions."); + "using ItemStacks.\n" + + "If a player exceeds the limit, they will be put on a cooldown, during which\n" + + "they will be very limited in terms of ItemStack or Inventory interactions."); this.log = config.getBoolean(configPath + ".log", false, "For debug purposes. Don't leave enabled for too long as it is very spammy."); this.closeInventory = config.getBoolean(configPath + ".close-open-inventory", true, "Whether to immediately close any open inventory of the player on limit exceed\n" + - "Note: Closing has to be scheduled so it will take a bit if the server is heavily\n" + - "lagging."); - this.playerDataCache = Caffeine.newBuilder().expireAfterWrite(Duration.ofMillis(Math.max(1L, - config.getLong(configPath + ".byte-data-keep-time-millis", 30_000, - "The time in millis in which to check if the player exceeded the limit.\n" + - "Needs to be at least as long as your lockout duration millis.")))).build(); + "Note: Closing has to be scheduled so it will take a bit if the server is heavily\n" + + "lagging."); + this.playerCacheMillis = Math.max(1L, config.getLong(configPath + ".byte-data-keep-time-millis", 30_000, + "The time in millis in which to check if the player exceeded the limit.\n" + + "Needs to be at least as long as your lockout duration millis.")); this.rateLimitBytes = config.getLong(configPath + ".rate-limit.bytesize-limit", 8_000_000, "The limit in bytes the server has sent the server in the form of ItemStacks,\n" + - "before the player will be put on a rate-limit.\n" + - "Should always be lower than your lockout bytesize limit."); + "before the player will be put on a rate-limit.\n" + + "Should always be lower than your lockout bytesize limit."); this.screenOpenDelay = config.getInt(configPath + ".rate-limit.timeframe-millis", 2500, "The time in millis in which a player is allowed to open x amounts of windows\n" + - "but not more."); + "but not more."); this.screenOpenLimit = config.getInt(configPath + ".rate-limit.max-window-opens-per-timeframe", 2, "The amount of windows that can be opened during the timeframe-millis."); this.lockoutBytes = config.getLong(configPath + ".lockout.bytesize-limit", 24_000_000, "The upper limit in bytes a player is allowed to request from the server\n" + - "within the configured timeframe before he will be put on cooldown.\n" + - "During the cooldown, he will not be able to open any inventory screens\n" + - "or interact with items."); + "within the configured timeframe before he will be put on cooldown.\n" + + "During the cooldown, he will not be able to open any inventory screens\n" + + "or interact with items."); this.lockoutMillis = config.getLong(configPath + ".lockout.duration-millis", 15_000, "The time in milliseconds the player will have to wait before\n" + - "being able to open an inventory again after he exceeded the limit."); + "being able to open an inventory again after he exceeded the limit."); this.measuredPacketTypes = config.getList(configPath + ".check-packets", Arrays.asList("SET_SLOT", "WINDOW_ITEMS")) .stream() .map(configuredPacketType -> { @@ -88,13 +87,9 @@ public InventoryLag() { .collect(Collectors.toCollection(HashSet::new)); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void enable() { + playerDataCache = Caffeine.newBuilder().expireAfterWrite(Duration.ofMillis(playerCacheMillis)).build(); plugin.getServer().getPluginManager().registerEvents(this, plugin); PacketEvents.getAPI().getEventManager().registerListener(asAbstract); } @@ -103,6 +98,11 @@ public void enable() { public void disable() { HandlerList.unregisterAll(this); PacketEvents.getAPI().getEventManager().unregisterListener(asAbstract); + if (playerDataCache != null) { + playerDataCache.invalidateAll(); + playerDataCache.cleanUp(); + playerDataCache = null; + } } @Override diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/packets/LecternCrash.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/packets/LecternCrash.java index 5cc6d6b00..a5d317ec2 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/packets/LecternCrash.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/packets/LecternCrash.java @@ -13,18 +13,17 @@ public class LecternCrash extends PacketModule { private final boolean log, kick; public LecternCrash() { - super("patches.lectern-crash-patch", PacketListenerPriority.HIGHEST); - try { this.LECTERN = InventoryType.valueOf("LECTERN"); } catch (IllegalArgumentException ignored) {} - config.addComment(configPath + ".enable", + super("patches.lectern-crash-patch", false, PacketListenerPriority.HIGHEST, "Patches an instant server crash exploit that involves sending\n" + "an invalid Window Click packet while taking a book out of a Lectern."); + try { this.LECTERN = InventoryType.valueOf("LECTERN"); } catch (IllegalArgumentException ignored) {} this.log = config.getBoolean(configPath + ".log", false); this.kick = config.getBoolean(configPath + ".kick-player", false); } @Override public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", true) && LECTERN != null; + return configEnabled && LECTERN != null; } @Override diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/packets/MapCursorLag.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/packets/MapCursorLag.java index 590dce777..59533a1e1 100644 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/packets/MapCursorLag.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/packets/MapCursorLag.java @@ -19,8 +19,7 @@ public class MapCursorLag extends PacketModule implements Listener { public MapCursorLag() { - super("patches.map-cursor-lag-patch", PacketListenerPriority.HIGHEST); - config.addComment( configPath + ".enable", + super("patches.map-cursor-lag-patch", true, PacketListenerPriority.HIGHEST, "Patches the famous stacked map cursor lag that causes both \n" + "client and server crashes."); } @@ -32,11 +31,6 @@ public void enable() { PacketEvents.getAPI().getEventManager().registerListener(asAbstract); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", true); - } - @Override public void disable() { HandlerList.unregisterAll(this); @@ -68,9 +62,8 @@ private void onChunkLoad(ChunkLoadEvent event) { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) private void onInteract(PlayerInteractEntityEvent event) { - Entity rightClicked = event.getRightClicked(); - if (EntityUtil.ITEM_FRAMES.contains(rightClicked.getType())) { - EntityUtil.disableMapPositionCursor((ItemFrame) rightClicked); + if (EntityUtil.ITEM_FRAMES.contains(event.getRightClicked().getType())) { + EntityUtil.disableMapPositionCursor((ItemFrame) event.getRightClicked()); } } } diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/packets/NoComExploit.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/packets/NoComExploit.java index 6ec63286c..9c96e4fcb 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/packets/NoComExploit.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/packets/NoComExploit.java @@ -20,9 +20,7 @@ public class NoComExploit extends PacketModule { private final boolean log, kick; public NoComExploit() { - super("patches.prevent-nocom-coordinate-exploit", PacketListenerPriority.HIGHEST); - shouldEnable(); - config.addComment(configPath + ".enable", + super("patches.prevent-nocom-coordinate-exploit", true, PacketListenerPriority.HIGHEST, "Prevents the abusable mechanic used by the infamous \"No Comment\"\n" + "coordinate exploit, where the server responds to requests that are\n" + "far outside of the sending player's reach, therefore either crashing\n" + @@ -35,11 +33,6 @@ public NoComExploit() { this.kick = config.getBoolean(configPath + ".kick-player", false); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", true); - } - @Override public void onPacketReceive(PacketReceiveEvent event) { if (event.isCancelled()) return; diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/packets/PacketModule.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/packets/PacketModule.java index cf4275353..d9cf7d734 100644 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/packets/PacketModule.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/packets/PacketModule.java @@ -9,16 +9,19 @@ import me.xginko.aef.utils.models.ExpiringSet; import java.time.Duration; -import java.util.Set; import java.util.UUID; public abstract class PacketModule extends AEFModule implements PacketListener { protected final PacketListenerAbstract asAbstract; - private final Set loggingCooldown; + protected final ExpiringSet loggingCooldown; - public PacketModule(String configPath, PacketListenerPriority priority) { - super(configPath); + public PacketModule(String configPath, boolean enabledByDefault, PacketListenerPriority priority) { + this(configPath, enabledByDefault, priority, null); + } + + public PacketModule(String configPath, boolean enabledByDefault, PacketListenerPriority priority, String comment) { + super(configPath, enabledByDefault, comment); this.asAbstract = asAbstract(priority); // Otherwise will log for each received packet, which would be a LOT this.loggingCooldown = new ExpiringSet<>(Duration.ofMinutes(5)); @@ -35,11 +38,9 @@ public void disable() { } public void onCancel(boolean log, boolean kick, User sender) { - if (log) { - if (!loggingCooldown.contains(sender.getUUID())) { - info(sender.getName() + " failed to trigger exploit."); - loggingCooldown.add(sender.getUUID()); - } + if (log && !loggingCooldown.contains(sender.getUUID())) { + info(sender.getName() + " failed to trigger exploit."); + loggingCooldown.add(sender.getUUID()); } if (kick) { diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/packets/PurpurBeehiveCrash.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/packets/PurpurBeehiveCrash.java index bb1394e88..22f97b3d1 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/packets/PurpurBeehiveCrash.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/packets/PurpurBeehiveCrash.java @@ -23,7 +23,7 @@ public class PurpurBeehiveCrash extends PacketModule { private final boolean log, kick; public PurpurBeehiveCrash() { - super("patches.beehive-crash-patch", PacketListenerPriority.HIGHEST); + super("patches.beehive-crash-patch", PlatformUtil.isPurpur(), PacketListenerPriority.HIGHEST); config.addComment(configPath + ".enable", "Patches a server crash exploit exclusive to Purpur servers.\n" + "This exploit works due to PurpurClient having a feature that\n" + @@ -38,11 +38,6 @@ public PurpurBeehiveCrash() { this.kick = config.getBoolean(configPath + ".kick-player", false); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", PlatformUtil.isPurpur()); - } - @Override @SuppressWarnings("UnstableApiUsage") public void onPacketReceive(PacketReceiveEvent event) { diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/packets/SequenceCrash.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/packets/SequenceCrash.java index 0a4556b97..d5251f28f 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/packets/SequenceCrash.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/packets/SequenceCrash.java @@ -13,8 +13,7 @@ public class SequenceCrash extends PacketModule { private final boolean log, kick; public SequenceCrash() { - super("patches.sequence-crash-patch", PacketListenerPriority.HIGHEST); - config.addComment(configPath + ".enable", + super("patches.sequence-crash-patch", PlatformUtil.getMinecraftVersion() >= 19, PacketListenerPriority.HIGHEST, "Patches a variety of lag/crash exploits that involves sending packets \n" + "with invalid sequences."); this.log = config.getBoolean(configPath + ".log", false); @@ -23,7 +22,7 @@ public SequenceCrash() { @Override public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", true) && PlatformUtil.getMinecraftVersion() >= 19; + return configEnabled && PlatformUtil.getMinecraftVersion() >= 19; } @Override diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/packets/SignLag.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/packets/SignLag.java index dcbb510b3..8a4d9b4bb 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/packets/SignLag.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/packets/SignLag.java @@ -1,5 +1,6 @@ package me.xginko.aef.modules.packets; +import com.github.retrooper.packetevents.PacketEvents; import com.github.retrooper.packetevents.event.PacketListenerPriority; import com.github.retrooper.packetevents.event.PacketReceiveEvent; import com.github.retrooper.packetevents.protocol.packettype.PacketType; @@ -11,19 +12,19 @@ public class SignLag extends PacketModule { - private final ExpiringSet cooldowns; + private final long cooldownMillis; private final int line_char_limit, total_char_limit; private final boolean log, kick; + private ExpiringSet cooldowns; + public SignLag() { - super("patches.sign-lag", PacketListenerPriority.HIGHEST); - config.addComment(configPath + ".enable", + super("patches.sign-lag", true, PacketListenerPriority.HIGHEST, "Patches a lag exploit that involves sending specific oversized \n" + "sign edit packets."); - this.cooldowns = new ExpiringSet<>(Duration.ofMillis(Math.max(1, - config.getInt(configPath + ".packet-delay-in-ticks", 10, - "How many ticks a player needs to wait to be able to send\n" + - "another sign update packet (renaming or writing).")) * 50L)); + this.cooldownMillis = Math.max(1, config.getInt(configPath + ".packet-delay-in-ticks", 10, + "How many ticks a player needs to wait to be able to send\n" + + "another sign update packet (renaming or writing).")) * 50L; this.line_char_limit = config.getInt(configPath + ".line-character-limit", 80, "Vanilla limit is 384 characters per line, which is too much."); this.total_char_limit = config.getInt(configPath + ".total-char-limit", 384, @@ -33,8 +34,19 @@ public SignLag() { } @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", true); + public void enable() { + cooldowns = new ExpiringSet<>(Duration.ofMillis(cooldownMillis)); + PacketEvents.getAPI().getEventManager().registerListener(asAbstract); + } + + @Override + public void disable() { + PacketEvents.getAPI().getEventManager().unregisterListener(asAbstract); + if (cooldowns != null) { + cooldowns.clear(); + cooldowns.cleanUp(); + cooldowns = null; + } } @Override diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/packets/TabCompleteCrash.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/packets/TabCompleteCrash.java index e6227dd26..bb2fbab92 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/packets/TabCompleteCrash.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/packets/TabCompleteCrash.java @@ -6,24 +6,21 @@ import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientTabComplete; import org.bukkit.permissions.ServerOperator; +import java.util.Arrays; + public class TabCompleteCrash extends PacketModule { - private static final String[] ABUSABLE_SEQUENCES = { "@", "[", "nbt", "=", "{", "}", "]" }; + private final String[] sequences; private final boolean log, kick; public TabCompleteCrash() { - super("patches.tab-complete-crash-patch", PacketListenerPriority.HIGHEST); - config.addComment(configPath + ".enable", + super("patches.tab-complete-crash-patch", true, PacketListenerPriority.HIGHEST, "Patches two lag exploits and an instant server shutdown exploit that\n" + "works by sending a malicious TabComplete packet that triggers a\n" + "StackOverflowError inside the TagParser class."); this.log = config.getBoolean(configPath + ".log", false); this.kick = config.getBoolean(configPath + ".kick-player", false); - } - - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", true); + this.sequences = config.getList("characters", Arrays.asList("@", "[", "nbt", "=", "{", "}", "]")).toArray(new String[0]); } @Override @@ -51,8 +48,8 @@ public void onPacketReceive(PacketReceiveEvent event) { if (event.getPlayer() == null || ((ServerOperator) event.getPlayer()).isOp()) return; - for (String sequence : ABUSABLE_SEQUENCES) { - if (text.indexOf(sequence) != -1) { + for (String sequence : sequences) { + if (text.contains(sequence)) { event.setCancelled(true); onCancel(log, kick, event.getUser()); return; diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/packets/WindowClickCrash.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/packets/WindowClickCrash.java index 90b2429b2..80bd48340 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/packets/WindowClickCrash.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/packets/WindowClickCrash.java @@ -11,7 +11,7 @@ public class WindowClickCrash extends PacketModule { private final boolean log, kick; public WindowClickCrash() { - super("patches.window-click-crash-patch", PacketListenerPriority.HIGHEST); + super("patches.window-click-crash-patch", true, PacketListenerPriority.HIGHEST); config.addComment(configPath + ".enable", "Patches a variety of different lag and crash methods that work\n" + "by sending invalid Window Click packets, causing the server to\n" + @@ -20,15 +20,11 @@ public WindowClickCrash() { this.kick = config.getBoolean(configPath + ".kick-player", false); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", true); - } - @Override public void onPacketReceive(PacketReceiveEvent event) { if (event.isCancelled()) return; if (event.getPacketType() != PacketType.Play.Client.CLICK_WINDOW) return; + WrapperPlayClientClickWindow packet = new WrapperPlayClientClickWindow(event); int button = packet.getButton(); diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/patches/GodMode.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/patches/GodMode.java index 6984ada84..9b6cbc9b1 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/patches/GodMode.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/patches/GodMode.java @@ -15,8 +15,7 @@ public class GodMode extends AEFModule implements Listener { public GodMode() { - super("patches.experimental-godmode-patch"); - config.addComment(configPath, + super("patches.experimental-godmode-patch", false, "Removes entities or players if they are invalid, dead or not located\n" + "within a ticking chunk. Not sure if this works."); } @@ -26,11 +25,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath, false); - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/patches/ItemDataBan.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/patches/ItemDataBan.java index d132c5846..a6f07c9be 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/patches/ItemDataBan.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/patches/ItemDataBan.java @@ -25,13 +25,14 @@ public class ItemDataBan extends AEFModule implements Listener { - private final Cache cachedItemSizes, cachedInventorySizes; + private final long itemSizeCacheMillis, inventorySizeCacheMillis; private final int maxBookSize, maxItemSize, maxInventorySize, maxAuthorChars, maxTitleChars, maxPages; private final boolean useUTF16, kickOnBigBook; + private Cache cachedItemSizes, cachedInventorySizes; + public ItemDataBan() { - super("patches.anti-item-ban"); - this.config.addComment(configPath+".enable", + super("patches.anti-item-ban", false, "More commonly known as book-ban: \n" + "Prevents player's getting banned from items with big nbt/compound data. \n" + "This check applies to all item data, not just books."); @@ -49,33 +50,34 @@ public ItemDataBan() { this.maxPages = config.getInt(configPath + ".max-pages", 100); this.maxItemSize = config.getInt(configPath + ".max-item-size", 56000); this.maxInventorySize = config.getInt(configPath + ".max-inventory-size", 2050000); - this.cachedItemSizes = Caffeine.newBuilder().expireAfterWrite(Duration.ofMillis( - Math.max(1, config.getInt(configPath + ".dropped-items-size-cache-ticks", 120, - "How long in ticks a dropped item's size should be cached after\n" + - "checking.")) * 50L - )).build(); - this.cachedInventorySizes = Caffeine.newBuilder().expireAfterWrite(Duration.ofMillis( - Math.max(1, config.getInt(configPath + ".player-inventory-size-cache-ticks", 20, - "How long in ticks a player's inventory size should be cached after\n" + - "checking.")) * 50L - )).build(); + this.itemSizeCacheMillis = Math.max(1,config.getInt(configPath + ".dropped-items-size-cache-ticks", 120, + "How long in ticks a dropped item's size should be cached after\n" + + "checking.")) * 50L; + this.inventorySizeCacheMillis = Math.max(1, config.getInt(configPath + ".player-inventory-size-cache-ticks", 20, + "How long in ticks a player's inventory size should be cached after\n" + + "checking.")) * 50L; } @Override public void enable() { + cachedItemSizes = Caffeine.newBuilder().expireAfterWrite(Duration.ofMillis(itemSizeCacheMillis)).build(); + cachedInventorySizes = Caffeine.newBuilder().expireAfterWrite(Duration.ofMillis(inventorySizeCacheMillis)).build(); plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); - cachedInventorySizes.cleanUp(); - cachedItemSizes.cleanUp(); + if (cachedItemSizes != null) { + cachedItemSizes.invalidateAll(); + cachedItemSizes.cleanUp(); + cachedItemSizes = null; + } + if (cachedInventorySizes != null) { + cachedInventorySizes.invalidateAll(); + cachedInventorySizes.cleanUp(); + cachedInventorySizes = null; + } } // Prevent players from creating big books diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/patches/TeleportCoordExploit.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/patches/TeleportCoordExploit.java index 17aaa72c1..4ec427216 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/patches/TeleportCoordExploit.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/patches/TeleportCoordExploit.java @@ -16,11 +16,10 @@ public class TeleportCoordExploit extends AEFModule implements Listener { private final int minDistanceToVanishPlayers; public TeleportCoordExploit() { - super("patches.prevent-teleport-coordinate-exploit"); - config.addComment(configPath + ".enable", + super("patches.prevent-teleport-coordinate-exploit", true, "Patches coordinate exploit for teleportation commands such as /tpa,\n" + - "/home AS WELL as respawn exploits. \n" + - "This is done by vanishing the player for x ticks before teleporting."); + "/home AS WELL as respawn exploits. \n" + + "This is done by vanishing the player for x ticks before teleporting."); this.minDistanceToVanishPlayers = config.getInt(configPath + ".min-distance-to-vanish-player", 100); this.teleportVanishTime = config.getInt(configPath + ".teleport-vanish-time-in-ticks", 10); } @@ -30,11 +29,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", true); - } - @Override public void disable() { HandlerList.unregisterAll(this); @@ -62,6 +56,8 @@ private void onTeleport(PlayerTeleportEvent event) { case PLUGIN: case COMMAND: case ENDER_PEARL: + case UNKNOWN: + case SPECTATE: if (LocationUtil.getRelDistance2D(event.getFrom(), event.getTo()) >= minDistanceToVanishPlayers) { Player player = event.getPlayer(); vanish(player); diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/patches/commandsign/CommandSign.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/patches/commandsign/CommandSign.java index 8868c5bb7..ac307719f 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/patches/commandsign/CommandSign.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/patches/commandsign/CommandSign.java @@ -16,11 +16,10 @@ public class CommandSign extends AEFModule implements Listener { private final Listener signCommandListener; public CommandSign() { - super("patches.prevent-command-sign"); - config.addComment(configPath + ".enable", + super("patches.prevent-command-sign", true, "Patch signs that have run_command NBT tags attached, allowing the \n" + - "to run a command with operator permissions on click. \n" + - "Recommended to enable if you had a rogue admin or backdoor incident."); + "to run a command with operator permissions on click. \n" + + "Recommended to enable if you had a rogue admin or backdoor incident."); this.signCommandListener = SignCommandListener.isSupported() ? new SignCommandListener() : this; } @@ -29,11 +28,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(signCommandListener, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", true); - } - @Override public void disable() { HandlerList.unregisterAll(signCommandListener); diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/patches/crashexploits/DispenserCrash.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/patches/crashexploits/DispenserCrash.java index 8cd71dd43..1102dadef 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/patches/crashexploits/DispenserCrash.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/patches/crashexploits/DispenserCrash.java @@ -15,10 +15,9 @@ public class DispenserCrash extends AEFModule implements Listener { private final boolean logIsEnabled; public DispenserCrash() { - super("patches.prevent-dispenser-crash"); - config.addComment(configPath + ".enable", + super("patches.prevent-dispenser-crash", true, "Prevents dispensers from crashing the server when dispensing\n" + - "items out of bounds: https://www.youtube.com/watch?v=XL17P87O6xA"); + "items out of bounds: https://www.youtube.com/watch?v=XL17P87O6xA"); this.logIsEnabled = config.getBoolean(configPath + ".log", false); } @@ -27,11 +26,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", true); - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/patches/crashexploits/EndGatewayCrash.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/patches/crashexploits/EndGatewayCrash.java index 4067f7265..bfa7062c2 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/patches/crashexploits/EndGatewayCrash.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/patches/crashexploits/EndGatewayCrash.java @@ -14,8 +14,7 @@ public class EndGatewayCrash extends AEFModule implements Listener { private final boolean logIsEnabled; public EndGatewayCrash() { - super("patches.prevent-end-gateway-crash"); - config.addComment(configPath + ".enable", + super("patches.prevent-end-gateway-crash", true, "Prevents a crash exploit involving boats and end gateways:\n" + "https://www.youtube.com/watch?v=c5nVBQeYo-I"); this.logIsEnabled = config.getBoolean(configPath + ".log", true); @@ -26,11 +25,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", true); - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/patches/crashexploits/MultipleEnderdragons.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/patches/crashexploits/MultipleEnderdragons.java index 2de326e8d..8e64207a4 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/patches/crashexploits/MultipleEnderdragons.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/patches/crashexploits/MultipleEnderdragons.java @@ -14,7 +14,7 @@ public class MultipleEnderdragons extends AEFModule implements Listener { private final boolean logIsEnabled; public MultipleEnderdragons() { - super("patches.prevent-multiple-enderdragons"); + super("patches.prevent-multiple-enderdragons", false); this.logIsEnabled = config.getBoolean(configPath + ".log", true); } @@ -23,11 +23,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/patches/crashexploits/RedstoneOnTrapdoorCrash.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/patches/crashexploits/RedstoneOnTrapdoorCrash.java index 694918fdf..71d21aba8 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/patches/crashexploits/RedstoneOnTrapdoorCrash.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/patches/crashexploits/RedstoneOnTrapdoorCrash.java @@ -7,7 +7,6 @@ import me.xginko.aef.utils.MaterialUtil; import org.bukkit.Location; import org.bukkit.Material; -import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; @@ -17,65 +16,59 @@ import org.bukkit.event.block.BlockRedstoneEvent; import java.time.Duration; +import java.util.concurrent.atomic.AtomicInteger; public class RedstoneOnTrapdoorCrash extends AEFModule implements Listener { - private final Cache trapdoorActivationCache; + private final long cacheTimeMillis; private final int trapdoorActivationLimit; private final boolean logIsEnabled; + private Cache trapdoorActivationCache; + public RedstoneOnTrapdoorCrash() { - super("patches.prevent-redstone-on-trapdoor-crash"); - config.addComment(configPath + ".enable", + super("patches.prevent-redstone-on-trapdoor-crash", true, "prevents a powerful crash exploit present in 1.13 - 1.19.3"); this.logIsEnabled = config.getBoolean(configPath + ".log", true); this.trapdoorActivationLimit = config.getInt(configPath + ".max-trapdoor-activations-by-redstone-per-time", 10); - this.trapdoorActivationCache = Caffeine.newBuilder().expireAfterWrite(Duration.ofMillis( - Math.max(config.getInt(configPath + ".time-in-ticks", 30, "1 sec = 20 ticks"), 1) * 50L - )).build(); + this.cacheTimeMillis = Math.max(1, config.getInt(configPath + ".time-in-ticks", 30, "1 sec = 20 ticks")) * 50L; } @Override public void enable() { + trapdoorActivationCache = Caffeine.newBuilder().expireAfterWrite(Duration.ofMillis(cacheTimeMillis)).build(); plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); + if (trapdoorActivationCache != null) { + trapdoorActivationCache.invalidateAll(); + trapdoorActivationCache.cleanUp(); + trapdoorActivationCache = null; + } } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) private void onRedstonePowerTrapdoor(BlockRedstoneEvent event) { - Block block = event.getBlock(); - if (!MaterialUtil.TRAPDOORS.contains(block.getType())) return; - - final Location trapdoorLoc = block.getLocation(); - Integer activationCount = trapdoorActivationCache.getIfPresent(trapdoorLoc); - if (activationCount == null) activationCount = 0; + if (!MaterialUtil.TRAPDOORS.contains(event.getBlock().getType())) return; - activationCount++; - trapdoorActivationCache.put(trapdoorLoc, activationCount); + final Location trapdoorLoc = event.getBlock().getLocation(); - if (activationCount > trapdoorActivationLimit) { - block.setType(Material.AIR); + if (trapdoorActivationCache.get(trapdoorLoc, k -> new AtomicInteger()).incrementAndGet() > trapdoorActivationLimit) { + event.getBlock().setType(Material.AIR); if (logIsEnabled) info("Prevented potential trapdoor crash at " + LocationUtil.toString(trapdoorLoc)); } } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) private void onBlockPlace(BlockPlaceEvent event) { - Block block = event.getBlock(); - if (block == null || !MaterialUtil.REDSTONE.contains(block.getType())) return; + if (event.getBlock() == null || !MaterialUtil.REDSTONE.contains(event.getBlock().getType())) return; - if (MaterialUtil.TRAPDOORS.contains(block.getRelative(BlockFace.DOWN).getType())) { + if (MaterialUtil.TRAPDOORS.contains(event.getBlock().getRelative(BlockFace.DOWN).getType())) { event.setCancelled(true); - if (logIsEnabled) info("Prevented potential trapdoor crash at " + LocationUtil.toString(block.getLocation())); + if (logIsEnabled) info("Prevented potential trapdoor crash at " + LocationUtil.toString(event.getBlock().getLocation())); } } } \ No newline at end of file diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/patches/crashexploits/WorldChangeCrash.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/patches/crashexploits/WorldChangeCrash.java index 7fddd8b8a..5a601c3ad 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/patches/crashexploits/WorldChangeCrash.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/patches/crashexploits/WorldChangeCrash.java @@ -14,34 +14,35 @@ public class WorldChangeCrash extends AEFModule implements Listener { - private final ExpiringSet recentWorldChangers; + private final long worldChangeDelayMillis; private final boolean logIsEnabled; + private ExpiringSet recentWorldChangers; + public WorldChangeCrash() { - super("patches.prevent-fast-world-teleport-crash"); - this.recentWorldChangers = new ExpiringSet<>(Duration.ofMillis( - Math.max(config.getInt(configPath + ".teleport-delay-millis", 1000, - "Time in milliseconds until an entity can teleport to\n" + - "another world again."), 1))); - config.addComment(configPath + ".enable", + super("patches.prevent-fast-world-teleport-crash", true, "Prevents crash methods that involve very fast teleporting\n" + - "between different worlds in a short time."); + "between different worlds in a short time."); + this.worldChangeDelayMillis = Math.max(1, config.getInt(configPath + ".teleport-delay-millis", 1000, + "Time in milliseconds until an entity can teleport to\n" + + "another world again.")); this.logIsEnabled = config.getBoolean(configPath + ".log", false); } @Override public void enable() { + recentWorldChangers = new ExpiringSet<>(Duration.ofMillis(worldChangeDelayMillis)); plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", true); - } - @Override public void disable() { HandlerList.unregisterAll(this); + if (recentWorldChangers != null) { + recentWorldChangers.clear(); + recentWorldChangers.cleanUp(); + recentWorldChangers = null; + } } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/BedTrap.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/BedTrap.java index 515a83b71..edfc7899e 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/BedTrap.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/BedTrap.java @@ -14,59 +14,53 @@ import java.time.Duration; import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; public class BedTrap extends AEFModule implements Listener { - private final Cache playerDeathNearBedCount; + private final long timeInSeconds; private final double maxBedDistanceSquared; private final int maxDeathsPerTime; private final boolean logIsEnabled; + private Cache playerDeathNearBedCount; + public BedTrap() { - super("preventions.anti-bed-trap"); - config.addComment(configPath + ".enable", - "Resets a players bed respawn they die too many times within \n" + + super("preventions.anti-bed-trap", false, + "Resets a players bed respawn they die too many times within\n" + "a certain timeframe."); this.logIsEnabled = config.getBoolean(configPath + ".log", false); this.maxDeathsPerTime = config.getInt(configPath + ".max-deaths-per-time", 7, "Amount of times player can die until he is determined as bed-trapped."); - this.playerDeathNearBedCount = Caffeine.newBuilder().expireAfterWrite(Duration.ofSeconds( - Math.max(1, config.getInt(configPath + ".time-in-seconds", 5, - "Time until death counter will be reset again")))).build(); + this.timeInSeconds = Math.max(1, config.getInt(configPath + ".time-in-seconds", 5, + "Time until death counter will be reset again")); this.maxBedDistanceSquared = NumberConversions.square(config.getDouble(configPath + ".max-distance-from-bed", 6.0)); } @Override public void enable() { + playerDeathNearBedCount = Caffeine.newBuilder().expireAfterWrite(Duration.ofSeconds(timeInSeconds)).build(); plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); + if (playerDeathNearBedCount != null) { + playerDeathNearBedCount.invalidateAll(); + playerDeathNearBedCount.cleanUp(); + playerDeathNearBedCount = null; + } } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) private void onDeath(PlayerDeathEvent event) { - final Player player = event.getEntity(); - if (!isNearBedSpawn(player)) return; - - Integer nearBedDeaths = playerDeathNearBedCount.getIfPresent(player.getUniqueId()); - if (nearBedDeaths == null) nearBedDeaths = 0; - nearBedDeaths++; + if (!isNearBedSpawn(event.getEntity())) return; - if (nearBedDeaths > maxDeathsPerTime) { - player.setBedSpawnLocation(null, true); - if (logIsEnabled) info("Reset bed respawn of potentially bed-trapped player '" + player.getName() + "'"); - return; + if (playerDeathNearBedCount.get(event.getEntity().getUniqueId(), k -> new AtomicInteger()).incrementAndGet() > maxDeathsPerTime) { + event.getEntity().setBedSpawnLocation(null, true); + if (logIsEnabled) info("Reset bed respawn of potentially bed-trapped player '" + event.getEntity().getName() + "'"); } - - playerDeathNearBedCount.put(player.getUniqueId(), nearBedDeaths); } private boolean isNearBedSpawn(Player player) { diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/DisableFish.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/DisableFish.java deleted file mode 100755 index 211b75c91..000000000 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/DisableFish.java +++ /dev/null @@ -1,63 +0,0 @@ -package me.xginko.aef.modules.preventions; - -import me.xginko.aef.modules.AEFModule; -import me.xginko.aef.utils.PlatformUtil; -import org.bukkit.entity.EntityType; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.HandlerList; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.CreatureSpawnEvent; - -import java.util.Arrays; -import java.util.EnumSet; -import java.util.Objects; -import java.util.Set; -import java.util.stream.Collectors; - -public class DisableFish extends AEFModule implements Listener { - - private final Set disabledFishes; - - public DisableFish() { - super("preventions.prevent-ambient-fish-spawns"); - config.addComment(configPath + ".enable", - "Prevent certain fish types from spawning in newer versions to combat lag."); - this.disabledFishes = config.getList(configPath + ".fish-types-to-prevent", - Arrays.asList("COD", "SALMON", "PUFFERFISH", "TROPICAL_FISH")) - .stream() - .map(configuredFish -> { - try { - return EntityType.valueOf(configuredFish); - } catch (IllegalArgumentException exception) { - if (PlatformUtil.getMinecraftVersion() > 12) - notRecognized(EntityType.class, configuredFish); - return null; - } - }) - .filter(Objects::nonNull) - .collect(Collectors.toCollection(() -> EnumSet.noneOf(EntityType.class))); - } - - @Override - public void enable() { - plugin.getServer().getPluginManager().registerEvents(this, plugin); - } - - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false) && PlatformUtil.getMinecraftVersion() > 12; - } - - @Override - public void disable() { - HandlerList.unregisterAll(this); - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - private void onCreatureSpawn(CreatureSpawnEvent event) { - if (disabledFishes.contains(event.getEntity().getType())) { - event.setCancelled(true); - } - } -} diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/MapSpam.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/MapSpam.java index 673b5d31f..9c6e8105f 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/MapSpam.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/MapSpam.java @@ -23,47 +23,47 @@ public class MapSpam extends AEFModule implements Listener { - private final Cache trackedPlayers; private final long cooldownMillis; private final int mapCreateLimit; private final boolean shouldNotifyPlayers; + private Cache trackedPlayers; + public MapSpam() { - super("preventions.prevent-map-reset-spam"); - config.addComment(configPath + ".enable", + super("preventions.prevent-map-reset-spam", false, "Puts a cooldown on creating maps so players cant reset\n" + - "map arts that easily.\n" + - "Only needed on versions below 1.12 and lower.\n" + - "Bypass permission: " + AEFPermission.BYPASS_MAP_SPAM.string()); + "map arts that easily.\n" + + "Only needed on versions below 1.12 and lower.\n" + + "Bypass permission: " + AEFPermission.BYPASS_MAP_SPAM.string()); this.shouldNotifyPlayers = config.getBoolean(configPath + ".notify-players", true, "Sends a message to players telling them how many maps\n" + "they can create per time"); this.cooldownMillis = TimeUnit.MINUTES.toMillis(Math.max(1, config.getInt(configPath + ".cooldown-time-in-minutes", 60))); - this.trackedPlayers = Caffeine.newBuilder().expireAfterWrite(Duration.ofMillis(cooldownMillis)).build(); this.mapCreateLimit = config.getInt(configPath + ".max-amount-of-maps-per-time", 4); } @Override public void enable() { + trackedPlayers = Caffeine.newBuilder().expireAfterWrite(Duration.ofMillis(cooldownMillis)).build(); plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); + if (trackedPlayers != null) { + trackedPlayers.invalidateAll(); + trackedPlayers.cleanUp(); + trackedPlayers = null; + } } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = false) private void onPlayerInteract(PlayerInteractEvent event) { if (event.getAction() == Action.LEFT_CLICK_AIR || event.getAction() == Action.LEFT_CLICK_BLOCK) return; final ItemStack mapItem = event.getItem(); - if (mapItem == null || mapItem.getType() != XMaterial.MAP.parseMaterial()) return; + if (mapItem == null || mapItem.getType() != XMaterial.MAP.get()) return; final Player player = event.getPlayer(); if (player.hasPermission(AEFPermission.BYPASS_MAP_SPAM.string())) return; diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/NetherRoof.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/NetherRoof.java index 7a2150d75..abc03ce6b 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/NetherRoof.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/NetherRoof.java @@ -7,13 +7,11 @@ import me.xginko.aef.utils.CachingPermTool; import me.xginko.aef.utils.LocationUtil; import org.bukkit.Location; -import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; -import org.bukkit.entity.Vehicle; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.HandlerList; @@ -29,8 +27,8 @@ public class NetherRoof extends AEFModule implements Listener { private final boolean safe_teleport_enabled; public NetherRoof() { - super("preventions.prevent-nether-roof"); - config.addComment(configPath + ".enable", "Prevent players from going above the nether roof."); + super("preventions.prevent-nether-roof", true, + "Prevent players from going above the nether roof."); this.safe_teleport_enabled = config.getBoolean(configPath + ".safely-teleport-players", true); } @@ -39,11 +37,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", true); - } - @Override public void disable() { HandlerList.unregisterAll(this); @@ -61,12 +54,11 @@ private void onTeleport(PlayerTeleportEvent event) { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) private void onPlayerMove(PlayerMoveEvent event) { - final Player player = event.getPlayer(); if ( - LocationUtil.isNetherCeiling(player.getLocation()) - && !CachingPermTool.hasPermission(AEFPermission.BYPASS_NETHER_ROOF, player) + LocationUtil.isNetherCeiling(event.getPlayer().getLocation()) + && !CachingPermTool.hasPermission(AEFPermission.BYPASS_NETHER_ROOF, event.getPlayer()) ) { - Location belowCeiling = getBelowCeilLocation(player.getLocation()); + Location belowCeiling = getBelowCeilLocation(event.getPlayer().getLocation()); event.setTo(belowCeiling); createSafespace(belowCeiling); } @@ -74,15 +66,14 @@ private void onPlayerMove(PlayerMoveEvent event) { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) private void onVehicleMove(VehicleMoveEvent event) { - final Vehicle vehicle = event.getVehicle(); - if (!LocationUtil.isNetherCeiling(vehicle.getLocation())) return; + if (!LocationUtil.isNetherCeiling(event.getVehicle().getLocation())) return; - for (Entity passenger : vehicle.getPassengers()) { + for (Entity passenger : event.getVehicle().getPassengers()) { if (passenger.getType() == EntityType.PLAYER && CachingPermTool.hasPermission(AEFPermission.BYPASS_NETHER_ROOF, (Player) passenger)) return; } - for (Entity entity : vehicle.getPassengers()) { + for (Entity entity : event.getVehicle().getPassengers()) { if (entity.getType() == EntityType.PLAYER) { this.teleportFromCeiling((Player) entity); } else { @@ -91,20 +82,19 @@ private void onVehicleMove(VehicleMoveEvent event) { } } - vehicle.remove(); + event.getVehicle().remove(); } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) private void onBlockPlace(BlockPlaceEvent event) { - final Player player = event.getPlayer(); - if (CachingPermTool.hasPermission(AEFPermission.BYPASS_NETHER_ROOF, player)) return; + if (CachingPermTool.hasPermission(AEFPermission.BYPASS_NETHER_ROOF, event.getPlayer())) return; if (LocationUtil.isNetherCeiling(event.getBlock().getLocation())) { event.setCancelled(true); } - if (LocationUtil.isNetherCeiling(player.getLocation())) { - teleportFromCeiling(player); + if (LocationUtil.isNetherCeiling(event.getPlayer().getLocation())) { + teleportFromCeiling(event.getPlayer()); } } @@ -127,30 +117,30 @@ private void createSafespace(Location location) { // Check block above for liquid or falling block Block blockAboveHead = location.clone().add(0, 2, 0).getBlock(); - if (isUnsafe(blockAboveHead) && blockAboveHead.getType() != XMaterial.NETHER_PORTAL.parseMaterial()) - blockAboveHead.setType(XMaterial.NETHERRACK.parseMaterial(), false); + if (isUnsafe(blockAboveHead) && blockAboveHead.getType() != XMaterial.NETHER_PORTAL.get()) + blockAboveHead.setType(XMaterial.NETHERRACK.get(), false); // Create an air pocket for the player Block blockAtPlayerLegs = location.getBlock(); - if (blockAtPlayerLegs.getType() != Material.AIR && blockAtPlayerLegs.getType() != XMaterial.NETHER_PORTAL.parseMaterial()) - blockAtPlayerLegs.setType(Material.AIR, false); + if (blockAtPlayerLegs.getType() != XMaterial.AIR.get() && blockAtPlayerLegs.getType() != XMaterial.NETHER_PORTAL.get()) + blockAtPlayerLegs.setType(XMaterial.AIR.get(), false); Block blockAtPlayerTorso = blockAtPlayerLegs.getRelative(BlockFace.UP); - if (blockAtPlayerTorso.getType() != Material.AIR && blockAtPlayerTorso.getType() != XMaterial.NETHER_PORTAL.parseMaterial()) - blockAtPlayerTorso.setType(Material.AIR, false); + if (blockAtPlayerTorso.getType() != XMaterial.AIR.get() && blockAtPlayerTorso.getType() != XMaterial.NETHER_PORTAL.get()) + blockAtPlayerTorso.setType(XMaterial.AIR.get(), false); // Check all sides of air pocket for liquids and fill with netherrack for (int i = 0; i < 2; i++) { Block airPocketBlock = blockAtPlayerLegs.getRelative(BlockFace.UP, i); for (BlockFace face : CARDINAL_FACES) { Block around = airPocketBlock.getRelative(face); - if (isUnsafe(around)) around.setType(XMaterial.NETHERRACK.parseMaterial(), false); + if (isUnsafe(around)) around.setType(XMaterial.NETHERRACK.get(), false); } } // Create block below feet if not solid Block blockBelowFeet = blockAtPlayerLegs.getRelative(BlockFace.DOWN); - if (isUnsafe(blockBelowFeet) || blockBelowFeet.getType().equals(XMaterial.NETHER_PORTAL.parseMaterial())) - blockBelowFeet.setType(XMaterial.NETHERRACK.parseMaterial(), true); + if (isUnsafe(blockBelowFeet) || blockBelowFeet.getType().equals(XMaterial.NETHER_PORTAL.get())) + blockBelowFeet.setType(XMaterial.NETHERRACK.get(), true); } private static boolean isUnsafe(Block block) { diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/PreventNonSurvival.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/PreventNonSurvival.java index 4cf950c46..608856c31 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/PreventNonSurvival.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/PreventNonSurvival.java @@ -24,8 +24,7 @@ public class PreventNonSurvival extends AEFModule implements Listener { private final boolean logIsEnabled; public PreventNonSurvival() { - super("preventions.prevent-non-survival-players"); - config.addComment(configPath + ".enable", + super("preventions.prevent-non-survival-players", false, "Checks if player is in survival and if not, puts him back into survival. \n" + "Useful if you had a backdoor incident."); this.logIsEnabled = config.getBoolean(configPath + ".log", true); @@ -39,9 +38,10 @@ public void enable() { } @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); + public void disable() { + HandlerList.unregisterAll(this); } + private void checkForIllegalGamemode(HumanEntity player) { if (allowedGamemodePlayers.contains(player.getName())) return; @@ -51,11 +51,6 @@ private void checkForIllegalGamemode(HumanEntity player) { } } - @Override - public void disable() { - HandlerList.unregisterAll(this); - } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) private void onInventory(InventoryEvent event) { checkForIllegalGamemode(event.getView().getPlayer()); diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/PreventOppedPlayers.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/PreventOppedPlayers.java index 4728d6a05..d394941e1 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/PreventOppedPlayers.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/PreventOppedPlayers.java @@ -22,8 +22,8 @@ public class PreventOppedPlayers extends AEFModule implements Listener { private final boolean logIsEnabled; public PreventOppedPlayers() { - super("preventions.prevent-opped-players"); - config.addComment(configPath + ".enable", "Useful if you suspect a backdoor has happened."); + super("preventions.prevent-opped-players", false, + "Useful if you suspect a backdoor has happened."); this.logIsEnabled = config.getBoolean(configPath + ".log", true); this.allowedOperators = new HashSet<>(config.getList(configPath + ".whitelisted-players", Collections.singletonList("Notch"))); } @@ -33,11 +33,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/blockbreak/PistonExplodePermBlockRemoval.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/blockbreak/PistonExplodePermBlockRemoval.java index 199b75d0d..10853c09d 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/blockbreak/PistonExplodePermBlockRemoval.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/blockbreak/PistonExplodePermBlockRemoval.java @@ -1,8 +1,8 @@ package me.xginko.aef.modules.preventions.blockbreak; +import com.cryptomorin.xseries.XMaterial; import me.xginko.aef.modules.AEFModule; import me.xginko.aef.utils.MaterialUtil; -import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.event.EventHandler; @@ -20,7 +20,7 @@ public class PistonExplodePermBlockRemoval extends AEFModule implements Listener private final Set whitelistedWorlds; public PistonExplodePermBlockRemoval() { - super("preventions.permanent-block-breaking.by-exploding-pistons"); + super("preventions.permanent-block-breaking.by-exploding-pistons", true); this.whitelistedWorlds = new HashSet<>(config.getList(configPath + ".whitelisted-worlds", Collections.singletonList("example_world_name"))); } @@ -30,11 +30,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", true); - } - @Override public void disable() { HandlerList.unregisterAll(this); @@ -66,6 +61,6 @@ private void onEntityExplode(EntityExplodeEvent event) { // Schedule a single delayed task to remove those blocks silently plugin.getServer().getScheduler().runTaskLater(plugin, () -> - pistons_that_could_break_indestructible_blocks.forEach(block -> block.setType(Material.AIR)), 5L); + pistons_that_could_break_indestructible_blocks.forEach(block -> block.setType(XMaterial.AIR.get())), 5L); } } diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/blockbreak/PistonPlaceWhileRetractPermBlockRemoval.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/blockbreak/PistonPlaceWhileRetractPermBlockRemoval.java index 2a4c0df86..a60ba7f46 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/blockbreak/PistonPlaceWhileRetractPermBlockRemoval.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/blockbreak/PistonPlaceWhileRetractPermBlockRemoval.java @@ -17,7 +17,7 @@ public class PistonPlaceWhileRetractPermBlockRemoval extends AEFModule implement private final Set whitelistedWorlds; public PistonPlaceWhileRetractPermBlockRemoval() { - super("preventions.permanent-block-breaking.by-placing-piston-on-retract"); + super("preventions.permanent-block-breaking.by-placing-piston-on-retract", true); this.whitelistedWorlds = new HashSet<>(config.getList(configPath + ".whitelisted-worlds", Collections.singletonList("example_world_name"))); } @@ -27,11 +27,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", true); - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/blockbreak/StructureGrowPermBlockRemoval.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/blockbreak/StructureGrowPermBlockRemoval.java index eb29574f2..c5d6ad1c9 100644 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/blockbreak/StructureGrowPermBlockRemoval.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/blockbreak/StructureGrowPermBlockRemoval.java @@ -14,8 +14,7 @@ public class StructureGrowPermBlockRemoval extends AEFModule implements Listener { public StructureGrowPermBlockRemoval() { - super("preventions.permanent-block-breaking.by-growing-structures"); - config.addComment(configPath + ".enable", + super("preventions.permanent-block-breaking.by-growing-structures", true, "Prevents removal of permanent blocks by growing structures \n" + "like mushrooms into them."); } @@ -25,11 +24,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", true); - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/portals/EndPortalDestruction.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/portals/EndPortalDestruction.java index d5ed97c98..497154fe0 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/portals/EndPortalDestruction.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/portals/EndPortalDestruction.java @@ -31,7 +31,7 @@ public class EndPortalDestruction extends AEFModule implements Listener { private final boolean logIsEnabled; public EndPortalDestruction() { - super("preventions.portals.prevent-destroying-end-portals"); + super("preventions.portals.prevent-destroying-end-portals", true); this.logIsEnabled = config.getBoolean(configPath + ".log", true); this.endBedrockProtectRadius = config.getInt(configPath + ".end.bedrock-protection-radius-blocks", 8); this.pillars = config.getList(configPath + ".end.pillar-blocks", @@ -67,11 +67,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", true); - } - @Override public void disable() { HandlerList.unregisterAll(this); @@ -87,14 +82,14 @@ private void onBlockDispense(BlockDispenseEvent event) { private boolean isNearEndPortal(Block dispenser) { for (BlockFace face : BlockFace.values()) { - if (dispenser.getRelative(face).getType() == XMaterial.END_PORTAL.parseMaterial()) return true; + if (dispenser.getRelative(face).getType() == XMaterial.END_PORTAL.get()) return true; } return false; } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) private void onPlayerBucketEvent(PlayerBucketEmptyEvent event) { - if (event.getBlockClicked().getRelative(event.getBlockFace()).getType() == XMaterial.END_PORTAL.parseMaterial()) { + if (event.getBlockClicked().getRelative(event.getBlockFace()).getType() == XMaterial.END_PORTAL.get()) { event.setCancelled(true); if (logIsEnabled) info("Prevented "+event.getPlayer().getName()+" from destroying an end portal!"); } @@ -162,6 +157,6 @@ private boolean isWithinEndProtectedRadius(Location location) { } private boolean isEndPortal(Material material) { - return material == XMaterial.END_PORTAL.parseMaterial() || material == XMaterial.END_PORTAL_FRAME.parseMaterial(); + return material == XMaterial.END_PORTAL.get() || material == XMaterial.END_PORTAL_FRAME.get(); } } \ No newline at end of file diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/portals/PreventAllEntitiesInPortals.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/portals/PreventAllEntitiesInPortals.java index e7859cb45..114085031 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/portals/PreventAllEntitiesInPortals.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/portals/PreventAllEntitiesInPortals.java @@ -11,8 +11,8 @@ public class PreventAllEntitiesInPortals extends AEFModule implements Listener { public PreventAllEntitiesInPortals() { - super("preventions.portals.prevent-all-entities-in-portals"); - config.addComment(configPath, "Only enable if you must. Does not affect players."); + super("preventions.portals.prevent-all-entities-in-portals", false, + "Only enable if you must. Does not affect players."); } @Override @@ -20,11 +20,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath, false); - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/portals/PreventPortalTraps.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/portals/PreventPortalTraps.java index b975a96ee..0f922be20 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/portals/PreventPortalTraps.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/portals/PreventPortalTraps.java @@ -15,8 +15,7 @@ public class PreventPortalTraps extends AEFModule implements Listener { private final long tpBackDelay; public PreventPortalTraps() { - super("preventions.portals.prevent-portal-traps"); - config.addComment(configPath + ".enable", + super("preventions.portals.prevent-portal-traps", false, "Teleports a player back to the original location if they have been\n" + "standing in a portal for too long."); this.tpBackDelay = config.getInt(configPath + ".wait-time-until-tp-back-in-seconds", 10) * 20L; @@ -27,11 +26,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); @@ -41,9 +35,9 @@ public void disable() { private void onPortal(PlayerPortalEvent event) { final Player player = event.getPlayer(); plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, () -> { - if (player.getLocation().getBlock().getType() == XMaterial.NETHER_PORTAL.parseMaterial()) { + if (player.getLocation().getBlock().getType() == XMaterial.NETHER_PORTAL.get()) { player.teleport(event.getFrom()); - player.playSound(player.getLocation(), XSound.BLOCK_PORTAL_TRAVEL.parseSound(), 1.0F, 1.0F); + player.playSound(player.getLocation(), XSound.BLOCK_PORTAL_TRAVEL.get(), 1.0F, 1.0F); } }, tpBackDelay); } diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/portals/PreventProjectilesInPortals.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/portals/PreventProjectilesInPortals.java index 452d6468b..e0ee080ee 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/portals/PreventProjectilesInPortals.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/portals/PreventProjectilesInPortals.java @@ -11,8 +11,8 @@ public class PreventProjectilesInPortals extends AEFModule implements Listener { public PreventProjectilesInPortals() { - super("preventions.portals.prevent-projectiles-in-portals"); - config.addComment(configPath, "Prevents a lag exploit. Might disable some chunk loader designs."); + super("preventions.portals.prevent-projectiles-in-portals", false, + "Prevents a lag exploit. Might disable some chunk loader designs."); } @Override @@ -20,11 +20,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath, false); - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/portals/PreventSpecificEntitiesInPortals.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/portals/PreventSpecificEntitiesInPortals.java index 61f9ed15d..218e7b3be 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/portals/PreventSpecificEntitiesInPortals.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/portals/PreventSpecificEntitiesInPortals.java @@ -1,5 +1,6 @@ package me.xginko.aef.modules.preventions.portals; +import com.cryptomorin.xseries.XEntityType; import me.xginko.aef.modules.AEFModule; import org.bukkit.entity.EntityType; import org.bukkit.event.EventHandler; @@ -8,25 +9,35 @@ import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityPortalEvent; -import java.util.Arrays; import java.util.EnumSet; +import java.util.List; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; +import java.util.stream.Stream; public class PreventSpecificEntitiesInPortals extends AEFModule implements Listener { private final Set forbiddenTypes; public PreventSpecificEntitiesInPortals() { - super("preventions.portals.prevent-specific-types"); - config.addComment(configPath + ".enable", + super("preventions.portals.prevent-specific-types", true, "Configure entities here that you suspect might be used in a dupe \n" + "with portals. \n" + "CAUTION: Will kill the entity on folia due to broken portal event. \n" + "There is sadly no other efficient way."); - this.forbiddenTypes = config.getList(configPath + ".entities", - Arrays.asList("DROPPED_ITEM", "FIREWORK", "PRIMED_TNT", "THROWN_EXP_BOTTLE", "EXPERIENCE_ORB", "ARMOR_STAND"), + List defaults = Stream.of( + XEntityType.ITEM, + XEntityType.FIREWORK_ROCKET, + XEntityType.TNT, + XEntityType.EXPERIENCE_BOTTLE, + XEntityType.EXPERIENCE_ORB, + XEntityType.ARMOR_STAND) + .filter(XEntityType::isSupported) + .map(XEntityType::get) + .map(Enum::name) + .collect(Collectors.toList()); + this.forbiddenTypes = config.getList(configPath + ".entities", defaults, "Defaults prevent common lag methods.") .stream() .map(configuredType -> { @@ -46,11 +57,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", true); - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/withers/RateLimitWitherSkulls.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/withers/RateLimitWitherSkulls.java index fc87f3797..4bd359502 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/withers/RateLimitWitherSkulls.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/withers/RateLimitWitherSkulls.java @@ -15,38 +15,49 @@ public class RateLimitWitherSkulls extends AEFModule implements Listener { - private final ExpiringSet targetingPlayers, targetingOther, notTargeting; + private final long playerCooldownMillis, otherCooldownMillis, notargetCooldownMillis; + + private ExpiringSet targetingPlayers, targetingOther, notTargeting; public RateLimitWitherSkulls() { - super("preventions.withers.rate-limit-shooting-skulls"); - config.addComment(configPath + ".enable", + super("preventions.withers.rate-limit-shooting-skulls", false, "This can help combat lag caused by a ton of wither skulls\n" + "spawning but weakens withers."); - this.targetingPlayers = new ExpiringSet<>(Duration.ofMillis(Math.max(1, - config.getInt(configPath + ".player-target-cooldown-in-ticks", 20, - "Cooldown until another skull will be shot at a player")) * 50L)); - this.targetingOther = new ExpiringSet<>(Duration.ofMillis(Math.max(1, - config.getInt(configPath + ".other-target-cooldown-in-ticks", 40, - "Cooldown until another skull can be shot at anything \n" + - "else other than a player.")) * 50L)); - this.notTargeting = new ExpiringSet<>(Duration.ofMillis(Math.max(1, - config.getInt(configPath + ".no-target-cooldown-in-ticks", 100, - "Cooldown when wither has no target")) * 50L)); + this.playerCooldownMillis = Math.max(1, config.getInt(configPath + ".player-target-cooldown-in-ticks", 20, + "Cooldown until another skull will be shot at a player")) * 50L; + this.otherCooldownMillis = Math.max(1, config.getInt(configPath + ".other-target-cooldown-in-ticks", 40, + "Cooldown until another skull can be shot at anything \n" + + "else other than a player.")) * 50L; + this.notargetCooldownMillis = Math.max(1, config.getInt(configPath + ".no-target-cooldown-in-ticks", 100, + "Cooldown when wither has no target")) * 50L; } @Override public void enable() { + targetingPlayers = new ExpiringSet<>(Duration.ofMillis(playerCooldownMillis)); + targetingOther = new ExpiringSet<>(Duration.ofMillis(otherCooldownMillis)); + notTargeting = new ExpiringSet<>(Duration.ofMillis(notargetCooldownMillis)); plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); + if (targetingPlayers != null) { + targetingPlayers.clear(); + targetingPlayers.cleanUp(); + targetingPlayers = null; + } + if (targetingOther != null) { + targetingOther.clear(); + targetingOther.cleanUp(); + targetingOther = null; + } + if (notTargeting != null) { + notTargeting.clear(); + notTargeting.cleanUp(); + notTargeting = null; + } } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/withers/RemoveSkullsOnChunkload.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/withers/RemoveSkullsOnChunkUnload.java similarity index 80% rename from AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/withers/RemoveSkullsOnChunkload.java rename to AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/withers/RemoveSkullsOnChunkUnload.java index cf30d403a..e12c47bfd 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/withers/RemoveSkullsOnChunkload.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/withers/RemoveSkullsOnChunkUnload.java @@ -12,13 +12,12 @@ import org.bukkit.event.entity.ProjectileLaunchEvent; import org.bukkit.event.world.ChunkUnloadEvent; -public class RemoveSkullsOnChunkload extends AEFModule implements Listener { +public class RemoveSkullsOnChunkUnload extends AEFModule implements Listener { - public RemoveSkullsOnChunkload() { - super("preventions.withers.remove-flying-wither-skulls.on-chunk-unload"); - config.addComment(configPath, + public RemoveSkullsOnChunkUnload() { + super("preventions.withers.remove-flying-wither-skulls.on-chunk-unload", true, "Removes wither skulls when the chunk gets unloaded.\n" + - "Use if you have a ton of them at spawn and they are causing lag."); + "Use if you have a ton of them at spawn and they are causing lag."); } @Override @@ -26,11 +25,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath, true); - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/withers/WitherSkullDropsAtSpawn.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/withers/WitherSkullDropsAtSpawn.java index f6f0d6650..2d3d11fa1 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/withers/WitherSkullDropsAtSpawn.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/withers/WitherSkullDropsAtSpawn.java @@ -1,9 +1,9 @@ package me.xginko.aef.modules.preventions.withers; +import com.cryptomorin.xseries.XEntityType; import io.github.thatsmusic99.configurationmaster.api.ConfigSection; import me.xginko.aef.modules.AEFModule; import me.xginko.aef.utils.LocationUtil; -import org.bukkit.entity.EntityType; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.HandlerList; @@ -12,15 +12,15 @@ import org.bukkit.util.NumberConversions; import java.util.HashMap; +import java.util.List; import java.util.Map; public class WitherSkullDropsAtSpawn extends AEFModule implements Listener { - private final Map worldsAndTheirRadiuses = new HashMap<>(); + private final Map worldsAndTheirRadiuses; public WitherSkullDropsAtSpawn() { - super("preventions.withers.disable-item-drops-at-spawn"); - config.addComment(configPath + ".enable", + super("preventions.withers.disable-item-drops-at-spawn", false, "Prevents wither skulls from dropping items when they hit a block\n" + "within a certain radius from 00. Can help with lag."); Map defaults = new HashMap<>(); @@ -28,7 +28,9 @@ public WitherSkullDropsAtSpawn() { defaults.put("world_nether", 5000); defaults.put("world_the_end", 5000); ConfigSection section = config.getConfigSection(configPath + ".worlds", defaults); - for (String world : section.getKeys(false)) { + List worlds = section.getKeys(false); + this.worldsAndTheirRadiuses = new HashMap<>(worlds.size()); + for (String world : worlds) { try { double radiusSquared = NumberConversions.square(Integer.parseInt(section.getString(world))); this.worldsAndTheirRadiuses.put(world, radiusSquared); @@ -43,11 +45,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); @@ -55,7 +52,7 @@ public void disable() { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) private void onEntityExplode(EntityExplodeEvent event) { - if (event.getEntityType() != EntityType.WITHER_SKULL) return; + if (event.getEntityType() != XEntityType.WITHER_SKULL.get()) return; if (!worldsAndTheirRadiuses.containsKey(event.getLocation().getWorld().getName())) return; if (LocationUtil.getSquaredDistance2DTo00(event.getLocation()) diff --git a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/withers/WitherSummonAtSpawn.java b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/withers/WitherSummonAtSpawn.java index eb12ac3f2..21bef40a9 100755 --- a/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/withers/WitherSummonAtSpawn.java +++ b/AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/preventions/withers/WitherSummonAtSpawn.java @@ -14,16 +14,16 @@ import org.bukkit.util.NumberConversions; import java.util.HashMap; +import java.util.List; import java.util.Map; public class WitherSummonAtSpawn extends AEFModule implements Listener { - private final Map worldsAndTheirRadiuses = new HashMap<>(); + private final Map worldsAndTheirRadiuses; private final boolean playersShouldBeInformed; public WitherSummonAtSpawn() { - super("preventions.withers.disable-summon-at-spawn"); - config.addComment(configPath + ".enable", + super("preventions.withers.disable-summon-at-spawn", false, "Disables spawning withers near a configurable radius around\n" + "spawn. Helps if players are generating endless amounts of withers\n" + "to lag the server."); @@ -33,7 +33,9 @@ public WitherSummonAtSpawn() { defaults.put("world_nether", 5000); defaults.put("world_the_end", 5000); ConfigSection section = config.getConfigSection(configPath + ".worlds", defaults); - for (String world : section.getKeys(false)) { + List worlds = section.getKeys(false); + this.worldsAndTheirRadiuses = new HashMap<>(worlds.size()); + for (String world : worlds) { try { Double radiusSquared = NumberConversions.square(Integer.parseInt(section.getString(world))); this.worldsAndTheirRadiuses.put(world, radiusSquared); @@ -48,11 +50,6 @@ public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @Override - public boolean shouldEnable() { - return config.getBoolean(configPath + ".enable", false); - } - @Override public void disable() { HandlerList.unregisterAll(this); diff --git a/shared/src/main/java/me/xginko/aef/modules/patches/commandsign/SignCommandListener.java b/shared/src/main/java/me/xginko/aef/modules/patches/commandsign/SignCommandListener.java index eef8d0697..41b733577 100644 --- a/shared/src/main/java/me/xginko/aef/modules/patches/commandsign/SignCommandListener.java +++ b/shared/src/main/java/me/xginko/aef/modules/patches/commandsign/SignCommandListener.java @@ -1,6 +1,5 @@ package me.xginko.aef.modules.patches.commandsign; -import io.papermc.paper.event.player.PlayerSignCommandPreprocessEvent; import me.xginko.aef.enums.AEFPermission; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; @@ -20,7 +19,7 @@ public class SignCommandListener implements Listener { } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - private void onSignCommandPreprocess(PlayerSignCommandPreprocessEvent event) { + private void onSignCommandPreprocess(io.papermc.paper.event.player.PlayerSignCommandPreprocessEvent event) { if (!event.getPlayer().hasPermission(AEFPermission.BYPASS_PREVENTION_COMMANDSIGN.bukkit())) { event.setCancelled(true); } diff --git a/shared/src/main/java/me/xginko/aef/utils/BlockUtil.java b/shared/src/main/java/me/xginko/aef/utils/BlockUtil.java index 13056d28d..913b668bc 100644 --- a/shared/src/main/java/me/xginko/aef/utils/BlockUtil.java +++ b/shared/src/main/java/me/xginko/aef/utils/BlockUtil.java @@ -1,8 +1,12 @@ package me.xginko.aef.utils; +import de.tr7zw.changeme.nbtapi.NBT; +import de.tr7zw.changeme.nbtapi.iface.ReadableNBT; import org.bukkit.Material; import org.bukkit.block.BlockState; import org.bukkit.block.data.Waterlogged; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.EnumMap; import java.util.Map; @@ -20,9 +24,13 @@ public static boolean isWaterloggedAvailable() { } private static final Map IS_WATERLOGGABLE_CACHE = new EnumMap<>(Material.class); - public static boolean isWaterlogged(BlockState blockState) { + public static boolean isWaterlogged(@Nullable BlockState blockState) { return blockState != null && IS_WATERLOGGABLE_CACHE.computeIfAbsent(blockState.getType(), k -> blockState.getBlockData() instanceof Waterlogged) && ((Waterlogged) blockState.getBlockData()).isWaterlogged(); } + + public static String getNBTString(@NotNull BlockState blockState) { + return NBT.get(blockState, ReadableNBT::toString); + } } diff --git a/shared/src/main/java/me/xginko/aef/utils/CachingPermTool.java b/shared/src/main/java/me/xginko/aef/utils/CachingPermTool.java index 774cef847..01655f32a 100644 --- a/shared/src/main/java/me/xginko/aef/utils/CachingPermTool.java +++ b/shared/src/main/java/me/xginko/aef/utils/CachingPermTool.java @@ -34,8 +34,10 @@ public static CachingPermTool enable(JavaPlugin plugin) { @Override public void disable() { HandlerList.unregisterAll(this); - for (Map.Entry> entry : permissionCacheMap.entrySet()) + for (Map.Entry> entry : permissionCacheMap.entrySet()) { + entry.getValue().invalidateAll(); entry.getValue().cleanUp(); + } permissionCacheMap.clear(); } @@ -52,11 +54,15 @@ public static boolean hasPermission(AEFPermission permission, HumanEntity human) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) private void onLeave(PlayerQuitEvent event) { - permissionCacheMap.remove(event.getPlayer().getUniqueId()); + Cache cache = permissionCacheMap.remove(event.getPlayer().getUniqueId()); + cache.invalidateAll(); + cache.cleanUp(); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) private void onKick(PlayerKickEvent event) { - permissionCacheMap.remove(event.getPlayer().getUniqueId()); + Cache cache = permissionCacheMap.remove(event.getPlayer().getUniqueId()); + cache.invalidateAll(); + cache.cleanUp(); } } diff --git a/shared/src/main/java/me/xginko/aef/utils/ItemUtil.java b/shared/src/main/java/me/xginko/aef/utils/ItemUtil.java index 21cafb4ca..d3b4155c3 100644 --- a/shared/src/main/java/me/xginko/aef/utils/ItemUtil.java +++ b/shared/src/main/java/me/xginko/aef/utils/ItemUtil.java @@ -48,7 +48,7 @@ public class ItemUtil { } } - if (BUNDLES_SUPPPORTED && itemStack.getType() == XMaterial.BUNDLE.parseMaterial()) { + if (BUNDLES_SUPPPORTED && itemStack.getType() == XMaterial.BUNDLE.get()) { return ((BundleMeta) itemStack.getItemMeta()).getItems(); } diff --git a/shared/src/main/java/me/xginko/aef/utils/MaterialUtil.java b/shared/src/main/java/me/xginko/aef/utils/MaterialUtil.java index 99bec95dc..1caaeffe5 100755 --- a/shared/src/main/java/me/xginko/aef/utils/MaterialUtil.java +++ b/shared/src/main/java/me/xginko/aef/utils/MaterialUtil.java @@ -144,6 +144,14 @@ public class MaterialUtil { .map(XMaterial::get) .collect(Collectors.toCollection(() -> EnumSet.noneOf(Material.class))); + public static final Set AIR = Stream.of( + XMaterial.AIR, + XMaterial.CAVE_AIR, + XMaterial.VOID_AIR) + .filter(XMaterial::isSupported) + .map(XMaterial::get) + .collect(Collectors.toCollection(() -> EnumSet.noneOf(Material.class))); + public static boolean isElytra(@Nullable ItemStack itemStack) { return itemStack != null && itemStack.getType() == XMaterial.ELYTRA.get(); } @@ -170,8 +178,9 @@ public static boolean isPlayerHead(ItemStack itemStack) { return true; if (itemStack.getItemMeta() instanceof BlockStateMeta) { BlockStateMeta blockStateMeta = (BlockStateMeta) itemStack.getItemMeta(); - if (blockStateMeta.hasBlockState() && blockStateMeta.getBlockState() instanceof Skull) + if (blockStateMeta.hasBlockState() && blockStateMeta.getBlockState() instanceof Skull) { return ((Skull) blockStateMeta.getBlockState()).getSkullType() == SkullType.PLAYER; + } } return false; }