Compare commits

...
101 Commits
Author SHA1 Message Date
rayzsyt c2634da6af Relocated proxy-commands load into separate function instead 2025-09-20 00:00:07 +02:00
rayzsyt bf04109e91 Added delayed reload of proxy-commands 2025-09-19 23:59:03 +02:00
rayzsyt ebc46247ad Fixed wrong display of missing parts after plugin-reload 2025-09-14 19:35:54 +02:00
rayzsyt bac1361f98 Removed unnecessary part 2025-09-14 19:26:41 +02:00
rayzsyt b26b1eacba Minor change to missing-parts format 2025-09-14 19:21:57 +02:00
rayzsyt 367357821e Minor change 2025-09-14 19:21:29 +02:00
rayzsyt 030154a135 Improved tutorial 2025-09-14 19:05:18 +02:00
rayzsyt b0bb78acdd Add BaseCommandCaseSensitive option 2025-09-14 18:50:58 +02:00
rayzsyt f98aafa8d1 Add BaseCommandCaseSensitive option 2025-09-14 18:50:54 +02:00
rayzsyt 805a041474 Remove lowercasing the commands 2025-09-14 18:50:16 +02:00
rayzsyt 3f5a0ae4a0 Update version name 2025-09-14 18:26:01 +02:00
rayzsyt 27caf727de Added Software-API info 2025-09-14 18:15:07 +02:00
rayzsyt 31a7d9bc9f Shorten Folia-Check 2025-09-14 18:09:02 +02:00
rayzsyt 3eaf2549e8 Integrated toggleInjection method 2025-09-14 18:07:15 +02:00
rayzsyt 6f0d290d0d Add toggleInjection method 2025-09-14 18:07:08 +02:00
rayzsyt a03da1bbd3 Experimental removal for unnecessary copy-operation 2025-09-14 17:42:39 +02:00
rayzsyt 35d6bd9ead Avoided modifying an iterating list 2025-09-14 17:42:23 +02:00
rayzsyt 97e7b712c7 Added try-catch to identify errors more precise 2025-09-14 17:41:48 +02:00
rayzsyt fcdcb8fa1c Small adjustment 2025-09-13 19:10:27 +02:00
rayzsyt 71b64d74e6 Improve check 2025-09-13 19:09:12 +02:00
rayzsyt bd411e3239 Test to avoid ArrayOutOfBounds issue 2025-09-13 18:24:05 +02:00
rayzsyt 91ce9326b2 Test to avoid ArrayOutOfBounds issue 2025-09-13 18:17:20 +02:00
rayzsyt 9711af2ff4 Removed unnecessary backend-only information 2025-09-05 02:44:25 +02:00
rayzsyt dabf1ca089 Add plugins information 2025-09-05 02:44:04 +02:00
rayzsyt f43c4f7680 Changed log priority 2025-08-29 15:22:01 +02:00
rayzsyt 28ecc7c92d Simplified function due to removal of debug logger 2025-08-29 15:21:35 +02:00
rayzsyt b36428b4ab Added info-method & fixed group-commands issue 2025-08-29 15:21:14 +02:00
rayzsyt 21d219ca53 Changed post-debug function 2025-08-29 15:20:47 +02:00
rayzsyt 497ea897d3 Removed debug logger 2025-08-29 15:20:12 +02:00
rayzsyt 35c4908936 Fix Blacklist/Whitelist issue 2025-08-29 15:19:58 +02:00
rayzsyt 091eb9ae8a Remove debug logger 2025-08-29 15:19:39 +02:00
rayzsyt 445a5d37c3 Remove debug logs 2025-08-29 15:19:13 +02:00
rayzsyt e6b8a9383e Update version name 2025-08-29 15:15:32 +02:00
rayzsyt 66b350eb5e Fix minor bug 2025-08-24 15:12:08 +02:00
rayzsyt da84e1164a Fix minor bug 2025-08-24 15:08:45 +02:00
rayzsyt cde86d46c3 Remove unnecessary Message-Formatting 2025-08-24 15:07:55 +02:00
rayzsyt 607ee2a6c8 Additional group-update check 2025-08-23 16:58:40 +02:00
rayzsyt 6219c7ce9a Add getSenderFromUUID method 2025-08-23 16:57:14 +02:00
rayzsyt 098035d280 Fix new groups not getting set 2025-08-23 16:56:56 +02:00
rayzsyt 111b1275c4 Fix logic (I gave every player perms to all groups ;-;) 2025-08-23 16:42:32 +02:00
rayzsyt d6119a41fb Remove unnecessary function calls 2025-08-23 14:34:36 +02:00
rayzsyt 095dfde3bb Change approach of scanning the list 2025-08-23 14:33:25 +02:00
rayzsyt 3bc56bc934 Change version 2025-08-22 18:15:12 +02:00
rayzsyt 14ecc52cda Improve player-groups storaging 2025-08-22 18:09:02 +02:00
rayzsyt 464355c91c Delayed when filteredCommands list is being set to when it's completed 2025-08-22 06:24:37 +02:00
rayzsyt 82e704eaf7 Readded native command handling 2025-08-21 23:33:08 +02:00
rayzsyt 54284a0543 Removed debug logger 2025-08-21 23:32:55 +02:00
rayzsyt 2cf07382df Update version name 2025-08-21 23:32:40 +02:00
rayzsyt 1de01ac745 Fixed Permission-Recognition issue (Without LuckPerms) 2025-08-19 22:45:01 +02:00
rayzsyt 66fce9fb50 Add 2025-08-19 20:49:08 +02:00
rayzsyt 017500fb5a Integrated LimitedList List 2025-08-19 20:49:03 +02:00
rayzsyt ddd8025fe5 Integrated Negation 2025-08-18 18:52:34 +02:00
rayzsyt f27bc065ba Ignore Negation 2025-08-18 18:52:18 +02:00
rayzsyt 9db3819866 Small method replacement 2025-08-18 18:51:55 +02:00
rayzsyt 8a5470dc68 Added Negation Operator (!) 2025-08-18 18:51:41 +02:00
rayzsyt 159f1b5938 Allows uppercase exceptions 2025-08-18 18:49:56 +02:00
rayzsyt 89fc1ef8ee Add (-_) operator 2025-08-17 18:38:12 +02:00
rayzsyt f249f77cfa Updated version 2025-08-17 18:37:59 +02:00
rayzsyt fad7525101 Removed unused import 2025-08-13 20:55:19 +02:00
rayzsyt 8dc3583ec7 Added delayed permission check if there's no LuckPerms installed 2025-08-13 20:54:40 +02:00
rayzsyt 2936faab56 Improved Logic 2025-08-13 20:52:45 +02:00
rayzsyt 637b7a263a Improved Update Command 2025-08-13 20:51:52 +02:00
rayzsyt be26033dfe Updated version name 2025-08-13 20:51:03 +02:00
rayzsyt 4bc7a7f292 Updated version name 2025-08-13 20:50:56 +02:00
rayzsyt 9b6a9061bc Fixed StackOverFlow Exploit 2025-08-13 20:50:46 +02:00
rayzsyt 6358358078 Added m, k and b to number criteria 2025-08-09 01:35:38 +02:00
rayzsyt 4c4224eb09 Update version name 2025-08-09 01:35:16 +02:00
rayzsyt 9100db600e Fixed removal of commands if "spaced" command was included 2025-08-08 17:49:12 +02:00
rayzsyt 263e3e6896 Removed unnecessary boolean 2025-08-08 04:34:42 +02:00
rayzsyt 26f326668f Fixed commands-update issue when reloading 2025-08-08 04:33:17 +02:00
rayzsyt 74e26a05f3 Update version name 2025-08-08 04:32:58 +02:00
rayzsyt 36145b1ee7 Update version name 2025-08-07 18:26:43 +02:00
rayzsyt 5f457c6e4a Fixed wrong display of blocked command in chat 2025-08-07 18:26:00 +02:00
rayzsyt 65dc540577 Improved performance of getAllCommands method 2025-08-07 01:59:32 +02:00
rayzsyt c338e29ec4 Changed method call 2025-08-07 01:59:08 +02:00
rayzsyt c253f6684b Small refactoring 2025-08-07 01:58:56 +02:00
rayzsyt aa740ffabf Fixed potential Folia incompatibility 2025-08-07 01:58:38 +02:00
rayzsyt e9ffe83a93 Integrated new methods from Loader 2025-08-07 01:58:19 +02:00
rayzsyt c83e83bb06 Integrated new method from Loader 2025-08-07 01:58:04 +02:00
rayzsyt b3c2e014c1 Add new methods 2025-08-07 01:57:54 +02:00
rayzsyt 6631da42e1 Fixed BLACKLIST mode issues 2025-08-07 01:57:44 +02:00
rayzsyt ac5233582f Change version name & integrated new default methods 2025-08-07 01:57:18 +02:00
rayzsyt 32a1f4351a Change version name 2025-08-07 01:57:01 +02:00
rayzsyt 2ff88eeb03 Fixed 1.8.8 incompatibility 2025-08-04 21:44:52 +02:00
rayzsyt 62b505450a Update version name 2025-08-04 21:44:11 +02:00
rayzsyt f7fd9dd42a Update version name 2025-08-04 18:31:55 +02:00
rayzsyt acd8e9291a Fix unnecessary offline-player cache spam 2025-08-02 16:20:17 +02:00
rayzsyt 50c80fc708 Change version name 2025-08-02 16:19:47 +02:00
rayzsyt bb02672085 Apply %args[.-.]% for in-game messages as well 2025-07-31 03:17:43 +02:00
rayzsyt f2e7efeaa6 Fix 0 commands 2025-07-31 03:04:39 +02:00
rayzsyt aa0863e726 Fix missing notification on /pl or /ver 2025-07-30 22:16:32 +02:00
rayzsyt 71cec6933f Add setDoesNotify function 2025-07-30 22:16:03 +02:00
rayzsyt c2d407cd62 Improved Update-Notifier 2025-07-30 22:15:54 +02:00
rayzsyt 61adaa19db Improved notification dedicator 2025-07-30 20:53:55 +02:00
rayzsyt 4c1cc0683d Add exceptional version names 2025-07-30 20:53:35 +02:00
rayzsyt ce3b42af38 Improved VersionComparer 2025-07-30 19:46:21 +02:00
rayzsyt 61c204ade0 Improved replaceArgsVariables Function 2025-07-30 17:18:34 +02:00
rayzsyt e13fae6e67 Removed Skript 2025-07-30 05:23:36 +02:00
rayzsyt 31e4c3caa4 Added variable examples for %args[.-.]% 2025-07-30 05:21:52 +02:00
rayzsyt bccb77667d Added variable %args[from-to]% 2025-07-30 05:18:25 +02:00
rayzsyt 4ab0791740 Updated version name 2025-07-30 05:18:04 +02:00
71 changed files with 1389 additions and 737 deletions

No files matched your search

