diff --git a/buildSrc/src/main/kotlin/packetevents.shadow-conventions.gradle.kts b/buildSrc/src/main/kotlin/packetevents.shadow-conventions.gradle.kts
index 890a250722..90ec2a9693 100644
--- a/buildSrc/src/main/kotlin/packetevents.shadow-conventions.gradle.kts
+++ b/buildSrc/src/main/kotlin/packetevents.shadow-conventions.gradle.kts
@@ -13,6 +13,8 @@ tasks {
relocate("net.kyori.adventure.text.serializer", "io.github.retrooper.packetevents.adventure.serializer")
relocate("net.kyori.option", "io.github.retrooper.packetevents.adventure.option")
+ relocate("org.bstats", "io.github.retrooper.packetevents.bstats")
+
dependencies {
exclude(dependency("com.google.code.gson:gson:.*"))
}
diff --git a/bungeecord/build.gradle.kts b/bungeecord/build.gradle.kts
index c5547cff38..68ba9b6aaa 100644
--- a/bungeecord/build.gradle.kts
+++ b/bungeecord/build.gradle.kts
@@ -10,6 +10,7 @@ repositories {
dependencies {
compileOnly(libs.bungeecord)
shadow(libs.bundles.adventure)
+ shadow(libs.bstats.bungeecord)
shadow(project(":api", "shadow"))
shadow(project(":netty-common"))
}
diff --git a/bungeecord/src/main/java/io/github/retrooper/packetevents/bstats/Metrics.java b/bungeecord/src/main/java/io/github/retrooper/packetevents/bstats/Metrics.java
deleted file mode 100644
index 3b5710dfc5..0000000000
--- a/bungeecord/src/main/java/io/github/retrooper/packetevents/bstats/Metrics.java
+++ /dev/null
@@ -1,758 +0,0 @@
-package io.github.retrooper.packetevents.bstats;
-
-import com.google.gson.JsonArray;
-import com.google.gson.JsonObject;
-import com.google.gson.JsonPrimitive;
-import net.md_5.bungee.api.plugin.Plugin;
-import net.md_5.bungee.config.Configuration;
-import net.md_5.bungee.config.ConfigurationProvider;
-import net.md_5.bungee.config.YamlConfiguration;
-
-import javax.net.ssl.HttpsURLConnection;
-import java.io.*;
-import java.lang.reflect.InvocationTargetException;
-import java.net.URL;
-import java.nio.charset.StandardCharsets;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.UUID;
-import java.util.concurrent.Callable;
-import java.util.concurrent.TimeUnit;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-import java.util.zip.GZIPOutputStream;
-
-//This file was taken from bStats https://github.com/Bastian/bStats-Metrics
-/**
- * bStats collects some data for plugin authors.
- *
- * Check out https://bStats.org/ to learn more about bStats!
- */
-@SuppressWarnings({"WeakerAccess", "unused"})
-public class Metrics {
-
- static {
- // You can use the property to disable the check in your test environment
- if (System.getProperty("bstats.relocatecheck") == null || !System.getProperty("bstats.relocatecheck").equals("false")) {
- // Maven's Relocate is clever and changes strings, too. So we have to use this little "trick" ... :D
- final String defaultPackage = new String(
- new byte[]{'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's', '.', 'b', 'u', 'n', 'g', 'e', 'e', 'c', 'o', 'r', 'd'});
- final String examplePackage = new String(new byte[]{'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'});
- // We want to make sure nobody just copy & pastes the example and use the wrong package names
- if (Metrics.class.getPackage().getName().equals(defaultPackage) || Metrics.class.getPackage().getName().equals(examplePackage)) {
- throw new IllegalStateException("bStats Metrics class has not been relocated correctly!");
- }
- }
- }
-
- // The version of this bStats class
- public static final int B_STATS_VERSION = 1;
-
- // The url to which the data is sent
- private static final String URL = "https://bStats.org/submitData/bungeecord";
-
- // The plugin
- private final Plugin plugin;
-
- // The plugin id
- private final int pluginId;
-
- // Is bStats enabled on this server?
- private boolean enabled;
-
- // The uuid of the server
- private String serverUUID;
-
- // Should failed requests be logged?
- private boolean logFailedRequests = false;
-
- // Should the sent data be logged?
- private static boolean logSentData;
-
- // Should the response text be logged?
- private static boolean logResponseStatusText;
-
- // A list with all known metrics class objects including this one
- private static final List knownMetricsInstances = new ArrayList<>();
-
- // A list with all custom charts
- private final List charts = new ArrayList<>();
-
- /**
- * Class constructor.
- *
- * @param plugin The plugin which stats should be submitted.
- * @param pluginId The id of the plugin.
- * It can be found at What is my plugin id?
- */
- public Metrics(Plugin plugin, int pluginId) {
- this.plugin = plugin;
- this.pluginId = pluginId;
-
- try {
- loadConfig();
- } catch (IOException e) {
- // Failed to load configuration
- plugin.getLogger().log(Level.WARNING, "Failed to load bStats config!", e);
- return;
- }
-
- // We are not allowed to send data about this server :(
- if (!enabled) {
- return;
- }
-
- Class> usedMetricsClass = getFirstBStatsClass();
- if (usedMetricsClass == null) {
- // Failed to get first metrics class
- return;
- }
- if (usedMetricsClass == getClass()) {
- // We are the first! :)
- linkMetrics(this);
- startSubmitting();
- } else {
- // We aren't the first so we link to the first metrics class
- try {
- usedMetricsClass.getMethod("linkMetrics", Object.class).invoke(null, this);
- } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
- if (logFailedRequests) {
- plugin.getLogger().log(Level.WARNING, "Failed to link to first metrics class " + usedMetricsClass.getName() + "!", e);
- }
- }
- }
- }
-
- /**
- * Checks if bStats is enabled.
- *
- * @return Whether bStats is enabled or not.
- */
- public boolean isEnabled() {
- return enabled;
- }
-
- /**
- * Adds a custom chart.
- *
- * @param chart The chart to add.
- */
- public void addCustomChart(CustomChart chart) {
- if (chart == null) {
- plugin.getLogger().log(Level.WARNING, "Chart cannot be null");
- }
- charts.add(chart);
- }
-
- /**
- * Links an other metrics class with this class.
- * This method is called using Reflection.
- *
- * @param metrics An object of the metrics class to link.
- */
- public static void linkMetrics(Object metrics) {
- knownMetricsInstances.add(metrics);
- }
-
- /**
- * Gets the plugin specific data.
- * This method is called using Reflection.
- *
- * @return The plugin specific data.
- */
- public JsonObject getPluginData() {
- JsonObject data = new JsonObject();
-
- String pluginName = plugin.getDescription().getName();
- String pluginVersion = plugin.getDescription().getVersion();
-
- data.addProperty("pluginName", pluginName);
- data.addProperty("id", pluginId);
- data.addProperty("pluginVersion", pluginVersion);
-
- JsonArray customCharts = new JsonArray();
- for (CustomChart customChart : charts) {
- // Add the data of the custom charts
- JsonObject chart = customChart.getRequestJsonObject(plugin.getLogger(), logFailedRequests);
- if (chart == null) { // If the chart is null, we skip it
- continue;
- }
- customCharts.add(chart);
- }
- data.add("customCharts", customCharts);
-
- return data;
- }
-
- private void startSubmitting() {
- // Many servers tend to restart at a fixed time at xx:00 which causes an uneven distribution of requests on the
- // bStats backend. To circumvent this problem, we introduce some randomness into the initial and second delay.
- // WARNING: You must not modify and part of this Metrics class, including the submit delay or frequency!
- // WARNING: Modifying this code will get your plugin banned on bStats. Just don't do it!
- long initialDelay = (long) (1000 * 60 * (3 + Math.random() * 3));
- long secondDelay = (long) (1000 * 60 * (Math.random() * 30));
- plugin.getProxy().getScheduler().schedule(plugin, this::submitData, initialDelay, TimeUnit.MILLISECONDS);
- plugin.getProxy().getScheduler().schedule(
- plugin, this::submitData, initialDelay + secondDelay, 1000 * 60 * 30, TimeUnit.MILLISECONDS);
- }
-
- /**
- * Gets the server specific data.
- *
- * @return The server specific data.
- */
- private JsonObject getServerData() {
- // Minecraft specific data
- int playerAmount = Math.min(plugin.getProxy().getOnlineCount(), 500);
- int onlineMode = plugin.getProxy().getConfig().isOnlineMode() ? 1 : 0;
- String bungeecordVersion = plugin.getProxy().getVersion();
- int managedServers = plugin.getProxy().getServers().size();
-
- // OS/Java specific data
- String javaVersion = System.getProperty("java.version");
- String osName = System.getProperty("os.name");
- String osArch = System.getProperty("os.arch");
- String osVersion = System.getProperty("os.version");
- int coreCount = Runtime.getRuntime().availableProcessors();
-
- JsonObject data = new JsonObject();
-
- data.addProperty("serverUUID", serverUUID);
-
- data.addProperty("playerAmount", playerAmount);
- data.addProperty("managedServers", managedServers);
- data.addProperty("onlineMode", onlineMode);
- data.addProperty("bungeecordVersion", bungeecordVersion);
-
- data.addProperty("javaVersion", javaVersion);
- data.addProperty("osName", osName);
- data.addProperty("osArch", osArch);
- data.addProperty("osVersion", osVersion);
- data.addProperty("coreCount", coreCount);
-
- return data;
- }
-
- /**
- * Collects the data and sends it afterwards.
- */
- private void submitData() {
- final JsonObject data = getServerData();
-
- final JsonArray pluginData = new JsonArray();
- // Search for all other bStats Metrics classes to get their plugin data
- for (Object metrics : knownMetricsInstances) {
- try {
- Object plugin = metrics.getClass().getMethod("getPluginData").invoke(metrics);
- if (plugin instanceof JsonObject) {
- pluginData.add((JsonObject) plugin);
- }
- } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { }
- }
-
- data.add("plugins", pluginData);
-
- try {
- // Send the data
- sendData(plugin, data);
- } catch (Exception e) {
- // Something went wrong! :(
- if (logFailedRequests) {
- plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats!", e);
- }
- }
- }
-
- /**
- * Loads the bStats configuration.
- *
- * @throws IOException If something did not work :(
- */
- private void loadConfig() throws IOException {
- File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats");
- bStatsFolder.mkdirs();
- File configFile = new File(bStatsFolder, "config.yml");
- if (!configFile.exists()) {
- writeFile(configFile,
- "#bStats collects some data for plugin authors like how many servers are using their plugins.",
- "#To honor their work, you should not disable it.",
- "#This has nearly no effect on the server performance!",
- "#Check out https://bStats.org/ to learn more :)",
- "enabled: true",
- "serverUuid: \"" + UUID.randomUUID() + "\"",
- "logFailedRequests: false",
- "logSentData: false",
- "logResponseStatusText: false");
- }
-
- Configuration configuration = ConfigurationProvider.getProvider(YamlConfiguration.class).load(configFile);
-
- // Load configuration
- enabled = configuration.getBoolean("enabled", true);
- serverUUID = configuration.getString("serverUuid");
- logFailedRequests = configuration.getBoolean("logFailedRequests", false);
- logSentData = configuration.getBoolean("logSentData", false);
- logResponseStatusText = configuration.getBoolean("logResponseStatusText", false);
- }
-
- /**
- * Gets the first bStat Metrics class.
- *
- * @return The first bStats metrics class.
- */
- private Class> getFirstBStatsClass() {
- File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats");
- bStatsFolder.mkdirs();
- File tempFile = new File(bStatsFolder, "temp.txt");
-
- try {
- String className = readFile(tempFile);
- if (className != null) {
- try {
- // Let's check if a class with the given name exists.
- return Class.forName(className);
- } catch (ClassNotFoundException ignored) { }
- }
- writeFile(tempFile, getClass().getName());
- return getClass();
- } catch (IOException e) {
- if (logFailedRequests) {
- plugin.getLogger().log(Level.WARNING, "Failed to get first bStats class!", e);
- }
- return null;
- }
- }
-
- /**
- * Reads the first line of the file.
- *
- * @param file The file to read. Cannot be null.
- * @return The first line of the file or {@code null} if the file does not exist or is empty.
- * @throws IOException If something did not work :(
- */
- private String readFile(File file) throws IOException {
- if (!file.exists()) {
- return null;
- }
- try (BufferedReader bufferedReader = new BufferedReader(new FileReader(file))) {
- return bufferedReader.readLine();
- }
- }
-
- /**
- * Writes a String to a file. It also adds a note for the user,
- *
- * @param file The file to write to. Cannot be null.
- * @param lines The lines to write.
- * @throws IOException If something did not work :(
- */
- private void writeFile(File file, String... lines) throws IOException {
- try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file))) {
- for (String line : lines) {
- bufferedWriter.write(line);
- bufferedWriter.newLine();
- }
- }
- }
-
- /**
- * Sends the data to the bStats server.
- *
- * @param plugin Any plugin. It's just used to get a logger instance.
- * @param data The data to send.
- * @throws Exception If the request failed.
- */
- private static void sendData(Plugin plugin, JsonObject data) throws Exception {
- if (data == null) {
- throw new IllegalArgumentException("Data cannot be null");
- }
- if (logSentData) {
- plugin.getLogger().info("Sending data to bStats: " + data);
- }
-
- HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();
-
- // Compress the data to save bandwidth
- byte[] compressedData = compress(data.toString());
-
- // Add headers
- connection.setRequestMethod("POST");
- connection.addRequestProperty("Accept", "application/json");
- connection.addRequestProperty("Connection", "close");
- connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
- connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
- connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
- connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);
-
- // Send data
- connection.setDoOutput(true);
- try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) {
- outputStream.write(compressedData);
- }
-
- StringBuilder builder = new StringBuilder();
-
- try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
- String line;
- while ((line = bufferedReader.readLine()) != null) {
- builder.append(line);
- }
- }
-
- if (logResponseStatusText) {
- plugin.getLogger().info("Sent data to bStats and received response: " + builder);
- }
- }
-
- /**
- * Gzips the given String.
- *
- * @param str The string to gzip.
- * @return The gzipped String.
- * @throws IOException If the compression failed.
- */
- private static byte[] compress(final String str) throws IOException {
- if (str == null) {
- return null;
- }
- ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
- try (GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) {
- gzip.write(str.getBytes(StandardCharsets.UTF_8));
- }
- return outputStream.toByteArray();
- }
-
-
- /**
- * Represents a custom chart.
- */
- public static abstract class CustomChart {
-
- // The id of the chart
- private final String chartId;
-
- /**
- * Class constructor.
- *
- * @param chartId The id of the chart.
- */
- CustomChart(String chartId) {
- if (chartId == null || chartId.isEmpty()) {
- throw new IllegalArgumentException("ChartId cannot be null or empty!");
- }
- this.chartId = chartId;
- }
-
- private JsonObject getRequestJsonObject(Logger logger, boolean logFailedRequests) {
- JsonObject chart = new JsonObject();
- chart.addProperty("chartId", chartId);
- try {
- JsonObject data = getChartData();
- if (data == null) {
- // If the data is null we don't send the chart.
- return null;
- }
- chart.add("data", data);
- } catch (Throwable t) {
- if (logFailedRequests) {
- logger.log(Level.WARNING, "Failed to get data for custom chart with id " + chartId, t);
- }
- return null;
- }
- return chart;
- }
-
- protected abstract JsonObject getChartData() throws Exception;
-
- }
-
- /**
- * Represents a custom simple pie.
- */
- public static class SimplePie extends CustomChart {
-
- private final Callable callable;
-
- /**
- * Class constructor.
- *
- * @param chartId The id of the chart.
- * @param callable The callable which is used to request the chart data.
- */
- public SimplePie(String chartId, Callable callable) {
- super(chartId);
- this.callable = callable;
- }
-
- @Override
- protected JsonObject getChartData() throws Exception {
- JsonObject data = new JsonObject();
- String value = callable.call();
- if (value == null || value.isEmpty()) {
- // Null = skip the chart
- return null;
- }
- data.addProperty("value", value);
- return data;
- }
- }
-
- /**
- * Represents a custom advanced pie.
- */
- public static class AdvancedPie extends CustomChart {
-
- private final Callable> callable;
-
- /**
- * Class constructor.
- *
- * @param chartId The id of the chart.
- * @param callable The callable which is used to request the chart data.
- */
- public AdvancedPie(String chartId, Callable> callable) {
- super(chartId);
- this.callable = callable;
- }
-
- @Override
- protected JsonObject getChartData() throws Exception {
- JsonObject data = new JsonObject();
- JsonObject values = new JsonObject();
- Map map = callable.call();
- if (map == null || map.isEmpty()) {
- // Null = skip the chart
- return null;
- }
- boolean allSkipped = true;
- for (Map.Entry entry : map.entrySet()) {
- if (entry.getValue() == 0) {
- continue; // Skip this invalid
- }
- allSkipped = false;
- values.addProperty(entry.getKey(), entry.getValue());
- }
- if (allSkipped) {
- // Null = skip the chart
- return null;
- }
- data.add("values", values);
- return data;
- }
- }
-
- /**
- * Represents a custom drilldown pie.
- */
- public static class DrilldownPie extends CustomChart {
-
- private final Callable>> callable;
-
- /**
- * Class constructor.
- *
- * @param chartId The id of the chart.
- * @param callable The callable which is used to request the chart data.
- */
- public DrilldownPie(String chartId, Callable>> callable) {
- super(chartId);
- this.callable = callable;
- }
-
- @Override
- public JsonObject getChartData() throws Exception {
- JsonObject data = new JsonObject();
- JsonObject values = new JsonObject();
- Map> map = callable.call();
- if (map == null || map.isEmpty()) {
- // Null = skip the chart
- return null;
- }
- boolean reallyAllSkipped = true;
- for (Map.Entry> entryValues : map.entrySet()) {
- JsonObject value = new JsonObject();
- boolean allSkipped = true;
- for (Map.Entry valueEntry : map.get(entryValues.getKey()).entrySet()) {
- value.addProperty(valueEntry.getKey(), valueEntry.getValue());
- allSkipped = false;
- }
- if (!allSkipped) {
- reallyAllSkipped = false;
- values.add(entryValues.getKey(), value);
- }
- }
- if (reallyAllSkipped) {
- // Null = skip the chart
- return null;
- }
- data.add("values", values);
- return data;
- }
- }
-
- /**
- * Represents a custom single line chart.
- */
- public static class SingleLineChart extends CustomChart {
-
- private final Callable callable;
-
- /**
- * Class constructor.
- *
- * @param chartId The id of the chart.
- * @param callable The callable which is used to request the chart data.
- */
- public SingleLineChart(String chartId, Callable callable) {
- super(chartId);
- this.callable = callable;
- }
-
- @Override
- protected JsonObject getChartData() throws Exception {
- JsonObject data = new JsonObject();
- int value = callable.call();
- if (value == 0) {
- // Null = skip the chart
- return null;
- }
- data.addProperty("value", value);
- return data;
- }
-
- }
-
- /**
- * Represents a custom multi line chart.
- */
- public static class MultiLineChart extends CustomChart {
-
- private final Callable> callable;
-
- /**
- * Class constructor.
- *
- * @param chartId The id of the chart.
- * @param callable The callable which is used to request the chart data.
- */
- public MultiLineChart(String chartId, Callable> callable) {
- super(chartId);
- this.callable = callable;
- }
-
- @Override
- protected JsonObject getChartData() throws Exception {
- JsonObject data = new JsonObject();
- JsonObject values = new JsonObject();
- Map map = callable.call();
- if (map == null || map.isEmpty()) {
- // Null = skip the chart
- return null;
- }
- boolean allSkipped = true;
- for (Map.Entry entry : map.entrySet()) {
- if (entry.getValue() == 0) {
- continue; // Skip this invalid
- }
- allSkipped = false;
- values.addProperty(entry.getKey(), entry.getValue());
- }
- if (allSkipped) {
- // Null = skip the chart
- return null;
- }
- data.add("values", values);
- return data;
- }
-
- }
-
- /**
- * Represents a custom simple bar chart.
- */
- public static class SimpleBarChart extends CustomChart {
-
- private final Callable> callable;
-
- /**
- * Class constructor.
- *
- * @param chartId The id of the chart.
- * @param callable The callable which is used to request the chart data.
- */
- public SimpleBarChart(String chartId, Callable> callable) {
- super(chartId);
- this.callable = callable;
- }
-
- @Override
- protected JsonObject getChartData() throws Exception {
- JsonObject data = new JsonObject();
- JsonObject values = new JsonObject();
- Map map = callable.call();
- if (map == null || map.isEmpty()) {
- // Null = skip the chart
- return null;
- }
- for (Map.Entry entry : map.entrySet()) {
- JsonArray categoryValues = new JsonArray();
- categoryValues.add(new JsonPrimitive(entry.getValue()));
- values.add(entry.getKey(), categoryValues);
- }
- data.add("values", values);
- return data;
- }
-
- }
-
- /**
- * Represents a custom advanced bar chart.
- */
- public static class AdvancedBarChart extends CustomChart {
-
- private final Callable> callable;
-
- /**
- * Class constructor.
- *
- * @param chartId The id of the chart.
- * @param callable The callable which is used to request the chart data.
- */
- public AdvancedBarChart(String chartId, Callable> callable) {
- super(chartId);
- this.callable = callable;
- }
-
- @Override
- protected JsonObject getChartData() throws Exception {
- JsonObject data = new JsonObject();
- JsonObject values = new JsonObject();
- Map map = callable.call();
- if (map == null || map.isEmpty()) {
- // Null = skip the chart
- return null;
- }
- boolean allSkipped = true;
- for (Map.Entry entry : map.entrySet()) {
- if (entry.getValue().length == 0) {
- continue; // Skip this invalid
- }
- allSkipped = false;
- JsonArray categoryValues = new JsonArray();
- for (int categoryValue : entry.getValue()) {
- categoryValues.add(new JsonPrimitive(categoryValue));
- }
- values.add(entry.getKey(), categoryValues);
- }
- if (allSkipped) {
- // Null = skip the chart
- return null;
- }
- data.add("values", values);
- return data;
- }
-
- }
-
-}
\ No newline at end of file
diff --git a/bungeecord/src/main/java/io/github/retrooper/packetevents/bungee/factory/BungeePacketEventsBuilder.java b/bungeecord/src/main/java/io/github/retrooper/packetevents/bungee/factory/BungeePacketEventsBuilder.java
index 2fe01abed1..c5b4c7ba9e 100644
--- a/bungeecord/src/main/java/io/github/retrooper/packetevents/bungee/factory/BungeePacketEventsBuilder.java
+++ b/bungeecord/src/main/java/io/github/retrooper/packetevents/bungee/factory/BungeePacketEventsBuilder.java
@@ -36,7 +36,6 @@
import com.github.retrooper.packetevents.protocol.player.UserProfile;
import com.github.retrooper.packetevents.settings.PacketEventsSettings;
import com.github.retrooper.packetevents.util.LogManager;
-import io.github.retrooper.packetevents.bstats.Metrics;
import io.github.retrooper.packetevents.impl.netty.NettyManagerImpl;
import io.github.retrooper.packetevents.impl.netty.manager.player.PlayerManagerAbstract;
import io.github.retrooper.packetevents.impl.netty.manager.protocol.ProtocolManagerAbstract;
@@ -49,6 +48,8 @@
import net.md_5.bungee.api.connection.Server;
import net.md_5.bungee.api.plugin.Plugin;
import net.md_5.bungee.protocol.ProtocolConstants;
+import org.bstats.bungeecord.Metrics;
+import org.bstats.charts.SimplePie;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -225,9 +226,7 @@ public void init() {
Metrics metrics = new Metrics(plugin, 11327);
//Just to have an idea of which versions of packetevents people use
- metrics.addCustomChart(new Metrics.SimplePie("packetevents_version", () -> {
- return getVersion().toStringWithoutSnapshot();
- }));
+ metrics.addCustomChart(new SimplePie("packetevents_version", () -> getVersion().toStringWithoutSnapshot()));
PacketType.Play.Client.load();
PacketType.Play.Server.load();
diff --git a/libs.versions.toml b/libs.versions.toml
index 85cd76ee65..fe1af3f92e 100644
--- a/libs.versions.toml
+++ b/libs.versions.toml
@@ -5,10 +5,13 @@ netty = "4.1.72.Final"
jetbrains-annotations = "23.0.0"
via-version = "4.5.0"
protocol-support = "3d24efeda6"
+bstats = "3.1.0"
paper = "1.20.6-R0.1-SNAPSHOT"
bungeecord = "1.21-R0.1-SNAPSHOT"
velocity = "3.1.0"
run-paper = "2.3.1"
+fabric-loom = "1.7.2"
+spongeGradle = "2.2.0"
[libraries]
adventure-api = { group = "net.kyori", name = "adventure-api", version.ref = "adventure" }
@@ -19,6 +22,10 @@ adventure-examination-string = { group = "net.kyori", name = "examination-string
adventure-text-serializer-gson = { group = "net.kyori", name = "adventure-text-serializer-gson", version.ref = "adventure" }
adventure-text-serializer-legacy = { group = "net.kyori", name = "adventure-text-serializer-legacy", version.ref = "adventure" }
adventure-text-serializer-json-legacy = { group = "net.kyori", name = "adventure-text-serializer-json-legacy-impl", version.ref = "adventure" }
+bstats-bukkit = { group = "org.bstats", name = "bstats-bukkit", version.ref = "bstats" }
+bstats-bungeecord = { group = "org.bstats", name = "bstats-bungeecord", version.ref = "bstats" }
+bstats-velocity = { group = "org.bstats", name = "bstats-velocity", version.ref = "bstats" }
+bstats-sponge = { group = "org.bstats", name = "bstats-sponge", version.ref = "bstats" }
jetbrains-annotations = { group = "org.jetbrains", name = "annotations", version.ref = "jetbrains-annotations" }
gson = { group = "com.google.code.gson", name = "gson", version = "2.11.0" }
netty = { group = "io.netty", name = "netty-all", version.ref = "netty" }
@@ -35,4 +42,5 @@ adventure-serializers = [ "adventure-text-serializer-gson", "adventure-text-seri
[plugins]
run-paper = { id = "xyz.jpenilla.run-paper", version.ref = "run-paper" }
run-velocity = { id = "xyz.jpenilla.run-velocity", version.ref = "run-paper" }
-fabric-loom = { id = "fabric-loom", version = "1.7.2" }
+fabric-loom = { id = "fabric-loom", version.ref = "fabric-loom" }
+spongeGradle = { id = "org.spongepowered.gradle.plugin", version.ref = "spongeGradle" }
diff --git a/spigot/build.gradle.kts b/spigot/build.gradle.kts
index 3a263936e2..26ea005b51 100644
--- a/spigot/build.gradle.kts
+++ b/spigot/build.gradle.kts
@@ -13,6 +13,7 @@ repositories {
dependencies {
compileOnly(libs.netty)
shadow(libs.bundles.adventure)
+ shadow(libs.bstats.bukkit)
shadow(project(":api", "shadow"))
shadow(project(":netty-common"))
diff --git a/spigot/src/main/java/io/github/retrooper/packetevents/bstats/Metrics.java b/spigot/src/main/java/io/github/retrooper/packetevents/bstats/Metrics.java
deleted file mode 100644
index 1bafa75ad1..0000000000
--- a/spigot/src/main/java/io/github/retrooper/packetevents/bstats/Metrics.java
+++ /dev/null
@@ -1,865 +0,0 @@
-/**
- * MIT License
- * Copyright (c) 2021 Bastian Oppermann
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in all
- * copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
- * SOFTWARE.
- */
-package io.github.retrooper.packetevents.bstats;
-
-import org.bukkit.Bukkit;
-import org.bukkit.configuration.file.YamlConfiguration;
-import org.bukkit.entity.Player;
-import org.bukkit.plugin.Plugin;
-import org.bukkit.plugin.java.JavaPlugin;
-
-import javax.net.ssl.HttpsURLConnection;
-import java.io.*;
-import java.lang.reflect.Method;
-import java.net.URL;
-import java.nio.charset.StandardCharsets;
-import java.util.*;
-import java.util.concurrent.Callable;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.TimeUnit;
-import java.util.function.BiConsumer;
-import java.util.function.Consumer;
-import java.util.function.Supplier;
-import java.util.logging.Level;
-import java.util.stream.Collectors;
-import java.util.zip.GZIPOutputStream;
-//Taken from: https://github.com/Bastian/bStats-Metrics
-public class Metrics {
-
- private final Plugin plugin;
-
- private final MetricsBase metricsBase;
-
- /**
- * Creates a new Metrics instance.
- *
- * @param plugin Your plugin instance.
- * @param serviceId The id of the service. It can be found at What is my plugin id?
- */
- public Metrics(JavaPlugin plugin, int serviceId) {
- this.plugin = plugin;
- // Get the config file
- File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats");
- File configFile = new File(bStatsFolder, "config.yml");
- YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile);
- if (!config.isSet("serverUuid")) {
- config.addDefault("enabled", true);
- config.addDefault("serverUuid", UUID.randomUUID().toString());
- config.addDefault("logFailedRequests", false);
- config.addDefault("logSentData", false);
- config.addDefault("logResponseStatusText", false);
- // Inform the server owners about bStats
- config
- .options()
- .header(
- "bStats (https://bStats.org) collects some basic information for plugin authors, like how\n"
- + "many people use their plugin and their total player count. It's recommended to keep bStats\n"
- + "enabled, but if you're not comfortable with this, you can turn this setting off. There is no\n"
- + "performance penalty associated with having metrics enabled, and data sent to bStats is fully\n"
- + "anonymous.")
- .copyDefaults(true);
- try {
- config.save(configFile);
- } catch (IOException ignored) {
- }
- }
- // Load the data
- boolean enabled = config.getBoolean("enabled", true);
- String serverUUID = config.getString("serverUuid");
- boolean logErrors = config.getBoolean("logFailedRequests", false);
- boolean logSentData = config.getBoolean("logSentData", false);
- boolean logResponseStatusText = config.getBoolean("logResponseStatusText", false);
- metricsBase =
- new MetricsBase(
- "bukkit",
- serverUUID,
- serviceId,
- enabled,
- this::appendPlatformData,
- this::appendServiceData,
- null,
- plugin::isEnabled,
- (message, error) -> this.plugin.getLogger().log(Level.WARNING, message, error),
- (message) -> this.plugin.getLogger().log(Level.INFO, message),
- logErrors,
- logSentData,
- logResponseStatusText);
- }
-
- /**
- * Adds a custom chart.
- *
- * @param chart The chart to add.
- */
- public void addCustomChart(CustomChart chart) {
- metricsBase.addCustomChart(chart);
- }
-
- private void appendPlatformData(JsonObjectBuilder builder) {
- builder.appendField("playerAmount", getPlayerAmount());
- builder.appendField("onlineMode", Bukkit.getOnlineMode() ? 1 : 0);
- builder.appendField("bukkitVersion", Bukkit.getVersion());
- builder.appendField("bukkitName", Bukkit.getName());
- builder.appendField("javaVersion", System.getProperty("java.version"));
- builder.appendField("osName", System.getProperty("os.name"));
- builder.appendField("osArch", System.getProperty("os.arch"));
- builder.appendField("osVersion", System.getProperty("os.version"));
- builder.appendField("coreCount", Runtime.getRuntime().availableProcessors());
- }
-
- private void appendServiceData(JsonObjectBuilder builder) {
- //TODO Remove
- builder.appendField("pluginVersion", plugin.getDescription().getVersion());
- }
-
- private int getPlayerAmount() {
- try {
- // Around MC 1.8 the return type was changed from an array to a collection,
- // This fixes java.lang.NoSuchMethodError:
- // org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection;
- Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers");
- return onlinePlayersMethod.getReturnType().equals(Collection.class)
- ? ((Collection>) onlinePlayersMethod.invoke(Bukkit.getServer())).size()
- : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length;
- } catch (Exception e) {
- // Just use the new method if the reflection failed
- return Bukkit.getOnlinePlayers().size();
- }
- }
-
- public static class MetricsBase {
-
- /**
- * The version of the Metrics class.
- */
- public static final String METRICS_VERSION = "2.2.1";
-
- private static final ScheduledExecutorService scheduler =
- Executors.newScheduledThreadPool(1, task -> new Thread(task, "bStats-Metrics"));
-
- private static final String REPORT_URL = "https://bStats.org/api/v2/data/%s";
-
- private final String platform;
-
- private final String serverUuid;
-
- private final int serviceId;
-
- private final Consumer appendPlatformDataConsumer;
-
- private final Consumer appendServiceDataConsumer;
-
- private final Consumer submitTaskConsumer;
-
- private final Supplier checkServiceEnabledSupplier;
-
- private final BiConsumer errorLogger;
-
- private final Consumer infoLogger;
-
- private final boolean logErrors;
-
- private final boolean logSentData;
-
- private final boolean logResponseStatusText;
-
- private final Set customCharts = new HashSet<>();
-
- private final boolean enabled;
-
- /**
- * Creates a new MetricsBase class instance.
- *
- * @param platform The platform of the service.
- * @param serviceId The id of the service.
- * @param serverUuid The server uuid.
- * @param enabled Whether or not data sending is enabled.
- * @param appendPlatformDataConsumer A consumer that receives a {@code JsonObjectBuilder} and
- * appends all platform-specific data.
- * @param appendServiceDataConsumer A consumer that receives a {@code JsonObjectBuilder} and
- * appends all service-specific data.
- * @param submitTaskConsumer A consumer that takes a runnable with the submit task. This can be
- * used to delegate the data collection to a another thread to prevent errors caused by
- * concurrency. Can be {@code null}.
- * @param checkServiceEnabledSupplier A supplier to check if the service is still enabled.
- * @param errorLogger A consumer that accepts log message and an error.
- * @param infoLogger A consumer that accepts info log messages.
- * @param logErrors Whether or not errors should be logged.
- * @param logSentData Whether or not the sent data should be logged.
- * @param logResponseStatusText Whether or not the response status text should be logged.
- */
- public MetricsBase(
- String platform,
- String serverUuid,
- int serviceId,
- boolean enabled,
- Consumer appendPlatformDataConsumer,
- Consumer appendServiceDataConsumer,
- Consumer submitTaskConsumer,
- Supplier checkServiceEnabledSupplier,
- BiConsumer errorLogger,
- Consumer infoLogger,
- boolean logErrors,
- boolean logSentData,
- boolean logResponseStatusText) {
- this.platform = platform;
- this.serverUuid = serverUuid;
- this.serviceId = serviceId;
- this.enabled = enabled;
- this.appendPlatformDataConsumer = appendPlatformDataConsumer;
- this.appendServiceDataConsumer = appendServiceDataConsumer;
- this.submitTaskConsumer = submitTaskConsumer;
- this.checkServiceEnabledSupplier = checkServiceEnabledSupplier;
- this.errorLogger = errorLogger;
- this.infoLogger = infoLogger;
- this.logErrors = logErrors;
- this.logSentData = logSentData;
- this.logResponseStatusText = logResponseStatusText;
- checkRelocation();
- if (enabled) {
- startSubmitting();
- }
- }
-
- /**
- * Gzips the given string.
- *
- * @param str The string to gzip.
- * @return The gzipped string.
- */
- private static byte[] compress(final String str) throws IOException {
- if (str == null) {
- return null;
- }
- ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
- try (GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) {
- gzip.write(str.getBytes(StandardCharsets.UTF_8));
- }
- return outputStream.toByteArray();
- }
-
- public void addCustomChart(CustomChart chart) {
- this.customCharts.add(chart);
- }
-
- private void startSubmitting() {
- final Runnable submitTask =
- () -> {
- if (!enabled || !checkServiceEnabledSupplier.get()) {
- // Submitting data or service is disabled
- scheduler.shutdown();
- return;
- }
- if (submitTaskConsumer != null) {
- submitTaskConsumer.accept(this::submitData);
- } else {
- this.submitData();
- }
- };
- // Many servers tend to restart at a fixed time at xx:00 which causes an uneven distribution
- // of requests on the
- // bStats backend. To circumvent this problem, we introduce some randomness into the initial
- // and second delay.
- // WARNING: You must not modify and part of this Metrics class, including the submit delay or
- // frequency!
- // WARNING: Modifying this code will get your plugin banned on bStats. Just don't do it!
- long initialDelay = (long) (1000 * 60 * (3 + Math.random() * 3));
- long secondDelay = (long) (1000 * 60 * (Math.random() * 30));
- scheduler.schedule(submitTask, initialDelay, TimeUnit.MILLISECONDS);
- scheduler.scheduleAtFixedRate(
- submitTask, initialDelay + secondDelay, 1000 * 60 * 30, TimeUnit.MILLISECONDS);
- }
-
- private void submitData() {
- final JsonObjectBuilder baseJsonBuilder = new JsonObjectBuilder();
- appendPlatformDataConsumer.accept(baseJsonBuilder);
- final JsonObjectBuilder serviceJsonBuilder = new JsonObjectBuilder();
- appendServiceDataConsumer.accept(serviceJsonBuilder);
- JsonObjectBuilder.JsonObject[] chartData =
- customCharts.stream()
- .map(customChart -> customChart.getRequestJsonObject(errorLogger, logErrors))
- .filter(Objects::nonNull)
- .toArray(JsonObjectBuilder.JsonObject[]::new);
- serviceJsonBuilder.appendField("id", serviceId);
- serviceJsonBuilder.appendField("customCharts", chartData);
- baseJsonBuilder.appendField("service", serviceJsonBuilder.build());
- baseJsonBuilder.appendField("serverUUID", serverUuid);
- baseJsonBuilder.appendField("metricsVersion", METRICS_VERSION);
- JsonObjectBuilder.JsonObject data = baseJsonBuilder.build();
- scheduler.execute(
- () -> {
- try {
- // Send the data
- sendData(data);
- } catch (Exception e) {
- // Something went wrong! :(
- if (logErrors) {
- errorLogger.accept("Could not submit bStats metrics data", e);
- }
- }
- });
- }
-
- private void sendData(JsonObjectBuilder.JsonObject data) throws Exception {
- if (logSentData) {
- infoLogger.accept("Sent bStats metrics data: " + data.toString());
- }
- String url = String.format(REPORT_URL, platform);
- HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();
- // Compress the data to save bandwidth
- byte[] compressedData = compress(data.toString());
- connection.setRequestMethod("POST");
- connection.addRequestProperty("Accept", "application/json");
- connection.addRequestProperty("Connection", "close");
- connection.addRequestProperty("Content-Encoding", "gzip");
- connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
- connection.setRequestProperty("Content-Type", "application/json");
- connection.setRequestProperty("User-Agent", "Metrics-Service/1");
- connection.setDoOutput(true);
- try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) {
- outputStream.write(compressedData);
- }
- StringBuilder builder = new StringBuilder();
- try (BufferedReader bufferedReader =
- new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
- String line;
- while ((line = bufferedReader.readLine()) != null) {
- builder.append(line);
- }
- }
- if (logResponseStatusText) {
- infoLogger.accept("Sent data to bStats and received response: " + builder);
- }
- }
-
- /**
- * Checks that the class was properly relocated.
- */
- private void checkRelocation() {
- // You can use the property to disable the check in your test environment
- if (System.getProperty("bstats.relocatecheck") == null
- || !System.getProperty("bstats.relocatecheck").equals("false")) {
- // Maven's Relocate is clever and changes strings, too. So we have to use this little
- // "trick" ... :D
- final String defaultPackage =
- new String(new byte[]{'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's'});
- final String examplePackage =
- new String(new byte[]{'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'});
- // We want to make sure no one just copy & pastes the example and uses the wrong package
- // names
- if (MetricsBase.class.getPackage().getName().startsWith(defaultPackage)
- || MetricsBase.class.getPackage().getName().startsWith(examplePackage)) {
- throw new IllegalStateException("bStats Metrics class has not been relocated correctly!");
- }
- }
- }
- }
-
- public static class AdvancedBarChart extends CustomChart {
-
- private final Callable> callable;
-
- /**
- * Class constructor.
- *
- * @param chartId The id of the chart.
- * @param callable The callable which is used to request the chart data.
- */
- public AdvancedBarChart(String chartId, Callable> callable) {
- super(chartId);
- this.callable = callable;
- }
-
- @Override
- protected JsonObjectBuilder.JsonObject getChartData() throws Exception {
- JsonObjectBuilder valuesBuilder = new JsonObjectBuilder();
- Map map = callable.call();
- if (map == null || map.isEmpty()) {
- // Null = skip the chart
- return null;
- }
- boolean allSkipped = true;
- for (Map.Entry entry : map.entrySet()) {
- if (entry.getValue().length == 0) {
- // Skip this invalid
- continue;
- }
- allSkipped = false;
- valuesBuilder.appendField(entry.getKey(), entry.getValue());
- }
- if (allSkipped) {
- // Null = skip the chart
- return null;
- }
- return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build();
- }
- }
-
- public static class SimpleBarChart extends CustomChart {
-
- private final Callable> callable;
-
- /**
- * Class constructor.
- *
- * @param chartId The id of the chart.
- * @param callable The callable which is used to request the chart data.
- */
- public SimpleBarChart(String chartId, Callable> callable) {
- super(chartId);
- this.callable = callable;
- }
-
- @Override
- protected JsonObjectBuilder.JsonObject getChartData() throws Exception {
- JsonObjectBuilder valuesBuilder = new JsonObjectBuilder();
- Map map = callable.call();
- if (map == null || map.isEmpty()) {
- // Null = skip the chart
- return null;
- }
- for (Map.Entry entry : map.entrySet()) {
- valuesBuilder.appendField(entry.getKey(), new int[]{entry.getValue()});
- }
- return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build();
- }
- }
-
- public static class MultiLineChart extends CustomChart {
-
- private final Callable> callable;
-
- /**
- * Class constructor.
- *
- * @param chartId The id of the chart.
- * @param callable The callable which is used to request the chart data.
- */
- public MultiLineChart(String chartId, Callable> callable) {
- super(chartId);
- this.callable = callable;
- }
-
- @Override
- protected JsonObjectBuilder.JsonObject getChartData() throws Exception {
- JsonObjectBuilder valuesBuilder = new JsonObjectBuilder();
- Map map = callable.call();
- if (map == null || map.isEmpty()) {
- // Null = skip the chart
- return null;
- }
- boolean allSkipped = true;
- for (Map.Entry entry : map.entrySet()) {
- if (entry.getValue() == 0) {
- // Skip this invalid
- continue;
- }
- allSkipped = false;
- valuesBuilder.appendField(entry.getKey(), entry.getValue());
- }
- if (allSkipped) {
- // Null = skip the chart
- return null;
- }
- return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build();
- }
- }
-
- public static class AdvancedPie extends CustomChart {
-
- private final Callable> callable;
-
- /**
- * Class constructor.
- *
- * @param chartId The id of the chart.
- * @param callable The callable which is used to request the chart data.
- */
- public AdvancedPie(String chartId, Callable> callable) {
- super(chartId);
- this.callable = callable;
- }
-
- @Override
- protected JsonObjectBuilder.JsonObject getChartData() throws Exception {
- JsonObjectBuilder valuesBuilder = new JsonObjectBuilder();
- Map map = callable.call();
- if (map == null || map.isEmpty()) {
- // Null = skip the chart
- return null;
- }
- boolean allSkipped = true;
- for (Map.Entry entry : map.entrySet()) {
- if (entry.getValue() == 0) {
- // Skip this invalid
- continue;
- }
- allSkipped = false;
- valuesBuilder.appendField(entry.getKey(), entry.getValue());
- }
- if (allSkipped) {
- // Null = skip the chart
- return null;
- }
- return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build();
- }
- }
-
- public abstract static class CustomChart {
-
- private final String chartId;
-
- protected CustomChart(String chartId) {
- if (chartId == null) {
- throw new IllegalArgumentException("chartId must not be null");
- }
- this.chartId = chartId;
- }
-
- public JsonObjectBuilder.JsonObject getRequestJsonObject(
- BiConsumer errorLogger, boolean logErrors) {
- JsonObjectBuilder builder = new JsonObjectBuilder();
- builder.appendField("chartId", chartId);
- try {
- JsonObjectBuilder.JsonObject data = getChartData();
- if (data == null) {
- // If the data is null we don't send the chart.
- return null;
- }
- builder.appendField("data", data);
- } catch (Throwable t) {
- if (logErrors) {
- errorLogger.accept("Failed to get data for custom chart with id " + chartId, t);
- }
- return null;
- }
- return builder.build();
- }
-
- protected abstract JsonObjectBuilder.JsonObject getChartData() throws Exception;
- }
-
- public static class SingleLineChart extends CustomChart {
-
- private final Callable callable;
-
- /**
- * Class constructor.
- *
- * @param chartId The id of the chart.
- * @param callable The callable which is used to request the chart data.
- */
- public SingleLineChart(String chartId, Callable callable) {
- super(chartId);
- this.callable = callable;
- }
-
- @Override
- protected JsonObjectBuilder.JsonObject getChartData() throws Exception {
- int value = callable.call();
- if (value == 0) {
- // Null = skip the chart
- return null;
- }
- return new JsonObjectBuilder().appendField("value", value).build();
- }
- }
-
- public static class SimplePie extends CustomChart {
-
- private final Callable callable;
-
- /**
- * Class constructor.
- *
- * @param chartId The id of the chart.
- * @param callable The callable which is used to request the chart data.
- */
- public SimplePie(String chartId, Callable callable) {
- super(chartId);
- this.callable = callable;
- }
-
- @Override
- protected JsonObjectBuilder.JsonObject getChartData() throws Exception {
- String value = callable.call();
- if (value == null || value.isEmpty()) {
- // Null = skip the chart
- return null;
- }
- return new JsonObjectBuilder().appendField("value", value).build();
- }
- }
-
- public static class DrilldownPie extends CustomChart {
-
- private final Callable>> callable;
-
- /**
- * Class constructor.
- *
- * @param chartId The id of the chart.
- * @param callable The callable which is used to request the chart data.
- */
- public DrilldownPie(String chartId, Callable>> callable) {
- super(chartId);
- this.callable = callable;
- }
-
- @Override
- public JsonObjectBuilder.JsonObject getChartData() throws Exception {
- JsonObjectBuilder valuesBuilder = new JsonObjectBuilder();
- Map> map = callable.call();
- if (map == null || map.isEmpty()) {
- // Null = skip the chart
- return null;
- }
- boolean reallyAllSkipped = true;
- for (Map.Entry> entryValues : map.entrySet()) {
- JsonObjectBuilder valueBuilder = new JsonObjectBuilder();
- boolean allSkipped = true;
- for (Map.Entry valueEntry : map.get(entryValues.getKey()).entrySet()) {
- valueBuilder.appendField(valueEntry.getKey(), valueEntry.getValue());
- allSkipped = false;
- }
- if (!allSkipped) {
- reallyAllSkipped = false;
- valuesBuilder.appendField(entryValues.getKey(), valueBuilder.build());
- }
- }
- if (reallyAllSkipped) {
- // Null = skip the chart
- return null;
- }
- return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build();
- }
- }
-
- /**
- * An extremely simple JSON builder.
- *
- * While this class is neither feature-rich nor the most performant one, it's sufficient enough
- * for its use-case.
- */
- public static class JsonObjectBuilder {
-
- private StringBuilder builder = new StringBuilder();
-
- private boolean hasAtLeastOneField = false;
-
- public JsonObjectBuilder() {
- builder.append("{");
- }
-
- /**
- * Escapes the given string like stated in https://www.ietf.org/rfc/rfc4627.txt.
- *
- *
This method escapes only the necessary characters '"', '\'. and '\u0000' - '\u001F'.
- * Compact escapes are not used (e.g., '\n' is escaped as "\u000a" and not as "\n").
- *
- * @param value The value to escape.
- * @return The escaped value.
- */
- private static String escape(String value) {
- final StringBuilder builder = new StringBuilder();
- for (int i = 0; i < value.length(); i++) {
- char c = value.charAt(i);
- if (c == '"') {
- builder.append("\\\"");
- } else if (c == '\\') {
- builder.append("\\\\");
- } else if (c <= '\u000F') {
- builder.append("\\u000").append(Integer.toHexString(c));
- } else if (c <= '\u001F') {
- builder.append("\\u00").append(Integer.toHexString(c));
- } else {
- builder.append(c);
- }
- }
- return builder.toString();
- }
-
- /**
- * Appends a null field to the JSON.
- *
- * @param key The key of the field.
- * @return A reference to this object.
- */
- public JsonObjectBuilder appendNull(String key) {
- appendFieldUnescaped(key, "null");
- return this;
- }
-
- /**
- * Appends a string field to the JSON.
- *
- * @param key The key of the field.
- * @param value The value of the field.
- * @return A reference to this object.
- */
- public JsonObjectBuilder appendField(String key, String value) {
- if (value == null) {
- throw new IllegalArgumentException("JSON value must not be null");
- }
- appendFieldUnescaped(key, "\"" + escape(value) + "\"");
- return this;
- }
-
- /**
- * Appends an integer field to the JSON.
- *
- * @param key The key of the field.
- * @param value The value of the field.
- * @return A reference to this object.
- */
- public JsonObjectBuilder appendField(String key, int value) {
- appendFieldUnescaped(key, String.valueOf(value));
- return this;
- }
-
- /**
- * Appends an object to the JSON.
- *
- * @param key The key of the field.
- * @param object The object.
- * @return A reference to this object.
- */
- public JsonObjectBuilder appendField(String key, JsonObject object) {
- if (object == null) {
- throw new IllegalArgumentException("JSON object must not be null");
- }
- appendFieldUnescaped(key, object.toString());
- return this;
- }
-
- /**
- * Appends a string array to the JSON.
- *
- * @param key The key of the field.
- * @param values The string array.
- * @return A reference to this object.
- */
- public JsonObjectBuilder appendField(String key, String[] values) {
- if (values == null) {
- throw new IllegalArgumentException("JSON values must not be null");
- }
- String escapedValues =
- Arrays.stream(values)
- .map(value -> "\"" + escape(value) + "\"")
- .collect(Collectors.joining(","));
- appendFieldUnescaped(key, "[" + escapedValues + "]");
- return this;
- }
-
- /**
- * Appends an integer array to the JSON.
- *
- * @param key The key of the field.
- * @param values The integer array.
- * @return A reference to this object.
- */
- public JsonObjectBuilder appendField(String key, int[] values) {
- if (values == null) {
- throw new IllegalArgumentException("JSON values must not be null");
- }
- String escapedValues =
- Arrays.stream(values).mapToObj(String::valueOf).collect(Collectors.joining(","));
- appendFieldUnescaped(key, "[" + escapedValues + "]");
- return this;
- }
-
- /**
- * Appends an object array to the JSON.
- *
- * @param key The key of the field.
- * @param values The integer array.
- * @return A reference to this object.
- */
- public JsonObjectBuilder appendField(String key, JsonObject[] values) {
- if (values == null) {
- throw new IllegalArgumentException("JSON values must not be null");
- }
- String escapedValues =
- Arrays.stream(values).map(JsonObject::toString).collect(Collectors.joining(","));
- appendFieldUnescaped(key, "[" + escapedValues + "]");
- return this;
- }
-
- /**
- * Appends a field to the object.
- *
- * @param key The key of the field.
- * @param escapedValue The escaped value of the field.
- */
- private void appendFieldUnescaped(String key, String escapedValue) {
- if (builder == null) {
- throw new IllegalStateException("JSON has already been built");
- }
- if (key == null) {
- throw new IllegalArgumentException("JSON key must not be null");
- }
- if (hasAtLeastOneField) {
- builder.append(",");
- }
- builder.append("\"").append(escape(key)).append("\":").append(escapedValue);
- hasAtLeastOneField = true;
- }
-
- /**
- * Builds the JSON string and invalidates this builder.
- *
- * @return The built JSON string.
- */
- public JsonObject build() {
- if (builder == null) {
- throw new IllegalStateException("JSON has already been built");
- }
- JsonObject object = new JsonObject(builder.append("}").toString());
- builder = null;
- return object;
- }
-
- /**
- * A super simple representation of a JSON object.
- *
- *
This class only exists to make methods of the {@link JsonObjectBuilder} type-safe and not
- * allow a raw string inputs for methods like {@link JsonObjectBuilder#appendField(String,
- * JsonObject)}.
- */
- public static class JsonObject {
-
- private final String value;
-
- private JsonObject(String value) {
- this.value = value;
- }
-
- @Override
- public String toString() {
- return value;
- }
- }
- }
-}
diff --git a/spigot/src/main/java/io/github/retrooper/packetevents/factory/spigot/SpigotPacketEventsBuilder.java b/spigot/src/main/java/io/github/retrooper/packetevents/factory/spigot/SpigotPacketEventsBuilder.java
index 39152b9d37..7830f63e4f 100644
--- a/spigot/src/main/java/io/github/retrooper/packetevents/factory/spigot/SpigotPacketEventsBuilder.java
+++ b/spigot/src/main/java/io/github/retrooper/packetevents/factory/spigot/SpigotPacketEventsBuilder.java
@@ -30,7 +30,6 @@
import com.github.retrooper.packetevents.protocol.world.states.WrappedBlockState;
import com.github.retrooper.packetevents.settings.PacketEventsSettings;
import com.github.retrooper.packetevents.util.LogManager;
-import io.github.retrooper.packetevents.bstats.Metrics;
import io.github.retrooper.packetevents.bukkit.InternalBukkitListener;
import io.github.retrooper.packetevents.injector.SpigotChannelInjector;
import io.github.retrooper.packetevents.injector.connection.ServerConnectionInitializer;
@@ -45,10 +44,11 @@
import io.github.retrooper.packetevents.util.protocolsupport.ProtocolSupportUtil;
import io.github.retrooper.packetevents.util.viaversion.CustomPipelineUtil;
import io.github.retrooper.packetevents.util.viaversion.ViaVersionUtil;
+import org.bstats.bukkit.Metrics;
+import org.bstats.charts.SimplePie;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
-import org.bukkit.plugin.java.JavaPlugin;
public class SpigotPacketEventsBuilder {
private static PacketEventsAPI API_INSTANCE;
@@ -141,9 +141,9 @@ public void init() {
getUpdateChecker().handleUpdateCheck();
}
- Metrics metrics = new Metrics((JavaPlugin) plugin, 11327);
+ Metrics metrics = new Metrics(plugin, 11327);
//Just to have an idea of which versions of packetevents people use
- metrics.addCustomChart(new Metrics.SimplePie("packetevents_version", () -> getVersion().toStringWithoutSnapshot()));
+ metrics.addCustomChart(new SimplePie("packetevents_version", () -> getVersion().toStringWithoutSnapshot()));
Bukkit.getPluginManager().registerEvents(new InternalBukkitListener(plugin), plugin);
if (lateBind) {
diff --git a/sponge/build.gradle.kts b/sponge/build.gradle.kts
index 6d0bfa9c5b..5f619ac515 100644
--- a/sponge/build.gradle.kts
+++ b/sponge/build.gradle.kts
@@ -4,7 +4,7 @@ import org.spongepowered.plugin.metadata.model.PluginDependency
plugins {
packetevents.`shadow-conventions`
packetevents.`library-conventions`
- id("org.spongepowered.gradle.plugin") version("2.0.2")
+ alias(libs.plugins.spongeGradle)
}
repositories {
@@ -42,6 +42,7 @@ dependencies {
}
shadow(project(":api", "shadow"))
shadow(project(":netty-common"))
+ shadow(libs.bstats.sponge)
compileOnly(libs.via.version)
}
diff --git a/sponge/src/main/java/io/github/retrooper/packetevents/sponge/PacketEventsPlugin.java b/sponge/src/main/java/io/github/retrooper/packetevents/sponge/PacketEventsPlugin.java
index 6c76450a7e..d7a1576db9 100644
--- a/sponge/src/main/java/io/github/retrooper/packetevents/sponge/PacketEventsPlugin.java
+++ b/sponge/src/main/java/io/github/retrooper/packetevents/sponge/PacketEventsPlugin.java
@@ -19,11 +19,7 @@
package io.github.retrooper.packetevents.sponge;
import com.github.retrooper.packetevents.PacketEvents;
-import com.github.retrooper.packetevents.event.PacketListenerPriority;
-import com.github.retrooper.packetevents.event.SimplePacketListenerAbstract;
-import com.github.retrooper.packetevents.event.UserConnectEvent;
-import com.github.retrooper.packetevents.event.UserDisconnectEvent;
-import com.github.retrooper.packetevents.event.UserLoginEvent;
+import com.github.retrooper.packetevents.event.*;
import com.github.retrooper.packetevents.event.simple.PacketPlaySendEvent;
import com.github.retrooper.packetevents.protocol.item.ItemStack;
import com.github.retrooper.packetevents.protocol.packettype.PacketType;
@@ -32,6 +28,8 @@
import com.google.inject.Inject;
import io.github.retrooper.packetevents.sponge.factory.SpongePacketEventsBuilder;
import io.github.retrooper.packetevents.sponge.util.SpongeConversionUtil;
+import org.bstats.charts.SimplePie;
+import org.bstats.sponge.Metrics;
import org.spongepowered.api.Server;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.Order;
@@ -44,8 +42,14 @@
@Plugin("packetevents")
public class PacketEventsPlugin {
+ private final PluginContainer pluginContainer;
+ private final Metrics metrics;
+
@Inject
- private PluginContainer pluginContainer;
+ public PacketEventsPlugin(PluginContainer pluginContainer, Metrics.Factory metricsFactory) {
+ this.pluginContainer = pluginContainer;
+ this.metrics = metricsFactory.make(11327);
+ }
@Listener(order = Order.EARLY)
public void onServerStart(final StartingEngineEvent event) {
@@ -56,6 +60,9 @@ public void onServerStart(final StartingEngineEvent event) {
PacketEvents.getAPI().getSettings().debug(false).downsampleColors(false).checkForUpdates(true).timeStampMode(TimeStampMode.MILLIS).reEncodeByDefault(true);
PacketEvents.getAPI().init();
+ //Just to have an idea of which versions of packetevents people use
+ metrics.addCustomChart(new SimplePie("packetevents_version", () -> PacketEvents.getAPI().getVersion().toStringWithoutSnapshot()));
+
SimplePacketListenerAbstract listener = new SimplePacketListenerAbstract(PacketListenerPriority.HIGH) {
// Testing ItemStack conversion, can be removed in future
diff --git a/velocity/build.gradle.kts b/velocity/build.gradle.kts
index 4102f5bd52..1c11f19cd9 100644
--- a/velocity/build.gradle.kts
+++ b/velocity/build.gradle.kts
@@ -16,6 +16,7 @@ dependencies {
annotationProcessor(libs.velocity)
shadow(project(":api", "shadow"))
shadow(project(":netty-common"))
+ shadow(libs.bstats.velocity)
// Velocity already bundles with adventure
}
diff --git a/velocity/src/main/java/io/github/retrooper/packetevents/PacketEventsPlugin.java b/velocity/src/main/java/io/github/retrooper/packetevents/PacketEventsPlugin.java
index 71e1e8e6ee..a28d20692c 100644
--- a/velocity/src/main/java/io/github/retrooper/packetevents/PacketEventsPlugin.java
+++ b/velocity/src/main/java/io/github/retrooper/packetevents/PacketEventsPlugin.java
@@ -30,6 +30,8 @@
import com.velocitypowered.api.plugin.annotation.DataDirectory;
import com.velocitypowered.api.proxy.ProxyServer;
import io.github.retrooper.packetevents.velocity.factory.VelocityPacketEventsBuilder;
+import org.bstats.charts.SimplePie;
+import org.bstats.velocity.Metrics;
import org.slf4j.Logger;
import java.nio.file.Path;
@@ -39,17 +41,20 @@ public class PacketEventsPlugin {
private final Logger logger;
private final PluginContainer pluginContainer;
private final Path dataDirectory;
+ private final Metrics.Factory metricsFactory;
@Inject
- public PacketEventsPlugin(final ProxyServer server,
- final Logger logger,
- final PluginContainer pluginContainer, @DataDirectory Path dataDirectory) {
+ public PacketEventsPlugin(
+ final ProxyServer server,
+ final Logger logger,
+ final PluginContainer pluginContainer,
+ @DataDirectory Path dataDirectory,
+ Metrics.Factory metricsFactory) {
this.server = server;
this.logger = logger;
this.pluginContainer = pluginContainer;
this.dataDirectory = dataDirectory;
- logger.info("Plugin started");
-
+ this.metricsFactory = metricsFactory;
}
@Subscribe
@@ -87,6 +92,13 @@ public void onPacketSend(PacketSendEvent event) {
};
//PacketEvents.getAPI().getEventManager().registerListener(listener);
PacketEvents.getAPI().init();
+
+ // Enable bStats
+ Metrics metrics = metricsFactory.make(this, 11327);
+ //Just to have an idea of which versions of packetevents people use
+ metrics.addCustomChart(new SimplePie("packetevents_version", () -> PacketEvents.getAPI().getVersion().toStringWithoutSnapshot()));
+
+ logger.info("Plugin started");
}
@Subscribe
diff --git a/velocity/src/main/java/io/github/retrooper/packetevents/bstats/Metrics.java b/velocity/src/main/java/io/github/retrooper/packetevents/bstats/Metrics.java
deleted file mode 100644
index 420953800b..0000000000
--- a/velocity/src/main/java/io/github/retrooper/packetevents/bstats/Metrics.java
+++ /dev/null
@@ -1,756 +0,0 @@
-/**
- * MIT License
- * Copyright (c) 2021 Bastian Oppermann
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in all
- * copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
- * SOFTWARE.
- */
-
-package io.github.retrooper.packetevents.bstats;
-
-import com.google.inject.Inject;
-import com.velocitypowered.api.plugin.PluginContainer;
-import com.velocitypowered.api.plugin.PluginDescription;
-import com.velocitypowered.api.plugin.annotation.DataDirectory;
-import com.velocitypowered.api.proxy.ProxyServer;
-import org.slf4j.Logger;
-
-import javax.net.ssl.HttpsURLConnection;
-import java.io.*;
-import java.net.URL;
-import java.nio.charset.StandardCharsets;
-import java.nio.file.Path;
-import java.util.*;
-import java.util.concurrent.Callable;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.TimeUnit;
-import java.util.function.BiConsumer;
-import java.util.function.Consumer;
-import java.util.function.Supplier;
-import java.util.regex.Pattern;
-import java.util.stream.Collectors;
-import java.util.zip.GZIPOutputStream;
-
-//This file was taken from bStats https://github.com/Bastian/bStats-Metrics
-//and has been modified to fit our needs (compactness by fitting it into one file)
-/**
- * bStats collects some data for plugin authors.
- *
- * Check out https://bStats.org/ to learn more about bStats!
- */
-public class Metrics {
-
- /**
- * A factory to create new Metrics classes.
- */
- public static class Factory {
-
- private final ProxyServer server;
- private final Logger logger;
- private final Path dataDirectory;
-
- // The constructor is not meant to be called by the user.
- // The instance is created using Dependency Injection
- @Inject
- private Factory(ProxyServer server, Logger logger, @DataDirectory Path dataDirectory) {
- this.server = server;
- this.logger = logger;
- this.dataDirectory = dataDirectory;
- }
-
- /**
- * Creates a new Metrics class.
- *
- * @param serviceId The id of the service.
- * It can be found at What is my plugin id?
- *
Not to be confused with Velocity's {@link PluginDescription#getId()} method!
- * @return A Metrics instance that can be used to register custom charts.
- *
The return value can be ignored, when you do not want to register custom charts.
- */
- public Metrics make(Object plugin, int serviceId) {
- return new Metrics(plugin, server, logger, dataDirectory, serviceId);
- }
- }
-
- //PacketEvents - Start
- public static Metrics createInstance(Object plugin, ProxyServer server, Logger logger, Path dataDirectory, int serviceId) {
- return new Metrics(plugin, server, logger, dataDirectory, serviceId);
- }
- //PacketEvents - End
-
- private final PluginContainer pluginContainer;
- private final ProxyServer server;
- private final MetricsBase metricsBase;
- private final Logger logger;
- private final Path dataDirectory;
-
- private String serverUUID;
- private boolean enabled;
- private boolean logErrors;
- private boolean logSentData;
- private boolean logResponseStatusText;
-
- private Metrics(Object plugin, ProxyServer server, Logger logger, Path dataDirectory, int serviceId) {
- pluginContainer = server.getPluginManager().fromInstance(plugin)
- .orElseThrow(() -> new IllegalArgumentException("The provided instance is not a plugin"));
- this.server = server;
- this.logger = logger;
- this.dataDirectory = dataDirectory;
-
- try {
- setupConfig(true);
- } catch (IOException e) {
- logger.error("Failed to create bStats config", e);
- }
-
- metricsBase = new MetricsBase(
- "velocity",
- serverUUID,
- serviceId,
- enabled,
- this::appendPlatformData,
- this::appendServiceData,
- task -> server.getScheduler().buildTask(plugin, task).schedule(),
- () -> true,
- logger::warn,
- logger::info,
- logErrors,
- logSentData,
- logResponseStatusText
- );
- }
-
- /**
- * Adds a custom chart.
- *
- * @param chart The chart to add.
- */
- public void addCustomChart(CustomChart chart) {
- metricsBase.addCustomChart(chart);
- }
-
- private void appendPlatformData(JsonObjectBuilder builder) {
- builder.appendField("playerAmount", server.getPlayerCount());
- builder.appendField("managedServers", server.getAllServers().size());
- builder.appendField("onlineMode", server.getConfiguration().isOnlineMode() ? 1 : 0);
- builder.appendField("velocityVersionVersion", server.getVersion().getVersion());
- builder.appendField("velocityVersionName", server.getVersion().getName());
- builder.appendField("velocityVersionVendor", server.getVersion().getVendor());
-
- builder.appendField("javaVersion", System.getProperty("java.version"));
- builder.appendField("osName", System.getProperty("os.name"));
- builder.appendField("osArch", System.getProperty("os.arch"));
- builder.appendField("osVersion", System.getProperty("os.version"));
- builder.appendField("coreCount", Runtime.getRuntime().availableProcessors());
- }
-
- private void appendServiceData(JsonObjectBuilder builder) {
- builder.appendField("pluginVersion", pluginContainer.getDescription().getVersion().orElse("unknown"));
- }
-
- /**
- * Setups the bStats configuration.
- *
- * @param recreateWhenMalformed Whether the method should recreate the config file when it's malformed.
- */
- public void setupConfig(boolean recreateWhenMalformed) throws IOException {
- File configFolder = dataDirectory.getParent().resolve("bStats").toFile();
- configFolder.mkdirs();
- File configFile = new File(configFolder, "config.txt");
- if (!configFile.exists()) {
- writeConfig(configFile);
- }
-
- List lines = readFile(configFile);
- if (lines == null) {
- throw new AssertionError("Content of newly created file is null");
- }
-
- enabled = getConfigValue("enabled", lines).map("true"::equals).orElse(true);
- serverUUID = getConfigValue("server-uuid", lines).orElse(null);
- logErrors = getConfigValue("log-errors", lines).map("true"::equals).orElse(false);
- logSentData = getConfigValue("log-sent-data", lines).map("true"::equals).orElse(false);
- logResponseStatusText = getConfigValue("log-response-status-text", lines).map("true"::equals).orElse(false);
-
- if (serverUUID == null) {
- if (recreateWhenMalformed) {
- logger.info("Found malformed bStats config file. Re-creating it...");
- configFile.delete();
- setupConfig(false);
- } else {
- throw new AssertionError("Failed to re-create malformed bStats config file");
- }
- }
- }
-
- /**
- * Creates a simple bStats configuration.
- *
- * @param file The config file.
- */
- private void writeConfig(File file) throws IOException {
- List configContent = new ArrayList<>();
- configContent.add("# bStats collects some basic information for plugin authors, like how many people use");
- configContent.add("# their plugin and their total player count. It's recommend to keep bStats enabled, but");
- configContent.add("# if you're not comfortable with this, you can turn this setting off. There is no");
- configContent.add("# performance penalty associated with having metrics enabled, and data sent to bStats");
- configContent.add("# can't identify your server.");
- configContent.add("enabled=true");
- configContent.add("server-uuid=" + UUID.randomUUID().toString());
- configContent.add("log-errors=false");
- configContent.add("log-sent-data=false");
- configContent.add("log-response-status-text=false");
- writeFile(file, configContent);
- }
-
- /**
- * Gets a config setting from the given list of lines of the file.
- *
- * @param key The key for the setting.
- * @param lines The lines of the file.
- * @return The value of the setting.
- */
- private Optional getConfigValue(String key, List lines) {
- return lines.stream()
- .filter(line -> line.startsWith(key + "="))
- .map(line -> line.replaceFirst(Pattern.quote(key + "="), ""))
- .findFirst();
- }
-
- /**
- * Reads the text content of the given file.
- *
- * @param file The file to read.
- * @return The lines of the given file.
- */
- private List readFile(File file) throws IOException {
- if (!file.exists()) {
- return null;
- }
- try (
- FileReader fileReader = new FileReader(file);
- BufferedReader bufferedReader = new BufferedReader(fileReader)
- ) {
- return bufferedReader.lines().collect(Collectors.toList());
- }
- }
-
- /**
- * Writes the given lines to the given file.
- *
- * @param file The file to write to.
- * @param lines The lines to write.
- */
- private void writeFile(File file, List lines) throws IOException {
- if (!file.exists()) {
- file.createNewFile();
- }
- try (
- FileWriter fileWriter = new FileWriter(file);
- BufferedWriter bufferedWriter = new BufferedWriter(fileWriter)
- ) {
- for (String line : lines) {
- bufferedWriter.write(line);
- bufferedWriter.newLine();
- }
- }
- }
-
- public static class SimplePie extends CustomChart {
-
- private final Callable callable;
-
- /**
- * Class constructor.
- *
- * @param chartId The id of the chart.
- * @param callable The callable which is used to request the chart data.
- */
- public SimplePie(String chartId, Callable callable) {
- super(chartId);
- this.callable = callable;
- }
-
- @Override
- protected JsonObjectBuilder.JsonObject getChartData() throws Exception {
- String value = callable.call();
- if (value == null || value.isEmpty()) {
- // Null = skip the chart
- return null;
- }
- return new JsonObjectBuilder()
- .appendField("value", value)
- .build();
- }
- }
-
- public static class JsonObjectBuilder {
-
- private StringBuilder builder = new StringBuilder();
- private boolean hasAtLeastOneField = false;
-
- public JsonObjectBuilder() {
- builder.append("{");
- }
-
- /**
- * Appends a null field to the JSON.
- *
- * @param key The key of the field.
- * @return A reference to this object.
- */
- public JsonObjectBuilder appendNull(String key) {
- appendFieldUnescaped(key, "null");
- return this;
- }
-
- /**
- * Appends a string field to the JSON.
- *
- * @param key The key of the field.
- * @param value The value of the field.
- * @return A reference to this object.
- */
- public JsonObjectBuilder appendField(String key, String value) {
- if (value == null) {
- throw new IllegalArgumentException("JSON value must not be null");
- }
- appendFieldUnescaped(key, "\"" + escape(value) + "\"");
- return this;
- }
-
- /**
- * Appends an integer field to the JSON.
- *
- * @param key The key of the field.
- * @param value The value of the field.
- * @return A reference to this object.
- */
- public JsonObjectBuilder appendField(String key, int value) {
- appendFieldUnescaped(key, String.valueOf(value));
- return this;
- }
-
- /**
- * Appends an object to the JSON.
- *
- * @param key The key of the field.
- * @param object The object.
- * @return A reference to this object.
- */
- public JsonObjectBuilder appendField(String key, JsonObject object) {
- if (object == null) {
- throw new IllegalArgumentException("JSON object must not be null");
- }
- appendFieldUnescaped(key, object.toString());
- return this;
- }
-
- /**
- * Appends a string array to the JSON.
- *
- * @param key The key of the field.
- * @param values The string array.
- * @return A reference to this object.
- */
- public JsonObjectBuilder appendField(String key, String[] values) {
- if (values == null) {
- throw new IllegalArgumentException("JSON values must not be null");
- }
- String escapedValues = Arrays.stream(values)
- .map(value -> "\"" + escape(value) + "\"")
- .collect(Collectors.joining(","));
- appendFieldUnescaped(key, "[" + escapedValues + "]");
- return this;
- }
-
- /**
- * Appends an integer array to the JSON.
- *
- * @param key The key of the field.
- * @param values The integer array.
- * @return A reference to this object.
- */
- public JsonObjectBuilder appendField(String key, int[] values) {
- if (values == null) {
- throw new IllegalArgumentException("JSON values must not be null");
- }
- String escapedValues = Arrays.stream(values)
- .mapToObj(String::valueOf)
- .collect(Collectors.joining(","));
- appendFieldUnescaped(key, "[" + escapedValues + "]");
- return this;
- }
-
- /**
- * Appends an object array to the JSON.
- *
- * @param key The key of the field.
- * @param values The integer array.
- * @return A reference to this object.
- */
- public JsonObjectBuilder appendField(String key, JsonObject[] values) {
- if (values == null) {
- throw new IllegalArgumentException("JSON values must not be null");
- }
- String escapedValues = Arrays.stream(values)
- .map(JsonObject::toString)
- .collect(Collectors.joining(","));
- appendFieldUnescaped(key, "[" + escapedValues + "]");
- return this;
- }
-
- /**
- * Appends a field to the object.
- *
- * @param key The key of the field.
- * @param escapedValue The escaped value of the field.
- */
- private void appendFieldUnescaped(String key, String escapedValue) {
- if (builder == null) {
- throw new IllegalStateException("JSON has already been built");
- }
- if (key == null) {
- throw new IllegalArgumentException("JSON key must not be null");
- }
- if (hasAtLeastOneField) {
- builder.append(",");
- }
- builder.append("\"").append(escape(key)).append("\":").append(escapedValue);
-
- hasAtLeastOneField = true;
- }
-
- /**
- * Builds the JSON string and invalidates this builder.
- *
- * @return The built JSON string.
- */
- public JsonObject build() {
- if (builder == null) {
- throw new IllegalStateException("JSON has already been built");
- }
- JsonObject object = new JsonObject(builder.append("}").toString());
- builder = null;
- return object;
- }
-
- /**
- * Escapes the given string like stated in https://www.ietf.org/rfc/rfc4627.txt.
- *
- * This method escapes only the necessary characters '"', '\'. and '\u0000' - '\u001F'.
- * Compact escapes are not used (e.g., '\n' is escaped as "\u000a" and not as "\n").
- *
- * @param value The value to escape.
- * @return The escaped value.
- */
- private static String escape(String value) {
- final StringBuilder builder = new StringBuilder();
- for (int i = 0; i < value.length(); i++) {
- char c = value.charAt(i);
- if (c == '"') {
- builder.append("\\\"");
- } else if (c == '\\') {
- builder.append("\\\\");
- } else if (c <= '\u000F') {
- builder.append("\\u000").append(Integer.toHexString(c));
- } else if (c <= '\u001F') {
- builder.append("\\u00").append(Integer.toHexString(c));
- } else {
- builder.append(c);
- }
- }
- return builder.toString();
- }
-
- /**
- * A super simple representation of a JSON object.
- *
- *
This class only exists to make methods of the {@link JsonObjectBuilder} type-safe and
- * not allow a raw string inputs for methods like {@link JsonObjectBuilder#appendField(String, JsonObject)}.
- */
- public static class JsonObject {
-
- private final String value;
-
- private JsonObject(String value) {
- this.value = value;
- }
-
- @Override
- public String toString() {
- return value;
- }
- }
-
- }
-
- public static abstract class CustomChart {
-
- private final String chartId;
-
- protected CustomChart(String chartId) {
- if (chartId == null) {
- throw new IllegalArgumentException("chartId must not be null");
- }
- this.chartId = chartId;
- }
-
- public JsonObjectBuilder.JsonObject getRequestJsonObject(BiConsumer errorLogger, boolean logErrors) {
- JsonObjectBuilder builder = new JsonObjectBuilder();
- builder.appendField("chartId", chartId);
- try {
- JsonObjectBuilder.JsonObject data = getChartData();
- if (data == null) {
- // If the data is null we don't send the chart.
- return null;
- }
- builder.appendField("data", data);
- } catch (Throwable t) {
- if (logErrors) {
-
- errorLogger.accept("Failed to get data for custom chart with id " + chartId, t);
- }
- return null;
- }
- return builder.build();
- }
-
- protected abstract JsonObjectBuilder.JsonObject getChartData() throws Exception;
-
- }
-
- public static class MetricsBase {
- /**
- * The version of the Metrics class.
- */
- public static final String METRICS_VERSION = "2.1.1-SNAPSHOT";
-
- private static final ScheduledExecutorService scheduler =
- Executors.newScheduledThreadPool(1, task -> new Thread(task, "bStats-Metrics"));
- private static final String REPORT_URL = "https://bStats.org/api/v2/data/%s";
-
- private final String platform;
- private final String serverUuid;
- private final int serviceId;
- private final Consumer appendPlatformDataConsumer;
- private final Consumer appendServiceDataConsumer;
- private final Consumer submitTaskConsumer;
- private final Supplier checkServiceEnabledSupplier;
-
- private final BiConsumer errorLogger;
- private final Consumer infoLogger;
-
- private final boolean logErrors;
- private final boolean logSentData;
- private final boolean logResponseStatusText;
-
- private final Set customCharts = new HashSet<>();
- private final boolean enabled;
-
- /**
- * Creates a new MetricsBase class instance.
- *
- * @param platform The platform of the service.
- * @param serviceId The id of the service.
- * @param serverUuid The server uuid.
- * @param enabled Whether or not data sending is enabled.
- * @param appendPlatformDataConsumer A consumer that receives a {@code JsonObjectBuilder} and appends all
- * platform-specific data.
- * @param appendServiceDataConsumer A consumer that receives a {@code JsonObjectBuilder} and appends all
- * service-specific data.
- * @param submitTaskConsumer A consumer that takes a runnable with the submit task.
- * This can be used to delegate the data collection to a another thread to prevent
- * errors caused by concurrency. Can be {@code null}.
- * @param checkServiceEnabledSupplier A supplier to check if the service is still enabled.
- * @param errorLogger A consumer that accepts log message and an error.
- * @param infoLogger A consumer that accepts info log messages.
- * @param logErrors Whether or not errors should be logged.
- * @param logSentData Whether or not the sent data should be logged.
- * @param logResponseStatusText Whether or not the response status text should be logged.
- */
- public MetricsBase(
- String platform,
- String serverUuid,
- int serviceId,
- boolean enabled,
- Consumer appendPlatformDataConsumer,
- Consumer appendServiceDataConsumer,
- Consumer submitTaskConsumer,
- Supplier checkServiceEnabledSupplier,
- BiConsumer errorLogger,
- Consumer infoLogger,
- boolean logErrors,
- boolean logSentData,
- boolean logResponseStatusText
- ) {
- this.platform = platform;
- this.serverUuid = serverUuid;
- this.serviceId = serviceId;
- this.enabled = enabled;
- this.appendPlatformDataConsumer = appendPlatformDataConsumer;
- this.appendServiceDataConsumer = appendServiceDataConsumer;
- this.submitTaskConsumer = submitTaskConsumer;
- this.checkServiceEnabledSupplier = checkServiceEnabledSupplier;
- this.errorLogger = errorLogger;
- this.infoLogger = infoLogger;
- this.logErrors = logErrors;
- this.logSentData = logSentData;
- this.logResponseStatusText = logResponseStatusText;
-
- checkRelocation();
-
- if (enabled) {
- startSubmitting();
- }
- }
-
- public void addCustomChart(CustomChart chart) {
- this.customCharts.add(chart);
- }
-
- private void startSubmitting() {
- final Runnable submitTask = () -> {
- if (!enabled || !checkServiceEnabledSupplier.get()) { // Submitting data or service is disabled
- scheduler.shutdown();
- return;
- }
- if (submitTaskConsumer != null) {
- submitTaskConsumer.accept(this::submitData);
- } else {
- this.submitData();
- }
- };
-
- // Many servers tend to restart at a fixed time at xx:00 which causes an uneven distribution of requests on the
- // bStats backend. To circumvent this problem, we introduce some randomness into the initial and second delay.
- // WARNING: You must not modify and part of this Metrics class, including the submit delay or frequency!
- // WARNING: Modifying this code will get your plugin banned on bStats. Just don't do it!
- long initialDelay = (long) (1000 * 60 * (3 + Math.random() * 3));
- long secondDelay = (long) (1000 * 60 * (Math.random() * 30));
- scheduler.schedule(submitTask, initialDelay, TimeUnit.MILLISECONDS);
- scheduler.scheduleAtFixedRate(submitTask, initialDelay + secondDelay, 1000 * 60 * 30, TimeUnit.MILLISECONDS);
- }
-
- private void submitData() {
- final JsonObjectBuilder baseJsonBuilder = new JsonObjectBuilder();
- appendPlatformDataConsumer.accept(baseJsonBuilder);
-
- final JsonObjectBuilder serviceJsonBuilder = new JsonObjectBuilder();
- appendServiceDataConsumer.accept(serviceJsonBuilder);
-
- JsonObjectBuilder.JsonObject[] chartData = customCharts.stream()
- .map(customChart -> customChart.getRequestJsonObject(errorLogger, logErrors))
- .filter(Objects::nonNull)
- .toArray(JsonObjectBuilder.JsonObject[]::new);
-
- serviceJsonBuilder.appendField("id", serviceId);
- serviceJsonBuilder.appendField("customCharts", chartData);
- baseJsonBuilder.appendField("service", serviceJsonBuilder.build());
- baseJsonBuilder.appendField("serverUUID", serverUuid);
- baseJsonBuilder.appendField("metricsVersion", METRICS_VERSION);
-
- JsonObjectBuilder.JsonObject data = baseJsonBuilder.build();
-
- scheduler.execute(() -> {
- try {
- // Send the data
- sendData(data);
- } catch (Exception e) {
- // Something went wrong! :(
- if (logErrors) {
- errorLogger.accept("Could not submit bStats metrics data", e);
- }
- }
- });
- }
-
- private void sendData(JsonObjectBuilder.JsonObject data) throws Exception {
- if (logSentData) {
- infoLogger.accept("Sent bStats metrics data: " + data.toString());
- }
-
- String url = String.format(REPORT_URL, platform);
- HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();
-
- // Compress the data to save bandwidth
- byte[] compressedData = compress(data.toString());
-
- connection.setRequestMethod("POST");
- connection.addRequestProperty("Accept", "application/json");
- connection.addRequestProperty("Connection", "close");
- connection.addRequestProperty("Content-Encoding", "gzip");
- connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
- connection.setRequestProperty("Content-Type", "application/json");
- connection.setRequestProperty("User-Agent", "Metrics-Service/1");
-
- connection.setDoOutput(true);
- try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) {
- outputStream.write(compressedData);
- }
-
- StringBuilder builder = new StringBuilder();
- try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
- String line;
- while ((line = bufferedReader.readLine()) != null) {
- builder.append(line);
- }
- }
-
- if (logResponseStatusText) {
- infoLogger.accept("Sent data to bStats and received response: " + builder);
- }
- }
-
- /**
- * Checks that the class was properly relocated.
- */
- private void checkRelocation() {
- // You can use the property to disable the check in your test environment
- if (System.getProperty("bstats.relocatecheck") == null || !System.getProperty("bstats.relocatecheck").equals("false")) {
- // Maven's Relocate is clever and changes strings, too. So we have to use this little "trick" ... :D
- final String defaultPackage = new String(
- new byte[]{'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's'});
- final String examplePackage = new String(new byte[]{'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'});
- // We want to make sure no one just copy & pastes the example and uses the wrong package names
- if (MetricsBase.class.getPackage().getName().startsWith(defaultPackage) || MetricsBase.class.getPackage().getName().startsWith(examplePackage)) {
- throw new IllegalStateException("bStats Metrics class has not been relocated correctly!");
- }
- }
- }
-
- /**
- * Gzips the given string.
- *
- * @param str The string to gzip.
- * @return The gzipped string.
- */
- private static byte[] compress(final String str) throws IOException {
- if (str == null) {
- return null;
- }
- ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
- try (GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) {
- gzip.write(str.getBytes(StandardCharsets.UTF_8));
- }
- return outputStream.toByteArray();
- }
-
- }
-}
\ No newline at end of file
diff --git a/velocity/src/main/java/io/github/retrooper/packetevents/velocity/factory/VelocityPacketEventsBuilder.java b/velocity/src/main/java/io/github/retrooper/packetevents/velocity/factory/VelocityPacketEventsBuilder.java
index 0272829588..5204b59ef2 100644
--- a/velocity/src/main/java/io/github/retrooper/packetevents/velocity/factory/VelocityPacketEventsBuilder.java
+++ b/velocity/src/main/java/io/github/retrooper/packetevents/velocity/factory/VelocityPacketEventsBuilder.java
@@ -39,7 +39,6 @@
import com.velocitypowered.api.proxy.Player;
import com.velocitypowered.api.proxy.ProxyServer;
import com.velocitypowered.api.proxy.ServerConnection;
-import io.github.retrooper.packetevents.bstats.Metrics;
import io.github.retrooper.packetevents.impl.netty.NettyManagerImpl;
import io.github.retrooper.packetevents.impl.netty.manager.player.PlayerManagerAbstract;
import io.github.retrooper.packetevents.impl.netty.manager.protocol.ProtocolManagerAbstract;
@@ -195,42 +194,32 @@ public boolean isLoaded() {
public void init() {
// Load if we haven't loaded already
load();
- if (!initialized) {
- server.getEventManager().register(plugin.getInstance().orElse(null), PostLoginEvent.class,
- (event) -> {
- Player player = event.getPlayer();
- Object channel = PacketEvents.getAPI().getPlayerManager().getChannel(player);
- // This only happens if a player is a fake player
- if(channel == null) {
- return;
- }
- PacketEvents.getAPI().getInjector().setPlayer(channel, player);
-
- User user = PacketEvents.getAPI().getPlayerManager().getUser(player);
- if (user == null)
- return;
-
- UserLoginEvent loginEvent = new UserLoginEvent(user, player);
- PacketEvents.getAPI().getEventManager().callEvent(loginEvent);
- });
- if (settings.shouldCheckForUpdates()) {
- getUpdateChecker().handleUpdateCheck();
- }
-
- Object instance = plugin.getInstance().orElse(null);
- if (instance != null) {
- Metrics metrics = Metrics.createInstance(plugin, server, logger, dataDirectory, 11327);
+ if (initialized) return;
+
+ server.getEventManager().register(plugin.getInstance().orElse(null), PostLoginEvent.class,
+ (event) -> {
+ Player player = event.getPlayer();
+ Object channel = PacketEvents.getAPI().getPlayerManager().getChannel(player);
+ // This only happens if a player is a fake player
+ if(channel == null) {
+ return;
+ }
+ PacketEvents.getAPI().getInjector().setPlayer(channel, player);
- //Just to have an idea of which versions of packetevents people use
- metrics.addCustomChart(new Metrics.SimplePie("packetevents_version", () -> {
- return getVersion().toStringWithoutSnapshot();
- }));
- }
+ User user = PacketEvents.getAPI().getPlayerManager().getUser(player);
+ if (user == null)
+ return;
- PacketType.Play.Client.load();
- PacketType.Play.Server.load();
- initialized = true;
+ UserLoginEvent loginEvent = new UserLoginEvent(user, player);
+ PacketEvents.getAPI().getEventManager().callEvent(loginEvent);
+ });
+ if (settings.shouldCheckForUpdates()) {
+ getUpdateChecker().handleUpdateCheck();
}
+
+ PacketType.Play.Client.load();
+ PacketType.Play.Server.load();
+ initialized = true;
}
@Override