Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
beee98d5d6 | ||
|
|
4d270891be | ||
|
|
7e9352661e | ||
|
|
3f47d56bed | ||
|
|
1d0cac3a2b | ||
|
|
64da26ea9f | ||
|
|
4e53b6d5b0 | ||
|
|
3b4ede3c22 | ||
|
|
59aade10a7 | ||
|
|
cd5bf7281b | ||
|
|
cd5bd87835 | ||
|
|
9384277901 | ||
|
|
3b43e647a4 | ||
|
|
f28ad44e62 | ||
|
|
0baec19db1 | ||
|
|
8ea83b3fab | ||
|
|
7eaadd9ad6 | ||
|
|
506985c9d1 | ||
|
|
3fb0181ad7 | ||
|
|
fc56bb6017 | ||
|
|
d9c60f45a4 | ||
|
|
342060b86e | ||
|
|
b5b30bd9d8 | ||
|
|
55eaac0bd4 | ||
|
|
7583aeade7 | ||
|
|
4be3712082 | ||
|
|
c1e28709ac | ||
|
|
f0965efe73 | ||
|
|
529cdd1e04 | ||
|
|
ce867d4065 | ||
|
|
1eefb78157 | ||
|
|
ff0c8d2a8d | ||
|
|
5a250d854d | ||
|
|
caacf0d8ae | ||
|
|
0f7d4a0548 | ||
|
|
4529f74f0a | ||
|
|
1eaf32983a | ||
|
|
24b0682e8b | ||
|
|
cbf3326de6 | ||
|
|
c4ae9198a4 | ||
|
|
c01798f2e2 | ||
|
|
5de8dbe98a | ||
|
|
00eecd1841 | ||
|
|
54783d657e | ||
|
|
e17b618b18 | ||
|
|
3c8371fe28 | ||
|
|
aafb677d01 | ||
|
|
3a945560a8 | ||
|
|
516156624e | ||
|
|
b6e37edfa3 | ||
|
|
6772d26747 | ||
|
|
145ff70e3d | ||
|
|
cd57c3d37f | ||
|
|
80413bab3a | ||
|
|
319e70696e | ||
|
|
dfda46bcb7 | ||
|
|
848a44c5da | ||
|
|
48a0666c79 | ||
|
|
d828a747db | ||
|
|
7ff7eb20b9 | ||
|
|
bae9d14ae5 | ||
|
|
9b2fc7da65 | ||
|
|
163686cf77 | ||
|
|
895fbcf07e | ||
|
|
004131ddc3 | ||
|
|
e59d116918 | ||
|
|
4ee9d4525a | ||
|
|
3d1672d4ef | ||
|
|
91fc9ee913 | ||
|
|
15604b0ec4 | ||
|
|
8108b949f7 | ||
|
|
aabaa2a332 | ||
|
|
0896a7c63e | ||
|
|
b4b6b19ec3 | ||
|
|
93289f5b24 | ||
|
|
5810652007 | ||
|
|
1e92763497 | ||
|
|
a699c807fd | ||
|
|
7ef48f4202 | ||
|
|
7dc8042de7 | ||
|
|
9d13bd482c | ||
|
|
306ab41f08 | ||
|
|
aea4950398 | ||
|
|
042c27c088 | ||
|
|
b699d2ffad | ||
|
|
0400b0beaf | ||
|
|
88030f82b6 | ||
|
|
e8f8bd5af4 | ||
|
|
bfbcaf1598 | ||
|
|
ffc57dd69a | ||
|
|
07fa5c256b | ||
|
|
c07357b89b | ||
|
|
629d492fad | ||
|
|
693ca51315 | ||
|
|
f65444cfe9 | ||
|
|
464b887ed5 | ||
|
|
1bdf20feb0 | ||
|
|
db89bfb5b5 | ||
|
|
efe2dd22e9 | ||
|
|
144be87448 | ||
|
|
217e7316b9 | ||
|
|
9bf2900bb5 | ||
|
|
23640b1772 | ||
|
|
fecf35b3a9 | ||
|
|
8068fe6a7f | ||
|
|
2f21538c76 | ||
|
|
340cad0b2f | ||
|
|
0c51c73f31 | ||
|
|
717db94dc2 | ||
|
|
51e6708fcb | ||
|
|
a6f22d090a | ||
|
|
979f39a171 | ||
|
|
0f057720b8 | ||
|
|
a4eb8bd8fe | ||
|
|
38a8f24c9c | ||
|
|
82de0cf4dc | ||
|
|
13fcea5b57 | ||
|
|
4292871294 | ||
|
|
827c7f92ae | ||
|
|
bcd28eddca | ||
|
|
4d873146dd | ||
|
|
95bcd6ceff | ||
|
|
b596873300 | ||
|
|
0425336f67 | ||
|
|
1a27bcbec2 | ||
|
|
17761fb649 | ||
|
|
9b287c5f83 | ||
|
|
ce44cd7297 | ||
|
|
4ee5a69a28 | ||
|
|
e7f19acc7f | ||
|
|
9d557260ae | ||
|
|
6bbf12182a | ||
|
|
54a582d3eb | ||
|
|
0cbf4edbd1 | ||
|
|
0d4d8a7bf1 | ||
|
|
332bed1bcb | ||
|
|
ecbcbbab12 | ||
|
|
e143dd14bf | ||
|
|
5234812a49 | ||
|
|
ec770ddd15 | ||
|
|
fbe0538a71 | ||
|
|
fb1027f4a8 | ||
|
|
97e6ad4245 | ||
|
|
2ef74e9166 | ||
|
|
05ce1fb059 | ||
|
|
3dcd31807f | ||
|
|
d026aeea41 | ||
|
|
5ab5ce9e95 | ||
|
|
cf5b5feb9c | ||
|
|
d579eb8e4a | ||
|
|
fec31fe4bb | ||
|
|
b6d25866c1 | ||
|
|
58fe4a2aeb | ||
|
|
37e9359b1f | ||
|
|
78adf1c9d0 | ||
|
|
19ad0c362c | ||
|
|
3785534b0e | ||
|
|
8e8fa85ec3 | ||
|
|
ad340f239e | ||
|
|
3e53c370ec | ||
|
|
dff6d30e78 | ||
|
|
275a7bb773 | ||
|
|
26ec7ec819 | ||
|
|
592981a678 | ||
|
|
fbe286ded5 | ||
|
|
7780e8a406 | ||
|
|
b70bc7ee51 | ||
|
|
57baf6675a | ||
|
|
8998498383 | ||
|
|
94a7c549d7 | ||
|
|
988b0e8080 | ||
|
|
22e51bf668 | ||
|
|
1f70b0048e | ||
|
|
e18ef8a927 | ||
|
|
86078e7869 | ||
|
|
212bf7174e | ||
|
|
284396ea28 | ||
|
|
0bd697cbd4 | ||
|
|
72be8e243e | ||
|
|
445fb84a40 | ||
|
|
1ebf5b4edb | ||
|
|
8869bc88d1 | ||
|
|
aae9708647 | ||
|
|
e9736c4031 | ||
|
|
28199b5e0b | ||
|
|
fe743d8302 | ||
|
|
2f08ea9509 | ||
|
|
854dcca6ee | ||
|
|
9072db7c1b | ||
|
|
2b0ca413b4 | ||
|
|
0f1ce81a31 | ||
|
|
1b714f25b8 | ||
|
|
c03b8b4810 | ||
|
|
5f0744dd0e | ||
|
|
fe1676620f | ||
|
|
ec5b2fe509 | ||
|
|
3efe63bb49 | ||
|
|
48a1dfbc26 | ||
|
|
0a604cf83d | ||
|
|
4bc657ab63 | ||
|
|
165e8f4474 | ||
|
|
a4ca8611f4 | ||
|
|
0f354e2dd9 | ||
|
|
c9bd62dc47 | ||
|
|
f8304aeb28 | ||
|
|
1fdf1312a0 | ||
|
|
295a7c406c | ||
|
|
78fbeed7d2 | ||
|
|
446127f7bb | ||
|
|
9dd172447c | ||
|
|
38cb530993 | ||
|
|
6bfd45727f | ||
|
|
9f69f078fc | ||
|
|
2050c6c044 | ||
|
|
26d57460d5 |
No files matched your search
@@ -0,0 +1,30 @@
|
||||
name: Build v2 for PR
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: [ v2 ]
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: Build
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
name: Checkout repo
|
||||
|
||||
- name: Set up JDK 17 (LTS)
|
||||
uses: actions/setup-java@v2
|
||||
with:
|
||||
java-version: '17'
|
||||
distribution: 'adopt'
|
||||
cache: maven
|
||||
|
||||
- name: Build with Maven
|
||||
run: mvn install --file pom.xml
|
||||
|
||||
- uses: actions/upload-artifact@v2
|
||||
name: Upload Artifact
|
||||
with:
|
||||
name: ChatItem.jar
|
||||
path: target/ChatItem-*.jar
|
||||
@@ -0,0 +1,36 @@
|
||||
name: Build v2
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ v2 ]
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: Build
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
name: Checkout repo
|
||||
|
||||
- name: Set up JDK 17 (LTS)
|
||||
uses: actions/setup-java@v2
|
||||
with:
|
||||
java-version: '17'
|
||||
distribution: 'adopt'
|
||||
cache: maven
|
||||
|
||||
- name: Build with Maven
|
||||
run: mvn install --file pom.xml
|
||||
|
||||
- uses: actions/upload-artifact@v2
|
||||
name: Upload Artifact
|
||||
with:
|
||||
name: ChatItem.jar
|
||||
path: target/ChatItem-*.jar
|
||||
- name: Send file README.md to discord channel
|
||||
uses: sinshutu/upload-to-discord@master
|
||||
env:
|
||||
DISCORD_WEBHOOK: ${{ secrets.DISCORD_WEBHOOK }}
|
||||
with:
|
||||
args: target/ChatItem-*.jar
|
||||
@@ -6,17 +6,13 @@
|
||||
|
||||
<groupId>me.dadus33</groupId>
|
||||
<artifactId>chatitem</artifactId>
|
||||
<version>1.4</version>
|
||||
<version>2.4.3</version>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>dmulloy2-repo</id>
|
||||
<url>http://repo.dmulloy2.net/nexus/repository/public/</url>
|
||||
</repository>
|
||||
<repository>
|
||||
<id>Bungeecord</id>
|
||||
<url>https://repo.md-5.net/content/groups/public/</url>
|
||||
@@ -29,14 +25,34 @@
|
||||
<id>sonatype</id>
|
||||
<url>https://oss.sonatype.org/content/repositories/snapshots/</url>
|
||||
</repository>
|
||||
<repository>
|
||||
<id>jitpack.io</id>
|
||||
<url>https://jitpack.io</url>
|
||||
</repository>
|
||||
<repository>
|
||||
<id>lang-utils-repo</id>
|
||||
<url>https://raw.github.com/MascusJeoraly/LanguageUtils/mvn-repo/</url>
|
||||
</repository>
|
||||
<repository>
|
||||
<id>protocollib-repo</id>
|
||||
<url>https://repo.dmulloy2.net/nexus/repository/public/</url>
|
||||
</repository>
|
||||
<repository>
|
||||
<id>viaversion-repo</id>
|
||||
<url>https://repo.viaversion.com</url>
|
||||
</repository>
|
||||
<repository>
|
||||
<id>jitpack.io</id>
|
||||
<url>https://jitpack.io</url>
|
||||
</repository>
|
||||
<id>elikill-repo</id>
|
||||
<url>https://repo.eliapp.fr:8081/repository/internal/</url>
|
||||
</repository>
|
||||
<repository>
|
||||
<id>dv8tion</id>
|
||||
<url>https://m2.dv8tion.net/releases</url>
|
||||
</repository>
|
||||
<repository>
|
||||
<id>Scarsz-Nexus</id>
|
||||
<url>https://nexus.scarsz.me/content/groups/public/</url>
|
||||
</repository>
|
||||
</repositories>
|
||||
|
||||
|
||||
@@ -55,26 +71,33 @@
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.comphenix.protocol</groupId>
|
||||
<artifactId>ProtocolLib</artifactId>
|
||||
<version>4.7.0</version>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-api</artifactId>
|
||||
<version>2.17.2</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-core</artifactId>
|
||||
<version>2.17.2</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.code.gson</groupId>
|
||||
<artifactId>gson</artifactId>
|
||||
<version>2.7</version>
|
||||
<version>2.9.0</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.meowj</groupId>
|
||||
<artifactId>LangUtils</artifactId>
|
||||
<version>1.9</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-api</artifactId>
|
||||
<version>2.14.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-core</artifactId>
|
||||
<version>2.14.1</version>
|
||||
<groupId>com.comphenix.protocol</groupId>
|
||||
<artifactId>ProtocolLib</artifactId>
|
||||
<version>5.0.0-SNAPSHOT</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@@ -84,23 +107,53 @@
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.github.ProtocolSupport</groupId>
|
||||
<groupId>io.shevchik</groupId>
|
||||
<artifactId>ProtocolSupport</artifactId>
|
||||
<version>f34959c331</version>
|
||||
<version>1.18.2-1-dev</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.netty</groupId>
|
||||
<artifactId>netty-all</artifactId>
|
||||
<version>4.1.53.Final</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.github.GeyserMC</groupId>
|
||||
<artifactId>opennbt</artifactId>
|
||||
<version>1.4</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.netty</groupId>
|
||||
<artifactId>netty-all</artifactId>
|
||||
<version>4.1.53.Final</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>dev.majek</groupId>
|
||||
<artifactId>HexNicks</artifactId>
|
||||
<version>2.2.1</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.kyori</groupId>
|
||||
<artifactId>adventure-api</artifactId>
|
||||
<version>4.11.0</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.kyori</groupId>
|
||||
<artifactId>adventure-platform-bungeecord</artifactId>
|
||||
<version>4.1.0</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.discordsrv</groupId>
|
||||
<artifactId>discordsrv</artifactId>
|
||||
<version>1.25.1</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.willfp</groupId>
|
||||
<artifactId>EcoEnchants</artifactId>
|
||||
<version>8.57.2</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
@@ -117,29 +170,20 @@
|
||||
</resource>
|
||||
</resources>
|
||||
|
||||
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.5.1</version>
|
||||
<version>3.10.1</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<version>3.0.2</version>
|
||||
<configuration>
|
||||
<outputDirectory>${dir}</outputDirectory>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-shade-plugin</artifactId>
|
||||
<version>3.2.4</version>
|
||||
<version>3.3.0</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
@@ -149,23 +193,41 @@
|
||||
<configuration>
|
||||
<minimizeJar>true</minimizeJar>
|
||||
<relocations>
|
||||
<relocation>
|
||||
<pattern>org.bstats</pattern>
|
||||
<shadedPattern>me.dadus33.libs.bstats</shadedPattern>
|
||||
</relocation>
|
||||
<relocation>
|
||||
<pattern>com.google.gson</pattern>
|
||||
<shadedPattern>me.dadus33.libs.gson</shadedPattern>
|
||||
</relocation>
|
||||
<relocation>
|
||||
<pattern>com.github.GeyserMC</pattern>
|
||||
<shadedPattern>me.dadus33.libs.opennbt</shadedPattern>
|
||||
<pattern>net.kyori.adventure.text.serializer.bungeecord</pattern>
|
||||
<shadedPattern>me.dadus33.libs.kyori.serializer.bungeecord</shadedPattern>
|
||||
</relocation>
|
||||
</relocations>
|
||||
<filters>
|
||||
<filter>
|
||||
<artifact>*</artifact>
|
||||
<excludes>
|
||||
<exclude>net.kyori:examination-api:**</exclude>
|
||||
<exclude>net.kyori:examination-string:**</exclude>
|
||||
<exclude>net.kyori:adventure-platform-api:**</exclude>
|
||||
<exclude>net.kyori:adventure-text-serializer-legacy:**</exclude>
|
||||
<exclude>net.kyori:adventure-text-serializer-gson:**</exclude>
|
||||
<exclude>net.kyori:adventure-platform-facet:**</exclude>
|
||||
<exclude>net.kyori:adventure-nbt:**</exclude>
|
||||
</excludes>
|
||||
</filter>
|
||||
</filters>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<version>3.2.2</version>
|
||||
<configuration>
|
||||
<outputDirectory>${export_dir}</outputDirectory>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
||||
@@ -1,147 +1,199 @@
|
||||
package me.dadus33.chatitem;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Server;
|
||||
import com.google.common.base.Strings;
|
||||
import me.dadus33.chatitem.chatmanager.ChatManager;
|
||||
import me.dadus33.chatitem.chatmanager.v1.PacketEditingChatManager;
|
||||
import me.dadus33.chatitem.chatmanager.v2.ChatListenerChatManager;
|
||||
import me.dadus33.chatitem.commands.CIReloadCommand;
|
||||
import me.dadus33.chatitem.commands.ChatItemCommand;
|
||||
import me.dadus33.chatitem.filters.Log4jFilter;
|
||||
import me.dadus33.chatitem.itemnamer.NamerManager;
|
||||
import me.dadus33.chatitem.listeners.InventoryListener;
|
||||
import me.dadus33.chatitem.listeners.JoinListener;
|
||||
import me.dadus33.chatitem.playernamer.PlayerNamerManager;
|
||||
import me.dadus33.chatitem.utils.SemVer;
|
||||
import me.dadus33.chatitem.utils.Storage;
|
||||
import me.dadus33.chatitem.utils.Utils;
|
||||
import me.dadus33.chatitem.utils.Version;
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.command.CommandExecutor;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.plugin.ServicePriority;
|
||||
import org.bukkit.command.PluginCommand;
|
||||
import org.bukkit.command.TabCompleter;
|
||||
import org.bukkit.plugin.PluginManager;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
|
||||
import me.dadus33.chatitem.api.APIImplementation;
|
||||
import me.dadus33.chatitem.api.ChatItemAPI;
|
||||
import me.dadus33.chatitem.commands.CIReload;
|
||||
import me.dadus33.chatitem.filters.Log4jFilter;
|
||||
import me.dadus33.chatitem.json.JSONManipulator;
|
||||
import me.dadus33.chatitem.json.JSONManipulatorCurrent;
|
||||
import me.dadus33.chatitem.listeners.ChatEventListener;
|
||||
import me.dadus33.chatitem.listeners.ChatPacketListenerV2;
|
||||
import me.dadus33.chatitem.listeners.ChatPacketValidatorV2;
|
||||
import me.dadus33.chatitem.packets.ChatItemPacketManager;
|
||||
import me.dadus33.chatitem.playerversion.IPlayerVersion;
|
||||
import me.dadus33.chatitem.playerversion.hooks.DefaultVersionHook;
|
||||
import me.dadus33.chatitem.playerversion.hooks.ProtocolSupportHook;
|
||||
import me.dadus33.chatitem.playerversion.hooks.ViaVersionHook;
|
||||
import me.dadus33.chatitem.utils.Storage;
|
||||
import java.util.*;
|
||||
|
||||
public class ChatItem extends JavaPlugin {
|
||||
|
||||
public final static int CFG_VER = 12;
|
||||
public final static int CFG_VER = 13;
|
||||
public static boolean discordSrvSupport = false, ecoEnchantsSupport = false, hasNewVersion = false;
|
||||
private static ChatItem instance;
|
||||
private ChatEventListener chatEventListener;
|
||||
private final String brandChannelName = Version.getVersion().isNewerOrEquals(Version.V1_13) ? "minecraft:brand" : "MC|Brand";
|
||||
private final List<ChatManager> chatManager = new ArrayList<>();
|
||||
private Log4jFilter filter;
|
||||
private Storage storage;
|
||||
private static boolean baseComponentAvailable = true;
|
||||
private IPlayerVersion playerVersionAdapter;
|
||||
private ChatItemPacketManager packetManager;
|
||||
|
||||
public static void reload(CommandSender sender) {
|
||||
ChatItem obj = getInstance();
|
||||
//obj.pm = ProtocolLibrary.getProtocolManager();
|
||||
obj.saveDefaultConfig();
|
||||
obj.reloadConfig();
|
||||
obj.storage = new Storage(obj.getConfig());
|
||||
//obj.packetListener.setStorage(obj.storage);
|
||||
//obj.packetValidator.setStorage(obj.storage);
|
||||
obj.chatEventListener.setStorage(obj.storage);
|
||||
obj.filter.setStorage(obj.storage);
|
||||
APIImplementation api = (APIImplementation) Bukkit.getServicesManager().getRegistration(ChatItemAPI.class).getProvider();
|
||||
api.setStorage(obj.storage);
|
||||
api.updateLogger();
|
||||
if (!obj.storage.RELOAD_MESSAGE.isEmpty())
|
||||
sender.sendMessage(obj.storage.RELOAD_MESSAGE);
|
||||
ChatItem pl = getInstance();
|
||||
if (pl.getConfig().getKeys(false).isEmpty())
|
||||
pl.saveDefaultConfig();
|
||||
pl.reloadConfig();
|
||||
String oldChatManager = pl.storage.MANAGER;
|
||||
pl.storage = new Storage(pl.getConfig());
|
||||
pl.chooseManagers();
|
||||
pl.filter.setStorage(pl.storage);
|
||||
if (!pl.storage.RELOAD_MESSAGE.isEmpty())
|
||||
sender.sendMessage(pl.storage.RELOAD_MESSAGE);
|
||||
if (!oldChatManager.equalsIgnoreCase(pl.storage.MANAGER))
|
||||
sender.sendMessage(ChatColor.GOLD + "Changing the manager with command reloading CAN produce issue. It's mostly suggested to restart after finding the better manager for you.");
|
||||
}
|
||||
|
||||
public static ChatItem getInstance() {
|
||||
return instance;
|
||||
}
|
||||
|
||||
public static void debug(String msg) {
|
||||
if (getInstance().getStorage().DEBUG)
|
||||
getInstance().getLogger().info("[Debug] " + msg.replace(ChatManager.SEPARATOR, 'S'));
|
||||
}
|
||||
|
||||
private void chooseManagers() {
|
||||
this.chatManager.forEach((cm) -> cm.unload(this));
|
||||
this.chatManager.clear();
|
||||
PluginManager pm = getServer().getPluginManager();
|
||||
String managerName = getStorage().MANAGER;
|
||||
|
||||
switch (managerName.toLowerCase(Locale.ROOT)) {
|
||||
case "both":
|
||||
this.chatManager.add(new PacketEditingChatManager(this));
|
||||
this.chatManager.add(new ChatListenerChatManager(this));
|
||||
getLogger().info("Manager automatically chosen: " + getVisualChatManagers());
|
||||
break;
|
||||
case "auto":
|
||||
if (getPluginThatRequirePacket().stream().map(pm::getPlugin).anyMatch(Objects::nonNull) && Version.getVersion().isNewerThan(Version.V1_7))
|
||||
this.chatManager.add(new PacketEditingChatManager(this));
|
||||
else
|
||||
this.chatManager.add(new ChatListenerChatManager(this));
|
||||
getLogger().info("Manager automatically chosen: " + getVisualChatManagers());
|
||||
break;
|
||||
case "packet":
|
||||
this.chatManager.add(new PacketEditingChatManager(this));
|
||||
getLogger().info("Manager chosen: " + getVisualChatManagers());
|
||||
break;
|
||||
case "chat":
|
||||
this.chatManager.add(new ChatListenerChatManager(this));
|
||||
getLogger().info("Manager chosen: " + getVisualChatManagers());
|
||||
break;
|
||||
default:
|
||||
getLogger().severe("----- WARN -----");
|
||||
getLogger().severe("Failed to find manager: " + managerName + ".");
|
||||
getLogger().severe("Please reset your config and/or check wiki for more information");
|
||||
getLogger().severe("Using default manager: chat.");
|
||||
getLogger().severe("----- WARN -----");
|
||||
this.chatManager.add(new ChatListenerChatManager(this));
|
||||
break;
|
||||
}
|
||||
|
||||
this.chatManager.forEach((cm) -> cm.load(this, getStorage()));
|
||||
|
||||
NamerManager.load(this);
|
||||
PlayerNamerManager.load(this);
|
||||
}
|
||||
|
||||
private List<String> getPluginThatRequirePacket() {
|
||||
return Arrays.asList("DeluxeChat", "HexNicks", "VentureChat");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
//Save the instance (we're basically a singleton)
|
||||
instance = this;
|
||||
|
||||
//Load ProtocolManager
|
||||
//pm = ProtocolLibrary.getProtocolManager();
|
||||
getLogger().info("Detected server version: " + Version.getVersion().name().toLowerCase());
|
||||
|
||||
//Load config
|
||||
saveDefaultConfig();
|
||||
storage = new Storage(getConfig());
|
||||
|
||||
//Load API
|
||||
APIImplementation api = new APIImplementation(storage);
|
||||
Bukkit.getServicesManager().register(ChatItemAPI.class, api, this, ServicePriority.Highest);
|
||||
|
||||
//Packet listeners
|
||||
packetManager = new ChatItemPacketManager(this);
|
||||
packetManager.getPacketManager().addHandler(new ChatPacketValidatorV2(storage));
|
||||
packetManager.getPacketManager().addHandler(new ChatPacketListenerV2(storage));
|
||||
/*packetListener = new ChatPacketListener(this, ListenerPriority.LOW, storage, PacketType.Play.Server.CHAT);
|
||||
packetValidator = new ChatPacketValidator(this, ListenerPriority.LOWEST, storage, PacketType.Play.Server.CHAT);
|
||||
pm.addPacketListener(packetValidator);
|
||||
pm.addPacketListener(packetListener);*/
|
||||
|
||||
if(Bukkit.getPluginManager().getPlugin("ViaVersion") != null){
|
||||
playerVersionAdapter = new ViaVersionHook();
|
||||
} else if(Bukkit.getPluginManager().getPlugin("ProtocolSupport") != null){
|
||||
playerVersionAdapter = new ProtocolSupportHook();
|
||||
} else {
|
||||
playerVersionAdapter = new DefaultVersionHook();
|
||||
}
|
||||
|
||||
//We halt the use of this system for now, until we can solve the infamous getProtocolVersion issue
|
||||
//Till then, users of both ViaVersion and ProtocolSupport should do just fine
|
||||
/*if(!protocolSupport && !viaVersion) {
|
||||
//We only implement our own way of getting protocol versions if we have no other choice
|
||||
pm.addPacketListener(new HandshakeListener(this, ListenerPriority.MONITOR, PacketType.Handshake.Client.SET_PROTOCOL));
|
||||
}*/
|
||||
|
||||
//Commands
|
||||
CIReload rld = new CIReload();
|
||||
Bukkit.getPluginCommand("cireload").setExecutor(rld);
|
||||
loadCommand(getCommand("cireload"), new CIReloadCommand());
|
||||
loadCommand(getCommand("chatitem"), new ChatItemCommand());
|
||||
|
||||
//Bukkit API listeners
|
||||
chatEventListener = new ChatEventListener(storage);
|
||||
Bukkit.getPluginManager().registerEvents(chatEventListener, this);
|
||||
// events
|
||||
PluginManager pm = getServer().getPluginManager();
|
||||
pm.registerEvents(new JoinListener(), this);
|
||||
pm.registerEvents(new InventoryListener(), this);
|
||||
|
||||
//Check for existence of BaseComponent class (only on spigot)
|
||||
try {
|
||||
Class.forName("net.md_5.bungee.api.chat.BaseComponent");
|
||||
} catch (ClassNotFoundException e) {
|
||||
baseComponentAvailable = false;
|
||||
}
|
||||
chooseManagers();
|
||||
|
||||
//Initialize Log4J filter (remove ugly console messages)
|
||||
filter = new Log4jFilter(storage);
|
||||
}
|
||||
|
||||
public IPlayerVersion getPlayerVersionAdapter() {
|
||||
return playerVersionAdapter;
|
||||
}
|
||||
|
||||
public ChatItemPacketManager getPacketManager() {
|
||||
return packetManager;
|
||||
}
|
||||
|
||||
public static String getVersion(Server server) {
|
||||
final String packageName = server.getClass().getPackage().getName();
|
||||
StringJoiner plugins = new StringJoiner(", ");
|
||||
if (pm.getPlugin("DiscordSRV") != null) {
|
||||
discordSrvSupport = true;
|
||||
plugins.add("DiscordSRV");
|
||||
}
|
||||
|
||||
return packageName.substring(packageName.lastIndexOf('.') + 1);
|
||||
if (pm.getPlugin("EcoEnchants") != null) {
|
||||
ecoEnchantsSupport = true;
|
||||
plugins.add("EcoEnchants");
|
||||
}
|
||||
if(plugins.length() > 0)
|
||||
getLogger().info("Load " + plugins.toString() + " support.");
|
||||
|
||||
|
||||
getServer().getMessenger().registerIncomingPluginChannel(this, brandChannelName, (chan, p, msg) -> {
|
||||
String client = new String(msg).substring(1);
|
||||
ChatItem.debug("Detected client " + client + " for " + p.getName());
|
||||
ItemPlayer.getPlayer(p).setClientName(client);
|
||||
});
|
||||
|
||||
if (storage.CHECK_UPDATE) {
|
||||
getServer().getScheduler().runTaskAsynchronously(this, () -> {
|
||||
String urlName = "https://api.spigotmc.org/legacy/update.php?resource=19064";
|
||||
String content = Utils.getFromURL(urlName);
|
||||
if (Strings.isNullOrEmpty(content))
|
||||
return;
|
||||
SemVer currentVersion = SemVer.parse(getDescription().getVersion());
|
||||
if (currentVersion == null)
|
||||
return;
|
||||
SemVer latestVersion = SemVer.parse(content);
|
||||
if (latestVersion != null && latestVersion.isNewerThan(currentVersion)) {
|
||||
hasNewVersion = !content.equalsIgnoreCase(getDescription().getVersion());
|
||||
if (hasNewVersion) {
|
||||
getLogger().info(storage.JOIN_UPDATE_MESSAGE);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean supportsChatComponentApi(){
|
||||
return baseComponentAvailable;
|
||||
public void loadCommand(PluginCommand cmd, Object obj) {
|
||||
if (obj instanceof CommandExecutor)
|
||||
cmd.setExecutor((CommandExecutor) obj);
|
||||
if (obj instanceof TabCompleter)
|
||||
cmd.setTabCompleter((TabCompleter) obj);
|
||||
}
|
||||
|
||||
public static JSONManipulator getManipulator(){
|
||||
/*
|
||||
We used to have 2 kinds of JSONManipulators because of my bad understanding of the 1.7 way of parsing JSON chat
|
||||
The interface should however stay as there might be great changes in future versions in JSON parsing (most likely 1.13)
|
||||
*/
|
||||
return new JSONManipulatorCurrent();
|
||||
//We just return a new one whenever requested for the moment, should implement a cache of some sort some time though
|
||||
public Storage getStorage() {
|
||||
return storage;
|
||||
}
|
||||
|
||||
public static void debug(String msg) {
|
||||
if(getInstance().getConfig().getBoolean("debug", false))
|
||||
getInstance().getLogger().info(msg);
|
||||
|
||||
public List<ChatManager> getChatManager() {
|
||||
return chatManager;
|
||||
}
|
||||
|
||||
public String getVisualChatManagers() {
|
||||
StringJoiner sj = new StringJoiner(", ");
|
||||
for (ChatManager cm : chatManager) {
|
||||
sj.add(cm.getName() + " (" + cm.getId() + ")");
|
||||
}
|
||||
return sj.toString();
|
||||
}
|
||||
|
||||
public boolean isHasNewVersion() {
|
||||
return hasNewVersion;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package me.dadus33.chatitem;
|
||||
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import me.dadus33.chatitem.playerversion.PlayerVersionManager;
|
||||
import me.dadus33.chatitem.utils.Version;
|
||||
|
||||
public class ItemPlayer {
|
||||
|
||||
private static final ConcurrentHashMap<UUID, ItemPlayer> PLAYERS = new ConcurrentHashMap<>();
|
||||
public static ItemPlayer getPlayer(Player p) {
|
||||
return PLAYERS.computeIfAbsent(p.getUniqueId(), ItemPlayer::new);
|
||||
}
|
||||
public static ItemPlayer getPlayer(UUID uuid) {
|
||||
return PLAYERS.computeIfAbsent(uuid, ItemPlayer::new);
|
||||
}
|
||||
private final UUID uuid;
|
||||
private int protocolVersion = 0;
|
||||
private Version version = null;
|
||||
private String clientName = "unknow";
|
||||
|
||||
public ItemPlayer(UUID uuid) {
|
||||
this.uuid = uuid;
|
||||
Player p = Bukkit.getPlayer(uuid);
|
||||
if(p != null)
|
||||
setVersion(PlayerVersionManager.getPlayerVersionAdapter().getPlayerVersion(p));
|
||||
}
|
||||
|
||||
public UUID getUUID() {
|
||||
return uuid;
|
||||
}
|
||||
|
||||
public Player getPlayer() {
|
||||
return Bukkit.getPlayer(uuid);
|
||||
}
|
||||
|
||||
public String getClientName() {
|
||||
return clientName;
|
||||
}
|
||||
|
||||
public void setClientName(String clientName) {
|
||||
this.clientName = clientName;
|
||||
}
|
||||
|
||||
public int getProtocolVersion() {
|
||||
if(protocolVersion == 0)
|
||||
setProtocolVersion(PlayerVersionManager.getPlayerVersionAdapter().getProtocolVersion(getPlayer()));
|
||||
return protocolVersion;
|
||||
}
|
||||
|
||||
public void setProtocolVersion(int protocolVersion) {
|
||||
this.protocolVersion = protocolVersion;
|
||||
if(version == Version.getVersion()) {// if is default
|
||||
version = Version.getVersion(protocolVersion);
|
||||
ChatItem.debug("Detected version " + version.name() + " (protocol: " + protocolVersion + ")");
|
||||
}
|
||||
}
|
||||
|
||||
public Version getVersion() {
|
||||
if(version == null)
|
||||
setVersion(PlayerVersionManager.getPlayerVersionAdapter().getPlayerVersion(getPlayer()));
|
||||
return version;
|
||||
}
|
||||
|
||||
public void setVersion(Version version) {
|
||||
this.version = version;
|
||||
if(protocolVersion == 0)
|
||||
this.protocolVersion = version.MAX_VER;
|
||||
}
|
||||
|
||||
public boolean isBuggedClient() {
|
||||
return getVersion().equals(Version.V1_7) && getClientName().toLowerCase().contains("lunarclient");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ItemPlayer[uuid=" + uuid + ",name=" + (getPlayer() != null ? getPlayer().getName() : "-") + ",version=" + version.name() + ",protocol=" + protocolVersion + ",client=" + clientName + "]";
|
||||
}
|
||||
}
|
||||
@@ -1,184 +0,0 @@
|
||||
package me.dadus33.chatitem.api;
|
||||
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
import me.dadus33.chatitem.json.JSONManipulator;
|
||||
import me.dadus33.chatitem.json.Translator;
|
||||
import me.dadus33.chatitem.listeners.ChatPacketListenerV2;
|
||||
import me.dadus33.chatitem.utils.ProtocolVersion;
|
||||
import me.dadus33.chatitem.utils.Storage;
|
||||
|
||||
public class APIImplementation implements ChatItemAPI {
|
||||
|
||||
private final static String DEFAULT_JSON = "{\"extra\":[{\"text\":\"i\"}]}";
|
||||
private final static String BASE_JSON = "{\"text\":\"\", \"extra\":[]}";
|
||||
private final static List<String> DEFAULT_REPLACEMENT = Collections.singletonList("i");
|
||||
|
||||
private Storage c;
|
||||
|
||||
private Logger logger;
|
||||
|
||||
public APIImplementation(Storage st){
|
||||
this.c = st;
|
||||
this.logger = ChatItem.getInstance().getLogger();
|
||||
}
|
||||
|
||||
public void updateLogger(){
|
||||
this.logger = ChatItem.getInstance().getLogger();
|
||||
}
|
||||
|
||||
public void setStorage(Storage newStorage){
|
||||
this.c = newStorage;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String getJSONFromItem(ItemStack item) {
|
||||
JSONManipulator manipulator = ChatItem.getManipulator();
|
||||
try {
|
||||
return manipulator.parse(DEFAULT_JSON, DEFAULT_REPLACEMENT, item, ChatPacketListenerV2.styleItem(item, c), ProtocolVersion.getServerVersion().MAX_VER);
|
||||
} catch (Exception e){
|
||||
logger.log(Level.SEVERE, "An unexpected exception was caught while running an API method from ChatItem. Please contact the developer immediately, providing him with the following stack-trace:");
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getJSONFromItem(ItemStack item, String customReplacement) {
|
||||
JSONManipulator manipulator = ChatItem.getManipulator();
|
||||
try {
|
||||
return manipulator.parse(DEFAULT_JSON, DEFAULT_REPLACEMENT, item, customReplacement, ProtocolVersion.getServerVersion().MAX_VER);
|
||||
} catch (Exception e){
|
||||
logger.log(Level.SEVERE, "An unexpected exception was caught while running an API method from ChatItem. Please contact the developer immediately, providing him with the following stack-trace:");
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getJSONFromItem(ItemStack item, Player client) {
|
||||
JSONManipulator manipulator = ChatItem.getManipulator();
|
||||
try {
|
||||
return manipulator.parse(DEFAULT_JSON, DEFAULT_REPLACEMENT, item, ChatPacketListenerV2.styleItem(item, c), ProtocolVersion.getClientVersion(client));
|
||||
} catch (Exception e){
|
||||
logger.log(Level.SEVERE, "An unexpected exception was caught while running an API method from ChatItem. Please contact the developer immediately, providing him with the following stack-trace:");
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getJSONFromItem(ItemStack item, String customReplacement, Player client) {
|
||||
JSONManipulator manipulator = ChatItem.getManipulator();
|
||||
try {
|
||||
return manipulator.parse(DEFAULT_JSON, DEFAULT_REPLACEMENT, item, customReplacement, ProtocolVersion.getClientVersion(client));
|
||||
} catch (Exception e){
|
||||
logger.log(Level.SEVERE, "An unexpected exception was caught while running an API method from ChatItem. Please contact the developer immediately, providing him with the following stack-trace:");
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getJSONFromInlineItem(String text, ItemStack... items) {
|
||||
JsonParser parser = new JsonParser();
|
||||
JsonObject obj = parser.parse(BASE_JSON).getAsJsonObject();
|
||||
obj.add("extra", Translator.toJson(text));
|
||||
String main = obj.toString();
|
||||
int version = ProtocolVersion.getServerVersion().MAX_VER;
|
||||
for(int i = 0; i < items.length; ++i){
|
||||
JSONManipulator manipulator = ChatItem.getManipulator();
|
||||
ItemStack item = items[i];
|
||||
String style = ChatPacketListenerV2.styleItem(item, c);
|
||||
List<String> replacements = Collections.singletonList("%_"+i);
|
||||
try {
|
||||
main = manipulator.parse(main, replacements, item, style, version);
|
||||
} catch (Exception e){
|
||||
logger.log(Level.SEVERE, "An unexpected exception was caught while running an API method from ChatItem. Please contact the developer immediately, providing him with the following stack-trace:");
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return main;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getJSONFromInlineItem(String text, String[] customReplacements, ItemStack... items) {
|
||||
JsonObject wrapper = new JsonObject();
|
||||
wrapper.add("extra", Translator.toJson(text));
|
||||
String main = wrapper.toString();
|
||||
int version = ProtocolVersion.getServerVersion().MAX_VER;
|
||||
for(int i = 0; i < items.length; ++i){
|
||||
JSONManipulator manipulator = ChatItem.getManipulator();
|
||||
ItemStack item = items[i];
|
||||
String style = Translator.toJson(customReplacements[i]).toString();
|
||||
List<String> replacements = Collections.singletonList("%_"+i);
|
||||
try {
|
||||
main = manipulator.parse(main, replacements, item, style, version);
|
||||
} catch (Exception e){
|
||||
logger.log(Level.SEVERE, "An unexpected exception was caught while running an API method from ChatItem. Please contact the developer immediately, providing him with the following stack-trace:");
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return main;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getJSONFromInlineItem(String text, Player client, ItemStack... items) {
|
||||
JsonParser parser = new JsonParser();
|
||||
JsonObject obj = parser.parse(BASE_JSON).getAsJsonObject();
|
||||
obj.add("extra", Translator.toJson(text));
|
||||
String main = obj.toString();
|
||||
int version = ProtocolVersion.getClientVersion(client);
|
||||
for(int i = 0; i < items.length; ++i){
|
||||
JSONManipulator manipulator = ChatItem.getManipulator();
|
||||
ItemStack item = items[i];
|
||||
String style = ChatPacketListenerV2.styleItem(item, c);
|
||||
List<String> replacements = Collections.singletonList("%_"+i);
|
||||
try {
|
||||
main = manipulator.parse(main, replacements, item, style, version);
|
||||
} catch (Exception e){
|
||||
logger.log(Level.SEVERE, "An unexpected exception was caught while running an API method from ChatItem. Please contact the developer immediately, providing him with the following stack-trace:");
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return main;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getJSONFromInlineItem(String text, Player client, String[] customReplacements, ItemStack... items) {
|
||||
JsonParser parser = new JsonParser();
|
||||
JsonObject obj = parser.parse(BASE_JSON).getAsJsonObject();
|
||||
obj.add("extra", Translator.toJson(text));
|
||||
String main = obj.toString();
|
||||
int version = ProtocolVersion.getClientVersion(client);
|
||||
for(int i = 0; i < items.length; ++i){
|
||||
JSONManipulator manipulator = ChatItem.getManipulator();
|
||||
ItemStack item = items[i];
|
||||
String style = Translator.toJson(customReplacements[i]).toString();
|
||||
List<String> replacements = Collections.singletonList("%_"+i);
|
||||
try {
|
||||
main = manipulator.parse(main, replacements, item, style, version);
|
||||
} catch (Exception e){
|
||||
logger.log(Level.SEVERE, "An unexpected exception was caught while running an API method from ChatItem. Please contact the developer immediately, providing him with the following stack-trace:");
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return main;
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
package me.dadus33.chatitem.api;
|
||||
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
public interface ChatItemAPI {
|
||||
String getJSONFromItem(ItemStack item);
|
||||
|
||||
String getJSONFromItem(ItemStack item, String customReplacement);
|
||||
|
||||
String getJSONFromItem(ItemStack item, Player client);
|
||||
|
||||
String getJSONFromItem(ItemStack item, String customReplacement, Player client);
|
||||
|
||||
String getJSONFromInlineItem(String text, ItemStack... items);
|
||||
|
||||
String getJSONFromInlineItem(String text, String[] customReplacements, ItemStack... items);
|
||||
|
||||
String getJSONFromInlineItem(String text, Player client, ItemStack... items);
|
||||
|
||||
String getJSONFromInlineItem(String text, Player client, String[] customReplacements, ItemStack... items);
|
||||
}
|
||||
@@ -0,0 +1,313 @@
|
||||
package me.dadus33.chatitem.chatmanager;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.Cancellable;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.meta.ItemMeta;
|
||||
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
import me.dadus33.chatitem.hook.EcoEnchantsSupport;
|
||||
import me.dadus33.chatitem.itemnamer.NamerManager;
|
||||
import me.dadus33.chatitem.utils.ItemUtils;
|
||||
import me.dadus33.chatitem.utils.Storage;
|
||||
import me.dadus33.chatitem.utils.Utils;
|
||||
|
||||
public abstract class ChatManager {
|
||||
|
||||
private final static HashMap<UUID, Long> COOLDOWNS = new HashMap<>();
|
||||
private final static HashMap<UUID, Long> LAST_INFO_MESSAGE = new HashMap<>();
|
||||
private final static String NAME = "{name}";
|
||||
private final static String AMOUNT = "{amount}";
|
||||
private final static String TIMES = "{times}";
|
||||
private final static String LEFT = "{remaining}";
|
||||
public final static char SEPARATOR = ((char) 0x0007);
|
||||
public final static String SEPARATOR_STR = "\\u0007";
|
||||
|
||||
public static String fixSeparator(String s) {
|
||||
return s.replace(ChatManager.SEPARATOR_STR, Character.toString(ChatManager.SEPARATOR));
|
||||
}
|
||||
|
||||
public static boolean equalsSeparator(String s) {
|
||||
return s.equalsIgnoreCase(SEPARATOR_STR) || s.equalsIgnoreCase(Character.toString(SEPARATOR));
|
||||
}
|
||||
|
||||
public static boolean containsSeparator(String s) {
|
||||
return s.contains(SEPARATOR_STR) || s.contains(Character.toString(SEPARATOR));
|
||||
}
|
||||
|
||||
public static boolean endsWithSeparator(String s) {
|
||||
return s.endsWith(SEPARATOR_STR) || s.endsWith(Character.toString(SEPARATOR));
|
||||
}
|
||||
|
||||
public static String[] splitWithSeparator(String msg) {
|
||||
List<String> list = new ArrayList<>();
|
||||
String current = "";
|
||||
for(String s : msg.split("")) {
|
||||
if(equalsSeparator(s)) {
|
||||
if(!current.isEmpty())
|
||||
list.add(current);
|
||||
current = "";
|
||||
} else
|
||||
current += s;
|
||||
}
|
||||
if(!current.isEmpty())
|
||||
list.add(current);
|
||||
return list.toArray(new String[] {});
|
||||
}
|
||||
|
||||
protected Storage s;
|
||||
|
||||
public ChatManager() {
|
||||
|
||||
}
|
||||
|
||||
public abstract String getName();
|
||||
|
||||
public abstract String getId();
|
||||
|
||||
public Storage getStorage() {
|
||||
return s;
|
||||
}
|
||||
|
||||
public void load(ChatItem pl, Storage s) {
|
||||
this.s = s;
|
||||
}
|
||||
|
||||
public abstract void unload(ChatItem pl);
|
||||
|
||||
/**
|
||||
* Get the item in hand as usable one.<br>
|
||||
* Will include, in lore, all informations from other plugins.
|
||||
*
|
||||
* @param p the player
|
||||
* @return the usable item
|
||||
*/
|
||||
public static ItemStack getUsableItem(Player p) {
|
||||
ItemStack item = HandItem.getBetterItem(p).clone();
|
||||
if(ChatItem.ecoEnchantsSupport) {
|
||||
List<String> addLore = EcoEnchantsSupport.getLores(item);
|
||||
if(!addLore.isEmpty()) {
|
||||
ItemMeta meta = item.getItemMeta();
|
||||
List<String> lores = meta.hasLore() ? meta.getLore() : new ArrayList<>();
|
||||
for(int i = 0; i < addLore.size(); i++)
|
||||
lores.add(i, addLore.get(i));
|
||||
|
||||
meta.setLore(lores);
|
||||
item.setItemMeta(meta);
|
||||
}
|
||||
}
|
||||
return item;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all lores lines of an item, to replace the show_item action which is not working with ViaBackwards
|
||||
*
|
||||
* @param item the item to get lines from
|
||||
* @return all lores
|
||||
*/
|
||||
public static List<String> getMaxLinesFromItem(Player p, ItemStack item) {
|
||||
List<String> lines = new ArrayList<>();
|
||||
if (item.hasItemMeta()) {
|
||||
ItemMeta meta = item.getItemMeta();
|
||||
lines.add(meta.hasDisplayName() ? meta.getDisplayName()
|
||||
: NamerManager.getName(p, item, ChatItem.getInstance().getStorage()));
|
||||
if (meta.hasEnchants()) {
|
||||
meta.getEnchants().forEach((enchant, lvl) -> {
|
||||
lines.add(ChatColor.RESET + Utils.getEnchantName(enchant) + " " + Utils.toRoman(lvl));
|
||||
});
|
||||
}
|
||||
if (meta.hasLore())
|
||||
lines.addAll(meta.getLore());
|
||||
} else {
|
||||
lines.add(NamerManager.getName(p, item, ChatItem.getInstance().getStorage()));
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the name of item according to player & config<br>
|
||||
* Prefer use {@link #getNameOfItem(Player, ItemStack, Storage)} if you want take in count the empty item
|
||||
*
|
||||
* @param p the player
|
||||
* @param item the item
|
||||
* @param c the config
|
||||
* @return the name of item
|
||||
*/
|
||||
public static String styleItem(Player p, ItemStack item, Storage c) {
|
||||
String replacer = c.NAME_FORMAT;
|
||||
String amount = c.AMOUNT_FORMAT;
|
||||
boolean dname = item.hasItemMeta() && item.getItemMeta().hasDisplayName();
|
||||
if (item.getAmount() == 1) {
|
||||
if (c.FORCE_ADD_AMOUNT) {
|
||||
amount = amount.replace(TIMES, "1");
|
||||
replacer = replacer.replace(AMOUNT, amount);
|
||||
} else {
|
||||
replacer = replacer.replace(AMOUNT, "");
|
||||
}
|
||||
} else {
|
||||
amount = amount.replace(TIMES, String.valueOf(item.getAmount()));
|
||||
replacer = replacer.replace(AMOUNT, amount);
|
||||
}
|
||||
if (dname) {
|
||||
String trp = item.getItemMeta().getDisplayName();
|
||||
ChatItem.debug("trp: " + trp);
|
||||
if (c.COLOR_IF_ALREADY_COLORED) {
|
||||
replacer = replacer.replace(NAME, ChatColor.stripColor(trp));
|
||||
} else {
|
||||
replacer = replacer.replace(NAME, trp);
|
||||
}
|
||||
} else {
|
||||
replacer = replacer.replace(NAME, NamerManager.getName(p, item, c));
|
||||
}
|
||||
return replacer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the name of item according to player & config
|
||||
*
|
||||
* @param p the player
|
||||
* @param item the item
|
||||
* @param c the config
|
||||
* @return the name of item or hand
|
||||
*/
|
||||
public static String getNameOfItem(Player p, ItemStack item, Storage c) {
|
||||
if(ItemUtils.isEmpty(item)) {
|
||||
if(c.HAND_DISABLED)
|
||||
return c.PLACEHOLDERS.get(0);
|
||||
else
|
||||
return c.HAND_NAME;
|
||||
}
|
||||
String replacer = c.NAME_FORMAT;
|
||||
String amount = c.AMOUNT_FORMAT;
|
||||
boolean dname = item.hasItemMeta() && item.getItemMeta().hasDisplayName();
|
||||
if (item.getAmount() == 1) {
|
||||
if (c.FORCE_ADD_AMOUNT) {
|
||||
amount = amount.replace(TIMES, "1");
|
||||
replacer = replacer.replace(AMOUNT, amount);
|
||||
} else {
|
||||
replacer = replacer.replace(AMOUNT, "");
|
||||
}
|
||||
} else {
|
||||
amount = amount.replace(TIMES, String.valueOf(item.getAmount()));
|
||||
replacer = replacer.replace(AMOUNT, amount);
|
||||
}
|
||||
if (dname) {
|
||||
String trp = item.getItemMeta().getDisplayName();
|
||||
if (c.COLOR_IF_ALREADY_COLORED) {
|
||||
replacer = replacer.replace(NAME, ChatColor.stripColor(trp));
|
||||
} else {
|
||||
replacer = replacer.replace(NAME, trp);
|
||||
}
|
||||
} else {
|
||||
replacer = replacer.replace(NAME, NamerManager.getName(p, item, c));
|
||||
}
|
||||
return replacer;
|
||||
}
|
||||
|
||||
public static String calculateTime(long seconds) {
|
||||
Storage c = ChatItem.getInstance().getStorage();
|
||||
if (seconds < 60) {
|
||||
return seconds + c.SECONDS;
|
||||
}
|
||||
if (seconds < 3600) {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
int minutes = (int) seconds / 60;
|
||||
builder.append(minutes).append(c.MINUTES);
|
||||
int secs = (int) seconds - minutes * 60;
|
||||
if (secs != 0) {
|
||||
builder.append(" ").append(secs).append(c.SECONDS);
|
||||
}
|
||||
return builder.toString();
|
||||
}
|
||||
StringBuilder builder = new StringBuilder();
|
||||
int hours = (int) seconds / 3600;
|
||||
builder.append(hours).append(c.HOURS);
|
||||
int minutes = (int) (seconds / 60) - (hours * 60);
|
||||
if (minutes != 0) {
|
||||
builder.append(" ").append(minutes).append(c.MINUTES);
|
||||
}
|
||||
int secs = (int) (seconds - ((seconds / 60) * 60));
|
||||
if (secs != 0) {
|
||||
builder.append(" ").append(secs).append(c.SECONDS);
|
||||
}
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
public static boolean canShowItem(Player p, ItemStack item, @Nullable Cancellable e) {
|
||||
Storage c = ChatItem.getInstance().getStorage();
|
||||
if (c.PERMISSION_ENABLED && !p.hasPermission(c.PERMISSION_NAME)) {
|
||||
if (!c.LET_MESSAGE_THROUGH) {
|
||||
if(e != null)
|
||||
e.setCancelled(true);
|
||||
}
|
||||
if (!c.NO_PERMISSION_MESSAGE.isEmpty() && c.SHOW_NO_PERM_NORMAL) {
|
||||
sendIfNeed(p, c.NO_PERMISSION_MESSAGE);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (item.getType().equals(Material.AIR)) {
|
||||
if (c.DENY_IF_NO_ITEM) {
|
||||
if(e != null)
|
||||
e.setCancelled(true);
|
||||
if (!c.DENY_MESSAGE.isEmpty())
|
||||
sendIfNeed(p, c.DENY_MESSAGE);
|
||||
return false;
|
||||
}
|
||||
if (c.HAND_DISABLED) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (c.COOLDOWN > 0 && !p.hasPermission("chatitem.ignore-cooldown")) {
|
||||
if (COOLDOWNS.containsKey(p.getUniqueId())) {
|
||||
long start = COOLDOWNS.get(p.getUniqueId());
|
||||
long current = System.currentTimeMillis() / 1000;
|
||||
long elapsed = current - start;
|
||||
if (elapsed >= c.COOLDOWN) {
|
||||
COOLDOWNS.remove(p.getUniqueId());
|
||||
} else {
|
||||
if (!c.LET_MESSAGE_THROUGH) {
|
||||
if(e != null)
|
||||
e.setCancelled(true);
|
||||
}
|
||||
if (!c.COOLDOWN_MESSAGE.isEmpty()) {
|
||||
long left = (start + c.COOLDOWN) - current;
|
||||
sendIfNeed(p, c.COOLDOWN_MESSAGE.replace(LEFT, ChatManager.calculateTime(left)));
|
||||
}
|
||||
ChatItem.debug("Cooldown");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
LAST_INFO_MESSAGE.put(p.getUniqueId(), System.currentTimeMillis()); // prevent showing item then send cooldown error message
|
||||
return true;
|
||||
}
|
||||
|
||||
private static void sendIfNeed(Player p, String msg) {
|
||||
Long time = LAST_INFO_MESSAGE.remove(p.getUniqueId());
|
||||
if(time != null) {
|
||||
long diff = System.currentTimeMillis() - time;
|
||||
if(diff < 100)
|
||||
return; // don't show message
|
||||
}
|
||||
p.sendMessage(msg);
|
||||
LAST_INFO_MESSAGE.put(p.getUniqueId(), System.currentTimeMillis());
|
||||
}
|
||||
|
||||
public static void clear(Player p) {
|
||||
COOLDOWNS.remove(p.getUniqueId());
|
||||
LAST_INFO_MESSAGE.remove(p.getUniqueId());
|
||||
}
|
||||
|
||||
public static void applyCooldown(Player p) {
|
||||
COOLDOWNS.put(p.getUniqueId(), System.currentTimeMillis() / 1000);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package me.dadus33.chatitem.chatmanager;
|
||||
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import me.dadus33.chatitem.utils.ItemUtils;
|
||||
import me.dadus33.chatitem.utils.Version;
|
||||
|
||||
public class HandItem {
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
public static ItemStack getBetterItem(Player p) {
|
||||
if(Version.getVersion().isNewerOrEquals(Version.V1_9)) {
|
||||
ItemStack main = p.getInventory().getItemInMainHand();
|
||||
if(!ItemUtils.isEmpty(main))
|
||||
return main;
|
||||
ItemStack off = p.getInventory().getItemInOffHand();
|
||||
return ItemUtils.isEmpty(off) ? main : off;
|
||||
}
|
||||
return p.getItemInHand();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package me.dadus33.chatitem.chatmanager.v1;
|
||||
|
||||
import java.lang.reflect.Constructor;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.event.HandlerList;
|
||||
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
import me.dadus33.chatitem.chatmanager.ChatManager;
|
||||
import me.dadus33.chatitem.chatmanager.v1.json.JSONManipulatorCurrent;
|
||||
import me.dadus33.chatitem.chatmanager.v1.listeners.ChatEventListener;
|
||||
import me.dadus33.chatitem.chatmanager.v1.listeners.ChatPacketManager;
|
||||
import me.dadus33.chatitem.chatmanager.v1.packets.ChatItemPacketManager;
|
||||
import me.dadus33.chatitem.chatmanager.v1.packets.PacketManager;
|
||||
import me.dadus33.chatitem.utils.PacketUtils;
|
||||
import me.dadus33.chatitem.utils.Storage;
|
||||
|
||||
public class PacketEditingChatManager extends ChatManager {
|
||||
|
||||
private final JSONManipulatorCurrent jsonManipulator;
|
||||
private boolean baseComponentAvailable = true;
|
||||
private final ChatItemPacketManager packetManager;
|
||||
private final ChatEventListener chatEventListener;
|
||||
private final ChatPacketManager chatPacketManager;
|
||||
|
||||
public PacketEditingChatManager(ChatItem pl) {
|
||||
jsonManipulator = new JSONManipulatorCurrent();
|
||||
packetManager = new ChatItemPacketManager(pl);
|
||||
chatEventListener = new ChatEventListener(this);
|
||||
chatPacketManager = new ChatPacketManager(this);
|
||||
|
||||
// Check for existence of BaseComponent class (only on spigot)
|
||||
try {
|
||||
Class.forName("net.md_5.bungee.api.chat.BaseComponent");
|
||||
} catch (ClassNotFoundException e) {
|
||||
baseComponentAvailable = false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "PacketEditing";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getId() {
|
||||
return "packet";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void load(ChatItem pl, Storage s) {
|
||||
super.load(pl, s);
|
||||
|
||||
Bukkit.getPluginManager().registerEvents(chatEventListener, pl);
|
||||
PacketManager pm = packetManager.getPacketManager();
|
||||
pm.addHandler(chatPacketManager);
|
||||
Bukkit.getOnlinePlayers().forEach(pm::addPlayer); // add actual online players
|
||||
}
|
||||
|
||||
@Override
|
||||
public void unload(ChatItem pl) {
|
||||
HandlerList.unregisterAll(chatEventListener);
|
||||
PacketManager pm = packetManager.getPacketManager();
|
||||
pm.removeHandler(chatPacketManager);
|
||||
pm.stop();
|
||||
}
|
||||
|
||||
public JSONManipulatorCurrent getManipulator() {
|
||||
return jsonManipulator;
|
||||
}
|
||||
|
||||
public boolean supportsChatComponentApi() {
|
||||
return baseComponentAvailable;
|
||||
}
|
||||
|
||||
public static Object createSystemChatPacket(String json) throws Exception {
|
||||
Class<?> packetClass = PacketUtils.getNmsClass("ClientboundSystemChatPacket", "network.protocol.game.");
|
||||
for (Constructor<?> cons : packetClass.getDeclaredConstructors()) {
|
||||
if (!cons.isAccessible())
|
||||
cons.setAccessible(true);
|
||||
if (cons.getParameterCount() == 2 && cons.getParameterTypes()[0].equals(String.class)
|
||||
&& cons.getParameterTypes()[1].equals(int.class)) { // "string, int"
|
||||
return cons.newInstance(json, 1);
|
||||
} else if (cons.getParameterCount() == 3 && cons.getParameterTypes()[1].equals(String.class)
|
||||
&& cons.getParameterTypes()[2].equals(int.class)) { // "component", "string", "int"
|
||||
return cons.newInstance(null, json, 1);
|
||||
}
|
||||
}
|
||||
ChatItem.getInstance().getLogger()
|
||||
.warning("Can't create a new packet for json " + json + ": no constructor found.");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package me.dadus33.chatitem.chatmanager.v1.basecomp;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import me.dadus33.chatitem.chatmanager.ChatManager;
|
||||
import me.dadus33.chatitem.chatmanager.v1.packets.ChatItemPacket;
|
||||
import me.dadus33.chatitem.utils.Storage;
|
||||
|
||||
public interface IBaseComponentGetter {
|
||||
|
||||
default boolean hasConditions() {
|
||||
return true;
|
||||
}
|
||||
|
||||
String getBaseComponentAsJSON(ChatItemPacket packet);
|
||||
|
||||
void writeJson(ChatItemPacket packet, String json);
|
||||
|
||||
/**
|
||||
* Use actual base component getter to check if the given json has placeholders
|
||||
*
|
||||
* @param c the storage config
|
||||
* @param json the json
|
||||
* @return the founded placeholder or null
|
||||
*/
|
||||
default @Nullable String hasPlaceholders(Storage c, String json) {
|
||||
if(json == null || json.isEmpty())
|
||||
return null;
|
||||
for (String rep : c.PLACEHOLDERS) {
|
||||
if (json.contains(rep)) {
|
||||
return rep;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
default @Nullable String getNameFromMessage(String json, String toReplace) {
|
||||
for (Player p : Bukkit.getOnlinePlayers()) {
|
||||
String name = toReplace + p.getName();
|
||||
if (json.contains(name))
|
||||
return p.getName();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Use actual base component getter to remove the player and the name.<br>
|
||||
* This is for special component which split message into sub string
|
||||
*
|
||||
* @param json the global json
|
||||
* @param toReplace the string which contains the placeholder
|
||||
* @param foundedPlayer the player which has the name in message
|
||||
* @return the replaced json
|
||||
*/
|
||||
default String removePlaceholdersAndName(String json, String toReplace, Player foundedPlayer) {
|
||||
return json.replace(toReplace + foundedPlayer.getName(), Character.toString(ChatManager.SEPARATOR));
|
||||
}
|
||||
}
|
||||
+283
@@ -0,0 +1,283 @@
|
||||
package me.dadus33.chatitem.chatmanager.v1.basecomp.hook;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.Arrays;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
import me.dadus33.chatitem.chatmanager.ChatManager;
|
||||
import me.dadus33.chatitem.chatmanager.v1.PacketEditingChatManager;
|
||||
import me.dadus33.chatitem.chatmanager.v1.basecomp.IBaseComponentGetter;
|
||||
import me.dadus33.chatitem.chatmanager.v1.packets.ChatItemPacket;
|
||||
import me.dadus33.chatitem.utils.ReflectionUtils;
|
||||
import me.dadus33.chatitem.utils.Storage;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.serializer.bungeecord.BungeeComponentSerializer;
|
||||
import net.md_5.bungee.chat.ComponentSerializer;
|
||||
|
||||
public class AdventureComponentGetter implements IBaseComponentGetter {
|
||||
|
||||
private boolean useExtra = false;
|
||||
|
||||
@Override
|
||||
public boolean hasConditions() {
|
||||
try {
|
||||
for (String cl : Arrays.asList("net.kyori.adventure.text.Component", "net.kyori.adventure.builder.AbstractBuilder",
|
||||
"net.kyori.adventure.text.serializer.bungeecord.BungeeComponentSerializer"))
|
||||
Class.forName(cl);
|
||||
} catch (Exception e) { // can't support this, adventure comp not found
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getBaseComponentAsJSON(ChatItemPacket packet) {
|
||||
Component comp = packet.getContent().getSpecificModifier(Component.class).readSafely(0);
|
||||
if(comp == null) {
|
||||
ChatItem.debug("The component is null.");
|
||||
return null;
|
||||
}
|
||||
String json = ComponentSerializer.toString(BungeeComponentSerializer.get().serialize(comp).clone());
|
||||
ChatItem.debug("AdventureJSON : " + json);
|
||||
JsonObject jsonObj = JsonParser.parseString(json).getAsJsonObject();
|
||||
if(jsonObj.has("with")) {
|
||||
JsonObject next = new JsonObject();
|
||||
next.add("extra", jsonObj.get("with"));
|
||||
return next.toString();
|
||||
}
|
||||
useExtra = true;
|
||||
return json;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String hasPlaceholders(Storage c, String json) {
|
||||
if(useExtra)
|
||||
return IBaseComponentGetter.super.hasPlaceholders(c, json);
|
||||
JsonObject jsonObj = JsonParser.parseString(json).getAsJsonObject();
|
||||
if(!jsonObj.has("extra"))
|
||||
return null;
|
||||
for(JsonElement element : jsonObj.get("extra").getAsJsonArray()) {
|
||||
if(element.isJsonObject()) {
|
||||
JsonObject withObj = element.getAsJsonObject();
|
||||
if(withObj.has("extra")) {
|
||||
String text = "";
|
||||
for(JsonElement extra : withObj.get("extra").getAsJsonArray()) {
|
||||
if(extra.isJsonObject()) {
|
||||
JsonObject extraObj = extra.getAsJsonObject();
|
||||
if(extraObj.has("text") && extraObj.get("text").isJsonPrimitive())
|
||||
text += extraObj.get("text").getAsString();
|
||||
}
|
||||
}
|
||||
String placeholder = IBaseComponentGetter.super.hasPlaceholders(c, text);
|
||||
if(placeholder != null)
|
||||
return placeholder;
|
||||
} else if(withObj.has("text")) {
|
||||
String placeholder = IBaseComponentGetter.super.hasPlaceholders(c, withObj.get("text").getAsString());
|
||||
if(placeholder != null)
|
||||
return placeholder;
|
||||
}
|
||||
} // ignoring all others because it should not appear
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getNameFromMessage(String json, String toReplace) {
|
||||
if(useExtra)
|
||||
return IBaseComponentGetter.super.getNameFromMessage(json, toReplace);
|
||||
String tmpName = IBaseComponentGetter.super.getNameFromMessage(json, toReplace);
|
||||
if(tmpName != null)
|
||||
return tmpName; // don't need to check for json if basically found
|
||||
JsonObject jsonObj = JsonParser.parseString(json).getAsJsonObject();
|
||||
if(!jsonObj.has("extra"))
|
||||
return null;
|
||||
for(JsonElement element : jsonObj.get("extra").getAsJsonArray()) {
|
||||
if(element.isJsonObject()) {
|
||||
JsonObject withObj = element.getAsJsonObject();
|
||||
if(withObj.has("extra")) {
|
||||
String text = "";
|
||||
for(JsonElement extra : withObj.get("extra").getAsJsonArray()) {
|
||||
if(extra.isJsonObject()) {
|
||||
JsonObject extraObj = extra.getAsJsonObject();
|
||||
if(extraObj.has("text") && extraObj.get("text").isJsonPrimitive())
|
||||
text += extraObj.get("text").getAsString();
|
||||
}
|
||||
}
|
||||
String possibleName = IBaseComponentGetter.super.getNameFromMessage(text, toReplace);
|
||||
if(possibleName != null)
|
||||
return possibleName;
|
||||
} else if(withObj.has("text")) {
|
||||
String possibleName = IBaseComponentGetter.super.getNameFromMessage(withObj.get("text").getAsString(), toReplace);
|
||||
if(possibleName != null)
|
||||
return possibleName;
|
||||
}
|
||||
} // ignoring all others because it should not appear
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String removePlaceholdersAndName(String json, String toReplace, Player foundedPlayer) {
|
||||
if(useExtra)
|
||||
return IBaseComponentGetter.super.removePlaceholdersAndName(json, toReplace, foundedPlayer);
|
||||
String tmpName = IBaseComponentGetter.super.removePlaceholdersAndName(json, toReplace, foundedPlayer);
|
||||
if(!tmpName.equals(json)) // if not the same -> name found and removed
|
||||
return tmpName;
|
||||
JsonObject jsonObj = JsonParser.parseString(json).getAsJsonObject();
|
||||
if(!jsonObj.has("extra"))
|
||||
return json;
|
||||
String searched = toReplace + foundedPlayer.getName();
|
||||
for(JsonElement element : jsonObj.get("extra").getAsJsonArray()) {
|
||||
if(element.isJsonObject()) {
|
||||
JsonObject withObj = element.getAsJsonObject();
|
||||
if(withObj.has("extra")) {
|
||||
String text = "";
|
||||
int possibleId = -1;
|
||||
JsonArray extraArray = withObj.get("extra").getAsJsonArray();
|
||||
for(int i = 0; i < extraArray.size(); i++) {
|
||||
JsonElement extra = extraArray.get(i);
|
||||
if(!extra.isJsonObject())
|
||||
continue; // prevent error but should not appear
|
||||
JsonObject extraObj = extra.getAsJsonObject();
|
||||
if(extraObj.has("text") && extraObj.get("text").isJsonPrimitive()) {
|
||||
String extraTxt = extraObj.get("text").getAsString();
|
||||
if(possibleId == -1) { // don't found the begin yet
|
||||
if(searched.startsWith(extraTxt)) { // begin of replaced
|
||||
possibleId = i;
|
||||
text = extraTxt;
|
||||
}
|
||||
} else {
|
||||
if(searched.startsWith(extraTxt, text.length()) || ChatManager.equalsSeparator(extraTxt)) {
|
||||
text += extraTxt;
|
||||
if(searched.equals(text)) { // found everything
|
||||
// change actual, then remove all old
|
||||
extraArray.set(i, JsonParser.parseString("{\"text\":\"" + Character.toString(ChatManager.SEPARATOR) + "\"}"));
|
||||
for(int x = possibleId; x < i; x++)
|
||||
extraArray.remove(possibleId); // remove elements
|
||||
ChatItem.debug("Cleaned: " + jsonObj.toString());
|
||||
return jsonObj.toString();
|
||||
}
|
||||
} else {
|
||||
possibleId = -1; // was not good things
|
||||
text = "";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ChatItem.debug("Failed to find: " + text + ", id: " + possibleId + " for " + withObj);
|
||||
}
|
||||
} // ignoring all others because it should not appear
|
||||
}
|
||||
ChatItem.debug("Nothing founded while trying to remove placeholders");
|
||||
return IBaseComponentGetter.super.removePlaceholdersAndName(json, toReplace, foundedPlayer);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void writeJson(ChatItemPacket packet, String json) {
|
||||
JsonElement globalElement = JsonParser.parseString(json);
|
||||
JsonArray extraArray = fixParsedArray(globalElement.getAsJsonObject().getAsJsonArray("extra"));
|
||||
String localJson;
|
||||
if(useExtra) {
|
||||
globalElement.getAsJsonObject().add("extra", extraArray);
|
||||
localJson = globalElement.toString();
|
||||
} else {
|
||||
JsonObject next = new JsonObject();
|
||||
next.addProperty("translate", "chat.type.text");
|
||||
next.add("with", extraArray);
|
||||
localJson = next.toString();
|
||||
}
|
||||
ChatItem.debug("Adventure Json: " + json);
|
||||
try {
|
||||
Class<?> packetClass = packet.getPacket().getClass();
|
||||
if(packetClass.getSimpleName().equalsIgnoreCase("PacketPlayOutChat")) {
|
||||
Field componentField = ReflectionUtils.getFirstFieldWith(packetClass, Component.class);
|
||||
if(componentField != null) {
|
||||
componentField.setAccessible(true);
|
||||
componentField.set(packet.getPacket(), BungeeComponentSerializer.legacy().deserialize(ComponentSerializer.parse(localJson)));
|
||||
} else {
|
||||
throw new UnsupportedOperationException("The packet PacketPlayOutChat doesn't have Kyori's field. It has: " + Arrays.asList(packetClass.getDeclaredFields()).stream().map(f -> f.getName() + ": " + f.getType().getName()).collect(Collectors.toList()));
|
||||
}
|
||||
} else if(packetClass.getSimpleName().equalsIgnoreCase("ClientboundSystemChatPacket")) {
|
||||
packet.setPacket(PacketEditingChatManager.createSystemChatPacket(localJson));
|
||||
} else {
|
||||
throw new UnsupportedOperationException("The packet " + packetClass.getSimpleName() + " isn't supported by the AdventureGetter. Please report this.");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public JsonArray fixParsedArray(JsonArray arr) {
|
||||
JsonArray next = new JsonArray();
|
||||
for(JsonElement e : arr) {
|
||||
if(e.isJsonArray()) {
|
||||
JsonObject obj = null;
|
||||
JsonArray extra = new JsonArray();
|
||||
for(JsonElement element : e.getAsJsonArray()) {
|
||||
JsonElement fixed = checkElement(element);
|
||||
if(obj == null && fixed.isJsonObject()) {
|
||||
obj = fixed.getAsJsonObject();
|
||||
} else {
|
||||
extra.add(fixed);
|
||||
}
|
||||
}
|
||||
if(obj != null && extra.size() > 0) {
|
||||
obj.add("extra", extra);
|
||||
}
|
||||
next.add(obj);
|
||||
} else
|
||||
next.add(checkElement(e));
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
private JsonElement checkElement(JsonElement e) {
|
||||
if(e.isJsonObject()) {
|
||||
JsonObject o = e.getAsJsonObject();
|
||||
if(o.has("hoverEvent")) {// only hover event
|
||||
JsonObject hoverObject = o.getAsJsonObject("hoverEvent");
|
||||
if(hoverObject.get("action").getAsString().equalsIgnoreCase("show_item") && hoverObject.has("value")) {// if it's item to fix
|
||||
String val = hoverObject.get("value").getAsString();
|
||||
// now, we should fix the value
|
||||
val = val.replaceAll("\\\"", "\"");
|
||||
ChatItem.debug("Fixed json: " + ("{" + val.substring(1, val.length() - 1) + "}"));
|
||||
hoverObject.remove("value");
|
||||
JsonElement tagElement = JsonParser.parseString("{" + val.substring(1, val.length() - 1) + "}");
|
||||
tagElement.getAsJsonObject().remove("tag");
|
||||
/*if(tagElement.getAsJsonObject().has("tag")) {
|
||||
JsonElement tag = tagElement.getAsJsonObject().get("tag");
|
||||
if(tag.isJsonObject()) {
|
||||
JsonObject tagObj = tag.getAsJsonObject();
|
||||
tagObj.entrySet().forEach(entry -> {
|
||||
ChatItem.debug("Tag json: " + entry.getKey() + " > " + entry.getValue());
|
||||
JsonElement value = entry.getValue();
|
||||
String sval = value.getAsString();
|
||||
if(Utils.isInteger(sval)) {
|
||||
if(Utils.isByte(sval))
|
||||
tagObj.addProperty(entry.getKey(), sval + "b");
|
||||
else if(Utils.isShort(sval))
|
||||
tagObj.addProperty(entry.getKey(), sval + "s");
|
||||
else if(Utils.isLong(sval))
|
||||
tagObj.addProperty(entry.getKey(), sval + "l");
|
||||
else
|
||||
tagObj.addProperty(entry.getKey(), value + "i");
|
||||
}
|
||||
});
|
||||
}
|
||||
}*/
|
||||
hoverObject.add("contents", tagElement);
|
||||
o.add("hoverEvent", hoverObject);
|
||||
}
|
||||
}
|
||||
}
|
||||
return e;
|
||||
}
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package me.dadus33.chatitem.chatmanager.v1.basecomp.hook;
|
||||
|
||||
import me.dadus33.chatitem.chatmanager.v1.basecomp.IBaseComponentGetter;
|
||||
import me.dadus33.chatitem.chatmanager.v1.packets.ChatItemPacket;
|
||||
import me.dadus33.chatitem.utils.Version;
|
||||
import net.md_5.bungee.api.chat.BaseComponent;
|
||||
import net.md_5.bungee.chat.ComponentSerializer;
|
||||
|
||||
public class BaseComponentGetter implements IBaseComponentGetter {
|
||||
|
||||
@Override
|
||||
public boolean hasConditions() {
|
||||
return Version.getVersion().isNewerOrEquals(Version.V1_8);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getBaseComponentAsJSON(ChatItemPacket packet) {
|
||||
BaseComponent[] comps = packet.getContent().getSpecificModifier(BaseComponent[].class).readSafely(0);
|
||||
return comps == null ? null : ComponentSerializer.toString(comps);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void writeJson(ChatItemPacket packet, String json) {
|
||||
packet.getContent().getSpecificModifier(BaseComponent[].class).write(0, ComponentSerializer.parse(json));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package me.dadus33.chatitem.chatmanager.v1.basecomp.hook;
|
||||
|
||||
import me.dadus33.chatitem.chatmanager.v1.basecomp.IBaseComponentGetter;
|
||||
import me.dadus33.chatitem.chatmanager.v1.packets.ChatItemPacket;
|
||||
import me.dadus33.chatitem.utils.PacketUtils;
|
||||
|
||||
public class ComponentGetter implements IBaseComponentGetter {
|
||||
|
||||
@Override
|
||||
public boolean hasConditions() {
|
||||
return PacketUtils.COMPONENT_CLASS != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getBaseComponentAsJSON(ChatItemPacket packet) {
|
||||
Object chatBaseComp = packet.getContent().getSpecificModifier(PacketUtils.COMPONENT_CLASS).readSafely(0);
|
||||
if (chatBaseComp != null) {
|
||||
try {
|
||||
return PacketUtils.CHAT_SERIALIZER.getMethod("a", PacketUtils.COMPONENT_CLASS)
|
||||
.invoke(null, packet.getPacket()).toString();
|
||||
} catch (Exception exc) {
|
||||
exc.printStackTrace();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void writeJson(ChatItemPacket packet, String json) {
|
||||
try {
|
||||
packet.getContent().getChatComponents().write(0, PacketUtils.CHAT_SERIALIZER.getMethod("a", String.class).invoke(null, json));
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
package me.dadus33.chatitem.chatmanager.v1.basecomp.hook;
|
||||
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.Method;
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
import me.dadus33.chatitem.chatmanager.v1.basecomp.IBaseComponentGetter;
|
||||
import me.dadus33.chatitem.chatmanager.v1.packets.ChatItemPacket;
|
||||
import me.dadus33.chatitem.chatmanager.v1.packets.PacketContent;
|
||||
import me.dadus33.chatitem.utils.PacketUtils;
|
||||
import me.dadus33.chatitem.utils.ReflectionUtils;
|
||||
|
||||
public class IChatBaseComponentGetter implements IBaseComponentGetter {
|
||||
|
||||
private Method serializerGetJson;
|
||||
private boolean canEditVariable = true;
|
||||
|
||||
public IChatBaseComponentGetter() {
|
||||
try {
|
||||
for (Method m : PacketUtils.CHAT_SERIALIZER.getDeclaredMethods()) {
|
||||
if (m.getParameterCount() == 1 && m.getParameterTypes()[0].equals(PacketUtils.COMPONENT_CLASS)
|
||||
&& m.getReturnType().equals(String.class)) {
|
||||
serializerGetJson = m;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (serializerGetJson == null)
|
||||
ChatItem.getInstance().getLogger().warning(
|
||||
"Failed to find JSON serializer in class: " + PacketUtils.CHAT_SERIALIZER.getCanonicalName());
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasConditions() {
|
||||
return serializerGetJson != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getBaseComponentAsJSON(ChatItemPacket packet) {
|
||||
try {
|
||||
Object obj = packet.getContent().getChatComponents().readSafely(0);
|
||||
return obj == null ? null : (String) serializerGetJson.invoke(null, obj);
|
||||
} catch (Exception exc) {
|
||||
exc.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void writeJson(ChatItemPacket packet, String json) {
|
||||
try {
|
||||
PacketContent content = packet.getContent();
|
||||
Object chatComponent = PacketUtils.CHAT_SERIALIZER.getMethod("a", String.class).invoke(null, json);
|
||||
if (canEditVariable)
|
||||
content.getChatComponents().write(0, chatComponent);
|
||||
else {
|
||||
try {
|
||||
Class<?> packetClass = packet.getPacket().getClass();
|
||||
if (packetClass.getSimpleName().equalsIgnoreCase("ClientboundSystemChatPacket")) {
|
||||
for (Constructor<?> cons : packetClass.getConstructors()) {
|
||||
if (cons.getParameterCount() == 6) {
|
||||
Object newPacket = cons.newInstance(chatComponent, Optional.empty(),
|
||||
content.getIntegers().readSafely(0, 0),
|
||||
content.getSpecificModifier(
|
||||
PacketUtils.getNmsClass("ChatSender", "network.chat.")).read(0),
|
||||
content.getSpecificModifier(Instant.class).read(0),
|
||||
ReflectionUtils.getObject(packet.getPacket(), "f"));
|
||||
packet.setPacket(newPacket);
|
||||
}
|
||||
}
|
||||
throw new UnsupportedOperationException("Failed to find valid constructor for packet "
|
||||
+ packetClass.getSimpleName() + ". Please report this.");
|
||||
} else {
|
||||
throw new UnsupportedOperationException("The packet " + packetClass.getSimpleName()
|
||||
+ " isn't supported by the AdventureGetter. Please report this.");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
} catch (IllegalAccessException e) {
|
||||
if (canEditVariable) {
|
||||
canEditVariable = false;
|
||||
writeJson(packet, json); // try again with good config
|
||||
} else
|
||||
e.printStackTrace(); // something else
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package me.dadus33.chatitem.chatmanager.v1.basecomp.hook;
|
||||
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
import me.dadus33.chatitem.chatmanager.v1.PacketEditingChatManager;
|
||||
import me.dadus33.chatitem.chatmanager.v1.basecomp.IBaseComponentGetter;
|
||||
import me.dadus33.chatitem.chatmanager.v1.packets.ChatItemPacket;
|
||||
|
||||
public class StringComponentGetter implements IBaseComponentGetter{
|
||||
|
||||
@Override
|
||||
public String getBaseComponentAsJSON(ChatItemPacket packet) {
|
||||
String json = packet.getContent().getStrings().readSafely(0);
|
||||
if(json != null && json.startsWith("[") && json.endsWith("]")) { // if used as array instead of json obj
|
||||
JsonArray extra = new JsonArray();
|
||||
for(JsonElement element : JsonParser.parseString(json).getAsJsonArray()) {
|
||||
if(element.isJsonObject()) { // ignore this
|
||||
extra.add(element);
|
||||
} else {
|
||||
ChatItem.debug("Ignoring element " + element);
|
||||
}
|
||||
}
|
||||
JsonObject jsonObject = new JsonObject();
|
||||
jsonObject.addProperty("text", "");
|
||||
jsonObject.add("extra", extra);
|
||||
json = jsonObject.toString();
|
||||
}
|
||||
return json;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void writeJson(ChatItemPacket packet, String json) {
|
||||
try {
|
||||
packet.setPacket(PacketEditingChatManager.createSystemChatPacket(json));
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
package me.dadus33.chatitem.chatmanager.v1.json;
|
||||
|
||||
import static me.dadus33.chatitem.utils.PacketUtils.getNmsClass;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.AbstractMap;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
import com.google.gson.JsonPrimitive;
|
||||
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
import me.dadus33.chatitem.chatmanager.ChatManager;
|
||||
import me.dadus33.chatitem.utils.PacketUtils;
|
||||
import me.dadus33.chatitem.utils.Reflect;
|
||||
import me.dadus33.chatitem.utils.Version;
|
||||
|
||||
@SuppressWarnings({ "unchecked" })
|
||||
public class JSONManipulatorCurrent {
|
||||
|
||||
private static final Class<?> CRAFT_ITEM_STACK_CLASS = PacketUtils.getObcClass("inventory.CraftItemStack");
|
||||
private static final Class<?> NMS_ITEM_STACK_CLASS = getNmsClass("ItemStack", "world.item.");
|
||||
private static final Method AS_NMS_COPY = Reflect.getMethod(CRAFT_ITEM_STACK_CLASS, "asNMSCopy", ItemStack.class);
|
||||
private static final Class<?> NBT_TAG_COMPOUND = getNmsClass("NBTTagCompound", "nbt.");
|
||||
private static final Method SAVE_NMS_ITEM_STACK_METHOD = Reflect.getMethod(NMS_ITEM_STACK_CLASS, NBT_TAG_COMPOUND,
|
||||
NBT_TAG_COMPOUND);
|
||||
private static final Field MAP = Reflect.getField(NBT_TAG_COMPOUND, "map", "x");
|
||||
|
||||
private static final ConcurrentHashMap<Map.Entry<Version, ItemStack>, JsonObject> STACKS = new ConcurrentHashMap<>();
|
||||
|
||||
private Version protocolVersion;
|
||||
private JsonObject itemTooltip;
|
||||
private JsonArray classicTooltip;
|
||||
|
||||
public String parse(String json, ItemStack item, String replacement, int protocol)
|
||||
throws Exception {
|
||||
JsonObject obj = JsonParser.parseString(json).getAsJsonObject();
|
||||
JsonArray array = obj.has("extra") ? obj.getAsJsonArray("extra") : new JsonArray();
|
||||
final AbstractMap.SimpleEntry<Version, ItemStack> p = new AbstractMap.SimpleEntry<>(
|
||||
protocolVersion = Version.getVersion(protocol), item);
|
||||
|
||||
if ((itemTooltip = STACKS.get(p)) == null) {
|
||||
JsonArray use = Translator.toJson(replacement); // We get the json representation of the old color
|
||||
// formatting method
|
||||
ChatItem.debug("Remplacement: " + replacement + " use: " + use.toString());
|
||||
// There's no public clone method for JSONObjects so we need to parse them every time
|
||||
JsonObject hover = new JsonObject();
|
||||
hover.addProperty("action", "show_item");
|
||||
|
||||
// Get the JSON representation of the item (well, not really JSON, but rather a string representation of NBT data)
|
||||
hover.addProperty("value", stringifyItem(this, item, protocolVersion));
|
||||
|
||||
JsonObject wrapper = new JsonObject(); // Create a wrapper object for the whole array
|
||||
wrapper.addProperty("text", ""); // The text field is compulsory, even if it's empty
|
||||
wrapper.add("extra", use);
|
||||
wrapper.add("hoverEvent", hover);
|
||||
|
||||
itemTooltip = wrapper; // Save the tooltip for later use when we encounter a placeholder
|
||||
STACKS.put(p, itemTooltip); // Save it in the cache too so when parsing other packets with the same item
|
||||
// (and client version) we no longer have to create it again
|
||||
// We remove it later when no longer needed to save memory
|
||||
Bukkit.getScheduler().runTaskLaterAsynchronously(ChatItem.getInstance(), () -> STACKS.remove(p), 100L);
|
||||
}
|
||||
|
||||
obj.add("extra", parseArray(array, itemTooltip));
|
||||
if (!obj.has("text")) {
|
||||
obj.addProperty("text", "");
|
||||
}
|
||||
return obj.toString();
|
||||
}
|
||||
|
||||
public String parseEmpty(String json, String repl, List<String> tooltip, Player sender) {
|
||||
JsonObject obj = JsonParser.parseString(json).getAsJsonObject();
|
||||
JsonArray array = obj.has("extra") ? obj.getAsJsonArray("extra") : new JsonArray();
|
||||
JsonArray use = Translator
|
||||
.toJson(repl.replace("{name}", sender.getName()).replace("{display-name}", sender.getDisplayName()));
|
||||
JsonObject hover = JsonParser.parseString("{\"action\":\"show_text\", \"value\": \"\"}").getAsJsonObject();
|
||||
|
||||
StringBuilder oneLineTooltip = new StringBuilder("");
|
||||
int index = 0;
|
||||
for (String m : tooltip) {
|
||||
oneLineTooltip
|
||||
.append(m.replace("{name}", sender.getName()).replace("{display-name}", sender.getDisplayName()));
|
||||
++index;
|
||||
if (index != tooltip.size()) {
|
||||
oneLineTooltip.append('\n');
|
||||
}
|
||||
}
|
||||
|
||||
hover.add("value", new JsonPrimitive(oneLineTooltip.toString()));
|
||||
if (!tooltip.isEmpty()) {
|
||||
for (JsonElement ob : use)
|
||||
ob.getAsJsonObject().add("hoverEvent", hover);
|
||||
classicTooltip = use;
|
||||
}
|
||||
obj.add("extra", parseArray(array, classicTooltip));
|
||||
if (!obj.has("text")) {
|
||||
obj.addProperty("text", "");
|
||||
}
|
||||
return obj.toString();
|
||||
}
|
||||
|
||||
private JsonArray parseArray(JsonArray arr, JsonElement tooltip) {
|
||||
JsonArray replacer = new JsonArray();
|
||||
for (int i = 0; i < arr.size(); ++i) {
|
||||
if (arr.get(i).isJsonNull()) {
|
||||
continue;
|
||||
} else if (arr.get(i).isJsonObject()) {
|
||||
addParsedJsonObjectToArray(arr.get(i).getAsJsonObject(), replacer, tooltip);
|
||||
} else if (arr.get(i).isJsonArray()) {
|
||||
JsonArray jar = arr.get(i).getAsJsonArray();
|
||||
if (jar.size() != 0) {
|
||||
jar = parseArray(arr.get(i).getAsJsonArray(), tooltip);
|
||||
replacer.set(i, jar);
|
||||
}
|
||||
} else {
|
||||
addParsedStringToArray(arr.get(i).getAsString(), replacer, arr.get(i), tooltip);
|
||||
}
|
||||
|
||||
}
|
||||
return replacer;
|
||||
}
|
||||
|
||||
private void addParsedJsonObjectToArray(JsonObject o, JsonArray rep, JsonElement tooltip) {
|
||||
JsonElement text = o.get("text");
|
||||
if (text == null) {
|
||||
JsonElement el = o.get("extra");
|
||||
if (el != null) {
|
||||
JsonArray jar = el.getAsJsonArray();
|
||||
if (jar.size() != 0) {
|
||||
o.add("extra", parseArray(jar, tooltip));
|
||||
} else {
|
||||
o.remove("extra");
|
||||
}
|
||||
}
|
||||
return;
|
||||
} else {
|
||||
if (text.getAsString().isEmpty()) {
|
||||
JsonElement el = o.get("extra");
|
||||
if (el != null) {
|
||||
JsonArray jar = el.getAsJsonArray();
|
||||
if (jar.size() != 0) {
|
||||
o.add("extra", parseArray(jar, tooltip));
|
||||
} else {
|
||||
o.remove("extra");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
addParsedStringToArray(text.getAsString(), rep, o, tooltip);
|
||||
}
|
||||
|
||||
private void addParsedStringToArray(String msg, JsonArray rep, JsonElement o, JsonElement tooltip) {
|
||||
ChatItem.debug("Checking " + msg + " > " + rep + ", o: " + o);
|
||||
if(!ChatManager.containsSeparator(msg)) {
|
||||
rep.add(o);
|
||||
return;
|
||||
}
|
||||
String current = "";
|
||||
for(String parts : msg.split("")) {
|
||||
if(ChatManager.equalsSeparator(parts)) {
|
||||
if(!current.isEmpty()) {
|
||||
rep.add(current);
|
||||
current = "";
|
||||
}
|
||||
rep.add(tooltip);
|
||||
} else {
|
||||
current += parts;
|
||||
}
|
||||
}
|
||||
if(!current.isEmpty())
|
||||
rep.add(current);
|
||||
}
|
||||
|
||||
@SuppressWarnings({ "deprecation" })
|
||||
public static String stringifyItem(JSONManipulatorCurrent j, ItemStack is, Version protocolVersion)
|
||||
throws Exception {
|
||||
Object nmsStack = JSONManipulatorCurrent.AS_NMS_COPY.invoke(null, is);
|
||||
Object nmsTag = JSONManipulatorCurrent.NBT_TAG_COMPOUND.newInstance();
|
||||
JSONManipulatorCurrent.SAVE_NMS_ITEM_STACK_METHOD.invoke(nmsStack, nmsTag);
|
||||
HashMap<String, String> tagMap = new HashMap<>();
|
||||
Map<String, Object> nmsMap = (Map<String, Object>) JSONManipulatorCurrent.MAP.get(nmsTag);
|
||||
String id = nmsMap.get("id").toString().replace("\"", "");
|
||||
Object realTag = nmsMap.get("tag");
|
||||
if (JSONManipulatorCurrent.NBT_TAG_COMPOUND.isInstance(realTag)) { // We need to make sure this is indeed an
|
||||
// NBTTagCompound
|
||||
Map<String, Object> realMap = (Map<String, Object>) JSONManipulatorCurrent.MAP.get(realTag);
|
||||
Set<Map.Entry<String, Object>> entrySet = realMap.entrySet();
|
||||
for (Map.Entry<String, Object> entry : entrySet) {
|
||||
tagMap.put(entry.getKey(), entry.getValue().toString());
|
||||
}
|
||||
}
|
||||
// TODO check for ID remapping
|
||||
// ItemRewriter.remapIds(Version.getVersion().MAX_VER, protocolVersion.MAX_VER,
|
||||
// is);
|
||||
StringBuilder sb = new StringBuilder("{id:");
|
||||
if (protocolVersion.equals(Version.V1_7))
|
||||
sb.append(id).append(","); // Append the id
|
||||
else
|
||||
sb.append("\"").append(id).append("\"").append(","); // Append the id
|
||||
sb.append("Count:").append(is.getAmount()).append("b"); // Append the amount
|
||||
|
||||
if (!tagMap.containsKey("Damage")) { // for new versions
|
||||
sb.append(",Damage:").append(is.getDurability()).append("s"); // Append the durability data
|
||||
}
|
||||
if (tagMap.isEmpty()) {
|
||||
sb.append("}");
|
||||
return sb.toString();
|
||||
}
|
||||
Set<Map.Entry<String, String>> entrySet = tagMap.entrySet();
|
||||
boolean first = true;
|
||||
sb.append(",tag:{"); // Start of the tag
|
||||
for (Map.Entry<String, String> entry : entrySet) {
|
||||
if (!first)
|
||||
sb.append(",");
|
||||
first = false;
|
||||
if (!entry.getKey().isEmpty()) {
|
||||
if(entry.getKey().contains(";"))
|
||||
sb.append("\"" + entry.getKey() + "\"");
|
||||
else
|
||||
sb.append(entry.getKey());
|
||||
sb.append(":");
|
||||
}
|
||||
ChatItem.debug("Cleaning " + entry.getKey() + ": " + entry.getValue() + " > " + cleanStr(entry.getValue()));
|
||||
sb.append(cleanStr(entry.getValue()));
|
||||
}
|
||||
sb.append("}}"); // End of tag and end of item
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private static String cleanStr(String s) {
|
||||
return s.startsWith("'") && s.endsWith("'") ? s.substring(1, s.length() - 1) : s;
|
||||
}
|
||||
}
|
||||
+73
-5
@@ -1,17 +1,83 @@
|
||||
package me.dadus33.chatitem.json;
|
||||
|
||||
package me.dadus33.chatitem.chatmanager.v1.json;
|
||||
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import org.bukkit.ChatColor;
|
||||
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
import me.dadus33.chatitem.utils.ColorManager;
|
||||
import net.md_5.bungee.api.ChatColor;
|
||||
|
||||
//Based on DarkSeraphim's system, but using Gson and supporting some more edge cases
|
||||
public class Translator {
|
||||
|
||||
private static final String STYLES = "klmnor"; //All style codes
|
||||
|
||||
|
||||
public static JsonArray toJson(String old){
|
||||
if(old.lastIndexOf(ChatColor.COLOR_CHAR) == -1){
|
||||
JsonArray arr = new JsonArray();
|
||||
JsonObject obj = new JsonObject();
|
||||
obj.addProperty("text", old);
|
||||
arr.add(obj);
|
||||
return arr;
|
||||
}
|
||||
JsonArray message = new JsonArray();
|
||||
JsonObject next = new JsonObject();
|
||||
String colorCode = "", text = "";
|
||||
boolean waiting = false;
|
||||
for (char args : old.toCharArray()) {
|
||||
if (args == '§') { // begin of color
|
||||
if(!text.isEmpty()) {
|
||||
next.addProperty("text", text);
|
||||
message.add(next);
|
||||
next = new JsonObject();
|
||||
text = "";
|
||||
}
|
||||
waiting = true; // waiting for color code
|
||||
} else if (waiting) { // if waiting for code and valid str
|
||||
// if it's hexademical value and with enough space for full color
|
||||
waiting = false;
|
||||
if(isStyle(args)) { // is style and not making rich color code
|
||||
next.addProperty(getStyleName(args), true);
|
||||
continue;
|
||||
}
|
||||
if(args == 'x' && !colorCode.isEmpty()) {
|
||||
if(!text.isEmpty()) // ignore this if no text before
|
||||
text += ColorManager.getColorString(colorCode);
|
||||
colorCode = "x";
|
||||
} else
|
||||
colorCode += args; // a color by itself
|
||||
} else {
|
||||
waiting = false;
|
||||
if(!colorCode.isEmpty()) { // manage color
|
||||
if(colorCode.startsWith("x") && colorCode.length() == 7) { // hex color code
|
||||
next.addProperty("color", ColorManager.getColor(colorCode).getName());
|
||||
} else if(colorCode.length() == 1) { // if only one color code
|
||||
if(next.has("color"))
|
||||
text += ColorManager.getColor(colorCode);
|
||||
else
|
||||
next.addProperty("color", ColorManager.getColor(colorCode).getName());
|
||||
} else if(!text.isEmpty())// no text before -> color will be used as "color"
|
||||
text += ColorManager.getColorString(colorCode);
|
||||
|
||||
ChatItem.debug("Add " + colorCode + " to " + text + ", msg: " + message);
|
||||
colorCode = "";
|
||||
}
|
||||
// basic text, not waiting for code after '§'
|
||||
text += args;
|
||||
}
|
||||
}
|
||||
if(!text.isEmpty() || message.isEmpty()) {
|
||||
next.addProperty("text", text);
|
||||
if(!next.has("color"))
|
||||
next.addProperty("color", "white");
|
||||
message.add(next);
|
||||
}
|
||||
return message;
|
||||
}
|
||||
|
||||
public static JsonArray toJsonOld(String old){
|
||||
if(old.lastIndexOf(ChatColor.COLOR_CHAR) == -1){
|
||||
JsonArray arr = new JsonArray();
|
||||
JsonObject obj = new JsonObject();
|
||||
@@ -105,7 +171,7 @@ public class Translator {
|
||||
}
|
||||
|
||||
private static String getColorName(char code){
|
||||
return ChatColor.getByChar(code).name().toLowerCase();
|
||||
return ChatColor.getByChar(code).getName().toLowerCase();
|
||||
}
|
||||
|
||||
private static String getStyleName(char code){
|
||||
@@ -116,7 +182,9 @@ public class Translator {
|
||||
case 'n': return "underlined";
|
||||
case 'o': return "italic";
|
||||
case 'r': return "reset";
|
||||
default: return null; //Should never happen. Made it return null to throw errors if a new format pops up and it really happens
|
||||
default:
|
||||
ChatItem.getInstance().getLogger().severe("Can't find code for style " + code);
|
||||
return null; //Should never happen. Made it return null to throw errors if a new format pops up and it really happens
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
package me.dadus33.chatitem.chatmanager.v1.listeners;
|
||||
|
||||
import static me.dadus33.chatitem.chatmanager.ChatManager.SEPARATOR;
|
||||
|
||||
import java.util.StringJoiner;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.command.Command;
|
||||
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.AsyncPlayerChatEvent;
|
||||
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
import me.dadus33.chatitem.chatmanager.ChatManager;
|
||||
import me.dadus33.chatitem.chatmanager.v1.PacketEditingChatManager;
|
||||
import me.dadus33.chatitem.utils.Storage;
|
||||
import me.dadus33.chatitem.utils.Utils;
|
||||
|
||||
public class ChatEventListener implements Listener {
|
||||
|
||||
private final PacketEditingChatManager manage;
|
||||
|
||||
public ChatEventListener(PacketEditingChatManager manage) {
|
||||
this.manage = manage;
|
||||
}
|
||||
|
||||
public Storage getStorage() {
|
||||
return this.manage.getStorage();
|
||||
}
|
||||
|
||||
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST) // We need to have lowest priority in order
|
||||
// to get to the event before DeluxeChat or
|
||||
// other plugins do
|
||||
public void onChat(AsyncPlayerChatEvent e) {
|
||||
if (e.getMessage().indexOf(SEPARATOR) != -1) { // If the BELL character is found, we have to remove it
|
||||
String msg = e.getMessage().replace(Character.toString(SEPARATOR), "");
|
||||
ChatItem.debug("Already bell in message: " + e.getMessage());
|
||||
e.setMessage(msg);
|
||||
}
|
||||
boolean found = false;
|
||||
final String oldMsg = e.getMessage();
|
||||
for (String rep : getStorage().PLACEHOLDERS)
|
||||
if (oldMsg.contains(rep)) {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
|
||||
if (!found) {
|
||||
ChatItem.debug("(v1) not found placeholders in: " + e.getMessage());
|
||||
return;
|
||||
}
|
||||
|
||||
Player p = e.getPlayer();
|
||||
ItemStack item = ChatManager.getUsableItem(p);
|
||||
if(!ChatManager.canShowItem(p, item, e))
|
||||
return;
|
||||
String s = e.getMessage(), firstPlaceholder = getStorage().PLACEHOLDERS.get(0);
|
||||
for (String placeholder : getStorage().PLACEHOLDERS) {
|
||||
s = s.replace(placeholder, firstPlaceholder);
|
||||
}
|
||||
if (Utils.countMatches(s, firstPlaceholder) > getStorage().LIMIT) {
|
||||
e.setCancelled(true);
|
||||
if (getStorage().LIMIT_MESSAGE.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
p.sendMessage(getStorage().LIMIT_MESSAGE);
|
||||
return;
|
||||
}
|
||||
|
||||
ChatItem.debug("(v1) Set placeholder: " + e.getMessage());
|
||||
try {
|
||||
StringJoiner msg = new StringJoiner(" ");
|
||||
for(String part : s.split(" ")) {
|
||||
if(part.equalsIgnoreCase(firstPlaceholder)) {
|
||||
msg.add(firstPlaceholder + SEPARATOR + p.getName());
|
||||
} else {
|
||||
msg.add(part);
|
||||
}
|
||||
}
|
||||
e.setMessage(msg.toString());
|
||||
e.setFormat(e.getFormat().replace(oldMsg, e.getMessage())); // set own message for plugin that already put the message into the format
|
||||
ChatItem.debug("Message: " + e.getMessage() + ", format: " + e.getFormat());
|
||||
} catch (Exception exc) {
|
||||
exc.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.LOWEST)
|
||||
public void onCommand(final PlayerCommandPreprocessEvent e) {
|
||||
if (e.getMessage().indexOf(SEPARATOR) != -1) { // If the BELL character is found, we have to remove it
|
||||
String msg = e.getMessage().replace(Character.toString(SEPARATOR), "");
|
||||
e.setMessage(msg);
|
||||
}
|
||||
String commandString = e.getMessage().split(" ")[0].replaceAll("^/+", ""); // First part of the command, without
|
||||
// leading slashes and without
|
||||
// arguments
|
||||
Command cmd = Bukkit.getPluginCommand(commandString);
|
||||
if (cmd == null) { // not a plugin command
|
||||
if (!getStorage().ALLOWED_DEFAULT_COMMANDS.contains(commandString)) {
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
if (!getStorage().ALLOWED_PLUGIN_COMMANDS.contains(cmd)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
Player p = e.getPlayer();
|
||||
boolean found = false;
|
||||
|
||||
for (String rep : getStorage().PLACEHOLDERS) {
|
||||
if (e.getMessage().contains(rep)) {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!found) {
|
||||
return;
|
||||
}
|
||||
ItemStack item = ChatManager.getUsableItem(p);
|
||||
if(!ChatManager.canShowItem(p, item, e))
|
||||
return;
|
||||
String s = e.getMessage(), firstPlaceholder = getStorage().PLACEHOLDERS.get(0);
|
||||
for (String placeholder : getStorage().PLACEHOLDERS) {
|
||||
s = s.replace(placeholder, firstPlaceholder);
|
||||
}
|
||||
if (Utils.countMatches(s, firstPlaceholder) > getStorage().LIMIT) {
|
||||
e.setCancelled(true);
|
||||
if (getStorage().LIMIT_MESSAGE.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
p.sendMessage(getStorage().LIMIT_MESSAGE);
|
||||
return;
|
||||
}
|
||||
|
||||
ChatItem.debug("(v1) Set placeholder: " + e.getMessage());
|
||||
try {
|
||||
StringJoiner msg = new StringJoiner(" ");
|
||||
for(String part : s.split(" ")) {
|
||||
if(part.equalsIgnoreCase(firstPlaceholder)) {
|
||||
msg.add(firstPlaceholder + Character.toString(SEPARATOR) + p.getName());
|
||||
} else {
|
||||
msg.add(part);
|
||||
}
|
||||
}
|
||||
e.setMessage(msg.toString());
|
||||
} catch (Exception exc) {
|
||||
exc.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
package me.dadus33.chatitem.chatmanager.v1.listeners;
|
||||
|
||||
import static me.dadus33.chatitem.chatmanager.ChatManager.SEPARATOR;
|
||||
import static me.dadus33.chatitem.chatmanager.ChatManager.SEPARATOR_STR;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.block.ShulkerBox;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.meta.BlockStateMeta;
|
||||
import org.bukkit.inventory.meta.BookMeta;
|
||||
import org.bukkit.inventory.meta.ItemMeta;
|
||||
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
import me.dadus33.chatitem.ItemPlayer;
|
||||
import me.dadus33.chatitem.chatmanager.ChatManager;
|
||||
import me.dadus33.chatitem.chatmanager.v1.PacketEditingChatManager;
|
||||
import me.dadus33.chatitem.chatmanager.v1.basecomp.IBaseComponentGetter;
|
||||
import me.dadus33.chatitem.chatmanager.v1.basecomp.hook.AdventureComponentGetter;
|
||||
import me.dadus33.chatitem.chatmanager.v1.basecomp.hook.BaseComponentGetter;
|
||||
import me.dadus33.chatitem.chatmanager.v1.basecomp.hook.ComponentGetter;
|
||||
import me.dadus33.chatitem.chatmanager.v1.basecomp.hook.IChatBaseComponentGetter;
|
||||
import me.dadus33.chatitem.chatmanager.v1.basecomp.hook.StringComponentGetter;
|
||||
import me.dadus33.chatitem.chatmanager.v1.packets.ChatItemPacket;
|
||||
import me.dadus33.chatitem.chatmanager.v1.packets.PacketContent;
|
||||
import me.dadus33.chatitem.chatmanager.v1.packets.PacketHandler;
|
||||
import me.dadus33.chatitem.chatmanager.v1.packets.PacketType;
|
||||
import me.dadus33.chatitem.utils.ItemUtils;
|
||||
import me.dadus33.chatitem.utils.PacketUtils;
|
||||
import me.dadus33.chatitem.utils.Storage;
|
||||
import me.dadus33.chatitem.utils.Version;
|
||||
import net.md_5.bungee.api.chat.BaseComponent;
|
||||
import net.md_5.bungee.chat.ComponentSerializer;
|
||||
|
||||
public class ChatPacketManager extends PacketHandler {
|
||||
|
||||
private Object lastSentPacket = null;
|
||||
private Method serializerGetJson;
|
||||
private PacketEditingChatManager manager;
|
||||
private final List<IBaseComponentGetter> baseComponentGetter = new ArrayList<>();
|
||||
|
||||
public ChatPacketManager(PacketEditingChatManager manager) {
|
||||
this.manager = manager;
|
||||
try {
|
||||
for (Method m : PacketUtils.CHAT_SERIALIZER.getDeclaredMethods()) {
|
||||
if (m.getParameterCount() == 1 && m.getParameterTypes()[0].equals(PacketUtils.COMPONENT_CLASS)
|
||||
&& m.getReturnType().equals(String.class)) {
|
||||
serializerGetJson = m;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (serializerGetJson == null)
|
||||
ChatItem.getInstance().getLogger().warning(
|
||||
"Failed to find JSON serializer in class: " + PacketUtils.CHAT_SERIALIZER.getCanonicalName());
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
for(IBaseComponentGetter getter : Arrays.asList(new IChatBaseComponentGetter(), new BaseComponentGetter(), new ComponentGetter(), new StringComponentGetter(), new AdventureComponentGetter())) {
|
||||
if(getter.hasConditions())
|
||||
baseComponentGetter.add(getter);
|
||||
}
|
||||
ChatItem.getInstance().getLogger().info("Loaded " + baseComponentGetter.size() + " getter for base components.");
|
||||
ChatItem.debug("BaseComponentGetters: " + String.join(", ", baseComponentGetter.stream().map(IBaseComponentGetter::getClass).map(Class::getSimpleName).collect(Collectors.toList())));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSend(ChatItemPacket e) {
|
||||
if (!e.hasPlayer() || !e.getPacketType().equals(PacketType.Server.CHAT))
|
||||
return;
|
||||
if (lastSentPacket != null && lastSentPacket == e.getPacket())
|
||||
return; // prevent infinite loop
|
||||
PacketContent packet = e.getContent();
|
||||
Version version = Version.getVersion();
|
||||
String json = "{}";
|
||||
IBaseComponentGetter choosedGetter = null;
|
||||
if (version.isNewerOrEquals(Version.V1_19)) {
|
||||
if(packet.getIntegers().readSafely(0, 0) != 1)
|
||||
return;
|
||||
choosedGetter = new StringComponentGetter();
|
||||
json = choosedGetter.getBaseComponentAsJSON(e); // if null, will be re-checked so anyway
|
||||
} else if (version.isNewerOrEquals(Version.V1_12)) {
|
||||
// only if action bar messages are supported in this version of minecraft
|
||||
try {
|
||||
if (((Enum<?>) packet
|
||||
.getSpecificModifier(PacketUtils.getNmsClass("ChatMessageType", "network.chat.")).read(0))
|
||||
.name().equals("GAME_INFO")) {
|
||||
return; // It means it's an actionbar message, and we ain't intercepting those
|
||||
}
|
||||
} catch (Exception exc) {
|
||||
exc.printStackTrace();
|
||||
}
|
||||
} else if (version.isNewerOrEquals(Version.V1_8) && packet.getBytes().readSafely(0) == (byte) 2) {
|
||||
return; // It means it's an actionbar message, and we ain't intercepting those
|
||||
}
|
||||
if(json == null || choosedGetter == null) {
|
||||
for(IBaseComponentGetter getters : baseComponentGetter) {
|
||||
String tmpJson = getters.getBaseComponentAsJSON(e);
|
||||
if(tmpJson != null) {
|
||||
json = ChatManager.fixSeparator(tmpJson);
|
||||
choosedGetter = getters;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if(json == null)
|
||||
return; // can't find something
|
||||
String placeholder = choosedGetter.hasPlaceholders(getStorage(), json);
|
||||
if (placeholder == null) {
|
||||
ChatItem.debug("No placeholders founded in " + json);
|
||||
ChatItem.debug("String: " + packet.getStrings().getContent());
|
||||
return; // then it's just a normal message without placeholders, so we leave it alone
|
||||
}
|
||||
ChatItem.debug("Found " + placeholder + " with " + choosedGetter.getClass().getName());
|
||||
String toReplace = null;
|
||||
if (json.lastIndexOf(SEPARATOR) != -1)
|
||||
toReplace = ((Object) SEPARATOR).toString();
|
||||
if (json.lastIndexOf(SEPARATOR_STR) != -1)
|
||||
toReplace = SEPARATOR_STR;
|
||||
if (toReplace == null) { // if the message doesn't contain the BELL separator
|
||||
ChatItem.debug("Not containing bell " + json);
|
||||
return;
|
||||
}
|
||||
toReplace = placeholder + toReplace; // add placeholder
|
||||
String name = choosedGetter.getNameFromMessage(json, toReplace);
|
||||
if (name == null) { // something went really bad, so we run away and hide (AKA the player left or is
|
||||
// on another server)
|
||||
ChatItem.debug("Name null for " + json);
|
||||
return;
|
||||
}
|
||||
Player itemPlayer = Bukkit.getPlayer(name);
|
||||
String localJson = choosedGetter.removePlaceholdersAndName(json, toReplace, itemPlayer);
|
||||
ChatItem.debug("Local json: " + localJson);
|
||||
IBaseComponentGetter fchoosedGetter = choosedGetter;
|
||||
e.setCancelled(true); // We cancel the packet as we're going to resend it anyways (ignoring listeners
|
||||
// this time)
|
||||
Bukkit.getScheduler().runTaskAsynchronously(ChatItem.getInstance(), () -> {
|
||||
Player p = e.getPlayer();
|
||||
if (getStorage().COOLDOWN > 0 && !itemPlayer.hasPermission("chatitem.ignore-cooldown")) {
|
||||
ChatManager.applyCooldown(itemPlayer);
|
||||
}
|
||||
String message = null;
|
||||
try {
|
||||
ItemStack item = ChatManager.getUsableItem(itemPlayer);
|
||||
if (!ItemUtils.isEmpty(item)) {
|
||||
ItemStack copy = item.clone();
|
||||
|
||||
if (ItemPlayer.getPlayer(p).isBuggedClient()) {
|
||||
String act = getStorage().BUGGED_CLIENT_ACTION;
|
||||
List<String> tooltip;// = act.equalsIgnoreCase("nothing") ? new ArrayList<>() : null;
|
||||
if (act.equalsIgnoreCase("tooltip"))
|
||||
tooltip = getStorage().BUGGED_CLIENTS_TOOLTIP;
|
||||
else if (act.equalsIgnoreCase("item"))
|
||||
tooltip = ChatManager.getMaxLinesFromItem(p, copy);
|
||||
else if (act.equalsIgnoreCase("show_both")) {
|
||||
tooltip = ChatManager.getMaxLinesFromItem(p, copy);
|
||||
tooltip.addAll(getStorage().BUGGED_CLIENTS_TOOLTIP);
|
||||
} else
|
||||
tooltip = new ArrayList<>();
|
||||
message = manager.getManipulator().parseEmpty(localJson,
|
||||
ChatManager.styleItem(p, copy, getStorage()), tooltip, itemPlayer);
|
||||
if (!manager.supportsChatComponentApi()) {
|
||||
ChatItem.debug("Use basic for 1.7 lunar");
|
||||
packet.getChatComponents().write(0, jsonToChatComponent(message));
|
||||
} else {
|
||||
ChatItem.debug("Use baseComponent for 1.7 lunar");
|
||||
packet.getSpecificModifier(BaseComponent[].class).write(0,
|
||||
ComponentSerializer.parse(message));
|
||||
}
|
||||
lastSentPacket = e.getPacket();
|
||||
PacketUtils.sendPacket(p, lastSentPacket);
|
||||
return;
|
||||
}
|
||||
if (copy.getType().name().contains("_BOOK")) { // filtering written books
|
||||
BookMeta bm = (BookMeta) copy.getItemMeta();
|
||||
bm.setPages(Collections.emptyList());
|
||||
copy.setItemMeta(bm);
|
||||
} else {
|
||||
if (copy.getType().name().contains("SHULKER_BOX")) { // if it's shulker
|
||||
if (copy.hasItemMeta()) {
|
||||
BlockStateMeta bsm = (BlockStateMeta) copy.getItemMeta();
|
||||
if (bsm.hasBlockState()) {
|
||||
ShulkerBox sb = (ShulkerBox) bsm.getBlockState();
|
||||
for (ItemStack itemInv : sb.getInventory()) {
|
||||
stripData(itemInv);
|
||||
}
|
||||
bsm.setBlockState(sb);
|
||||
}
|
||||
copy.setItemMeta(bsm);
|
||||
}
|
||||
}
|
||||
}
|
||||
message = manager.getManipulator().parse(localJson, copy,
|
||||
ChatManager.styleItem(p, copy, getStorage()), ItemPlayer.getPlayer(itemPlayer).getProtocolVersion());
|
||||
} else {
|
||||
if (!getStorage().HAND_DISABLED) {
|
||||
message = manager.getManipulator().parseEmpty(localJson, getStorage().HAND_NAME, getStorage().HAND_TOOLTIP, itemPlayer);
|
||||
}
|
||||
}
|
||||
} catch (Exception e1) {
|
||||
e1.printStackTrace();
|
||||
}
|
||||
if (message != null) {
|
||||
ChatItem.debug("(v1) Writing message: " + message);
|
||||
fchoosedGetter.writeJson(e, message);
|
||||
}
|
||||
lastSentPacket = e.getPacket();
|
||||
PacketUtils.sendPacket(p, lastSentPacket);
|
||||
});
|
||||
}
|
||||
|
||||
private Object jsonToChatComponent(String json) {
|
||||
try {
|
||||
return PacketUtils.CHAT_SERIALIZER.getMethod("a", String.class).invoke(null, json);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private void stripData(ItemStack i) {
|
||||
if (i == null) {
|
||||
return;
|
||||
}
|
||||
if (i.getType().equals(Material.AIR)) {
|
||||
return;
|
||||
}
|
||||
if (!i.hasItemMeta()) {
|
||||
return;
|
||||
}
|
||||
ItemMeta im = Bukkit.getItemFactory().getItemMeta(i.getType());
|
||||
ItemMeta original = i.getItemMeta();
|
||||
if (original.hasDisplayName()) {
|
||||
im.setDisplayName(original.getDisplayName());
|
||||
}
|
||||
i.setItemMeta(im);
|
||||
}
|
||||
|
||||
public Storage getStorage() {
|
||||
return manager.getStorage();
|
||||
}
|
||||
}
|
||||
+8
-7
@@ -1,5 +1,4 @@
|
||||
package me.dadus33.chatitem.listeners;
|
||||
|
||||
package me.dadus33.chatitem.chatmanager.v1.listeners;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
|
||||
@@ -10,16 +9,18 @@ import com.comphenix.protocol.events.PacketEvent;
|
||||
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
import me.dadus33.chatitem.playerversion.hooks.DefaultVersionHook;
|
||||
import me.dadus33.chatitem.utils.ProtocolVersion;
|
||||
import me.dadus33.chatitem.utils.Version;
|
||||
|
||||
public class HandshakeListener extends PacketAdapter{
|
||||
public class HandshakeListener extends PacketAdapter {
|
||||
|
||||
public HandshakeListener() {
|
||||
super(ChatItem.getInstance(), ListenerPriority.MONITOR, PacketType.Handshake.Client.SET_PROTOCOL);
|
||||
public HandshakeListener(ChatItem pl) {
|
||||
super(pl, ListenerPriority.MONITOR, PacketType.Handshake.Client.SET_PROTOCOL);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPacketReceiving(final PacketEvent e){
|
||||
if(e.isPlayerTemporary() || e.getPlayer() == null)
|
||||
return;
|
||||
PacketType.Protocol p = e.getPacket().getProtocols().read(0);
|
||||
if(p == PacketType.Protocol.STATUS || p == PacketType.Protocol.LEGACY){
|
||||
return;
|
||||
@@ -27,6 +28,6 @@ public class HandshakeListener extends PacketAdapter{
|
||||
final int version = e.getPacket().getIntegers().readSafely(0);
|
||||
//Delay the mapping to make sure the true address of the player was received when using bungeecord or other types of proxies
|
||||
Bukkit.getScheduler().scheduleSyncDelayedTask(getPlugin(), () ->
|
||||
DefaultVersionHook.PROTOCOL_PER_ADDRESS.put(ProtocolVersion.stringifyAdress(e.getPlayer().getAddress()), version), 10L);
|
||||
DefaultVersionHook.PROTOCOL_PER_ADDRESS.put(Version.stringifyAdress(e.getPlayer().getAddress()), version), 10L);
|
||||
}
|
||||
}
|
||||
+6
-7
@@ -1,14 +1,13 @@
|
||||
package me.dadus33.chatitem.packets;
|
||||
package me.dadus33.chatitem.chatmanager.v1.packets;
|
||||
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
public class ChatItemPacket {
|
||||
|
||||
protected Player player;
|
||||
protected final Player player;
|
||||
protected Object packet;
|
||||
protected PacketType type;
|
||||
protected boolean cancel = false;
|
||||
protected PacketMetadata metaData = new PacketMetadata();
|
||||
|
||||
public ChatItemPacket(PacketType type, Object packet, Player player) {
|
||||
this.player = player;
|
||||
@@ -31,6 +30,10 @@ public class ChatItemPacket {
|
||||
public Object getPacket() {
|
||||
return packet;
|
||||
}
|
||||
|
||||
public void setPacket(Object packet) {
|
||||
this.packet = packet;
|
||||
}
|
||||
|
||||
public String getPacketName() {
|
||||
return packet.getClass().getSimpleName();
|
||||
@@ -51,8 +54,4 @@ public class ChatItemPacket {
|
||||
public PacketContent getContent() {
|
||||
return new PacketContent(this);
|
||||
}
|
||||
|
||||
public PacketMetadata getMetaData() {
|
||||
return metaData;
|
||||
}
|
||||
}
|
||||
+15
-10
@@ -1,11 +1,13 @@
|
||||
package me.dadus33.chatitem.packets;
|
||||
package me.dadus33.chatitem.chatmanager.v1.packets;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
import me.dadus33.chatitem.packets.custom.CustomPacketManager;
|
||||
import me.dadus33.chatitem.packets.protocollib.ProtocollibPacketManager;
|
||||
import me.dadus33.chatitem.chatmanager.v1.packets.custom.CustomPacketManager;
|
||||
import me.dadus33.chatitem.chatmanager.v1.packets.protocollib.ProtocollibPacketManager;
|
||||
|
||||
public class ChatItemPacketManager {
|
||||
|
||||
@@ -18,12 +20,14 @@ public class ChatItemPacketManager {
|
||||
pl.getLogger().info("The plugin ProtocolLib has been detected. Loading Protocollib support ...");
|
||||
packetManager = new ProtocollibPacketManager(pl);
|
||||
} else {
|
||||
pl.getLogger().warning("The plugin ProtocolLib has been detected but you have an OLD version, so we cannot use it.");
|
||||
pl.getLogger().warning("The plugin ProtocolLib has been detected but you have an old or too new version, so we cannot use it.");
|
||||
pl.getLogger().warning("Fallback to default Packet system ...");
|
||||
packetManager = new CustomPacketManager(pl);
|
||||
}
|
||||
} else
|
||||
} else {
|
||||
pl.getLogger().info("Loading own packet system.");
|
||||
packetManager = new CustomPacketManager(pl);
|
||||
}
|
||||
}
|
||||
|
||||
public PacketManager getPacketManager() {
|
||||
@@ -31,11 +35,12 @@ public class ChatItemPacketManager {
|
||||
}
|
||||
|
||||
private boolean checkProtocollibConditions() {
|
||||
try {
|
||||
Class.forName("com.comphenix.protocol.injector.server.TemporaryPlayer");
|
||||
return true;
|
||||
} catch (ClassNotFoundException e) {
|
||||
return false;
|
||||
for(String searchedClass : Arrays.asList("com.comphenix.protocol.injector.server.TemporaryPlayer", "com.comphenix.protocol.injector.temporary.TemporaryPlayer")) { // class since 4.4.0 until 4.8.0, then the new one
|
||||
try {
|
||||
Class.forName(searchedClass);
|
||||
return true; // class found
|
||||
} catch (ClassNotFoundException e) {}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
+12
-3
@@ -1,9 +1,11 @@
|
||||
package me.dadus33.chatitem.packets;
|
||||
package me.dadus33.chatitem.chatmanager.v1.packets;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.Objects;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import me.dadus33.chatitem.utils.PacketUtils;
|
||||
|
||||
@@ -148,7 +150,7 @@ public class PacketContent {
|
||||
* @throws NoSuchElementException if the value doesn't exist
|
||||
*/
|
||||
public T read(int i) {
|
||||
return content.values().stream().filter(Objects::nonNull).findFirst().get();
|
||||
return content.values().stream().filter(Objects::nonNull).collect(Collectors.toList()).get(i);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -169,7 +171,8 @@ public class PacketContent {
|
||||
* @return the requested value.
|
||||
*/
|
||||
public T readSafely(int i, T defaultValue) {
|
||||
return content.values().stream().filter(Objects::nonNull).findFirst().orElse(defaultValue);
|
||||
List<T> vals = content.values().stream().filter(Objects::nonNull).collect(Collectors.toList());
|
||||
return vals.size() <= i ? defaultValue : vals.get(i);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -185,6 +188,12 @@ public class PacketContent {
|
||||
} else {
|
||||
content.put(key, value);
|
||||
try {
|
||||
key.setAccessible(true);
|
||||
/*if(Modifier.isFinal(key.getModifiers())) {
|
||||
Field modifiersField = Field.class.getDeclaredField("modifiers");
|
||||
modifiersField.setAccessible(true);
|
||||
modifiersField.setInt(key, key.getModifiers() & ~Modifier.FINAL);
|
||||
}*/
|
||||
key.set(obj, value);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package me.dadus33.chatitem.packets;
|
||||
package me.dadus33.chatitem.chatmanager.v1.packets;
|
||||
|
||||
public abstract class PacketHandler {
|
||||
|
||||
+4
-4
@@ -1,4 +1,4 @@
|
||||
package me.dadus33.chatitem.packets;
|
||||
package me.dadus33.chatitem.chatmanager.v1.packets;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
@@ -6,9 +6,9 @@ import org.bukkit.entity.Player;
|
||||
|
||||
public abstract class PacketManager {
|
||||
|
||||
public abstract void addPlayer(Player p);
|
||||
public abstract void removePlayer(Player p);
|
||||
public abstract void clear();
|
||||
public void addPlayer(Player p) {}
|
||||
public void removePlayer(Player p) {}
|
||||
public abstract void stop();
|
||||
|
||||
private final ArrayList<PacketHandler> handlers = new ArrayList<>();
|
||||
public boolean addHandler(PacketHandler handler) {
|
||||
+15
-3
@@ -1,6 +1,7 @@
|
||||
package me.dadus33.chatitem.packets;
|
||||
package me.dadus33.chatitem.chatmanager.v1.packets;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
public interface PacketType {
|
||||
@@ -10,6 +11,13 @@ public interface PacketType {
|
||||
String getFullName();
|
||||
List<String> getAlias();
|
||||
|
||||
public static List<PacketType> values() {
|
||||
List<PacketType> list = new ArrayList<>();
|
||||
list.addAll(Arrays.asList(Server.values()));
|
||||
list.addAll(Arrays.asList(Handshake.values()));
|
||||
return list;
|
||||
}
|
||||
|
||||
static final String SERVER_PREFIX = "PacketPlayOut", HANDSHAKE_PREFIX = "PacketHandshaking";
|
||||
|
||||
public static PacketType getType(String packetName) {
|
||||
@@ -18,6 +26,10 @@ public interface PacketType {
|
||||
} else if(packetName.startsWith(HANDSHAKE_PREFIX)) {
|
||||
return getPacketTypeFor(packetName, Handshake.values(), Handshake.UNSET);
|
||||
} else {
|
||||
for(PacketType types : values()) {
|
||||
if(types.getFullName().equalsIgnoreCase(packetName) || types.getAlias().contains(packetName))
|
||||
return types;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -31,7 +43,7 @@ public interface PacketType {
|
||||
|
||||
public static enum Server implements PacketType {
|
||||
|
||||
CHAT("Chat"),
|
||||
CHAT("Chat", "ClientboundPlayerChatPacket", "ClientboundSystemChatPacket"),
|
||||
UNSET("Unset");
|
||||
|
||||
private final String packetName, fullName;
|
||||
@@ -41,7 +53,7 @@ public interface PacketType {
|
||||
this.packetName = packetName;
|
||||
this.fullName = SERVER_PREFIX + packetName;
|
||||
for(String al : alias)
|
||||
this.alias.add(SERVER_PREFIX + al);
|
||||
this.alias.add(al);
|
||||
}
|
||||
|
||||
@Override
|
||||
+20
-22
@@ -1,4 +1,4 @@
|
||||
package me.dadus33.chatitem.packets.custom;
|
||||
package me.dadus33.chatitem.chatmanager.v1.packets.custom;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
@@ -10,15 +10,15 @@ import org.bukkit.event.player.PlayerJoinEvent;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
|
||||
import me.dadus33.chatitem.packets.ChatItemPacket;
|
||||
import me.dadus33.chatitem.packets.PacketManager;
|
||||
import me.dadus33.chatitem.packets.PacketType;
|
||||
import me.dadus33.chatitem.packets.custom.channel.ChannelAbstract;
|
||||
import me.dadus33.chatitem.packets.custom.channel.INC2Channel;
|
||||
import me.dadus33.chatitem.packets.custom.channel.INCChannel;
|
||||
import me.dadus33.chatitem.packets.custom.channel.NMUChannel;
|
||||
import me.dadus33.chatitem.utils.ProtocolVersion;
|
||||
import me.dadus33.chatitem.chatmanager.v1.packets.ChatItemPacket;
|
||||
import me.dadus33.chatitem.chatmanager.v1.packets.PacketManager;
|
||||
import me.dadus33.chatitem.chatmanager.v1.packets.PacketType;
|
||||
import me.dadus33.chatitem.chatmanager.v1.packets.custom.channel.ChannelAbstract;
|
||||
import me.dadus33.chatitem.chatmanager.v1.packets.custom.channel.INC2Channel;
|
||||
import me.dadus33.chatitem.chatmanager.v1.packets.custom.channel.INCChannel;
|
||||
import me.dadus33.chatitem.chatmanager.v1.packets.custom.channel.NMUChannel;
|
||||
import me.dadus33.chatitem.utils.Utils;
|
||||
import me.dadus33.chatitem.utils.Version;
|
||||
|
||||
public class CustomPacketManager extends PacketManager implements Listener {
|
||||
|
||||
@@ -29,24 +29,21 @@ public class CustomPacketManager extends PacketManager implements Listener {
|
||||
|
||||
public CustomPacketManager(Plugin pl) {
|
||||
this.pl = pl;
|
||||
ProtocolVersion version = ProtocolVersion.getServerVersion();
|
||||
if (version.isNewerOrEquals(ProtocolVersion.V1_17))
|
||||
Version version = Version.getVersion();
|
||||
if (version.isNewerOrEquals(Version.V1_17))
|
||||
channel = new INC2Channel(this);
|
||||
else if (version.equals(ProtocolVersion.V1_7))
|
||||
else if (version.equals(Version.V1_7))
|
||||
channel = new NMUChannel(this);
|
||||
else
|
||||
channel = new INCChannel(this);
|
||||
pl.getServer().getPluginManager().registerEvents(this, pl);
|
||||
|
||||
// we wait the start server
|
||||
Bukkit.getScheduler().runTaskLater(pl, new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
isStarted = true;
|
||||
for(Player p : Utils.getOnlinePlayers())
|
||||
addPlayer(p);
|
||||
}
|
||||
}, 40);
|
||||
Bukkit.getScheduler().runTaskLater(pl, () -> {
|
||||
isStarted = true;
|
||||
for(Player p : Utils.getOnlinePlayers())
|
||||
addPlayer(p);
|
||||
}, 20);
|
||||
}
|
||||
|
||||
public Plugin getPlugin() {
|
||||
@@ -75,7 +72,7 @@ public class CustomPacketManager extends PacketManager implements Listener {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
public void stop() {
|
||||
for(Player player : Utils.getOnlinePlayers())
|
||||
removePlayer(player);
|
||||
if(channel.getAddChannelExecutor() != null)
|
||||
@@ -85,8 +82,9 @@ public class CustomPacketManager extends PacketManager implements Listener {
|
||||
}
|
||||
|
||||
public ChatItemPacket onPacketSent(PacketType type, Player sender, Object packet) {
|
||||
if(type == null)
|
||||
if(type == null) {
|
||||
return null;
|
||||
}
|
||||
ChatItemPacket customPacket = new ChatItemPacket(type, packet, sender);
|
||||
notifyHandlersSent(customPacket);
|
||||
return customPacket;
|
||||
+20
-7
@@ -1,19 +1,21 @@
|
||||
package me.dadus33.chatitem.packets.custom.channel;
|
||||
package me.dadus33.chatitem.chatmanager.v1.packets.custom.channel;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import me.dadus33.chatitem.packets.custom.CustomPacketManager;
|
||||
import me.dadus33.chatitem.playerversion.hooks.DefaultVersionHook;
|
||||
import me.dadus33.chatitem.ItemPlayer;
|
||||
import me.dadus33.chatitem.chatmanager.v1.packets.custom.CustomPacketManager;
|
||||
|
||||
public abstract class ChannelAbstract {
|
||||
|
||||
private ExecutorService addChannelExecutor, removeChannelExecutor;
|
||||
static final String KEY_HANDSHAKE = "packet_handshake_negativity", KEY_HANDLER_SERVER = "packet_handler", KEY_SERVER = "packet_server_negativity";
|
||||
static final String KEY_HANDSHAKE = "packet_handshake_chatitem", KEY_HANDLER_SERVER = "packet_handler", KEY_SERVER = "packet_server_chatitem";
|
||||
|
||||
private CustomPacketManager customPacketManager;
|
||||
private HashSet<UUID> players = new HashSet<>();
|
||||
@@ -31,7 +33,7 @@ public abstract class ChannelAbstract {
|
||||
}
|
||||
|
||||
public ExecutorService getOrCreateAddChannelExecutor() {
|
||||
if(addChannelExecutor == null)
|
||||
if(addChannelExecutor == null || addChannelExecutor.isTerminated())
|
||||
addChannelExecutor = Executors.newSingleThreadExecutor();
|
||||
return addChannelExecutor;
|
||||
}
|
||||
@@ -41,7 +43,7 @@ public abstract class ChannelAbstract {
|
||||
}
|
||||
|
||||
public ExecutorService getOrCreateRemoveChannelExecutor() {
|
||||
if(removeChannelExecutor == null)
|
||||
if(removeChannelExecutor == null || removeChannelExecutor.isTerminated())
|
||||
removeChannelExecutor = Executors.newSingleThreadExecutor();
|
||||
return removeChannelExecutor;
|
||||
}
|
||||
@@ -52,7 +54,7 @@ public abstract class ChannelAbstract {
|
||||
try {
|
||||
Integer protocol = customPacketManager.protocolVersionPerChannel.remove(getChannel(p));
|
||||
if(protocol != null)
|
||||
DefaultVersionHook.PROTOCOL_PER_UUID.put(p.getUniqueId(), protocol);
|
||||
ItemPlayer.getPlayer(p).setProtocolVersion(protocol);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
@@ -64,6 +66,17 @@ public abstract class ChannelAbstract {
|
||||
removeChannel(p, p.getUniqueId().toString());
|
||||
}
|
||||
|
||||
public void removeAllPlayers() {
|
||||
new ArrayList<>(players).forEach((uuid) -> {
|
||||
Player p = Bukkit.getPlayer(uuid);
|
||||
if(p != null) // player don't left
|
||||
removeChannel(Bukkit.getPlayer(uuid), uuid.toString());
|
||||
});
|
||||
players.clear();
|
||||
}
|
||||
|
||||
protected abstract void stopPipelines();
|
||||
|
||||
public abstract void addChannel(Player player, String endChannelName);
|
||||
|
||||
public abstract void removeChannel(Player player, String endChannelName);
|
||||
+26
-9
@@ -1,31 +1,42 @@
|
||||
package me.dadus33.chatitem.packets.custom.channel;
|
||||
package me.dadus33.chatitem.chatmanager.v1.packets.custom.channel;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.logging.Level;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
|
||||
import io.netty.channel.Channel;
|
||||
import io.netty.channel.ChannelHandler;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.ChannelInboundHandlerAdapter;
|
||||
import io.netty.channel.ChannelInitializer;
|
||||
import me.dadus33.chatitem.packets.ChatItemPacket;
|
||||
import me.dadus33.chatitem.packets.PacketContent;
|
||||
import me.dadus33.chatitem.packets.PacketType;
|
||||
import me.dadus33.chatitem.packets.custom.CustomPacketManager;
|
||||
import io.netty.channel.ChannelPipeline;
|
||||
import me.dadus33.chatitem.chatmanager.v1.packets.PacketContent;
|
||||
import me.dadus33.chatitem.chatmanager.v1.packets.PacketType;
|
||||
import me.dadus33.chatitem.chatmanager.v1.packets.PacketContent.ContentModifier;
|
||||
import me.dadus33.chatitem.chatmanager.v1.packets.custom.CustomPacketManager;
|
||||
|
||||
public class ChannelInboundHandler extends ChannelInboundHandlerAdapter {
|
||||
|
||||
public static final HashMap<Channel, ChatItemPacket> TMP = new HashMap<>();
|
||||
private CustomPacketManager packetManager;
|
||||
private List<ChannelPipeline> pipelines = new ArrayList<>();
|
||||
|
||||
public ChannelInboundHandler(CustomPacketManager packetManager) {
|
||||
this.packetManager = packetManager;
|
||||
}
|
||||
|
||||
public void clean() {
|
||||
pipelines.forEach(ChannelPipeline::removeFirst);
|
||||
pipelines.clear();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
|
||||
ctx.fireChannelRead(msg);
|
||||
((Channel) msg).pipeline().addFirst(new ChannelInitializer<Channel>() {
|
||||
ChannelPipeline pipe = ((Channel) msg).pipeline();
|
||||
pipelines.add(pipe);
|
||||
pipe.addFirst(new ChannelInitializer<Channel>() {
|
||||
@Override
|
||||
protected void initChannel(Channel channel) {
|
||||
try {
|
||||
@@ -63,7 +74,13 @@ public class ChannelInboundHandler extends ChannelInboundHandlerAdapter {
|
||||
try {
|
||||
PacketType packetType = PacketType.getType(packet.getClass().getSimpleName());
|
||||
if(packetType != null && packetType == PacketType.Handshake.IS_SET_PROTOCOL) {
|
||||
packetManager.protocolVersionPerChannel.put(channel, new PacketContent(packet).getIntegers().readSafely(0, 0));
|
||||
ContentModifier<Integer> ints = new PacketContent(packet).getIntegers();
|
||||
int possibleProtocol = ints.readSafely(0, 0);
|
||||
if(possibleProtocol == Bukkit.getPort())
|
||||
possibleProtocol = ints.readSafely(1, 0);
|
||||
if(possibleProtocol == -1 || possibleProtocol == 255)
|
||||
possibleProtocol = ints.readSafely(2, 0);
|
||||
packetManager.protocolVersionPerChannel.put(channel, possibleProtocol);
|
||||
}
|
||||
super.channelRead(ctx, packet);
|
||||
} catch (Exception e) {
|
||||
+23
-17
@@ -1,4 +1,4 @@
|
||||
package me.dadus33.chatitem.packets.custom.channel;
|
||||
package me.dadus33.chatitem.chatmanager.v1.packets.custom.channel;
|
||||
|
||||
import static me.dadus33.chatitem.utils.PacketUtils.getPlayerConnection;
|
||||
|
||||
@@ -11,31 +11,42 @@ import io.netty.channel.Channel;
|
||||
import io.netty.channel.ChannelFuture;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.ChannelOutboundHandlerAdapter;
|
||||
import io.netty.channel.ChannelPipeline;
|
||||
import io.netty.channel.ChannelPromise;
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
import me.dadus33.chatitem.packets.ChatItemPacket;
|
||||
import me.dadus33.chatitem.packets.PacketType;
|
||||
import me.dadus33.chatitem.packets.custom.CustomPacketManager;
|
||||
import me.dadus33.chatitem.playerversion.hooks.DefaultVersionHook;
|
||||
import me.dadus33.chatitem.chatmanager.v1.packets.ChatItemPacket;
|
||||
import me.dadus33.chatitem.chatmanager.v1.packets.PacketType;
|
||||
import me.dadus33.chatitem.chatmanager.v1.packets.custom.CustomPacketManager;
|
||||
import me.dadus33.chatitem.utils.PacketUtils;
|
||||
import me.dadus33.chatitem.utils.ProtocolVersion;
|
||||
import me.dadus33.chatitem.utils.ReflectionUtils;
|
||||
import me.dadus33.chatitem.utils.Version;
|
||||
|
||||
public class INC2Channel extends ChannelAbstract {
|
||||
|
||||
private final ChannelInboundHandler boundHandler;
|
||||
private ChannelPipeline pipeline;
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public INC2Channel(CustomPacketManager customPacketManager) {
|
||||
super(customPacketManager);
|
||||
boundHandler = new ChannelInboundHandler(customPacketManager);
|
||||
try {
|
||||
Object mcServer = ReflectionUtils.callMethod(PacketUtils.getCraftServer(), "getServer");
|
||||
Object mcServer = ReflectionUtils.callMethod(PacketUtils.getCraftServer(), Version.getVersion().equals(Version.V1_17) ? "getServer" : "b");
|
||||
Object co = ReflectionUtils.getFirstWith(mcServer, PacketUtils.getNmsClass("MinecraftServer", "server."), PacketUtils.getNmsClass("ServerConnection", "server.network."));
|
||||
((List<ChannelFuture>) ReflectionUtils.getField(co, "f")).forEach((channelFuture) -> {
|
||||
channelFuture.channel().pipeline().addFirst(new ChannelInboundHandler(customPacketManager));
|
||||
((List<ChannelFuture>) ReflectionUtils.getObject(co, "f")).forEach((channelFuture) -> {
|
||||
pipeline = channelFuture.channel().pipeline();
|
||||
pipeline.addFirst(boundHandler);
|
||||
});
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void stopPipelines() {
|
||||
pipeline.remove(boundHandler);
|
||||
boundHandler.clean();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addChannel(final Player player, String endChannelName) {
|
||||
@@ -46,10 +57,6 @@ public class INC2Channel extends ChannelAbstract {
|
||||
Channel channel = getChannel(player);
|
||||
// Managing outgoing packet (to the player)
|
||||
channel.pipeline().addAfter(KEY_HANDLER_SERVER, KEY_SERVER + endChannelName, new ChannelHandlerSent(player));
|
||||
|
||||
ChatItemPacket pa = ChannelInboundHandler.TMP.remove(channel);
|
||||
if(pa != null)
|
||||
DefaultVersionHook.PROTOCOL_PER_UUID.put(player.getUniqueId(), pa.getContent().getIntegers().readSafely(0, ProtocolVersion.getServerVersion().MAX_VER));
|
||||
} catch (NoSuchElementException e) {
|
||||
// appear when the player's channel isn't accessible because of reload.
|
||||
getPacketManager().getPlugin().getLogger().warning("Please, don't use reload, this can produce some problem. Currently, " + player.getName() + " isn't fully checked because of that. More details: " + e.getMessage() + " (NoSuchElementException)");
|
||||
@@ -80,9 +87,8 @@ public class INC2Channel extends ChannelAbstract {
|
||||
|
||||
@Override
|
||||
public Channel getChannel(Player p) throws Exception {
|
||||
Object playerConnection = getPlayerConnection(p);
|
||||
Object networkManager = playerConnection.getClass().getField("a").get(playerConnection);
|
||||
return (Channel) networkManager.getClass().getDeclaredField("k").get(networkManager);//(Channel) networkManager.getClass().getDeclaredField("channel").get(networkManager);
|
||||
Object playerConnection = ReflectionUtils.getObject(getPlayerConnection(p), Version.getVersion().isNewerOrEquals(Version.V1_19) ? "b" : "a");
|
||||
return ReflectionUtils.getFirstWith(playerConnection, playerConnection.getClass(), Channel.class);//(Channel) networkManager.getClass().getDeclaredField("channel").get(networkManager);
|
||||
}
|
||||
|
||||
private class ChannelHandlerSent extends ChannelOutboundHandlerAdapter {
|
||||
@@ -98,7 +104,7 @@ public class INC2Channel extends ChannelAbstract {
|
||||
ChatItemPacket nextPacket = getPacketManager().onPacketSent(PacketType.getType(packet.getClass().getSimpleName()), owner, packet);
|
||||
if(nextPacket != null && nextPacket.isCancelled())
|
||||
return;
|
||||
super.write(ctx, packet, promise);
|
||||
super.write(ctx, nextPacket == null ? packet : nextPacket.getPacket(), promise);
|
||||
}
|
||||
}
|
||||
}
|
||||
+22
-21
@@ -1,4 +1,4 @@
|
||||
package me.dadus33.chatitem.packets.custom.channel;
|
||||
package me.dadus33.chatitem.chatmanager.v1.packets.custom.channel;
|
||||
|
||||
import static me.dadus33.chatitem.utils.PacketUtils.getPlayerConnection;
|
||||
|
||||
@@ -12,24 +12,28 @@ import io.netty.channel.Channel;
|
||||
import io.netty.channel.ChannelFuture;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.ChannelOutboundHandlerAdapter;
|
||||
import io.netty.channel.ChannelPipeline;
|
||||
import io.netty.channel.ChannelPromise;
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
import me.dadus33.chatitem.packets.ChatItemPacket;
|
||||
import me.dadus33.chatitem.packets.PacketContent;
|
||||
import me.dadus33.chatitem.packets.PacketType;
|
||||
import me.dadus33.chatitem.packets.custom.CustomPacketManager;
|
||||
import me.dadus33.chatitem.playerversion.hooks.DefaultVersionHook;
|
||||
import me.dadus33.chatitem.chatmanager.v1.packets.ChatItemPacket;
|
||||
import me.dadus33.chatitem.chatmanager.v1.packets.PacketContent;
|
||||
import me.dadus33.chatitem.chatmanager.v1.packets.PacketType;
|
||||
import me.dadus33.chatitem.chatmanager.v1.packets.custom.CustomPacketManager;
|
||||
import me.dadus33.chatitem.utils.PacketUtils;
|
||||
import me.dadus33.chatitem.utils.ProtocolVersion;
|
||||
import me.dadus33.chatitem.utils.ReflectionUtils;
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public class INCChannel extends ChannelAbstract {
|
||||
|
||||
private final ChannelInboundHandler boundHandler;
|
||||
private ChannelPipeline pipeline;
|
||||
|
||||
public INCChannel(CustomPacketManager customPacketManager) {
|
||||
super(customPacketManager);
|
||||
boundHandler = new ChannelInboundHandler(customPacketManager);
|
||||
getFuturChannel().forEach((channelFuture) -> {
|
||||
channelFuture.channel().pipeline().addFirst(new ChannelInboundHandler(customPacketManager));
|
||||
pipeline = channelFuture.channel().pipeline();
|
||||
pipeline.addFirst(boundHandler);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -48,6 +52,12 @@ public class INCChannel extends ChannelAbstract {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void stopPipelines() {
|
||||
pipeline.remove(boundHandler);
|
||||
boundHandler.clean();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addChannel(final Player player, String endChannelName) {
|
||||
@@ -58,10 +68,6 @@ public class INCChannel extends ChannelAbstract {
|
||||
Channel channel = getChannel(player);
|
||||
// Managing outgoing packet (to the player)
|
||||
channel.pipeline().addAfter(KEY_HANDLER_SERVER, KEY_SERVER + endChannelName, new ChannelHandlerSent(player));
|
||||
|
||||
ChatItemPacket pa = ChannelInboundHandler.TMP.remove(channel);
|
||||
if(pa != null)
|
||||
DefaultVersionHook.PROTOCOL_PER_UUID.put(player.getUniqueId(), pa.getContent().getIntegers().readSafely(0, ProtocolVersion.getServerVersion().MAX_VER));
|
||||
} catch (NoSuchElementException e) {
|
||||
// appear when the player's channel isn't accessible because of reload.
|
||||
getPacketManager().getPlugin().getLogger().warning("Please, don't use reload, this can produce some problem. Currently, " + player.getName() + " isn't fully checked because of that. More details: " + e.getMessage() + " (NoSuchElementException)");
|
||||
@@ -108,15 +114,10 @@ public class INCChannel extends ChannelAbstract {
|
||||
|
||||
@Override
|
||||
public void write(ChannelHandlerContext ctx, Object packet, ChannelPromise promise) throws Exception {
|
||||
try {
|
||||
ChatItemPacket nextPacket = getPacketManager().onPacketSent(PacketType.getType(packet.getClass().getSimpleName()), owner, packet);
|
||||
if(nextPacket != null && nextPacket.isCancelled())
|
||||
return;
|
||||
super.write(ctx, packet, promise);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
super.write(ctx, packet, promise);
|
||||
}
|
||||
ChatItemPacket nextPacket = getPacketManager().onPacketSent(PacketType.getType(packet.getClass().getSimpleName()), owner, packet);
|
||||
if(nextPacket != null && nextPacket.isCancelled())
|
||||
return;
|
||||
super.write(ctx, nextPacket == null ? packet : nextPacket.getPacket(), promise);
|
||||
}
|
||||
}
|
||||
}
|
||||
+19
-9
@@ -1,4 +1,4 @@
|
||||
package me.dadus33.chatitem.packets.custom.channel;
|
||||
package me.dadus33.chatitem.chatmanager.v1.packets.custom.channel;
|
||||
|
||||
import static me.dadus33.chatitem.utils.PacketUtils.getPlayerConnection;
|
||||
|
||||
@@ -9,10 +9,10 @@ import java.util.logging.Level;
|
||||
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import me.dadus33.chatitem.packets.ChatItemPacket;
|
||||
import me.dadus33.chatitem.packets.PacketContent;
|
||||
import me.dadus33.chatitem.packets.PacketType;
|
||||
import me.dadus33.chatitem.packets.custom.CustomPacketManager;
|
||||
import me.dadus33.chatitem.chatmanager.v1.packets.ChatItemPacket;
|
||||
import me.dadus33.chatitem.chatmanager.v1.packets.PacketContent;
|
||||
import me.dadus33.chatitem.chatmanager.v1.packets.PacketType;
|
||||
import me.dadus33.chatitem.chatmanager.v1.packets.custom.CustomPacketManager;
|
||||
import me.dadus33.chatitem.utils.PacketUtils;
|
||||
import me.dadus33.chatitem.utils.ReflectionUtils;
|
||||
import net.minecraft.util.io.netty.channel.Channel;
|
||||
@@ -22,10 +22,14 @@ import net.minecraft.util.io.netty.channel.ChannelHandlerContext;
|
||||
import net.minecraft.util.io.netty.channel.ChannelInboundHandlerAdapter;
|
||||
import net.minecraft.util.io.netty.channel.ChannelInitializer;
|
||||
import net.minecraft.util.io.netty.channel.ChannelOutboundHandlerAdapter;
|
||||
import net.minecraft.util.io.netty.channel.ChannelPipeline;
|
||||
import net.minecraft.util.io.netty.channel.ChannelPromise;
|
||||
|
||||
public class NMUChannel extends ChannelAbstract {
|
||||
|
||||
private ChannelInboundHandlerAdapter boundHandler;
|
||||
private ChannelPipeline pipeline;
|
||||
|
||||
public NMUChannel(CustomPacketManager customPacketManager) {
|
||||
super(customPacketManager);
|
||||
try {
|
||||
@@ -33,9 +37,10 @@ public class NMUChannel extends ChannelAbstract {
|
||||
Object mcServer = dedicatedSrv.getClass().getMethod("getServer").invoke(dedicatedSrv);
|
||||
Object co = ReflectionUtils.getFirstWith(mcServer, PacketUtils.getNmsClass("MinecraftServer", "server."), PacketUtils.getNmsClass("ServerConnection", "network."));
|
||||
@SuppressWarnings("unchecked")
|
||||
List<ChannelFuture> g = (List<ChannelFuture>) ReflectionUtils.getField(co, "g");
|
||||
List<ChannelFuture> g = (List<ChannelFuture>) ReflectionUtils.getObject(co, "g", "e");
|
||||
g.forEach((channelFuture) -> {
|
||||
channelFuture.channel().pipeline().addFirst(new ChannelInboundHandlerAdapter() {
|
||||
pipeline = channelFuture.channel().pipeline();
|
||||
pipeline.addFirst(boundHandler = new ChannelInboundHandlerAdapter() {
|
||||
@Override
|
||||
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
|
||||
((Channel) msg).pipeline().addFirst(new ChannelInitializer<Channel>() {
|
||||
@@ -69,6 +74,11 @@ public class NMUChannel extends ChannelAbstract {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void stopPipelines() {
|
||||
pipeline.remove(boundHandler);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addChannel(final Player player, String endChannelName) {
|
||||
@@ -129,7 +139,7 @@ public class NMUChannel extends ChannelAbstract {
|
||||
ChatItemPacket nextPacket = getPacketManager().onPacketSent(PacketType.getType(packet.getClass().getSimpleName()), owner, packet);
|
||||
if(nextPacket != null && nextPacket.isCancelled())
|
||||
return;
|
||||
super.write(ctx, packet, promise);
|
||||
super.write(ctx, nextPacket == null ? packet : nextPacket.getPacket(), promise);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -146,7 +156,7 @@ public class NMUChannel extends ChannelAbstract {
|
||||
try {
|
||||
PacketType packetType = PacketType.getType(packet.getClass().getSimpleName());
|
||||
if(packetType != null && packetType == PacketType.Handshake.IS_SET_PROTOCOL) {
|
||||
getPacketManager().protocolVersionPerChannel.put(channel, new PacketContent(packet).getIntegers().readSafely(0, 0));
|
||||
getPacketManager().protocolVersionPerChannel.put(channel, new PacketContent(packet).getIntegers().readSafely(1, 0));
|
||||
}
|
||||
super.channelRead(ctx, packet);
|
||||
} catch (Exception e) {
|
||||
+26
-21
@@ -1,9 +1,9 @@
|
||||
package me.dadus33.chatitem.packets.protocollib;
|
||||
package me.dadus33.chatitem.chatmanager.v1.packets.protocollib;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
|
||||
import com.comphenix.protocol.PacketType.Play;
|
||||
import com.comphenix.protocol.ProtocolLibrary;
|
||||
@@ -12,42 +12,47 @@ import com.comphenix.protocol.events.ListenerPriority;
|
||||
import com.comphenix.protocol.events.PacketAdapter;
|
||||
import com.comphenix.protocol.events.PacketEvent;
|
||||
|
||||
import me.dadus33.chatitem.listeners.HandshakeListener;
|
||||
import me.dadus33.chatitem.packets.ChatItemPacket;
|
||||
import me.dadus33.chatitem.packets.PacketManager;
|
||||
import me.dadus33.chatitem.packets.PacketType;
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
import me.dadus33.chatitem.chatmanager.v1.listeners.HandshakeListener;
|
||||
import me.dadus33.chatitem.chatmanager.v1.packets.ChatItemPacket;
|
||||
import me.dadus33.chatitem.chatmanager.v1.packets.PacketManager;
|
||||
import me.dadus33.chatitem.chatmanager.v1.packets.PacketType;
|
||||
|
||||
public class ProtocollibPacketManager extends PacketManager {
|
||||
|
||||
private final ProtocolManager protocolManager;
|
||||
|
||||
public ProtocollibPacketManager(Plugin pl) {
|
||||
public ProtocollibPacketManager(ChatItem pl) {
|
||||
protocolManager = ProtocolLibrary.getProtocolManager();
|
||||
protocolManager.addPacketListener(new PacketAdapter(pl, ListenerPriority.LOWEST, Arrays.asList(Play.Server.CHAT)) {
|
||||
List<com.comphenix.protocol.PacketType> list = new ArrayList<>();
|
||||
list.add(Play.Server.CHAT);
|
||||
try {
|
||||
list.add((com.comphenix.protocol.PacketType) Play.Server.class.getDeclaredField("SYSTEM_CHAT").get(null));
|
||||
} catch (Exception e) {
|
||||
// ignore because using old version
|
||||
}
|
||||
protocolManager.addPacketListener(new PacketAdapter(pl, ListenerPriority.LOWEST, list) {
|
||||
@Override
|
||||
public void onPacketSending(PacketEvent e) {
|
||||
Player p = e.getPlayer();
|
||||
if (p == null || e.isPlayerTemporary())
|
||||
return;
|
||||
ChatItemPacket packet = onPacketSent(PacketType.getType(e.getPacket().getHandle().getClass().getSimpleName()),
|
||||
p, e.getPacket().getHandle());
|
||||
if(packet == null)
|
||||
ChatItemPacket packet = onPacketSent(PacketType.getType(e.getPacket().getHandle().getClass().getSimpleName()), p, e.getPacket().getHandle());
|
||||
if(packet == null) {
|
||||
ChatItem.debug("Can't find packet: " + e.getPacket().getHandle().getClass().getName());
|
||||
return;
|
||||
}
|
||||
if(!e.isCancelled())
|
||||
e.setCancelled(packet.isCancelled());
|
||||
}
|
||||
});
|
||||
protocolManager.addPacketListener(new HandshakeListener());
|
||||
protocolManager.addPacketListener(new HandshakeListener(pl));
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void addPlayer(Player p) {}
|
||||
|
||||
@Override
|
||||
public void removePlayer(Player p) {}
|
||||
|
||||
@Override
|
||||
public void clear() {}
|
||||
public void stop() {
|
||||
protocolManager.removePacketListeners(ChatItem.getInstance());
|
||||
}
|
||||
|
||||
public ChatItemPacket onPacketSent(PacketType type, Player sender, Object packet) {
|
||||
if(type == null)
|
||||
+2
-1
@@ -1,8 +1,9 @@
|
||||
package me.dadus33.chatitem.utils;
|
||||
package me.dadus33.chatitem.chatmanager.v1.utils;
|
||||
|
||||
|
||||
import com.github.steveice10.opennbt.tag.builtin.CompoundTag;
|
||||
|
||||
@Deprecated
|
||||
public class Item {
|
||||
private String id;
|
||||
private byte amount;
|
||||
@@ -0,0 +1,50 @@
|
||||
package me.dadus33.chatitem.chatmanager.v1.utils;
|
||||
|
||||
import static me.dadus33.chatitem.utils.Version.V1_10;
|
||||
import static me.dadus33.chatitem.utils.Version.V1_11;
|
||||
import static me.dadus33.chatitem.utils.Version.V1_8;
|
||||
import static me.dadus33.chatitem.utils.Version.V1_9;
|
||||
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
@Deprecated
|
||||
public class ItemRewriter {
|
||||
|
||||
public static String remapIds(int server, int player, ItemStack is) {
|
||||
Item item = new Item();
|
||||
item.setAmount((byte)is.getAmount());
|
||||
//item.setData(is.getDurability());
|
||||
//item.setId(id);
|
||||
//item.setTag(tag);
|
||||
if (areIdsCompatible(server, player)) {
|
||||
return item.getId();
|
||||
}
|
||||
if ((server >= V1_9.MIN_VER && player <= V1_8.MAX_VER) || (player >= V1_9.MIN_VER && server <= V1_8.MAX_VER)) {
|
||||
if ((server >= V1_9.MIN_VER && player <= V1_8.MAX_VER)) {
|
||||
ItemRewriter_1_9_TO_1_8.reversedToClient(item);
|
||||
} else
|
||||
ItemRewriter_1_9_TO_1_8.toClient(item);
|
||||
}
|
||||
if ((server <= V1_10.MAX_VER && player >= V1_11.MIN_VER)
|
||||
|| (player <= V1_10.MAX_VER && server >= V1_11.MIN_VER)) {
|
||||
if (server <= V1_10.MAX_VER && player >= V1_11.MIN_VER) {
|
||||
ItemRewriter_1_11_TO_1_10.toClient(item);
|
||||
} else {
|
||||
ItemRewriter_1_11_TO_1_10.reverseToClient(item);
|
||||
}
|
||||
}
|
||||
return item.getId();
|
||||
}
|
||||
|
||||
public static boolean areIdsCompatible(int version1, int version2) {
|
||||
if ((version1 >= V1_9.MIN_VER && version2 <= V1_8.MAX_VER)
|
||||
|| (version2 >= V1_9.MIN_VER && version1 <= V1_8.MAX_VER)) {
|
||||
return false;
|
||||
}
|
||||
if ((version1 <= V1_10.MAX_VER && version2 >= V1_11.MIN_VER)
|
||||
|| (version1 <= V1_10.MAX_VER && version2 >= V1_11.MIN_VER)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -1,4 +1,4 @@
|
||||
package me.dadus33.chatitem.utils;
|
||||
package me.dadus33.chatitem.chatmanager.v1.utils;
|
||||
|
||||
|
||||
import com.github.steveice10.opennbt.tag.builtin.CompoundTag;
|
||||
@@ -10,6 +10,7 @@ import com.google.common.collect.HashBiMap;
|
||||
/**
|
||||
* Thanks to the developers of ViaVersion for this!
|
||||
*/
|
||||
@Deprecated
|
||||
public class ItemRewriter_1_11_TO_1_10 {
|
||||
private static BiMap<String, String> oldToNewNames = HashBiMap.create();
|
||||
|
||||
+2
-1
@@ -1,4 +1,4 @@
|
||||
package me.dadus33.chatitem.utils;
|
||||
package me.dadus33.chatitem.chatmanager.v1.utils;
|
||||
|
||||
|
||||
import com.github.steveice10.opennbt.tag.builtin.CompoundTag;
|
||||
@@ -9,6 +9,7 @@ import java.util.Map;
|
||||
/**
|
||||
* Thanks to the developers of ViaVersion for this!
|
||||
*/
|
||||
@Deprecated
|
||||
public class ItemRewriter_1_9_TO_1_8 {
|
||||
|
||||
private static final Map<String, Integer> ENTTIY_NAME_TO_ID = new HashMap<>();
|
||||
@@ -0,0 +1,347 @@
|
||||
package me.dadus33.chatitem.chatmanager.v2;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
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.AsyncPlayerChatEvent;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
import me.dadus33.chatitem.ItemPlayer;
|
||||
import me.dadus33.chatitem.chatmanager.ChatManager;
|
||||
import me.dadus33.chatitem.hook.DiscordSrvSupport;
|
||||
import me.dadus33.chatitem.playernamer.PlayerNamerManager;
|
||||
import me.dadus33.chatitem.utils.ColorManager;
|
||||
import me.dadus33.chatitem.utils.ItemUtils;
|
||||
import me.dadus33.chatitem.utils.PacketUtils;
|
||||
import me.dadus33.chatitem.utils.ReflectionUtils;
|
||||
import me.dadus33.chatitem.utils.Storage;
|
||||
import me.dadus33.chatitem.utils.Utils;
|
||||
import net.md_5.bungee.api.ChatColor;
|
||||
import net.md_5.bungee.api.chat.BaseComponent;
|
||||
import net.md_5.bungee.api.chat.ComponentBuilder;
|
||||
import net.md_5.bungee.api.chat.HoverEvent;
|
||||
import net.md_5.bungee.api.chat.HoverEvent.Action;
|
||||
import net.md_5.bungee.api.chat.TextComponent;
|
||||
import net.md_5.bungee.api.chat.hover.content.Text;
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
public class ChatListener implements Listener {
|
||||
|
||||
private static Method saveMethod;
|
||||
private static boolean shouldUseAppendMethod = false;
|
||||
|
||||
static {
|
||||
try {
|
||||
Class<?> nbtTag = PacketUtils.getNmsClass("NBTTagCompound", "nbt.");
|
||||
Class<?> itemClass = PacketUtils.getNmsClass("ItemStack", "world.item.");
|
||||
for (Method m : itemClass.getDeclaredMethods()) {
|
||||
if (m.getParameterTypes().length == 1) {
|
||||
if (m.getParameterTypes()[0].equals(nbtTag) && m.getReturnType().equals(nbtTag)) {
|
||||
saveMethod = m;
|
||||
}
|
||||
}
|
||||
}
|
||||
try {
|
||||
ComponentBuilder.class.getDeclaredMethod("append", BaseComponent[].class);
|
||||
shouldUseAppendMethod = true;
|
||||
} catch (Exception e) {
|
||||
shouldUseAppendMethod = false;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
|
||||
}
|
||||
Logger log = ChatItem.getInstance().getLogger();
|
||||
String appendMethodMsg = shouldUseAppendMethod ? "Use ComponentBuilder's method."
|
||||
: "Use own ComponentBuilder append method.";
|
||||
if (saveMethod == null)
|
||||
log.info("Failed to find save method. Using default system. " + appendMethodMsg);
|
||||
else
|
||||
log.info("Save method founded: " + saveMethod.getName() + ". " + appendMethodMsg);
|
||||
}
|
||||
|
||||
private ChatListenerChatManager manage;
|
||||
|
||||
public ChatListener(ChatListenerChatManager manage) {
|
||||
this.manage = manage;
|
||||
}
|
||||
|
||||
public Storage getStorage() {
|
||||
return manage.getStorage();
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void onChat(AsyncPlayerChatEvent e) {
|
||||
Storage c = getStorage();
|
||||
if (e.isCancelled()) {
|
||||
if (ChatItem.getInstance().getChatManager().size() == 1) { // only chat
|
||||
String msg = e.getMessage().toLowerCase();
|
||||
for (String rep : c.PLACEHOLDERS) {
|
||||
if (msg.contains(rep)) {
|
||||
ChatItem.debug(
|
||||
"You choose 'chat' manager but it seems to don't be the good choice. More informations here: https://github.com/dadus33-plugins/ChatItem/wiki");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
ChatItem.debug("Chat cancelled for " + e.getPlayer().getName());
|
||||
return;
|
||||
}
|
||||
Player p = e.getPlayer();
|
||||
boolean hasv1 = false;
|
||||
String placeholder = null;
|
||||
for (String rep : c.PLACEHOLDERS) {
|
||||
// v1 try to manage it, but the message have not been changed by another plugin
|
||||
if (e.getMessage().contains(rep + ChatManager.SEPARATOR + p.getName())) {
|
||||
hasv1 = true;
|
||||
ChatItem.debug("Found v1 placeholders in v2");
|
||||
placeholder = rep;
|
||||
break;
|
||||
}
|
||||
if (e.getMessage().contains(rep)) {
|
||||
placeholder = rep;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (placeholder == null) { // if not found
|
||||
ChatItem.debug("(v2) Can't found placeholder in: " + e.getMessage() + " > " + PlayerNamerManager.getPlayerNamer().getName(p));
|
||||
return;
|
||||
}
|
||||
ItemStack item = ChatManager.getUsableItem(p);
|
||||
if(!ChatManager.canShowItem(p, item, e))
|
||||
return;
|
||||
e.setCancelled(true);
|
||||
String format = e.getFormat();
|
||||
String msg, defMsg = e.getMessage();
|
||||
for (String rep : c.PLACEHOLDERS) {
|
||||
if (hasv1) // remove v1 char
|
||||
defMsg = defMsg.replace(rep + ChatManager.SEPARATOR + p.getName(), String.valueOf(ChatManager.SEPARATOR));
|
||||
else
|
||||
defMsg = defMsg.replace(rep, String.valueOf(ChatManager.SEPARATOR));
|
||||
}
|
||||
if (Utils.countMatches(defMsg, String.valueOf(ChatManager.SEPARATOR)) > getStorage().LIMIT) {
|
||||
e.setCancelled(true);
|
||||
if (getStorage().LIMIT_MESSAGE.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
p.sendMessage(getStorage().LIMIT_MESSAGE);
|
||||
return;
|
||||
}
|
||||
if (format.contains("%1$s") || format.contains("%2$s")) {
|
||||
msg = (format.contains("%2$s") ? String.format(format, p.getDisplayName(), defMsg)
|
||||
: String.format(format, p.getDisplayName()));
|
||||
} else {
|
||||
msg = format.replace(e.getMessage(), defMsg);
|
||||
}
|
||||
String itemName = ChatManager.getNameOfItem(p, item, c);
|
||||
String loggedMessage = msg.replace(ChatManager.SEPARATOR + "", itemName).replace("{name}", p.getName())
|
||||
.replace("{display-name}", p.getDisplayName());
|
||||
Bukkit.getConsoleSender().sendMessage(loggedMessage); // show in log
|
||||
if (ChatItem.discordSrvSupport)
|
||||
DiscordSrvSupport.sendChatMessage(p, defMsg.replace(ChatManager.SEPARATOR + "", itemName).replace("{name}", p.getName())
|
||||
.replace("{display-name}", p.getDisplayName()));
|
||||
ChatItem.debug("Msg: " + msg.replace(ChatColor.COLOR_CHAR, '&') + ", format: " + format);
|
||||
e.getRecipients().forEach((pl) -> showItem(pl, p, item, msg));
|
||||
if (c.COOLDOWN > 0 && !p.hasPermission("chatitem.ignore-cooldown"))
|
||||
ChatManager.applyCooldown(p);
|
||||
}
|
||||
|
||||
public static void showItem(Player to, Player origin, ItemStack item, String msg) {
|
||||
ComponentBuilder builder = new ComponentBuilder("");
|
||||
ChatColor color = ChatColor.WHITE;
|
||||
String colorCode = "", text = "";
|
||||
boolean waiting = false;
|
||||
for (char args : msg.toCharArray()) {
|
||||
if (args == '§') { // begin of color
|
||||
if (colorCode.isEmpty() && !text.isEmpty()) { // text before this char
|
||||
ChatItem.debug("Append " + text);
|
||||
appendToComponentBuilder(builder, new ComponentBuilder(text).color(color).create());
|
||||
text = "";
|
||||
}
|
||||
waiting = true; // waiting for color code
|
||||
} else if (waiting) { // if waiting for code and valid str
|
||||
// if it's hexademical value and with enough space for full color
|
||||
waiting = false;
|
||||
if(args == 'r' && colorCode.isEmpty()) {
|
||||
color = ChatColor.RESET;
|
||||
continue;
|
||||
}
|
||||
if(args == 'x' && !colorCode.isEmpty()) {
|
||||
text += ColorManager.getColorString(colorCode);
|
||||
colorCode = "x";
|
||||
} else
|
||||
colorCode += args; // a color by itself
|
||||
} else {
|
||||
waiting = false;
|
||||
if(!colorCode.isEmpty()) {
|
||||
if(colorCode.startsWith("x") && colorCode.length() >= 7) {
|
||||
if(colorCode.length() == 7)
|
||||
color = ColorManager.getColor(colorCode);
|
||||
else {
|
||||
color = ColorManager.getColor(colorCode.substring(0, 7)); // only the hex code
|
||||
ChatItem.debug("Adding color for " + colorCode.substring(7, colorCode.length()) + " (in " + colorCode + ")");
|
||||
text += ColorManager.getColorString(colorCode.substring(7, colorCode.length()));
|
||||
}
|
||||
} else if(colorCode.length() == 1) // if only one color code
|
||||
color = ColorManager.getColor(colorCode);
|
||||
else
|
||||
text += ColorManager.getColorString(colorCode);
|
||||
colorCode = "";
|
||||
}
|
||||
if (args == ChatManager.SEPARATOR) {
|
||||
// here put the item
|
||||
appendToComponentBuilder(builder, fixColorComponent(text, color));
|
||||
addItem(builder, to, origin, item);
|
||||
text = "";
|
||||
} else {
|
||||
// basic text, not waiting for code after '§'
|
||||
text += args;
|
||||
}
|
||||
}
|
||||
}
|
||||
if(!text.isEmpty())
|
||||
appendToComponentBuilder(builder, new ComponentBuilder(text).color(color).create());
|
||||
to.spigot().sendMessage(builder.create());
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts an {@link org.bukkit.inventory.ItemStack} to a Json string for
|
||||
* sending with {@link net.md_5.bungee.api.chat.BaseComponent}'s.
|
||||
*
|
||||
* @param itemStack the item to convert
|
||||
* @return the Json string representation of the item
|
||||
*/
|
||||
public static String convertItemStackToJson(ItemStack itemStack) {
|
||||
try {
|
||||
Class<?> nbtTag = PacketUtils.getNmsClass("NBTTagCompound", "nbt.");
|
||||
Class<?> craftItemClass = PacketUtils.getObcClass("inventory.CraftItemStack");
|
||||
Object nmsNbtTagCompoundObj = nbtTag.getConstructor().newInstance();
|
||||
if (saveMethod == null) {
|
||||
Object nmsItemStackObj = craftItemClass.getMethod("asNMSCopy", ItemStack.class).invoke(null, itemStack);
|
||||
return nmsItemStackObj.getClass().getMethod("save", nbtTag)
|
||||
.invoke(nmsItemStackObj, nmsNbtTagCompoundObj).toString();
|
||||
} else {
|
||||
Object nmsItemStackObj = craftItemClass.getMethod("asNMSCopy", ItemStack.class).invoke(null, itemStack);
|
||||
return saveMethod.invoke(nmsItemStackObj, nmsNbtTagCompoundObj).toString();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static void addItem(ComponentBuilder builder, Player to, Player origin, ItemStack item) {
|
||||
Storage c = ChatItem.getInstance().getStorage();
|
||||
if (!ItemUtils.isEmpty(item)) {
|
||||
ComponentBuilder itemComponent = new ComponentBuilder(ChatManager.styleItem(to, item, c));
|
||||
String itemJson = convertItemStackToJson(item);
|
||||
ChatItem.debug("Item for " + to.getName() + " (ver: " + ItemPlayer.getPlayer(to).getVersion().name() + ") : " + itemJson);
|
||||
itemComponent.event(new HoverEvent(Action.SHOW_ITEM, new ComponentBuilder(itemJson).create()));
|
||||
appendToComponentBuilder(builder, itemComponent.create());
|
||||
} else {
|
||||
String handName = c.HAND_NAME;
|
||||
ComponentBuilder handComp = new ComponentBuilder("");
|
||||
ComponentBuilder handTooltip = new ComponentBuilder("");
|
||||
int stay = c.HAND_TOOLTIP.size();
|
||||
for (String line : c.HAND_TOOLTIP) {
|
||||
stay--;
|
||||
handTooltip.append(ColorManager.fixColor(line.replace("{name}", origin.getName()).replace("{display-name}", origin.getDisplayName())));
|
||||
if (stay > 0)
|
||||
handTooltip.append("\n");
|
||||
}
|
||||
handComp.event(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new Text(handTooltip.create())));
|
||||
if (handName.contains("{display-name}")) {
|
||||
String[] splitted = handName.split("\\{display-name\\}");
|
||||
for (int i = 0; i < (splitted.length - 1); i++) {
|
||||
handComp.append(splitted[i]);
|
||||
appendToComponentBuilder(handComp, PlayerNamerManager.getPlayerNamer().getName(origin));
|
||||
}
|
||||
handComp.append(splitted[splitted.length - 1]);
|
||||
} else
|
||||
handComp.append(handName.replace("{name}", origin.getName()));
|
||||
appendToComponentBuilder(builder, handComp.create());
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static void appendToComponentBuilder(ComponentBuilder builder, BaseComponent[] comps) {
|
||||
if (shouldUseAppendMethod) {
|
||||
try {
|
||||
builder.append(comps);
|
||||
} catch (Exception e) {
|
||||
ChatItem.getInstance().getLogger().severe(
|
||||
"This should NEVER append. The ComponentBuilder#append(BaseComponent[]) was found but it's NOT. Using own next time.");
|
||||
shouldUseAppendMethod = false;
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
Field currentField = ReflectionUtils.getField(builder, "current");
|
||||
List<BaseComponent> parts = (List<BaseComponent>) ReflectionUtils.getObject(builder, "parts");
|
||||
parts.add(new TextComponent((TextComponent) currentField.get(builder)));
|
||||
parts.addAll(Arrays.asList(comps));
|
||||
currentField.set(builder, new TextComponent(""));
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static BaseComponent[] fixColorComponent(String message, ChatColor color) {
|
||||
ComponentBuilder builder = new ComponentBuilder("");
|
||||
String colorCode = "", text = "";
|
||||
boolean waiting = false;
|
||||
for (char args : message.toCharArray()) {
|
||||
if (args == '§') { // begin of color
|
||||
if (colorCode.isEmpty() && !text.isEmpty()) { // text before this char
|
||||
ChatItem.debug("Append while fixing name " + text);
|
||||
appendToComponentBuilder(builder, new ComponentBuilder(text).color(color).create());
|
||||
text = "";
|
||||
}
|
||||
waiting = true; // waiting for color code
|
||||
} else if (waiting) { // if waiting for code and valid str
|
||||
// if it's hexademical value and with enough space for full color
|
||||
waiting = false;
|
||||
if(args == 'r' && colorCode.isEmpty()) {
|
||||
color = ChatColor.RESET;
|
||||
continue;
|
||||
}
|
||||
if(args == 'x' && !colorCode.isEmpty()) {
|
||||
text += ColorManager.getColorString(colorCode);
|
||||
colorCode = "x";
|
||||
} else
|
||||
colorCode += args; // a color by itself
|
||||
} else {
|
||||
waiting = false;
|
||||
if(!colorCode.isEmpty()) {
|
||||
if(colorCode.startsWith("x") && colorCode.length() >= 7) {
|
||||
if(colorCode.length() == 7)
|
||||
color = ColorManager.getColor(colorCode);
|
||||
else {
|
||||
color = ColorManager.getColor(colorCode.substring(0, 7)); // only the hex code
|
||||
ChatItem.debug("Adding color for " + colorCode.substring(7, colorCode.length()) + " (in " + colorCode + ")");
|
||||
text += ColorManager.getColorString(colorCode.substring(7, colorCode.length()));
|
||||
}
|
||||
} else if(colorCode.length() == 1) // if only one color code
|
||||
color = ColorManager.getColor(colorCode);
|
||||
else
|
||||
text += ColorManager.getColorString(colorCode);
|
||||
colorCode = "";
|
||||
}
|
||||
// basic text, not waiting for code after '§'
|
||||
text += args;
|
||||
}
|
||||
}
|
||||
if(!text.isEmpty())
|
||||
appendToComponentBuilder(builder, new ComponentBuilder(text).color(color).create());
|
||||
return builder.create();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package me.dadus33.chatitem.chatmanager.v2;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.event.HandlerList;
|
||||
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
import me.dadus33.chatitem.chatmanager.ChatManager;
|
||||
import me.dadus33.chatitem.utils.Storage;
|
||||
|
||||
public class ChatListenerChatManager extends ChatManager {
|
||||
|
||||
private final ChatListener chatListener;
|
||||
private boolean baseComponentAvailable = true;
|
||||
|
||||
public ChatListenerChatManager(ChatItem pl) {
|
||||
chatListener = new ChatListener(this);
|
||||
|
||||
//Check for existence of BaseComponent class (only on spigot)
|
||||
try {
|
||||
Class.forName("net.md_5.bungee.api.chat.BaseComponent");
|
||||
} catch (ClassNotFoundException e) {
|
||||
baseComponentAvailable = false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "ChatListener";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getId() {
|
||||
return "chat";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void load(ChatItem pl, Storage s) {
|
||||
super.load(pl, s);
|
||||
|
||||
Bukkit.getPluginManager().registerEvents(chatListener, pl);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void unload(ChatItem pl) {
|
||||
HandlerList.unregisterAll(chatListener);
|
||||
}
|
||||
|
||||
public boolean supportsChatComponentApi(){
|
||||
return baseComponentAvailable;
|
||||
}
|
||||
}
|
||||
+3
-3
@@ -1,16 +1,16 @@
|
||||
package me.dadus33.chatitem.commands;
|
||||
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
import org.bukkit.command.Command;
|
||||
import org.bukkit.command.CommandExecutor;
|
||||
import org.bukkit.command.CommandSender;
|
||||
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
|
||||
public class CIReload implements CommandExecutor {
|
||||
public class CIReloadCommand implements CommandExecutor {
|
||||
|
||||
@Override
|
||||
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
|
||||
ChatItem.reload(sender);
|
||||
ChatItem.reload(sender);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package me.dadus33.chatitem.commands;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.command.Command;
|
||||
import org.bukkit.command.CommandExecutor;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.command.TabExecutor;
|
||||
import org.bukkit.configuration.ConfigurationSection;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
import me.dadus33.chatitem.chatmanager.ChatManager;
|
||||
import me.dadus33.chatitem.chatmanager.v2.ChatListener;
|
||||
import me.dadus33.chatitem.listeners.InventoryListener;
|
||||
import me.dadus33.chatitem.utils.Messages;
|
||||
import me.dadus33.chatitem.utils.Storage;
|
||||
import net.md_5.bungee.api.chat.ClickEvent;
|
||||
import net.md_5.bungee.api.chat.ComponentBuilder;
|
||||
import net.md_5.bungee.api.chat.HoverEvent;
|
||||
import net.md_5.bungee.api.chat.TextComponent;
|
||||
import net.md_5.bungee.api.chat.hover.content.Text;
|
||||
|
||||
public class ChatItemCommand implements CommandExecutor, TabExecutor {
|
||||
|
||||
@Override
|
||||
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
|
||||
if (!(sender instanceof Player)) {
|
||||
Messages.sendMessage(sender, "only-players");
|
||||
return false;
|
||||
}
|
||||
Player p = (Player) sender;
|
||||
if (args.length == 0) {
|
||||
Messages.sendMessage(p, "chatitem-cmd.help");
|
||||
} else if (args[0].equalsIgnoreCase("admin")) {
|
||||
InventoryListener.open(p);
|
||||
} else if (args[0].equalsIgnoreCase("reload")) {
|
||||
ChatItem.reload(sender);
|
||||
} else if (args[0].equalsIgnoreCase("show")) {
|
||||
Player cible = args.length == 1 ? p : Bukkit.getPlayer(args[1]);
|
||||
if(cible == null) {
|
||||
p.sendMessage(ChatColor.RED + "The player " + args[1] + " can't be found.");
|
||||
return false;
|
||||
}
|
||||
Storage c = ChatItem.getInstance().getStorage();
|
||||
ItemStack item = ChatManager.getUsableItem(cible);
|
||||
ChatListener.showItem(p, cible, item, c.COMMAND_FORMAT.replace("%name%", cible.getName()).replace("%item%", ChatManager.SEPARATOR + ""));
|
||||
} else if (args[0].equalsIgnoreCase("broadcast")) {
|
||||
Player cible = args.length == 1 ? p : Bukkit.getPlayer(args[1]);
|
||||
if(cible == null) {
|
||||
p.sendMessage(ChatColor.RED + "The player " + args[1] + " can't be found.");
|
||||
return false;
|
||||
}
|
||||
Storage c = ChatItem.getInstance().getStorage();
|
||||
ItemStack item = ChatManager.getUsableItem(cible);
|
||||
for(Player all : Bukkit.getOnlinePlayers())
|
||||
ChatListener.showItem(all, cible, item, c.COMMAND_FORMAT.replace("%name%", cible.getName()).replace("%item%", ChatManager.SEPARATOR + ""));
|
||||
} else if (args[0].equalsIgnoreCase("link") || args[0].equalsIgnoreCase("links")) {
|
||||
ConfigurationSection config = ChatItem.getInstance().getConfig()
|
||||
.getConfigurationSection("messages.chatitem-cmd.links");
|
||||
TextComponent text = new TextComponent(Storage.color(config.getString("begin")));
|
||||
for (String key : config.getConfigurationSection("list").getKeys(false)) {
|
||||
ConfigurationSection linkConfig = config.getConfigurationSection("list." + key);
|
||||
TextComponent linkComp = new TextComponent(Storage.color(linkConfig.getString("message")));
|
||||
String hover = Storage.color(linkConfig.getString("hover"));
|
||||
if (hover != null)
|
||||
linkComp.setHoverEvent(
|
||||
new HoverEvent(HoverEvent.Action.SHOW_TEXT, new Text(new ComponentBuilder(hover).create())));
|
||||
String link = linkConfig.getString("link");
|
||||
if (link != null)
|
||||
linkComp.setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, link));
|
||||
text.addExtra(linkComp);
|
||||
}
|
||||
p.spigot().sendMessage(text);
|
||||
} else {
|
||||
Messages.sendMessage(p, "chatitem-cmd.help");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] arg) {
|
||||
List<String> list = new ArrayList<>();
|
||||
String prefix = arg[arg.length - 1].toLowerCase(Locale.ROOT);
|
||||
for (String s : Arrays.asList("help", "admin", "reload", "link", "show", "broadcast"))
|
||||
if (prefix.isEmpty() || s.startsWith(prefix))
|
||||
list.add(s);
|
||||
return list.isEmpty() ? null : list;
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
package me.dadus33.chatitem.filters;
|
||||
|
||||
import me.dadus33.chatitem.listeners.ChatEventListener;
|
||||
import me.dadus33.chatitem.utils.Storage;
|
||||
import static org.apache.logging.log4j.core.Filter.Result.NEUTRAL;
|
||||
|
||||
import org.apache.logging.log4j.Level;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Marker;
|
||||
@@ -12,67 +12,70 @@ import org.apache.logging.log4j.message.Message;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import static org.apache.logging.log4j.core.Filter.Result.NEUTRAL;
|
||||
|
||||
import me.dadus33.chatitem.chatmanager.ChatManager;
|
||||
import me.dadus33.chatitem.utils.Storage;
|
||||
|
||||
public class Log4jFilter implements Filter {
|
||||
|
||||
private Storage c;
|
||||
private Storage c;
|
||||
|
||||
public Log4jFilter(Storage st){
|
||||
c = st;
|
||||
((Logger) LogManager.getRootLogger()).addFilter(this);
|
||||
}
|
||||
public Log4jFilter(Storage st) {
|
||||
c = st;
|
||||
((Logger) LogManager.getRootLogger()).addFilter(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Result getOnMismatch() {
|
||||
return NEUTRAL;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Result getOnMismatch() {
|
||||
return NEUTRAL;
|
||||
}
|
||||
@Override
|
||||
public Result getOnMatch() {
|
||||
return NEUTRAL;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Result getOnMatch() {
|
||||
return NEUTRAL;
|
||||
}
|
||||
@Override
|
||||
public Result filter(Logger logger, Level level, Marker marker, String s, Object... objects) {
|
||||
return checkMessage(s);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Result filter(Logger logger, Level level, Marker marker, String s, Object... objects) {
|
||||
return checkMessage(s);
|
||||
}
|
||||
@Override
|
||||
public Result filter(Logger logger, Level level, Marker marker, Object o, Throwable throwable) {
|
||||
return checkMessage(((Message) o).getFormattedMessage());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Result filter(Logger logger, Level level, Marker marker, Object o, Throwable throwable) {
|
||||
return checkMessage(((Message)o).getFormattedMessage());
|
||||
}
|
||||
@Override
|
||||
public Result filter(Logger logger, Level level, Marker marker, Message message, Throwable throwable) {
|
||||
return checkMessage(message.getFormattedMessage());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Result filter(Logger logger, Level level, Marker marker, Message message, Throwable throwable) {
|
||||
return checkMessage(message.getFormattedMessage());
|
||||
}
|
||||
@Override
|
||||
public Result filter(LogEvent logEvent) {
|
||||
return checkMessage(logEvent.getMessage().getFormattedMessage());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Result filter(LogEvent logEvent) {
|
||||
return checkMessage(logEvent.getMessage().getFormattedMessage());
|
||||
}
|
||||
public void stop() {
|
||||
// seems to be required
|
||||
}
|
||||
|
||||
private Result checkMessage(String msg){
|
||||
if(msg==null){
|
||||
return Result.NEUTRAL;
|
||||
}
|
||||
for(String placeholder : c.PLACEHOLDERS){
|
||||
if(msg.contains(placeholder)){
|
||||
for(Player p : Bukkit.getOnlinePlayers()){
|
||||
if(msg.contains(ChatEventListener.SEPARATOR +p.getName())){
|
||||
return Result.DENY;
|
||||
}
|
||||
}
|
||||
private Result checkMessage(String msg) {
|
||||
if (msg == null) {
|
||||
return Result.NEUTRAL;
|
||||
}
|
||||
for (String placeholder : c.PLACEHOLDERS) {
|
||||
if (msg.contains(placeholder)) {
|
||||
for (Player p : Bukkit.getOnlinePlayers()) {
|
||||
if (msg.contains(ChatManager.SEPARATOR + p.getName())) {
|
||||
return Result.DENY;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
return Result.NEUTRAL;
|
||||
}
|
||||
}
|
||||
}
|
||||
return Result.NEUTRAL;
|
||||
}
|
||||
|
||||
public void setStorage(Storage nst){
|
||||
this.c = nst;
|
||||
}
|
||||
public void setStorage(Storage nst) {
|
||||
this.c = nst;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package me.dadus33.chatitem.hook;
|
||||
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import github.scarsz.discordsrv.DiscordSRV;
|
||||
|
||||
public class DiscordSrvSupport {
|
||||
|
||||
public static void sendChatMessage(Player p, String message) {
|
||||
DiscordSRV pl = DiscordSRV.getPlugin();
|
||||
if (DiscordSRV.config().getBooleanElse("UseModernPaperChatEvent", false) && pl.isModernChatEventAvailable()) {
|
||||
return;
|
||||
}
|
||||
pl.processChatMessage(p, message, pl.getOptionalChannel("global"), false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package me.dadus33.chatitem.hook;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import com.willfp.ecoenchants.display.EnchantmentCache;
|
||||
import com.willfp.ecoenchants.enchantments.util.EnchantChecks;
|
||||
|
||||
public class EcoEnchantsSupport {
|
||||
|
||||
public static List<String> getLores(ItemStack item) {
|
||||
List<String> lores = new ArrayList<>();
|
||||
EnchantChecks.getEnchantsOnItem(item).forEach((en, lvl) -> {
|
||||
lores.add(EnchantmentCache.getEntry(en).getNameWithLevel(lvl));
|
||||
});
|
||||
return lores;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package me.dadus33.chatitem.itemnamer;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import me.dadus33.chatitem.utils.Storage;
|
||||
|
||||
public interface INamer {
|
||||
|
||||
/**
|
||||
* Get priority of this namer.<br>
|
||||
* Get first name that is not null, with this order:
|
||||
* - MAJOR
|
||||
*
|
||||
*
|
||||
* @return priority
|
||||
*/
|
||||
Priority getPriority();
|
||||
|
||||
/**
|
||||
* Get the name of the item thanks to this namer.
|
||||
*
|
||||
* @param item the item to get the name
|
||||
* @param storage the actual config
|
||||
* @return the name or null if can't find a name
|
||||
*/
|
||||
String getName(Player p, ItemStack item, Storage storage);
|
||||
|
||||
enum Priority {
|
||||
MAJOR(4),
|
||||
IMPORTANT(3),
|
||||
MEDIUM(2),
|
||||
SMALL(1),
|
||||
MINOR(0);
|
||||
|
||||
private final int priority;
|
||||
|
||||
Priority(int priority) {
|
||||
this.priority = priority;
|
||||
}
|
||||
|
||||
public int getPriority() {
|
||||
return priority;
|
||||
}
|
||||
|
||||
public static List<Priority> getOrderedPriorities() {
|
||||
return Arrays.stream(values()).sorted((p1, p2) -> p2.getPriority() - p1.getPriority()).collect(Collectors.toList());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package me.dadus33.chatitem.itemnamer;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.StringJoiner;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.plugin.PluginManager;
|
||||
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
import me.dadus33.chatitem.itemnamer.INamer.Priority;
|
||||
import me.dadus33.chatitem.itemnamer.hook.ChatItemTranslationNamer;
|
||||
import me.dadus33.chatitem.itemnamer.hook.DefaultNamer;
|
||||
import me.dadus33.chatitem.itemnamer.hook.ItemDisplayNamer;
|
||||
import me.dadus33.chatitem.itemnamer.hook.LangUtilsNamer;
|
||||
import me.dadus33.chatitem.utils.Storage;
|
||||
|
||||
public class NamerManager {
|
||||
|
||||
private static final HashMap<Priority, List<INamer>> NAMER_PER_PRIORITY = new HashMap<>();
|
||||
|
||||
public static void load(ChatItem pl) {
|
||||
NAMER_PER_PRIORITY.clear();
|
||||
|
||||
StringJoiner sj = new StringJoiner(", ");
|
||||
PluginManager pm = Bukkit.getPluginManager();
|
||||
if(pm.getPlugin("LangUtils") != null) {
|
||||
addNamer(new LangUtilsNamer());
|
||||
sj.add("LangUtils");
|
||||
}
|
||||
if(sj.length() > 0)
|
||||
pl.getLogger().info("Loaded namer for plugin " + sj.toString() + ".");
|
||||
|
||||
addNamer(new ChatItemTranslationNamer());
|
||||
addNamer(new ItemDisplayNamer());
|
||||
addNamer(new DefaultNamer());
|
||||
}
|
||||
|
||||
/**
|
||||
* Add namer according to his {@link INamer#getPriority()}'s value
|
||||
*
|
||||
* @param namer the namer to add
|
||||
*/
|
||||
public static void addNamer(INamer namer) {
|
||||
List<INamer> namers = getOrCreate(namer.getPriority());
|
||||
namers.add(namer);
|
||||
}
|
||||
|
||||
private static List<INamer> getOrCreate(Priority p){
|
||||
return NAMER_PER_PRIORITY.computeIfAbsent(p, (a) -> new ArrayList<>());
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the name of this item, according to this storage.
|
||||
*
|
||||
* @param p the player that will see the name
|
||||
* @param item the item to show
|
||||
* @param storage the storage
|
||||
* @return the name (should NOT return null)
|
||||
*/
|
||||
public static String getName(Player p, ItemStack item, Storage storage) {
|
||||
for(Priority pr : Priority.getOrderedPriorities()) {
|
||||
List<INamer> allNamers = NAMER_PER_PRIORITY.get(pr);
|
||||
if(allNamers == null || allNamers.isEmpty())
|
||||
continue;
|
||||
for(INamer namer : allNamers) {
|
||||
String tmpName = namer.getName(p, item, storage);
|
||||
if(tmpName != null)
|
||||
return tmpName;
|
||||
}
|
||||
}
|
||||
return null; // this should NEVER append
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package me.dadus33.chatitem.itemnamer.hook;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import me.dadus33.chatitem.itemnamer.INamer;
|
||||
import me.dadus33.chatitem.utils.Storage;
|
||||
|
||||
public class ChatItemTranslationNamer implements INamer {
|
||||
|
||||
@Override
|
||||
public Priority getPriority() {
|
||||
return Priority.SMALL;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName(Player p, ItemStack item, Storage storage) {
|
||||
HashMap<Short, String> translationSection = storage.TRANSLATIONS.get(item.getType().name());
|
||||
if (translationSection != null) {
|
||||
@SuppressWarnings("deprecation")
|
||||
String translated = translationSection.get(item.getDurability());
|
||||
return translated;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package me.dadus33.chatitem.itemnamer.hook;
|
||||
|
||||
import org.apache.commons.lang.WordUtils;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import me.dadus33.chatitem.itemnamer.INamer;
|
||||
import me.dadus33.chatitem.utils.Storage;
|
||||
|
||||
public class DefaultNamer implements INamer {
|
||||
|
||||
@Override
|
||||
public Priority getPriority() {
|
||||
return Priority.MINOR;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName(Player p, ItemStack item, Storage storage) {
|
||||
Material m = item.getType();
|
||||
return m.equals(Material.TNT) ? "TNT" : WordUtils.capitalize(m.name().replaceAll("_", " ").toLowerCase());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package me.dadus33.chatitem.itemnamer.hook;
|
||||
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import me.dadus33.chatitem.itemnamer.INamer;
|
||||
import me.dadus33.chatitem.utils.Storage;
|
||||
|
||||
public class ItemDisplayNamer implements INamer {
|
||||
|
||||
@Override
|
||||
public Priority getPriority() {
|
||||
return Priority.MEDIUM;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName(Player p, ItemStack item, Storage storage) {
|
||||
if(item.hasItemMeta() && item.getItemMeta().hasDisplayName()) {
|
||||
String name = item.getItemMeta().getDisplayName();
|
||||
return storage.COLOR_IF_ALREADY_COLORED ? ChatColor.stripColor(name) : name;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package me.dadus33.chatitem.itemnamer.hook;
|
||||
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import com.meowj.langutils.lang.LanguageHelper;
|
||||
|
||||
import me.dadus33.chatitem.itemnamer.INamer;
|
||||
import me.dadus33.chatitem.utils.Storage;
|
||||
|
||||
public class LangUtilsNamer implements INamer {
|
||||
|
||||
@Override
|
||||
public Priority getPriority() {
|
||||
return Priority.IMPORTANT;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName(Player p, ItemStack item, Storage storage) {
|
||||
return LanguageHelper.getItemName(item, p);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
package me.dadus33.chatitem.json;
|
||||
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.util.List;
|
||||
|
||||
|
||||
public interface JSONManipulator {
|
||||
String parse(String json, List<String> replacements, ItemStack item, String repl, int protocol) throws InvocationTargetException, IllegalAccessException, InstantiationException, NoSuchFieldException, NoSuchMethodException;
|
||||
String parseEmpty(String json, List<String> replacements, String repl, List<String> tooltip, Player sender);
|
||||
}
|
||||
@@ -1,903 +0,0 @@
|
||||
package me.dadus33.chatitem.json;
|
||||
|
||||
import com.github.steveice10.opennbt.tag.builtin.*;
|
||||
import com.google.gson.*;
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
import me.dadus33.chatitem.utils.Item;
|
||||
import me.dadus33.chatitem.utils.PacketUtils;
|
||||
import me.dadus33.chatitem.utils.ProtocolVersion;
|
||||
import me.dadus33.chatitem.utils.Reflect;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Type;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public class JSONManipulatorCurrent implements JSONManipulator{
|
||||
|
||||
private static final Class<?> CRAFT_ITEM_STACK_CLASS = PacketUtils.getObcClass("inventory.CraftItemStack");
|
||||
private static final Class<?> NBT_STRING = PacketUtils.getNmsClass("NBTTagString", "nbt.");
|
||||
private static final Class<?> NBT_LIST = PacketUtils.getNmsClass("NBTTagList", "nbt.");
|
||||
private static final Map<Type, Tag> TYPES_TO_OPEN_NBT_TAGS = new HashMap<>();
|
||||
private static final List<Class<?>> NBT_BASE_CLASSES = new ArrayList<>();
|
||||
private static final List<Field> NBT_BASE_DATA_FIELD = new ArrayList<>();
|
||||
private static final Class<?> NMS_ITEM_STACK_CLASS = PacketUtils.getNmsClass("ItemStack", "world.item.");
|
||||
private static final Method AS_NMS_COPY = Reflect.getMethod(CRAFT_ITEM_STACK_CLASS, "asNMSCopy", ItemStack.class);
|
||||
private static final Class<?> NBT_TAG_COMPOUND = PacketUtils.getNmsClass("NBTTagCompound", "nbt.");
|
||||
private static final Method SAVE_NMS_ITEM_STACK_METHOD = Reflect.getMethod(NMS_ITEM_STACK_CLASS, "save", NBT_TAG_COMPOUND);
|
||||
private static final Field MAP = Reflect.getField(NBT_TAG_COMPOUND, "map", "x");
|
||||
private static final Field LIST_FIELD = Reflect.getField(NBT_LIST, "list", "c");
|
||||
|
||||
//Tags to be ignored. Currently it only contains tags from PortableHorses, but feel free to submit a pull request to add tags from your plugins
|
||||
private static final List<String> IGNORED = Arrays.asList("horsetag", "phorse", "iscnameviz", "cname");
|
||||
|
||||
private static final ConcurrentHashMap<Map.Entry<ProtocolVersion, ItemStack>, JsonObject> STACKS = new ConcurrentHashMap<>();
|
||||
|
||||
static{
|
||||
NBT_BASE_CLASSES.add(PacketUtils.getNmsClass("NBTTagByte", "nbt."));
|
||||
NBT_BASE_CLASSES.add(PacketUtils.getNmsClass("NBTTagByteArray", "nbt."));
|
||||
NBT_BASE_CLASSES.add(PacketUtils.getNmsClass("NBTTagDouble", "nbt."));
|
||||
NBT_BASE_CLASSES.add(PacketUtils.getNmsClass("NBTTagFloat", "nbt."));
|
||||
NBT_BASE_CLASSES.add(PacketUtils.getNmsClass("NBTTagInt", "nbt."));
|
||||
NBT_BASE_CLASSES.add(PacketUtils.getNmsClass("NBTTagIntArray", "nbt."));
|
||||
NBT_BASE_CLASSES.add(PacketUtils.getNmsClass("NBTTagLong", "nbt."));
|
||||
NBT_BASE_CLASSES.add(PacketUtils.getNmsClass("NBTTagShort", "nbt."));
|
||||
|
||||
for (Class<?> NBT_BASE_CLASS : NBT_BASE_CLASSES) {
|
||||
NBT_BASE_DATA_FIELD.add(Reflect.getField(NBT_BASE_CLASS, "data", "c", "x"));
|
||||
}
|
||||
|
||||
TYPES_TO_OPEN_NBT_TAGS.put(Byte.class, new ByteTag(""));
|
||||
TYPES_TO_OPEN_NBT_TAGS.put(Byte[].class, new ByteArrayTag(""));
|
||||
TYPES_TO_OPEN_NBT_TAGS.put(Double.class, new DoubleTag(""));
|
||||
TYPES_TO_OPEN_NBT_TAGS.put(Float.class, new FloatTag(""));
|
||||
TYPES_TO_OPEN_NBT_TAGS.put(Integer.class, new IntTag(""));
|
||||
TYPES_TO_OPEN_NBT_TAGS.put(Integer[].class, new IntArrayTag(""));
|
||||
TYPES_TO_OPEN_NBT_TAGS.put(Long.class, new LongTag(""));
|
||||
TYPES_TO_OPEN_NBT_TAGS.put(Short.class, new ShortTag(""));
|
||||
//Add the primitive types too, just in case
|
||||
TYPES_TO_OPEN_NBT_TAGS.put(byte.class, new ByteTag(""));
|
||||
TYPES_TO_OPEN_NBT_TAGS.put(byte[].class, new ByteArrayTag(""));
|
||||
TYPES_TO_OPEN_NBT_TAGS.put(double.class, new DoubleTag(""));
|
||||
TYPES_TO_OPEN_NBT_TAGS.put(float.class, new FloatTag(""));
|
||||
TYPES_TO_OPEN_NBT_TAGS.put(int.class, new IntTag(""));
|
||||
TYPES_TO_OPEN_NBT_TAGS.put(int[].class, new IntArrayTag(""));
|
||||
TYPES_TO_OPEN_NBT_TAGS.put(long.class, new LongTag(""));
|
||||
TYPES_TO_OPEN_NBT_TAGS.put(short.class, new ShortTag(""));
|
||||
|
||||
}
|
||||
|
||||
private List<String> replaces;
|
||||
private String rgx;
|
||||
private ProtocolVersion protocolVersion;
|
||||
private JsonObject itemTooltip;
|
||||
private JsonArray classicTooltip;
|
||||
private final JsonParser PARSER = new JsonParser();
|
||||
|
||||
|
||||
public String parse(String json, List<String> replacements, ItemStack item, String replacement, int protocol) throws InvocationTargetException, IllegalAccessException, InstantiationException, NoSuchFieldException, NoSuchMethodException {
|
||||
JsonObject obj = PARSER.parse(json).getAsJsonObject();
|
||||
JsonArray array = obj.getAsJsonArray("extra");
|
||||
replaces = replacements;
|
||||
String regex = "";
|
||||
for (int i = 0; i < replacements.size(); ++i) {
|
||||
if (replacements.size() == 1) {
|
||||
regex = Pattern.quote(replacements.get(0));
|
||||
break;
|
||||
}
|
||||
if (i == 0 || i + 1 == replacements.size()) {
|
||||
if (i == 0) {
|
||||
regex = "(" + Pattern.quote(replacements.get(i));
|
||||
} else {
|
||||
regex = regex.concat("|").concat(Pattern.quote(replacements.get(i))).concat(")");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
regex = regex.concat("|").concat(Pattern.quote(replacements.get(i)));
|
||||
}
|
||||
rgx = regex;
|
||||
JsonArray rep = new JsonArray();
|
||||
final AbstractMap.SimpleEntry<ProtocolVersion, ItemStack> p = new AbstractMap.SimpleEntry<>(protocolVersion = ProtocolVersion.getVersion(protocol), item);
|
||||
|
||||
if ((itemTooltip = STACKS.get(p)) == null) {
|
||||
JsonArray use = Translator.toJson(replacement); //We get the json representation of the old color formatting method
|
||||
|
||||
JsonObject hover = PARSER.parse("{\"action\":\"show_item\", \"value\": \"\"}").getAsJsonObject(); //There's no public clone method for JSONObjects so we need to parse them every time
|
||||
|
||||
String jsonRep = stringifyItem(item); //Get the JSON representation of the item (well, not really JSON, but rather a string representation of NBT data)
|
||||
hover.addProperty("value", jsonRep);
|
||||
|
||||
JsonObject wrapper = new JsonObject(); //Create a wrapper object for the whole array
|
||||
wrapper.addProperty("text", ""); //The text field is compulsory, even if it's empty
|
||||
wrapper.add("extra", use);
|
||||
wrapper.add("hoverEvent", hover);
|
||||
|
||||
itemTooltip = wrapper; //Save the tooltip for later use when we encounter a placeholder
|
||||
STACKS.put(p, itemTooltip); //Save it in the cache too so when parsing other packets with the same item (and client version) we no longer have to create it again
|
||||
Bukkit.getScheduler().runTaskLaterAsynchronously(ChatItem.getInstance(), () ->
|
||||
STACKS.remove(p)
|
||||
, 100L); //We remove it later when no longer needed to save memory
|
||||
}
|
||||
|
||||
for (int i = 0; i < array.size(); ++i) {
|
||||
if (array.get(i).isJsonObject()){
|
||||
JsonObject o = array.get(i).getAsJsonObject();
|
||||
boolean inside = false;
|
||||
for (String replace : replacements)
|
||||
if (o.toString().contains(replace)) {
|
||||
if (inside) {
|
||||
break;
|
||||
}
|
||||
inside = true;
|
||||
}
|
||||
JsonElement text = o.get("text");
|
||||
if (text == null) {
|
||||
JsonElement el = o.get("extra");
|
||||
if (el != null) {
|
||||
JsonArray jar = el.getAsJsonArray();
|
||||
if(jar.size()!=0) {
|
||||
jar = parseArray(jar);
|
||||
o.add("extra", jar);
|
||||
}else{
|
||||
o.remove("extra");
|
||||
}
|
||||
}
|
||||
continue;
|
||||
} else {
|
||||
if (text.getAsString().isEmpty()) {
|
||||
JsonElement el = o.get("extra");
|
||||
if (el != null) {
|
||||
JsonArray jar = el.getAsJsonArray();
|
||||
if(jar.size()!=0) {
|
||||
jar = parseArray(jar);
|
||||
o.add("extra", jar);
|
||||
}else{
|
||||
o.remove("extra");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
String msg = text.getAsString();
|
||||
boolean isLast = false;
|
||||
boolean done = false;
|
||||
boolean fnd;
|
||||
String[] splits;
|
||||
for (String repls : replacements) {
|
||||
if (done) {
|
||||
break;
|
||||
}
|
||||
isLast = msg.endsWith(repls);
|
||||
if (isLast) {
|
||||
done = true;
|
||||
msg = msg.concat(".");
|
||||
}
|
||||
}
|
||||
splits = msg.split(regex);
|
||||
fnd = splits.length != 1;
|
||||
if (fnd)
|
||||
for (int j = 0; j < splits.length; ++j) {
|
||||
boolean endDot = (j == splits.length - 1) && isLast;
|
||||
if (!splits[j].isEmpty() && !endDot) {
|
||||
String st = o.toString();
|
||||
JsonObject fix = PARSER.parse(st).getAsJsonObject();
|
||||
fix.addProperty("text", splits[j]);
|
||||
rep.add(fix);
|
||||
}
|
||||
if (j != splits.length - 1) {
|
||||
rep.add(itemTooltip);
|
||||
}
|
||||
}
|
||||
if (!fnd) {
|
||||
rep.add(o);
|
||||
}
|
||||
}else{
|
||||
if(array.get(i).isJsonNull()){
|
||||
continue;
|
||||
}else{
|
||||
if(array.get(i).isJsonArray()){
|
||||
JsonArray jar = array.get(i).getAsJsonArray();
|
||||
if(jar.size()!=0) {
|
||||
jar = parseArray(array.get(i).getAsJsonArray());
|
||||
rep.set(i, jar);
|
||||
}
|
||||
}else{
|
||||
|
||||
|
||||
String msg = array.get(i).getAsString();
|
||||
boolean isLast = false;
|
||||
boolean done = false;
|
||||
boolean fnd;
|
||||
String[] splits;
|
||||
for (String repls : replacements) {
|
||||
if (done) {
|
||||
break;
|
||||
}
|
||||
isLast = msg.endsWith(repls);
|
||||
if (isLast) {
|
||||
done = true;
|
||||
msg = msg.concat(".");
|
||||
}
|
||||
}
|
||||
splits = msg.split(regex);
|
||||
fnd = splits.length != 1;
|
||||
if (fnd)
|
||||
for (int j = 0; j < splits.length; ++j) {
|
||||
boolean endDot = (j == splits.length - 1) && isLast;
|
||||
if (!splits[j].isEmpty() && !endDot) {
|
||||
JsonElement fix = new JsonPrimitive(splits[j]);
|
||||
rep.add(fix);
|
||||
}
|
||||
if (j != splits.length - 1) {
|
||||
rep.add(itemTooltip);
|
||||
}
|
||||
}
|
||||
if (!fnd) {
|
||||
rep.add(array.get(i));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
obj.add("extra", rep);
|
||||
if(!obj.has("text")){
|
||||
obj.addProperty("text", "");
|
||||
}
|
||||
return obj.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String parseEmpty(String json, List<String> replacements, String repl, List<String> tooltip, Player sender) {
|
||||
JsonObject obj = PARSER.parse(json).getAsJsonObject();
|
||||
JsonArray array = obj.getAsJsonArray("extra");
|
||||
replaces = replacements;
|
||||
String regex = "";
|
||||
for (int i = 0; i < replacements.size(); ++i) {
|
||||
if (replacements.size() == 1) {
|
||||
regex = Pattern.quote(replacements.get(0));
|
||||
break;
|
||||
}
|
||||
if (i == 0 || i + 1 == replacements.size()) {
|
||||
if (i == 0) {
|
||||
regex = "(" + Pattern.quote(replacements.get(i));
|
||||
} else {
|
||||
regex = regex.concat("|").concat(Pattern.quote(replacements.get(i))).concat(")");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
regex = regex.concat("|").concat(Pattern.quote(replacements.get(i)));
|
||||
}
|
||||
rgx = regex;
|
||||
JsonArray rep = new JsonArray();
|
||||
JsonArray use = Translator.toJson(repl.replace("{name}", sender.getName()).replace("{display-name}", sender.getDisplayName()));
|
||||
JsonObject hover = PARSER.parse("{\"action\":\"show_text\", \"value\": \"\"}").getAsJsonObject();
|
||||
|
||||
StringBuilder oneLineTooltip = new StringBuilder("");
|
||||
int index = 0;
|
||||
for(String m : tooltip){
|
||||
oneLineTooltip.append(m.replace("{name}", sender.getName()).replace("{display-name}", sender.getDisplayName()));
|
||||
++index;
|
||||
if(index!=tooltip.size()){
|
||||
oneLineTooltip.append('\n');
|
||||
}
|
||||
}
|
||||
|
||||
hover.add("value", new JsonPrimitive(oneLineTooltip.toString()));
|
||||
for (JsonElement ob : use)
|
||||
ob.getAsJsonObject().add("hoverEvent", hover);
|
||||
|
||||
classicTooltip = use;
|
||||
|
||||
for (int i = 0; i < array.size(); ++i) {
|
||||
if (array.get(i).isJsonObject()){
|
||||
JsonObject o = array.get(i).getAsJsonObject();
|
||||
boolean inside = false;
|
||||
for (String replace : replacements)
|
||||
if (o.toString().contains(replace)) {
|
||||
if (inside) {
|
||||
break;
|
||||
}
|
||||
inside = true;
|
||||
}
|
||||
JsonElement text = o.get("text");
|
||||
if (text == null) {
|
||||
JsonElement el = o.get("extra");
|
||||
if (el != null) {
|
||||
JsonArray jar = el.getAsJsonArray();
|
||||
if(jar.size()!=0) {
|
||||
jar = parseNoItemArray(jar);
|
||||
o.add("extra", jar);
|
||||
}else{
|
||||
o.remove("extra");
|
||||
}
|
||||
}
|
||||
continue;
|
||||
} else {
|
||||
if (text.getAsString().isEmpty()) {
|
||||
JsonElement el = o.get("extra");
|
||||
if (el != null) {
|
||||
JsonArray jar = el.getAsJsonArray();
|
||||
if(jar.size()!=0) {
|
||||
jar = parseNoItemArray(jar);
|
||||
o.add("extra", jar);
|
||||
}else{
|
||||
o.remove("extra");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
String msg = text.getAsString();
|
||||
boolean isLast = false;
|
||||
boolean done = false;
|
||||
boolean fnd;
|
||||
String[] splits;
|
||||
for (String repls : replacements) {
|
||||
if (done) {
|
||||
break;
|
||||
}
|
||||
isLast = msg.endsWith(repls);
|
||||
if (isLast) {
|
||||
done = true;
|
||||
msg = msg.concat(".");
|
||||
}
|
||||
}
|
||||
splits = msg.split(regex);
|
||||
fnd = splits.length != 1;
|
||||
if (fnd)
|
||||
for (int j = 0; j < splits.length; ++j) {
|
||||
boolean endDot = (j == splits.length - 1) && isLast;
|
||||
if (!splits[j].isEmpty() && !endDot) {
|
||||
String st = o.toString();
|
||||
JsonObject fix = PARSER.parse(st).getAsJsonObject();
|
||||
fix.addProperty("text", splits[j]);
|
||||
rep.add(fix);
|
||||
}
|
||||
if (j != splits.length - 1) {
|
||||
rep.addAll(use);
|
||||
}
|
||||
}
|
||||
if (!fnd) {
|
||||
rep.add(o);
|
||||
}
|
||||
}else{
|
||||
if(array.get(i).isJsonNull()){
|
||||
continue;
|
||||
}else{
|
||||
if(array.get(i).isJsonArray()){
|
||||
JsonArray jar = array.get(i).getAsJsonArray();
|
||||
if(jar.size()!=0) {
|
||||
jar = parseNoItemArray(array.get(i).getAsJsonArray());
|
||||
rep.set(i, jar);
|
||||
}
|
||||
}else{
|
||||
|
||||
|
||||
String msg = array.get(i).getAsString();
|
||||
boolean isLast = false;
|
||||
boolean done = false;
|
||||
boolean fnd;
|
||||
String[] splits;
|
||||
for (String repls : replacements) {
|
||||
if (done) {
|
||||
break;
|
||||
}
|
||||
isLast = msg.endsWith(repls);
|
||||
if (isLast) {
|
||||
done = true;
|
||||
msg = msg.concat(".");
|
||||
}
|
||||
}
|
||||
splits = msg.split(regex);
|
||||
fnd = splits.length != 1;
|
||||
if (fnd)
|
||||
for (int j = 0; j < splits.length; ++j) {
|
||||
boolean endDot = (j == splits.length - 1) && isLast;
|
||||
if (!splits[j].isEmpty() && !endDot) {
|
||||
JsonElement fix = new JsonPrimitive(splits[j]);
|
||||
rep.add(fix);
|
||||
}
|
||||
if (j != splits.length - 1) {
|
||||
rep.addAll(use);
|
||||
}
|
||||
}
|
||||
if (!fnd) {
|
||||
rep.add(array.get(i));
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
obj.add("extra", rep);
|
||||
return obj.toString();
|
||||
}
|
||||
|
||||
private JsonArray parseNoItemArray(JsonArray arr) {
|
||||
JsonArray replacer = new JsonArray();
|
||||
for (int i = 0; i < arr.size(); ++i) {
|
||||
if (arr.get(i).isJsonObject()){
|
||||
JsonObject o = arr.get(i).getAsJsonObject();
|
||||
boolean inside = false;
|
||||
for (String replacement : replaces)
|
||||
if (o.toString().contains(replacement)) {
|
||||
if (inside) {
|
||||
break;
|
||||
}
|
||||
inside = true;
|
||||
}
|
||||
if (!inside) { //the placeholder we're looking for is not inside this element, so we continue searching
|
||||
replacer.add(o);
|
||||
continue;
|
||||
}
|
||||
JsonElement text = o.get("text");
|
||||
if (text == null) {
|
||||
continue;
|
||||
}
|
||||
if (text.getAsString().isEmpty()) {
|
||||
JsonElement el = o.get("extra");
|
||||
if (el == null) {
|
||||
continue;
|
||||
}
|
||||
JsonArray jar = el.getAsJsonArray();
|
||||
if(jar.size()!=0) {
|
||||
jar = parseNoItemArray(jar);
|
||||
o.add("extra", jar);
|
||||
}else{
|
||||
o.remove("extra");
|
||||
}
|
||||
}
|
||||
|
||||
String msg = text.getAsString();
|
||||
boolean isLast = false;
|
||||
boolean done = false;
|
||||
boolean fnd;
|
||||
String[] splits;
|
||||
for (String repls : replaces) {
|
||||
if (done) {
|
||||
break;
|
||||
}
|
||||
isLast = msg.endsWith(repls);
|
||||
if (isLast) {
|
||||
done = true;
|
||||
msg = msg.concat(".");
|
||||
}
|
||||
}
|
||||
splits = msg.split(rgx);
|
||||
fnd = splits.length != 1;
|
||||
if (fnd)
|
||||
for (int j = 0; j < splits.length; ++j) {
|
||||
boolean endDot = (j == splits.length - 1) && isLast;
|
||||
if (!splits[j].isEmpty() && !endDot) {
|
||||
String st = o.toString();
|
||||
JsonObject fix = PARSER.parse(st).getAsJsonObject();
|
||||
fix.addProperty("text", splits[j]);
|
||||
replacer.add(fix);
|
||||
}
|
||||
if (j != splits.length - 1) {
|
||||
replacer.addAll(classicTooltip);
|
||||
}
|
||||
}
|
||||
if (!fnd) {
|
||||
replacer.add(o);
|
||||
}
|
||||
}else{
|
||||
if(arr.get(i).isJsonNull()){
|
||||
continue;
|
||||
}else{
|
||||
if(arr.get(i).isJsonArray()){
|
||||
JsonArray jar = arr.get(i).getAsJsonArray();
|
||||
if(jar.size()!=0) {
|
||||
jar = parseNoItemArray(arr.get(i).getAsJsonArray());
|
||||
replacer.set(i, jar);
|
||||
}
|
||||
}else{
|
||||
String msg = arr.get(i).getAsString();
|
||||
boolean isLast = false;
|
||||
boolean done = false;
|
||||
boolean fnd;
|
||||
String[] splits;
|
||||
for (String repls : replaces) {
|
||||
if (done) {
|
||||
break;
|
||||
}
|
||||
isLast = msg.endsWith(repls);
|
||||
if (isLast) {
|
||||
done = true;
|
||||
msg = msg.concat(".");
|
||||
}
|
||||
}
|
||||
splits = msg.split(rgx);
|
||||
fnd = splits.length != 1;
|
||||
if (fnd)
|
||||
for (int j = 0; j < splits.length; ++j) {
|
||||
boolean endDot = (j == splits.length - 1) && isLast;
|
||||
if (!splits[j].isEmpty() && !endDot) {
|
||||
JsonElement fix = new JsonPrimitive(splits[j]);
|
||||
replacer.add(fix);
|
||||
}
|
||||
if (j != splits.length - 1) {
|
||||
replacer.addAll(classicTooltip);
|
||||
}
|
||||
}
|
||||
if (!fnd) {
|
||||
replacer.add(arr.get(i));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
return replacer;
|
||||
}
|
||||
|
||||
private JsonArray parseArray(JsonArray arr) {
|
||||
JsonArray replacer = new JsonArray();
|
||||
for (int i = 0; i < arr.size(); ++i) {
|
||||
if (arr.get(i).isJsonObject()){
|
||||
JsonObject o = arr.get(i).getAsJsonObject();
|
||||
boolean inside = false;
|
||||
for (String replacement : replaces)
|
||||
if (o.toString().contains(replacement)) {
|
||||
if (inside) {
|
||||
break;
|
||||
}
|
||||
inside = true;
|
||||
}
|
||||
if (!inside) { //the placeholder we're looking for is not inside this element, so we continue searching
|
||||
replacer.add(o);
|
||||
continue;
|
||||
}
|
||||
JsonElement text = o.get("text");
|
||||
if (text == null) {
|
||||
continue;
|
||||
}
|
||||
if (text.getAsString().isEmpty()) {
|
||||
JsonElement el = o.get("extra");
|
||||
if (el == null) {
|
||||
continue;
|
||||
}
|
||||
JsonArray jar = el.getAsJsonArray();
|
||||
if(jar.size()!=0) {
|
||||
jar = parseArray(jar);
|
||||
o.add("extra", jar);
|
||||
}else{
|
||||
o.remove("extra");
|
||||
}
|
||||
}
|
||||
|
||||
String msg = text.getAsString();
|
||||
boolean isLast = false;
|
||||
boolean done = false;
|
||||
boolean fnd;
|
||||
String[] splits;
|
||||
for (String repls : replaces) {
|
||||
if (done) {
|
||||
break;
|
||||
}
|
||||
isLast = msg.endsWith(repls);
|
||||
if (isLast) {
|
||||
done = true;
|
||||
msg = msg.concat(".");
|
||||
}
|
||||
}
|
||||
splits = msg.split(rgx);
|
||||
fnd = splits.length != 1;
|
||||
if (fnd)
|
||||
for (int j = 0; j < splits.length; ++j) {
|
||||
boolean endDot = (j == splits.length - 1) && isLast;
|
||||
if (!splits[j].isEmpty() && !endDot) {
|
||||
String st = o.toString();
|
||||
JsonObject fix = PARSER.parse(st).getAsJsonObject();
|
||||
fix.addProperty("text", splits[j]);
|
||||
replacer.add(fix);
|
||||
}
|
||||
if (j != splits.length - 1) {
|
||||
replacer.add(itemTooltip);
|
||||
}
|
||||
}
|
||||
if (!fnd) {
|
||||
replacer.add(o);
|
||||
}
|
||||
}else{
|
||||
if(arr.get(i).isJsonNull()){
|
||||
continue;
|
||||
}else{
|
||||
if(arr.get(i).isJsonArray()){
|
||||
JsonArray jar = arr.get(i).getAsJsonArray();
|
||||
if(jar.size()!=0) {
|
||||
jar = parseArray(arr.get(i).getAsJsonArray());
|
||||
replacer.set(i, jar);
|
||||
}
|
||||
}else{
|
||||
String msg = arr.get(i).getAsString();
|
||||
boolean isLast = false;
|
||||
boolean done = false;
|
||||
boolean fnd;
|
||||
String[] splits;
|
||||
for (String repls : replaces) {
|
||||
if (done) {
|
||||
break;
|
||||
}
|
||||
isLast = msg.endsWith(repls);
|
||||
if (isLast) {
|
||||
done = true;
|
||||
msg = msg.concat(".");
|
||||
}
|
||||
}
|
||||
splits = msg.split(rgx);
|
||||
fnd = splits.length != 1;
|
||||
if (fnd)
|
||||
for (int j = 0; j < splits.length; ++j) {
|
||||
boolean endDot = (j == splits.length - 1) && isLast;
|
||||
if (!splits[j].isEmpty() && !endDot) {
|
||||
JsonElement fix = new JsonPrimitive(splits[j]);
|
||||
replacer.add(fix);
|
||||
}
|
||||
if (j != splits.length - 1) {
|
||||
replacer.add(itemTooltip);
|
||||
}
|
||||
}
|
||||
if (!fnd) {
|
||||
replacer.add(arr.get(i));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
return replacer;
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
private Item toItem(ItemStack is) throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException {
|
||||
CompoundTag tag = new CompoundTag("tag");
|
||||
|
||||
Object nmsStack = AS_NMS_COPY.invoke(null, is);
|
||||
Object nmsTag = NBT_TAG_COMPOUND.newInstance();
|
||||
SAVE_NMS_ITEM_STACK_METHOD.invoke(nmsStack, nmsTag);
|
||||
Map<String, Object> nmsMap = (Map<String, Object>) MAP.get(nmsTag);
|
||||
String id = nmsMap.get("id").toString().replace("\"", "");
|
||||
Object realTag = nmsMap.get("tag");
|
||||
if(NBT_TAG_COMPOUND.isInstance(realTag)) { //We need to make sure this is indeed an NBTTagCompound
|
||||
Map<String, Object> realMap = (Map<String, Object>) MAP.get(realTag);
|
||||
Set<Map.Entry<String, Object>> entrySet = realMap.entrySet();
|
||||
Map<String, Tag> map = tag.getValue();
|
||||
for (Map.Entry<String, Object> entry : entrySet) {
|
||||
map.put(entry.getKey(), toOpenTag(entry.getValue(), entry.getKey()));
|
||||
}
|
||||
tag.setValue(map);
|
||||
}
|
||||
|
||||
Item item = new Item();
|
||||
item.setAmount((byte)is.getAmount());
|
||||
item.setData(is.getDurability());
|
||||
item.setId(id);
|
||||
item.setTag(tag);
|
||||
return item;
|
||||
}
|
||||
|
||||
private Tag toOpenTag(Object nmsTag, String name) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException, InstantiationException {
|
||||
if(NBT_TAG_COMPOUND.isInstance(nmsTag)) {
|
||||
CompoundTag tag = new CompoundTag(name);
|
||||
Map<String, Tag> tagMap = tag.getValue();
|
||||
|
||||
Map<String, Object> nmsMap = (Map<String, Object>) MAP.get(nmsTag);
|
||||
Set<Map.Entry<String, Object>> entrySet = nmsMap.entrySet();
|
||||
for (Map.Entry<String, Object> entry : entrySet) {
|
||||
Tag value = toOpenTag(entry.getValue(), entry.getKey());
|
||||
tagMap.put(entry.getKey(), value);
|
||||
}
|
||||
tag.setValue(tagMap);
|
||||
return tag;
|
||||
} else {
|
||||
//Strings are a special case as they need proper escaping
|
||||
if(NBT_STRING.isInstance(nmsTag)) {
|
||||
String toString = nmsTag.toString();
|
||||
if (toString.startsWith("\"") && toString.endsWith("\"")) {
|
||||
toString = toString.substring(1, toString.length() - 1);
|
||||
//toString = escapeSpecials(toString);
|
||||
return new StringTag(name, toString);
|
||||
}
|
||||
}
|
||||
|
||||
//NBTTag Lists are also special, as they are a sort of compound themselves and need to be parsed recursively
|
||||
if(NBT_LIST.isInstance(nmsTag)){
|
||||
List<Object> nmsNBTBaseList = (List<Object>) LIST_FIELD.get(nmsTag);
|
||||
List<Tag> list = new ArrayList<>();
|
||||
int i = 0;
|
||||
for(Object baseTag : nmsNBTBaseList){
|
||||
list.add(toOpenTag(baseTag, String.valueOf(i)));
|
||||
++i;
|
||||
}
|
||||
return new ListTag(name, list);
|
||||
}
|
||||
|
||||
for(int i = 0; i < NBT_BASE_CLASSES.size(); ++i){
|
||||
Class<?> c = NBT_BASE_CLASSES.get(i);
|
||||
if(c.isInstance(nmsTag)){
|
||||
Object value = NBT_BASE_DATA_FIELD.get(i).get(nmsTag);
|
||||
|
||||
Tag t = TYPES_TO_OPEN_NBT_TAGS.get(value.getClass()).getClass().getConstructor(String.class).newInstance(name);
|
||||
|
||||
if(t instanceof ByteTag){
|
||||
((ByteTag)t).setValue((byte)value);
|
||||
((ByteTag)t).setValue((byte)value);
|
||||
return t;
|
||||
}
|
||||
if(t instanceof ByteArrayTag){
|
||||
((ByteArrayTag)t).setValue((byte[])value);
|
||||
return t;
|
||||
}
|
||||
if(t instanceof DoubleTag){
|
||||
((DoubleTag)t).setValue((double)value);
|
||||
return t;
|
||||
}
|
||||
if(t instanceof FloatTag){
|
||||
((FloatTag)t).setValue((float)value);
|
||||
return t;
|
||||
}
|
||||
if(t instanceof IntTag){
|
||||
((IntTag)t).setValue((int)value);
|
||||
return t;
|
||||
}
|
||||
if(t instanceof IntArrayTag){
|
||||
((IntArrayTag)t).setValue((int[])value);
|
||||
return t;
|
||||
}
|
||||
if(t instanceof LongTag){
|
||||
((LongTag)t).setValue((long)value);
|
||||
return t;
|
||||
}
|
||||
if(t instanceof ShortTag){
|
||||
((ShortTag)t).setValue((short)value);
|
||||
return t;
|
||||
}
|
||||
return null; //Should never happen
|
||||
}
|
||||
}
|
||||
return null; //Should never happen
|
||||
}
|
||||
}
|
||||
|
||||
private String stringifyItem(ItemStack stack) throws InvocationTargetException, IllegalAccessException, InstantiationException, NoSuchFieldException, NoSuchMethodException {
|
||||
Item item = toItem(stack);
|
||||
ProtocolVersion.remapIds(ProtocolVersion.getServerVersion().MAX_VER, protocolVersion.MAX_VER, item);
|
||||
StringBuilder sb = new StringBuilder("{id:");
|
||||
sb.append("\"").append(item.getId()).append("\"").append(","); //Append the id
|
||||
sb.append("Count:").append(item.getAmount()).append("b,"); //Append the amount
|
||||
sb.append("Damage:").append(item.getData()).append("s"); //Append the durability data
|
||||
|
||||
Map<String, Tag> tagMap = item.getTag().getValue();
|
||||
if(tagMap.isEmpty()){
|
||||
sb.append("}");
|
||||
return sb.toString();
|
||||
}
|
||||
Set<Map.Entry<String, Tag>> entrySet = tagMap.entrySet();
|
||||
boolean first = true;
|
||||
sb.append(",tag:{"); //Start of the tag
|
||||
for(Map.Entry<String, Tag> entry : entrySet){
|
||||
String key = entry.getKey();
|
||||
if(IGNORED.contains(key)){
|
||||
continue;
|
||||
}
|
||||
Pattern pattern = Pattern.compile("[{}\\[\\],\":\\\\/]");
|
||||
Matcher matcher = pattern.matcher(key);
|
||||
if(matcher.find()){
|
||||
continue; //Skip invalid keys, as they can cause exceptions client-side
|
||||
}
|
||||
String value = stringifyTag(entry.getValue());
|
||||
if(!first){
|
||||
sb.append(",");
|
||||
}
|
||||
sb.append(key).append(":").append(value);
|
||||
first = false;
|
||||
}
|
||||
sb.append("}}"); //End of tag and end of item
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private String stringifyTag(Tag normalTag){
|
||||
if(normalTag instanceof CompoundTag) {
|
||||
StringBuilder sb = new StringBuilder("{");
|
||||
CompoundTag tagCompound = (CompoundTag) normalTag;
|
||||
Map<String, Tag> tagMap = tagCompound.getValue();
|
||||
Set<Map.Entry<String, Tag>> entrySet = tagMap.entrySet();
|
||||
for(Map.Entry<String, Tag> entry : entrySet){
|
||||
String value = stringifyTag(entry.getValue());
|
||||
if(value == null){
|
||||
continue;
|
||||
}
|
||||
if(sb.length()>1){
|
||||
sb.append(",");
|
||||
}
|
||||
sb.append(entry.getKey()).append(":").append(value);
|
||||
}
|
||||
|
||||
sb.append("}");
|
||||
return sb.toString();
|
||||
} else {
|
||||
if(normalTag instanceof StringTag) {
|
||||
return "\""+((StringTag)normalTag).getValue()+"\""; //Should be already escaped
|
||||
}
|
||||
|
||||
if(normalTag instanceof ListTag){
|
||||
List<Tag> list = ((ListTag)normalTag).getValue();
|
||||
StringBuilder sb = new StringBuilder("[");
|
||||
boolean first = true;
|
||||
for(Tag tag : list){
|
||||
String index = tag.getName();
|
||||
String value = stringifyTag(tag);
|
||||
if(value == null){
|
||||
continue;
|
||||
}
|
||||
if(!first){
|
||||
sb.append(",");
|
||||
}
|
||||
if(protocolVersion.MAX_VER <= ProtocolVersion.V1_11.MAX_VER){ //it's before 1.12
|
||||
sb.append(index).append(":").append(value);
|
||||
}else{
|
||||
sb.append(value);
|
||||
}
|
||||
|
||||
first = false;
|
||||
}
|
||||
sb.append("]");
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
if(normalTag instanceof ByteTag){
|
||||
return normalTag.getValue()+"b";
|
||||
}
|
||||
if(normalTag instanceof ByteArrayTag){
|
||||
return "["+((byte[])normalTag.getValue()).length+" bytes]";
|
||||
}
|
||||
if(normalTag instanceof DoubleTag){
|
||||
return (double)normalTag.getValue()+"d";
|
||||
}
|
||||
if(normalTag instanceof FloatTag){
|
||||
return (float)normalTag.getValue()+"f";
|
||||
}
|
||||
if(normalTag instanceof IntTag){
|
||||
return String.valueOf((int)normalTag.getValue());
|
||||
}
|
||||
if(normalTag instanceof IntArrayTag){
|
||||
int[] array = (int[])normalTag.getValue();
|
||||
if(array.length == 0){
|
||||
return null;
|
||||
}
|
||||
StringBuilder sb = new StringBuilder("[");
|
||||
boolean first = true;
|
||||
for(int i : array){
|
||||
if(!first){
|
||||
sb.append(",");
|
||||
}
|
||||
sb.append(i);
|
||||
first = false;
|
||||
}
|
||||
sb.append("]");
|
||||
return sb.toString();
|
||||
}
|
||||
if(normalTag instanceof LongTag){
|
||||
return (long)normalTag.getValue()+"L";
|
||||
}
|
||||
if(normalTag instanceof ShortTag){
|
||||
return (short)normalTag.getValue()+"s";
|
||||
}
|
||||
return null; //Should never happen
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -1,256 +0,0 @@
|
||||
package me.dadus33.chatitem.listeners;
|
||||
|
||||
import me.dadus33.chatitem.utils.Storage;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.command.Command;
|
||||
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.AsyncPlayerChatEvent;
|
||||
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
public class ChatEventListener implements Listener {
|
||||
|
||||
private Storage c;
|
||||
public final static char SEPARATOR = ((char)0x0007);
|
||||
private final static String LEFT = "{remaining}";
|
||||
private final HashMap<String, Long> COOLDOWNS = new HashMap<>();
|
||||
|
||||
public ChatEventListener(Storage storage) {
|
||||
c = storage;
|
||||
}
|
||||
|
||||
private String calculateTime(long seconds){
|
||||
if(seconds < 60){
|
||||
return seconds+c.SECONDS;
|
||||
}
|
||||
if(seconds < 3600){
|
||||
StringBuilder builder = new StringBuilder();
|
||||
int minutes = (int) seconds / 60;
|
||||
builder.append(minutes).append(c.MINUTES);
|
||||
int secs = (int) seconds - minutes*60;
|
||||
if(secs != 0){
|
||||
builder.append(" ").append(secs).append(c.SECONDS);
|
||||
}
|
||||
return builder.toString();
|
||||
}
|
||||
StringBuilder builder = new StringBuilder();
|
||||
int hours = (int) seconds / 3600;
|
||||
builder.append(hours).append(c.HOURS);
|
||||
int minutes = (int) (seconds/60) - (hours*60);
|
||||
if(minutes != 0){
|
||||
builder.append(" ").append(minutes).append(c.MINUTES);
|
||||
}
|
||||
int secs = (int) (seconds - ((seconds/60)*60));
|
||||
if(secs != 0){
|
||||
builder.append(" ").append(secs).append(c.SECONDS);
|
||||
}
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
private int countOccurrences(String findStr, String str){
|
||||
int lastIndex = 0;
|
||||
int count = 0;
|
||||
while(lastIndex != -1){
|
||||
|
||||
lastIndex = str.indexOf(findStr,lastIndex);
|
||||
|
||||
if(lastIndex != -1){
|
||||
count++;
|
||||
lastIndex += findStr.length();
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST) //We need to have lowest priority in order to get to the event before DeluxeChat or other plugins do
|
||||
public void onChat(final AsyncPlayerChatEvent e) {
|
||||
if(e.getMessage().indexOf(SEPARATOR)!=-1){ //If the BELL character is found, we have to remove it
|
||||
String msg = e.getMessage().replace(Character.toString(SEPARATOR), "");
|
||||
e.setMessage(msg);
|
||||
}
|
||||
boolean found = false;
|
||||
|
||||
for (String rep : c.PLACEHOLDERS)
|
||||
if (e.getMessage().contains(rep)) {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
|
||||
if (!found) {
|
||||
return;
|
||||
}
|
||||
|
||||
Player p = e.getPlayer();
|
||||
|
||||
if (!p.hasPermission("chatitem.use")) {
|
||||
if(!c.LET_MESSAGE_THROUGH) {
|
||||
e.setCancelled(true);
|
||||
}
|
||||
if(!c.NO_PERMISSION_MESSAGE.isEmpty() && c.SHOW_NO_PERM_NORMAL){
|
||||
p.sendMessage(c.NO_PERMISSION_MESSAGE);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (p.getItemInHand().getType().equals(Material.AIR)) {
|
||||
if (c.DENY_IF_NO_ITEM) {
|
||||
e.setCancelled(true);
|
||||
if (!c.DENY_MESSAGE.isEmpty())
|
||||
e.getPlayer().sendMessage(c.DENY_MESSAGE);
|
||||
return;
|
||||
}
|
||||
if(c.HAND_DISABLED) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
if(c.COOLDOWN > 0 && !p.hasPermission("chatitem.ignore-cooldown")){
|
||||
if(COOLDOWNS.containsKey(p.getName())){
|
||||
long start = COOLDOWNS.get(p.getName());
|
||||
long current = System.currentTimeMillis()/1000;
|
||||
long elapsed = current - start;
|
||||
if(elapsed >= c.COOLDOWN){
|
||||
COOLDOWNS.remove(p.getName());
|
||||
}else{
|
||||
if(!c.LET_MESSAGE_THROUGH) {
|
||||
e.setCancelled(true);
|
||||
}
|
||||
if(!c.COOLDOWN_MESSAGE.isEmpty()){
|
||||
long left = (start + c.COOLDOWN) - current;
|
||||
p.sendMessage(c.COOLDOWN_MESSAGE.replace(LEFT, calculateTime(left)));
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
String s = e.getMessage();
|
||||
for(String placeholder : c.PLACEHOLDERS){
|
||||
s = s.replace(placeholder, c.PLACEHOLDERS.get(0));
|
||||
}
|
||||
int occurrences = countOccurrences(c.PLACEHOLDERS.get(0), s);
|
||||
|
||||
if(occurrences>c.LIMIT){
|
||||
e.setCancelled(true);
|
||||
if(c.LIMIT_MESSAGE.isEmpty()){
|
||||
return;
|
||||
}
|
||||
e.getPlayer().sendMessage(c.LIMIT_MESSAGE);
|
||||
return;
|
||||
}
|
||||
|
||||
String oldmsg = e.getMessage();
|
||||
StringBuilder sb = new StringBuilder(oldmsg);
|
||||
sb.append(SEPARATOR).append(e.getPlayer().getName());
|
||||
e.setMessage(sb.toString());
|
||||
Bukkit.getConsoleSender().sendMessage(String.format(e.getFormat(), e.getPlayer().getDisplayName(), oldmsg));
|
||||
if(!p.hasPermission("chatitem.ignore-cooldown")) {
|
||||
COOLDOWNS.put(p.getName(), System.currentTimeMillis() / 1000);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
@EventHandler(priority = EventPriority.LOWEST)
|
||||
public void onCommand(final PlayerCommandPreprocessEvent e){
|
||||
if(e.getMessage().indexOf(SEPARATOR)!=-1){ //If the BELL character is found, we have to remove it
|
||||
String msg = e.getMessage().replace(Character.toString(SEPARATOR), "");
|
||||
e.setMessage(msg);
|
||||
}
|
||||
String commandString = e.getMessage().split(" ")[0].replaceAll("^/+", ""); //First part of the command, without leading slashes and without arguments
|
||||
Command cmd = Bukkit.getPluginCommand(commandString);
|
||||
if(cmd==null){ //not a plugin command
|
||||
if(!c.ALLOWED_DEFAULT_COMMANDS.contains(commandString)){
|
||||
return;
|
||||
}
|
||||
}else{
|
||||
if(!c.ALLOWED_PLUGIN_COMMANDS.contains(cmd)){
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
Player p = e.getPlayer();
|
||||
boolean found = false;
|
||||
|
||||
for (String rep : c.PLACEHOLDERS) {
|
||||
if (e.getMessage().contains(rep)) {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!found) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!p.hasPermission("chatitem.use")) {
|
||||
if(!c.NO_PERMISSION_MESSAGE.isEmpty() && c.SHOW_NO_PERM_COMMAND){
|
||||
p.sendMessage(c.NO_PERMISSION_MESSAGE);
|
||||
}
|
||||
e.setCancelled(true);
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.getPlayer().getItemInHand().getType().equals(Material.AIR)) {
|
||||
if (c.DENY_IF_NO_ITEM) {
|
||||
e.setCancelled(true);
|
||||
if (!c.DENY_MESSAGE.isEmpty()) {
|
||||
e.getPlayer().sendMessage(c.DENY_MESSAGE);
|
||||
}
|
||||
}
|
||||
if(c.HAND_DISABLED) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if(c.COOLDOWN > 0 && !p.hasPermission("chatitem.ignore-cooldown")){
|
||||
if(COOLDOWNS.containsKey(p.getName())){
|
||||
long start = COOLDOWNS.get(p.getName());
|
||||
long current = System.currentTimeMillis()/1000;
|
||||
long elapsed = current - start;
|
||||
if(elapsed >= c.COOLDOWN){
|
||||
COOLDOWNS.remove(p.getName());
|
||||
}else{
|
||||
if(!c.LET_MESSAGE_THROUGH) {
|
||||
e.setCancelled(true);
|
||||
}
|
||||
if(!c.COOLDOWN_MESSAGE.isEmpty()){
|
||||
long left = (start + c.COOLDOWN) - current;
|
||||
p.sendMessage(c.COOLDOWN_MESSAGE.replace(LEFT, calculateTime(left)));
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
String s = e.getMessage();
|
||||
for(String placeholder : c.PLACEHOLDERS){
|
||||
s = s.replace(placeholder, c.PLACEHOLDERS.get(0));
|
||||
}
|
||||
int occurrences = countOccurrences(c.PLACEHOLDERS.get(0), s);
|
||||
|
||||
if(occurrences>c.LIMIT){
|
||||
e.setCancelled(true);
|
||||
if(c.LIMIT_MESSAGE.isEmpty()){
|
||||
return;
|
||||
}
|
||||
e.getPlayer().sendMessage(c.LIMIT_MESSAGE);
|
||||
return;
|
||||
}
|
||||
|
||||
StringBuilder sb = new StringBuilder(e.getMessage());
|
||||
sb.append(SEPARATOR).append(e.getPlayer().getName());
|
||||
e.setMessage(sb.toString());
|
||||
if(!p.hasPermission("chatitem.ignore-cooldown")) {
|
||||
COOLDOWNS.put(p.getName(), System.currentTimeMillis() / 1000);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public void setStorage(Storage st) {
|
||||
c = st;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package me.dadus33.chatitem.listeners;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
import org.bukkit.inventory.Inventory;
|
||||
import org.bukkit.inventory.InventoryHolder;
|
||||
|
||||
public class ChatItemAdminHolder implements InventoryHolder {
|
||||
|
||||
public final HashMap<Integer, String> keyBySlot = new HashMap<>();
|
||||
|
||||
@Override
|
||||
public Inventory getInventory() {
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,233 +0,0 @@
|
||||
package me.dadus33.chatitem.listeners;
|
||||
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.block.ShulkerBox;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.meta.BlockStateMeta;
|
||||
import org.bukkit.inventory.meta.BookMeta;
|
||||
import org.bukkit.inventory.meta.ItemMeta;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
|
||||
import com.comphenix.protocol.PacketType;
|
||||
import com.comphenix.protocol.ProtocolLibrary;
|
||||
import com.comphenix.protocol.events.ListenerPriority;
|
||||
import com.comphenix.protocol.events.PacketAdapter;
|
||||
import com.comphenix.protocol.events.PacketContainer;
|
||||
import com.comphenix.protocol.events.PacketEvent;
|
||||
import com.comphenix.protocol.wrappers.WrappedChatComponent;
|
||||
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
import me.dadus33.chatitem.utils.ProtocolVersion;
|
||||
import me.dadus33.chatitem.utils.Storage;
|
||||
import net.md_5.bungee.api.chat.BaseComponent;
|
||||
import net.md_5.bungee.chat.ComponentSerializer;
|
||||
|
||||
@Deprecated
|
||||
public class ChatPacketListener extends PacketAdapter {
|
||||
|
||||
private final static String NAME = "{name}";
|
||||
private final static String AMOUNT = "{amount}";
|
||||
private final static String TIMES = "{times}";
|
||||
private final static List<Material> SHULKER_BOXES = new ArrayList<>();
|
||||
|
||||
private Storage c;
|
||||
|
||||
|
||||
public ChatPacketListener(Plugin plugin, ListenerPriority listenerPriority, Storage s, PacketType... types) {
|
||||
super(plugin, listenerPriority, types);
|
||||
if(ProtocolVersion.getServerVersion().isNewerOrEquals(ProtocolVersion.V1_11)){
|
||||
SHULKER_BOXES.addAll(Arrays.asList(Material.BLACK_SHULKER_BOX, Material.BLUE_SHULKER_BOX,
|
||||
Material.BROWN_SHULKER_BOX, Material.CYAN_SHULKER_BOX, Material.GRAY_SHULKER_BOX, Material.GREEN_SHULKER_BOX,
|
||||
Material.LIGHT_BLUE_SHULKER_BOX, Material.LIME_SHULKER_BOX, Material.MAGENTA_SHULKER_BOX, Material.ORANGE_SHULKER_BOX,
|
||||
Material.PINK_SHULKER_BOX, Material.PURPLE_SHULKER_BOX, Material.RED_SHULKER_BOX, Material.LIGHT_GRAY_SHULKER_BOX,
|
||||
Material.WHITE_SHULKER_BOX, Material.YELLOW_SHULKER_BOX));
|
||||
}
|
||||
c = s;
|
||||
}
|
||||
|
||||
private static String materialToName(Material m) {
|
||||
if (m.equals(Material.TNT)) {
|
||||
return "TNT";
|
||||
}
|
||||
String orig = m.toString().toLowerCase();
|
||||
String[] splits = orig.split("_");
|
||||
StringBuilder sb = new StringBuilder(orig.length());
|
||||
int pos = 0;
|
||||
for (String split : splits) {
|
||||
sb.append(split);
|
||||
int loc = sb.lastIndexOf(split);
|
||||
char charLoc = sb.charAt(loc);
|
||||
if (!(split.equalsIgnoreCase("of") || split.equalsIgnoreCase("and") ||
|
||||
split.equalsIgnoreCase("with") || split.equalsIgnoreCase("on")))
|
||||
sb.setCharAt(loc, Character.toUpperCase(charLoc));
|
||||
if (pos != splits.length - 1)
|
||||
sb.append(' ');
|
||||
++pos;
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private void stripData(ItemStack i){
|
||||
if(i == null){
|
||||
return;
|
||||
}
|
||||
if(i.getType().equals(Material.AIR)){
|
||||
return;
|
||||
}
|
||||
if(!i.hasItemMeta()){
|
||||
return;
|
||||
}
|
||||
ItemMeta im = Bukkit.getItemFactory().getItemMeta(i.getType());
|
||||
ItemMeta original = i.getItemMeta();
|
||||
if(original.hasDisplayName()){
|
||||
im.setDisplayName(original.getDisplayName());
|
||||
}
|
||||
i.setItemMeta(im);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPacketSending(final PacketEvent e) {
|
||||
if(e.isPlayerTemporary())
|
||||
return;
|
||||
final PacketContainer packet = e.getPacket();
|
||||
if(!packet.getMeta("parse").isPresent()){ //First we check if the packet validator has validated this packet to be parsed by us
|
||||
return;
|
||||
}
|
||||
final boolean usesBaseComponents = (boolean)packet.getMeta("base-component").orElse(false); //The packet validator should also tell if this packet uses base components
|
||||
e.setCancelled(true); //We cancel the packet as we're going to resend it anyways (ignoring listeners this time)
|
||||
Bukkit.getScheduler().runTaskAsynchronously(ChatItem.getInstance(), () -> {
|
||||
String json = (String)packet.getMeta("json").orElse(""); //The packet validator got the json for us, so no need to get it again
|
||||
int topIndex = -1;
|
||||
String name = null;
|
||||
for(Player p : Bukkit.getOnlinePlayers()){
|
||||
String pname = "\\u0007"+p.getName();
|
||||
if(!json.contains(pname)){
|
||||
continue;
|
||||
}
|
||||
int index = json.lastIndexOf(pname)+pname.length();
|
||||
if(index>topIndex){
|
||||
topIndex = index;
|
||||
name = pname.replace("\\u0007", "");
|
||||
}
|
||||
}
|
||||
if(name==null){ //something went really bad, so we run away and hide (AKA the player left or is on another server)
|
||||
return;
|
||||
}
|
||||
|
||||
Player p = Bukkit.getPlayer(name);
|
||||
StringBuilder builder = new StringBuilder(json);
|
||||
builder.replace(topIndex-(name.length()+6), topIndex, ""); //we remove both the name and the separator from the json string
|
||||
json = builder.toString();
|
||||
|
||||
String message = null;
|
||||
try {
|
||||
if(!p.getItemInHand().getType().equals(Material.AIR)) {
|
||||
ItemStack copy = p.getItemInHand().clone();
|
||||
if(copy.getType().name().contains("_BOOK")){ //filtering written books
|
||||
BookMeta bm = (BookMeta)copy.getItemMeta();
|
||||
bm.setPages(Collections.emptyList());
|
||||
copy.setItemMeta(bm);
|
||||
} else {
|
||||
if (ProtocolVersion.getServerVersion().isNewerOrEquals(ProtocolVersion.V1_11)) { //filtering shulker boxes
|
||||
if (SHULKER_BOXES.contains(copy.getType())) {
|
||||
if (copy.hasItemMeta()) {
|
||||
BlockStateMeta bsm = (BlockStateMeta) copy.getItemMeta();
|
||||
if (bsm.hasBlockState()) {
|
||||
ShulkerBox sb = (ShulkerBox) bsm.getBlockState();
|
||||
for (ItemStack item : sb.getInventory()) {
|
||||
stripData(item);
|
||||
}
|
||||
bsm.setBlockState(sb);
|
||||
}
|
||||
copy.setItemMeta(bsm);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
message = ChatItem.getManipulator().parse(json, c.PLACEHOLDERS, copy, styleItem(copy, c), ProtocolVersion.getClientVersion(e.getPlayer()));
|
||||
} else {
|
||||
if(!c.HAND_DISABLED){
|
||||
message = ChatItem.getManipulator().parseEmpty(json, c.PLACEHOLDERS, c.HAND_NAME, c.HAND_TOOLTIP, p);
|
||||
}
|
||||
}
|
||||
} catch (InvocationTargetException | IllegalAccessException | InstantiationException | NoSuchFieldException | NoSuchMethodException e1) {
|
||||
e1.printStackTrace();
|
||||
}
|
||||
if(message!=null) {
|
||||
if(!usesBaseComponents) {
|
||||
packet.getChatComponents().writeSafely(0, WrappedChatComponent.fromJson(message));
|
||||
}else{
|
||||
packet.getSpecificModifier(BaseComponent[].class).writeSafely(0, ComponentSerializer.parse(message));
|
||||
}
|
||||
try {
|
||||
ProtocolLibrary.getProtocolManager().sendServerPacket(e.getPlayer(), packet, false);
|
||||
} catch (InvocationTargetException e1) {
|
||||
e1.printStackTrace();
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
ProtocolLibrary.getProtocolManager().sendServerPacket(e.getPlayer(), packet, false);
|
||||
} catch (InvocationTargetException e1) {
|
||||
e1.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void setStorage(Storage st) {
|
||||
c = st;
|
||||
}
|
||||
|
||||
public static String styleItem(ItemStack item, Storage c){
|
||||
String replacer = c.NAME_FORMAT;
|
||||
String amount = c.AMOUNT_FORMAT;
|
||||
boolean dname = item.hasItemMeta() ? item.getItemMeta().hasDisplayName() : false;
|
||||
|
||||
if (item.getAmount() == 1) {
|
||||
if (c.FORCE_ADD_AMOUNT) {
|
||||
amount = amount.replace(TIMES, "1");
|
||||
replacer = replacer.replace(AMOUNT, amount);
|
||||
} else {
|
||||
replacer = replacer.replace(AMOUNT, "");
|
||||
}
|
||||
} else {
|
||||
amount = amount.replace(TIMES, String.valueOf(item.getAmount()));
|
||||
replacer = replacer.replace(AMOUNT, amount);
|
||||
}
|
||||
if (dname) {
|
||||
String trp = item.getItemMeta().getDisplayName();
|
||||
if(c.COLOR_IF_ALREADY_COLORED){
|
||||
replacer = replacer.replace(NAME, ChatColor.stripColor(trp));
|
||||
} else {
|
||||
replacer = replacer.replace(NAME, trp);
|
||||
}
|
||||
} else {
|
||||
HashMap<Short, String> translationSection = c.TRANSLATIONS.get(item.getType().name());
|
||||
if(translationSection==null){
|
||||
String trp = materialToName(item.getType());
|
||||
replacer = replacer.replace(NAME, trp);
|
||||
}else {
|
||||
String translated = translationSection.get(item.getDurability());
|
||||
if (translated != null) {
|
||||
replacer = replacer.replace(NAME, translated);
|
||||
} else {
|
||||
replacer = replacer.replace(NAME, materialToName(item.getType()));
|
||||
}
|
||||
}
|
||||
}
|
||||
return replacer;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,229 +0,0 @@
|
||||
package me.dadus33.chatitem.listeners;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.block.ShulkerBox;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.meta.BlockStateMeta;
|
||||
import org.bukkit.inventory.meta.BookMeta;
|
||||
import org.bukkit.inventory.meta.ItemMeta;
|
||||
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
import me.dadus33.chatitem.packets.ChatItemPacket;
|
||||
import me.dadus33.chatitem.packets.PacketContent;
|
||||
import me.dadus33.chatitem.packets.PacketHandler;
|
||||
import me.dadus33.chatitem.packets.PacketMetadata;
|
||||
import me.dadus33.chatitem.packets.PacketType;
|
||||
import me.dadus33.chatitem.utils.PacketUtils;
|
||||
import me.dadus33.chatitem.utils.ProtocolVersion;
|
||||
import me.dadus33.chatitem.utils.Storage;
|
||||
import net.md_5.bungee.api.chat.BaseComponent;
|
||||
import net.md_5.bungee.chat.ComponentSerializer;
|
||||
|
||||
public class ChatPacketListenerV2 extends PacketHandler {
|
||||
|
||||
private final static String NAME = "{name}";
|
||||
private final static String AMOUNT = "{amount}";
|
||||
private final static String TIMES = "{times}";
|
||||
|
||||
private Storage c;
|
||||
|
||||
public ChatPacketListenerV2(Storage s) {
|
||||
c = s;
|
||||
}
|
||||
|
||||
private static String materialToName(Material m) {
|
||||
if (m.equals(Material.TNT)) {
|
||||
return "TNT";
|
||||
}
|
||||
String orig = m.toString().toLowerCase();
|
||||
String[] splits = orig.split("_");
|
||||
StringBuilder sb = new StringBuilder(orig.length());
|
||||
int pos = 0;
|
||||
for (String split : splits) {
|
||||
sb.append(split);
|
||||
int loc = sb.lastIndexOf(split);
|
||||
char charLoc = sb.charAt(loc);
|
||||
if (!(split.equalsIgnoreCase("of") || split.equalsIgnoreCase("and") || split.equalsIgnoreCase("with")
|
||||
|| split.equalsIgnoreCase("on")))
|
||||
sb.setCharAt(loc, Character.toUpperCase(charLoc));
|
||||
if (pos != splits.length - 1)
|
||||
sb.append(' ');
|
||||
++pos;
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private void stripData(ItemStack i) {
|
||||
if (i == null) {
|
||||
return;
|
||||
}
|
||||
if (i.getType().equals(Material.AIR)) {
|
||||
return;
|
||||
}
|
||||
if (!i.hasItemMeta()) {
|
||||
return;
|
||||
}
|
||||
ItemMeta im = Bukkit.getItemFactory().getItemMeta(i.getType());
|
||||
ItemMeta original = i.getItemMeta();
|
||||
if (original.hasDisplayName()) {
|
||||
im.setDisplayName(original.getDisplayName());
|
||||
}
|
||||
i.setItemMeta(im);
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
@Override
|
||||
public void onSend(ChatItemPacket e) {
|
||||
if(!e.hasPlayer() || !e.getPacketType().equals(PacketType.Server.CHAT)) {
|
||||
return;
|
||||
}
|
||||
final PacketContent packet = e.getContent();
|
||||
final PacketMetadata meta = e.getMetaData();
|
||||
if (!meta.hasMeta("parse")) { // First we check if the packet validator has validated this packet to be parsed
|
||||
// by us
|
||||
ChatItem.debug("Can't parse : " + e.getPacket());
|
||||
meta.getMetas().forEach((s, o) -> ChatItem.debug("metaData: " + s + " > " + o));
|
||||
return;
|
||||
}
|
||||
meta.removeMeta("parse");
|
||||
boolean usesBaseComponents = meta.getMeta("base-component", false); // The packet validator should also tell if this
|
||||
// packet uses base
|
||||
// components
|
||||
e.setCancelled(true); // We cancel the packet as we're going to resend it anyways (ignoring listeners
|
||||
// this time)
|
||||
Bukkit.getScheduler().runTaskAsynchronously(ChatItem.getInstance(), () -> {
|
||||
String json = (String) meta.getMeta("json", ""); // The packet validator got the json for us, so no need to
|
||||
// get it again
|
||||
|
||||
int topIndex = -1;
|
||||
String name = null;
|
||||
for (Player p : Bukkit.getOnlinePlayers()) {
|
||||
String pname = "\\u0007" + p.getName();
|
||||
if (!json.contains(pname)) {
|
||||
continue;
|
||||
}
|
||||
int index = json.lastIndexOf(pname) + pname.length();
|
||||
if (index > topIndex) {
|
||||
topIndex = index;
|
||||
name = pname.replace("\\u0007", "");
|
||||
}
|
||||
}
|
||||
if (name == null) { // something went really bad, so we run away and hide (AKA the player left or is
|
||||
// on another server)
|
||||
ChatItem.debug("Name null for " + json);
|
||||
return;
|
||||
}
|
||||
|
||||
Player p = Bukkit.getPlayer(name);
|
||||
StringBuilder builder = new StringBuilder(json);
|
||||
builder.replace(topIndex - (name.length() + 6), topIndex, ""); // we remove both the name and the separator
|
||||
// from the json string
|
||||
json = builder.toString();
|
||||
|
||||
String message = null;
|
||||
try {
|
||||
if (!p.getItemInHand().getType().equals(Material.AIR)) {
|
||||
ItemStack copy = p.getItemInHand().clone();
|
||||
if (copy.getType().name().contains("_BOOK")) { // filtering written books
|
||||
BookMeta bm = (BookMeta) copy.getItemMeta();
|
||||
bm.setPages(Collections.emptyList());
|
||||
copy.setItemMeta(bm);
|
||||
} else {
|
||||
if (copy.getType().name().contains("SHULKER_BOX")) { // if it's shulker
|
||||
if (copy.hasItemMeta()) {
|
||||
BlockStateMeta bsm = (BlockStateMeta) copy.getItemMeta();
|
||||
if (bsm.hasBlockState()) {
|
||||
ShulkerBox sb = (ShulkerBox) bsm.getBlockState();
|
||||
for (ItemStack item : sb.getInventory()) {
|
||||
stripData(item);
|
||||
}
|
||||
bsm.setBlockState(sb);
|
||||
}
|
||||
copy.setItemMeta(bsm);
|
||||
}
|
||||
}
|
||||
}
|
||||
message = ChatItem.getManipulator().parse(json, c.PLACEHOLDERS, copy, styleItem(copy, c),
|
||||
ProtocolVersion.getClientVersion(e.getPlayer()));
|
||||
} else {
|
||||
if (!c.HAND_DISABLED) {
|
||||
message = ChatItem.getManipulator().parseEmpty(json, c.PLACEHOLDERS, c.HAND_NAME,
|
||||
c.HAND_TOOLTIP, p);
|
||||
}
|
||||
}
|
||||
} catch (Exception e1) {
|
||||
e1.printStackTrace();
|
||||
}
|
||||
if (message != null) {
|
||||
if (!usesBaseComponents) {
|
||||
packet.getChatComponents().write(0, jsonToChatComponent(message));
|
||||
} else {
|
||||
packet.getSpecificModifier(BaseComponent[].class).write(0, ComponentSerializer.parse(message));
|
||||
}
|
||||
}
|
||||
PacketUtils.sendPacket(p, e.getPacket());
|
||||
});
|
||||
}
|
||||
|
||||
private Object jsonToChatComponent(String json) {
|
||||
try {
|
||||
return PacketUtils.CHAT_SERIALIZER.getMethod("a", String.class).invoke(null, json);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public void setStorage(Storage st) {
|
||||
c = st;
|
||||
}
|
||||
|
||||
public static String styleItem(ItemStack item, Storage c) {
|
||||
String replacer = c.NAME_FORMAT;
|
||||
String amount = c.AMOUNT_FORMAT;
|
||||
boolean dname = item.hasItemMeta() ? item.getItemMeta().hasDisplayName() : false;
|
||||
|
||||
if (item.getAmount() == 1) {
|
||||
if (c.FORCE_ADD_AMOUNT) {
|
||||
amount = amount.replace(TIMES, "1");
|
||||
replacer = replacer.replace(AMOUNT, amount);
|
||||
} else {
|
||||
replacer = replacer.replace(AMOUNT, "");
|
||||
}
|
||||
} else {
|
||||
amount = amount.replace(TIMES, String.valueOf(item.getAmount()));
|
||||
replacer = replacer.replace(AMOUNT, amount);
|
||||
}
|
||||
if (dname) {
|
||||
String trp = item.getItemMeta().getDisplayName();
|
||||
if (c.COLOR_IF_ALREADY_COLORED) {
|
||||
replacer = replacer.replace(NAME, ChatColor.stripColor(trp));
|
||||
} else {
|
||||
replacer = replacer.replace(NAME, trp);
|
||||
}
|
||||
} else {
|
||||
HashMap<Short, String> translationSection = c.TRANSLATIONS.get(item.getType().name());
|
||||
if (translationSection == null) {
|
||||
String trp = materialToName(item.getType());
|
||||
replacer = replacer.replace(NAME, trp);
|
||||
} else {
|
||||
@SuppressWarnings("deprecation")
|
||||
String translated = translationSection.get(item.getDurability());
|
||||
if (translated != null) {
|
||||
replacer = replacer.replace(NAME, translated);
|
||||
} else {
|
||||
replacer = replacer.replace(NAME, materialToName(item.getType()));
|
||||
}
|
||||
}
|
||||
}
|
||||
return replacer;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
package me.dadus33.chatitem.listeners;
|
||||
|
||||
import org.bukkit.plugin.Plugin;
|
||||
|
||||
import com.comphenix.protocol.PacketType;
|
||||
import com.comphenix.protocol.events.ListenerPriority;
|
||||
import com.comphenix.protocol.events.PacketAdapter;
|
||||
import com.comphenix.protocol.events.PacketContainer;
|
||||
import com.comphenix.protocol.events.PacketEvent;
|
||||
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
import me.dadus33.chatitem.utils.ProtocolVersion;
|
||||
import me.dadus33.chatitem.utils.Storage;
|
||||
import net.md_5.bungee.api.chat.BaseComponent;
|
||||
import net.md_5.bungee.chat.ComponentSerializer;
|
||||
|
||||
@Deprecated
|
||||
public class ChatPacketValidator extends PacketAdapter {
|
||||
|
||||
private Storage c;
|
||||
|
||||
public ChatPacketValidator(Plugin plugin, ListenerPriority listenerPriority, Storage s, PacketType... types) {
|
||||
super(plugin, listenerPriority, types);
|
||||
c = s;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPacketSending(PacketEvent e){
|
||||
if(e.isPlayerTemporary())
|
||||
return;
|
||||
ProtocolVersion version = ProtocolVersion.getServerVersion();
|
||||
if(version.isNewerOrEquals(ProtocolVersion.V1_8)) { //only if action bar messages are supported in this version of minecraft
|
||||
if(version.isNewerOrEquals(ProtocolVersion.V1_12)){
|
||||
try {
|
||||
if(((Enum<?>)e.getPacket().getSpecificModifier(Class.forName("net.minecraft.server." + ProtocolVersion.BUKKIT_VERSION + ".ChatMessageType")).read(0)).name().equals("GAME_INFO")){
|
||||
return; //It means it's an actionbar message, and we ain't intercepting those
|
||||
}
|
||||
} catch (Exception exc) {
|
||||
exc.printStackTrace();
|
||||
}
|
||||
} else if (e.getPacket().getBytes().readSafely(0) == (byte) 2) {
|
||||
return; //It means it's an actionbar message, and we ain't intercepting those
|
||||
}
|
||||
}
|
||||
boolean usesBaseComponents = false;
|
||||
PacketContainer packet = e.getPacket();
|
||||
String json;
|
||||
if(packet.getChatComponents().readSafely(0)==null){ //null check for some cases of messages sent using spigot's Chat Component API or other means
|
||||
if(ChatItem.supportsChatComponentApi()){ //only if the API is supported in this server distribution
|
||||
BaseComponent[] components = packet.getSpecificModifier(BaseComponent[].class).readSafely(0);
|
||||
if(components == null){
|
||||
return;
|
||||
}
|
||||
json = ComponentSerializer.toString(components);
|
||||
usesBaseComponents = true;
|
||||
}else{
|
||||
return; //We don't know how to deal with anything else. Most probably some mod message we shouldn't mess with anyways
|
||||
}
|
||||
}else{
|
||||
json = packet.getChatComponents().readSafely(0).getJson();
|
||||
}
|
||||
|
||||
boolean found = false;
|
||||
for (String rep : c.PLACEHOLDERS)
|
||||
if (json.contains(rep)) {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
if (!found) {
|
||||
return; //then it's just a normal message without placeholders, so we leave it alone
|
||||
}
|
||||
if(json.lastIndexOf("\\u0007")==-1){ //if the message doesn't contain the BELL separator, then it's certainly NOT a message we want to parse
|
||||
return;
|
||||
}
|
||||
|
||||
packet.setMeta("parse", true); //We mark this packet to be parsed by the packet listener
|
||||
packet.setMeta("base-component", usesBaseComponents); //We also tell it whether this packet uses the base component API
|
||||
packet.setMeta("json", json); //And we finally provide it with the json we already got from the packet
|
||||
}
|
||||
|
||||
public void setStorage(Storage st){
|
||||
c = st;
|
||||
}
|
||||
}
|
||||
@@ -1,101 +0,0 @@
|
||||
package me.dadus33.chatitem.listeners;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
import me.dadus33.chatitem.packets.ChatItemPacket;
|
||||
import me.dadus33.chatitem.packets.PacketContent;
|
||||
import me.dadus33.chatitem.packets.PacketHandler;
|
||||
import me.dadus33.chatitem.packets.PacketMetadata;
|
||||
import me.dadus33.chatitem.packets.PacketType;
|
||||
import me.dadus33.chatitem.utils.PacketUtils;
|
||||
import me.dadus33.chatitem.utils.ProtocolVersion;
|
||||
import me.dadus33.chatitem.utils.Storage;
|
||||
import net.md_5.bungee.api.chat.BaseComponent;
|
||||
import net.md_5.bungee.chat.ComponentSerializer;
|
||||
|
||||
public class ChatPacketValidatorV2 extends PacketHandler {
|
||||
|
||||
private Storage c;
|
||||
private Method serializerGetJson;
|
||||
|
||||
public ChatPacketValidatorV2(Storage s) {
|
||||
c = s;
|
||||
try {
|
||||
for(Method m : PacketUtils.CHAT_SERIALIZER.getDeclaredMethods()) {
|
||||
if(m.getParameterCount() == 1 && m.getParameterTypes()[0].equals(PacketUtils.COMPONENT_CLASS) && m.getReturnType().equals(String.class)) {
|
||||
serializerGetJson = m;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if(serializerGetJson == null)
|
||||
ChatItem.getInstance().getLogger().warning("Failed to find JSON serializer in class: " + PacketUtils.CHAT_SERIALIZER.getCanonicalName());
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSend(ChatItemPacket e) {
|
||||
if(!e.hasPlayer() || !e.getPacketType().equals(PacketType.Server.CHAT))
|
||||
return;
|
||||
ProtocolVersion version = ProtocolVersion.getServerVersion();
|
||||
if(version.isNewerOrEquals(ProtocolVersion.V1_8)) { //only if action bar messages are supported in this version of minecraft
|
||||
if(version.isNewerOrEquals(ProtocolVersion.V1_12)){
|
||||
try {
|
||||
if(((Enum<?>)e.getContent().getSpecificModifier(PacketUtils.getNmsClass("ChatMessageType", "network.chat.")).read(0)).name().equals("GAME_INFO")){
|
||||
return; //It means it's an actionbar message, and we ain't intercepting those
|
||||
}
|
||||
} catch (Exception exc) {
|
||||
exc.printStackTrace();
|
||||
}
|
||||
} else if (e.getContent().getBytes().readSafely(0) == (byte) 2) {
|
||||
return; //It means it's an actionbar message, and we ain't intercepting those
|
||||
}
|
||||
}
|
||||
boolean usesBaseComponents = false;
|
||||
PacketContent packet = e.getContent();
|
||||
String json;
|
||||
if(packet.getChatComponents().readSafely(0) == null){ //null check for some cases of messages sent using spigot's Chat Component API or other means
|
||||
if(!ChatItem.supportsChatComponentApi()) //only if the API is supported in this server distribution
|
||||
return;//We don't know how to deal with anything else. Most probably some mod message we shouldn't mess with anyways
|
||||
|
||||
BaseComponent[] components = packet.getSpecificModifier(BaseComponent[].class).readSafely(0);
|
||||
if(components == null){
|
||||
return;
|
||||
}
|
||||
json = ComponentSerializer.toString(components);
|
||||
usesBaseComponents = true;
|
||||
} else {
|
||||
try {
|
||||
json = (String) serializerGetJson.invoke(null, packet.getChatComponents().readSafely(0));// (String) ReflectionUtils.callMethod(packet.getChatComponents().readSafely(0), "getJson");
|
||||
} catch (Exception exc) {
|
||||
exc.printStackTrace();
|
||||
json = "{}";
|
||||
}
|
||||
}
|
||||
|
||||
boolean found = false;
|
||||
for (String rep : c.PLACEHOLDERS) {
|
||||
if (json.contains(rep)) {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!found) {
|
||||
return; //then it's just a normal message without placeholders, so we leave it alone
|
||||
}
|
||||
if(json.lastIndexOf("\\u0007") == -1){ //if the message doesn't contain the BELL separator, then it's certainly NOT a message we want to parse
|
||||
ChatItem.debug("Not containb bell " + json);
|
||||
return;
|
||||
}
|
||||
PacketMetadata meta = e.getMetaData();
|
||||
meta.setMeta("parse", true); //We mark this packet to be parsed by the packet listener
|
||||
meta.setMeta("base-component", usesBaseComponents); //We also tell it whether this packet uses the base component API
|
||||
meta.setMeta("json", json); //And we finally provide it with the json we already got from the packet
|
||||
}
|
||||
|
||||
public void setStorage(Storage st){
|
||||
c = st;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package me.dadus33.chatitem.listeners;
|
||||
|
||||
import static me.dadus33.chatitem.utils.ItemUtils.createItem;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.inventory.ClickType;
|
||||
import org.bukkit.event.inventory.InventoryClickEvent;
|
||||
import org.bukkit.inventory.Inventory;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
import me.dadus33.chatitem.utils.ItemUtils;
|
||||
import me.dadus33.chatitem.utils.Messages;
|
||||
import me.dadus33.chatitem.utils.Storage;
|
||||
|
||||
public class InventoryListener implements Listener {
|
||||
|
||||
@EventHandler
|
||||
public void onClick(InventoryClickEvent e) {
|
||||
if(e.getClickedInventory() == null || !(e.getWhoClicked() instanceof Player) || e.getCurrentItem() == null
|
||||
|| !(e.getClickedInventory().getHolder() instanceof ChatItemAdminHolder))
|
||||
return;
|
||||
e.setCancelled(true);
|
||||
Player p = (Player) e.getWhoClicked();
|
||||
ItemStack item = e.getCurrentItem();
|
||||
Material type = item.getType();
|
||||
Storage c = ChatItem.getInstance().getStorage();
|
||||
if(type.equals(ItemUtils.MATERIAL_CLOSE)) {
|
||||
p.closeInventory();
|
||||
} else if(type.equals(Material.PAPER)) {
|
||||
ChatItemAdminHolder holder = (ChatItemAdminHolder) e.getClickedInventory().getHolder();
|
||||
String key = holder.keyBySlot.get(e.getSlot());
|
||||
if(key != null) {
|
||||
setInConfig("manager", key);
|
||||
p.closeInventory();
|
||||
ChatItem.reload(p);
|
||||
}
|
||||
} else if(type.equals(ItemUtils.INK_SAC)) {
|
||||
setInConfig("general.color-if-already-colored", c.COLOR_IF_ALREADY_COLORED = !c.COLOR_IF_ALREADY_COLORED);
|
||||
open(p);
|
||||
} else if(type.equals(Material.REDSTONE)) {
|
||||
setInConfig("general.deny-if-no-item", c.DENY_IF_NO_ITEM = !c.DENY_IF_NO_ITEM);
|
||||
open(p);
|
||||
} else if(type.equals(Material.STICK)) {
|
||||
setInConfig("general.hand.disabled", c.HAND_DISABLED = !c.HAND_DISABLED);
|
||||
open(p);
|
||||
} else if(type.equals(ItemUtils.FIREWORK_CHARGE)) {
|
||||
setInConfig("debug", c.DEBUG = !c.DEBUG);
|
||||
open(p);
|
||||
} else if(type.equals(Material.IRON_DOOR)) {
|
||||
if(e.getClick().equals(ClickType.RIGHT))
|
||||
c.LIMIT--;
|
||||
else if(e.getClick().equals(ClickType.LEFT))
|
||||
c.LIMIT++;
|
||||
setInConfig("general.limit-per-message", c.LIMIT);
|
||||
open(p);
|
||||
} else if(type.equals(Material.APPLE)) {
|
||||
if(e.getClick().equals(ClickType.RIGHT))
|
||||
c.COOLDOWN--;
|
||||
else if(e.getClick().equals(ClickType.LEFT))
|
||||
c.COOLDOWN++;
|
||||
setInConfig("general.cooldown", c.COOLDOWN);
|
||||
open(p);
|
||||
}
|
||||
}
|
||||
|
||||
private void setInConfig(String key, Object val) {
|
||||
ChatItem pl = ChatItem.getInstance();
|
||||
pl.getConfig().set(key, val);
|
||||
pl.saveConfig();
|
||||
}
|
||||
|
||||
public static void open(Player p) {
|
||||
ChatItemAdminHolder holder = new ChatItemAdminHolder();
|
||||
Storage c = ChatItem.getInstance().getStorage();
|
||||
Inventory inv = Bukkit.createInventory(holder, 27, Messages.getMessage("admin-inv.name"));
|
||||
for(int i = 0; i < inv.getSize(); i ++)
|
||||
inv.setItem(i, createItem(ItemUtils.WHITE_STAINED_GLASS, "-"));
|
||||
|
||||
int slot = 0;
|
||||
for(String manager : Arrays.asList("both", "auto", "packet", "chat")) {
|
||||
holder.keyBySlot.put(slot, manager);
|
||||
inv.setItem(slot++, getManagerItem(manager));
|
||||
}
|
||||
inv.setItem(slot + 1, getManagerItem("actual", "%manager%", Messages.getMessage("admin-inv.manager." + c.MANAGER + ".name")));
|
||||
|
||||
inv.setItem(8, getBoolChangeItem(ItemUtils.FIREWORK_CHARGE, "debug", c.DEBUG));
|
||||
|
||||
inv.setItem(18, getBoolChangeItem(ItemUtils.INK_SAC, "color-if-already-colored", c.COLOR_IF_ALREADY_COLORED));
|
||||
inv.setItem(19, getBoolChangeItem(Material.REDSTONE, "deny-no-item", c.DENY_IF_NO_ITEM));
|
||||
inv.setItem(20, getBoolChangeItem(Material.STICK, "hand-disabled", c.HAND_DISABLED));
|
||||
inv.setItem(21, getAmountChangeItem(Material.IRON_DOOR, "limit-per-message", c.LIMIT));
|
||||
inv.setItem(22, getAmountChangeItem(Material.APPLE, "cooldown", c.COOLDOWN));
|
||||
|
||||
inv.setItem(26, createItem(ItemUtils.MATERIAL_CLOSE, Messages.getMessage("admin-inv.close")));
|
||||
p.openInventory(inv);
|
||||
}
|
||||
|
||||
private static ItemStack getBoolChangeItem(Material type, String key, boolean b) {
|
||||
return createItem(type, Messages.getMessage("admin-inv." + key, "%state%", Messages.getMessage(b ? "enabled" : "disabled")), Messages.getMessageList("admin-inv.bool-lore"));
|
||||
}
|
||||
|
||||
private static ItemStack getAmountChangeItem(Material type, String key, int amount) {
|
||||
return createItem(type, Messages.getMessage("admin-inv." + key, "%state%", amount), Messages.getMessageList("admin-inv.amount-lore"));
|
||||
}
|
||||
|
||||
private static ItemStack getManagerItem(String manager, Object... placeholders) {
|
||||
return createItem(Material.PAPER, Messages.getMessage("admin-inv.manager." + manager + ".name", placeholders),
|
||||
Messages.getMessageList("admin-inv.manager." + manager + ".lore", placeholders));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package me.dadus33.chatitem.listeners;
|
||||
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.PlayerJoinEvent;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
import me.dadus33.chatitem.chatmanager.ChatManager;
|
||||
import net.md_5.bungee.api.chat.ClickEvent;
|
||||
import net.md_5.bungee.api.chat.ComponentBuilder;
|
||||
import net.md_5.bungee.api.chat.HoverEvent;
|
||||
import net.md_5.bungee.api.chat.TextComponent;
|
||||
import net.md_5.bungee.api.chat.hover.content.Text;
|
||||
|
||||
public class JoinListener implements Listener {
|
||||
|
||||
@EventHandler
|
||||
public void onJoin(PlayerJoinEvent e) {
|
||||
Player p = e.getPlayer();
|
||||
if(!p.isOp())
|
||||
return;
|
||||
ChatItem pl = ChatItem.getInstance();
|
||||
if(pl.isHasNewVersion()) {
|
||||
TextComponent text = new TextComponent(pl.getStorage().JOIN_UPDATE_MESSAGE);
|
||||
text.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new Text(new ComponentBuilder(pl.getStorage().JOIN_UPDATE_HOVER).create())));
|
||||
text.setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, "https://www.spigotmc.org/resources/19064/"));
|
||||
p.spigot().sendMessage(text);
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onLeft(PlayerQuitEvent e) {
|
||||
ChatManager.clear(e.getPlayer());
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
package me.dadus33.chatitem.packets;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
public class PacketMetadata {
|
||||
|
||||
private final HashMap<String, Object> metas = new HashMap<>();
|
||||
|
||||
public void setMeta(String key, Object obj) {
|
||||
this.metas.put(key, obj);
|
||||
}
|
||||
|
||||
public boolean hasMeta(String key) {
|
||||
return metas.containsKey(key);
|
||||
}
|
||||
|
||||
public void removeMeta(String key) {
|
||||
metas.remove(key);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T> T getMeta(String key, T def) {
|
||||
return (T) metas.getOrDefault(key, def);
|
||||
}
|
||||
|
||||
public HashMap<String, Object> getMetas() {
|
||||
return metas;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package me.dadus33.chatitem.playernamer;
|
||||
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import net.md_5.bungee.api.chat.BaseComponent;
|
||||
|
||||
public interface IPlayerNamer {
|
||||
|
||||
public BaseComponent[] getName(Player p);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package me.dadus33.chatitem.playernamer;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
import me.dadus33.chatitem.playernamer.hook.DefaultPlayerNamer;
|
||||
import me.dadus33.chatitem.playernamer.hook.HexNicksPlayerNamer;
|
||||
|
||||
public class PlayerNamerManager {
|
||||
|
||||
private static IPlayerNamer playerNamer;
|
||||
public static IPlayerNamer getPlayerNamer() {
|
||||
return playerNamer;
|
||||
}
|
||||
public static void setPlayerNamer(IPlayerNamer playerNamer) {
|
||||
PlayerNamerManager.playerNamer = playerNamer;
|
||||
}
|
||||
|
||||
public static void load(ChatItem pl) {
|
||||
if(Bukkit.getPluginManager().getPlugin("HexNicks") != null) {
|
||||
setPlayerNamer(new HexNicksPlayerNamer());
|
||||
pl.getLogger().info("Enable support for HexNicks plugin !");
|
||||
} else {
|
||||
setPlayerNamer(new DefaultPlayerNamer());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package me.dadus33.chatitem.playernamer.hook;
|
||||
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import me.dadus33.chatitem.playernamer.IPlayerNamer;
|
||||
import net.md_5.bungee.api.chat.BaseComponent;
|
||||
import net.md_5.bungee.api.chat.ComponentBuilder;
|
||||
|
||||
public class DefaultPlayerNamer implements IPlayerNamer {
|
||||
|
||||
@Override
|
||||
public BaseComponent[] getName(Player p) {
|
||||
return new ComponentBuilder(p.getName()).create();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package me.dadus33.chatitem.playernamer.hook;
|
||||
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import dev.majek.hexnicks.Nicks;
|
||||
import me.dadus33.chatitem.playernamer.IPlayerNamer;
|
||||
import net.kyori.adventure.text.serializer.bungeecord.BungeeComponentSerializer;
|
||||
import net.md_5.bungee.api.chat.BaseComponent;
|
||||
|
||||
public class HexNicksPlayerNamer implements IPlayerNamer {
|
||||
|
||||
@Override
|
||||
public BaseComponent[] getName(Player p) {
|
||||
return BungeeComponentSerializer.get().serialize(Nicks.api().getStoredNick(p).join());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -2,13 +2,13 @@ package me.dadus33.chatitem.playerversion;
|
||||
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import me.dadus33.chatitem.utils.ProtocolVersion;
|
||||
import me.dadus33.chatitem.utils.Version;
|
||||
|
||||
public interface IPlayerVersion {
|
||||
|
||||
public int getProtocolVersion(Player p);
|
||||
|
||||
default ProtocolVersion getPlayerVersion(Player p) {
|
||||
return ProtocolVersion.getVersion(getProtocolVersion(p));
|
||||
default Version getPlayerVersion(Player p) {
|
||||
return Version.getVersion(getProtocolVersion(p), Version.getVersion());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package me.dadus33.chatitem.playerversion;
|
||||
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
import me.dadus33.chatitem.playerversion.hooks.DefaultVersionHook;
|
||||
import me.dadus33.chatitem.playerversion.hooks.ProtocolSupportHook;
|
||||
import me.dadus33.chatitem.playerversion.hooks.ViaVersionHook;
|
||||
import org.bukkit.Bukkit;
|
||||
|
||||
public class PlayerVersionManager {
|
||||
|
||||
private static final IPlayerVersion playerVersionAdapter;
|
||||
|
||||
static {
|
||||
ChatItem pl = ChatItem.getInstance();
|
||||
if (Bukkit.getPluginManager().getPlugin("ProtocolSupport") != null) {
|
||||
playerVersionAdapter = new ProtocolSupportHook();
|
||||
pl.getLogger().info("Loading ProtocolSupport support ...");
|
||||
} else if (Bukkit.getPluginManager().getPlugin("ViaVersion") != null) {
|
||||
playerVersionAdapter = new ViaVersionHook();
|
||||
pl.getLogger().info("Loading ViaVersion support ...");
|
||||
} else {
|
||||
playerVersionAdapter = new DefaultVersionHook();
|
||||
}
|
||||
}
|
||||
|
||||
public static IPlayerVersion getPlayerVersionAdapter() {
|
||||
return playerVersionAdapter;
|
||||
}
|
||||
}
|
||||
@@ -1,22 +1,18 @@
|
||||
package me.dadus33.chatitem.playerversion.hooks;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.UUID;
|
||||
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import me.dadus33.chatitem.playerversion.IPlayerVersion;
|
||||
import me.dadus33.chatitem.utils.ProtocolVersion;
|
||||
import me.dadus33.chatitem.utils.Version;
|
||||
|
||||
public class DefaultVersionHook implements IPlayerVersion {
|
||||
|
||||
public static final HashMap<String, Integer> PROTOCOL_PER_ADDRESS = new HashMap<>();
|
||||
public static final HashMap<UUID, Integer> PROTOCOL_PER_UUID = new HashMap<>();
|
||||
|
||||
@Override
|
||||
public int getProtocolVersion(Player p) {
|
||||
if(PROTOCOL_PER_UUID.containsKey(p.getUniqueId()))
|
||||
return PROTOCOL_PER_UUID.get(p.getUniqueId());
|
||||
return PROTOCOL_PER_ADDRESS.getOrDefault(ProtocolVersion.stringifyAdress(p.getAddress()), ProtocolVersion.getServerVersion().MAX_VER);
|
||||
return PROTOCOL_PER_ADDRESS.getOrDefault(Version.stringifyAdress(p.getAddress()), Version.getVersion().MAX_VER);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package me.dadus33.chatitem.utils;
|
||||
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
import net.md_5.bungee.api.ChatColor;
|
||||
|
||||
public class ColorManager {
|
||||
|
||||
public static String getColorString(String input) {
|
||||
if (input == null || input.isEmpty())
|
||||
return "";
|
||||
StringBuilder str = new StringBuilder();
|
||||
if (Version.getVersion().isNewerOrEquals(Version.V1_16) && input.startsWith("x")) { // x mean it's an hex
|
||||
ChatItem.debug("Removing char x at begin: " + input.substring(1));
|
||||
input = input.substring(1);
|
||||
if (input.length() >= 6) { // at least hex
|
||||
str.append(ChatColor.of("#" + input.substring(0, 6))); // get first hex color code
|
||||
ChatItem.debug("Str with hex: " + str);
|
||||
if (input.length() > 6) // if as another color code
|
||||
str.append(getColorString(input.substring(6))); // get color for after
|
||||
return str.toString();
|
||||
} else
|
||||
ChatItem.debug("Low len: " + input.length());
|
||||
}
|
||||
// not hex
|
||||
for (char c : input.toCharArray())
|
||||
str.append(ChatColor.getByChar(c));
|
||||
return str.toString();
|
||||
}
|
||||
|
||||
public static ChatColor getColor(String input) {
|
||||
if (input == null || input.isEmpty())
|
||||
return ChatColor.RESET;
|
||||
if (Version.getVersion().isNewerOrEquals(Version.V1_16) && input.startsWith("x")) { // x mean it's an hex
|
||||
ChatItem.debug("Removing char x at begin: " + input.substring(1));
|
||||
if (input.length() >= 7) { // at least hex, and 7 because we count the "x"
|
||||
return ChatColor.of("#" + input.substring(1, 7)); // get first hex color code
|
||||
} else
|
||||
ChatItem.debug("Low len: " + input.length());
|
||||
}
|
||||
// not hex
|
||||
return ChatColor.getByChar(input.charAt(0));
|
||||
}
|
||||
|
||||
public static String fixColor(String message) {
|
||||
String colorCode = "", text = "";
|
||||
boolean waiting = false;
|
||||
for (char args : message.toCharArray()) {
|
||||
if (args == '§') { // begin of color
|
||||
waiting = true; // waiting for color code
|
||||
} else if (waiting) { // if waiting for code and valid str
|
||||
// if it's hexademical value and with enough space for full color
|
||||
waiting = false;
|
||||
if (args == 'r' && colorCode.isEmpty()) {
|
||||
text += ChatColor.RESET;
|
||||
continue;
|
||||
}
|
||||
if (args == 'x' && !colorCode.isEmpty()) {
|
||||
text += ColorManager.getColorString(colorCode);
|
||||
colorCode = "x";
|
||||
} else
|
||||
colorCode += args; // a color by itself
|
||||
} else {
|
||||
waiting = false;
|
||||
if (!colorCode.isEmpty()) {
|
||||
if (colorCode.startsWith("x") && colorCode.length() >= 7) {
|
||||
if (colorCode.length() == 7)
|
||||
text += ColorManager.getColor(colorCode);
|
||||
else {
|
||||
text += ColorManager.getColor(colorCode.substring(0, 7)); // only the hex code
|
||||
ChatItem.debug("Adding color for " + colorCode.substring(7, colorCode.length()) + " (in "
|
||||
+ colorCode + ")");
|
||||
text += ColorManager.getColorString(colorCode.substring(7, colorCode.length()));
|
||||
}
|
||||
} else if (colorCode.length() == 1) // if only one color code
|
||||
text += ColorManager.getColor(colorCode);
|
||||
else
|
||||
text += ColorManager.getColorString(colorCode);
|
||||
colorCode = "";
|
||||
}
|
||||
// basic text, not waiting for code after '§'
|
||||
text += args;
|
||||
}
|
||||
}
|
||||
return text;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package me.dadus33.chatitem.utils;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.inventory.ItemFlag;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.meta.ItemMeta;
|
||||
|
||||
public class ItemUtils {
|
||||
|
||||
public static final Material MATERIAL_CLOSE = getMaterialWithCompatibility("BARRIER", "REDSTONE_BLOCK");
|
||||
|
||||
// items
|
||||
public static final Material EMPTY_MAP = getMaterialWithCompatibility("EMPTY_MAP", "MAP");
|
||||
public static final Material BOOK_AND_QUILL = getMaterialWithCompatibility("BOOK_AND_QUILL", "WRITTEN_BOOK");
|
||||
public static final Material WEB = getMaterialWithCompatibility("WEB", "COBWEB");
|
||||
public static final Material FIREBALL = getMaterialWithCompatibility("FIREBALL", "FIRE_CHARGE");
|
||||
public static final Material INK_SAC = getMaterialWithCompatibility("INK_SAC", "INK_SACK", "DYE", "GRAY_DYE");
|
||||
public static final Material FIREWORK_CHARGE = getMaterialWithCompatibility("FIREWORK_CHARGE", "FIRE_CHARGE");
|
||||
|
||||
public static final Material BIRCH_WOOD_STAIRS = getMaterialWithCompatibility("BIRCH_WOOD_STAIRS", "BIRCH_STAIRS");
|
||||
|
||||
// colored items
|
||||
public static final Material GRAY_STAINED_GLASS_PANE = getMaterialWithCompatibility("STAINED_GLASS_PANE", "GRAY_STAINED_GLASS_PANE");
|
||||
public static final Material WHITE_STAINED_GLASS = getMaterialWithCompatibility("STAINED_GLASS_PANE", "WHITE_STAINED_GLASS_PANE");
|
||||
|
||||
public static Material getMaterialWithCompatibility(String... tempMat) {
|
||||
for(String s : tempMat) {
|
||||
try {
|
||||
Material m = (Material) Material.class.getField(s).get(Material.class);
|
||||
if(m != null)
|
||||
return m;
|
||||
} catch (IllegalArgumentException | IllegalAccessException | SecurityException e2) {
|
||||
e2.printStackTrace();
|
||||
} catch (NoSuchFieldException e) {}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static ItemStack createItem(Material m, String name, String... lore) {
|
||||
return createItem(m, name, 1, lore);
|
||||
}
|
||||
|
||||
public static ItemStack createItem(Material m, String name, int quantite, String... lore) {
|
||||
ItemStack item = new ItemStack(m, quantite);
|
||||
ItemMeta meta = (ItemMeta) item.getItemMeta();
|
||||
meta.setDisplayName(ChatColor.RESET + name);
|
||||
meta.setLore(Arrays.asList(lore));
|
||||
item.setItemMeta(meta);
|
||||
return item;
|
||||
}
|
||||
|
||||
public static ItemStack createItem(Material m, String name, List<String> lore) {
|
||||
return createItem(m, name, 1, lore);
|
||||
}
|
||||
|
||||
public static ItemStack createItem(Material m, String name, int quantite, List<String> lore) {
|
||||
ItemStack item = new ItemStack(m, quantite);
|
||||
ItemMeta meta = (ItemMeta) item.getItemMeta();
|
||||
meta.setDisplayName(ChatColor.RESET + name);
|
||||
meta.setLore(lore);
|
||||
item.setItemMeta(meta);
|
||||
return item;
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
public static ItemStack createItem(Material m, String name, int amount, byte b, String... lore) {
|
||||
ItemStack item = new ItemStack(m, amount, b);
|
||||
ItemMeta meta = (ItemMeta) item.getItemMeta();
|
||||
meta.setDisplayName(ChatColor.RESET + name);
|
||||
meta.setLore(Arrays.asList(lore));
|
||||
item.setItemMeta(meta);
|
||||
return item;
|
||||
}
|
||||
|
||||
public static ItemStack hideAttributes(ItemStack stack) {
|
||||
if (Version.getVersion().isNewerThan(Version.V1_7)) {
|
||||
ItemMeta meta = stack.getItemMeta();
|
||||
// All ItemFlags are used to hide attributes, their javadoc says so too.
|
||||
meta.addItemFlags(ItemFlag.values());
|
||||
stack.setItemMeta(meta);
|
||||
}
|
||||
return stack;
|
||||
}
|
||||
|
||||
public static boolean isEmpty(ItemStack item) {
|
||||
return item == null || item.getType().equals(Material.AIR);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package me.dadus33.chatitem.utils;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.bukkit.command.CommandSender;
|
||||
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
|
||||
public class Messages {
|
||||
|
||||
public static void sendMessage(CommandSender p, String key, Object... placeholders) {
|
||||
getMessageList(key, placeholders).forEach(p::sendMessage);
|
||||
}
|
||||
|
||||
public static String getMessage(String key, Object... placeholders) {
|
||||
return colorAndPlaceholders(ChatItem.getInstance().getConfig().getString("messages." + key, key), placeholders);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static List<String> getMessageList(String key, Object... placeholders) {
|
||||
Object obj = ChatItem.getInstance().getConfig().get("messages." + key);
|
||||
if(obj == null)
|
||||
return Arrays.asList(key);
|
||||
if(obj instanceof List) {
|
||||
return ((List<String>) obj).stream().map((s) -> colorAndPlaceholders(s, placeholders)).collect(Collectors.toList());
|
||||
} else if(obj instanceof String)
|
||||
return Arrays.asList(colorAndPlaceholders((String) obj, placeholders));
|
||||
else
|
||||
return Arrays.asList(colorAndPlaceholders(obj.toString(), placeholders));
|
||||
}
|
||||
|
||||
private static String colorAndPlaceholders(String msg, Object... placeholders) {
|
||||
if(msg == null)
|
||||
return "";
|
||||
for (int index = 0; index <= placeholders.length - 1; index += 2) {
|
||||
msg = msg.replace(String.valueOf(placeholders[index]), String.valueOf(placeholders[index + 1]));
|
||||
}
|
||||
return Storage.color(msg);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
package me.dadus33.chatitem.utils;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
@@ -11,21 +13,21 @@ public class PacketUtils {
|
||||
.split(",")[3];
|
||||
public static final String NMS_PREFIX;
|
||||
public static final String OBC_PREFIX;
|
||||
|
||||
public static final boolean IS_THERMOS;
|
||||
public static final Class<?> CRAFT_PLAYER_CLASS, CRAFT_SERVER_CLASS, CHAT_SERIALIZER, COMPONENT_CLASS;
|
||||
|
||||
/**
|
||||
* This Map is to reduce Reflection action which take more ressources than just RAM action
|
||||
* This Map is to reduce Reflection action which take more resources than just RAM action
|
||||
*/
|
||||
private static final HashMap<String, Class<?>> ALL_CLASS;
|
||||
private static final Map<String, Class<?>> ALL_CLASS = Collections.synchronizedMap(new HashMap<String, Class<?>>());
|
||||
|
||||
static {
|
||||
ALL_CLASS = new HashMap<>();
|
||||
NMS_PREFIX = ProtocolVersion.getServerVersion().isNewerOrEquals(ProtocolVersion.V1_17) ? "net.minecraft." : "net.minecraft.server." + VERSION + ".";
|
||||
IS_THERMOS = isClassExist("thermos.Thermos");
|
||||
NMS_PREFIX = Version.getVersion().isNewerOrEquals(Version.V1_17) || IS_THERMOS ? "net.minecraft." : "net.minecraft.server." + VERSION + ".";
|
||||
OBC_PREFIX = "org.bukkit.craftbukkit." + VERSION + ".";
|
||||
CRAFT_PLAYER_CLASS = getObcClass("entity.CraftPlayer");
|
||||
CHAT_SERIALIZER = getNmsClass("IChatBaseComponent$ChatSerializer", "network.chat.", "ChatSerializer");
|
||||
COMPONENT_CLASS = getNmsClass("IChatBaseComponent", "network.chat.");
|
||||
CRAFT_PLAYER_CLASS = getObcClass("entity.CraftPlayer");
|
||||
CRAFT_SERVER_CLASS = getObcClass("CraftServer");
|
||||
}
|
||||
|
||||
@@ -37,7 +39,7 @@ public class PacketUtils {
|
||||
*/
|
||||
public static Class<?> getNmsClass(String name, String packagePrefix, String... alias){
|
||||
return ALL_CLASS.computeIfAbsent(name, (a) -> {
|
||||
String fullPrefix = NMS_PREFIX + (ProtocolVersion.getServerVersion().isNewerOrEquals(ProtocolVersion.V1_17) ? packagePrefix : "");
|
||||
String fullPrefix = NMS_PREFIX + (Version.getVersion().isNewerOrEquals(Version.V1_17) || IS_THERMOS ? packagePrefix : "");
|
||||
try {
|
||||
Class<?> clazz = Class.forName(fullPrefix + name);
|
||||
if(clazz != null)
|
||||
@@ -94,41 +96,6 @@ public class PacketUtils {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current player ping
|
||||
*
|
||||
* @param p the player
|
||||
* @return the player ping
|
||||
*/
|
||||
public static int getPing(Player p) {
|
||||
try {
|
||||
Object entityPlayer = getEntityPlayer(p);
|
||||
return entityPlayer.getClass().getField("ping").getInt(entityPlayer);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get NMS player connection of specified player
|
||||
*
|
||||
* @param p Player of which we want to get the player connection
|
||||
* @return the NMS player connection
|
||||
*/
|
||||
public static Object getPlayerConnection(Player p) {
|
||||
try {
|
||||
Object entityPlayer = getEntityPlayer(p);
|
||||
if(ProtocolVersion.getServerVersion().isNewerOrEquals(ProtocolVersion.V1_17))
|
||||
return entityPlayer.getClass().getField("b").get(entityPlayer);
|
||||
else
|
||||
return entityPlayer.getClass().getField("playerConnection").get(entityPlayer);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get NMS entity player of specified one
|
||||
*
|
||||
@@ -145,32 +112,31 @@ public class PacketUtils {
|
||||
}
|
||||
}
|
||||
|
||||
public static String getNmsEntityName(Object nmsEntity) {
|
||||
public static boolean isClassExist(String name) {
|
||||
try {
|
||||
if(ProtocolVersion.getServerVersion().isNewerOrEquals(ProtocolVersion.V1_13)) {
|
||||
Object chatBaseComponent = getNmsClass("Entity", "world.entity.").getDeclaredMethod("getDisplayName").invoke(nmsEntity);
|
||||
return (String) getNmsClass("IChatBaseComponent", "network.chat.").getDeclaredMethod("getString").invoke(chatBaseComponent);
|
||||
} else {
|
||||
return (String) getNmsClass("Entity", "world.entity.").getDeclaredMethod("getName").invoke(nmsEntity);
|
||||
}
|
||||
Class.forName(name);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send the packet to the specified player
|
||||
* Get NMS player connection of specified player
|
||||
*
|
||||
* @param p which will receive the packet
|
||||
* @param packet the packet to sent
|
||||
* @param p Player of which we want to get the player connection
|
||||
* @return the NMS player connection
|
||||
*/
|
||||
public static void sendPacket(Player p, Object packet) {
|
||||
public static Object getPlayerConnection(Player p) {
|
||||
try {
|
||||
Object playerConnection = getPlayerConnection(p);
|
||||
playerConnection.getClass().getMethod("sendPacket", getNmsClass("Packet", "network.protocol.")).invoke(playerConnection, packet);
|
||||
Object entityPlayer = getEntityPlayer(p);
|
||||
if(Version.getVersion().isNewerOrEquals(Version.V1_17))
|
||||
return entityPlayer.getClass().getField("b").get(entityPlayer);
|
||||
else
|
||||
return entityPlayer.getClass().getField("playerConnection").get(entityPlayer);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -189,4 +155,19 @@ public class PacketUtils {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send the packet to the specified player
|
||||
*
|
||||
* @param p which will receive the packet
|
||||
* @param packet the packet to sent
|
||||
*/
|
||||
public static void sendPacket(Player p, Object packet) {
|
||||
try {
|
||||
Object playerConnection = getPlayerConnection(p);
|
||||
playerConnection.getClass().getMethod(Version.getVersion().isNewerOrEquals(Version.V1_18) ? "a" : "sendPacket", getNmsClass("Packet", "network.protocol.")).invoke(playerConnection, packet);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,121 +0,0 @@
|
||||
package me.dadus33.chatitem.utils;
|
||||
|
||||
import java.net.InetSocketAddress;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
|
||||
public enum ProtocolVersion {
|
||||
|
||||
// http://wiki.vg/Protocol_version_numbers
|
||||
V1_7(0, 5, 0),
|
||||
V1_8(6, 47, 1),
|
||||
V1_9(49, 110, 2), // 1.9.X - Starts with 49 as 48 was an april fools update
|
||||
V1_10(201, 210, 3), // 1.10.X - Starts with 201 because why not.
|
||||
V1_11(301, 316, 4),
|
||||
V1_12(317, 340, 5),
|
||||
V1_13(341, 440, 6),
|
||||
V1_14(100, 441, 500),
|
||||
V1_15(100, 550, 578),
|
||||
V1_16(100, 700, 754),
|
||||
V1_17(100, 755, 756),
|
||||
V1_18(100, 757, 800),
|
||||
V1_19(100, 801, 1000),
|
||||
HIGHER(Integer.MAX_VALUE, -1, Integer.MAX_VALUE);
|
||||
|
||||
// Latest version should always have the upper limit set to Integer.MAX_VALUE so
|
||||
// I don't have to update the plugin for every minor protocol change
|
||||
|
||||
public final int MIN_VER;
|
||||
public final int MAX_VER;
|
||||
public final int index; // Represents how new the version is (0 - extremely old)
|
||||
|
||||
private static final ProtocolVersion SERVER_VERSION;
|
||||
public static final String BUKKIT_VERSION;
|
||||
|
||||
static {
|
||||
BUKKIT_VERSION = Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3];
|
||||
SERVER_VERSION = getVersionByName(BUKKIT_VERSION);
|
||||
}
|
||||
|
||||
ProtocolVersion(int min, int max, int index) {
|
||||
this.MIN_VER = min;
|
||||
this.MAX_VER = max;
|
||||
this.index = index;
|
||||
}
|
||||
|
||||
public boolean isNewerThan(ProtocolVersion other) {
|
||||
return index > other.index;
|
||||
}
|
||||
|
||||
public boolean isNewerOrEquals(ProtocolVersion other) {
|
||||
return index >= other.index;
|
||||
}
|
||||
|
||||
public static ProtocolVersion getVersionByName(String name) {
|
||||
for (ProtocolVersion v : ProtocolVersion.values())
|
||||
if (name.toLowerCase().startsWith(v.name().toLowerCase()))
|
||||
return v;
|
||||
return HIGHER;
|
||||
}
|
||||
|
||||
public static ProtocolVersion getVersion(int protocolVersion) {
|
||||
for (ProtocolVersion ver : ProtocolVersion.values()) {
|
||||
if (protocolVersion >= ver.MIN_VER && protocolVersion <= ver.MAX_VER) {
|
||||
return ver;
|
||||
}
|
||||
}
|
||||
return HIGHER;
|
||||
}
|
||||
|
||||
public static ProtocolVersion getServerVersion() {
|
||||
return SERVER_VERSION;
|
||||
}
|
||||
|
||||
public static void remapIds(int server, int player, Item item) {
|
||||
if (areIdsCompatible(server, player)) {
|
||||
return;
|
||||
}
|
||||
if ((server >= V1_9.MIN_VER && player <= V1_8.MAX_VER) || (player >= V1_9.MIN_VER && server <= V1_8.MAX_VER)) {
|
||||
if ((server >= V1_9.MIN_VER && player <= V1_8.MAX_VER)) {
|
||||
ItemRewriter_1_9_TO_1_8.reversedToClient(item);
|
||||
return;
|
||||
}
|
||||
ItemRewriter_1_9_TO_1_8.toClient(item);
|
||||
return;
|
||||
}
|
||||
if ((server <= V1_10.MAX_VER && player >= V1_11.MIN_VER)
|
||||
|| (player <= V1_10.MAX_VER && server >= V1_11.MIN_VER)) {
|
||||
if (server <= V1_10.MAX_VER && player >= V1_11.MIN_VER) {
|
||||
ItemRewriter_1_11_TO_1_10.toClient(item);
|
||||
} else {
|
||||
ItemRewriter_1_11_TO_1_10.reverseToClient(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean areIdsCompatible(int version1, int version2) {
|
||||
if ((version1 >= V1_9.MIN_VER && version2 <= V1_8.MAX_VER)
|
||||
|| (version2 >= V1_9.MIN_VER && version1 <= V1_8.MAX_VER)) {
|
||||
return false;
|
||||
}
|
||||
if ((version1 <= V1_10.MAX_VER && version2 >= V1_11.MIN_VER)
|
||||
|| (version1 <= V1_10.MAX_VER && version2 >= V1_11.MIN_VER)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static int getClientVersion(Player p) {
|
||||
return ChatItem.getInstance().getPlayerVersionAdapter().getProtocolVersion(p);
|
||||
}
|
||||
|
||||
public static String stringifyAdress(InetSocketAddress address) {
|
||||
String port = String.valueOf(address.getPort());
|
||||
String ip = address.getAddress().getHostAddress();
|
||||
return ip + ":" + port;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -16,6 +16,28 @@ public class Reflect {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static Method getMethod(Class<?> clazz, Class<?> returned, Class<?>... params) {
|
||||
try {
|
||||
for(Method m : clazz.getDeclaredMethods()) {
|
||||
if(returned.equals(m.getReturnType()) && areParamsEquals(m.getParameterTypes(), params))
|
||||
return m;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static boolean areParamsEquals(Class<?>[] p1, Class<?>[] p2) {
|
||||
if(p1.length != p2.length)
|
||||
return false;
|
||||
for(int i = 0; i < p1.length; i++) {
|
||||
if(!p1[i].equals(p2[i]))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static Field getField(Class<?> clazz, String... fieldNames){
|
||||
for(String field : fieldNames) {
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package me.dadus33.chatitem.utils;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Modifier;
|
||||
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
|
||||
public class ReflectionUtils {
|
||||
|
||||
@@ -21,6 +24,31 @@ public class ReflectionUtils {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the specified field name in the object source
|
||||
*
|
||||
* @param source where we will find the field
|
||||
* @param field the name of the field
|
||||
* @return the requested object of the field
|
||||
*/
|
||||
public static Object getObject(Object source, String... field) {
|
||||
try {
|
||||
for(String fieldName : field) {
|
||||
try {
|
||||
Field f = source.getClass().getDeclaredField(fieldName);
|
||||
f.setAccessible(true);
|
||||
return f.get(source);
|
||||
} catch (NoSuchFieldException e) {
|
||||
// ignore because going to next item
|
||||
}
|
||||
}
|
||||
ChatItem.getInstance().getLogger().severe("Failed to find fields: " + String.join(", ", field) + " in " + source.getClass().getSimpleName());
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the specified field name in the object source
|
||||
*
|
||||
@@ -28,11 +56,11 @@ public class ReflectionUtils {
|
||||
* @param field the name of the field
|
||||
* @return the requested field
|
||||
*/
|
||||
public static Object getField(Object source, String field) {
|
||||
public static Field getField(Object source, String field) {
|
||||
try {
|
||||
Field f = source.getClass().getDeclaredField(field);
|
||||
f.setAccessible(true);
|
||||
return f.get(source);
|
||||
return f;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
@@ -56,7 +84,7 @@ public class ReflectionUtils {
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the first field which have the searching for class type
|
||||
* Get the first object which have the searching for class type
|
||||
*
|
||||
* @param from the object where we will try to find the field
|
||||
* @param clazz the class that have to define the field
|
||||
@@ -67,11 +95,30 @@ public class ReflectionUtils {
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <T> T getFirstWith(Object from, Class<?> clazz, Class<T> searchingFor) throws Exception {
|
||||
for (Field f : clazz.getDeclaredFields()) {
|
||||
if (f.getType().equals(searchingFor)) {
|
||||
if (f.getType().equals(searchingFor) && !Modifier.isStatic(f.getModifiers())) {
|
||||
f.setAccessible(true);
|
||||
return (T) f.get(from);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the first field which have the searching for class type
|
||||
*
|
||||
* @param from the object where we will try to find the field
|
||||
* @param clazz the class that have to define the field
|
||||
* @param searchingFor the class of the required field
|
||||
* @return the field (or null if not found)
|
||||
* @throws Exception if something gone wrong
|
||||
*/
|
||||
public static Field getFirstFieldWith(Class<?> clazz, Class<?> searchingFor) throws Exception {
|
||||
for (Field f : clazz.getDeclaredFields()) {
|
||||
if (f.getType().equals(searchingFor) && !Modifier.isStatic(f.getModifiers())) {
|
||||
f.setAccessible(true);
|
||||
return f;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
package me.dadus33.chatitem.utils;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.Objects;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
/**
|
||||
* Represents the simplified SemVer schema Negativity uses for its plugin versions.
|
||||
*/
|
||||
public final class SemVer implements Comparable<SemVer> {
|
||||
|
||||
private final int major;
|
||||
private final int minor;
|
||||
private final int patch;
|
||||
|
||||
private final @Nullable Suffix suffix;
|
||||
|
||||
public SemVer(int major, int minor, int patch, @Nullable Suffix suffix) {
|
||||
this.major = major;
|
||||
this.minor = minor;
|
||||
this.patch = patch;
|
||||
this.suffix = suffix;
|
||||
}
|
||||
|
||||
public boolean isNewerThan(SemVer other) {
|
||||
return this.compareTo(other) > 0;
|
||||
}
|
||||
|
||||
public boolean isOlderThan(SemVer other) {
|
||||
return this.compareTo(other) < 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Slightly different from {@link #equals} in that this method will return
|
||||
* true if the suffix has the same {@link Suffix#getWeight() weight}
|
||||
* but not the same {@link Suffix#getText()} text
|
||||
*/
|
||||
public boolean isEquivalentTo(SemVer other) {
|
||||
return this.compareTo(other) == 0;
|
||||
}
|
||||
|
||||
public int getMajor() {
|
||||
return major;
|
||||
}
|
||||
|
||||
public int getMinor() {
|
||||
return minor;
|
||||
}
|
||||
|
||||
public int getPatch() {
|
||||
return patch;
|
||||
}
|
||||
|
||||
public @Nullable Suffix getSuffix() {
|
||||
return suffix;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int compareTo(SemVer o) {
|
||||
int majorDelta = Integer.compare(this.major, o.major);
|
||||
if (majorDelta != 0) {
|
||||
return majorDelta;
|
||||
}
|
||||
int minorDelta = Integer.compare(this.minor, o.minor);
|
||||
if (minorDelta != 0) {
|
||||
return minorDelta;
|
||||
}
|
||||
int patchDelta = Integer.compare(this.patch, o.patch);
|
||||
if (patchDelta != 0) {
|
||||
return patchDelta;
|
||||
}
|
||||
if (this.suffix != null) {
|
||||
return o.suffix != null ? this.suffix.compareTo(o.suffix) : -1;
|
||||
}
|
||||
if (o.suffix != null) {
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
SemVer semVer = (SemVer) o;
|
||||
return major == semVer.major && minor == semVer.minor && patch == semVer.patch && Objects.equals(suffix, semVer.suffix);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(major, minor, patch, suffix);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "SemVer{major=" + major + ", minor=" + minor + ", patch=" + patch + ", suffix=" + suffix + '}';
|
||||
}
|
||||
|
||||
public String toFormattedString() {
|
||||
if (suffix == null) {
|
||||
if(patch > 0)
|
||||
return major + "." + minor + (patch > 0 ? "." + patch : "");
|
||||
}
|
||||
return major + "." + minor + (patch > 0 ? "." + patch : "") + (suffix == null ? "" : "-" + suffix.getText());
|
||||
}
|
||||
|
||||
public static @Nullable SemVer parse(String text) {
|
||||
if (text == null || text.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String[] suffixSplit = text.split("-", 2);
|
||||
Suffix suffix = null;
|
||||
if (suffixSplit.length > 1) {
|
||||
suffix = Suffix.of(suffixSplit[1]);
|
||||
}
|
||||
|
||||
String[] parts = suffixSplit[0].split("\\.");
|
||||
int major;
|
||||
try {
|
||||
major = Integer.parseInt(parts[0]);
|
||||
} catch (NumberFormatException e) {
|
||||
return null;
|
||||
}
|
||||
int minor = 0;
|
||||
if (parts.length > 1) {
|
||||
try {
|
||||
minor = Integer.parseInt(parts[1]);
|
||||
} catch (NumberFormatException ignore) {
|
||||
}
|
||||
}
|
||||
int patch = 0;
|
||||
if (parts.length > 2) {
|
||||
try {
|
||||
patch = Integer.parseInt(parts[2]);
|
||||
} catch (NumberFormatException ignore) {
|
||||
}
|
||||
}
|
||||
return new SemVer(major, minor, patch, suffix);
|
||||
}
|
||||
|
||||
public static final class Suffix implements Comparable<Suffix> {
|
||||
|
||||
public static final Suffix SNAPSHOT = new Suffix(0, "SNAPSHOT");
|
||||
public static final Suffix ALPHA = new Suffix(1, "ALPHA");
|
||||
public static final Suffix BETA = new Suffix(2, "BETA");
|
||||
public static final Suffix GAMMA = new Suffix(3, "GAMMA");
|
||||
public static final Suffix DELTA = new Suffix(4, "DELTA");
|
||||
|
||||
private final int weight;
|
||||
private final String text;
|
||||
|
||||
public Suffix(int weight, String text) {
|
||||
this.weight = weight;
|
||||
this.text = text;
|
||||
}
|
||||
|
||||
public int getWeight() {
|
||||
return weight;
|
||||
}
|
||||
|
||||
public String getText() {
|
||||
return text;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int compareTo(Suffix o) {
|
||||
return Integer.compare(this.weight, o.weight);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
Suffix suffix = (Suffix) o;
|
||||
return weight == suffix.weight && text.equals(suffix.text);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(weight, text);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Suffix{weight=" + weight + ", text='" + text + "'}";
|
||||
}
|
||||
|
||||
public static Suffix of(String text) {
|
||||
String uppercaseText = text.toUpperCase(Locale.ROOT);
|
||||
switch (uppercaseText) {
|
||||
case "SNAPSHOT":
|
||||
return SNAPSHOT;
|
||||
case "ALPHA":
|
||||
return ALPHA;
|
||||
case "BETA":
|
||||
return BETA;
|
||||
case "GAMMA":
|
||||
return GAMMA;
|
||||
case "DELTA":
|
||||
return DELTA;
|
||||
default:
|
||||
return new Suffix(-1, uppercaseText);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,86 +11,82 @@ import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.logging.Level;
|
||||
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class Storage {
|
||||
|
||||
private FileConfiguration conf;
|
||||
public final HashMap<String, HashMap<Short, String>> TRANSLATIONS = new HashMap<>();
|
||||
public final Boolean COLOR_IF_ALREADY_COLORED;
|
||||
public final Boolean FORCE_ADD_AMOUNT;
|
||||
public final Boolean LET_MESSAGE_THROUGH;
|
||||
public final Boolean DENY_IF_NO_ITEM;
|
||||
public final Boolean HAND_DISABLED;
|
||||
public final Boolean SHOW_NO_PERM_NORMAL;
|
||||
public final Boolean SHOW_NO_PERM_COMMAND;
|
||||
public final String HAND_NAME;
|
||||
public final String NAME_FORMAT;
|
||||
public final String AMOUNT_FORMAT;
|
||||
public final String NO_PERMISSION_MESSAGE;
|
||||
public final String DENY_MESSAGE;
|
||||
public final String LIMIT_MESSAGE;
|
||||
public final String RELOAD_MESSAGE;
|
||||
public final String COOLDOWN_MESSAGE;
|
||||
public final String SECONDS;
|
||||
public final String MINUTES;
|
||||
public final String HOURS;
|
||||
private final Integer CONFIG_VERSION;
|
||||
public final Long COOLDOWN;
|
||||
public final Integer LIMIT;
|
||||
public final String HAND_NAME, NAME_FORMAT, AMOUNT_FORMAT, COMMAND_FORMAT, MANAGER, PERMISSION_NAME, BUGGED_CLIENT_ACTION;
|
||||
public final String NO_PERMISSION_MESSAGE, DENY_MESSAGE, RELOAD_MESSAGE, COOLDOWN_MESSAGE, LIMIT_MESSAGE;
|
||||
public final String SECONDS, MINUTES, HOURS;
|
||||
public final String JOIN_UPDATE_MESSAGE, JOIN_UPDATE_HOVER;
|
||||
public final List<Command> ALLOWED_PLUGIN_COMMANDS = new ArrayList<>();
|
||||
public final List<String> ALLOWED_DEFAULT_COMMANDS = new ArrayList<>();
|
||||
public final List<String> PLACEHOLDERS;
|
||||
public final List<String> HAND_TOOLTIP;
|
||||
public final List<String> PLACEHOLDERS, HAND_TOOLTIP, BUGGED_CLIENTS_TOOLTIP;
|
||||
public boolean COLOR_IF_ALREADY_COLORED, FORCE_ADD_AMOUNT, LET_MESSAGE_THROUGH, DENY_IF_NO_ITEM, DEBUG,
|
||||
HAND_DISABLED, SHOW_NO_PERM_NORMAL, CHECK_UPDATE, SHOW_NO_PERM_COMMAND, PERMISSION_ENABLED;
|
||||
public int CONFIG_VERSION, LIMIT, COOLDOWN;
|
||||
private FileConfiguration conf;
|
||||
|
||||
public Storage(FileConfiguration cnf) {
|
||||
this.conf = cnf;
|
||||
CONFIG_VERSION = conf.getInt("config-version");
|
||||
CONFIG_VERSION = conf.getInt("config-version", 13);
|
||||
checkConfigVersion();
|
||||
Set<String> keys = conf.getConfigurationSection("Translations").getKeys(false);
|
||||
this.MANAGER = conf.getString("manager", "auto");
|
||||
Set<String> keys = conf.getConfigurationSection("translations").getKeys(false);
|
||||
for (String key : keys) {
|
||||
HashMap<Short, String> entry = new HashMap<>();
|
||||
Set<String> subKeys = conf.getConfigurationSection("Translations.".concat(key)).getKeys(false);
|
||||
Set<String> subKeys = conf.getConfigurationSection("translations.".concat(key)).getKeys(false);
|
||||
for (String subKey : subKeys) {
|
||||
entry.put(Short.parseShort(subKey), color(conf.getString("Translations.".concat(key).concat(".")
|
||||
.concat(subKey))));
|
||||
entry.put(Short.parseShort(subKey),
|
||||
color(conf.getString("translations.".concat(key).concat(".").concat(subKey))));
|
||||
}
|
||||
|
||||
TRANSLATIONS.put(key, entry);
|
||||
}
|
||||
COOLDOWN = conf.getLong("General.cooldown");
|
||||
LIMIT = conf.getInt("General.limit");
|
||||
List<String> added = conf.getStringList("General.placeholders");
|
||||
PLACEHOLDERS = ImmutableList.copyOf(added);
|
||||
NAME_FORMAT = color(conf.getString("General.name-format"));
|
||||
AMOUNT_FORMAT = color(conf.getString("General.amount-format"));
|
||||
COLOR_IF_ALREADY_COLORED = conf.getBoolean("General.color-if-already-colored");
|
||||
LET_MESSAGE_THROUGH = conf.getBoolean("General.let-message-through");
|
||||
FORCE_ADD_AMOUNT = conf.getBoolean("General.force-add-amount");
|
||||
DENY_IF_NO_ITEM = conf.getBoolean("General.deny-if-no-item");
|
||||
HAND_DISABLED = conf.getBoolean("General.hand.disabled");
|
||||
SHOW_NO_PERM_NORMAL = conf.getBoolean("General.show-no-permission-message.normal");
|
||||
SHOW_NO_PERM_COMMAND = conf.getBoolean("General.show-no-permission-message.command");
|
||||
DENY_MESSAGE = color(conf.getString("Messages.deny-message"));
|
||||
HAND_NAME = color(conf.getString("General.hand.name"));
|
||||
LIMIT_MESSAGE = color(conf.getString("Messages.limit-message"));
|
||||
RELOAD_MESSAGE = color(conf.getString("Messages.reload-success"));
|
||||
NO_PERMISSION_MESSAGE = color(conf.getString("Messages.no-permission"));
|
||||
COOLDOWN_MESSAGE = color(conf.getString("Messages.cooldown-message"));
|
||||
SECONDS = color(conf.getString("Messages.seconds"));
|
||||
MINUTES = color(conf.getString("Messages.minutes"));
|
||||
HOURS = color(conf.getString("Messages.hours"));
|
||||
HAND_TOOLTIP = conf.getStringList("General.hand.tooltip");
|
||||
DEBUG = conf.getBoolean("debug", false);
|
||||
PLACEHOLDERS = ImmutableList.copyOf(conf.getStringList("general.placeholders"));
|
||||
NAME_FORMAT = color(conf.getString("general.name-format", "&b&l&o{name} {amount}&r"));
|
||||
AMOUNT_FORMAT = color(conf.getString("general.amount-format", "x{times}"));
|
||||
COMMAND_FORMAT = color(conf.getString("general.command-format", "&6%name%'s item is %item%"));
|
||||
COLOR_IF_ALREADY_COLORED = conf.getBoolean("general.color-if-already-colored", true);
|
||||
LET_MESSAGE_THROUGH = conf.getBoolean("general.let-message-through", true);
|
||||
FORCE_ADD_AMOUNT = conf.getBoolean("general.force-add-amount", true);
|
||||
DENY_IF_NO_ITEM = conf.getBoolean("general.deny-if-no-item", false);
|
||||
LIMIT = conf.getInt("general.limit", 8);
|
||||
COOLDOWN = conf.getInt("general.cooldown", 60);
|
||||
SHOW_NO_PERM_NORMAL = conf.getBoolean("general.show-no-permission-message.normal", true);
|
||||
SHOW_NO_PERM_COMMAND = conf.getBoolean("general.show-no-permission-message.command", false);
|
||||
PERMISSION_ENABLED = conf.getBoolean("general.permission.enabled", false);
|
||||
PERMISSION_NAME = conf.getString("general.permission.name", "chatitem.use");
|
||||
HAND_DISABLED = conf.getBoolean("general.hand.disabled", false);
|
||||
HAND_NAME = color(conf.getString("general.hand.name", "&b&l&o{display-name}&b&l&o's hand"));
|
||||
HAND_TOOLTIP = conf.getStringList("general.hand.tooltip").stream().map(Storage::color).collect(Collectors.toList());
|
||||
BUGGED_CLIENT_ACTION = conf.getString("general.bugged_client.action", "show_both");
|
||||
BUGGED_CLIENTS_TOOLTIP = conf.getStringList("general.bugged_client.tooltip").stream().map(Storage::color).collect(Collectors.toList());
|
||||
CHECK_UPDATE = conf.getBoolean("general.check-update", true);
|
||||
DENY_MESSAGE = color(conf.getString("messages.deny-message", "&c&lYou have no item in hand!"));
|
||||
RELOAD_MESSAGE = color(conf.getString("messages.reload-success", "&b&lSuccessful reload!"));
|
||||
NO_PERMISSION_MESSAGE = color(conf.getString("messages.no-permission",
|
||||
"&c&lI'm sorry, but you are not allowed to use the placeholder in chat!"));
|
||||
COOLDOWN_MESSAGE = color(conf.getString("messages.cooldown-message",
|
||||
"&c&lYou can only use items in chat once a minute! You have {remaining} left!"));
|
||||
JOIN_UPDATE_MESSAGE = color(conf.getString("messages.join-update.message",
|
||||
"&cA new version of ChatItem is available. &aClick here to download."));
|
||||
JOIN_UPDATE_HOVER = color(conf.getString("messages.join-update.hover", "&6Click to go to spigot page !"));
|
||||
LIMIT_MESSAGE = color(conf.getString("messages.limit-message", "&c&lYou can only add 8 item placeholders per message!"));
|
||||
|
||||
SECONDS = color(conf.getString("messages.seconds", " seconds"));
|
||||
MINUTES = color(conf.getString("messages.minutes", " minutes"));
|
||||
HOURS = color(conf.getString("messages.hours", " hours"));
|
||||
colorStringList(HAND_TOOLTIP);
|
||||
final List<String> cmds = conf.getStringList("General.commands");
|
||||
final List<String> cmds = conf.getStringList("general.commands");
|
||||
Bukkit.getScheduler().runTaskLaterAsynchronously(ChatItem.getInstance(), () -> {
|
||||
for(String s : cmds){
|
||||
for (String s : cmds) {
|
||||
Command c = Bukkit.getPluginCommand(s);
|
||||
if(c!=null) {
|
||||
if (c != null) {
|
||||
ALLOWED_PLUGIN_COMMANDS.add(c);
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
ALLOWED_DEFAULT_COMMANDS.add(s);
|
||||
}
|
||||
}
|
||||
@@ -98,29 +94,30 @@ public class Storage {
|
||||
|
||||
}
|
||||
|
||||
private static String color(String s) {
|
||||
return ChatColor.translateAlternateColorCodes('&', s);
|
||||
public static String color(String s) {
|
||||
return s == null || s.isEmpty() ? s : ChatColor.translateAlternateColorCodes('&', s);
|
||||
}
|
||||
|
||||
private static void colorStringList(List<String> input) {
|
||||
for (int i = 0; i < input.size(); ++i) {
|
||||
input.set(i, color(input.get(i)));
|
||||
}
|
||||
}
|
||||
|
||||
private void checkConfigVersion() {
|
||||
int latestVersion = ChatItem.CFG_VER;
|
||||
if (latestVersion != CONFIG_VERSION) {
|
||||
Bukkit.getLogger().log(Level.WARNING, ChatColor.RED + "ChatItem detected an older or invalid configuration file. Replacing it with the default config...");
|
||||
ChatItem pl = ChatItem.getInstance();
|
||||
pl.getLogger().warning(ChatColor.RED
|
||||
+ "ChatItem detected an older or invalid configuration file. Replacing it with the default config...");
|
||||
performOverwrite();
|
||||
conf = ChatItem.getInstance().getConfig();
|
||||
Bukkit.getLogger().log(Level.WARNING, ChatColor.RED + "Replacement complete!");
|
||||
conf = pl.getConfig();
|
||||
pl.getLogger().warning(ChatColor.RED + "Replacement complete!");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private void performOverwrite() {
|
||||
ChatItem.getInstance().saveResource("config.yml", true);
|
||||
}
|
||||
|
||||
private static void colorStringList(List<String> input){
|
||||
for(int i=0; i<input.size(); ++i){
|
||||
input.set(i, color(input.get(i)));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,66 +1,177 @@
|
||||
package me.dadus33.chatitem.utils;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.enchantments.Enchantment;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.TreeMap;
|
||||
|
||||
public class Utils {
|
||||
|
||||
public static final String VERSION = Bukkit.getServer().getClass().getPackage().getName().replace(".", ",")
|
||||
.split(",")[3];
|
||||
private final static TreeMap<Integer, String> ROMAN_KEYS = new TreeMap<>();
|
||||
private final static HashMap<String, String> ENCHANTS_NAMES = new HashMap<>();
|
||||
|
||||
public static String coloredMessage(String msg) {
|
||||
return ChatColor.translateAlternateColorCodes('&', msg);
|
||||
}
|
||||
static {
|
||||
ROMAN_KEYS.put(1000, "M");
|
||||
ROMAN_KEYS.put(900, "CM");
|
||||
ROMAN_KEYS.put(500, "D");
|
||||
ROMAN_KEYS.put(400, "CD");
|
||||
ROMAN_KEYS.put(100, "C");
|
||||
ROMAN_KEYS.put(90, "XC");
|
||||
ROMAN_KEYS.put(50, "L");
|
||||
ROMAN_KEYS.put(40, "XL");
|
||||
ROMAN_KEYS.put(10, "X");
|
||||
ROMAN_KEYS.put(9, "IX");
|
||||
ROMAN_KEYS.put(5, "V");
|
||||
ROMAN_KEYS.put(4, "IV");
|
||||
ROMAN_KEYS.put(1, "I");
|
||||
|
||||
public static List<String> coloredMessage(String... messages) {
|
||||
List<String> ret = new ArrayList<>();
|
||||
for (String message : messages) {
|
||||
ret.add(coloredMessage(message));
|
||||
}
|
||||
return ret;
|
||||
ENCHANTS_NAMES.put("ARROW_DAMAGE", "Power");
|
||||
ENCHANTS_NAMES.put("ARROW_FIRE", "Flame");
|
||||
ENCHANTS_NAMES.put("ARROW_INFINITE", "Infinity");
|
||||
ENCHANTS_NAMES.put("ARROW_KNOCKBACK", "Punch");
|
||||
ENCHANTS_NAMES.put("BINDING_CURSE", "Curse of Binding");
|
||||
ENCHANTS_NAMES.put("DAMAGE_ALL", "Sharpness");
|
||||
ENCHANTS_NAMES.put("DAMAGE_ARTHROPODS", "Bane of Arthropods");
|
||||
ENCHANTS_NAMES.put("DAMAGE_UNDEAD", "Smite");
|
||||
ENCHANTS_NAMES.put("DEPTH_STRIDER", "Depth Strider");
|
||||
ENCHANTS_NAMES.put("DIG_SPEED", "Efficiency");
|
||||
ENCHANTS_NAMES.put("DURABILITY", "Unbreaking");
|
||||
ENCHANTS_NAMES.put("FIRE_ASPECT", "Fire Aspect");
|
||||
ENCHANTS_NAMES.put("FROST_WALKER", "Frost Walker");
|
||||
ENCHANTS_NAMES.put("KNOCKBACK", "Knockback");
|
||||
ENCHANTS_NAMES.put("LOOT_BONUS_BLOCKS", "Fortune");
|
||||
ENCHANTS_NAMES.put("LOOT_BONUS_MOBS", "Looting");
|
||||
ENCHANTS_NAMES.put("LUCK", "Luck of the Sea");
|
||||
ENCHANTS_NAMES.put("LURE", "Lure");
|
||||
ENCHANTS_NAMES.put("MENDING", "Mending");
|
||||
ENCHANTS_NAMES.put("OXYGEN", "Respiration");
|
||||
ENCHANTS_NAMES.put("PROTECTION_ENVIRONMENTAL ", "Protection");
|
||||
ENCHANTS_NAMES.put("PROTECTION_EXPLOSIONS", "Blast Protection");
|
||||
ENCHANTS_NAMES.put("PROTECTION_FALL", "Feather Falling");
|
||||
ENCHANTS_NAMES.put("PROTECTION_FIRE", "Fire Protection");
|
||||
ENCHANTS_NAMES.put("PROTECTION_PROJECTILE", "Projectile Protection");
|
||||
ENCHANTS_NAMES.put("SILK_TOUCH", "Silk Touch");
|
||||
ENCHANTS_NAMES.put("SWEEPING_EDGE", "Sweeping Edge");
|
||||
ENCHANTS_NAMES.put("THORNS", "Thorns");
|
||||
ENCHANTS_NAMES.put("VANISHING_CURSE", "Cure of Vanishing");
|
||||
ENCHANTS_NAMES.put("WATER_WORKER", "Aqua Affinity");
|
||||
}
|
||||
|
||||
public static List<Player> getOnlinePlayers() {
|
||||
List<Player> list = new ArrayList<>();
|
||||
try {
|
||||
Class<?> mcServer = PacketUtils.getNmsClass("MinecraftServer", "server.");
|
||||
Object server = mcServer.getMethod("getServer").invoke(mcServer);
|
||||
Object craftServer = server.getClass().getField("server").get(server);
|
||||
Object getted = craftServer.getClass().getMethod("getOnlinePlayers").invoke(craftServer);
|
||||
if (getted instanceof Player[])
|
||||
for (Player obj : (Player[]) getted)
|
||||
list.add(obj);
|
||||
else if (getted instanceof List)
|
||||
for (Object obj : (List<?>) getted)
|
||||
list.add((Player) obj);
|
||||
else
|
||||
System.out.println("Unknow getOnlinePlayers");
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return list;
|
||||
return new ArrayList<>(Bukkit.getOnlinePlayers());
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current player ping
|
||||
*
|
||||
* @param p the player
|
||||
* @return the player ping
|
||||
*/
|
||||
public static int getPing(Player p) {
|
||||
public static String toRoman(int number) {
|
||||
int l = ROMAN_KEYS.floorKey(number);
|
||||
if (number == l) {
|
||||
return ROMAN_KEYS.get(number);
|
||||
}
|
||||
return ROMAN_KEYS.get(l) + toRoman(number - l);
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
public static String getEnchantName(Enchantment enchant) {
|
||||
String name = ENCHANTS_NAMES.get(enchant.getName());
|
||||
if (name == null) {
|
||||
|
||||
ChatItem.getInstance().getLogger()
|
||||
.warning("Unknown enchant " + enchant.getName() + ". Please report this to Elikill58.");
|
||||
}
|
||||
return name;
|
||||
}
|
||||
|
||||
public static String getFromURL(String urlName) {
|
||||
ChatItem pl = ChatItem.getInstance();
|
||||
try {
|
||||
Object entityPlayer = PacketUtils.getEntityPlayer(p);
|
||||
if(ProtocolVersion.getServerVersion().isNewerOrEquals(ProtocolVersion.V1_17))
|
||||
return entityPlayer.getClass().getField("e").getInt(entityPlayer);
|
||||
else
|
||||
return entityPlayer.getClass().getField("ping").getInt(entityPlayer);
|
||||
} catch (Exception e) {
|
||||
URL url = new URL(urlName);
|
||||
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
|
||||
connection.setUseCaches(true);
|
||||
connection.setConnectTimeout(5000);
|
||||
connection.setReadTimeout(5000);
|
||||
connection.setRequestProperty("User-Agent", "ChatItem " + pl.getDescription().getVersion());
|
||||
connection.setDoOutput(true);
|
||||
connection.setRequestMethod("GET");
|
||||
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
|
||||
StringBuilder content = new StringBuilder();
|
||||
String input;
|
||||
while ((input = br.readLine()) != null)
|
||||
content.append(input);
|
||||
br.close();
|
||||
return content.toString();
|
||||
} catch (SocketTimeoutException e) {
|
||||
pl.getLogger().info("Failed to access to " + urlName + " (Reason: timed out).");
|
||||
} catch (UnknownHostException | MalformedURLException e) {
|
||||
pl.getLogger().info("Could not use the internet connection to check for update or send stats");
|
||||
} catch (ConnectException e) {
|
||||
pl.getLogger().warning("Cannot connect to " + urlName + " (Reason: " + e.getMessage() + ").");
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return 0;
|
||||
return null;
|
||||
}
|
||||
|
||||
public static int indexOf(CharSequence s, CharSequence searched, int i) {
|
||||
return s.toString().indexOf(searched.toString(), i);
|
||||
}
|
||||
|
||||
public static boolean isEmpty(CharSequence s) {
|
||||
return (s == null || s.length() == 0);
|
||||
}
|
||||
|
||||
public static int countMatches(CharSequence str, CharSequence searched) {
|
||||
if (isEmpty(str) || isEmpty(searched))
|
||||
return 0;
|
||||
byte b = 0;
|
||||
int i = 0;
|
||||
while ((i = indexOf(str, searched, i)) != -1) {
|
||||
b++;
|
||||
i += searched.length();
|
||||
}
|
||||
return b;
|
||||
}
|
||||
|
||||
public static boolean isInteger(String s) {
|
||||
try {
|
||||
Integer.parseInt(s);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean isByte(String s) {
|
||||
try {
|
||||
Byte.parseByte(s);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean isShort(String s) {
|
||||
try {
|
||||
Short.parseShort(s);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean isLong(String s) {
|
||||
try {
|
||||
Long.parseLong(s);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package me.dadus33.chatitem.utils;
|
||||
|
||||
import java.net.InetSocketAddress;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
|
||||
public enum Version {
|
||||
|
||||
// http://wiki.vg/Protocol_version_numbers
|
||||
V1_7(0, 5, 0),
|
||||
V1_8(6, 47, 1),
|
||||
V1_9(49, 110, 2), // 1.9.X - Starts with 49 as 48 was an april fools update
|
||||
V1_10(201, 210, 3), // 1.10.X - Starts with 201 because why not.
|
||||
V1_11(301, 316, 4),
|
||||
V1_12(317, 340, 5),
|
||||
V1_13(341, 440, 6),
|
||||
V1_14(100, 441, 500),
|
||||
V1_15(100, 550, 578),
|
||||
V1_16(100, 700, 754),
|
||||
V1_17(100, 755, 756),
|
||||
V1_18(100, 757, 758),
|
||||
V1_19(100, 759, 1000),
|
||||
HIGHER(Integer.MAX_VALUE, -1, Integer.MAX_VALUE);
|
||||
|
||||
// Latest version should always have the upper limit set to Integer.MAX_VALUE so
|
||||
// I don't have to update the plugin for every minor protocol change
|
||||
|
||||
public final int MIN_VER;
|
||||
public final int MAX_VER;
|
||||
public final int index; // Represents how new the version is (0 - extremely old)
|
||||
|
||||
private static final Version SERVER_VERSION;
|
||||
public static final String BUKKIT_VERSION;
|
||||
|
||||
static {
|
||||
BUKKIT_VERSION = Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3];
|
||||
SERVER_VERSION = getVersionByName(BUKKIT_VERSION);
|
||||
}
|
||||
|
||||
Version(int min, int max, int index) {
|
||||
this.MIN_VER = min;
|
||||
this.MAX_VER = max;
|
||||
this.index = index;
|
||||
}
|
||||
|
||||
public boolean isNewerOrEquals(Version other) {
|
||||
return index >= other.index;
|
||||
}
|
||||
|
||||
public boolean isNewerThan(Version other) {
|
||||
return index > other.index;
|
||||
}
|
||||
|
||||
public static Version getVersionByName(String name) {
|
||||
for (Version v : Version.values())
|
||||
if (name.toLowerCase().startsWith(v.name().toLowerCase()))
|
||||
return v;
|
||||
return HIGHER;
|
||||
}
|
||||
|
||||
public static Version getVersion(int protocolVersion) {
|
||||
for (Version ver : Version.values()) {
|
||||
if (protocolVersion >= ver.MIN_VER && protocolVersion <= ver.MAX_VER) {
|
||||
return ver;
|
||||
}
|
||||
}
|
||||
return HIGHER;
|
||||
}
|
||||
|
||||
public static Version getVersion(int protocolVersion, Version def) {
|
||||
for (Version ver : Version.values()) {
|
||||
if (protocolVersion >= ver.MIN_VER && protocolVersion <= ver.MAX_VER) {
|
||||
return ver;
|
||||
}
|
||||
}
|
||||
ChatItem.debug("Failed to find version for protocol " + protocolVersion);
|
||||
return def;
|
||||
}
|
||||
|
||||
public static Version getVersion() {
|
||||
return SERVER_VERSION;
|
||||
}
|
||||
|
||||
public static String stringifyAdress(InetSocketAddress address) {
|
||||
String port = String.valueOf(address.getPort());
|
||||
String ip = address.getAddress().getHostAddress();
|
||||
return ip + ":" + port;
|
||||
}
|
||||
}
|
||||
+162
-53
@@ -1,53 +1,73 @@
|
||||
#Config for ChatItem
|
||||
#For info visit
|
||||
#https://www.spigotmc.org/resources/chatitem.19064/
|
||||
|
||||
#Version info, DON'T TOUCH
|
||||
config-version: 12
|
||||
# Config for ChatItem
|
||||
# For info visit
|
||||
# Spigotmc: https://www.spigotmc.org/resources/chatitem.19064/
|
||||
# Discord: https://discord.gg/ttA5CjMhk7
|
||||
|
||||
# Version info, DON'T TOUCH
|
||||
config-version: 13
|
||||
|
||||
# By default, it's in "both" mode.
|
||||
#
|
||||
# Available mode :
|
||||
# - "both" : Prevent chat editing with multiple plugins by using all ways possible to edit the chat.
|
||||
# - "auto" : Choose automatically between all available according to actual plugins.
|
||||
# - "packet" : The working system for 1.4's ChatItem version (and older)
|
||||
# It was working with lot of others chat plugin, specially those who made hover text.
|
||||
# - "chat" : New system which works without other chat plugin, which is simpler and with lower
|
||||
# amount of possible issues.
|
||||
# You can replace 'both' by another mode that should correspond to what you want.
|
||||
# If you don't know which one use, come on discord (link at begin of config or in spigotmc)
|
||||
manager: "both"
|
||||
|
||||
#General configuration
|
||||
General:
|
||||
#The placeholders you want to use for the item. You can add as many as you want.
|
||||
general:
|
||||
# The placeholders to display an item in chat.
|
||||
placeholders:
|
||||
- "[i]"
|
||||
- "{item}"
|
||||
# How will the item be displayed in chat? {name} represents the display name of
|
||||
# the item, or material name (ex. Diamond Sword) if it doesn't have a customized
|
||||
# display name nor any available translation, and {amount} will be replaced by
|
||||
# the amount-format configured bellow.
|
||||
# You can use color codes.
|
||||
# The format of the item placeholders.
|
||||
name-format: "&b&l&o{name} {amount}&r"
|
||||
# The amount format that will replace the {amount} placeholder in the 'name-format'
|
||||
# field above. The {times} placeholder represents the number of times the item is
|
||||
# presented in the itemstack, in other words, the actual item amount in the stack
|
||||
# the player holds. You can use color codes too.
|
||||
# The format of the {amount} placeholder.
|
||||
# {times} correspond to amount of item
|
||||
amount-format: "x{times}"
|
||||
# Should we apply the colors/formats set in the name format and/or amount format
|
||||
# settings on the name of the item even though it already has a color of it's own,
|
||||
# like a custom display name? Setting this to true will always disregard any color
|
||||
# or or message
|
||||
# Should we use the translated item name or the custom name of an item
|
||||
color-if-already-colored: true
|
||||
# Should we add the item amount even if there's only one item in the stack?
|
||||
# Should we always show the amount, even if it's just one
|
||||
force-add-amount: true
|
||||
# Should we let the message through, as-is (with the placeholder not replaced)
|
||||
# if the user doesn't have permission or if the user is on cooldown?
|
||||
let-message-through: true
|
||||
# Should we cancel the user message if the item in his (main) hand is air or null?
|
||||
# (No item in hand, that is)
|
||||
# Should we allow users to show their hands off
|
||||
deny-if-no-item: false
|
||||
# If the above (deny-if-no-item) is set to false, what should the placeholder be replaced with?
|
||||
# Bellow you can configure that behaviour.
|
||||
hand:
|
||||
# Should the empty hand formatting be totally disabled? That will just leave the placeholder
|
||||
# untouched in the final message
|
||||
# Should we completely disable users being able to show their hands off
|
||||
disabled: false
|
||||
# The string the placeholder shall be replaced with. You can use {name} as a placeholder for
|
||||
# the player's name and {display-name} as a placeholder for the player's display (custom) name.
|
||||
# The name of the hand chat message.
|
||||
name: "&b&l&o{display-name}&b&l&o's hand"
|
||||
# The text to be displayed whe users hove their cursor above the name
|
||||
# The lore of the hand chat message.
|
||||
tooltip:
|
||||
- "&7Nothing to see here"
|
||||
- "&7Just the empty hand of {display-name}."
|
||||
# Manage what is showed for bugged client.
|
||||
# Specially lunar client with old version (1.7)
|
||||
bugged_client:
|
||||
# You can try to show the most informations as possible:
|
||||
# item name & lore. You will not see specific item meta-data
|
||||
# Or just show the bugged tooltip.
|
||||
#
|
||||
# Action available:
|
||||
# nothing: no hover
|
||||
# item: only try to get values from item
|
||||
# tooltip: only show tooltip
|
||||
# show_both: show item & tooltip below
|
||||
action: "show_both"
|
||||
tooltip:
|
||||
- "&7Failed to parse item for your client"
|
||||
|
||||
# Format used with using /chatitem show
|
||||
command-format: "&6%name%'s item is %item%"
|
||||
|
||||
# Here you can choose which commands will the plugin attempt to parse. Console commands will all be ignored,
|
||||
# however player commands will be taken into consideration. To add a command, simply add an element to the list
|
||||
@@ -63,40 +83,134 @@ General:
|
||||
show-no-permission-message:
|
||||
normal: true
|
||||
command: false
|
||||
# Manage permission to use placeholders
|
||||
permission:
|
||||
enabled: false
|
||||
name: "chatitem.use"
|
||||
# Here you can set the limit on how many placeholders a user is allowed to use inside a message.
|
||||
# Allowing too many placeholders can result in client crashes.
|
||||
limit: 8
|
||||
# The cooldown, in seconds, between allowing players to send messages with items. Setting this to 0
|
||||
# will remove the cooldown entirely.
|
||||
cooldown: 60
|
||||
|
||||
|
||||
# Check if the plugin have update
|
||||
check-update: true
|
||||
|
||||
|
||||
# Messages section. You can disable any of them by simply leaving them empty, like this: ""
|
||||
Messages:
|
||||
# The message users will get upon attempting to use the placeholder without any item in hand.
|
||||
messages:
|
||||
# The message sent if showing off hands is disabled and the user isn't holding an item.
|
||||
# Only works if 'General.deny-if-no-item' is set to true!
|
||||
deny-message: "&c&lYou have no item in hand!"
|
||||
# The message you will get after reloading the plugin using /cireload.
|
||||
# The message sent after the configuration file is successfully reloaded.
|
||||
reload-success: "&b&lSuccessful reload!"
|
||||
# The message a player will get when attempting to send a message with more placeholders then the allowed limit.
|
||||
limit-message: "&c&lYou can only add 8 item placeholders per message!"
|
||||
# The message to display players when they can't display items in chat due to the cooldown
|
||||
# The message sent if the player is on cooldown from sending a placeholder.
|
||||
cooldown-message: "&c&lYou can only use items in chat once a minute! You have {remaining} left!"
|
||||
# The no permission message to be showed to players who don't have the required permission to use the placeholder
|
||||
# The message sent if the no permission messages are enabled and the user doesn't have permission to send an item placeholder.
|
||||
no-permission: "&c&lI'm sorry, but you are not allowed to use the placeholder in chat!"
|
||||
# The message sent if the player uses more placeholders than configured in one message.
|
||||
limit-message: "&c&lYou can only add 8 item placeholders per message!"
|
||||
# All message about the update of the plugin
|
||||
join-update:
|
||||
message: "&cA new version of ChatItem is available. &aClick here to download."
|
||||
hover: "&6Click to go to spigot page !"
|
||||
# For all commands ran by console by reserved to player
|
||||
only-players: "&cOnly players can run this command"
|
||||
# All messages for the /chatitem command
|
||||
chatitem-cmd:
|
||||
help:
|
||||
- "&6/chatitem admin : &7Manage some options"
|
||||
- "&6/chatitem links : &7See all links which are usefull"
|
||||
links:
|
||||
begin: "&aAll usefull links: "
|
||||
list:
|
||||
1:
|
||||
message: "\n&7- &eSpigotmc updates"
|
||||
hover: "&6Click to go to spigot page !"
|
||||
link: "https://www.spigotmc.org/resources/19064/"
|
||||
2:
|
||||
message: " "
|
||||
3:
|
||||
message: "&7(Original author: &aDadus33"
|
||||
hover: "&6See &aDadus33&6's profile"
|
||||
link: "https://www.spigotmc.org/members/10224/"
|
||||
4:
|
||||
message: "&7, "
|
||||
5:
|
||||
message: "&7Maintainer: &aElikill58&7)"
|
||||
hover: "&6See &aElikill58&6's profile"
|
||||
link: "https://www.spigotmc.org/members/310762/"
|
||||
6:
|
||||
message: "\n&7- &6Support on discord"
|
||||
hover: "&6Click to open discord !"
|
||||
link: "https://discord.gg/ttA5CjMhk7"
|
||||
# All messages in admin inventory
|
||||
admin-inv:
|
||||
name: "ChatItem - Admin"
|
||||
close: "Close"
|
||||
# Generic lores for options items
|
||||
amount-lore:
|
||||
- "&aLeft-click: &6+1"
|
||||
- "&aRight-click: &6-1"
|
||||
bool-lore:
|
||||
- "&7Click to enable/disable"
|
||||
# Name of options items
|
||||
color-if-already-colored: "&6Color if already colored: %state%"
|
||||
deny-no-item: "&6Deny without item: %state%"
|
||||
hand-disabled: "&6Hand disabled: %state%"
|
||||
limit-per-message: "&6Limit per message: &a%state%"
|
||||
cooldown: "&6Cooldown: &a%state%"
|
||||
debug: "&6Debug: &a%state%"
|
||||
# Change name and lore of all managers
|
||||
manager:
|
||||
both:
|
||||
name: "&6Use both manager&7: &aPacket & Chat"
|
||||
lore:
|
||||
- "&aTry both manager. Very usefull when you have lot of plugins"
|
||||
- "&eIt enable to use ChatItem for all type of messages"
|
||||
- ""
|
||||
- "&7Since ChatItem v2.1"
|
||||
auto:
|
||||
name: "&6Choose automatically"
|
||||
lore:
|
||||
- "&aChoose automatically between managers available"
|
||||
- "&aaccording to actuals plugins."
|
||||
- "&eThis is better when you are not using own plugin."
|
||||
- ""
|
||||
- "&7Since ChatItem v2.1"
|
||||
packet:
|
||||
name: "&6Intercept packets"
|
||||
lore:
|
||||
- "&aChange message sent directly by intercepting packet"
|
||||
- "&aCan use &6ProtocolLib &aif present."
|
||||
- "&cCan have error with &e/cir &c!"
|
||||
- ""
|
||||
- "&7Originally made until ChatItem v1.4"
|
||||
chat:
|
||||
name: "&6Change basic message"
|
||||
lore:
|
||||
- "&aVery quick and usefull for server without plugin message !"
|
||||
- "&aIt enable to use ChatItem without packet reading."
|
||||
- "&eIt's more optimized than others manager"
|
||||
- ""
|
||||
- "&7Since ChatItem v2.0"
|
||||
# The item that show the actual manager
|
||||
actual:
|
||||
name: '&6Actual manager: %manager%'
|
||||
lore: []
|
||||
# All the fields bellow shold be translated in your own language. Those will be used in the {remaining} format of the cooldown message.
|
||||
# You should leave a space as a PREFIX as we will add a number in front of them
|
||||
seconds: " seconds"
|
||||
minutes: " minutes"
|
||||
hours: " hours"
|
||||
|
||||
|
||||
enabled: "&aEnabled"
|
||||
disabled: "&cDisabled"
|
||||
|
||||
|
||||
# Translations
|
||||
# Below you can find a set of default values for all items in Minecraft 1.8.
|
||||
Translations:
|
||||
# This is used to display prettier names in chat for items/blocks. Modifying this is usually unnecessary unless you know what you're doing.
|
||||
translations:
|
||||
## Blocks ##
|
||||
STONE:
|
||||
1: "Granite"
|
||||
STONE:
|
||||
0: "Stone"
|
||||
1: "Granite"
|
||||
@@ -689,8 +803,8 @@ Translations:
|
||||
STONE_PICKAXE:
|
||||
0: "Stone Pickaxe"
|
||||
STONE_AXE:
|
||||
0: "Stone Axe
|
||||
DIAMOND_SWORD: "
|
||||
0: "Stone Axe"
|
||||
DIAMOND_SWORD:
|
||||
0: "Diamond Sword"
|
||||
DIAMOND_SPADE:
|
||||
0: "Diamond Shovel"
|
||||
@@ -842,8 +956,6 @@ Translations:
|
||||
1: "Raw Salmon"
|
||||
2: "Clownfish"
|
||||
3: "Pufferfish"
|
||||
COOKED_FISH:
|
||||
0: "Cooked Fish"
|
||||
COOKED_FISH:
|
||||
0: "Cooked Salmon"
|
||||
INK_SACK:
|
||||
@@ -975,9 +1087,6 @@ Translations:
|
||||
16394: "Splash Potion of Slowness"
|
||||
16426: "Splash Potion of Slowness II"
|
||||
16458: "Extended Splash Potion of Slowness"
|
||||
16395: "Splash Potion of Leaping"
|
||||
16427: "Splash Potion of Leaping II"
|
||||
16459: "Extended Splash Potion of Leaping"
|
||||
16396: "Splash Potion of Harming"
|
||||
16428: "Splash Potion of Harming II"
|
||||
16460: "Extended Splash Potion of Harming"
|
||||
@@ -1058,8 +1167,8 @@ Translations:
|
||||
POISONOUS_POTATO:
|
||||
0: "Poisonous Potato"
|
||||
EMPTY_MAP:
|
||||
0: "Empty Map
|
||||
GOLDEN_CARROT: "
|
||||
0: "Empty Map"
|
||||
GOLDEN_CARROT:
|
||||
0: "Golden Carrot"
|
||||
SKULL_ITEM:
|
||||
0: "Skeleton Head"
|
||||
|
||||
@@ -2,7 +2,7 @@ name: ChatItem
|
||||
main: me.dadus33.chatitem.ChatItem
|
||||
version: ${project.version}
|
||||
|
||||
softdepend: [ViaVersion, ProtocolSupport, ProtocolLib]
|
||||
softdepend: [ViaVersion, ProtocolSupport, ProtocolLib, LangUtils, HexNicks, EcoEnchants, DiscordSRV]
|
||||
authors: [dadus33, WOLFI3654, Elikill58]
|
||||
api-version: 1.13
|
||||
|
||||
@@ -11,6 +11,9 @@ commands:
|
||||
description: Reload the ChatItem config.
|
||||
aliases: [chatitemreload, citemreload, cir]
|
||||
permission: chatitem.reload
|
||||
chatitem:
|
||||
description: See and edit ChatItem informations
|
||||
permission: chatitem.reload
|
||||
permissions:
|
||||
chatitem.reload:
|
||||
description: Allows reloading the config
|
||||
|
||||
Reference in new issue
Block a user