forked from upstream/ProAntiTab
Compare commits
67
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
11ee68fa3f | ||
|
|
2c3d3fac92 | ||
|
|
e524f898da | ||
|
|
c181cfbbc4 | ||
|
|
1110466235 | ||
|
|
a965dd231b | ||
|
|
6418e4f42a | ||
|
|
e71909fcd7 | ||
|
|
c6f9fc8d3e | ||
|
|
88cb03c82e | ||
|
|
b53678764a | ||
|
|
1f7743d089 | ||
|
|
a60b6896f7 | ||
|
|
34c33df136 | ||
|
|
ef63674b0c | ||
|
|
130af1547d | ||
|
|
cdb17c1ea8 | ||
|
|
8f4f4b6438 | ||
|
|
3a0fc6e579 | ||
|
|
e0747a5101 | ||
|
|
5741dab763 | ||
|
|
5d7a8bb4c5 | ||
|
|
786b2fa560 | ||
|
|
5cf51052d2 | ||
|
|
22eaecb17f | ||
|
|
816354bb92 | ||
|
|
2fc6d96bd9 | ||
|
|
3f472b0bf5 | ||
|
|
41417893be | ||
|
|
64a7b80ec5 | ||
|
|
65f136f2b8 | ||
|
|
618bee5e9b | ||
|
|
ea377e4841 | ||
|
|
6e1aa252c2 | ||
|
|
733f73a9b2 | ||
|
|
89b3fb65a2 | ||
|
|
148f24f516 | ||
|
|
b80ad195ca | ||
|
|
6e33bed086 | ||
|
|
245e433ab9 | ||
|
|
2c0da8670c | ||
|
|
fb509c2404 | ||
|
|
c425891587 | ||
|
|
d57a43710e | ||
|
|
8ba07fdbb2 | ||
|
|
405210a98c | ||
|
|
be3a3f0a79 | ||
|
|
50c8a46411 | ||
|
|
428ddfb78d | ||
|
|
56bd8be247 | ||
|
|
f7b2aa281e | ||
|
|
0599d504af | ||
|
|
471e0b100f | ||
|
|
52d842b27a | ||
|
|
dfc6ba91eb | ||
|
|
54d59d7b03 | ||
|
|
a4931199af | ||
|
|
02469e977c | ||
|
|
f9386fd3f1 | ||
|
|
242590f3e8 | ||
|
|
65c383491e | ||
|
|
0356c2f606 | ||
|
|
60067f75d3 | ||
|
|
e896ccb72d | ||
|
|
6c3dc58cd6 | ||
|
|
57ada83bfe | ||
|
|
8a86f05133 |
No files matched your search
+26
-39
@@ -1,42 +1,29 @@
|
||||
# Compiled class file
|
||||
*.class
|
||||
bin/
|
||||
target/
|
||||
# Maven
|
||||
/target/
|
||||
|
||||
# Log file
|
||||
*.log
|
||||
|
||||
# BlueJ files
|
||||
*.ctxt
|
||||
|
||||
# Mobile Tools for Java (J2ME)
|
||||
.mtj.tmp/
|
||||
|
||||
# Package Files #
|
||||
*.jar
|
||||
*.war
|
||||
*.nar
|
||||
*.ear
|
||||
*.zip
|
||||
*.tar.gz
|
||||
*.rar
|
||||
|
||||
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
|
||||
hs_err_pid*
|
||||
|
||||
# eclipse
|
||||
.settings
|
||||
.classpath
|
||||
.project
|
||||
|
||||
# intellij
|
||||
.idea/
|
||||
|
||||
# other
|
||||
# IntelliJ IDEA
|
||||
/.idea/
|
||||
*.iml
|
||||
run/
|
||||
*.iws
|
||||
*.ipr
|
||||
|
||||
# Gradle
|
||||
.gradle/
|
||||
build/
|
||||
!gradle/wrapper/gradle-wrapper.jar
|
||||
# Eclipse
|
||||
/.classpath
|
||||
/.project
|
||||
/.settings/
|
||||
|
||||
# VS Code
|
||||
/.vscode/
|
||||
|
||||
# Local environment and logs
|
||||
.env
|
||||
.env.*
|
||||
*.log
|
||||
*.tmp
|
||||
|
||||
# OS files
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# Maven Shade Plugin
|
||||
dependency-reduced-pom.xml
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
<groupId>de.rayzs.pat</groupId>
|
||||
<artifactId>ProAntiTab</artifactId>
|
||||
<version>2.3.4</version>
|
||||
<version>2.5.1</version>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>17</maven.compiler.source>
|
||||
@@ -14,6 +14,11 @@
|
||||
</properties>
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>papermc</id>
|
||||
<url>https://repo.papermc.io/repository/maven-public/</url>
|
||||
</repository>
|
||||
|
||||
<repository>
|
||||
<id>spigot-repo</id>
|
||||
<url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
|
||||
@@ -24,14 +29,15 @@
|
||||
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
|
||||
</repository>
|
||||
|
||||
<repository>
|
||||
<id>papermc</id>
|
||||
<url>https://repo.papermc.io/repository/maven-public/</url>
|
||||
</repository>
|
||||
|
||||
<repository>
|
||||
<id>jitpack.io</id>
|
||||
<url>https://jitpack.io</url>
|
||||
<releases>
|
||||
<enabled>true</enabled>
|
||||
</releases>
|
||||
<snapshots>
|
||||
<enabled>false</enabled>
|
||||
</snapshots>
|
||||
</repository>
|
||||
|
||||
<repository>
|
||||
@@ -72,28 +78,23 @@
|
||||
<url>https://repo.william278.net/papiproxybridge</url>
|
||||
</repository>
|
||||
|
||||
<repository>
|
||||
<id>central-snapshots</id>
|
||||
<url>https://central.sonatype.com/repository/maven-snapshots/</url>
|
||||
</repository>
|
||||
|
||||
<repository>
|
||||
<id>AlessioDP</id>
|
||||
<url>https://repo.alessiodp.com/releases/</url>
|
||||
</repository>
|
||||
|
||||
</repositories>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<dependency>
|
||||
<groupId>dev.folia</groupId>
|
||||
<artifactId>folia-api</artifactId>
|
||||
<version>1.20.1-R0.1-SNAPSHOT</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.spigotmc</groupId>
|
||||
<artifactId>spigot-api</artifactId>
|
||||
<version>1.19-R0.1-SNAPSHOT</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>io.netty</groupId>
|
||||
<artifactId>netty-all</artifactId>
|
||||
<version>4.2.0.Final</version>
|
||||
<groupId>io.papermc.paper</groupId>
|
||||
<artifactId>paper-api</artifactId>
|
||||
<version>1.21.11-R0.1-SNAPSHOT</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
@@ -104,77 +105,6 @@
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>net.md-5</groupId>
|
||||
<artifactId>bungeecord-protocol</artifactId>
|
||||
<version>1.16-R0.4</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
|
||||
<dependency>
|
||||
<groupId>com.mojang</groupId>
|
||||
<artifactId>authlib</artifactId>
|
||||
<version>4.0.43</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.github.ElgarL</groupId>
|
||||
<artifactId>groupmanager</artifactId>
|
||||
<version>3.2</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.mojang</groupId>
|
||||
<artifactId>brigadier</artifactId>
|
||||
<version>1.1.8</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.mojang</groupId>
|
||||
<artifactId>datafixerupper</artifactId>
|
||||
<version>6.0.8</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.mojang</groupId>
|
||||
<artifactId>logging</artifactId>
|
||||
<version>1.1.1</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.maven</groupId>
|
||||
<artifactId>maven-resolver-provider</artifactId>
|
||||
<version>3.8.5</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.maven.resolver</groupId>
|
||||
<artifactId>maven-resolver-connector-basic</artifactId>
|
||||
<version>1.7.3</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.maven.resolver</groupId>
|
||||
<artifactId>maven-resolver-transport-http</artifactId>
|
||||
<version>1.7.3</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-core</artifactId>
|
||||
<version>2.18.0</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>io.github.waterfallmc</groupId>
|
||||
<artifactId>waterfall-api</artifactId>
|
||||
@@ -182,13 +112,6 @@
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>net.william278</groupId>
|
||||
<artifactId>papiproxybridge</artifactId>
|
||||
<version>1.4</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.velocitypowered</groupId>
|
||||
<artifactId>velocity-api</artifactId>
|
||||
@@ -209,56 +132,64 @@
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
|
||||
<dependency>
|
||||
<groupId>org.sonatype.sisu</groupId>
|
||||
<artifactId>sisu-guice</artifactId>
|
||||
<version>2.1.7</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.spongepowered</groupId>
|
||||
<artifactId>configurate-hocon</artifactId>
|
||||
<version>4.1.2</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>net.kyori</groupId>
|
||||
<artifactId>adventure-text-minimessage</artifactId>
|
||||
<version>4.26.1</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>net.kyori</groupId>
|
||||
<artifactId>adventure-api</artifactId>
|
||||
<version>4.26.1</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>net.kyori</groupId>
|
||||
<artifactId>adventure-platform-api</artifactId>
|
||||
<version>4.4.1</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>net.kyori</groupId>
|
||||
<artifactId>adventure-platform-bungeecord</artifactId>
|
||||
<version>4.4.1</version>
|
||||
<scope>compile</scope>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>net.kyori</groupId>
|
||||
<artifactId>adventure-platform-bukkit</artifactId>
|
||||
<version>4.4.1</version>
|
||||
<scope>compile</scope>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>net.kyori</groupId>
|
||||
<artifactId>adventure-text-serializer-legacy</artifactId>
|
||||
<version>5.2.0</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>io.netty</groupId>
|
||||
<artifactId>netty-all</artifactId>
|
||||
<version>4.2.0.Final</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>5.11.4</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
|
||||
<!-- PLUGIN COMPATIBILITIES -->
|
||||
|
||||
|
||||
<!-- Permission plugins -->
|
||||
|
||||
<dependency>
|
||||
<groupId>net.luckperms</groupId>
|
||||
<artifactId>api</artifactId>
|
||||
<version>5.5</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.github.ElgarL</groupId>
|
||||
<artifactId>groupmanager</artifactId>
|
||||
<version>3.2</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
|
||||
<!-- PAPI -->
|
||||
|
||||
<dependency>
|
||||
<groupId>me.clip</groupId>
|
||||
<artifactId>placeholderapi</artifactId>
|
||||
@@ -267,12 +198,15 @@
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>net.luckperms</groupId>
|
||||
<artifactId>api</artifactId>
|
||||
<version>5.4</version>
|
||||
<groupId>net.william278</groupId>
|
||||
<artifactId>papiproxybridge</artifactId>
|
||||
<version>1.4</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
|
||||
<!-- Extras -->
|
||||
|
||||
<dependency>
|
||||
<groupId>com.viaversion</groupId>
|
||||
<artifactId>viaversion-api</artifactId>
|
||||
@@ -280,59 +214,7 @@
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>io.papermc.paper</groupId>
|
||||
<artifactId>paper-api</artifactId>
|
||||
<version>1.17-R0.1-SNAPSHOT</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>IgnoreThisJar</finalName>
|
||||
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<excludes>
|
||||
<exclude>*.txt</exclude>
|
||||
</excludes>
|
||||
</resource>
|
||||
</resources>
|
||||
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-shade-plugin</artifactId>
|
||||
<version>3.3.0</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>shade</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
<configuration>
|
||||
<finalName>ProAntiTab</finalName>
|
||||
<shadedArtifactAttached>false</shadedArtifactAttached>
|
||||
<shadedClassifierName>shaded</shadedClassifierName>
|
||||
<artifactSet>
|
||||
<excludes/>
|
||||
</artifactSet>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>17</source>
|
||||
<target>17</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
||||
</project>
|
||||
@@ -22,7 +22,7 @@ public class PATEventHandler {
|
||||
return event;
|
||||
}
|
||||
|
||||
public static FilteredSuggestionEvent callFilteredSuggestionEvents(CommandSender player, List<String> suggestions) {
|
||||
public static FilteredSuggestionEvent callFilteredSuggestionEvents(CommandSender player, HashSet<String> suggestions) {
|
||||
FilteredSuggestionEvent event = EmptyEvent.createEmptyFilteredSuggestionEvent(player, suggestions);
|
||||
|
||||
for (PATEvent patEvent : EVENTS) {
|
||||
@@ -70,7 +70,7 @@ public class PATEventHandler {
|
||||
return event;
|
||||
}
|
||||
|
||||
public static UpdatePlayerCommandsEvent callUpdatePlayerCommandsEvents(CommandSender player, List<String> commands, boolean serverBased) {
|
||||
public static UpdatePlayerCommandsEvent callUpdatePlayerCommandsEvents(CommandSender player, HashSet<String> commands, boolean serverBased) {
|
||||
UpdatePlayerCommandsEvent event = EmptyEvent.createEmptyUpdatePlayerCommandsEvent(player, commands, serverBased);
|
||||
|
||||
for (PATEvent patEvent : EVENTS) {
|
||||
@@ -143,7 +143,7 @@ public class PATEventHandler {
|
||||
};
|
||||
}
|
||||
|
||||
public static UpdatePlayerCommandsEvent createEmptyUpdatePlayerCommandsEvent(CommandSender player, List<String> commands, boolean serverBased) {
|
||||
public static UpdatePlayerCommandsEvent createEmptyUpdatePlayerCommandsEvent(CommandSender player, HashSet<String> commands, boolean serverBased) {
|
||||
return new UpdatePlayerCommandsEvent(player, commands, serverBased) {
|
||||
@Override
|
||||
public void handle(UpdatePlayerCommandsEvent event) {
|
||||
@@ -170,7 +170,7 @@ public class PATEventHandler {
|
||||
};
|
||||
}
|
||||
|
||||
public static FilteredSuggestionEvent createEmptyFilteredSuggestionEvent(CommandSender player, List<String> suggestions) {
|
||||
public static FilteredSuggestionEvent createEmptyFilteredSuggestionEvent(CommandSender player, HashSet<String> suggestions) {
|
||||
return new FilteredSuggestionEvent(player, suggestions) {
|
||||
@Override
|
||||
public void handle(FilteredSuggestionEvent event) {
|
||||
|
||||
@@ -7,24 +7,24 @@ import java.util.*;
|
||||
|
||||
public abstract class FilteredSuggestionEvent extends PATEvent<FilteredSuggestionEvent> {
|
||||
|
||||
private List<String> suggestions;
|
||||
private HashSet<String> suggestions;
|
||||
|
||||
public FilteredSuggestionEvent() {
|
||||
super(null);
|
||||
this.suggestions = null;
|
||||
}
|
||||
|
||||
public FilteredSuggestionEvent(CommandSender player, List<String> suggestions) {
|
||||
public FilteredSuggestionEvent(CommandSender player, HashSet<String> suggestions) {
|
||||
super(player);
|
||||
|
||||
this.suggestions = suggestions;
|
||||
}
|
||||
|
||||
public List<String> getSuggestions() {
|
||||
public HashSet<String> getSuggestions() {
|
||||
return suggestions;
|
||||
}
|
||||
|
||||
public void setSuggestions(List<String> suggestions) {
|
||||
public void setSuggestions(HashSet<String> suggestions) {
|
||||
this.suggestions = suggestions;
|
||||
}
|
||||
}
|
||||
@@ -3,25 +3,25 @@ package de.rayzs.pat.api.event.events;
|
||||
import de.rayzs.pat.api.event.PATEvent;
|
||||
import de.rayzs.pat.utils.sender.CommandSender;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.HashSet;
|
||||
|
||||
public abstract class UpdatePlayerCommandsEvent extends PATEvent<UpdatePlayerCommandsEvent> {
|
||||
|
||||
private List<String> commands;
|
||||
private HashSet<String> commands;
|
||||
private boolean serverBased;
|
||||
|
||||
public UpdatePlayerCommandsEvent() {
|
||||
super(null);;
|
||||
}
|
||||
|
||||
public UpdatePlayerCommandsEvent(CommandSender player, List<String> commands, boolean serverBased) {
|
||||
public UpdatePlayerCommandsEvent(CommandSender player, HashSet<String> commands, boolean serverBased) {
|
||||
super(player);
|
||||
|
||||
this.commands = commands;
|
||||
this.serverBased = serverBased;
|
||||
}
|
||||
|
||||
public List<String> getCommands() {
|
||||
public HashSet<String> getCommands() {
|
||||
return commands;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package de.rayzs.pat.api.storage;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@@ -11,6 +12,7 @@ import de.rayzs.pat.api.storage.config.messages.*;
|
||||
import de.rayzs.pat.api.storage.config.settings.*;
|
||||
import de.rayzs.pat.plugin.logger.Logger;
|
||||
import de.rayzs.pat.plugin.system.subargument.SubArgument;
|
||||
import de.rayzs.pat.utils.StringUtils;
|
||||
import de.rayzs.pat.utils.configuration.updater.ConfigUpdater;
|
||||
import de.rayzs.pat.utils.group.Group;
|
||||
import de.rayzs.pat.utils.permission.PermissionPlugin;
|
||||
@@ -90,6 +92,12 @@ public class Storage {
|
||||
Logger.warning("Read more about it here: https://rayzs.de/products/proantitab/nkppf");
|
||||
}
|
||||
|
||||
private static String generateToken() {
|
||||
byte[] bytes = new byte[32];
|
||||
new SecureRandom().nextBytes(bytes);
|
||||
return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
|
||||
}
|
||||
|
||||
public static PermissionPlugin getPermissionPlugin() {
|
||||
return PERMISSION_PLUGIN;
|
||||
}
|
||||
@@ -110,51 +118,38 @@ public class Storage {
|
||||
}
|
||||
|
||||
public static void loadToken() {
|
||||
Files.TOKEN.reload();
|
||||
|
||||
boolean invalidEnv = false;
|
||||
|
||||
if (Reflection.isProxyServer()) {
|
||||
boolean loadFromEnv = (Boolean) Files.TOKEN.getOrSet("load-from-env.enabled", false);
|
||||
String envVariable = (String) Files.TOKEN.getOrSet("load-from-env.name", "PAT_TOKEN");
|
||||
|
||||
if (loadFromEnv) {
|
||||
Logger.info("Looking up token from environment variable: " + envVariable);
|
||||
TOKEN = System.getenv(envVariable);
|
||||
|
||||
if (TOKEN != null) {
|
||||
return;
|
||||
} else invalidEnv = true;
|
||||
}
|
||||
|
||||
TOKEN = (String) Files.TOKEN.getOrSet("token", UUID.randomUUID().toString());
|
||||
|
||||
if (invalidEnv)
|
||||
Logger.warning("Environment variable not found! Using default Token from the token.yml instead.");
|
||||
|
||||
if (!Reflection.isProxyServer() && !ConfigSections.Settings.HANDLE_THROUGH_PROXY.ENABLED) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!ConfigSections.Settings.HANDLE_THROUGH_PROXY.ENABLED) {
|
||||
return;
|
||||
}
|
||||
if (Reflection.isProxyServer()) Files.TOKEN.reload();
|
||||
|
||||
boolean loadFromEnv = ConfigSections.Settings.HANDLE_THROUGH_PROXY.LOAD_FROM_ENV;
|
||||
String envVariable = ConfigSections.Settings.HANDLE_THROUGH_PROXY.ENV_NAME;
|
||||
|
||||
final boolean loadFromEnv = Reflection.isProxyServer()
|
||||
? (Boolean) Files.TOKEN.getOrSet("load-from-env.enabled", false)
|
||||
: ConfigSections.Settings.HANDLE_THROUGH_PROXY.LOAD_FROM_ENV;
|
||||
|
||||
final String envVariable = Reflection.isProxyServer()
|
||||
? (String) Files.TOKEN.getOrSet("load-from-env.name", "PAT_TOKEN")
|
||||
: ConfigSections.Settings.HANDLE_THROUGH_PROXY.ENV_NAME;
|
||||
|
||||
boolean useDefaultToken = true;
|
||||
|
||||
if (loadFromEnv) {
|
||||
Logger.info("Looking up token from environment variable: " + envVariable);
|
||||
TOKEN = System.getenv(envVariable);
|
||||
|
||||
if (TOKEN != null) {
|
||||
return;
|
||||
} else invalidEnv = true;
|
||||
|
||||
if (TOKEN == null) {
|
||||
Logger.warning("Environment variable not found! Using default Token from the file instead.");
|
||||
} else useDefaultToken = false;
|
||||
}
|
||||
|
||||
TOKEN = ConfigSections.Settings.HANDLE_THROUGH_PROXY.TOKEN;
|
||||
|
||||
if (invalidEnv)
|
||||
Logger.warning("Environment variable not found! Using default Token from the config.yml instead.");
|
||||
if (useDefaultToken) {
|
||||
TOKEN = Reflection.isProxyServer()
|
||||
? (String) Files.TOKEN.getOrSet("token", generateToken())
|
||||
: ConfigSections.Settings.HANDLE_THROUGH_PROXY.TOKEN;
|
||||
}
|
||||
}
|
||||
|
||||
public static void loadConfig() {
|
||||
@@ -168,7 +163,7 @@ public class Storage {
|
||||
|
||||
public static void reload() {
|
||||
boolean proxy = Reflection.isProxyServer();
|
||||
boolean backend = Storage.ConfigSections.Settings.HANDLE_THROUGH_PROXY.ENABLED && !proxy;
|
||||
boolean backend = ConfigSections.Settings.HANDLE_THROUGH_PROXY.ENABLED && !proxy;
|
||||
|
||||
ConfigUpdater.initialize();
|
||||
Storage.loadAll(Reflection.isProxyServer() || !backend);
|
||||
@@ -191,7 +186,7 @@ public class Storage {
|
||||
Communicator.Proxy2Backend.sendDataSync();
|
||||
}
|
||||
|
||||
Storage.Files.CUSTOM_RESPONSES.reload();
|
||||
Files.CUSTOM_RESPONSES.reload();
|
||||
ResponseHandler.update();
|
||||
|
||||
ConfigUpdater.broadcastMissingParts();
|
||||
@@ -208,8 +203,8 @@ public class Storage {
|
||||
|
||||
if (server != null) {
|
||||
|
||||
Storage.Blacklist.clearServerBlacklists(server);
|
||||
Storage.Blacklist.loadCachedServerBlacklists(server);
|
||||
Blacklist.clearServerBlacklists(server);
|
||||
Blacklist.loadCachedServerBlacklists(server);
|
||||
|
||||
final List<String> associatedServers = getServers()
|
||||
.stream()
|
||||
@@ -217,19 +212,19 @@ public class Storage {
|
||||
.toList();
|
||||
|
||||
associatedServers.forEach(s -> {
|
||||
Storage.Blacklist.clearServerBlacklists(s);
|
||||
Storage.Blacklist.loadCachedServerBlacklists(s);
|
||||
Blacklist.clearServerBlacklists(s);
|
||||
Blacklist.loadCachedServerBlacklists(s);
|
||||
});
|
||||
|
||||
associatedServers.forEach(serverName -> {
|
||||
final List<UUID> playerIds = Storage.getLoader().getPlayerIdsByServer(serverName);
|
||||
final List<String> commands = Blacklist.Collector.collectAllServerCommands(serverName);
|
||||
final HashSet<String> commands = Blacklist.Collector.collectAllServerCommands(serverName);
|
||||
|
||||
playerIds.forEach(playerId -> {
|
||||
final CommandSender sender = CommandSender.from(playerId);
|
||||
|
||||
final List<String> playerCommands = new ArrayList<>(commands);
|
||||
final List<String> groupCommands = Blacklist.Collector.collectAllPlayerGroupCommands(sender, serverName);
|
||||
final HashSet<String> playerCommands = new HashSet<>(commands);
|
||||
final HashSet<String> groupCommands = Blacklist.Collector.collectAllPlayerGroupCommands(sender, serverName);
|
||||
|
||||
playerCommands.addAll(groupCommands);
|
||||
|
||||
@@ -240,15 +235,15 @@ public class Storage {
|
||||
|
||||
} else {
|
||||
|
||||
Storage.Blacklist.Experimental.forceCacheReset();
|
||||
Blacklist.Experimental.forceCacheReset();
|
||||
final List<UUID> playerIds = Storage.getLoader().getPlayerIds();
|
||||
|
||||
playerIds.forEach(playerId -> {
|
||||
final CommandSender sender = CommandSender.from(playerId);
|
||||
|
||||
final List<String> serverCommands = Storage.Blacklist.Collector.collectAllServerCommands(sender.getServerName());
|
||||
final List<String> playerCommands = new ArrayList<>(serverCommands);
|
||||
final List<String> groupCommands = Storage.Blacklist.Collector.collectAllPlayerGroupCommands(sender, sender.getServerName());
|
||||
final HashSet<String> serverCommands = Blacklist.Collector.collectAllServerCommands(sender.getServerName());
|
||||
final HashSet<String> playerCommands = new HashSet<>(serverCommands);
|
||||
final HashSet<String> groupCommands = Blacklist.Collector.collectAllPlayerGroupCommands(sender, sender.getServerName());
|
||||
|
||||
playerCommands.addAll(groupCommands);
|
||||
|
||||
@@ -314,13 +309,12 @@ public class Storage {
|
||||
return false;
|
||||
}
|
||||
|
||||
public static boolean isServer(String originServer, String targetServer) {
|
||||
originServer = originServer.toLowerCase();
|
||||
targetServer = targetServer.toLowerCase();
|
||||
|
||||
public static boolean isServer(final String originServer, final String targetServer) {
|
||||
if (originServer.endsWith("*")) {
|
||||
originServer = originServer.substring(0, originServer.length() - 2);
|
||||
return targetServer.startsWith(originServer);
|
||||
return StringUtils.startsWithIgnoreCase(
|
||||
originServer.substring(0, originServer.length() - 2),
|
||||
targetServer
|
||||
);
|
||||
}
|
||||
|
||||
return originServer.equalsIgnoreCase(targetServer);
|
||||
@@ -346,8 +340,11 @@ public class Storage {
|
||||
|
||||
public static final AllowGroupOverrulingSection ALLOW_GROUP_OVERRULING = new AllowGroupOverrulingSection();
|
||||
public static final AutoLowercaseCommandsSection AUTO_LOWERCASE_COMMANDS = new AutoLowercaseCommandsSection();
|
||||
public static final TurnBlacklistToWhitelistSection TURN_BLACKLIST_TO_WHITELIST = new TurnBlacklistToWhitelistSection();
|
||||
public static final BlockNamespaceCommandsSection BLOCK_NAMESPACE_COMMANDS = new BlockNamespaceCommandsSection();
|
||||
public static final HandleThroughProxySection HANDLE_THROUGH_PROXY = new HandleThroughProxySection();
|
||||
public static final HidePluginChannelsSection HIDE_PLUGIN_CHANNELS = new HidePluginChannelsSection();
|
||||
public static final TabCompletionForNotExistingCommandsSection TAB_COMPLETION_FOR_NOT_EXISTING_COMMANDS = new TabCompletionForNotExistingCommandsSection();
|
||||
public static final InjectionFailedSection INJECTION_FAILED = new InjectionFailedSection();
|
||||
public static final PatchExploitSection PATCH_EXPLOITS = new PatchExploitSection();
|
||||
public static final CustomBrandSection CUSTOM_BRAND = new CustomBrandSection();
|
||||
@@ -356,9 +353,9 @@ public class Storage {
|
||||
public static final CustomVersionSection CUSTOM_VERSION = new CustomVersionSection();
|
||||
public static final DisableSyncSection DISABLE_SYNC = new DisableSyncSection();
|
||||
public static final ForwardConsoleNotificationAlertsSection FORWARD_CONSOLE_NOTIFICATIONS = new ForwardConsoleNotificationAlertsSection();
|
||||
public static final ForwardLuckPermsChangesSection FORWARD_LUCK_PERMS_CHANGES_SECTION = new ForwardLuckPermsChangesSection();
|
||||
public static final CustomProtocolPingSection CUSTOM_PROTOCOL_PING = new CustomProtocolPingSection();
|
||||
public static final CustomUnknownCommandSection CUSTOM_UNKNOWN_COMMAND = new CustomUnknownCommandSection();
|
||||
public static final TurnBlacklistToWhitelistSection TURN_BLACKLIST_TO_WHITELIST = new TurnBlacklistToWhitelistSection();
|
||||
public static final BaseCommandCaseSensitiveSection BASE_COMMAND_CASE_SENSITIVE = new BaseCommandCaseSensitiveSection();
|
||||
public static final UpdateGroupsPerWorldSection UPDATE_GROUPS_PER_WORLD = new UpdateGroupsPerWorldSection();
|
||||
public static final UpdateGroupsPerServerSection UPDATE_GROUPS_PER_SERVER = new UpdateGroupsPerServerSection();
|
||||
@@ -422,7 +419,7 @@ public class Storage {
|
||||
public static String findAndReplace(Player player, String request) {
|
||||
String result = null, param = "";
|
||||
|
||||
if(USE_PLACEHOLDERAPI) {
|
||||
if (USE_PLACEHOLDERAPI) {
|
||||
for (PlaceholderStorage storage : PLACEHOLDERS) {
|
||||
if (!storage.getRequest().startsWith(request)) continue;
|
||||
|
||||
@@ -438,7 +435,7 @@ public class Storage {
|
||||
|
||||
// Second time because of nested placeholders
|
||||
if (result != null && result.contains("%")) {
|
||||
result = PlaceholderReplacer.replace(player, result);
|
||||
result = PlaceholderReplacer.applyPlaceholders(CommandSender.from(player), result);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -459,15 +456,15 @@ public class Storage {
|
||||
* @param serverName Target server name.
|
||||
* @return List of collected commands.
|
||||
*/
|
||||
public static List<String> collectAllServerCommands(String serverName) {
|
||||
List<String> commands = new ArrayList<>(Storage.Blacklist.getBlacklist().getCommands());
|
||||
public static HashSet<String> collectAllServerCommands(String serverName) {
|
||||
HashSet<String> commands = new HashSet<>(Blacklist.getBlacklist().getCommands());
|
||||
if (!Reflection.isProxyServer())
|
||||
return commands;
|
||||
|
||||
if (serverName == null)
|
||||
return commands;
|
||||
|
||||
List<GeneralBlacklist> blacklists = Storage.Blacklist.getServerBlacklists(serverName);
|
||||
List<GeneralBlacklist> blacklists = Blacklist.getServerBlacklists(serverName);
|
||||
for (GeneralBlacklist blacklist : blacklists)
|
||||
commands.addAll(blacklist.getCommands());
|
||||
|
||||
@@ -482,9 +479,9 @@ public class Storage {
|
||||
* @param serverName Target server name.
|
||||
* @return List of collected commands.
|
||||
*/
|
||||
public static List<String> collectAllPlayerGroupCommands(CommandSender sender, String serverName) {
|
||||
final List<String> commands = new ArrayList<>();
|
||||
final List<Group> groups = GroupManager.getPlayerGroups(sender);
|
||||
public static HashSet<String> collectAllPlayerGroupCommands(CommandSender sender, String serverName) {
|
||||
final HashSet<String> commands = new HashSet<>();
|
||||
final List<Group> groups = GroupManager.getPlayerGroups(sender, sender.isOperator());
|
||||
|
||||
if (serverName == null) {
|
||||
groups.forEach(group -> commands.addAll(group.getCommands()));
|
||||
@@ -617,28 +614,63 @@ public class Storage {
|
||||
return IGNORED_SERVERS.isListed(server);
|
||||
}
|
||||
|
||||
public static boolean canPlayerAccess(CommandSender sender, List<Group> groups, String command, BlockType type) {
|
||||
return canPlayerAccess(sender, groups, command, type, null);
|
||||
public static boolean canPlayerAccess(
|
||||
final CommandSender sender,
|
||||
final List<Group> groups,
|
||||
final String command,
|
||||
final BlockType type,
|
||||
final boolean isOperator
|
||||
) {
|
||||
return canPlayerAccess(sender, groups, command, type, null, isOperator);
|
||||
}
|
||||
|
||||
public static boolean canPlayerAccessChat(CommandSender sender, List<Group> groups, String command) {
|
||||
return canPlayerAccess(sender, groups, command, BlockType.CHAT, null);
|
||||
public static boolean canPlayerAccessChat(
|
||||
final CommandSender sender,
|
||||
final List<Group> groups,
|
||||
final String command,
|
||||
final boolean isOperator
|
||||
) {
|
||||
return canPlayerAccess(sender, groups, command, BlockType.CHAT, null, isOperator);
|
||||
}
|
||||
|
||||
|
||||
public static boolean canPlayerAccessChat(CommandSender sender, List<Group> groups, String command, String server) {
|
||||
return canPlayerAccess(sender, groups, command, BlockType.CHAT, server);
|
||||
public static boolean canPlayerAccessChat(
|
||||
final CommandSender sender,
|
||||
final List<Group> groups,
|
||||
final String command,
|
||||
final String server,
|
||||
final boolean isOperator
|
||||
) {
|
||||
return canPlayerAccess(sender, groups, command, BlockType.CHAT, server, isOperator);
|
||||
}
|
||||
|
||||
public static boolean canPlayerAccessTab(CommandSender sender, List<Group> groups, String command) {
|
||||
return canPlayerAccess(sender, groups, command, BlockType.TAB, null);
|
||||
public static boolean canPlayerAccessTab(
|
||||
final CommandSender sender,
|
||||
final List<Group> groups,
|
||||
final String command,
|
||||
final boolean isOperator
|
||||
) {
|
||||
return canPlayerAccess(sender, groups, command, BlockType.TAB, null, isOperator);
|
||||
}
|
||||
|
||||
public static boolean canPlayerAccessTab(CommandSender sender, List<Group> groups, String command, String server) {
|
||||
return canPlayerAccess(sender, groups, command, BlockType.TAB, server);
|
||||
public static boolean canPlayerAccessTab(
|
||||
final CommandSender sender,
|
||||
final List<Group> groups,
|
||||
final String command,
|
||||
final String server,
|
||||
final boolean isOperator
|
||||
) {
|
||||
return canPlayerAccess(sender, groups, command, BlockType.TAB, server, isOperator);
|
||||
}
|
||||
|
||||
public static boolean canPlayerAccess(CommandSender sender, List<Group> groups, String command, BlockType type, String server) {
|
||||
public static boolean canPlayerAccess(
|
||||
final CommandSender sender,
|
||||
final List<Group> groups,
|
||||
final String command,
|
||||
final BlockType type,
|
||||
final String server,
|
||||
final boolean isOperator
|
||||
) {
|
||||
final boolean allowGroupOverruling = ConfigSections.Settings.ALLOW_GROUP_OVERRULING.ENABLED;
|
||||
final boolean blocked = isBlocked(command, type, server);
|
||||
|
||||
@@ -653,7 +685,7 @@ public class Storage {
|
||||
}
|
||||
|
||||
if (Storage.getPermissionPlugin() != PermissionPlugin.NONE) {
|
||||
if (PermissionUtil.hasBypassPermission(sender, command)) {
|
||||
if (PermissionUtil.hasBypassPermission(sender, command, isOperator)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -667,7 +699,7 @@ public class Storage {
|
||||
}
|
||||
|
||||
if (Storage.getPermissionPlugin() != PermissionPlugin.NONE) {
|
||||
if (PermissionUtil.hasBypassPermission(sender, command)) {
|
||||
if (PermissionUtil.hasBypassPermission(sender, command, isOperator)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -728,7 +760,7 @@ public class Storage {
|
||||
String command = type.toString() + unmodifiedCommand;
|
||||
|
||||
if (server == null || !isIgnoredServer(server)) {
|
||||
listed = BLACKLIST.isListed(command, false);
|
||||
listed = BLACKLIST.isListed(command);
|
||||
}
|
||||
|
||||
if (server == null) {
|
||||
@@ -749,7 +781,7 @@ public class Storage {
|
||||
break;
|
||||
}
|
||||
|
||||
listed = blacklist.isListed(command, false);
|
||||
listed = blacklist.isListed(command);
|
||||
}
|
||||
|
||||
if (!listed && type != BlockType.BOTH) {
|
||||
|
||||
+3
-3
@@ -30,10 +30,10 @@ public class BlockNamespaceCommandsSection extends ConfigStorage {
|
||||
return false;
|
||||
}
|
||||
|
||||
return StringUtils.getFirstArg(command).contains(":");
|
||||
return StringUtils.getFirstArg(command).indexOf(':') != -1;
|
||||
}
|
||||
|
||||
public boolean doesBypass(CommandSender sender) {
|
||||
return !ENABLED || PermissionUtil.hasPermission(sender, "namespace");
|
||||
public boolean doesBypass(final CommandSender sender, final boolean isOperator) {
|
||||
return !ENABLED || PermissionUtil.hasPermission(sender, "namespace", isOperator);
|
||||
}
|
||||
}
|
||||
@@ -38,6 +38,7 @@ public class CustomPluginsSection extends ConfigStorage {
|
||||
if (currentCommand.equalsIgnoreCase(command))
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
+9
-1
@@ -1,6 +1,7 @@
|
||||
package de.rayzs.pat.api.storage.config.settings;
|
||||
|
||||
import de.rayzs.pat.api.storage.storages.ConfigStorage;
|
||||
import de.rayzs.pat.plugin.logger.Logger;
|
||||
import de.rayzs.pat.utils.configuration.helper.*;
|
||||
import de.rayzs.pat.api.storage.Storage;
|
||||
import java.util.Collections;
|
||||
@@ -18,8 +19,15 @@ public class CustomUnknownCommandSection extends ConfigStorage {
|
||||
public void load() {
|
||||
super.load();
|
||||
|
||||
if(Storage.ConfigSections.Settings.HANDLE_THROUGH_PROXY.ENABLED) return;
|
||||
if (Storage.ConfigSections.Settings.HANDLE_THROUGH_PROXY.ENABLED) return;
|
||||
|
||||
|
||||
ENABLED = new ConfigSectionHelper<Boolean>(this, "enabled", true).getOrSet();
|
||||
MESSAGE = new MultipleMessagesHelper(this, "message", Collections.singletonList("&cThis command does not exist!"));
|
||||
|
||||
|
||||
if (ENABLED && Storage.ConfigSections.Settings.TURN_BLACKLIST_TO_WHITELIST.ENABLED) {
|
||||
Logger.warning("It's not recommended to use the 'custom-unknown-command' feature when you are already using ProAntiTab in WHITELIST mode! Since in this mode, all commands except the once you specifically allow, are blocked anyway. So instead, change the 'blocked' message to your desired message. It has the same effect.");
|
||||
}
|
||||
}
|
||||
}
|
||||
+22
@@ -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.Reflection;
|
||||
import de.rayzs.pat.utils.configuration.helper.ConfigSectionHelper;
|
||||
|
||||
public class ForwardLuckPermsChangesSection extends ConfigStorage {
|
||||
|
||||
public boolean ENABLED = false;
|
||||
|
||||
public ForwardLuckPermsChangesSection() {
|
||||
super("auto-forward-luckperms-changes");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void load() {
|
||||
super.load();
|
||||
if (Reflection.isProxyServer()) return;
|
||||
|
||||
ENABLED = new ConfigSectionHelper<Boolean>(this, null, false).getOrSet();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
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.Arrays;
|
||||
import java.util.HashSet;
|
||||
|
||||
public class HidePluginChannelsSection extends ConfigStorage {
|
||||
|
||||
public boolean ENABLED;
|
||||
public MultipleMessagesHelper WHITELISTED_CHANNELS;
|
||||
|
||||
private final HashSet<String> REGISTER_CHANNELS = new HashSet<>(
|
||||
Arrays.asList("register", "unregister", "minecraft:register", "minecraft:unregister")
|
||||
);
|
||||
|
||||
public HidePluginChannelsSection() {
|
||||
super("plugin-channels-hider");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void load() {
|
||||
super.load();
|
||||
ENABLED = new ConfigSectionHelper<Boolean>(this, "enabled", false).getOrSet();
|
||||
WHITELISTED_CHANNELS = new MultipleMessagesHelper(this, "whitelisted-channels", Arrays.asList(
|
||||
"minecraft:brand",
|
||||
"bungeecord:main",
|
||||
"velocity:main"
|
||||
));
|
||||
}
|
||||
|
||||
public boolean isRegisterChannel(final String channelId) {
|
||||
return REGISTER_CHANNELS.contains(channelId);
|
||||
}
|
||||
}
|
||||
+22
@@ -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.Reflection;
|
||||
import de.rayzs.pat.utils.configuration.helper.ConfigSectionHelper;
|
||||
|
||||
public class TabCompletionForNotExistingCommandsSection extends ConfigStorage {
|
||||
|
||||
public boolean ENABLED;
|
||||
|
||||
public TabCompletionForNotExistingCommandsSection() {
|
||||
super("tab-completion-for-not-existing-commands");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void load() {
|
||||
super.load();
|
||||
if (!Reflection.isProxyServer()) return;
|
||||
|
||||
ENABLED = new ConfigSectionHelper<Boolean>(this, null, false).getOrSet();
|
||||
}
|
||||
}
|
||||
@@ -9,17 +9,13 @@ import java.util.*;
|
||||
public class BlacklistStorage extends StorageTemplate implements Serializable {
|
||||
|
||||
private List<String> commands = new ArrayList<>();
|
||||
private List<String> hiddenCommands = new ArrayList<>();
|
||||
private HashSet<String> hiddenCommands = new HashSet<>();
|
||||
|
||||
public BlacklistStorage(String navigatePath) {
|
||||
super(Storage.Files.STORAGE, navigatePath);
|
||||
}
|
||||
|
||||
public boolean isListed(String command) {
|
||||
return isListed(command, false);
|
||||
}
|
||||
|
||||
public boolean isListed(String command, boolean ignoreColons) {
|
||||
final boolean caseSensitive = Storage.ConfigSections.Settings.BASE_COMMAND_CASE_SENSITIVE.ENABLED;
|
||||
final boolean turn = Storage.ConfigSections.Settings.TURN_BLACKLIST_TO_WHITELIST.ENABLED;
|
||||
|
||||
@@ -27,35 +23,18 @@ public class BlacklistStorage extends StorageTemplate implements Serializable {
|
||||
return false;
|
||||
}
|
||||
|
||||
boolean isNegated = Storage.Blacklist.BlockTypeFetcher.isNegated(command);
|
||||
final boolean isNegated = Storage.Blacklist.BlockTypeFetcher.isNegated(command);
|
||||
final boolean takeFirstArgument = !isNegated == turn;
|
||||
|
||||
if (!isNegated == turn) {
|
||||
if (takeFirstArgument) {
|
||||
command = StringUtils.getFirstArg(command);
|
||||
}
|
||||
|
||||
for (String listedCommand : hiddenCommands) {
|
||||
if (listedCommand == null)
|
||||
continue;
|
||||
|
||||
if (ignoreColons) {
|
||||
command = StringUtils.getFirstArg(command);
|
||||
|
||||
if (command.contains(":"))
|
||||
command = command.substring(command.indexOf(':'));
|
||||
}
|
||||
|
||||
if (!isNegated == turn) {
|
||||
listedCommand = StringUtils.getFirstArg(listedCommand);
|
||||
}
|
||||
|
||||
if (caseSensitive && listedCommand.equals(command)) {
|
||||
return true;
|
||||
} else if (!caseSensitive && listedCommand.equalsIgnoreCase(command)) {
|
||||
return true;
|
||||
}
|
||||
if (!caseSensitive) {
|
||||
command = command.toLowerCase();
|
||||
}
|
||||
|
||||
return false;
|
||||
return hiddenCommands.contains(command);
|
||||
}
|
||||
|
||||
public void setList(List<String> commands) {
|
||||
@@ -86,10 +65,6 @@ public class BlacklistStorage extends StorageTemplate implements Serializable {
|
||||
return commands;
|
||||
}
|
||||
|
||||
public List<String> getHiddenCommands() {
|
||||
return hiddenCommands;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save() {
|
||||
getConfig().setAndSave(getNavigatePath(), commands);
|
||||
@@ -99,10 +74,13 @@ public class BlacklistStorage extends StorageTemplate implements Serializable {
|
||||
public void load() {
|
||||
getConfig().reload();
|
||||
|
||||
final boolean caseSensitive = Storage.ConfigSections.Settings.BASE_COMMAND_CASE_SENSITIVE.ENABLED;
|
||||
|
||||
|
||||
commands = (ArrayList<String>) getConfig().getOrSet(getNavigatePath(), commands);
|
||||
|
||||
final List<String> tmpCommands = commands != null ? new ArrayList<>(commands) : new ArrayList<>();
|
||||
final Set<String> pluginListCommands = new HashSet<>(), negatedPluginListCommands = new HashSet<>();
|
||||
final HashSet<String> pluginListCommands = new HashSet<>(), negatedPluginListCommands = new HashSet<>();
|
||||
|
||||
final String pluginCommandPrefix = "plugin=";
|
||||
final String negatedPluginCommandPrefix = Storage.Blacklist.BlockType.NEGATE + pluginCommandPrefix;
|
||||
@@ -128,7 +106,8 @@ public class BlacklistStorage extends StorageTemplate implements Serializable {
|
||||
for (String pluginCommand : pluginCommands) {
|
||||
tmpCommands.remove(pluginCommand);
|
||||
|
||||
tmpCommands.add(Storage.Blacklist.BlockType.NEGATE + pluginCommand);
|
||||
pluginCommand = Storage.Blacklist.BlockType.NEGATE + pluginCommand;
|
||||
tmpCommands.add(caseSensitive ? pluginCommand : pluginCommand.toLowerCase());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -141,11 +120,36 @@ public class BlacklistStorage extends StorageTemplate implements Serializable {
|
||||
final String negated = Storage.Blacklist.BlockType.NEGATE + pluginCommand;
|
||||
|
||||
if (!commands.contains(negated) && !tmpCommands.contains(negated)) {
|
||||
tmpCommands.add(pluginCommand);
|
||||
tmpCommands.add(caseSensitive ? pluginCommand : pluginCommand.toLowerCase());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
hiddenCommands = tmpCommands;
|
||||
|
||||
if (!Storage.ConfigSections.Settings.TURN_BLACKLIST_TO_WHITELIST.ENABLED) {
|
||||
hiddenCommands = new HashSet<>(tmpCommands);
|
||||
return;
|
||||
}
|
||||
|
||||
final List<String> finalisedCommands = new ArrayList<>();
|
||||
for (String command : tmpCommands) {
|
||||
|
||||
if (Storage.Blacklist.BlockTypeFetcher.isNegated(command)) {
|
||||
finalisedCommands.add(caseSensitive ? command : StringUtils.lowercaseFirstArgument(command));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (command.contains(" ")) {
|
||||
final String firstArgument = StringUtils.getFirstArg(command);
|
||||
|
||||
if (!finalisedCommands.contains(firstArgument)) {
|
||||
finalisedCommands.add(caseSensitive ? firstArgument : firstArgument.toLowerCase());
|
||||
}
|
||||
}
|
||||
|
||||
finalisedCommands.add(caseSensitive ? command : StringUtils.lowercaseFirstArgument(command));
|
||||
}
|
||||
|
||||
hiddenCommands = new HashSet<>(finalisedCommands);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,360 +1,339 @@
|
||||
package de.rayzs.pat.plugin;
|
||||
|
||||
|
||||
import de.rayzs.pat.plugin.system.communication.cph.impl.BungeeCommunicationHandler;
|
||||
import de.rayzs.pat.plugin.system.serverbrand.CustomServerBrand;
|
||||
import de.rayzs.pat.plugin.system.communication.pmc.impl.BungeePluginMessageClient;
|
||||
import de.rayzs.pat.plugin.system.converter.StorageConverter;
|
||||
import de.rayzs.pat.plugin.command.CommandProcess;
|
||||
import de.rayzs.pat.plugin.system.serverbrand.impl.BungeeServerBrand;
|
||||
import de.rayzs.pat.plugin.packetanalyzer.proxy.BungeePacketAnalyzer;
|
||||
import de.rayzs.pat.plugin.system.subargument.SubArgument;
|
||||
import de.rayzs.pat.utils.configuration.Configurator;
|
||||
import de.rayzs.pat.utils.configuration.updater.ConfigUpdater;
|
||||
import de.rayzs.pat.utils.message.MessageTranslator;
|
||||
import de.rayzs.pat.utils.hooks.LuckPermsHook;
|
||||
import de.rayzs.pat.plugin.system.communication.Communicator;
|
||||
import de.rayzs.pat.utils.permission.PermissionUtil;
|
||||
import de.rayzs.pat.utils.response.ResponseHandler;
|
||||
import de.rayzs.pat.utils.response.action.ActionHandler;
|
||||
import de.rayzs.pat.utils.sender.CommandSender;
|
||||
import net.md_5.bungee.api.scheduler.ScheduledTask;
|
||||
import de.rayzs.pat.plugin.command.impl.BungeeCommand;
|
||||
import de.rayzs.pat.plugin.listeners.bungee.*;
|
||||
import de.rayzs.pat.utils.group.GroupManager;
|
||||
import net.md_5.bungee.api.config.ServerInfo;
|
||||
import de.rayzs.pat.plugin.metrics.bStats;
|
||||
import de.rayzs.pat.plugin.logger.Logger;
|
||||
import net.md_5.bungee.api.connection.*;
|
||||
import de.rayzs.pat.api.storage.Storage;
|
||||
import net.md_5.bungee.api.ProxyServer;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import net.md_5.bungee.api.plugin.*;
|
||||
import de.rayzs.pat.utils.*;
|
||||
import java.util.*;
|
||||
|
||||
public class BungeeLoader extends Plugin implements PluginLoader {
|
||||
|
||||
private ScheduledTask updaterTask;
|
||||
|
||||
private static Plugin plugin;
|
||||
private static java.util.logging.Logger logger;
|
||||
|
||||
private static final HashMap<String, CommandsCache> commandsCacheMap = new HashMap<>();
|
||||
|
||||
@Override
|
||||
public void onLoad() {
|
||||
Configurator.createResourcedFile("files\\proxy-config.yml", "config.yml", false);
|
||||
Configurator.createResourcedFile("files\\proxy-storage.yml", "storage.yml", false);
|
||||
Configurator.createResourcedFile("files\\proxy-placeholders.yml", "placeholders.yml", false);
|
||||
Configurator.createResourcedFile("files\\proxy-custom-responses.yml", "custom-responses.yml", false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
plugin = this;
|
||||
logger = getLogger();
|
||||
|
||||
Reflection.initialize(getProxy());
|
||||
|
||||
CommandProcess.initialize();
|
||||
ConfigUpdater.initialize();
|
||||
|
||||
Storage.initialize(this, getDescription().getVersion());
|
||||
VersionComparer.get().setCurrentVersion(Storage.CURRENT_VERSION);
|
||||
|
||||
Storage.loadAll(true);
|
||||
|
||||
MessageTranslator.initialize();
|
||||
GroupManager.initialize();
|
||||
|
||||
bStats.initialize(this);
|
||||
PluginManager manager = ProxyServer.getInstance().getPluginManager();
|
||||
|
||||
registerCommand("bungeeproantitab", "bpat");
|
||||
|
||||
manager.registerListener(this, new BungeePlayerConnectionListener());
|
||||
manager.registerListener(this, new BungeeAntiTabListener());
|
||||
manager.registerListener(this, new BungeeBlockCommandListener());
|
||||
manager.registerListener(this, new BungeePingListener());
|
||||
|
||||
if (Reflection.isPaper())
|
||||
manager.registerListener(this, new WaterfallAntiTabListener());
|
||||
|
||||
startUpdaterTask();
|
||||
|
||||
if (manager.getPlugin("LuckPerms") != null)
|
||||
LuckPermsHook.initialize();
|
||||
|
||||
if(manager.getPlugin("PAPIProxyBridge") != null) {
|
||||
Storage.USE_PAPIPROXYBRIDGE = true;
|
||||
Logger.info("Successfully hooked into PAPIProxyBridge!");
|
||||
}
|
||||
|
||||
BungeePacketAnalyzer.injectAll();
|
||||
|
||||
Storage.broadcastPermissionsPluginNotice();
|
||||
ConfigUpdater.broadcastMissingParts();
|
||||
|
||||
ActionHandler.initialize();
|
||||
SubArgument.initialize();
|
||||
|
||||
ResponseHandler.update();
|
||||
|
||||
StorageConverter.initialize();
|
||||
|
||||
CustomServerBrand.initialize(new BungeeServerBrand());
|
||||
Communicator.initialize(new BungeePluginMessageClient(), new BungeeCommunicationHandler());
|
||||
|
||||
// Reload proxy commands after 1, 5, and 15 seconds.
|
||||
for (int i : new Integer[] { 1, 5, 15 }) {
|
||||
ProxyServer.getInstance().getScheduler().schedule(this, BungeePacketAnalyzer::loadProxyCommands, i, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
BungeePacketAnalyzer.injectAll();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
BungeePacketAnalyzer.uninjectAll();
|
||||
MessageTranslator.closeAudiences();
|
||||
}
|
||||
|
||||
private static void registerCommand(String... commands) {
|
||||
for (String commandName : commands) {
|
||||
BungeeCommand command = new BungeeCommand(commandName);
|
||||
ProxyServer.getInstance().getPluginManager().registerCommand(plugin, command);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addPermission(String permission) {}
|
||||
|
||||
@Override
|
||||
public void removePermission(String permission) {}
|
||||
|
||||
@Override
|
||||
public Object getPluginObj() {
|
||||
return plugin;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateCommands() {
|
||||
Communicator.Proxy2Backend.sendUpdateCommand();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateCommands(CommandSender sender) {
|
||||
Communicator.Proxy2Backend.sendUpdateCommand(sender.getUniqueId(), sender.getServerName());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleReload() {
|
||||
BungeePacketAnalyzer.loadProxyCommands();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delayedPermissionsReload() {
|
||||
getProxy().getScheduler().schedule(this, () -> {
|
||||
PermissionUtil.reloadPermissions();
|
||||
Storage.getLoader().resetCommandsCache();
|
||||
|
||||
Communicator.Proxy2Backend.sendUpdateCommand();
|
||||
}, 1, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delayedPermissionsReload(CommandSender sender) {
|
||||
getProxy().getScheduler().schedule(this, () -> {
|
||||
PermissionUtil.reloadPermissions(sender.getUniqueId());
|
||||
Communicator.Proxy2Backend.sendUpdateCommand(sender.getUniqueId(), sender.getServerName());
|
||||
}, 1, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean doesCommandExist(String command) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getAllCommands(boolean useColons) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getConsoleSender() {
|
||||
return ProxyServer.getInstance().getConsole();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getPlayerObjByName(String name) {
|
||||
return plugin.getProxy().getPlayer(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getPlayerObjByUUID(UUID uuid) {
|
||||
return plugin.getProxy().getPlayer(uuid);
|
||||
}
|
||||
|
||||
@Override
|
||||
public HashMap<String, CommandsCache> getPerServerCommandsCacheMap() {
|
||||
return commandsCacheMap;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CommandsCache getBukkitCommandsCacheMap() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void resetCommandsCache() {
|
||||
new ArrayList<>(commandsCacheMap.values()).forEach(CommandsCache::reset);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPlayerServerName(UUID uuid) {
|
||||
final String cachedServerName = Storage.getCachedPlayerServername(uuid);
|
||||
if (cachedServerName != null) {
|
||||
return cachedServerName;
|
||||
}
|
||||
|
||||
ProxiedPlayer player = ProxyServer.getInstance().getPlayer(uuid);
|
||||
|
||||
if (player == null || player.getServer() == null || player.getServer().getInfo() == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return player.getServer().getInfo().getName();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<UUID> getPlayerIds() {
|
||||
return new ArrayList<>(ProxyServer.getInstance().getPlayers().stream().map(ProxiedPlayer::getUniqueId).toList());
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<UUID> getPlayerIdsByServer(String server) {
|
||||
List<UUID> uuids = new ArrayList<>();
|
||||
|
||||
getServerNames().stream()
|
||||
.filter(serverName -> Storage.isServer(server, serverName))
|
||||
.forEach(serverName -> {
|
||||
ServerInfo serverInfo = ProxyServer.getInstance().getServerInfo(serverName);
|
||||
|
||||
if (serverInfo == null)
|
||||
return;
|
||||
|
||||
uuids.addAll(serverInfo.getPlayers().stream().map(ProxiedPlayer::getUniqueId).toList());
|
||||
});
|
||||
|
||||
return uuids;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getOnlinePlayerNames(String serverName) {
|
||||
return new ArrayList<>(ProxyServer.getInstance().getPlayers().stream()
|
||||
.filter(player -> {
|
||||
if (player == null || player.getServer() == null || player.getServer().getInfo() == null)
|
||||
return false;
|
||||
|
||||
return player.getServer().getInfo().getName().equalsIgnoreCase(serverName);
|
||||
|
||||
}).map(ProxiedPlayer::getName).toList());
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isPlayerOnline(String playerName) {
|
||||
return ProxyServer.getInstance().getPlayer(playerName) != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean doesPlayerExist(String playerName) {
|
||||
return isPlayerOnline(playerName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getOnlinePlayerNames() {
|
||||
return new ArrayList<>(ProxyServer.getInstance().getPlayers().stream().map(ProxiedPlayer::getName).toList());
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getOfflinePlayerNames() {
|
||||
return new ArrayList<>(ProxyServer.getInstance().getPlayers().stream().map(ProxiedPlayer::getName).toList());
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getPlayerNames() {
|
||||
return new ArrayList<>(ProxyServer.getInstance().getPlayers().stream().map(ProxiedPlayer::getName).toList());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getNameByUUID(UUID uuid) {
|
||||
ProxiedPlayer player = ProxyServer.getInstance().getPlayer(uuid);
|
||||
return player != null ? player.getName() : "";
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID getUUIDByName(String playerName) {
|
||||
ProxiedPlayer player = ProxyServer.getInstance().getPlayer(playerName);
|
||||
return player != null ? player.getUniqueId() : null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getServerNames() {
|
||||
return new ArrayList<>(ProxyServer.getInstance().getServers().keySet().stream().toList());
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getFormattedPluginNames(String format) {
|
||||
List<String> pluginNames = new ArrayList<>();
|
||||
|
||||
for (Plugin plugin : ProxyServer.getInstance().getPluginManager().getPlugins()) {
|
||||
PluginDescription description = plugin.getDescription();
|
||||
|
||||
pluginNames.add(
|
||||
format.replace("%n", description.getName())
|
||||
.replace("%v", description.getVersion())
|
||||
);
|
||||
}
|
||||
|
||||
return pluginNames;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getPluginCommands(String pluginName, boolean useColons) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
public void startUpdaterTask() {
|
||||
if (!Storage.ConfigSections.Settings.UPDATE.ENABLED)
|
||||
return;
|
||||
|
||||
updaterTask = getProxy().getScheduler().schedule(this, () -> {
|
||||
|
||||
if (VersionComparer.get().computeComparison())
|
||||
getProxy().getScheduler().cancel(updaterTask);
|
||||
|
||||
}, 20L, Storage.ConfigSections.Settings.UPDATE.PERIOD, TimeUnit.MILLISECONDS);
|
||||
}
|
||||
|
||||
public static String getServerNameByPlayerUUID(UUID uuid) {
|
||||
ProxiedPlayer proxiedPlayer = ProxyServer.getInstance().getPlayer(uuid);
|
||||
if(proxiedPlayer == null) return null;
|
||||
|
||||
Server server = proxiedPlayer.getServer();
|
||||
if(server == null) return null;
|
||||
|
||||
ServerInfo serverInfo = server.getInfo();
|
||||
if(serverInfo == null) return null;
|
||||
|
||||
return serverInfo.getName();
|
||||
}
|
||||
|
||||
public static Plugin getPlugin() {
|
||||
return plugin;
|
||||
}
|
||||
|
||||
public static java.util.logging.Logger getPluginLogger() {
|
||||
return logger;
|
||||
}
|
||||
package de.rayzs.pat.plugin;
|
||||
|
||||
|
||||
import de.rayzs.pat.plugin.system.communication.cph.impl.BungeeCommunicationHandler;
|
||||
import de.rayzs.pat.plugin.system.serverbrand.CustomServerBrand;
|
||||
import de.rayzs.pat.plugin.system.communication.pmc.impl.BungeePluginMessageClient;
|
||||
import de.rayzs.pat.plugin.system.converter.StorageConverter;
|
||||
import de.rayzs.pat.plugin.command.CommandProcess;
|
||||
import de.rayzs.pat.plugin.system.serverbrand.impl.BungeeServerBrand;
|
||||
import de.rayzs.pat.plugin.packetanalyzer.proxy.BungeePacketAnalyzer;
|
||||
import de.rayzs.pat.plugin.system.subargument.SubArgument;
|
||||
import de.rayzs.pat.utils.configuration.Configurator;
|
||||
import de.rayzs.pat.utils.configuration.updater.ConfigUpdater;
|
||||
import de.rayzs.pat.utils.message.MessageHelper;
|
||||
import de.rayzs.pat.utils.hooks.LuckPermsHook;
|
||||
import de.rayzs.pat.plugin.system.communication.Communicator;
|
||||
import de.rayzs.pat.utils.response.ResponseHandler;
|
||||
import de.rayzs.pat.utils.response.action.ActionHandler;
|
||||
import de.rayzs.pat.utils.sender.CommandSender;
|
||||
import net.md_5.bungee.api.scheduler.ScheduledTask;
|
||||
import de.rayzs.pat.plugin.command.impl.BungeeCommand;
|
||||
import de.rayzs.pat.plugin.listeners.bungee.*;
|
||||
import de.rayzs.pat.utils.group.GroupManager;
|
||||
import net.md_5.bungee.api.config.ServerInfo;
|
||||
import de.rayzs.pat.plugin.metrics.bStats;
|
||||
import de.rayzs.pat.plugin.logger.Logger;
|
||||
import net.md_5.bungee.api.connection.*;
|
||||
import de.rayzs.pat.api.storage.Storage;
|
||||
import net.md_5.bungee.api.ProxyServer;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import net.md_5.bungee.api.plugin.*;
|
||||
import de.rayzs.pat.utils.*;
|
||||
import java.util.*;
|
||||
|
||||
public class BungeeLoader extends Plugin implements PluginLoader {
|
||||
|
||||
private ScheduledTask updaterTask;
|
||||
|
||||
private static Plugin plugin;
|
||||
private static java.util.logging.Logger logger;
|
||||
|
||||
private static final HashMap<String, CommandsCache> commandsCacheMap = new HashMap<>();
|
||||
|
||||
@Override
|
||||
public void onLoad() {
|
||||
Configurator.createResourcedFile("files\\proxy-config.yml", "config.yml", false);
|
||||
Configurator.createResourcedFile("files\\proxy-storage.yml", "storage.yml", false);
|
||||
Configurator.createResourcedFile("files\\proxy-placeholders.yml", "placeholders.yml", false);
|
||||
Configurator.createResourcedFile("files\\proxy-custom-responses.yml", "custom-responses.yml", false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
plugin = this;
|
||||
logger = getLogger();
|
||||
|
||||
Reflection.initialize(getProxy());
|
||||
|
||||
CommandProcess.initialize();
|
||||
ConfigUpdater.initialize();
|
||||
|
||||
Storage.initialize(this, getDescription().getVersion());
|
||||
VersionComparer.get().setCurrentVersion(Storage.CURRENT_VERSION);
|
||||
|
||||
Storage.loadAll(true);
|
||||
|
||||
MessageHelper.initialize();
|
||||
GroupManager.initialize();
|
||||
|
||||
bStats.initialize(this);
|
||||
PluginManager manager = ProxyServer.getInstance().getPluginManager();
|
||||
|
||||
ProxyServer.getInstance().getPluginManager().registerCommand(
|
||||
plugin,
|
||||
new BungeeCommand("bungeeproantitab", "proantitab.use", "bpat")
|
||||
);
|
||||
|
||||
manager.registerListener(this, new BungeePlayerConnectionListener());
|
||||
manager.registerListener(this, new BungeeAntiTabListener());
|
||||
manager.registerListener(this, new BungeeBlockCommandListener());
|
||||
manager.registerListener(this, new BungeePingListener());
|
||||
|
||||
if (Reflection.isPaper())
|
||||
manager.registerListener(this, new WaterfallAntiTabListener());
|
||||
|
||||
startUpdaterTask();
|
||||
|
||||
if (manager.getPlugin("LuckPerms") != null) {
|
||||
manager.registerListener(this, new BungeeLuckPermsWarning());
|
||||
LuckPermsHook.initialize();
|
||||
}
|
||||
|
||||
if(manager.getPlugin("PAPIProxyBridge") != null) {
|
||||
Storage.USE_PAPIPROXYBRIDGE = true;
|
||||
Logger.info("Successfully hooked into PAPIProxyBridge!");
|
||||
}
|
||||
|
||||
BungeePacketAnalyzer.injectAll();
|
||||
|
||||
Storage.broadcastPermissionsPluginNotice();
|
||||
ConfigUpdater.broadcastMissingParts();
|
||||
|
||||
ActionHandler.initialize();
|
||||
SubArgument.initialize();
|
||||
|
||||
ResponseHandler.update();
|
||||
|
||||
StorageConverter.initialize();
|
||||
|
||||
CustomServerBrand.initialize(new BungeeServerBrand());
|
||||
Communicator.initialize(new BungeePluginMessageClient(), new BungeeCommunicationHandler());
|
||||
|
||||
// Reload proxy commands after 1, 5, and 15 seconds.
|
||||
for (int i : new Integer[] { 1, 5, 15 }) {
|
||||
ProxyServer.getInstance().getScheduler().schedule(this, BungeePacketAnalyzer::loadProxyCommands, i, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
BungeePacketAnalyzer.injectAll();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
BungeePacketAnalyzer.uninjectAll();
|
||||
MessageHelper.closeAudiences();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addPermission(String permission) {}
|
||||
|
||||
@Override
|
||||
public void removePermission(String permission) {}
|
||||
|
||||
@Override
|
||||
public Object getPluginObj() {
|
||||
return plugin;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateCommands() {
|
||||
Communicator.Proxy2Backend.sendUpdateCommand();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateCommands(CommandSender sender) {
|
||||
Communicator.Proxy2Backend.sendUpdateCommand(sender.getUniqueId(), sender.getServerName());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleReload() {
|
||||
BungeePacketAnalyzer.loadProxyCommands();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean doesCommandExist(String command) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getAllCommands(boolean useColons) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getConsoleSender() {
|
||||
return ProxyServer.getInstance().getConsole();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getPlayerObjByName(String name) {
|
||||
return plugin.getProxy().getPlayer(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getPlayerObjByUUID(UUID uuid) {
|
||||
return plugin.getProxy().getPlayer(uuid);
|
||||
}
|
||||
|
||||
@Override
|
||||
public HashMap<String, CommandsCache> getPerServerCommandsCacheMap() {
|
||||
return commandsCacheMap;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CommandsCache getBukkitCommandsCacheMap() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void resetCommandsCache() {
|
||||
new ArrayList<>(commandsCacheMap.values()).forEach(CommandsCache::reset);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPlayerServerName(UUID uuid) {
|
||||
final String cachedServerName = Storage.getCachedPlayerServername(uuid);
|
||||
if (cachedServerName != null) {
|
||||
return cachedServerName;
|
||||
}
|
||||
|
||||
ProxiedPlayer player = ProxyServer.getInstance().getPlayer(uuid);
|
||||
|
||||
if (player == null || player.getServer() == null || player.getServer().getInfo() == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return player.getServer().getInfo().getName();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<UUID> getPlayerIds() {
|
||||
return new ArrayList<>(ProxyServer.getInstance().getPlayers().stream().map(ProxiedPlayer::getUniqueId).toList());
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<UUID> getPlayerIdsByServer(String server) {
|
||||
List<UUID> uuids = new ArrayList<>();
|
||||
|
||||
getServerNames().stream()
|
||||
.filter(serverName -> Storage.isServer(server, serverName))
|
||||
.forEach(serverName -> {
|
||||
ServerInfo serverInfo = ProxyServer.getInstance().getServerInfo(serverName);
|
||||
|
||||
if (serverInfo == null)
|
||||
return;
|
||||
|
||||
uuids.addAll(serverInfo.getPlayers().stream().map(ProxiedPlayer::getUniqueId).toList());
|
||||
});
|
||||
|
||||
return uuids;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getOnlinePlayerNames(String serverName) {
|
||||
return new ArrayList<>(ProxyServer.getInstance().getPlayers().stream()
|
||||
.filter(player -> {
|
||||
if (player == null || player.getServer() == null || player.getServer().getInfo() == null)
|
||||
return false;
|
||||
|
||||
return player.getServer().getInfo().getName().equalsIgnoreCase(serverName);
|
||||
|
||||
}).map(ProxiedPlayer::getName).toList());
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isPlayerOnline(String playerName) {
|
||||
return ProxyServer.getInstance().getPlayer(playerName) != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean doesPlayerExist(String playerName) {
|
||||
return isPlayerOnline(playerName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getOnlinePlayerNames() {
|
||||
return new ArrayList<>(ProxyServer.getInstance().getPlayers().stream().map(ProxiedPlayer::getName).toList());
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getOfflinePlayerNames() {
|
||||
return new ArrayList<>(ProxyServer.getInstance().getPlayers().stream().map(ProxiedPlayer::getName).toList());
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getPlayerNames() {
|
||||
return new ArrayList<>(ProxyServer.getInstance().getPlayers().stream().map(ProxiedPlayer::getName).toList());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getNameByUUID(UUID uuid) {
|
||||
ProxiedPlayer player = ProxyServer.getInstance().getPlayer(uuid);
|
||||
return player != null ? player.getName() : "";
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID getUUIDByName(String playerName) {
|
||||
ProxiedPlayer player = ProxyServer.getInstance().getPlayer(playerName);
|
||||
return player != null ? player.getUniqueId() : null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getServerNames() {
|
||||
return new ArrayList<>(ProxyServer.getInstance().getServers().keySet().stream().toList());
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getFormattedPluginNames(String format) {
|
||||
List<String> pluginNames = new ArrayList<>();
|
||||
|
||||
for (Plugin plugin : ProxyServer.getInstance().getPluginManager().getPlugins()) {
|
||||
PluginDescription description = plugin.getDescription();
|
||||
|
||||
pluginNames.add(
|
||||
format.replace("%n", description.getName())
|
||||
.replace("%v", description.getVersion())
|
||||
);
|
||||
}
|
||||
|
||||
return pluginNames;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getPluginCommands(String pluginName, boolean useColons) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
public void startUpdaterTask() {
|
||||
if (!Storage.ConfigSections.Settings.UPDATE.ENABLED)
|
||||
return;
|
||||
|
||||
updaterTask = getProxy().getScheduler().schedule(this, () -> {
|
||||
|
||||
if (VersionComparer.get().computeComparison())
|
||||
getProxy().getScheduler().cancel(updaterTask);
|
||||
|
||||
}, 1, Storage.ConfigSections.Settings.UPDATE.PERIOD, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
public static String getServerNameByPlayerUUID(UUID uuid) {
|
||||
ProxiedPlayer proxiedPlayer = ProxyServer.getInstance().getPlayer(uuid);
|
||||
if(proxiedPlayer == null) return null;
|
||||
|
||||
Server server = proxiedPlayer.getServer();
|
||||
if(server == null) return null;
|
||||
|
||||
ServerInfo serverInfo = server.getInfo();
|
||||
if(serverInfo == null) return null;
|
||||
|
||||
return serverInfo.getName();
|
||||
}
|
||||
|
||||
public static Plugin getPlugin() {
|
||||
return plugin;
|
||||
}
|
||||
|
||||
public static java.util.logging.Logger getPluginLogger() {
|
||||
return logger;
|
||||
}
|
||||
}
|
||||
@@ -34,10 +34,6 @@ public interface PluginLoader {
|
||||
HashMap<String, CommandsCache> getPerServerCommandsCacheMap();
|
||||
CommandsCache getBukkitCommandsCacheMap();
|
||||
|
||||
void delayedPermissionsReload();
|
||||
|
||||
void delayedPermissionsReload(CommandSender sender);
|
||||
|
||||
void resetCommandsCache();
|
||||
|
||||
List<String> getServerNames();
|
||||
|
||||
@@ -1,363 +1,335 @@
|
||||
package de.rayzs.pat.plugin;
|
||||
|
||||
import com.velocitypowered.api.event.proxy.ProxyInitializeEvent;
|
||||
import com.velocitypowered.api.proxy.Player;
|
||||
import com.velocitypowered.api.proxy.ServerConnection;
|
||||
import com.velocitypowered.api.proxy.server.RegisteredServer;
|
||||
import de.rayzs.pat.plugin.system.communication.cph.impl.VelocityCommunicationHandler;
|
||||
import de.rayzs.pat.plugin.system.serverbrand.CustomServerBrand;
|
||||
import de.rayzs.pat.plugin.system.communication.pmc.impl.VelocityPluginMessageClient;
|
||||
import de.rayzs.pat.plugin.packetanalyzer.proxy.VelocityPacketAnalyzer;
|
||||
import de.rayzs.pat.plugin.system.converter.StorageConverter;
|
||||
import de.rayzs.pat.plugin.system.serverbrand.impl.VelocityServerBrand;
|
||||
import de.rayzs.pat.plugin.command.CommandProcess;
|
||||
import de.rayzs.pat.plugin.system.subargument.SubArgument;
|
||||
import de.rayzs.pat.utils.CommandsCache;
|
||||
import de.rayzs.pat.plugin.metrics.impl.VelocityMetrics;
|
||||
import com.velocitypowered.api.scheduler.ScheduledTask;
|
||||
import de.rayzs.pat.utils.configuration.Configurator;
|
||||
import de.rayzs.pat.utils.configuration.updater.ConfigUpdater;
|
||||
import de.rayzs.pat.utils.permission.PermissionUtil;
|
||||
import de.rayzs.pat.plugin.command.impl.VelocityCommand;
|
||||
import de.rayzs.pat.utils.message.MessageTranslator;
|
||||
import de.rayzs.pat.plugin.system.communication.Communicator;
|
||||
import de.rayzs.pat.utils.hooks.LuckPermsHook;
|
||||
import com.velocitypowered.api.proxy.ProxyServer;
|
||||
import de.rayzs.pat.plugin.listeners.velocity.*;
|
||||
import de.rayzs.pat.utils.group.GroupManager;
|
||||
import de.rayzs.pat.utils.VersionComparer;
|
||||
import de.rayzs.pat.plugin.logger.Logger;
|
||||
import com.velocitypowered.api.plugin.*;
|
||||
import de.rayzs.pat.api.storage.Storage;
|
||||
import com.velocitypowered.api.event.*;
|
||||
import de.rayzs.pat.utils.Reflection;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
|
||||
import com.google.inject.Inject;
|
||||
import de.rayzs.pat.utils.response.ResponseHandler;
|
||||
import de.rayzs.pat.utils.response.action.ActionHandler;
|
||||
import de.rayzs.pat.utils.sender.CommandSender;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
@Plugin(name = "ProAntiTab",
|
||||
id = "proantitab",
|
||||
version = "2.3.4",
|
||||
authors = "Rayzs_YT",
|
||||
description = "Hides more than just your plugins.",
|
||||
url = "https://www.rayzs.de/products/proantitab/page",
|
||||
dependencies = {
|
||||
@Dependency(id = "luckperms", optional = true),
|
||||
@Dependency(id = "papiproxybridge", optional = true)
|
||||
})
|
||||
public class VelocityLoader implements PluginLoader {
|
||||
|
||||
private static VelocityLoader instance;
|
||||
|
||||
private static ProxyServer server;
|
||||
private static org.slf4j.Logger logger;
|
||||
|
||||
private final EventManager manager;
|
||||
private final VelocityMetrics.Factory metricsFactory;
|
||||
private ScheduledTask updaterTask;
|
||||
|
||||
private static final HashMap<String, CommandsCache> commandsCacheMap = new HashMap<>();
|
||||
|
||||
@Inject
|
||||
public VelocityLoader(ProxyServer server, org.slf4j.Logger logger, VelocityMetrics.Factory metricsFactory) {
|
||||
VelocityLoader.instance = this;
|
||||
VelocityLoader.server = server;
|
||||
VelocityLoader.logger = logger;
|
||||
|
||||
this.manager = server.getEventManager();
|
||||
this.metricsFactory = metricsFactory;
|
||||
}
|
||||
|
||||
@Subscribe
|
||||
public void onProxyInitialization(ProxyInitializeEvent event) {
|
||||
PluginContainer pluginContainer = server.getPluginManager().getPlugin("proantitab").get();
|
||||
|
||||
Configurator.createResourcedFile("files\\proxy-config.yml", "config.yml", false);
|
||||
Configurator.createResourcedFile("files\\proxy-storage.yml", "storage.yml", false);
|
||||
Configurator.createResourcedFile("files\\proxy-placeholders.yml", "placeholders.yml", false);
|
||||
Configurator.createResourcedFile("files\\proxy-custom-responses.yml", "custom-responses.yml", false);
|
||||
|
||||
Reflection.initialize(server);
|
||||
|
||||
CommandProcess.initialize();
|
||||
ConfigUpdater.initialize();
|
||||
|
||||
Storage.initialize(this, pluginContainer.getDescription().getVersion().get());
|
||||
VersionComparer.get().setCurrentVersion(Storage.CURRENT_VERSION);
|
||||
|
||||
Storage.loadAll(true);
|
||||
MessageTranslator.initialize();
|
||||
GroupManager.initialize();
|
||||
|
||||
metricsFactory.make(this, 21638);
|
||||
|
||||
server.getCommandManager().register("bpat", new VelocityCommand(), "bungeeproantitab");
|
||||
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));
|
||||
|
||||
startUpdaterTask();
|
||||
|
||||
if (server.getPluginManager().getPlugin("luckperms").isPresent())
|
||||
LuckPermsHook.initialize();
|
||||
|
||||
if (server.getPluginManager().getPlugin("papiproxybridge").isPresent()) {
|
||||
Storage.USE_PAPIPROXYBRIDGE = true;
|
||||
Logger.info("Successfully hooked into PAPIProxyBridge!");
|
||||
}
|
||||
|
||||
Storage.broadcastPermissionsPluginNotice();
|
||||
ConfigUpdater.broadcastMissingParts();
|
||||
|
||||
ActionHandler.initialize();
|
||||
SubArgument.initialize();
|
||||
|
||||
ResponseHandler.update();
|
||||
|
||||
StorageConverter.initialize();
|
||||
CustomServerBrand.initialize(new VelocityServerBrand());
|
||||
|
||||
Communicator.initialize(new VelocityPluginMessageClient(), new VelocityCommunicationHandler());
|
||||
|
||||
VelocityPacketAnalyzer.injectAll();
|
||||
}
|
||||
|
||||
public static org.slf4j.Logger getPluginLogger() {
|
||||
return logger;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addPermission(String permission) {}
|
||||
|
||||
@Override
|
||||
public void removePermission(String permission) {}
|
||||
|
||||
@Override
|
||||
public Object getPluginObj() {
|
||||
return instance;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateCommands() {
|
||||
Communicator.Proxy2Backend.sendUpdateCommand();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateCommands(CommandSender sender) {
|
||||
Communicator.Proxy2Backend.sendUpdateCommand(sender.getUniqueId(), sender.getServerName());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delayedPermissionsReload() {
|
||||
server.getScheduler().buildTask(VelocityLoader.instance, () -> {
|
||||
PermissionUtil.reloadPermissions();
|
||||
resetCommandsCache();
|
||||
|
||||
Communicator.Proxy2Backend.sendUpdateCommand();
|
||||
}).delay(1, TimeUnit.SECONDS).schedule();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delayedPermissionsReload(CommandSender sender) {
|
||||
server.getScheduler().buildTask(VelocityLoader.instance, () -> {
|
||||
PermissionUtil.reloadPermissions(sender);
|
||||
|
||||
Communicator.Proxy2Backend.sendUpdateCommand(sender.getUniqueId(), sender.getServerName());
|
||||
}).delay(1, TimeUnit.SECONDS).schedule();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleReload() {}
|
||||
|
||||
@Override
|
||||
public boolean doesCommandExist(String command) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getAllCommands(boolean useColons) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getConsoleSender() {
|
||||
return server.getConsoleCommandSource();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getPlayerObjByName(String name) {
|
||||
return server.getPlayer(name).orElse(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getPlayerObjByUUID(UUID uuid) {
|
||||
return server.getPlayer(uuid).orElse(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void resetCommandsCache() {
|
||||
new ArrayList<>(commandsCacheMap.values()).forEach(CommandsCache::reset);
|
||||
}
|
||||
|
||||
@Override
|
||||
public HashMap<String, CommandsCache> getPerServerCommandsCacheMap() {
|
||||
return commandsCacheMap;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CommandsCache getBukkitCommandsCacheMap() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isPlayerOnline(String playerName) {
|
||||
return server.getPlayer(playerName).isPresent();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean doesPlayerExist(String playerName) {
|
||||
return isPlayerOnline(playerName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<UUID> getPlayerIdsByServer(String serverName) {
|
||||
List<UUID> uuids = new ArrayList<>();
|
||||
|
||||
getServerNames().stream()
|
||||
.filter(originServerName -> Storage.isServer(serverName, originServerName))
|
||||
.forEach(originServerName -> {
|
||||
Optional<RegisteredServer> optionalRegServerInfo = server.getServer(serverName);
|
||||
|
||||
if (optionalRegServerInfo.isEmpty())
|
||||
return;
|
||||
|
||||
RegisteredServer regServerInfo = optionalRegServerInfo.get();
|
||||
uuids.addAll(regServerInfo.getPlayersConnected().stream().map(Player::getUniqueId).toList());
|
||||
});
|
||||
|
||||
return uuids;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPlayerServerName(UUID uuid) {
|
||||
final String cachedServerName = Storage.getCachedPlayerServername(uuid);
|
||||
if (cachedServerName != null) {
|
||||
return cachedServerName;
|
||||
}
|
||||
|
||||
Optional<Player> optPlayer = server.getPlayer(uuid);
|
||||
|
||||
if (optPlayer.isEmpty())
|
||||
return null;
|
||||
|
||||
Player player = optPlayer.get();
|
||||
Optional<ServerConnection> optConnection = player.getCurrentServer();
|
||||
|
||||
if (optConnection.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
ServerConnection connection = optConnection.get();
|
||||
return connection.getServer().getServerInfo().getName();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<UUID> getPlayerIds() {
|
||||
return server.getAllPlayers().stream().map(Player::getUniqueId).toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getOnlinePlayerNames(String serverName) {
|
||||
return server.getAllPlayers().stream()
|
||||
.filter(player -> {
|
||||
Optional<ServerConnection> optConnection = player.getCurrentServer();
|
||||
|
||||
if (optConnection.isEmpty())
|
||||
return false;
|
||||
|
||||
ServerConnection connection = optConnection.get();
|
||||
return connection.getServer().getServerInfo().getName().equalsIgnoreCase(serverName);
|
||||
|
||||
}).map(Player::getUsername).toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getOnlinePlayerNames() {
|
||||
return server.getAllPlayers().stream().map(Player::getUsername).toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getOfflinePlayerNames() {
|
||||
return server.getAllPlayers().stream().map(Player::getUsername).toList();
|
||||
}
|
||||
|
||||
public List<String> getPlayerNames() {
|
||||
return server.getAllPlayers().stream().map(Player::getUsername).toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getNameByUUID(UUID uuid) {
|
||||
Player player = server.getPlayer(uuid).orElse(null);
|
||||
return player != null ? player.getUsername() : "";
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID getUUIDByName(String playerName) {
|
||||
Player player = server.getPlayer(playerName).orElse(null);
|
||||
return player != null ? player.getUniqueId() : null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getServerNames() {
|
||||
return new ArrayList<>(server.getAllServers().stream().map(registeredServer -> registeredServer.getServerInfo().getName()).toList());
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getFormattedPluginNames(String format) {
|
||||
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(
|
||||
format.replace("%n", pluginName)
|
||||
.replace("%v", version)
|
||||
);
|
||||
}
|
||||
|
||||
return pluginNames;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getPluginCommands(String pluginName, boolean useColons) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
public void startUpdaterTask() {
|
||||
if (!Storage.ConfigSections.Settings.UPDATE.ENABLED) return;
|
||||
|
||||
updaterTask = server.getScheduler().buildTask(this, () -> {
|
||||
|
||||
if (VersionComparer.get().computeComparison())
|
||||
updaterTask.cancel();
|
||||
|
||||
}).delay(1, TimeUnit.SECONDS).repeat(Storage.ConfigSections.Settings.UPDATE.PERIOD, TimeUnit.SECONDS).schedule();
|
||||
}
|
||||
|
||||
public static ProxyServer getServer() {
|
||||
return server;
|
||||
}
|
||||
|
||||
public static VelocityLoader getInstance() {
|
||||
return instance;
|
||||
}
|
||||
}
|
||||
package de.rayzs.pat.plugin;
|
||||
|
||||
import com.velocitypowered.api.event.proxy.ProxyInitializeEvent;
|
||||
import com.velocitypowered.api.proxy.Player;
|
||||
import com.velocitypowered.api.proxy.ServerConnection;
|
||||
import com.velocitypowered.api.proxy.server.RegisteredServer;
|
||||
import de.rayzs.pat.plugin.system.communication.cph.impl.VelocityCommunicationHandler;
|
||||
import de.rayzs.pat.plugin.system.serverbrand.CustomServerBrand;
|
||||
import de.rayzs.pat.plugin.system.communication.pmc.impl.VelocityPluginMessageClient;
|
||||
import de.rayzs.pat.plugin.packetanalyzer.proxy.VelocityPacketAnalyzer;
|
||||
import de.rayzs.pat.plugin.system.converter.StorageConverter;
|
||||
import de.rayzs.pat.plugin.system.serverbrand.impl.VelocityServerBrand;
|
||||
import de.rayzs.pat.plugin.command.CommandProcess;
|
||||
import de.rayzs.pat.plugin.system.subargument.SubArgument;
|
||||
import de.rayzs.pat.utils.CommandsCache;
|
||||
import de.rayzs.pat.plugin.metrics.impl.VelocityMetrics;
|
||||
import com.velocitypowered.api.scheduler.ScheduledTask;
|
||||
import de.rayzs.pat.utils.configuration.Configurator;
|
||||
import de.rayzs.pat.utils.configuration.updater.ConfigUpdater;
|
||||
import de.rayzs.pat.plugin.command.impl.VelocityCommand;
|
||||
import de.rayzs.pat.utils.message.MessageHelper;
|
||||
import de.rayzs.pat.plugin.system.communication.Communicator;
|
||||
import de.rayzs.pat.utils.hooks.LuckPermsHook;
|
||||
import com.velocitypowered.api.proxy.ProxyServer;
|
||||
import de.rayzs.pat.plugin.listeners.velocity.*;
|
||||
import de.rayzs.pat.utils.group.GroupManager;
|
||||
import de.rayzs.pat.utils.VersionComparer;
|
||||
import de.rayzs.pat.plugin.logger.Logger;
|
||||
import com.velocitypowered.api.plugin.*;
|
||||
import de.rayzs.pat.api.storage.Storage;
|
||||
import com.velocitypowered.api.event.*;
|
||||
import de.rayzs.pat.utils.Reflection;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
|
||||
import com.google.inject.Inject;
|
||||
import de.rayzs.pat.utils.response.ResponseHandler;
|
||||
import de.rayzs.pat.utils.response.action.ActionHandler;
|
||||
import de.rayzs.pat.utils.sender.CommandSender;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public class VelocityLoader implements PluginLoader {
|
||||
|
||||
private static VelocityLoader instance;
|
||||
|
||||
private static ProxyServer server;
|
||||
private static org.slf4j.Logger logger;
|
||||
|
||||
private final EventManager manager;
|
||||
private final VelocityMetrics.Factory metricsFactory;
|
||||
private ScheduledTask updaterTask;
|
||||
|
||||
private static final HashMap<String, CommandsCache> commandsCacheMap = new HashMap<>();
|
||||
|
||||
@Inject
|
||||
public VelocityLoader(ProxyServer server, org.slf4j.Logger logger, VelocityMetrics.Factory metricsFactory) {
|
||||
VelocityLoader.instance = this;
|
||||
VelocityLoader.server = server;
|
||||
VelocityLoader.logger = logger;
|
||||
|
||||
this.manager = server.getEventManager();
|
||||
this.metricsFactory = metricsFactory;
|
||||
}
|
||||
|
||||
@Subscribe
|
||||
public void onProxyInitialization(ProxyInitializeEvent event) {
|
||||
PluginContainer pluginContainer = server.getPluginManager().getPlugin("proantitab").get();
|
||||
|
||||
Configurator.createResourcedFile("files\\proxy-config.yml", "config.yml", false);
|
||||
Configurator.createResourcedFile("files\\proxy-storage.yml", "storage.yml", false);
|
||||
Configurator.createResourcedFile("files\\proxy-placeholders.yml", "placeholders.yml", false);
|
||||
Configurator.createResourcedFile("files\\proxy-custom-responses.yml", "custom-responses.yml", false);
|
||||
|
||||
Reflection.initialize(server);
|
||||
|
||||
CommandProcess.initialize();
|
||||
ConfigUpdater.initialize();
|
||||
|
||||
Storage.initialize(this, pluginContainer.getDescription().getVersion().get());
|
||||
VersionComparer.get().setCurrentVersion(Storage.CURRENT_VERSION);
|
||||
|
||||
Storage.loadAll(true);
|
||||
MessageHelper.initialize();
|
||||
GroupManager.initialize();
|
||||
|
||||
metricsFactory.make(this, 21638);
|
||||
|
||||
server.getCommandManager().register("bpat", new VelocityCommand(), "bungeeproantitab");
|
||||
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));
|
||||
|
||||
startUpdaterTask();
|
||||
|
||||
if (server.getPluginManager().getPlugin("luckperms").isPresent()) {
|
||||
server.getEventManager().register(this, new VelocityLuckPermsWarning(server));
|
||||
LuckPermsHook.initialize();
|
||||
}
|
||||
|
||||
if (server.getPluginManager().getPlugin("papiproxybridge").isPresent()) {
|
||||
Storage.USE_PAPIPROXYBRIDGE = true;
|
||||
Logger.info("Successfully hooked into PAPIProxyBridge!");
|
||||
}
|
||||
|
||||
Storage.broadcastPermissionsPluginNotice();
|
||||
ConfigUpdater.broadcastMissingParts();
|
||||
|
||||
ActionHandler.initialize();
|
||||
SubArgument.initialize();
|
||||
|
||||
ResponseHandler.update();
|
||||
|
||||
StorageConverter.initialize();
|
||||
CustomServerBrand.initialize(new VelocityServerBrand());
|
||||
|
||||
Communicator.initialize(new VelocityPluginMessageClient(), new VelocityCommunicationHandler());
|
||||
|
||||
VelocityPacketAnalyzer.injectAll();
|
||||
}
|
||||
|
||||
public static org.slf4j.Logger getPluginLogger() {
|
||||
return logger;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addPermission(String permission) {}
|
||||
|
||||
@Override
|
||||
public void removePermission(String permission) {}
|
||||
|
||||
@Override
|
||||
public Object getPluginObj() {
|
||||
return instance;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateCommands() {
|
||||
Communicator.Proxy2Backend.sendUpdateCommand();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateCommands(CommandSender sender) {
|
||||
Communicator.Proxy2Backend.sendUpdateCommand(sender.getUniqueId(), sender.getServerName());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleReload() {}
|
||||
|
||||
@Override
|
||||
public boolean doesCommandExist(String command) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getAllCommands(boolean useColons) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getConsoleSender() {
|
||||
return server.getConsoleCommandSource();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getPlayerObjByName(String name) {
|
||||
return server.getPlayer(name).orElse(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getPlayerObjByUUID(UUID uuid) {
|
||||
return server.getPlayer(uuid).orElse(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void resetCommandsCache() {
|
||||
new ArrayList<>(commandsCacheMap.values()).forEach(CommandsCache::reset);
|
||||
}
|
||||
|
||||
@Override
|
||||
public HashMap<String, CommandsCache> getPerServerCommandsCacheMap() {
|
||||
return commandsCacheMap;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CommandsCache getBukkitCommandsCacheMap() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isPlayerOnline(String playerName) {
|
||||
return server.getPlayer(playerName).isPresent();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean doesPlayerExist(String playerName) {
|
||||
return isPlayerOnline(playerName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<UUID> getPlayerIdsByServer(String serverName) {
|
||||
List<UUID> uuids = new ArrayList<>();
|
||||
|
||||
getServerNames().stream()
|
||||
.filter(originServerName -> Storage.isServer(serverName, originServerName))
|
||||
.forEach(originServerName -> {
|
||||
Optional<RegisteredServer> optionalRegServerInfo = server.getServer(serverName);
|
||||
|
||||
if (optionalRegServerInfo.isEmpty())
|
||||
return;
|
||||
|
||||
RegisteredServer regServerInfo = optionalRegServerInfo.get();
|
||||
uuids.addAll(regServerInfo.getPlayersConnected().stream().map(Player::getUniqueId).toList());
|
||||
});
|
||||
|
||||
return uuids;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPlayerServerName(UUID uuid) {
|
||||
final String cachedServerName = Storage.getCachedPlayerServername(uuid);
|
||||
if (cachedServerName != null) {
|
||||
return cachedServerName;
|
||||
}
|
||||
|
||||
Optional<Player> optPlayer = server.getPlayer(uuid);
|
||||
|
||||
if (optPlayer.isEmpty())
|
||||
return null;
|
||||
|
||||
Player player = optPlayer.get();
|
||||
Optional<ServerConnection> optConnection = player.getCurrentServer();
|
||||
|
||||
if (optConnection.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
ServerConnection connection = optConnection.get();
|
||||
return connection.getServer().getServerInfo().getName();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<UUID> getPlayerIds() {
|
||||
return server.getAllPlayers().stream().map(Player::getUniqueId).toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getOnlinePlayerNames(String serverName) {
|
||||
return server.getAllPlayers().stream()
|
||||
.filter(player -> {
|
||||
Optional<ServerConnection> optConnection = player.getCurrentServer();
|
||||
|
||||
if (optConnection.isEmpty())
|
||||
return false;
|
||||
|
||||
ServerConnection connection = optConnection.get();
|
||||
return connection.getServer().getServerInfo().getName().equalsIgnoreCase(serverName);
|
||||
|
||||
}).map(Player::getUsername).toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getOnlinePlayerNames() {
|
||||
return server.getAllPlayers().stream().map(Player::getUsername).toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getOfflinePlayerNames() {
|
||||
return server.getAllPlayers().stream().map(Player::getUsername).toList();
|
||||
}
|
||||
|
||||
public List<String> getPlayerNames() {
|
||||
return server.getAllPlayers().stream().map(Player::getUsername).toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getNameByUUID(UUID uuid) {
|
||||
Player player = server.getPlayer(uuid).orElse(null);
|
||||
return player != null ? player.getUsername() : "";
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID getUUIDByName(String playerName) {
|
||||
Player player = server.getPlayer(playerName).orElse(null);
|
||||
return player != null ? player.getUniqueId() : null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getServerNames() {
|
||||
return new ArrayList<>(server.getAllServers().stream().map(registeredServer -> registeredServer.getServerInfo().getName()).toList());
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getFormattedPluginNames(String format) {
|
||||
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(
|
||||
format.replace("%n", pluginName)
|
||||
.replace("%v", version)
|
||||
);
|
||||
}
|
||||
|
||||
return pluginNames;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getPluginCommands(String pluginName, boolean useColons) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
public void startUpdaterTask() {
|
||||
if (!Storage.ConfigSections.Settings.UPDATE.ENABLED) return;
|
||||
|
||||
updaterTask = server.getScheduler().buildTask(this, () -> {
|
||||
|
||||
if (VersionComparer.get().computeComparison())
|
||||
updaterTask.cancel();
|
||||
|
||||
}).delay(1, TimeUnit.SECONDS).repeat(Storage.ConfigSections.Settings.UPDATE.PERIOD, TimeUnit.SECONDS).schedule();
|
||||
}
|
||||
|
||||
public static ProxyServer getServer() {
|
||||
return server;
|
||||
}
|
||||
|
||||
public static VelocityLoader getInstance() {
|
||||
return instance;
|
||||
}
|
||||
}
|
||||
@@ -66,9 +66,10 @@ public class CommandProcess {
|
||||
}
|
||||
|
||||
public static void handleCommand(Object senderObj, String[] args, String label) {
|
||||
CommandSender sender = CommandSender.from(senderObj);
|
||||
final CommandSender sender = CommandSender.from(senderObj);
|
||||
final boolean isOperator = sender.isOperator();
|
||||
|
||||
if (!PermissionUtil.hasPermissionWithResponse(sender, "use"))
|
||||
if (!PermissionUtil.hasPermissionWithResponse(sender, "use", isOperator))
|
||||
return;
|
||||
|
||||
if (args.length == 0) {
|
||||
@@ -109,7 +110,7 @@ public class CommandProcess {
|
||||
}
|
||||
|
||||
ProCommand command = optCommand.get();
|
||||
if (!PermissionUtil.hasPermissionWithResponse(sender, command.getName()))
|
||||
if (!PermissionUtil.hasPermissionWithResponse(sender, command.getName(), isOperator))
|
||||
return;
|
||||
|
||||
if (!command.execute(sender, commandArgs)) {
|
||||
@@ -137,7 +138,7 @@ public class CommandProcess {
|
||||
}
|
||||
|
||||
ProCommand command = optCommand.get();
|
||||
if (!PermissionUtil.hasPermissionWithResponse(sender, command.getName()))
|
||||
if (!PermissionUtil.hasPermissionWithResponse(sender, command.getName(), isOperator))
|
||||
return;
|
||||
|
||||
if (!command.execute(sender, commandArgs)) {
|
||||
@@ -147,10 +148,11 @@ public class CommandProcess {
|
||||
}
|
||||
|
||||
public static List<String> handleTabComplete(Object senderObj, String[] args) {
|
||||
CommandSender sender = CommandSender.from(senderObj);
|
||||
List<String> result = new ArrayList<>();
|
||||
final CommandSender sender = CommandSender.from(senderObj);
|
||||
final boolean isOperator = sender.isOperator();
|
||||
final List<String> result = new ArrayList<>();
|
||||
|
||||
if (!PermissionUtil.hasPermission(sender, "use"))
|
||||
if (!PermissionUtil.hasPermission(sender, "use", isOperator))
|
||||
return result;
|
||||
|
||||
if (args.length <= 1) {
|
||||
@@ -164,7 +166,7 @@ public class CommandProcess {
|
||||
if (!Reflection.isProxyServer() && cmd.isProxyOnly())
|
||||
return false;
|
||||
|
||||
return PermissionUtil.hasPermission(sender, cmd.getName());
|
||||
return PermissionUtil.hasPermission(sender, cmd.getName(), isOperator);
|
||||
})
|
||||
.forEach(cmd -> {
|
||||
result.add(cmd.getName());
|
||||
@@ -185,7 +187,7 @@ public class CommandProcess {
|
||||
.filter(cmd -> {
|
||||
|
||||
if (Reflection.isProxyServer() && cmd.isServerCommand())
|
||||
return PermissionUtil.hasPermission(sender, cmd.getName());
|
||||
return PermissionUtil.hasPermission(sender, cmd.getName(), isOperator);
|
||||
|
||||
return false;
|
||||
})
|
||||
@@ -206,7 +208,7 @@ public class CommandProcess {
|
||||
optCommand = COMMANDS.stream().filter(cmd -> {
|
||||
|
||||
if (Reflection.isProxyServer() && cmd.isServerCommand()) {
|
||||
return cmd.isCommand(servCommandName) && PermissionUtil.hasPermission(sender, cmd.getName());
|
||||
return cmd.isCommand(servCommandName) && PermissionUtil.hasPermission(sender, cmd.getName(), isOperator);
|
||||
}
|
||||
|
||||
return false;
|
||||
@@ -231,7 +233,7 @@ public class CommandProcess {
|
||||
if (optCommand.isPresent()) {
|
||||
ProCommand command = optCommand.get();
|
||||
|
||||
if (PermissionUtil.hasPermission(sender, command.getName())) {
|
||||
if (PermissionUtil.hasPermission(sender, command.getName(), isOperator)) {
|
||||
List<String> cmdCompletions = command.tabComplete(sender, commandArgs);
|
||||
result.addAll(cmdCompletions != null ? cmdCompletions : List.of());
|
||||
}
|
||||
|
||||
@@ -25,7 +25,7 @@ public class UpdateCommand extends ProCommand {
|
||||
if (playerObj != null) {
|
||||
CommandSender s = CommandSender.from(playerObj);
|
||||
|
||||
assert s != null;
|
||||
Objects.requireNonNull(s);
|
||||
PermissionUtil.reloadPermissions(s);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -6,8 +6,8 @@ import net.md_5.bungee.api.plugin.*;
|
||||
|
||||
public class BungeeCommand extends Command implements TabExecutor {
|
||||
|
||||
public BungeeCommand(String name) {
|
||||
super(name);
|
||||
public BungeeCommand(String name, String permission, String... aliases) {
|
||||
super(name, permission, aliases);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -11,6 +11,11 @@ public class VelocityCommand implements SimpleCommand {
|
||||
CommandProcess.handleCommand(invocation.source(), invocation.arguments(), "bpat");
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasPermission(Invocation invocation) {
|
||||
return invocation.source().hasPermission("proantitab.use");
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> suggest(Invocation invocation) {
|
||||
return CommandProcess.handleTabComplete(invocation.source(), invocation.arguments());
|
||||
|
||||
@@ -1,98 +1,99 @@
|
||||
package de.rayzs.pat.plugin.listeners.bukkit;
|
||||
|
||||
import de.rayzs.pat.api.event.events.FilteredSuggestionEvent;
|
||||
import de.rayzs.pat.utils.group.Group;
|
||||
import de.rayzs.pat.utils.group.GroupManager;
|
||||
import de.rayzs.pat.utils.scheduler.PATScheduler;
|
||||
import de.rayzs.pat.utils.sender.CommandSender;
|
||||
import org.bukkit.event.player.PlayerCommandSendEvent;
|
||||
import de.rayzs.pat.utils.permission.PermissionUtil;
|
||||
import de.rayzs.pat.utils.hooks.ViaVersionHook;
|
||||
import de.rayzs.pat.api.event.PATEventHandler;
|
||||
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 java.util.*;
|
||||
|
||||
public class BukkitAntiTabListener implements Listener {
|
||||
|
||||
private final List<UUID> knownOperators = new ArrayList<>();
|
||||
|
||||
|
||||
@EventHandler (priority = EventPriority.LOWEST)
|
||||
public void onPlayerCommandSend(PlayerCommandSendEvent event) {
|
||||
final Player player = event.getPlayer();
|
||||
final CommandSender sender = CommandSender.from(player);
|
||||
final UUID uuid = player.getUniqueId();
|
||||
|
||||
|
||||
if (Storage.ConfigSections.Settings.HANDLE_THROUGH_PROXY.ENABLED) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (player.isOp()) {
|
||||
if (!knownOperators.contains(uuid)) {
|
||||
knownOperators.add(uuid);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.getCommands().isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
Storage.getLoader().getBukkitCommandsCacheMap().handleCommands(Storage.ConfigSections.Settings.TURN_BLACKLIST_TO_WHITELIST.ENABLED
|
||||
? Storage.Blacklist.getBlacklist().getCommands()
|
||||
: BukkitLoader.getAllCommands()
|
||||
);
|
||||
|
||||
if (!player.isOp() && knownOperators.contains(uuid)) {
|
||||
knownOperators.remove(uuid);
|
||||
PermissionUtil.reloadPermissions(sender);
|
||||
}
|
||||
|
||||
if (PermissionUtil.hasBypassPermission(sender)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (Reflection.isCraftbukkit() && !Bukkit.getOnlinePlayers().contains(player)) {
|
||||
event.getCommands().clear();
|
||||
|
||||
PATScheduler.createScheduler(player::updateCommands, 10);
|
||||
return;
|
||||
}
|
||||
|
||||
final List<Group> groups = GroupManager.getPlayerGroups(sender);
|
||||
final List<String> playerCommands = Storage.getLoader().getBukkitCommandsCacheMap().getPlayerCommands(new ArrayList<>(event.getCommands()), sender, groups);
|
||||
final FilteredSuggestionEvent filteredSuggestionEvent = PATEventHandler.callFilteredSuggestionEvents(sender, playerCommands);
|
||||
|
||||
event.getCommands().clear();
|
||||
|
||||
if (filteredSuggestionEvent.isCancelled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
event.getCommands().addAll(filteredSuggestionEvent.getSuggestions());
|
||||
|
||||
if (Storage.ConfigSections.Settings.CUSTOM_PLUGIN.ALWAYS_TAB_COMPLETABLE) {
|
||||
event.getCommands().addAll(Storage.ConfigSections.Settings.CUSTOM_PLUGIN.COMMANDS.getLines());
|
||||
}
|
||||
|
||||
if (Storage.ConfigSections.Settings.CUSTOM_VERSION.ALWAYS_TAB_COMPLETABLE) {
|
||||
event.getCommands().addAll(Storage.ConfigSections.Settings.CUSTOM_VERSION.COMMANDS.getLines());
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean notUpdatablePlayer(UUID uuid) {
|
||||
return Storage.USE_VIAVERSION && Reflection.isAtLeast(1, 16) && ViaVersionHook.getPlayerProtocol(uuid) < 754;
|
||||
}
|
||||
|
||||
public void updateCommands(Player player) {
|
||||
if (!notUpdatablePlayer(player.getUniqueId()))
|
||||
player.updateCommands();
|
||||
}
|
||||
}
|
||||
package de.rayzs.pat.plugin.listeners.bukkit;
|
||||
|
||||
import de.rayzs.pat.api.event.events.FilteredSuggestionEvent;
|
||||
import de.rayzs.pat.utils.group.Group;
|
||||
import de.rayzs.pat.utils.group.GroupManager;
|
||||
import de.rayzs.pat.utils.scheduler.PATScheduler;
|
||||
import de.rayzs.pat.utils.sender.CommandSender;
|
||||
import org.bukkit.event.player.PlayerCommandSendEvent;
|
||||
import de.rayzs.pat.utils.permission.PermissionUtil;
|
||||
import de.rayzs.pat.utils.hooks.ViaVersionHook;
|
||||
import de.rayzs.pat.api.event.PATEventHandler;
|
||||
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 java.util.*;
|
||||
|
||||
public class BukkitAntiTabListener implements Listener {
|
||||
|
||||
private final List<UUID> knownOperators = new ArrayList<>();
|
||||
|
||||
|
||||
@EventHandler (priority = EventPriority.LOWEST)
|
||||
public void onPlayerCommandSend(PlayerCommandSendEvent event) {
|
||||
|
||||
if (Storage.ConfigSections.Settings.HANDLE_THROUGH_PROXY.ENABLED) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
final Player player = event.getPlayer();
|
||||
final CommandSender sender = CommandSender.from(player);
|
||||
final UUID uuid = player.getUniqueId();
|
||||
final boolean isOperator = player.isOp();
|
||||
|
||||
if (player.isOp()) {
|
||||
if (!knownOperators.contains(uuid)) {
|
||||
knownOperators.add(uuid);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.getCommands().isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
Storage.getLoader().getBukkitCommandsCacheMap().handleCommands(Storage.ConfigSections.Settings.TURN_BLACKLIST_TO_WHITELIST.ENABLED
|
||||
? Storage.Blacklist.getBlacklist().getCommands()
|
||||
: BukkitLoader.getAllCommands()
|
||||
);
|
||||
|
||||
if (!isOperator && knownOperators.contains(uuid)) {
|
||||
knownOperators.remove(uuid);
|
||||
PermissionUtil.reloadPermissions(sender);
|
||||
}
|
||||
|
||||
if (PermissionUtil.hasBypassPermission(sender, isOperator)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (Reflection.isBukkit() && !Bukkit.getOnlinePlayers().contains(player)) {
|
||||
event.getCommands().clear();
|
||||
|
||||
PATScheduler.createScheduler(player::updateCommands, 10);
|
||||
return;
|
||||
}
|
||||
|
||||
final List<Group> groups = GroupManager.getPlayerGroups(sender, isOperator);
|
||||
final HashSet<String> playerCommands = Storage.getLoader().getBukkitCommandsCacheMap().getPlayerCommands(new ArrayList<>(event.getCommands()), sender, groups, isOperator);
|
||||
final FilteredSuggestionEvent filteredSuggestionEvent = PATEventHandler.callFilteredSuggestionEvents(sender, playerCommands);
|
||||
|
||||
if (filteredSuggestionEvent.isCancelled()) {
|
||||
event.getCommands().clear();
|
||||
return;
|
||||
}
|
||||
|
||||
event.getCommands().removeIf(command -> !filteredSuggestionEvent.getSuggestions().contains(command));
|
||||
|
||||
if (Storage.ConfigSections.Settings.CUSTOM_PLUGIN.ALWAYS_TAB_COMPLETABLE) {
|
||||
event.getCommands().addAll(Storage.ConfigSections.Settings.CUSTOM_PLUGIN.COMMANDS.getLines());
|
||||
}
|
||||
|
||||
if (Storage.ConfigSections.Settings.CUSTOM_VERSION.ALWAYS_TAB_COMPLETABLE) {
|
||||
event.getCommands().addAll(Storage.ConfigSections.Settings.CUSTOM_VERSION.COMMANDS.getLines());
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean notUpdatablePlayer(UUID uuid) {
|
||||
return Storage.USE_VIAVERSION && Reflection.isAtLeast(1, 16) && ViaVersionHook.getPlayerProtocol(uuid) < 754;
|
||||
}
|
||||
|
||||
public void updateCommands(Player player) {
|
||||
if (!notUpdatablePlayer(player.getUniqueId()))
|
||||
player.updateCommands();
|
||||
}
|
||||
}
|
||||
+226
-227
@@ -1,227 +1,226 @@
|
||||
package de.rayzs.pat.plugin.listeners.bukkit;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import de.rayzs.pat.plugin.system.subargument.SubArgument;
|
||||
import de.rayzs.pat.utils.group.Group;
|
||||
import de.rayzs.pat.utils.group.GroupManager;
|
||||
import de.rayzs.pat.utils.response.ResponseHandler;
|
||||
import de.rayzs.pat.utils.sender.CommandSender;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
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.logger.Logger;
|
||||
import de.rayzs.pat.utils.StringUtils;
|
||||
import de.rayzs.pat.utils.message.MessageTranslator;
|
||||
import de.rayzs.pat.utils.permission.PermissionUtil;
|
||||
|
||||
public class BukkitBlockCommandListener implements Listener {
|
||||
|
||||
@EventHandler (priority = EventPriority.HIGHEST)
|
||||
public void onUnknownCommandRecognition(PlayerCommandPreprocessEvent event) {
|
||||
final Player player = event.getPlayer();
|
||||
final CommandSender sender = CommandSender.from(player);
|
||||
final 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(sender))
|
||||
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());
|
||||
}
|
||||
|
||||
@EventHandler (priority = EventPriority.LOWEST)
|
||||
public void onPlayerCommandProcess(PlayerCommandPreprocessEvent event) {
|
||||
final Player player = event.getPlayer();
|
||||
final CommandSender sender = CommandSender.from(player);
|
||||
|
||||
final String commandFirstArg = StringUtils.getFirstArg(event.getMessage());
|
||||
|
||||
if (Storage.ConfigSections.Settings.AUTO_LOWERCASE_COMMANDS.isCommand(commandFirstArg)) {
|
||||
String command = event.getMessage();
|
||||
|
||||
if (command.contains(" ")) {
|
||||
String[] args = command.split(" ");
|
||||
args[0] = args[0].toLowerCase();
|
||||
command = String.join(" ", args);
|
||||
} else command = command.toLowerCase();
|
||||
|
||||
if (!commandFirstArg.equals(command)) {
|
||||
player.chat(command);
|
||||
event.setCancelled(true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
World world = player.getWorld();
|
||||
String command = event.getMessage(),
|
||||
worldName = world.getName();
|
||||
|
||||
command = command.substring(1);
|
||||
final String commandWithArguments = command;
|
||||
|
||||
command = StringUtils.getFirstArg(command);
|
||||
|
||||
if (Storage.ConfigSections.Settings.HANDLE_THROUGH_PROXY.ENABLED) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (PermissionUtil.hasBypassPermission(sender, command)) {
|
||||
return;
|
||||
}
|
||||
|
||||
final String displayCommand = StringUtils.replaceTriggers(command, "", "\\", "<", ">", "&");
|
||||
|
||||
List<String> notificationMessage = MessageTranslator.replaceMessageList(
|
||||
Storage.ConfigSections.Messages.NOTIFICATION.ALERT,
|
||||
"%player%", player.getName(),
|
||||
"%command%", displayCommand,
|
||||
"%world%", worldName);
|
||||
|
||||
if (Storage.ConfigSections.Settings.CUSTOM_PLUGIN.isCommand(command)) {
|
||||
|
||||
MessageTranslator.send(
|
||||
player,
|
||||
Storage.ConfigSections.Settings.CUSTOM_PLUGIN.MESSAGE,
|
||||
"%command%", StringUtils.getFirstArg(displayCommand)
|
||||
);
|
||||
|
||||
if (Storage.SEND_CONSOLE_NOTIFICATION)
|
||||
Logger.info(notificationMessage);
|
||||
|
||||
Storage.NOTIFY_PLAYERS.forEach(uuid -> {
|
||||
Object p = Storage.getLoader().getPlayerObjByUUID(uuid);
|
||||
if (p != null) {
|
||||
MessageTranslator.send(p, notificationMessage);
|
||||
}
|
||||
});
|
||||
|
||||
event.setCancelled(true);
|
||||
return;
|
||||
}
|
||||
|
||||
if (Storage.ConfigSections.Settings.CUSTOM_VERSION.isCommand(command)) {
|
||||
|
||||
MessageTranslator.send(
|
||||
player,
|
||||
Storage.ConfigSections.Settings.CUSTOM_VERSION.MESSAGE,
|
||||
"%command%", StringUtils.getFirstArg(displayCommand)
|
||||
);
|
||||
|
||||
if (Storage.SEND_CONSOLE_NOTIFICATION)
|
||||
Logger.info(notificationMessage);
|
||||
|
||||
Storage.NOTIFY_PLAYERS.forEach(uuid -> {
|
||||
Object p = Storage.getLoader().getPlayerObjByUUID(uuid);
|
||||
if (p != null) {
|
||||
MessageTranslator.send(p, notificationMessage);
|
||||
}
|
||||
});
|
||||
|
||||
event.setCancelled(true);
|
||||
return;
|
||||
}
|
||||
|
||||
final boolean cancelBlockedCommand = Storage.ConfigSections.Settings.CANCEL_COMMAND.ENABLED;
|
||||
final List<Group> groups = GroupManager.getPlayerGroups(sender);
|
||||
|
||||
boolean allowed = Storage.Blacklist.canPlayerAccessChat(sender, groups, command);
|
||||
boolean blockedNamespace = false;
|
||||
|
||||
if (!Storage.ConfigSections.Settings.BLOCK_NAMESPACE_COMMANDS.doesBypass(sender)) {
|
||||
blockedNamespace = cancelBlockedCommand
|
||||
? Storage.ConfigSections.Settings.BLOCK_NAMESPACE_COMMANDS.isCommand(command)
|
||||
: Storage.ConfigSections.Settings.BLOCK_NAMESPACE_COMMANDS.doesAlwaysBlock(command);
|
||||
|
||||
if (blockedNamespace) allowed = false;
|
||||
}
|
||||
|
||||
if (!Storage.ConfigSections.Settings.CANCEL_COMMAND.ENABLED && !blockedNamespace) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!allowed) {
|
||||
ExecuteCommandEvent executeCommandEvent = PATEventHandler.callExecuteCommandEvents(
|
||||
sender,
|
||||
event.getMessage(),
|
||||
true,
|
||||
!Storage.ConfigSections.Settings.TURN_BLACKLIST_TO_WHITELIST.ENABLED
|
||||
);
|
||||
|
||||
if (executeCommandEvent.isBlocked()) {
|
||||
event.setCancelled(true);
|
||||
|
||||
MessageTranslator.send(
|
||||
sender,
|
||||
ResponseHandler.getResponse(
|
||||
sender.getUniqueId(),
|
||||
sender.getName(),
|
||||
sender.getServerName(),
|
||||
event.getMessage(),
|
||||
Storage.ConfigSections.Settings.CANCEL_COMMAND.BASE_COMMAND_RESPONSE.getLines()
|
||||
), "%command%", StringUtils.getFirstArg(displayCommand)
|
||||
);
|
||||
|
||||
if (!executeCommandEvent.doesNotify())
|
||||
return;
|
||||
|
||||
if (Storage.SEND_CONSOLE_NOTIFICATION)
|
||||
Logger.info(notificationMessage);
|
||||
|
||||
Storage.NOTIFY_PLAYERS.stream().filter(uuid -> Bukkit.getServer().getPlayer(uuid) != null).forEach(uuid -> {
|
||||
Player target = Bukkit.getServer().getPlayer(uuid);
|
||||
MessageTranslator.send(target, notificationMessage);
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
if (executeCommandEvent.isCancelled())
|
||||
return;
|
||||
}
|
||||
|
||||
ExecuteCommandEvent executeCommandEvent = PATEventHandler.callExecuteCommandEvents(
|
||||
sender,
|
||||
event.getMessage(),
|
||||
SubArgument.get().getExecuteHandler().handleCommandExecution(sender, event.getMessage()),
|
||||
false
|
||||
);
|
||||
|
||||
if (executeCommandEvent.isBlocked()) {
|
||||
event.setCancelled(true);
|
||||
|
||||
MessageTranslator.send(
|
||||
sender,
|
||||
ResponseHandler.getResponse(
|
||||
sender.getUniqueId(),
|
||||
sender.getName(),
|
||||
sender.getServerName(),
|
||||
event.getMessage()
|
||||
),
|
||||
"%command%",
|
||||
StringUtils.replaceTriggers(
|
||||
commandWithArguments, "",
|
||||
"\\", "<", ">", "&"
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
package de.rayzs.pat.plugin.listeners.bukkit;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import de.rayzs.pat.plugin.system.subargument.SubArgument;
|
||||
import de.rayzs.pat.utils.group.Group;
|
||||
import de.rayzs.pat.utils.group.GroupManager;
|
||||
import de.rayzs.pat.utils.response.ResponseHandler;
|
||||
import de.rayzs.pat.utils.sender.CommandSender;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
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.logger.Logger;
|
||||
import de.rayzs.pat.utils.StringUtils;
|
||||
import de.rayzs.pat.utils.message.MessageHelper;
|
||||
import de.rayzs.pat.utils.permission.PermissionUtil;
|
||||
|
||||
public class BukkitBlockCommandListener implements Listener {
|
||||
|
||||
@EventHandler (priority = EventPriority.HIGHEST)
|
||||
public void onUnknownCommandRecognition(PlayerCommandPreprocessEvent event) {
|
||||
final Player player = event.getPlayer();
|
||||
final CommandSender sender = CommandSender.from(player);
|
||||
final World world = player.getWorld();
|
||||
final boolean isOperator = player.isOp();
|
||||
|
||||
String rawCommand = StringUtils.getFirstArg(event.getMessage()),
|
||||
command = rawCommand.substring(1);
|
||||
|
||||
if (!Storage.ConfigSections.Settings.CUSTOM_UNKNOWN_COMMAND.ENABLED || event.isCancelled()) return;
|
||||
|
||||
if (PermissionUtil.hasBypassPermission(sender, isOperator))
|
||||
return;
|
||||
|
||||
if (Storage.getLoader().doesCommandExist(command))
|
||||
return;
|
||||
|
||||
event.setCancelled(true);
|
||||
MessageHelper.sendMessage(sender, Storage.ConfigSections.Settings.CUSTOM_UNKNOWN_COMMAND.MESSAGE, "%command%", command, "%world%", world.getName());
|
||||
}
|
||||
|
||||
@EventHandler (priority = EventPriority.LOWEST)
|
||||
public void onPlayerCommandProcess(PlayerCommandPreprocessEvent event) {
|
||||
final Player player = event.getPlayer();
|
||||
final CommandSender sender = CommandSender.from(player);
|
||||
final boolean isOperator = player.isOp();
|
||||
|
||||
final String commandFirstArg = StringUtils.getFirstArg(event.getMessage());
|
||||
|
||||
if (Storage.ConfigSections.Settings.AUTO_LOWERCASE_COMMANDS.isCommand(commandFirstArg)) {
|
||||
String command = event.getMessage();
|
||||
|
||||
if (command.contains(" ")) {
|
||||
String[] args = command.split(" ");
|
||||
args[0] = args[0].toLowerCase();
|
||||
command = String.join(" ", args);
|
||||
} else command = command.toLowerCase();
|
||||
|
||||
if (!commandFirstArg.equals(command)) {
|
||||
player.chat(command);
|
||||
event.setCancelled(true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
World world = player.getWorld();
|
||||
String command = event.getMessage(),
|
||||
worldName = world.getName();
|
||||
|
||||
command = command.substring(1);
|
||||
final String commandWithArguments = command;
|
||||
|
||||
command = StringUtils.getFirstArg(command);
|
||||
|
||||
if (Storage.ConfigSections.Settings.HANDLE_THROUGH_PROXY.ENABLED) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (PermissionUtil.hasBypassPermission(sender, command, isOperator)) {
|
||||
return;
|
||||
}
|
||||
|
||||
final String displayCommand = StringUtils.replaceTriggers(command, "", "\\", "<", ">", "&");
|
||||
final String notificationMessage = StringUtils.replace(
|
||||
Storage.ConfigSections.Messages.NOTIFICATION.ALERT.getLines(),
|
||||
"%player%", player.getName(),
|
||||
"%command%", displayCommand,
|
||||
"%world%", worldName);
|
||||
|
||||
if (Storage.ConfigSections.Settings.CUSTOM_PLUGIN.isCommand(command)) {
|
||||
|
||||
MessageHelper.sendMessage(
|
||||
sender,
|
||||
Storage.ConfigSections.Settings.CUSTOM_PLUGIN.MESSAGE,
|
||||
"%command%", StringUtils.getFirstArg(displayCommand)
|
||||
);
|
||||
|
||||
if (Storage.SEND_CONSOLE_NOTIFICATION)
|
||||
Logger.info(notificationMessage);
|
||||
|
||||
Storage.NOTIFY_PLAYERS.forEach(uuid -> {
|
||||
final CommandSender otherSender = CommandSender.from(uuid);
|
||||
if (otherSender != null) {
|
||||
MessageHelper.sendMessage(otherSender, notificationMessage);
|
||||
}
|
||||
});
|
||||
|
||||
event.setCancelled(true);
|
||||
return;
|
||||
}
|
||||
|
||||
if (Storage.ConfigSections.Settings.CUSTOM_VERSION.isCommand(command)) {
|
||||
|
||||
MessageHelper.sendMessage(
|
||||
sender,
|
||||
Storage.ConfigSections.Settings.CUSTOM_VERSION.MESSAGE,
|
||||
"%command%", StringUtils.getFirstArg(displayCommand)
|
||||
);
|
||||
|
||||
if (Storage.SEND_CONSOLE_NOTIFICATION)
|
||||
Logger.info(notificationMessage);
|
||||
|
||||
Storage.NOTIFY_PLAYERS.forEach(uuid -> {
|
||||
Object p = Storage.getLoader().getPlayerObjByUUID(uuid);
|
||||
if (p != null) {
|
||||
MessageHelper.sendMessage(sender, notificationMessage);
|
||||
}
|
||||
});
|
||||
|
||||
event.setCancelled(true);
|
||||
return;
|
||||
}
|
||||
|
||||
final boolean cancelBlockedCommand = Storage.ConfigSections.Settings.CANCEL_COMMAND.ENABLED;
|
||||
final List<Group> groups = GroupManager.getPlayerGroups(sender, isOperator);
|
||||
|
||||
boolean allowed = Storage.Blacklist.canPlayerAccessChat(sender, groups, command, isOperator);
|
||||
boolean blockedNamespace = false;
|
||||
|
||||
if (!Storage.ConfigSections.Settings.BLOCK_NAMESPACE_COMMANDS.doesBypass(sender, isOperator)) {
|
||||
blockedNamespace = cancelBlockedCommand
|
||||
? Storage.ConfigSections.Settings.BLOCK_NAMESPACE_COMMANDS.isCommand(command)
|
||||
: Storage.ConfigSections.Settings.BLOCK_NAMESPACE_COMMANDS.doesAlwaysBlock(command);
|
||||
|
||||
if (blockedNamespace) allowed = false;
|
||||
}
|
||||
|
||||
if (!Storage.ConfigSections.Settings.CANCEL_COMMAND.ENABLED && !blockedNamespace) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!allowed) {
|
||||
ExecuteCommandEvent executeCommandEvent = PATEventHandler.callExecuteCommandEvents(
|
||||
sender,
|
||||
event.getMessage(),
|
||||
true,
|
||||
!Storage.ConfigSections.Settings.TURN_BLACKLIST_TO_WHITELIST.ENABLED
|
||||
);
|
||||
|
||||
if (executeCommandEvent.isBlocked()) {
|
||||
event.setCancelled(true);
|
||||
|
||||
|
||||
MessageHelper.sendMessage(
|
||||
sender,
|
||||
ResponseHandler.getResponse(
|
||||
sender.getUniqueId(),
|
||||
sender.getName(),
|
||||
sender.getServerName(),
|
||||
event.getMessage(),
|
||||
Storage.ConfigSections.Settings.CANCEL_COMMAND.BASE_COMMAND_RESPONSE.getLines()
|
||||
), "%command%", StringUtils.getFirstArg(displayCommand)
|
||||
);
|
||||
|
||||
if (!executeCommandEvent.doesNotify())
|
||||
return;
|
||||
|
||||
if (Storage.SEND_CONSOLE_NOTIFICATION)
|
||||
Logger.info(notificationMessage);
|
||||
|
||||
Storage.NOTIFY_PLAYERS.stream().filter(uuid -> Bukkit.getServer().getPlayer(uuid) != null).forEach(uuid -> {
|
||||
final CommandSender otherSender = CommandSender.from(uuid);
|
||||
MessageHelper.sendMessage(otherSender, notificationMessage);
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
if (executeCommandEvent.isCancelled())
|
||||
return;
|
||||
}
|
||||
|
||||
ExecuteCommandEvent executeCommandEvent = PATEventHandler.callExecuteCommandEvents(
|
||||
sender,
|
||||
event.getMessage(),
|
||||
SubArgument.get().getExecuteHandler().handleCommandExecution(sender, event.getMessage()),
|
||||
false
|
||||
);
|
||||
|
||||
if (executeCommandEvent.isBlocked()) {
|
||||
event.setCancelled(true);
|
||||
|
||||
MessageHelper.sendMessage(
|
||||
sender,
|
||||
ResponseHandler.getResponse(
|
||||
sender.getUniqueId(),
|
||||
sender.getName(),
|
||||
sender.getServerName(),
|
||||
event.getMessage()
|
||||
),
|
||||
"%command%",
|
||||
StringUtils.replaceTriggers(
|
||||
commandWithArguments, "",
|
||||
"\\", "<", ">", "&"
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package de.rayzs.pat.plugin.listeners.bukkit;
|
||||
|
||||
import de.rayzs.pat.api.storage.Storage;
|
||||
import de.rayzs.pat.utils.LuckPermsWarning;
|
||||
import de.rayzs.pat.utils.scheduler.PATScheduler;
|
||||
import de.rayzs.pat.utils.sender.CommandSender;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
|
||||
import org.bukkit.event.server.ServerCommandEvent;
|
||||
|
||||
public class BukkitLuckPermsWarning implements Listener {
|
||||
|
||||
@EventHandler
|
||||
public void onConsoleCommandExecution(final ServerCommandEvent event) {
|
||||
if (LuckPermsWarning.alreadyAnnounced()) return;
|
||||
|
||||
if (Storage.ConfigSections.Settings.UPDATE_GROUPS_PER_WORLD.ENABLED || Storage.ConfigSections.Settings.UPDATE_GROUPS_PER_SERVER.ENABLED) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
final CommandSender sender = CommandSender.from(event.getSender());
|
||||
final String command = event.getCommand();
|
||||
|
||||
if (LuckPermsWarning.shouldSendLuckPermsWarning(sender, command)) {
|
||||
PATScheduler.createScheduler(() -> {
|
||||
LuckPermsWarning.sendAnnouncement(sender);
|
||||
}, 20);
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onPlayerCommandExecution(final PlayerCommandPreprocessEvent event) {
|
||||
if (LuckPermsWarning.alreadyAnnounced()) return;
|
||||
|
||||
if (Storage.ConfigSections.Settings.UPDATE_GROUPS_PER_WORLD.ENABLED || Storage.ConfigSections.Settings.UPDATE_GROUPS_PER_SERVER.ENABLED) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
final CommandSender sender = CommandSender.from(event.getPlayer());
|
||||
final String command = event.getMessage();
|
||||
|
||||
if (LuckPermsWarning.shouldSendLuckPermsWarning(sender, command.substring(1))) {
|
||||
PATScheduler.createScheduler(() -> {
|
||||
LuckPermsWarning.sendAnnouncement(sender);
|
||||
}, 20);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,8 @@ import de.rayzs.pat.plugin.packetanalyzer.bukkit.BukkitPacketAnalyzer;
|
||||
import de.rayzs.pat.plugin.system.communication.BackendUpdater;
|
||||
import de.rayzs.pat.plugin.logger.Logger;
|
||||
import de.rayzs.pat.plugin.system.subargument.SubArgument;
|
||||
import de.rayzs.pat.utils.message.MessageTranslator;
|
||||
import de.rayzs.pat.utils.message.MessageHelper;
|
||||
import de.rayzs.pat.utils.message.replacer.PlaceholderReplacer;
|
||||
import de.rayzs.pat.utils.permission.PermissionPlugin;
|
||||
import de.rayzs.pat.utils.permission.PermissionUtil;
|
||||
import de.rayzs.pat.api.storage.Storage;
|
||||
@@ -17,12 +18,15 @@ import org.bukkit.event.player.*;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.*;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public class BukkitPlayerListener implements Listener {
|
||||
|
||||
@EventHandler
|
||||
public void onPlayerJoin(PlayerJoinEvent event) {
|
||||
final Player player = event.getPlayer();
|
||||
final CommandSender sender = CommandSender.from(player);
|
||||
final boolean isOperator = player.isOp();
|
||||
|
||||
PATEventHandler.callServerPlayersChangeEvents(sender, ServerPlayersChangeEvent.Type.JOINED);
|
||||
SubArgument.get().updateCachedPlayerNames();
|
||||
@@ -38,34 +42,34 @@ public class BukkitPlayerListener implements Listener {
|
||||
CustomServerBrand.get().sendBrandToPlayer(player);
|
||||
}
|
||||
|
||||
if (!Storage.ConfigSections.Settings.HANDLE_THROUGH_PROXY.ENABLED) {
|
||||
if (Storage.getPermissionPlugin() != PermissionPlugin.LUCKPERMS) {
|
||||
if (!Storage.ConfigSections.Settings.HANDLE_THROUGH_PROXY.ENABLED && Storage.getPermissionPlugin() != PermissionPlugin.LUCKPERMS) {
|
||||
PATScheduler.createScheduler(() -> {
|
||||
|
||||
PATScheduler.createScheduler(() -> {
|
||||
if (Storage.getPermissionPlugin() == PermissionPlugin.GROUPMANAGER) {
|
||||
PermissionUtil.reloadPermissions(sender);
|
||||
}
|
||||
|
||||
if (Storage.getPermissionPlugin() == PermissionPlugin.GROUPMANAGER) {
|
||||
PermissionUtil.reloadPermissions(sender);
|
||||
}
|
||||
|
||||
Storage.getLoader().updateCommands(sender);
|
||||
}, 20);
|
||||
|
||||
}
|
||||
Storage.getLoader().updateCommands(sender);
|
||||
}, 20);
|
||||
}
|
||||
|
||||
if (!BukkitPacketAnalyzer.inject(player)) {
|
||||
|
||||
final BukkitPacketAnalyzer.InjectionState injectionState = BukkitPacketAnalyzer.inject(player);
|
||||
|
||||
|
||||
if (injectionState == BukkitPacketAnalyzer.InjectionState.FAILED) {
|
||||
PATScheduler.createScheduler(() -> {
|
||||
if (player.isOnline()) {
|
||||
if (!BukkitPacketAnalyzer.inject(player)) {
|
||||
if (BukkitPacketAnalyzer.inject(player) == BukkitPacketAnalyzer.InjectionState.FAILED) {
|
||||
|
||||
if (Storage.ConfigSections.Settings.INJECTION_FAILED.ENABLED) {
|
||||
|
||||
Logger.info(MessageTranslator.replaceMessage(
|
||||
Logger.info(PlaceholderReplacer.applyPlaceholders(
|
||||
sender,
|
||||
Storage.ConfigSections.Settings.INJECTION_FAILED.CONSOLE_MESSAGE
|
||||
));
|
||||
|
||||
player.kickPlayer(MessageTranslator.replaceMessage(
|
||||
player.kickPlayer(PlaceholderReplacer.applyPlaceholders(
|
||||
sender,
|
||||
Storage.ConfigSections.Settings.INJECTION_FAILED.KICK_MESSAGE
|
||||
));
|
||||
@@ -74,12 +78,14 @@ public class BukkitPlayerListener implements Listener {
|
||||
}
|
||||
}
|
||||
}, 10);
|
||||
} else if (injectionState == BukkitPacketAnalyzer.InjectionState.SKIPPED) {
|
||||
Logger.warning("Skipped injection for " + player.getName() + ". Player seems to have a corrupted pipeline. (A fake player?)");
|
||||
}
|
||||
|
||||
if (Storage.OUTDATED && PermissionUtil.hasPermission(sender, "joinupdate")) {
|
||||
if (Storage.OUTDATED && PermissionUtil.hasPermission(sender, "joinupdate", isOperator)) {
|
||||
PATScheduler.createScheduler(() -> {
|
||||
if (player.isOnline()) {
|
||||
MessageTranslator.send(player, Storage.ConfigSections.Settings.UPDATE.OUTDATED.getLines());
|
||||
MessageHelper.sendMessage(sender, Storage.ConfigSections.Settings.UPDATE.OUTDATED.getLines());
|
||||
}
|
||||
}, 20);
|
||||
}
|
||||
@@ -108,7 +114,7 @@ public class BukkitPlayerListener implements Listener {
|
||||
if (Storage.ConfigSections.Settings.UPDATE_GROUPS_PER_WORLD.ENABLED) {
|
||||
CommandSender sender = CommandSender.from(player);
|
||||
|
||||
assert sender != null;
|
||||
Objects.requireNonNull(sender);
|
||||
PermissionUtil.reloadPermissions(sender);
|
||||
Storage.getLoader().updateCommands(sender);
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import de.rayzs.pat.api.storage.Storage;
|
||||
import de.rayzs.pat.utils.ExpireCache;
|
||||
import de.rayzs.pat.utils.StringUtils;
|
||||
import de.rayzs.pat.utils.message.replacer.PlaceholderReplacer;
|
||||
import de.rayzs.pat.utils.sender.CommandSender;
|
||||
import org.bukkit.event.*;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.profile.PlayerTextures;
|
||||
@@ -86,35 +87,7 @@ public class PaperServerListPing implements Listener {
|
||||
}
|
||||
|
||||
if (Storage.ConfigSections.Settings.CUSTOM_PROTOCOL_PING.USE_CENTER_VARIABLE) {
|
||||
|
||||
int biggestLine = 0;
|
||||
for (int i = 0; i < lines.size(); i++) {
|
||||
String line = replaceString(lines.get(i), online, onlineExtend, max);
|
||||
lines.set(i, line);
|
||||
|
||||
if (line.startsWith("%center%")) {
|
||||
biggestLine = Math.max(biggestLine, Math.max(0, line.length() - 8));
|
||||
}
|
||||
}
|
||||
|
||||
for (int i = 0; i < lines.size(); i++) {
|
||||
String line = lines.get(i);
|
||||
|
||||
if (line.startsWith("%center%")) {
|
||||
int length = Math.max(0, line.length() - 8);
|
||||
int diff = biggestLine - length;
|
||||
|
||||
int left = diff / 2;
|
||||
int right = diff - left;
|
||||
|
||||
line = " ".repeat(left)
|
||||
+ line.substring(8)
|
||||
+ " ".repeat(right);
|
||||
|
||||
lines.set(i, line);
|
||||
}
|
||||
}
|
||||
|
||||
StringUtils.centralize(lines);
|
||||
}
|
||||
|
||||
lines.forEach(line -> {
|
||||
@@ -133,7 +106,9 @@ public class PaperServerListPing implements Listener {
|
||||
.replace("%online%", String.valueOf(online))
|
||||
.replace("%max%", String.valueOf(max));
|
||||
|
||||
return replaced.contains("%") ? PlaceholderReplacer.replace(null, replaced) : replaced;
|
||||
return replaced.contains("%")
|
||||
? PlaceholderReplacer.applyPlaceholders(CommandSender.from(Bukkit.getConsoleSender()), replaced)
|
||||
: replaced;
|
||||
}
|
||||
|
||||
private static class ProtocolHoverLine implements PlayerProfile {
|
||||
@@ -246,7 +221,7 @@ public class PaperServerListPing implements Listener {
|
||||
}
|
||||
|
||||
@Override
|
||||
public org.bukkit.profile.@NotNull PlayerProfile clone() {
|
||||
public PlayerProfile clone() {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,112 +1,112 @@
|
||||
package de.rayzs.pat.plugin.listeners.bungee;
|
||||
|
||||
import de.rayzs.pat.api.event.PATEventHandler;
|
||||
import de.rayzs.pat.api.event.events.FilteredTabCompletionEvent;
|
||||
import de.rayzs.pat.plugin.packetanalyzer.proxy.BungeePacketAnalyzer;
|
||||
import de.rayzs.pat.api.storage.Storage;
|
||||
import de.rayzs.pat.utils.StringUtils;
|
||||
import de.rayzs.pat.utils.group.Group;
|
||||
import de.rayzs.pat.utils.group.GroupManager;
|
||||
import de.rayzs.pat.utils.permission.PermissionUtil;
|
||||
import de.rayzs.pat.utils.sender.CommandSender;
|
||||
import net.md_5.bungee.api.config.ServerInfo;
|
||||
import net.md_5.bungee.api.connection.ProxiedPlayer;
|
||||
import net.md_5.bungee.api.event.TabCompleteEvent;
|
||||
import net.md_5.bungee.api.event.TabCompleteResponseEvent;
|
||||
import net.md_5.bungee.api.plugin.Listener;
|
||||
import net.md_5.bungee.event.EventHandler;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class BungeeAntiTabListener implements Listener {
|
||||
|
||||
@EventHandler
|
||||
public void onTabCompleteResponse(TabCompleteResponseEvent event) {
|
||||
|
||||
if(!(event.getReceiver() instanceof ProxiedPlayer)) return;
|
||||
|
||||
ProxiedPlayer player = (ProxiedPlayer) event.getReceiver();
|
||||
CommandSender sender = CommandSender.from(player);
|
||||
|
||||
ServerInfo serverInfo = player.getServer().getInfo();
|
||||
String serverName = serverInfo.getName();
|
||||
|
||||
String rawCursor = BungeePacketAnalyzer.getPlayerInput(player);
|
||||
|
||||
if (rawCursor == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!rawCursor.startsWith("/")) {
|
||||
return;
|
||||
}
|
||||
|
||||
String cursor = rawCursor.substring(1);
|
||||
|
||||
if (event.getSuggestions().isEmpty())
|
||||
return;
|
||||
|
||||
if (Storage.Blacklist.isDisabledServer(serverName))
|
||||
return;
|
||||
|
||||
if (PermissionUtil.hasBypassPermission(sender))
|
||||
return;
|
||||
|
||||
|
||||
|
||||
final List<Group> groups = GroupManager.getPlayerGroups(sender);
|
||||
final boolean doesBypassNamespace = Storage.ConfigSections.Settings.BLOCK_NAMESPACE_COMMANDS.doesBypass(sender);
|
||||
final boolean spaces = cursor.contains(" ");
|
||||
|
||||
boolean cancelsBeforeHand = false;
|
||||
|
||||
if (Storage.ConfigSections.Settings.BLOCK_NAMESPACE_COMMANDS.isCommand(cursor) && !doesBypassNamespace) {
|
||||
cancelsBeforeHand = true;
|
||||
}
|
||||
|
||||
if (!cancelsBeforeHand && !cursor.isEmpty()) {
|
||||
cancelsBeforeHand = !Storage.Blacklist.canPlayerAccessTab(sender, groups, StringUtils.getFirstArg(cursor), serverName);
|
||||
}
|
||||
|
||||
if (!cancelsBeforeHand) {
|
||||
cancelsBeforeHand = Storage.ConfigSections.Settings.CUSTOM_PLUGIN.isCommand(cursor) || Storage.ConfigSections.Settings.CUSTOM_VERSION.isCommand(cursor);
|
||||
}
|
||||
|
||||
if (spaces) {
|
||||
if (cancelsBeforeHand) {
|
||||
event.getSuggestions().clear();
|
||||
return;
|
||||
}
|
||||
|
||||
FilteredTabCompletionEvent filteredTabCompletionEvent = PATEventHandler.callFilteredTabCompletionEvents(sender, rawCursor, new ArrayList<>(event.getSuggestions()));
|
||||
|
||||
if (filteredTabCompletionEvent.isCancelled()) {
|
||||
event.getSuggestions().clear();
|
||||
} else {
|
||||
event.getSuggestions().removeIf(s -> !filteredTabCompletionEvent.getCompletion().contains(s));
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
event.getSuggestions().removeIf(s -> {
|
||||
String cpy = s;
|
||||
if (cpy.startsWith("/")) {
|
||||
cpy = cpy.substring(1);
|
||||
}
|
||||
|
||||
if (Storage.ConfigSections.Settings.CUSTOM_PLUGIN.isTabCompletable(cpy) || Storage.ConfigSections.Settings.CUSTOM_VERSION.isTabCompletable(cpy)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return !Storage.Blacklist.canPlayerAccessTab(sender, groups, cpy, serverName);
|
||||
});
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onTabComplete(TabCompleteEvent event) {
|
||||
ProxiedPlayer player = (ProxiedPlayer) event.getSender();
|
||||
BungeePacketAnalyzer.setPlayerInput(player, event.getCursor());
|
||||
}
|
||||
}
|
||||
package de.rayzs.pat.plugin.listeners.bungee;
|
||||
|
||||
import de.rayzs.pat.api.event.PATEventHandler;
|
||||
import de.rayzs.pat.api.event.events.FilteredTabCompletionEvent;
|
||||
import de.rayzs.pat.plugin.packetanalyzer.proxy.BungeePacketAnalyzer;
|
||||
import de.rayzs.pat.api.storage.Storage;
|
||||
import de.rayzs.pat.utils.StringUtils;
|
||||
import de.rayzs.pat.utils.group.Group;
|
||||
import de.rayzs.pat.utils.group.GroupManager;
|
||||
import de.rayzs.pat.utils.permission.PermissionUtil;
|
||||
import de.rayzs.pat.utils.sender.CommandSender;
|
||||
import net.md_5.bungee.api.config.ServerInfo;
|
||||
import net.md_5.bungee.api.connection.ProxiedPlayer;
|
||||
import net.md_5.bungee.api.event.TabCompleteEvent;
|
||||
import net.md_5.bungee.api.event.TabCompleteResponseEvent;
|
||||
import net.md_5.bungee.api.plugin.Listener;
|
||||
import net.md_5.bungee.event.EventHandler;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class BungeeAntiTabListener implements Listener {
|
||||
|
||||
@EventHandler
|
||||
public void onTabCompleteResponse(TabCompleteResponseEvent event) {
|
||||
|
||||
if(!(event.getReceiver() instanceof ProxiedPlayer)) return;
|
||||
|
||||
ProxiedPlayer player = (ProxiedPlayer) event.getReceiver();
|
||||
CommandSender sender = CommandSender.from(player);
|
||||
|
||||
ServerInfo serverInfo = player.getServer().getInfo();
|
||||
String serverName = serverInfo.getName();
|
||||
|
||||
String rawCursor = BungeePacketAnalyzer.getPlayerInput(player);
|
||||
|
||||
if (rawCursor == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!rawCursor.startsWith("/")) {
|
||||
return;
|
||||
}
|
||||
|
||||
String cursor = rawCursor.substring(1);
|
||||
|
||||
if (event.getSuggestions().isEmpty())
|
||||
return;
|
||||
|
||||
if (Storage.Blacklist.isDisabledServer(serverName))
|
||||
return;
|
||||
|
||||
if (PermissionUtil.hasBypassPermission(sender, false))
|
||||
return;
|
||||
|
||||
|
||||
|
||||
final List<Group> groups = GroupManager.getPlayerGroups(sender, false);
|
||||
final boolean doesBypassNamespace = Storage.ConfigSections.Settings.BLOCK_NAMESPACE_COMMANDS.doesBypass(sender, false);
|
||||
final boolean spaces = cursor.contains(" ");
|
||||
|
||||
boolean cancelsBeforeHand = false;
|
||||
|
||||
if (Storage.ConfigSections.Settings.BLOCK_NAMESPACE_COMMANDS.isCommand(cursor) && !doesBypassNamespace) {
|
||||
cancelsBeforeHand = true;
|
||||
}
|
||||
|
||||
if (!cancelsBeforeHand && !cursor.isEmpty()) {
|
||||
cancelsBeforeHand = !Storage.Blacklist.canPlayerAccessTab(sender, groups, StringUtils.getFirstArg(cursor), serverName, false);
|
||||
}
|
||||
|
||||
if (!cancelsBeforeHand) {
|
||||
cancelsBeforeHand = Storage.ConfigSections.Settings.CUSTOM_PLUGIN.isCommand(cursor) || Storage.ConfigSections.Settings.CUSTOM_VERSION.isCommand(cursor);
|
||||
}
|
||||
|
||||
if (spaces) {
|
||||
if (cancelsBeforeHand) {
|
||||
event.getSuggestions().clear();
|
||||
return;
|
||||
}
|
||||
|
||||
FilteredTabCompletionEvent filteredTabCompletionEvent = PATEventHandler.callFilteredTabCompletionEvents(sender, rawCursor, new ArrayList<>(event.getSuggestions()));
|
||||
|
||||
if (filteredTabCompletionEvent.isCancelled()) {
|
||||
event.getSuggestions().clear();
|
||||
} else {
|
||||
event.getSuggestions().removeIf(s -> !filteredTabCompletionEvent.getCompletion().contains(s));
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
event.getSuggestions().removeIf(s -> {
|
||||
String cpy = s;
|
||||
if (cpy.startsWith("/")) {
|
||||
cpy = cpy.substring(1);
|
||||
}
|
||||
|
||||
if (Storage.ConfigSections.Settings.CUSTOM_PLUGIN.isTabCompletable(cpy) || Storage.ConfigSections.Settings.CUSTOM_VERSION.isTabCompletable(cpy)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return !Storage.Blacklist.canPlayerAccessTab(sender, groups, cpy, serverName, false);
|
||||
});
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onTabComplete(TabCompleteEvent event) {
|
||||
ProxiedPlayer player = (ProxiedPlayer) event.getSender();
|
||||
BungeePacketAnalyzer.setPlayerInput(player, event.getCursor());
|
||||
}
|
||||
}
|
||||
+197
-195
@@ -1,195 +1,197 @@
|
||||
package de.rayzs.pat.plugin.listeners.bungee;
|
||||
|
||||
import de.rayzs.pat.plugin.system.communication.Communicator;
|
||||
import de.rayzs.pat.api.event.events.ExecuteCommandEvent;
|
||||
import de.rayzs.pat.plugin.system.subargument.SubArgument;
|
||||
import de.rayzs.pat.utils.group.Group;
|
||||
import de.rayzs.pat.utils.group.GroupManager;
|
||||
import de.rayzs.pat.utils.permission.PermissionUtil;
|
||||
import de.rayzs.pat.utils.message.MessageTranslator;
|
||||
import de.rayzs.pat.utils.response.ResponseHandler;
|
||||
import de.rayzs.pat.utils.sender.CommandSender;
|
||||
import net.md_5.bungee.api.event.ChatEvent;
|
||||
import net.md_5.bungee.api.plugin.Listener;
|
||||
import de.rayzs.pat.plugin.logger.Logger;
|
||||
import de.rayzs.pat.api.storage.Storage;
|
||||
import net.md_5.bungee.api.connection.*;
|
||||
import de.rayzs.pat.utils.StringUtils;
|
||||
import de.rayzs.pat.api.event.*;
|
||||
import net.md_5.bungee.event.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class BungeeBlockCommandListener implements Listener {
|
||||
|
||||
@EventHandler (priority = EventPriority.HIGHEST)
|
||||
public void onChat(ChatEvent event) {
|
||||
if (event.isCancelled()) return;
|
||||
|
||||
final Connection connection = event.getSender();
|
||||
if (! (connection instanceof ProxiedPlayer) || !event.getMessage().startsWith("/"))
|
||||
return;
|
||||
|
||||
final ProxiedPlayer player = (ProxiedPlayer) connection;
|
||||
final CommandSender sender = CommandSender.from(player);
|
||||
final String serverName = player.getServer().getInfo().getName();
|
||||
|
||||
String command = event.getMessage();
|
||||
|
||||
if (PermissionUtil.hasBypassPermission(sender, command) || Storage.Blacklist.isDisabledServer(serverName))
|
||||
return;
|
||||
|
||||
command = command.startsWith("/") ? command.substring(1) : command;
|
||||
final String commandWithArguments = command;
|
||||
command = StringUtils.getFirstArg(command);
|
||||
|
||||
if (Communicator.get().hasConnectedClients() && Storage.ConfigSections.Settings.AUTO_LOWERCASE_COMMANDS.isCommand(command)) {
|
||||
command = command.toLowerCase();
|
||||
}
|
||||
|
||||
final String displayCommand = StringUtils.replaceTriggers(command, "", "\\", "<", ">", "&");
|
||||
|
||||
|
||||
final List<String> notificationMessage = MessageTranslator.replaceMessageList(
|
||||
Storage.ConfigSections.Messages.NOTIFICATION.ALERT,
|
||||
"%player%", player.getName(),
|
||||
"%command%", displayCommand,
|
||||
"%server%", serverName);
|
||||
|
||||
if (Storage.ConfigSections.Settings.CUSTOM_PLUGIN.isCommand(command)) {
|
||||
|
||||
Communicator.Proxy2Backend.sendNotification(player.getUniqueId(), serverName, displayCommand);
|
||||
|
||||
MessageTranslator.send(
|
||||
player,
|
||||
Storage.ConfigSections.Settings.CUSTOM_PLUGIN.MESSAGE,
|
||||
"%command%", StringUtils.getFirstArg(displayCommand)
|
||||
);
|
||||
|
||||
if (Storage.SEND_CONSOLE_NOTIFICATION)
|
||||
Logger.info(notificationMessage);
|
||||
|
||||
Storage.NOTIFY_PLAYERS.stream().forEach(uuid -> {
|
||||
Object p = Storage.getLoader().getPlayerObjByUUID(uuid);
|
||||
if (p != null) {
|
||||
MessageTranslator.send(p, notificationMessage);
|
||||
}
|
||||
});
|
||||
|
||||
event.setCancelled(true);
|
||||
return;
|
||||
}
|
||||
|
||||
if (Storage.ConfigSections.Settings.CUSTOM_VERSION.isCommand(command)) {
|
||||
|
||||
Communicator.Proxy2Backend.sendNotification(player.getUniqueId(), serverName, displayCommand);
|
||||
|
||||
MessageTranslator.send(
|
||||
player,
|
||||
Storage.ConfigSections.Settings.CUSTOM_VERSION.MESSAGE,
|
||||
"%command%", StringUtils.getFirstArg(displayCommand)
|
||||
);
|
||||
|
||||
if (Storage.SEND_CONSOLE_NOTIFICATION)
|
||||
Logger.info(notificationMessage);
|
||||
|
||||
Storage.NOTIFY_PLAYERS.forEach(uuid -> {
|
||||
Object p = Storage.getLoader().getPlayerObjByUUID(uuid);
|
||||
if (p != null) {
|
||||
MessageTranslator.send(p, notificationMessage);
|
||||
}
|
||||
});
|
||||
|
||||
event.setCancelled(true);
|
||||
return;
|
||||
}
|
||||
|
||||
final List<Group> groups = GroupManager.getPlayerGroups(sender);
|
||||
final boolean cancelBlockedCommand = Storage.ConfigSections.Settings.CANCEL_COMMAND.ENABLED;
|
||||
|
||||
boolean allowed = Storage.Blacklist.canPlayerAccessChat(sender, groups, command, serverName);
|
||||
boolean blockedNamespace = false;
|
||||
|
||||
if (!Storage.ConfigSections.Settings.BLOCK_NAMESPACE_COMMANDS.doesBypass(sender)) {
|
||||
blockedNamespace = cancelBlockedCommand
|
||||
? Storage.ConfigSections.Settings.BLOCK_NAMESPACE_COMMANDS.isCommand(command)
|
||||
: Storage.ConfigSections.Settings.BLOCK_NAMESPACE_COMMANDS.doesAlwaysBlock(command);
|
||||
|
||||
if (blockedNamespace) allowed = false;
|
||||
}
|
||||
|
||||
if (!Storage.ConfigSections.Settings.CANCEL_COMMAND.ENABLED && !blockedNamespace) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!allowed) {
|
||||
ExecuteCommandEvent executeCommandEvent = PATEventHandler.callExecuteCommandEvents(
|
||||
sender,
|
||||
event.getMessage(),
|
||||
true,
|
||||
!Storage.ConfigSections.Settings.TURN_BLACKLIST_TO_WHITELIST.ENABLED
|
||||
);
|
||||
|
||||
if (executeCommandEvent.isBlocked()) {
|
||||
event.setCancelled(true);
|
||||
|
||||
MessageTranslator.send(
|
||||
sender,
|
||||
ResponseHandler.getResponse(
|
||||
sender.getUniqueId(),
|
||||
sender.getName(),
|
||||
serverName,
|
||||
event.getMessage(),
|
||||
Storage.ConfigSections.Settings.CANCEL_COMMAND.BASE_COMMAND_RESPONSE.getLines()
|
||||
), "%command%", StringUtils.getFirstArg(displayCommand)
|
||||
);
|
||||
|
||||
if (!executeCommandEvent.doesNotify())
|
||||
return;
|
||||
|
||||
Communicator.Proxy2Backend.sendNotification(player.getUniqueId(), serverName, displayCommand);
|
||||
|
||||
if (Storage.SEND_CONSOLE_NOTIFICATION)
|
||||
Logger.info(notificationMessage);
|
||||
|
||||
Storage.NOTIFY_PLAYERS.forEach(uuid -> {
|
||||
Object p = Storage.getLoader().getPlayerObjByUUID(uuid);
|
||||
|
||||
if (p != null) {
|
||||
MessageTranslator.send(p, notificationMessage);
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
if (executeCommandEvent.isCancelled())
|
||||
return;
|
||||
}
|
||||
|
||||
ExecuteCommandEvent executeCommandEvent = PATEventHandler.callExecuteCommandEvents(
|
||||
sender,
|
||||
event.getMessage(),
|
||||
SubArgument.get().getExecuteHandler().handleCommandExecution(sender, event.getMessage()),
|
||||
false
|
||||
);
|
||||
|
||||
if (executeCommandEvent.isBlocked()) {
|
||||
event.setCancelled(true);
|
||||
|
||||
MessageTranslator.send(
|
||||
sender,
|
||||
ResponseHandler.getResponse(
|
||||
sender.getUniqueId(),
|
||||
sender.getName(),
|
||||
serverName,
|
||||
event.getMessage()
|
||||
),
|
||||
"%command%",
|
||||
StringUtils.replaceTriggers(
|
||||
commandWithArguments, "",
|
||||
"\\", "<", ">", "&"
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
package de.rayzs.pat.plugin.listeners.bungee;
|
||||
|
||||
import de.rayzs.pat.plugin.system.communication.Communicator;
|
||||
import de.rayzs.pat.api.event.events.ExecuteCommandEvent;
|
||||
import de.rayzs.pat.plugin.system.subargument.SubArgument;
|
||||
import de.rayzs.pat.utils.group.Group;
|
||||
import de.rayzs.pat.utils.group.GroupManager;
|
||||
import de.rayzs.pat.utils.permission.PermissionUtil;
|
||||
import de.rayzs.pat.utils.message.MessageHelper;
|
||||
import de.rayzs.pat.utils.response.ResponseHandler;
|
||||
import de.rayzs.pat.utils.sender.CommandSender;
|
||||
import net.md_5.bungee.api.event.ChatEvent;
|
||||
import net.md_5.bungee.api.plugin.Listener;
|
||||
import de.rayzs.pat.plugin.logger.Logger;
|
||||
import de.rayzs.pat.api.storage.Storage;
|
||||
import net.md_5.bungee.api.connection.*;
|
||||
import de.rayzs.pat.utils.StringUtils;
|
||||
import de.rayzs.pat.api.event.*;
|
||||
import net.md_5.bungee.event.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class BungeeBlockCommandListener implements Listener {
|
||||
|
||||
@EventHandler (priority = EventPriority.HIGHEST)
|
||||
public void onChat(ChatEvent event) {
|
||||
if (event.isCancelled()) return;
|
||||
|
||||
final Connection connection = event.getSender();
|
||||
if (! (connection instanceof ProxiedPlayer) || !event.getMessage().startsWith("/"))
|
||||
return;
|
||||
|
||||
final ProxiedPlayer player = (ProxiedPlayer) connection;
|
||||
final CommandSender sender = CommandSender.from(player);
|
||||
final String serverName = player.getServer().getInfo().getName();
|
||||
|
||||
String command = event.getMessage();
|
||||
|
||||
if (PermissionUtil.hasBypassPermission(sender, command, false) || Storage.Blacklist.isDisabledServer(serverName))
|
||||
return;
|
||||
|
||||
command = command.startsWith("/") ? command.substring(1) : command;
|
||||
final String commandWithArguments = command;
|
||||
command = StringUtils.getFirstArg(command);
|
||||
|
||||
if (Communicator.get().hasConnectedClients() && Storage.ConfigSections.Settings.AUTO_LOWERCASE_COMMANDS.isCommand(command)) {
|
||||
command = command.toLowerCase();
|
||||
}
|
||||
|
||||
final String displayCommand = StringUtils.replaceTriggers(command, "", "\\", "<", ">", "&");
|
||||
|
||||
|
||||
final String notificationMessage = StringUtils.replace(
|
||||
Storage.ConfigSections.Messages.NOTIFICATION.ALERT.getLines(),
|
||||
"%player%", player.getName(),
|
||||
"%command%", displayCommand,
|
||||
"%server%", serverName);
|
||||
|
||||
if (Storage.ConfigSections.Settings.CUSTOM_PLUGIN.isCommand(command)) {
|
||||
|
||||
Communicator.Proxy2Backend.sendNotification(player.getUniqueId(), serverName, displayCommand);
|
||||
|
||||
MessageHelper.sendMessage(
|
||||
sender,
|
||||
Storage.ConfigSections.Settings.CUSTOM_PLUGIN.MESSAGE,
|
||||
"%command%", StringUtils.getFirstArg(displayCommand)
|
||||
);
|
||||
|
||||
if (Storage.SEND_CONSOLE_NOTIFICATION)
|
||||
Logger.info(notificationMessage);
|
||||
|
||||
Storage.NOTIFY_PLAYERS.stream().forEach(uuid -> {
|
||||
final CommandSender otherSender = CommandSender.from(uuid);
|
||||
|
||||
if (otherSender != null) {
|
||||
MessageHelper.sendMessage(otherSender, notificationMessage);
|
||||
}
|
||||
});
|
||||
|
||||
event.setCancelled(true);
|
||||
return;
|
||||
}
|
||||
|
||||
if (Storage.ConfigSections.Settings.CUSTOM_VERSION.isCommand(command)) {
|
||||
|
||||
Communicator.Proxy2Backend.sendNotification(player.getUniqueId(), serverName, displayCommand);
|
||||
|
||||
MessageHelper.sendMessage(
|
||||
sender,
|
||||
Storage.ConfigSections.Settings.CUSTOM_VERSION.MESSAGE,
|
||||
"%command%", StringUtils.getFirstArg(displayCommand)
|
||||
);
|
||||
|
||||
if (Storage.SEND_CONSOLE_NOTIFICATION)
|
||||
Logger.info(notificationMessage);
|
||||
|
||||
Storage.NOTIFY_PLAYERS.forEach(uuid -> {
|
||||
final CommandSender otherSender = CommandSender.from(uuid);
|
||||
|
||||
if (otherSender != null) {
|
||||
MessageHelper.sendMessage(otherSender, notificationMessage);
|
||||
}
|
||||
});
|
||||
|
||||
event.setCancelled(true);
|
||||
return;
|
||||
}
|
||||
|
||||
final List<Group> groups = GroupManager.getPlayerGroups(sender, false);
|
||||
final boolean cancelBlockedCommand = Storage.ConfigSections.Settings.CANCEL_COMMAND.ENABLED;
|
||||
|
||||
boolean allowed = Storage.Blacklist.canPlayerAccessChat(sender, groups, command, serverName, false);
|
||||
boolean blockedNamespace = false;
|
||||
|
||||
if (!Storage.ConfigSections.Settings.BLOCK_NAMESPACE_COMMANDS.doesBypass(sender, false)) {
|
||||
blockedNamespace = cancelBlockedCommand
|
||||
? Storage.ConfigSections.Settings.BLOCK_NAMESPACE_COMMANDS.isCommand(command)
|
||||
: Storage.ConfigSections.Settings.BLOCK_NAMESPACE_COMMANDS.doesAlwaysBlock(command);
|
||||
|
||||
if (blockedNamespace) allowed = false;
|
||||
}
|
||||
|
||||
if (!Storage.ConfigSections.Settings.CANCEL_COMMAND.ENABLED && !blockedNamespace) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!allowed) {
|
||||
ExecuteCommandEvent executeCommandEvent = PATEventHandler.callExecuteCommandEvents(
|
||||
sender,
|
||||
event.getMessage(),
|
||||
true,
|
||||
!Storage.ConfigSections.Settings.TURN_BLACKLIST_TO_WHITELIST.ENABLED
|
||||
);
|
||||
|
||||
if (executeCommandEvent.isBlocked()) {
|
||||
event.setCancelled(true);
|
||||
|
||||
MessageHelper.sendMessage(
|
||||
sender,
|
||||
ResponseHandler.getResponse(
|
||||
sender.getUniqueId(),
|
||||
sender.getName(),
|
||||
serverName,
|
||||
event.getMessage(),
|
||||
Storage.ConfigSections.Settings.CANCEL_COMMAND.BASE_COMMAND_RESPONSE.getLines()
|
||||
), "%command%", StringUtils.getFirstArg(displayCommand)
|
||||
);
|
||||
|
||||
if (!executeCommandEvent.doesNotify())
|
||||
return;
|
||||
|
||||
Communicator.Proxy2Backend.sendNotification(player.getUniqueId(), serverName, displayCommand);
|
||||
|
||||
if (Storage.SEND_CONSOLE_NOTIFICATION)
|
||||
Logger.info(notificationMessage);
|
||||
|
||||
Storage.NOTIFY_PLAYERS.forEach(uuid -> {
|
||||
final CommandSender otherSender = CommandSender.from(uuid);
|
||||
|
||||
if (otherSender != null) {
|
||||
MessageHelper.sendMessage(otherSender, notificationMessage);
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
if (executeCommandEvent.isCancelled())
|
||||
return;
|
||||
}
|
||||
|
||||
ExecuteCommandEvent executeCommandEvent = PATEventHandler.callExecuteCommandEvents(
|
||||
sender,
|
||||
event.getMessage(),
|
||||
SubArgument.get().getExecuteHandler().handleCommandExecution(sender, event.getMessage()),
|
||||
false
|
||||
);
|
||||
|
||||
if (executeCommandEvent.isBlocked()) {
|
||||
event.setCancelled(true);
|
||||
|
||||
MessageHelper.sendMessage(
|
||||
sender,
|
||||
ResponseHandler.getResponse(
|
||||
sender.getUniqueId(),
|
||||
sender.getName(),
|
||||
serverName,
|
||||
event.getMessage()
|
||||
),
|
||||
"%command%",
|
||||
StringUtils.replaceTriggers(
|
||||
commandWithArguments, "",
|
||||
"\\", "<", ">", "&"
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package de.rayzs.pat.plugin.listeners.bungee;
|
||||
|
||||
import de.rayzs.pat.api.storage.Storage;
|
||||
import de.rayzs.pat.plugin.BukkitLoader;
|
||||
import de.rayzs.pat.plugin.BungeeLoader;
|
||||
import de.rayzs.pat.utils.LuckPermsWarning;
|
||||
import de.rayzs.pat.utils.sender.CommandSender;
|
||||
import net.md_5.bungee.api.ProxyServer;
|
||||
import net.md_5.bungee.api.connection.ProxiedPlayer;
|
||||
import net.md_5.bungee.api.event.ChatEvent;
|
||||
import net.md_5.bungee.api.plugin.Listener;
|
||||
import net.md_5.bungee.event.EventHandler;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public class BungeeLuckPermsWarning implements Listener {
|
||||
|
||||
@EventHandler
|
||||
public void onPlayerCommandExecution(final ChatEvent event) {
|
||||
if (LuckPermsWarning.alreadyAnnounced()) return;
|
||||
|
||||
if (Storage.ConfigSections.Settings.UPDATE_GROUPS_PER_WORLD.ENABLED || Storage.ConfigSections.Settings.UPDATE_GROUPS_PER_SERVER.ENABLED) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
if (! (event.getSender() instanceof ProxiedPlayer player)) return;
|
||||
|
||||
final CommandSender sender = CommandSender.from(player);
|
||||
final String command = event.getMessage();
|
||||
|
||||
if (LuckPermsWarning.shouldSendLuckPermsWarning(sender, command.substring(1))) {
|
||||
ProxyServer.getInstance().getScheduler().schedule(
|
||||
BungeeLoader.getPlugin(),
|
||||
() -> LuckPermsWarning.sendAnnouncement(sender),
|
||||
1, TimeUnit.SECONDS
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package de.rayzs.pat.plugin.listeners.bungee;
|
||||
|
||||
import de.rayzs.pat.plugin.logger.Logger;
|
||||
import de.rayzs.pat.utils.StringUtils;
|
||||
import net.md_5.bungee.api.event.ProxyPingEvent;
|
||||
import net.md_5.bungee.api.plugin.Listener;
|
||||
import de.rayzs.pat.api.storage.Storage;
|
||||
@@ -20,14 +21,16 @@ public class BungeePingListener implements Listener {
|
||||
ProxyServer proxyServer = BungeeLoader.getPlugin().getProxy();
|
||||
int online = proxyServer.getOnlineCount(),
|
||||
onlineExtend = online + Storage.ConfigSections.Settings.CUSTOM_PROTOCOL_PING.EXTEND_COUNT,
|
||||
max = -1;
|
||||
tmpMax = -1;
|
||||
|
||||
try {
|
||||
max = proxyServer.getConfigurationAdapter().getListeners().iterator().next().getMaxPlayers();
|
||||
tmpMax = proxyServer.getConfigurationAdapter().getListeners().iterator().next().getMaxPlayers();
|
||||
} catch (Throwable throwable) {
|
||||
Logger.warning("Failed to read max-players count for %max% placeholder! Using -1 as default value instead.");
|
||||
}
|
||||
|
||||
final int max = tmpMax;
|
||||
|
||||
ServerPing serverPing = event.getResponse();
|
||||
|
||||
int protocol = Storage.ConfigSections.Settings.CUSTOM_PROTOCOL_PING.ALWAYS_SHOW ? -1 : serverPing.getVersion().getProtocol();
|
||||
@@ -55,32 +58,11 @@ public class BungeePingListener implements Listener {
|
||||
} else {
|
||||
List<String> cpyLines = new ArrayList<>(Storage.ConfigSections.Settings.CUSTOM_PROTOCOL_PING.PLAYERLIST.getLines());
|
||||
|
||||
int biggestLine = 0;
|
||||
for (int i = 0; i < cpyLines.size(); i++) {
|
||||
String line = replaceString(cpyLines.get(i), online, onlineExtend, max);
|
||||
cpyLines.set(i, line);
|
||||
|
||||
if (line.startsWith("%center%")) {
|
||||
biggestLine = Math.max(biggestLine, Math.max(0, line.length() - 8));
|
||||
}
|
||||
}
|
||||
cpyLines.replaceAll(string -> replaceString(string, online, onlineExtend, max));
|
||||
StringUtils.centralize(cpyLines);
|
||||
|
||||
for (int i = 0; i < cpyLines.size(); i++) {
|
||||
String line = cpyLines.get(i);
|
||||
|
||||
if (line.startsWith("%center%")) {
|
||||
int length = Math.max(0, line.length() - 8);
|
||||
int diff = biggestLine - length;
|
||||
|
||||
int left = diff / 2;
|
||||
int right = diff - left;
|
||||
|
||||
line = " ".repeat(left)
|
||||
+ line.substring(8)
|
||||
+ " ".repeat(right);
|
||||
}
|
||||
|
||||
playerInfos[i] = new ServerPing.PlayerInfo(line, "");
|
||||
playerInfos[i] = new ServerPing.PlayerInfo(cpyLines.get(i), "");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+85
-83
@@ -1,83 +1,85 @@
|
||||
package de.rayzs.pat.plugin.listeners.bungee;
|
||||
|
||||
import de.rayzs.pat.plugin.system.serverbrand.CustomServerBrand;
|
||||
import de.rayzs.pat.api.event.PATEventHandler;
|
||||
import de.rayzs.pat.api.event.events.ServerPlayersChangeEvent;
|
||||
import de.rayzs.pat.plugin.packetanalyzer.proxy.BungeePacketAnalyzer;
|
||||
import de.rayzs.pat.plugin.system.subargument.SubArgument;
|
||||
import de.rayzs.pat.utils.permission.PermissionUtil;
|
||||
import de.rayzs.pat.utils.message.MessageTranslator;
|
||||
import de.rayzs.pat.utils.sender.CommandSender;
|
||||
import net.md_5.bungee.api.connection.ProxiedPlayer;
|
||||
import net.md_5.bungee.api.plugin.Listener;
|
||||
import de.rayzs.pat.api.storage.Storage;
|
||||
import de.rayzs.pat.plugin.BungeeLoader;
|
||||
import net.md_5.bungee.api.ProxyServer;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import net.md_5.bungee.api.event.*;
|
||||
import net.md_5.bungee.event.*;
|
||||
|
||||
public class BungeePlayerConnectionListener implements Listener {
|
||||
|
||||
@EventHandler (priority = EventPriority.LOWEST)
|
||||
public void onPostLogin(PostLoginEvent event) {
|
||||
final ProxiedPlayer player = event.getPlayer();
|
||||
final CommandSender sender = CommandSender.from(player);
|
||||
|
||||
PATEventHandler.callServerPlayersChangeEvents(sender, ServerPlayersChangeEvent.Type.JOINED);
|
||||
SubArgument.get().updateCachedPlayerNames();
|
||||
|
||||
if(CustomServerBrand.get().isEnabled())
|
||||
ProxyServer.getInstance().getScheduler().schedule(BungeeLoader.getPlugin(), () -> {
|
||||
if (player.isConnected()) CustomServerBrand.get().sendBrandToPlayer(player);
|
||||
}, 500, TimeUnit.MILLISECONDS);
|
||||
|
||||
PermissionUtil.setPlayerPermissions(sender);
|
||||
|
||||
if (Storage.OUTDATED && PermissionUtil.hasPermission(sender, "joinupdate")) {
|
||||
ProxyServer.getInstance().getScheduler().schedule(BungeeLoader.getPlugin(), () -> {
|
||||
if (player.isConnected()) {
|
||||
MessageTranslator.send(player, Storage.ConfigSections.Settings.UPDATE.OUTDATED, "%player%", player.getName());
|
||||
}
|
||||
}, 1, TimeUnit.SECONDS);
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler (priority = EventPriority.LOWEST)
|
||||
public void onServerSwitch(ServerSwitchEvent event) {
|
||||
ProxiedPlayer player = event.getPlayer();
|
||||
|
||||
BungeePacketAnalyzer.inject(player);
|
||||
|
||||
if (Storage.ConfigSections.Settings.UPDATE_GROUPS_PER_SERVER.ENABLED) {
|
||||
CommandSender sender = CommandSender.from(player);
|
||||
|
||||
assert sender != null;
|
||||
PermissionUtil.reloadPermissions(sender);
|
||||
}
|
||||
|
||||
if (Storage.ConfigSections.Settings.CUSTOM_BRAND.REPEAT_DELAY != -1) {
|
||||
return;
|
||||
}
|
||||
|
||||
CustomServerBrand.get().sendBrandToPlayer(player);
|
||||
}
|
||||
|
||||
@EventHandler (priority = EventPriority.LOWEST)
|
||||
public void onPlayerDisconnectEvent(PlayerDisconnectEvent event) {
|
||||
final ProxiedPlayer player = event.getPlayer();
|
||||
final CommandSender sender = CommandSender.from(player);
|
||||
|
||||
PATEventHandler.callServerPlayersChangeEvents(sender, ServerPlayersChangeEvent.Type.LEFT);
|
||||
SubArgument.get().updateCachedPlayerNames();
|
||||
|
||||
PermissionUtil.resetPermissions(player.getUniqueId());
|
||||
BungeePacketAnalyzer.uninject(player);
|
||||
|
||||
if (Storage.ConfigSections.Settings.CUSTOM_BRAND.REPEAT_DELAY != -1) {
|
||||
return;
|
||||
}
|
||||
|
||||
CustomServerBrand.get().sendBrandToPlayer(player);
|
||||
}
|
||||
}
|
||||
package de.rayzs.pat.plugin.listeners.bungee;
|
||||
|
||||
import de.rayzs.pat.plugin.system.serverbrand.CustomServerBrand;
|
||||
import de.rayzs.pat.api.event.PATEventHandler;
|
||||
import de.rayzs.pat.api.event.events.ServerPlayersChangeEvent;
|
||||
import de.rayzs.pat.plugin.packetanalyzer.proxy.BungeePacketAnalyzer;
|
||||
import de.rayzs.pat.plugin.system.subargument.SubArgument;
|
||||
import de.rayzs.pat.utils.permission.PermissionUtil;
|
||||
import de.rayzs.pat.utils.message.MessageHelper;
|
||||
import de.rayzs.pat.utils.sender.CommandSender;
|
||||
import net.md_5.bungee.api.connection.ProxiedPlayer;
|
||||
|
||||
import java.util.Objects;
|
||||
import net.md_5.bungee.api.plugin.Listener;
|
||||
import de.rayzs.pat.api.storage.Storage;
|
||||
import de.rayzs.pat.plugin.BungeeLoader;
|
||||
import net.md_5.bungee.api.ProxyServer;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import net.md_5.bungee.api.event.*;
|
||||
import net.md_5.bungee.event.*;
|
||||
|
||||
public class BungeePlayerConnectionListener implements Listener {
|
||||
|
||||
@EventHandler (priority = EventPriority.LOWEST)
|
||||
public void onPostLogin(PostLoginEvent event) {
|
||||
final ProxiedPlayer player = event.getPlayer();
|
||||
final CommandSender sender = CommandSender.from(player);
|
||||
|
||||
PATEventHandler.callServerPlayersChangeEvents(sender, ServerPlayersChangeEvent.Type.JOINED);
|
||||
SubArgument.get().updateCachedPlayerNames();
|
||||
|
||||
if(CustomServerBrand.get().isEnabled())
|
||||
ProxyServer.getInstance().getScheduler().schedule(BungeeLoader.getPlugin(), () -> {
|
||||
if (player.isConnected()) CustomServerBrand.get().sendBrandToPlayer(player);
|
||||
}, 500, TimeUnit.MILLISECONDS);
|
||||
|
||||
PermissionUtil.setPlayerPermissions(sender);
|
||||
|
||||
if (Storage.OUTDATED && PermissionUtil.hasPermission(sender, "joinupdate", false)) {
|
||||
ProxyServer.getInstance().getScheduler().schedule(BungeeLoader.getPlugin(), () -> {
|
||||
if (player.isConnected()) {
|
||||
MessageHelper.sendMessage(sender, Storage.ConfigSections.Settings.UPDATE.OUTDATED, "%player%", player.getName());
|
||||
}
|
||||
}, 1, TimeUnit.SECONDS);
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler (priority = EventPriority.LOWEST)
|
||||
public void onServerSwitch(ServerSwitchEvent event) {
|
||||
ProxiedPlayer player = event.getPlayer();
|
||||
|
||||
BungeePacketAnalyzer.inject(player);
|
||||
|
||||
if (Storage.ConfigSections.Settings.UPDATE_GROUPS_PER_SERVER.ENABLED) {
|
||||
CommandSender sender = CommandSender.from(player);
|
||||
|
||||
Objects.requireNonNull(sender);
|
||||
PermissionUtil.reloadPermissions(sender);
|
||||
}
|
||||
|
||||
if (Storage.ConfigSections.Settings.CUSTOM_BRAND.REPEAT_DELAY != -1) {
|
||||
return;
|
||||
}
|
||||
|
||||
CustomServerBrand.get().sendBrandToPlayer(player);
|
||||
}
|
||||
|
||||
@EventHandler (priority = EventPriority.LOWEST)
|
||||
public void onPlayerDisconnectEvent(PlayerDisconnectEvent event) {
|
||||
final ProxiedPlayer player = event.getPlayer();
|
||||
final CommandSender sender = CommandSender.from(player);
|
||||
|
||||
PATEventHandler.callServerPlayersChangeEvents(sender, ServerPlayersChangeEvent.Type.LEFT);
|
||||
SubArgument.get().updateCachedPlayerNames();
|
||||
|
||||
PermissionUtil.resetPermissions(player.getUniqueId());
|
||||
BungeePacketAnalyzer.uninject(player);
|
||||
|
||||
if (Storage.ConfigSections.Settings.CUSTOM_BRAND.REPEAT_DELAY != -1) {
|
||||
return;
|
||||
}
|
||||
|
||||
CustomServerBrand.get().sendBrandToPlayer(player);
|
||||
}
|
||||
}
|
||||
@@ -1,73 +1,70 @@
|
||||
package de.rayzs.pat.plugin.listeners.bungee;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import de.rayzs.pat.api.event.PATEventHandler;
|
||||
import de.rayzs.pat.api.event.events.FilteredSuggestionEvent;
|
||||
import de.rayzs.pat.api.storage.Storage;
|
||||
import de.rayzs.pat.utils.CommandsCache;
|
||||
import de.rayzs.pat.utils.group.Group;
|
||||
import de.rayzs.pat.utils.group.GroupManager;
|
||||
import de.rayzs.pat.utils.permission.PermissionUtil;
|
||||
import de.rayzs.pat.utils.sender.CommandSender;
|
||||
import io.github.waterfallmc.waterfall.event.ProxyDefineCommandsEvent;
|
||||
import net.md_5.bungee.api.connection.ProxiedPlayer;
|
||||
import net.md_5.bungee.api.plugin.Command;
|
||||
import net.md_5.bungee.api.plugin.Listener;
|
||||
import net.md_5.bungee.event.EventHandler;
|
||||
import net.md_5.bungee.event.EventPriority;
|
||||
|
||||
public class WaterfallAntiTabListener implements Listener {
|
||||
|
||||
@EventHandler(priority = EventPriority.LOWEST)
|
||||
public void onProxyDefineCommands(ProxyDefineCommandsEvent event) {
|
||||
if (!(event.getReceiver() instanceof ProxiedPlayer) || event.getCommands().isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
final ProxiedPlayer player = (ProxiedPlayer) event.getReceiver();
|
||||
final CommandSender sender = CommandSender.from(player);
|
||||
final String serverName = player.getServer().getInfo().getName();
|
||||
|
||||
if (Storage.Blacklist.isDisabledServer(serverName) || PermissionUtil.hasBypassPermission(sender)) {
|
||||
return;
|
||||
}
|
||||
|
||||
final List<Group> groups = GroupManager.getPlayerGroups(sender);
|
||||
final Map<String, CommandsCache> cache = Storage.getLoader().getPerServerCommandsCacheMap();
|
||||
|
||||
if (!cache.containsKey(serverName)) {
|
||||
cache.put(serverName, new CommandsCache());
|
||||
}
|
||||
|
||||
final CommandsCache commandsCache = cache.get(serverName);
|
||||
final List<String> commandsAsString = new ArrayList<>();
|
||||
final HashMap<String, Command> commandsMap = new HashMap<>(event.getCommands());
|
||||
|
||||
event.getCommands().forEach((key, value) -> commandsAsString.add(key));
|
||||
commandsCache.handleCommands(commandsAsString, serverName);
|
||||
|
||||
List<String> playerCommands = commandsCache.getPlayerCommands(commandsAsString, sender, groups, serverName);
|
||||
event.getCommands().entrySet().removeIf(command -> {
|
||||
|
||||
if (Storage.ConfigSections.Settings.CUSTOM_PLUGIN.isTabCompletable(command.getKey()) || Storage.ConfigSections.Settings.CUSTOM_VERSION.isTabCompletable(command.getKey())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return playerCommands.contains(command.getKey());
|
||||
});
|
||||
|
||||
FilteredSuggestionEvent filteredSuggestionEvent = PATEventHandler.callFilteredSuggestionEvents(sender, new ArrayList<>(event.getCommands().keySet()));
|
||||
if (filteredSuggestionEvent.isCancelled()) event.getCommands().clear();
|
||||
|
||||
for (String commandName : filteredSuggestionEvent.getSuggestions()) {
|
||||
|
||||
if (!event.getCommands().containsKey(commandName))
|
||||
event.getCommands().put(commandName, commandsMap.get(commandName));
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
package de.rayzs.pat.plugin.listeners.bungee;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
import de.rayzs.pat.api.event.PATEventHandler;
|
||||
import de.rayzs.pat.api.event.events.FilteredSuggestionEvent;
|
||||
import de.rayzs.pat.api.storage.Storage;
|
||||
import de.rayzs.pat.utils.CommandsCache;
|
||||
import de.rayzs.pat.utils.group.Group;
|
||||
import de.rayzs.pat.utils.group.GroupManager;
|
||||
import de.rayzs.pat.utils.permission.PermissionUtil;
|
||||
import de.rayzs.pat.utils.sender.CommandSender;
|
||||
import io.github.waterfallmc.waterfall.event.ProxyDefineCommandsEvent;
|
||||
import net.md_5.bungee.api.connection.ProxiedPlayer;
|
||||
import net.md_5.bungee.api.plugin.Command;
|
||||
import net.md_5.bungee.api.plugin.Listener;
|
||||
import net.md_5.bungee.event.EventHandler;
|
||||
import net.md_5.bungee.event.EventPriority;
|
||||
|
||||
public class WaterfallAntiTabListener implements Listener {
|
||||
|
||||
@EventHandler(priority = EventPriority.LOWEST)
|
||||
public void onProxyDefineCommands(ProxyDefineCommandsEvent event) {
|
||||
if (!(event.getReceiver() instanceof ProxiedPlayer) || event.getCommands().isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
final ProxiedPlayer player = (ProxiedPlayer) event.getReceiver();
|
||||
final CommandSender sender = CommandSender.from(player);
|
||||
final String serverName = player.getServer().getInfo().getName();
|
||||
|
||||
if (Storage.Blacklist.isDisabledServer(serverName) || PermissionUtil.hasBypassPermission(sender, false)) {
|
||||
return;
|
||||
}
|
||||
|
||||
final List<Group> groups = GroupManager.getPlayerGroups(sender, false);
|
||||
final Map<String, CommandsCache> cache = Storage.getLoader().getPerServerCommandsCacheMap();
|
||||
|
||||
if (!cache.containsKey(serverName)) {
|
||||
cache.put(serverName, new CommandsCache());
|
||||
}
|
||||
|
||||
final CommandsCache commandsCache = cache.get(serverName);
|
||||
final List<String> commandsAsString = new ArrayList<>();
|
||||
final HashMap<String, Command> commandsMap = new HashMap<>(event.getCommands());
|
||||
|
||||
event.getCommands().forEach((key, value) -> commandsAsString.add(key));
|
||||
commandsCache.handleCommands(commandsAsString, serverName);
|
||||
|
||||
HashSet<String> playerCommands = commandsCache.getPlayerCommands(commandsAsString, sender, groups, serverName, false);
|
||||
event.getCommands().entrySet().removeIf(command -> {
|
||||
|
||||
if (Storage.ConfigSections.Settings.CUSTOM_PLUGIN.isTabCompletable(command.getKey()) || Storage.ConfigSections.Settings.CUSTOM_VERSION.isTabCompletable(command.getKey())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return playerCommands.contains(command.getKey());
|
||||
});
|
||||
|
||||
FilteredSuggestionEvent filteredSuggestionEvent = PATEventHandler.callFilteredSuggestionEvents(sender, new HashSet<>(event.getCommands().keySet()));
|
||||
if (filteredSuggestionEvent.isCancelled()) event.getCommands().clear();
|
||||
|
||||
for (String commandName : filteredSuggestionEvent.getSuggestions()) {
|
||||
|
||||
if (!event.getCommands().containsKey(commandName))
|
||||
event.getCommands().put(commandName, commandsMap.get(commandName));
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
+135
-134
@@ -1,134 +1,135 @@
|
||||
package de.rayzs.pat.plugin.listeners.velocity;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import com.velocitypowered.api.event.PostOrder;
|
||||
import com.velocitypowered.api.event.Subscribe;
|
||||
import com.velocitypowered.api.event.command.PlayerAvailableCommandsEvent;
|
||||
import com.velocitypowered.api.event.player.TabCompleteEvent;
|
||||
import com.velocitypowered.api.proxy.Player;
|
||||
import com.velocitypowered.api.proxy.ProxyServer;
|
||||
|
||||
import de.rayzs.pat.api.event.PATEventHandler;
|
||||
import de.rayzs.pat.api.event.events.FilteredSuggestionEvent;
|
||||
import de.rayzs.pat.api.storage.Storage;
|
||||
import de.rayzs.pat.plugin.logger.Logger;
|
||||
import de.rayzs.pat.utils.CommandsCache;
|
||||
import de.rayzs.pat.utils.group.Group;
|
||||
import de.rayzs.pat.utils.group.GroupManager;
|
||||
import de.rayzs.pat.utils.permission.PermissionUtil;
|
||||
import de.rayzs.pat.utils.sender.CommandSender;
|
||||
|
||||
public class VelocityAntiTabListener {
|
||||
|
||||
private static ProxyServer server;
|
||||
|
||||
public VelocityAntiTabListener(ProxyServer server) {
|
||||
VelocityAntiTabListener.server = server;
|
||||
}
|
||||
|
||||
@Subscribe (order = PostOrder.LAST)
|
||||
public void onTabComplete(TabCompleteEvent event) {
|
||||
final Player player = event.getPlayer();
|
||||
|
||||
if (!event.getPartialMessage().startsWith("/")) {
|
||||
return;
|
||||
}
|
||||
|
||||
final String serverName = player.getCurrentServer().isPresent() ? player.getCurrentServer().get().getServerInfo().getName() : "unknown";
|
||||
|
||||
if (Storage.Blacklist.isDisabledServer(serverName)) {
|
||||
return;
|
||||
}
|
||||
|
||||
final CommandSender sender = CommandSender.from(player);
|
||||
|
||||
if (PermissionUtil.hasBypassPermission(sender) || event.getSuggestions().isEmpty() || player.getCurrentServer().isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
final List<Group> groups = GroupManager.getPlayerGroups(sender);
|
||||
|
||||
event.getSuggestions().removeIf(command -> {
|
||||
if (Storage.ConfigSections.Settings.CUSTOM_PLUGIN.isTabCompletable(command) || Storage.ConfigSections.Settings.CUSTOM_VERSION.isTabCompletable(command)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return !Storage.Blacklist.canPlayerAccessTab(sender, groups, command, serverName);
|
||||
});
|
||||
|
||||
FilteredSuggestionEvent filteredSuggestionEvent = PATEventHandler.callFilteredSuggestionEvents(sender, event.getSuggestions());
|
||||
if(filteredSuggestionEvent.isCancelled()) event.getSuggestions().clear();
|
||||
}
|
||||
|
||||
@Subscribe (order = PostOrder.LAST)
|
||||
public void onPlayerAvailableCommands(PlayerAvailableCommandsEvent event) {
|
||||
try {
|
||||
final Player player = event.getPlayer();
|
||||
|
||||
if (event.getRootNode().getChildren().isEmpty() || !player.getCurrentServer().isPresent()) {
|
||||
return;
|
||||
}
|
||||
|
||||
final CommandSender sender = CommandSender.from(player);
|
||||
|
||||
if (PermissionUtil.hasBypassPermission(sender)) {
|
||||
return;
|
||||
}
|
||||
|
||||
final String serverName = player.getCurrentServer().get().getServer().getServerInfo().getName();
|
||||
|
||||
if (Storage.Blacklist.isDisabledServer(serverName)) {
|
||||
return;
|
||||
}
|
||||
|
||||
Map<String, CommandsCache> cache = Storage.getLoader().getPerServerCommandsCacheMap();
|
||||
|
||||
if (!cache.containsKey(serverName)) {
|
||||
cache.put(serverName, new CommandsCache());
|
||||
}
|
||||
|
||||
final CommandsCache commandsCache = cache.get(serverName);
|
||||
final List<Group> groups = GroupManager.getPlayerGroups(sender);
|
||||
final 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);
|
||||
|
||||
final boolean newer = player.getProtocolVersion().getProtocol() > 340, argsChildrenExist = event.getRootNode().getChild("args") != null;
|
||||
final List<String> playerCommands = commandsCache.getPlayerCommands(commandsAsString, sender, groups, serverName);
|
||||
|
||||
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;
|
||||
|
||||
if (Storage.ConfigSections.Settings.CUSTOM_PLUGIN.isTabCompletable(command.getName()) || Storage.ConfigSections.Settings.CUSTOM_VERSION.isTabCompletable(command.getName())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return !playerCommands.contains(command.getName());
|
||||
});
|
||||
} catch (Exception exception) {
|
||||
Logger.warning("An error occurred while processing commands in PAT: " + exception.getMessage());
|
||||
exception.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
package de.rayzs.pat.plugin.listeners.velocity;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import com.velocitypowered.api.event.PostOrder;
|
||||
import com.velocitypowered.api.event.Subscribe;
|
||||
import com.velocitypowered.api.event.command.PlayerAvailableCommandsEvent;
|
||||
import com.velocitypowered.api.event.player.TabCompleteEvent;
|
||||
import com.velocitypowered.api.proxy.Player;
|
||||
import com.velocitypowered.api.proxy.ProxyServer;
|
||||
|
||||
import de.rayzs.pat.api.event.PATEventHandler;
|
||||
import de.rayzs.pat.api.event.events.FilteredSuggestionEvent;
|
||||
import de.rayzs.pat.api.storage.Storage;
|
||||
import de.rayzs.pat.plugin.logger.Logger;
|
||||
import de.rayzs.pat.utils.CommandsCache;
|
||||
import de.rayzs.pat.utils.group.Group;
|
||||
import de.rayzs.pat.utils.group.GroupManager;
|
||||
import de.rayzs.pat.utils.permission.PermissionUtil;
|
||||
import de.rayzs.pat.utils.sender.CommandSender;
|
||||
|
||||
public class VelocityAntiTabListener {
|
||||
|
||||
private final ProxyServer server;
|
||||
|
||||
public VelocityAntiTabListener(ProxyServer server) {
|
||||
this.server = server;
|
||||
}
|
||||
|
||||
@Subscribe (order = PostOrder.LAST)
|
||||
public void onTabComplete(TabCompleteEvent event) {
|
||||
final Player player = event.getPlayer();
|
||||
|
||||
if (!event.getPartialMessage().startsWith("/")) {
|
||||
return;
|
||||
}
|
||||
|
||||
final String serverName = player.getCurrentServer().isPresent() ? player.getCurrentServer().get().getServerInfo().getName() : "unknown";
|
||||
|
||||
if (Storage.Blacklist.isDisabledServer(serverName)) {
|
||||
return;
|
||||
}
|
||||
|
||||
final CommandSender sender = CommandSender.from(player);
|
||||
|
||||
if (PermissionUtil.hasBypassPermission(sender, false) || event.getSuggestions().isEmpty() || player.getCurrentServer().isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
final List<Group> groups = GroupManager.getPlayerGroups(sender, false);
|
||||
|
||||
event.getSuggestions().removeIf(command -> {
|
||||
if (Storage.ConfigSections.Settings.CUSTOM_PLUGIN.isTabCompletable(command) || Storage.ConfigSections.Settings.CUSTOM_VERSION.isTabCompletable(command)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return !Storage.Blacklist.canPlayerAccessTab(sender, groups, command, serverName, false);
|
||||
});
|
||||
|
||||
FilteredSuggestionEvent filteredSuggestionEvent = PATEventHandler.callFilteredSuggestionEvents(sender, new HashSet<>(event.getSuggestions()));
|
||||
if(filteredSuggestionEvent.isCancelled()) event.getSuggestions().clear();
|
||||
}
|
||||
|
||||
@Subscribe (order = PostOrder.LAST)
|
||||
public void onPlayerAvailableCommands(PlayerAvailableCommandsEvent event) {
|
||||
try {
|
||||
final Player player = event.getPlayer();
|
||||
|
||||
if (event.getRootNode().getChildren().isEmpty() || !player.getCurrentServer().isPresent()) {
|
||||
return;
|
||||
}
|
||||
|
||||
final CommandSender sender = CommandSender.from(player);
|
||||
|
||||
if (PermissionUtil.hasBypassPermission(sender, false)) {
|
||||
return;
|
||||
}
|
||||
|
||||
final String serverName = player.getCurrentServer().get().getServer().getServerInfo().getName();
|
||||
|
||||
if (Storage.Blacklist.isDisabledServer(serverName)) {
|
||||
return;
|
||||
}
|
||||
|
||||
Map<String, CommandsCache> cache = Storage.getLoader().getPerServerCommandsCacheMap();
|
||||
|
||||
if (!cache.containsKey(serverName)) {
|
||||
cache.put(serverName, new CommandsCache());
|
||||
}
|
||||
|
||||
final CommandsCache commandsCache = cache.get(serverName);
|
||||
final List<Group> groups = GroupManager.getPlayerGroups(sender, false);
|
||||
final 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);
|
||||
|
||||
final boolean newer = player.getProtocolVersion().getProtocol() > 340, argsChildrenExist = event.getRootNode().getChild("args") != null;
|
||||
final HashSet<String> playerCommands = commandsCache.getPlayerCommands(commandsAsString, sender, groups, serverName, false);
|
||||
|
||||
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;
|
||||
|
||||
if (Storage.ConfigSections.Settings.CUSTOM_PLUGIN.isTabCompletable(command.getName()) || Storage.ConfigSections.Settings.CUSTOM_VERSION.isTabCompletable(command.getName())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return !playerCommands.contains(command.getName());
|
||||
});
|
||||
} catch (Exception exception) {
|
||||
Logger.warning("An error occurred while processing commands in PAT: " + exception.getMessage());
|
||||
exception.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
+231
-214
@@ -1,215 +1,232 @@
|
||||
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.plugin.logger.Logger;
|
||||
import de.rayzs.pat.plugin.system.communication.Communicator;
|
||||
import de.rayzs.pat.api.event.events.ExecuteCommandEvent;
|
||||
import de.rayzs.pat.plugin.system.subargument.SubArgument;
|
||||
import de.rayzs.pat.utils.group.Group;
|
||||
import de.rayzs.pat.utils.group.GroupManager;
|
||||
import de.rayzs.pat.utils.message.MessageTranslator;
|
||||
import de.rayzs.pat.utils.permission.PermissionUtil;
|
||||
import com.velocitypowered.api.proxy.Player;
|
||||
import de.rayzs.pat.api.storage.Storage;
|
||||
import de.rayzs.pat.utils.StringUtils;
|
||||
import de.rayzs.pat.api.event.*;
|
||||
import de.rayzs.pat.utils.response.ResponseHandler;
|
||||
import de.rayzs.pat.utils.sender.CommandSender;
|
||||
|
||||
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));
|
||||
}
|
||||
|
||||
public static CommandExecuteEvent handleCommand(CommandExecuteEvent event) {
|
||||
if (!event.getResult().isAllowed()) {
|
||||
return event;
|
||||
}
|
||||
|
||||
final CommandSource commandSource = event.getCommandSource();
|
||||
final Object consoleSender = Storage.getLoader().getConsoleSender();
|
||||
|
||||
if(! (commandSource instanceof Player))
|
||||
return event;
|
||||
|
||||
final Player player = (Player) commandSource;
|
||||
final CommandSender sender = CommandSender.from(player);
|
||||
final String serverName = player.getCurrentServer().isPresent()
|
||||
? player.getCurrentServer().get().getServerInfo().getName()
|
||||
: "unknown";
|
||||
|
||||
final String commandWithArguments = event.getCommand().startsWith("/") ? event.getCommand().substring(1) : event.getCommand();
|
||||
|
||||
String tmpCommand = StringUtils.getFirstArg(event.getCommand());
|
||||
if (Communicator.get().hasConnectedClients() && Storage.ConfigSections.Settings.AUTO_LOWERCASE_COMMANDS.isCommand(tmpCommand)) {
|
||||
tmpCommand = tmpCommand.toLowerCase();
|
||||
}
|
||||
|
||||
final String command = tmpCommand;
|
||||
|
||||
if (PermissionUtil.hasBypassPermission(sender, command) || Storage.Blacklist.isDisabledServer(serverName))
|
||||
return event;
|
||||
|
||||
final String displayCommand = StringUtils.replaceTriggers(command, "", "\\", "<", ">", "&");
|
||||
|
||||
|
||||
final List<String> notificationMessage = MessageTranslator.replaceMessageList(
|
||||
Storage.ConfigSections.Messages.NOTIFICATION.ALERT,
|
||||
"%player%", player.getUsername(),
|
||||
"%command%", displayCommand,
|
||||
"%server%", serverName
|
||||
);
|
||||
|
||||
if (Storage.ConfigSections.Settings.CUSTOM_PLUGIN.isCommand(command)) {
|
||||
|
||||
Communicator.Proxy2Backend.sendNotification(player.getUniqueId(), serverName, displayCommand);
|
||||
|
||||
MessageTranslator.send(
|
||||
player,
|
||||
Storage.ConfigSections.Settings.CUSTOM_PLUGIN.MESSAGE,
|
||||
"%command%", StringUtils.getFirstArg(displayCommand)
|
||||
);
|
||||
|
||||
if (Storage.SEND_CONSOLE_NOTIFICATION)
|
||||
MessageTranslator.send(consoleSender, notificationMessage);
|
||||
|
||||
Storage.NOTIFY_PLAYERS.forEach(uuid -> {
|
||||
Object p = Storage.getLoader().getPlayerObjByUUID(uuid);
|
||||
if (p != null) {
|
||||
MessageTranslator.send(p, notificationMessage);
|
||||
}
|
||||
});
|
||||
|
||||
event.setResult(CommandExecuteEvent.CommandResult.denied());
|
||||
return event;
|
||||
}
|
||||
|
||||
if (Storage.ConfigSections.Settings.CUSTOM_VERSION.isCommand(command)) {
|
||||
|
||||
Communicator.Proxy2Backend.sendNotification(player.getUniqueId(), serverName, displayCommand);
|
||||
|
||||
MessageTranslator.send(
|
||||
player,
|
||||
Storage.ConfigSections.Settings.CUSTOM_VERSION.MESSAGE,
|
||||
"%command%", StringUtils.getFirstArg(displayCommand)
|
||||
);
|
||||
|
||||
if (Storage.SEND_CONSOLE_NOTIFICATION)
|
||||
MessageTranslator.send(consoleSender, notificationMessage);
|
||||
|
||||
Storage.NOTIFY_PLAYERS.forEach(uuid -> {
|
||||
Object p = Storage.getLoader().getPlayerObjByUUID(uuid);
|
||||
if (p != null) {
|
||||
MessageTranslator.send(p, notificationMessage);
|
||||
}
|
||||
});
|
||||
|
||||
event.setResult(CommandExecuteEvent.CommandResult.denied());
|
||||
return event;
|
||||
}
|
||||
|
||||
final boolean cancelBlockedCommand = Storage.ConfigSections.Settings.CANCEL_COMMAND.ENABLED;
|
||||
final List<Group> groups = GroupManager.getPlayerGroups(sender);
|
||||
|
||||
boolean allowed = Storage.Blacklist.canPlayerAccessChat(sender, groups, command, serverName);
|
||||
boolean blockedNamespace = false;
|
||||
|
||||
|
||||
if (!Storage.ConfigSections.Settings.BLOCK_NAMESPACE_COMMANDS.doesBypass(sender)) {
|
||||
blockedNamespace = cancelBlockedCommand
|
||||
? Storage.ConfigSections.Settings.BLOCK_NAMESPACE_COMMANDS.isCommand(command)
|
||||
: Storage.ConfigSections.Settings.BLOCK_NAMESPACE_COMMANDS.doesAlwaysBlock(command);
|
||||
|
||||
if (blockedNamespace) allowed = false;
|
||||
}
|
||||
|
||||
|
||||
if (!Storage.ConfigSections.Settings.CANCEL_COMMAND.ENABLED && !blockedNamespace) {
|
||||
return event;
|
||||
}
|
||||
|
||||
|
||||
if (!allowed) {
|
||||
|
||||
ExecuteCommandEvent executeCommandEvent = PATEventHandler.callExecuteCommandEvents(
|
||||
sender,
|
||||
event.getCommand(),
|
||||
true,
|
||||
!Storage.ConfigSections.Settings.TURN_BLACKLIST_TO_WHITELIST.ENABLED
|
||||
);
|
||||
|
||||
if (executeCommandEvent.isBlocked()) {
|
||||
event.setResult(CommandExecuteEvent.CommandResult.denied());
|
||||
|
||||
MessageTranslator.send(
|
||||
sender,
|
||||
ResponseHandler.getResponse(
|
||||
sender.getUniqueId(),
|
||||
sender.getName(),
|
||||
serverName,
|
||||
event.getCommand(),
|
||||
Storage.ConfigSections.Settings.CANCEL_COMMAND.BASE_COMMAND_RESPONSE.getLines()
|
||||
), "%command%", StringUtils.getFirstArg(displayCommand)
|
||||
);
|
||||
|
||||
if (!executeCommandEvent.doesNotify())
|
||||
return event;
|
||||
|
||||
Communicator.Proxy2Backend.sendNotification(player.getUniqueId(), serverName, displayCommand);
|
||||
|
||||
if (Storage.SEND_CONSOLE_NOTIFICATION)
|
||||
MessageTranslator.send(consoleSender, notificationMessage);
|
||||
|
||||
Storage.NOTIFY_PLAYERS.forEach(uuid -> {
|
||||
Object p = Storage.getLoader().getPlayerObjByUUID(uuid);
|
||||
if (p != null) {
|
||||
MessageTranslator.send(p, notificationMessage);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (executeCommandEvent.isCancelled())
|
||||
return event;
|
||||
}
|
||||
|
||||
|
||||
final ExecuteCommandEvent executeCommandEvent = PATEventHandler.callExecuteCommandEvents(
|
||||
sender,
|
||||
event.getCommand(),
|
||||
SubArgument.get().getExecuteHandler().handleCommandExecution(sender, event.getCommand()),
|
||||
false
|
||||
);
|
||||
|
||||
if (executeCommandEvent.isBlocked()) {
|
||||
event.setResult(CommandExecuteEvent.CommandResult.denied());
|
||||
|
||||
MessageTranslator.send(
|
||||
sender,
|
||||
ResponseHandler.getResponse(
|
||||
sender.getUniqueId(),
|
||||
sender.getName(),
|
||||
serverName,
|
||||
event.getCommand()
|
||||
),
|
||||
"%command%",
|
||||
StringUtils.replaceTriggers(
|
||||
commandWithArguments, "",
|
||||
"\\", "<", ">", "&"
|
||||
)
|
||||
);
|
||||
|
||||
}
|
||||
|
||||
return event;
|
||||
}
|
||||
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.plugin.system.communication.Communicator;
|
||||
import de.rayzs.pat.api.event.events.ExecuteCommandEvent;
|
||||
import de.rayzs.pat.plugin.system.subargument.SubArgument;
|
||||
import de.rayzs.pat.utils.group.Group;
|
||||
import de.rayzs.pat.utils.group.GroupManager;
|
||||
import de.rayzs.pat.utils.message.MessageHelper;
|
||||
import de.rayzs.pat.utils.permission.PermissionUtil;
|
||||
import com.velocitypowered.api.proxy.Player;
|
||||
import de.rayzs.pat.api.storage.Storage;
|
||||
import de.rayzs.pat.utils.StringUtils;
|
||||
import de.rayzs.pat.api.event.*;
|
||||
import de.rayzs.pat.utils.response.ResponseHandler;
|
||||
import de.rayzs.pat.utils.sender.CommandSender;
|
||||
|
||||
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));
|
||||
}
|
||||
|
||||
public static CommandExecuteEvent handleCommand(CommandExecuteEvent event) {
|
||||
if (!event.getResult().isAllowed()) {
|
||||
return event;
|
||||
}
|
||||
|
||||
final CommandSource commandSource = event.getCommandSource();
|
||||
final CommandSender consoleSender = CommandSender.from(Storage.getLoader().getConsoleSender());
|
||||
|
||||
if(! (commandSource instanceof Player))
|
||||
return event;
|
||||
|
||||
final Player player = (Player) commandSource;
|
||||
final CommandSender sender = CommandSender.from(player);
|
||||
final String serverName = player.getCurrentServer().isPresent()
|
||||
? player.getCurrentServer().get().getServerInfo().getName()
|
||||
: "unknown";
|
||||
|
||||
final String commandWithArguments = event.getCommand().startsWith("/") ? event.getCommand().substring(1) : event.getCommand();
|
||||
|
||||
String tmpCommand = StringUtils.getFirstArg(event.getCommand());
|
||||
if (Communicator.get().hasConnectedClients() && Storage.ConfigSections.Settings.AUTO_LOWERCASE_COMMANDS.isCommand(tmpCommand)) {
|
||||
tmpCommand = tmpCommand.toLowerCase();
|
||||
}
|
||||
|
||||
final String command = tmpCommand;
|
||||
|
||||
if (PermissionUtil.hasBypassPermission(sender, command, false) || Storage.Blacklist.isDisabledServer(serverName))
|
||||
return event;
|
||||
|
||||
final String displayCommand = StringUtils.replaceTriggers(command, "", "\\", "<", ">", "&");
|
||||
|
||||
|
||||
final String notificationMessage = StringUtils.replace(
|
||||
Storage.ConfigSections.Messages.NOTIFICATION.ALERT.getLines(),
|
||||
"%player%", player.getUsername(),
|
||||
"%command%", displayCommand,
|
||||
"%server%", serverName
|
||||
);
|
||||
|
||||
if (Storage.ConfigSections.Settings.CUSTOM_PLUGIN.isCommand(command)) {
|
||||
|
||||
Communicator.Proxy2Backend.sendNotification(player.getUniqueId(), serverName, displayCommand);
|
||||
|
||||
MessageHelper.sendMessage(
|
||||
sender,
|
||||
Storage.ConfigSections.Settings.CUSTOM_PLUGIN.MESSAGE,
|
||||
"%command%", StringUtils.getFirstArg(displayCommand)
|
||||
);
|
||||
|
||||
if (Storage.SEND_CONSOLE_NOTIFICATION)
|
||||
MessageHelper.sendMessage(consoleSender, notificationMessage);
|
||||
|
||||
Storage.NOTIFY_PLAYERS.forEach(uuid -> {
|
||||
final CommandSender otherSender = CommandSender.from(uuid);
|
||||
|
||||
if (otherSender != null) {
|
||||
MessageHelper.sendMessage(otherSender, notificationMessage);
|
||||
}
|
||||
});
|
||||
|
||||
event.setResult(CommandExecuteEvent.CommandResult.denied());
|
||||
return event;
|
||||
}
|
||||
|
||||
if (Storage.ConfigSections.Settings.CUSTOM_VERSION.isCommand(command)) {
|
||||
|
||||
Communicator.Proxy2Backend.sendNotification(player.getUniqueId(), serverName, displayCommand);
|
||||
|
||||
MessageHelper.sendMessage(
|
||||
sender,
|
||||
Storage.ConfigSections.Settings.CUSTOM_VERSION.MESSAGE,
|
||||
"%command%", StringUtils.getFirstArg(displayCommand)
|
||||
);
|
||||
|
||||
if (Storage.SEND_CONSOLE_NOTIFICATION)
|
||||
MessageHelper.sendMessage(consoleSender, notificationMessage);
|
||||
|
||||
Storage.NOTIFY_PLAYERS.forEach(uuid -> {
|
||||
final CommandSender otherSender = CommandSender.from(uuid);
|
||||
|
||||
if (otherSender != null) {
|
||||
MessageHelper.sendMessage(otherSender, notificationMessage);
|
||||
}
|
||||
});
|
||||
|
||||
event.setResult(CommandExecuteEvent.CommandResult.denied());
|
||||
return event;
|
||||
}
|
||||
|
||||
final boolean cancelBlockedCommand = Storage.ConfigSections.Settings.CANCEL_COMMAND.ENABLED;
|
||||
final List<Group> groups = GroupManager.getPlayerGroups(sender, false);
|
||||
|
||||
boolean allowed = Storage.Blacklist.canPlayerAccessChat(sender, groups, command, serverName, false);
|
||||
boolean blockedNamespace = false;
|
||||
|
||||
|
||||
if (!Storage.ConfigSections.Settings.BLOCK_NAMESPACE_COMMANDS.doesBypass(sender, false)) {
|
||||
blockedNamespace = cancelBlockedCommand
|
||||
? Storage.ConfigSections.Settings.BLOCK_NAMESPACE_COMMANDS.isCommand(command)
|
||||
: Storage.ConfigSections.Settings.BLOCK_NAMESPACE_COMMANDS.doesAlwaysBlock(command);
|
||||
|
||||
if (blockedNamespace) allowed = false;
|
||||
}
|
||||
|
||||
|
||||
if (!Storage.ConfigSections.Settings.CANCEL_COMMAND.ENABLED && !blockedNamespace) {
|
||||
return event;
|
||||
}
|
||||
|
||||
|
||||
if (!allowed) {
|
||||
ExecuteCommandEvent executeCommandEvent = PATEventHandler.callExecuteCommandEvents(
|
||||
sender,
|
||||
event.getCommand(),
|
||||
true,
|
||||
!Storage.ConfigSections.Settings.TURN_BLACKLIST_TO_WHITELIST.ENABLED
|
||||
);
|
||||
|
||||
if (executeCommandEvent.isBlocked()) {
|
||||
event.setResult(CommandExecuteEvent.CommandResult.denied());
|
||||
|
||||
MessageHelper.sendMessage(
|
||||
sender,
|
||||
ResponseHandler.getResponse(
|
||||
sender.getUniqueId(),
|
||||
sender.getName(),
|
||||
serverName,
|
||||
event.getCommand(),
|
||||
Storage.ConfigSections.Settings.CANCEL_COMMAND.BASE_COMMAND_RESPONSE.getLines()
|
||||
), "%command%", StringUtils.getFirstArg(displayCommand)
|
||||
);
|
||||
|
||||
if (!executeCommandEvent.doesNotify())
|
||||
return event;
|
||||
|
||||
Communicator.Proxy2Backend.sendNotification(player.getUniqueId(), serverName, displayCommand);
|
||||
|
||||
if (Storage.SEND_CONSOLE_NOTIFICATION)
|
||||
MessageHelper.sendMessage(consoleSender, notificationMessage);
|
||||
|
||||
Storage.NOTIFY_PLAYERS.forEach(uuid -> {
|
||||
final CommandSender otherSender = CommandSender.from(uuid);
|
||||
|
||||
if (otherSender != null) {
|
||||
MessageHelper.sendMessage(otherSender, notificationMessage);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (executeCommandEvent.isCancelled())
|
||||
return event;
|
||||
}
|
||||
|
||||
|
||||
final ExecuteCommandEvent executeCommandEvent = PATEventHandler.callExecuteCommandEvents(
|
||||
sender,
|
||||
event.getCommand(),
|
||||
SubArgument.get().getExecuteHandler().handleCommandExecution(sender, event.getCommand()),
|
||||
false
|
||||
);
|
||||
|
||||
if (executeCommandEvent.isBlocked()) {
|
||||
|
||||
/*
|
||||
if (event.getCommand().toLowerCase().contains("discord")) {
|
||||
Logger.info("Blocked for " + player.getUsername() + " (" + command + " -> " + event.getCommand() + ")");
|
||||
Logger.info("Groups: " + (groups.isEmpty() ? "None" : String.join(", ", groups.stream().map(Group::getGroupName).toList())));
|
||||
Logger.info("Server: " + serverName + " (" + sender.getServerName() + ")");
|
||||
Arguments argument = SubArgument.get().getPlayerArgument(sender);
|
||||
|
||||
if (argument != null) {
|
||||
Logger.info("Chat Arguments: " + String.join(", ", argument.CHAT_ARGUMENTS.getAllInputs()));
|
||||
Logger.info("Tab Arguments: " + String.join(", ", argument.TAB_ARGUMENTS.getAllInputs()));
|
||||
} else Logger.info("Arguments: /");
|
||||
}
|
||||
*/
|
||||
|
||||
|
||||
event.setResult(CommandExecuteEvent.CommandResult.denied());
|
||||
|
||||
MessageHelper.sendMessage(
|
||||
sender,
|
||||
ResponseHandler.getResponse(
|
||||
sender.getUniqueId(),
|
||||
sender.getName(),
|
||||
serverName,
|
||||
event.getCommand()
|
||||
),
|
||||
"%command%",
|
||||
StringUtils.replaceTriggers(
|
||||
commandWithArguments, "",
|
||||
"\\", "<", ">", "&"
|
||||
)
|
||||
);
|
||||
|
||||
}
|
||||
|
||||
return event;
|
||||
}
|
||||
}
|
||||
+120
-117
@@ -1,117 +1,120 @@
|
||||
package de.rayzs.pat.plugin.listeners.velocity;
|
||||
|
||||
import com.velocitypowered.api.event.connection.DisconnectEvent;
|
||||
import com.velocitypowered.api.proxy.server.ServerInfo;
|
||||
import de.rayzs.pat.plugin.system.serverbrand.CustomServerBrand;
|
||||
import de.rayzs.pat.api.event.PATEventHandler;
|
||||
import de.rayzs.pat.api.event.events.ServerPlayersChangeEvent;
|
||||
import de.rayzs.pat.plugin.packetanalyzer.proxy.VelocityPacketAnalyzer;
|
||||
import de.rayzs.pat.plugin.logger.Logger;
|
||||
import de.rayzs.pat.plugin.system.subargument.SubArgument;
|
||||
import de.rayzs.pat.utils.message.MessageTranslator;
|
||||
import de.rayzs.pat.utils.permission.PermissionUtil;
|
||||
import com.velocitypowered.api.event.Subscribe;
|
||||
import com.velocitypowered.api.event.player.*;
|
||||
import de.rayzs.pat.plugin.VelocityLoader;
|
||||
import de.rayzs.pat.api.storage.Storage;
|
||||
import com.velocitypowered.api.proxy.*;
|
||||
import de.rayzs.pat.utils.sender.CommandSender;
|
||||
import net.kyori.adventure.text.Component;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public class VelocityConnectionListener {
|
||||
|
||||
private final ProxyServer server;
|
||||
private final VelocityLoader loader;
|
||||
|
||||
public VelocityConnectionListener(ProxyServer server, VelocityLoader loader) {
|
||||
this.server = server;
|
||||
this.loader = loader;
|
||||
}
|
||||
|
||||
@Subscribe
|
||||
public void onServerPreConnect(ServerPreConnectEvent event) {
|
||||
final Player player = event.getPlayer();
|
||||
final CommandSender sender = CommandSender.from(player);
|
||||
|
||||
if (Storage.ConfigSections.Settings.UPDATE_GROUPS_PER_SERVER.ENABLED) {
|
||||
final ServerInfo serverInfo = event.getOriginalServer().getServerInfo();
|
||||
if (serverInfo != null) Storage.tempCachePlayerToServer(player.getUniqueId(), serverInfo.getName());
|
||||
}
|
||||
|
||||
PATEventHandler.callServerPlayersChangeEvents(sender, ServerPlayersChangeEvent.Type.JOINED);
|
||||
SubArgument.get().updateCachedPlayerNames();
|
||||
|
||||
if(CustomServerBrand.get().isEnabled())
|
||||
server.getScheduler().buildTask(loader, () -> {
|
||||
if (player.isActive()) CustomServerBrand.get().sendBrandToPlayer(player);
|
||||
}).delay(500, TimeUnit.MILLISECONDS).schedule();
|
||||
|
||||
PermissionUtil.setPlayerPermissions(sender);
|
||||
|
||||
if (Storage.OUTDATED && PermissionUtil.hasPermission(sender, "joinupdate")) {
|
||||
server.getScheduler().buildTask(loader, () -> {
|
||||
if (player.isActive())
|
||||
MessageTranslator.send(player, Storage.ConfigSections.Settings.UPDATE.OUTDATED, "%player%", player.getUsername());
|
||||
}).delay(1, TimeUnit.SECONDS).schedule();
|
||||
}
|
||||
}
|
||||
|
||||
@Subscribe
|
||||
public void onServerSwitch(ServerConnectedEvent event) {
|
||||
final Player player = event.getPlayer();
|
||||
|
||||
if (!VelocityPacketAnalyzer.isInjected(player)) {
|
||||
|
||||
if (!VelocityPacketAnalyzer.inject(player)) {
|
||||
server.getScheduler().buildTask(loader, () -> {
|
||||
if (!VelocityPacketAnalyzer.inject(player)) {
|
||||
if (Storage.ConfigSections.Settings.INJECTION_FAILED.ENABLED) {
|
||||
|
||||
Logger.info(MessageTranslator.replaceMessage(
|
||||
player,
|
||||
Storage.ConfigSections.Settings.INJECTION_FAILED.CONSOLE_MESSAGE
|
||||
));
|
||||
|
||||
player.disconnect(Component.text(
|
||||
MessageTranslator.replaceMessage(
|
||||
player,
|
||||
Storage.ConfigSections.Settings.INJECTION_FAILED.KICK_MESSAGE
|
||||
)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
}).delay(1, TimeUnit.SECONDS).schedule();
|
||||
}
|
||||
}
|
||||
|
||||
if (Storage.ConfigSections.Settings.UPDATE_GROUPS_PER_SERVER.ENABLED) {
|
||||
final ServerInfo serverInfo = event.getServer().getServerInfo();
|
||||
if (serverInfo != null) Storage.tempCachePlayerToServer(player.getUniqueId(), serverInfo.getName());
|
||||
|
||||
CommandSender sender = CommandSender.from(player);
|
||||
assert sender != null;
|
||||
PermissionUtil.reloadPermissions(sender);
|
||||
}
|
||||
|
||||
if (Storage.ConfigSections.Settings.CUSTOM_BRAND.REPEAT_DELAY != -1) {
|
||||
return;
|
||||
}
|
||||
|
||||
CustomServerBrand.get().sendBrandToPlayer(player);
|
||||
}
|
||||
|
||||
@Subscribe
|
||||
public void onDisconnect(DisconnectEvent event) {
|
||||
final Player player = event.getPlayer();
|
||||
final CommandSender sender = CommandSender.from(player);
|
||||
|
||||
PATEventHandler.callServerPlayersChangeEvents(sender, ServerPlayersChangeEvent.Type.LEFT);
|
||||
SubArgument.get().updateCachedPlayerNames();
|
||||
|
||||
PermissionUtil.resetPermissions(player.getUniqueId());
|
||||
VelocityPacketAnalyzer.uninject(player);
|
||||
}
|
||||
}
|
||||
package de.rayzs.pat.plugin.listeners.velocity;
|
||||
|
||||
import com.velocitypowered.api.event.connection.DisconnectEvent;
|
||||
import com.velocitypowered.api.proxy.server.ServerInfo;
|
||||
import de.rayzs.pat.plugin.system.serverbrand.CustomServerBrand;
|
||||
import de.rayzs.pat.api.event.PATEventHandler;
|
||||
import de.rayzs.pat.api.event.events.ServerPlayersChangeEvent;
|
||||
import de.rayzs.pat.plugin.packetanalyzer.proxy.VelocityPacketAnalyzer;
|
||||
import de.rayzs.pat.plugin.logger.Logger;
|
||||
import de.rayzs.pat.plugin.system.subargument.SubArgument;
|
||||
import de.rayzs.pat.utils.message.MessageHelper;
|
||||
import de.rayzs.pat.utils.message.replacer.PlaceholderReplacer;
|
||||
import de.rayzs.pat.utils.permission.PermissionUtil;
|
||||
import com.velocitypowered.api.event.Subscribe;
|
||||
import com.velocitypowered.api.event.player.*;
|
||||
import de.rayzs.pat.plugin.VelocityLoader;
|
||||
import de.rayzs.pat.api.storage.Storage;
|
||||
import com.velocitypowered.api.proxy.*;
|
||||
import de.rayzs.pat.utils.sender.CommandSender;
|
||||
import net.kyori.adventure.text.Component;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public class VelocityConnectionListener {
|
||||
|
||||
private final ProxyServer server;
|
||||
private final VelocityLoader loader;
|
||||
|
||||
public VelocityConnectionListener(ProxyServer server, VelocityLoader loader) {
|
||||
this.server = server;
|
||||
this.loader = loader;
|
||||
}
|
||||
|
||||
@Subscribe
|
||||
public void onServerPreConnect(ServerPreConnectEvent event) {
|
||||
final Player player = event.getPlayer();
|
||||
final CommandSender sender = CommandSender.from(player);
|
||||
|
||||
if (Storage.ConfigSections.Settings.UPDATE_GROUPS_PER_SERVER.ENABLED) {
|
||||
final ServerInfo serverInfo = event.getOriginalServer().getServerInfo();
|
||||
if (serverInfo != null) Storage.tempCachePlayerToServer(player.getUniqueId(), serverInfo.getName());
|
||||
}
|
||||
|
||||
PATEventHandler.callServerPlayersChangeEvents(sender, ServerPlayersChangeEvent.Type.JOINED);
|
||||
SubArgument.get().updateCachedPlayerNames();
|
||||
|
||||
if(CustomServerBrand.get().isEnabled())
|
||||
server.getScheduler().buildTask(loader, () -> {
|
||||
if (player.isActive()) CustomServerBrand.get().sendBrandToPlayer(player);
|
||||
}).delay(500, TimeUnit.MILLISECONDS).schedule();
|
||||
|
||||
PermissionUtil.setPlayerPermissions(sender);
|
||||
|
||||
if (Storage.OUTDATED && PermissionUtil.hasPermission(sender, "joinupdate", false)) {
|
||||
server.getScheduler().buildTask(loader, () -> {
|
||||
if (player.isActive())
|
||||
MessageHelper.sendMessage(sender, Storage.ConfigSections.Settings.UPDATE.OUTDATED, "%player%", player.getUsername());
|
||||
}).delay(1, TimeUnit.SECONDS).schedule();
|
||||
}
|
||||
}
|
||||
|
||||
@Subscribe
|
||||
public void onServerSwitch(ServerConnectedEvent event) {
|
||||
final Player player = event.getPlayer();
|
||||
final CommandSender sender = CommandSender.from(player);
|
||||
|
||||
if (!VelocityPacketAnalyzer.isInjected(player)) {
|
||||
|
||||
if (!VelocityPacketAnalyzer.inject(player)) {
|
||||
server.getScheduler().buildTask(loader, () -> {
|
||||
if (!VelocityPacketAnalyzer.inject(player)) {
|
||||
if (Storage.ConfigSections.Settings.INJECTION_FAILED.ENABLED) {
|
||||
|
||||
Logger.info(PlaceholderReplacer.applyPlaceholders(
|
||||
sender,
|
||||
Storage.ConfigSections.Settings.INJECTION_FAILED.CONSOLE_MESSAGE
|
||||
));
|
||||
|
||||
player.disconnect(Component.text(
|
||||
PlaceholderReplacer.applyPlaceholders(
|
||||
sender,
|
||||
Storage.ConfigSections.Settings.INJECTION_FAILED.KICK_MESSAGE
|
||||
)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
}).delay(1, TimeUnit.SECONDS).schedule();
|
||||
}
|
||||
}
|
||||
|
||||
if (Storage.ConfigSections.Settings.UPDATE_GROUPS_PER_SERVER.ENABLED) {
|
||||
final ServerInfo serverInfo = event.getServer().getServerInfo();
|
||||
if (serverInfo != null) Storage.tempCachePlayerToServer(player.getUniqueId(), serverInfo.getName());
|
||||
|
||||
Objects.requireNonNull(sender);
|
||||
PermissionUtil.reloadPermissions(sender);
|
||||
}
|
||||
|
||||
if (Storage.ConfigSections.Settings.CUSTOM_BRAND.REPEAT_DELAY != -1) {
|
||||
return;
|
||||
}
|
||||
|
||||
CustomServerBrand.get().sendBrandToPlayer(player);
|
||||
}
|
||||
|
||||
@Subscribe
|
||||
public void onDisconnect(DisconnectEvent event) {
|
||||
final Player player = event.getPlayer();
|
||||
final CommandSender sender = CommandSender.from(player);
|
||||
|
||||
PATEventHandler.callServerPlayersChangeEvents(sender, ServerPlayersChangeEvent.Type.LEFT);
|
||||
SubArgument.get().updateCachedPlayerNames();
|
||||
|
||||
PermissionUtil.resetPermissions(player.getUniqueId());
|
||||
VelocityPacketAnalyzer.uninject(player);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package de.rayzs.pat.plugin.listeners.velocity;
|
||||
|
||||
import com.velocitypowered.api.command.CommandSource;
|
||||
import com.velocitypowered.api.event.Subscribe;
|
||||
import com.velocitypowered.api.event.command.CommandExecuteEvent;
|
||||
import com.velocitypowered.api.proxy.Player;
|
||||
import com.velocitypowered.api.proxy.ProxyServer;
|
||||
import de.rayzs.pat.api.storage.Storage;
|
||||
import de.rayzs.pat.plugin.VelocityLoader;
|
||||
import de.rayzs.pat.utils.LuckPermsWarning;
|
||||
import de.rayzs.pat.utils.sender.CommandSender;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public class VelocityLuckPermsWarning {
|
||||
|
||||
private final ProxyServer server;
|
||||
|
||||
public VelocityLuckPermsWarning(ProxyServer server) {
|
||||
this.server = server;
|
||||
}
|
||||
|
||||
@Subscribe
|
||||
public void onCommandExecute(final CommandExecuteEvent event) {
|
||||
if (LuckPermsWarning.alreadyAnnounced()) return;
|
||||
|
||||
if (Storage.ConfigSections.Settings.UPDATE_GROUPS_PER_WORLD.ENABLED || Storage.ConfigSections.Settings.UPDATE_GROUPS_PER_SERVER.ENABLED) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
final CommandSource commandSource = event.getCommandSource();
|
||||
if(! (commandSource instanceof Player player)) return;
|
||||
|
||||
final CommandSender sender = CommandSender.from(player);
|
||||
final String command = event.getCommand();
|
||||
|
||||
if (LuckPermsWarning.shouldSendLuckPermsWarning(sender, command)) {
|
||||
server.getScheduler().buildTask(
|
||||
VelocityLoader.getInstance(),
|
||||
() -> LuckPermsWarning.sendAnnouncement(sender)
|
||||
).delay(1, TimeUnit.SECONDS).schedule();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import com.velocitypowered.api.proxy.server.ServerPing;
|
||||
import com.velocitypowered.api.proxy.ProxyServer;
|
||||
import com.velocitypowered.api.event.Subscribe;
|
||||
import de.rayzs.pat.api.storage.Storage;
|
||||
import de.rayzs.pat.utils.StringUtils;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
@@ -12,11 +13,11 @@ import java.util.UUID;
|
||||
|
||||
public class VelocityPingListener {
|
||||
|
||||
private static ProxyServer server;
|
||||
private static final UUID RANDOM_UUID = UUID.randomUUID();
|
||||
private ProxyServer server;
|
||||
|
||||
public VelocityPingListener(ProxyServer server) {
|
||||
VelocityPingListener.server = server;
|
||||
this.server = server;
|
||||
}
|
||||
|
||||
@Subscribe
|
||||
@@ -53,29 +54,10 @@ public class VelocityPingListener {
|
||||
} else {
|
||||
List<String> cpyLines = new ArrayList<>(Storage.ConfigSections.Settings.CUSTOM_PROTOCOL_PING.PLAYERLIST.getLines());
|
||||
|
||||
int biggestLine = 0;
|
||||
for (int i = 0; i < cpyLines.size(); i++) {
|
||||
String line = replaceString(cpyLines.get(i), online, extend, max);
|
||||
cpyLines.set(i, line);
|
||||
|
||||
if (line.startsWith("%center%")) {
|
||||
biggestLine = Math.max(biggestLine, Math.max(0, line.length() - 8));
|
||||
}
|
||||
}
|
||||
cpyLines.replaceAll(string -> replaceString(string, online, extend, max));
|
||||
StringUtils.centralize(cpyLines);
|
||||
|
||||
for (String line : cpyLines) {
|
||||
if (line.startsWith("%center%")) {
|
||||
int length = Math.max(0, line.length() - 8);
|
||||
int diff = biggestLine - length;
|
||||
|
||||
int left = diff / 2;
|
||||
int right = diff - left;
|
||||
|
||||
line = " ".repeat(left)
|
||||
+ line.substring(8)
|
||||
+ " ".repeat(right);
|
||||
}
|
||||
|
||||
builder.samplePlayers(new ServerPing.SamplePlayer(line, RANDOM_UUID));
|
||||
}
|
||||
|
||||
|
||||
@@ -1,188 +1,188 @@
|
||||
package de.rayzs.pat.plugin.logger;
|
||||
|
||||
import de.rayzs.pat.plugin.system.communication.Communicator;
|
||||
import de.rayzs.pat.plugin.system.communication.client.Client;
|
||||
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.utils.*;
|
||||
import de.rayzs.pat.utils.group.Group;
|
||||
import de.rayzs.pat.utils.group.GroupManager;
|
||||
import de.rayzs.pat.utils.permission.PermissionPlugin;
|
||||
|
||||
import java.net.URL;
|
||||
import java.util.*;
|
||||
import java.io.*;
|
||||
|
||||
public class Logger {
|
||||
|
||||
private static final String LOG_HEADER;
|
||||
|
||||
static {
|
||||
final String software = Reflection.getSoftware().isProxySoftware()
|
||||
? Reflection.getSoftware().toString()
|
||||
: Reflection.getVersionName();
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
public static void warning(List<String> messages) {
|
||||
LOGGER.warn(messages);
|
||||
}
|
||||
|
||||
public static void info(String message) {
|
||||
LOGGER.info(message);
|
||||
}
|
||||
|
||||
public static void warning(String message) {
|
||||
LOGGER.warn(message);
|
||||
}
|
||||
|
||||
public static String post() throws IOException {
|
||||
|
||||
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();
|
||||
DataOutputStream outputStream;
|
||||
String response;
|
||||
|
||||
connection.setDoOutput(true);
|
||||
connection.setInstanceFollowRedirects(false);
|
||||
connection.setRequestMethod("POST");
|
||||
connection.setRequestProperty("User-Agent", "ProAntiTab");
|
||||
connection.setRequestProperty("Content-Length", Integer.toString(postDataLength));
|
||||
connection.setUseCaches(false);
|
||||
|
||||
outputStream = new DataOutputStream(connection.getOutputStream());
|
||||
outputStream.write(textInBytes);
|
||||
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
|
||||
response = reader.readLine();
|
||||
|
||||
if (response == null || !response.contains("\"key\"")) return null;
|
||||
response = response.substring(response.indexOf(":") + 2, response.length() - 2);
|
||||
return "https://haste.rayzs.de/" + response + ".txt";
|
||||
}
|
||||
|
||||
private static String createInfo() {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
|
||||
if (!Reflection.isProxyServer()) {
|
||||
builder.append("Detected Software-API: ")
|
||||
.append(Reflection.getSoftware().toString())
|
||||
.append("\n\n");
|
||||
}
|
||||
|
||||
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("Installed plugins: \n ")
|
||||
.append(String.join("\n ", Storage.getLoader().getFormattedPluginNames("%n (%v)")))
|
||||
.append("\n\n");
|
||||
|
||||
builder.append("Detected supported plugins:")
|
||||
.append("\n");
|
||||
|
||||
builder.append(" LuckPerms: ")
|
||||
.append(Storage.getPermissionPlugin() == PermissionPlugin.LUCKPERMS)
|
||||
.append("\n");
|
||||
|
||||
if (!Reflection.isProxyServer()) {
|
||||
builder.append(" GroupManager: ")
|
||||
.append(Storage.getPermissionPlugin() == PermissionPlugin.GROUPMANAGER)
|
||||
.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 ? TimeConverter.calcAndGetTime(Communicator.get().getLastSync()) : "Deactivated")
|
||||
.append("\n");
|
||||
|
||||
builder.append("last-received-alive-response-packet: ")
|
||||
.append(Storage.ConfigSections.Settings.HANDLE_THROUGH_PROXY.ENABLED ? TimeConverter.calcAndGetTime(Communicator.get().getLastReceivedKeepAliveResponse()) : "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.ENABLED ? "Deactivated" : (TimeConverter.calcAndGetTime(Communicator.get().getLastSync())))
|
||||
.append("\n\n");
|
||||
|
||||
builder.append("synced-server: ");
|
||||
Iterator<Client> iterator = Communicator.get().getClients().iterator();
|
||||
while (iterator.hasNext()) {
|
||||
Client clientInfo = iterator.next();
|
||||
|
||||
builder.append(clientInfo.getServerName())
|
||||
.append(" (")
|
||||
.append(clientInfo.getFormattedLastReceivedKeepAlivePacketTime() + " / " + clientInfo.getFormattedSyncTime())
|
||||
.append(")");
|
||||
|
||||
if (iterator.hasNext()) {
|
||||
builder.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();
|
||||
}
|
||||
}
|
||||
package de.rayzs.pat.plugin.logger;
|
||||
|
||||
import de.rayzs.pat.plugin.system.communication.Communicator;
|
||||
import de.rayzs.pat.plugin.system.communication.client.Client;
|
||||
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.utils.*;
|
||||
import de.rayzs.pat.utils.group.Group;
|
||||
import de.rayzs.pat.utils.group.GroupManager;
|
||||
import de.rayzs.pat.utils.permission.PermissionPlugin;
|
||||
|
||||
import java.net.URL;
|
||||
import java.util.*;
|
||||
import java.io.*;
|
||||
|
||||
public class Logger {
|
||||
|
||||
private static final String LOG_HEADER;
|
||||
|
||||
static {
|
||||
final String software = Reflection.getSoftware().isProxySoftware()
|
||||
? Reflection.getSoftware().toString()
|
||||
: Reflection.getVersionName();
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
public static void warning(List<String> messages) {
|
||||
LOGGER.warn(messages);
|
||||
}
|
||||
|
||||
public static void info(String message) {
|
||||
LOGGER.info(message);
|
||||
}
|
||||
|
||||
public static void warning(String message) {
|
||||
LOGGER.warn(message);
|
||||
}
|
||||
|
||||
public static String post() throws IOException {
|
||||
|
||||
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();
|
||||
DataOutputStream outputStream;
|
||||
String response;
|
||||
|
||||
connection.setDoOutput(true);
|
||||
connection.setInstanceFollowRedirects(false);
|
||||
connection.setRequestMethod("POST");
|
||||
connection.setRequestProperty("User-Agent", "ProAntiTab");
|
||||
connection.setRequestProperty("Content-Length", Integer.toString(postDataLength));
|
||||
connection.setUseCaches(false);
|
||||
|
||||
outputStream = new DataOutputStream(connection.getOutputStream());
|
||||
outputStream.write(textInBytes);
|
||||
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
|
||||
response = reader.readLine();
|
||||
|
||||
if (response == null || !response.contains("\"key\"")) return null;
|
||||
response = response.substring(response.indexOf(":") + 2, response.length() - 2);
|
||||
return "https://haste.rayzs.de/" + response + ".txt";
|
||||
}
|
||||
|
||||
private static String createInfo() {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
|
||||
if (!Reflection.isProxyServer()) {
|
||||
builder.append("Detected Software-API: ")
|
||||
.append(Reflection.getSoftware().toString())
|
||||
.append("\n\n");
|
||||
}
|
||||
|
||||
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("Installed plugins: \n ")
|
||||
.append(String.join("\n ", Storage.getLoader().getFormattedPluginNames("%n (%v)")))
|
||||
.append("\n\n");
|
||||
|
||||
builder.append("Detected supported plugins:")
|
||||
.append("\n");
|
||||
|
||||
builder.append(" LuckPerms: ")
|
||||
.append(Storage.getPermissionPlugin() == PermissionPlugin.LUCKPERMS)
|
||||
.append("\n");
|
||||
|
||||
if (!Reflection.isProxyServer()) {
|
||||
builder.append(" GroupManager: ")
|
||||
.append(Storage.getPermissionPlugin() == PermissionPlugin.GROUPMANAGER)
|
||||
.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 ? TimeConverter.calcAndGetTime(Communicator.get().getLastSync()) : "Deactivated")
|
||||
.append("\n");
|
||||
|
||||
builder.append("last-received-alive-response-packet: ")
|
||||
.append(Storage.ConfigSections.Settings.HANDLE_THROUGH_PROXY.ENABLED ? TimeConverter.calcAndGetTime(Communicator.get().getLastReceivedKeepAliveResponse()) : "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.ENABLED ? "Deactivated" : (TimeConverter.calcAndGetTime(Communicator.get().getLastSync())))
|
||||
.append("\n\n");
|
||||
|
||||
builder.append("synced-server: ");
|
||||
Iterator<Client> iterator = Communicator.get().getClients().iterator();
|
||||
while (iterator.hasNext()) {
|
||||
Client clientInfo = iterator.next();
|
||||
|
||||
builder.append(clientInfo.getServerName())
|
||||
.append(" (")
|
||||
.append(clientInfo.getFormattedLastReceivedKeepAlivePacketTime() + " / " + clientInfo.getFormattedSyncTime())
|
||||
.append(")");
|
||||
|
||||
if (iterator.hasNext()) {
|
||||
builder.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,13 +1,16 @@
|
||||
package de.rayzs.pat.plugin.logger.impl;
|
||||
|
||||
import de.rayzs.pat.utils.message.MessageTranslator;
|
||||
import de.rayzs.pat.utils.message.MessageHelper;
|
||||
import de.rayzs.pat.plugin.BukkitLoader;
|
||||
import de.rayzs.pat.plugin.logger.*;
|
||||
import de.rayzs.pat.utils.message.replacer.PlaceholderReplacer;
|
||||
import de.rayzs.pat.utils.sender.CommandSender;
|
||||
import org.bukkit.Bukkit;
|
||||
import java.util.*;
|
||||
|
||||
public class BukkitLogger implements LoggerTemplate {
|
||||
|
||||
private final CommandSender console = CommandSender.from(Bukkit.getServer().getConsoleSender());
|
||||
private final java.util.logging.Logger logger = BukkitLoader.getPluginLogger();
|
||||
|
||||
@Override
|
||||
@@ -37,10 +40,10 @@ public class BukkitLogger implements LoggerTemplate {
|
||||
|
||||
@Override
|
||||
public void send(LoggerPriority priority, String message) {
|
||||
message = MessageTranslator.replaceMessage(message);
|
||||
message = PlaceholderReplacer.applyPlaceholders(null, message);
|
||||
|
||||
if (message.contains("§")) {
|
||||
MessageTranslator.send(Bukkit.getServer().getConsoleSender(), message);
|
||||
MessageHelper.sendMessage(console, message);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,13 +1,17 @@
|
||||
package de.rayzs.pat.plugin.logger.impl;
|
||||
|
||||
import de.rayzs.pat.utils.message.MessageTranslator;
|
||||
import de.rayzs.pat.utils.message.MessageHelper;
|
||||
import de.rayzs.pat.plugin.BungeeLoader;
|
||||
import de.rayzs.pat.utils.message.replacer.PlaceholderReplacer;
|
||||
import de.rayzs.pat.utils.sender.CommandSender;
|
||||
import net.md_5.bungee.api.ProxyServer;
|
||||
import de.rayzs.pat.plugin.logger.*;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public class BungeeLogger implements LoggerTemplate {
|
||||
|
||||
private final CommandSender console = CommandSender.from(ProxyServer.getInstance().getConsole());
|
||||
private final java.util.logging.Logger logger = BungeeLoader.getPluginLogger();
|
||||
|
||||
@Override
|
||||
@@ -37,10 +41,10 @@ public class BungeeLogger implements LoggerTemplate {
|
||||
|
||||
@Override
|
||||
public void send(LoggerPriority priority, String message) {
|
||||
message = MessageTranslator.replaceMessage(message);
|
||||
message = PlaceholderReplacer.applyPlaceholders(null, message);
|
||||
|
||||
if (message.contains("§")) {
|
||||
MessageTranslator.send(ProxyServer.getInstance().getConsole(), message);
|
||||
MessageHelper.sendMessage(console, message);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
package de.rayzs.pat.plugin.logger.impl;
|
||||
|
||||
import de.rayzs.pat.utils.message.MessageTranslator;
|
||||
import de.rayzs.pat.utils.message.MessageHelper;
|
||||
import de.rayzs.pat.plugin.VelocityLoader;
|
||||
import de.rayzs.pat.plugin.logger.*;
|
||||
import de.rayzs.pat.utils.message.replacer.PlaceholderReplacer;
|
||||
import de.rayzs.pat.utils.sender.CommandSender;
|
||||
import org.slf4j.Logger;
|
||||
import java.util.*;
|
||||
|
||||
public class VelocityLogger implements LoggerTemplate {
|
||||
|
||||
private final CommandSender console = CommandSender.from(VelocityLoader.getServer().getConsoleCommandSource());
|
||||
private final Logger logger = VelocityLoader.getPluginLogger();
|
||||
|
||||
@Override
|
||||
@@ -37,10 +40,10 @@ public class VelocityLogger implements LoggerTemplate {
|
||||
|
||||
@Override
|
||||
public void send(LoggerPriority priority, String message) {
|
||||
message = MessageTranslator.replaceMessage(message);
|
||||
message = PlaceholderReplacer.applyPlaceholders(null, message);
|
||||
|
||||
if (message.contains("§")) {
|
||||
MessageTranslator.send(VelocityLoader.getServer().getConsoleCommandSource(), message);
|
||||
MessageHelper.sendMessage(console, message);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
package de.rayzs.pat.plugin.metrics;
|
||||
|
||||
import de.rayzs.pat.plugin.metrics.impl.*;
|
||||
import de.rayzs.pat.utils.Reflection;
|
||||
|
||||
public class bStats {
|
||||
|
||||
public static void initialize(Object pluginObj) {
|
||||
if(Reflection.isProxyServer()) new BungeeMetrics(pluginObj, 20090);
|
||||
else new BukkitMetrics(pluginObj, 20089);
|
||||
}
|
||||
}
|
||||
package de.rayzs.pat.plugin.metrics;
|
||||
|
||||
import de.rayzs.pat.plugin.metrics.impl.*;
|
||||
import de.rayzs.pat.utils.Reflection;
|
||||
|
||||
public class bStats {
|
||||
|
||||
public static void initialize(Object pluginObj) {
|
||||
if(Reflection.isProxyServer()) new BungeeMetrics(pluginObj, 20090);
|
||||
else new BukkitMetrics(pluginObj, 20089);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
+169
-24
@@ -5,6 +5,10 @@ import de.rayzs.pat.plugin.packetanalyzer.bukkit.handlers.LegacyPacketHandler;
|
||||
import de.rayzs.pat.plugin.packetanalyzer.bukkit.handlers.ModernCommandsNodeHandler;
|
||||
import de.rayzs.pat.plugin.packetanalyzer.bukkit.handlers.ModernPacketHandler;
|
||||
import de.rayzs.pat.utils.permission.PermissionUtil;
|
||||
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.Field;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import de.rayzs.pat.api.storage.Storage;
|
||||
import de.rayzs.pat.utils.ExpireCache;
|
||||
@@ -16,6 +20,7 @@ import org.bukkit.entity.Player;
|
||||
import io.netty.channel.*;
|
||||
import org.bukkit.Bukkit;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
public class BukkitPacketAnalyzer {
|
||||
|
||||
@@ -48,15 +53,15 @@ public class BukkitPacketAnalyzer {
|
||||
channel.pipeline().writeAndFlush(object);
|
||||
}
|
||||
|
||||
public static boolean inject(Player player) {
|
||||
if (Storage.ConfigSections.Settings.HANDLE_THROUGH_PROXY.ENABLED)
|
||||
return true;
|
||||
public static InjectionState inject(Player player) {
|
||||
if (Storage.ConfigSections.Settings.HANDLE_THROUGH_PROXY.ENABLED && !Storage.ConfigSections.Settings.HIDE_PLUGIN_CHANNELS.ENABLED)
|
||||
return InjectionState.SKIPPED;
|
||||
|
||||
try {
|
||||
Channel channel = Reflection.getPlayerChannel(player);
|
||||
|
||||
if (channel == null) {
|
||||
return false;
|
||||
if (channel == null || !channel.pipeline().names().contains(PIPELINE_NAME)) {
|
||||
return InjectionState.SKIPPED;
|
||||
}
|
||||
|
||||
if (channel.pipeline().names().contains(BukkitPacketAnalyzer.HANDLER_NAME))
|
||||
@@ -72,24 +77,36 @@ public class BukkitPacketAnalyzer {
|
||||
// changed the compilation and therefore the variables again.
|
||||
|
||||
Reflection.toggleInjectionMethod();
|
||||
final boolean success = inject(player);
|
||||
final InjectionState state = inject(player);
|
||||
|
||||
if (!success) {
|
||||
if (state == InjectionState.FAILED) {
|
||||
Logger.warning("Both injection methods failed! Please report this back to me on my Discord! (https://www.rayzs.de/discord)");
|
||||
}
|
||||
|
||||
return success;
|
||||
return state;
|
||||
|
||||
} catch (NoSuchFieldException noSuchFieldException) {
|
||||
|
||||
if (!Storage.ConfigSections.Settings.INJECTION_FAILED.ENABLED) {
|
||||
return InjectionState.SUCCESS;
|
||||
}
|
||||
|
||||
Logger.warning("Failed to inject into " + player.getName() + " and kicked the player as result, to avoid any security risks.");
|
||||
Logger.warning("You can read more about it here: https://www.rayzs.de/products/proantitab/pkafi");
|
||||
Logger.warning("Error details: " + noSuchFieldException.getMessage());
|
||||
|
||||
return InjectionState.FAILED;
|
||||
|
||||
} catch (Exception exception) {
|
||||
if (!Storage.ConfigSections.Settings.INJECTION_FAILED.SUPPRESS_EXCEPTIONS) {
|
||||
exception.printStackTrace();
|
||||
}
|
||||
|
||||
return false;
|
||||
return InjectionState.FAILED;
|
||||
|
||||
}
|
||||
|
||||
return true;
|
||||
return InjectionState.SUCCESS;
|
||||
}
|
||||
|
||||
public static void uninject(UUID uuid) {
|
||||
@@ -103,7 +120,7 @@ public class BukkitPacketAnalyzer {
|
||||
}
|
||||
|
||||
public static void uninject(Channel channel) {
|
||||
if (Storage.ConfigSections.Settings.HANDLE_THROUGH_PROXY.ENABLED)
|
||||
if (Storage.ConfigSections.Settings.HANDLE_THROUGH_PROXY.ENABLED && !Storage.ConfigSections.Settings.HIDE_PLUGIN_CHANNELS.ENABLED)
|
||||
return;
|
||||
|
||||
if (channel != null) {
|
||||
@@ -116,6 +133,10 @@ public class BukkitPacketAnalyzer {
|
||||
}
|
||||
}
|
||||
|
||||
public enum InjectionState {
|
||||
SUCCESS, FAILED, SKIPPED
|
||||
}
|
||||
|
||||
public static String getPlayerInput(Player player) {
|
||||
String input = PLAYER_INPUT_CACHE.get(player);
|
||||
PLAYER_INPUT_CACHE.remove(player);
|
||||
@@ -131,64 +152,103 @@ public class BukkitPacketAnalyzer {
|
||||
private final Player player;
|
||||
private final CommandSender sender;
|
||||
|
||||
private long lastCheckedForOperatorPermission = System.currentTimeMillis();
|
||||
private boolean operatorStatus;
|
||||
|
||||
private PacketDecoder(Player player) {
|
||||
this.player = player;
|
||||
this.sender = CommandSender.from(player);
|
||||
|
||||
this.operatorStatus = player.isOp();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void channelRead(ChannelHandlerContext channel, Object packetObj) {
|
||||
try {
|
||||
if (packetObj.getClass() == null || Storage.ConfigSections.Settings.HANDLE_THROUGH_PROXY.ENABLED) {
|
||||
if (packetObj.getClass() == null) {
|
||||
super.channelRead(channel, packetObj);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
String packetName = packetObj.getClass().getSimpleName();
|
||||
|
||||
if (Storage.ConfigSections.Settings.HIDE_PLUGIN_CHANNELS.ENABLED && packetName.equalsIgnoreCase("ServerboundCustomPayloadPacket")) {
|
||||
final Object newPacketObj = handlePluginChannelPacket(packetObj);
|
||||
|
||||
if (newPacketObj != null)
|
||||
super.channelRead(channel, newPacketObj);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
if (Storage.ConfigSections.Settings.HANDLE_THROUGH_PROXY.ENABLED) {
|
||||
super.channelRead(channel, packetObj);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
if (!packetName.equals("PacketPlayInTabComplete") && !packetName.equals("ServerboundCommandSuggestionPacket")) {
|
||||
super.channelRead(channel, packetObj);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!PermissionUtil.hasBypassPermission(sender)) {
|
||||
|
||||
if (!PACKET_HANDLER.handleIncomingPacket(player, sender, packetObj))
|
||||
return;
|
||||
if (!hasBypassPermission() && !PACKET_HANDLER.handleIncomingPacket(player, sender, packetObj, false)) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
super.channelRead(channel, packetObj);
|
||||
} catch (Throwable exception) { exception.printStackTrace(); }
|
||||
} catch (Throwable exception) {
|
||||
exception.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(ChannelHandlerContext channel, Object packetObj, ChannelPromise promise) {
|
||||
try {
|
||||
|
||||
if(packetObj.getClass() == null || Storage.ConfigSections.Settings.HANDLE_THROUGH_PROXY.ENABLED) {
|
||||
if(packetObj.getClass() == null) {
|
||||
super.write(channel, packetObj, promise);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
final String packetName = packetObj.getClass().getSimpleName();
|
||||
|
||||
if (Storage.ConfigSections.Settings.HIDE_PLUGIN_CHANNELS.ENABLED && packetName.equalsIgnoreCase("ClientboundCustomPayloadPacket")) {
|
||||
final Object newPacketObj = handlePluginChannelPacket(packetObj);
|
||||
|
||||
if (newPacketObj != null)
|
||||
super.write(channel, newPacketObj, promise);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
if (Storage.ConfigSections.Settings.HANDLE_THROUGH_PROXY.ENABLED) {
|
||||
super.write(channel, packetObj, promise);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
final boolean isCommandsPacket = packetName.equals("ClientboundCommandsPacket");
|
||||
final boolean isTabCompletePacket = packetName.equals("PacketPlayOutTabComplete") || packetName.equals("ClientboundCommandSuggestionsPacket");
|
||||
|
||||
if (!isCommandsPacket && !isTabCompletePacket || PermissionUtil.hasBypassPermission(sender)) {
|
||||
if (!isCommandsPacket && !isTabCompletePacket || hasBypassPermission()) {
|
||||
super.write(channel, packetObj, promise);
|
||||
return;
|
||||
}
|
||||
|
||||
if (isCommandsPacket) {
|
||||
COMMANDS_NODE_HANDLER.handleOutgoingPacket(player, sender, packetObj);
|
||||
COMMANDS_NODE_HANDLER.handleOutgoingPacket(player, sender, packetObj, false);
|
||||
|
||||
super.write(channel, packetObj, promise);
|
||||
return;
|
||||
}
|
||||
|
||||
UUID uuid = player.getUniqueId();
|
||||
Object sentPacketObj = SENT_PACKET.get(uuid);
|
||||
final UUID uuid = sender.getUniqueId();
|
||||
final Object sentPacketObj = SENT_PACKET.get(uuid);
|
||||
|
||||
if (sentPacketObj != null) {
|
||||
if (sentPacketObj == packetObj) {
|
||||
@@ -198,8 +258,9 @@ public class BukkitPacketAnalyzer {
|
||||
}
|
||||
}
|
||||
|
||||
if (!PACKET_HANDLER.handleOutgoingPacket(player, sender, packetObj))
|
||||
if (!PACKET_HANDLER.handleOutgoingPacket(player, sender, packetObj, false)) {
|
||||
return;
|
||||
}
|
||||
|
||||
super.write(channel, packetObj, promise);
|
||||
|
||||
@@ -207,5 +268,89 @@ public class BukkitPacketAnalyzer {
|
||||
exception.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
private boolean hasBypassPermission() {
|
||||
if (PermissionUtil.hasBypassPermission(sender, false)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (System.currentTimeMillis() - this.lastCheckedForOperatorPermission >= 2000) {
|
||||
this.lastCheckedForOperatorPermission = System.currentTimeMillis();
|
||||
this.operatorStatus = player.isOp();
|
||||
return this.operatorStatus;
|
||||
}
|
||||
|
||||
return this.operatorStatus;
|
||||
}
|
||||
|
||||
|
||||
private Object handlePluginChannelPacket(Object packet) throws NoSuchFieldException, IllegalAccessException {
|
||||
final Field payloadField = packet.getClass().getDeclaredField("payload");
|
||||
payloadField.setAccessible(true);
|
||||
|
||||
final Object payloadObj = payloadField.get(packet);
|
||||
Field channelField;
|
||||
|
||||
try {
|
||||
channelField = payloadObj.getClass().getDeclaredField("id");
|
||||
} catch (NoSuchFieldException noSuchFieldException) {
|
||||
return packet;
|
||||
}
|
||||
|
||||
channelField.setAccessible(true);
|
||||
|
||||
final Object channelIdObj = channelField.get(payloadObj);
|
||||
final String channelId = channelIdObj.toString();
|
||||
channelField.setAccessible(false);
|
||||
|
||||
|
||||
if (!Storage.ConfigSections.Settings.HIDE_PLUGIN_CHANNELS.isRegisterChannel(channelId)) {
|
||||
return packet;
|
||||
}
|
||||
|
||||
|
||||
final Field dataField = payloadObj.getClass().getDeclaredField("data");
|
||||
dataField.setAccessible(true);
|
||||
|
||||
final byte[] data = (byte[]) dataField.get(payloadObj);
|
||||
dataField.setAccessible(true);
|
||||
|
||||
final String dataStr = new String(data, StandardCharsets.UTF_8);
|
||||
final String[] channels = dataStr.split("\u0000");
|
||||
|
||||
final List<String> filteredChannels = new ArrayList<>(Arrays.asList(channels));
|
||||
final AtomicBoolean changedAnything = new AtomicBoolean(false);
|
||||
|
||||
filteredChannels.removeIf(channel -> {
|
||||
if (!Storage.ConfigSections.Settings.HIDE_PLUGIN_CHANNELS.WHITELISTED_CHANNELS.getLines().contains(channel)) {
|
||||
changedAnything.set(true);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
});
|
||||
|
||||
if (!changedAnything.get()) {
|
||||
return packet;
|
||||
}
|
||||
|
||||
try {
|
||||
final Class<?> customPayloadClass = packet.getClass().getConstructors()[0].getParameterTypes()[0];
|
||||
final Class<?> discardPayloadClass = payloadObj.getClass();
|
||||
|
||||
final Constructor<?> discardPayloadConstr = discardPayloadClass.getConstructor(channelIdObj.getClass(), byte[].class);
|
||||
final Object newDiscardPayloadObj = discardPayloadConstr.newInstance(
|
||||
channelIdObj,
|
||||
String.join("\u0000", filteredChannels).getBytes()
|
||||
);
|
||||
|
||||
final Constructor<?> newPacketConstr = packet.getClass().getConstructor(customPayloadClass);
|
||||
return newPacketConstr.newInstance(newDiscardPayloadObj);
|
||||
} catch (Exception exception) {
|
||||
exception.printStackTrace();
|
||||
}
|
||||
|
||||
return packet;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,17 @@ import de.rayzs.pat.utils.sender.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
public interface BukkitPacketHandler {
|
||||
boolean handleIncomingPacket(Player player, CommandSender sender, Object packetObj) throws Exception;
|
||||
boolean handleOutgoingPacket(Player player, CommandSender sender, Object packetObj) throws Exception;
|
||||
boolean handleIncomingPacket(
|
||||
final Player player,
|
||||
final CommandSender sender,
|
||||
final Object packetObj,
|
||||
final boolean isOperator
|
||||
) throws Exception;
|
||||
|
||||
boolean handleOutgoingPacket(
|
||||
final Player player,
|
||||
final CommandSender sender,
|
||||
final Object packetObj,
|
||||
final boolean isOperator
|
||||
) throws Exception;
|
||||
}
|
||||
+16
-6
@@ -23,7 +23,12 @@ import de.rayzs.pat.utils.Reflection;
|
||||
public class LegacyPacketHandler implements BukkitPacketHandler {
|
||||
|
||||
@Override
|
||||
public boolean handleIncomingPacket(Player player, CommandSender sender, Object packetObj) throws Exception {
|
||||
public boolean handleIncomingPacket(
|
||||
final Player player,
|
||||
final CommandSender sender,
|
||||
final Object packetObj,
|
||||
final boolean isOperator
|
||||
) throws Exception {
|
||||
Field stringField = Reflection.getFirstFieldByType(packetObj.getClass(), "String", Reflection.SearchOption.ENDS);
|
||||
if(stringField == null) {
|
||||
Logger.warning("Failed PacketAnalyze process! (#1)");
|
||||
@@ -36,14 +41,19 @@ public class LegacyPacketHandler implements BukkitPacketHandler {
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean handleOutgoingPacket(Player player, CommandSender sender, Object packetObj) throws Exception {
|
||||
public boolean handleOutgoingPacket(
|
||||
final Player player,
|
||||
final CommandSender sender,
|
||||
final Object packetObj,
|
||||
final boolean isOperator
|
||||
) throws Exception {
|
||||
final String rawInput = BukkitPacketAnalyzer.getPlayerInput(player);
|
||||
|
||||
if(rawInput == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
final List<Group> groups = GroupManager.getPlayerGroups(sender);
|
||||
final List<Group> groups = GroupManager.getPlayerGroups(sender, isOperator);
|
||||
|
||||
String input = rawInput;
|
||||
boolean cancelsBeforeHand = false;
|
||||
@@ -54,7 +64,7 @@ public class LegacyPacketHandler implements BukkitPacketHandler {
|
||||
|
||||
input = input.substring(1);
|
||||
|
||||
final boolean doesBypassNamespace = Storage.ConfigSections.Settings.BLOCK_NAMESPACE_COMMANDS.doesBypass(sender);
|
||||
final boolean doesBypassNamespace = Storage.ConfigSections.Settings.BLOCK_NAMESPACE_COMMANDS.doesBypass(sender, isOperator);
|
||||
final boolean spaces = input.contains(" ");
|
||||
|
||||
if (Storage.ConfigSections.Settings.BLOCK_NAMESPACE_COMMANDS.isCommand(input) && !doesBypassNamespace) {
|
||||
@@ -62,7 +72,7 @@ public class LegacyPacketHandler implements BukkitPacketHandler {
|
||||
}
|
||||
|
||||
if (!cancelsBeforeHand && !input.isEmpty()) {
|
||||
cancelsBeforeHand = !Storage.Blacklist.canPlayerAccessTab(sender, groups, StringUtils.getFirstArg(input));
|
||||
cancelsBeforeHand = !Storage.Blacklist.canPlayerAccessTab(sender, groups, StringUtils.getFirstArg(input), isOperator);
|
||||
}
|
||||
|
||||
if (!cancelsBeforeHand) {
|
||||
@@ -117,7 +127,7 @@ public class LegacyPacketHandler implements BukkitPacketHandler {
|
||||
return false;
|
||||
}
|
||||
|
||||
return !Storage.Blacklist.canPlayerAccessTab(sender, groups, cpy);
|
||||
return !Storage.Blacklist.canPlayerAccessTab(sender, groups, cpy, isOperator);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
+18
-3
@@ -5,18 +5,33 @@ import de.rayzs.pat.plugin.system.subargument.SubArgument;
|
||||
import de.rayzs.pat.utils.node.BukkitCommandNodeHelper;
|
||||
import de.rayzs.pat.utils.sender.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
public class ModernCommandsNodeHandler implements BukkitPacketHandler {
|
||||
|
||||
public boolean handleIncomingPacket(Player player, CommandSender sender, Object packetObj) throws Exception {
|
||||
public boolean handleIncomingPacket(
|
||||
final Player player,
|
||||
final CommandSender sender,
|
||||
final Object packetObj,
|
||||
final boolean isOperator
|
||||
) {
|
||||
// Ignored
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean handleOutgoingPacket(Player player, CommandSender sender, Object packetObj) throws Exception {
|
||||
public boolean handleOutgoingPacket(
|
||||
final Player player,
|
||||
final CommandSender sender,
|
||||
final Object packetObj,
|
||||
final boolean isOperator
|
||||
) throws Exception {
|
||||
final BukkitCommandNodeHelper helper = new BukkitCommandNodeHelper(packetObj);
|
||||
|
||||
SubArgument.get().getCommandNodeHandler().handleCommandNode(helper, SubArgument.get().getPlayerArgument(sender));
|
||||
SubArgument.get().getCommandNodeHandler().handleCommandNode(
|
||||
helper,
|
||||
SubArgument.get().getPlayerArgument(sender)
|
||||
);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
+22
-12
@@ -23,7 +23,7 @@ import de.rayzs.pat.api.storage.Storage;
|
||||
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.MessageTranslator;
|
||||
import de.rayzs.pat.utils.message.MessageHelper;
|
||||
import de.rayzs.pat.utils.scheduler.PATScheduler;
|
||||
|
||||
public class ModernPacketHandler implements BukkitPacketHandler {
|
||||
@@ -31,10 +31,15 @@ public class ModernPacketHandler implements BukkitPacketHandler {
|
||||
private static boolean modifiable = true;
|
||||
|
||||
@Override
|
||||
public boolean handleIncomingPacket(Player player, CommandSender sender, Object packetObj) throws Exception {
|
||||
public boolean handleIncomingPacket(
|
||||
final Player player,
|
||||
final CommandSender sender,
|
||||
final Object packetObj,
|
||||
final boolean isOperator
|
||||
) throws Exception {
|
||||
Field stringField = Reflection.getFirstFieldByType(packetObj.getClass(), "String", Reflection.SearchOption.ENDS);
|
||||
|
||||
if(stringField == null) {
|
||||
if (stringField == null) {
|
||||
Logger.warning("Failed PacketAnalyze process! (#1)");
|
||||
return false;
|
||||
}
|
||||
@@ -43,8 +48,8 @@ public class ModernPacketHandler implements BukkitPacketHandler {
|
||||
if (!text.isBlank() && text.charAt(0) != '/') text = '/' + text;
|
||||
|
||||
if (Storage.ConfigSections.Settings.PATCH_EXPLOITS.isMalicious(text)) {
|
||||
MessageTranslator.send(
|
||||
Bukkit.getConsoleSender(),
|
||||
MessageHelper.sendMessage(
|
||||
CommandSender.from(Bukkit.getConsoleSender()),
|
||||
Storage.ConfigSections.Settings.PATCH_EXPLOITS.ALERT_MESSAGE.get().replace("%player%", player.getName())
|
||||
);
|
||||
|
||||
@@ -62,7 +67,12 @@ public class ModernPacketHandler implements BukkitPacketHandler {
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean handleOutgoingPacket(Player player, CommandSender sender, Object packetObj) throws Exception {
|
||||
public boolean handleOutgoingPacket(
|
||||
final Player player,
|
||||
final CommandSender sender,
|
||||
final Object packetObj,
|
||||
final boolean isOperator
|
||||
) throws Exception {
|
||||
Object suggestionObj;
|
||||
String rawInput = BukkitPacketAnalyzer.getPlayerInput(player), input = rawInput;
|
||||
|
||||
@@ -70,10 +80,10 @@ public class ModernPacketHandler implements BukkitPacketHandler {
|
||||
return false;
|
||||
}
|
||||
|
||||
final List<Group> groups = GroupManager.getPlayerGroups(sender);
|
||||
final boolean is121Packet = packetObj.getClass().getSimpleName().equals("ClientboundCommandSuggestionsPacket");
|
||||
final List<Group> groups = GroupManager.getPlayerGroups(sender, isOperator);
|
||||
|
||||
boolean is121Packet = packetObj.getClass().getSimpleName().equals("ClientboundCommandSuggestionsPacket"),
|
||||
cancelsBeforeHand = false;
|
||||
boolean cancelsBeforeHand = false;
|
||||
|
||||
int spaces = 0;
|
||||
if(input.startsWith("/") || is121Packet) {
|
||||
@@ -85,7 +95,7 @@ public class ModernPacketHandler implements BukkitPacketHandler {
|
||||
if (spaces > 0) input = split[0];
|
||||
}
|
||||
|
||||
cancelsBeforeHand = !Storage.Blacklist.canPlayerAccessTab(sender, groups, input);
|
||||
cancelsBeforeHand = !Storage.Blacklist.canPlayerAccessTab(sender, groups, input, isOperator);
|
||||
|
||||
if (!cancelsBeforeHand)
|
||||
cancelsBeforeHand = Storage.ConfigSections.Settings.CUSTOM_VERSION.isTabCompletable(input) || Storage.ConfigSections.Settings.CUSTOM_PLUGIN.isTabCompletable(input);
|
||||
@@ -114,7 +124,7 @@ public class ModernPacketHandler implements BukkitPacketHandler {
|
||||
if (spaces == 0) {
|
||||
suggestions.removeIf(suggestion -> {
|
||||
String command = getSuggestionFromEntry(suggestion);
|
||||
return !Storage.Blacklist.canPlayerAccessTab(sender, groups, command);
|
||||
return !Storage.Blacklist.canPlayerAccessTab(sender, groups, command, isOperator);
|
||||
});
|
||||
|
||||
return true;
|
||||
@@ -190,7 +200,7 @@ public class ModernPacketHandler implements BukkitPacketHandler {
|
||||
|
||||
suggestions.getList().removeIf(suggestion -> {
|
||||
String command = suggestion.getText();
|
||||
return !Storage.Blacklist.canPlayerAccessTab(sender, groups, command);
|
||||
return !Storage.Blacklist.canPlayerAccessTab(sender, groups, command, isOperator);
|
||||
});
|
||||
|
||||
return true;
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
package de.rayzs.pat.plugin.packetanalyzer.proxy;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
import com.mojang.brigadier.tree.CommandNode;
|
||||
|
||||
@@ -144,18 +146,19 @@ public class BungeePacketAnalyzer {
|
||||
private static void modifyCommands(ProxiedPlayer player, CommandSender sender, Commands commands) {
|
||||
String serverName = sender.getServerName();
|
||||
|
||||
final boolean ignore = PermissionUtil.hasBypassPermission(sender) || Storage.Blacklist.isDisabledServer(serverName);
|
||||
final boolean ignore = PermissionUtil.hasBypassPermission(sender, false) || Storage.Blacklist.isDisabledServer(serverName);
|
||||
|
||||
ProxyCommandNodeHelper helper = new ProxyCommandNodeHelper<CommandNode>(commands.getRoot());
|
||||
|
||||
List<String> commandsAsString = new ArrayList<>(PROXY_COMMANDS);
|
||||
final ProxyCommandNodeHelper helper = new ProxyCommandNodeHelper<CommandNode>(commands.getRoot());
|
||||
final List<String> commandsAsString = new ArrayList<>(PROXY_COMMANDS);
|
||||
commandsAsString.addAll(helper.getChildrenNames());
|
||||
|
||||
List<String> playerCommands = new ArrayList<>();
|
||||
final List<Group> groups = ignore
|
||||
? Collections.emptyList()
|
||||
: GroupManager.getPlayerGroups(sender, false);
|
||||
|
||||
HashSet<String> playerCommands = new HashSet<>();
|
||||
|
||||
if (!ignore) {
|
||||
final List<Group> groups = GroupManager.getPlayerGroups(sender);
|
||||
|
||||
final Map<String, CommandsCache> cache = Storage.getLoader().getPerServerCommandsCacheMap();
|
||||
if (!cache.containsKey(serverName)) {
|
||||
cache.put(serverName, new CommandsCache());
|
||||
@@ -164,7 +167,7 @@ public class BungeePacketAnalyzer {
|
||||
final CommandsCache commandsCache = cache.get(serverName);
|
||||
commandsCache.handleCommands(commandsAsString, serverName);
|
||||
|
||||
final List<String> tmpPlayerCommands = commandsCache.getPlayerCommands(commandsAsString, sender, groups, serverName);
|
||||
final HashSet<String> tmpPlayerCommands = commandsCache.getPlayerCommands(commandsAsString, sender, groups, serverName, false);
|
||||
|
||||
if (commands.getRoot().getChildren().size() != 0) {
|
||||
helper.removeIf(str -> !tmpPlayerCommands.contains(str));
|
||||
@@ -216,6 +219,14 @@ public class BungeePacketAnalyzer {
|
||||
}
|
||||
}
|
||||
|
||||
if (Storage.ConfigSections.Settings.TAB_COMPLETION_FOR_NOT_EXISTING_COMMANDS.ENABLED) {
|
||||
for (Group group : groups) {
|
||||
for (String groupCommands : group.getAllCommands(serverName)) {
|
||||
helper.add(groupCommands, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!ignore) {
|
||||
SubArgument.get().getCommandNodeHandler().handleCommandNode(helper, SubArgument.get().getPlayerArgument(sender));
|
||||
}
|
||||
@@ -240,6 +251,7 @@ public class BungeePacketAnalyzer {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private static class PacketDecoder extends MessageToMessageDecoder<PacketWrapper> {
|
||||
|
||||
private final ProxiedPlayer player;
|
||||
@@ -262,6 +274,31 @@ public class BungeePacketAnalyzer {
|
||||
|
||||
if (CustomServerBrand.get().isEnabled() && CustomServerBrand.get().isBrandTag(pluginMessage.getTag())) {
|
||||
return;
|
||||
} else if (Storage.ConfigSections.Settings.HIDE_PLUGIN_CHANNELS.ENABLED) {
|
||||
final String channelId = pluginMessage.getTag();
|
||||
|
||||
if (Storage.ConfigSections.Settings.HIDE_PLUGIN_CHANNELS.isRegisterChannel(channelId)) {
|
||||
final String dataStr = new String(pluginMessage.getData(), StandardCharsets.UTF_8);
|
||||
final String[] channels = dataStr.split("\u0000");
|
||||
|
||||
final List<String> filteredChannels = new ArrayList<>(Arrays.asList(channels));
|
||||
final AtomicBoolean changedAnything = new AtomicBoolean(false);
|
||||
|
||||
filteredChannels.removeIf(channel -> {
|
||||
if (!Storage.ConfigSections.Settings.HIDE_PLUGIN_CHANNELS.WHITELISTED_CHANNELS.getLines().contains(channel)) {
|
||||
changedAnything.set(true);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
});
|
||||
|
||||
if (changedAnything.get()) {
|
||||
pluginMessage.setData(String.join("\u0000", filteredChannels).getBytes());
|
||||
player.unsafe().sendPacket(pluginMessage);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} else if (wrapper.packet instanceof Commands response) {
|
||||
|
||||
+64
-14
@@ -1,17 +1,16 @@
|
||||
package de.rayzs.pat.plugin.packetanalyzer.proxy;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
import com.mojang.brigadier.suggestion.SuggestionProvider;
|
||||
import com.velocitypowered.api.command.CommandSource;
|
||||
import com.velocitypowered.api.proxy.Player;
|
||||
import com.velocitypowered.proxy.protocol.MinecraftPacket;
|
||||
import com.velocitypowered.proxy.protocol.packet.AvailableCommandsPacket;
|
||||
import com.velocitypowered.proxy.protocol.packet.PluginMessagePacket;
|
||||
import com.velocitypowered.proxy.protocol.packet.TabCompleteRequestPacket;
|
||||
import com.velocitypowered.proxy.protocol.packet.TabCompleteResponsePacket;
|
||||
import com.velocitypowered.proxy.protocol.packet.*;
|
||||
import com.velocitypowered.proxy.protocol.packet.chat.session.UnsignedPlayerCommandPacket;
|
||||
|
||||
import de.rayzs.pat.plugin.system.serverbrand.CustomServerBrand;
|
||||
@@ -28,10 +27,12 @@ import de.rayzs.pat.utils.Reflection;
|
||||
import de.rayzs.pat.utils.StringUtils;
|
||||
import de.rayzs.pat.utils.group.Group;
|
||||
import de.rayzs.pat.utils.group.GroupManager;
|
||||
import de.rayzs.pat.utils.message.MessageTranslator;
|
||||
import de.rayzs.pat.utils.message.MessageHelper;
|
||||
import de.rayzs.pat.utils.node.ProxyCommandNodeHelper;
|
||||
import de.rayzs.pat.utils.permission.PermissionUtil;
|
||||
import de.rayzs.pat.utils.sender.CommandSender;
|
||||
import io.netty.buffer.ByteBuf;
|
||||
import io.netty.buffer.Unpooled;
|
||||
import io.netty.channel.Channel;
|
||||
import io.netty.channel.ChannelDuplexHandler;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
@@ -177,7 +178,7 @@ public class VelocityPacketAnalyzer {
|
||||
|
||||
final String serverName = sender.getServerName();
|
||||
|
||||
final boolean ignore = PermissionUtil.hasBypassPermission(sender) || Storage.Blacklist.isDisabledServer(serverName);
|
||||
final boolean ignore = PermissionUtil.hasBypassPermission(sender, false) || Storage.Blacklist.isDisabledServer(serverName);
|
||||
final ProxyCommandNodeHelper<CommandSource> helper = new ProxyCommandNodeHelper<>(commands.getRootNode());
|
||||
|
||||
final List<String> commandsAsString = new ArrayList<>();
|
||||
@@ -187,7 +188,7 @@ public class VelocityPacketAnalyzer {
|
||||
return;
|
||||
}
|
||||
|
||||
final List<Group> groups = GroupManager.getPlayerGroups(sender);
|
||||
final List<Group> groups = GroupManager.getPlayerGroups(sender, false);
|
||||
|
||||
final Map<String, CommandsCache> cache = Storage.getLoader().getPerServerCommandsCacheMap();
|
||||
if (!cache.containsKey(serverName)) {
|
||||
@@ -197,7 +198,7 @@ public class VelocityPacketAnalyzer {
|
||||
final CommandsCache commandsCache = cache.get(serverName);
|
||||
commandsCache.handleCommands(commandsAsString, serverName);
|
||||
|
||||
final List<String> playerCommands = commandsCache.getPlayerCommands(commandsAsString, sender, groups, serverName);
|
||||
final HashSet<String> playerCommands = commandsCache.getPlayerCommands(commandsAsString, sender, groups, serverName, false);
|
||||
helper.removeIf(str -> {
|
||||
if (str.equals("args")) {
|
||||
return false;
|
||||
@@ -206,6 +207,18 @@ public class VelocityPacketAnalyzer {
|
||||
return !playerCommands.contains(str);
|
||||
});
|
||||
|
||||
if (Storage.ConfigSections.Settings.TAB_COMPLETION_FOR_NOT_EXISTING_COMMANDS.ENABLED) {
|
||||
for (Group group : groups) {
|
||||
for (String groupServerName : group.getBlacklistServerNames(serverName)) {
|
||||
if (Storage.isServer(groupServerName, serverName)) {
|
||||
for (String groupCommands : group.getAllCommands(groupServerName)) {
|
||||
helper.add(groupCommands, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (Storage.ConfigSections.Settings.CUSTOM_VERSION.ALWAYS_TAB_COMPLETABLE) {
|
||||
Storage.ConfigSections.Settings.CUSTOM_VERSION.COMMANDS.getLines().forEach(input -> helper.add(input, false));
|
||||
}
|
||||
@@ -217,6 +230,37 @@ public class VelocityPacketAnalyzer {
|
||||
SubArgument.get().getCommandNodeHandler().handleCommandNode(helper, SubArgument.get().getPlayerArgument(sender));
|
||||
}
|
||||
|
||||
private static void handlePluginMessageChannelsPacket(final PluginMessagePacket packet) {
|
||||
final String channelId = packet.getChannel();
|
||||
|
||||
if (Storage.ConfigSections.Settings.HIDE_PLUGIN_CHANNELS.isRegisterChannel(channelId)) {
|
||||
final ByteBuf buf = packet.content();
|
||||
final byte[] data = new byte[buf.readableBytes()];
|
||||
buf.getBytes(buf.readerIndex(), data);
|
||||
|
||||
final String dataStr = new String(data, StandardCharsets.UTF_8);
|
||||
final String[] channels = dataStr.split("\u0000");
|
||||
|
||||
final List<String> filteredChannels = new ArrayList<>(Arrays.asList(channels));
|
||||
final AtomicBoolean changedAnything = new AtomicBoolean(false);
|
||||
|
||||
filteredChannels.removeIf(channel -> {
|
||||
if (!Storage.ConfigSections.Settings.HIDE_PLUGIN_CHANNELS.WHITELISTED_CHANNELS.getLines().contains(channel)) {
|
||||
changedAnything.set(true);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
});
|
||||
|
||||
if (changedAnything.get()) {
|
||||
final ByteBuf newBuf = Unpooled.wrappedBuffer(String.join("\u0000", filteredChannels).getBytes());
|
||||
packet.replace(newBuf);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private static class PacketDecoder extends ChannelDuplexHandler {
|
||||
|
||||
private final Player player;
|
||||
@@ -253,6 +297,10 @@ public class VelocityPacketAnalyzer {
|
||||
}
|
||||
}
|
||||
|
||||
if (packet instanceof PluginMessagePacket pluginMessagePacket && Storage.ConfigSections.Settings.HIDE_PLUGIN_CHANNELS.ENABLED) {
|
||||
handlePluginMessageChannelsPacket(pluginMessagePacket);
|
||||
}
|
||||
|
||||
if (packet instanceof UnsignedPlayerCommandPacket unsignedPlayerCommandPacket) {
|
||||
if (!VelocityBlockCommandListener.handleCommand(player, unsignedPlayerCommandPacket.getCommand()).getResult().isAllowed())
|
||||
return;
|
||||
@@ -262,7 +310,7 @@ public class VelocityPacketAnalyzer {
|
||||
if (request.getCommand() != null) {
|
||||
|
||||
if (Storage.ConfigSections.Settings.PATCH_EXPLOITS.isMalicious(request.getCommand())) {
|
||||
MessageTranslator.send(VelocityLoader.getServer().getConsoleCommandSource(), Storage.ConfigSections.Settings.PATCH_EXPLOITS.ALERT_MESSAGE.get().replace("%player%", player.getUsername()));
|
||||
MessageHelper.sendMessage(CommandSender.from(VelocityLoader.getServer().getConsoleCommandSource()), Storage.ConfigSections.Settings.PATCH_EXPLOITS.ALERT_MESSAGE.get().replace("%player%", player.getUsername()));
|
||||
player.disconnect(LegacyComponentSerializer.legacyAmpersand().deserialize(Storage.ConfigSections.Settings.PATCH_EXPLOITS.KICK_MESSAGE.get()));
|
||||
} else {
|
||||
insertPlayerInput(player, request.getCommand());
|
||||
@@ -282,11 +330,13 @@ public class VelocityPacketAnalyzer {
|
||||
MinecraftPacket packet = (MinecraftPacket) msg;
|
||||
|
||||
if (packet instanceof PluginMessagePacket pluginMessagePacket) {
|
||||
if(CustomServerBrand.get().isEnabled() && CustomServerBrand.get().isBrandTag(pluginMessagePacket.getChannel()) && !player.getCurrentServer().isPresent()) {
|
||||
if (CustomServerBrand.get().isEnabled() && CustomServerBrand.get().isBrandTag(pluginMessagePacket.getChannel()) && !player.getCurrentServer().isPresent()) {
|
||||
final PacketUtils.BrandManipulate brandManipulatePacket = CustomServerBrand.get().createBrandPacket(player);
|
||||
|
||||
super.write(ctx, new PluginMessagePacket(pluginMessagePacket.getChannel(), brandManipulatePacket.getByteBuf()), promise);
|
||||
return;
|
||||
} else if (Storage.ConfigSections.Settings.HIDE_PLUGIN_CHANNELS.ENABLED) {
|
||||
handlePluginMessageChannelsPacket(pluginMessagePacket);
|
||||
}
|
||||
|
||||
} else if (packet instanceof TabCompleteResponsePacket response) {
|
||||
@@ -298,8 +348,8 @@ public class VelocityPacketAnalyzer {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!PermissionUtil.hasBypassPermission(sender) && player.getCurrentServer().isPresent()) {
|
||||
final List<Group> groups = GroupManager.getPlayerGroups(sender);
|
||||
if (!PermissionUtil.hasBypassPermission(sender, false) && player.getCurrentServer().isPresent()) {
|
||||
final List<Group> groups = GroupManager.getPlayerGroups(sender, false);
|
||||
|
||||
boolean cancelsBeforeHand = false;
|
||||
String playerInput = getPlayerInput(player), rawPlayerInput = playerInput, server = player.getCurrentServer().get().getServerInfo().getName();
|
||||
@@ -312,7 +362,7 @@ public class VelocityPacketAnalyzer {
|
||||
}
|
||||
|
||||
if (!playerInput.equals("/")) {
|
||||
cancelsBeforeHand = !Storage.Blacklist.canPlayerAccessTab(sender, groups, StringUtils.replaceFirst(playerInput, "/", ""), server);
|
||||
cancelsBeforeHand = !Storage.Blacklist.canPlayerAccessTab(sender, groups, StringUtils.replaceFirst(playerInput, "/", ""), server, false);
|
||||
|
||||
if (!cancelsBeforeHand) {
|
||||
cancelsBeforeHand = Storage.ConfigSections.Settings.CUSTOM_VERSION.isTabCompletable(StringUtils.replaceFirst(playerInput, "/", "")) || Storage.ConfigSections.Settings.CUSTOM_PLUGIN.isTabCompletable(StringUtils.replaceFirst(playerInput, "/", ""));
|
||||
@@ -336,7 +386,7 @@ public class VelocityPacketAnalyzer {
|
||||
return false;
|
||||
}
|
||||
|
||||
return !Storage.Blacklist.canPlayerAccessTab(sender, groups, command, player.getCurrentServer().get().getServerInfo().getName());
|
||||
return !Storage.Blacklist.canPlayerAccessTab(sender, groups, command, player.getCurrentServer().get().getServerInfo().getName(), false);
|
||||
});
|
||||
|
||||
} else {
|
||||
|
||||
@@ -62,6 +62,18 @@ public class Communicator {
|
||||
);
|
||||
}
|
||||
|
||||
public static void sendPlayerPermissionChangesPacket(UUID playerId) {
|
||||
get().send2Proxy(
|
||||
new CommunicationPackets.Backend2Proxy.AnnouncePlayerPermissionChanges(playerId)
|
||||
);
|
||||
}
|
||||
|
||||
public static void sendGroupPermissionChangesPacket(Set<UUID> playerIds) {
|
||||
get().send2Proxy(
|
||||
new CommunicationPackets.Backend2Proxy.AnnounceGroupPermissionChanges(playerIds)
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static class Proxy2Backend {
|
||||
@@ -174,10 +186,6 @@ public class Communicator {
|
||||
|
||||
// BACKEND -> PROXY
|
||||
public void handleB2PPacket(String serverName, CommunicationPackets.PATPacket incomingPacket) {
|
||||
if (!incomingPacket.tokenMatches(Storage.TOKEN)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (incomingPacket instanceof CommunicationPackets.Backend2Proxy.KeepAlivePacket packet) {
|
||||
final Client client = clients.get(serverName);
|
||||
if (client == null) return;
|
||||
@@ -235,17 +243,12 @@ public class Communicator {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
// Handles all packets that can be handled with as pleased inside the CommunicationPacketHandler...
|
||||
communicationPacketHandler.handleReceivedPacket(incomingPacket);
|
||||
}
|
||||
|
||||
// PROXY -> BACKEND
|
||||
public void handleP2BPacket(CommunicationPackets.PATPacket incomingPacket) {
|
||||
if (!incomingPacket.tokenMatches(Storage.TOKEN)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (incomingPacket instanceof CommunicationPackets.Proxy2Backend.KeepAliveResponsePacket packet) {
|
||||
|
||||
lastReceivedKeepAliveResponse = System.currentTimeMillis();
|
||||
|
||||
+6
-4
@@ -6,7 +6,8 @@ import de.rayzs.pat.plugin.system.communication.cph.CommunicationPacketHandler;
|
||||
import de.rayzs.pat.plugin.logger.Logger;
|
||||
import de.rayzs.pat.utils.CommunicationPackets;
|
||||
import de.rayzs.pat.utils.Reflection;
|
||||
import de.rayzs.pat.utils.message.MessageTranslator;
|
||||
import de.rayzs.pat.utils.StringUtils;
|
||||
import de.rayzs.pat.utils.message.MessageHelper;
|
||||
import de.rayzs.pat.utils.scheduler.PATScheduler;
|
||||
import de.rayzs.pat.utils.sender.CommandSender;
|
||||
import org.bukkit.Bukkit;
|
||||
@@ -59,12 +60,13 @@ public class BukkitCommunicationHandler implements CommunicationPacketHandler {
|
||||
return;
|
||||
}
|
||||
|
||||
final List<String> notificationMessage = MessageTranslator.replaceMessageList(
|
||||
Storage.ConfigSections.Messages.NOTIFICATION.ALERT,
|
||||
final String notificationMessage = StringUtils.replace(
|
||||
Storage.ConfigSections.Messages.NOTIFICATION.ALERT.getLines(),
|
||||
"%player%", player.getName(),
|
||||
"%command%", packet.command(),
|
||||
"%server%", Storage.SERVER_NAME,
|
||||
"%world%", player.getWorld().getName());
|
||||
"%world%", player.getWorld().getName()
|
||||
);
|
||||
|
||||
Logger.info(notificationMessage);
|
||||
}
|
||||
|
||||
+28
-1
@@ -1,12 +1,39 @@
|
||||
package de.rayzs.pat.plugin.system.communication.cph.impl;
|
||||
|
||||
import de.rayzs.pat.api.storage.Storage;
|
||||
import de.rayzs.pat.plugin.BungeeLoader;
|
||||
import de.rayzs.pat.plugin.system.communication.cph.CommunicationPacketHandler;
|
||||
import de.rayzs.pat.utils.CommunicationPackets;
|
||||
import de.rayzs.pat.utils.hooks.LuckPermsHook;
|
||||
import de.rayzs.pat.utils.permission.PermissionPlugin;
|
||||
import de.rayzs.pat.utils.permission.PermissionUtil;
|
||||
import net.md_5.bungee.api.ProxyServer;
|
||||
import java.util.UUID;
|
||||
|
||||
public class BungeeCommunicationHandler implements CommunicationPacketHandler {
|
||||
|
||||
@Override
|
||||
public void handleReceivedPacket(CommunicationPackets.PATPacket packet) {
|
||||
public void handleReceivedPacket(CommunicationPackets.PATPacket incomingPacket) {
|
||||
|
||||
if (Storage.getPermissionPlugin() == PermissionPlugin.LUCKPERMS) {
|
||||
|
||||
if (incomingPacket instanceof CommunicationPackets.Backend2Proxy.AnnouncePlayerPermissionChanges packet) {
|
||||
ProxyServer.getInstance().getScheduler().runAsync(BungeeLoader.getPlugin(), () -> {
|
||||
LuckPermsHook.forcePermissionRecalculation(packet.playerId());
|
||||
PermissionUtil.reloadPermissions(packet.playerId());
|
||||
});
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (incomingPacket instanceof CommunicationPackets.Backend2Proxy.AnnounceGroupPermissionChanges packet) {
|
||||
ProxyServer.getInstance().getScheduler().runAsync(BungeeLoader.getPlugin(), () -> {
|
||||
for (UUID playerId : packet.playerIds()) {
|
||||
LuckPermsHook.forcePermissionRecalculation(playerId);
|
||||
PermissionUtil.reloadPermissions(playerId);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+27
-1
@@ -1,12 +1,38 @@
|
||||
package de.rayzs.pat.plugin.system.communication.cph.impl;
|
||||
|
||||
import de.rayzs.pat.api.storage.Storage;
|
||||
import de.rayzs.pat.plugin.VelocityLoader;
|
||||
import de.rayzs.pat.plugin.system.communication.cph.CommunicationPacketHandler;
|
||||
import de.rayzs.pat.utils.CommunicationPackets;
|
||||
import de.rayzs.pat.utils.hooks.LuckPermsHook;
|
||||
import de.rayzs.pat.utils.permission.PermissionPlugin;
|
||||
import de.rayzs.pat.utils.permission.PermissionUtil;
|
||||
import java.util.UUID;
|
||||
|
||||
public class VelocityCommunicationHandler implements CommunicationPacketHandler {
|
||||
|
||||
@Override
|
||||
public void handleReceivedPacket(CommunicationPackets.PATPacket packet) {
|
||||
public void handleReceivedPacket(CommunicationPackets.PATPacket incomingPacket) {
|
||||
|
||||
if (Storage.getPermissionPlugin() == PermissionPlugin.LUCKPERMS) {
|
||||
|
||||
if (incomingPacket instanceof CommunicationPackets.Backend2Proxy.AnnouncePlayerPermissionChanges packet) {
|
||||
VelocityLoader.getServer().getScheduler().buildTask(VelocityLoader.getInstance(), task -> {
|
||||
LuckPermsHook.forcePermissionRecalculation(packet.playerId());
|
||||
PermissionUtil.reloadPermissions(packet.playerId());
|
||||
}).schedule();
|
||||
}
|
||||
|
||||
if (incomingPacket instanceof CommunicationPackets.Backend2Proxy.AnnounceGroupPermissionChanges packet) {
|
||||
VelocityLoader.getServer().getScheduler().buildTask(VelocityLoader.getInstance(), task -> {
|
||||
for (UUID playerId : packet.playerIds()) {
|
||||
if (Storage.getPermissionPlugin() == PermissionPlugin.LUCKPERMS) {
|
||||
LuckPermsHook.forcePermissionRecalculation(playerId);
|
||||
PermissionUtil.reloadPermissions(playerId);
|
||||
}
|
||||
}
|
||||
}).schedule();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+6
-1
@@ -80,7 +80,12 @@ public class BungeePluginMessageClient implements PluginMessageClient, Listener
|
||||
return;
|
||||
}
|
||||
|
||||
final Server server = (Server) event.getSender();
|
||||
// Private channel: never forward matching traffic between a player and backend.
|
||||
event.setCancelled(true);
|
||||
|
||||
if (!(event.getSender() instanceof Server server)) {
|
||||
return;
|
||||
}
|
||||
final String serverName = server.getInfo().getName();
|
||||
final UUID clientId = Communicator.get().getClientId(serverName);
|
||||
|
||||
|
||||
+8
-2
@@ -76,11 +76,17 @@ public class VelocityPluginMessageClient implements PluginMessageClient {
|
||||
|
||||
@Subscribe
|
||||
public void onQueryReceive(PluginMessageEvent event) {
|
||||
if (event.getIdentifier() != IDENTIFIER) {
|
||||
if (!IDENTIFIER.equals(event.getIdentifier())) {
|
||||
return;
|
||||
}
|
||||
|
||||
final ServerConnection server = (ServerConnection) event.getSource();
|
||||
// This is a private proxy/backend channel. Mark it handled before inspecting
|
||||
// the source so player-originated messages are never forwarded downstream.
|
||||
event.setResult(PluginMessageEvent.ForwardResult.handled());
|
||||
|
||||
if (!(event.getSource() instanceof ServerConnection server)) {
|
||||
return;
|
||||
}
|
||||
final String serverName = server.getServerInfo().getName();
|
||||
final UUID clientId = Communicator.get().getClientId(serverName);
|
||||
|
||||
|
||||
@@ -2,12 +2,15 @@ package de.rayzs.pat.plugin.system.serverbrand.impl;
|
||||
|
||||
import de.rayzs.pat.plugin.packetanalyzer.bukkit.BukkitPacketAnalyzer;
|
||||
import de.rayzs.pat.plugin.system.serverbrand.ServerBrand;
|
||||
import de.rayzs.pat.utils.message.MessageTranslator;
|
||||
import de.rayzs.pat.utils.message.MessageHelper;
|
||||
import de.rayzs.pat.api.storage.Storage;
|
||||
import de.rayzs.pat.plugin.BukkitLoader;
|
||||
import de.rayzs.pat.utils.message.replacer.PlaceholderReplacer;
|
||||
import de.rayzs.pat.utils.scheduler.PATScheduler;
|
||||
import de.rayzs.pat.utils.scheduler.PATSchedulerTask;
|
||||
import de.rayzs.pat.utils.sender.CommandSender;
|
||||
import io.netty.channel.Channel;
|
||||
import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
import de.rayzs.pat.utils.*;
|
||||
@@ -78,6 +81,9 @@ public class BukkitServerBrand implements ServerBrand {
|
||||
|
||||
} else {
|
||||
|
||||
|
||||
final long timeAdjustment = Reflection.isFoliaServer() ? 50 : 1;
|
||||
|
||||
TASK = PATScheduler.createAsyncScheduler(new Runnable() {
|
||||
|
||||
final int length = Storage.ConfigSections.Settings.CUSTOM_BRAND.BRANDS.getLines().size();
|
||||
@@ -91,7 +97,7 @@ public class BukkitServerBrand implements ServerBrand {
|
||||
Bukkit.getOnlinePlayers().forEach(player -> send(player));
|
||||
}
|
||||
|
||||
}, 1, Storage.ConfigSections.Settings.CUSTOM_BRAND.REPEAT_DELAY);
|
||||
}, timeAdjustment, timeAdjustment * Storage.ConfigSections.Settings.CUSTOM_BRAND.REPEAT_DELAY);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -134,7 +140,7 @@ public class BukkitServerBrand implements ServerBrand {
|
||||
|
||||
if (!Reflection.isWeird()) {
|
||||
final PacketUtils.BrandManipulate serverBrand = new PacketUtils.BrandManipulate(
|
||||
MessageTranslator.replaceMessage(player, customBrand)
|
||||
PlaceholderReplacer.applyPlaceholders(CommandSender.from(player), customBrand)
|
||||
);
|
||||
|
||||
player.sendPluginMessage(
|
||||
@@ -155,7 +161,7 @@ public class BukkitServerBrand implements ServerBrand {
|
||||
|
||||
final Object brandPayloadObj = brandPayloadClass
|
||||
.getDeclaredConstructor(String.class)
|
||||
.newInstance(MessageTranslator.replaceMessage(player, customBrand));
|
||||
.newInstance(PlaceholderReplacer.applyPlaceholders(CommandSender.from(player), customBrand));
|
||||
|
||||
final Object customPacketPayloadPacket = clientBoundCustomPacketPayloadPacketClass
|
||||
.getDeclaredConstructor(customPacketPayloadPacketClass)
|
||||
|
||||
@@ -2,7 +2,8 @@ package de.rayzs.pat.plugin.system.serverbrand.impl;
|
||||
|
||||
import de.rayzs.pat.plugin.system.serverbrand.ServerBrand;
|
||||
import de.rayzs.pat.utils.StringUtils;
|
||||
import de.rayzs.pat.utils.message.MessageTranslator;
|
||||
import de.rayzs.pat.utils.message.MessageHelper;
|
||||
import de.rayzs.pat.utils.message.replacer.PlaceholderReplacer;
|
||||
import net.md_5.bungee.api.scheduler.ScheduledTask;
|
||||
import net.md_5.bungee.protocol.ProtocolConstants;
|
||||
import net.md_5.bungee.api.connection.*;
|
||||
@@ -29,7 +30,7 @@ public class BungeeServerBrand implements ServerBrand {
|
||||
}
|
||||
|
||||
if (Storage.ConfigSections.Settings.CUSTOM_BRAND.REPEAT_DELAY == -1) {
|
||||
BRAND = MessageTranslator.replaceMessage(
|
||||
BRAND = PlaceholderReplacer.applyPlaceholders(null,
|
||||
Storage.ConfigSections.Settings.CUSTOM_BRAND.BRANDS.getLines().get(0)
|
||||
) + "§r";
|
||||
|
||||
@@ -46,7 +47,7 @@ public class BungeeServerBrand implements ServerBrand {
|
||||
public void run() {
|
||||
animationPos = (++animationPos) % length;
|
||||
|
||||
BRAND = MessageTranslator.replaceMessage(
|
||||
BRAND = PlaceholderReplacer.applyPlaceholders(null,
|
||||
Storage.ConfigSections.Settings.CUSTOM_BRAND.BRANDS.getLines().get(animationPos)
|
||||
) + "§r";
|
||||
|
||||
|
||||
@@ -2,7 +2,8 @@ package de.rayzs.pat.plugin.system.serverbrand.impl;
|
||||
|
||||
import com.velocitypowered.api.scheduler.ScheduledTask;
|
||||
import de.rayzs.pat.plugin.system.serverbrand.ServerBrand;
|
||||
import de.rayzs.pat.utils.message.MessageTranslator;
|
||||
import de.rayzs.pat.utils.message.MessageHelper;
|
||||
import de.rayzs.pat.utils.message.replacer.PlaceholderReplacer;
|
||||
import net.md_5.bungee.protocol.ProtocolConstants;
|
||||
import de.rayzs.pat.plugin.VelocityLoader;
|
||||
import de.rayzs.pat.api.storage.Storage;
|
||||
@@ -49,7 +50,7 @@ public class VelocityServerBrand implements ServerBrand {
|
||||
}
|
||||
|
||||
if (Storage.ConfigSections.Settings.CUSTOM_BRAND.REPEAT_DELAY == -1) {
|
||||
BRAND = MessageTranslator.replaceMessage(Storage.ConfigSections.Settings.CUSTOM_BRAND.BRANDS.getLines().get(0)) + "§r";
|
||||
BRAND = PlaceholderReplacer.applyPlaceholders(null, Storage.ConfigSections.Settings.CUSTOM_BRAND.BRANDS.getLines().get(0)) + "§r";
|
||||
SERVER.getAllPlayers().forEach(this::send);
|
||||
} else {
|
||||
TASK = SERVER.getScheduler().buildTask(VelocityLoader.getInstance(), new Runnable() {
|
||||
@@ -61,7 +62,7 @@ public class VelocityServerBrand implements ServerBrand {
|
||||
public void run() {
|
||||
animationPos = (++animationPos) % length;
|
||||
|
||||
BRAND = MessageTranslator.replaceMessage(
|
||||
BRAND = PlaceholderReplacer.applyPlaceholders(null,
|
||||
Storage.ConfigSections.Settings.CUSTOM_BRAND.BRANDS.getLines().get(animationPos)
|
||||
) + "§r";
|
||||
|
||||
|
||||
+2
@@ -98,6 +98,8 @@ public class CommandNodeHandler extends SubArgumentHandler {
|
||||
break;
|
||||
}
|
||||
|
||||
if (input == null) continue;
|
||||
|
||||
final Storage.Blacklist.BlockType type = Storage.Blacklist.BlockTypeFetcher.getType(input);
|
||||
if (type == Storage.Blacklist.BlockType.CHAT) {
|
||||
continue;
|
||||
|
||||
+12
-1
@@ -1,6 +1,7 @@
|
||||
package de.rayzs.pat.plugin.system.subargument.handler.impl;
|
||||
|
||||
import de.rayzs.pat.api.storage.Storage;
|
||||
import de.rayzs.pat.plugin.logger.Logger;
|
||||
import de.rayzs.pat.plugin.system.subargument.handler.SubArgumentHandler;
|
||||
import de.rayzs.pat.plugin.system.subargument.SubArgument;
|
||||
import de.rayzs.pat.utils.StringUtils;
|
||||
@@ -67,6 +68,16 @@ public class ExecuteHandler extends SubArgumentHandler {
|
||||
listed = !turn;
|
||||
}
|
||||
|
||||
/*
|
||||
final boolean blocked = turn != listed;
|
||||
if (blocked && command.contains("discord")) {
|
||||
Logger.info("Yes, sub-argument was blocked! (" + sender.getName() + ", " + command + ")");
|
||||
Logger.info("-> " + turn + ", " + listed + ", " + negated);
|
||||
}
|
||||
|
||||
return blocked;
|
||||
*/
|
||||
|
||||
return turn != listed;
|
||||
}
|
||||
|
||||
@@ -133,7 +144,7 @@ public class ExecuteHandler extends SubArgumentHandler {
|
||||
c = StringUtils.replaceLast(c, " ", "");
|
||||
}
|
||||
|
||||
listed = c.equalsIgnoreCase(cpyCommand) || cpyCommand.startsWith(c + " ");
|
||||
listed = c.equalsIgnoreCase(cpyCommand) || StringUtils.startsWithIgnoreCase(c + " ", cpyCommand);
|
||||
|
||||
if (listed && ends && cpyCommand.length() > c.length()) {
|
||||
listed = false;
|
||||
|
||||
+13
-8
@@ -1,10 +1,10 @@
|
||||
package de.rayzs.pat.plugin.system.subargument.handler.impl;
|
||||
|
||||
import de.rayzs.pat.api.storage.Storage;
|
||||
import de.rayzs.pat.plugin.logger.Logger;
|
||||
import de.rayzs.pat.plugin.system.subargument.handler.SubArgumentHandler;
|
||||
import de.rayzs.pat.plugin.system.subargument.SubArgument;
|
||||
import de.rayzs.pat.utils.NumberUtils;
|
||||
import de.rayzs.pat.utils.StringUtils;
|
||||
import de.rayzs.pat.utils.sender.CommandSender;
|
||||
import de.rayzs.pat.plugin.system.subargument.argument.Arguments;
|
||||
|
||||
@@ -134,16 +134,21 @@ public class TabCompleteHandler extends SubArgumentHandler {
|
||||
possibilities.removeIf(possibility -> getInstance().getCachedOnlinePlayerNames().contains(possibility));
|
||||
|
||||
|
||||
possibilities.removeIf(s -> {
|
||||
if (negated.contains(s)) {
|
||||
return false;
|
||||
}
|
||||
if (!arguments.getResultTab(StringUtils.getFirstArg(cursor)).isEmpty() && result.isEmpty()) {
|
||||
possibilities.clear();
|
||||
possibilities.add("///////////");
|
||||
} else {
|
||||
possibilities.removeIf(s -> {
|
||||
if (negated.contains(s)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return result.contains(s);
|
||||
});
|
||||
return result.contains(s);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (possibilities.isEmpty()) {
|
||||
if (turn && possibilities.isEmpty()) {
|
||||
return suggestions;
|
||||
}
|
||||
|
||||
|
||||
+4
-10
@@ -1,14 +1,13 @@
|
||||
package de.rayzs.pat.plugin.system.subargument.handler.impl;
|
||||
|
||||
import de.rayzs.pat.api.storage.Storage;
|
||||
import de.rayzs.pat.plugin.logger.Logger;
|
||||
import de.rayzs.pat.plugin.system.subargument.handler.SubArgumentHandler;
|
||||
import de.rayzs.pat.plugin.system.subargument.SubArgument;
|
||||
import de.rayzs.pat.utils.Reflection;
|
||||
import de.rayzs.pat.utils.sender.CommandSender;
|
||||
import de.rayzs.pat.plugin.system.subargument.argument.Arguments;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.HashSet;
|
||||
|
||||
public class UpdateArgumentsHandler extends SubArgumentHandler {
|
||||
|
||||
@@ -16,7 +15,7 @@ public class UpdateArgumentsHandler extends SubArgumentHandler {
|
||||
super(instance);
|
||||
}
|
||||
|
||||
public void updatePlayerArguments(CommandSender sender, List<String> commands, List<String> serverCommands, List<String> groupCommands) {
|
||||
public void updatePlayerArguments(CommandSender sender, HashSet<String> commands, HashSet<String> serverCommands, HashSet<String> groupCommands) {
|
||||
final Arguments arguments = getInstance().getPlayerArgument(sender);
|
||||
|
||||
arguments.clearArguments();
|
||||
@@ -40,17 +39,12 @@ public class UpdateArgumentsHandler extends SubArgumentHandler {
|
||||
|
||||
} else {
|
||||
|
||||
for (String command : Arguments.get().CHAT_ARGUMENTS.getGeneralArgument().getInputs()) {
|
||||
for (String command : commands) {
|
||||
if (groupCommands.contains(command)) continue;
|
||||
|
||||
arguments.CHAT_ARGUMENTS.buildArguments(Storage.Blacklist.BlockTypeFetcher.modify(command));
|
||||
arguments.buildArgumentStacks(command);
|
||||
}
|
||||
|
||||
for (String command : Arguments.get().TAB_ARGUMENTS.getGeneralArgument().getInputs()) {
|
||||
if (groupCommands.contains(command)) continue;
|
||||
|
||||
arguments.TAB_ARGUMENTS.buildArguments(Storage.Blacklist.BlockTypeFetcher.modify(command));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -83,32 +83,48 @@ public class CommandsCache {
|
||||
filteredCommands = tmpFilteredCommands;
|
||||
}
|
||||
|
||||
public List<String> getPlayerCommands(Collection<String> unfilteredCommands, CommandSender sender, List<Group> groups) {
|
||||
return getPlayerCommands(unfilteredCommands, sender, groups, null);
|
||||
public HashSet<String> getPlayerCommands(
|
||||
final Collection<String> unfilteredCommands,
|
||||
final CommandSender sender,
|
||||
final List<Group> groups,
|
||||
final boolean isOperator
|
||||
) {
|
||||
return getPlayerCommands(unfilteredCommands, sender, groups, null, isOperator);
|
||||
}
|
||||
|
||||
public List<String> getPlayerCommands(Collection<String> unfilteredCommands, CommandSender sender, List<Group> groups, String serverName) {
|
||||
List<String> playerCommands = new LinkedList<>(unfilteredCommands);
|
||||
List<String> localFilteredCommands = filteredCommands == null ? null : new LinkedList<>();
|
||||
public HashSet<String> getPlayerCommands(
|
||||
final Collection<String> unfilteredCommands,
|
||||
final CommandSender sender,
|
||||
final List<Group> groups,
|
||||
final String serverName,
|
||||
final boolean isOperator
|
||||
) {
|
||||
final HashSet<String> playerCommands = new HashSet<>(unfilteredCommands);
|
||||
final HashSet<String> localFilteredCommands = filteredCommands == null ? null : Reflection.isProxyServer()
|
||||
? new HashSet<>() : new HashSet<>(filteredCommands);
|
||||
|
||||
if (localFilteredCommands == null)
|
||||
return playerCommands;
|
||||
|
||||
if (Reflection.isProxyServer()) {
|
||||
// Slower and step-by-step due to some conflicts in the past with proxy servers.
|
||||
|
||||
final int max = filteredCommands.size();
|
||||
for (int i = 0; i < max; i++) {
|
||||
try {
|
||||
String command = filteredCommands.get(i);
|
||||
localFilteredCommands.add(command);
|
||||
} catch (IndexOutOfBoundsException indexOutOfBoundsException) {
|
||||
Logger.warning("Array is out of bounds " + i + "/" + max + "! " + indexOutOfBoundsException.getMessage());
|
||||
break;
|
||||
final int max = filteredCommands.size();
|
||||
|
||||
for (int i = 0; i < max; i++) {
|
||||
try {
|
||||
String command = filteredCommands.get(i);
|
||||
localFilteredCommands.add(command);
|
||||
} catch (IndexOutOfBoundsException indexOutOfBoundsException) {
|
||||
//Logger.warning("Array is out of bounds " + i + "/" + max + "! " + indexOutOfBoundsException.getMessage());
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (!PermissionUtil.hasBypassPermission(sender)) {
|
||||
boolean hasNamespaceBypass = Storage.ConfigSections.Settings.BLOCK_NAMESPACE_COMMANDS.doesBypass(sender);
|
||||
if (!PermissionUtil.hasBypassPermission(sender, isOperator)) {
|
||||
boolean hasNamespaceBypass = Storage.ConfigSections.Settings.BLOCK_NAMESPACE_COMMANDS.doesBypass(sender, isOperator);
|
||||
|
||||
playerCommands.removeIf(command -> {
|
||||
if (!hasNamespaceBypass && Storage.ConfigSections.Settings.BLOCK_NAMESPACE_COMMANDS.isCommand(command)) {
|
||||
@@ -119,12 +135,12 @@ public class CommandsCache {
|
||||
return false;
|
||||
}
|
||||
|
||||
return !Storage.Blacklist.canPlayerAccessTab(sender, groups, command, serverName);
|
||||
return !Storage.Blacklist.canPlayerAccessTab(sender, groups, command, serverName, isOperator);
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
final List<String> serverCommands = Storage.Blacklist.Collector.collectAllServerCommands(serverName);
|
||||
final HashSet<String> serverCommands = Storage.Blacklist.Collector.collectAllServerCommands(serverName);
|
||||
|
||||
SubArgument.get().getUpdateArgumentsHandler().updatePlayerArguments(
|
||||
sender,
|
||||
@@ -139,7 +155,7 @@ public class CommandsCache {
|
||||
serverName != null
|
||||
);
|
||||
|
||||
return playerCommands.stream().map(command -> {
|
||||
return new HashSet<>(playerCommands.stream().map(command -> {
|
||||
command = StringUtils.getFirstArg(command);
|
||||
|
||||
Storage.Blacklist.BlockType type = Storage.Blacklist.BlockTypeFetcher.getType(command);
|
||||
@@ -147,7 +163,7 @@ public class CommandsCache {
|
||||
return command;
|
||||
|
||||
return Storage.Blacklist.BlockTypeFetcher.modify(command, type);
|
||||
}).toList();
|
||||
}).toList());
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -1,50 +1,93 @@
|
||||
package de.rayzs.pat.utils;
|
||||
|
||||
import de.rayzs.pat.plugin.system.communication.Communicator;
|
||||
import de.rayzs.pat.api.storage.Storage;
|
||||
import de.rayzs.pat.plugin.system.communication.Communicator;
|
||||
import de.rayzs.pat.utils.configuration.helper.MultipleMessagesHelper;
|
||||
|
||||
import java.util.*;
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.GCMParameterSpec;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.io.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* Wire codec for communication between proxy and backend servers.
|
||||
*
|
||||
* <p>Packets are explicitly encoded and protected with AES-256-GCM before
|
||||
* transmission. Encryption keys are derived from {@link Storage#TOKEN},
|
||||
* using backend UUIDs only as derivation context.
|
||||
*
|
||||
* <p>The codec does not use native Java deserialization for network data,
|
||||
* and all variable-length fields are bounded before allocation.
|
||||
*/
|
||||
public class CommunicationPackets {
|
||||
|
||||
|
||||
public static final byte PROTOCOL_VERSION = 1;
|
||||
private static final byte INIT_PACKET = 0;
|
||||
private static final byte NOT_INIT_PACKET = 1;
|
||||
|
||||
private static final int HEADER_LENGTH = 2;
|
||||
private static final int NONCE_LENGTH = 12;
|
||||
private static final int GCM_TAG_BITS = 128;
|
||||
private static final int GCM_TAG_LENGTH = GCM_TAG_BITS / 8;
|
||||
// Velocity defaults to 32,767 bytes for plugin message payloads.
|
||||
private static final int MAX_WIRE_BYTES = 32_767;
|
||||
private static final int MAX_PLAINTEXT_BYTES = MAX_WIRE_BYTES - HEADER_LENGTH - NONCE_LENGTH - GCM_TAG_LENGTH;
|
||||
private static final SecureRandom RANDOM = new SecureRandom();
|
||||
private static final byte[] HKDF_SALT = "ProAntiTab/plugin-messaging/v1".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
// Stable packet IDs. Do not reorder/reuse IDs without a protocol-version bump.
|
||||
private static final byte P_UPDATE = 1;
|
||||
private static final byte P_IDENTITY = 2;
|
||||
private static final byte P_NOTIFICATION = 3;
|
||||
private static final byte P_EXEC_CONSOLE = 4;
|
||||
private static final byte P_EXEC_PLAYER = 5;
|
||||
private static final byte P_CONSOLE_MESSAGE = 6;
|
||||
private static final byte P_KEEPALIVE_RESPONSE = 7;
|
||||
private static final byte P_DATA_SYNC = 8;
|
||||
private static final byte P_IDENTITY_REQUEST = 20;
|
||||
private static final byte P_IDENTITY_RESPONSE = 21;
|
||||
private static final byte P_DATA_SYNC_RECEIVED = 22;
|
||||
private static final byte P_KEEPALIVE = 23;
|
||||
private static final byte P_PLAYER_PERMISSION_CHANGE = 24;
|
||||
private static final byte P_GROUP_PERMISSION_CHANGE = 25;
|
||||
|
||||
public static byte[] preparePacket(Object object) {
|
||||
return preparePacket(object, Communicator.get().getId());
|
||||
}
|
||||
|
||||
public static byte[] preparePacket(Object object, UUID id) {
|
||||
if (!isValidPacket(object)) {
|
||||
if (!isValidPacket(object) || Storage.TOKEN == null || Storage.TOKEN.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
final boolean isInitialPacket = isInitialPacket(object);
|
||||
final ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
|
||||
try {
|
||||
final boolean initial = isInitialPacket(object);
|
||||
if (!initial && id == null) {
|
||||
return null;
|
||||
}
|
||||
final byte[] plaintext = encodePacket((PATPacket) object);
|
||||
final byte[] nonce = new byte[NONCE_LENGTH];
|
||||
RANDOM.nextBytes(nonce);
|
||||
|
||||
try (ObjectOutputStream outputStream = new ObjectOutputStream(arrayOutputStream)) {
|
||||
outputStream.writeObject(object);
|
||||
outputStream.flush();
|
||||
// Wire format: [version:1][init:1][nonce:12][ciphertext + GCM tag:16].
|
||||
// The version and init flag are authenticated as GCM additional authenticated data.
|
||||
final byte[] header = new byte[]{PROTOCOL_VERSION, initial ? INIT_PACKET : NOT_INIT_PACKET};
|
||||
final SecretKeySpec key = deriveKey(Storage.TOKEN, initial ? null : id);
|
||||
final byte[] ciphertext = encrypt(plaintext, key, nonce, header);
|
||||
|
||||
final byte[] encryptedBytes = xor(arrayOutputStream.toByteArray(), isInitialPacket
|
||||
? Storage.TOKEN
|
||||
: id.toString()
|
||||
);
|
||||
|
||||
final byte[] bytes = new byte[encryptedBytes.length + 1];
|
||||
|
||||
bytes[0] = isInitialPacket ? INIT_PACKET : NOT_INIT_PACKET;
|
||||
System.arraycopy(encryptedBytes, 0, bytes, 1, bytes.length - 1);
|
||||
|
||||
return bytes;
|
||||
|
||||
} catch (Exception ignored) { }
|
||||
|
||||
return null;
|
||||
final byte[] result = new byte[header.length + NONCE_LENGTH + ciphertext.length];
|
||||
System.arraycopy(header, 0, result, 0, header.length);
|
||||
System.arraycopy(nonce, 0, result, header.length, NONCE_LENGTH);
|
||||
System.arraycopy(ciphertext, 0, result, header.length + NONCE_LENGTH, ciphertext.length);
|
||||
return result;
|
||||
} catch (IOException | GeneralSecurityException ignored) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static Object readPacket(byte[] bytes) {
|
||||
@@ -52,143 +95,265 @@ public class CommunicationPackets {
|
||||
}
|
||||
|
||||
public static Object readPacket(byte[] bytes, UUID id) {
|
||||
if (bytes.length == 0) {
|
||||
if (bytes == null || bytes.length < HEADER_LENGTH + NONCE_LENGTH + GCM_TAG_LENGTH
|
||||
|| bytes.length > MAX_WIRE_BYTES || Storage.TOKEN == null || Storage.TOKEN.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
final byte init = bytes[0];
|
||||
bytes = Arrays.copyOfRange(bytes, 1, bytes.length);
|
||||
|
||||
bytes = xor(bytes, isInitialPacket(init)
|
||||
? Storage.TOKEN
|
||||
: id.toString()
|
||||
);
|
||||
|
||||
final ByteArrayInputStream arrayInputStream = new ByteArrayInputStream(bytes);
|
||||
|
||||
try (ObjectInput input = new ObjectInputStream(arrayInputStream)) {
|
||||
final Object object = input.readObject();
|
||||
|
||||
if (object.getClass() == null || !isValidPacket(object)) {
|
||||
try {
|
||||
final byte version = bytes[0];
|
||||
final byte initFlag = bytes[1];
|
||||
if (version != PROTOCOL_VERSION || (initFlag != INIT_PACKET && initFlag != NOT_INIT_PACKET)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return object;
|
||||
} catch (Exception ignored) { }
|
||||
final boolean initial = initFlag == INIT_PACKET;
|
||||
if (!initial && id == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return null;
|
||||
final byte[] header = Arrays.copyOfRange(bytes, 0, 2);
|
||||
final byte[] nonce = Arrays.copyOfRange(bytes, 2, 2 + NONCE_LENGTH);
|
||||
final byte[] ciphertext = Arrays.copyOfRange(bytes, 2 + NONCE_LENGTH, bytes.length);
|
||||
|
||||
final SecretKeySpec key = deriveKey(Storage.TOKEN, initial ? null : id);
|
||||
// Authentication is verified by GCM before decodePacket() sees any plaintext.
|
||||
final byte[] plaintext = decrypt(ciphertext, key, nonce, header);
|
||||
return decodePacket(plaintext, initial);
|
||||
} catch (IOException | GeneralSecurityException ignored) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Yes, I am aware that xor is not the best encryption out there,
|
||||
// but it will suffice for now since the encryption shouldn't be too heavy.
|
||||
private static byte[] xor(byte[] bytes, String key) {
|
||||
final byte[] output = new byte[bytes.length];
|
||||
final byte[] secret = key.getBytes();
|
||||
private static SecretKeySpec deriveKey(String token, UUID id) throws GeneralSecurityException {
|
||||
// RFC 5869 HKDF-SHA-256. The token is the input keying material; the UUID is
|
||||
// public context used to separate normal-session keys between backend identities.
|
||||
final Mac mac = Mac.getInstance("HmacSHA256");
|
||||
|
||||
int pos = 0;
|
||||
// HKDF-Extract(salt, IKM)
|
||||
mac.init(new SecretKeySpec(HKDF_SALT, "HmacSHA256"));
|
||||
final byte[] prk = mac.doFinal(token.getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
for (int i = 0; i < bytes.length; i++) {
|
||||
output[i] = (byte) (bytes[i] ^ secret[pos]);
|
||||
pos += 1;
|
||||
// HKDF-Expand(PRK, info, 32). One HMAC block is sufficient for an AES-256 key.
|
||||
final String context = id == null ? "initial" : "backend:" + id;
|
||||
final byte[] info = context.getBytes(StandardCharsets.UTF_8);
|
||||
mac.init(new SecretKeySpec(prk, "HmacSHA256"));
|
||||
mac.update(info);
|
||||
mac.update((byte) 0x01);
|
||||
final byte[] okm = mac.doFinal();
|
||||
return new SecretKeySpec(okm, "AES");
|
||||
}
|
||||
|
||||
if (pos >= secret.length) {
|
||||
pos = 0;
|
||||
private static byte[] encrypt(byte[] plaintext, SecretKeySpec key, byte[] nonce, byte[] aad) throws GeneralSecurityException {
|
||||
final Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
|
||||
cipher.init(Cipher.ENCRYPT_MODE, key, new GCMParameterSpec(GCM_TAG_BITS, nonce));
|
||||
cipher.updateAAD(aad);
|
||||
return cipher.doFinal(plaintext);
|
||||
}
|
||||
|
||||
private static byte[] decrypt(byte[] ciphertext, SecretKeySpec key, byte[] nonce, byte[] aad) throws GeneralSecurityException {
|
||||
final Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
|
||||
cipher.init(Cipher.DECRYPT_MODE, key, new GCMParameterSpec(GCM_TAG_BITS, nonce));
|
||||
cipher.updateAAD(aad);
|
||||
return cipher.doFinal(ciphertext);
|
||||
}
|
||||
|
||||
private static byte[] encodePacket(PATPacket packet) throws IOException {
|
||||
final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
|
||||
try (DataOutputStream out = new DataOutputStream(new BoundedOutputStream(buffer, MAX_PLAINTEXT_BYTES))) {
|
||||
if (packet instanceof Proxy2Backend.UpdatePacket p) {
|
||||
out.writeByte(P_UPDATE); writeNullableUuid(out, p.playerId());
|
||||
} else if (packet instanceof Proxy2Backend.IdentityPacket p) {
|
||||
out.writeByte(P_IDENTITY); writeUuid(out, p.targetServerId()); writeString(out, p.serverName());
|
||||
} else if (packet instanceof Proxy2Backend.NotificationPacket p) {
|
||||
out.writeByte(P_NOTIFICATION); writeUuid(out, p.playerId()); writeString(out, p.command());
|
||||
} else if (packet instanceof Proxy2Backend.ExecuteConsoleCommandPacket p) {
|
||||
out.writeByte(P_EXEC_CONSOLE); writeString(out, p.command());
|
||||
} else if (packet instanceof Proxy2Backend.ExecutePlayerCommandPacket p) {
|
||||
out.writeByte(P_EXEC_PLAYER); writeUuid(out, p.playerId()); writeString(out, p.command());
|
||||
} else if (packet instanceof Proxy2Backend.ConsoleMessagePacket p) {
|
||||
out.writeByte(P_CONSOLE_MESSAGE); writeString(out, p.message());
|
||||
} else if (packet instanceof Proxy2Backend.KeepAliveResponsePacket) {
|
||||
out.writeByte(P_KEEPALIVE_RESPONSE);
|
||||
} else if (packet instanceof Proxy2Backend.DataSyncPacket p) {
|
||||
out.writeByte(P_DATA_SYNC);
|
||||
writeString(out, p.messages().prefix());
|
||||
out.writeBoolean(p.autoLowerCase().enabled());
|
||||
out.writeBoolean(p.unknownCommand().enabled());
|
||||
final List<String> lines = p.unknownCommand().message().getLines();
|
||||
out.writeInt(lines.size());
|
||||
for (String line : lines) writeString(out, line);
|
||||
} else if (packet instanceof Backend2Proxy.IdentityRequestPacket p) {
|
||||
out.writeByte(P_IDENTITY_REQUEST); writeUuid(out, p.serverId());
|
||||
} else if (packet instanceof Backend2Proxy.IdentityResponsePacket p) {
|
||||
out.writeByte(P_IDENTITY_RESPONSE); writeUuid(out, p.serverId());
|
||||
} else if (packet instanceof Backend2Proxy.DataSyncReceivedPacket) {
|
||||
out.writeByte(P_DATA_SYNC_RECEIVED);
|
||||
} else if (packet instanceof Backend2Proxy.KeepAlivePacket) {
|
||||
out.writeByte(P_KEEPALIVE);
|
||||
} else if (packet instanceof Backend2Proxy.AnnouncePlayerPermissionChanges p) {
|
||||
out.writeByte(P_PLAYER_PERMISSION_CHANGE); writeUuid(out, p.playerId());
|
||||
} else if (packet instanceof Backend2Proxy.AnnounceGroupPermissionChanges p) {
|
||||
out.writeByte(P_GROUP_PERMISSION_CHANGE);
|
||||
out.writeInt(p.playerIds().size());
|
||||
for (UUID uuid : p.playerIds()) writeUuid(out, uuid);
|
||||
} else {
|
||||
throw new IOException("Unknown packet type");
|
||||
}
|
||||
}
|
||||
|
||||
return output;
|
||||
if (buffer.size() > MAX_PLAINTEXT_BYTES) throw new IOException("Packet too large");
|
||||
return buffer.toByteArray();
|
||||
}
|
||||
|
||||
public static boolean isValidPacket(Object object) {
|
||||
return object instanceof PATPacket;
|
||||
}
|
||||
private static PATPacket decodePacket(byte[] bytes, boolean initial) throws IOException {
|
||||
if (bytes.length == 0 || bytes.length > MAX_PLAINTEXT_BYTES) throw new IOException("Invalid packet length");
|
||||
try (DataInputStream in = new DataInputStream(new ByteArrayInputStream(bytes))) {
|
||||
final int type = in.readUnsignedByte();
|
||||
final PATPacket packet = switch (type) {
|
||||
case P_UPDATE -> new Proxy2Backend.UpdatePacket(readNullableUuid(in));
|
||||
case P_IDENTITY -> new Proxy2Backend.IdentityPacket(readUuid(in), readString(in));
|
||||
case P_NOTIFICATION -> new Proxy2Backend.NotificationPacket(readUuid(in), readString(in));
|
||||
case P_EXEC_CONSOLE -> new Proxy2Backend.ExecuteConsoleCommandPacket(readString(in));
|
||||
case P_EXEC_PLAYER -> new Proxy2Backend.ExecutePlayerCommandPacket(readUuid(in), readString(in));
|
||||
case P_CONSOLE_MESSAGE -> new Proxy2Backend.ConsoleMessagePacket(readString(in));
|
||||
case P_KEEPALIVE_RESPONSE -> new Proxy2Backend.KeepAliveResponsePacket();
|
||||
case P_DATA_SYNC -> {
|
||||
final Proxy2Backend.DataSyncPacket.Messages messages =
|
||||
new Proxy2Backend.DataSyncPacket.Messages(readString(in));
|
||||
final Proxy2Backend.DataSyncPacket.AutoLowerCase autoLowerCase =
|
||||
new Proxy2Backend.DataSyncPacket.AutoLowerCase(in.readBoolean());
|
||||
final boolean unknownEnabled = in.readBoolean();
|
||||
final int count = readCount(in, Integer.BYTES);
|
||||
final List<String> lines = new ArrayList<>(count);
|
||||
for (int i = 0; i < count; i++) lines.add(readString(in));
|
||||
final Proxy2Backend.DataSyncPacket.UnknownCommand unknown =
|
||||
new Proxy2Backend.DataSyncPacket.UnknownCommand(
|
||||
unknownEnabled, new MultipleMessagesHelper(lines));
|
||||
yield new Proxy2Backend.DataSyncPacket(messages, autoLowerCase, unknown);
|
||||
}
|
||||
case P_IDENTITY_REQUEST -> new Backend2Proxy.IdentityRequestPacket(readUuid(in));
|
||||
case P_IDENTITY_RESPONSE -> new Backend2Proxy.IdentityResponsePacket(readUuid(in));
|
||||
case P_DATA_SYNC_RECEIVED -> new Backend2Proxy.DataSyncReceivedPacket();
|
||||
case P_KEEPALIVE -> new Backend2Proxy.KeepAlivePacket();
|
||||
case P_PLAYER_PERMISSION_CHANGE -> new Backend2Proxy.AnnouncePlayerPermissionChanges(readUuid(in));
|
||||
case P_GROUP_PERMISSION_CHANGE -> {
|
||||
final int count = readCount(in, 2 * Long.BYTES);
|
||||
final Set<UUID> ids = new HashSet<>(Math.max(16, count));
|
||||
for (int i = 0; i < count; i++) ids.add(readUuid(in));
|
||||
yield new Backend2Proxy.AnnounceGroupPermissionChanges(ids);
|
||||
}
|
||||
default -> throw new IOException("Unknown packet type: " + type);
|
||||
};
|
||||
|
||||
public static boolean isP2BPacket(Object object) {
|
||||
return object instanceof P2BPacket;
|
||||
}
|
||||
|
||||
public static boolean isB2PPacket(Object object) {
|
||||
return object instanceof B2PPacket;
|
||||
}
|
||||
|
||||
public static boolean isInitialPacket(Object object) {
|
||||
return object instanceof InitialPacket;
|
||||
}
|
||||
|
||||
public static boolean isInitialPacket(byte[] bytes) {
|
||||
return bytes.length > 0 && isInitialPacket(bytes[0]);
|
||||
}
|
||||
|
||||
public static boolean isInitialPacket(byte b) {
|
||||
return b == INIT_PACKET;
|
||||
}
|
||||
|
||||
public interface PATPacket extends Serializable {
|
||||
String token = Storage.TOKEN;
|
||||
|
||||
default boolean tokenMatches(String token) {
|
||||
return PATPacket.token.equals(token);
|
||||
if (in.available() != 0) throw new IOException("Trailing packet data");
|
||||
if (initial != isInitialPacket(packet)) throw new IOException("Packet/header type mismatch");
|
||||
return packet;
|
||||
}
|
||||
}
|
||||
|
||||
// Reject oversized plaintext as it is written, rather than after allocating it.
|
||||
private static final class BoundedOutputStream extends FilterOutputStream {
|
||||
private final int limit;
|
||||
private int written;
|
||||
|
||||
private interface InitialPacket extends PATPacket {}
|
||||
private interface Synchronizable extends Serializable {}
|
||||
private BoundedOutputStream(OutputStream out, int limit) {
|
||||
super(out);
|
||||
this.limit = limit;
|
||||
}
|
||||
|
||||
private interface P2BPacket extends PATPacket {}
|
||||
private interface B2PPacket extends PATPacket {}
|
||||
@Override
|
||||
public void write(int value) throws IOException {
|
||||
if (written >= limit) throw new IOException("Packet too large");
|
||||
out.write(value);
|
||||
written++;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(byte[] bytes, int offset, int length) throws IOException {
|
||||
if (length > limit - written) throw new IOException("Packet too large");
|
||||
out.write(bytes, offset, length);
|
||||
written += length;
|
||||
}
|
||||
}
|
||||
|
||||
private static void writeString(DataOutputStream out, String value) throws IOException {
|
||||
if (value == null) throw new IOException("Null string");
|
||||
final byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
|
||||
out.writeInt(bytes.length);
|
||||
out.write(bytes);
|
||||
}
|
||||
|
||||
private static String readString(DataInputStream in) throws IOException {
|
||||
final int length = in.readInt();
|
||||
if (length < 0 || length > in.available()) {
|
||||
throw new IOException("Invalid string length");
|
||||
}
|
||||
return new String(in.readNBytes(length), StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private static int readCount(DataInputStream in, int minimumEntryBytes) throws IOException {
|
||||
final int count = in.readInt();
|
||||
if (count < 0 || count > in.available() / minimumEntryBytes) {
|
||||
throw new IOException("Invalid collection size");
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
private static void writeUuid(DataOutputStream out, UUID uuid) throws IOException {
|
||||
if (uuid == null) throw new IOException("Null UUID");
|
||||
out.writeLong(uuid.getMostSignificantBits());
|
||||
out.writeLong(uuid.getLeastSignificantBits());
|
||||
}
|
||||
|
||||
private static UUID readUuid(DataInputStream in) throws IOException {
|
||||
return new UUID(in.readLong(), in.readLong());
|
||||
}
|
||||
|
||||
private static void writeNullableUuid(DataOutputStream out, UUID uuid) throws IOException {
|
||||
out.writeBoolean(uuid != null);
|
||||
if (uuid != null) writeUuid(out, uuid);
|
||||
}
|
||||
|
||||
private static UUID readNullableUuid(DataInputStream in) throws IOException {
|
||||
return in.readBoolean() ? readUuid(in) : null;
|
||||
}
|
||||
|
||||
public static boolean isValidPacket(Object object) { return object instanceof PATPacket; }
|
||||
public static boolean isP2BPacket(Object object) { return object instanceof P2BPacket; }
|
||||
public static boolean isB2PPacket(Object object) { return object instanceof B2PPacket; }
|
||||
public static boolean isInitialPacket(Object object) { return object instanceof InitialPacket; }
|
||||
// Routing hint only; the flag is authenticated by readPacket().
|
||||
public static boolean isInitialPacket(byte[] bytes) { return bytes != null && bytes.length > 1 && bytes[0] == PROTOCOL_VERSION && bytes[1] == INIT_PACKET; }
|
||||
|
||||
public interface PATPacket { }
|
||||
private interface InitialPacket extends PATPacket { }
|
||||
private interface Synchronizable { }
|
||||
private interface P2BPacket extends PATPacket { }
|
||||
private interface B2PPacket extends PATPacket { }
|
||||
|
||||
public static class Proxy2Backend {
|
||||
|
||||
private Proxy2Backend() { }
|
||||
|
||||
public record UpdatePacket(UUID playerId) implements P2BPacket {
|
||||
public boolean forEveryone() { return playerId == null; }
|
||||
}
|
||||
|
||||
public record UpdatePacket(UUID playerId) implements P2BPacket { public boolean forEveryone() { return playerId == null; } }
|
||||
public record IdentityPacket(UUID targetServerId, String serverName) implements InitialPacket, P2BPacket { }
|
||||
|
||||
public record NotificationPacket(UUID playerId, String command) implements P2BPacket { }
|
||||
|
||||
public record ExecuteConsoleCommandPacket(String command) implements P2BPacket { }
|
||||
|
||||
public record ExecutePlayerCommandPacket(UUID playerId, String command) implements P2BPacket { }
|
||||
|
||||
public record ConsoleMessagePacket(String message) implements P2BPacket { }
|
||||
|
||||
public record KeepAliveResponsePacket() implements P2BPacket { }
|
||||
|
||||
public record DataSyncPacket(
|
||||
Messages messages,
|
||||
AutoLowerCase autoLowerCase,
|
||||
UnknownCommand unknownCommand
|
||||
) implements P2BPacket {
|
||||
|
||||
public record Messages(String prefix)
|
||||
implements Synchronizable {}
|
||||
|
||||
public record AutoLowerCase(boolean enabled)
|
||||
implements Synchronizable {}
|
||||
|
||||
public record UnknownCommand(boolean enabled, MultipleMessagesHelper message)
|
||||
implements Synchronizable {}
|
||||
|
||||
public record DataSyncPacket(Messages messages, AutoLowerCase autoLowerCase, UnknownCommand unknownCommand) implements P2BPacket {
|
||||
public record Messages(String prefix) implements Synchronizable { }
|
||||
public record AutoLowerCase(boolean enabled) implements Synchronizable { }
|
||||
public record UnknownCommand(boolean enabled, MultipleMessagesHelper message) implements Synchronizable { }
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static class Backend2Proxy {
|
||||
|
||||
private Backend2Proxy() { }
|
||||
|
||||
public record IdentityRequestPacket(UUID serverId) implements InitialPacket, B2PPacket { }
|
||||
|
||||
public record IdentityResponsePacket(UUID serverId) implements InitialPacket, B2PPacket { }
|
||||
|
||||
public record DataSyncReceivedPacket() implements B2PPacket { }
|
||||
|
||||
public record KeepAlivePacket() implements B2PPacket { }
|
||||
|
||||
public record AnnouncePlayerPermissionChanges(UUID playerId) implements B2PPacket { }
|
||||
public record AnnounceGroupPermissionChanges(Set<UUID> playerIds) implements B2PPacket { }
|
||||
}
|
||||
}
|
||||
@@ -1,88 +1,89 @@
|
||||
package de.rayzs.pat.utils;
|
||||
|
||||
import de.rayzs.pat.plugin.logger.Logger;
|
||||
|
||||
import java.util.*;
|
||||
import java.net.*;
|
||||
|
||||
public class ConnectionBuilder {
|
||||
|
||||
private String url = null, response = null;
|
||||
private List<String> responseList = new ArrayList<>();
|
||||
private Object[] parameters = null;
|
||||
private int timeout = -1;
|
||||
|
||||
public ConnectionBuilder setUrl(String url) {
|
||||
this.url = url;
|
||||
return this;
|
||||
}
|
||||
|
||||
public ConnectionBuilder setTimeout(int timeout) {
|
||||
this.timeout = timeout;
|
||||
return this;
|
||||
}
|
||||
|
||||
public ConnectionBuilder setProperties(Object... parameters) {
|
||||
this.parameters = parameters;
|
||||
return this;
|
||||
}
|
||||
|
||||
public ConnectionBuilder connect() {
|
||||
try {
|
||||
String rawUrl = url;
|
||||
URL url = new URL(rawUrl);
|
||||
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
|
||||
|
||||
if(timeout != -1) connection.setConnectTimeout(timeout);
|
||||
|
||||
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;
|
||||
continue;
|
||||
}
|
||||
|
||||
secondParam = parameter;
|
||||
|
||||
connection.setRequestProperty((String) firstParam, (String) secondParam);
|
||||
firstParam = null;
|
||||
}
|
||||
}
|
||||
|
||||
Scanner scanner = new Scanner(connection.getInputStream());
|
||||
StringBuilder builder = new StringBuilder("\\");
|
||||
String next;
|
||||
|
||||
while (scanner.hasNextLine()) {
|
||||
next = scanner.nextLine();
|
||||
responseList.add(next);
|
||||
builder.append(" ").append(next);
|
||||
}
|
||||
|
||||
response = builder.toString().replace("\\ ", "");
|
||||
|
||||
} catch (Exception exception) {
|
||||
Logger.warning("Could not reach plugin page! More information below. (" + exception + ")");
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public boolean hasResponse() {
|
||||
return response != null;
|
||||
}
|
||||
|
||||
public String getResponse() {
|
||||
return response;
|
||||
}
|
||||
|
||||
public List<String> getResponseList() {
|
||||
return responseList;
|
||||
}
|
||||
package de.rayzs.pat.utils;
|
||||
|
||||
import de.rayzs.pat.plugin.logger.Logger;
|
||||
|
||||
import java.util.*;
|
||||
import java.net.*;
|
||||
|
||||
public class ConnectionBuilder {
|
||||
|
||||
private String url = null, response = null;
|
||||
private List<String> responseList = new ArrayList<>();
|
||||
private Object[] parameters = null;
|
||||
private int timeout = -1;
|
||||
|
||||
public ConnectionBuilder setUrl(String url) {
|
||||
this.url = url;
|
||||
return this;
|
||||
}
|
||||
|
||||
public ConnectionBuilder setTimeout(int timeout) {
|
||||
this.timeout = timeout;
|
||||
return this;
|
||||
}
|
||||
|
||||
public ConnectionBuilder setProperties(Object... parameters) {
|
||||
this.parameters = parameters;
|
||||
return this;
|
||||
}
|
||||
|
||||
public ConnectionBuilder connect() {
|
||||
try {
|
||||
String rawUrl = url;
|
||||
URL url = new URL(rawUrl);
|
||||
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
|
||||
|
||||
if(timeout != -1) connection.setConnectTimeout(timeout);
|
||||
|
||||
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;
|
||||
continue;
|
||||
}
|
||||
|
||||
secondParam = parameter;
|
||||
|
||||
connection.setRequestProperty((String) firstParam, (String) secondParam);
|
||||
firstParam = null;
|
||||
}
|
||||
}
|
||||
|
||||
try (Scanner scanner = new Scanner(connection.getInputStream())) {
|
||||
final StringBuilder builder = new StringBuilder("\\");
|
||||
String next;
|
||||
|
||||
while (scanner.hasNextLine()) {
|
||||
next = scanner.nextLine();
|
||||
responseList.add(next);
|
||||
builder.append(" ").append(next);
|
||||
}
|
||||
|
||||
response = builder.toString().replace("\\ ", "");
|
||||
}
|
||||
|
||||
} catch (Exception exception) {
|
||||
Logger.warning("Could not reach plugin page! More information below. (" + exception + ")");
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public boolean hasResponse() {
|
||||
return response != null;
|
||||
}
|
||||
|
||||
public String getResponse() {
|
||||
return response;
|
||||
}
|
||||
|
||||
public List<String> getResponseList() {
|
||||
return responseList;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package de.rayzs.pat.utils;
|
||||
|
||||
import de.rayzs.pat.api.storage.Storage;
|
||||
import de.rayzs.pat.plugin.logger.Logger;
|
||||
import de.rayzs.pat.utils.permission.PermissionPlugin;
|
||||
import de.rayzs.pat.utils.permission.PermissionUtil;
|
||||
import de.rayzs.pat.utils.sender.CommandSender;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
public class LuckPermsWarning {
|
||||
|
||||
private static boolean ALREADY_ANNOUNCED = false;
|
||||
|
||||
private static final Set<String> LUCKPERMS_PREFIXES = Set.of(
|
||||
"luckperms", "lp",
|
||||
"luckpermsbungee", "lpb",
|
||||
"luckpermsvelocity", "lpv"
|
||||
);
|
||||
|
||||
private static final Set<String> LUCKPERMS_COMMANDS_SET = Set.of(
|
||||
"set", "unset",
|
||||
"settemp", "unsettemp"
|
||||
);
|
||||
|
||||
private static final String LUCKPERMS_WARNING = "&6&l[ProAntiTab] " +
|
||||
"&e&lHey! &eYou just set a ProAntiTab permission using a world/server as context. " +
|
||||
"However, PAT won't be able to detect this as of now. To fix this, please go to your &6&oplugins/ProAntiTab/config.yml&e and set the option &6&o'%s'&e to &a<rue&e. " +
|
||||
"Afterwards, just execute '&6/%s reload'&e to apply the changes.";
|
||||
|
||||
public static boolean shouldSendLuckPermsWarning(final CommandSender sender, final String command) {
|
||||
if (ALREADY_ANNOUNCED) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (Storage.getPermissionPlugin() != PermissionPlugin.LUCKPERMS) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!LUCKPERMS_PREFIXES.contains(StringUtils.getFirstArg(command))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!sender.isConsole() && !PermissionUtil.hasPermission(sender, "*", false) && !sender.isOperator()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
final String[] commandArgs = command.split(" ");
|
||||
|
||||
|
||||
final String fth = getStrAtIndex(commandArgs, 5);
|
||||
if (!StringUtils.startsWithIgnoreCase("proantitab.", fth)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
final String thd = getStrAtIndex(commandArgs, 3);
|
||||
if (!thd.equalsIgnoreCase("permission")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
final String fst = getStrAtIndex(commandArgs, 1);
|
||||
if (!fst.equalsIgnoreCase("group") && !fst.equalsIgnoreCase("user")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!LUCKPERMS_COMMANDS_SET.contains(getStrAtIndex(commandArgs, 4))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (int i = 6; i < commandArgs.length; i++) {
|
||||
final String context = getStrAtIndex(commandArgs, i);
|
||||
final boolean res = StringUtils.startsWithIgnoreCase("server=", context)
|
||||
|| StringUtils.startsWithIgnoreCase("world=", context);
|
||||
|
||||
if (res) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public static void sendAnnouncement(final CommandSender sender) {
|
||||
if (ALREADY_ANNOUNCED) return;
|
||||
|
||||
ALREADY_ANNOUNCED = true;
|
||||
|
||||
final String message = LUCKPERMS_WARNING.formatted(
|
||||
Reflection.isProxyServer() ? "update-groups-per-server" : "update-groups-per-world",
|
||||
Reflection.isProxyServer() ? "bpat" : "pat"
|
||||
);
|
||||
|
||||
if (!sender.isConsole()) Logger.info(message);
|
||||
sender.sendMessage(message);
|
||||
}
|
||||
|
||||
public static boolean alreadyAnnounced() {
|
||||
return ALREADY_ANNOUNCED;
|
||||
}
|
||||
|
||||
private static String getStrAtIndex(final String[] args, final int index) {
|
||||
if (index < 0 || index >= args.length) return "";
|
||||
return args[index];
|
||||
}
|
||||
}
|
||||
@@ -20,12 +20,12 @@ public class Reflection {
|
||||
if (doesClassExist("org.bukkit.Server")) {
|
||||
try {
|
||||
|
||||
software = doesClassExist("io.papermc.paper.threadedregions.RegionizedServer")
|
||||
software = doesClassExist("io.izzel.arclight.i18n.ArclightConfig")
|
||||
? Software.ARCLIGHT : doesClassExist("io.papermc.paper.threadedregions.RegionizedServer")
|
||||
? Software.FOLIA : doesClassExist("com.destroystokyo.paper.Metrics")
|
||||
? Software.PAPER : doesClassExist("org.spigotmc.SpigotConfig")
|
||||
? Software.SPIGOT : Software.BUKKIT;
|
||||
|
||||
|
||||
loadVersionName(serverObj);
|
||||
loadAges();
|
||||
|
||||
@@ -66,13 +66,26 @@ public class Reflection {
|
||||
return software == Software.FOLIA;
|
||||
}
|
||||
|
||||
public static boolean isCraftbukkit() {
|
||||
public static boolean isBukkit() {
|
||||
return software == Software.BUKKIT;
|
||||
}
|
||||
|
||||
public static boolean isSpigot() {
|
||||
return software == Software.SPIGOT;
|
||||
}
|
||||
|
||||
public static boolean isArclight() {
|
||||
return software == Software.ARCLIGHT;
|
||||
}
|
||||
|
||||
public static boolean isProxyServer() {
|
||||
return software.isProxySoftware();
|
||||
}
|
||||
|
||||
public static boolean isBungeeServer() {
|
||||
return software == Software.BUNGEECORD;
|
||||
}
|
||||
|
||||
public static boolean isVelocityServer() {
|
||||
return software == Software.VELOCITY;
|
||||
}
|
||||
@@ -422,6 +435,7 @@ public class Reflection {
|
||||
SPIGOT(false, false),
|
||||
PAPER(true, false),
|
||||
FOLIA(true, false),
|
||||
ARCLIGHT(false, false),
|
||||
|
||||
BUNGEECORD(false, true),
|
||||
WATERFALL(true, true),
|
||||
|
||||
@@ -1,9 +1,54 @@
|
||||
package de.rayzs.pat.utils;
|
||||
|
||||
import de.rayzs.pat.utils.message.MessageHelper;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public class StringUtils {
|
||||
|
||||
public static boolean startsWithIgnoreCase(String startingWithSource, String str) {
|
||||
final int strCutLength = startingWithSource.length();
|
||||
if (strCutLength >= str.length()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return startingWithSource.equalsIgnoreCase(str.substring(0, strCutLength));
|
||||
}
|
||||
|
||||
public static void centralize(List<String> lines) {
|
||||
final Map<Integer, Integer> sizes = new HashMap<>();
|
||||
final String centerVariable = "%center%";
|
||||
|
||||
int biggestSize = 0;
|
||||
for (int i = 0; i < lines.size(); i++) {
|
||||
String line = lines.get(i);
|
||||
|
||||
if (line.startsWith(centerVariable)) {
|
||||
line = MessageHelper.strip(line.substring(centerVariable.length()));
|
||||
|
||||
int size = line.length();
|
||||
sizes.put(i, size);
|
||||
biggestSize = Math.max(biggestSize, size);
|
||||
}
|
||||
}
|
||||
|
||||
if (sizes.isEmpty()) return;
|
||||
|
||||
for (int i = 0; i < lines.size(); i++) {
|
||||
final int size = sizes.getOrDefault(i, -1);
|
||||
|
||||
if (size != -1) {
|
||||
final int diff = biggestSize - size;
|
||||
final int left = diff / 2;
|
||||
final int right = diff - left;
|
||||
|
||||
lines.set(i,
|
||||
" ".repeat(left) + lines.get(i).substring(centerVariable.length()) + " ".repeat(right)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static String replaceFirst(String input, String trigger, String replacement) {
|
||||
|
||||
if (!input.contains(trigger)) {
|
||||
@@ -79,28 +124,33 @@ public class StringUtils {
|
||||
return input;
|
||||
}
|
||||
|
||||
public static String replace(List<String> input, String... replacements) {
|
||||
return replace(String.join("\n", input), replacements);
|
||||
}
|
||||
|
||||
public static String replace(String input, String... replacements) {
|
||||
final HashMap<String, String> REPLACEMENTS = new HashMap<>();
|
||||
if (replacements.length == 0) {
|
||||
return input;
|
||||
}
|
||||
|
||||
if (replacements.length > 0) {
|
||||
String firstReplacementInput = null, secondReplacementInput = null;
|
||||
|
||||
for (String replacement : replacements) {
|
||||
if (firstReplacementInput == null) firstReplacementInput = replacement;
|
||||
else secondReplacementInput = replacement;
|
||||
final HashMap<String, String> cache = new HashMap<>();
|
||||
String firstReplacementInput = null, secondReplacementInput = null;
|
||||
|
||||
if (firstReplacementInput != null && secondReplacementInput != null) {
|
||||
REPLACEMENTS.put(firstReplacementInput, secondReplacementInput);
|
||||
firstReplacementInput = null;
|
||||
secondReplacementInput = null;
|
||||
}
|
||||
for (String replacement : replacements) {
|
||||
if (firstReplacementInput == null) firstReplacementInput = replacement;
|
||||
else secondReplacementInput = replacement;
|
||||
|
||||
if (firstReplacementInput != null && secondReplacementInput != null) {
|
||||
cache.put(firstReplacementInput, secondReplacementInput);
|
||||
firstReplacementInput = null;
|
||||
secondReplacementInput = null;
|
||||
}
|
||||
}
|
||||
|
||||
String text = input;
|
||||
if (replacements.length > 0)
|
||||
for (Map.Entry<String, String> entry : REPLACEMENTS.entrySet())
|
||||
text = text.replace(entry.getKey(), entry.getValue());
|
||||
for (Map.Entry<String, String> entry : cache.entrySet())
|
||||
text = text.replace(entry.getKey(), entry.getValue());
|
||||
|
||||
return text;
|
||||
}
|
||||
@@ -109,15 +159,36 @@ public class StringUtils {
|
||||
return replaceTriggers(input, "", targets);
|
||||
}
|
||||
|
||||
public static int countMatches(Character character, String string) {
|
||||
public static int countMatches(Character searching, String source) {
|
||||
int count = 0;
|
||||
for (char c : string.toCharArray()) {
|
||||
if (character == c) count++;
|
||||
for (char c : source.toCharArray()) {
|
||||
if (searching == c) count++;
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
public static int countMatches(final String searching, final String source) {
|
||||
char[] sourceChars = source.toCharArray();
|
||||
|
||||
int matches = 0, success = 0;
|
||||
for (char character : sourceChars) {
|
||||
if (success == searching.length()) {
|
||||
matches++;
|
||||
success = 0;
|
||||
}
|
||||
|
||||
if (character != searching.charAt(success)) {
|
||||
success = 0;
|
||||
continue;
|
||||
}
|
||||
|
||||
success++;
|
||||
}
|
||||
|
||||
return matches;
|
||||
}
|
||||
|
||||
public static boolean isLowercased(String str) {
|
||||
if (str == null || str.isBlank())
|
||||
return false;
|
||||
@@ -156,15 +227,24 @@ public class StringUtils {
|
||||
return true;
|
||||
}
|
||||
|
||||
public static String getFirstArg(String input) {
|
||||
if (input.contains(" ")) {
|
||||
String[] split = input.split(" ");
|
||||
public static String lowercaseFirstArgument(String str) {
|
||||
final String[] split = str.split(" ");
|
||||
|
||||
if (split.length > 0)
|
||||
input = split[0];
|
||||
if (split.length <= 1) {
|
||||
return str.toLowerCase();
|
||||
}
|
||||
|
||||
return input;
|
||||
split[0] = split[0].toLowerCase();
|
||||
return String.join(" ", split);
|
||||
}
|
||||
|
||||
public static boolean equals(String str1, String str2, boolean caseSensitive) {
|
||||
return caseSensitive ? str1.equals(str2) : str1.equalsIgnoreCase(str2);
|
||||
}
|
||||
|
||||
public static String getFirstArg(String input) {
|
||||
final int index = input.indexOf(' ');
|
||||
return index == -1 ? input : input.substring(0, index);
|
||||
}
|
||||
|
||||
public static String getLineText(List<String> lines, int line) {
|
||||
|
||||
@@ -1,22 +1,22 @@
|
||||
package de.rayzs.pat.utils.configuration;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.io.File;
|
||||
|
||||
public interface ConfigurationBuilder {
|
||||
void reload();
|
||||
void save();
|
||||
String getFilePath();
|
||||
ConfigurationBuilder set(String path, String target, Object object);
|
||||
ConfigurationBuilder set(String target, Object object);
|
||||
ConfigurationBuilder setAndSave(String path, String target, Object object);
|
||||
ConfigurationBuilder setAndSave(String target, Object object);
|
||||
Object getOrSet(String path, String target, Object object);
|
||||
Object getOrSet(String target, Object object);
|
||||
Object get(String target);
|
||||
Object get(String path, String target);
|
||||
Collection<String> getKeys(boolean deep);
|
||||
Collection<String> getKeys(String section, boolean deep);
|
||||
File getFile();
|
||||
boolean loadDefault();
|
||||
}
|
||||
package de.rayzs.pat.utils.configuration;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.io.File;
|
||||
|
||||
public interface ConfigurationBuilder {
|
||||
void reload();
|
||||
void save();
|
||||
String getFilePath();
|
||||
ConfigurationBuilder set(String path, String target, Object object);
|
||||
ConfigurationBuilder set(String target, Object object);
|
||||
ConfigurationBuilder setAndSave(String path, String target, Object object);
|
||||
ConfigurationBuilder setAndSave(String target, Object object);
|
||||
Object getOrSet(String path, String target, Object object);
|
||||
Object getOrSet(String target, Object object);
|
||||
Object get(String target);
|
||||
Object get(String path, String target);
|
||||
Collection<String> getKeys(boolean deep);
|
||||
Collection<String> getKeys(String section, boolean deep);
|
||||
File getFile();
|
||||
boolean loadDefault();
|
||||
}
|
||||
@@ -1,87 +1,87 @@
|
||||
package de.rayzs.pat.utils.configuration;
|
||||
|
||||
import de.rayzs.pat.utils.configuration.impl.*;
|
||||
import de.rayzs.pat.utils.*;
|
||||
import java.util.HashMap;
|
||||
import java.net.*;
|
||||
import java.io.*;
|
||||
|
||||
public class Configurator {
|
||||
|
||||
private static final HashMap<String, ConfigurationBuilder> CONFIGURATION_HASHES = new HashMap<>();
|
||||
|
||||
private static final String FILE_PATH = "./plugins/ProAntiTab";
|
||||
|
||||
public static ConfigurationBuilder get(String fileName, String filePath) {
|
||||
String keyName = filePath + "/" + fileName;
|
||||
if(CONFIGURATION_HASHES.containsKey(keyName))
|
||||
return CONFIGURATION_HASHES.get(keyName);
|
||||
|
||||
ConfigurationBuilder configurationBuilder = Reflection.isProxyServer()
|
||||
? new ProxyConfigurationBuilder(fileName, filePath)
|
||||
: new BukkitConfigurationBuilder(fileName, filePath);
|
||||
CONFIGURATION_HASHES.put(keyName, configurationBuilder);
|
||||
return configurationBuilder;
|
||||
}
|
||||
|
||||
public static ConfigurationBuilder get(String fileName) {
|
||||
String keyName = FILE_PATH + "/" + fileName;
|
||||
if(CONFIGURATION_HASHES.containsKey(keyName))
|
||||
return CONFIGURATION_HASHES.get(keyName);
|
||||
|
||||
ConfigurationBuilder configurationBuilder = Reflection.isProxyServer()
|
||||
? new ProxyConfigurationBuilder(fileName)
|
||||
: new BukkitConfigurationBuilder(fileName);
|
||||
CONFIGURATION_HASHES.put(keyName, configurationBuilder);
|
||||
return configurationBuilder;
|
||||
}
|
||||
|
||||
public static InputStream getResource(String filename) {
|
||||
try {
|
||||
URL url = Configurator.class.getClassLoader().getResource(filename);
|
||||
if (url == null) {
|
||||
return null;
|
||||
} else {
|
||||
URLConnection connection = url.openConnection();
|
||||
connection.setUseCaches(false);
|
||||
return connection.getInputStream();
|
||||
}
|
||||
} catch (Throwable throwable) {
|
||||
throwable.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static void createResourcedFile(String resourcePath, String exportResourcePath, boolean replace) {
|
||||
if (resourcePath == null || resourcePath.isEmpty())
|
||||
return;
|
||||
|
||||
resourcePath = resourcePath.replace('\\', '/');
|
||||
InputStream inputStream = getResource(resourcePath);
|
||||
|
||||
if (inputStream == null)
|
||||
return;
|
||||
|
||||
File dataFolder = new File(FILE_PATH);
|
||||
File outputFile = new File(dataFolder, exportResourcePath);
|
||||
|
||||
if (!dataFolder.exists())
|
||||
dataFolder.mkdirs();
|
||||
|
||||
try {
|
||||
if (!outputFile.exists() || replace) {
|
||||
OutputStream outputStream = new FileOutputStream(outputFile);
|
||||
byte[] buffer = new byte[1024];
|
||||
int length;
|
||||
|
||||
while((length = inputStream.read(buffer)) > 0)
|
||||
outputStream.write(buffer, 0, length);
|
||||
|
||||
outputStream.close();
|
||||
inputStream.close();
|
||||
}
|
||||
} catch (Throwable throwable) {
|
||||
throwable.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
package de.rayzs.pat.utils.configuration;
|
||||
|
||||
import de.rayzs.pat.utils.configuration.impl.*;
|
||||
import de.rayzs.pat.utils.*;
|
||||
import java.util.HashMap;
|
||||
import java.net.*;
|
||||
import java.io.*;
|
||||
|
||||
public class Configurator {
|
||||
|
||||
private static final HashMap<String, ConfigurationBuilder> CONFIGURATION_HASHES = new HashMap<>();
|
||||
|
||||
private static final String FILE_PATH = "./plugins/ProAntiTab";
|
||||
|
||||
public static ConfigurationBuilder get(String fileName, String filePath) {
|
||||
String keyName = filePath + "/" + fileName;
|
||||
if(CONFIGURATION_HASHES.containsKey(keyName))
|
||||
return CONFIGURATION_HASHES.get(keyName);
|
||||
|
||||
ConfigurationBuilder configurationBuilder = Reflection.isProxyServer()
|
||||
? new ProxyConfigurationBuilder(fileName, filePath)
|
||||
: new BukkitConfigurationBuilder(fileName, filePath);
|
||||
CONFIGURATION_HASHES.put(keyName, configurationBuilder);
|
||||
return configurationBuilder;
|
||||
}
|
||||
|
||||
public static ConfigurationBuilder get(String fileName) {
|
||||
String keyName = FILE_PATH + "/" + fileName;
|
||||
if(CONFIGURATION_HASHES.containsKey(keyName))
|
||||
return CONFIGURATION_HASHES.get(keyName);
|
||||
|
||||
ConfigurationBuilder configurationBuilder = Reflection.isProxyServer()
|
||||
? new ProxyConfigurationBuilder(fileName)
|
||||
: new BukkitConfigurationBuilder(fileName);
|
||||
CONFIGURATION_HASHES.put(keyName, configurationBuilder);
|
||||
return configurationBuilder;
|
||||
}
|
||||
|
||||
public static InputStream getResource(String filename) {
|
||||
try {
|
||||
URL url = Configurator.class.getClassLoader().getResource(filename);
|
||||
if (url == null) {
|
||||
return null;
|
||||
} else {
|
||||
URLConnection connection = url.openConnection();
|
||||
connection.setUseCaches(false);
|
||||
return connection.getInputStream();
|
||||
}
|
||||
} catch (Throwable throwable) {
|
||||
throwable.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static void createResourcedFile(String resourcePath, String exportResourcePath, boolean replace) {
|
||||
if (resourcePath == null || resourcePath.isEmpty())
|
||||
return;
|
||||
|
||||
resourcePath = resourcePath.replace('\\', '/');
|
||||
InputStream inputStream = getResource(resourcePath);
|
||||
|
||||
if (inputStream == null)
|
||||
return;
|
||||
|
||||
File dataFolder = new File(FILE_PATH);
|
||||
File outputFile = new File(dataFolder, exportResourcePath);
|
||||
|
||||
if (!dataFolder.exists())
|
||||
dataFolder.mkdirs();
|
||||
|
||||
try {
|
||||
if (!outputFile.exists() || replace) {
|
||||
OutputStream outputStream = new FileOutputStream(outputFile);
|
||||
byte[] buffer = new byte[1024];
|
||||
int length;
|
||||
|
||||
while((length = inputStream.read(buffer)) > 0)
|
||||
outputStream.write(buffer, 0, length);
|
||||
|
||||
outputStream.close();
|
||||
inputStream.close();
|
||||
}
|
||||
} catch (Throwable throwable) {
|
||||
throwable.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,21 +6,26 @@ import java.util.*;
|
||||
|
||||
public class MultipleMessagesHelper implements Serializable {
|
||||
|
||||
private final ArrayList<String> lines;
|
||||
private final List<String> lines;
|
||||
|
||||
/** Construct a message set from authenticated wire data. */
|
||||
public MultipleMessagesHelper(List<String> lines) {
|
||||
this.lines = new ArrayList<>(lines);
|
||||
}
|
||||
|
||||
public MultipleMessagesHelper(ConfigStorage config, String path, List<String> input) {
|
||||
ConfigSectionHelper<ArrayList<String>> sectionHelper = new ConfigSectionHelper<>(config, path, input);
|
||||
final ConfigSectionHelper<ArrayList<String>> sectionHelper = new ConfigSectionHelper<>(config, path, input);
|
||||
final Object resultObj = sectionHelper.getOrSet();
|
||||
|
||||
if(!sectionHelper.exist()) {
|
||||
lines = new ArrayList<>(input);
|
||||
sectionHelper.set(lines);
|
||||
if (resultObj instanceof List list) {
|
||||
lines = (List<String>) list;
|
||||
return;
|
||||
}
|
||||
|
||||
lines = sectionHelper.get();
|
||||
lines = input;
|
||||
}
|
||||
|
||||
public ArrayList<String> getLines() {
|
||||
public List<String> getLines() {
|
||||
return lines;
|
||||
}
|
||||
}
|
||||
+146
-146
@@ -1,146 +1,146 @@
|
||||
package de.rayzs.pat.utils.configuration.impl;
|
||||
|
||||
import de.rayzs.pat.utils.configuration.ConfigurationBuilder;
|
||||
import de.rayzs.pat.utils.configuration.updater.ConfigUpdater;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import de.rayzs.pat.plugin.logger.Logger;
|
||||
import org.bukkit.ChatColor;
|
||||
import java.util.Collection;
|
||||
import java.io.File;
|
||||
|
||||
public class BukkitConfigurationBuilder implements ConfigurationBuilder {
|
||||
|
||||
private String fileName, filePath;
|
||||
private File file;
|
||||
private boolean loadDefault;
|
||||
private YamlConfiguration configuration;
|
||||
|
||||
public BukkitConfigurationBuilder(String fileName) {
|
||||
init(fileName);
|
||||
}
|
||||
|
||||
public BukkitConfigurationBuilder(String fileName, String filePath) {
|
||||
this.filePath = filePath;
|
||||
init(fileName);
|
||||
}
|
||||
|
||||
protected void init(String fileName) {
|
||||
this.fileName = fileName;
|
||||
this.file = new File((this.filePath == null) ? "./plugins/ProAntiTab" : this.filePath, fileName + ".yml");
|
||||
this.loadDefault = !this.file.exists();
|
||||
this.configuration = YamlConfiguration.loadConfiguration(this.file);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getFilePath() {
|
||||
return filePath;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void reload() {
|
||||
init(this.fileName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save() {
|
||||
try { this.configuration.save(this.file);
|
||||
} catch (Exception exception) {
|
||||
Logger.info("Could not save configuration file! [file=" + this.fileName + ", message=" + exception.getMessage() + "]");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigurationBuilder set(String path, String target, Object object) {
|
||||
this.configuration.set(((path != null) ? (path + ".") : "") + target, object instanceof String ? ((String) object).replace("§", "&") : object);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigurationBuilder set(String target, Object object) {
|
||||
set(null, target, object);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigurationBuilder setAndSave(String path, String target, Object object) {
|
||||
set(path, target, object);
|
||||
save();
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigurationBuilder setAndSave(String target, Object object) {
|
||||
set(target, object);
|
||||
save();
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getOrSet(String path, String target, Object object) {
|
||||
Object result = get(path, target);
|
||||
if (result != null)
|
||||
return result;
|
||||
|
||||
if (fileName.equals("config") && !ConfigUpdater.shouldAutoUpdate()) {
|
||||
ConfigUpdater.addMissingPart((!path.isBlank() ? path + "." : "") + target);
|
||||
return object;
|
||||
}
|
||||
|
||||
set(path, target, object);
|
||||
save();
|
||||
|
||||
return get(path, target);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getOrSet(String target, Object object) {
|
||||
Object result = get(target);
|
||||
if (result != null)
|
||||
return result;
|
||||
|
||||
if (fileName.equals("config") && !ConfigUpdater.shouldAutoUpdate()) {
|
||||
ConfigUpdater.addMissingPart(target);
|
||||
return object;
|
||||
}
|
||||
|
||||
set(target, object);
|
||||
save();
|
||||
|
||||
return get(target);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object get(String target) {
|
||||
return get(null, target);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object get(String path, String target) {
|
||||
Object object = this.configuration.get(((path != null) ? (path + ".") : "") + target);
|
||||
if (object instanceof String) {
|
||||
String objString = (String) object;
|
||||
return ChatColor.translateAlternateColorCodes('&', objString);
|
||||
}
|
||||
return object;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<String> getKeys(boolean deep) {
|
||||
return this.configuration.getKeys(deep);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<String> getKeys(String section, boolean deep) {
|
||||
return this.configuration.getConfigurationSection(section).getKeys(deep);
|
||||
}
|
||||
|
||||
@Override
|
||||
public File getFile() {
|
||||
return file;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean loadDefault() {
|
||||
return loadDefault;
|
||||
}
|
||||
}
|
||||
package de.rayzs.pat.utils.configuration.impl;
|
||||
|
||||
import de.rayzs.pat.utils.configuration.ConfigurationBuilder;
|
||||
import de.rayzs.pat.utils.configuration.updater.ConfigUpdater;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import de.rayzs.pat.plugin.logger.Logger;
|
||||
import org.bukkit.ChatColor;
|
||||
import java.util.Collection;
|
||||
import java.io.File;
|
||||
|
||||
public class BukkitConfigurationBuilder implements ConfigurationBuilder {
|
||||
|
||||
private String fileName, filePath;
|
||||
private File file;
|
||||
private boolean loadDefault;
|
||||
private YamlConfiguration configuration;
|
||||
|
||||
public BukkitConfigurationBuilder(String fileName) {
|
||||
init(fileName);
|
||||
}
|
||||
|
||||
public BukkitConfigurationBuilder(String fileName, String filePath) {
|
||||
this.filePath = filePath;
|
||||
init(fileName);
|
||||
}
|
||||
|
||||
protected void init(String fileName) {
|
||||
this.fileName = fileName;
|
||||
this.file = new File((this.filePath == null) ? "./plugins/ProAntiTab" : this.filePath, fileName + ".yml");
|
||||
this.loadDefault = !this.file.exists();
|
||||
this.configuration = YamlConfiguration.loadConfiguration(this.file);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getFilePath() {
|
||||
return filePath;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void reload() {
|
||||
init(this.fileName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save() {
|
||||
try { this.configuration.save(this.file);
|
||||
} catch (Exception exception) {
|
||||
Logger.info("Could not save configuration file! [file=" + this.fileName + ", message=" + exception.getMessage() + "]");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigurationBuilder set(String path, String target, Object object) {
|
||||
this.configuration.set(((path != null) ? (path + ".") : "") + target, object instanceof String ? ((String) object).replace("§", "&") : object);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigurationBuilder set(String target, Object object) {
|
||||
set(null, target, object);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigurationBuilder setAndSave(String path, String target, Object object) {
|
||||
set(path, target, object);
|
||||
save();
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigurationBuilder setAndSave(String target, Object object) {
|
||||
set(target, object);
|
||||
save();
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getOrSet(String path, String target, Object object) {
|
||||
Object result = get(path, target);
|
||||
if (result != null)
|
||||
return result;
|
||||
|
||||
if (fileName.equals("config") && !ConfigUpdater.shouldAutoUpdate()) {
|
||||
ConfigUpdater.addMissingPart((!path.isBlank() ? path + "." : "") + target);
|
||||
return object;
|
||||
}
|
||||
|
||||
set(path, target, object);
|
||||
save();
|
||||
|
||||
return get(path, target);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getOrSet(String target, Object object) {
|
||||
Object result = get(target);
|
||||
if (result != null)
|
||||
return result;
|
||||
|
||||
if (fileName.equals("config") && !ConfigUpdater.shouldAutoUpdate()) {
|
||||
ConfigUpdater.addMissingPart(target);
|
||||
return object;
|
||||
}
|
||||
|
||||
set(target, object);
|
||||
save();
|
||||
|
||||
return get(target);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object get(String target) {
|
||||
return get(null, target);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object get(String path, String target) {
|
||||
Object object = this.configuration.get(((path != null) ? (path + ".") : "") + target);
|
||||
if (object instanceof String) {
|
||||
String objString = (String) object;
|
||||
return ChatColor.translateAlternateColorCodes('&', objString);
|
||||
}
|
||||
return object;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<String> getKeys(boolean deep) {
|
||||
return this.configuration.getKeys(deep);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<String> getKeys(String section, boolean deep) {
|
||||
return this.configuration.getConfigurationSection(section).getKeys(deep);
|
||||
}
|
||||
|
||||
@Override
|
||||
public File getFile() {
|
||||
return file;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean loadDefault() {
|
||||
return loadDefault;
|
||||
}
|
||||
}
|
||||
+153
-153
@@ -1,153 +1,153 @@
|
||||
package de.rayzs.pat.utils.configuration.impl;
|
||||
|
||||
import de.rayzs.pat.utils.configuration.ConfigurationBuilder;
|
||||
import de.rayzs.pat.utils.configuration.updater.ConfigUpdater;
|
||||
import de.rayzs.pat.utils.configuration.yaml.*;
|
||||
import de.rayzs.pat.plugin.logger.Logger;
|
||||
import java.util.Collection;
|
||||
import java.io.File;
|
||||
|
||||
public class ProxyConfigurationBuilder implements ConfigurationBuilder {
|
||||
|
||||
private String fileName, filePath;
|
||||
private File file;
|
||||
private boolean loadDefault;
|
||||
private Configuration configuration;
|
||||
|
||||
public ProxyConfigurationBuilder(String fileName) {
|
||||
init(fileName);
|
||||
}
|
||||
|
||||
public ProxyConfigurationBuilder(String filePath, String fileName) {
|
||||
this.filePath = filePath;
|
||||
init(fileName);
|
||||
}
|
||||
|
||||
protected void init(String fileName) {
|
||||
filePath = filePath == null ? "./plugins/ProAntiTab" : filePath;
|
||||
File directory = new File(filePath);
|
||||
|
||||
this.fileName = fileName;
|
||||
|
||||
try {
|
||||
if(!directory.isDirectory()) directory.mkdirs();
|
||||
file = new File(filePath, fileName + ".yml");
|
||||
loadDefault = !file.exists();
|
||||
if(!file.exists()) file.createNewFile();
|
||||
configuration = ConfigurationProvider.getProvider(YamlConfiguration.class).load(file);
|
||||
} catch (Exception exception) { exception.printStackTrace(); }
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getFilePath() {
|
||||
return filePath;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void reload() {
|
||||
init(this.fileName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save() {
|
||||
try { ConfigurationProvider.getProvider(YamlConfiguration.class).save(configuration, file);
|
||||
} catch (Exception exception) {
|
||||
Logger.warning("Could not save configuration file! [file=" + fileName + ", message=" + exception.getMessage() + "]");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigurationBuilder set(String path, String target, Object object) {
|
||||
this.configuration.set(((path != null) ? (path + ".") : "") + target, object instanceof String ? ((String) object).replace("§", "&") : object);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigurationBuilder set(String target, Object object) {
|
||||
set(null, target, object);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigurationBuilder setAndSave(String path, String target, Object object) {
|
||||
set(path, target, object);
|
||||
save();
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigurationBuilder setAndSave(String target, Object object) {
|
||||
set(target, object);
|
||||
save();
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getOrSet(String path, String target, Object object) {
|
||||
Object result = get(path, target);
|
||||
if (result != null)
|
||||
return result;
|
||||
|
||||
if (fileName.equals("config") && !ConfigUpdater.shouldAutoUpdate()) {
|
||||
ConfigUpdater.addMissingPart((!path.isBlank() ? path + "." : "") + target);
|
||||
return object;
|
||||
}
|
||||
|
||||
set(path, target, object);
|
||||
save();
|
||||
|
||||
return get(path, target);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getOrSet(String target, Object object) {
|
||||
Object result = get(target);
|
||||
if (result != null)
|
||||
return result;
|
||||
|
||||
if (fileName.equals("config") && !ConfigUpdater.shouldAutoUpdate()) {
|
||||
ConfigUpdater.addMissingPart(target);
|
||||
return object;
|
||||
}
|
||||
|
||||
set(target, object);
|
||||
save();
|
||||
|
||||
return get(target);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object get(String target) {
|
||||
return get(null, target);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object get(String path, String target) {
|
||||
Object object = this.configuration.get(((path != null) ? (path + ".") : "") + target);
|
||||
if (object instanceof String) {
|
||||
String objString = (String) object;
|
||||
return objString.replace("&", "§");
|
||||
}
|
||||
return object;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<String> getKeys(boolean deep) {
|
||||
return this.configuration.getKeys();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<String> getKeys(String section, boolean deep) {
|
||||
return this.configuration.getSection(section).getKeys();
|
||||
}
|
||||
|
||||
@Override
|
||||
public File getFile() {
|
||||
return file;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean loadDefault() {
|
||||
return loadDefault;
|
||||
}
|
||||
}
|
||||
package de.rayzs.pat.utils.configuration.impl;
|
||||
|
||||
import de.rayzs.pat.utils.configuration.ConfigurationBuilder;
|
||||
import de.rayzs.pat.utils.configuration.updater.ConfigUpdater;
|
||||
import de.rayzs.pat.utils.configuration.yaml.*;
|
||||
import de.rayzs.pat.plugin.logger.Logger;
|
||||
import java.util.Collection;
|
||||
import java.io.File;
|
||||
|
||||
public class ProxyConfigurationBuilder implements ConfigurationBuilder {
|
||||
|
||||
private String fileName, filePath;
|
||||
private File file;
|
||||
private boolean loadDefault;
|
||||
private Configuration configuration;
|
||||
|
||||
public ProxyConfigurationBuilder(String fileName) {
|
||||
init(fileName);
|
||||
}
|
||||
|
||||
public ProxyConfigurationBuilder(String filePath, String fileName) {
|
||||
this.filePath = filePath;
|
||||
init(fileName);
|
||||
}
|
||||
|
||||
protected void init(String fileName) {
|
||||
filePath = filePath == null ? "./plugins/ProAntiTab" : filePath;
|
||||
File directory = new File(filePath);
|
||||
|
||||
this.fileName = fileName;
|
||||
|
||||
try {
|
||||
if(!directory.isDirectory()) directory.mkdirs();
|
||||
file = new File(filePath, fileName + ".yml");
|
||||
loadDefault = !file.exists();
|
||||
if(!file.exists()) file.createNewFile();
|
||||
configuration = ConfigurationProvider.getProvider(YamlConfiguration.class).load(file);
|
||||
} catch (Exception exception) { exception.printStackTrace(); }
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getFilePath() {
|
||||
return filePath;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void reload() {
|
||||
init(this.fileName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save() {
|
||||
try { ConfigurationProvider.getProvider(YamlConfiguration.class).save(configuration, file);
|
||||
} catch (Exception exception) {
|
||||
Logger.warning("Could not save configuration file! [file=" + fileName + ", message=" + exception.getMessage() + "]");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigurationBuilder set(String path, String target, Object object) {
|
||||
this.configuration.set(((path != null) ? (path + ".") : "") + target, object instanceof String ? ((String) object).replace("§", "&") : object);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigurationBuilder set(String target, Object object) {
|
||||
set(null, target, object);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigurationBuilder setAndSave(String path, String target, Object object) {
|
||||
set(path, target, object);
|
||||
save();
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigurationBuilder setAndSave(String target, Object object) {
|
||||
set(target, object);
|
||||
save();
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getOrSet(String path, String target, Object object) {
|
||||
Object result = get(path, target);
|
||||
if (result != null)
|
||||
return result;
|
||||
|
||||
if (fileName.equals("config") && !ConfigUpdater.shouldAutoUpdate()) {
|
||||
ConfigUpdater.addMissingPart((!path.isBlank() ? path + "." : "") + target);
|
||||
return object;
|
||||
}
|
||||
|
||||
set(path, target, object);
|
||||
save();
|
||||
|
||||
return get(path, target);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getOrSet(String target, Object object) {
|
||||
Object result = get(target);
|
||||
if (result != null)
|
||||
return result;
|
||||
|
||||
if (fileName.equals("config") && !ConfigUpdater.shouldAutoUpdate()) {
|
||||
ConfigUpdater.addMissingPart(target);
|
||||
return object;
|
||||
}
|
||||
|
||||
set(target, object);
|
||||
save();
|
||||
|
||||
return get(target);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object get(String target) {
|
||||
return get(null, target);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object get(String path, String target) {
|
||||
Object object = this.configuration.get(((path != null) ? (path + ".") : "") + target);
|
||||
if (object instanceof String) {
|
||||
String objString = (String) object;
|
||||
return objString.replace("&", "§");
|
||||
}
|
||||
return object;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<String> getKeys(boolean deep) {
|
||||
return this.configuration.getKeys();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<String> getKeys(String section, boolean deep) {
|
||||
return this.configuration.getSection(section).getKeys();
|
||||
}
|
||||
|
||||
@Override
|
||||
public File getFile() {
|
||||
return file;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean loadDefault() {
|
||||
return loadDefault;
|
||||
}
|
||||
}
|
||||
@@ -1,296 +1,296 @@
|
||||
package de.rayzs.pat.utils.configuration.yaml;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public final class Configuration {
|
||||
|
||||
/*
|
||||
Copyright (c) 2012, md_5. All rights reserved.
|
||||
Original code from Bungeecord source:
|
||||
https://github.com/SpigotMC/BungeeCord/blob/master/config/src/main/java/net/md_5/bungee/config/Configuration.java
|
||||
*/
|
||||
|
||||
private static final char SEPARATOR = '.';
|
||||
|
||||
final Map<String, Object> self;
|
||||
|
||||
private final Configuration defaults;
|
||||
|
||||
public Configuration() {
|
||||
this(null);
|
||||
}
|
||||
|
||||
public Configuration(Configuration defaults) {
|
||||
this(new LinkedHashMap<>(), defaults);
|
||||
}
|
||||
|
||||
Configuration(Map<?, ?> map, Configuration defaults) {
|
||||
this.self = new LinkedHashMap<>();
|
||||
this.defaults = defaults;
|
||||
for (Map.Entry<?, ?> entry : map.entrySet()) {
|
||||
String key = (entry.getKey() == null) ? "null" : entry.getKey().toString();
|
||||
if (entry.getValue() instanceof Map) {
|
||||
this.self.put(key, new Configuration((Map<?, ?>)entry.getValue(), (defaults == null) ? null : defaults.getSection(key)));
|
||||
continue;
|
||||
}
|
||||
this.self.put(key, entry.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
private Configuration getSectionFor(String path) {
|
||||
int index = path.indexOf('.');
|
||||
if (index == -1)
|
||||
return this;
|
||||
String root = path.substring(0, index);
|
||||
Object section = this.self.get(root);
|
||||
if (section == null) {
|
||||
section = new Configuration((this.defaults == null) ? null : this.defaults.getSection(root));
|
||||
this.self.put(root, section);
|
||||
}
|
||||
return (Configuration)section;
|
||||
}
|
||||
|
||||
private String getChild(String path) {
|
||||
int index = path.indexOf('.');
|
||||
return (index == -1) ? path : path.substring(index + 1);
|
||||
}
|
||||
|
||||
public <T> T get(String path, T def) {
|
||||
Object val;
|
||||
Configuration section = getSectionFor(path);
|
||||
if (section == this) {
|
||||
val = this.self.get(path);
|
||||
} else {
|
||||
val = section.get(getChild(path), def);
|
||||
}
|
||||
if (val == null && def instanceof Configuration)
|
||||
this.self.put(path, def);
|
||||
return (val != null) ? (T)val : def;
|
||||
}
|
||||
|
||||
public boolean contains(String path) {
|
||||
return (get(path, null) != null);
|
||||
}
|
||||
|
||||
public Object get(String path) {
|
||||
return get(path, getDefault(path));
|
||||
}
|
||||
|
||||
public Object getDefault(String path) {
|
||||
return (this.defaults == null) ? null : this.defaults.get(path);
|
||||
}
|
||||
|
||||
public void set(String path, Object value) {
|
||||
if (value instanceof Map)
|
||||
value = new Configuration((Map<?, ?>)value, (this.defaults == null) ? null : this.defaults.getSection(path));
|
||||
Configuration section = getSectionFor(path);
|
||||
if (section == this) {
|
||||
if (value == null) {
|
||||
this.self.remove(path);
|
||||
} else {
|
||||
this.self.put(path, value);
|
||||
}
|
||||
} else {
|
||||
section.set(getChild(path), value);
|
||||
}
|
||||
}
|
||||
|
||||
public Configuration getSection(String path) {
|
||||
Object def = getDefault(path);
|
||||
return (Configuration)get(path, (def instanceof Configuration) ? def : new Configuration((this.defaults == null) ? null : this.defaults.getSection(path)));
|
||||
}
|
||||
|
||||
public Collection<String> getKeys() {
|
||||
return new LinkedHashSet<>(this.self.keySet());
|
||||
}
|
||||
|
||||
public byte getByte(String path) {
|
||||
Object def = getDefault(path);
|
||||
return getByte(path, (def instanceof Number) ? ((Number)def).byteValue() : 0);
|
||||
}
|
||||
|
||||
public byte getByte(String path, byte def) {
|
||||
Object val = get(path, Byte.valueOf(def));
|
||||
return (val instanceof Number) ? ((Number)val).byteValue() : def;
|
||||
}
|
||||
|
||||
public List<Byte> getByteList(String path) {
|
||||
List<?> list = getList(path);
|
||||
List<Byte> result = new ArrayList<>();
|
||||
for (Object object : list) {
|
||||
if (object instanceof Number)
|
||||
result.add(Byte.valueOf(((Number)object).byteValue()));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public short getShort(String path) {
|
||||
Object def = getDefault(path);
|
||||
return getShort(path, (def instanceof Number) ? ((Number)def).shortValue() : 0);
|
||||
}
|
||||
|
||||
public short getShort(String path, short def) {
|
||||
Object val = get(path, Short.valueOf(def));
|
||||
return (val instanceof Number) ? ((Number)val).shortValue() : def;
|
||||
}
|
||||
|
||||
public List<Short> getShortList(String path) {
|
||||
List<?> list = getList(path);
|
||||
List<Short> result = new ArrayList<>();
|
||||
for (Object object : list) {
|
||||
if (object instanceof Number)
|
||||
result.add(Short.valueOf(((Number)object).shortValue()));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public int getInt(String path) {
|
||||
Object def = getDefault(path);
|
||||
return getInt(path, (def instanceof Number) ? ((Number)def).intValue() : 0);
|
||||
}
|
||||
|
||||
public int getInt(String path, int def) {
|
||||
Object val = get(path, Integer.valueOf(def));
|
||||
return (val instanceof Number) ? ((Number)val).intValue() : def;
|
||||
}
|
||||
|
||||
public List<Integer> getIntList(String path) {
|
||||
List<?> list = getList(path);
|
||||
List<Integer> result = new ArrayList<>();
|
||||
for (Object object : list) {
|
||||
if (object instanceof Number)
|
||||
result.add(Integer.valueOf(((Number)object).intValue()));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public long getLong(String path) {
|
||||
Object def = getDefault(path);
|
||||
return getLong(path, (def instanceof Number) ? ((Number)def).longValue() : 0L);
|
||||
}
|
||||
|
||||
public long getLong(String path, long def) {
|
||||
Object val = get(path, Long.valueOf(def));
|
||||
return (val instanceof Number) ? ((Number)val).longValue() : def;
|
||||
}
|
||||
|
||||
public List<Long> getLongList(String path) {
|
||||
List<?> list = getList(path);
|
||||
List<Long> result = new ArrayList<>();
|
||||
for (Object object : list) {
|
||||
if (object instanceof Number)
|
||||
result.add(Long.valueOf(((Number)object).longValue()));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public float getFloat(String path) {
|
||||
Object def = getDefault(path);
|
||||
return getFloat(path, (def instanceof Number) ? ((Number)def).floatValue() : 0.0F);
|
||||
}
|
||||
|
||||
public float getFloat(String path, float def) {
|
||||
Object val = get(path, Float.valueOf(def));
|
||||
return (val instanceof Number) ? ((Number)val).floatValue() : def;
|
||||
}
|
||||
|
||||
public List<Float> getFloatList(String path) {
|
||||
List<?> list = getList(path);
|
||||
List<Float> result = new ArrayList<>();
|
||||
for (Object object : list) {
|
||||
if (object instanceof Number)
|
||||
result.add(Float.valueOf(((Number)object).floatValue()));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public double getDouble(String path) {
|
||||
Object def = getDefault(path);
|
||||
return getDouble(path, (def instanceof Number) ? ((Number)def).doubleValue() : 0.0D);
|
||||
}
|
||||
|
||||
public double getDouble(String path, double def) {
|
||||
Object val = get(path, Double.valueOf(def));
|
||||
return (val instanceof Number) ? ((Number)val).doubleValue() : def;
|
||||
}
|
||||
|
||||
public List<Double> getDoubleList(String path) {
|
||||
List<?> list = getList(path);
|
||||
List<Double> result = new ArrayList<>();
|
||||
for (Object object : list) {
|
||||
if (object instanceof Number)
|
||||
result.add(Double.valueOf(((Number)object).doubleValue()));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public boolean getBoolean(String path) {
|
||||
Object def = getDefault(path);
|
||||
return getBoolean(path, (def instanceof Boolean) ? ((Boolean)def).booleanValue() : false);
|
||||
}
|
||||
|
||||
public boolean getBoolean(String path, boolean def) {
|
||||
Object val = get(path, Boolean.valueOf(def));
|
||||
return (val instanceof Boolean) ? ((Boolean)val).booleanValue() : def;
|
||||
}
|
||||
|
||||
public List<Boolean> getBooleanList(String path) {
|
||||
List<?> list = getList(path);
|
||||
List<Boolean> result = new ArrayList<>();
|
||||
for (Object object : list) {
|
||||
if (object instanceof Boolean)
|
||||
result.add((Boolean)object);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public char getChar(String path) {
|
||||
Object def = getDefault(path);
|
||||
return getChar(path, (def instanceof Character) ? ((Character)def).charValue() : Character.MIN_VALUE);
|
||||
}
|
||||
|
||||
public char getChar(String path, char def) {
|
||||
Object val = get(path, Character.valueOf(def));
|
||||
return (val instanceof Character) ? ((Character)val).charValue() : def;
|
||||
}
|
||||
|
||||
public List<Character> getCharList(String path) {
|
||||
List<?> list = getList(path);
|
||||
List<Character> result = new ArrayList<>();
|
||||
for (Object object : list) {
|
||||
if (object instanceof Character)
|
||||
result.add((Character)object);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public String getString(String path) {
|
||||
Object def = getDefault(path);
|
||||
return getString(path, (def instanceof String) ? (String)def : "");
|
||||
}
|
||||
|
||||
public String getString(String path, String def) {
|
||||
Object val = get(path, def);
|
||||
return (val instanceof String) ? (String)val : def;
|
||||
}
|
||||
|
||||
public List<String> getStringList(String path) {
|
||||
List<?> list = getList(path);
|
||||
List<String> result = new ArrayList<>();
|
||||
for (Object object : list) {
|
||||
if (object instanceof String)
|
||||
result.add((String)object);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public List<?> getList(String path) {
|
||||
Object def = getDefault(path);
|
||||
return getList(path, (def instanceof List) ? (List)def : Collections.EMPTY_LIST);
|
||||
}
|
||||
|
||||
public List<?> getList(String path, List<?> def) {
|
||||
Object val = (Object)get(path, def);
|
||||
return (val instanceof List) ? (List)val : def;
|
||||
}
|
||||
}
|
||||
package de.rayzs.pat.utils.configuration.yaml;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public final class Configuration {
|
||||
|
||||
/*
|
||||
Copyright (c) 2012, md_5. All rights reserved.
|
||||
Original code from Bungeecord source:
|
||||
https://github.com/SpigotMC/BungeeCord/blob/master/config/src/main/java/net/md_5/bungee/config/Configuration.java
|
||||
*/
|
||||
|
||||
private static final char SEPARATOR = '.';
|
||||
|
||||
final Map<String, Object> self;
|
||||
|
||||
private final Configuration defaults;
|
||||
|
||||
public Configuration() {
|
||||
this(null);
|
||||
}
|
||||
|
||||
public Configuration(Configuration defaults) {
|
||||
this(new LinkedHashMap<>(), defaults);
|
||||
}
|
||||
|
||||
Configuration(Map<?, ?> map, Configuration defaults) {
|
||||
this.self = new LinkedHashMap<>();
|
||||
this.defaults = defaults;
|
||||
for (Map.Entry<?, ?> entry : map.entrySet()) {
|
||||
String key = (entry.getKey() == null) ? "null" : entry.getKey().toString();
|
||||
if (entry.getValue() instanceof Map) {
|
||||
this.self.put(key, new Configuration((Map<?, ?>)entry.getValue(), (defaults == null) ? null : defaults.getSection(key)));
|
||||
continue;
|
||||
}
|
||||
this.self.put(key, entry.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
private Configuration getSectionFor(String path) {
|
||||
int index = path.indexOf('.');
|
||||
if (index == -1)
|
||||
return this;
|
||||
String root = path.substring(0, index);
|
||||
Object section = this.self.get(root);
|
||||
if (section == null) {
|
||||
section = new Configuration((this.defaults == null) ? null : this.defaults.getSection(root));
|
||||
this.self.put(root, section);
|
||||
}
|
||||
return (Configuration)section;
|
||||
}
|
||||
|
||||
private String getChild(String path) {
|
||||
int index = path.indexOf('.');
|
||||
return (index == -1) ? path : path.substring(index + 1);
|
||||
}
|
||||
|
||||
public <T> T get(String path, T def) {
|
||||
Object val;
|
||||
Configuration section = getSectionFor(path);
|
||||
if (section == this) {
|
||||
val = this.self.get(path);
|
||||
} else {
|
||||
val = section.get(getChild(path), def);
|
||||
}
|
||||
if (val == null && def instanceof Configuration)
|
||||
this.self.put(path, def);
|
||||
return (val != null) ? (T)val : def;
|
||||
}
|
||||
|
||||
public boolean contains(String path) {
|
||||
return (get(path, null) != null);
|
||||
}
|
||||
|
||||
public Object get(String path) {
|
||||
return get(path, getDefault(path));
|
||||
}
|
||||
|
||||
public Object getDefault(String path) {
|
||||
return (this.defaults == null) ? null : this.defaults.get(path);
|
||||
}
|
||||
|
||||
public void set(String path, Object value) {
|
||||
if (value instanceof Map)
|
||||
value = new Configuration((Map<?, ?>)value, (this.defaults == null) ? null : this.defaults.getSection(path));
|
||||
Configuration section = getSectionFor(path);
|
||||
if (section == this) {
|
||||
if (value == null) {
|
||||
this.self.remove(path);
|
||||
} else {
|
||||
this.self.put(path, value);
|
||||
}
|
||||
} else {
|
||||
section.set(getChild(path), value);
|
||||
}
|
||||
}
|
||||
|
||||
public Configuration getSection(String path) {
|
||||
Object def = getDefault(path);
|
||||
return (Configuration)get(path, (def instanceof Configuration) ? def : new Configuration((this.defaults == null) ? null : this.defaults.getSection(path)));
|
||||
}
|
||||
|
||||
public Collection<String> getKeys() {
|
||||
return new LinkedHashSet<>(this.self.keySet());
|
||||
}
|
||||
|
||||
public byte getByte(String path) {
|
||||
Object def = getDefault(path);
|
||||
return getByte(path, (def instanceof Number) ? ((Number)def).byteValue() : 0);
|
||||
}
|
||||
|
||||
public byte getByte(String path, byte def) {
|
||||
Object val = get(path, Byte.valueOf(def));
|
||||
return (val instanceof Number) ? ((Number)val).byteValue() : def;
|
||||
}
|
||||
|
||||
public List<Byte> getByteList(String path) {
|
||||
List<?> list = getList(path);
|
||||
List<Byte> result = new ArrayList<>();
|
||||
for (Object object : list) {
|
||||
if (object instanceof Number)
|
||||
result.add(Byte.valueOf(((Number)object).byteValue()));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public short getShort(String path) {
|
||||
Object def = getDefault(path);
|
||||
return getShort(path, (def instanceof Number) ? ((Number)def).shortValue() : 0);
|
||||
}
|
||||
|
||||
public short getShort(String path, short def) {
|
||||
Object val = get(path, Short.valueOf(def));
|
||||
return (val instanceof Number) ? ((Number)val).shortValue() : def;
|
||||
}
|
||||
|
||||
public List<Short> getShortList(String path) {
|
||||
List<?> list = getList(path);
|
||||
List<Short> result = new ArrayList<>();
|
||||
for (Object object : list) {
|
||||
if (object instanceof Number)
|
||||
result.add(Short.valueOf(((Number)object).shortValue()));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public int getInt(String path) {
|
||||
Object def = getDefault(path);
|
||||
return getInt(path, (def instanceof Number) ? ((Number)def).intValue() : 0);
|
||||
}
|
||||
|
||||
public int getInt(String path, int def) {
|
||||
Object val = get(path, Integer.valueOf(def));
|
||||
return (val instanceof Number) ? ((Number)val).intValue() : def;
|
||||
}
|
||||
|
||||
public List<Integer> getIntList(String path) {
|
||||
List<?> list = getList(path);
|
||||
List<Integer> result = new ArrayList<>();
|
||||
for (Object object : list) {
|
||||
if (object instanceof Number)
|
||||
result.add(Integer.valueOf(((Number)object).intValue()));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public long getLong(String path) {
|
||||
Object def = getDefault(path);
|
||||
return getLong(path, (def instanceof Number) ? ((Number)def).longValue() : 0L);
|
||||
}
|
||||
|
||||
public long getLong(String path, long def) {
|
||||
Object val = get(path, Long.valueOf(def));
|
||||
return (val instanceof Number) ? ((Number)val).longValue() : def;
|
||||
}
|
||||
|
||||
public List<Long> getLongList(String path) {
|
||||
List<?> list = getList(path);
|
||||
List<Long> result = new ArrayList<>();
|
||||
for (Object object : list) {
|
||||
if (object instanceof Number)
|
||||
result.add(Long.valueOf(((Number)object).longValue()));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public float getFloat(String path) {
|
||||
Object def = getDefault(path);
|
||||
return getFloat(path, (def instanceof Number) ? ((Number)def).floatValue() : 0.0F);
|
||||
}
|
||||
|
||||
public float getFloat(String path, float def) {
|
||||
Object val = get(path, Float.valueOf(def));
|
||||
return (val instanceof Number) ? ((Number)val).floatValue() : def;
|
||||
}
|
||||
|
||||
public List<Float> getFloatList(String path) {
|
||||
List<?> list = getList(path);
|
||||
List<Float> result = new ArrayList<>();
|
||||
for (Object object : list) {
|
||||
if (object instanceof Number)
|
||||
result.add(Float.valueOf(((Number)object).floatValue()));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public double getDouble(String path) {
|
||||
Object def = getDefault(path);
|
||||
return getDouble(path, (def instanceof Number) ? ((Number)def).doubleValue() : 0.0D);
|
||||
}
|
||||
|
||||
public double getDouble(String path, double def) {
|
||||
Object val = get(path, Double.valueOf(def));
|
||||
return (val instanceof Number) ? ((Number)val).doubleValue() : def;
|
||||
}
|
||||
|
||||
public List<Double> getDoubleList(String path) {
|
||||
List<?> list = getList(path);
|
||||
List<Double> result = new ArrayList<>();
|
||||
for (Object object : list) {
|
||||
if (object instanceof Number)
|
||||
result.add(Double.valueOf(((Number)object).doubleValue()));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public boolean getBoolean(String path) {
|
||||
Object def = getDefault(path);
|
||||
return getBoolean(path, (def instanceof Boolean) ? ((Boolean)def).booleanValue() : false);
|
||||
}
|
||||
|
||||
public boolean getBoolean(String path, boolean def) {
|
||||
Object val = get(path, Boolean.valueOf(def));
|
||||
return (val instanceof Boolean) ? ((Boolean)val).booleanValue() : def;
|
||||
}
|
||||
|
||||
public List<Boolean> getBooleanList(String path) {
|
||||
List<?> list = getList(path);
|
||||
List<Boolean> result = new ArrayList<>();
|
||||
for (Object object : list) {
|
||||
if (object instanceof Boolean)
|
||||
result.add((Boolean)object);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public char getChar(String path) {
|
||||
Object def = getDefault(path);
|
||||
return getChar(path, (def instanceof Character) ? ((Character)def).charValue() : Character.MIN_VALUE);
|
||||
}
|
||||
|
||||
public char getChar(String path, char def) {
|
||||
Object val = get(path, Character.valueOf(def));
|
||||
return (val instanceof Character) ? ((Character)val).charValue() : def;
|
||||
}
|
||||
|
||||
public List<Character> getCharList(String path) {
|
||||
List<?> list = getList(path);
|
||||
List<Character> result = new ArrayList<>();
|
||||
for (Object object : list) {
|
||||
if (object instanceof Character)
|
||||
result.add((Character)object);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public String getString(String path) {
|
||||
Object def = getDefault(path);
|
||||
return getString(path, (def instanceof String) ? (String)def : "");
|
||||
}
|
||||
|
||||
public String getString(String path, String def) {
|
||||
Object val = get(path, def);
|
||||
return (val instanceof String) ? (String)val : def;
|
||||
}
|
||||
|
||||
public List<String> getStringList(String path) {
|
||||
List<?> list = getList(path);
|
||||
List<String> result = new ArrayList<>();
|
||||
for (Object object : list) {
|
||||
if (object instanceof String)
|
||||
result.add((String)object);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public List<?> getList(String path) {
|
||||
Object def = getDefault(path);
|
||||
return getList(path, (def instanceof List) ? (List)def : Collections.EMPTY_LIST);
|
||||
}
|
||||
|
||||
public List<?> getList(String path, List<?> def) {
|
||||
Object val = (Object)get(path, def);
|
||||
return (val instanceof List) ? (List)val : def;
|
||||
}
|
||||
}
|
||||
@@ -1,48 +1,48 @@
|
||||
package de.rayzs.pat.utils.configuration.yaml;
|
||||
|
||||
import java.util.*;
|
||||
import java.io.*;
|
||||
|
||||
public abstract class ConfigurationProvider {
|
||||
|
||||
/*
|
||||
Copyright (c) 2012, md_5. All rights reserved.
|
||||
Original code from Bungeecord source:
|
||||
https://github.com/SpigotMC/BungeeCord/blob/master/config/src/main/java/net/md_5/bungee/config/ConfigurationProvider.java
|
||||
*/
|
||||
|
||||
private static final Map<Class<? extends ConfigurationProvider>, ConfigurationProvider> providers = new HashMap<>();
|
||||
|
||||
static {
|
||||
try {
|
||||
providers.put(YamlConfiguration.class, new YamlConfiguration());
|
||||
} catch (NoClassDefFoundError noClassDefFoundError) {}
|
||||
try {
|
||||
providers.put(JsonConfiguration.class, new JsonConfiguration());
|
||||
} catch (NoClassDefFoundError noClassDefFoundError) {}
|
||||
}
|
||||
|
||||
public abstract Configuration load(String paramString, Configuration paramConfiguration);
|
||||
|
||||
public abstract Configuration load(String paramString);
|
||||
|
||||
public abstract Configuration load(InputStream paramInputStream, Configuration paramConfiguration);
|
||||
|
||||
public abstract Configuration load(InputStream paramInputStream);
|
||||
|
||||
public abstract Configuration load(Reader paramReader, Configuration paramConfiguration);
|
||||
|
||||
public abstract Configuration load(Reader paramReader);
|
||||
|
||||
public abstract Configuration load(File paramFile, Configuration paramConfiguration) throws IOException;
|
||||
|
||||
public abstract Configuration load(File paramFile) throws IOException;
|
||||
|
||||
public abstract void save(Configuration paramConfiguration, Writer paramWriter);
|
||||
|
||||
public abstract void save(Configuration paramConfiguration, File paramFile) throws IOException;
|
||||
|
||||
public static ConfigurationProvider getProvider(Class<? extends ConfigurationProvider> provider) {
|
||||
return providers.get(provider);
|
||||
}
|
||||
}
|
||||
package de.rayzs.pat.utils.configuration.yaml;
|
||||
|
||||
import java.util.*;
|
||||
import java.io.*;
|
||||
|
||||
public abstract class ConfigurationProvider {
|
||||
|
||||
/*
|
||||
Copyright (c) 2012, md_5. All rights reserved.
|
||||
Original code from Bungeecord source:
|
||||
https://github.com/SpigotMC/BungeeCord/blob/master/config/src/main/java/net/md_5/bungee/config/ConfigurationProvider.java
|
||||
*/
|
||||
|
||||
private static final Map<Class<? extends ConfigurationProvider>, ConfigurationProvider> providers = new HashMap<>();
|
||||
|
||||
static {
|
||||
try {
|
||||
providers.put(YamlConfiguration.class, new YamlConfiguration());
|
||||
} catch (NoClassDefFoundError noClassDefFoundError) {}
|
||||
try {
|
||||
providers.put(JsonConfiguration.class, new JsonConfiguration());
|
||||
} catch (NoClassDefFoundError noClassDefFoundError) {}
|
||||
}
|
||||
|
||||
public abstract Configuration load(String paramString, Configuration paramConfiguration);
|
||||
|
||||
public abstract Configuration load(String paramString);
|
||||
|
||||
public abstract Configuration load(InputStream paramInputStream, Configuration paramConfiguration);
|
||||
|
||||
public abstract Configuration load(InputStream paramInputStream);
|
||||
|
||||
public abstract Configuration load(Reader paramReader, Configuration paramConfiguration);
|
||||
|
||||
public abstract Configuration load(Reader paramReader);
|
||||
|
||||
public abstract Configuration load(File paramFile, Configuration paramConfiguration) throws IOException;
|
||||
|
||||
public abstract Configuration load(File paramFile) throws IOException;
|
||||
|
||||
public abstract void save(Configuration paramConfiguration, Writer paramWriter);
|
||||
|
||||
public abstract void save(Configuration paramConfiguration, File paramFile) throws IOException;
|
||||
|
||||
public static ConfigurationProvider getProvider(Class<? extends ConfigurationProvider> provider) {
|
||||
return providers.get(provider);
|
||||
}
|
||||
}
|
||||
@@ -1,72 +1,72 @@
|
||||
package de.rayzs.pat.utils.configuration.yaml;
|
||||
|
||||
import com.google.common.base.Charsets;
|
||||
import java.lang.reflect.Type;
|
||||
import com.google.gson.*;
|
||||
import java.util.*;
|
||||
import java.io.*;
|
||||
|
||||
public class JsonConfiguration extends ConfigurationProvider {
|
||||
|
||||
/*
|
||||
Copyright (c) 2012, md_5. All rights reserved.
|
||||
Original code from Bungeecord source:
|
||||
https://github.com/SpigotMC/BungeeCord/blob/master/config/src/main/java/net/md_5/bungee/config/JsonConfiguration.java
|
||||
*/
|
||||
|
||||
private final Gson json = (new GsonBuilder()).serializeNulls().setPrettyPrinting().registerTypeAdapter(Configuration.class, new JsonSerializer<Configuration>() {
|
||||
public JsonElement serialize(Configuration src, Type typeOfSrc, JsonSerializationContext context) {
|
||||
return context.serialize(src.self);
|
||||
}
|
||||
}).create();
|
||||
|
||||
public void save(Configuration config, File file) throws IOException {
|
||||
try (Writer writer = new OutputStreamWriter(new FileOutputStream(file), Charsets.UTF_8)) {
|
||||
save(config, writer);
|
||||
}
|
||||
}
|
||||
|
||||
public void save(Configuration config, Writer writer) {
|
||||
this.json.toJson(config.self, writer);
|
||||
}
|
||||
|
||||
public Configuration load(File file) throws IOException {
|
||||
return load(file, (Configuration)null);
|
||||
}
|
||||
|
||||
public Configuration load(File file, Configuration defaults) throws IOException {
|
||||
try (FileInputStream is = new FileInputStream(file)) {
|
||||
return load(is, defaults);
|
||||
}
|
||||
}
|
||||
|
||||
public Configuration load(Reader reader) {
|
||||
return load(reader, (Configuration)null);
|
||||
}
|
||||
|
||||
public Configuration load(Reader reader, Configuration defaults) {
|
||||
Map<String, Object> map = (Map<String, Object>)this.json.fromJson(reader, LinkedHashMap.class);
|
||||
if (map == null)
|
||||
map = new LinkedHashMap<>();
|
||||
return new Configuration(map, defaults);
|
||||
}
|
||||
|
||||
public Configuration load(InputStream is) {
|
||||
return load(is, (Configuration)null);
|
||||
}
|
||||
|
||||
public Configuration load(InputStream is, Configuration defaults) {
|
||||
return load(new InputStreamReader(is, Charsets.UTF_8), defaults);
|
||||
}
|
||||
|
||||
public Configuration load(String string) {
|
||||
return load(string, (Configuration)null);
|
||||
}
|
||||
|
||||
public Configuration load(String string, Configuration defaults) {
|
||||
Map<String, Object> map = (Map<String, Object>)this.json.fromJson(string, LinkedHashMap.class);
|
||||
if (map == null)
|
||||
map = new LinkedHashMap<>();
|
||||
return new Configuration(map, defaults);
|
||||
}
|
||||
}
|
||||
package de.rayzs.pat.utils.configuration.yaml;
|
||||
|
||||
import com.google.common.base.Charsets;
|
||||
import java.lang.reflect.Type;
|
||||
import com.google.gson.*;
|
||||
import java.util.*;
|
||||
import java.io.*;
|
||||
|
||||
public class JsonConfiguration extends ConfigurationProvider {
|
||||
|
||||
/*
|
||||
Copyright (c) 2012, md_5. All rights reserved.
|
||||
Original code from Bungeecord source:
|
||||
https://github.com/SpigotMC/BungeeCord/blob/master/config/src/main/java/net/md_5/bungee/config/JsonConfiguration.java
|
||||
*/
|
||||
|
||||
private final Gson json = (new GsonBuilder()).serializeNulls().setPrettyPrinting().registerTypeAdapter(Configuration.class, new JsonSerializer<Configuration>() {
|
||||
public JsonElement serialize(Configuration src, Type typeOfSrc, JsonSerializationContext context) {
|
||||
return context.serialize(src.self);
|
||||
}
|
||||
}).create();
|
||||
|
||||
public void save(Configuration config, File file) throws IOException {
|
||||
try (Writer writer = new OutputStreamWriter(new FileOutputStream(file), Charsets.UTF_8)) {
|
||||
save(config, writer);
|
||||
}
|
||||
}
|
||||
|
||||
public void save(Configuration config, Writer writer) {
|
||||
this.json.toJson(config.self, writer);
|
||||
}
|
||||
|
||||
public Configuration load(File file) throws IOException {
|
||||
return load(file, (Configuration)null);
|
||||
}
|
||||
|
||||
public Configuration load(File file, Configuration defaults) throws IOException {
|
||||
try (FileInputStream is = new FileInputStream(file)) {
|
||||
return load(is, defaults);
|
||||
}
|
||||
}
|
||||
|
||||
public Configuration load(Reader reader) {
|
||||
return load(reader, (Configuration)null);
|
||||
}
|
||||
|
||||
public Configuration load(Reader reader, Configuration defaults) {
|
||||
Map<String, Object> map = (Map<String, Object>)this.json.fromJson(reader, LinkedHashMap.class);
|
||||
if (map == null)
|
||||
map = new LinkedHashMap<>();
|
||||
return new Configuration(map, defaults);
|
||||
}
|
||||
|
||||
public Configuration load(InputStream is) {
|
||||
return load(is, (Configuration)null);
|
||||
}
|
||||
|
||||
public Configuration load(InputStream is, Configuration defaults) {
|
||||
return load(new InputStreamReader(is, Charsets.UTF_8), defaults);
|
||||
}
|
||||
|
||||
public Configuration load(String string) {
|
||||
return load(string, (Configuration)null);
|
||||
}
|
||||
|
||||
public Configuration load(String string, Configuration defaults) {
|
||||
Map<String, Object> map = (Map<String, Object>)this.json.fromJson(string, LinkedHashMap.class);
|
||||
if (map == null)
|
||||
map = new LinkedHashMap<>();
|
||||
return new Configuration(map, defaults);
|
||||
}
|
||||
}
|
||||
@@ -1,129 +1,129 @@
|
||||
package de.rayzs.pat.utils.configuration.yaml;
|
||||
|
||||
import org.yaml.snakeyaml.constructor.Constructor;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import org.yaml.snakeyaml.LoaderOptions;
|
||||
import org.yaml.snakeyaml.representer.*;
|
||||
import org.yaml.snakeyaml.nodes.Node;
|
||||
import org.yaml.snakeyaml.*;
|
||||
import java.util.*;
|
||||
import java.io.*;
|
||||
|
||||
public class YamlConfiguration extends ConfigurationProvider {
|
||||
|
||||
/*
|
||||
Copyright (c) 2012, md_5. All rights reserved.
|
||||
Original code from Bungeecord source:
|
||||
https://github.com/SpigotMC/BungeeCord/blob/master/config/src/main/java/net/md_5/bungee/config/YamlConfiguration.java
|
||||
*/
|
||||
|
||||
private final ThreadLocal<Yaml> yaml = new ThreadLocal<Yaml>()
|
||||
{
|
||||
@Override
|
||||
protected Yaml initialValue()
|
||||
{
|
||||
DumperOptions options = new DumperOptions();
|
||||
options.setDefaultFlowStyle( DumperOptions.FlowStyle.BLOCK );
|
||||
|
||||
Representer representer = new Representer( options )
|
||||
{
|
||||
{
|
||||
representers.put( Configuration.class, new Represent()
|
||||
{
|
||||
@Override
|
||||
public Node representData(Object data)
|
||||
{
|
||||
return represent( ( (Configuration) data ).self );
|
||||
}
|
||||
} );
|
||||
}
|
||||
};
|
||||
|
||||
return new Yaml( new Constructor( new LoaderOptions() ), representer, options );
|
||||
}
|
||||
};
|
||||
|
||||
@Override
|
||||
public void save(Configuration config, File file) throws IOException
|
||||
{
|
||||
try ( Writer writer = new OutputStreamWriter( new FileOutputStream( file ), StandardCharsets.UTF_8 ) )
|
||||
{
|
||||
save( config, writer );
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save(Configuration config, Writer writer)
|
||||
{
|
||||
yaml.get().dump( config.self, writer );
|
||||
}
|
||||
|
||||
@Override
|
||||
public Configuration load(File file) throws IOException
|
||||
{
|
||||
return load( file, null );
|
||||
}
|
||||
|
||||
@Override
|
||||
public Configuration load(File file, Configuration defaults) throws IOException
|
||||
{
|
||||
try ( FileInputStream is = new FileInputStream( file ) )
|
||||
{
|
||||
return load( is, defaults );
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Configuration load(Reader reader)
|
||||
{
|
||||
return load( reader, null );
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public Configuration load(Reader reader, Configuration defaults)
|
||||
{
|
||||
Map<String, Object> map = yaml.get().loadAs( reader, LinkedHashMap.class );
|
||||
if ( map == null )
|
||||
{
|
||||
map = new LinkedHashMap<>();
|
||||
}
|
||||
return new Configuration( map, defaults );
|
||||
}
|
||||
|
||||
@Override
|
||||
public Configuration load(InputStream is)
|
||||
{
|
||||
return load( is, null );
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public Configuration load(InputStream is, Configuration defaults)
|
||||
{
|
||||
Map<String, Object> map = yaml.get().loadAs( is, LinkedHashMap.class );
|
||||
if ( map == null )
|
||||
{
|
||||
map = new LinkedHashMap<>();
|
||||
}
|
||||
return new Configuration( map, defaults );
|
||||
}
|
||||
|
||||
@Override
|
||||
public Configuration load(String string)
|
||||
{
|
||||
return load( string, null );
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public Configuration load(String string, Configuration defaults)
|
||||
{
|
||||
Map<String, Object> map = yaml.get().loadAs( string, LinkedHashMap.class );
|
||||
if ( map == null )
|
||||
{
|
||||
map = new LinkedHashMap<>();
|
||||
}
|
||||
return new Configuration( map, defaults );
|
||||
}
|
||||
}
|
||||
package de.rayzs.pat.utils.configuration.yaml;
|
||||
|
||||
import org.yaml.snakeyaml.constructor.Constructor;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import org.yaml.snakeyaml.LoaderOptions;
|
||||
import org.yaml.snakeyaml.representer.*;
|
||||
import org.yaml.snakeyaml.nodes.Node;
|
||||
import org.yaml.snakeyaml.*;
|
||||
import java.util.*;
|
||||
import java.io.*;
|
||||
|
||||
public class YamlConfiguration extends ConfigurationProvider {
|
||||
|
||||
/*
|
||||
Copyright (c) 2012, md_5. All rights reserved.
|
||||
Original code from Bungeecord source:
|
||||
https://github.com/SpigotMC/BungeeCord/blob/master/config/src/main/java/net/md_5/bungee/config/YamlConfiguration.java
|
||||
*/
|
||||
|
||||
private final ThreadLocal<Yaml> yaml = new ThreadLocal<Yaml>()
|
||||
{
|
||||
@Override
|
||||
protected Yaml initialValue()
|
||||
{
|
||||
DumperOptions options = new DumperOptions();
|
||||
options.setDefaultFlowStyle( DumperOptions.FlowStyle.BLOCK );
|
||||
|
||||
Representer representer = new Representer( options )
|
||||
{
|
||||
{
|
||||
representers.put( Configuration.class, new Represent()
|
||||
{
|
||||
@Override
|
||||
public Node representData(Object data)
|
||||
{
|
||||
return represent( ( (Configuration) data ).self );
|
||||
}
|
||||
} );
|
||||
}
|
||||
};
|
||||
|
||||
return new Yaml( new Constructor( new LoaderOptions() ), representer, options );
|
||||
}
|
||||
};
|
||||
|
||||
@Override
|
||||
public void save(Configuration config, File file) throws IOException
|
||||
{
|
||||
try ( Writer writer = new OutputStreamWriter( new FileOutputStream( file ), StandardCharsets.UTF_8 ) )
|
||||
{
|
||||
save( config, writer );
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save(Configuration config, Writer writer)
|
||||
{
|
||||
yaml.get().dump( config.self, writer );
|
||||
}
|
||||
|
||||
@Override
|
||||
public Configuration load(File file) throws IOException
|
||||
{
|
||||
return load( file, null );
|
||||
}
|
||||
|
||||
@Override
|
||||
public Configuration load(File file, Configuration defaults) throws IOException
|
||||
{
|
||||
try ( FileInputStream is = new FileInputStream( file ) )
|
||||
{
|
||||
return load( is, defaults );
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Configuration load(Reader reader)
|
||||
{
|
||||
return load( reader, null );
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public Configuration load(Reader reader, Configuration defaults)
|
||||
{
|
||||
Map<String, Object> map = yaml.get().loadAs( reader, LinkedHashMap.class );
|
||||
if ( map == null )
|
||||
{
|
||||
map = new LinkedHashMap<>();
|
||||
}
|
||||
return new Configuration( map, defaults );
|
||||
}
|
||||
|
||||
@Override
|
||||
public Configuration load(InputStream is)
|
||||
{
|
||||
return load( is, null );
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public Configuration load(InputStream is, Configuration defaults)
|
||||
{
|
||||
Map<String, Object> map = yaml.get().loadAs( is, LinkedHashMap.class );
|
||||
if ( map == null )
|
||||
{
|
||||
map = new LinkedHashMap<>();
|
||||
}
|
||||
return new Configuration( map, defaults );
|
||||
}
|
||||
|
||||
@Override
|
||||
public Configuration load(String string)
|
||||
{
|
||||
return load( string, null );
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public Configuration load(String string, Configuration defaults)
|
||||
{
|
||||
Map<String, Object> map = yaml.get().loadAs( string, LinkedHashMap.class );
|
||||
if ( map == null )
|
||||
{
|
||||
map = new LinkedHashMap<>();
|
||||
}
|
||||
return new Configuration( map, defaults );
|
||||
}
|
||||
}
|
||||
@@ -156,12 +156,12 @@ public class Group implements Serializable {
|
||||
this.priority = priority;
|
||||
}
|
||||
|
||||
public boolean hasPermission(CommandSender sender) {
|
||||
return PermissionUtil.hasPermission(sender, "group." + this.groupName);
|
||||
public boolean hasPermission(final CommandSender sender, final boolean isOperator) {
|
||||
return PermissionUtil.hasPermission(sender, "group." + this.groupName, isOperator);
|
||||
}
|
||||
|
||||
public boolean hasPermission(UUID uuid) {
|
||||
return PermissionUtil.hasPermission(uuid, "group." + this.groupName);
|
||||
public boolean hasPermission(final UUID uuid, final boolean isOperator) {
|
||||
return PermissionUtil.hasPermission(uuid, "group." + this.groupName, isOperator);
|
||||
}
|
||||
|
||||
public boolean contains(String command) {
|
||||
|
||||
@@ -45,8 +45,8 @@ public class GroupManager {
|
||||
});
|
||||
}
|
||||
|
||||
public static List<Group> getPlayerGroups(UUID uuid) {
|
||||
List<Group> playerGroups = new ArrayList<>(GroupManager.getGroups().stream().filter(group -> group.hasPermission(uuid)).toList());
|
||||
public static List<Group> getPlayerGroups(final UUID uuid, final boolean isOperator) {
|
||||
List<Group> playerGroups = new ArrayList<>(GroupManager.getGroups().stream().filter(group -> group.hasPermission(uuid, isOperator)).toList());
|
||||
|
||||
int priority = playerGroups.stream()
|
||||
.mapToInt(Group::getPriority)
|
||||
@@ -58,8 +58,8 @@ public class GroupManager {
|
||||
return playerGroups;
|
||||
}
|
||||
|
||||
public static List<Group> getPlayerGroups(CommandSender sender) {
|
||||
List<Group> playerGroups = new ArrayList<>(GroupManager.getGroups().stream().filter(group -> group.hasPermission(sender)).toList());
|
||||
public static List<Group> getPlayerGroups(final CommandSender sender, final boolean isOperator) {
|
||||
List<Group> playerGroups = new ArrayList<>(GroupManager.getGroups().stream().filter(group -> group.hasPermission(sender, isOperator)).toList());
|
||||
|
||||
int priority = playerGroups.stream()
|
||||
.mapToInt(Group::getPriority)
|
||||
@@ -70,11 +70,11 @@ public class GroupManager {
|
||||
return playerGroups;
|
||||
}
|
||||
|
||||
public static AccessResult canAccessCommand(List<Group> groups, String unmodifiedCommand, Storage.Blacklist.BlockType type) {
|
||||
public static AccessResult canAccessCommand(List<Group> groups, String unmodifiedCommand, BlockType type) {
|
||||
return canAccessCommand(groups, unmodifiedCommand, type, null);
|
||||
}
|
||||
|
||||
public static AccessResult canAccessCommand(List<Group> groups, String unmodifiedCommand, Storage.Blacklist.BlockType type, String server) {
|
||||
public static AccessResult canAccessCommand(List<Group> groups, String unmodifiedCommand, BlockType type, String server) {
|
||||
if (groups == null || groups.isEmpty()) {
|
||||
return AccessResult.NO_GROUPS;
|
||||
}
|
||||
@@ -132,7 +132,7 @@ public class GroupManager {
|
||||
}
|
||||
|
||||
if (!permitted && type != BlockType.BOTH)
|
||||
return canAccessCommand(groups, unmodifiedCommand, Storage.Blacklist.BlockType.BOTH, server);
|
||||
return canAccessCommand(groups, unmodifiedCommand, BlockType.BOTH, server);
|
||||
|
||||
return permitted ? AccessResult.ALLOWED : AccessResult.NOT_LISTED;
|
||||
}
|
||||
|
||||
@@ -5,10 +5,9 @@ import de.rayzs.pat.plugin.system.subargument.SubArgument;
|
||||
import de.rayzs.pat.utils.permission.PermissionPlugin;
|
||||
import de.rayzs.pat.utils.sender.CommandSender;
|
||||
import net.luckperms.api.context.ImmutableContextSet;
|
||||
import net.luckperms.api.event.LuckPermsEvent;
|
||||
import net.luckperms.api.event.sync.PreNetworkSyncEvent;
|
||||
import de.rayzs.pat.utils.permission.PermissionUtil;
|
||||
import net.luckperms.api.model.PermissionHolder;
|
||||
import net.luckperms.api.model.group.Group;
|
||||
import net.luckperms.api.model.user.User;
|
||||
import de.rayzs.pat.plugin.logger.Logger;
|
||||
import de.rayzs.pat.api.storage.Storage;
|
||||
@@ -20,6 +19,8 @@ import net.luckperms.api.*;
|
||||
import net.luckperms.api.query.QueryOptions;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class LuckPermsHook {
|
||||
|
||||
@@ -35,29 +36,58 @@ public class LuckPermsHook {
|
||||
eventBus.subscribe(
|
||||
Storage.getLoader().getPluginObj(),
|
||||
NodeAddEvent.class,
|
||||
event -> handleNodeChange(event.getTarget(), event.getNode()));
|
||||
event ->
|
||||
handleNodeChange(event.getTarget(), event.getNode())
|
||||
);
|
||||
|
||||
eventBus.subscribe(
|
||||
Storage.getLoader().getPluginObj(),
|
||||
NodeRemoveEvent.class,
|
||||
event -> handleNodeChange(event.getTarget(), event.getNode())
|
||||
event ->
|
||||
handleNodeChange(event.getTarget(), event.getNode())
|
||||
);
|
||||
|
||||
eventBus.subscribe(
|
||||
Storage.getLoader().getPluginObj(),
|
||||
NodeClearEvent.class,
|
||||
event -> handleNodesChange(event.getTarget(), event.getNodes())
|
||||
event ->
|
||||
handleNodesChange(event.getTarget(), event.getNodes())
|
||||
);
|
||||
|
||||
/* Probably not required anymore, since
|
||||
commands and permissions are already reloaded, in case
|
||||
the player updates some kind of PAT related permission.
|
||||
|
||||
This here only reload permissions and even updates player commands
|
||||
for all unnecessarily since why updating EVERYTHING for just
|
||||
one tiny group change or anything, which may not even be related
|
||||
to any PAT changes?
|
||||
|
||||
At least, so the thought. Therefore to be on the save side, it's disabled for now.
|
||||
This should also save some server memory.
|
||||
|
||||
eventBus.subscribe(
|
||||
Storage.getLoader().getPluginObj(),
|
||||
PreNetworkSyncEvent.class,
|
||||
event -> Storage.getLoader().delayedPermissionsReload()
|
||||
PostNetworkSyncEvent.class,
|
||||
event -> PermissionUtil.reloadPermissions()
|
||||
);
|
||||
*/
|
||||
}
|
||||
|
||||
public static Map<String, Boolean> getPermissions(UUID uuid) {
|
||||
final User user = PROVIDER.getUserManager().getUser(uuid);
|
||||
public static boolean forcePermissionRecalculation(UUID playerId) {
|
||||
final User user = PROVIDER.getUserManager().getUser(playerId);
|
||||
if (user == null) return false;
|
||||
|
||||
try {
|
||||
PROVIDER.getUserManager().loadUser(playerId).get();
|
||||
return true;
|
||||
} catch (InterruptedException | ExecutionException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static Map<String, Boolean> getPermissions(UUID playerId) {
|
||||
final User user = PROVIDER.getUserManager().getUser(playerId);
|
||||
|
||||
if (user == null) {
|
||||
return null;
|
||||
@@ -66,7 +96,7 @@ public class LuckPermsHook {
|
||||
final ImmutableContextSet.Builder builder = ImmutableContextSet.builder();
|
||||
|
||||
if (Storage.ConfigSections.Settings.UPDATE_GROUPS_PER_SERVER.ENABLED || Storage.ConfigSections.Settings.UPDATE_GROUPS_PER_WORLD.ENABLED) {
|
||||
final String contextValue = Storage.getLoader().getPlayerServerName(uuid);
|
||||
final String contextValue = Storage.getLoader().getPlayerServerName(playerId);
|
||||
|
||||
if (contextValue != null) {
|
||||
builder.add("server", contextValue).add("world", contextValue);
|
||||
@@ -95,24 +125,16 @@ public class LuckPermsHook {
|
||||
}
|
||||
|
||||
private static void handleNodesChange(PermissionHolder holder, Set<Node> nodes) {
|
||||
boolean relevant = false;
|
||||
|
||||
for (Node node : nodes) {
|
||||
if (node.getType() != NodeType.PERMISSION) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isRelevantPermission(node)) {
|
||||
relevant = true;
|
||||
handleAfterNodeChange(holder);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!relevant) {
|
||||
return;
|
||||
}
|
||||
|
||||
handleAfterNodeChange(holder);
|
||||
}
|
||||
|
||||
private static void handleNodeChange(PermissionHolder holder, Node node) {
|
||||
@@ -128,8 +150,34 @@ public class LuckPermsHook {
|
||||
}
|
||||
|
||||
private static void handleAfterNodeChange(PermissionHolder holder) {
|
||||
final boolean forwardChanges = Storage.ConfigSections.Settings.HANDLE_THROUGH_PROXY.ENABLED && Storage.ConfigSections.Settings.FORWARD_LUCK_PERMS_CHANGES_SECTION.ENABLED;
|
||||
|
||||
|
||||
if (! (holder instanceof User user)) {
|
||||
Storage.getLoader().delayedPermissionsReload();
|
||||
|
||||
if (holder instanceof Group group) {
|
||||
|
||||
if (!Reflection.isProxyServer() && forwardChanges) {
|
||||
final Set<UUID> playerIds = Storage.getLoader().getPlayerIds().stream().filter(id -> {
|
||||
final User user = PROVIDER.getUserManager().getUser(id);
|
||||
|
||||
return user != null && user.getCachedData().getPermissionData().checkPermission("group." + group.getName()).asBoolean();
|
||||
}).collect(Collectors.toSet());
|
||||
|
||||
Communicator.Backend2Proxy.sendGroupPermissionChangesPacket(playerIds);
|
||||
return;
|
||||
}
|
||||
|
||||
Storage.getLoader().getPlayerIds().forEach(id -> {
|
||||
final User user = PROVIDER.getUserManager().getUser(id);
|
||||
|
||||
if (user != null) {
|
||||
final boolean result = user.getCachedData().getPermissionData().checkPermission("group." + group.getName()).asBoolean();
|
||||
if (result) handleAfterNodeChange(user);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -139,27 +187,31 @@ public class LuckPermsHook {
|
||||
}
|
||||
|
||||
|
||||
final String serverName = sender.getServerName();
|
||||
PermissionUtil.reloadPermissions(sender);
|
||||
|
||||
|
||||
if (Reflection.isProxyServer()) {
|
||||
final List<String> serverCommands = Storage.Blacklist.Collector.collectAllServerCommands(serverName);
|
||||
final List<String> groupCommands = Storage.Blacklist.Collector.collectAllPlayerGroupCommands(sender, serverName);
|
||||
final String serverName = sender.getServerName();
|
||||
final HashSet<String> serverCommands = Storage.Blacklist.Collector.collectAllServerCommands(serverName);
|
||||
final HashSet<String> groupCommands = Storage.Blacklist.Collector.collectAllPlayerGroupCommands(sender, serverName);
|
||||
|
||||
final List<String> playerCommands = new ArrayList<>(serverCommands);
|
||||
final HashSet<String> playerCommands = new HashSet<>(serverCommands);
|
||||
playerCommands.addAll(groupCommands);
|
||||
|
||||
SubArgument.get().getUpdateArgumentsHandler().updatePlayerArguments(sender, playerCommands, serverCommands, groupCommands);
|
||||
Communicator.Proxy2Backend.sendUpdateCommand(user.getUniqueId(), serverName);
|
||||
}
|
||||
|
||||
Storage.getLoader().delayedPermissionsReload(sender);
|
||||
} else if (forwardChanges) {
|
||||
Communicator.Backend2Proxy.sendPlayerPermissionChangesPacket(sender.getUniqueId());
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isRelevantPermission(Node node) {
|
||||
final String key = node.getKey();
|
||||
|
||||
return key.startsWith("group.")
|
||||
return key.equals("*")
|
||||
|| key.startsWith("group.")
|
||||
|| key.startsWith("proantitab.")
|
||||
|| key.equals("*");
|
||||
|| key.startsWith("-proantitab.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package de.rayzs.pat.utils.message;
|
||||
|
||||
import de.rayzs.pat.plugin.logger.Logger;
|
||||
import de.rayzs.pat.utils.configuration.helper.MultipleMessagesHelper;
|
||||
import de.rayzs.pat.utils.message.replacer.PlaceholderReplacer;
|
||||
import de.rayzs.pat.utils.message.translators.*;
|
||||
import de.rayzs.pat.utils.*;
|
||||
import de.rayzs.pat.utils.sender.CommandSender;
|
||||
|
||||
import java.sql.Ref;
|
||||
import java.util.List;
|
||||
|
||||
public class MessageHelper {
|
||||
|
||||
private static boolean support;
|
||||
private static Translator translator = null;
|
||||
|
||||
public static void initialize() {
|
||||
|
||||
if (Reflection.isBukkit() || Reflection.isSpigot()) {
|
||||
Logger.warning("MiniMessage support disabled! Your server software is too old. Please switch to a more modern paper-based fork such as Paper, Purpur, Leaf..., etc to enable MiniMessage support.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (Reflection.isBungeeServer() && !Reflection.doesClassExist("net.kyori.adventure.util.Buildable$Builder")) {
|
||||
Logger.warning("MiniMessage support disabled! Since MiniMessage isn't supported for Bungeecord anymore and this version of Bungeecord is too advanced, MiniMessage support is disabled!");
|
||||
return;
|
||||
}
|
||||
|
||||
support = true;
|
||||
translator = Reflection.isVelocityServer() ? new VelocityMessageTranslator()
|
||||
: Reflection.isProxyServer() ? new BungeeMessageTranslator()
|
||||
: Reflection.isPaper() ? new PaperMessageTranslator()
|
||||
: new BukkitMessageTranslator();
|
||||
}
|
||||
|
||||
public static void sendMessage(CommandSender sender, MultipleMessagesHelper texts, String... replacements) {
|
||||
sendMessage(sender, texts.getLines(), replacements);
|
||||
}
|
||||
|
||||
public static void sendMessage(CommandSender sender, List<String> texts, String... replacements) {
|
||||
sendMessage(sender, StringUtils.getStringList(texts, "\n"), replacements);
|
||||
}
|
||||
|
||||
public static void sendMessage(CommandSender sender, String text, String... replacements) {
|
||||
if (text.isEmpty()) return;
|
||||
|
||||
|
||||
if (!Reflection.isProxyServer()) {
|
||||
text = PlaceholderReplacer.applyPlaceholders(sender, text, replacements);
|
||||
|
||||
if (support) {
|
||||
translator.send(sender, text);
|
||||
return;
|
||||
}
|
||||
|
||||
sender.sendMessage(text);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
if (support) {
|
||||
PlaceholderReplacer.applyProxyPlaceholders(sender, text, result -> translator.send(sender, result), replacements);
|
||||
return;
|
||||
}
|
||||
|
||||
PlaceholderReplacer.applyProxyPlaceholders(sender, text, sender::sendMessage, replacements);
|
||||
}
|
||||
|
||||
public static void sendActionbar(CommandSender sender, String message) {
|
||||
if (!support) {
|
||||
sender.sendActionbar(message);
|
||||
return;
|
||||
}
|
||||
|
||||
translator.sendActionbar(sender, message);
|
||||
}
|
||||
|
||||
public static void sendTitle(CommandSender sender, String title, String subtitle, int fadeIn, int stay, int fadeOut) {
|
||||
if (!support) {
|
||||
sender.sendTitle(title, subtitle, fadeIn, stay, fadeOut);
|
||||
return;
|
||||
}
|
||||
|
||||
translator.sendTitle(sender, title, subtitle, fadeIn, stay, fadeOut);
|
||||
}
|
||||
|
||||
public static void playSound(CommandSender sender, String soundKey, float volume, float pitch) throws Exception {
|
||||
translator.playSound(sender, soundKey, volume, pitch);
|
||||
}
|
||||
|
||||
public static String strip(String text) {
|
||||
return translator.strip(text);
|
||||
}
|
||||
|
||||
public static void closeAudiences() {
|
||||
if (translator == null) return;
|
||||
translator.close();
|
||||
}
|
||||
|
||||
public static boolean isSupported() {
|
||||
return support;
|
||||
}
|
||||
}
|
||||
@@ -1,214 +0,0 @@
|
||||
package de.rayzs.pat.utils.message;
|
||||
|
||||
import de.rayzs.pat.utils.configuration.helper.MultipleMessagesHelper;
|
||||
import de.rayzs.pat.utils.message.replacer.PlaceholderReplacer;
|
||||
import de.rayzs.pat.utils.message.translators.*;
|
||||
import de.rayzs.pat.api.storage.Storage;
|
||||
import de.rayzs.pat.utils.*;
|
||||
import de.rayzs.pat.utils.sender.CommandSender;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public class MessageTranslator {
|
||||
|
||||
private static final HashMap<Character, String> colors = new HashMap<>(), endingColors = new HashMap<>();
|
||||
private static boolean support;
|
||||
private static Translator translator = null;
|
||||
|
||||
public static void initialize() {
|
||||
colors.put('1', "<dark_blue>");
|
||||
colors.put('2', "<dark_green>");
|
||||
colors.put('3', "<dark_aqua>");
|
||||
colors.put('4', "<dark_red>");
|
||||
colors.put('5', "<dark_purple>");
|
||||
colors.put('6', "<gold>");
|
||||
colors.put('7', "<gray>");
|
||||
colors.put('8', "<dark_gray>");
|
||||
colors.put('9', "<blue>");
|
||||
colors.put('a', "<green>");
|
||||
colors.put('b', "<aqua>");
|
||||
colors.put('c', "<red>");
|
||||
colors.put('d', "<light_purple>");
|
||||
colors.put('e', "<yellow>");
|
||||
colors.put('f', "<white>");
|
||||
colors.put('m', "<st>");
|
||||
colors.put('k', "<obf>");
|
||||
colors.put('r', "<reset>");
|
||||
colors.put('o', "<i>");
|
||||
colors.put('l', "<b>");
|
||||
|
||||
for (Map.Entry<Character, String> entry : colors.entrySet())
|
||||
endingColors.put(entry.getKey(), "</" + entry.getValue().substring(1));
|
||||
|
||||
support = !Reflection.isCraftbukkit() && (Reflection.isAtLeast(1, 18) || Reflection.isProxyServer());
|
||||
|
||||
if (support) {
|
||||
translator = Reflection.isVelocityServer() ? new VelocityMessageTranslator()
|
||||
: Reflection.isProxyServer() ? new BungeeMessageTranslator()
|
||||
: new BukkitMessageTranslator();
|
||||
}
|
||||
}
|
||||
|
||||
public static String translateLegacy(String text) {
|
||||
text = replaceMessage(text);
|
||||
if(!text.contains("§")) return text;
|
||||
|
||||
for (Map.Entry<Character, String> entry : colors.entrySet())
|
||||
text = text.replace("§" + entry.getKey(), entry.getValue());
|
||||
|
||||
return text;
|
||||
}
|
||||
|
||||
public static String colorless(String text) {
|
||||
text = replaceMessage(text);
|
||||
if(!text.contains("§")) return text;
|
||||
|
||||
for (Map.Entry<Character, String> entry : colors.entrySet())
|
||||
text = text.replace("§" + entry.getKey(), "");
|
||||
|
||||
return text;
|
||||
}
|
||||
|
||||
public static void send(Object target, MultipleMessagesHelper texts) {
|
||||
String stringList = StringUtils.getStringList(texts.getLines(), "\n");
|
||||
send(target, stringList);
|
||||
}
|
||||
|
||||
public static void send(Object target, MultipleMessagesHelper texts, String... replacements) {
|
||||
String stringList = StringUtils.getStringList(texts.getLines(), "\n");
|
||||
send(target, stringList, replacements);
|
||||
}
|
||||
|
||||
public static void send(Object target, List<String> texts) {
|
||||
String stringList = StringUtils.getStringList(texts, "\n");
|
||||
send(target, stringList);
|
||||
}
|
||||
|
||||
public static void send(Object target, List<String> texts, String... replacements) {
|
||||
texts = replaceMessageList(texts, replacements);
|
||||
send(target, texts);
|
||||
}
|
||||
|
||||
public static void send(Object target, String text, String... replacements) {
|
||||
if (text.isEmpty()) return;
|
||||
|
||||
text = replaceMessageString(target, text, replacements);
|
||||
|
||||
if (text.contains("%no-message%")) return;
|
||||
|
||||
if(translator == null) {
|
||||
|
||||
CommandSender sender = target instanceof CommandSender
|
||||
? (CommandSender) target
|
||||
: CommandSender.from(target);
|
||||
|
||||
if (!PlaceholderReplacer.process(sender, text, sender::sendMessage))
|
||||
sender.sendMessage(text);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
final Object tmpTarget = target instanceof CommandSender sender
|
||||
? sender.getSenderObject() : target;
|
||||
|
||||
if (PlaceholderReplacer.process(target, text, result -> translator.send(tmpTarget, result))) {
|
||||
return;
|
||||
}
|
||||
|
||||
translator.send(tmpTarget, text);
|
||||
}
|
||||
|
||||
public static String replaceMessage(String text) {
|
||||
return replaceMessage(null, text);
|
||||
}
|
||||
|
||||
public static String replaceMessage(Object targetObj, String text) {
|
||||
CommandSender sender = targetObj == null ? null
|
||||
: targetObj instanceof CommandSender
|
||||
? (CommandSender) targetObj
|
||||
: CommandSender.from(targetObj);
|
||||
|
||||
String executorName = (sender == null || sender.isConsole())
|
||||
? ""
|
||||
: sender.getName();
|
||||
|
||||
String token = (Storage.ConfigSections.Settings.HANDLE_THROUGH_PROXY.ENABLED || Reflection.isProxyServer())
|
||||
? Storage.CENSORED_TOKEN
|
||||
: "/";
|
||||
|
||||
String serverName = Storage.SERVER_NAME == null ? "/" : Storage.SERVER_NAME;
|
||||
|
||||
text = StringUtils.replace(text,
|
||||
"&", "§",
|
||||
"\\n", "\n",
|
||||
"%executor%", executorName,
|
||||
"%prefix%", Storage.ConfigSections.Messages.PREFIX.PREFIX,
|
||||
"%pat_general_prefix%", Storage.ConfigSections.Messages.PREFIX.PREFIX,
|
||||
"%token%", token,
|
||||
"%sync_server_name%", serverName,
|
||||
"%server%", serverName,
|
||||
"%current_version%", Storage.CURRENT_VERSION,
|
||||
"%newest_version%", Storage.NEWER_VERSION
|
||||
);
|
||||
|
||||
return PlaceholderReplacer.replace(targetObj, text);
|
||||
}
|
||||
|
||||
public static String replaceMessageString(Object targetObj, String rawText, String... replacements) {
|
||||
return replaceMessage(targetObj, StringUtils.replace(rawText, replacements));
|
||||
}
|
||||
|
||||
public static List<String> replaceMessageList(MultipleMessagesHelper rawText, String... replacements) {
|
||||
return replaceMessageList(rawText.getLines(), replacements);
|
||||
}
|
||||
|
||||
public static List<String> replaceMessageList(List<String> rawText, String... replacements) {
|
||||
final HashMap<String, String> REPLACEMENTS = new HashMap<>();
|
||||
List<String> result = new ArrayList<>();
|
||||
|
||||
if(replacements != null) {
|
||||
String firstReplacementInput = null, secondReplacementInput = null;
|
||||
for (String replacement : replacements) {
|
||||
if (firstReplacementInput == null) firstReplacementInput = replacement;
|
||||
else secondReplacementInput = replacement;
|
||||
|
||||
if (firstReplacementInput != null && secondReplacementInput != null) {
|
||||
REPLACEMENTS.put(firstReplacementInput, secondReplacementInput);
|
||||
firstReplacementInput = null;
|
||||
secondReplacementInput = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
rawText.forEach(text -> {
|
||||
if(replacements != null)
|
||||
for (Map.Entry<String, String> entry : REPLACEMENTS.entrySet())
|
||||
text = text.replace(entry.getKey(), entry.getValue());
|
||||
String resultText = replaceMessage(text);
|
||||
result.add(resultText);
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public static void sendActionbar(Object targetObj, String message) {
|
||||
translator.sendActionbar(targetObj, message);
|
||||
}
|
||||
|
||||
public static void sendTitle(Object targetObj, String title, String subtitle, int fadeIn, int stay, int fadeOut) {
|
||||
translator.sendTitle(targetObj, title, subtitle, fadeIn, stay, fadeOut);
|
||||
}
|
||||
|
||||
public static void playSound(Object targetObj, String soundKey, float volume, float pitch) throws Exception {
|
||||
translator.playSound(targetObj, soundKey, volume, pitch);
|
||||
}
|
||||
|
||||
public static void closeAudiences() {
|
||||
if(translator == null) return;
|
||||
translator.close();
|
||||
}
|
||||
|
||||
public static boolean isSupported() {
|
||||
return support;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package de.rayzs.pat.utils.message;
|
||||
|
||||
import de.rayzs.pat.utils.StringUtils;
|
||||
import de.rayzs.pat.utils.sender.CommandSender;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.minimessage.MiniMessage;
|
||||
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
|
||||
@@ -9,21 +10,21 @@ public interface Translator {
|
||||
|
||||
MiniMessage miniMessage = MiniMessage.miniMessage();
|
||||
|
||||
String translate(String text);
|
||||
String strip(String text);
|
||||
|
||||
void send(Object target, String text);
|
||||
void send(CommandSender sender, String text);
|
||||
|
||||
void sendActionbar(Object target, String text);
|
||||
void sendActionbar(CommandSender sender, String text);
|
||||
|
||||
void sendTitle(Object target, String title, String subtitle, int fadeIn, int stay, int fadeOut);
|
||||
void sendTitle(CommandSender sender, String title, String subtitle, int fadeIn, int stay, int fadeOut);
|
||||
|
||||
void playSound(Object target, String soundKey, float volume, float pitch) throws Exception;
|
||||
void playSound(CommandSender sender, String soundKey, float volume, float pitch) throws Exception;
|
||||
|
||||
default Component toComponent(String text) {
|
||||
text = StringUtils.replace(text, "§", "&");
|
||||
|
||||
Component legacy = LegacyComponentSerializer.legacyAmpersand().deserialize(text);
|
||||
text = StringUtils.replace(miniMessage.serialize(legacy), "\\", "");
|
||||
final Component legacy = LegacyComponentSerializer.legacyAmpersand().deserialize(text);
|
||||
text = miniMessage.serialize(legacy).replace("\\", "");
|
||||
|
||||
return miniMessage.deserialize(text);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
package de.rayzs.pat.utils.message.replacer;
|
||||
|
||||
import de.rayzs.pat.utils.Reflection;
|
||||
import de.rayzs.pat.utils.StringUtils;
|
||||
import de.rayzs.pat.utils.message.replacer.impl.*;
|
||||
import de.rayzs.pat.api.storage.Storage;
|
||||
import de.rayzs.pat.utils.sender.CommandSender;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class PlaceholderReplacer {
|
||||
@@ -9,8 +14,10 @@ public class PlaceholderReplacer {
|
||||
private static BukkitPlaceholderReplacer BUKKIT_PLACEHOLDER_REPLACER = null;
|
||||
private static ProxyPlaceholderReplacer PROXY_PLACEHOLDER_REPLACER = null;
|
||||
|
||||
public static String replace(Object playerObj, String text) {
|
||||
if (!Storage.USE_PLACEHOLDERAPI)
|
||||
public static String applyPlaceholders(CommandSender sender, String text, String... replacements) {
|
||||
text = applyGeneralReplacements(sender, text, replacements);
|
||||
|
||||
if (Reflection.isProxyServer() || !Storage.USE_PLACEHOLDERAPI)
|
||||
return text;
|
||||
|
||||
if (!text.contains("%"))
|
||||
@@ -19,18 +26,51 @@ public class PlaceholderReplacer {
|
||||
if (BUKKIT_PLACEHOLDER_REPLACER == null)
|
||||
BUKKIT_PLACEHOLDER_REPLACER = new BukkitPlaceholderReplacer();
|
||||
|
||||
return BUKKIT_PLACEHOLDER_REPLACER.process(playerObj, text);
|
||||
return BUKKIT_PLACEHOLDER_REPLACER.process(sender, text);
|
||||
}
|
||||
|
||||
public static boolean process(Object playerObj, String text, Consumer<String> consumer) {
|
||||
if (!Storage.USE_PAPIPROXYBRIDGE)
|
||||
return false;
|
||||
public static void applyProxyPlaceholders(CommandSender sender, String text, Consumer<String> consumer, String... replacements) {
|
||||
text = applyPlaceholders(sender, text, replacements);
|
||||
|
||||
if (!text.contains("%")) return false;
|
||||
if (!Storage.USE_PAPIPROXYBRIDGE) {
|
||||
consumer.accept(text);
|
||||
return;
|
||||
}
|
||||
|
||||
if (PROXY_PLACEHOLDER_REPLACER == null)
|
||||
if (!text.contains("%")) {
|
||||
consumer.accept(text);
|
||||
return;
|
||||
}
|
||||
|
||||
if (PROXY_PLACEHOLDER_REPLACER == null) {
|
||||
PROXY_PLACEHOLDER_REPLACER = new ProxyPlaceholderReplacer();
|
||||
}
|
||||
|
||||
return PROXY_PLACEHOLDER_REPLACER.process(playerObj, text, consumer);
|
||||
if (!PROXY_PLACEHOLDER_REPLACER.process(sender, text, consumer)) {
|
||||
consumer.accept(text);
|
||||
}
|
||||
}
|
||||
|
||||
private static String applyGeneralReplacements(CommandSender sender, String text, String... replacements) {
|
||||
final String executorName = sender == null ? "" : sender.getName();
|
||||
|
||||
final String token = (Storage.ConfigSections.Settings.HANDLE_THROUGH_PROXY.ENABLED || Reflection.isProxyServer())
|
||||
? Storage.CENSORED_TOKEN
|
||||
: "/";
|
||||
|
||||
final String serverName = Objects.requireNonNullElse(Storage.SERVER_NAME, "/");
|
||||
|
||||
return StringUtils.replace(StringUtils.replace(text, replacements),
|
||||
"&", "§",
|
||||
"\\n", "\n",
|
||||
"%executor%", executorName,
|
||||
"%prefix%", Storage.ConfigSections.Messages.PREFIX.PREFIX,
|
||||
"%pat_general_prefix%", Storage.ConfigSections.Messages.PREFIX.PREFIX,
|
||||
"%token%", token,
|
||||
"%sync_server_name%", serverName,
|
||||
"%server%", serverName,
|
||||
"%current_version%", Storage.CURRENT_VERSION,
|
||||
"%newest_version%", Storage.NEWER_VERSION
|
||||
);
|
||||
}
|
||||
}
|
||||
+5
-10
@@ -6,17 +6,12 @@ import org.bukkit.entity.Player;
|
||||
|
||||
public class BukkitPlaceholderReplacer {
|
||||
|
||||
public String process(Object playerObj, String text) {
|
||||
Player player = null;
|
||||
public String process(CommandSender sender, String text) {
|
||||
|
||||
if(playerObj != null)
|
||||
if(playerObj instanceof CommandSender) {
|
||||
CommandSender sender = (CommandSender) playerObj;
|
||||
player = sender.isPlayer() ? (Player) sender.getSenderObject() : null;
|
||||
} else if(playerObj instanceof Player)
|
||||
player = (Player) playerObj;
|
||||
if (sender.isPlayer() && sender.getSenderObject() instanceof Player player) {
|
||||
return PlaceholderAPI.setPlaceholders(player, text);
|
||||
}
|
||||
|
||||
|
||||
return PlaceholderAPI.setPlaceholders(player, text);
|
||||
return PlaceholderAPI.setPlaceholders(null, text);
|
||||
}
|
||||
}
|
||||
+3
-26
@@ -15,33 +15,10 @@ public class ProxyPlaceholderReplacer {
|
||||
placeholderAPI.setRequestTimeout(1500);
|
||||
}
|
||||
|
||||
public boolean process(Object playerObj, String text, Consumer<String> consumer) {
|
||||
UUID uuid = null;
|
||||
|
||||
if(playerObj != null)
|
||||
|
||||
if (playerObj instanceof CommandSender) {
|
||||
|
||||
uuid = ((CommandSender) playerObj).getUniqueId();
|
||||
|
||||
} else if (Reflection.isVelocityServer()) {
|
||||
|
||||
if (playerObj instanceof com.velocitypowered.api.proxy.Player)
|
||||
uuid = ((com.velocitypowered.api.proxy.Player) playerObj).getUniqueId();
|
||||
|
||||
} else if (Reflection.isProxyServer()) {
|
||||
|
||||
if (playerObj instanceof net.md_5.bungee.api.connection.ProxiedPlayer)
|
||||
uuid = ((net.md_5.bungee.api.connection.ProxiedPlayer) playerObj).getUniqueId();
|
||||
|
||||
} else {
|
||||
if (playerObj instanceof org.bukkit.entity.Player)
|
||||
uuid = ((org.bukkit.entity.Player) playerObj).getUniqueId();
|
||||
}
|
||||
|
||||
if(uuid == null) return false;
|
||||
placeholderAPI.formatPlaceholders(text, uuid).thenAccept(consumer);
|
||||
public boolean process(CommandSender sender, String text, Consumer<String> consumer) {
|
||||
if (sender == null || !sender.isPlayer()) return false;
|
||||
|
||||
placeholderAPI.formatPlaceholders(text, sender.getUniqueId()).thenAccept(consumer);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import net.kyori.adventure.platform.bukkit.BukkitAudiences;
|
||||
import net.kyori.adventure.audience.Audience;
|
||||
import de.rayzs.pat.plugin.BukkitLoader;
|
||||
import net.kyori.adventure.title.Title;
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.Sound;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import de.rayzs.pat.utils.message.*;
|
||||
@@ -20,39 +21,68 @@ public class BukkitMessageTranslator implements Translator {
|
||||
}
|
||||
|
||||
@Override
|
||||
public String translate(String text) {
|
||||
return miniMessage.serialize(miniMessage.deserialize(MessageTranslator.translateLegacy(text)));
|
||||
public String strip(String text) {
|
||||
return ChatColor.stripColor(miniMessage.stripTags(text));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void send(Object target, String text) {
|
||||
Audience audience = target instanceof Player ? audiences.player((Player) target) : audiences.sender((CommandSender) target);
|
||||
public void send(de.rayzs.pat.utils.sender.CommandSender sender, String text) {
|
||||
final Audience audience = sender.getSenderObject() instanceof Player player
|
||||
? audiences.player(player)
|
||||
: sender.getSenderObject() instanceof CommandSender commandSender
|
||||
? audiences.sender(commandSender)
|
||||
: null;
|
||||
|
||||
|
||||
if (audience == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
audience.sendMessage(toComponent(text));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendActionbar(Object target, String text) {
|
||||
Audience audience = target instanceof Player ? audiences.player((Player) target) : audiences.sender((CommandSender) target);
|
||||
public void sendActionbar(de.rayzs.pat.utils.sender.CommandSender sender, String text) {
|
||||
final Audience audience = sender.getSenderObject() instanceof Player player
|
||||
? audiences.player(player)
|
||||
: sender.getSenderObject() instanceof CommandSender commandSender
|
||||
? audiences.sender(commandSender)
|
||||
: null;
|
||||
|
||||
|
||||
if (audience == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
audience.sendActionBar(toComponent(text));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendTitle(Object target, String titleStr, String subtitleStr, int fadeIn, int stay, int fadeOut) {
|
||||
Audience audience = target instanceof Player ? audiences.player((Player) target) : audiences.sender((CommandSender) target);
|
||||
public void sendTitle(de.rayzs.pat.utils.sender.CommandSender sender, String titleStr, String subtitleStr, int fadeIn, int stay, int fadeOut) {
|
||||
|
||||
Title.Times times = Title.Times.times(Duration.ofMillis(fadeIn), Duration.ofMillis(stay), Duration.ofMillis(fadeOut));
|
||||
Title title = Title.title(toComponent(titleStr), toComponent(subtitleStr), times);
|
||||
final Audience audience = sender.getSenderObject() instanceof Player player
|
||||
? audiences.player(player)
|
||||
: sender.getSenderObject() instanceof CommandSender commandSender
|
||||
? audiences.sender(commandSender)
|
||||
: null;
|
||||
|
||||
|
||||
if (audience == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
final Title.Times times = Title.Times.times(Duration.ofMillis(fadeIn), Duration.ofMillis(stay), Duration.ofMillis(fadeOut));
|
||||
final Title title = Title.title(toComponent(titleStr), toComponent(subtitleStr), times);
|
||||
|
||||
audience.showTitle(title);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void playSound(Object target, String soundKey, float volume, float pitch) throws Exception {
|
||||
if (target instanceof Player player) {
|
||||
public void playSound(de.rayzs.pat.utils.sender.CommandSender sender, String soundKey, float volume, float pitch) throws Exception {
|
||||
if (sender.getSenderObject() instanceof Player player) {
|
||||
Sound sound = Sound.valueOf(soundKey);
|
||||
|
||||
player.playSound(player.getLocation(), sound, volume, pitch);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,17 +1,15 @@
|
||||
package de.rayzs.pat.utils.message.translators;
|
||||
|
||||
import de.rayzs.pat.utils.StringUtils;
|
||||
import net.kyori.adventure.key.Key;
|
||||
import net.kyori.adventure.sound.Sound;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.platform.bungeecord.BungeeAudiences;
|
||||
import net.kyori.adventure.title.Title;
|
||||
import net.md_5.bungee.api.connection.ProxiedPlayer;
|
||||
import de.rayzs.pat.utils.message.MessageTranslator;
|
||||
import net.kyori.adventure.audience.Audience;
|
||||
import de.rayzs.pat.utils.message.Translator;
|
||||
import net.md_5.bungee.api.CommandSender;
|
||||
import de.rayzs.pat.plugin.BungeeLoader;
|
||||
import org.bukkit.ChatColor;
|
||||
|
||||
import java.time.Duration;
|
||||
|
||||
@@ -24,39 +22,79 @@ public class BungeeMessageTranslator implements Translator {
|
||||
}
|
||||
|
||||
@Override
|
||||
public String translate(String text) {
|
||||
return miniMessage.serialize(miniMessage.deserialize(MessageTranslator.translateLegacy(text)));
|
||||
public String strip(String text) {
|
||||
return ChatColor.stripColor(miniMessage.stripTags(text));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void send(Object target, String text) {
|
||||
Audience audience = target instanceof ProxiedPlayer ? audiences.player((ProxiedPlayer) target) : audiences.sender((CommandSender) target);
|
||||
public void send(de.rayzs.pat.utils.sender.CommandSender sender, String text) {
|
||||
final Audience audience = sender.getSenderObject() instanceof ProxiedPlayer player
|
||||
? audiences.player(player)
|
||||
: sender.getSenderObject() instanceof CommandSender commandSender
|
||||
? audiences.sender(commandSender)
|
||||
: null;
|
||||
|
||||
|
||||
if (audience == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
audience.sendMessage(toComponent(text));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendActionbar(Object target, String text) {
|
||||
Audience audience = target instanceof ProxiedPlayer ? audiences.player((ProxiedPlayer) target) : audiences.sender((CommandSender) target);
|
||||
public void sendActionbar(de.rayzs.pat.utils.sender.CommandSender sender, String text) {
|
||||
final Audience audience = sender.getSenderObject() instanceof ProxiedPlayer player
|
||||
? audiences.player(player)
|
||||
: sender.getSenderObject() instanceof CommandSender commandSender
|
||||
? audiences.sender(commandSender)
|
||||
: null;
|
||||
|
||||
|
||||
if (audience == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
audience.sendActionBar(toComponent(text));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendTitle(Object target, String titleStr, String subtitleStr, int fadeIn, int stay, int fadeOut) {
|
||||
Audience audience = target instanceof ProxiedPlayer ? audiences.player((ProxiedPlayer) target) : audiences.sender((CommandSender) target);
|
||||
public void sendTitle(de.rayzs.pat.utils.sender.CommandSender sender, String titleStr, String subtitleStr, int fadeIn, int stay, int fadeOut) {
|
||||
final Audience audience = sender.getSenderObject() instanceof ProxiedPlayer player
|
||||
? audiences.player(player)
|
||||
: sender.getSenderObject() instanceof CommandSender commandSender
|
||||
? audiences.sender(commandSender)
|
||||
: null;
|
||||
|
||||
Title.Times times = Title.Times.times(Duration.ofMillis(fadeIn), Duration.ofMillis(stay), Duration.ofMillis(fadeOut));
|
||||
Title title = Title.title(toComponent(titleStr), toComponent(subtitleStr), times);
|
||||
|
||||
if (audience == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
final Title.Times times = Title.Times.times(Duration.ofMillis(fadeIn), Duration.ofMillis(stay), Duration.ofMillis(fadeOut));
|
||||
final Title title = Title.title(toComponent(titleStr), toComponent(subtitleStr), times);
|
||||
|
||||
audience.showTitle(title);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void playSound(Object target, String soundKey, float volume, float pitch) throws Exception {
|
||||
Audience audience = target instanceof ProxiedPlayer ? audiences.player((ProxiedPlayer) target) : audiences.sender((CommandSender) target);
|
||||
Sound sound = Sound.sound(Key.key(soundKey), Sound.Source.MASTER, 1f, 1f);
|
||||
public void playSound(de.rayzs.pat.utils.sender.CommandSender sender, String soundKey, float volume, float pitch) throws Exception {
|
||||
final Audience audience = sender.getSenderObject() instanceof ProxiedPlayer player
|
||||
? audiences.player(player)
|
||||
: sender.getSenderObject() instanceof CommandSender commandSender
|
||||
? audiences.sender(commandSender)
|
||||
: null;
|
||||
|
||||
|
||||
if (audience == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
final Sound sound = Sound.sound(Key.key(soundKey), Sound.Source.MASTER, 1f, 1f);
|
||||
audience.playSound(sound, Sound.Emitter.self());
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
package de.rayzs.pat.utils.message.translators;
|
||||
|
||||
import de.rayzs.pat.utils.message.Translator;
|
||||
import net.kyori.adventure.title.Title;
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.Sound;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import java.time.Duration;
|
||||
|
||||
public class PaperMessageTranslator implements Translator {
|
||||
|
||||
@Override
|
||||
public String strip(String text) {
|
||||
return ChatColor.stripColor(miniMessage.stripTags(text));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void send(de.rayzs.pat.utils.sender.CommandSender sender, String text) {
|
||||
if (sender.getSenderObject() instanceof Player player) {
|
||||
player.sendMessage(toComponent(text));
|
||||
} else if (sender.getSenderObject() instanceof CommandSender commandSender) {
|
||||
commandSender.sendMessage(toComponent(text));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendActionbar(de.rayzs.pat.utils.sender.CommandSender sender, String text) {
|
||||
if (sender.getSenderObject() instanceof Player player) {
|
||||
player.sendActionBar(toComponent(text));
|
||||
} else if (sender.getSenderObject() instanceof CommandSender commandSender) {
|
||||
commandSender.sendActionBar(toComponent(text));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendTitle(de.rayzs.pat.utils.sender.CommandSender sender, String titleStr, String subtitleStr, int fadeIn, int stay, int fadeOut) {
|
||||
final Title.Times times = Title.Times.times(Duration.ofMillis(fadeIn), Duration.ofMillis(stay), Duration.ofMillis(fadeOut));
|
||||
final Title title = Title.title(toComponent(titleStr), toComponent(subtitleStr), times);
|
||||
|
||||
if (sender.getSenderObject() instanceof Player player) {
|
||||
player.showTitle(title);
|
||||
} else if (sender.getSenderObject() instanceof CommandSender commandSender) {
|
||||
commandSender.showTitle(title);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void playSound(de.rayzs.pat.utils.sender.CommandSender sender, String soundKey, float volume, float pitch) throws Exception {
|
||||
if (sender.getSenderObject() instanceof Player player) {
|
||||
final Sound sound = Sound.valueOf(soundKey);
|
||||
player.playSound(player.getLocation(), sound, volume, pitch);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {}
|
||||
}
|
||||
+13
-14
@@ -12,39 +12,38 @@ import java.time.Duration;
|
||||
public class VelocityMessageTranslator implements Translator {
|
||||
|
||||
@Override
|
||||
public String translate(String text) {
|
||||
return MiniMessage.miniMessage().serialize(miniMessage.deserialize(MessageTranslator.translateLegacy(text)));
|
||||
public String strip(String text) {
|
||||
return miniMessage.stripTags(text);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void send(Object target, String text) {
|
||||
if (target instanceof CommandSource source) {
|
||||
public void send(de.rayzs.pat.utils.sender.CommandSender sender, String text) {
|
||||
if (sender.getSenderObject() instanceof CommandSource source) {
|
||||
source.sendMessage(toComponent(text));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendActionbar(Object target, String text) {
|
||||
if (target instanceof CommandSource source) {
|
||||
public void sendActionbar(de.rayzs.pat.utils.sender.CommandSender sender, String text) {
|
||||
if (sender.getSenderObject() instanceof CommandSource source) {
|
||||
source.sendActionBar(toComponent(text));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendTitle(Object target, String titleStr, String subtitleStr, int fadeIn, int stay, int fadeOut) {
|
||||
Title.Times times = Title.Times.times(Duration.ofMillis(fadeIn), Duration.ofMillis(stay), Duration.ofMillis(fadeOut));
|
||||
Title title = Title.title(toComponent(titleStr), toComponent(subtitleStr), times);
|
||||
public void sendTitle(de.rayzs.pat.utils.sender.CommandSender sender, String titleStr, String subtitleStr, int fadeIn, int stay, int fadeOut) {
|
||||
final Title.Times times = Title.Times.times(Duration.ofMillis(fadeIn), Duration.ofMillis(stay), Duration.ofMillis(fadeOut));
|
||||
final Title title = Title.title(toComponent(titleStr), toComponent(subtitleStr), times);
|
||||
|
||||
if (target instanceof CommandSource source) {
|
||||
if (sender.getSenderObject() instanceof CommandSource source) {
|
||||
source.showTitle(title);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void playSound(Object target, String soundKey, float volume, float pitch) throws Exception {
|
||||
if (target instanceof CommandSource source) {
|
||||
Sound sound = Sound.sound(Key.key(soundKey), Sound.Source.MASTER, 1f, 1f);
|
||||
|
||||
public void playSound(de.rayzs.pat.utils.sender.CommandSender sender, String soundKey, float volume, float pitch) throws Exception {
|
||||
if (sender.getSenderObject() instanceof CommandSource source) {
|
||||
final Sound sound = Sound.sound(Key.key(soundKey), Sound.Source.MASTER, 1f, 1f);
|
||||
source.playSound(sound, Sound.Emitter.self());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -65,7 +65,8 @@ public class PermissionUtil {
|
||||
} else if (Storage.getPermissionPlugin() == PermissionPlugin.GROUPMANAGER) {
|
||||
GroupManagerHook.setPermissions(sender.getUniqueId());
|
||||
} else {
|
||||
GroupManager.getGroups().forEach(group -> group.hasPermission(sender));
|
||||
final boolean isOperator = sender.isOperator();
|
||||
GroupManager.getGroups().forEach(group -> group.hasPermission(sender, isOperator));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -75,7 +76,11 @@ public class PermissionUtil {
|
||||
} else if (Storage.getPermissionPlugin() == PermissionPlugin.GROUPMANAGER) {
|
||||
GroupManagerHook.setPermissions(uuid);
|
||||
} else {
|
||||
GroupManager.getGroups().forEach(group -> group.hasPermission(uuid));
|
||||
final CommandSender sender = CommandSender.from(uuid);
|
||||
if (sender == null) return;
|
||||
|
||||
final boolean isOperator = sender.isOperator();
|
||||
GroupManager.getGroups().forEach(group -> group.hasPermission(uuid, isOperator));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -87,19 +92,38 @@ public class PermissionUtil {
|
||||
}
|
||||
|
||||
public static void setPermission(UUID uuid, String permission, boolean permitted) {
|
||||
PermissionMap permissionMap;
|
||||
PermissionMap permissionMap = MAP.get(uuid);
|
||||
|
||||
if(!MAP.containsKey(uuid)) {
|
||||
if(permissionMap == null) {
|
||||
permissionMap = new PermissionMap(uuid);
|
||||
MAP.put(uuid, permissionMap);
|
||||
} else permissionMap = MAP.get(uuid);
|
||||
}
|
||||
|
||||
|
||||
final boolean isNegatedPermission = permission.charAt(0) == '-';
|
||||
|
||||
// Ignore because set permission is negated.
|
||||
if (!isNegatedPermission && permissionMap.isPermitted("-" + permission)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (isNegatedPermission) {
|
||||
final String nonNegatedPermission = permission.substring(1);
|
||||
|
||||
if (permissionMap.isPermitted(nonNegatedPermission)) {
|
||||
permissionMap.setState(nonNegatedPermission, false);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
permissionMap.setState(permission, permitted);
|
||||
}
|
||||
|
||||
public static boolean hasPermission(Object targetObj, String permission) {
|
||||
PermissionMap permissionMap;
|
||||
public static boolean hasPermission(final Object targetObj, final String permission, final boolean isOperator) {
|
||||
if (isOperator) return true;
|
||||
|
||||
|
||||
PermissionMap permissionMap;
|
||||
CommandSender sender = null;
|
||||
UUID uuid = null;
|
||||
|
||||
@@ -127,8 +151,7 @@ public class PermissionUtil {
|
||||
return true;
|
||||
}
|
||||
|
||||
return sender.isOperator()
|
||||
|| sender.hasPermission("*")
|
||||
return sender.hasPermission("*")
|
||||
|| sender.hasPermission("proantitab.*")
|
||||
|| sender.hasPermission("proantitab." + permission);
|
||||
}
|
||||
@@ -161,31 +184,33 @@ public class PermissionUtil {
|
||||
permissionMap.setState("proantitab." + permission, sender.hasPermission("proantitab." + permission));
|
||||
|
||||
}
|
||||
|
||||
if (sender.isOperator()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return permissionMap.isPermitted("*") || permissionMap.isPermitted("proantitab.*") || permissionMap.isPermitted("proantitab." + permission);
|
||||
return permissionMap.isPermitted("*")
|
||||
|| permissionMap.isPermitted("proantitab.*")
|
||||
|| permissionMap.isPermitted("proantitab." + permission);
|
||||
}
|
||||
|
||||
public static boolean hasBypassPermission(Object targetObj) {
|
||||
public static boolean hasBypassPermission(Object targetObj, final boolean isOperator) {
|
||||
|
||||
if (!Reflection.isProxyServer() && Storage.ConfigSections.Settings.HANDLE_THROUGH_PROXY.ENABLED) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return hasPermission(targetObj, "bypass");
|
||||
return hasPermission(targetObj, "bypass", isOperator);
|
||||
}
|
||||
|
||||
public static boolean hasBypassPermission(Object targetObj, String command) {
|
||||
public static boolean hasBypassPermission(
|
||||
final Object targetObj,
|
||||
final String command,
|
||||
final boolean isOperator
|
||||
) {
|
||||
|
||||
if (!Reflection.isProxyServer() && Storage.ConfigSections.Settings.HANDLE_THROUGH_PROXY.ENABLED) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (hasBypassPermission(targetObj)) {
|
||||
if (hasBypassPermission(targetObj, isOperator)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -193,11 +218,15 @@ public class PermissionUtil {
|
||||
return false;
|
||||
}
|
||||
|
||||
return hasPermission(targetObj, "bypass." + command);
|
||||
return hasPermission(targetObj, "bypass." + command, isOperator);
|
||||
}
|
||||
|
||||
public static boolean hasPermissionWithResponse(Object targetObj, String command) {
|
||||
boolean permitted = hasPermission(targetObj, command);
|
||||
public static boolean hasPermissionWithResponse(
|
||||
final Object targetObj,
|
||||
final String command,
|
||||
final boolean isOperator
|
||||
) {
|
||||
boolean permitted = hasPermission(targetObj, command, isOperator);
|
||||
|
||||
if (!permitted && targetObj instanceof CommandSender) {
|
||||
String message = Storage.ConfigSections.Messages.NO_PERMISSION.MESSAGE;
|
||||
|
||||
@@ -4,7 +4,8 @@ import de.rayzs.pat.plugin.system.communication.Communicator;
|
||||
import de.rayzs.pat.api.storage.Storage;
|
||||
import de.rayzs.pat.plugin.logger.Logger;
|
||||
import de.rayzs.pat.utils.StringUtils;
|
||||
import de.rayzs.pat.utils.message.MessageTranslator;
|
||||
import de.rayzs.pat.utils.message.MessageHelper;
|
||||
import de.rayzs.pat.utils.sender.CommandSender;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
@@ -25,8 +26,8 @@ public interface Action {
|
||||
final String displayCommand = StringUtils.replaceTriggers(command, "", "\\", "<", ">", "&");
|
||||
|
||||
|
||||
final List<String> notificationMessage = MessageTranslator.replaceMessageList(
|
||||
Storage.ConfigSections.Messages.NOTIFICATION.ALERT,
|
||||
final String notificationMessage = StringUtils.replace(
|
||||
Storage.ConfigSections.Messages.NOTIFICATION.ALERT.getLines(),
|
||||
"%player%", playerName,
|
||||
"%command%", displayCommand,
|
||||
"%server%", serverName);
|
||||
@@ -36,10 +37,11 @@ public interface Action {
|
||||
if (Storage.SEND_CONSOLE_NOTIFICATION)
|
||||
Logger.info(notificationMessage);
|
||||
|
||||
Storage.NOTIFY_PLAYERS.stream().forEach(tmpUUID -> {
|
||||
Object p = Storage.getLoader().getPlayerObjByUUID(tmpUUID);
|
||||
if (p != null) {
|
||||
MessageTranslator.send(p, notificationMessage);
|
||||
Storage.NOTIFY_PLAYERS.stream().forEach(otherUuid -> {
|
||||
final CommandSender otherSender = CommandSender.from(otherUuid);
|
||||
|
||||
if (otherSender != null) {
|
||||
MessageHelper.sendMessage(otherSender, notificationMessage);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
package de.rayzs.pat.utils.response.action;
|
||||
|
||||
import de.rayzs.pat.utils.response.action.impl.BungeeAction;
|
||||
import de.rayzs.pat.utils.response.action.impl.ModernBukkitAction;
|
||||
import de.rayzs.pat.utils.response.action.impl.OldBukkitAction;
|
||||
import de.rayzs.pat.utils.response.action.impl.BukkitAction;
|
||||
import de.rayzs.pat.utils.response.action.impl.VelocityAction;
|
||||
import de.rayzs.pat.utils.Reflection;
|
||||
import java.util.UUID;
|
||||
@@ -11,8 +10,7 @@ public class ActionHandler {
|
||||
|
||||
private static final Action ACTION = Reflection.isProxyServer() ? Reflection.isVelocityServer()
|
||||
? new VelocityAction() : new BungeeAction()
|
||||
: Reflection.isAtMost(1, 16)
|
||||
? new OldBukkitAction() : new ModernBukkitAction();
|
||||
: new BukkitAction();
|
||||
|
||||
public static void initialize() {}
|
||||
|
||||
|
||||
+24
-23
@@ -2,10 +2,11 @@ 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.MessageTranslator;
|
||||
import de.rayzs.pat.utils.message.MessageHelper;
|
||||
import de.rayzs.pat.utils.message.replacer.PlaceholderReplacer;
|
||||
import de.rayzs.pat.utils.response.ResponseHandler;
|
||||
import de.rayzs.pat.utils.response.action.Action;
|
||||
import de.rayzs.pat.utils.sender.CommandSender;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.potion.PotionEffect;
|
||||
@@ -13,19 +14,19 @@ import org.bukkit.potion.PotionEffectType;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public class ModernBukkitAction implements Action {
|
||||
public class BukkitAction implements Action {
|
||||
|
||||
@Override
|
||||
public void executeConsoleCommand(String action, UUID uuid, String command, String message) {
|
||||
Player player = Bukkit.getPlayer(uuid);
|
||||
final CommandSender sender = CommandSender.from(uuid);
|
||||
message = ResponseHandler.replaceArgsVariables(message, command);
|
||||
|
||||
if (player != null) {
|
||||
message = StringUtils.replace(message, "%player%", player.getName());
|
||||
if (sender != null) {
|
||||
message = StringUtils.replace(message, "%player%", sender.getName());
|
||||
}
|
||||
|
||||
if (message.contains("%")) {
|
||||
message = PlaceholderReplacer.replace(player, message);
|
||||
message = PlaceholderReplacer.applyPlaceholders(sender, message);
|
||||
}
|
||||
|
||||
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), message);
|
||||
@@ -33,37 +34,37 @@ public class ModernBukkitAction implements Action {
|
||||
|
||||
@Override
|
||||
public void executePlayerCommand(String action, UUID uuid, String command, String message) {
|
||||
Player player = Bukkit.getPlayer(uuid);
|
||||
final CommandSender sender = CommandSender.from(uuid);
|
||||
|
||||
if (player == null) {
|
||||
if (sender == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
message = StringUtils.replace(message, "%player%", player.getName());
|
||||
message = StringUtils.replace(message, "%player%", sender.getName());
|
||||
message = ResponseHandler.replaceArgsVariables(message, command);
|
||||
|
||||
if (message.contains("%")) {
|
||||
message = PlaceholderReplacer.replace(player, message);
|
||||
message = PlaceholderReplacer.applyPlaceholders(sender, message);
|
||||
}
|
||||
|
||||
Bukkit.dispatchCommand(player, message);
|
||||
sender.execute(message);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendTitle(String action, UUID uuid, String command, String title, String subTitle, int fadeIn, int stay, int fadeOut) {
|
||||
Player player = Bukkit.getPlayer(uuid);
|
||||
final CommandSender sender = CommandSender.from(uuid);
|
||||
|
||||
if (player == null) {
|
||||
if (sender == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
title = ResponseHandler.replaceArgsVariables(title, command);
|
||||
subTitle = ResponseHandler.replaceArgsVariables(subTitle, command);
|
||||
|
||||
title = StringUtils.replace(title, "&", "§", "%player%", player.getName());
|
||||
subTitle = StringUtils.replace(subTitle, "&", "§", "%player%", player.getName());
|
||||
title = StringUtils.replace(title, "%player%", sender.getName());
|
||||
subTitle = StringUtils.replace(subTitle, "%player%", sender.getName());
|
||||
|
||||
MessageTranslator.sendTitle(player, title, subTitle, fadeIn, stay, fadeOut);
|
||||
MessageHelper.sendTitle(sender, title, subTitle, fadeIn, stay, fadeOut);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -92,14 +93,14 @@ public class ModernBukkitAction implements Action {
|
||||
|
||||
@Override
|
||||
public void playSound(String action, UUID uuid, String soundName, float volume, float pitch) {
|
||||
Player player = Bukkit.getPlayer(uuid);
|
||||
final CommandSender sender = CommandSender.from(uuid);
|
||||
|
||||
if (player == null) {
|
||||
if (sender == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
MessageTranslator.playSound(player, soundName, volume, pitch);
|
||||
MessageHelper.playSound(sender, soundName, volume, pitch);
|
||||
} catch (Exception exception) {
|
||||
Logger.warning("! Failed to read action: " + action);
|
||||
Logger.warning(" > The sound \"" + soundName + "\" could not be found!");
|
||||
@@ -110,15 +111,15 @@ public class ModernBukkitAction implements Action {
|
||||
|
||||
@Override
|
||||
public void sendActionbar(String action, UUID uuid, String command, String message) {
|
||||
Player player = Bukkit.getPlayer(uuid);
|
||||
final CommandSender sender = CommandSender.from(uuid);
|
||||
|
||||
if (player == null) {
|
||||
if (sender == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
message = StringUtils.replace(message, "%player%", player.getName());
|
||||
message = StringUtils.replace(message, "%player%", sender.getName());
|
||||
message = ResponseHandler.replaceArgsVariables(message, command);
|
||||
|
||||
MessageTranslator.sendActionbar(player, message);
|
||||
MessageHelper.sendActionbar(sender, message);
|
||||
}
|
||||
}
|
||||
@@ -2,9 +2,10 @@ 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.MessageTranslator;
|
||||
import de.rayzs.pat.utils.message.MessageHelper;
|
||||
import de.rayzs.pat.utils.response.ResponseHandler;
|
||||
import de.rayzs.pat.utils.response.action.Action;
|
||||
import de.rayzs.pat.utils.sender.CommandSender;
|
||||
import net.md_5.bungee.api.ProxyServer;
|
||||
import net.md_5.bungee.api.connection.ProxiedPlayer;
|
||||
|
||||
@@ -40,19 +41,19 @@ public class BungeeAction implements Action {
|
||||
|
||||
@Override
|
||||
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);
|
||||
final CommandSender sender = CommandSender.from(uuid);
|
||||
|
||||
if (player == null) {
|
||||
if (sender == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
title = ResponseHandler.replaceArgsVariables(title, command);
|
||||
subTitle = ResponseHandler.replaceArgsVariables(subTitle, command);
|
||||
|
||||
title = StringUtils.replace(title, "%player%", player.getName());
|
||||
subTitle = StringUtils.replace(subTitle, "%player%", player.getName());
|
||||
title = StringUtils.replace(title, "%player%", sender.getName());
|
||||
subTitle = StringUtils.replace(subTitle, "%player%", sender.getName());
|
||||
|
||||
MessageTranslator.sendTitle(player, title, subTitle, fadeIn, stay, fadeOut);
|
||||
MessageHelper.sendTitle(sender, title, subTitle, fadeIn, stay, fadeOut);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -61,14 +62,14 @@ public class BungeeAction implements Action {
|
||||
|
||||
@Override
|
||||
public void playSound(String action, UUID uuid, String soundName, float volume, float pitch) {
|
||||
ProxiedPlayer player = ProxyServer.getInstance().getPlayer(uuid);
|
||||
final CommandSender sender = CommandSender.from(uuid);
|
||||
|
||||
if (player == null) {
|
||||
if (sender == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
MessageTranslator.playSound(player, soundName, volume, pitch);
|
||||
MessageHelper.playSound(sender, soundName, volume, pitch);
|
||||
} catch (Exception exception) {
|
||||
Logger.warning("! Failed to read action: " + action);
|
||||
Logger.warning(" > The sound \"" + soundName + "\" could not be found!");
|
||||
@@ -79,14 +80,14 @@ public class BungeeAction implements Action {
|
||||
|
||||
@Override
|
||||
public void sendActionbar(String action, UUID uuid, String command, String message) {
|
||||
ProxiedPlayer player = ProxyServer.getInstance().getPlayer(uuid);
|
||||
final CommandSender sender = CommandSender.from(uuid);
|
||||
|
||||
if (player == null) {
|
||||
if (sender == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
message = StringUtils.replace(message, "%player%", player.getName());
|
||||
message = StringUtils.replace(message, "%player%", sender.getName());
|
||||
message = ResponseHandler.replaceArgsVariables(message, command);
|
||||
MessageTranslator.sendActionbar(player, message);
|
||||
MessageHelper.sendActionbar(sender, message);
|
||||
}
|
||||
}
|
||||
@@ -1,156 +0,0 @@
|
||||
package de.rayzs.pat.utils.response.action.impl;
|
||||
|
||||
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;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.potion.PotionEffect;
|
||||
import org.bukkit.potion.PotionEffectType;
|
||||
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
|
||||
public class OldBukkitAction implements Action {
|
||||
|
||||
private String versionPackage = null;
|
||||
|
||||
@Override
|
||||
public void executeConsoleCommand(String action, UUID uuid, String command, String message) {
|
||||
Player player = Bukkit.getPlayer(uuid);
|
||||
message = ResponseHandler.replaceArgsVariables(message, command);
|
||||
|
||||
if(player != null) {
|
||||
message = StringUtils.replace(message, "%player%", player.getName());
|
||||
}
|
||||
|
||||
if (message.contains("%")) {
|
||||
message = PlaceholderReplacer.replace(player, message);
|
||||
}
|
||||
|
||||
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), message);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void executePlayerCommand(String action, UUID uuid, String command, String message) {
|
||||
Player player = Bukkit.getPlayer(uuid);
|
||||
|
||||
if (player == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
message = ResponseHandler.replaceArgsVariables(message, command);
|
||||
message = StringUtils.replace(message, "%player%", player.getName());
|
||||
|
||||
if (message.contains("%")) {
|
||||
message = PlaceholderReplacer.replace(player, message);
|
||||
}
|
||||
|
||||
Bukkit.dispatchCommand(player, message);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendTitle(String action, UUID uuid, String command, String title, String subTitle, int fadeIn, int stay, int fadeOut) {
|
||||
Player player = Bukkit.getPlayer(uuid);
|
||||
|
||||
if (player == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
title = StringUtils.replace(title, "&", "§", "%player%", player.getName());
|
||||
subTitle = StringUtils.replace(title, "&", "§", "%player%", player.getName());
|
||||
|
||||
title = ResponseHandler.replaceArgsVariables(title, command);
|
||||
subTitle = ResponseHandler.replaceArgsVariables(subTitle, command);
|
||||
|
||||
title = PlaceholderReplacer.replace(player, title);
|
||||
subTitle = PlaceholderReplacer.replace(player, subTitle);
|
||||
|
||||
player.sendTitle(title, subTitle);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addPotionEffect(String action, UUID uuid, String potionEffectTypeName, int duration, int amplifier) {
|
||||
Player player = Bukkit.getPlayer(uuid);
|
||||
|
||||
if (player == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
PotionEffectType potionEffectType = null;
|
||||
try {
|
||||
potionEffectType = PotionEffectType.getByName(potionEffectTypeName);
|
||||
} catch (Exception ignored) { }
|
||||
|
||||
if (potionEffectType == null) {
|
||||
Logger.warning("! Failed to read action: " + action);
|
||||
Logger.warning(" > The effect \"" + potionEffectTypeName + "\" could not be found!");
|
||||
Logger.warning(" > Here's an example of an existing effect:");
|
||||
Logger.warning(" > BLINDNESS, REGENERATION");
|
||||
return;
|
||||
}
|
||||
|
||||
player.addPotionEffect(new PotionEffect(potionEffectType, duration, amplifier));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void playSound(String action, UUID uuid, String soundName, float volume, float pitch) {
|
||||
Player player = Bukkit.getPlayer(uuid);
|
||||
|
||||
if(player == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
Sound sound = Sound.valueOf(soundName);
|
||||
player.playSound(player.getLocation(), sound, volume, pitch);
|
||||
} catch (Exception exception) {
|
||||
Logger.warning("! Failed to read action: " + action);
|
||||
Logger.warning(" > The sound \"" + soundName + "\" could not be found!");
|
||||
Logger.warning(" > Here's an example of an existing sound effect:");
|
||||
Logger.warning(" > ENTITY_ENDER_DRAGON_GROWL");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendActionbar(String action, UUID uuid, String command, String message) {
|
||||
Player player = Bukkit.getPlayer(uuid);
|
||||
|
||||
if (player == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
message = ResponseHandler.replaceArgsVariables(message, command);
|
||||
message = StringUtils.replace(message, "&", "§", "%player%", player.getName());
|
||||
message = PlaceholderReplacer.replace(player, message);
|
||||
|
||||
try {
|
||||
if (versionPackage == null) {
|
||||
versionPackage = Reflection.getVersionPackageName();
|
||||
}
|
||||
|
||||
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\":\"" + 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);
|
||||
|
||||
} catch (ClassNotFoundException
|
||||
| NoSuchMethodException
|
||||
| IllegalAccessException
|
||||
| InvocationTargetException
|
||||
| NoSuchFieldException
|
||||
| InstantiationException exception) {
|
||||
|
||||
Logger.warning("! Failed to run action: " + action);
|
||||
Logger.warning(" > Actionbars are not supported in this server version!");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,12 @@
|
||||
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.message.MessageHelper;
|
||||
import de.rayzs.pat.utils.response.ResponseHandler;
|
||||
import de.rayzs.pat.utils.response.action.Action;
|
||||
import com.velocitypowered.api.proxy.Player;
|
||||
import de.rayzs.pat.plugin.VelocityLoader;
|
||||
import de.rayzs.pat.utils.StringUtils;
|
||||
import de.rayzs.pat.utils.sender.CommandSender;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
@@ -14,49 +14,48 @@ public class VelocityAction implements Action {
|
||||
|
||||
@Override
|
||||
public void executeConsoleCommand(String action, UUID uuid, String command, String message) {
|
||||
Optional<Player> optPlayer = VelocityLoader.getServer().getPlayer(uuid);
|
||||
final CommandSender sender = CommandSender.from(uuid);
|
||||
message = ResponseHandler.replaceArgsVariables(message, command);
|
||||
|
||||
if (optPlayer.isPresent()) {
|
||||
message = message.replace("%player%", optPlayer.get().getUsername());
|
||||
if (sender != null && sender.isPlayer()) {
|
||||
message = message.replace("%player%", sender.getName());
|
||||
}
|
||||
|
||||
VelocityLoader.getServer().getCommandManager().executeAsync(VelocityLoader.getServer().getConsoleCommandSource(), message);
|
||||
VelocityLoader.getServer().getCommandManager().executeAsync(
|
||||
VelocityLoader.getServer().getConsoleCommandSource(),
|
||||
message
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void executePlayerCommand(String action, UUID uuid, String command, String message) {
|
||||
Optional<Player> optPlayer = VelocityLoader.getServer().getPlayer(uuid);
|
||||
final CommandSender sender = CommandSender.from(uuid);
|
||||
|
||||
if (optPlayer.isEmpty()) {
|
||||
if (sender == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
Player player = optPlayer.get();
|
||||
|
||||
message = message.replace("%player%", player.getUsername());
|
||||
message = message.replace("%player%", sender.getName());
|
||||
message = ResponseHandler.replaceArgsVariables(message, command);
|
||||
|
||||
VelocityLoader.getServer().getCommandManager().executeAsync(player, message);
|
||||
sender.execute(message);
|
||||
}
|
||||
|
||||
@Override
|
||||
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);
|
||||
final CommandSender sender = CommandSender.from(uuid);
|
||||
|
||||
if (optPlayer.isEmpty()) {
|
||||
if (sender == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
Player player = optPlayer.get();
|
||||
|
||||
title = ResponseHandler.replaceArgsVariables(title, command);
|
||||
subTitle = ResponseHandler.replaceArgsVariables(subTitle, command);
|
||||
|
||||
title = StringUtils.replace(title, "%player%", player.getUsername());
|
||||
subTitle = StringUtils.replace(subTitle, "%player%", player.getUsername());
|
||||
title = StringUtils.replace(title, "%player%", sender.getName());
|
||||
subTitle = StringUtils.replace(subTitle, "%player%", sender.getName());
|
||||
|
||||
MessageTranslator.sendTitle(player, title, subTitle, fadeIn, stay, fadeOut);
|
||||
MessageHelper.sendTitle(sender, title, subTitle, fadeIn, stay, fadeOut);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -65,16 +64,14 @@ public class VelocityAction implements Action {
|
||||
|
||||
@Override
|
||||
public void playSound(String action, UUID uuid, String soundName, float volume, float pitch) {
|
||||
Optional<Player> optPlayer = VelocityLoader.getServer().getPlayer(uuid);
|
||||
final CommandSender sender = CommandSender.from(uuid);
|
||||
|
||||
if (optPlayer.isEmpty()) {
|
||||
if (sender == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
Player player = optPlayer.get();
|
||||
|
||||
try {
|
||||
MessageTranslator.playSound(player, soundName, volume, pitch);
|
||||
MessageHelper.playSound(sender, soundName, volume, pitch);
|
||||
} catch (Exception exception) {
|
||||
Logger.warning("! Failed to read action: " + action);
|
||||
Logger.warning(" > The sound \"" + soundName + "\" could not be found!");
|
||||
@@ -85,17 +82,15 @@ public class VelocityAction implements Action {
|
||||
|
||||
@Override
|
||||
public void sendActionbar(String action, UUID uuid, String command, String message) {
|
||||
Optional<Player> optPlayer = VelocityLoader.getServer().getPlayer(uuid);
|
||||
final CommandSender sender = CommandSender.from(uuid);
|
||||
|
||||
if (optPlayer.isEmpty()) {
|
||||
if (sender == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
Player player = optPlayer.get();
|
||||
|
||||
message = ResponseHandler.replaceArgsVariables(message, command);
|
||||
message = StringUtils.replace(message, "%player%", player.getUsername());
|
||||
message = StringUtils.replace(message, "%player%", sender.getName());
|
||||
|
||||
MessageTranslator.sendActionbar(player, message);
|
||||
MessageHelper.sendActionbar(sender, message);
|
||||
}
|
||||
}
|
||||
Loaded 100 of 113 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user