+1 -16
View File
@@ -6,7 +6,7 @@
<groupId>de.rayzs.pat</groupId>
<artifactId>ProAntiTab</artifactId>
<version>2.0.4</version>
<version>2.0.16</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
@@ -72,25 +72,10 @@
<url>https://repo.william278.net/papiproxybridge</url>
</repository>
<repository>
<id>skript-releases</id>
<name>Skript Repository</name>
<url>https://repo.skriptlang.org/releases</url>
</repository>
</repositories>
<dependencies>
<!--
<dependency>
<groupId>org.skriptlang</groupId>
<artifactId>Skript</artifactId>
<version>2.10.1</version>
<scope>provided</scope>
</dependency>
!-->
<dependency>
<groupId>dev.folia</groupId>
<artifactId>folia-api</artifactId>
@@ -10,8 +10,8 @@ public class PATEventHandler {
private static List<PATEvent> EVENTS = new ArrayList<>();
public static ExecuteCommandEvent callExecuteCommandEvents(Object senderObj, String command, boolean blocked) {
ExecuteCommandEvent event = EmptyEvent.createEmptyExecuteCommandEvent(senderObj, command, blocked);
public static ExecuteCommandEvent callExecuteCommandEvents(Object senderObj, String command, boolean blocked, boolean notify) {
ExecuteCommandEvent event = EmptyEvent.createEmptyExecuteCommandEvent(senderObj, command, blocked, notify);
for (PATEvent patEvent : EVENTS) {
if(patEvent instanceof ExecuteCommandEvent) {
@@ -169,8 +169,8 @@ public class PATEventHandler {
};
}
public static ExecuteCommandEvent createEmptyExecuteCommandEvent(Object senderObj, String command, boolean blocked) {
return new ExecuteCommandEvent(senderObj, command, blocked) {
public static ExecuteCommandEvent createEmptyExecuteCommandEvent(Object senderObj, String command, boolean blocked, boolean notify) {
return new ExecuteCommandEvent(senderObj, command, blocked, notify) {
@Override
public void handle(ExecuteCommandEvent event) {
@@ -5,18 +5,24 @@ import de.rayzs.pat.api.event.PATEvent;
public abstract class ExecuteCommandEvent extends PATEvent<ExecuteCommandEvent> {
private final String command;
private boolean blocked;
private boolean blocked, notify;
public ExecuteCommandEvent() {
super(null);
this.blocked = false;
this.notify = false;
this.command = null;
}
public ExecuteCommandEvent(Object senderObj, String command, boolean blocked) {
public ExecuteCommandEvent(Object senderObj, String command, boolean blocked, boolean notify) {
super(senderObj);
this.blocked = blocked;
this.command = command;
this.notify = notify;
}
public void setDoesNotify(boolean notify) {
this.notify = notify;
}
public String getCommand() {
@@ -27,6 +33,10 @@ public abstract class ExecuteCommandEvent extends PATEvent<ExecuteCommandEvent>
return blocked;
}
public boolean doesNotify() {
return notify;
}
public void setBlocked(boolean blocked) {
this.blocked = blocked;
}
@@ -47,8 +47,8 @@ public class BukkitPacketAnalyzer {
try {
Channel channel = Reflection.getPlayerChannel(player);
if (channel == null) {
Logger.warning("Failed to inject " + player.getName() + "! Channel is null.");
return false;
}
@@ -57,8 +57,22 @@ public class BukkitPacketAnalyzer {
channel.pipeline().addBefore(BukkitPacketAnalyzer.PIPELINE_NAME, BukkitPacketAnalyzer.HANDLER_NAME, new PacketDecoder(player));
BukkitPacketAnalyzer.INJECTED_PLAYERS.put(player.getUniqueId(), channel);
} catch (Throwable throwable) {
throwable.printStackTrace();
} catch (IndexOutOfBoundsException indexOutOfBoundsException) {
Reflection.toggleInjectionMethod();
Logger.info("Injection failed. Switching to secondary injection method.");
boolean success = inject(player);
if (success) {
Logger.info("Secondary injection method was successful.");
} else {
Logger.warning("Secondary injection method failed!");
}
return success;
} catch (Exception exception) {
exception.printStackTrace();
return false;
}
@@ -47,9 +47,13 @@ public class BungeePacketAnalyzer {
private static Class<?> channelWrapperClass, serverConnectionClass;
private static final List<String> PROXY_COMMANDS;
private static List<String> PROXY_COMMANDS;
static {
loadProxyCommands();
}
public static void loadProxyCommands() {
PROXY_COMMANDS = ProxyServer.getInstance().getPluginManager().getCommands().stream().map(entry -> {
String key = entry.getKey();
return key.startsWith("/") ? key.substring(1) : key;
@@ -146,7 +150,7 @@ public class BungeePacketAnalyzer {
CommandsCache commandsCache = cache.get(serverName);
List<String> commandsAsString = new ArrayList<String>(PROXY_COMMANDS);
List<String> commandsAsString = new ArrayList<>(PROXY_COMMANDS);
commandsAsString.addAll(helper.getChildrenNames());
commandsCache.handleCommands(commandsAsString, serverName);
@@ -163,14 +167,16 @@ public class BungeePacketAnalyzer {
if (commands.getRoot().getChild(command.getKey()) != null)
continue;
if (!command.getValue().hasPermission(player))
if (!command.getValue().hasPermission(player)) {
continue;
}
String commandName = command.getKey();
commandName = commandName.startsWith("/") ? commandName.substring(1) : commandName;
if (!playerCommands.contains(commandName))
if (!playerCommands.contains(commandName)) {
continue;
}
CommandNode dummy = createDummyCommandNode(command.getKey());
commands.getRoot().addChild(dummy);
@@ -213,7 +213,6 @@ public class VelocityPacketAnalyzer {
final String cursor = playerInput;
if (!cursor.startsWith("/") && spaces < 2 && player.getProtocolVersion().getProtocol() >= 754) {
Logger.debug("Player won't receive TabCompleteResponsePacket because the client protocol id is " + player.getProtocolVersion().getProtocol() + "! This doesn't makes sense, that's why.");
return;
}
@@ -4,6 +4,7 @@ import java.util.*;
import java.util.concurrent.TimeUnit;
import de.rayzs.pat.api.communication.Communicator;
import de.rayzs.pat.api.storage.config.settings.*;
import de.rayzs.pat.plugin.listeners.bukkit.BukkitAntiTabListener;
import de.rayzs.pat.plugin.logger.Logger;
import de.rayzs.pat.plugin.modules.SubArgsModule;
@@ -28,19 +29,6 @@ import de.rayzs.pat.api.storage.config.messages.ReloadSection;
import de.rayzs.pat.api.storage.config.messages.ServerListSection;
import de.rayzs.pat.api.storage.config.messages.StatsSection;
import de.rayzs.pat.api.storage.config.messages.UpdatePermissionsSection;
import de.rayzs.pat.api.storage.config.settings.AutoLowercaseCommandsSection;
import de.rayzs.pat.api.storage.config.settings.BlockNamespaceCommandsSection;
import de.rayzs.pat.api.storage.config.settings.CancelCommandSection;
import de.rayzs.pat.api.storage.config.settings.CustomBrandSection;
import de.rayzs.pat.api.storage.config.settings.CustomPluginsSection;
import de.rayzs.pat.api.storage.config.settings.CustomProtocolPingSection;
import de.rayzs.pat.api.storage.config.settings.CustomUnknownCommandSection;
import de.rayzs.pat.api.storage.config.settings.CustomVersionSection;
import de.rayzs.pat.api.storage.config.settings.DisableSyncSection;
import de.rayzs.pat.api.storage.config.settings.HandleThroughProxySection;
import de.rayzs.pat.api.storage.config.settings.PatchExploitSection;
import de.rayzs.pat.api.storage.config.settings.TurnBlacklistToWhitelistSection;
import de.rayzs.pat.api.storage.config.settings.UpdateSection;
import de.rayzs.pat.api.storage.placeholders.commands.general.ListCommandsPlaceholder;
import de.rayzs.pat.api.storage.placeholders.commands.general.ListReversedCommandsPlaceholder;
import de.rayzs.pat.api.storage.placeholders.commands.general.ListSizeCommandsPlaceholder;
@@ -204,6 +192,8 @@ public class Storage {
} else {
Storage.Blacklist.Experimental.forceCacheReset();
if (isVelocity) {
List<UUID> playerIds = Storage.getLoader().getPlayerIds();
@@ -300,6 +290,7 @@ public class Storage {
public static CustomProtocolPingSection CUSTOM_PROTOCOL_PING = new CustomProtocolPingSection();
public static CustomUnknownCommandSection CUSTOM_UNKNOWN_COMMAND = new CustomUnknownCommandSection();
public static TurnBlacklistToWhitelistSection TURN_BLACKLIST_TO_WHITELIST = new TurnBlacklistToWhitelistSection();
public static BaseCommandCaseSensitiveSection BASE_COMMAND_CASE_SENSITIVE = new BaseCommandCaseSensitiveSection();
public static UpdateSection UPDATE = new UpdateSection();
public static void initialize() {}
@@ -384,6 +375,19 @@ public class Storage {
public static class Blacklist {
public static class Experimental {
public static void forceCacheReset() {
for (Object o : CACHED_SERVER_BLACKLIST.getCache().asMap().keySet()) {
String s = (String) o;
clearServerBlacklists(s);
loadCachedServerBlacklists(s);
}
}
}
public enum BlockType {
CHAT("[CMD]"),
TAB("[TAB]"),
@@ -428,14 +432,9 @@ public class Storage {
BLACKLIST.getConfig().getKeys("global.servers", true).forEach(key -> {
GeneralBlacklist blacklist = BlacklistCreator.createGeneralBlacklist(key);
blacklist.load();
SERVER_BLACKLISTS.put(key, blacklist);
});
loadAllCachedServerBlacklists();
}
private static void loadAllCachedServerBlacklists() {
getServers().forEach(Blacklist::loadCachedServerBlacklists);
}
@@ -443,9 +442,7 @@ public class Storage {
List<GeneralBlacklist> blacklists = SERVER_BLACKLISTS.entrySet().stream()
.filter(entry ->
isServer(entry.getKey(), server)
).map(entry ->
entry.getValue()
).toList();
).map(Map.Entry::getValue).toList();
CACHED_SERVER_BLACKLIST.put(server, blacklists);
}
@@ -547,10 +544,25 @@ public class Storage {
}
public static boolean isBlocked(String command, BlockType type, String server) {
BlockType negation = BlockType.NEGATE;
String negatedCommand = negation + command;
boolean listed = isListed(command, type, server),
negatedListed = isListed(negatedCommand, type, server),
turn = ConfigSections.Settings.TURN_BLACKLIST_TO_WHITELIST.ENABLED;
return !(listed && turn);
if (!turn && negatedListed) {
listed = !listed;
}
if (turn) {
return !listed;
} else {
return listed;
}
}
private static boolean isListed(String unmodifiedCommand, BlockType type, String server) {
@@ -560,18 +572,17 @@ public class Storage {
boolean turn = Storage.ConfigSections.Settings.TURN_BLACKLIST_TO_WHITELIST.ENABLED;
boolean listed = false;
if (type == BlockType.NEGATE)
turn = !turn;
String command = type.toString() + unmodifiedCommand;
if (server == null || !isIgnoredServer(server))
if (server == null || !isIgnoredServer(server)) {
listed = BLACKLIST.isListed(command, !turn);
}
if (server == null) {
if (!listed && type != BlockType.BOTH)
if (!listed && type != BlockType.BOTH) {
return isListed(unmodifiedCommand, BlockType.BOTH, null);
}
return listed;
}
@@ -581,7 +592,7 @@ public class Storage {
blacklists.add(BLACKLIST);
for (GeneralBlacklist blacklist : blacklists) {
if (listed && turn) {
if (listed/* && turn*/) {
break;
}
@@ -1,6 +1,5 @@
package de.rayzs.pat.api.storage.config.settings;
import de.rayzs.pat.api.storage.Storage;
import de.rayzs.pat.api.storage.storages.ConfigStorage;
import de.rayzs.pat.utils.Reflection;
import de.rayzs.pat.utils.StringUtils;
@@ -0,0 +1,22 @@
package de.rayzs.pat.api.storage.config.settings;
import de.rayzs.pat.api.storage.storages.ConfigStorage;
import de.rayzs.pat.utils.configuration.helper.ConfigSectionHelper;
import de.rayzs.pat.utils.configuration.helper.MultipleMessagesHelper;
import java.util.Collections;
public class BaseCommandCaseSensitiveSection extends ConfigStorage {
public boolean ENABLED;
public BaseCommandCaseSensitiveSection() {
super("base-command-case-sensitive");
}
@Override
public void load() {
super.load();
ENABLED = new ConfigSectionHelper<Boolean>(this, null, true).getOrSet();
}
}
@@ -20,27 +20,37 @@ public class BlacklistStorage extends StorageTemplate implements Serializable {
return isListed(command, !Storage.ConfigSections.Settings.TURN_BLACKLIST_TO_WHITELIST.ENABLED);
}
public boolean isListed(String command, boolean ignoreCollons) {
if(commands == null) {
public boolean isListed(String command, boolean ignoreColons) {
final boolean caseSensitive = Storage.ConfigSections.Settings.BASE_COMMAND_CASE_SENSITIVE.ENABLED;
if (commands == null || command.isEmpty()) {
return false;
}
if (commands.contains("*"))
if (!isNegated(command) && commands.contains("*")) {
return true;
}
for (String listedCommand : commands) {
if(listedCommand == null)
if (listedCommand == null)
continue;
if (ignoreCollons) {
if (ignoreColons) {
command = StringUtils.getFirstArg(command);
if (command.contains(":"))
command = command.substring(command.indexOf(':'));
}
if (StringUtils.getFirstArg(listedCommand).equalsIgnoreCase(StringUtils.getFirstArg(command)))
return true;
if (caseSensitive) {
if (StringUtils.getFirstArg(listedCommand).equals(StringUtils.getFirstArg(command))) {
return true;
}
} else {
if (StringUtils.getFirstArg(listedCommand).equalsIgnoreCase(StringUtils.getFirstArg(command))) {
return true;
}
}
}
return false;
@@ -81,4 +91,17 @@ public class BlacklistStorage extends StorageTemplate implements Serializable {
getConfig().reload();
commands = (ArrayList<String>) getConfig().getOrSet(getNavigatePath(), commands);
}
private boolean isNegated(String command) {
if (command.isEmpty()) {
return false;
}
boolean negated = command.charAt(0) == '!';
if (!negated && command.length() > 5)
negated = command.charAt(5) == '!';
return negated;
}
}
@@ -35,12 +35,17 @@ import java.util.*;
public class BukkitLoader extends JavaPlugin implements PluginLoader {
private static List<String> commands = new ArrayList<>(), allowedCommands = new ArrayList<>();
private static Plugin plugin;
private static java.util.logging.Logger logger;
private static boolean loaded = false, checkUpdate = false, suggestions = false;
private static boolean loaded = false, suggestions = false;
private static Map<String, Command> commandsMap = null;
private PATSchedulerTask updaterTask;
private final List<String> offlinePlayerNames = new ArrayList<>();
private long lastCommandsLoad = -1;
@Override
public void onLoad() {
Configurator.createResourcedFile("files\\bukkit-config.yml", "config.yml", false);
@@ -54,6 +59,10 @@ public class BukkitLoader extends JavaPlugin implements PluginLoader {
plugin = this;
logger = getLogger();
for (OfflinePlayer offlinePlayerName : Bukkit.getOfflinePlayers()) {
offlinePlayerNames.add(offlinePlayerName.getName());
}
loadCommandMap();
CommandProcess.initialize();
@@ -61,7 +70,7 @@ public class BukkitLoader extends JavaPlugin implements PluginLoader {
ConfigUpdater.initialize();
Storage.initialize(this, getDescription().getVersion());
VersionComparer.setCurrentVersion(Storage.CURRENT_VERSION);
VersionComparer.get().setCurrentVersion(Storage.CURRENT_VERSION);
Storage.loadAll(true);
@@ -104,12 +113,15 @@ public class BukkitLoader extends JavaPlugin implements PluginLoader {
if (getServer().getPluginManager().getPlugin("ViaVersion") != null)
ViaVersionAdapter.initialize();
if (Storage.USE_SIMPLECLOUD)
if (Storage.USE_SIMPLECLOUD) {
Logger.warning("Detected SimpleCloud. Therefore, MiniMessages are disabled!");
}
ConfigUpdater.broadcastMissingParts();
ActionHandler.initialize();
SubArgsModule.initialize();
PATScheduler.createScheduler(this::loadAllCommands);
}
@Override
@@ -128,6 +140,21 @@ public class BukkitLoader extends JavaPlugin implements PluginLoader {
}
}
@Override
public void handleReload() {
loadAllCommands();
}
@Override
public boolean doesCommandExist(String command) {
if (commandsMap == null)
return false;
loadAllCommands();
return getAllCommands().contains(command);
}
@Override
public Object getConsoleSender() {
return Bukkit.getConsoleSender();
@@ -158,7 +185,7 @@ public class BukkitLoader extends JavaPlugin implements PluginLoader {
@Override
public boolean doesPlayerExist(String playerName) {
return getOfflinePlayerNames().contains(playerName);
return isPlayerOnline(playerName) || ArrayUtils.containsIgnoreCase(getPlayerNames(), playerName);
}
@Override
@@ -188,15 +215,14 @@ public class BukkitLoader extends JavaPlugin implements PluginLoader {
@Override
public List<String> getOfflinePlayerNames() {
return new ArrayList<>(List.of(Bukkit.getOfflinePlayers())).stream().map(OfflinePlayer::getName).toList();
return offlinePlayerNames;
}
@Override
public List<String> getPlayerNames() {
List<String> playerNames = new ArrayList<>();
List<String> playerNames = new ArrayList<>(offlinePlayerNames);
playerNames.addAll(getOnlinePlayerNames());
playerNames.addAll(getOfflinePlayerNames());
return playerNames;
}
@@ -219,41 +245,13 @@ public class BukkitLoader extends JavaPlugin implements PluginLoader {
}
public void startUpdaterTask() {
if (!Storage.ConfigSections.Settings.UPDATE.ENABLED) return;
if (!Storage.ConfigSections.Settings.UPDATE.ENABLED)
return;
updaterTask = PATScheduler.createAsyncScheduler(() -> {
String result = new ConnectionBuilder().setUrl("https://www.rayzs.de/proantitab/api/version.php")
.setProperties("ProAntiTab", "4654").connect().getResponse();
if (result == null)
result = "/";
if (!result.equals("/")) {
Storage.NEWER_VERSION = result;
VersionComparer.setNewestVersion(Storage.NEWER_VERSION);
if (VersionComparer.isDeveloperVersion()) {
updaterTask.cancelTask();
Logger.info("§8[§fPAT | Bukkit§8] §7Please be aware that you are currently using a §bdeveloper §7version of ProAntiTab. Bugs, errors and a lot of debug messages might be included.");
} else if (!checkUpdate && (VersionComparer.isNewest() || VersionComparer.isUnreleased())) {
updaterTask.cancelTask();
checkUpdate = true;
if (VersionComparer.isUnreleased()) {
Logger.info("§8[§fPAT | Bukkit§8] §7Please be aware that you are currently using an §eunreleased §7version of ProAntiTab.");
return;
}
Storage.ConfigSections.Settings.UPDATE.UPDATED.getLines().forEach(Logger::warning);
} else if (VersionComparer.isOutdated()) {
updaterTask.cancelTask();
Storage.OUTDATED = true;
Storage.ConfigSections.Settings.UPDATE.OUTDATED.getLines().forEach(Logger::warning);
}
} else {
Logger.warning("Failed to connect to plugin page! Version comparison cannot be made. (No internet?)");
}
if (VersionComparer.get().computeComparison())
updaterTask.cancelTask();
}, 20L, 20L * Storage.ConfigSections.Settings.UPDATE.PERIOD);
}
@@ -320,24 +318,31 @@ public class BukkitLoader extends JavaPlugin implements PluginLoader {
if (!loaded)
loaded = true;
if (Reflection.getMinor() >= 13) {
if (updatedList) {
BukkitAntiTabListener.updateCommands();
Logger.debug("Force server to load all players tab-completion due to received sync!");
}
if (Reflection.getMinor() >= 13 && updatedList) {
BukkitAntiTabListener.updateCommands();
}
PATEventHandler.callReceiveSyncEvents(packetBundle);
}
public static boolean doesCommandExist(String command, boolean replace) {
if (commandsMap == null)
return false;
public static List<String> getAllCommands() {
return new ArrayList<>(commands);
}
if (replace) command = StringUtils.replaceFirst(command, "/", "");
return getAllCommands().contains(command);
public static List<String> getAllowedCommands() {
return new ArrayList<>(allowedCommands);
}
@Override
public List<String> getPluginNames() {
List<String> pluginNames = new ArrayList<>();
for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) {
PluginDescriptionFile description = plugin.getDescription();
pluginNames.add(description.getName() + " (" + description.getVersion() + ")");
}
return pluginNames;
}
private void loadCommandMap() {
@@ -348,45 +353,65 @@ public class BukkitLoader extends JavaPlugin implements PluginLoader {
SimpleCommandMap simpleCommandMap = (SimpleCommandMap) commandMapField.get(Bukkit.getPluginManager());
Field knownCommandsField = SimpleCommandMap.class.getDeclaredField("knownCommands");
knownCommandsField.setAccessible(true);
commandsMap = (Map<String, Command>)knownCommandsField.get(simpleCommandMap);
commandsMap = (Map<String, Command>) knownCommandsField.get(simpleCommandMap);
}
} catch (Throwable ignored) { }
if(commandsMap == null)
if (commandsMap == null) {
Logger.warning("Failed to get server commands!");
}
}
public static List<String> getNotBlockedCommands() {
List<String> commands = new ArrayList<>();
Bukkit.getHelpMap().getHelpTopics().stream()
.filter(topic -> !topic.getName().contains(":") && topic.getName().startsWith("/") && !Storage.Blacklist.getBlacklist().isListed(topic.getName().replaceFirst("/", "")))
.forEach(topic -> commands.add(topic.getName().replaceFirst("/", "")));
return commands;
}
private void loadAllCommands() {
public static List<String> getAllCommands() {
if (commandsMap == null) return getNotBlockedCommands();
if (lastCommandsLoad != -1 && System.currentTimeMillis() - lastCommandsLoad < 1000)
return;
List<String> result = new LinkedList<>();
for (String command : commandsMap.keySet()) if(!result.contains(command)) result.add(command);
List<String> result = new ArrayList<>();
if(Reflection.getMinor() == 20 && Reflection.getRelease() >= 5 || Reflection.getMinor() >= 21)
for (String s : commandsMap.keySet()) {
if (commandsMap.containsKey(s)) {
if (!commandsMap.get(s).getAliases().isEmpty()) {
for (String alias : commandsMap.get(s).getAliases()) {
if (!result.contains(alias)) result.add(alias);
}
if (commandsMap == null) {
result.addAll(
Bukkit.getHelpMap().getHelpTopics().stream()
.map(topic -> {
String name = topic.getName();
} else if (Bukkit.getServer().getCommandAliases().get(s) != null)
for (String alias : Bukkit.getServer().getCommandAliases().get(s))
if (!result.contains(alias)) result.add(alias);
}
if (name.startsWith("/"))
name = name.substring(1);
return name;
}).toList()
);
return;
}
commandsMap.entrySet().forEach(entry -> {
String key = entry.getKey();
Command command = entry.getValue();
result.add(key);
if (!command.getAliases().isEmpty()) {
result.addAll(command.getAliases());
}
});
boolean turn = Storage.ConfigSections.Settings.TURN_BLACKLIST_TO_WHITELIST.ENABLED;
List<String> allowedCommands = new ArrayList<>(result).stream().filter(command -> {
if (turn) {
return Storage.Blacklist.getBlacklist().isListed(command);
} else {
return !Storage.Blacklist.getBlacklist().isListed(command);
}
return result;
}
}).toList();
lastCommandsLoad = System.currentTimeMillis();
BukkitLoader.commands = result;
BukkitLoader.allowedCommands = allowedCommands;
}
public static boolean useSuggestions() {
return suggestions;
@@ -33,7 +33,6 @@ public class BungeeLoader extends Plugin implements PluginLoader {
private static Plugin plugin;
private static java.util.logging.Logger logger;
private static boolean checkUpdate = false;
private static final HashMap<String, CommandsCache> commandsCacheMap = new HashMap<>();
@Override
@@ -56,7 +55,7 @@ public class BungeeLoader extends Plugin implements PluginLoader {
Storage.USE_SIMPLECLOUD = Reflection.doesClassExist("eu.thesimplecloud.plugin.startup.CloudPlugin");
Storage.initialize(this, getDescription().getVersion());
VersionComparer.setCurrentVersion(Storage.CURRENT_VERSION);
VersionComparer.get().setCurrentVersion(Storage.CURRENT_VERSION);
Storage.loadAll(true);
@@ -98,6 +97,8 @@ public class BungeeLoader extends Plugin implements PluginLoader {
ConfigUpdater.broadcastMissingParts();
ActionHandler.initialize();
SubArgsModule.initialize();
ProxyServer.getInstance().getScheduler().schedule(this, BungeePacketAnalyzer::loadProxyCommands, 1, TimeUnit.SECONDS);
}
@Override
@@ -113,6 +114,16 @@ public class BungeeLoader extends Plugin implements PluginLoader {
}
}
@Override
public void handleReload() {
BungeePacketAnalyzer.loadProxyCommands();
}
@Override
public boolean doesCommandExist(String command) {
return false;
}
@Override
public Object getConsoleSender() {
return ProxyServer.getInstance().getConsole();
@@ -225,44 +236,27 @@ public class BungeeLoader extends Plugin implements PluginLoader {
return new ArrayList<>(ProxyServer.getInstance().getServers().keySet().stream().toList());
}
@Override
public List<String> getPluginNames() {
List<String> pluginNames = new ArrayList<>();
for (Plugin plugin : ProxyServer.getInstance().getPluginManager().getPlugins()) {
PluginDescription description = plugin.getDescription();
pluginNames.add(description.getName() + " (" + description.getVersion() + ")");
}
return pluginNames;
}
public void startUpdaterTask() {
if (!Storage.ConfigSections.Settings.UPDATE.ENABLED) return;
if (!Storage.ConfigSections.Settings.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 == null)
result = "/";
if (VersionComparer.get().computeComparison())
getProxy().getScheduler().cancel(updaterTask);
if (!result.equals("/")) {
Storage.NEWER_VERSION = result;
VersionComparer.setNewestVersion(Storage.NEWER_VERSION);
if(VersionComparer.isDeveloperVersion()) {
getProxy().getScheduler().cancel(updaterTask);
Logger.info("§8[§fPAT | Proxy§8] §7Please be aware that you are currently using a §bdeveloper §7version of ProAntiTab. Bugs, errors and a lot of debug messages might be included.");
} else if(!checkUpdate && (VersionComparer.isNewest() || VersionComparer.isUnreleased())) {
getProxy().getScheduler().cancel(updaterTask);
checkUpdate = true;
if(VersionComparer.isUnreleased()) {
Logger.info("§8[§fPAT | Proxy§8] §7Please be aware that you are currently using an §eunreleased §7version of ProAntiTab.");
return;
}
checkUpdate = true;
Storage.ConfigSections.Settings.UPDATE.UPDATED.getLines().forEach(Logger::warning);
} else if(VersionComparer.isOutdated()) {
Storage.OUTDATED = true;
Storage.ConfigSections.Settings.UPDATE.OUTDATED.getLines().forEach(Logger::warning);
}
} else {
Logger.warning("Failed to connect to plugin page! Version comparison cannot be made. (No internet?)");
}
}, 20L, Storage.ConfigSections.Settings.UPDATE.PERIOD, TimeUnit.MILLISECONDS);
}
@@ -8,6 +8,9 @@ import java.util.UUID;
public interface PluginLoader {
void handleReload();
boolean doesCommandExist(String command);
HashMap<String, CommandsCache> getCommandsCacheMap();
void updateCommandCache();
@@ -35,4 +38,6 @@ public interface PluginLoader {
List<String> getPlayerNames();
List<String> getOnlinePlayerNames();
List<String> getOfflinePlayerNames();
List<String> getPluginNames();
}
@@ -38,7 +38,7 @@ import java.util.*;
@Plugin(name = "ProAntiTab",
id = "proantitab",
version = "2.0.4",
version = "2.0.16",
authors = "Rayzs_YT",
description = "Hide more than just your plugins. Hide almost everything!",
url = "https://www.rayzs.de/products/proantitab/page",
@@ -58,7 +58,6 @@ public class VelocityLoader implements PluginLoader {
private ScheduledTask updaterTask;
private static final HashMap<String, CommandsCache> commandsCacheMap = new HashMap<>();
private static boolean checkUpdate = false;
@Inject
public VelocityLoader(ProxyServer server, org.slf4j.Logger logger, VelocityMetrics.Factory metricsFactory) {
@@ -85,7 +84,7 @@ public class VelocityLoader implements PluginLoader {
Storage.USE_SIMPLECLOUD = Reflection.doesClassExist("eu.thesimplecloud.plugin.startup.CloudPlugin");
Storage.initialize(this, pluginContainer.getDescription().getVersion().get());
VersionComparer.setCurrentVersion(Storage.CURRENT_VERSION);
VersionComparer.get().setCurrentVersion(Storage.CURRENT_VERSION);
Storage.loadAll(true);
MessageTranslator.initialize();
@@ -95,7 +94,7 @@ public class VelocityLoader implements PluginLoader {
metricsFactory.make(this, 21638);
server.getCommandManager().register("bpat", new VelocityCommand(), "bungeeproantitab");
//server.getEventManager().register(this, new VelocityBlockCommandListener(server));
server.getEventManager().register(this, new VelocityBlockCommandListener());
server.getEventManager().register(this, new VelocityAntiTabListener(server));
server.getEventManager().register(this, new VelocityConnectionListener(server, this));
server.getEventManager().register(this, new VelocityPingListener(server));
@@ -145,6 +144,14 @@ public class VelocityLoader implements PluginLoader {
}).delay(1, TimeUnit.SECONDS).schedule();
}
@Override
public void handleReload() {}
@Override
public boolean doesCommandExist(String command) {
return false;
}
@Override
public Object getConsoleSender() {
return server.getConsoleCommandSource();
@@ -267,63 +274,32 @@ public class VelocityLoader implements PluginLoader {
return new ArrayList<>(server.getAllServers().stream().map(registeredServer -> registeredServer.getServerInfo().getName()).toList());
}
@Override
public List<String> getPluginNames() {
List<String> pluginNames = new ArrayList<>();
for (PluginContainer plugin : server.getPluginManager().getPlugins()) {
PluginDescription description = plugin.getDescription();
String pluginName = description.getName().orElse("/");
String version = description.getVersion().orElse("/");
pluginNames.add(pluginName + " (" + version + ")");
}
return pluginNames;
}
public void startUpdaterTask() {
if (!Storage.ConfigSections.Settings.UPDATE.ENABLED) return;
updaterTask = server.getScheduler().buildTask(this, () -> {
String result = new ConnectionBuilder().setUrl("https://www.rayzs.de/proantitab/api/version.php")
.setProperties("ProAntiTab", "4654").connect().getResponse();
if (result == null)
result = "/";
if (VersionComparer.get().computeComparison())
updaterTask.cancel();
if (!result.equals("/")) {
Storage.NEWER_VERSION = result;
VersionComparer.setNewestVersion(Storage.NEWER_VERSION);
if (VersionComparer.isDeveloperVersion()) {
updaterTask.cancel();
MessageTranslator.send(server.getConsoleCommandSource(), "<dark_gray>[</dark_gray><white>PAT | Proxy</white><dark_gray>]</dark_gray> <gray>Please be aware that you are currently using a</gray> <aqua>developer</aqua> <gray>version of ProAntiTab. Bugs, errors and a lot of debug messages might be included.</gray>");
} else if (!checkUpdate && (VersionComparer.isNewest() || VersionComparer.isUnreleased())) {
updaterTask.cancel();
checkUpdate = true;
if (VersionComparer.isUnreleased()) {
MessageTranslator.send(server.getConsoleCommandSource(), "<dark_gray>[</dark_gray><white>PAT | Proxy</white><dark_gray>]</dark_gray> <gray>Please be aware that you are currently using an</gray> <yellow>unreleased</yellow> <gray>version of ProAntiTab.</gray>");
return;
}
checkUpdate = true;
MessageTranslator.send(server.getConsoleCommandSource(), Storage.ConfigSections.Settings.UPDATE.UPDATED.getLines());
} else if (VersionComparer.isOutdated()) {
Storage.OUTDATED = true;
MessageTranslator.send(server.getConsoleCommandSource(), Storage.ConfigSections.Settings.UPDATE.OUTDATED.getLines());
}
} else {
Logger.warning("Failed to connect to plugin page! Version comparison cannot be made. (No internet?)");
}
}).delay(1, TimeUnit.SECONDS).repeat(Storage.ConfigSections.Settings.UPDATE.PERIOD, TimeUnit.SECONDS).schedule();
}
public static String getServerNameByPlayerUUID(UUID uuid) {
Optional<Player> optPlayer = server.getPlayer(uuid);
if(!optPlayer.isPresent()) return null;
Player player = optPlayer.get();
Optional<ServerConnection> optServer = player.getCurrentServer();
if(!optServer.isPresent()) return null;
ServerConnection server = optServer.get();
if(server.getServerInfo() == null) return null;
return server.getServerInfo().getName();
}
public static ProxyServer getServer() {
return server;
}
@@ -5,15 +5,12 @@ import org.bukkit.event.player.PlayerCommandSendEvent;
import de.rayzs.pat.utils.permission.PermissionUtil;
import de.rayzs.pat.utils.adapter.ViaVersionAdapter;
import de.rayzs.pat.api.event.PATEventHandler;
import de.rayzs.pat.plugin.logger.Logger;
import de.rayzs.pat.api.storage.Storage;
import de.rayzs.pat.plugin.BukkitLoader;
import org.bukkit.entity.Player;
import de.rayzs.pat.utils.*;
import org.bukkit.event.*;
import org.bukkit.Bukkit;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.*;
public class BukkitAntiTabListener implements Listener {
@@ -27,13 +24,11 @@ public class BukkitAntiTabListener implements Listener {
String uuidSubstring = uuid.toString().substring(uuid.toString().length() - 5);
if (Storage.USE_VELOCITY || player.isOp()) {
Logger.debug("Doesn't even tried to create the commands list for player with uuid " + uuidSubstring + ". (Veloctiy? " + Storage.USE_VELOCITY + ". OP? " + player.isOp() + ")");
return;
}
if (!BukkitLoader.isLoaded()) {
event.getCommands().clear();
Logger.debug("Doesn't even tried to create the commands list for player with uuid " + uuidSubstring + ". (not loaded)");
return;
}
@@ -41,15 +36,13 @@ public class BukkitAntiTabListener implements Listener {
return;
if (event.getCommands().isEmpty()) {
Logger.debug("No available commands to filter! Ignoring rest of the code until at least one command is listed in there.");
return;
}
List<String> allCommands = getCommands();
List<String> allCommands = getCommands();
COMMANDS_CACHE.handleCommands(allCommands);
if (PermissionUtil.hasBypassPermission(player)) {
Logger.debug("Player with uuid " + uuidSubstring + " skipped the commands-list creation due to its permissions.");
return;
}
@@ -62,7 +55,6 @@ public class BukkitAntiTabListener implements Listener {
return;
event.getCommands().addAll(filteredSuggestionEvent.getSuggestions());
Logger.debug("Player with uuid " + uuidSubstring + " has a total of " + playerCommands.size() + " commands.");
}
public static List<String> getCommands() {
@@ -13,7 +13,6 @@ import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import de.rayzs.pat.api.event.PATEventHandler;
import de.rayzs.pat.api.event.events.ExecuteCommandEvent;
import de.rayzs.pat.api.storage.Storage;
import de.rayzs.pat.plugin.BukkitLoader;
import de.rayzs.pat.plugin.logger.Logger;
import de.rayzs.pat.utils.StringUtils;
import de.rayzs.pat.utils.message.MessageTranslator;
@@ -25,14 +24,20 @@ public class BukkitBlockCommandListener implements Listener {
public void onUnknownCommandRecognition(PlayerCommandPreprocessEvent event) {
Player player = event.getPlayer();
World world = player.getWorld();
String rawCommand = StringUtils.getFirstArg(event.getMessage()),
command = rawCommand.substring(1);
if (!Storage.ConfigSections.Settings.CUSTOM_UNKNOWN_COMMAND.ENABLED || event.isCancelled()) return;
if (PermissionUtil.hasBypassPermission(player)) return;
//if (BukkitLoader.doesCommandExist(command, false)) return;
if (Bukkit.getHelpMap().getHelpTopic(rawCommand) != null) return;
if (PermissionUtil.hasBypassPermission(player))
return;
if (Storage.getLoader().doesCommandExist(command))
return;
if (Bukkit.getHelpMap().getHelpTopic(rawCommand) != null)
return;
event.setCancelled(true);
MessageTranslator.send(player, Storage.ConfigSections.Settings.CUSTOM_UNKNOWN_COMMAND.MESSAGE, "%command%", command, "%world%", world.getName());
@@ -41,8 +46,9 @@ public class BukkitBlockCommandListener implements Listener {
@EventHandler (priority = EventPriority.LOWEST)
public void onPlayerCommandProcess(PlayerCommandPreprocessEvent event) {
Player player = event.getPlayer();
final String commandFirstArg = StringUtils.getFirstArg(event.getMessage());
if (Storage.ConfigSections.Settings.AUTO_LOWERCASE_COMMANDS.isCommand(StringUtils.getFirstArg(event.getMessage()))) {
if (Storage.ConfigSections.Settings.AUTO_LOWERCASE_COMMANDS.isCommand(commandFirstArg)) {
String command = event.getMessage();
if (command.contains(" ")) {
@@ -51,9 +57,11 @@ public class BukkitBlockCommandListener implements Listener {
command = String.join(" ", args);
} else command = command.toLowerCase();
player.chat(command);
event.setCancelled(true);
return;
if (!commandFirstArg.equals(command)) {
player.chat(command);
event.setCancelled(true);
return;
}
}
World world = player.getWorld();
@@ -65,10 +73,8 @@ public class BukkitBlockCommandListener implements Listener {
command = command.substring(1);
command = StringUtils.getFirstArg(command);
final String displayName = command;
command = StringUtils.replaceTriggers(command, "", "\\", "<", ">", "&");
command = command.toLowerCase();
final String displayName = StringUtils.replaceTriggers(command, "", "\\", "<", ">", "&");
//command = command.toLowerCase();
List<String> notificationMessage = MessageTranslator.replaceMessageList(
Storage.ConfigSections.Messages.NOTIFICATION.ALERT,
@@ -86,12 +92,17 @@ public class BukkitBlockCommandListener implements Listener {
return;
if (!Storage.Blacklist.canPlayerAccessChat(player, command)) {
ExecuteCommandEvent executeCommandEvent = PATEventHandler.callExecuteCommandEvents(player, event.getMessage(), true);
ExecuteCommandEvent executeCommandEvent = PATEventHandler.callExecuteCommandEvents(
player,
event.getMessage(),
true,
!Storage.ConfigSections.Settings.TURN_BLACKLIST_TO_WHITELIST.ENABLED
);
if (executeCommandEvent.isBlocked()) {
event.setCancelled(true);
if (Storage.ConfigSections.Settings.TURN_BLACKLIST_TO_WHITELIST.ENABLED)
if (!executeCommandEvent.doesNotify())
return;
if (Storage.SEND_CONSOLE_NOTIFICATION)
@@ -108,7 +119,7 @@ public class BukkitBlockCommandListener implements Listener {
return;
}
ExecuteCommandEvent executeCommandEvent = PATEventHandler.callExecuteCommandEvents(player, event.getMessage(), false);
ExecuteCommandEvent executeCommandEvent = PATEventHandler.callExecuteCommandEvents(player, event.getMessage(), false, false);
if (executeCommandEvent.isBlocked())
event.setCancelled(true);
}
@@ -5,14 +5,16 @@ import de.rayzs.pat.api.event.PATEventHandler;
import de.rayzs.pat.api.event.events.ServerPlayersChangeEvent;
import de.rayzs.pat.api.netty.bukkit.BukkitPacketAnalyzer;
import de.rayzs.pat.api.communication.BackendUpdater;
import de.rayzs.pat.plugin.logger.Logger;
import de.rayzs.pat.utils.message.MessageTranslator;
import de.rayzs.pat.utils.permission.PermissionUtil;
import de.rayzs.pat.api.storage.Storage;
import de.rayzs.pat.plugin.BukkitLoader;
import de.rayzs.pat.utils.scheduler.PATScheduler;
import de.rayzs.pat.utils.sender.CommandSender;
import de.rayzs.pat.utils.sender.CommandSenderHandler;
import org.bukkit.event.player.*;
import org.bukkit.entity.Player;
import org.bukkit.event.*;
import org.bukkit.Bukkit;
public class BukkitPlayerConnectionListener implements Listener {
@@ -21,19 +23,40 @@ public class BukkitPlayerConnectionListener implements Listener {
Player player = event.getPlayer();
PATEventHandler.callServerPlayersChangeEvents(player, ServerPlayersChangeEvent.Type.JOINED);
if(Storage.ConfigSections.Settings.HANDLE_THROUGH_PROXY.ENABLED)
if (Storage.ConfigSections.Settings.HANDLE_THROUGH_PROXY.ENABLED)
BackendUpdater.handle();
PermissionUtil.setPlayerPermissions(player.getUniqueId());
CustomServerBrand.preparePlayer(player);
if(CustomServerBrand.isEnabled())
if (CustomServerBrand.isEnabled())
CustomServerBrand.sendBrandToPlayer(player);
if(!BukkitPacketAnalyzer.inject(player)) player.kickPlayer("Failed to inject player!");
if (!Storage.USE_LUCKPERMS && !Storage.ConfigSections.Settings.HANDLE_THROUGH_PROXY.ENABLED) {
PATScheduler.createScheduler(() -> {
CommandSender sender = CommandSenderHandler.from(player);
assert sender != null;
PermissionUtil.reloadPermissions(sender);
BukkitAntiTabListener.handleTabCompletion(player.getUniqueId());
}, 20);
}
if (!BukkitPacketAnalyzer.inject(player)) {
PATScheduler.createScheduler(() -> {
if (player.isOnline()) {
if (!BukkitPacketAnalyzer.inject(player)) {
Logger.warning("Failed to inject into player! (" + player.getName() + ")" );
player.kickPlayer("Failed to inject player!");
}
}
}, 10);
}
if(Storage.OUTDATED && PermissionUtil.hasPermission(player, "joinupdate")) {
Bukkit.getScheduler().runTaskLater(BukkitLoader.getPlugin(), () -> {
PATScheduler.createScheduler(() -> {
if (player.isOnline()) {
MessageTranslator.send(player, Storage.ConfigSections.Settings.UPDATE.OUTDATED.getLines());
}
@@ -36,10 +36,9 @@ public class BungeeBlockCommandListener implements Listener {
command = command.startsWith("/") ? command.substring(1) : command;
command = StringUtils.getFirstArg(command);
final String displayCommand = command;
final String displayCommand = StringUtils.replaceTriggers(command, "", "\\", "<", ">", "&");
command = StringUtils.replaceTriggers(command, "", "\\", "<", ">", "&");
command = command.toLowerCase();
//command = command.toLowerCase();
List<String> notificationMessage = MessageTranslator.replaceMessageList(
Storage.ConfigSections.Messages.NOTIFICATION.ALERT,
@@ -51,12 +50,17 @@ public class BungeeBlockCommandListener implements Listener {
return;
if (!Storage.Blacklist.canPlayerAccessChat(player, command, serverName)) {
ExecuteCommandEvent executeCommandEvent = PATEventHandler.callExecuteCommandEvents(player, event.getMessage(), true);
ExecuteCommandEvent executeCommandEvent = PATEventHandler.callExecuteCommandEvents(
player,
event.getMessage(),
true,
!Storage.ConfigSections.Settings.TURN_BLACKLIST_TO_WHITELIST.ENABLED
);
if (executeCommandEvent.isBlocked()) {
event.setCancelled(true);
if (Storage.ConfigSections.Settings.TURN_BLACKLIST_TO_WHITELIST.ENABLED)
if (!executeCommandEvent.doesNotify())
return;
if (Storage.SEND_CONSOLE_NOTIFICATION)
@@ -76,7 +80,7 @@ public class BungeeBlockCommandListener implements Listener {
return;
}
ExecuteCommandEvent executeCommandEvent = PATEventHandler.callExecuteCommandEvents(player, event.getMessage(), false);
ExecuteCommandEvent executeCommandEvent = PATEventHandler.callExecuteCommandEvents(player, event.getMessage(), false, false);
if (executeCommandEvent.isBlocked())
event.setCancelled(true);
}
@@ -24,7 +24,7 @@ public class BungeePingListener implements Listener {
try {
max = proxyServer.getConfigurationAdapter().getListeners().iterator().next().getMaxPlayers();
} catch (Throwable throwable) {
Logger.debug("Failed to read max-players count for %max% placeholder! Using -1 as default value instead.");
Logger.warning("Failed to read max-players count for %max% placeholder! Using -1 as default value instead.");
}
ServerPing serverPing = event.getResponse();
@@ -43,46 +43,56 @@ public class VelocityAntiTabListener {
@Subscribe (order = PostOrder.LAST)
public void onPlayerAvailableCommands(PlayerAvailableCommandsEvent event) {
Player player = event.getPlayer();
try {
Player player = event.getPlayer();
if(event.getRootNode().getChildren().isEmpty() || !player.getCurrentServer().isPresent())
return;
if (event.getRootNode().getChildren().isEmpty() || !player.getCurrentServer().isPresent()) {
return;
}
String serverName = player.getCurrentServer().get().getServer().getServerInfo().getName();
String serverName = player.getCurrentServer().get().getServer().getServerInfo().getName();
Map<String, CommandsCache> cache = Storage.getLoader().getCommandsCacheMap();
Map<String, CommandsCache> cache = Storage.getLoader().getCommandsCacheMap();
if(!cache.containsKey(serverName))
cache.put(serverName, new CommandsCache());
if (!cache.containsKey(serverName)) {
cache.put(serverName, new CommandsCache());
}
CommandsCache commandsCache = cache.get(serverName);
CommandsCache commandsCache = cache.get(serverName);
List<String> commandsAsString = new ArrayList<>();
event.getRootNode().getChildren().stream().filter(command -> command != null && command.getName() != null).forEach(command -> commandsAsString.add(command.getName()));
commandsCache.handleCommands(commandsAsString, serverName);
List<String> commandsAsString = new ArrayList<>();
event.getRootNode().getChildren().stream().filter(command -> command != null && command.getName() != null).forEach(command -> commandsAsString.add(command.getName()));
commandsCache.handleCommands(commandsAsString, serverName);
if (PermissionUtil.hasBypassPermission(player))
return;
if (PermissionUtil.hasBypassPermission(player)) {
return;
}
final boolean newer = player.getProtocolVersion().getProtocol() > 340, argsChildrenExist = event.getRootNode().getChild("args") != null;
final List<String> playerCommands = commandsCache.getPlayerCommands(commandsAsString, player, player.getUniqueId(), serverName);
final boolean newer = player.getProtocolVersion().getProtocol() > 340, argsChildrenExist = event.getRootNode().getChild("args") != null;
final List<String> playerCommands = commandsCache.getPlayerCommands(commandsAsString, player, player.getUniqueId(), serverName);
if (event.getRootNode().getChildren().size() == 1
&& newer && argsChildrenExist
&& event.getRootNode().getChild("args").getChildren().isEmpty()) {
return;
if (event.getRootNode().getChildren().size() == 1
&& newer && argsChildrenExist
&& event.getRootNode().getChild("args").getChildren().isEmpty()) {
return;
}
if (event.getRootNode().getChildren().size() == 1 && newer && argsChildrenExist) {
return;
}
event.getRootNode().getChildren().removeIf(command -> {
if (command == null || command.getName() == null)
return true;
if (command.getName().equals("args"))
return false;
return !playerCommands.contains(command.getName());
});
} catch (Exception exception) {
System.out.println("An error occurred while processing commands in PAT: " + exception.getMessage());
exception.printStackTrace();
}
if(event.getRootNode().getChildren().size() == 1 && newer && argsChildrenExist) return;
event.getRootNode().getChildren().removeIf(command -> {
if (command == null || command.getName() == null)
return true;
if (command.getName().equals("args"))
return false;
return !playerCommands.contains(command.getName());
});
}
}
@@ -1,5 +1,6 @@
package de.rayzs.pat.plugin.listeners.velocity;
import com.velocitypowered.api.event.Subscribe;
import com.velocitypowered.api.event.command.CommandExecuteEvent;
import com.velocitypowered.api.command.CommandSource;
import de.rayzs.pat.api.event.events.ExecuteCommandEvent;
@@ -13,6 +14,11 @@ import java.util.List;
public class VelocityBlockCommandListener {
@Subscribe
public void onCommandExecute(CommandExecuteEvent event) {
handleCommand(event);
}
public static CommandExecuteEvent handleCommand(Player player, String command) {
return handleCommand(new CommandExecuteEvent(player, command));
}
@@ -39,10 +45,9 @@ public class VelocityBlockCommandListener {
if (bypassPermission)
return event;
final String displayCommand = command;
final String displayCommand = StringUtils.replaceTriggers(command, "", "\\", "<", ">", "&");
command = StringUtils.replaceTriggers(command, "", "\\", "<", ">", "&");
command = command.toLowerCase();
//command = command.toLowerCase();
List<String> notificationMessage = MessageTranslator.replaceMessageList(
@@ -56,12 +61,16 @@ public class VelocityBlockCommandListener {
return event;
if (!Storage.Blacklist.canPlayerAccessChat(player, command, serverName)) {
ExecuteCommandEvent executeCommandEvent = PATEventHandler.callExecuteCommandEvents(player, event.getCommand(), true);
ExecuteCommandEvent executeCommandEvent = PATEventHandler.callExecuteCommandEvents(
player,
event.getCommand(),
true,
!Storage.ConfigSections.Settings.TURN_BLACKLIST_TO_WHITELIST.ENABLED);
if (executeCommandEvent.isBlocked()) {
event.setResult(CommandExecuteEvent.CommandResult.denied());
if (Storage.ConfigSections.Settings.TURN_BLACKLIST_TO_WHITELIST.ENABLED)
if (!executeCommandEvent.doesNotify())
return event;
if (Storage.SEND_CONSOLE_NOTIFICATION)
@@ -79,7 +88,7 @@ public class VelocityBlockCommandListener {
return event;
}
ExecuteCommandEvent executeCommandEvent = PATEventHandler.callExecuteCommandEvents(player, event.getCommand(), false);
ExecuteCommandEvent executeCommandEvent = PATEventHandler.callExecuteCommandEvents(player, event.getCommand(), false, false);
if (executeCommandEvent.isBlocked())
event.setResult(CommandExecuteEvent.CommandResult.denied());
@@ -1,21 +1,41 @@
package de.rayzs.pat.plugin.logger;
import de.rayzs.pat.api.communication.Communicator;
import de.rayzs.pat.api.communication.client.ClientInfo;
import de.rayzs.pat.api.storage.Storage;
import de.rayzs.pat.api.storage.blacklist.impl.GeneralBlacklist;
import de.rayzs.pat.plugin.logger.impl.*;
import java.nio.charset.StandardCharsets;
import javax.net.ssl.HttpsURLConnection;
import de.rayzs.pat.api.storage.Storage;
import de.rayzs.pat.utils.Reflection;
import de.rayzs.pat.utils.*;
import de.rayzs.pat.utils.group.Group;
import de.rayzs.pat.utils.group.GroupManager;
import java.net.URL;
import java.util.*;
import java.io.*;
public class Logger {
private static final String LOG_HEADER;
static {
final String software = Reflection.isProxyServer()
? Reflection.isVelocityServer() ? "Velocity" : "Bungeecord"
: (Reflection.isPaper() ? "Paper" : Reflection.isFoliaServer() ? "Folia" : "Spigot/Bukkit");
final String version = Reflection.isProxyServer() ? "" : " " + Reflection.getRawVersionName().replace("_", ".");
LOG_HEADER = "> ProAntiTab v" + Storage.CURRENT_VERSION + " [" + software + version + "]";
}
private final static LoggerTemplate LOGGER =
Reflection.isVelocityServer() ? new VelocityLogger()
: Reflection.isProxyServer() ? new BungeeLogger()
: new BukkitLogger();
public static void info(List<String> messages) {
LOGGER.info(messages);
}
@@ -24,10 +44,6 @@ public class Logger {
LOGGER.warn(messages);
}
public static void debug(List<String> messages) {
LOGGER.debug(messages);
}
public static void info(String message) {
LOGGER.info(message);
}
@@ -36,25 +52,9 @@ public class Logger {
LOGGER.warn(message);
}
public static void debug(String message) {
LOGGER.debug(message);
}
public static String post() throws IOException {
ArrayList<String> clonedLogs = new ArrayList<>(LOGGER.getLogs());
int startIndex = clonedLogs.size() > 980 ? clonedLogs.size() - 980 : 0;
StringBuilder textBuilder = new StringBuilder("[ProAntiTab " + Storage.CURRENT_VERSION + " | " + (Reflection.isProxyServer() ? Reflection.isVelocityServer() ? "Velocity" : "Proxy" : Reflection.isPaper() ? "Paper" : "Bukkit") + "]" + (Reflection.getRawVersionName() != null ? " Server version: " + Reflection.getVersionName() + " " + Reflection.getRawVersionName().replace("_", ".") : "") + "\n" + (startIndex != 0 ? "... another part is split!\n\n" : ""));
for (int i = startIndex; i < clonedLogs.size(); i++) {
if (clonedLogs.get(i) == null)
continue;
String line = clonedLogs.get(i);
textBuilder.append("\n");
textBuilder.append(line);
}
byte[] textInBytes = textBuilder.toString().getBytes(StandardCharsets.UTF_8);
byte[] textInBytes = (LOG_HEADER + "\n\n" + createInfo()).getBytes(StandardCharsets.UTF_8);
int postDataLength = textInBytes.length;
URL url = new URL("https://haste.rayzs.de/documents");
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
@@ -77,4 +77,94 @@ public class Logger {
response = response.substring(response.indexOf(":") + 2, response.length() - 2);
return "https://haste.rayzs.de/" + response + ".txt";
}
private static String createInfo() {
StringBuilder builder = new StringBuilder();
builder.append("Updated: ")
.append(!Storage.OUTDATED)
.append("\n\n");
builder.append("Mode: ")
.append(Storage.ConfigSections.Settings.TURN_BLACKLIST_TO_WHITELIST.ENABLED ? "WHITELIST" : "BLACKLIST")
.append("\n");
builder.append("Detected Software-API: ")
.append(Reflection.isProxyServer()
? Reflection.isPaper() ? "Waterfall" :
Reflection.isVelocityServer() ? "Velocity" : "Bungeecord"
: Reflection.isFoliaServer() ? "Folia"
: Reflection.isPaper() ? "Paper" : "Spigot")
.append("\n");
builder.append("Installed plugins: \n ")
.append(String.join("\n ", Storage.getLoader().getPluginNames()))
.append("\n\n");
builder.append("Detected supported plugins:")
.append("\n");
builder.append(" LuckPerms: ")
.append(Storage.USE_LUCKPERMS)
.append("\n");
builder.append(" PlaceholderAPI: ")
.append(Storage.USE_PLACEHOLDERAPI)
.append("\n");
builder.append(" ViaVersion: ")
.append(Storage.USE_VIAVERSION)
.append("\n\n");
if (!Reflection.isProxyServer()) {
builder.append("server-name: ")
.append(Storage.ConfigSections.Settings.HANDLE_THROUGH_PROXY.ENABLED ? Storage.SERVER_NAME : "Not connected to a proxy using PAT")
.append("\n");
builder.append("last-received-sync: ")
.append(Storage.ConfigSections.Settings.HANDLE_THROUGH_PROXY.ENABLED ? Storage.LAST_SYNC : "Deactivated")
.append("\n");
}
builder.append("\ncommands: ")
.append(String.join(", ", Storage.Blacklist.getBlacklist().getCommands()))
.append("\n\n");
if (Reflection.isProxyServer()) {
builder.append("\nservers: ")
.append(String.join(", ", Storage.getServers()))
.append("\n");
builder.append("last-sent-sync: ")
.append(Storage.ConfigSections.Settings.DISABLE_SYNC.DISABLED ? "Deactivated" : (System.currentTimeMillis() - Storage.LAST_SYNC))
.append("\n\n");
for (ClientInfo client : Communicator.CLIENTS) {
builder.append("synced-server: ")
.append(client.getName() + " (" + client.getSyncTime() + ")")
.append(", ");
}
builder.append("\n\n");
}
if (Reflection.isProxyServer()) {
builder.append("server-commands:").append("\n");
for (Map.Entry<String, GeneralBlacklist> blacklist : Storage.Blacklist.getBlacklists()) {
builder.append(" ")
.append(blacklist.getKey()).append(": ")
.append(String.join(", ", blacklist.getValue().getCommands()))
.append("\n");
}
}
builder.append("\ngroups:");
for (Group group : GroupManager.getGroups()) {
builder.append("\n")
.append(group.getGroupInfo());
}
return builder.toString();
}
}
@@ -1,3 +1,3 @@
package de.rayzs.pat.plugin.logger;
public enum LoggerPriority { INFO, WARNING, DEBUG }
public enum LoggerPriority { INFO, WARNING }
@@ -1,23 +1,16 @@
package de.rayzs.pat.plugin.logger;
import java.text.SimpleDateFormat;
import java.util.List;
public interface LoggerTemplate {
SimpleDateFormat TIME_FORMAT = new SimpleDateFormat("HH:mm:ss:SS");
List<String> getLogs();
void info(List<String> messages);
void warn(List<String> messages);
void debug(List<String> messages);
void send(LoggerPriority priority, List<String> messages);
void info(String message);
void warn(String message);
void debug(String message);
void send(LoggerPriority priority, String message);
}
@@ -1,25 +1,15 @@
package de.rayzs.pat.plugin.logger.impl;
import de.rayzs.pat.plugin.BukkitLoader;
import de.rayzs.pat.plugin.logger.LoggerPriority;
import de.rayzs.pat.plugin.logger.LoggerTemplate;
import de.rayzs.pat.utils.message.MessageTranslator;
import de.rayzs.pat.plugin.BukkitLoader;
import de.rayzs.pat.plugin.logger.*;
import org.bukkit.Bukkit;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.*;
public class BukkitLogger implements LoggerTemplate {
private final List<String> LOGS = new ArrayList<>();
private final java.util.logging.Logger logger = BukkitLoader.getPluginLogger();
@Override
public List<String> getLogs() {
return LOGS;
}
@Override
public void info(List<String> messages) {
messages.forEach(this::info);
@@ -30,11 +20,6 @@ public class BukkitLogger implements LoggerTemplate {
messages.forEach(this::warn);
}
@Override
public void debug(List<String> messages) {
messages.forEach(this::debug);
}
@Override
public void send(LoggerPriority priority, List<String> messages) {
messages.forEach(message -> send(priority, message));
@@ -50,22 +35,10 @@ public class BukkitLogger implements LoggerTemplate {
send(LoggerPriority.WARNING, message);
}
@Override
public void debug(String message) {
send(LoggerPriority.DEBUG, message);
}
@Override
public void send(LoggerPriority priority, String message) {
message = MessageTranslator.replaceMessage(message);
String time = TIME_FORMAT.format(new Date(System.currentTimeMillis()));
if(time.length() != 12) time = time.substring(0, 9) + 0 + time.split(":")[3];
LOGS.add("[" + priority.name() + " | " + time + "] " + MessageTranslator.colorless(message));
if (priority == LoggerPriority.DEBUG)
return;
if (message.contains("§")) {
MessageTranslator.send(Bukkit.getServer().getConsoleSender(), message);
return;
@@ -1,25 +1,15 @@
package de.rayzs.pat.plugin.logger.impl;
import de.rayzs.pat.plugin.BungeeLoader;
import de.rayzs.pat.plugin.logger.LoggerPriority;
import de.rayzs.pat.plugin.logger.LoggerTemplate;
import de.rayzs.pat.utils.message.MessageTranslator;
import de.rayzs.pat.plugin.BungeeLoader;
import net.md_5.bungee.api.ProxyServer;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import de.rayzs.pat.plugin.logger.*;
import java.util.*;
public class BungeeLogger implements LoggerTemplate {
private final List<String> LOGS = new ArrayList<>();
private final java.util.logging.Logger logger = BungeeLoader.getPluginLogger();
@Override
public List<String> getLogs() {
return LOGS;
}
@Override
public void info(List<String> messages) {
messages.forEach(this::info);
@@ -30,11 +20,6 @@ public class BungeeLogger implements LoggerTemplate {
messages.forEach(this::warn);
}
@Override
public void debug(List<String> messages) {
messages.forEach(this::debug);
}
@Override
public void send(LoggerPriority priority, List<String> messages) {
messages.forEach(message -> send(priority, message));
@@ -50,22 +35,10 @@ public class BungeeLogger implements LoggerTemplate {
send(LoggerPriority.WARNING, message);
}
@Override
public void debug(String message) {
send(LoggerPriority.DEBUG, message);
}
@Override
public void send(LoggerPriority priority, String message) {
message = MessageTranslator.replaceMessage(message);
String time = TIME_FORMAT.format(new Date(System.currentTimeMillis()));
if(time.length() != 12) time = time.substring(0, 9) + 0 + time.split(":")[3];
LOGS.add("[" + priority.name() + " | " + time + "] " + MessageTranslator.colorless(message));
if (priority == LoggerPriority.DEBUG)
return;
if (message.contains("§")) {
MessageTranslator.send(ProxyServer.getInstance().getConsole(), message);
return;
@@ -1,25 +1,15 @@
package de.rayzs.pat.plugin.logger.impl;
import de.rayzs.pat.plugin.VelocityLoader;
import de.rayzs.pat.plugin.logger.LoggerPriority;
import de.rayzs.pat.plugin.logger.LoggerTemplate;
import de.rayzs.pat.utils.message.MessageTranslator;
import de.rayzs.pat.plugin.VelocityLoader;
import de.rayzs.pat.plugin.logger.*;
import org.slf4j.Logger;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.*;
public class VelocityLogger implements LoggerTemplate {
private final List<String> LOGS = new ArrayList<>();
private final Logger logger = VelocityLoader.getPluginLogger();
@Override
public List<String> getLogs() {
return LOGS;
}
@Override
public void info(List<String> messages) {
messages.forEach(this::info);
@@ -30,11 +20,6 @@ public class VelocityLogger implements LoggerTemplate {
messages.forEach(this::warn);
}
@Override
public void debug(List<String> messages) {
messages.forEach(this::debug);
}
@Override
public void send(LoggerPriority priority, List<String> messages) {
messages.forEach(message -> send(priority, message));
@@ -50,22 +35,10 @@ public class VelocityLogger implements LoggerTemplate {
send(LoggerPriority.WARNING, message);
}
@Override
public void debug(String message) {
send(LoggerPriority.DEBUG, message);
}
@Override
public void send(LoggerPriority priority, String message) {
message = MessageTranslator.replaceMessage(message);
String time = TIME_FORMAT.format(new Date(System.currentTimeMillis()));
if(time.length() != 12) time = time.substring(0, 9) + 0 + time.split(":")[3];
LOGS.add("[" + priority.name() + " | " + time + "] " + MessageTranslator.colorless(message));
if (priority == LoggerPriority.DEBUG)
return;
if (message.contains("§")) {
MessageTranslator.send(VelocityLoader.getServer().getConsoleCommandSource(), message);
return;
@@ -1,5 +1,6 @@
package de.rayzs.pat.plugin.metrics.impl;
import de.rayzs.pat.utils.scheduler.PATScheduler;
import org.bukkit.configuration.file.YamlConfiguration;
import java.nio.charset.StandardCharsets;
import javax.net.ssl.HttpsURLConnection;
@@ -171,7 +172,7 @@ public class BukkitMetrics {
}
// 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);
PATScheduler.createScheduler(this::submitData);
};
// Many servers tend to restart at a fixed time at xx:00 which causes an uneven distribution of requests on the
@@ -23,7 +23,10 @@ public class ExecuteCommand extends ExecuteCommandEvent {
? command.substring(1)
: command;
final String displayCommand = StringUtils.getFirstArg(command);
final String displayCommand = StringUtils.replaceTriggers(
command, "",
"\\", "<", ">", "&"
);
CommandSender sender = CommandSenderHandler.from(event.getSenderObj());
@@ -37,11 +40,12 @@ public class ExecuteCommand extends ExecuteCommandEvent {
MessageTranslator.send(
event.getSenderObj(),
Storage.ConfigSections.Settings.CUSTOM_PLUGIN.MESSAGE,
"%command%", displayCommand
"%command%", StringUtils.getFirstArg(displayCommand)
);
event.setBlocked(true);
event.setCancelled(true);
event.setDoesNotify(true);
return;
}
@@ -50,21 +54,22 @@ public class ExecuteCommand extends ExecuteCommandEvent {
MessageTranslator.send(
event.getSenderObj(),
Storage.ConfigSections.Settings.CUSTOM_VERSION.MESSAGE,
"%command%", displayCommand
"%command%", StringUtils.getFirstArg(displayCommand)
);
event.setBlocked(true);
event.setCancelled(true);
event.setDoesNotify(true);
return;
}
if (command.contains(" ") && !canPlayerExecute(sender, command)) {
if (isBlocked(sender, command)) {
event.setBlocked(true);
event.setCancelled(true);
MessageTranslator.send(event.getSenderObj(),
ResponseHandler.getResponse(uuid, event.getCommand()),
"%command%", command);
"%command%", displayCommand);
return;
}
@@ -77,23 +82,57 @@ public class ExecuteCommand extends ExecuteCommandEvent {
MessageTranslator.send(
event.getSenderObj(),
ResponseHandler.getResponse(uuid, event.getCommand(), Storage.ConfigSections.Settings.CANCEL_COMMAND.BASE_COMMAND_RESPONSE.getLines()),
"%command%", displayCommand
"%command%", StringUtils.getFirstArg(displayCommand)
);
}
private boolean canPlayerExecute(CommandSender sender, String command) {
boolean turn = Storage.ConfigSections.Settings.TURN_BLACKLIST_TO_WHITELIST.ENABLED;
boolean listed = false;
private boolean isBlocked(CommandSender sender, String command) {
final Arguments arguments = SubArgsModule.PLAYER_COMMANDS.getOrDefault(sender.getUniqueId(), Arguments.ARGUMENTS);
final List<String> commands = new ArrayList<>(arguments.CHAT_ARGUMENTS.getGeneralArgument().getInputs());
final String firstArgument = StringUtils.getFirstArg(command);
Arguments arguments = SubArgsModule.PLAYER_COMMANDS.getOrDefault(sender.getUniqueId(), Arguments.ARGUMENTS);
List<String> commands = new ArrayList<>(arguments.CHAT_ARGUMENTS.getGeneralArgument().getInputs());
final String blockBaseCommandStr = firstArgument + " -_";
final boolean blockBaseCommand = commands.contains(blockBaseCommandStr);
if (!command.contains(" ")) {
return blockBaseCommand;
}
if (blockBaseCommand) {
commands.remove(blockBaseCommandStr);
}
boolean inCommands = commands.stream().anyMatch(c -> StringUtils.getFirstArg(c).equalsIgnoreCase(firstArgument));
boolean negationInCommands = commands.stream().anyMatch(c -> StringUtils.getFirstArg(c).equalsIgnoreCase("!" + firstArgument));
if (!inCommands && !negationInCommands) {
return false;
}
boolean turn = Storage.ConfigSections.Settings.TURN_BLACKLIST_TO_WHITELIST.ENABLED;
boolean listed = isListed(command, commands);
boolean negated = isListed("!" + command, commands);
if (!listed && !inCommands) {
listed = turn;
}
if (negated) {
listed = !turn;
}
return turn != listed;
}
private boolean isListed(String command, List<String> commands) {
boolean listed = false;
final String unmodifiable = command;
final String firstArgUnmodifiable = StringUtils.getFirstArg(unmodifiable);
if (commands.stream().noneMatch(c -> StringUtils.getFirstArg(c).equalsIgnoreCase(firstArgUnmodifiable))) {
return true;
}
commands = commands.stream().map(c -> {
if (c.contains("%hidden")) {
@@ -107,8 +146,9 @@ public class ExecuteCommand extends ExecuteCommandEvent {
StringUtils.getFirstArg(s).equalsIgnoreCase(firstArgUnmodifiable) && s.contains("%")
).toList();
if (!placeholderCommands.isEmpty())
if (!placeholderCommands.isEmpty()) {
command = SubArgsModule.replacePlaceholders(command);
}
String cpyCommand;
for (String c : commands) {
@@ -140,6 +180,6 @@ public class ExecuteCommand extends ExecuteCommandEvent {
}
}
return turn == listed;
return listed;
}
}
@@ -13,20 +13,50 @@ public class TabCompletion extends FilteredTabCompletionEvent {
@Override
public void handle(FilteredTabCompletionEvent event) {
String cursor = StringUtils.replaceFirst(event.getCursor(), "/", "");
final String cursor = event.getCursor().substring(1);
if (event.getCompletion().isEmpty()) return;
UUID uuid = event.getSenderObj() instanceof UUID
final boolean turn = Storage.ConfigSections.Settings.TURN_BLACKLIST_TO_WHITELIST.ENABLED;
final UUID uuid = event.getSenderObj() instanceof UUID
? (UUID) event.getSenderObj()
: CommandSenderHandler.from(event.getSenderObj()).getUniqueId();
Arguments arguments = SubArgsModule.PLAYER_COMMANDS.getOrDefault(uuid, Arguments.ARGUMENTS);
List<String> possibilities = event.getCompletion(), result = new ArrayList<>(arguments.getResultTab(cursor));
final Arguments arguments = SubArgsModule.PLAYER_COMMANDS.getOrDefault(uuid, Arguments.ARGUMENTS);
if (Storage.ConfigSections.Settings.TURN_BLACKLIST_TO_WHITELIST.ENABLED) {
List<String> possibilities = event.getCompletion(), result = new ArrayList<>(arguments.getResultTab(cursor));
final List<String> negated = new ArrayList<>(arguments.getResultTab("!" + cursor));
final List<String> negatedInputs = new ArrayList<>(arguments.TAB_ARGUMENTS.INPUTS).stream().filter(s -> {
if (s.isEmpty())
return false;
boolean n = s.charAt(0) == '!';
if (!n && s.length() > 5)
n = s.charAt(5) == '!';
return n;
}).map(s -> s.substring(1 + (s.charAt(0) == '[' ? 5 : 0))).toList();
if (negatedInputs.stream().anyMatch(cursor::startsWith)) {
if (turn) {
event.setCompletion(new ArrayList<>());
}
return;
}
result.removeIf(s -> s.contains("-_"));
if (turn) {
possibilities = result;
if (possibilities.isEmpty() && !negated.isEmpty()) {
possibilities = event.getCompletion();
possibilities.removeAll(negated);
}
if (result.contains("%numbers%")) {
possibilities.remove("%numbers%");
possibilities.addAll(event.getCompletion().stream().filter(NumberUtils::isDigit).toList());
@@ -75,7 +105,6 @@ public class TabCompletion extends FilteredTabCompletionEvent {
}
} else {
if (result.contains("%numbers%"))
possibilities.removeIf(NumberUtils::isDigit);
@@ -85,11 +114,18 @@ public class TabCompletion extends FilteredTabCompletionEvent {
if (result.contains("%online_players%"))
possibilities.removeIf(possibility -> SubArgsModule.getOnlinePlayerNames().contains(possibility));
possibilities.removeAll(result);
possibilities.removeIf(s -> {
if (negated.contains(s)) {
return false;
}
return result.contains(s);
});
}
cursor = StringUtils.getFirstArg(cursor.toLowerCase());
if (possibilities.isEmpty() && !SubArgsModule.GENERAL_LIST.contains(cursor)) {
String firstCursorArg = StringUtils.getFirstArg(cursor.toLowerCase());
if (possibilities.isEmpty() && !SubArgsModule.GENERAL_LIST.contains(firstCursorArg)) {
return;
}
@@ -48,11 +48,26 @@ public class UpdateList {
for (String command : event.getCommands())
argument.buildArgumentStacks(command);
for (String command : argument.CHAT_ARGUMENTS.getGeneralArgument().getInputs())
argument.CHAT_ARGUMENTS.buildArguments(Storage.Blacklist.BlockTypeFetcher.modify(command));
final List<String> chatInputs = new ArrayList<>(argument.CHAT_ARGUMENTS.getGeneralArgument().getInputs());
final List<String> tabInput = new ArrayList<>(argument.TAB_ARGUMENTS.getGeneralArgument().getInputs());
for (String command : argument.TAB_ARGUMENTS.getGeneralArgument().getInputs())
argument.TAB_ARGUMENTS.buildArguments(Storage.Blacklist.BlockTypeFetcher.modify(command));
for (String command : chatInputs) {
Storage.Blacklist.BlockType type = Storage.Blacklist.BlockTypeFetcher.getType(command);
if (type != Storage.Blacklist.BlockType.NEGATE)
command = Storage.Blacklist.BlockTypeFetcher.modify(command, type);
argument.CHAT_ARGUMENTS.buildArguments(Storage.Blacklist.BlockTypeFetcher.modify(command));
}
for (String command : tabInput) {
Storage.Blacklist.BlockType type = Storage.Blacklist.BlockTypeFetcher.getType(command);
if (type != Storage.Blacklist.BlockType.NEGATE)
command = Storage.Blacklist.BlockTypeFetcher.modify(command, type);
argument.TAB_ARGUMENTS.buildArguments(command);
}
for (String command : SubArgsModule.getGroupCommands(uuid, serverName))
argument.buildArgumentStacks(command);
@@ -1,9 +1,13 @@
package de.rayzs.pat.plugin.process.impl.local.info;
import de.rayzs.pat.plugin.listeners.bukkit.BukkitAntiTabListener;
import de.rayzs.pat.utils.Reflection;
import de.rayzs.pat.utils.permission.PermissionUtil;
import de.rayzs.pat.api.command.ProCommand;
import de.rayzs.pat.api.storage.Storage;
import de.rayzs.pat.utils.sender.CommandSender;
import de.rayzs.pat.utils.sender.CommandSenderHandler;
import java.util.*;
public class UpdateCommand extends ProCommand {
@@ -19,17 +23,35 @@ public class UpdateCommand extends ProCommand {
public boolean execute(CommandSender sender, String[] args) {
if (args.length == 0) {
PermissionUtil.reloadPermissions();
Storage.getLoader().getOnlinePlayerNames().forEach(name -> {
Object playerObj = Storage.getLoader().getPlayerObjByName(name);
if (playerObj != null) {
CommandSender s = CommandSenderHandler.from(playerObj);
assert s != null;
PermissionUtil.reloadPermissions(s);
}
});
if (!Reflection.isProxyServer()) {
BukkitAntiTabListener.handleTabCompletion();
}
sender.sendMessage(Storage.ConfigSections.Messages.UPDATE_PERMISSIONS.UPDATE_ALL);
return true;
}
String name = args[0];
UUID uuid = Storage.getLoader().getUUIDByName(name);
Object playerObj = Storage.getLoader().getPlayerObjByUUID(uuid);
CommandSender targetSender = CommandSenderHandler.from(playerObj);
boolean exist = uuid != null;
boolean exist = targetSender != null;
if (exist) {
name = Storage.getLoader().getNameByUUID(uuid);
name = targetSender.getName();
}
String message = exist
@@ -39,7 +61,13 @@ public class UpdateCommand extends ProCommand {
message = message.replace("%target%", name);
if (exist) {
PermissionUtil.reloadPermissions(uuid);
PermissionUtil.reloadPermissions(targetSender);
if (!Reflection.isProxyServer()) {
BukkitAntiTabListener.handleTabCompletion(uuid);
}
}
sender.sendMessage(message);
@@ -48,6 +76,6 @@ public class UpdateCommand extends ProCommand {
@Override
public List<String> tabComplete(CommandSender sender, String[] args) {
return args.length < 2 ? Storage.getLoader().getPlayerNames() : null;
return args.length < 2 ? Storage.getLoader().getOnlinePlayerNames() : null;
}
}
@@ -107,7 +107,7 @@ public class AddCommand extends ProCommand {
if (Reflection.isProxyServer())
return null;
return BukkitLoader.getNotBlockedCommands();
return BukkitLoader.getAllowedCommands();
}
String fullString = String.join(" ", args);
@@ -60,9 +60,7 @@ public class RemoveCommand extends ProCommand {
final int length = args.length;
if (length == 1) {
boolean exist = command.contains(" ")
? Storage.Blacklist.getBlacklist().getCommands().contains(command)
: Storage.Blacklist.getBlacklist().isListed(command);
boolean exist = Storage.Blacklist.getBlacklist().getCommands().contains(command);
if (exist) {
Storage.Blacklist.getBlacklist().remove(command).save();
@@ -2,6 +2,7 @@ package de.rayzs.pat.plugin.process.impl.local.system;
import de.rayzs.pat.api.communication.BackendUpdater;
import de.rayzs.pat.api.brand.CustomServerBrand;
import de.rayzs.pat.api.storage.blacklist.impl.GeneralBlacklist;
import de.rayzs.pat.utils.configuration.updater.ConfigUpdater;
import de.rayzs.pat.utils.group.GroupManager;
import de.rayzs.pat.api.command.ProCommand;
@@ -25,7 +26,9 @@ public class ReloadCommand extends ProCommand {
boolean backend = Storage.ConfigSections.Settings.HANDLE_THROUGH_PROXY.ENABLED && !proxy;
sender.sendMessage(Storage.ConfigSections.Messages.RELOAD.LOADING);
ConfigUpdater.initialize();
Storage.loadAll(Reflection.isProxyServer() || !backend);
CustomServerBrand.initialize();
GroupManager.clearAllGroups();
GroupManager.initialize();
@@ -35,13 +38,13 @@ public class ReloadCommand extends ProCommand {
BackendUpdater.start();
}
ConfigUpdater.broadcastMissingParts();
if (!backend) {
Storage.handleChange();
}
ConfigUpdater.initialize();
ConfigUpdater.broadcastMissingParts();
Storage.getLoader().handleReload();
sender.sendMessage(Storage.ConfigSections.Messages.RELOAD.DONE);
return true;
@@ -15,7 +15,7 @@ public class CommandsCache {
if (change || !isOutdated(commands))
return;
filteredCommands = new LinkedList<>();
LinkedList<String> tmpFilteredCommands = new LinkedList<>();
allCommands = new ArrayList<>(commands);
for (String command : allCommands) {
@@ -36,6 +36,7 @@ public class CommandsCache {
}
filteredCommands = tmpFilteredCommands;
change = true;
}
@@ -43,7 +44,7 @@ public class CommandsCache {
if(!isOutdated(commands))
return;
filteredCommands = new LinkedList<>();
LinkedList<String> tmpFilteredCommands = new LinkedList<>();
allCommands = new ArrayList<>(commands);
for (String command : allCommands) {
@@ -53,7 +54,7 @@ public class CommandsCache {
if (type != Storage.Blacklist.BlockType.BOTH && type != Storage.Blacklist.BlockType.TAB)
continue;
if (isFilterListAvailable(server)) {
if (isFilterListAvailable()) {
if (filteredCommands.contains(command))
continue;
@@ -62,6 +63,8 @@ public class CommandsCache {
}
}
filteredCommands = tmpFilteredCommands;
}
public List<String> getPlayerCommands(Collection<String> unfilteredCommands, Object targetObj, UUID uuid) {
@@ -70,11 +73,23 @@ public class CommandsCache {
public List<String> getPlayerCommands(Collection<String> unfilteredCommands, Object targetObj, UUID uuid, String serverName) {
List<String> playerCommands = new LinkedList<>(unfilteredCommands);
List<String> localFilteredCommands = filteredCommands == null ? null : new LinkedList<>(filteredCommands);
List<String> localFilteredCommands = filteredCommands == null ? null : new LinkedList<>();
if (localFilteredCommands == null)
return playerCommands;
final int max = filteredCommands.size();
for (int i = 0; i < max; i++) {
try {
String command = filteredCommands.get(i);
filteredCommands.add(command);
} catch (ArrayIndexOutOfBoundsException outOfBoundsException) {
System.out.println("Array is out of bounds " + i + "/" + max + "! " + outOfBoundsException.getMessage());
break;
}
}
boolean hasNamespaceBypass = Storage.ConfigSections.Settings.BLOCK_NAMESPACE_COMMANDS.doesBypass(targetObj);
@@ -90,12 +105,6 @@ public class CommandsCache {
return !Storage.Blacklist.canPlayerAccessTab(targetObj, command, serverName);
});
String uuidSubstring = uuid.toString().substring(uuid.toString().length() - 5);
if(playerCommands.isEmpty())
Logger.debug("Commands list for player with uuid " + uuidSubstring + " is empty! (" + (filteredCommands != null ? filteredCommands.size() : "null") + " | " + (unfilteredCommands != null ? unfilteredCommands.size() : "null") + ")");
else
Logger.debug("Created list of commands for player with uuid " + uuidSubstring + " with a total of " + playerCommands.size() + " commands!");
PATEventHandler.callUpdatePlayerCommandsEvents(targetObj, playerCommands, serverName != null);
return playerCommands.stream().map(command -> {
@@ -111,15 +120,7 @@ public class CommandsCache {
}
public boolean isFilterListAvailable() {
return isFilterListAvailable(null);
}
public boolean isFilterListAvailable(String server) {
boolean available = this.filteredCommands != null;
if(!available)
Logger.debug("FilterList didn't exist during built!" + (server != null ? "(server: " + server + ")" : ""));
return available;
return this.filteredCommands != null;
}
public void updateChangeState() {
@@ -37,16 +37,21 @@ public class ConnectionBuilder {
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
connection.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
if(parameters != null && 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;
if (firstParam == null) {
firstParam = parameter;
continue;
}
secondParam = parameter;
connection.setRequestProperty((String) firstParam, (String) secondParam);
firstParam = null;
}
}
@@ -0,0 +1,43 @@
package de.rayzs.pat.utils;
import java.util.ArrayDeque;
import java.util.function.Consumer;
public class LimitedList<T> {
private ArrayDeque<T> list = new ArrayDeque<>();
private final int maxCapacity;
public LimitedList(int maxCapacity) {
this.maxCapacity = maxCapacity;
}
public LimitedList(LimitedList<T> list) {
this.maxCapacity = list.maxCapacity;
this.list = new ArrayDeque<>(list.getList());
}
public void add(T element) {
if (list.size() == maxCapacity) {
list.removeFirst();
}
list.add(element);
}
public void iterate(Consumer<T> action) {
list.forEach(action);
}
public int getSize() {
return list.size();
}
public int getMaxCapacity() {
return maxCapacity;
}
private ArrayDeque<T> getList() {
return list;
}
}
@@ -2,6 +2,8 @@ package de.rayzs.pat.utils;
public class NumberUtils {
private static final char[] EXCEPTIONS = {'.', ',', 'k', 'm', 'b'};
public static boolean isBetween(int n, int l, int r) {
int min = Math.min(l, r);
int max = Math.max(l, r);
@@ -16,10 +18,9 @@ public class NumberUtils {
int length = str.length();
for (int i = 0; i < length; i++) {
char c = str.charAt(i);
if (c == '.' || c == ',')
if (isExceptionalDigit(c))
continue;
if (!Character.isDigit(c))
@@ -28,4 +29,17 @@ public class NumberUtils {
return true;
}
private static boolean isExceptionalDigit(char c) {
for (char q : EXCEPTIONS) {
if (c == q) {
return true;
}
if (Character.isAlphabetic(c) && c == Character.toUpperCase(q)) {
return true;
}
}
return false;
}
}
@@ -25,10 +25,10 @@ public class Reflection {
proxy = false;
} catch (Throwable ignored) { proxy = true; }
if(!proxy) {
if (!proxy) {
try {
Class.forName("com.destroystokyo.paper.proxy.VelocityProxy");
folia = versionName.toLowerCase().contains("folia");
Class.forName("io.papermc.paper.threadedregions.RegionizedServer");
folia = true;
} catch (Throwable throwable) {
folia = false;
}
@@ -46,7 +46,7 @@ public class Reflection {
}
}
if(proxy) {
if (proxy) {
try {
Class.forName("com.velocitypowered.api.proxy.ProxyServer");
velocity = true;
@@ -58,6 +58,10 @@ public class Reflection {
oldChannelMethod = folia || paper && Reflection.isWeird();
}
public static void toggleInjectionMethod() {
oldChannelMethod = !oldChannelMethod;
}
public static String getVersionPackageName() {return versionPackageName;}
public static int[] getAges() { return new int[]{major, minor, release}; }
@@ -1,121 +1,179 @@
package de.rayzs.pat.utils;
import de.rayzs.pat.api.storage.Storage;
import de.rayzs.pat.plugin.logger.Logger;
import java.util.Arrays;
import java.util.List;
public class VersionComparer {
private static Version CURRENT_VERSION, NEWEST_VERSION;
public enum VersionState { NEWER, UPDATED, OUTDATED }
public static void setCurrentVersion(String versionName) {
if(CURRENT_VERSION != null && CURRENT_VERSION.getVersionName().equals(versionName)) return;
CURRENT_VERSION = new Version(versionName);
private static final VersionComparer instance = new VersionComparer();
public static VersionComparer get() {
return instance;
}
public static void setNewestVersion(String versionName) {
if(NEWEST_VERSION != null && NEWEST_VERSION.getVersionName().equals(versionName))
private VersionComparer() {}
private final List<String> ignoreVersions = Arrays.asList("1.9.1", "1.9.2");
private final String versionUrl = "https://www.rayzs.de/proantitab/api/version.php";
private final int versionLength = 3;
private Version currentVersion, newestVersion;
private VersionState versionState = VersionState.UPDATED;
private boolean shouldAnnounce = true;
public boolean computeComparison() {
String result = new ConnectionBuilder().setUrl(versionUrl)
.setProperties("ProAntiTab", "4454")
.connect()
.getResponse();
if (result == null)
result = "/";
if (result.equals("/")) {
Logger.warning("Failed to connect to plugin page! Version comparison cannot be made. (No internet?)");
return false;
}
Storage.NEWER_VERSION = result;
VersionComparer.get().setNewestVersion(Storage.NEWER_VERSION);
if (VersionComparer.get().isNewer()) {
if (shouldAnnounce) {
shouldAnnounce = false;
Logger.info("§8[§fPAT | Bukkit§8] §7Please be aware that you are currently using a §bdeveloper §7version of ProAntiTab. Bugs, errors and a lot of debug messages might be included.");
}
return true;
}
if (VersionComparer.get().isUpdated()) {
if (shouldAnnounce) {
shouldAnnounce = false;
Storage.ConfigSections.Settings.UPDATE.UPDATED.getLines().forEach(Logger::warning);
}
return false;
}
if (VersionComparer.get().isOutdated()) {
if (shouldAnnounce) {
shouldAnnounce = false;
Storage.OUTDATED = true;
Storage.ConfigSections.Settings.UPDATE.OUTDATED.getLines().forEach(Logger::warning);
}
return true;
}
return false;
}
public void setCurrentVersion(String version) {
if (version == null)
return;
NEWEST_VERSION = new Version(versionName);
currentVersion = new Version(version);
}
public static Version getCurrentVersion() {
return CURRENT_VERSION;
public void setNewestVersion(String version) {
if (version == null)
return;
if (ignoreVersions.contains(version))
return;
newestVersion = new Version(version);
compute();
}
public static Version getNewestVersion() {
return NEWEST_VERSION;
public VersionState getVersionState() {
return versionState;
}
public static boolean isNewest() {
if(CURRENT_VERSION == null || NEWEST_VERSION == null) return true;
return CURRENT_VERSION.isSame(NEWEST_VERSION);
public boolean isUpdated() {
return versionState == VersionState.UPDATED;
}
public static boolean isUnreleased() {
if(CURRENT_VERSION == null || NEWEST_VERSION == null) return true;
return CURRENT_VERSION.isNewer(NEWEST_VERSION);
public boolean isOutdated() {
return versionState == VersionState.OUTDATED;
}
public static boolean isOutdated() {
if(CURRENT_VERSION == null || NEWEST_VERSION == null) return false;
return CURRENT_VERSION.isOlder(NEWEST_VERSION);
public boolean isNewer() {
return versionState == VersionState.NEWER;
}
public static boolean isDeveloperVersion() {
return CURRENT_VERSION.getState() == State.DEV;
}
private void compute() {
if (currentVersion == null || newestVersion == null)
return;
public static class Version {
private final String versionName;
private int release = -1, major = -1, patch = -1;
private State state = State.RELEASE;
int[] crntNum = currentVersion.getVersionNums();
int[] newNum = newestVersion.getVersionNums();
public Version(String version) {
this.versionName = version;
for (int i = 0; i < versionLength; i++) {
try {
String[] versionSplit = version.split("\\.");
release = Integer.parseInt(versionSplit[0]);
major = Integer.parseInt(versionSplit[1]);
String patchAsString = versionSplit[2];
patchAsString = patchAsString.contains("-") ? patchAsString.split("-")[0] : patchAsString;
patch = Integer.parseInt(patchAsString);
if(!version.contains("-")) return;
String stateName = version.split("-")[1].toUpperCase();
state = State.valueOf(stateName);
} catch (Throwable throwable) {
Logger.warning("Failed to read version name! [" + version + "]");
throwable.printStackTrace();
if (crntNum[i] > newNum[i]) {
versionState = VersionState.NEWER;
return;
}
if (crntNum[i] < newNum[i]) {
versionState = VersionState.OUTDATED;
return;
}
}
}
private class Version {
private final int[] versionNums = new int[versionLength];
private final String versionString;
public Version(String versionString) {
this.versionString = versionString;
setVersionNums();
}
public String getVersionName() {
return versionName;
return versionString;
}
public boolean isSame(Version version) {
return version.getVersionName().equals(versionName);
public int[] getVersionNums() {
return versionNums;
}
public boolean isNewer(Version comparedVersion) {
return !isSame(comparedVersion) && !isOlder(comparedVersion);
private void setVersionNums() {
if (!versionString.contains("."))
return;
String[] details = versionString.split("\\.");
for (int i = 0; i < details.length; i++) {
if (i >= versionLength)
break;
String detailString = details[i];
if (!NumberUtils.isDigit(detailString))
continue;
int detail = Integer.parseInt(detailString);
versionNums[i] = detail;
}
}
public boolean isOlder(Version comparedVersion) {
if(release > comparedVersion.getRelease()) return false;
if(major > comparedVersion.getMajor()) return false;
return patch < comparedVersion.getPatch();
}
public int getRelease() {
return release;
}
public int getMajor() {
return major;
}
public int getPatch() {
return patch;
}
public State getState() {
return state;
}
public boolean isInvalid() {
return release == -1 || major == -1 || patch == -1;
}
}
public enum State {
RELEASE, DEV, ALPHA, BETA
}
}
@@ -83,7 +83,7 @@ public class BukkitConfigurationBuilder implements ConfigurationBuilder {
if (fileName.equals("config")) {
if (!ConfigUpdater.shouldAutoUpdate()) {
ConfigUpdater.addMissingPart(path + "." + target);
ConfigUpdater.addMissingPart((!path.isBlank() ? path + "." : "") + target);
return object;
}
@@ -90,7 +90,7 @@ public class ProxyConfigurationBuilder implements ConfigurationBuilder {
if (fileName.equals("config")) {
if (!ConfigUpdater.shouldAutoUpdate()) {
ConfigUpdater.addMissingPart(path + "." + target);
ConfigUpdater.addMissingPart((!path.isBlank() ? path + "." : "") + target);
return object;
}
@@ -13,8 +13,7 @@ import java.util.*;
public class ConfigUpdater {
private static List<String> NEWEST_CONFIG_INPUT = new ArrayList<>(),
MISSING_PARTS = new ArrayList<>();
private static final List<String> MISSING_PARTS = new ArrayList<>();
private static boolean LOADED = false, AUTO_UPDATE = false, ANNOUNCE = false;
@@ -22,19 +21,19 @@ public class ConfigUpdater {
HOW_TO_READ_FILE_NAME = "How-To-Read.txt";
public static void initialize() {
try {
MISSING_PARTS.clear();
LOADED = false;
MISSING_PARTS.clear();
try {
ConfigurationBuilder config = Configurator.get("config");
ANNOUNCE = (boolean) config.getOrSet("updater.announce-missing-parts", true);
AUTO_UPDATE = (boolean) config.getOrSet("updater.auto-update-config", false);
LOADED = true;
} catch (Exception exception) {
Logger.warning("Failed to find section 'updater.auto-config-updater' in config.yml!");
}
LOADED = true;
}
public static boolean shouldAutoUpdate() {
@@ -69,9 +68,6 @@ public class ConfigUpdater {
if (!ANNOUNCE)
return;
List<String> configInput = new LinkedList<>(Arrays.asList("# WARNING: This file is auto generated and its sole purpose is to be used as comparison!\n# WARNING: It will be deleted once this file is no longer needed.", " ", " "));
configInput.addAll(NEWEST_CONFIG_INPUT);
Configurator.createResourcedFile(
"files\\" + (Reflection.isProxyServer() ? "proxy" : "bukkit") + "-config.yml",
COMPARABLE_FILE_NAME,
@@ -1,16 +1,14 @@
package de.rayzs.pat.utils.group;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import de.rayzs.pat.api.storage.Storage;
import de.rayzs.pat.api.storage.blacklist.BlacklistCreator;
import de.rayzs.pat.api.storage.blacklist.impl.GroupBlacklist;
import de.rayzs.pat.utils.ExpireCache;
import de.rayzs.pat.utils.Reflection;
import de.rayzs.pat.utils.configuration.ConfigurationBuilder;
import de.rayzs.pat.utils.permission.PermissionUtil;
@@ -58,6 +56,37 @@ public class Group implements Serializable {
loadServerBlacklist();
}
public String getGroupInfo() {
StringBuilder builder = new StringBuilder();
builder.append(" groupName: ")
.append(groupName).append("\n")
.append(" priority: ")
.append(priority).append("\n");
builder.append(" commands: ")
.append(String.join(", ", getCommands()))
.append("\n");
if (Reflection.isProxyServer()) {
builder.append(" servers:\n");
for (Map.Entry<String, GroupBlacklist> entry : groupServerBlacklist.entrySet()) {
builder.append(" ")
.append(entry.getKey())
.append(": ");
for (GroupBlacklist blacklist : getAllServerGroupBlacklist(entry.getKey())) {
builder.append(String.join(", ", blacklist.getCommands()));
builder.append(", ");
}
builder.append("\n");
}
}
return builder.toString();
}
private void loadServerBlacklist() {
String path = "groups." + groupName + ".servers";
@@ -152,15 +181,16 @@ public class Group implements Serializable {
GroupBlacklist groupBlacklist;
if (this.groupServerBlacklist.containsKey(server) && this.groupServerBlacklist.get(server) != null)
if (this.groupServerBlacklist.get(server) != null)
groupBlacklist = this.groupServerBlacklist.get(server);
else {
groupBlacklist = BlacklistCreator.createGroupBlacklist(this.groupName, server, ignoreExist);
this.groupServerBlacklist.put(server, groupBlacklist);
}
if (groupBlacklist != null)
groupBlacklist.load();
if (groupBlacklist != null) {
groupBlacklist.load();
this.groupServerBlacklist.put(server, groupBlacklist);
}
}
return groupBlacklist;
}
@@ -6,7 +6,10 @@ import de.rayzs.pat.api.storage.Storage;
import de.rayzs.pat.api.storage.Storage.Blacklist.BlockType;
import de.rayzs.pat.api.storage.blacklist.BlacklistCreator;
import de.rayzs.pat.api.storage.blacklist.impl.GroupBlacklist;
import de.rayzs.pat.plugin.logger.Logger;
import de.rayzs.pat.utils.Reflection;
import de.rayzs.pat.utils.sender.CommandSender;
import de.rayzs.pat.utils.sender.CommandSenderHandler;
public class GroupManager {
@@ -57,29 +60,46 @@ public class GroupManager {
}
public static boolean canAccessCommand(Object targetObj, String unmodifiedCommand, Storage.Blacklist.BlockType type, String server) {
final List<Group> playerGroups = getPlayerGroups(targetObj);
final CommandSender sender = CommandSenderHandler.from(targetObj);
if(playerGroups.isEmpty()) {
if (sender == null) {
Logger.warning("Failed to load player! (GroupManager#62)");
return false;
}
final List<Group> playerGroups = sender.getGroups();
if (playerGroups == null || playerGroups.isEmpty()) {
return false;
}
String command = type.toString() + unmodifiedCommand;
boolean permitted = playerGroups.stream().anyMatch(group -> {
if (group == null)
return false;
boolean permitted = false;
for (Group group : playerGroups) {
permitted = group.contains(command);
if (permitted) {
break;
}
if (server != null) {
List<String> servers = group.getBlacklistServerNames(server);
for (String s : servers) {
if (group.contains(command, s))
return true;
if (group.contains(command, s)) {
permitted = true;
break;
}
}
}
return group.contains(command);
});
}
if (!permitted && type != BlockType.BOTH)
return canAccessCommand(targetObj, unmodifiedCommand, Storage.Blacklist.BlockType.BOTH, server);
@@ -41,8 +41,13 @@ public class PermissionMap {
}
public PermissionState getPermissionState(String permission) {
if(!hasPermissionState(permission)) return PermissionState.EMPTY;
return permissionMap.get(permission) ? PermissionState.PERMITTED : PermissionState.DENIED;
if (!hasPermissionState(permission)) {
return PermissionState.EMPTY;
}
return permissionMap.get(permission)
? PermissionState.PERMITTED
: PermissionState.DENIED;
}
public boolean hasPermissionState(String permission) {
@@ -1,11 +1,9 @@
package de.rayzs.pat.utils.permission;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Set;
import java.util.UUID;
import java.util.*;
import de.rayzs.pat.api.storage.Storage;
import de.rayzs.pat.utils.group.GroupManager;
import de.rayzs.pat.utils.sender.CommandSender;
import de.rayzs.pat.utils.sender.CommandSenderHandler;
import de.rayzs.pat.utils.adapter.LuckPermsAdapter;
@@ -19,15 +17,24 @@ public class PermissionUtil {
}
public static void reloadPermissions() {
MAP.keySet().forEach(PermissionUtil::reloadPermissions);
List<UUID> uuids = new ArrayList<>(MAP.keySet());
uuids.forEach(PermissionUtil::reloadPermissions);
}
public static void reloadPermissions(UUID uuid) {
if (!MAP.containsKey(uuid))
return;
MAP.get(uuid).clear();
resetPermissions(uuid);
setPlayerPermissions(uuid);
CommandSender sender = CommandSenderHandler.getSenderFromUUID(uuid);
if (sender != null) {
sender.updateGroups();
}
}
public static void reloadPermissions(CommandSender sender) {
resetPermissions(sender.getUniqueId());
setPlayerPermissions(sender);
sender.updateGroups();
}
public static String getPermissionsAsString(UUID uuid) {
@@ -41,17 +48,32 @@ public class PermissionUtil {
public static Set<String> getPermissions(UUID uuid) {
PermissionMap permissionMap = MAP.get(uuid);
if(permissionMap == null) return null;
if(permissionMap == null)
return null;
return permissionMap.getHashedPermissions();
}
public static void setPlayerPermissions(CommandSender sender) {
if (Storage.USE_LUCKPERMS) {
LuckPermsAdapter.setPermissions(sender.getUniqueId());
} else {
GroupManager.getGroups().forEach(group -> group.hasPermission(sender));
}
}
public static void setPlayerPermissions(UUID uuid) {
if (Storage.USE_LUCKPERMS)
if (Storage.USE_LUCKPERMS) {
LuckPermsAdapter.setPermissions(uuid);
} else {
GroupManager.getGroups().forEach(group -> group.hasPermission(uuid));
}
}
public static void resetPermissions(UUID uuid) {
if(!MAP.containsKey(uuid)) return;
if (!MAP.containsKey(uuid))
return;
MAP.get(uuid).clear();
}
@@ -86,7 +108,7 @@ public class PermissionUtil {
uuid = sender.getUniqueId();
}
if(!MAP.containsKey(uuid)) {
if (!MAP.containsKey(uuid)) {
MAP.put(uuid, new PermissionMap(uuid));
return false;
}
@@ -94,20 +116,22 @@ public class PermissionUtil {
permissionMap = MAP.get(uuid);
if (sender != null) {
if (!Storage.USE_LUCKPERMS) {
if (permissionMap.hasPermissionState("*"))
if (!permissionMap.hasPermissionState("*"))
permissionMap.setState("*", sender.hasPermission("*"));
if (permissionMap.hasPermissionState("proantitab.*"))
if (!permissionMap.hasPermissionState("proantitab.*"))
permissionMap.setState("proantitab.*", sender.hasPermission("proantitab.*"));
if (permissionMap.hasPermissionState("proantitab." + permission))
if (!permissionMap.hasPermissionState("proantitab." + permission))
permissionMap.setState("proantitab." + permission, sender.hasPermission("proantitab." + permission));
}
if (sender.isOperator())
if (!Storage.ConfigSections.Settings.HANDLE_THROUGH_PROXY.ENABLED)
return true;
if (sender.isOperator() && !Storage.ConfigSections.Settings.HANDLE_THROUGH_PROXY.ENABLED)
return true;
}
return permissionMap.isPermitted("*") || permissionMap.isPermitted("proantitab.*") || permissionMap.isPermitted("proantitab." + permission);
@@ -7,6 +7,7 @@ import de.rayzs.pat.utils.*;
import de.rayzs.pat.utils.response.action.ActionHandler;
import java.util.*;
import java.util.stream.Collectors;
public class ResponseHandler {
@@ -23,12 +24,61 @@ public class ResponseHandler {
});
}
public static String replaceArgsVariables(String input, String command) {
if (!input.contains(" "))
return input;
String[] commandSplit = command.contains(" ") ? command.split(" ") : new String[]{command};
String[] split = input.split(" ");
for (int i = 0; i < split.length; i++) {
String part = split[i];
if (! (part.startsWith("%args[") && part.endsWith("]%")))
continue;
part = part.substring(part.indexOf('[') + 1, part.lastIndexOf(']'));
int length = commandSplit.length, fromIndex, toIndex;
if (part.contains("-")) {
String[] indexSplit = part.split("-");
fromIndex = Integer.parseInt(indexSplit[0]) - 1;
toIndex = Integer.parseInt(indexSplit[1]);
} else {
fromIndex = Integer.parseInt(part);
toIndex = fromIndex;
}
if (fromIndex < 0 || toIndex > length) {
Logger.warning("Custom response contains an error! (" + input + ")");
Logger.warning("Out of bounds! (Input: " + input + ", Possible: " + (length > 1 ? "1-" : "") + length + ")");
continue;
}
String replacement;
if (fromIndex == toIndex) {
replacement = commandSplit[fromIndex - 1];
} else {
replacement = String.join(" ", Arrays.copyOfRange(commandSplit, fromIndex, toIndex));;
}
split[i] = replacement;
}
return String.join(" ", split);
}
public static List<String> getResponse(UUID uuid, String input) {
return getResponse(uuid, input, Storage.ConfigSections.Settings.CANCEL_COMMAND.SUB_COMMAND_RESPONSE.getLines());
}
public static List<String> getResponse(UUID uuid, String input, List<String> defaultMessage) {
final String finalInput = input.startsWith("/") ? StringUtils.replaceFirst(input, "/", "") : input;
final String finalInput = input.startsWith("/") && input.length() > 1
? input.substring(1)
: input;
final Optional<Response> optionalResponse = RESPONSES.stream().filter(response -> {
for (String trigger : response.triggers)
@@ -39,8 +89,11 @@ public class ResponseHandler {
}).findFirst();
if (uuid != null && optionalResponse.isPresent()) {
optionalResponse.get().executeAction(uuid);
return optionalResponse.get().message;
optionalResponse.get().executeAction(uuid, finalInput);
return new ArrayList<>(optionalResponse.get().message)
.stream().map(s -> replaceArgsVariables(s, finalInput))
.collect(Collectors.toList());
}
return defaultMessage;
@@ -56,7 +109,7 @@ public class ResponseHandler {
this.actions = (List<String>) Storage.Files.CUSTOM_RESPONSES.getOrSet(key + ".actions", new ArrayList<>());
}
public void executeAction(UUID uuid) {
public void executeAction(UUID uuid, String command) {
String[] split;
for (String action : actions) {
@@ -142,7 +195,7 @@ public class ResponseHandler {
continue;
}
ActionHandler.sendTitle(action, uuid, split[1], split[2], fadeIn, stay, fadeOut);
ActionHandler.sendTitle(action, uuid, command, split[1], split[2], fadeIn, stay, fadeOut);
continue;
case "sound":
@@ -192,7 +245,7 @@ public class ResponseHandler {
Logger.warning(" > e.g: console::say Hello world!");
}
ActionHandler.executeConsoleCommand(action, uuid, split[1]);
ActionHandler.executeConsoleCommand(action, uuid, command, split[1]);
case "execute":
if (split.length == 1) {
@@ -203,7 +256,7 @@ public class ResponseHandler {
Logger.warning(" > e.g: execute::help");
}
ActionHandler.executePlayerCommand(action, uuid, split[1]);
ActionHandler.executePlayerCommand(action, uuid, command, split[1]);
case "actionbar":
if (split.length == 1) {
@@ -214,7 +267,7 @@ public class ResponseHandler {
Logger.warning(" > e.g: actionbar::I like COOKIES");
}
ActionHandler.sendActionbar(action, uuid, split[1]);
ActionHandler.sendActionbar(action, uuid, command, split[1]);
}
}
@@ -4,11 +4,11 @@ import java.util.UUID;
public interface Action {
void executeConsoleCommand(String action, UUID uuid, String command);
void executePlayerCommand(String action, UUID uuid, String command);
void sendTitle(String action, UUID uuid, String title, String subTitle, int fadeIn, int stay, int fadeOut);
void executeConsoleCommand(String action, UUID uuid, String command, String message);
void executePlayerCommand(String action, UUID uuid, String command, String message);
void sendTitle(String action, UUID uuid, String command, String title, String subTitle, int fadeIn, int stay, int fadeOut);
void addPotionEffect(String action, UUID uuid, String potionEffectTypeName, int duration, int amplifier);
void playSound(String action, UUID uuid, String soundName, float volume, float pitch);
void sendActionbar(String action, UUID uuid, String text);
void sendActionbar(String action, UUID uuid, String command, String message);
}
@@ -6,20 +6,23 @@ import java.util.UUID;
public class ActionHandler {
private static final Action ACTION = Reflection.isProxyServer() ? Reflection.isVelocityServer() ? new VelocityAction() : new BungeeAction() : Reflection.getMinor() <= 16 ? new OldBukkitAction() : new ModernBukkitAction();
private static final Action ACTION = Reflection.isProxyServer() ? Reflection.isVelocityServer()
? new VelocityAction() : new BungeeAction()
: Reflection.getMinor() <= 16
? new OldBukkitAction() : new ModernBukkitAction();
public static void initialize() {}
public static void executeConsoleCommand(String action, UUID uuid, String command) {
ACTION.executeConsoleCommand(action, uuid, command);
public static void executeConsoleCommand(String action, UUID uuid, String command, String message) {
ACTION.executeConsoleCommand(action, uuid, command, message);
}
public static void executePlayerCommand(String action, UUID uuid, String command) {
ACTION.executePlayerCommand(action, uuid, command);
public static void executePlayerCommand(String action, UUID uuid, String command, String message) {
ACTION.executePlayerCommand(action, uuid, command, message);
}
public static void sendTitle(String action, UUID uuid, String title, String subTitle, int fadeIn, int stay, int fadeOut) {
ACTION.sendTitle(action, uuid, title, subTitle, fadeIn, stay, fadeOut);
public static void sendTitle(String action, UUID uuid, String command, String title, String subTitle, int fadeIn, int stay, int fadeOut) {
ACTION.sendTitle(action, uuid, command, title, subTitle, fadeIn, stay, fadeOut);
}
public static void addPotionEffect(String action, UUID uuid, String potionEffectType, int duration, int amplifier) {
@@ -30,7 +33,7 @@ public class ActionHandler {
ACTION.playSound(action, uuid, soundName, volume, pitch);
}
public static void sendActionbar(String action, UUID uuid, String text) {
ACTION.sendActionbar(action, uuid, text);
public static void sendActionbar(String action, UUID uuid, String command, String message) {
ACTION.sendActionbar(action, uuid, command, message);
}
}
@@ -2,6 +2,7 @@ package de.rayzs.pat.utils.response.action.impl;
import de.rayzs.pat.plugin.logger.Logger;
import de.rayzs.pat.utils.StringUtils;
import de.rayzs.pat.utils.response.ResponseHandler;
import de.rayzs.pat.utils.response.action.Action;
import net.md_5.bungee.api.ChatMessageType;
import net.md_5.bungee.api.ProxyServer;
@@ -14,28 +15,32 @@ import java.util.UUID;
public class BungeeAction implements Action {
@Override
public void executeConsoleCommand(String action, UUID uuid, String command) {
public void executeConsoleCommand(String action, UUID uuid, String command, String message) {
ProxiedPlayer player = ProxyServer.getInstance().getPlayer(uuid);
message = ResponseHandler.replaceArgsVariables(message, command);
if (player != null)
command = command.replace("%player%", player.getName());
message = message.replace("%player%", player.getName());
ProxyServer.getInstance().getPluginManager().dispatchCommand(ProxyServer.getInstance().getConsole(), command);
ProxyServer.getInstance().getPluginManager().dispatchCommand(ProxyServer.getInstance().getConsole(), message);
}
@Override
public void executePlayerCommand(String action, UUID uuid, String command) {
public void executePlayerCommand(String action, UUID uuid, String command, String message) {
ProxiedPlayer player = ProxyServer.getInstance().getPlayer(uuid);
message = ResponseHandler.replaceArgsVariables(message, command);
if (player != null)
command = command.replace("%player%", player.getName());
message = command.replace("%player%", player.getName());
ProxyServer.getInstance().getPluginManager().dispatchCommand(player, command);
ProxyServer.getInstance().getPluginManager().dispatchCommand(player, message);
}
@Override
public void sendTitle(String action, UUID uuid, String title, String subTitle, int fadeIn, int stay, int fadeOut) {
public void sendTitle(String action, UUID uuid, String command, String title, String subTitle, int fadeIn, int stay, int fadeOut) {
ProxiedPlayer player = ProxyServer.getInstance().getPlayer(uuid);
title = ResponseHandler.replaceArgsVariables(title, command);
subTitle = ResponseHandler.replaceArgsVariables(subTitle, command);
if (player == null)
return;
@@ -58,12 +63,13 @@ public class BungeeAction implements Action {
}
@Override
public void sendActionbar(String action, UUID uuid, String text) {
public void sendActionbar(String action, UUID uuid, String command, String message) {
ProxiedPlayer player = ProxyServer.getInstance().getPlayer(uuid);
message = ResponseHandler.replaceArgsVariables(message, command);
if (player == null)
return;
player.sendMessage(ChatMessageType.ACTION_BAR, new TextComponent(StringUtils.replace(text, "%player%", player.getName())));
player.sendMessage(ChatMessageType.ACTION_BAR, new TextComponent(StringUtils.replace(message, "%player%", player.getName())));
}
}
@@ -3,6 +3,7 @@ package de.rayzs.pat.utils.response.action.impl;
import de.rayzs.pat.plugin.logger.Logger;
import de.rayzs.pat.utils.StringUtils;
import de.rayzs.pat.utils.message.replacer.PlaceholderReplacer;
import de.rayzs.pat.utils.response.ResponseHandler;
import de.rayzs.pat.utils.response.action.Action;
import net.md_5.bungee.api.ChatMessageType;
import net.md_5.bungee.api.chat.TextComponent;
@@ -17,35 +18,39 @@ import java.util.UUID;
public class ModernBukkitAction implements Action {
@Override
public void executeConsoleCommand(String action, UUID uuid, String command) {
public void executeConsoleCommand(String action, UUID uuid, String command, String message) {
Player player = Bukkit.getPlayer(uuid);
message = ResponseHandler.replaceArgsVariables(message, command);
if (player != null)
command = command.replace("%player%", player.getName());
message = message.replace("%player%", player.getName());
if (command.contains("%"))
command = PlaceholderReplacer.replace(player, command);
if (message.contains("%"))
message = PlaceholderReplacer.replace(player, message);
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command);
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), message);
}
@Override
public void executePlayerCommand(String action, UUID uuid, String command) {
public void executePlayerCommand(String action, UUID uuid, String command, String message) {
Player player = Bukkit.getPlayer(uuid);
message = ResponseHandler.replaceArgsVariables(message, command);
if(player != null)
command = command.replace("%player%", player.getName());
message = message.replace("%player%", player.getName());
if (command.contains("%"))
command = PlaceholderReplacer.replace(player, command);
if (message.contains("%"))
message = PlaceholderReplacer.replace(player, message);
if (player != null)
Bukkit.dispatchCommand(player, command);
Bukkit.dispatchCommand(player, message);
}
@Override
public void sendTitle(String action, UUID uuid, String title, String subTitle, int fadeIn, int stay, int fadeOut) {
public void sendTitle(String action, UUID uuid, String command, String title, String subTitle, int fadeIn, int stay, int fadeOut) {
Player player = Bukkit.getPlayer(uuid);
title = ResponseHandler.replaceArgsVariables(title, command);
subTitle = ResponseHandler.replaceArgsVariables(subTitle, command);
if (player == null)
return;
@@ -98,14 +103,15 @@ public class ModernBukkitAction implements Action {
}
@Override
public void sendActionbar(String action, UUID uuid, String text) {
public void sendActionbar(String action, UUID uuid, String command, String message) {
Player player = Bukkit.getPlayer(uuid);
message = ResponseHandler.replaceArgsVariables(message, command);
if (player == null)
return;
text = PlaceholderReplacer.replace(player, StringUtils.replace(text, "&", "§", "%player%", player.getName()));
message = PlaceholderReplacer.replace(player, StringUtils.replace(message, "&", "§", "%player%", player.getName()));
player.spigot().sendMessage(ChatMessageType.ACTION_BAR, new TextComponent(text));
player.spigot().sendMessage(ChatMessageType.ACTION_BAR, new TextComponent(message));
}
}
@@ -4,6 +4,7 @@ import de.rayzs.pat.plugin.logger.Logger;
import de.rayzs.pat.utils.Reflection;
import de.rayzs.pat.utils.StringUtils;
import de.rayzs.pat.utils.message.replacer.PlaceholderReplacer;
import de.rayzs.pat.utils.response.ResponseHandler;
import de.rayzs.pat.utils.response.action.Action;
import org.bukkit.Bukkit;
import org.bukkit.Sound;
@@ -21,33 +22,40 @@ public class OldBukkitAction implements Action {
private String versionPackage = null;
@Override
public void executeConsoleCommand(String action, UUID uuid, String command) {
public void executeConsoleCommand(String action, UUID uuid, String command, String message) {
Player player = Bukkit.getPlayer(uuid);
if(player != null) command = command.replace("%player%", player.getName());
message = ResponseHandler.replaceArgsVariables(message, command);
if (command.contains("%"))
command = PlaceholderReplacer.replace(player, command);
if(player != null)
message = message.replace("%player%", player.getName());
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command);
if (message.contains("%"))
message = PlaceholderReplacer.replace(player, message);
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), message);
}
@Override
public void executePlayerCommand(String action, UUID uuid, String command) {
public void executePlayerCommand(String action, UUID uuid, String command, String message) {
Player player = Bukkit.getPlayer(uuid);
message = ResponseHandler.replaceArgsVariables(message, command);
if (player != null)
command = command.replace("%player%", player.getName());
message = message.replace("%player%", player.getName());
if (command.contains("%"))
command = PlaceholderReplacer.replace(player, command);
if (message.contains("%"))
message = PlaceholderReplacer.replace(player, message);
if (player != null)
Bukkit.dispatchCommand(player, command);
Bukkit.dispatchCommand(player, message);
}
@Override
public void sendTitle(String action, UUID uuid, String title, String subTitle, int fadeIn, int stay, int fadeOut) {
public void sendTitle(String action, UUID uuid, String command, String title, String subTitle, int fadeIn, int stay, int fadeOut) {
Player player = Bukkit.getPlayer(uuid);
title = ResponseHandler.replaceArgsVariables(title, command);
subTitle = ResponseHandler.replaceArgsVariables(subTitle, command);
if (player == null) return;
title = PlaceholderReplacer.replace(player, StringUtils.replace(title, "&", "§", "%player%", player.getName()));
@@ -98,13 +106,14 @@ public class OldBukkitAction implements Action {
}
@Override
public void sendActionbar(String action, UUID uuid, String text) {
public void sendActionbar(String action, UUID uuid, String command, String message) {
Player player = Bukkit.getPlayer(uuid);
message = ResponseHandler.replaceArgsVariables(message, command);
if (player == null)
return;
text = PlaceholderReplacer.replace(player, StringUtils.replace(text, "&", "§", "%player%", player.getName()));
message = PlaceholderReplacer.replace(player, StringUtils.replace(message, "&", "§", "%player%", player.getName()));
try {
if (versionPackage == null)
@@ -112,7 +121,7 @@ public class OldBukkitAction implements Action {
Object entityPlayer = player.getClass().getMethod("getHandle").invoke(player);
Constructor<?> constructor = (Objects.<Class<?>>requireNonNull(Class.forName("net.minecraft.server." + versionPackage + ".PacketPlayOutChat"))).getConstructor(Class.forName("net.minecraft.server." + versionPackage + ".IChatBaseComponent"), byte.class);
Object iChatBaseComponent = (Objects.requireNonNull(Class.forName("net.minecraft.server." + versionPackage + ".IChatBaseComponent"))).getDeclaredClasses()[0].getMethod("a", String.class).invoke(null, "{\"text\":\"" + text + "\"}");
Object iChatBaseComponent = (Objects.requireNonNull(Class.forName("net.minecraft.server." + versionPackage + ".IChatBaseComponent"))).getDeclaredClasses()[0].getMethod("a", String.class).invoke(null, "{\"text\":\"" + message + "\"}");
Object actionbarPacket = constructor.newInstance(iChatBaseComponent, (byte) 2);
Object playerConnection = entityPlayer.getClass().getField("playerConnection").get(entityPlayer);
playerConnection.getClass().getMethod("sendPacket", Class.forName("net.minecraft.server." + versionPackage + ".Packet")).invoke(playerConnection, actionbarPacket);
@@ -123,6 +132,7 @@ public class OldBukkitAction implements Action {
| InvocationTargetException
| NoSuchFieldException
| InstantiationException exception) {
Logger.warning("! Failed to run action: " + action);
Logger.warning(" > Actionbars are not supported in this server version!");
}
@@ -2,6 +2,7 @@ package de.rayzs.pat.utils.response.action.impl;
import de.rayzs.pat.plugin.logger.Logger;
import de.rayzs.pat.utils.message.MessageTranslator;
import de.rayzs.pat.utils.response.ResponseHandler;
import net.kyori.adventure.text.minimessage.MiniMessage;
import de.rayzs.pat.utils.response.action.Action;
import com.velocitypowered.api.proxy.Player;
@@ -14,22 +15,33 @@ import java.time.*;
public class VelocityAction implements Action {
@Override
public void executeConsoleCommand(String action, UUID uuid, String command) {
public void executeConsoleCommand(String action, UUID uuid, String command, String message) {
Optional<Player> optPlayer = VelocityLoader.getServer().getPlayer(uuid);
if (optPlayer.isPresent()) command = command.replace("%player%", optPlayer.get().getUsername());
VelocityLoader.getServer().getCommandManager().executeAsync(VelocityLoader.getServer().getConsoleCommandSource(), command);
message = ResponseHandler.replaceArgsVariables(message, command);
if (optPlayer.isPresent())
message = message.replace("%player%", optPlayer.get().getUsername());
VelocityLoader.getServer().getCommandManager().executeAsync(VelocityLoader.getServer().getConsoleCommandSource(), message);
}
@Override
public void executePlayerCommand(String action, UUID uuid, String command) {
public void executePlayerCommand(String action, UUID uuid, String command, String message) {
Optional<Player> optPlayer = VelocityLoader.getServer().getPlayer(uuid);
if (optPlayer.isPresent()) command = command.replace("%player%", optPlayer.get().getUsername());
VelocityLoader.getServer().getCommandManager().executeAsync(optPlayer.get(), command);
message = ResponseHandler.replaceArgsVariables(message, command);
if (optPlayer.isPresent())
message = command.replace("%player%", optPlayer.get().getUsername());
VelocityLoader.getServer().getCommandManager().executeAsync(optPlayer.get(), message);
}
@Override
public void sendTitle(String action, UUID uuid, String title, String subTitle, int fadeIn, int stay, int fadeOut) {
public void sendTitle(String action, UUID uuid, String command, String title, String subTitle, int fadeIn, int stay, int fadeOut) {
Optional<Player> optPlayer = VelocityLoader.getServer().getPlayer(uuid);
title = ResponseHandler.replaceArgsVariables(title, command);
subTitle = ResponseHandler.replaceArgsVariables(subTitle, command);
if (!optPlayer.isPresent()) return;
Player player = optPlayer.get();
@@ -51,11 +63,14 @@ public class VelocityAction implements Action {
}
@Override
public void sendActionbar(String action, UUID uuid, String text) {
public void sendActionbar(String action, UUID uuid, String command, String message) {
Optional<Player> optPlayer = VelocityLoader.getServer().getPlayer(uuid);
if (!optPlayer.isPresent()) return;
message = ResponseHandler.replaceArgsVariables(message, command);
if (!optPlayer.isPresent())
return;
Player player = optPlayer.get();
player.sendActionBar(MiniMessage.miniMessage().deserialize(MessageTranslator.replaceMessage(StringUtils.replace(text, "%player%", player.getUsername()))));
player.sendActionBar(MiniMessage.miniMessage().deserialize(MessageTranslator.replaceMessage(StringUtils.replace(message, "%player%", player.getUsername()))));
}
}
@@ -1,5 +1,8 @@
package de.rayzs.pat.utils.sender;
import de.rayzs.pat.utils.group.Group;
import java.util.List;
import java.util.UUID;
public interface CommandSender {
@@ -17,5 +20,8 @@ public interface CommandSender {
String getName();
String getServerName();
List<Group> getGroups();
void updateGroups();
void sendMessage(String message);
}
@@ -1,10 +1,18 @@
package de.rayzs.pat.utils.sender;
import java.util.UUID;
import de.rayzs.pat.utils.ExpireCache;
import de.rayzs.pat.utils.group.Group;
import de.rayzs.pat.utils.group.GroupManager;
import java.util.List;
import java.util.concurrent.TimeUnit;
public abstract class CommandSenderAbstract implements CommandSender {
private static final byte KEY = (byte) 0;
private final Object senderObj;
private final ExpireCache<Byte, List<Group>> groups = new ExpireCache<>(1, TimeUnit.HOURS);
public CommandSenderAbstract(Object senderObj) {
this.senderObj = senderObj;
@@ -14,4 +22,19 @@ public abstract class CommandSenderAbstract implements CommandSender {
public Object getSenderObject() {
return senderObj;
}
@Override
public List<Group> getGroups() {
final List<Group> groupList = groups.get(KEY);
if (groupList == null) {
return groups.putAndGet(KEY, GroupManager.getPlayerGroups(getUniqueId()));
}
return groupList;
}
protected void setGroups(List<Group> groups) {
this.groups.putIgnoreIfContains(KEY, groups);
}
}
@@ -14,6 +14,10 @@ public class CommandSenderHandler {
private static final ExpireCache<UUID, CommandSender> CACHE = new ExpireCache<>(1, TimeUnit.HOURS);
public static CommandSender getSenderFromUUID(UUID uuid) {
return CACHE.get(uuid);
}
public static CommandSender from(Object senderObj) {
UUID uuid = extractUUID(senderObj);
@@ -31,8 +35,9 @@ public class CommandSenderHandler {
sender = new BukkitSender(senderObj);
}
if (sender.getUniqueId() == null)
if (sender.getUniqueId() == null) {
return null;
}
return CACHE.putAndGet(uuid, sender);
}
@@ -1,6 +1,7 @@
package de.rayzs.pat.utils.sender.impl;
import de.rayzs.pat.api.storage.Storage;
import de.rayzs.pat.utils.group.GroupManager;
import de.rayzs.pat.utils.message.MessageTranslator;
import de.rayzs.pat.utils.sender.CommandSenderAbstract;
import de.rayzs.pat.utils.sender.CommandSenderHandler;
@@ -26,6 +27,7 @@ public class BukkitSender extends CommandSenderAbstract {
this.uuid = player.getUniqueId();
this.console = false;
updateGroups();
return;
}
@@ -42,11 +44,6 @@ public class BukkitSender extends CommandSenderAbstract {
this.console = true;
}
@Override
public Object getSenderObject() {
return sender;
}
@Override
public boolean isConsole() {
return this.console;
@@ -91,4 +88,9 @@ public class BukkitSender extends CommandSenderAbstract {
sender.sendMessage(MessageTranslator.replaceMessage(sender, message));
}
@Override
public void updateGroups() {
setGroups(GroupManager.getPlayerGroups(this.uuid));
}
}
@@ -1,6 +1,7 @@
package de.rayzs.pat.utils.sender.impl;
import de.rayzs.pat.api.storage.Storage;
import de.rayzs.pat.utils.group.GroupManager;
import de.rayzs.pat.utils.message.MessageTranslator;
import de.rayzs.pat.utils.sender.CommandSenderAbstract;
import de.rayzs.pat.utils.sender.CommandSenderHandler;
@@ -27,6 +28,7 @@ public class BungeeSender extends CommandSenderAbstract {
this.uuid = player.getUniqueId();
this.console = false;
updateGroups();
return;
}
@@ -43,11 +45,6 @@ public class BungeeSender extends CommandSenderAbstract {
this.console = true;
}
@Override
public Object getSenderObject() {
return sender;
}
@Override
public boolean isConsole() {
return this.console;
@@ -94,4 +91,9 @@ public class BungeeSender extends CommandSenderAbstract {
sender.sendMessage(MessageTranslator.replaceMessage(sender, message));
}
@Override
public void updateGroups() {
setGroups(GroupManager.getPlayerGroups(this.uuid));
}
}
@@ -3,6 +3,7 @@ package de.rayzs.pat.utils.sender.impl;
import com.velocitypowered.api.command.CommandSource;
import com.velocitypowered.api.proxy.Player;
import de.rayzs.pat.api.storage.Storage;
import de.rayzs.pat.utils.group.GroupManager;
import de.rayzs.pat.utils.message.MessageTranslator;
import de.rayzs.pat.utils.sender.CommandSenderAbstract;
import de.rayzs.pat.utils.sender.CommandSenderHandler;
@@ -27,6 +28,7 @@ public class VelocitySender extends CommandSenderAbstract {
this.uuid = player.getUniqueId();
this.console = false;
updateGroups();
return;
}
@@ -43,11 +45,6 @@ public class VelocitySender extends CommandSenderAbstract {
this.console = true;
}
@Override
public Object getSenderObject() {
return sender;
}
@Override
public boolean isConsole() {
return this.console;
@@ -89,4 +86,9 @@ public class VelocitySender extends CommandSenderAbstract {
public void sendMessage(String message) {
MessageTranslator.send(sender, message);
}
@Override
public void updateGroups() {
setGroups(GroupManager.getPlayerGroups(this.uuid));
}
}
@@ -1,5 +1,7 @@
package de.rayzs.pat.utils.subargs;
import de.rayzs.pat.utils.StringUtils;
import java.util.*;
public class ArgumentBuilder {
@@ -15,7 +17,7 @@ public class ArgumentBuilder {
}
public List<String> getResult(String input) {
String firstInputArg = input.contains(" ") ? input.split(" ")[0] : input;
String firstInputArg = StringUtils.getFirstArg(input);
for (Map.Entry<String, ArgumentStack> entry : source.ARGUMENT_STACKS.entrySet()) {
if (!entry.getKey().equals(firstInputArg))
@@ -12,9 +12,12 @@ public class ArgumentSource {
public final HashMap<String, ArgumentStack> ARGUMENT_STACKS = new HashMap<>();
public ArgumentBuilder getGeneralArgument() {
/* Experimental removal
ArgumentBuilder copiedGeneralArguments = new ArgumentBuilder(this);
GENERAL.getInputs().forEach(copiedGeneralArguments::buildArgumentStacks);
return copiedGeneralArguments;
*/
return GENERAL;
}
public List<String> getOptions(String input) {
@@ -23,7 +23,9 @@ public class Arguments {
public void buildArgumentStacks(String input) {
Storage.Blacklist.BlockType type = Storage.Blacklist.BlockTypeFetcher.getType(input);
input = Storage.Blacklist.BlockTypeFetcher.modify(input, type);
if (type != Storage.Blacklist.BlockType.NEGATE) {
input = Storage.Blacklist.BlockTypeFetcher.modify(input, type);
}
switch (type) {
case TAB:
+1 -1
View File
@@ -3,7 +3,7 @@ description: Hide more than just your plugins. Hide almost everything!
website: https://www.rayzs.de/products/proantitab/page
author: Rayzs_YT
version: 2.0.4
version: 2.0.16
main: de.rayzs.pat.plugin.BungeeLoader
softDepends: [LuckPerms, PAPIProxyBridge]
@@ -54,6 +54,15 @@ handle-through-proxy:
# Enabling this will disable ALL commands except for those that are in the (group-)list.
turn-blacklist-to-whitelist: true
# This decides whether PAT ignores or detects whether a command is written in upper/-lower cased letters.
# Here are a few examples if this option is enabled:
# Example with allowing the command "HelP"
# /help --> Blocked
# /Help --> Blocked
# /HelP --> Allowed
# Pro tip: You can also just use auto-lowercase-commands feature instead. ^^
base-command-case-sensitive: true
# Here you can customize the server version that is displayed on a ping. (The text at the player-count)
# (!) Warning: It's required to use Paper or Purpur to use this feature!
# (!) Supported server versions: 1.12.2 - latest
@@ -32,6 +32,15 @@
# Syntax: effect::potionEffect::duration::amplifier
# Example: effect::BLINDNESS::45::1
# Possible variable:
# %args[from-to]% to get the command arguments
# Example if you've typed: /shop open gui user
# %args[1]% = shop
# %args[2]% = open
# %args[1-2]% = shop open
# %args[1-3]% = shop open gui
# %args[2-4]% = open gui user
# Here are a few examples:
# Example for all blocked commands.
+50 -14
View File
@@ -1,28 +1,33 @@
Confused about the display of missing parts in the console?
It's actually quite easy to read and I'll show you how its done! :D
Let's take the for the following missing path:
Missing parts are written in this format right here: xyz.zyx.idk
A more befitting example would be something like:
--> test-feature.enabled
In the config.yml, this would look like this:
test-feature:
enabled: true
test-feature:
enabled: true
Now another example with something more fitting to your case:
Here's another example of this format:
--> info.version.updated
In the config.yml, this would look like this:
info:
version:
updated: ...
info:
version:
updated: ...
-----------------------------------------------------------------------
Then what should I copy or how should I transfer the information from the one to the other config.yml?
Now that we know how things from the missing parts look like in the config.yml, let's go over to the more important part.
Inserting the missing parts to your current config.yml. But how and what exactly?
Well, it's actually quite easy. Just take a look on what is missing.
If PAT says, something like this is missing:
- test-feature.enabled
@@ -31,14 +36,45 @@ If PAT says, something like this is missing:
Then this basically just means, that the entire section for "test-feature" is missing.
In other words, check the "comparable-config.yml" and look for the "test-feature" section.
It would look like this:
It would look like this for example:
test-feature:
enabled: true
message: "Hello World"
failed: "Error ;c"
test-feature:
enabled: true
message: "Hello World"
failed: "Error ;c"
Just copy the entire thing and paste it somewhere in the config.yml.
Once you've reloaded the plugin then, using "/(b)pat reload", everything should work fine.
If something went wrong, PAT will let you know! ^^
If something went wrong, PAT will let you know! ^^
Here's a more close to your case example. Let's say your config.yml looks like this:
handle-through-proxy:
...
turn-blacklist-to-whitelist: true
custom-protocol-ping:
...
and now let's say PAT says that "base-command-case-sensitive" is missing.
Then this would be what PAT is looking for as solution:
handle-through-proxy:
...
turn-blacklist-to-whitelist: true
base-command-case-sensitive: true/false
custom-protocol-ping:
...
On how exactly it needs to be implemented can be seen in the comparison-config.yml file,
as this is the original version which would be generated by default.
@@ -40,6 +40,14 @@ disable-sync: false
# Enabling this will disable ALL commands except for those that are in the (group-)list.
turn-blacklist-to-whitelist: true
# This decides whether PAT ignores or detects whether a command is written in upper/-lower cased letters.
# Here are a few examples if this option is enabled:
# Example with allowing the command "HelP"
# /help --> Blocked
# /Help --> Blocked
# /HelP --> Allowed
base-command-case-sensitive: true
# Here you can customize the server version that is displayed on a ping. (The text at the player-count)
custom-protocol-ping:
enabled: true
@@ -26,6 +26,15 @@
# Syntax: title::title::subtitle::5::20::5
# Example: title::&aTest title::&cHello %player%!
# Possible variable:
# %args[from-to]% to get the command arguments
# Example if you've typed: /shop open gui user
# %args[1]% = shop
# %args[2]% = open
# %args[1-2]% = shop open
# %args[1-3]% = shop open gui
# %args[2-4]% = open gui user
# Here are a few examples:
# Example for all blocked commands.
+1 -1
View File
@@ -3,7 +3,7 @@ description: Hide more than just your plugins. Hide almost everything!
website: https://www.rayzs.de/products/proantitab/page
author: Rayzs_YT
version: 2.0.4
version: 2.0.16
api-version: 1.13
folia-supported: true
main: de.rayzs.pat.plugin.BukkitLoader