Major Code Change

This commit is contained in:
Alihan authored and GitHub committed 2024-05-09 23:24:26 +02:00
1 parent f9a6b0fbfc
commit b2b1de9ca2
51 files changed
+5868

No files matched your search

@@ -0,0 +1,140 @@
package de.rayzs.pat.plugin;
import de.rayzs.pat.plugin.commands.BukkitCommand;
import de.rayzs.pat.plugin.listeners.bukkit.BukkitAntiTabListener;
import de.rayzs.pat.plugin.listeners.bukkit.BukkitBlockCommandListener;
import de.rayzs.pat.plugin.listeners.bukkit.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.communication.ClientCommunication;
import de.rayzs.pat.utils.configuration.Configurator;
import de.rayzs.pat.utils.group.GroupManager;
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.*;
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);
Configurator.createResourcedFile(getDataFolder(), "files\\bukkit-storage.yml", "storage.yml", false);
}
@Override
public void onEnable() {
plugin = this;
logger = getLogger();
Reflection.initialize(getServer());
bStats.initialize(this);
Storage.load();
PluginManager manager = getServer().getPluginManager();
if(Storage.BUNGEECORD)
Bukkit.getScheduler().scheduleSyncRepeatingTask(this, ClientCommunication::sendRequest, 40, 20*10);
else {
GroupManager.initialize();
PacketAnalyzer.injectAll();
manager.registerEvents(new BukkitBlockCommandListener(), this);
}
if(Reflection.getMinor() >= 18) manager.registerEvents(new BukkitAntiTabListener(), this);
else manager.registerEvents(new BukkitPlayerConnectionListener(), this);
registerCommand("proantitab", "pat");
startUpdaterTask();
}
@Override
public void onDisable() {
if(!Storage.BUNGEECORD)
PacketAnalyzer.uninjectAll();
}
public void registerCommand(String... commands) {
BukkitCommand command = new BukkitCommand();
for (String commandName : commands) {
PluginCommand pluginCommand = getCommand(commandName);
pluginCommand.setExecutor(command);
pluginCommand.setTabCompleter(command);
}
}
public static void synchronizeCommandData(boolean turn, List<String> commands) {
if (!Storage.BLOCKED_COMMANDS_LIST.containsAll(commands) || !commands.containsAll(Storage.BLOCKED_COMMANDS_LIST))
Storage.BLOCKED_COMMANDS_LIST = commands;
if (Storage.TURN_BLACKLIST_TO_WHITELIST != turn)
Storage.TURN_BLACKLIST_TO_WHITELIST = turn;
if(Reflection.getMinor() >= 18) BukkitAntiTabListener.handleTabCompletion(commands);
}
public void startUpdaterTask() {
if (!Storage.UPDATE_ENABLED || Storage.BUNGEECORD) 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;
Storage.UPDATE_NOTIFICATION.forEach(message -> Logger.warning(message.replace("&", "§")));
}
}
}, 20L, 20L * Storage.UPDATE_PERIOD);
}
public static void synchronizeGroupData(String information) {
GroupManager.clearAllGroups();
Map<String, List<String>> groups = new HashMap<>();
String[] groupPartSplits = information.split("\\\\"),
groupInformation;
for (String groupPartSplit : groupPartSplits) {
groupInformation = groupPartSplit.split(";");
String groupName = groupInformation[0];
List<String> commands = new ArrayList<>();
for(int i = 1; i < groupInformation.length; i++)
commands.add(groupInformation[i]);
groups.put(groupName, commands);
}
for (Map.Entry<String, List<String>> entry : groups.entrySet())
GroupManager.setGroup(entry.getKey(), entry.getValue());
}
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,110 @@
package de.rayzs.pat.plugin;
import de.rayzs.pat.plugin.commands.BungeeCommand;
import de.rayzs.pat.plugin.listeners.bungee.BungeeAntiTabListener;
import de.rayzs.pat.plugin.listeners.bungee.BungeeBlockCommandListener;
import de.rayzs.pat.plugin.listeners.bungee.BungeePlayerConnectionListener;
import de.rayzs.pat.plugin.listeners.bungee.WaterfallAntiTabListener;
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.communication.ClientCommunication;
import de.rayzs.pat.utils.configuration.Configurator;
import de.rayzs.pat.utils.group.GroupManager;
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.concurrent.TimeUnit;
public class BungeeLoader extends Plugin {
private static Plugin plugin;
private static java.util.logging.Logger logger;
private ScheduledTask updaterTask;
private static boolean isConnectedToSpigot = false;
@Override
public void onLoad() {
Configurator.createResourcedFile(getDataFolder(), "files\\bungee-config.yml", "config.yml", false);
Configurator.createResourcedFile(getDataFolder(), "files\\bungee-storage.yml", "storage.yml", false);
}
@Override
public void onEnable() {
plugin = this;
logger = getLogger();
Reflection.initialize(getProxy());
Storage.load();
GroupManager.initialize();
bStats.initialize(this);
PluginManager manager = ProxyServer.getInstance().getPluginManager();
registerCommand("bungeeproantitab", "bpat", "pat", "proantitab");
manager.registerListener(this, new BungeePlayerConnectionListener());
manager.registerListener(this, new BungeeAntiTabListener());
manager.registerListener(this, new BungeeBlockCommandListener());
try {
Class.forName("io.github.waterfallmc.waterfall.QueryResult");
manager.registerListener(this, new WaterfallAntiTabListener());
} catch (ClassNotFoundException ignored) {
ProxyServer.getInstance().getScheduler().schedule(this, () -> {
logger.warning("We advice you to use WaterFall instead for a better experience!");
logger.warning("It's also required to really block every Bungeecord command with ProAntiTab!");
}, 2, TimeUnit.SECONDS);
}
startUpdaterTask();
ProxyServer.getInstance().getScheduler().schedule(this, () -> ClientCommunication.sendInformation("instance::"), 2, TimeUnit.SECONDS);
}
private static void registerCommand(String... commands) {
for (String commandName : commands) {
BungeeCommand command = new BungeeCommand(commandName);
ProxyServer.getInstance().getPluginManager().registerCommand(plugin, command);
}
}
public static boolean isConnectedToSpigot() {
return isConnectedToSpigot;
}
public static void handleIfConnectedToSpigot() {
if(isConnectedToSpigot) return;
logger.info("Found compatible Spigot server!");
isConnectedToSpigot = true;
}
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;
Storage.UPDATE_NOTIFICATION.forEach(message -> Logger.warning(message.replace("&", "§")));
}
}
}, 20L, Storage.UPDATE_PERIOD, TimeUnit.MILLISECONDS);
}
public static Plugin getPlugin() {
return plugin;
}
public static java.util.logging.Logger getPluginLogger() {
return logger;
}
}
@@ -0,0 +1,85 @@
package de.rayzs.pat.plugin;
import com.google.inject.Inject;
import com.mojang.brigadier.tree.RootCommandNode;
import com.velocitypowered.api.command.CommandSource;
import com.velocitypowered.api.event.EventManager;
import com.velocitypowered.api.event.Subscribe;
import com.velocitypowered.api.event.command.PlayerAvailableCommandsEvent;
import com.velocitypowered.api.event.proxy.ProxyInitializeEvent;
import com.velocitypowered.api.plugin.Plugin;
import com.velocitypowered.api.proxy.Player;
import com.velocitypowered.api.proxy.ProxyServer;
import com.velocitypowered.api.scheduler.ScheduledTask;
import de.rayzs.pat.plugin.commands.VelocityCommand;
import de.rayzs.pat.plugin.listeners.velocity.VelocityAntiTabListener;
import de.rayzs.pat.plugin.listeners.velocity.VelocityBlockCommandListener;
import de.rayzs.pat.plugin.listeners.velocity.VelocityConnectionListener;
import de.rayzs.pat.plugin.logger.Logger;
import de.rayzs.pat.plugin.metrics.impl.VelocityMetrics;
import de.rayzs.pat.utils.ConnectionBuilder;
import de.rayzs.pat.utils.MessageTranslator;
import de.rayzs.pat.utils.Reflection;
import de.rayzs.pat.utils.Storage;
import de.rayzs.pat.utils.group.GroupManager;
import net.kyori.adventure.text.minimessage.MiniMessage;
import java.util.concurrent.TimeUnit;
@Plugin(name = "ProAntiTab",
id = "proantitab",
version = "1.5.3",
authors = "Rayzs_YT",
description = "A simple structured AntiTab plugin to prevent specific commands from being executed and auto-tab-completed.")
public class VelocityLoader {
private final VelocityLoader plugin;
private final ProxyServer server;
private final EventManager manager;
private final VelocityMetrics.Factory metricsFactory;
private ScheduledTask task;
@Inject
public VelocityLoader(ProxyServer server, VelocityMetrics.Factory metricsFactory) {
this.plugin = this;
this.server = server;
this.manager = server.getEventManager();
this.metricsFactory = metricsFactory;
}
@Subscribe
public void onProxyInitialization(ProxyInitializeEvent event) {
Reflection.initialize(server);
Storage.load();
GroupManager.initialize();
metricsFactory.make(this, 21638);
server.getCommandManager().register("pat", new VelocityCommand(), "bpat", "bungeeproantitab", "proantitab");
server.getEventManager().register(this, new VelocityBlockCommandListener(server));
server.getEventManager().register(this, new VelocityAntiTabListener(server));
server.getEventManager().register(this, new VelocityConnectionListener(server, this));
startUpdaterTask();
}
public void startUpdaterTask() {
if (!Storage.UPDATE_ENABLED) return;
task = server.getScheduler().buildTask(this, () -> {
String result = new ConnectionBuilder().setUrl("https://www.rayzs.de/proantitab/api/version.php")
.setProperties("ProAntiTab", "4654").connect().getResponse();
if (!result.equals("1.5.3")) {
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;
Storage.UPDATE_NOTIFICATION.forEach(message -> server.getConsoleCommandSource().sendMessage(MiniMessage.miniMessage().deserialize(MessageTranslator.translate(message.replace("&", "§")))));
}
}
}).delay(1, TimeUnit.SECONDS).repeat(Storage.UPDATE_PERIOD, TimeUnit.SECONDS).schedule();
}
}
@@ -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,18 @@
package de.rayzs.pat.plugin.commands;
import com.velocitypowered.api.command.SimpleCommand;
import de.rayzs.pat.plugin.process.CommandProcess;
import java.util.List;
public class VelocityCommand implements SimpleCommand {
@Override
public void execute(Invocation invocation) {
CommandProcess.handleCommand(invocation.source(), invocation.arguments(), "vpat");
}
@Override
public List<String> suggest(Invocation invocation) {
return CommandProcess.handleTabComplete(invocation.source(), invocation.arguments());
}
}
@@ -0,0 +1,37 @@
package de.rayzs.pat.plugin.listeners.bukkit;
import org.bukkit.event.player.PlayerCommandSendEvent;
import org.bukkit.entity.Player;
import de.rayzs.pat.utils.*;
import org.bukkit.event.*;
import org.bukkit.Bukkit;
import java.util.*;
public class BukkitAntiTabListener implements Listener {
@EventHandler (priority = EventPriority.LOWEST)
public void onPlayerCommandSend(PlayerCommandSendEvent event) {
Player player = event.getPlayer();
if (PermissionUtil.hasBypassPermission(player)) return;
event.getCommands().removeIf(command -> {
if(Storage.TURN_BLACKLIST_TO_WHITELIST)
return !Storage.isCommandBlockedPrecise(command) && !PermissionUtil.hasBypassPermission(player, command);
else return Storage.isCommandBlocked(command) && !PermissionUtil.hasBypassPermission(player, command);
});
}
public static void updateCommands() {
if(Reflection.getMinor() >= 18) Bukkit.getOnlinePlayers().forEach(Player::updateCommands);
}
public static void handleTabCompletion(List<String> commands) {
for (Player player : Bukkit.getOnlinePlayers()) {
List<String> dummy = new ArrayList<>(commands);
PlayerCommandSendEvent event = new PlayerCommandSendEvent(player, dummy);
Bukkit.getPluginManager().callEvent(event);
player.updateCommands();
}
}
}
@@ -0,0 +1,60 @@
package de.rayzs.pat.plugin.listeners.bukkit;
import de.rayzs.pat.plugin.logger.Logger;
import de.rayzs.pat.utils.*;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.event.*;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.help.HelpTopic;
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(Storage.USE_UNKNOWN_COMMAND) {
String targetCommand = rawCommand.contains(" ") ? rawCommand.split(" ")[0] : rawCommand;
HelpTopic helpTopic = Bukkit.getHelpMap().getHelpTopic(targetCommand);
if(helpTopic == null) {
for (String line : Storage.UNKNOWN_COMMAND) player.sendMessage(line.replace("&", "§"));
event.setCancelled(true);
return;
}
}
if(rawCommand.equals("/")) return;
if((Storage.TURN_BLACKLIST_TO_WHITELIST)) {
if(Storage.isCommandBlockedPrecise(command)) return;
if(PermissionUtil.hasBypassPermission(player, command)) return;
player.sendMessage(Storage.CANCEL_COMMANDS_MESSAGE.replace("%command%", rawCommand.replaceFirst("/", "")));
event.setCancelled(true);
return;
}
if (command.contains(":")) {
String[] commandSplit = command.split(":");
if(commandSplit.length > 1) command = commandSplit[1];
}
if (!Storage.isCommandBlocked(commandLowerCased)) return;
if (PermissionUtil.hasBypassPermission(player, command)) return;
player.sendMessage(Storage.CANCEL_COMMANDS_MESSAGE.replace("%command%", rawCommand.replaceFirst("/", "")));
final World world = player.getWorld();
final String worldName = world.getName(), alertMessage = Storage.NOTIFY_ALERT.replace("%player%", player.getName()).replace("%command%", command).replace("%world%", worldName);
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,36 @@
package de.rayzs.pat.plugin.listeners.bukkit;
import de.rayzs.pat.plugin.BukkitLoader;
import de.rayzs.pat.plugin.logger.Logger;
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
public void onPlayerJoin(PlayerJoinEvent event) {
Player player = event.getPlayer();
if(!PacketAnalyzer.inject(player) && Reflection.getMinor() <= 17) player.kickPlayer("Failed to inject player!");
if(!Storage.BUNGEECORD && Storage.OUTDATED_VERSION && (PermissionUtil.hasPermission(player, "update"))) {
Bukkit.getScheduler().runTaskLater(BukkitLoader.getPlugin(), () -> {
if(player.isOnline()) {
Storage.UPDATE_NOTIFICATION.forEach(message -> player.sendMessage(message.replace("&", "§")));
}
}, 20);
}
}
@EventHandler (priority = EventPriority.LOWEST)
public void onPlayerQuit(PlayerQuitEvent event) {
Player player = event.getPlayer();
PacketAnalyzer.uninject(player.getUniqueId());
}
}
@@ -0,0 +1,104 @@
package de.rayzs.pat.plugin.listeners.bungee;
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.*;
public class BungeeAntiTabListener implements Listener {
@EventHandler
public void onTabComplete(TabCompleteEvent event) {
if(!(event.getSender() instanceof ProxiedPlayer)) return;
ProxiedPlayer player = (ProxiedPlayer) event.getSender();
if(PermissionUtil.hasBypassPermission(player)) return;
event.getSuggestions().removeIf(command -> {
if(Storage.TURN_BLACKLIST_TO_WHITELIST)
return !Storage.isCommandBlockedPrecise(command) && !PermissionUtil.hasBypassPermission(player, command);
else return Storage.isCommandBlockedPrecise(command) && !PermissionUtil.hasBypassPermission(player, command);
});
}
@EventHandler
public void onTabComplete(TabCompleteResponseEvent event) {
if(!(event.getSender() instanceof ProxiedPlayer)) return;
ProxiedPlayer player = (ProxiedPlayer) event.getSender();
if(PermissionUtil.hasBypassPermission(player)) return;
event.getSuggestions().removeIf(command -> {
if(Storage.TURN_BLACKLIST_TO_WHITELIST)
return !Storage.isCommandBlockedPrecise(command) && !PermissionUtil.hasBypassPermission(player, command);
else return Storage.isCommandBlocked(command) && !PermissionUtil.hasBypassPermission(player, command);
});
}
/*
@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)) {
System.out.println(1);
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(Storage.TURN_BLACKLIST_TO_WHITELIST) {
if(Storage.isCommandBlockedPrecise(tempName) && !event.getSuggestions().contains(command))
event.getSuggestions().add(command);
else if(!Storage.isCommandBlockedPrecise(tempName) && !PermissionUtil.hasBypassPermission(player, tempName))
event.getSuggestions().remove(command);
continue;
}
if (tempName.contains(":")) {
String[] tempCommandSplit = tempName.split(":");
if(tempCommandSplit.length > 1) tempName = tempCommandSplit[1];
}
if (!Storage.isCommandBlocked(tempName)) continue;
if(PermissionUtil.hasBypassPermission(player, tempName)) continue;
event.getSuggestions().remove(command);
}
}*/
}
@@ -0,0 +1,54 @@
package de.rayzs.pat.plugin.listeners.bungee;
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.config.ServerInfo;
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(rawCommand.equals("/")) return;
if(Storage.TURN_BLACKLIST_TO_WHITELIST) {
if(Storage.isCommandBlockedPrecise(command)) return;
if(PermissionUtil.hasBypassPermission(player, command)) return;
player.sendMessage(Storage.CANCEL_COMMANDS_MESSAGE.replace("%command%", rawCommand.replaceFirst("/", "")));
event.setCancelled(true);
return;
}
if (command.contains(":")) {
String[] commandSplit = command.split(":");
if(commandSplit.length > 1) command = commandSplit[1];
}
if(!Storage.isCommandBlocked(command) || PermissionUtil.hasBypassPermission(player, command)) return;
player.sendMessage(Storage.CANCEL_COMMANDS_MESSAGE.replace("%command%", rawCommand.replaceFirst("/", "")));
final ServerInfo serverInfo = player.getServer().getInfo();
final String serverName = serverInfo != null ? serverInfo.getName() : "unknown",
alertMessage = Storage.NOTIFY_ALERT.replace("%player%", player.getName()).replace("%command%", command).replace("%server%", serverName);
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,28 @@
package de.rayzs.pat.plugin.listeners.bungee;
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()) {
Storage.UPDATE_NOTIFICATION.forEach(message -> player.sendMessage(message.replace("&", "§")));
}
}, 1, TimeUnit.SECONDS);
}
}
}
@@ -0,0 +1,28 @@
package de.rayzs.pat.plugin.listeners.bungee;
import de.rayzs.pat.utils.PermissionUtil;
import de.rayzs.pat.utils.Storage;
import io.github.waterfallmc.waterfall.event.ProxyDefineCommandsEvent;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.plugin.Listener;
import net.md_5.bungee.event.EventHandler;
import net.md_5.bungee.event.EventPriority;
public class WaterfallAntiTabListener implements Listener {
@EventHandler(priority = EventPriority.LOWEST)
public void onProxyDefineCommands(ProxyDefineCommandsEvent event) {
if(!(event.getReceiver() instanceof ProxiedPlayer) || event.getCommands().isEmpty()) return;
ProxiedPlayer player = (ProxiedPlayer) event.getReceiver();
if(PermissionUtil.hasBypassPermission(player)) return;
event.getCommands().entrySet().removeIf(entry -> {
String command = entry.getKey();
if(Storage.TURN_BLACKLIST_TO_WHITELIST)
return !Storage.isCommandBlockedPrecise(command) && !PermissionUtil.hasBypassPermission(player, command);
else return Storage.isCommandBlocked(command) && !PermissionUtil.hasBypassPermission(player, command);
});
}
}
@@ -0,0 +1,64 @@
package de.rayzs.pat.plugin.listeners.velocity;
import com.mojang.brigadier.tree.RootCommandNode;
import com.velocitypowered.api.event.PostOrder;
import com.velocitypowered.api.event.Subscribe;
import com.velocitypowered.api.event.command.PlayerAvailableCommandsEvent;
import com.velocitypowered.api.event.player.TabCompleteEvent;
import com.velocitypowered.api.proxy.Player;
import com.velocitypowered.api.proxy.ProxyServer;
import de.rayzs.pat.utils.PermissionUtil;
import de.rayzs.pat.utils.Storage;
import java.util.HashMap;
public class VelocityAntiTabListener {
private static ProxyServer server;
public VelocityAntiTabListener(ProxyServer server) {
VelocityAntiTabListener.server = server;
}
@Subscribe
public void onTabComplete(TabCompleteEvent event) {
if(!Storage.CANCEL_COMMANDS) return;
Player player = event.getPlayer();
if(PermissionUtil.hasBypassPermission(player)) return;
event.getSuggestions().removeIf(command -> {
if(Storage.TURN_BLACKLIST_TO_WHITELIST)
return !Storage.isCommandBlockedPrecise(command) && !PermissionUtil.hasBypassPermission(player, command);
else return Storage.isCommandBlockedPrecise(command) && !PermissionUtil.hasBypassPermission(player, command);
});
}
@Subscribe (order = PostOrder.FIRST)
public void onPlayerAvailableCommands(PlayerAvailableCommandsEvent event) {
if(!Storage.CANCEL_COMMANDS) return;
Player player = event.getPlayer();
if(PermissionUtil.hasBypassPermission(player)) return;
event.getRootNode().getChildren().removeIf(command -> {
String commandName = command.getName();
if(Storage.TURN_BLACKLIST_TO_WHITELIST)
return !Storage.isCommandBlockedPrecise(commandName) && !PermissionUtil.hasBypassPermission(player, commandName);
return Storage.isCommandBlockedPrecise(commandName) && !PermissionUtil.hasBypassPermission(player, commandName);
});
}
public static void updateCommands() {
/*
for (Player player : server.getAllPlayers()) {
RootCommandNode<?> rootCommandNode = PLAYER_ROOT_NODES.get(player);
if(rootCommandNode == null) return;
PlayerAvailableCommandsEvent event = new PlayerAvailableCommandsEvent(player, rootCommandNode);
server.getEventManager().fireAndForget(event);
}
*/
}
}
@@ -0,0 +1,59 @@
package de.rayzs.pat.plugin.listeners.velocity;
import com.velocitypowered.api.command.CommandSource;
import com.velocitypowered.api.event.Subscribe;
import com.velocitypowered.api.event.command.CommandExecuteEvent;
import com.velocitypowered.api.proxy.Player;
import com.velocitypowered.api.proxy.ProxyServer;
import de.rayzs.pat.plugin.logger.Logger;
import de.rayzs.pat.utils.MessageTranslator;
import de.rayzs.pat.utils.PermissionUtil;
import de.rayzs.pat.utils.Storage;
import net.kyori.adventure.text.minimessage.MiniMessage;
public class VelocityBlockCommandListener {
private final ProxyServer server;
public VelocityBlockCommandListener(ProxyServer server) {
this.server = server;
}
@Subscribe
public void onPlayerChat(CommandExecuteEvent event) {
if(!Storage.CANCEL_COMMANDS || !event.getResult().isAllowed()) return;
CommandSource commandSource = event.getCommandSource();
if(!(commandSource instanceof Player)) return;
Player player = (Player) commandSource;
String command = event.getCommand();
if(Storage.TURN_BLACKLIST_TO_WHITELIST) {
if(Storage.isCommandBlockedPrecise(command)) return;
if(PermissionUtil.hasBypassPermission(player, command)) return;
player.sendMessage(MiniMessage.miniMessage().deserialize(MessageTranslator.translate(Storage.CANCEL_COMMANDS_MESSAGE.replace("%command%", command.replaceFirst("/", "")))));
event.setResult(CommandExecuteEvent.CommandResult.denied());
return;
}
if (command.contains(":")) {
String[] commandSplit = command.split(":");
if(commandSplit.length > 1) command = commandSplit[1];
}
if(!Storage.isCommandBlocked(command) || PermissionUtil.hasBypassPermission(player, command)) return;
player.sendMessage(MiniMessage.miniMessage().deserialize(MessageTranslator.translate(Storage.CANCEL_COMMANDS_MESSAGE.replace("%command%", command.replaceFirst("/", "")))));
final String serverName = player.getCurrentServer().isPresent() ? player.getCurrentServer().get().getServerInfo().getName() : "unknown",
alertMessage = Storage.NOTIFY_ALERT.replace("%player%", player.getUsername()).replace("%command%", command).replace("%server%", serverName);
Storage.NOTIFY_PLAYERS.stream().filter(uuid -> server.getPlayer(uuid).isPresent() && server.getPlayer(uuid).get().isActive()).forEach(uuid -> {
server.getPlayer(uuid).get().sendMessage(MiniMessage.miniMessage().deserialize(MessageTranslator.translate(alertMessage)));
});
if(Storage.CONSOLE_NOTIFICATION_ENABLED) server.getConsoleCommandSource().sendMessage(MiniMessage.miniMessage().deserialize(MessageTranslator.translate(alertMessage)));
event.setResult(CommandExecuteEvent.CommandResult.denied());
}
}
@@ -0,0 +1,35 @@
package de.rayzs.pat.plugin.listeners.velocity;
import com.velocitypowered.api.event.Subscribe;
import com.velocitypowered.api.event.player.ServerPreConnectEvent;
import com.velocitypowered.api.proxy.Player;
import com.velocitypowered.api.proxy.ProxyServer;
import de.rayzs.pat.plugin.VelocityLoader;
import de.rayzs.pat.utils.MessageTranslator;
import de.rayzs.pat.utils.PermissionUtil;
import de.rayzs.pat.utils.Storage;
import net.kyori.adventure.text.minimessage.MiniMessage;
import java.util.concurrent.TimeUnit;
public class VelocityConnectionListener {
private final ProxyServer server;
private final VelocityLoader loader;
public VelocityConnectionListener(ProxyServer server, VelocityLoader loader) {
this.server = server;
this.loader = loader;
}
@Subscribe
public void onServerPreConnect(ServerPreConnectEvent event) {
Player player = event.getPlayer();
if(Storage.OUTDATED_VERSION && (PermissionUtil.hasPermission(player, "update"))) {
server.getScheduler().buildTask(loader, () -> {
if (player.isActive()) {
Storage.UPDATE_NOTIFICATION.forEach(message -> player.sendMessage(MiniMessage.miniMessage().deserialize(MessageTranslator.translate(message))));
}
}).delay(1, TimeUnit.SECONDS).schedule();
}
}
}
@@ -0,0 +1,37 @@
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.isVelocityServer() ? null
: Reflection.isProxyServer()
? 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) {
if(LOGGER == null) {
System.out.println(text);
return;
}
boolean hasColors = text.contains("§");
if(hasColors) {
if (Reflection.isProxyServer()) 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.isProxyServer()) 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;
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,107 @@
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(Storage.TURN_BLACKLIST_TO_WHITELIST) {
if(!Storage.isCommandBlockedPrecise(tempName)) continue;
if(PermissionUtil.hasBypassPermission(player, tempName)) continue;
newResultList.add(s);
continue;
}
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,256 @@
package de.rayzs.pat.plugin.process;
import de.rayzs.pat.plugin.BukkitLoader;
import de.rayzs.pat.plugin.listeners.bukkit.BukkitAntiTabListener;
import de.rayzs.pat.plugin.listeners.velocity.VelocityAntiTabListener;
import de.rayzs.pat.utils.*;
import de.rayzs.pat.utils.communication.ClientCommunication;
import de.rayzs.pat.utils.group.*;
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, extra;
Group group;
boolean bool;
if(!PermissionUtil.hasPermissionWithResponse(sender, "use")) return;
if(Storage.BUNGEECORD) {
if(!Reflection.isProxyServer())
sender.sendMessage(Storage.BUNGEECORD_MESSAGE);
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.isVelocityServer()) VelocityAntiTabListener.updateCommands();
else if(!Reflection.isProxyServer() && Reflection.getMinor() >= 18) 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.isVelocityServer()) VelocityAntiTabListener.updateCommands();
else if(!Reflection.isProxyServer()) {
if(Reflection.getMinor() >= 18) BukkitAntiTabListener.updateCommands();
} else ClientCommunication.synchronizeInformation();
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 "listgroups":
case "lg":
if(!PermissionUtil.hasPermissionWithResponse(sender, "listgroups")) return;
StringBuilder groupsBuilder = new StringBuilder();
for (int i = 0; i < GroupManager.getGroupNames().size(); i++) {
bool = (i >= GroupManager.getGroupNames().size() - 1);
groupsBuilder.append(Storage.GROUPS_LIST_GROUPS_MESSAGE).append(GroupManager.getGroupNames().get(i));
if (!bool)
groupsBuilder.append(Storage.GROUPS_LIST_SPLITTER_MESSAGE);
}
sender.sendMessage(Storage.GROUPS_LIST_MESSAGE.replace("%size%", String.valueOf(GroupManager.getGroupNames().size())).replace("%groups%", groupsBuilder.toString()));
return;
}
case 2:
task = args[0].toLowerCase();
sub = args[1];
bool = Storage.BLOCKED_COMMANDS_LIST.contains(sub);
switch (task) {
case "ls":
case "list":
if(!PermissionUtil.hasPermissionWithResponse(sender, "list")) return;
group = GroupManager.getGroupByName(sub.toLowerCase());
if(group == null) {
sender.sendMessage(Storage.GROUP_NOT_EXIST_MESSAGE.replace("%group%", sub));
return;
}
StringBuilder blacklistedCommandBuilder = new StringBuilder();
for (int i = 0; i < group.getCommands().size(); i++) {
bool = (i >= group.getCommands().size() - 1);
blacklistedCommandBuilder.append(Storage.GROUP_LIST_COMMAND_MESSAGE).append(group.getCommands().get(i));
if (!bool)
blacklistedCommandBuilder.append(Storage.GROUP_LIST_SPLITTER_MESSAGE);
}
sender.sendMessage(Storage.GROUP_LIST_MESSAGE.replace("%size%", String.valueOf(group.getCommands().size())).replace("%commands%", blacklistedCommandBuilder.toString()).replace("%group%", group.getGroupName()));
return;
case "creategroup":
case "cg":
if(!PermissionUtil.hasPermissionWithResponse(sender, "creategroup")) return;
if(sub.equalsIgnoreCase("commands")) return;
bool = GroupManager.isGroupRegistered(sub.toLowerCase());
if(!bool) GroupManager.registerGroup(sub.toLowerCase());
sender.sendMessage((bool ? Storage.GROUP_ALREADY_CREATED_MESSAGE : Storage.GROUP_CREATE_MESSAGE).replace("%group%", sub.toLowerCase()));
return;
case "deletegroup":
case "dg":
if(!PermissionUtil.hasPermissionWithResponse(sender, "deletegroup")) return;
bool = GroupManager.isGroupRegistered(sub.toLowerCase());
if(bool) GroupManager.unregisterGroup(sub.toLowerCase());
sender.sendMessage((bool ? Storage.GROUP_DELETE_MESSAGE : Storage.GROUP_NOT_EXIST_MESSAGE).replace("%group%", sub.toLowerCase()));
return;
case "clear": case "cls":
if(!PermissionUtil.hasPermissionWithResponse(sender, "clear")) return;
group = GroupManager.getGroupByName(sub);
if(group == null) {
sender.sendMessage(Storage.GROUP_NOT_EXIST_MESSAGE.replace("%group%", sub));
return;
}
group.clear();
if(Reflection.isVelocityServer()) VelocityAntiTabListener.updateCommands();
else if(!Reflection.isProxyServer()) {
if(Reflection.getMinor() >= 18) BukkitAntiTabListener.updateCommands();
} else ClientCommunication.synchronizeInformation();
sender.sendMessage(Storage.GROUP_CLEAR_MESSAGE.replace("%group%", group.getGroupName()));
return;
case "add":
if(!PermissionUtil.hasPermissionWithResponse(sender, "add")) return;
if (!bool) {
Storage.BLOCKED_COMMANDS_LIST.add(sub);
Storage.save();
if(Reflection.isVelocityServer()) VelocityAntiTabListener.updateCommands();
else if(!Reflection.isProxyServer()) {
if(Reflection.getMinor() >= 18) BukkitAntiTabListener.updateCommands();
} else ClientCommunication.synchronizeInformation();
}
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.isVelocityServer()) VelocityAntiTabListener.updateCommands();
else if(!Reflection.isProxyServer()) {
if(Reflection.getMinor() >= 18) BukkitAntiTabListener.updateCommands();
} else ClientCommunication.synchronizeInformation();
}
sender.sendMessage((!bool ? Storage.BLACKLIST_REMOVE_FAIL_MESSAGE : Storage.BLACKLIST_REMOVE_MESSAGE).replace("%command%", sub));
return;
}
case 3:
task = args[0].toLowerCase();
sub = args[1].toLowerCase();
extra = args[2].toLowerCase();
group = GroupManager.getGroupByName(extra);
if(group == null) {
sender.sendMessage(Storage.GROUP_NOT_EXIST_MESSAGE.replace("%group%", extra));
return;
}
extra = group.getGroupName();
bool = group.contains(sub);
switch (task) {
case "add":
if(!PermissionUtil.hasPermissionWithResponse(sender, "add")) return;
if (!bool) group.add(sub);
sender.sendMessage((bool ? Storage.GROUP_ADD_FAIL_MESSAGE : Storage.GROUP_ADD_MESSAGE).replace("%command%", sub).replace("%group%", extra));
return;
case "remove":
case "rem":
case "rm":
if(!PermissionUtil.hasPermissionWithResponse(sender, "remove")) return;
if (bool) group.remove(sub);
sender.sendMessage((!bool ? Storage.GROUP_REMOVE_FAIL_MESSAGE : Storage.GROUP_REMOVE_MESSAGE).replace("%command%", sub).replace("%group%", extra));
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, "creategroup")) suggestions.addAll(Arrays.asList("creategroup", "cg"));
if (PermissionUtil.hasPermission(sender, "deletegroup")) suggestions.addAll(Arrays.asList("deletegroup", "dg"));
if (PermissionUtil.hasPermission(sender, "deletegroup")) suggestions.addAll(Arrays.asList("listgroups", "lg"));
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(Arrays.asList("deletegroup", "dg").contains(args[0].toLowerCase()) && PermissionUtil.hasPermission(sender, "deletegroup")) suggestions.addAll(GroupManager.getGroupNames());
if(Arrays.asList("clear", "cls").contains(args[0].toLowerCase()) && PermissionUtil.hasPermission(sender, "clear")) suggestions.addAll(GroupManager.getGroupNames());
if(Arrays.asList("ls", "list").contains(args[0].toLowerCase()) && PermissionUtil.hasPermission(sender, "list")) suggestions.addAll(GroupManager.getGroupNames());
if(args[0].equals("add") && PermissionUtil.hasPermission(sender, "add") && !Reflection.isProxyServer()) 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;
case 3:
if(args[0].equals("add") && PermissionUtil.hasPermission(sender, "add") && !Reflection.isProxyServer()) suggestions.addAll(GroupManager.getGroupByNameNotIncludingCommand(args[1]));
if(Arrays.asList("remove", "rem", "rm").contains(args[0].toLowerCase()) && PermissionUtil.hasPermission(sender, "remove")) suggestions.addAll(GroupManager.getGroupByNameOnlyIncludingCommand(args[1]));
break;
}
suggestions.stream().filter(suggestion -> suggestion.startsWith(args[args.length-1].toLowerCase())).forEach(result::add);
return result;
}
}
@@ -0,0 +1,53 @@
package de.rayzs.pat.utils;
import com.velocitypowered.api.command.CommandSource;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
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.isVelocityServer() ? sender instanceof com.velocitypowered.api.proxy.Player
: Reflection.isProxyServer() ? sender instanceof ProxiedPlayer
: sender instanceof Player;
}
public boolean hasPermission(String permission) {
if(isConsole()) return true;
return Reflection.isVelocityServer()
&& sender instanceof CommandSource
? ((CommandSource) sender).hasPermission(permission)
: Reflection.isProxyServer()
&& sender instanceof ProxiedPlayer
? ((ProxiedPlayer) sender).hasPermission(permission)
: sender instanceof Player
&& (((Player) sender).hasPermission(permission)
|| ((Player) sender).isOp());
}
public void sendMessage(String text) {
if(Reflection.isVelocityServer()) ((CommandSource) sender).sendMessage(MiniMessage.miniMessage().deserialize(MessageTranslator.translate(text)));
else if(Reflection.isProxyServer()) ((net.md_5.bungee.api.CommandSender) sender).sendMessage(text);
else ((org.bukkit.command.CommandSender) sender).sendMessage(text);
}
public UUID getUniqueId() {
if(Reflection.isVelocityServer()) return ((com.velocitypowered.api.proxy.Player) sender).getUniqueId();
else if(Reflection.isProxyServer()) 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,35 @@
package de.rayzs.pat.utils;
import de.rayzs.pat.utils.group.Group;
import de.rayzs.pat.utils.group.GroupManager;
import java.util.List;
public class DataConverter {
public static String convertCommandsToString(List<String> commands) {
if(commands.isEmpty()) return "§";
StringBuilder result = new StringBuilder();
for (int i = 0; i < commands.size(); i++) {
result.append(commands.get(i));
if(i < (commands.size() - 1)) result.append(";");
}
return result.toString();
}
public static String convertGroupsToString() {
if(GroupManager.getGroups().isEmpty()) return "§";
StringBuilder result = new StringBuilder();
for (Group group : GroupManager.getGroups()) {
result.append(group.getGroupName());
for (String command : group.getCommands())
result.append(";" + command);
result.append("\\\\");
}
return result.toString();
}
}
@@ -0,0 +1,50 @@
package de.rayzs.pat.utils;
import java.util.HashMap;
import java.util.Map;
public class MessageTranslator {
private static final HashMap<Character, String> COLORS = new HashMap<>();
static {
COLORS.put('1', "<dark_blue>");
COLORS.put('2', "<dark_green>");
COLORS.put('3', "<dark_aqua>");
COLORS.put('4', "<dark_red>");
COLORS.put('5', "<dark_purple>");
COLORS.put('6', "<orange>");
COLORS.put('7', "<gray>");
COLORS.put('8', "<dark_gray>");
COLORS.put('9', "<blue>");
COLORS.put('a', "<green>");
COLORS.put('b', "<aqua>");
COLORS.put('c', "<red>");
COLORS.put('d', "<light_purple>");
COLORS.put('e', "<yellow>");
COLORS.put('f', "<white>");
COLORS.put('m', "<st>");
COLORS.put('k', "<obf>");
COLORS.put('n', "<r>");
COLORS.put('o', "<i>");
COLORS.put('l', "<b>");
}
public static String translate(String text) {
if(!Reflection.isVelocityServer()) return text.replace("&", "§");
if(!text.contains("§")) return text;
for (Map.Entry<Character, String> entry : COLORS.entrySet())
text = text.replace("§" + entry.getKey(), entry.getValue());
return text;
}
public static String clear(String text) {
for (Map.Entry<Character, String> entry : COLORS.entrySet())
text = text.replace("§" + entry.getKey(), "");
return text;
}
}
@@ -0,0 +1,34 @@
package de.rayzs.pat.utils;
import de.rayzs.pat.utils.group.GroupManager;
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())
|| GroupManager.canAccessCommand(targetObj, command);
}
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,235 @@
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, proxy, velocity;
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");
proxy = false;
} catch (ClassNotFoundException ignored) { proxy = true; }
if(proxy) {
try {
Class.forName("com.velocitypowered.api.proxy.ProxyServer");
velocity = true;
} catch (ClassNotFoundException ignored) { velocity = false; }
}
if (!proxy) {
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 isProxyServer() {
return proxy;
}
public static boolean isVelocityServer() {
return velocity;
}
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 = proxy ? 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,181 @@
package de.rayzs.pat.utils;
import de.rayzs.pat.utils.configuration.*;
import java.util.*;
public class Storage {
public static ConfigurationBuilder CONFIGURATION = Configurator.get("config"), STORAGE = Configurator.get("storage");;
public static List<String> UNKNOWN_COMMAND, BLOCKED_COMMANDS_LIST, COMMAND_HELP = new ArrayList<>(), UPDATE_NOTIFICATION = new ArrayList<>();
public static List<UUID> NOTIFY_PLAYERS = new ArrayList<>();
public static String TOKEN = UUID.randomUUID().toString(), BUNGEECORD_MESSAGE, 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,
GROUP_CREATE_MESSAGE, GROUP_DELETE_MESSAGE, GROUP_ALREADY_CREATED_MESSAGE, GROUP_NOT_EXIST_MESSAGE, GROUP_CLEAR_MESSAGE, GROUP_LIST_COMMAND_MESSAGE, GROUP_ADD_MESSAGE, GROUP_ADD_FAIL_MESSAGE, GROUP_REMOVE_MESSAGE, GROUP_REMOVE_FAIL_MESSAGE, GROUP_LIST_MESSAGE, GROUP_LIST_SPLITTER_MESSAGE, GROUPS_LIST_MESSAGE, GROUPS_LIST_SPLITTER_MESSAGE, GROUPS_LIST_GROUPS_MESSAGE;
public static boolean BUNGEECORD = false, USE_UNKNOWN_COMMAND, TURN_BLACKLIST_TO_WHITELIST, CANCEL_COMMANDS, UPDATE_ENABLED, OUTDATED_VERSION = false, CONSOLE_NOTIFICATION_ENABLED = true;
public static int UPDATE_PERIOD;
public static void load() {
STORAGE.reload();
CONFIGURATION.reload();
ArrayList<String> defaultBlockedCommandArray = new ArrayList<>(),
defaultHelpArray = new ArrayList<>(),
defaultUnknownCommandArray = new ArrayList<>(),
defaultNotificationArray = 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 notify &7to get alerted");
defaultHelpArray.add("&f listgroups &7List all groups");
defaultHelpArray.add("&f creategroup (group) &7Create a group");
defaultHelpArray.add("&f deletegroup (group) &7Delete a group");
defaultHelpArray.add("&f list &8(optional: group) &7to see all listed commands");
defaultHelpArray.add("&f clear &8(optional: group) &7to clear the list");
defaultHelpArray.add("&f add/remove (command) &8(optional: group) &7to manage the list");
defaultUnknownCommandArray.add("&cThis command does not exist!");
defaultNotificationArray.add("&8[&4ProAntiTab&8] &cYou're using an outdated version of this plugin!");
defaultNotificationArray.add("&8[&4ProAntiTab&8] &cPlease update it on: &ehttps://www.rayzs.de/products/proantitab/page");
UPDATE_ENABLED = (boolean) CONFIGURATION.getOrSet("updater.enabled", true);
UPDATE_PERIOD = (int) CONFIGURATION.getOrSet("updater.period", 18000);
UPDATE_NOTIFICATION = (ArrayList<String>) CONFIGURATION.getOrSet("updater.notification", defaultNotificationArray);
COMMAND_HELP = (ArrayList<String>) CONFIGURATION.getOrSet("help", defaultHelpArray);
BLOCKED_COMMANDS_LIST = (ArrayList<String>) STORAGE.getOrSet("commands", defaultBlockedCommandArray);
NO_PERMISSIONS = (String) CONFIGURATION.getOrSet("no-permissions", "&cYou are not allowed to execute this command! Missing permission: &4proantitab.%permission%");
if(!Reflection.isProxyServer()) {
BUNGEECORD = (boolean) CONFIGURATION.getOrSet("handle-through-bungeecord.enabled", BUNGEECORD);
BUNGEECORD_MESSAGE = (String) CONFIGURATION.getOrSet("handle-through-bungeecord.message", BUNGEECORD_MESSAGE);
USE_UNKNOWN_COMMAND = (boolean) CONFIGURATION.getOrSet("custom-unknown-command.enabled", USE_UNKNOWN_COMMAND);
UNKNOWN_COMMAND = (ArrayList<String>) CONFIGURATION.getOrSet("custom-unknown-command.message", defaultUnknownCommandArray);
}
TOKEN = (String) CONFIGURATION.getOrSet(Reflection.isProxyServer() ? "token" : "handle-through-bungeecord.token", Reflection.isProxyServer() ? TOKEN : "insert-token-of-bungeecord-here");
NOTIFY_ENABLED = (String) CONFIGURATION.getOrSet("notification.enabled", "&aEnabled notifications!");
NOTIFY_DISABLED = (String) CONFIGURATION.getOrSet("notification.disabled", "&cDisabled notifications!");
NOTIFY_ALERT = (String) CONFIGURATION.getOrSet("notification.alert", "&8[&4ALERT&8] &c%player% tried to execute the following blocked command: &4%command%");
CANCEL_COMMANDS = (boolean) CONFIGURATION.getOrSet("cancel-blocked-commands.enabled", true);
CANCEL_COMMANDS_MESSAGE = (String) CONFIGURATION.getOrSet("cancel-blocked-commands.message", "&cThe command '%command%' is blocked!");
TURN_BLACKLIST_TO_WHITELIST = (boolean) CONFIGURATION.getOrSet("turn-blacklist-to-whitelist", false);
BLACKLIST_CLEAR_MESSAGE = (String) CONFIGURATION.getOrSet("blacklist.clear", "&aList has been cleared!");
BLACKLIST_LIST_MESSAGE = (String) CONFIGURATION.getOrSet("blacklist.list.message", "&7Listed commands (&f%size%&7)&8: &f%commands%");
BLACKLIST_LIST_SPLITTER_MESSAGE = (String) CONFIGURATION.getOrSet("blacklist.list.splitter", "&7, ");
BLACKLIST_LIST_COMMAND_MESSAGE = (String) CONFIGURATION.getOrSet("blacklist.list.command", "&f");
BLACKLIST_ADD_MESSAGE = (String) CONFIGURATION.getOrSet("blacklist.add.success", "&aSuccessfully added %command% into list!");
BLACKLIST_ADD_FAIL_MESSAGE = (String) CONFIGURATION.getOrSet("blacklist.add.failed", "&c%command% is already in the list!");
BLACKLIST_REMOVE_MESSAGE = (String) CONFIGURATION.getOrSet("blacklist.remove.success", "&aSuccessfully removed %command% from the list!");
BLACKLIST_REMOVE_FAIL_MESSAGE = (String) CONFIGURATION.getOrSet("blacklist.remove.failed", "&c%command% is not listed!");
GROUPS_LIST_MESSAGE = (String) CONFIGURATION.getOrSet("group.list-groups.message", "&7All groups (&f%size%&7)&8: &f%groups%");
GROUPS_LIST_SPLITTER_MESSAGE = (String) CONFIGURATION.getOrSet("group.list-groups.splitter", "&7, ");
GROUPS_LIST_GROUPS_MESSAGE = (String) CONFIGURATION.getOrSet("group.list-groups.group", "&f");
GROUP_CREATE_MESSAGE = (String) CONFIGURATION.getOrSet("group.create", "&aGroup %group% has been created!");
GROUP_ALREADY_CREATED_MESSAGE = (String) CONFIGURATION.getOrSet("group.already-exist", "&cGroup %group% already exist!");
GROUP_NOT_EXIST_MESSAGE = (String) CONFIGURATION.getOrSet("group.does-not-exist", "&cGroup %group% does not exist!");
GROUP_DELETE_MESSAGE = (String) CONFIGURATION.getOrSet("group.delete", "&cGroup %group% has been deleted!");
GROUP_CLEAR_MESSAGE = (String) CONFIGURATION.getOrSet("group.clear", "&aList of group %group% has been cleared!");
GROUP_LIST_MESSAGE = (String) CONFIGURATION.getOrSet("group.list.message", "&7Listed commands of group %group% (&f%size%&7)&8: &f%commands%");
GROUP_LIST_SPLITTER_MESSAGE = (String) CONFIGURATION.getOrSet("group.list.splitter", "&7, ");
GROUP_LIST_COMMAND_MESSAGE = (String) CONFIGURATION.getOrSet("group.list.command", "&f");
GROUP_ADD_MESSAGE = (String) CONFIGURATION.getOrSet("group.add.success", "&aSuccessfully added %command% into the list of group %group%!");
GROUP_ADD_FAIL_MESSAGE = (String) CONFIGURATION.getOrSet("group.add.failed", "&c%command% is already in the list of group %group%!");
GROUP_REMOVE_MESSAGE = (String) CONFIGURATION.getOrSet("group.remove.success", "&aSuccessfully removed %command% from the list of group %group%!");
GROUP_REMOVE_FAIL_MESSAGE = (String) CONFIGURATION.getOrSet("group.remove.failed", "&c%command% is not listed in the group %group%!");
COMMAND_UNKNOWN = (String) CONFIGURATION.getOrSet("command-failed", "&cFailed to execute this command! Use '/pat' to see all available commands.");
RELOAD_LOADING = (String) CONFIGURATION.getOrSet("reload.loading", "&eReloading all configuration files...");
RELOAD_DONE = (String) CONFIGURATION.getOrSet("reload.done", "&aSuccessfully reloaded all configuration files!");
}
public static void save() {
CONFIGURATION
.set("updater.enabled", UPDATE_ENABLED)
.set("updater.period", UPDATE_PERIOD)
.set("updater.notification", UPDATE_NOTIFICATION)
.set("no-permissions", NO_PERMISSIONS)
.set("command-failed", COMMAND_UNKNOWN)
.set("reload.loading", RELOAD_LOADING)
.set("reload.done", RELOAD_DONE)
.set("help", COMMAND_HELP)
.set("cancel-blocked-commands.enabled", CANCEL_COMMANDS)
.set("cancel-blocked-commands.message", CANCEL_COMMANDS_MESSAGE)
.set("turn-blacklist-to-whitelist", TURN_BLACKLIST_TO_WHITELIST)
.set("blacklist.clear", BLACKLIST_CLEAR_MESSAGE)
.set("blacklist.add.success", BLACKLIST_ADD_MESSAGE)
.set("blacklist.remove.success", BLACKLIST_REMOVE_MESSAGE)
.set("blacklist.add.failed", BLACKLIST_ADD_FAIL_MESSAGE)
.set("blacklist.remove.failed", BLACKLIST_REMOVE_FAIL_MESSAGE)
.set("blacklist.list.message", BLACKLIST_LIST_MESSAGE)
.set("blacklist.list.command", BLACKLIST_LIST_COMMAND_MESSAGE)
.set("blacklist.list.splitter", BLACKLIST_LIST_SPLITTER_MESSAGE)
.set("group.create", GROUP_CREATE_MESSAGE)
.set("group.delete", GROUP_DELETE_MESSAGE)
.set("group.already-exist", GROUP_ALREADY_CREATED_MESSAGE)
.set("group.does-not-exist", GROUP_NOT_EXIST_MESSAGE)
.set("group.clear", GROUP_CLEAR_MESSAGE)
.set("group.add.success", GROUP_ADD_MESSAGE)
.set("group.remove.success", GROUP_REMOVE_MESSAGE)
.set("group.add.failed", GROUP_ADD_FAIL_MESSAGE)
.set("group.remove.failed", GROUP_REMOVE_FAIL_MESSAGE)
.set("group.list.message", GROUP_LIST_MESSAGE)
.set("group.list.command", GROUP_LIST_COMMAND_MESSAGE)
.set("group.list.splitter", GROUP_LIST_SPLITTER_MESSAGE)
.set("group.list-groups.message", GROUPS_LIST_MESSAGE)
.set("group.list-groups.group", GROUPS_LIST_GROUPS_MESSAGE)
.set("group.list-groups.splitter", GROUPS_LIST_SPLITTER_MESSAGE);
if(!Reflection.isProxyServer()) {
CONFIGURATION.set("custom-unknown-command.enabled", USE_UNKNOWN_COMMAND)
.set("custom-unknown-command.message", UNKNOWN_COMMAND)
.set("handle-through-bungeecord.enabled", BUNGEECORD)
.set("handle-through-bungeecord.token", TOKEN)
.set("handle-through-bungeecord.message", BUNGEECORD_MESSAGE);
}
STORAGE.setAndSave("commands", BLOCKED_COMMANDS_LIST);
CONFIGURATION.save();
}
public static boolean isCommandBlocked(String command) {
String[] split;
if(command.contains(" ")) {
split = command.split(" ");
if(split.length > 0) command = split[0];
command = command.split(" ")[0];
}
if(command.contains(":")) {
split = command.split(":");
if(split.length > 0) command = split[1];
}
for (String blockedCommand : BLOCKED_COMMANDS_LIST) {
if(blockedCommand.equals(command.toLowerCase())) return true;
}
return false;
}
public static boolean isCommandBlockedPrecise(String command) {
String[] split;
if(command.contains(" ")) {
split = command.split(" ");
if(split.length > 0) command = split[0];
command = command.split(" ")[0];
}
for (String blockedCommand : BLOCKED_COMMANDS_LIST) {
if(blockedCommand.equals(command.toLowerCase())) return true;
}
return false;
}
}
@@ -0,0 +1,6 @@
package de.rayzs.pat.utils.communication;
public interface Client {
String CHANNEL_NAME = "pat:channel";
void sendInformation(String information);
}
@@ -0,0 +1,53 @@
package de.rayzs.pat.utils.communication;
import de.rayzs.pat.plugin.BukkitLoader;
import de.rayzs.pat.plugin.BungeeLoader;
import de.rayzs.pat.utils.DataConverter;
import de.rayzs.pat.utils.Reflection;
import de.rayzs.pat.utils.Storage;
import de.rayzs.pat.utils.communication.impl.*;
import java.util.*;
public class ClientCommunication {
private static final Client CLIENT = Reflection.isVelocityServer() ? null : Reflection.isProxyServer() ? new BungeeClient() : new BukkitClient();
public static void sendInformation(String information) {
if(CLIENT == null) return;
CLIENT.sendInformation(information);
}
public static void receiveInformation(String information) {
if(!information.contains("::")) return;
String[] args = information.split("::");
switch (args[0].toLowerCase()) {
case "request":
if(args.length != 2 || !args[1].equals(Storage.TOKEN)) return;
BungeeLoader.handleIfConnectedToSpigot();
synchronizeInformation();
break;
case "receive-commands":
if(args.length != 3) return;
BukkitLoader.synchronizeCommandData(Boolean.parseBoolean(args[1]), args[2].equals("§") ? new ArrayList<>() : Arrays.asList(args[2].split(";")));
break;
case "receive-groups":
if(args.length != 2) return;
BukkitLoader.synchronizeGroupData(args[1]);
break;
}
}
public static void synchronizeInformation() {
sendInformation("receive-commands::" + Storage.TURN_BLACKLIST_TO_WHITELIST + "::" + (DataConverter.convertCommandsToString(Storage.BLOCKED_COMMANDS_LIST)));
sendInformation("receive-groups::" + DataConverter.convertGroupsToString());
}
public static void sendRequest() {
sendInformation("request::" + Storage.TOKEN);
}
public static Client getClient() {
return CLIENT;
}
}
@@ -0,0 +1,37 @@
package de.rayzs.pat.utils.communication.impl;
import org.bukkit.*;
import com.google.common.io.*;
import org.bukkit.entity.Player;
import de.rayzs.pat.plugin.BukkitLoader;
import de.rayzs.pat.utils.communication.*;
import org.bukkit.plugin.messaging.PluginMessageListener;
public class BukkitClient implements Client, PluginMessageListener {
private static final Server SERVER = Bukkit.getServer();
public BukkitClient() {
SERVER.getMessenger().registerIncomingPluginChannel(BukkitLoader.getPlugin(), CHANNEL_NAME, this);
SERVER.getMessenger().registerOutgoingPluginChannel(BukkitLoader.getPlugin(), CHANNEL_NAME);
}
@Override
public void sendInformation(String information) {
try {
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF(information);
SERVER.sendPluginMessage(BukkitLoader.getPlugin(), CHANNEL_NAME, out.toByteArray());
} catch (Throwable throwable) { throwable.printStackTrace(); }
}
@Override
public void onPluginMessageReceived(String channel, Player player, byte[] bytes) {
if(!channel.equals(CHANNEL_NAME)) return;
try {
ByteArrayDataInput input = ByteStreams.newDataInput(bytes);
String information = input.readUTF();
Bukkit.getScheduler().scheduleSyncDelayedTask(BukkitLoader.getPlugin(), () -> ClientCommunication.receiveInformation(information));
} catch (Throwable throwable) { throwable.printStackTrace(); }
}
}
@@ -0,0 +1,42 @@
package de.rayzs.pat.utils.communication.impl;
import java.io.*;
import net.md_5.bungee.api.ProxyServer;
import de.rayzs.pat.plugin.BungeeLoader;
import de.rayzs.pat.utils.communication.*;
import net.md_5.bungee.event.EventHandler;
import net.md_5.bungee.api.plugin.Listener;
import net.md_5.bungee.api.config.ServerInfo;
import net.md_5.bungee.api.event.PluginMessageEvent;
public class BungeeClient implements Client, Listener {
private static final ProxyServer SERVER = ProxyServer.getInstance();
public BungeeClient() {
SERVER.registerChannel(CHANNEL_NAME);
SERVER.getPluginManager().registerListener(BungeeLoader.getPlugin(), this);
}
@Override
public void sendInformation(String information) {
for(ServerInfo serverInfo : ProxyServer.getInstance().getServers().values()) {
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(stream);
out.writeUTF(information);
serverInfo.sendData(CHANNEL_NAME, stream.toByteArray());
} catch (Throwable throwable) { throwable.printStackTrace(); }
}
}
@EventHandler
public void onQueryReceive(PluginMessageEvent event) {
if (!event.getTag().equalsIgnoreCase(CHANNEL_NAME)) return;
try {
DataInputStream input = new DataInputStream(new ByteArrayInputStream(event.getData()));
String information = input.readUTF();
ClientCommunication.receiveInformation(information);
} catch (Throwable throwable) { throwable.printStackTrace(); }
}
}
@@ -0,0 +1,21 @@
package de.rayzs.pat.utils.configuration;
import java.io.File;
import java.util.Collection;
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);
Collection<String> getKeys(boolean deep);
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.isProxyServer()
? new ProxyConfigurationBuilder(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.isProxyServer()
? new ProxyConfigurationBuilder(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,126 @@
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;
import java.util.Collection;
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 Collection<String> getKeys(boolean deep) {
return this.configuration.getKeys(deep);
}
@Override
public File getFile() {
return file;
}
@Override
public boolean loadDefault() {
return loadDefault;
}
}
@@ -0,0 +1,133 @@
package de.rayzs.pat.utils.configuration.impl;
import de.rayzs.pat.plugin.logger.Logger;
import de.rayzs.pat.utils.configuration.ConfigurationBuilder;
import java.io.File;
import java.util.Collection;
import de.rayzs.pat.utils.configuration.yaml.*;
public class ProxyConfigurationBuilder implements ConfigurationBuilder {
private String fileName, filePath;
private File file;
private boolean loadDefault;
private Configuration configuration;
public ProxyConfigurationBuilder(String fileName) {
init(fileName);
}
public ProxyConfigurationBuilder(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 objString.replace("&", "§");
}
return object;
}
@Override
public Collection<String> getKeys(boolean deep) {
return this.configuration.getKeys();
}
@Override
public File getFile() {
return file;
}
@Override
public boolean loadDefault() {
return loadDefault;
}
}
@@ -0,0 +1,295 @@
package de.rayzs.pat.utils.configuration.yaml;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
public final class Configuration {
private static final char SEPARATOR = '.';
final Map<String, Object> self;
private final Configuration defaults;
public Configuration() {
this(null);
}
public Configuration(Configuration defaults) {
this(new LinkedHashMap<>(), defaults);
}
Configuration(Map<?, ?> map, Configuration defaults) {
this.self = new LinkedHashMap<>();
this.defaults = defaults;
for (Map.Entry<?, ?> entry : map.entrySet()) {
String key = (entry.getKey() == null) ? "null" : entry.getKey().toString();
if (entry.getValue() instanceof Map) {
this.self.put(key, new Configuration((Map<?, ?>)entry.getValue(), (defaults == null) ? null : defaults.getSection(key)));
continue;
}
this.self.put(key, entry.getValue());
}
}
private Configuration getSectionFor(String path) {
int index = path.indexOf('.');
if (index == -1)
return this;
String root = path.substring(0, index);
Object section = this.self.get(root);
if (section == null) {
section = new Configuration((this.defaults == null) ? null : this.defaults.getSection(root));
this.self.put(root, section);
}
return (Configuration)section;
}
private String getChild(String path) {
int index = path.indexOf('.');
return (index == -1) ? path : path.substring(index + 1);
}
public <T> T get(String path, T def) {
Object val;
Configuration section = getSectionFor(path);
if (section == this) {
val = this.self.get(path);
} else {
val = section.get(getChild(path), def);
}
if (val == null && def instanceof Configuration)
this.self.put(path, def);
return (val != null) ? (T)val : def;
}
public boolean contains(String path) {
return (get(path, null) != null);
}
public Object get(String path) {
return get(path, getDefault(path));
}
public Object getDefault(String path) {
return (this.defaults == null) ? null : this.defaults.get(path);
}
public void set(String path, Object value) {
if (value instanceof Map)
value = new Configuration((Map<?, ?>)value, (this.defaults == null) ? null : this.defaults.getSection(path));
Configuration section = getSectionFor(path);
if (section == this) {
if (value == null) {
this.self.remove(path);
} else {
this.self.put(path, value);
}
} else {
section.set(getChild(path), value);
}
}
public Configuration getSection(String path) {
Object def = getDefault(path);
return (Configuration)get(path, (def instanceof Configuration) ? def : new Configuration((this.defaults == null) ? null : this.defaults.getSection(path)));
}
public Collection<String> getKeys() {
return new LinkedHashSet<>(this.self.keySet());
}
public byte getByte(String path) {
Object def = getDefault(path);
return getByte(path, (def instanceof Number) ? ((Number)def).byteValue() : 0);
}
public byte getByte(String path, byte def) {
Object val = get(path, Byte.valueOf(def));
return (val instanceof Number) ? ((Number)val).byteValue() : def;
}
public List<Byte> getByteList(String path) {
List<?> list = getList(path);
List<Byte> result = new ArrayList<>();
for (Object object : list) {
if (object instanceof Number)
result.add(Byte.valueOf(((Number)object).byteValue()));
}
return result;
}
public short getShort(String path) {
Object def = getDefault(path);
return getShort(path, (def instanceof Number) ? ((Number)def).shortValue() : 0);
}
public short getShort(String path, short def) {
Object val = get(path, Short.valueOf(def));
return (val instanceof Number) ? ((Number)val).shortValue() : def;
}
public List<Short> getShortList(String path) {
List<?> list = getList(path);
List<Short> result = new ArrayList<>();
for (Object object : list) {
if (object instanceof Number)
result.add(Short.valueOf(((Number)object).shortValue()));
}
return result;
}
public int getInt(String path) {
Object def = getDefault(path);
return getInt(path, (def instanceof Number) ? ((Number)def).intValue() : 0);
}
public int getInt(String path, int def) {
Object val = get(path, Integer.valueOf(def));
return (val instanceof Number) ? ((Number)val).intValue() : def;
}
public List<Integer> getIntList(String path) {
List<?> list = getList(path);
List<Integer> result = new ArrayList<>();
for (Object object : list) {
if (object instanceof Number)
result.add(Integer.valueOf(((Number)object).intValue()));
}
return result;
}
public long getLong(String path) {
Object def = getDefault(path);
return getLong(path, (def instanceof Number) ? ((Number)def).longValue() : 0L);
}
public long getLong(String path, long def) {
Object val = get(path, Long.valueOf(def));
return (val instanceof Number) ? ((Number)val).longValue() : def;
}
public List<Long> getLongList(String path) {
List<?> list = getList(path);
List<Long> result = new ArrayList<>();
for (Object object : list) {
if (object instanceof Number)
result.add(Long.valueOf(((Number)object).longValue()));
}
return result;
}
public float getFloat(String path) {
Object def = getDefault(path);
return getFloat(path, (def instanceof Number) ? ((Number)def).floatValue() : 0.0F);
}
public float getFloat(String path, float def) {
Object val = get(path, Float.valueOf(def));
return (val instanceof Number) ? ((Number)val).floatValue() : def;
}
public List<Float> getFloatList(String path) {
List<?> list = getList(path);
List<Float> result = new ArrayList<>();
for (Object object : list) {
if (object instanceof Number)
result.add(Float.valueOf(((Number)object).floatValue()));
}
return result;
}
public double getDouble(String path) {
Object def = getDefault(path);
return getDouble(path, (def instanceof Number) ? ((Number)def).doubleValue() : 0.0D);
}
public double getDouble(String path, double def) {
Object val = get(path, Double.valueOf(def));
return (val instanceof Number) ? ((Number)val).doubleValue() : def;
}
public List<Double> getDoubleList(String path) {
List<?> list = getList(path);
List<Double> result = new ArrayList<>();
for (Object object : list) {
if (object instanceof Number)
result.add(Double.valueOf(((Number)object).doubleValue()));
}
return result;
}
public boolean getBoolean(String path) {
Object def = getDefault(path);
return getBoolean(path, (def instanceof Boolean) ? ((Boolean)def).booleanValue() : false);
}
public boolean getBoolean(String path, boolean def) {
Object val = get(path, Boolean.valueOf(def));
return (val instanceof Boolean) ? ((Boolean)val).booleanValue() : def;
}
public List<Boolean> getBooleanList(String path) {
List<?> list = getList(path);
List<Boolean> result = new ArrayList<>();
for (Object object : list) {
if (object instanceof Boolean)
result.add((Boolean)object);
}
return result;
}
public char getChar(String path) {
Object def = getDefault(path);
return getChar(path, (def instanceof Character) ? ((Character)def).charValue() : Character.MIN_VALUE);
}
public char getChar(String path, char def) {
Object val = get(path, Character.valueOf(def));
return (val instanceof Character) ? ((Character)val).charValue() : def;
}
public List<Character> getCharList(String path) {
List<?> list = getList(path);
List<Character> result = new ArrayList<>();
for (Object object : list) {
if (object instanceof Character)
result.add((Character)object);
}
return result;
}
public String getString(String path) {
Object def = getDefault(path);
return getString(path, (def instanceof String) ? (String)def : "");
}
public String getString(String path, String def) {
Object val = get(path, def);
return (val instanceof String) ? (String)val : def;
}
public List<String> getStringList(String path) {
List<?> list = getList(path);
List<String> result = new ArrayList<>();
for (Object object : list) {
if (object instanceof String)
result.add((String)object);
}
return result;
}
public List<?> getList(String path) {
Object def = getDefault(path);
return getList(path, (def instanceof List) ? (List)def : Collections.EMPTY_LIST);
}
public List<?> getList(String path, List<?> def) {
Object val = (Object)get(path, def);
return (val instanceof List) ? (List)val : def;
}
}
@@ -0,0 +1,46 @@
package de.rayzs.pat.utils.configuration.yaml;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
public abstract class ConfigurationProvider {
private static final Map<Class<? extends ConfigurationProvider>, ConfigurationProvider> providers = new HashMap<>();
static {
try {
providers.put(YamlConfiguration.class, new YamlConfiguration());
} catch (NoClassDefFoundError noClassDefFoundError) {}
try {
providers.put(JsonConfiguration.class, new JsonConfiguration());
} catch (NoClassDefFoundError noClassDefFoundError) {}
}
public abstract Configuration load(String paramString, Configuration paramConfiguration);
public abstract Configuration load(String paramString);
public abstract Configuration load(InputStream paramInputStream, Configuration paramConfiguration);
public abstract Configuration load(InputStream paramInputStream);
public abstract Configuration load(Reader paramReader, Configuration paramConfiguration);
public abstract Configuration load(Reader paramReader);
public abstract Configuration load(File paramFile, Configuration paramConfiguration) throws IOException;
public abstract Configuration load(File paramFile) throws IOException;
public abstract void save(Configuration paramConfiguration, Writer paramWriter);
public abstract void save(Configuration paramConfiguration, File paramFile) throws IOException;
public static ConfigurationProvider getProvider(Class<? extends ConfigurationProvider> provider) {
return providers.get(provider);
}
}
@@ -0,0 +1,78 @@
package de.rayzs.pat.utils.configuration.yaml;
import com.google.common.base.Charsets;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.lang.reflect.Type;
import java.util.LinkedHashMap;
import java.util.Map;
public class JsonConfiguration extends ConfigurationProvider {
private final Gson json = (new GsonBuilder()).serializeNulls().setPrettyPrinting().registerTypeAdapter(Configuration.class, new JsonSerializer<Configuration>() {
public JsonElement serialize(Configuration src, Type typeOfSrc, JsonSerializationContext context) {
return context.serialize(src.self);
}
}).create();
public void save(Configuration config, File file) throws IOException {
try (Writer writer = new OutputStreamWriter(new FileOutputStream(file), Charsets.UTF_8)) {
save(config, writer);
}
}
public void save(Configuration config, Writer writer) {
this.json.toJson(config.self, writer);
}
public Configuration load(File file) throws IOException {
return load(file, (Configuration)null);
}
public Configuration load(File file, Configuration defaults) throws IOException {
try (FileInputStream is = new FileInputStream(file)) {
return load(is, defaults);
}
}
public Configuration load(Reader reader) {
return load(reader, (Configuration)null);
}
public Configuration load(Reader reader, Configuration defaults) {
Map<String, Object> map = (Map<String, Object>)this.json.fromJson(reader, LinkedHashMap.class);
if (map == null)
map = new LinkedHashMap<>();
return new Configuration(map, defaults);
}
public Configuration load(InputStream is) {
return load(is, (Configuration)null);
}
public Configuration load(InputStream is, Configuration defaults) {
return load(new InputStreamReader(is, Charsets.UTF_8), defaults);
}
public Configuration load(String string) {
return load(string, (Configuration)null);
}
public Configuration load(String string, Configuration defaults) {
Map<String, Object> map = (Map<String, Object>)this.json.fromJson(string, LinkedHashMap.class);
if (map == null)
map = new LinkedHashMap<>();
return new Configuration(map, defaults);
}
}
@@ -0,0 +1,134 @@
package de.rayzs.pat.utils.configuration.yaml;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.Map;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.Constructor;
import org.yaml.snakeyaml.representer.Representer;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.nodes.Node;
import org.yaml.snakeyaml.representer.Represent;
public class YamlConfiguration extends ConfigurationProvider {
private final ThreadLocal<Yaml> yaml = new ThreadLocal<Yaml>()
{
@Override
protected Yaml initialValue()
{
DumperOptions options = new DumperOptions();
options.setDefaultFlowStyle( DumperOptions.FlowStyle.BLOCK );
Representer representer = new Representer( options )
{
{
representers.put( Configuration.class, new Represent()
{
@Override
public Node representData(Object data)
{
return represent( ( (Configuration) data ).self );
}
} );
}
};
return new Yaml( new Constructor( new LoaderOptions() ), representer, options );
}
};
@Override
public void save(Configuration config, File file) throws IOException
{
try ( Writer writer = new OutputStreamWriter( new FileOutputStream( file ), StandardCharsets.UTF_8 ) )
{
save( config, writer );
}
}
@Override
public void save(Configuration config, Writer writer)
{
yaml.get().dump( config.self, writer );
}
@Override
public Configuration load(File file) throws IOException
{
return load( file, null );
}
@Override
public Configuration load(File file, Configuration defaults) throws IOException
{
try ( FileInputStream is = new FileInputStream( file ) )
{
return load( is, defaults );
}
}
@Override
public Configuration load(Reader reader)
{
return load( reader, null );
}
@Override
@SuppressWarnings("unchecked")
public Configuration load(Reader reader, Configuration defaults)
{
Map<String, Object> map = yaml.get().loadAs( reader, LinkedHashMap.class );
if ( map == null )
{
map = new LinkedHashMap<>();
}
return new Configuration( map, defaults );
}
@Override
public Configuration load(InputStream is)
{
return load( is, null );
}
@Override
@SuppressWarnings("unchecked")
public Configuration load(InputStream is, Configuration defaults)
{
Map<String, Object> map = yaml.get().loadAs( is, LinkedHashMap.class );
if ( map == null )
{
map = new LinkedHashMap<>();
}
return new Configuration( map, defaults );
}
@Override
public Configuration load(String string)
{
return load( string, null );
}
@Override
@SuppressWarnings("unchecked")
public Configuration load(String string, Configuration defaults)
{
Map<String, Object> map = yaml.get().loadAs( string, LinkedHashMap.class );
if ( map == null )
{
map = new LinkedHashMap<>();
}
return new Configuration( map, defaults );
}
}
@@ -0,0 +1,78 @@
package de.rayzs.pat.utils.group;
import de.rayzs.pat.plugin.listeners.bukkit.BukkitAntiTabListener;
import de.rayzs.pat.utils.*;
import java.util.*;
public class Group {
private final String groupName;
private List<String> commands;
public Group(String groupName) {
this.groupName = groupName.toLowerCase();
this.commands = !Reflection.isProxyServer() && Storage.BUNGEECORD ? new ArrayList<>() : (List<String>) Storage.STORAGE.getOrSet(this.groupName, new ArrayList<>());
}
public Group(String groupName, List<String> commands) {
this.groupName = groupName.toLowerCase();
this.commands = commands;
}
public void add(String command) {
command = command.toLowerCase();
if(contains(command)) return;
commands.add(command);
save();
if(!Reflection.isProxyServer() && Reflection.getMinor() >= 18) BukkitAntiTabListener.updateCommands();
}
public void remove(String command) {
command = command.toLowerCase();
if(!contains(command)) return;
commands.remove(command);
save();
if(!Reflection.isProxyServer() && Reflection.getMinor() >= 18) BukkitAntiTabListener.updateCommands();
}
public void clear() {
commands.clear();
save();
if(!Reflection.isProxyServer() && Reflection.getMinor() >= 18) BukkitAntiTabListener.updateCommands();
}
public boolean hasPermission(Object targetObj) {
return PermissionUtil.hasPermission(targetObj, "group." + groupName);
}
public void save() {
if(!Reflection.isProxyServer() && Storage.BUNGEECORD) return;
Storage.STORAGE.setAndSave(groupName, commands);
}
public boolean contains(String command) {
String[] split;
if(command.contains(" ")) {
split = command.split(" ");
if(split.length > 0) command = split[0];
command = command.split(" ")[0];
}
return commands.contains(command);
}
public List<String> getCommands() {
return commands;
}
public void setCommands(List<String> commands) {
this.commands = commands;
if(!Reflection.isProxyServer() && Reflection.getMinor() >= 18) BukkitAntiTabListener.updateCommands();
}
public String getGroupName() {
return groupName;
}
}
@@ -0,0 +1,90 @@
package de.rayzs.pat.utils.group;
import de.rayzs.pat.utils.*;
import java.util.*;
public class GroupManager {
private static final List<Group> GROUPS = new ArrayList<>();
public static void initialize() {
Storage.STORAGE.getKeys(true).stream().filter(key -> !key.equals("commands")).forEach(GroupManager::registerGroup);
}
public static boolean canAccessCommand(Object targetObj, String command) {
return GROUPS.stream().filter(group -> group.contains(command) && group.hasPermission(targetObj)
).findFirst().orElse(null) != null;
}
public static void setGroup(String groupName, List<String> commands) {
if(groupName.length() < 1) return;
Group group = registerAndGetGroup(groupName);
group.setCommands(commands);
}
public static Group registerAndGetGroup(String groupName) {
Group group = getGroupByName(groupName);
if(group != null) return group;
group = new Group(groupName);
GROUPS.add(group);
return group;
}
public static void registerGroup(String groupName) {
if(isGroupRegistered(groupName)) return;
GROUPS.add(new Group(groupName));
}
public static void addToGroup(String groupName, String command) {
Group group = getGroupByName(groupName);
if(groupName == null) return;
group.add(command);
}
public static void removeFromGroup(String groupName, String command) {
Group group = getGroupByName(groupName);
if(groupName == null) return;
group.remove(command);
}
public static void unregisterGroup(String groupName) {
Group group = getGroupByName(groupName);
if(group == null) return;
Storage.STORAGE.setAndSave(group.getGroupName(), null);
GROUPS.remove(group);
}
public static Group getGroupByName(String groupName) {
return GROUPS.stream().filter(group -> group.getGroupName().equals(groupName)).findFirst().orElse(null);
}
public static List<Group> getGroups() {
return GROUPS;
}
public static List<String> getGroupNames() {
List<String> result = new ArrayList<>();
GROUPS.forEach(group -> result.add(group.getGroupName()));
return result;
}
public static List<String> getGroupByNameOnlyIncludingCommand(String command) {
List<String> result = new ArrayList<>();
GROUPS.stream().filter(group -> group.contains(command)).forEach(group -> result.add(group.getGroupName()));
return result;
}
public static List<String> getGroupByNameNotIncludingCommand(String command) {
List<String> result = new ArrayList<>();
GROUPS.stream().filter(group -> !group.contains(command)).forEach(group -> result.add(group.getGroupName()));
return result;
}
public static void clearAllGroups() {
GROUPS.clear();
}
public static boolean isGroupRegistered(String groupName) {
return getGroupByName(groupName) != null;
}
}