Skip to content

Commit

Permalink
Serializers, common code extraction, code style improvements, update …
Browse files Browse the repository at this point in the history
…gradle and dependencies, etc.
  • Loading branch information
mdxd44 committed Apr 20, 2022
1 parent f6f4ef4 commit 4d231bb
Show file tree
Hide file tree
Showing 23 changed files with 560 additions and 1,056 deletions.
10 changes: 5 additions & 5 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,16 @@ jobs:
fail-fast: true
steps:
- name: Checkout
uses: actions/checkout@v2.4.0
uses: actions/checkout@v3.0.1
- name: Set up JDK ${{ matrix.java }}
uses: actions/setup-java@v2.5.0
uses: actions/setup-java@v3.1.1
with:
distribution: adopt
java-version: ${{ matrix.java }}
- name: Build LimboFilter
run: ./gradlew build
- name: Upload LimboFilter
uses: actions/upload-artifact@v2.3.1
uses: actions/upload-artifact@v3.0.0
with:
name: LimboFilter Built On ${{ matrix.java }} JDK
path: "build/libs/limbofilter*.jar"
Expand All @@ -31,10 +31,10 @@ jobs:
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Release the build
uses: ncipollo/release-action@v1
uses: ncipollo/release-action@v1.10.0
with:
artifacts: "build/libs/limbofilter*.jar"
body: ${{ join(github.event.commits.*.message, '\n') }}
prerelease: true
name: JDK ${{ matrix.java }} Dev-build
tag: dev-build-jdk-${{ matrix.java }}
tag: dev-build-jdk-${{ matrix.java }}
25 changes: 1 addition & 24 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,32 +1,15 @@
# User-specific stuff
# IntelliJ user-specific stuff
.idea/

*.iml
*.ipr
*.iws

# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/

# JIRA plugin
atlassian-ide-plugin.xml

# Compiled class file
*.class

# Log file
*.log

# BlueJ files
*.ctxt

# Package Files
*.jar
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar
Expand Down Expand Up @@ -104,12 +87,6 @@ $RECYCLE.BIN/
.gradle
build/

# Ignore Gradle GUI config
gradle-app.setting

# Cache of project
.gradletasknamecache

# Gradle Patch
**/build/

