mirror of
https://github.com/RayzsYT/ProAntiTab.git
synced 2026-12-01 12:59:43 -05:00
Initial commit
This commit is contained in:
1 parent
b53e708fef
commit
742ebad8fb
30 files changed
+3217
No files matched your search
@@ -0,0 +1,98 @@
|
||||
package de.rayzs.pat.plugin;
|
||||
|
||||
import de.rayzs.pat.plugin.commands.BukkitCommand;
|
||||
import de.rayzs.pat.plugin.listeners.BukkitAntiTabListener;
|
||||
import de.rayzs.pat.plugin.listeners.BukkitBlockCommandListener;
|
||||
import de.rayzs.pat.plugin.listeners.BukkitPlayerConnectionListener;
|
||||
import de.rayzs.pat.plugin.logger.Logger;
|
||||
import de.rayzs.pat.plugin.metrics.bStats;
|
||||
import de.rayzs.pat.plugin.netty.PacketAnalyzer;
|
||||
import de.rayzs.pat.utils.configuration.Configurator;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.command.PluginCommand;
|
||||
import org.bukkit.plugin.*;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
import de.rayzs.pat.utils.*;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
public class BukkitLoader extends JavaPlugin {
|
||||
|
||||
private static Plugin plugin;
|
||||
private static java.util.logging.Logger logger;
|
||||
private int updaterTaskId;
|
||||
|
||||
@Override
|
||||
public void onLoad() {
|
||||
Configurator.createResourcedFile(getDataFolder(), "files\\bukkit-config.yml", "config.yml", false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
plugin = this;
|
||||
logger = getLogger();
|
||||
|
||||
Reflection.initialize(getServer());
|
||||
Storage.load();
|
||||
bStats.initialize(this);
|
||||
|
||||
PacketAnalyzer.injectAll();
|
||||
|
||||
BukkitCommand command = new BukkitCommand();
|
||||
Arrays.asList(new String[] { "proantitab", "pat" } ).forEach(commandName -> {
|
||||
PluginCommand pluginCommand = getCommand(commandName);
|
||||
pluginCommand.setExecutor(command);
|
||||
pluginCommand.setTabCompleter(command);
|
||||
});
|
||||
|
||||
PluginManager manager = getServer().getPluginManager();
|
||||
manager.registerEvents(new BukkitPlayerConnectionListener(), this);
|
||||
manager.registerEvents(new BukkitBlockCommandListener(), this);
|
||||
if(Reflection.getMinor() >= 18) manager.registerEvents(new BukkitAntiTabListener(), this);
|
||||
|
||||
startUpdaterTask();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
PacketAnalyzer.uninjectAll();
|
||||
}
|
||||
|
||||
public void startUpdaterTask() {
|
||||
if (!Storage.UPDATE_ENABLED) return;
|
||||
updaterTaskId = Bukkit.getScheduler().scheduleAsyncRepeatingTask(this, () -> {
|
||||
String result = new ConnectionBuilder().setUrl("https://www.rayzs.de/proantitab/api/version.php")
|
||||
.setProperties("ProAntiTab", "4654").connect().getResponse();
|
||||
if (!result.equals(getDescription().getVersion())) {
|
||||
Bukkit.getScheduler().cancelTask(updaterTaskId);
|
||||
if (result.equals("unknown")) {
|
||||
Logger.warning("Failed reaching web host! (firewall enabled? website down?)");
|
||||
} else if (result.equals("exception")) {
|
||||
Logger.warning("Failed creating web instance! (outdated java version?)");
|
||||
} else {
|
||||
Storage.OUTDATED_VERSION = true;
|
||||
Logger.warning("You're using an outdated version of this plugin!");
|
||||
Logger.warning("Please update it on: https://www.rayzs.de/products/proantitab/page");
|
||||
}
|
||||
}
|
||||
}, 20L, 20L * Storage.UPDATE_PERIOD);
|
||||
}
|
||||
|
||||
public static List<String> getNotBlockedCommands() {
|
||||
List<String> commands = new ArrayList<>();
|
||||
Bukkit.getHelpMap().getHelpTopics().stream()
|
||||
.filter(topic -> !topic.getName().contains(":") && topic.getName().startsWith("/") && !Storage.isCommandBlocked(topic.getName().replaceFirst("/", "")))
|
||||
.forEach(topic -> commands.add(topic.getName().replaceFirst("/", "")));
|
||||
return commands;
|
||||
}
|
||||
|
||||
public static Plugin getPlugin() {
|
||||
return plugin;
|
||||
}
|
||||
|
||||
public static java.util.logging.Logger getPluginLogger() {
|
||||
return logger;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package de.rayzs.pat.plugin;
|
||||
|
||||
import de.rayzs.pat.plugin.commands.BungeeCommand;
|
||||
import de.rayzs.pat.plugin.listeners.*;
|
||||
import de.rayzs.pat.plugin.logger.Logger;
|
||||
import de.rayzs.pat.plugin.metrics.bStats;
|
||||
import de.rayzs.pat.utils.ConnectionBuilder;
|
||||
import de.rayzs.pat.utils.Reflection;
|
||||
import de.rayzs.pat.utils.configuration.Configurator;
|
||||
import net.md_5.bungee.api.ProxyServer;
|
||||
import net.md_5.bungee.api.plugin.Plugin;
|
||||
import de.rayzs.pat.utils.Storage;
|
||||
import net.md_5.bungee.api.plugin.PluginManager;
|
||||
import net.md_5.bungee.api.scheduler.ScheduledTask;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public class BungeeLoader extends Plugin {
|
||||
|
||||
private static Plugin plugin;
|
||||
private static java.util.logging.Logger logger;
|
||||
private ScheduledTask updaterTask;
|
||||
|
||||
@Override
|
||||
public void onLoad() {
|
||||
Configurator.createResourcedFile(getDataFolder(), "files\\bungee-config.yml", "config.yml", false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
plugin = this;
|
||||
logger = getLogger();
|
||||
|
||||
Reflection.initialize(getProxy());
|
||||
Storage.load();
|
||||
bStats.initialize(this);
|
||||
PluginManager manager = ProxyServer.getInstance().getPluginManager();
|
||||
|
||||
Arrays.asList(new String[] { "bungeeproantitab", "bpat" } ).forEach(commandName -> {
|
||||
BungeeCommand command = new BungeeCommand(commandName);
|
||||
manager.registerCommand(this, command);
|
||||
});
|
||||
|
||||
manager.registerListener(this, new BungeePlayerConnectionListener());
|
||||
manager.registerListener(this, new BungeeAntiTabListener());
|
||||
manager.registerListener(this, new BungeeBlockCommandListener());
|
||||
|
||||
startUpdaterTask();
|
||||
}
|
||||
|
||||
public void startUpdaterTask() {
|
||||
if (!Storage.UPDATE_ENABLED) return;
|
||||
updaterTask = getProxy().getScheduler().schedule(this, () -> {
|
||||
String result = new ConnectionBuilder().setUrl("https://www.rayzs.de/proantitab/api/version.php")
|
||||
.setProperties("ProAntiTab", "4654").connect().getResponse();
|
||||
if (!result.equals(getDescription().getVersion())) {
|
||||
getProxy().getScheduler().cancel(updaterTask);
|
||||
if (result.equals("unknown")) {
|
||||
Logger.warning("Failed reaching web host! (firewall enabled? website down?)");
|
||||
} else if (result.equals("exception")) {
|
||||
Logger.warning("Failed creating web instance! (outdated java version?)");
|
||||
} else {
|
||||
Storage.OUTDATED_VERSION = true;
|
||||
Logger.warning("You're using an outdated version of this plugin!");
|
||||
Logger.warning("Please update it on: https://www.rayzs.de/products/proantitab/page");
|
||||
}
|
||||
}
|
||||
}, 20L, Storage.UPDATE_PERIOD, TimeUnit.MILLISECONDS);
|
||||
}
|
||||
|
||||
public static Plugin getPlugin() {
|
||||
return plugin;
|
||||
}
|
||||
|
||||
public static java.util.logging.Logger getPluginLogger() {
|
||||
return logger;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package de.rayzs.pat.plugin.commands;
|
||||
|
||||
import de.rayzs.pat.plugin.process.CommandProcess;
|
||||
import org.bukkit.command.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class BukkitCommand implements CommandExecutor, TabCompleter {
|
||||
|
||||
@Override
|
||||
public boolean onCommand(CommandSender commandSender, Command command, String s, String[] strings) {
|
||||
CommandProcess.handleCommand(commandSender, strings, s);
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> onTabComplete(CommandSender commandSender, Command command, String s, String[] strings) {
|
||||
return CommandProcess.handleTabComplete(commandSender, strings);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package de.rayzs.pat.plugin.commands;
|
||||
|
||||
import de.rayzs.pat.plugin.process.CommandProcess;
|
||||
import net.md_5.bungee.api.CommandSender;
|
||||
import net.md_5.bungee.api.plugin.*;
|
||||
|
||||
public class BungeeCommand extends Command implements TabExecutor {
|
||||
|
||||
public BungeeCommand(String name) {
|
||||
super(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(CommandSender commandSender, String[] strings) {
|
||||
CommandProcess.handleCommand(commandSender, strings, "bpat");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Iterable<String> onTabComplete(CommandSender commandSender, String[] strings) {
|
||||
return CommandProcess.handleTabComplete(commandSender, strings);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package de.rayzs.pat.plugin.listeners;
|
||||
|
||||
import org.bukkit.event.player.PlayerCommandSendEvent;
|
||||
import org.bukkit.entity.Player;
|
||||
import de.rayzs.pat.utils.*;
|
||||
import org.bukkit.event.*;
|
||||
import org.bukkit.Bukkit;
|
||||
|
||||
public class BukkitAntiTabListener implements Listener {
|
||||
|
||||
@EventHandler (priority = EventPriority.LOWEST)
|
||||
public void onPlayerCommandSend(PlayerCommandSendEvent event) {
|
||||
Player player = event.getPlayer();
|
||||
if(PermissionUtil.hasBypassPermission(player)) return;
|
||||
|
||||
for (int i = 0; i < event.getCommands().size(); i++) {
|
||||
String command = (String) event.getCommands().toArray()[i], tempName = command;
|
||||
|
||||
if (tempName.contains(":")) tempName = tempName.split(":")[1];
|
||||
|
||||
if (Storage.isCommandBlocked(tempName)) {
|
||||
if(PermissionUtil.hasBypassPermission(player, tempName)) {
|
||||
event.getCommands().add(command);
|
||||
if(!event.getCommands().contains(tempName)) event.getCommands().add(tempName);
|
||||
}
|
||||
else {
|
||||
event.getCommands().remove(command);
|
||||
if(event.getCommands().contains(tempName)) event.getCommands().remove(tempName);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void updateCommands() {
|
||||
if(Reflection.getMinor() >= 18) Bukkit.getOnlinePlayers().forEach(Player::updateCommands);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package de.rayzs.pat.plugin.listeners;
|
||||
|
||||
import de.rayzs.pat.plugin.logger.Logger;
|
||||
import de.rayzs.pat.utils.PermissionUtil;
|
||||
import de.rayzs.pat.utils.Storage;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.*;
|
||||
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
|
||||
|
||||
public class BukkitBlockCommandListener implements Listener {
|
||||
|
||||
@EventHandler (priority = EventPriority.LOWEST)
|
||||
public void onPlayerCommandProcess(PlayerCommandPreprocessEvent event) {
|
||||
if(!Storage.CANCEL_COMMANDS) return;
|
||||
|
||||
Player player = event.getPlayer();
|
||||
String rawCommand = event.getMessage(), command = rawCommand.replaceFirst("/", ""), commandLowerCased = command.toLowerCase();
|
||||
if (command.contains(":")) command = command.split(":")[1];
|
||||
|
||||
if (!Storage.isCommandBlocked(commandLowerCased)) return;
|
||||
|
||||
if (PermissionUtil.hasBypassPermission(player, command)) return;
|
||||
|
||||
player.sendMessage(Storage.CANCEL_COMMANDS_MESSAGE.replace("%command%", rawCommand.replaceFirst("/", "")));
|
||||
|
||||
final String alertMessage = Storage.NOTIFY_ALERT.replace("%player%", player.getName()).replace("%command%", command);
|
||||
Storage.NOTIFY_PLAYERS.stream().filter(uuid -> Bukkit.getServer().getPlayer(uuid) != null).forEach(uuid -> {
|
||||
Player notifier = Bukkit.getServer().getPlayer(uuid);
|
||||
notifier.sendMessage(alertMessage);
|
||||
});
|
||||
if(Storage.CONSOLE_NOTIFICATION_ENABLED) Logger.info(alertMessage);
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package de.rayzs.pat.plugin.listeners;
|
||||
|
||||
import de.rayzs.pat.plugin.BukkitLoader;
|
||||
import de.rayzs.pat.plugin.netty.PacketAnalyzer;
|
||||
import de.rayzs.pat.utils.PermissionUtil;
|
||||
import de.rayzs.pat.utils.Reflection;
|
||||
import de.rayzs.pat.utils.Storage;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.event.player.*;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.*;
|
||||
|
||||
public class BukkitPlayerConnectionListener implements Listener {
|
||||
|
||||
@EventHandler (priority = EventPriority.LOWEST)
|
||||
public void onPlayerJoin(PlayerJoinEvent event) {
|
||||
Player player = event.getPlayer();
|
||||
if(!PacketAnalyzer.inject(player) && Reflection.getMinor() <= 17) player.kickPlayer("Failed to inject player!");
|
||||
|
||||
if(Storage.OUTDATED_VERSION && (PermissionUtil.hasPermission(player, "update"))) {
|
||||
Bukkit.getScheduler().runTaskLater(BukkitLoader.getPlugin(), () -> {
|
||||
if(player.isOnline()) {
|
||||
player.sendMessage("§8[§4ProAntiTab§8] §cYou're using an outdated version of this plugin!");
|
||||
player.sendMessage("§8[§4ProAntiTab§8] §cPlease update it on: https://www.rayzs.de/products/proantitab/page");
|
||||
}
|
||||
}, 20);
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler (priority = EventPriority.LOWEST)
|
||||
public void onPlayerQuit(PlayerQuitEvent event) {
|
||||
Player player = event.getPlayer();
|
||||
PacketAnalyzer.uninject(player.getUniqueId());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package de.rayzs.pat.plugin.listeners;
|
||||
|
||||
import de.rayzs.pat.utils.PermissionUtil;
|
||||
import de.rayzs.pat.utils.Storage;
|
||||
import net.md_5.bungee.api.connection.ProxiedPlayer;
|
||||
import net.md_5.bungee.api.event.TabCompleteEvent;
|
||||
import net.md_5.bungee.api.event.TabCompleteResponseEvent;
|
||||
import net.md_5.bungee.api.plugin.Listener;
|
||||
import net.md_5.bungee.event.*;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public class BungeeAntiTabListener implements Listener {
|
||||
|
||||
@EventHandler (priority = EventPriority.LOWEST)
|
||||
public void onTabComplete(TabCompleteEvent event) {
|
||||
if(!(event.getSender() instanceof ProxiedPlayer)) return;
|
||||
|
||||
ProxiedPlayer player = (ProxiedPlayer) event.getSender();
|
||||
if(PermissionUtil.hasBypassPermission(player)) return;
|
||||
|
||||
for (int i = 0; i < event.getSuggestions().size(); i++) {
|
||||
String command = (String) event.getSuggestions().toArray()[i], tempName = command;
|
||||
|
||||
if (tempName.contains(":")) tempName = tempName.split(":")[1];
|
||||
if (Storage.isCommandBlocked(tempName)) {
|
||||
if(PermissionUtil.hasBypassPermission(player, tempName)) event.getSuggestions().add(command);
|
||||
else event.getSuggestions().remove(command);
|
||||
}
|
||||
}
|
||||
|
||||
String command = event.getCursor();
|
||||
if(command.contains(" ")) command = command.split(" ")[0].toLowerCase();
|
||||
if (command.contains(":")) command = command.split(":")[1];
|
||||
if(command.startsWith("/")) command = command.replaceFirst("/", "");
|
||||
|
||||
if (!Storage.isCommandBlocked(command)) return;
|
||||
event.setCancelled(!PermissionUtil.hasBypassPermission(player, command));
|
||||
}
|
||||
|
||||
@EventHandler (priority = EventPriority.LOWEST)
|
||||
public void onTabComplete(TabCompleteResponseEvent event) {
|
||||
if(!(event.getReceiver() instanceof ProxiedPlayer)) return;
|
||||
|
||||
ProxiedPlayer player = (ProxiedPlayer) event.getReceiver();
|
||||
if(PermissionUtil.hasBypassPermission(player)) return;
|
||||
|
||||
int size = event.getSuggestions().size();
|
||||
List<String> dummy = new ArrayList<>(event.getSuggestions());
|
||||
|
||||
for (int i = 0; i < size; i++) {
|
||||
String command = dummy.get(i), tempName = command;
|
||||
|
||||
if (tempName.startsWith("/")) tempName = tempName.replaceFirst("/", "");
|
||||
if (tempName.contains(":")) tempName = tempName.split(":")[1];
|
||||
|
||||
if (!Storage.isCommandBlocked(tempName)) continue;
|
||||
if(PermissionUtil.hasBypassPermission(player, tempName)) continue;
|
||||
event.getSuggestions().remove(command);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package de.rayzs.pat.plugin.listeners;
|
||||
|
||||
import de.rayzs.pat.plugin.logger.Logger;
|
||||
import de.rayzs.pat.utils.PermissionUtil;
|
||||
import de.rayzs.pat.utils.Storage;
|
||||
import net.md_5.bungee.api.ProxyServer;
|
||||
import net.md_5.bungee.api.connection.*;
|
||||
import net.md_5.bungee.api.event.ChatEvent;
|
||||
import net.md_5.bungee.api.plugin.Listener;
|
||||
import net.md_5.bungee.event.*;
|
||||
|
||||
public class BungeeBlockCommandListener implements Listener {
|
||||
|
||||
@EventHandler (priority = EventPriority.LOWEST)
|
||||
public void onChat(ChatEvent event) {
|
||||
if(!Storage.CANCEL_COMMANDS) return;
|
||||
|
||||
Connection connection = event.getSender();
|
||||
if(!(connection instanceof ProxiedPlayer) || !event.getMessage().startsWith("/")) return;
|
||||
|
||||
ProxiedPlayer player = (ProxiedPlayer) connection;
|
||||
String rawCommand = event.getMessage(), command = rawCommand.replaceFirst("/", "").toLowerCase();
|
||||
if(command.contains(":")) command = command.split(":")[1];
|
||||
|
||||
if(!Storage.isCommandBlocked(command) || PermissionUtil.hasBypassPermission(player, command)) return;
|
||||
player.sendMessage(Storage.CANCEL_COMMANDS_MESSAGE.replace("%command%", rawCommand.replaceFirst("/", "")));
|
||||
|
||||
final String alertMessage = Storage.NOTIFY_ALERT.replace("%player%", player.getName()).replace("%command%", command);
|
||||
Storage.NOTIFY_PLAYERS.stream().filter(uuid -> ProxyServer.getInstance().getPlayer(uuid) != null).forEach(uuid -> {
|
||||
ProxiedPlayer notifier = ProxyServer.getInstance().getPlayer(uuid);
|
||||
notifier.sendMessage(alertMessage);
|
||||
});
|
||||
if(Storage.CONSOLE_NOTIFICATION_ENABLED) Logger.info(alertMessage);
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package de.rayzs.pat.plugin.listeners;
|
||||
|
||||
import de.rayzs.pat.plugin.BungeeLoader;
|
||||
import de.rayzs.pat.utils.PermissionUtil;
|
||||
import de.rayzs.pat.utils.Storage;
|
||||
import net.md_5.bungee.api.ProxyServer;
|
||||
import net.md_5.bungee.api.connection.ProxiedPlayer;
|
||||
import net.md_5.bungee.api.event.PostLoginEvent;
|
||||
import net.md_5.bungee.api.plugin.Listener;
|
||||
import net.md_5.bungee.event.EventHandler;
|
||||
import net.md_5.bungee.event.EventPriority;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public class BungeePlayerConnectionListener implements Listener {
|
||||
|
||||
@EventHandler (priority = EventPriority.LOWEST)
|
||||
public void onPostLogin(PostLoginEvent event) {
|
||||
ProxiedPlayer player = event.getPlayer();
|
||||
if(Storage.OUTDATED_VERSION && (PermissionUtil.hasPermission(player, "update"))) {
|
||||
ProxyServer.getInstance().getScheduler().schedule(BungeeLoader.getPlugin(), () -> {
|
||||
if (player.isConnected()) {
|
||||
player.sendMessage("§8[§4ProAntiTab§8] §cYou're using an outdated version of this plugin!");
|
||||
player.sendMessage("§8[§4ProAntiTab§8] §cPlease update it on: https://www.rayzs.de/products/proantitab/page");
|
||||
}
|
||||
}, 1, TimeUnit.SECONDS);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package de.rayzs.pat.plugin.logger;
|
||||
|
||||
import de.rayzs.pat.plugin.*;
|
||||
import de.rayzs.pat.utils.Reflection;
|
||||
import net.md_5.bungee.api.ProxyServer;
|
||||
import java.util.logging.Level;
|
||||
import org.bukkit.Bukkit;
|
||||
|
||||
public class Logger {
|
||||
|
||||
private final static java.util.logging.Logger LOGGER =
|
||||
Reflection.isBungeecordServer()
|
||||
? BungeeLoader.getPluginLogger()
|
||||
: BukkitLoader.getPluginLogger();
|
||||
|
||||
public static void info(String text) { send(Priority.INFO, text); }
|
||||
public static void warning(String text) { send(Priority.WARNING, text); }
|
||||
|
||||
protected static void send(Priority priority, String text) {
|
||||
boolean hasColors = text.contains("§");
|
||||
if(hasColors) {
|
||||
if (Reflection.isBungeecordServer()) ProxyServer.getInstance().getConsole().sendMessage(text);
|
||||
else Bukkit.getServer().getConsoleSender().sendMessage(text);
|
||||
return;
|
||||
}
|
||||
|
||||
Level level = Level.parse(priority.name());
|
||||
LOGGER.log(level, text);
|
||||
}
|
||||
|
||||
protected enum Priority { INFO, WARNING }
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package de.rayzs.pat.plugin.metrics;
|
||||
|
||||
import de.rayzs.pat.plugin.metrics.impl.BukkitMetrics;
|
||||
import de.rayzs.pat.plugin.metrics.impl.BungeeMetrics;
|
||||
import de.rayzs.pat.utils.Reflection;
|
||||
|
||||
public class bStats {
|
||||
|
||||
public static void initialize(Object pluginObj) {
|
||||
if(Reflection.isBungeecordServer()) new BungeeMetrics(pluginObj, 20090);
|
||||
else new BukkitMetrics(pluginObj, 20089);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,722 @@
|
||||
package de.rayzs.pat.plugin.metrics.impl;
|
||||
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
import com.google.gson.JsonPrimitive;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
import org.bukkit.plugin.RegisteredServiceProvider;
|
||||
import org.bukkit.plugin.ServicePriority;
|
||||
|
||||
import javax.net.ssl.HttpsURLConnection;
|
||||
import java.io.*;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.net.URL;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.logging.Level;
|
||||
import java.util.zip.GZIPOutputStream;
|
||||
|
||||
/**
|
||||
* bStats collects some data for plugin authors.
|
||||
* <p>
|
||||
* Check out https://bStats.org/ to learn more about bStats!
|
||||
*/
|
||||
@SuppressWarnings({"WeakerAccess", "unused"})
|
||||
public class BukkitMetrics {
|
||||
|
||||
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', 'k', 'k', 'i', 't'});
|
||||
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 (BukkitMetrics.class.getPackage().getName().equals(defaultPackage) || BukkitMetrics.class.getPackage().getName().equals(examplePackage)) {
|
||||
throw new IllegalStateException("bStats Metrics class has not been relocated correctly!");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// This ThreadFactory enforces the naming convention for our Threads
|
||||
private final ThreadFactory threadFactory = task -> new Thread(task, "bStats-Metrics");
|
||||
|
||||
// Executor service for requests
|
||||
// We use an executor service because the Bukkit scheduler is affected by server lags
|
||||
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1, threadFactory);
|
||||
|
||||
// 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/bukkit";
|
||||
|
||||
// Is bStats enabled on this server?
|
||||
private boolean enabled;
|
||||
|
||||
// Should failed requests be logged?
|
||||
private static boolean logFailedRequests;
|
||||
|
||||
// Should the sent data be logged?
|
||||
private static boolean logSentData;
|
||||
|
||||
// Should the response text be logged?
|
||||
private static boolean logResponseStatusText;
|
||||
|
||||
// The uuid of the server
|
||||
private static String serverUUID;
|
||||
|
||||
// The plugin
|
||||
private final Plugin plugin;
|
||||
|
||||
// The plugin id
|
||||
private final int pluginId;
|
||||
|
||||
// A list with all custom charts
|
||||
private final List<CustomChart> charts = new ArrayList<>();
|
||||
|
||||
public BukkitMetrics(Object pluginObj, int pluginId) {
|
||||
if (pluginObj == null) throw new IllegalArgumentException("Plugin cannot be null!");
|
||||
if(!(pluginObj instanceof Plugin)) throw new IllegalArgumentException("pluginObj has an invalid instance!");
|
||||
Plugin plugin = (Plugin) pluginObj;
|
||||
|
||||
this.plugin = plugin;
|
||||
this.pluginId = pluginId;
|
||||
|
||||
// Get the config file
|
||||
File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats");
|
||||
File configFile = new File(bStatsFolder, "config.yml");
|
||||
YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile);
|
||||
|
||||
// Check if the config file exists
|
||||
if (!config.isSet("serverUuid")) {
|
||||
|
||||
// Add default values
|
||||
config.addDefault("enabled", true);
|
||||
// Every server gets it's unique random id.
|
||||
config.addDefault("serverUuid", UUID.randomUUID().toString());
|
||||
// Should failed request be logged?
|
||||
config.addDefault("logFailedRequests", false);
|
||||
// Should the sent data be logged?
|
||||
config.addDefault("logSentData", false);
|
||||
// Should the response text be logged?
|
||||
config.addDefault("logResponseStatusText", false);
|
||||
|
||||
// Inform the server owners about bStats
|
||||
config.options().header(
|
||||
"bStats collects some data for plugin authors like how many servers are using their plugins.\n" +
|
||||
"To honor their work, you should not disable it.\n" +
|
||||
"This has nearly no effect on the server performance!\n" +
|
||||
"Check out https://bStats.org/ to learn more :)"
|
||||
).copyDefaults(true);
|
||||
try {
|
||||
config.save(configFile);
|
||||
} catch (IOException ignored) { }
|
||||
}
|
||||
|
||||
// Load the data
|
||||
enabled = config.getBoolean("enabled", true);
|
||||
serverUUID = config.getString("serverUuid");
|
||||
logFailedRequests = config.getBoolean("logFailedRequests", false);
|
||||
logSentData = config.getBoolean("logSentData", false);
|
||||
logResponseStatusText = config.getBoolean("logResponseStatusText", false);
|
||||
|
||||
if (enabled) {
|
||||
boolean found = false;
|
||||
// Search for all other bStats Metrics classes to see if we are the first one
|
||||
for (Class<?> service : Bukkit.getServicesManager().getKnownServices()) {
|
||||
try {
|
||||
service.getField("B_STATS_VERSION"); // Our identifier :)
|
||||
found = true; // We aren't the first
|
||||
break;
|
||||
} catch (NoSuchFieldException ignored) { }
|
||||
}
|
||||
// Register our service
|
||||
Bukkit.getServicesManager().register(BukkitMetrics.class, this, plugin, ServicePriority.Normal);
|
||||
if (!found) {
|
||||
// We are the first!
|
||||
startSubmitting();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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) {
|
||||
throw new IllegalArgumentException("Chart cannot be null!");
|
||||
}
|
||||
charts.add(chart);
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the Scheduler which submits our data every 30 minutes.
|
||||
*/
|
||||
private void startSubmitting() {
|
||||
final Runnable submitTask = () -> {
|
||||
if (!plugin.isEnabled()) { // Plugin was disabled
|
||||
scheduler.shutdown();
|
||||
return;
|
||||
}
|
||||
// Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler
|
||||
// Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;)
|
||||
Bukkit.getScheduler().runTask(plugin, 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);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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); // Append the name of the plugin
|
||||
data.addProperty("id", pluginId); // Append the id of the plugin
|
||||
data.addProperty("pluginVersion", pluginVersion); // Append the version of the plugin
|
||||
JsonArray customCharts = new JsonArray();
|
||||
for (CustomChart customChart : charts) {
|
||||
// Add the data of the custom charts
|
||||
JsonObject chart = customChart.getRequestJsonObject();
|
||||
if (chart == null) { // If the chart is null, we skip it
|
||||
continue;
|
||||
}
|
||||
customCharts.add(chart);
|
||||
}
|
||||
data.add("customCharts", customCharts);
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the server specific data.
|
||||
*
|
||||
* @return The server specific data.
|
||||
*/
|
||||
private JsonObject getServerData() {
|
||||
// Minecraft specific data
|
||||
int playerAmount;
|
||||
try {
|
||||
// Around MC 1.8 the return type was changed to a collection from an array,
|
||||
// This fixes java.lang.NoSuchMethodError: org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection;
|
||||
Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers");
|
||||
playerAmount = onlinePlayersMethod.getReturnType().equals(Collection.class)
|
||||
? ((Collection<?>) onlinePlayersMethod.invoke(Bukkit.getServer())).size()
|
||||
: ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length;
|
||||
} catch (Exception e) {
|
||||
playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed
|
||||
}
|
||||
int onlineMode = Bukkit.getOnlineMode() ? 1 : 0;
|
||||
String bukkitVersion = Bukkit.getVersion();
|
||||
String bukkitName = Bukkit.getName();
|
||||
|
||||
// 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("onlineMode", onlineMode);
|
||||
data.addProperty("bukkitVersion", bukkitVersion);
|
||||
data.addProperty("bukkitName", bukkitName);
|
||||
|
||||
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();
|
||||
|
||||
JsonArray pluginData = new JsonArray();
|
||||
// Search for all other bStats Metrics classes to get their plugin data
|
||||
for (Class<?> service : Bukkit.getServicesManager().getKnownServices()) {
|
||||
try {
|
||||
service.getField("B_STATS_VERSION"); // Our identifier :)
|
||||
|
||||
for (RegisteredServiceProvider<?> provider : Bukkit.getServicesManager().getRegistrations(service)) {
|
||||
try {
|
||||
Object plugin = provider.getService().getMethod("getPluginData").invoke(provider.getProvider());
|
||||
if (plugin instanceof JsonObject) {
|
||||
pluginData.add((JsonObject) plugin);
|
||||
} else { // old bstats version compatibility
|
||||
try {
|
||||
Class<?> jsonObjectJsonSimple = Class.forName("org.json.simple.JSONObject");
|
||||
if (plugin.getClass().isAssignableFrom(jsonObjectJsonSimple)) {
|
||||
Method jsonStringGetter = jsonObjectJsonSimple.getDeclaredMethod("toJSONString");
|
||||
jsonStringGetter.setAccessible(true);
|
||||
String jsonString = (String) jsonStringGetter.invoke(plugin);
|
||||
JsonObject object = new JsonParser().parse(jsonString).getAsJsonObject();
|
||||
pluginData.add(object);
|
||||
}
|
||||
} catch (ClassNotFoundException e) {
|
||||
// minecraft version 1.14+
|
||||
if (logFailedRequests) {
|
||||
this.plugin.getLogger().log(Level.SEVERE, "Encountered unexpected exception", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { }
|
||||
}
|
||||
} catch (NoSuchFieldException ignored) { }
|
||||
}
|
||||
|
||||
data.add("plugins", pluginData);
|
||||
|
||||
// Create a new thread for the connection to the bStats server
|
||||
new Thread(() -> {
|
||||
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 of " + plugin.getName(), e);
|
||||
}
|
||||
}
|
||||
}).start();
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 (Bukkit.isPrimaryThread()) {
|
||||
throw new IllegalAccessException("This method must not be called from the main thread!");
|
||||
}
|
||||
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
|
||||
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() {
|
||||
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) {
|
||||
Bukkit.getLogger().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<String> 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<String> 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<Map<String, Integer>> 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<Map<String, Integer>> callable) {
|
||||
super(chartId);
|
||||
this.callable = callable;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected JsonObject getChartData() throws Exception {
|
||||
JsonObject data = new JsonObject();
|
||||
JsonObject values = new JsonObject();
|
||||
Map<String, Integer> map = callable.call();
|
||||
if (map == null || map.isEmpty()) {
|
||||
// Null = skip the chart
|
||||
return null;
|
||||
}
|
||||
boolean allSkipped = true;
|
||||
for (Map.Entry<String, Integer> 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<Map<String, Map<String, Integer>>> 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<Map<String, Map<String, Integer>>> callable) {
|
||||
super(chartId);
|
||||
this.callable = callable;
|
||||
}
|
||||
|
||||
@Override
|
||||
public JsonObject getChartData() throws Exception {
|
||||
JsonObject data = new JsonObject();
|
||||
JsonObject values = new JsonObject();
|
||||
Map<String, Map<String, Integer>> map = callable.call();
|
||||
if (map == null || map.isEmpty()) {
|
||||
// Null = skip the chart
|
||||
return null;
|
||||
}
|
||||
boolean reallyAllSkipped = true;
|
||||
for (Map.Entry<String, Map<String, Integer>> entryValues : map.entrySet()) {
|
||||
JsonObject value = new JsonObject();
|
||||
boolean allSkipped = true;
|
||||
for (Map.Entry<String, Integer> 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<Integer> 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<Integer> 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<Map<String, Integer>> 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<Map<String, Integer>> callable) {
|
||||
super(chartId);
|
||||
this.callable = callable;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected JsonObject getChartData() throws Exception {
|
||||
JsonObject data = new JsonObject();
|
||||
JsonObject values = new JsonObject();
|
||||
Map<String, Integer> map = callable.call();
|
||||
if (map == null || map.isEmpty()) {
|
||||
// Null = skip the chart
|
||||
return null;
|
||||
}
|
||||
boolean allSkipped = true;
|
||||
for (Map.Entry<String, Integer> 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<Map<String, Integer>> 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<Map<String, Integer>> callable) {
|
||||
super(chartId);
|
||||
this.callable = callable;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected JsonObject getChartData() throws Exception {
|
||||
JsonObject data = new JsonObject();
|
||||
JsonObject values = new JsonObject();
|
||||
Map<String, Integer> map = callable.call();
|
||||
if (map == null || map.isEmpty()) {
|
||||
// Null = skip the chart
|
||||
return null;
|
||||
}
|
||||
for (Map.Entry<String, Integer> 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<Map<String, int[]>> 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<Map<String, int[]>> callable) {
|
||||
super(chartId);
|
||||
this.callable = callable;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected JsonObject getChartData() throws Exception {
|
||||
JsonObject data = new JsonObject();
|
||||
JsonObject values = new JsonObject();
|
||||
Map<String, int[]> map = callable.call();
|
||||
if (map == null || map.isEmpty()) {
|
||||
// Null = skip the chart
|
||||
return null;
|
||||
}
|
||||
boolean allSkipped = true;
|
||||
for (Map.Entry<String, int[]> 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,761 @@
|
||||
package de.rayzs.pat.plugin.metrics.impl;
|
||||
|
||||
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;
|
||||
|
||||
/**
|
||||
* bStats collects some data for plugin authors.
|
||||
* <p>
|
||||
* Check out https://bStats.org/ to learn more about bStats!
|
||||
*/
|
||||
@SuppressWarnings({"WeakerAccess", "unused"})
|
||||
public class BungeeMetrics {
|
||||
|
||||
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 (BungeeMetrics.class.getPackage().getName().equals(defaultPackage) || BungeeMetrics.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<Object> knownMetricsInstances = new ArrayList<>();
|
||||
|
||||
// A list with all custom charts
|
||||
private final List<CustomChart> charts = new ArrayList<>();
|
||||
|
||||
/**
|
||||
* Class constructor.
|
||||
*
|
||||
* @param pluginObj The plugin which stats should be submitted.
|
||||
* @param pluginId The id of the plugin.
|
||||
* It can be found at <a href="https://bstats.org/what-is-my-plugin-id">What is my plugin id?</a>
|
||||
*/
|
||||
public BungeeMetrics(Object pluginObj, int pluginId) {
|
||||
if (pluginObj == null) throw new IllegalArgumentException("Plugin cannot be null!");
|
||||
if(!(pluginObj instanceof Plugin)) throw new IllegalArgumentException("pluginObj has an invalid instance!");
|
||||
Plugin plugin = (Plugin) pluginObj;
|
||||
|
||||
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<String> 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<String> 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<Map<String, Integer>> 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<Map<String, Integer>> callable) {
|
||||
super(chartId);
|
||||
this.callable = callable;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected JsonObject getChartData() throws Exception {
|
||||
JsonObject data = new JsonObject();
|
||||
JsonObject values = new JsonObject();
|
||||
Map<String, Integer> map = callable.call();
|
||||
if (map == null || map.isEmpty()) {
|
||||
// Null = skip the chart
|
||||
return null;
|
||||
}
|
||||
boolean allSkipped = true;
|
||||
for (Map.Entry<String, Integer> 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<Map<String, Map<String, Integer>>> 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<Map<String, Map<String, Integer>>> callable) {
|
||||
super(chartId);
|
||||
this.callable = callable;
|
||||
}
|
||||
|
||||
@Override
|
||||
public JsonObject getChartData() throws Exception {
|
||||
JsonObject data = new JsonObject();
|
||||
JsonObject values = new JsonObject();
|
||||
Map<String, Map<String, Integer>> map = callable.call();
|
||||
if (map == null || map.isEmpty()) {
|
||||
// Null = skip the chart
|
||||
return null;
|
||||
}
|
||||
boolean reallyAllSkipped = true;
|
||||
for (Map.Entry<String, Map<String, Integer>> entryValues : map.entrySet()) {
|
||||
JsonObject value = new JsonObject();
|
||||
boolean allSkipped = true;
|
||||
for (Map.Entry<String, Integer> 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<Integer> 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<Integer> 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<Map<String, Integer>> 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<Map<String, Integer>> callable) {
|
||||
super(chartId);
|
||||
this.callable = callable;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected JsonObject getChartData() throws Exception {
|
||||
JsonObject data = new JsonObject();
|
||||
JsonObject values = new JsonObject();
|
||||
Map<String, Integer> map = callable.call();
|
||||
if (map == null || map.isEmpty()) {
|
||||
// Null = skip the chart
|
||||
return null;
|
||||
}
|
||||
boolean allSkipped = true;
|
||||
for (Map.Entry<String, Integer> 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<Map<String, Integer>> 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<Map<String, Integer>> callable) {
|
||||
super(chartId);
|
||||
this.callable = callable;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected JsonObject getChartData() throws Exception {
|
||||
JsonObject data = new JsonObject();
|
||||
JsonObject values = new JsonObject();
|
||||
Map<String, Integer> map = callable.call();
|
||||
if (map == null || map.isEmpty()) {
|
||||
// Null = skip the chart
|
||||
return null;
|
||||
}
|
||||
for (Map.Entry<String, Integer> 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<Map<String, int[]>> 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<Map<String, int[]>> callable) {
|
||||
super(chartId);
|
||||
this.callable = callable;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected JsonObject getChartData() throws Exception {
|
||||
JsonObject data = new JsonObject();
|
||||
JsonObject values = new JsonObject();
|
||||
Map<String, int[]> map = callable.call();
|
||||
if (map == null || map.isEmpty()) {
|
||||
// Null = skip the chart
|
||||
return null;
|
||||
}
|
||||
boolean allSkipped = true;
|
||||
for (Map.Entry<String, int[]> 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;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package de.rayzs.pat.plugin.netty;
|
||||
|
||||
import de.rayzs.pat.utils.PermissionUtil;
|
||||
import de.rayzs.pat.utils.Reflection;
|
||||
import de.rayzs.pat.utils.Storage;
|
||||
import io.netty.channel.*;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
public class PacketAnalyzer {
|
||||
|
||||
public static final ConcurrentHashMap<UUID, Channel> INJECTED_PLAYERS = new ConcurrentHashMap<>();
|
||||
public static final String CHANNEL_NAME = "pat-packethandler", HANDLER_NAME = "packet_handler";
|
||||
|
||||
public static void injectAll() {
|
||||
Bukkit.getOnlinePlayers().forEach(PacketAnalyzer::inject);
|
||||
}
|
||||
|
||||
public static void uninjectAll() {
|
||||
PacketAnalyzer.INJECTED_PLAYERS.keySet().forEach(PacketAnalyzer::uninject);
|
||||
PacketAnalyzer.INJECTED_PLAYERS.clear();
|
||||
}
|
||||
|
||||
public static boolean inject(Player player) {
|
||||
if(Reflection.getMinor() >= 18) return true;
|
||||
try {
|
||||
Channel channel = Reflection.getPlayerChannel(player);
|
||||
if(channel == null) {
|
||||
System.err.println("Failed to inject " + player.getName() + "! Channel is null.");
|
||||
return false;
|
||||
}
|
||||
|
||||
channel.pipeline().addAfter(PacketAnalyzer.HANDLER_NAME, PacketAnalyzer.CHANNEL_NAME, new PacketDecoder(player));
|
||||
PacketAnalyzer.INJECTED_PLAYERS.put(player.getUniqueId(), channel);
|
||||
} catch (Throwable throwable) {
|
||||
throwable.printStackTrace();
|
||||
return false;
|
||||
} return true;
|
||||
}
|
||||
|
||||
public static void uninject(UUID uuid) {
|
||||
if(Reflection.getMinor() >= 18) return;
|
||||
if(PacketAnalyzer.INJECTED_PLAYERS.containsKey(uuid)) {
|
||||
Channel channel = PacketAnalyzer.INJECTED_PLAYERS.get(uuid);
|
||||
if(channel != null) {
|
||||
PacketAnalyzer.INJECTED_PLAYERS.remove(uuid);
|
||||
channel.eventLoop().submit(() -> {
|
||||
ChannelPipeline pipeline = channel.pipeline();
|
||||
if (pipeline.names().contains(PacketAnalyzer.CHANNEL_NAME)) pipeline.remove(PacketAnalyzer.CHANNEL_NAME);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static class PacketDecoder extends ChannelDuplexHandler {
|
||||
|
||||
Player player;
|
||||
PacketDecoder(Player player) {
|
||||
this.player = player;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(ChannelHandlerContext channel, Object packetObj, ChannelPromise promise) throws Exception {
|
||||
try {
|
||||
if (!player.hasPermission("proantitab.bypass") && packetObj.getClass() != null) {
|
||||
String packetName = packetObj.getClass().getSimpleName();
|
||||
if (packetName.equals("PacketPlayOutTabComplete")) {
|
||||
for (Field field : Reflection.getFields(packetObj)) {
|
||||
field.setAccessible(true);
|
||||
Object result = field.get(packetObj);
|
||||
|
||||
if (!(result instanceof String[])) continue;
|
||||
List<String> newResultList = new ArrayList<>();
|
||||
String[] tR = (String[]) result;
|
||||
String tempName;
|
||||
|
||||
for (String s : tR) {
|
||||
tempName = s.replaceFirst("/", "");
|
||||
if (tempName.contains(":")) tempName = tempName.split(":")[1];
|
||||
|
||||
if (!Storage.isCommandBlocked(tempName)
|
||||
|| Storage.isCommandBlocked(tempName)
|
||||
&& PermissionUtil.hasBypassPermission(player, tempName))
|
||||
newResultList.add(s);
|
||||
}
|
||||
|
||||
field.set(packetObj, newResultList.toArray(new String[0]));
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Throwable ignored) { }
|
||||
super.write(channel, packetObj, promise);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package de.rayzs.pat.plugin.process;
|
||||
|
||||
import de.rayzs.pat.plugin.BukkitLoader;
|
||||
import de.rayzs.pat.plugin.listeners.BukkitAntiTabListener;
|
||||
import de.rayzs.pat.utils.*;
|
||||
import java.util.*;
|
||||
|
||||
public class CommandProcess {
|
||||
|
||||
public static void handleCommand(Object senderObj, String[] args, String label) {
|
||||
CommandSender sender = new CommandSender(senderObj);
|
||||
int length = args.length;
|
||||
String task, sub;
|
||||
boolean bool;
|
||||
if(!PermissionUtil.hasPermissionWithResponse(sender, "use")) return;
|
||||
|
||||
try {
|
||||
switch (length) {
|
||||
case 1:
|
||||
task = args[0].toLowerCase();
|
||||
|
||||
switch (task) {
|
||||
case "reload":
|
||||
case "rl":
|
||||
if(!PermissionUtil.hasPermissionWithResponse(sender, "reload")) return;
|
||||
sender.sendMessage(Storage.RELOAD_LOADING);
|
||||
Storage.load();
|
||||
if(!Reflection.isBungeecordServer()) BukkitAntiTabListener.updateCommands();
|
||||
sender.sendMessage(Storage.RELOAD_DONE);
|
||||
return;
|
||||
case "clear": case "cls":
|
||||
if(!PermissionUtil.hasPermissionWithResponse(sender, "clear")) return;
|
||||
Storage.BLOCKED_COMMANDS_LIST.clear();
|
||||
Storage.save();
|
||||
if(!Reflection.isBungeecordServer()) BukkitAntiTabListener.updateCommands();
|
||||
sender.sendMessage(Storage.BLACKLIST_CLEAR_MESSAGE);
|
||||
return;
|
||||
case "notify":
|
||||
if(!PermissionUtil.hasPermissionWithResponse(sender, "notify")) return;
|
||||
if(sender.isConsole()) {
|
||||
bool = Storage.CONSOLE_NOTIFICATION_ENABLED;
|
||||
Storage.CONSOLE_NOTIFICATION_ENABLED = !Storage.CONSOLE_NOTIFICATION_ENABLED;
|
||||
} else {
|
||||
bool = Storage.NOTIFY_PLAYERS.contains(sender.getUniqueId());
|
||||
if(bool) Storage.NOTIFY_PLAYERS.remove(sender.getUniqueId());
|
||||
else Storage.NOTIFY_PLAYERS.add(sender.getUniqueId());
|
||||
}
|
||||
|
||||
sender.sendMessage(bool ? Storage.NOTIFY_DISABLED : Storage.NOTIFY_ENABLED);
|
||||
return;
|
||||
case "ls":
|
||||
case "list":
|
||||
if(!PermissionUtil.hasPermissionWithResponse(sender, "list")) return;
|
||||
StringBuilder blacklistedCommandBuilder = new StringBuilder();
|
||||
for (int i = 0; i < Storage.BLOCKED_COMMANDS_LIST.size(); i++) {
|
||||
bool = (i >= Storage.BLOCKED_COMMANDS_LIST.size() - 1);
|
||||
blacklistedCommandBuilder.append(Storage.BLACKLIST_LIST_COMMAND_MESSAGE).append(Storage.BLOCKED_COMMANDS_LIST.get(i));
|
||||
if (!bool)
|
||||
blacklistedCommandBuilder.append(Storage.BLACKLIST_LIST_SPLITTER_MESSAGE);
|
||||
}
|
||||
sender.sendMessage(Storage.BLACKLIST_LIST_MESSAGE.replace("%size%", String.valueOf(Storage.BLOCKED_COMMANDS_LIST.size())).replace("%commands%", blacklistedCommandBuilder.toString()));
|
||||
return;
|
||||
}
|
||||
case 2:
|
||||
task = args[0].toLowerCase();
|
||||
sub = args[1];
|
||||
bool = Storage.BLOCKED_COMMANDS_LIST.contains(sub);
|
||||
switch (task) {
|
||||
case "add":
|
||||
if(!PermissionUtil.hasPermissionWithResponse(sender, "add")) return;
|
||||
if (!bool) {
|
||||
Storage.BLOCKED_COMMANDS_LIST.add(sub);
|
||||
Storage.save();
|
||||
if(!Reflection.isBungeecordServer()) BukkitAntiTabListener.updateCommands();
|
||||
}
|
||||
sender.sendMessage((bool ? Storage.BLACKLIST_ADD_FAIL_MESSAGE : Storage.BLACKLIST_ADD_MESSAGE).replace("%command%", sub));
|
||||
return;
|
||||
case "remove":
|
||||
case "rem":
|
||||
case "rm":
|
||||
if(!PermissionUtil.hasPermissionWithResponse(sender, "remove")) return;
|
||||
if (bool) {
|
||||
Storage.BLOCKED_COMMANDS_LIST.remove(sub);
|
||||
Storage.save();
|
||||
if(!Reflection.isBungeecordServer()) BukkitAntiTabListener.updateCommands();
|
||||
}
|
||||
sender.sendMessage((!bool ? Storage.BLACKLIST_REMOVE_FAIL_MESSAGE : Storage.BLACKLIST_REMOVE_MESSAGE).replace("%command%", sub));
|
||||
return;
|
||||
}
|
||||
|
||||
default:
|
||||
for (String line : Storage.COMMAND_HELP) sender.sendMessage(line.replace("&", "§").replace("%label%", label));
|
||||
}
|
||||
} catch (ArrayIndexOutOfBoundsException arrayIndexOutOfBoundsException) {
|
||||
sender.sendMessage(Storage.COMMAND_UNKNOWN);
|
||||
} catch (Throwable throwable) {
|
||||
throwable.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static List<String> handleTabComplete(Object senderObj, String[] args) {
|
||||
CommandSender sender = new CommandSender(senderObj);
|
||||
final List<String> suggestions = new ArrayList<>(), result = new ArrayList<>();
|
||||
|
||||
switch (args.length) {
|
||||
case 1:
|
||||
if (PermissionUtil.hasPermission(sender, "notify")) suggestions.add("notify");
|
||||
if (PermissionUtil.hasPermission(sender, "list")) suggestions.addAll(Arrays.asList("list", "ls"));
|
||||
if (PermissionUtil.hasPermission(sender, "clear")) suggestions.addAll(Arrays.asList("clear", "cls"));
|
||||
if (PermissionUtil.hasPermission(sender, "reload")) suggestions.addAll(Arrays.asList("reload", "rl"));
|
||||
if (PermissionUtil.hasPermission(sender, "add")) suggestions.add("add");
|
||||
if (PermissionUtil.hasPermission(sender, "remove")) suggestions.addAll(Arrays.asList("remove", "rem", "rm"));
|
||||
break;
|
||||
case 2:
|
||||
if(args[0].equals("add") && PermissionUtil.hasPermission(sender, "add") && !Reflection.isBungeecordServer()) suggestions.addAll(BukkitLoader.getNotBlockedCommands());
|
||||
if(Arrays.asList("remove", "rem", "rm").contains(args[0].toLowerCase()) && PermissionUtil.hasPermission(sender, "remove")) suggestions.addAll(Storage.BLOCKED_COMMANDS_LIST);
|
||||
break;
|
||||
}
|
||||
|
||||
suggestions.stream().filter(suggestion -> suggestion.startsWith(args[args.length-1].toLowerCase())).forEach(result::add);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package de.rayzs.pat.utils;
|
||||
|
||||
import net.md_5.bungee.api.connection.*;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public class CommandSender {
|
||||
|
||||
private final Object sender;
|
||||
|
||||
public CommandSender(Object sender) {
|
||||
this.sender = sender;
|
||||
}
|
||||
|
||||
public boolean isConsole() {
|
||||
return !isPlayer();
|
||||
}
|
||||
|
||||
public boolean isPlayer() {
|
||||
return Reflection.isBungeecordServer() ? sender instanceof ProxiedPlayer : sender instanceof Player;
|
||||
}
|
||||
|
||||
public boolean hasPermission(String permission) {
|
||||
if(isConsole()) return true;
|
||||
return Reflection.isBungeecordServer()
|
||||
&& sender instanceof ProxiedPlayer
|
||||
? ((ProxiedPlayer) sender).hasPermission(permission)
|
||||
: sender instanceof Player
|
||||
&& (((Player) sender).hasPermission(permission)
|
||||
|| ((Player) sender).isOp());
|
||||
}
|
||||
|
||||
public void sendMessage(String text) {
|
||||
if(Reflection.isBungeecordServer()) ((net.md_5.bungee.api.CommandSender) sender).sendMessage(text);
|
||||
else ((org.bukkit.command.CommandSender) sender).sendMessage(text);
|
||||
}
|
||||
|
||||
public UUID getUniqueId() {
|
||||
if(Reflection.isBungeecordServer()) return ((ProxiedPlayer) sender).getUniqueId();
|
||||
else return ((Player) sender).getUniqueId();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package de.rayzs.pat.utils;
|
||||
|
||||
import de.rayzs.pat.plugin.logger.Logger;
|
||||
|
||||
import java.util.Scanner;
|
||||
import java.net.*;
|
||||
|
||||
public class ConnectionBuilder {
|
||||
|
||||
private String url = null, response = null;
|
||||
private Object[] parameters = null;
|
||||
|
||||
public ConnectionBuilder setUrl(String url) {
|
||||
this.url = url;
|
||||
return this;
|
||||
}
|
||||
|
||||
public ConnectionBuilder setProperties(Object... parameters) {
|
||||
this.parameters = parameters;
|
||||
return this;
|
||||
}
|
||||
|
||||
public ConnectionBuilder connect() {
|
||||
try {
|
||||
String rawUrl = url;
|
||||
URL url = new URL(rawUrl);
|
||||
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
|
||||
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
|
||||
connection.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
|
||||
if(parameters.length > 0) {
|
||||
Object firstParam = null, secondParam = null;
|
||||
for (Object parameter : parameters) {
|
||||
if(firstParam == null) firstParam = parameter;
|
||||
else if(secondParam == null) secondParam = parameter;
|
||||
else {
|
||||
connection.setRequestProperty((String) firstParam, (String) secondParam);
|
||||
firstParam = null;
|
||||
secondParam = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Scanner scanner = new Scanner(connection.getInputStream());
|
||||
StringBuilder builder = new StringBuilder("\\");
|
||||
while (scanner.hasNextLine()) builder.append(" ").append(scanner.next());
|
||||
response = builder.toString().replace("\\ ", "");
|
||||
} catch (Exception exception) {
|
||||
Logger.warning("§cFailed to built connection to website! [" + exception.getMessage() + "]");
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public boolean hasResponse() {
|
||||
return response != null;
|
||||
}
|
||||
|
||||
public String getResponse() {
|
||||
return response;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package de.rayzs.pat.utils;
|
||||
|
||||
public class PermissionUtil {
|
||||
|
||||
public static boolean hasPermission(Object targetObj, String permission) {
|
||||
CommandSender sender;
|
||||
|
||||
if(targetObj instanceof CommandSender) sender = (CommandSender) targetObj;
|
||||
else sender = new CommandSender(targetObj);
|
||||
|
||||
return sender.hasPermission("proantitab.*") || sender.hasPermission("proantitab." + permission);
|
||||
}
|
||||
|
||||
public static boolean hasBypassPermission(Object targetObj) {
|
||||
return hasPermission(targetObj, "bypass");
|
||||
}
|
||||
|
||||
public static boolean hasBypassPermission(Object targetObj, String command) {
|
||||
return hasBypassPermission(targetObj) || hasPermission(targetObj, "bypass." + command.toLowerCase());
|
||||
}
|
||||
|
||||
public static boolean hasPermissionWithResponse(Object targetObj, String command) {
|
||||
boolean permitted = hasPermission(targetObj, command);
|
||||
if(!permitted) {
|
||||
if(targetObj instanceof CommandSender)
|
||||
((CommandSender) targetObj).sendMessage(Storage.NO_PERMISSIONS.replace("%permission%", "proantitab." + command));
|
||||
}
|
||||
return permitted;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
package de.rayzs.pat.utils;
|
||||
|
||||
import io.netty.channel.Channel;
|
||||
import net.md_5.bungee.api.ProxyServer;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
import java.lang.reflect.*;
|
||||
import java.util.*;
|
||||
|
||||
public class Reflection {
|
||||
|
||||
private static boolean legacy, bungeecord;
|
||||
private static String versionName, rawVersionName, versionPackageName;
|
||||
private static Version version;
|
||||
private static int major, minor, release;
|
||||
|
||||
public static void initialize(Object serverObj) {
|
||||
try {
|
||||
Class.forName("org.bukkit.Server");
|
||||
bungeecord = false;
|
||||
} catch (ClassNotFoundException ignored) { bungeecord = true; }
|
||||
|
||||
if (!bungeecord) {
|
||||
loadVersionName(serverObj);
|
||||
loadAges();
|
||||
loadVersionEnum();
|
||||
legacy = minor <= 16;
|
||||
} else version = Version.UNKNOWN;
|
||||
}
|
||||
|
||||
public static int[] getAges() { return new int[]{major, minor, release}; }
|
||||
public static String getVersionName() { return versionName; }
|
||||
public static String getRawVersionName() { return rawVersionName; }
|
||||
public static Version getVersion() { return version; }
|
||||
public static boolean isModern() { return !legacy; }
|
||||
public static boolean isLegacy() { return legacy; }
|
||||
|
||||
public static boolean isBungeecordServer() {
|
||||
return bungeecord;
|
||||
}
|
||||
|
||||
public static Class<?> getClass(String path, String name) throws ClassNotFoundException {
|
||||
String classPath = path + "." + name;
|
||||
return Class.forName(classPath);
|
||||
}
|
||||
|
||||
public static Class<?> getPacketClass() throws ClassNotFoundException {
|
||||
String classPath = (isLegacy() ? "net.minecraft.server." + versionPackageName : "net.minecraft.network.protocol") + ".Packet";
|
||||
return Class.forName(classPath);
|
||||
}
|
||||
|
||||
public static Field getFieldByName(Class<?> clazz, String fieldName) throws NoSuchFieldException {
|
||||
Field field = clazz.getDeclaredField(fieldName);
|
||||
openAccess(field, true);
|
||||
return field;
|
||||
}
|
||||
|
||||
public static boolean openAccess(Field field) {
|
||||
return openAccess(field, false);
|
||||
}
|
||||
|
||||
public static boolean openAccess(Field field, boolean ignore) {
|
||||
if(!ignore && (Modifier.isFinal(field.getModifiers()) || field.isAccessible())) {
|
||||
return false;
|
||||
}
|
||||
field.setAccessible(true);
|
||||
return true;
|
||||
}
|
||||
|
||||
public static boolean closeAccess(Field field, boolean ignore) {
|
||||
if(!ignore && Modifier.isFinal(field.getModifiers()) || !field.isAccessible()) return false;
|
||||
field.setAccessible(false);
|
||||
return true;
|
||||
}
|
||||
|
||||
public static boolean closeAccess(Field field) {
|
||||
return closeAccess(field, false);
|
||||
}
|
||||
|
||||
public static List<Field> getFields(Object obj) {
|
||||
return getFields(obj.getClass());
|
||||
}
|
||||
|
||||
public static List<Field> getFields(Class<?> clazz) {
|
||||
List<Field> result = new ArrayList<>();
|
||||
List<Field[]> fieldLists = Arrays.asList(clazz.getFields(), clazz.getDeclaredFields());
|
||||
|
||||
for (Field[] fields : fieldLists)
|
||||
for(Field field : fields)
|
||||
result.addAll(Collections.singletonList(field));
|
||||
return result;
|
||||
}
|
||||
|
||||
public static List<Field> getFieldsByType(Class<?> clazz, String type) {
|
||||
boolean useContains = type.endsWith("%contains%");
|
||||
boolean useStarts = type.endsWith("%starts%");
|
||||
boolean useEnds = type.endsWith("%ends%");
|
||||
|
||||
if(useContains) type = type.replace("%contains%", "");
|
||||
else if(useStarts) type = type.replace("%starts%", "");
|
||||
else if(useEnds) type = type.replace("%ends%", "");
|
||||
|
||||
type = type.replace("%contains%", "");
|
||||
|
||||
List<Field> result = new ArrayList<>();
|
||||
List<Field> fieldLists = getFields(clazz);
|
||||
|
||||
for (Field field : fieldLists) {
|
||||
String typeName = field.getAnnotatedType().getType().getTypeName();
|
||||
if(useContains && typeName.contains(type)
|
||||
|| useStarts && typeName.startsWith(type)
|
||||
|| useEnds && typeName.endsWith(type)
|
||||
|| typeName.equals(type)) {
|
||||
openAccess(field, true);
|
||||
result.add(field);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public static Object getPlayerConnection(Player player) throws Exception {
|
||||
Object entityPlayer = player.getClass().getMethod("getHandle").invoke(player);
|
||||
return getFieldsByType(entityPlayer.getClass(), "PlayerConnection%contains%").get(0).get(entityPlayer);
|
||||
}
|
||||
|
||||
public static Channel getPlayerChannel(Player player) throws Exception {
|
||||
Object playerConnection = getPlayerConnection(player),
|
||||
networkManager = getPlayerNetworkManager(playerConnection);
|
||||
Optional<Field> optional = getFieldsByType(networkManager.getClass(), "Channel%ends%").stream().findFirst();
|
||||
if(!optional.isPresent()) return null;
|
||||
Object channelObject = optional.get().get(networkManager);
|
||||
return (Channel) channelObject;
|
||||
}
|
||||
|
||||
public static Object getPlayerNetworkManager(Object playerConnection) throws Exception {
|
||||
Optional<Field> optional = getFieldsByType(playerConnection.getClass(), "NetworkManager%contains%").stream().findFirst();
|
||||
if(!optional.isPresent()) return null;
|
||||
return optional.get().get(playerConnection);
|
||||
}
|
||||
|
||||
public static void setFieldValue(Field field, Object clazzObj, Object value, boolean closeAccessibility) throws IllegalAccessException {
|
||||
field.set(clazzObj, value);
|
||||
if(closeAccessibility) field.setAccessible(false);
|
||||
}
|
||||
|
||||
public static void getAndSetField(String fieldName, Class<?> clazz, Object clazzObj, Object value, boolean closeAccessibility) throws Exception {
|
||||
Field field = getFieldByName(clazz, fieldName);
|
||||
setFieldValue(field, clazzObj, value, closeAccessibility);
|
||||
}
|
||||
|
||||
public static void getAndSetField(Field field, Object clazzObj, Object value, boolean closeAccessibility) throws Exception {
|
||||
setFieldValue(field, clazzObj, value, closeAccessibility);
|
||||
}
|
||||
|
||||
public static boolean doesClassExist(String classPath, String className) {
|
||||
classPath = (classPath.contains("/") ? className.replace("/", ".") : classPath).toLowerCase();
|
||||
return doesClassExist(classPath + "." + className);
|
||||
}
|
||||
|
||||
public static boolean doesClassExist(String className) {
|
||||
try {
|
||||
Class.forName(className);
|
||||
return true;
|
||||
}catch (ClassNotFoundException classNotFoundException) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static void loadVersionName(Object serverObject) {
|
||||
try {
|
||||
versionName = bungeecord ? ProxyServer.getInstance().getName() : Bukkit.getName();
|
||||
rawVersionName = (String) serverObject.getClass().getMethod("getBukkitVersion").invoke(serverObject);
|
||||
rawVersionName = rawVersionName.split("-")[0].replace(".", "_");
|
||||
versionPackageName = serverObject.getClass().getPackage().getName();
|
||||
versionPackageName = versionPackageName.substring(versionPackageName.lastIndexOf('.') + 1);
|
||||
}catch (Exception exception) {
|
||||
exception.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
private static void loadVersionEnum() {
|
||||
try {
|
||||
final String primaryVersionName, fullVersionName;
|
||||
StringBuilder builder = new StringBuilder("v_");
|
||||
builder.append(major).append("_").append(minor);
|
||||
primaryVersionName = builder.toString();
|
||||
if (release != 0) builder.append("_").append(release);
|
||||
fullVersionName = builder.toString();
|
||||
boolean couldFindOriginalVersion = Arrays.stream(Version.values()).anyMatch(searchingVersion -> searchingVersion.toString().equals(fullVersionName));
|
||||
version = Version.valueOf(couldFindOriginalVersion ? fullVersionName : primaryVersionName);
|
||||
} catch (Exception exception) {
|
||||
version = Version.UNSUPPORTED;
|
||||
}
|
||||
}
|
||||
|
||||
private static void loadAges() {
|
||||
String[] versionArgs = rawVersionName.split("_");
|
||||
major = Integer.parseInt(versionArgs[0]);
|
||||
minor = Integer.parseInt(versionArgs[1]);
|
||||
release = versionArgs.length > 2 ? Integer.parseInt(versionArgs[2]) : 0;
|
||||
}
|
||||
|
||||
public static int getMajor() { return major; }
|
||||
public static int getMinor() { return minor; }
|
||||
public static int getRelease() { return release; }
|
||||
|
||||
public enum Version {
|
||||
UNKNOWN, UNSUPPORTED,
|
||||
v_1_8, v_1_8_8,
|
||||
v_1_9, v_1_9_4,
|
||||
v_1_10, v_1_10_2,
|
||||
v_1_11, v_1_11_2,
|
||||
v_1_12, v_1_12_2,
|
||||
v_1_13, v_1_13_2,
|
||||
v_1_14, v_1_14_4,
|
||||
v_1_15, v_1_15_2,
|
||||
v_1_16, v_1_16_4, v_1_16_5,
|
||||
v_1_17, v_1_17_1, v_1_18,
|
||||
v_1_18_1, v_1_18_2,
|
||||
v_1_19, v_1_19_1, v_1_19_2, v_1_19_3, v_1_19_4,
|
||||
v_1_20, v_1_20_1, v_1_20_2, v_1_20_3, v_1_20_4,
|
||||
v_1_21, v_1_21_1, v_1_21_2,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package de.rayzs.pat.utils;
|
||||
|
||||
import de.rayzs.pat.utils.configuration.*;
|
||||
import java.util.*;
|
||||
|
||||
public class Storage {
|
||||
|
||||
public static ConfigurationBuilder CONFIGURATION = Configurator.get("config");
|
||||
public static ArrayList<String> BLOCKED_COMMANDS_LIST, COMMAND_HELP = new ArrayList<>();
|
||||
public static List<UUID> NOTIFY_PLAYERS = new ArrayList<>();
|
||||
public static String NOTIFY_ALERT, NOTIFY_ENABLED, NOTIFY_DISABLED, CANCEL_COMMANDS_MESSAGE, COMMAND_UNKNOWN, NO_PERMISSIONS, RELOAD_LOADING, RELOAD_DONE, BLACKLIST_CLEAR_MESSAGE, BLACKLIST_LIST_COMMAND_MESSAGE, BLACKLIST_ADD_MESSAGE, BLACKLIST_ADD_FAIL_MESSAGE, BLACKLIST_REMOVE_MESSAGE, BLACKLIST_REMOVE_FAIL_MESSAGE, BLACKLIST_LIST_MESSAGE, BLACKLIST_LIST_SPLITTER_MESSAGE;
|
||||
public static boolean CANCEL_COMMANDS, UPDATE_ENABLED, OUTDATED_VERSION = false, CONSOLE_NOTIFICATION_ENABLED = true;
|
||||
public static int UPDATE_PERIOD;
|
||||
|
||||
public static void load() {
|
||||
CONFIGURATION.reload();
|
||||
|
||||
ArrayList<String> defaultBlockedCommandArray = new ArrayList<>(),
|
||||
defaultHelpArray = new ArrayList<>();
|
||||
|
||||
defaultBlockedCommandArray.addAll(Arrays.asList("help", "?", "about", "ver", "version", "icanhasbukkit", "pl", "plugins"));
|
||||
defaultHelpArray.add("&7Available commands are: &f/%label%&7...");
|
||||
defaultHelpArray.add("&f reload &7to reload the plugin");
|
||||
defaultHelpArray.add("&f list &7to see all blacklisted commands");
|
||||
defaultHelpArray.add("&f add/remove (command) &7to manage the blacklist");
|
||||
defaultHelpArray.add("&f notify &7to get alerted");
|
||||
defaultHelpArray.add("&f clear &7to clear the blacklist");
|
||||
|
||||
UPDATE_ENABLED = (boolean) CONFIGURATION.getOrSet("updater.enabled", true);
|
||||
UPDATE_PERIOD = (int) CONFIGURATION.getOrSet("updater.period", 18000);
|
||||
|
||||
COMMAND_HELP = (ArrayList<String>) CONFIGURATION.getOrSet("settings.help", defaultHelpArray);
|
||||
BLOCKED_COMMANDS_LIST = (ArrayList<String>) CONFIGURATION.getOrSet("settings.blacklist.commands", defaultBlockedCommandArray);
|
||||
NO_PERMISSIONS = (String) CONFIGURATION.getOrSet("settings.no-permissions", "&cYou are not allowed to execute this command! Missing permission: &4proantitab.%permission%");
|
||||
|
||||
NOTIFY_ENABLED = (String) CONFIGURATION.getOrSet("settings.notification.enabled", "&aEnabled notifications!");
|
||||
NOTIFY_DISABLED = (String) CONFIGURATION.getOrSet("settings.notification.disabled", "&cDisabled notifications!");
|
||||
NOTIFY_ALERT = (String) CONFIGURATION.getOrSet("settings.notification.alert", "&8[&4ALERT&8] &c%player% tried to execute the following blocked command: &4%command%");
|
||||
|
||||
CANCEL_COMMANDS = (boolean) CONFIGURATION.getOrSet("settings.cancel-blocked-commands.enabled", true);
|
||||
CANCEL_COMMANDS_MESSAGE = (String) CONFIGURATION.getOrSet("settings.cancel-blocked-commands.message", "&cThe command '%command%' is blocked!");
|
||||
|
||||
BLACKLIST_CLEAR_MESSAGE = (String) CONFIGURATION.getOrSet("settings.blacklist.clear.message", "&aList of blacklisted commands has been cleared!");
|
||||
BLACKLIST_LIST_MESSAGE = (String) CONFIGURATION.getOrSet("settings.blacklist.list.message", "&7Blocked commands (&f%size%&7)&8: &f%commands%");
|
||||
BLACKLIST_LIST_SPLITTER_MESSAGE = (String) CONFIGURATION.getOrSet("settings.blacklist.list.splitter", "&7, ");
|
||||
BLACKLIST_LIST_COMMAND_MESSAGE = (String) CONFIGURATION.getOrSet("settings.blacklist.list.command", "&f");
|
||||
BLACKLIST_ADD_MESSAGE = (String) CONFIGURATION.getOrSet("settings.blacklist.add.success", "&aSuccessfully added %command% into blocked-commands list!");
|
||||
BLACKLIST_ADD_FAIL_MESSAGE = (String) CONFIGURATION.getOrSet("settings.blacklist.add.fail", "&c%command% is already in the list!");
|
||||
BLACKLIST_REMOVE_MESSAGE = (String) CONFIGURATION.getOrSet("settings.blacklist.remove.success", "&aSuccessfully removed %command% from blocked-commands list!");
|
||||
BLACKLIST_REMOVE_FAIL_MESSAGE = (String) CONFIGURATION.getOrSet("settings.blacklist.remove.fail", "&c%command% is not listed!");
|
||||
|
||||
COMMAND_UNKNOWN = (String) CONFIGURATION.getOrSet("settings.unknown-command", "&cFailed to execute this command! Use '/pat' to see all available commands.");
|
||||
RELOAD_LOADING = (String) CONFIGURATION.getOrSet("settings.reload.loading", "&eReloading all configuration files...");
|
||||
RELOAD_DONE = (String) CONFIGURATION.getOrSet("settings.reload.done", "&aSuccessfully reloaded all configuration files!");
|
||||
}
|
||||
|
||||
public static void save() {
|
||||
CONFIGURATION
|
||||
.set("updater.enabled", UPDATE_ENABLED)
|
||||
.set("updater.period", UPDATE_PERIOD)
|
||||
.set("settings.no-permissions", NO_PERMISSIONS)
|
||||
.set("settings.unknown-command", COMMAND_UNKNOWN)
|
||||
.set("settings.reload.loading", RELOAD_LOADING)
|
||||
.set("settings.reload.done", RELOAD_DONE)
|
||||
.set("settings.help", COMMAND_HELP)
|
||||
.set("settings.cancel-blocked-commands.enabled", CANCEL_COMMANDS)
|
||||
.set("settings.cancel-blocked-commands.message", CANCEL_COMMANDS_MESSAGE)
|
||||
.set("settings.blacklist.commands", BLOCKED_COMMANDS_LIST)
|
||||
.set("settings.blacklist.clear.message", BLACKLIST_CLEAR_MESSAGE)
|
||||
.set("settings.blacklist.add.success", BLACKLIST_ADD_MESSAGE)
|
||||
.set("settings.blacklist.remove.success", BLACKLIST_REMOVE_MESSAGE)
|
||||
.set("settings.blacklist.add.failed", BLACKLIST_ADD_FAIL_MESSAGE)
|
||||
.set("settings.blacklist.remove.failed", BLACKLIST_REMOVE_FAIL_MESSAGE)
|
||||
.set("settings.blacklist.list.message", BLACKLIST_LIST_MESSAGE)
|
||||
.set("settings.blacklist.list.command", BLACKLIST_LIST_COMMAND_MESSAGE)
|
||||
.set("settings.blacklist.list.splitter", BLACKLIST_LIST_SPLITTER_MESSAGE)
|
||||
.save();
|
||||
}
|
||||
|
||||
public static boolean isCommandBlocked(String command) {
|
||||
if(command.contains(" ")) command = command.split(" ")[0];
|
||||
if(command.contains(":")) command = command.split(":")[1];
|
||||
for (String blockedCommand : BLOCKED_COMMANDS_LIST) {
|
||||
if(blockedCommand.equals(command.toLowerCase())) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package de.rayzs.pat.utils.configuration;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
public interface ConfigurationBuilder {
|
||||
void reload();
|
||||
void save();
|
||||
String getFilePath();
|
||||
ConfigurationBuilder set(String path, String target, Object object);
|
||||
ConfigurationBuilder set(String target, Object object);
|
||||
ConfigurationBuilder setAndSave(String path, String target, Object object);
|
||||
ConfigurationBuilder setAndSave(String target, Object object);
|
||||
Object getOrSet(String path, String target, Object object);
|
||||
Object getOrSet(String target, Object object);
|
||||
Object get(String target);
|
||||
Object get(String path, String target);
|
||||
File getFile();
|
||||
boolean loadDefault();
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package de.rayzs.pat.utils.configuration;
|
||||
|
||||
import java.io.*;
|
||||
import java.net.*;
|
||||
import java.util.HashMap;
|
||||
import de.rayzs.pat.utils.*;
|
||||
import de.rayzs.pat.utils.configuration.impl.*;
|
||||
|
||||
public class Configurator {
|
||||
|
||||
private static final HashMap<String, ConfigurationBuilder> CONFIGURATION_HASHES = new HashMap<>();
|
||||
|
||||
public static ConfigurationBuilder get(String fileName, String filePath) {
|
||||
String keyName = filePath + "/" + fileName;
|
||||
if(CONFIGURATION_HASHES.containsKey(keyName))
|
||||
return CONFIGURATION_HASHES.get(keyName);
|
||||
|
||||
ConfigurationBuilder configurationBuilder = Reflection.isBungeecordServer()
|
||||
? new BungeeConfigurationBuilder(fileName, filePath)
|
||||
: new BukkitConfigurationBuilder(fileName, filePath);
|
||||
CONFIGURATION_HASHES.put(keyName, configurationBuilder);
|
||||
return configurationBuilder;
|
||||
}
|
||||
|
||||
public static ConfigurationBuilder get(String fileName) {
|
||||
String keyName = "./plugins/ProAntiTab/" + fileName;
|
||||
if(CONFIGURATION_HASHES.containsKey(keyName))
|
||||
return CONFIGURATION_HASHES.get(keyName);
|
||||
|
||||
ConfigurationBuilder configurationBuilder = Reflection.isBungeecordServer()
|
||||
? new BungeeConfigurationBuilder(fileName)
|
||||
: new BukkitConfigurationBuilder(fileName);
|
||||
CONFIGURATION_HASHES.put(keyName, configurationBuilder);
|
||||
return configurationBuilder;
|
||||
}
|
||||
|
||||
public static InputStream getResource(String filename) {
|
||||
try {
|
||||
URL url = Configurator.class.getClassLoader().getResource(filename);
|
||||
if (url == null) {
|
||||
return null;
|
||||
} else {
|
||||
URLConnection connection = url.openConnection();
|
||||
connection.setUseCaches(false);
|
||||
return connection.getInputStream();
|
||||
}
|
||||
} catch (Throwable throwable) {
|
||||
throwable.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static void createResourcedFile(File dataFolder, String resourcePath, String exportRessourcePath, boolean replace) {
|
||||
if (resourcePath == null || resourcePath.equals("")) return;
|
||||
resourcePath = resourcePath.replace('\\', '/');
|
||||
InputStream inputStream = getResource(resourcePath);
|
||||
if (inputStream == null) return;
|
||||
|
||||
File outputFile = new File(dataFolder, exportRessourcePath);
|
||||
if (!dataFolder.exists()) dataFolder.mkdirs();
|
||||
|
||||
try {
|
||||
if (!outputFile.exists() || replace) {
|
||||
OutputStream outputStream = new FileOutputStream(outputFile);
|
||||
byte[] buffer = new byte[1024];
|
||||
int length;
|
||||
|
||||
while((length = inputStream.read(buffer)) > 0) outputStream.write(buffer, 0, length);
|
||||
outputStream.close();
|
||||
inputStream.close();
|
||||
}
|
||||
} catch (Throwable throwable) {
|
||||
throwable.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package de.rayzs.pat.utils.configuration.impl;
|
||||
|
||||
import de.rayzs.pat.plugin.logger.Logger;
|
||||
import de.rayzs.pat.utils.configuration.ConfigurationBuilder;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import org.bukkit.ChatColor;
|
||||
import java.io.File;
|
||||
|
||||
public class BukkitConfigurationBuilder implements ConfigurationBuilder {
|
||||
|
||||
private String fileName, filePath;
|
||||
private File file;
|
||||
private boolean loadDefault;
|
||||
private YamlConfiguration configuration;
|
||||
|
||||
public BukkitConfigurationBuilder(String fileName) {
|
||||
init(fileName);
|
||||
}
|
||||
|
||||
public BukkitConfigurationBuilder(String fileName, String filePath) {
|
||||
this.filePath = filePath;
|
||||
init(fileName);
|
||||
}
|
||||
|
||||
protected void init(String fileName) {
|
||||
this.fileName = fileName;
|
||||
this.file = new File((this.filePath == null) ? "./plugins/ProAntiTab" : this.filePath, fileName + ".yml");
|
||||
this.loadDefault = !this.file.exists();
|
||||
this.configuration = YamlConfiguration.loadConfiguration(this.file);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getFilePath() {
|
||||
return filePath;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void reload() {
|
||||
init(this.fileName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save() {
|
||||
try { this.configuration.save(this.file);
|
||||
} catch (Exception exception) {
|
||||
Logger.info("Could not save configuration file! [file=" + this.fileName + ", message=" + exception.getMessage() + "]");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigurationBuilder set(String path, String target, Object object) {
|
||||
this.configuration.set(((path != null) ? (path + ".") : "") + target, object instanceof String ? ((String) object).replace("§", "&") : object);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigurationBuilder set(String target, Object object) {
|
||||
set(null, target, object);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigurationBuilder setAndSave(String path, String target, Object object) {
|
||||
set(path, target, object);
|
||||
save();
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigurationBuilder setAndSave(String target, Object object) {
|
||||
set(target, object);
|
||||
save();
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getOrSet(String path, String target, Object object) {
|
||||
Object result = get(path, target);
|
||||
if (result != null)
|
||||
return result;
|
||||
set(path, target, object);
|
||||
save();
|
||||
return get(path, target);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getOrSet(String target, Object object) {
|
||||
Object result = get(target);
|
||||
if (result != null)
|
||||
return result;
|
||||
set(target, object);
|
||||
save();
|
||||
return get(target);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object get(String target) {
|
||||
return get(null, target);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object get(String path, String target) {
|
||||
Object object = this.configuration.get(((path != null) ? (path + ".") : "") + target);
|
||||
if (object instanceof String) {
|
||||
String objString = (String) object;
|
||||
return ChatColor.translateAlternateColorCodes('&', objString);
|
||||
}
|
||||
return object;
|
||||
}
|
||||
|
||||
@Override
|
||||
public File getFile() {
|
||||
return file;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean loadDefault() {
|
||||
return loadDefault;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package de.rayzs.pat.utils.configuration.impl;
|
||||
|
||||
import de.rayzs.pat.plugin.logger.Logger;
|
||||
import de.rayzs.pat.utils.configuration.ConfigurationBuilder;
|
||||
import net.md_5.bungee.api.ChatColor;
|
||||
import net.md_5.bungee.config.*;
|
||||
import java.io.File;
|
||||
|
||||
public class BungeeConfigurationBuilder implements ConfigurationBuilder {
|
||||
|
||||
private String fileName, filePath;
|
||||
private File file;
|
||||
private boolean loadDefault;
|
||||
private Configuration configuration;
|
||||
|
||||
public BungeeConfigurationBuilder(String fileName) {
|
||||
init(fileName);
|
||||
}
|
||||
|
||||
public BungeeConfigurationBuilder(String filePath, String fileName) {
|
||||
this.filePath = filePath;
|
||||
init(fileName);
|
||||
}
|
||||
|
||||
protected void init(String fileName) {
|
||||
filePath = filePath == null ? "./plugins/ProAntiTab" : filePath;
|
||||
File directory = new File(filePath);
|
||||
|
||||
this.fileName = fileName;
|
||||
|
||||
try {
|
||||
if(!directory.isDirectory()) directory.mkdirs();
|
||||
file = new File(filePath, fileName + ".yml");
|
||||
loadDefault = !file.exists();
|
||||
if(!file.exists()) file.createNewFile();
|
||||
configuration = ConfigurationProvider.getProvider(YamlConfiguration.class).load(file);
|
||||
}catch (Exception exception) { exception.printStackTrace(); }
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getFilePath() {
|
||||
return filePath;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void reload() {
|
||||
init(this.fileName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save() {
|
||||
try { ConfigurationProvider.getProvider(YamlConfiguration.class).save(configuration, file);
|
||||
} catch (Exception exception) {
|
||||
Logger.info("Could not save configuration file! [file=" + fileName + ", message=" + exception.getMessage() + "]");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigurationBuilder set(String path, String target, Object object) {
|
||||
this.configuration.set(((path != null) ? (path + ".") : "") + target, object instanceof String ? ((String) object).replace("§", "&") : object);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigurationBuilder set(String target, Object object) {
|
||||
set(null, target, object);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigurationBuilder setAndSave(String path, String target, Object object) {
|
||||
set(path, target, object);
|
||||
save();
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigurationBuilder setAndSave(String target, Object object) {
|
||||
set(target, object);
|
||||
save();
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getOrSet(String path, String target, Object object) {
|
||||
Object result = get(path, target);
|
||||
if (result != null)
|
||||
return result;
|
||||
set(path, target, object);
|
||||
save();
|
||||
return get(path, target);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getOrSet(String target, Object object) {
|
||||
Object result = get(target);
|
||||
if (result != null)
|
||||
return result;
|
||||
set(target, object);
|
||||
save();
|
||||
return get(target);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object get(String target) {
|
||||
return get(null, target);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object get(String path, String target) {
|
||||
Object object = this.configuration.get(((path != null) ? (path + ".") : "") + target);
|
||||
if (object instanceof String) {
|
||||
String objString = (String) object;
|
||||
return ChatColor.translateAlternateColorCodes('&', objString);
|
||||
}
|
||||
return object;
|
||||
}
|
||||
|
||||
@Override
|
||||
public File getFile() {
|
||||
return file;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean loadDefault() {
|
||||
return loadDefault;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user