Skip to content

Commit

Permalink
improved custom config manager handling
Browse files Browse the repository at this point in the history
  • Loading branch information
AoElite committed Oct 22, 2024
1 parent bfd3433 commit a65f244
Show file tree
Hide file tree
Showing 13 changed files with 225 additions and 145 deletions.
8 changes: 2 additions & 6 deletions src/main/java/ac/grim/grimac/GrimAPI.java
Original file line number Diff line number Diff line change
@@ -1,38 +1,34 @@
package ac.grim.grimac;

import ac.grim.grimac.api.GrimAbstractAPI;
import ac.grim.grimac.manager.*;
import ac.grim.grimac.manager.config.BaseConfigManager;
import ac.grim.grimac.utils.anticheat.PlayerDataManager;
import lombok.Getter;
import org.bukkit.Bukkit;
import org.bukkit.plugin.ServicePriority;
import org.bukkit.plugin.java.JavaPlugin;

@Getter
public enum GrimAPI {
INSTANCE;

private final BaseConfigManager configManager = new BaseConfigManager();
private final AlertManagerImpl alertManager = new AlertManagerImpl();
private final SpectateManager spectateManager = new SpectateManager();
private final DiscordManager discordManager = new DiscordManager();
private final PlayerDataManager playerDataManager = new PlayerDataManager();
private final TickManager tickManager = new TickManager();
private final GrimExternalAPI externalAPI = new GrimExternalAPI(this);
private InitManager initManager;
private ConfigManagerImpl configManager;
private JavaPlugin plugin;

public void load(final JavaPlugin plugin) {
this.plugin = plugin;
this.configManager = new ConfigManagerImpl();
initManager = new InitManager();
initManager.load();
}

public void start(final JavaPlugin plugin) {
this.plugin = plugin;
initManager.start();
Bukkit.getServicesManager().register(GrimAbstractAPI.class, externalAPI, plugin, ServicePriority.Normal);
}

public void stop(final JavaPlugin plugin) {
Expand Down
77 changes: 54 additions & 23 deletions src/main/java/ac/grim/grimac/GrimExternalAPI.java
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
package ac.grim.grimac;

import ac.grim.grimac.api.AbstractCheck;
import ac.grim.grimac.api.GrimAbstractAPI;
import ac.grim.grimac.api.GrimUser;
import ac.grim.grimac.api.alerts.AlertManager;
import ac.grim.grimac.api.config.ConfigManager;
import ac.grim.grimac.api.events.GrimReloadEvent;
import ac.grim.grimac.manager.config.ConfigManagerFileImpl;
import ac.grim.grimac.manager.init.Initable;
import ac.grim.grimac.player.GrimPlayer;
import ac.grim.grimac.utils.anticheat.LogUtil;
import ac.grim.grimac.utils.common.ConfigReloadObserver;
import com.github.retrooper.packetevents.netty.channel.ChannelHelper;
import io.github.retrooper.packetevents.util.SpigotReflectionUtil;
Expand All @@ -17,6 +18,7 @@
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.ServicePriority;
import org.jetbrains.annotations.Nullable;

import java.util.Map;
Expand Down Expand Up @@ -113,25 +115,29 @@ public ConfigManager getConfigManager() {
}

private ConfigManager configManager = null;
private final ConfigManagerFileImpl configManagerFile = new ConfigManagerFileImpl();
private boolean started = false;

// on load, load the config & register the service
public void load() {
reload(configManagerFile);
Bukkit.getServicesManager().register(GrimAbstractAPI.class, this, GrimAPI.INSTANCE.getPlugin(), ServicePriority.Normal);
}

// handles any config loading that's needed to be done after load
@Override
public void start() {
if (configManager == null) configManager = GrimAPI.INSTANCE.getConfigManager();
variableReplacements.put("%player%", GrimUser::getName);
variableReplacements.put("%uuid%", user -> user.getUniqueId().toString());
variableReplacements.put("%ping%", user -> user.getTransactionPing() + "");
variableReplacements.put("%brand%", GrimUser::getBrand);
variableReplacements.put("%h_sensitivity%", user -> ((int) Math.round(user.getHorizontalSensitivity() * 200)) + "");
variableReplacements.put("%v_sensitivity%", user -> ((int) Math.round(user.getVerticalSensitivity() * 200)) + "");
variableReplacements.put("%fast_math%", user -> !user.isVanillaMath() + "");
variableReplacements.put("%tps%", user -> String.format("%.2f", SpigotReflectionUtil.getTPS()));
variableReplacements.put("%version%", GrimUser::getVersionName);
variableReplacements.put("%prefix%", user -> ChatColor.translateAlternateColorCodes('&', GrimAPI.INSTANCE.getConfigManager().getConfig().getStringElse("prefix", "&bGrim &8»")));
started = true;
try {
GrimAPI.INSTANCE.getConfigManager().start();
} catch (Exception e) {
e.printStackTrace();
}
}

@Override
public void reload(ConfigManager config) {
if (config.isLoadedAsync()) {
if (config.isLoadedAsync() && started) {
FoliaScheduler.getAsyncScheduler().runNow(GrimAPI.INSTANCE.getPlugin(),
o -> successfulReload(config));
} else {
Expand All @@ -141,7 +147,7 @@ public void reload(ConfigManager config) {

@Override
public CompletableFuture<Boolean> reloadAsync(ConfigManager config) {
if (config.isLoadedAsync()) {
if (config.isLoadedAsync() && started) {
CompletableFuture<Boolean> future = new CompletableFuture<>();
FoliaScheduler.getAsyncScheduler().runNow(GrimAPI.INSTANCE.getPlugin(),
o -> future.complete(successfulReload(config)));
Expand All @@ -153,32 +159,57 @@ public CompletableFuture<Boolean> reloadAsync(ConfigManager config) {
private boolean successfulReload(ConfigManager config) {
try {
config.reload();
GrimAPI.INSTANCE.getConfigManager().load(config);
if (started) GrimAPI.INSTANCE.getConfigManager().start();
onReload(config);
FoliaScheduler.getAsyncScheduler().runNow(GrimAPI.INSTANCE.getPlugin(),
if (started) FoliaScheduler.getAsyncScheduler().runNow(GrimAPI.INSTANCE.getPlugin(),
o -> Bukkit.getPluginManager().callEvent(new GrimReloadEvent(true)));
return true;
} catch (Exception e) {
e.printStackTrace();
}
FoliaScheduler.getAsyncScheduler().runNow(GrimAPI.INSTANCE.getPlugin(),
if (started) FoliaScheduler.getAsyncScheduler().runNow(GrimAPI.INSTANCE.getPlugin(),
o -> Bukkit.getPluginManager().callEvent(new GrimReloadEvent(false)));
return false;
}

@Override
public void onReload(ConfigManager newConfig) {
configManager = newConfig != null ? newConfig : configManager;
//Reload checks for all players
if (newConfig == null) {
LogUtil.warn("ConfigManager not set. Using default config file manager.");
configManager = configManagerFile;
} else {
configManager = newConfig;
}
// Update variables
updateVariables();
// Restart
GrimAPI.INSTANCE.getDiscordManager().start();
GrimAPI.INSTANCE.getSpectateManager().start();
// Don't reload players if the plugin hasn't started yet
if (!started) return;
// Reload checks for all players
for (GrimPlayer grimPlayer : GrimAPI.INSTANCE.getPlayerDataManager().getEntries()) {
ChannelHelper.runInEventLoop(grimPlayer.user.getChannel(), () -> {
grimPlayer.reload(configManager);
grimPlayer.updatePermissions();
grimPlayer.reload(configManager);
});
}
//Restart
GrimAPI.INSTANCE.getDiscordManager().start();
GrimAPI.INSTANCE.getSpectateManager().start();
GrimAPI.INSTANCE.getExternalAPI().start();
}

private void updateVariables() {
variableReplacements.putIfAbsent("%player%", GrimUser::getName);
variableReplacements.putIfAbsent("%uuid%", user -> user.getUniqueId().toString());
variableReplacements.putIfAbsent("%ping%", user -> user.getTransactionPing() + "");
variableReplacements.putIfAbsent("%brand%", GrimUser::getBrand);
variableReplacements.putIfAbsent("%h_sensitivity%", user -> ((int) Math.round(user.getHorizontalSensitivity() * 200)) + "");
variableReplacements.putIfAbsent("%v_sensitivity%", user -> ((int) Math.round(user.getVerticalSensitivity() * 200)) + "");
variableReplacements.putIfAbsent("%fast_math%", user -> !user.isVanillaMath() + "");
variableReplacements.putIfAbsent("%tps%", user -> String.format("%.2f", SpigotReflectionUtil.getTPS()));
variableReplacements.putIfAbsent("%version%", GrimUser::getVersionName);
// static variables
staticReplacements.putIfAbsent("%prefix%", ChatColor.translateAlternateColorCodes('&', GrimAPI.INSTANCE.getConfigManager().getPrefix()));
staticReplacements.putIfAbsent("%grim_version%", getGrimVersion());
}

}
2 changes: 1 addition & 1 deletion src/main/java/ac/grim/grimac/checks/Check.java
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ public final boolean flagAndAlert() {
}

public final boolean flag() {
if (player.disableGrim || (experimental && !GrimAPI.INSTANCE.getConfigManager().isExperimentalChecks()) || exempted)
if (player.disableGrim || (experimental && !player.isExperimentalChecks()) || exempted)
return false; // Avoid calling event if disabled

FlagEvent event = new FlagEvent(player, this);
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/ac/grim/grimac/commands/GrimSendAlert.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public void sendAlert(String string) {
bukkitPlayer.sendMessage(string);
}

if (GrimAPI.INSTANCE.getConfigManager().getConfig().getBooleanElse("alerts.print-to-console", true)) {
if (GrimAPI.INSTANCE.getConfigManager().isPrintAlertsToConsole()) {
LogUtil.console(string); // Print alert to console
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -348,7 +348,7 @@ private boolean isMojangStupid(GrimPlayer player, WrapperPlayClientPlayerFlying
// Additionally, only yaw/pitch matters: https://github.com/GrimAnticheat/Grim/issues/1275#issuecomment-1872444018
// 1.9+ isn't impacted by this packet as much.
if (PacketEvents.getAPI().getServerManager().getVersion().isOlderThanOrEquals(ServerVersion.V_1_9)) {
if (GrimAPI.INSTANCE.getConfigManager().getConfig().getBooleanElse("cancel-duplicate-packet", true)) {
if (player.isCancelDuplicatePacket()) {
player.packetStateData.cancelDuplicatePacket = true;
}
} else {
Expand All @@ -358,7 +358,7 @@ private boolean isMojangStupid(GrimPlayer player, WrapperPlayClientPlayerFlying

player.packetStateData.lastPacketWasOnePointSeventeenDuplicate = true;

if (!GrimAPI.INSTANCE.getConfigManager().isIgnoreDuplicatePacketRotation()) {
if (!player.isIgnoreDuplicatePacketRotation()) {
if (player.xRot != location.getYaw() || player.yRot != location.getPitch()) {
player.lastXRot = player.xRot;
player.lastYRot = player.yRot;
Expand Down Expand Up @@ -428,7 +428,7 @@ public void onPacketReceive(PacketReceiveEvent event) {
if (WrapperPlayClientPlayerFlying.isFlying(event.getPacketType())) {
WrapperPlayClientPlayerFlying flying = new WrapperPlayClientPlayerFlying(event);
Location pos = flying.getLocation();
boolean ignoreRotation = player.packetStateData.lastPacketWasOnePointSeventeenDuplicate && GrimAPI.INSTANCE.getConfigManager().isIgnoreDuplicatePacketRotation();
boolean ignoreRotation = player.packetStateData.lastPacketWasOnePointSeventeenDuplicate && player.isIgnoreDuplicatePacketRotation();
handleFlying(player, pos.getX(), pos.getY(), pos.getZ(), ignoreRotation ? player.xRot : pos.getYaw(), ignoreRotation ? player.yRot : pos.getPitch(), flying.hasPositionChanged(), flying.hasRotationChanged(), flying.isOnGround(), teleportData, event);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package ac.grim.grimac.events.packets;

import ac.grim.grimac.GrimAPI;
import ac.grim.grimac.api.config.ConfigManager;
import ac.grim.grimac.checks.Check;
import ac.grim.grimac.checks.type.PacketCheck;
import ac.grim.grimac.player.GrimPlayer;
Expand Down Expand Up @@ -53,7 +53,6 @@ public class PacketEntityReplication extends Check implements PacketCheck {
private final List<Integer> despawnedEntitiesThisTransaction = new ArrayList<>();

// Maximum ping when a firework boost is removed from the player.
private final int maxFireworkBoostPing = GrimAPI.INSTANCE.getConfigManager().getConfig().getIntElse("max-ping-firework-boost", 1000);

public PacketEntityReplication(GrimPlayer player) {
super(player);
Expand Down Expand Up @@ -500,4 +499,12 @@ public void onEndOfTickEvent() {
public void tickStartTick() {
hasSentPreWavePacket = false;
}

private int maxFireworkBoostPing = 1000;

@Override
public void onReload(ConfigManager config) {
maxFireworkBoostPing = config.getIntElse("max-ping-firework-boost", 1000);
}

}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package ac.grim.grimac.events.packets;

import ac.grim.grimac.GrimAPI;
import ac.grim.grimac.api.config.ConfigManager;
import ac.grim.grimac.checks.Check;
import ac.grim.grimac.checks.type.PacketCheck;
import ac.grim.grimac.player.GrimPlayer;
Expand Down Expand Up @@ -37,7 +37,6 @@ public void onPacketSend(PacketSendEvent event) {

if (lastSentPlayerCanFly && !abilities.isFlightAllowed()) {
int noFlying = player.lastTransactionSent.get();
int maxFlyingPing = GrimAPI.INSTANCE.getConfigManager().getConfig().getIntElse("max-ping-out-of-flying", 1000);
if (maxFlyingPing != -1) {
player.runNettyTaskInMs(() -> {
if (player.lastTransactionReceived.get() < noFlying) {
Expand All @@ -56,4 +55,12 @@ public void onPacketSend(PacketSendEvent event) {

}
}

int maxFlyingPing = 1000;

@Override
public void onReload(ConfigManager config) {
maxFlyingPing = config.getIntElse("max-ping-out-of-flying", 1000);
}

}
69 changes: 36 additions & 33 deletions src/main/java/ac/grim/grimac/manager/InitManager.java
Original file line number Diff line number Diff line change
@@ -1,69 +1,72 @@
package ac.grim.grimac.manager;

import ac.grim.grimac.GrimAPI;
import ac.grim.grimac.GrimExternalAPI;
import ac.grim.grimac.manager.init.Initable;
import ac.grim.grimac.manager.init.load.PacketEventsInit;
import ac.grim.grimac.manager.init.start.*;
import ac.grim.grimac.manager.init.stop.TerminatePacketEvents;
import com.google.common.collect.ClassToInstanceMap;
import com.google.common.collect.ImmutableClassToInstanceMap;
import com.google.common.collect.ImmutableList;
import lombok.Getter;

public class InitManager {
private final ClassToInstanceMap<Initable> initializersOnLoad;
private final ClassToInstanceMap<Initable> initializersOnStart;
private final ClassToInstanceMap<Initable> initializersOnStop;

private final ImmutableList<Initable> initializersOnLoad;
private final ImmutableList<Initable> initializersOnStart;
private final ImmutableList<Initable> initializersOnStop;

@Getter private boolean loaded = false;
@Getter private boolean started = false;
@Getter private boolean stopped = false;

public InitManager() {
initializersOnLoad = new ImmutableClassToInstanceMap.Builder<Initable>()
.put(PacketEventsInit.class, new PacketEventsInit())
initializersOnLoad = ImmutableList.<Initable>builder()
.add(new PacketEventsInit())
.add(() -> GrimAPI.INSTANCE.getExternalAPI().load())
.build();

initializersOnStart = new ImmutableClassToInstanceMap.Builder<Initable>()
.put(GrimExternalAPI.class, GrimAPI.INSTANCE.getExternalAPI())
.put(ExemptOnlinePlayers.class, new ExemptOnlinePlayers())
.put(EventManager.class, new EventManager())
.put(PacketManager.class, new PacketManager())
.put(ViaBackwardsManager.class, new ViaBackwardsManager())
.put(TickRunner.class, new TickRunner())
.put(TickEndEvent.class, new TickEndEvent())
.put(CommandRegister.class, new CommandRegister())
.put(BStats.class, new BStats())
.put(PacketLimiter.class, new PacketLimiter())
.put(DiscordManager.class, GrimAPI.INSTANCE.getDiscordManager())
.put(SpectateManager.class, GrimAPI.INSTANCE.getSpectateManager())
.put(JavaVersion.class, new JavaVersion())
.put(ViaVersion.class, new ViaVersion())
initializersOnStart = ImmutableList.<Initable>builder()
.add(GrimAPI.INSTANCE.getExternalAPI())
.add(new ExemptOnlinePlayers())
.add(new EventManager())
.add(new PacketManager())
.add(new ViaBackwardsManager())
.add(new TickRunner())
.add(new TickEndEvent())
.add(new CommandRegister())
.add(new BStats())
.add(new PacketLimiter())
.add(GrimAPI.INSTANCE.getDiscordManager())
.add(GrimAPI.INSTANCE.getSpectateManager())
.add(new JavaVersion())
.add(new ViaVersion())
.build();

initializersOnStop = new ImmutableClassToInstanceMap.Builder<Initable>()
.put(TerminatePacketEvents.class, new TerminatePacketEvents())
initializersOnStop = ImmutableList.<Initable>builder()
.add(new TerminatePacketEvents())
.build();
}

public void load() {
for (Initable initable : initializersOnLoad.values()) {
initable.start();
}
for (Initable initable : initializersOnLoad) handle(initable);
loaded = true;
}

public void start() {
for (Initable initable : initializersOnStart.values()) {
initable.start();
}
for (Initable initable : initializersOnStart) handle(initable);
started = true;
}

public void stop() {
for (Initable initable : initializersOnStop.values()) {
for (Initable initable : initializersOnStop) handle(initable);
stopped = true;
}

private void handle(Initable initable) {
try {
initable.start();
} catch (Exception e) {
e.printStackTrace();
}
stopped = true;
}

}
Loading

0 comments on commit a65f244

Please sign in to comment.