Expand Down
14 changes: 6 additions & 8 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
plugins {
id("java")
id("checkstyle")
id("com.github.spotbugs").version("5.0.5")
id("com.github.spotbugs").version("5.0.6")
id("org.cadixdev.licenser").version("0.6.1")
id("com.github.johnrengelman.shadow").version("7.1.2")
}
Expand Down Expand Up @@ -38,10 +38,10 @@ dependencies {

compileOnly("com.velocitypowered:velocity-api:3.1.2-SNAPSHOT")
annotationProcessor("com.velocitypowered:velocity-api:3.1.2-SNAPSHOT")
compileOnly("com.velocitypowered:velocity-proxy:3.1.2-SNAPSHOT") // From Elytrium Repo
compileOnly("com.velocitypowered:velocity-proxy:3.1.2-SNAPSHOT") // From Elytrium Repo.

// Needs for some velocity methods
compileOnly("io.netty:netty-codec:4.1.75.Final")
// Needs for some velocity methods.
compileOnly("io.netty:netty-codec:4.1.76.Final")

implementation("org.bstats:bstats-velocity:3.0.0")

Expand All @@ -51,17 +51,15 @@ dependencies {
shadowJar {
getArchiveClassifier().set("")

// Why are we increasing the size of the plugin if we can do that? :thinking:
relocate("org.bstats", "net.elytrium.limboapi.thirdparty.org.bstats")
exclude("org/bstats/**")
relocate("org.bstats", "net.elytrium.limbofilter.thirdparty.org.bstats")
}

license {
setHeader(file("HEADER.txt"))
}

checkstyle {
setToolVersion("9.2.1")
setToolVersion("10.1")
setConfigFile(file("${this.getRootDir()}/config/checkstyle/checkstyle.xml"))
setConfigProperties("configDirectory": "${this.getRootDir()}/config/checkstyle")

Expand Down
1 change: 0 additions & 1 deletion config/checkstyle/checkstyle.xml
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@

<module name="TreeWalker">
<module name="MissingOverride"/>
<module name="FinalClass"/>
<module name="RedundantImport"/>
<module name="UnusedImports"/>
<module name="RequireThis">
Expand Down
Binary file modified gradle/wrapper/gradle-wrapper.jar
Binary file not shown.
2 changes: 1 addition & 1 deletion gradle/wrapper/gradle-wrapper.properties
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
123 changes: 89 additions & 34 deletions src/main/java/net/elytrium/limbofilter/LimboFilter.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,23 @@
import com.velocitypowered.api.plugin.annotation.DataDirectory;
import com.velocitypowered.api.proxy.Player;
import com.velocitypowered.api.proxy.ProxyServer;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOError;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.file.Path;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import net.elytrium.java.commons.mc.serialization.Serializer;
import net.elytrium.java.commons.mc.serialization.Serializers;
import net.elytrium.java.commons.updates.UpdatesChecker;
import net.elytrium.limboapi.api.Limbo;
import net.elytrium.limboapi.api.LimboFactory;
import net.elytrium.limboapi.api.chunk.Dimension;
Expand All @@ -51,7 +59,8 @@
import net.elytrium.limbofilter.handler.BotFilterSessionHandler;
import net.elytrium.limbofilter.listener.FilterListener;
import net.elytrium.limbofilter.stats.Statistics;
import net.elytrium.limbofilter.utils.UpdatesChecker;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.serializer.ComponentSerializer;
import org.bstats.charts.SimplePie;
import org.bstats.charts.SingleLineChart;
import org.bstats.velocity.Metrics;
Expand All @@ -72,10 +81,13 @@
)
public class LimboFilter {

private static Logger logger;
private static Serializer serializer;

private final Map<String, CachedUser> cachedFilterChecks = new ConcurrentHashMap<>();

private final Path dataDirectory;
private final Logger logger;
private final File configFile;
private final Metrics.Factory metricsFactory;
private final ProxyServer server;
private final CachedPackets packets;
Expand All @@ -85,15 +97,16 @@ public class LimboFilter {

private CachedCaptcha cachedCaptcha;
private Limbo filterServer;
private Metrics metrics;
private VirtualWorld filterWorld;

@Inject
public LimboFilter(ProxyServer server, Logger logger, Metrics.Factory metricsFactory, @DataDirectory Path dataDirectory) {
public LimboFilter(Logger logger, ProxyServer server, Metrics.Factory metricsFactory, @DataDirectory Path dataDirectory) {
setLogger(logger);

this.server = server;
this.logger = logger;
this.metricsFactory = metricsFactory;
this.dataDirectory = dataDirectory;
this.configFile = this.dataDirectory.resolve("config.yml").toFile();
this.packets = new CachedPackets();
this.generator = new CaptchaGenerator(this);
this.statistics = new Statistics();
Expand All @@ -103,26 +116,40 @@ public LimboFilter(ProxyServer server, Logger logger, Metrics.Factory metricsFac

@Subscribe
public void onProxyInitialization(ProxyInitializeEvent event) {
this.metrics = this.metricsFactory.make(this, 13699);
Metrics metrics = this.metricsFactory.make(this, 13699);

this.reload();
metrics.addCustomChart(new SimplePie("filter_type", () -> Settings.IMP.MAIN.CHECK_STATE));
metrics.addCustomChart(new SimplePie("load_world", () -> String.valueOf(Settings.IMP.MAIN.LOAD_WORLD)));
metrics.addCustomChart(new SimplePie("check_brand", () -> String.valueOf(Settings.IMP.MAIN.CHECK_CLIENT_BRAND)));
metrics.addCustomChart(new SimplePie("check_settings", () -> String.valueOf(Settings.IMP.MAIN.CHECK_CLIENT_SETTINGS)));
metrics.addCustomChart(new SimplePie("has_backplate", () -> String.valueOf(!Settings.IMP.MAIN.CAPTCHA_GENERATOR.BACKPLATE_PATHS.isEmpty())));

this.metrics.addCustomChart(new SimplePie("filter_type", () -> Settings.IMP.MAIN.CHECK_STATE));
this.metrics.addCustomChart(new SimplePie("load_world", () -> String.valueOf(Settings.IMP.MAIN.LOAD_WORLD)));
this.metrics.addCustomChart(new SimplePie("check_brand", () -> String.valueOf(Settings.IMP.MAIN.CHECK_CLIENT_BRAND)));
this.metrics.addCustomChart(new SimplePie("check_settings", () -> String.valueOf(Settings.IMP.MAIN.CHECK_CLIENT_SETTINGS)));
this.metrics.addCustomChart(new SimplePie("has_backplate", () ->
String.valueOf(!Settings.IMP.MAIN.CAPTCHA_GENERATOR.BACKPLATE_PATHS.isEmpty())));
metrics.addCustomChart(new SingleLineChart("pings", () -> Math.toIntExact(this.statistics.getPings())));
metrics.addCustomChart(new SingleLineChart("connections", () -> Math.toIntExact(this.statistics.getConnections())));

this.metrics.addCustomChart(new SingleLineChart("pings", () -> Math.toIntExact(this.statistics.getPings())));
this.metrics.addCustomChart(new SingleLineChart("connections", () -> Math.toIntExact(this.statistics.getConnections())));
Settings.IMP.setLogger(logger);

UpdatesChecker.checkForUpdates(this.getLogger());
this.reload();

if (!UpdatesChecker.checkVersionByURL("https://raw.githubusercontent.com/Elytrium/LimboFilter/master/VERSION", Settings.IMP.VERSION)) {
logger.error("****************************************");
logger.warn("The new LimboFilter update was found, please update.");
logger.error("https://github.com/Elytrium/LimboFilter/releases/");
logger.error("****************************************");
}
}

@SuppressWarnings("SwitchStatementWithTooFewBranches")
@SuppressFBWarnings(value = "NP_NULL_ON_SOME_PATH", justification = "LEGACY_AMPERSAND can't be null in velocity.")
public void reload() {
Settings.IMP.reload(new File(this.dataDirectory.toFile().getAbsoluteFile(), "config.yml"));
Settings.IMP.reload(this.configFile, Settings.IMP.PREFIX);

ComponentSerializer<Component, Component, String> serializer = Serializers.valueOf(Settings.IMP.SERIALIZER.toUpperCase(Locale.ROOT)).getSerializer();
if (serializer == null) {
logger.warn("The specified serializer could not be founded, using default. (LEGACY_AMPERSAND)");
setSerializer(new Serializer(Objects.requireNonNull(Serializers.LEGACY_AMPERSAND.getSerializer())));
} else {
setSerializer(new Serializer(serializer));
}

BotFilterSessionHandler.setFallingCheckTotalTime(Settings.IMP.MAIN.FALLING_CHECK_TICKS * 50L);

Expand Down Expand Up @@ -164,7 +191,7 @@ public void reload() {
break;
}
default: {
this.logger.error("Incorrect world file type.");
logger.error("Incorrect world file type.");
this.server.shutdown();
return;
}
Expand All @@ -191,8 +218,8 @@ public void reload() {
this.server.getEventManager().unregisterListeners(this);
this.server.getEventManager().register(this, new FilterListener(this));

Executors.newScheduledThreadPool(1, task -> new Thread(task, "purge-cache")).scheduleAtFixedRate(() ->
this.checkCache(this.cachedFilterChecks),
Executors.newScheduledThreadPool(1, task -> new Thread(task, "purge-cache")).scheduleAtFixedRate(
() -> this.checkCache(this.cachedFilterChecks),
Settings.IMP.MAIN.PURGE_CACHE_MILLIS,
Settings.IMP.MAIN.PURGE_CACHE_MILLIS,
TimeUnit.MILLISECONDS
Expand All @@ -202,8 +229,10 @@ public void reload() {
public void cacheFilterUser(Player player) {
String username = player.getUsername();
this.cachedFilterChecks.remove(username);
this.cachedFilterChecks.put(username,
new CachedUser(player.getRemoteAddress().getAddress(), System.currentTimeMillis() + Settings.IMP.MAIN.PURGE_CACHE_MILLIS));
this.cachedFilterChecks.put(
username,
new CachedUser(player.getRemoteAddress().getAddress(), System.currentTimeMillis() + Settings.IMP.MAIN.PURGE_CACHE_MILLIS)
);
}

public boolean shouldCheck(Player player) {
Expand All @@ -230,41 +259,51 @@ public void sendToFilterServer(Player player) {
try {
this.filterServer.spawnPlayer(player, new BotFilterSessionHandler(player, this));
} catch (Throwable t) {
this.logger.error("Error", t);
logger.error("Error", t);
}
}

private void checkCache(Map<String, CachedUser> userMap) {
userMap.entrySet().stream()
.filter(u -> u.getValue().getCheckTime() <= System.currentTimeMillis())
.filter(user -> user.getValue().getCheckTime() <= System.currentTimeMillis())
.map(Map.Entry::getKey)
.forEach(userMap::remove);
}

public boolean checkCpsLimit(int limit) {
if (limit == -1) {
if (limit != -1) {
return limit <= this.statistics.getConnections();
} else {
return false;
}

return limit <= this.statistics.getConnections();
}

public boolean checkPpsLimit(int limit) {
if (limit == -1) {
if (limit != -1) {
return limit <= this.statistics.getPings();
} else {
return false;
}
}

return limit <= this.statistics.getPings();
public File getFile(String filename) {
File dataDirectoryFile = this.dataDirectory.resolve(filename).toFile();
if (dataDirectoryFile.exists()) {
return dataDirectoryFile;
} else {
File rootFile = new File(filename);
if (rootFile.exists()) {
return rootFile;
} else {
throw new IOError(new FileNotFoundException("File " + filename + "cannot be founded!"));
}
}
}

public ProxyServer getServer() {
return this.server;
}

public Logger getLogger() {
return this.logger;
}

public LimboFactory getFactory() {
return this.factory;
}
Expand All @@ -285,6 +324,22 @@ public VirtualWorld getFilterWorld() {
return this.filterWorld;
}

private static void setLogger(Logger logger) {
LimboFilter.logger = logger;
}

public static Logger getLogger() {
return logger;
}

private static void setSerializer(Serializer serializer) {
LimboFilter.serializer = serializer;
}

public static Serializer getSerializer() {
return serializer;
}

private static class CachedUser {

private final InetAddress inetAddress;
Expand Down
Loading

0 comments on commit 4d231bb

Please sign in to comment.