Compare commits
176
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b5f5353596 | ||
|
|
3c2d092200 | ||
|
|
b1dac86e96 | ||
|
|
4b0c8ef6ff | ||
|
|
02e53a9dd6 | ||
|
|
37f6051794 | ||
|
|
6280cb211b | ||
|
|
6e7554e0a4 | ||
|
|
6435ea0dad | ||
|
|
4e7b14e618 | ||
|
|
c9ea8061c8 | ||
|
|
4b966f056e | ||
|
|
3a2d0ee44d | ||
|
|
5ee9cca3d7 | ||
|
|
e21f236a09 | ||
|
|
554dd8ad39 | ||
|
|
b7a60f1352 | ||
|
|
b8e5e213ae | ||
|
|
08101a8d18 | ||
|
|
4ccb543869 | ||
|
|
153667135b | ||
|
|
00ca8ac11b | ||
|
|
44867e86d8 | ||
|
|
36148b5969 | ||
|
|
103ef2a4f2 | ||
|
|
40f67cc41f | ||
|
|
df555f7151 | ||
|
|
c76c35974c | ||
|
|
81f9711019 | ||
|
|
4edccde81c | ||
|
|
eac6d1c68a | ||
|
|
1914174e42 | ||
|
|
4a7f37451a | ||
|
|
4d90a80788 | ||
|
|
3713ad41af | ||
|
|
b8ba6eac69 | ||
|
|
25f8b585b0 | ||
|
|
746b3b58a0 | ||
|
|
89f61e0178 | ||
|
|
9d7de56889 | ||
|
|
5fb210e841 | ||
|
|
0a9af0d430 | ||
|
|
37681d8b27 | ||
|
|
79e03e97bd | ||
|
|
db08be3fa8 | ||
|
|
4133f30701 | ||
|
|
08434a5df2 | ||
|
|
ae825569cf | ||
|
|
1a4f95cd80 | ||
|
|
4edc061969 | ||
|
|
e508790d9f | ||
|
|
c26259f5e7 | ||
|
|
62bf8b07fb | ||
|
|
bd93d3e610 | ||
|
|
c0a37084ce | ||
|
|
0f42e22da9 | ||
|
|
5e10bb4450 | ||
|
|
b88a1ca83e | ||
|
|
05ae520cf1 | ||
|
|
76123c895d | ||
|
|
4284497bf5 | ||
|
|
62a7b10142 | ||
|
|
cd341109de | ||
|
|
68fb201855 | ||
|
|
baa4eab53f | ||
|
|
20c5fc3e45 | ||
|
|
818cd535bb | ||
|
|
1107b7fe90 | ||
|
|
bed3a87c09 | ||
|
|
499d0eb93c | ||
|
|
913d04b96a | ||
|
|
497c317d3f | ||
|
|
c9d8d52406 | ||
|
|
38f8e47b92 | ||
|
|
6fb80712be | ||
|
|
00ef83bd67 | ||
|
|
1615bdf739 | ||
|
|
09854352a1 | ||
|
|
c6585bb94a | ||
|
|
1e359523fa | ||
|
|
885f6b9d7a | ||
|
|
f2a49e2f3a | ||
|
|
7c8b61c6eb | ||
|
|
f502cfa548 | ||
|
|
fcef1245d6 | ||
|
|
b6c4ad0170 | ||
|
|
a97710b2c4 | ||
|
|
64642cdc58 | ||
|
|
9ac6e7abbc | ||
|
|
fddf389169 | ||
|
|
3006a7857c | ||
|
|
e370723a82 | ||
|
|
2a496b9a1a | ||
|
|
655304bd52 | ||
|
|
0081c616d3 | ||
|
|
824cf62e4c | ||
|
|
8f5c90557f | ||
|
|
7e6cb9910c | ||
|
|
0e6f35804d | ||
|
|
fbcfbceaa4 | ||
|
|
4a6d46d1da | ||
|
|
8779653211 | ||
|
|
c4c511315a | ||
|
|
bcc0bbdd2a | ||
|
|
ffe1bb8b44 | ||
|
|
64cdccc2d1 | ||
|
|
920a055f02 | ||
|
|
4d524244d6 | ||
|
|
429e4a597c | ||
|
|
5a310e3f60 | ||
|
|
58c5f4607f | ||
|
|
b436c73f47 | ||
|
|
806ceea250 | ||
|
|
9a4ef0fe5b | ||
|
|
241f80ca3c | ||
|
|
710bbf3163 | ||
|
|
4ee561c18f | ||
|
|
17754f2dfe | ||
|
|
6a683508d4 | ||
|
|
bcc8ac08f2 | ||
|
|
429a664e81 | ||
|
|
49dadb897a | ||
|
|
3cf54d39a1 | ||
|
|
187d1212f5 | ||
|
|
d3776e161f | ||
|
|
010ea46ff2 | ||
|
|
db8119affd | ||
|
|
484a6b46a0 | ||
|
|
a48f259b99 | ||
|
|
2b9ae264fd | ||
|
|
207b066ecb | ||
|
|
587432269a | ||
|
|
a080e18571 | ||
|
|
7b758882be | ||
|
|
beafc6a635 | ||
|
|
0da4039b70 | ||
|
|
b89e18b149 | ||
|
|
07243fbf91 | ||
|
|
4b90aaa070 | ||
|
|
9d74eb067a | ||
|
|
c51f62a9fb | ||
|
|
badddd29ed | ||
|
|
d188289e84 | ||
|
|
1b9fd3bf90 | ||
|
|
0d98b4408e | ||
|
|
769abab65c | ||
|
|
78311f60b4 | ||
|
|
bd31b5791c | ||
|
|
cd5cfa47ec | ||
|
|
d31bdbef68 | ||
|
|
a82b50b1d0 | ||
|
|
912bbcf371 | ||
|
|
af5d63ea93 | ||
|
|
69681553c8 | ||
|
|
3f6856ddab | ||
|
|
9d55208563 | ||
|
|
2b8ce53553 | ||
|
|
6b157320c4 | ||
|
|
ba3da92061 | ||
|
|
dc6ce9c260 | ||
|
|
cf45b8e436 | ||
|
|
fc8966dab0 | ||
|
|
c537e72a27 | ||
|
|
dee359a37d | ||
|
|
34f67345e2 | ||
|
|
d937f5d89e | ||
|
|
856a5f182f | ||
|
|
6653b9c057 | ||
|
|
0b60780fe2 | ||
|
|
a16b2ea462 | ||
|
|
05771d975c | ||
|
|
417b63e86d | ||
|
|
01da231510 | ||
|
|
5e2559c1ee | ||
|
|
0bb784f7f2 | ||
|
|
eef3bf80c8 |
No files matched your search
@@ -10,14 +10,14 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
name: Checkout repo
|
||||
|
||||
- name: Set up JDK 17 (LTS)
|
||||
uses: actions/setup-java@v3
|
||||
- name: Set up JDK 21
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
java-version: '17'
|
||||
distribution: 'adopt'
|
||||
java-version: '21'
|
||||
distribution: 'temurin'
|
||||
cache: maven
|
||||
|
||||
- name: Build with Maven
|
||||
@@ -27,4 +27,4 @@ jobs:
|
||||
name: Upload Artifact
|
||||
with:
|
||||
name: ChatItem.jar
|
||||
path: target/ChatItem-*.jar
|
||||
path: target/ChatItem-*.jar
|
||||
@@ -10,20 +10,20 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
name: Checkout repo
|
||||
|
||||
- name: Set up JDK 17 (LTS)
|
||||
uses: actions/setup-java@v3
|
||||
- name: Set up JDK 21
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
java-version: '17'
|
||||
distribution: 'adopt'
|
||||
java-version: '21'
|
||||
distribution: 'temurin'
|
||||
cache: maven
|
||||
|
||||
- name: Build with Maven
|
||||
run: mvn install --file pom.xml
|
||||
|
||||
- uses: actions/upload-artifact@v3
|
||||
- uses: actions/upload-artifact@v4
|
||||
name: Upload Artifact
|
||||
with:
|
||||
name: ChatItem.jar
|
||||
|
||||
@@ -8,11 +8,11 @@ You can:
|
||||
- [  ](https://discord.gg/yng5PPf62h)
|
||||
- [Check the wiki](https://github.com/dadus33-plugins/ChatItem/wiki)
|
||||
|
||||
# Item not well showed in chat
|
||||
# Item doesn't show up well in chat
|
||||
|
||||
You can try to do `/chatitem admin` then select different paper item. It will change how the plugin try to add item in chat.
|
||||
You can do `/chatitem admin` then select one of the other paper items in the menu. It will change how the plugin tries to display items in chat.
|
||||
|
||||
**If you already have issue, please do**:
|
||||
**If you still have an issue, please do**:
|
||||
1) Do `/chatitem admin` then select on "Debug" item at top right
|
||||
2) Try to use ChatItem in chat
|
||||
3) Come on discord [here](https://discord.gg/yng5PPf62h) or in private message: `Elikill58#0743`
|
||||
|
||||
@@ -5,8 +5,8 @@
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>me.dadus33</groupId>
|
||||
<artifactId>chatitem</artifactId>
|
||||
<version>2.4.7</version>
|
||||
<artifactId>ChatItem</artifactId>
|
||||
<version>2.6.3-SNAPSHOT</version>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
@@ -52,24 +52,29 @@
|
||||
<repository>
|
||||
<id>Scarsz-Nexus</id>
|
||||
<url>https://nexus.scarsz.me/content/groups/public/</url>
|
||||
</repository>
|
||||
</repository>
|
||||
<repository>
|
||||
<id>PaperMC</id>
|
||||
<url>https://repo.papermc.io/repository/maven-public/</url>
|
||||
</repository>
|
||||
<repository>
|
||||
<id>mvdw-software</id>
|
||||
<url>http://repo.mvdw-software.be/content/groups/public/</url>
|
||||
</repository>
|
||||
<repository>
|
||||
<id>essentials-snapshots</id>
|
||||
<url>https://repo.essentialsx.net/snapshots/</url>
|
||||
</repository>
|
||||
</repositories>
|
||||
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.spigotmc</groupId>
|
||||
<artifactId>spigot-api</artifactId>
|
||||
<version>1.17-R0.1-SNAPSHOT</version>
|
||||
<groupId>io.papermc.paper</groupId>
|
||||
<artifactId>paper-api</artifactId>
|
||||
<version>1.21-R0.1-SNAPSHOT</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.bukkit</groupId>
|
||||
<artifactId>minecraft-server</artifactId>
|
||||
<version>1.7.10</version>
|
||||
<type>jar</type>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.code.gson</groupId>
|
||||
<artifactId>gson</artifactId>
|
||||
@@ -85,13 +90,13 @@
|
||||
<dependency>
|
||||
<groupId>com.comphenix.protocol</groupId>
|
||||
<artifactId>ProtocolLib</artifactId>
|
||||
<version>5.0.0-SNAPSHOT</version>
|
||||
<version>5.3.0</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.viaversion</groupId>
|
||||
<artifactId>viaversion-api</artifactId>
|
||||
<version>4.6.2</version>
|
||||
<version>5.0.3</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@@ -115,25 +120,25 @@
|
||||
<dependency>
|
||||
<groupId>dev.majek</groupId>
|
||||
<artifactId>HexNicks</artifactId>
|
||||
<version>2.2.1</version>
|
||||
<version>3.1.1</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.kyori</groupId>
|
||||
<artifactId>adventure-api</artifactId>
|
||||
<version>4.13.0</version>
|
||||
<version>4.17.0</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.kyori</groupId>
|
||||
<artifactId>adventure-platform-bukkit</artifactId>
|
||||
<version>4.3.0</version>
|
||||
<scope>compile</scope>
|
||||
<version>4.3.4</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.discordsrv</groupId>
|
||||
<artifactId>discordsrv</artifactId>
|
||||
<version>1.26.2</version>
|
||||
<version>1.28.1</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@@ -143,9 +148,9 @@
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.github.kangarko</groupId>
|
||||
<artifactId>ChatControl-Free</artifactId>
|
||||
<version>5.9.5</version>
|
||||
<groupId>com.github.Auxilor</groupId>
|
||||
<artifactId>EcoEnchants</artifactId>
|
||||
<version>12.5.1</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@@ -154,6 +159,36 @@
|
||||
<version>3.7.7</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.willfp</groupId>
|
||||
<artifactId>eco</artifactId>
|
||||
<version>6.66.1</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>me.clip</groupId>
|
||||
<artifactId>placeholderapi</artifactId>
|
||||
<version>2.11.6</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>be.maximvdw</groupId>
|
||||
<artifactId>MVdWPlaceholderAPI</artifactId>
|
||||
<version>3.1.1-SNAPSHOT</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.github.MilkBowl</groupId>
|
||||
<artifactId>VaultAPI</artifactId>
|
||||
<version>1.7.1</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.essentialsx</groupId>
|
||||
<artifactId>EssentialsX</artifactId>
|
||||
<version>2.21.0-SNAPSHOT</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
@@ -194,8 +229,8 @@
|
||||
<shadedPattern>me.dadus33.libs.gson</shadedPattern>
|
||||
</relocation>
|
||||
<relocation>
|
||||
<pattern>net.kyori.adventure.text.serializer.bungeecord</pattern>
|
||||
<shadedPattern>me.dadus33.libs.kyori.serializer.bungeecord</shadedPattern>
|
||||
<pattern>com.github.steveice10.opennbt</pattern>
|
||||
<shadedPattern>me.dadus33.libs.opennbt</shadedPattern>
|
||||
</relocation>
|
||||
</relocations>
|
||||
<filters>
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
package me.dadus33.chatitem;
|
||||
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.TextComponent;
|
||||
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
|
||||
|
||||
public class C {
|
||||
|
||||
public static TextComponent text(String s) {
|
||||
return LegacyComponentSerializer.legacySection().deserialize(s);
|
||||
}
|
||||
|
||||
public static String string(Component c) {
|
||||
return LegacyComponentSerializer.legacySection().serialize(c);
|
||||
}
|
||||
}
|
||||
@@ -5,39 +5,67 @@ import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Objects;
|
||||
import java.util.StringJoiner;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.command.CommandExecutor;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.command.PluginCommand;
|
||||
import org.bukkit.command.TabCompleter;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.plugin.PluginManager;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
|
||||
import com.google.common.base.Strings;
|
||||
|
||||
import me.dadus33.chatitem.chatmanager.ChatEventListener;
|
||||
import me.dadus33.chatitem.chatmanager.ChatManager;
|
||||
import me.dadus33.chatitem.chatmanager.v1.PacketEditingChatManager;
|
||||
import me.dadus33.chatitem.chatmanager.v2.ChatListenerChatManager;
|
||||
import me.dadus33.chatitem.chatmanager.v3.PaperChatManager;
|
||||
import me.dadus33.chatitem.chatmanager.v4.OwnManager;
|
||||
import me.dadus33.chatitem.commands.CIReloadCommand;
|
||||
import me.dadus33.chatitem.commands.ChatItemCommand;
|
||||
import me.dadus33.chatitem.hook.ChatControlSupport;
|
||||
import me.dadus33.chatitem.hook.ChatManagerSupport;
|
||||
import me.dadus33.chatitem.hook.ecoenchants.EcoEnchantsSupport;
|
||||
import me.dadus33.chatitem.hook.placeholders.EssentialsPlaceholdersHook;
|
||||
import me.dadus33.chatitem.hook.placeholders.IPlaceholders;
|
||||
import me.dadus33.chatitem.hook.placeholders.MVdWPlaceholderAPIHook;
|
||||
import me.dadus33.chatitem.hook.placeholders.OwnPlaceholder;
|
||||
import me.dadus33.chatitem.hook.placeholders.PlaceholderAPIHook;
|
||||
import me.dadus33.chatitem.hook.placeholders.VaultPlaceholderHook;
|
||||
import me.dadus33.chatitem.invsee.InvShower;
|
||||
import me.dadus33.chatitem.itemnamer.NamerManager;
|
||||
import me.dadus33.chatitem.listeners.InventoryListener;
|
||||
import me.dadus33.chatitem.listeners.JoinListener;
|
||||
import me.dadus33.chatitem.listeners.TranslationInventoryListener;
|
||||
import me.dadus33.chatitem.platform.IPlatform;
|
||||
import me.dadus33.chatitem.platform.hook.PaperPlatform;
|
||||
import me.dadus33.chatitem.platform.hook.SpigotPlatform;
|
||||
import me.dadus33.chatitem.playernamer.PlayerNamerManager;
|
||||
import me.dadus33.chatitem.utils.ReflectionUtils;
|
||||
import me.dadus33.chatitem.utils.SemVer;
|
||||
import me.dadus33.chatitem.utils.Utils;
|
||||
import me.dadus33.chatitem.utils.Version;
|
||||
|
||||
public class ChatItem extends JavaPlugin {
|
||||
|
||||
private static final List<IPlaceholders> PLACEHOLDERS = new ArrayList<>();
|
||||
public static List<IPlaceholders> getPlaceholders() {
|
||||
return PLACEHOLDERS;
|
||||
}
|
||||
public static String replace(Player p, String text) {
|
||||
for(IPlaceholders ip : getPlaceholders())
|
||||
text = ip.replace(p, text);
|
||||
return text;
|
||||
}
|
||||
private static final IPlatform platform = Utils.IS_PAPER ? new PaperPlatform() : new SpigotPlatform();
|
||||
public static IPlatform getPlatform() {
|
||||
return platform;
|
||||
}
|
||||
public final static int CFG_VER = 13;
|
||||
public static boolean discordSrvSupport = false, ecoEnchantsSupport = false, hasNewVersion = false;
|
||||
public static boolean discordSrvSupport = false, hasNewVersion = false;
|
||||
private static ChatItem instance;
|
||||
private final String brandChannelName = Version.getVersion().isNewerOrEquals(Version.V1_13) ? "minecraft:brand" : "MC|Brand";
|
||||
private final List<ChatManager> chatManager = new ArrayList<>();
|
||||
@@ -48,16 +76,15 @@ public class ChatItem extends JavaPlugin {
|
||||
if (pl.getConfig().getKeys(false).isEmpty())
|
||||
pl.saveDefaultConfig();
|
||||
pl.reloadConfig();
|
||||
String oldChatManager = pl.storage.manager;
|
||||
pl.storage = new Storage(pl.getConfig());
|
||||
pl.chooseManagers();
|
||||
//pl.chooseManagers();
|
||||
Translation.load(pl);
|
||||
InvShower.getInvShower().clear();
|
||||
if(sender != null) {
|
||||
if (!pl.storage.messageReload.isEmpty())
|
||||
sender.sendMessage(pl.storage.messageReload);
|
||||
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.");
|
||||
}
|
||||
ChatManager.setTesting(null);
|
||||
}
|
||||
|
||||
public static ChatItem getInstance() {
|
||||
@@ -68,32 +95,32 @@ public class ChatItem extends JavaPlugin {
|
||||
if (getInstance().getStorage().debug)
|
||||
getInstance().getLogger().info("[Debug] " + msg.replace(ChatManager.SEPARATOR, 'S').replace(ChatManager.SEPARATOR_END, 'E'));
|
||||
}
|
||||
public static boolean hasDebug() {
|
||||
return getInstance().getStorage().debug;
|
||||
}
|
||||
|
||||
private void chooseManagers() {
|
||||
this.chatManager.forEach((cm) -> cm.unload(this));
|
||||
this.chatManager.clear();
|
||||
PluginManager pm = getServer().getPluginManager();
|
||||
|
||||
this.chatManager.add(new PacketEditingChatManager(this));
|
||||
this.chatManager.add(new ChatListenerChatManager(this));
|
||||
if(Utils.IS_PAPER) {
|
||||
this.chatManager.add(new PaperChatManager(this));
|
||||
this.chatManager.add(new OwnManager());
|
||||
}
|
||||
|
||||
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 "all":
|
||||
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 "paper":
|
||||
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:
|
||||
@@ -102,7 +129,6 @@ public class ChatItem extends JavaPlugin {
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -112,7 +138,7 @@ public class ChatItem extends JavaPlugin {
|
||||
PlayerNamerManager.load(this);
|
||||
}
|
||||
|
||||
private List<String> getPluginThatRequirePacket() {
|
||||
public static List<String> getPluginThatRequirePacket() {
|
||||
return Arrays.asList("DeluxeChat", "HexNicks", "VentureChat", "ItemsAdder");
|
||||
}
|
||||
|
||||
@@ -120,7 +146,7 @@ public class ChatItem extends JavaPlugin {
|
||||
public void onEnable() {
|
||||
// Save the instance (we're basically a singleton)
|
||||
instance = this;
|
||||
getLogger().info("Detected server version: " + Version.getVersion().name().toLowerCase());
|
||||
getLogger().info("Detected server version: " + Version.getVersion().name().toLowerCase() + " (Platform: " + getPlatform().getName() + ")");
|
||||
|
||||
// Load config
|
||||
if (!new File(getDataFolder(), "config.yml").exists()) {
|
||||
@@ -144,6 +170,7 @@ public class ChatItem extends JavaPlugin {
|
||||
pm.registerEvents(new JoinListener(), this);
|
||||
pm.registerEvents(new InventoryListener(), this);
|
||||
pm.registerEvents(new TranslationInventoryListener(), this);
|
||||
pm.registerEvents(new ChatEventListener(), this);
|
||||
|
||||
chooseManagers();
|
||||
|
||||
@@ -152,38 +179,54 @@ public class ChatItem extends JavaPlugin {
|
||||
discordSrvSupport = true;
|
||||
plugins.add("DiscordSRV");
|
||||
}
|
||||
if (pm.isPluginEnabled("ChatControl")) {
|
||||
if (pm.isPluginEnabled("ChatControl") && ReflectionUtils.isClassExist("org.mineacademy.chatcontrol.settings.Settings")) {
|
||||
ChatControlSupport.init(this);
|
||||
plugins.add("ChatControl");
|
||||
}
|
||||
if (pm.isPluginEnabled("ChatManager")) {
|
||||
if (pm.isPluginEnabled("ChatManager") && ReflectionUtils.isClassExist("me.h1dd3nxn1nja.chatmanager.Main")) {
|
||||
ChatManagerSupport.init(this);
|
||||
plugins.add("ChatManager");
|
||||
}
|
||||
if (pm.isPluginEnabled("EcoEnchants") && pm.getPlugin("EcoEnchants").getDescription().getVersion().startsWith("8.")) {
|
||||
ecoEnchantsSupport = true;
|
||||
if (pm.isPluginEnabled("EcoEnchants") && EcoEnchantsSupport.load()) {
|
||||
plugins.add("EcoEnchants");
|
||||
}
|
||||
if (pm.isPluginEnabled("PlaceholderAPI")) {
|
||||
plugins.add("PlaceholderAPI");
|
||||
PLACEHOLDERS.add(new PlaceholderAPIHook());
|
||||
}
|
||||
if (pm.isPluginEnabled("Essentials")) {
|
||||
plugins.add("Essentials");
|
||||
PLACEHOLDERS.add(new EssentialsPlaceholdersHook());
|
||||
}
|
||||
if (pm.isPluginEnabled("MVdWPlaceholderAPI")) {
|
||||
plugins.add("MVdWPlaceholderAPI");
|
||||
PLACEHOLDERS.add(new MVdWPlaceholderAPIHook());
|
||||
}
|
||||
if (pm.isPluginEnabled("Vault")) {
|
||||
plugins.add("Vault");
|
||||
PLACEHOLDERS.add(new VaultPlaceholderHook());
|
||||
}
|
||||
|
||||
if (plugins.length() > 0)
|
||||
getLogger().info("Load " + plugins.toString() + " support.");
|
||||
|
||||
PLACEHOLDERS.add(new OwnPlaceholder());
|
||||
Translation.load(this);
|
||||
|
||||
getServer().getMessenger().registerIncomingPluginChannel(this, brandChannelName, (chan, p, msg) -> ItemPlayer.getPlayer(p).setClientName(new String(msg).substring(1)));
|
||||
|
||||
if (storage.checkUpdate) {
|
||||
getServer().getScheduler().runTaskAsynchronously(this, () -> {
|
||||
CompletableFuture.runAsync(() -> {
|
||||
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());
|
||||
SemVer currentVersion = SemVer.parse(getPlatform().getPluginVersion(this));
|
||||
if (currentVersion == null)
|
||||
return;
|
||||
SemVer latestVersion = SemVer.parse(content);
|
||||
if (latestVersion != null && latestVersion.isNewerThan(currentVersion)) {
|
||||
hasNewVersion = !content.equalsIgnoreCase(getDescription().getVersion());
|
||||
hasNewVersion = !content.equalsIgnoreCase(getPlatform().getPluginVersion(this));
|
||||
if (hasNewVersion)
|
||||
getLogger().info(storage.updateMessage);
|
||||
}
|
||||
@@ -205,6 +248,14 @@ public class ChatItem extends JavaPlugin {
|
||||
public List<ChatManager> getChatManager() {
|
||||
return chatManager;
|
||||
}
|
||||
|
||||
public boolean isManagerEnabled(String id) {
|
||||
for (ChatManager cm : chatManager) {
|
||||
if(cm.getId().equalsIgnoreCase(id))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public String getVisualChatManagers() {
|
||||
StringJoiner sj = new StringJoiner(", ");
|
||||
|
||||
@@ -73,7 +73,7 @@ public class ItemPlayer {
|
||||
}
|
||||
|
||||
public boolean isBuggedClient() {
|
||||
return (getVersion().equals(Version.V1_7) && getClientName().toLowerCase().contains("lunarclient")) || (!getVersion().isNewerOrEquals(Version.V1_15) && Version.getVersion().isNewerOrEquals(Version.V1_16));
|
||||
return (!getVersion().isNewerOrEquals(Version.V1_15) && Version.getVersion().isNewerOrEquals(Version.V1_16));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
package me.dadus33.chatitem;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import me.dadus33.chatitem.chatmanager.ChatManager;
|
||||
import me.dadus33.chatitem.utils.Colors;
|
||||
|
||||
public enum ItemSlot {
|
||||
|
||||
HAND("", false),
|
||||
HELMET("helmet", false),
|
||||
CHESTPLATE("chestplate", false),
|
||||
LEGGINGS("leggings", false),
|
||||
BOOTS("boots", false),
|
||||
INVENTORY("inventory", true),
|
||||
ENDERCHEST("enderchest", true);
|
||||
|
||||
private final boolean command;
|
||||
private final String key;
|
||||
|
||||
private ItemSlot(String key, boolean command) {
|
||||
this.command = command;
|
||||
this.key = key;
|
||||
}
|
||||
|
||||
public String getKey() {
|
||||
return key;
|
||||
}
|
||||
|
||||
public boolean isBasic() {
|
||||
return key.equalsIgnoreCase("");
|
||||
}
|
||||
|
||||
public boolean isCommand() {
|
||||
return command;
|
||||
}
|
||||
|
||||
public List<String> getPlaceholders() {
|
||||
return ChatItem.getInstance().getConfig().getStringList(isBasic() ? "general.placeholders" : "general.other-placeholders." + key + ".keys");
|
||||
}
|
||||
|
||||
public boolean isEnabled() {
|
||||
return isBasic() || ChatItem.getInstance().getConfig().getBoolean("general.other-placeholders." + key + ".enabled", true);
|
||||
}
|
||||
|
||||
public boolean isDenyIfNoItem() {
|
||||
return ChatItem.getInstance().getConfig().getBoolean("general" + (isBasic() ? "" : ".other-placeholders." + key) + ".deny-if-no-item", true);
|
||||
}
|
||||
|
||||
public String getShowMessage() {
|
||||
return Colors.color(ChatItem.getInstance().getConfig().getString("general" + (isBasic() ? "" : ".other-placeholders." + key) + ".show", ""));
|
||||
}
|
||||
|
||||
public boolean hasPlaceholders(String message) {
|
||||
for (String rep : getPlaceholders()) {
|
||||
if (message.contains(rep)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public String replacePlaceholdersToSeparator(String message) {
|
||||
for(String rep : getPlaceholders())
|
||||
message = message.replace(rep, Character.toString(ChatManager.SEPARATOR));
|
||||
return message;
|
||||
}
|
||||
|
||||
public static ItemSlot getItemSlotFromMessage(String message) {
|
||||
for(ItemSlot slot : ItemSlot.values()) {
|
||||
if(slot.isEnabled() && slot.hasPlaceholders(message)) {
|
||||
return slot;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static ItemSlot getItemSlotByKey(String key) {
|
||||
for(ItemSlot slot : ItemSlot.values()) {
|
||||
if(slot.isEnabled() && slot.getKey().equalsIgnoreCase(key)) {
|
||||
return slot;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -3,10 +3,9 @@ package me.dadus33.chatitem;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.configuration.file.FileConfiguration;
|
||||
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import me.dadus33.chatitem.utils.Colors;
|
||||
|
||||
public class Storage {
|
||||
|
||||
@@ -14,8 +13,8 @@ public class Storage {
|
||||
public final String messageNoPermission, messageDeny, messageReload, messageCooldown, messageLimit, messageIgnoredItem;
|
||||
public final String SECONDS, minutes, hours;
|
||||
public final String updateMessage, updateHover;
|
||||
public final List<String> placeholders, tooltipHand, tooltipBuggedClient, ignoredItems;
|
||||
public boolean colorIfColored, addAmountForced, letMessageThrough, denyIfNoItem, debug, handDisabled, showNoPermissionMessage, checkUpdate, permissionEnabled;
|
||||
public final List<String> tooltipHand, tooltipBuggedClient, ignoredItems;
|
||||
public boolean colorIfColored, addAmountForced, letMessageThrough, debug, handDisabled, showNoPermissionMessage, checkUpdate, permissionEnabled, cmdBroadcast, cmdShow, discordSrvSendMsg;
|
||||
public int configVersion, limit, cooldown;
|
||||
private FileConfiguration conf;
|
||||
|
||||
@@ -24,16 +23,16 @@ public class Storage {
|
||||
configVersion = conf.getInt("config-version", 13);
|
||||
checkConfigVersion();
|
||||
this.manager = conf.getString("manager", "auto");
|
||||
if(manager == "both")
|
||||
manager = "all";
|
||||
language = conf.getString("general.language", "en_gb");
|
||||
debug = conf.getBoolean("debug", false);
|
||||
placeholders = ImmutableList.copyOf(conf.getStringList("general.placeholders"));
|
||||
nameFormat = color(conf.getString("general.name-format", "&b&l&o{name} {amount}&r"));
|
||||
amountFormat = color(conf.getString("general.amount-format", "x{times}"));
|
||||
commandFormat = color(conf.getString("general.command-format", "&6%name%'s item is %item%"));
|
||||
colorIfColored = conf.getBoolean("general.color-if-already-colored", true);
|
||||
letMessageThrough = conf.getBoolean("general.let-message-through", true);
|
||||
addAmountForced = conf.getBoolean("general.force-add-amount", true);
|
||||
denyIfNoItem = conf.getBoolean("general.deny-if-no-item", false);
|
||||
limit = conf.getInt("general.limit", 8);
|
||||
cooldown = conf.getInt("general.cooldown", 60);
|
||||
showNoPermissionMessage = conf.getBoolean("general.show-no-permission-message.normal", true);
|
||||
@@ -46,6 +45,8 @@ public class Storage {
|
||||
tooltipBuggedClient = conf.getStringList("general.bugged_client.tooltip").stream().map(Storage::color).collect(Collectors.toList());
|
||||
ignoredItems = conf.getStringList("general.ignored_items");
|
||||
checkUpdate = conf.getBoolean("general.check-update", true);
|
||||
cmdShow = conf.getBoolean("general.sub-commands.broadcast", true);
|
||||
cmdBroadcast = conf.getBoolean("general.sub-commands.show", true);
|
||||
messageDeny = color(conf.getString("messages.deny-message", "&c&lYou have no item in hand!"));
|
||||
messageReload = color(conf.getString("messages.reload-success", "&b&lSuccessful reload!"));
|
||||
messageNoPermission = color(conf.getString("messages.no-permission", "&c&lI'm sorry, but you are not allowed to use the placeholder in chat!"));
|
||||
@@ -54,16 +55,16 @@ public class Storage {
|
||||
updateHover = color(conf.getString("messages.join-update.hover", "&6Click to go to spigot page !"));
|
||||
messageLimit = color(conf.getString("messages.limit-message", "&c&lYou can only add 8 item placeholders per message!"));
|
||||
messageIgnoredItem = color(conf.getString("messages.ignored-item", "&cThis item is not allowed to be showed."));
|
||||
discordSrvSendMsg = conf.getBoolean("discord-srv-send-our", true);
|
||||
|
||||
SECONDS = color(conf.getString("messages.seconds", " seconds"));
|
||||
minutes = color(conf.getString("messages.minutes", " minutes"));
|
||||
hours = color(conf.getString("messages.hours", " hours"));
|
||||
colorStringList(tooltipHand);
|
||||
|
||||
}
|
||||
|
||||
public static String color(String s) {
|
||||
return s == null || s.isEmpty() ? s : ChatColor.translateAlternateColorCodes('&', s);
|
||||
return s == null || s.isEmpty() ? s : Colors.translateAlternateColorCodes('&', s);
|
||||
}
|
||||
|
||||
private static void colorStringList(List<String> input) {
|
||||
@@ -76,10 +77,10 @@ public class Storage {
|
||||
int latestVersion = ChatItem.CFG_VER;
|
||||
if (latestVersion != configVersion) {
|
||||
ChatItem pl = ChatItem.getInstance();
|
||||
pl.getLogger().warning(ChatColor.RED + "ChatItem detected an older or invalid configuration file. Replacing it with the default config...");
|
||||
pl.getLogger().warning("ChatItem detected an older or invalid configuration file. Replacing it with the default config...");
|
||||
performOverwrite();
|
||||
conf = pl.getConfig();
|
||||
pl.getLogger().warning(ChatColor.RED + "Replacement complete!");
|
||||
pl.getLogger().warning("Replacement complete!");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -14,11 +14,13 @@ import java.util.stream.Collectors;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
|
||||
import me.dadus33.chatitem.utils.Utils;
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
public class Translation {
|
||||
|
||||
private static File folder;
|
||||
@@ -34,8 +36,12 @@ public class Translation {
|
||||
allLangsConfig = Utils.copyLoadFile(pl.getDataFolder(), "langs.yml", "langs.yml");
|
||||
|
||||
allLangsConfig.getStringList("all").forEach(langKey -> {
|
||||
JsonObject content = JsonParser.parseReader(new InputStreamReader(pl.getResource("lang/" + langKey + ".json"))).getAsJsonObject();
|
||||
allLangs.put(langKey, content.get("language.name").getAsString() + " (" + content.get("language.region").getAsString() + ")");
|
||||
try {
|
||||
JsonObject content = JsonParser.parseReader(new InputStreamReader(pl.getResource("lang/" + langKey + ".json"))).getAsJsonObject();
|
||||
allLangs.put(langKey, content.get("language.name").getAsString() + " (" + content.get("language.region").getAsString() + ")");
|
||||
} catch (Exception e) {
|
||||
pl.getLogger().severe("Failed to load lang with key " + langKey + " : " + e.getMessage() + " (" + e.getStackTrace()[0].toString() + ")");
|
||||
}
|
||||
});
|
||||
allLangs = allLangs.entrySet().stream().sorted(Entry.comparingByValue()).collect(Collectors.toMap(Entry::getKey, Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
|
||||
loadLang(pl.getStorage().language);
|
||||
@@ -49,6 +55,11 @@ public class Translation {
|
||||
return messages;
|
||||
}
|
||||
|
||||
public static String getMessage(String key) {
|
||||
JsonElement result = messages.get(key);
|
||||
return result == null ? "" : result.getAsString();
|
||||
}
|
||||
|
||||
public static void loadLang(String lang) {
|
||||
ChatItem pl = ChatItem.getInstance();
|
||||
File langFile = new File(folder, lang + ".json");
|
||||
@@ -71,15 +82,23 @@ public class Translation {
|
||||
pl.getLogger().info("Loaded translation for " + lang + ".");
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
public static String get(ItemStack item) {
|
||||
String key = (item.getType().isBlock() ? "block" : "item") + ".minecraft." + item.getType().name().toLowerCase().replace("_", ".");
|
||||
String key = (item.getType().isBlock() ? "block" : "item") + ".minecraft." + item.getType().name().toLowerCase();
|
||||
if (messages != null && messages.has(key)) {
|
||||
return messages.get(key).getAsString();
|
||||
} else
|
||||
ChatItem.debug("Failed to find translation for " + key);
|
||||
return legacy.getString(item.getType().name() + "." + item.getDurability(), item.getType().name().toLowerCase().replace("_", " "));
|
||||
}
|
||||
|
||||
public static String getOr(ItemStack item, String def) {
|
||||
String key = (item.getType().isBlock() ? "block" : "item") + ".minecraft." + item.getType().name().toLowerCase();
|
||||
if (messages != null && messages.has(key)) {
|
||||
return messages.get(key).getAsString();
|
||||
} else
|
||||
ChatItem.debug("Failed to find translation for " + key);
|
||||
return legacy.getString(item.getType().name() + "." + item.getDurability(), def);
|
||||
}
|
||||
|
||||
protected void thisMethodShouldNotBeUsed_InsteadToUpdateLangFileFromLocalInstall() throws Exception {
|
||||
File dir = new File("dir/to/result");
|
||||
|
||||
@@ -8,6 +8,7 @@ import org.bukkit.entity.Player;
|
||||
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
import me.dadus33.chatitem.ItemPlayer;
|
||||
import me.dadus33.chatitem.ItemSlot;
|
||||
import me.dadus33.chatitem.utils.Utils;
|
||||
|
||||
public class Chat {
|
||||
@@ -20,8 +21,8 @@ public class Chat {
|
||||
return CHAT.stream().filter(o -> o.getId() == id).findFirst();
|
||||
}
|
||||
}
|
||||
public static Chat create(Player p, String message) {
|
||||
return new Chat(actualId++, p, message);
|
||||
public static Chat create(Player p, String message, ChatAction action) {
|
||||
return new Chat(actualId++, p, message, action);
|
||||
}
|
||||
public static Chat getFrom(String message) {
|
||||
boolean found = false;
|
||||
@@ -42,12 +43,14 @@ public class Chat {
|
||||
private final int id;
|
||||
private final Player p;
|
||||
private final String message;
|
||||
private final ChatAction action;
|
||||
|
||||
public Chat(int id, Player p, String message) {
|
||||
public Chat(int id, Player p, String message, ChatAction action) {
|
||||
this.time = System.currentTimeMillis();
|
||||
this.id = id;
|
||||
this.p = p;
|
||||
this.message = message;
|
||||
this.action = action;
|
||||
CHAT.add(this);
|
||||
}
|
||||
|
||||
@@ -67,6 +70,14 @@ public class Chat {
|
||||
return message;
|
||||
}
|
||||
|
||||
public ItemSlot getSlot() {
|
||||
return action.getSlot();
|
||||
}
|
||||
|
||||
public ChatAction getAction() {
|
||||
return action;
|
||||
}
|
||||
|
||||
public ItemPlayer getItemPlayer() {
|
||||
return ItemPlayer.getPlayer(getPlayer());
|
||||
}
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
package me.dadus33.chatitem.chatmanager;
|
||||
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import me.dadus33.chatitem.ItemSlot;
|
||||
|
||||
public class ChatAction {
|
||||
|
||||
private boolean isItem;
|
||||
private ItemSlot slot;
|
||||
private String command;
|
||||
private ItemStack item;
|
||||
private Player origin;
|
||||
|
||||
public ChatAction(ItemSlot slot, Player origin, ItemStack item) {
|
||||
this.slot = slot;
|
||||
this.item = item == null ? new ItemStack(Material.AIR) : item;
|
||||
this.origin = origin;
|
||||
this.isItem = true;
|
||||
}
|
||||
|
||||
public ChatAction(ItemSlot slot, Player origin, String command) {
|
||||
this.slot = slot;
|
||||
this.command = command;
|
||||
this.origin = origin;
|
||||
this.isItem = false;
|
||||
}
|
||||
|
||||
public Player getOrigin() {
|
||||
return origin;
|
||||
}
|
||||
|
||||
public ItemSlot getSlot() {
|
||||
return slot;
|
||||
}
|
||||
|
||||
public boolean isItem() {
|
||||
return isItem;
|
||||
}
|
||||
|
||||
public String getCommand() {
|
||||
return command;
|
||||
}
|
||||
|
||||
public boolean hasCommand() {
|
||||
return command != null && command != "";
|
||||
}
|
||||
|
||||
public ItemStack getItem() {
|
||||
return item == null ? new ItemStack(Material.AIR) : item;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ChatAction[slot=" + slot + ",command=" + command + ",item=" + item + ",origin=" + origin + "]";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package me.dadus33.chatitem.chatmanager;
|
||||
|
||||
import static me.dadus33.chatitem.chatmanager.ChatManager.SEPARATOR;
|
||||
import static me.dadus33.chatitem.chatmanager.ChatManager.SEPARATOR_END;
|
||||
|
||||
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 me.dadus33.chatitem.ChatItem;
|
||||
import me.dadus33.chatitem.ItemSlot;
|
||||
import me.dadus33.chatitem.Storage;
|
||||
import me.dadus33.chatitem.utils.Utils;
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
public class ChatEventListener implements Listener {
|
||||
|
||||
private Storage getStorage() {
|
||||
return ChatItem.getInstance().getStorage();
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.LOWEST)
|
||||
public void onChat(AsyncPlayerChatEvent e) {
|
||||
if (ChatManager.containsSeparator(e.getMessage())) { // If the BELL character is found, we have to remove it
|
||||
e.setMessage(ChatManager.removeSeparator(e.getMessage()));
|
||||
}
|
||||
Player p = e.getPlayer();
|
||||
String oldMsg = e.getMessage();
|
||||
ItemSlot slot = ItemSlot.getItemSlotFromMessage(e.getMessage());
|
||||
if (slot == null) {
|
||||
ChatItem.debug("(general) not found placeholders in: " + e.getMessage());
|
||||
return;
|
||||
}
|
||||
ChatAction action = ChatManager.getChatAction(slot, p);
|
||||
if(!ChatManager.canUsePlaceholder(p, action, slot, e))
|
||||
return;
|
||||
String s = slot.replacePlaceholdersToSeparator(e.getMessage());
|
||||
if (Utils.countMatches(s, Character.toString(ChatManager.SEPARATOR)) > getStorage().limit) {
|
||||
e.setCancelled(true);
|
||||
if (!getStorage().messageLimit.isEmpty())
|
||||
p.sendMessage(getStorage().messageLimit);
|
||||
return;
|
||||
}
|
||||
|
||||
Chat c = Chat.create(p, oldMsg, action);
|
||||
ChatItem.debug("(general) Set placeholder to message " + c);
|
||||
e.setMessage(s.replace(Character.toString(ChatManager.SEPARATOR), SEPARATOR + Integer.toString(c.getId()) + SEPARATOR_END));
|
||||
e.setFormat(e.getFormat().replace(oldMsg, e.getMessage())); // set own message for plugin that already put the message into the format
|
||||
}
|
||||
}
|
||||
@@ -1,26 +1,39 @@
|
||||
package me.dadus33.chatitem.chatmanager;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.block.ShulkerBox;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.Cancellable;
|
||||
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.ItemSlot;
|
||||
import me.dadus33.chatitem.Storage;
|
||||
import me.dadus33.chatitem.hook.EcoEnchantsSupport;
|
||||
import me.dadus33.chatitem.hook.ecoenchants.EcoEnchantsSupport;
|
||||
import me.dadus33.chatitem.invsee.InvShower;
|
||||
import me.dadus33.chatitem.invsee.hook.EnderChestShower;
|
||||
import me.dadus33.chatitem.invsee.hook.PlayerInventoryShower;
|
||||
import me.dadus33.chatitem.itemnamer.NamerManager;
|
||||
import me.dadus33.chatitem.utils.Colors;
|
||||
import me.dadus33.chatitem.utils.ItemUtils;
|
||||
import me.dadus33.chatitem.utils.Messages;
|
||||
import me.dadus33.chatitem.utils.Utils;
|
||||
import me.dadus33.chatitem.utils.Version;
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
public abstract class ChatManager {
|
||||
|
||||
public static String inTest = null;
|
||||
@@ -90,27 +103,48 @@ public abstract class ChatManager {
|
||||
* @param p the player
|
||||
* @return the usable item
|
||||
*/
|
||||
public static ItemStack getUsableItem(Player p) {
|
||||
ItemStack item = HandItem.getBetterItem(p).clone();
|
||||
public static ItemStack getUsableItem(Player p, ItemSlot slot) {
|
||||
if (slot == null)
|
||||
return null;
|
||||
ItemStack betterItem = HandItem.getBetterItem(p, slot);
|
||||
if (betterItem == null)
|
||||
return null;
|
||||
|
||||
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);
|
||||
ChatItem.debug("Added " + addLore.size() + " lores from EcoEnchants");
|
||||
} else
|
||||
ChatItem.debug("No lore to add from EcoEnchants");
|
||||
ItemStack item = betterItem.clone();
|
||||
if (slot.isDenyIfNoItem() && ItemUtils.isEmpty(item))
|
||||
return null;
|
||||
if (EcoEnchantsSupport.hasSupport()) {
|
||||
item = EcoEnchantsSupport.manageItem(item);
|
||||
} else if (item.hasItemMeta()) {
|
||||
ItemMeta meta = item.getItemMeta();
|
||||
if (meta instanceof BookMeta) { // filtering written books
|
||||
BookMeta bm = (BookMeta) item.getItemMeta();
|
||||
bm.setPages(Collections.emptyList());
|
||||
item.setItemMeta(bm);
|
||||
} else if (meta instanceof BlockStateMeta && Version.getVersion().isNewerOrEquals(Version.V1_9)) { // if it's a block
|
||||
BlockStateMeta bsm = (BlockStateMeta) item.getItemMeta();
|
||||
if (bsm.hasBlockState() && bsm.getBlockState() instanceof ShulkerBox) {
|
||||
ShulkerBox sb = (ShulkerBox) bsm.getBlockState();
|
||||
for (ItemStack itemInv : sb.getInventory()) {
|
||||
ItemUtils.stripData(itemInv);
|
||||
}
|
||||
bsm.setBlockState(sb);
|
||||
}
|
||||
item.setItemMeta(bsm);
|
||||
}
|
||||
}
|
||||
|
||||
return item;
|
||||
}
|
||||
|
||||
public static ChatAction getChatAction(ItemSlot slot, Player p) {
|
||||
if (slot.isCommand()) {
|
||||
UUID uuid = UUID.randomUUID();
|
||||
InvShower.add(uuid.toString(), slot == ItemSlot.INVENTORY ? new PlayerInventoryShower(p) : new EnderChestShower(p));
|
||||
return new ChatAction(slot, p, "/chatitem seeinv " + uuid.toString());
|
||||
}
|
||||
return new ChatAction(slot, p, getUsableItem(p, slot));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all lores lines of an item, to replace the show_item action which is not
|
||||
* working with ViaBackwards
|
||||
@@ -118,20 +152,20 @@ public abstract class ChatManager {
|
||||
* @param item the item to get lines from
|
||||
* @return all lores
|
||||
*/
|
||||
public static List<String> getMaxLinesFromItem(Player p, ItemStack item) {
|
||||
public static List<String> getMaxLinesFromItem(Player viewer, 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()));
|
||||
lines.add(NamerManager.getName(viewer, item, ChatItem.getInstance().getStorage()));
|
||||
if (meta.hasEnchants()) {
|
||||
meta.getEnchants().forEach((enchant, lvl) -> {
|
||||
lines.add(ChatColor.RESET + Utils.getEnchantName(enchant) + " " + Utils.toRoman(lvl));
|
||||
lines.add(Colors.RESET + Utils.getEnchantName(enchant) + " " + Utils.toRoman(lvl));
|
||||
});
|
||||
}
|
||||
if (meta.hasLore())
|
||||
lines.addAll(meta.getLore());
|
||||
} else {
|
||||
lines.add(NamerManager.getName(p, item, ChatItem.getInstance().getStorage()));
|
||||
lines.add(NamerManager.getName(viewer, item, ChatItem.getInstance().getStorage()));
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
@@ -141,12 +175,12 @@ public abstract class ChatManager {
|
||||
* 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
|
||||
* @param viewer 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) {
|
||||
public static String styleItem(Player viewer, ItemStack item, Storage c) {
|
||||
String replacer = c.nameFormat;
|
||||
String amount = c.amountFormat;
|
||||
if (item.getAmount() == 1) {
|
||||
@@ -160,18 +194,7 @@ public abstract class ChatManager {
|
||||
amount = amount.replace(TIMES, String.valueOf(item.getAmount()));
|
||||
replacer = replacer.replace(AMOUNT, amount);
|
||||
}
|
||||
if (item.hasItemMeta() && item.getItemMeta().hasDisplayName()) {
|
||||
String trp = item.getItemMeta().getDisplayName();
|
||||
ChatItem.debug("trp: " + trp);
|
||||
if (c.colorIfColored) {
|
||||
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;
|
||||
return replacer.replace(NAME, NamerManager.getName(viewer, item, c));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -182,14 +205,51 @@ public abstract class ChatManager {
|
||||
* @param c the config
|
||||
* @return the name of item or hand
|
||||
*/
|
||||
public static String getNameOfItem(Player p, ItemStack item, Storage c) {
|
||||
public static String getNameOfItem(Player p, ItemStack item, Player viewer, Storage c) {
|
||||
if (ItemUtils.isEmpty(item)) {
|
||||
if (c.handDisabled)
|
||||
return c.placeholders.get(0);
|
||||
else
|
||||
return c.handName;
|
||||
return ItemSlot.HAND.getPlaceholders().get(0);
|
||||
return getHandName(p);
|
||||
}
|
||||
return styleItem(p, item, c);
|
||||
return ChatItem.replace(p, styleItem(viewer, item, c));
|
||||
}
|
||||
|
||||
public static String getNameForChatAction(Player viewer, Chat chat, Storage c) {
|
||||
ChatAction action = chat.getAction();
|
||||
if (action.isItem()) {
|
||||
ItemStack item = action.getItem();
|
||||
if (ItemUtils.isEmpty(item)) {
|
||||
if (c.handDisabled)
|
||||
return chat.getSlot().getPlaceholders().get(0);
|
||||
return getHandName(chat);
|
||||
}
|
||||
return ChatItem.replace(chat.getPlayer(), styleItem(viewer, item, c));
|
||||
}
|
||||
return ChatItem.replace(chat.getPlayer(), Messages.getMessage(action.getSlot().name().toLowerCase() + ".chat", "%cible%", action.getOrigin().getName()));
|
||||
}
|
||||
|
||||
public static String getNameForChatAction(Player viewer, ChatAction action, Storage c) {
|
||||
if (action.isItem()) {
|
||||
ItemStack item = action.getItem();
|
||||
if (ItemUtils.isEmpty(item)) {
|
||||
if (c.handDisabled)
|
||||
return action.getSlot().getPlaceholders().get(0);
|
||||
else
|
||||
return getHandName(action.getOrigin());
|
||||
}
|
||||
return ChatItem.replace(action.getOrigin(), styleItem(viewer, item, c));
|
||||
}
|
||||
return ChatItem.replace(action.getOrigin(), Messages.getMessage(action.getSlot().name().toLowerCase() + ".chat", "%cible%", action.getOrigin().getName()));
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public static String getHandName(Player p) {
|
||||
return ChatItem.replace(p, ChatItem.getInstance().getStorage().handName.replace("{name}", p.getName()).replace("{display-name}", p.getDisplayName()));
|
||||
}
|
||||
|
||||
public static String getHandName(Chat c) {
|
||||
Player p = c.getPlayer();
|
||||
return ChatItem.replace(p, ChatItem.getInstance().getStorage().handName.replace("{name}", p.getName()).replace("{display-name}", p.getDisplayName()));
|
||||
}
|
||||
|
||||
public static String calculateTime(long seconds) {
|
||||
@@ -221,7 +281,7 @@ public abstract class ChatManager {
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
public static boolean canShowItem(Player p, ItemStack item, @Nullable Cancellable e) {
|
||||
public static boolean canUsePlaceholder(Player p, ChatAction action, ItemSlot slot, @Nullable Cancellable e) {
|
||||
Storage c = ChatItem.getInstance().getStorage();
|
||||
if (c.permissionEnabled && !p.hasPermission(c.permissionName)) {
|
||||
if (!c.letMessageThrough) {
|
||||
@@ -233,8 +293,8 @@ public abstract class ChatManager {
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (item.getType().equals(Material.AIR)) {
|
||||
if (c.denyIfNoItem) {
|
||||
if (action.isItem() && action.getItem().getType().equals(Material.AIR) && slot.isBasic()) {
|
||||
if (slot.isDenyIfNoItem()) {
|
||||
if (e != null)
|
||||
e.setCancelled(true);
|
||||
if (!c.messageDeny.isEmpty())
|
||||
@@ -266,9 +326,11 @@ public abstract class ChatManager {
|
||||
}
|
||||
}
|
||||
}
|
||||
for (String ignored : c.ignoredItems) {
|
||||
if (item.getType().name().toLowerCase().contains(ignored.toLowerCase())) {
|
||||
return false;
|
||||
if (action.isItem()) {
|
||||
for (String ignored : c.ignoredItems) {
|
||||
if (action.getItem().getType().name().toLowerCase().contains(ignored.toLowerCase())) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -295,16 +357,33 @@ public abstract class ChatManager {
|
||||
public static void applyCooldown(Player p) {
|
||||
COOLDOWNS.put(p.getUniqueId(), System.currentTimeMillis() / 1000);
|
||||
}
|
||||
|
||||
|
||||
public static boolean isTestingEnabled() {
|
||||
return inTest != null;
|
||||
}
|
||||
|
||||
|
||||
public static boolean isTesting(String actual) {
|
||||
return inTest != null && (inTest == "both" || inTest.equalsIgnoreCase(actual));
|
||||
return inTest != null && (inTest == "both" || inTest == "all" || inTest.equalsIgnoreCase(actual));
|
||||
}
|
||||
|
||||
|
||||
public static void setTesting(String actual) {
|
||||
inTest = actual;
|
||||
}
|
||||
|
||||
public static boolean isSelected(String actual) {
|
||||
if(isTestingEnabled())
|
||||
return true;
|
||||
String selected = ChatItem.getInstance().getStorage().manager;
|
||||
if (selected.equalsIgnoreCase("both") || selected.equalsIgnoreCase("all"))
|
||||
return true;
|
||||
if (selected == "auto") {
|
||||
if (Utils.IS_PAPER && actual == "paper")
|
||||
return true;
|
||||
else if (actual == "packet" && ChatItem.getPluginThatRequirePacket().stream().map(Bukkit.getPluginManager()::getPlugin).anyMatch(Objects::nonNull))
|
||||
return true;
|
||||
else if (actual == "chat")
|
||||
return true;
|
||||
}
|
||||
return selected.equalsIgnoreCase(actual);
|
||||
}
|
||||
}
|
||||
@@ -3,20 +3,36 @@ package me.dadus33.chatitem.chatmanager;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import me.dadus33.chatitem.ItemSlot;
|
||||
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;
|
||||
public static ItemStack getBetterItem(Player p, ItemSlot slot) {
|
||||
switch (slot) {
|
||||
case HAND:
|
||||
if(Version.getVersion().isNewerOrEquals(Version.V1_9)) {
|
||||
ItemStack main = p.getInventory().getItemInMainHand();
|
||||
if(!ItemUtils.isEmpty(main))
|
||||
return main;
|
||||
return p.getInventory().getItemInOffHand();
|
||||
}
|
||||
return p.getItemInHand();
|
||||
case HELMET:
|
||||
return p.getInventory().getHelmet();
|
||||
case CHESTPLATE:
|
||||
return p.getInventory().getChestplate();
|
||||
case LEGGINGS:
|
||||
return p.getInventory().getLeggings();
|
||||
case BOOTS:
|
||||
return p.getInventory().getBoots();
|
||||
case ENDERCHEST:
|
||||
break;
|
||||
case INVENTORY:
|
||||
break;
|
||||
}
|
||||
return p.getItemInHand();
|
||||
return null; // should never happen
|
||||
}
|
||||
}
|
||||
@@ -1,29 +1,29 @@
|
||||
package me.dadus33.chatitem.chatmanager.v1;
|
||||
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.event.HandlerList;
|
||||
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
import me.dadus33.chatitem.Storage;
|
||||
import me.dadus33.chatitem.chatmanager.ChatManager;
|
||||
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.PacketContent;
|
||||
import me.dadus33.chatitem.chatmanager.v1.packets.PacketManager;
|
||||
import me.dadus33.chatitem.utils.PacketUtils;
|
||||
import me.dadus33.chatitem.utils.ReflectionUtils;
|
||||
import me.dadus33.chatitem.utils.Utils;
|
||||
|
||||
public class PacketEditingChatManager extends ChatManager {
|
||||
|
||||
private boolean baseComponentAvailable = true;
|
||||
private final ChatItemPacketManager packetManager;
|
||||
private final ChatEventListener chatEventListener;
|
||||
private final ChatPacketManager chatPacketManager;
|
||||
|
||||
public PacketEditingChatManager(ChatItem pl) {
|
||||
packetManager = new ChatItemPacketManager(pl);
|
||||
chatEventListener = new ChatEventListener(this);
|
||||
chatPacketManager = new ChatPacketManager(this);
|
||||
|
||||
// Check for existence of BaseComponent class (only on spigot)
|
||||
@@ -48,7 +48,6 @@ public class PacketEditingChatManager extends ChatManager {
|
||||
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
|
||||
@@ -56,7 +55,6 @@ public class PacketEditingChatManager extends ChatManager {
|
||||
|
||||
@Override
|
||||
public void unload(ChatItem pl) {
|
||||
HandlerList.unregisterAll(chatEventListener);
|
||||
PacketManager pm = packetManager.getPacketManager();
|
||||
pm.removeHandler(chatPacketManager);
|
||||
pm.stop();
|
||||
@@ -65,20 +63,35 @@ public class PacketEditingChatManager extends ChatManager {
|
||||
public boolean supportsChatComponentApi() {
|
||||
return baseComponentAvailable;
|
||||
}
|
||||
|
||||
private static String checkPacketSize(String packet, int maxSize) {
|
||||
int size = packet.getBytes().length;
|
||||
while(size > maxSize) {
|
||||
packet = packet.replaceFirst(" ", " ");
|
||||
if(size == packet.getBytes().length)
|
||||
break; // could not fix myself
|
||||
size = packet.getBytes().length;
|
||||
}
|
||||
return packet;
|
||||
}
|
||||
|
||||
public static Object createSystemChatPacket(String json) throws Exception {
|
||||
Object packet = internalCreateSystemChatPacket(json);
|
||||
public static Object createSystemChatPacket(String json, Object old) throws Exception {
|
||||
json = checkPacketSize(json, 150000);
|
||||
Object packet = internalCreateSystemChatPacket(json, old);
|
||||
if(packet != null)
|
||||
return packet;
|
||||
packet = internalCreateSystemChatPacket(PacketUtils.ICB_FROM_JSON.invoke(null, json));
|
||||
Object icb = ChatItem.getPlatform().jsonToBaseComponent(json);
|
||||
if(icb != null)
|
||||
packet = internalCreateSystemChatPacket(icb, old);
|
||||
if(packet != null)
|
||||
return packet;
|
||||
ChatItem.getInstance().getLogger().warning("Can't create a new packet for json " + json);
|
||||
return null;
|
||||
}
|
||||
|
||||
private static Object internalCreateSystemChatPacket(Object obj) throws Exception {
|
||||
Class<?> packetClass = PacketUtils.getNmsClass("ClientboundSystemChatPacket", "network.protocol.game.", "PacketPlayOutChat");
|
||||
private static Object internalCreateSystemChatPacket(Object obj, Object old) throws Exception {
|
||||
Class<?> packetClass = PacketUtils.getNmsClass("ClientboundSystemChatPacket", "network.protocol.game.", "ClientboundPlayerChatPacket", "PacketPlayOutChat");
|
||||
Class<?> chatMessageTypeClass = Utils.isClassExist("net.minecraft.network.chat.ChatMessageType") ? PacketUtils.getNmsClass("ChatMessageType", "network.chat.") : null;
|
||||
Constructor<?> betterOne = null;
|
||||
Object[] betterParam = null;
|
||||
for (Constructor<?> cons : packetClass.getDeclaredConstructors()) {
|
||||
@@ -89,6 +102,8 @@ public class PacketEditingChatManager extends ChatManager {
|
||||
if(obj instanceof String) {
|
||||
if (cons.getParameterCount() == 2 && cons.getParameterTypes()[0].equals(String.class) && cons.getParameterTypes()[1].equals(int.class)) { // "string, int"
|
||||
return cons.newInstance(obj, 1);
|
||||
} else if (cons.getParameterCount() == 2 && cons.getParameterTypes()[0].equals(String.class) && cons.getParameterTypes()[1].equals(boolean.class)) { // "string, boolean"
|
||||
return cons.newInstance(obj, false); // false for no overlay
|
||||
} else if (cons.getParameterCount() == 3 && cons.getParameterTypes()[1].equals(String.class)) { // "component", "string", <something not checked>
|
||||
Class<?> secondParam = cons.getParameterTypes()[2];
|
||||
if (secondParam.equals(int.class)) // "component", "string", "int"
|
||||
@@ -96,14 +111,34 @@ public class PacketEditingChatManager extends ChatManager {
|
||||
else if (secondParam.equals(boolean.class)) // "component", "string", "boolean"
|
||||
return cons.newInstance(null, obj, false);
|
||||
}
|
||||
} else if(obj.getClass().isAssignableFrom(PacketUtils.COMPONENT_CLASS)) {
|
||||
if (cons.getParameterCount() == 2 && cons.getParameterTypes()[0].isAssignableFrom(PacketUtils.COMPONENT_CLASS) && cons.getParameterTypes()[1].equals(boolean.class)) // "string, boolean"
|
||||
return cons.newInstance(obj, false);
|
||||
}
|
||||
|
||||
int nbPut = 0;
|
||||
Object[] params = new Object[cons.getParameterCount()];
|
||||
for(int i = 0; i < params.length; i++) {
|
||||
if(cons.getParameterTypes()[i].isAssignableFrom(obj.getClass())) {
|
||||
Class<?> type = cons.getParameterTypes()[i];
|
||||
if(type.isAssignableFrom(obj.getClass())) {
|
||||
params[i] = obj;
|
||||
nbPut++;
|
||||
} else if(chatMessageTypeClass != null && type.isAssignableFrom(chatMessageTypeClass)) {
|
||||
params[i] = getChatMessageType();
|
||||
} else if(type.isAssignableFrom(boolean.class)) // need to set primitives
|
||||
params[i] = false;
|
||||
else if(type.isAssignableFrom(int.class)) // need to set primitives
|
||||
params[i] = 0;
|
||||
else {
|
||||
boolean found = false;
|
||||
for(Class<?> prim : Arrays.asList(float.class, long.class)) { // if not primitive
|
||||
if(type.isAssignableFrom(prim)) {
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
if(!found) {
|
||||
params[i] = new PacketContent(old).getSpecificModifier(type).readSafely(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
if(nbPut == 1) {
|
||||
@@ -118,8 +153,18 @@ public class PacketEditingChatManager extends ChatManager {
|
||||
ChatItem.getInstance().getLogger().warning("Some constructor seems to have too many " + obj.getClass().getSimpleName() + ". Class: " + packetClass.getSimpleName());
|
||||
}
|
||||
if(betterOne != null && betterParam != null) {
|
||||
return betterOne.newInstance(betterParam);
|
||||
try {
|
||||
return betterOne.newInstance(betterParam);
|
||||
} catch (IllegalArgumentException e) {
|
||||
ChatItem.getInstance().getLogger().warning("Failed to create a new packet to send. " + betterOne.getParameterCount() + " (" + Utils.arrayToString(betterOne.getParameterTypes()) + "). Params: " + Utils.arrayToString(betterParam));
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static Object getChatMessageType() throws Exception {
|
||||
Class<?> c = PacketUtils.getNmsClass("ChatMessageType", "network.chat.");
|
||||
return ReflectionUtils.getMethod(c, c, byte.class).invoke(null, (byte) 0);
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,10 @@
|
||||
package me.dadus33.chatitem.chatmanager.v1.basecomp;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonElement;
|
||||
@@ -11,7 +12,6 @@ import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
import me.dadus33.chatitem.ItemPlayer;
|
||||
import me.dadus33.chatitem.Storage;
|
||||
import me.dadus33.chatitem.chatmanager.Chat;
|
||||
import me.dadus33.chatitem.chatmanager.ChatManager;
|
||||
@@ -45,9 +45,12 @@ public interface IComponentManager {
|
||||
return null;
|
||||
}
|
||||
|
||||
default Object manageItem(Player p, Chat chat, ChatItemPacket packet, ItemStack item, Storage c) throws Exception {
|
||||
String message = JSONManipulator.getInstance().parse(chat, getBaseComponentAsJSON(packet), item, ChatManager.styleItem(chat.getPlayer(), item, c),
|
||||
ItemPlayer.getPlayer(p).getProtocolVersion());
|
||||
default Object manageContent(Player viewer, Chat chat, ChatItemPacket packet, String json, Storage c) throws Exception {
|
||||
String message;
|
||||
if (Utils.isBeforeChatJson(viewer))
|
||||
message = JSONManipulator.getInstance().parseEmpty(chat, json, chat.getAction().isItem() ? ChatManager.getMaxLinesFromItem(viewer, chat.getAction().getItem()) : new ArrayList<>(), chat.getPlayer());
|
||||
else
|
||||
message = JSONManipulator.getInstance().parse(chat, json, chat.getAction(), ChatManager.getNameForChatAction(viewer, chat, c));
|
||||
if (message != null) {
|
||||
ChatItem.debug("(v1) Writing message: " + message);
|
||||
writeJson(packet, message);
|
||||
@@ -55,8 +58,8 @@ public interface IComponentManager {
|
||||
return packet.getPacket();
|
||||
}
|
||||
|
||||
default Object manageEmpty(Player p, Chat chat, ChatItemPacket packet, Storage c) {
|
||||
String message = JSONManipulator.getInstance().parseEmpty(getBaseComponentAsJSON(packet), c.handName, c.tooltipHand, chat.getPlayer());
|
||||
default Object manageEmpty(Player p, Chat chat, ChatItemPacket packet, String json, Storage c) {
|
||||
String message = JSONManipulator.getInstance().parseEmpty(chat, json, c.tooltipHand, chat.getPlayer());
|
||||
if (message != null) {
|
||||
ChatItem.debug("(v1) Writing empty message: " + message);
|
||||
writeJson(packet, message);
|
||||
@@ -74,7 +77,14 @@ public interface IComponentManager {
|
||||
}
|
||||
|
||||
private Chat search() {
|
||||
JsonObject jsonObj = JsonParser.parseString(json).getAsJsonObject();
|
||||
JsonObject jsonObj;
|
||||
try {
|
||||
jsonObj = JsonParser.parseString(json).getAsJsonObject();
|
||||
} catch (Exception e) {
|
||||
if(searchInString(json))
|
||||
return getWithId();
|
||||
return null;
|
||||
}
|
||||
if (jsonObj.has("extra")) {
|
||||
if (searchInExtra(jsonObj.getAsJsonArray("extra"))) {
|
||||
return getWithId();
|
||||
@@ -82,11 +92,11 @@ public interface IComponentManager {
|
||||
}
|
||||
if (jsonObj.has("text")) {
|
||||
JsonElement text = jsonObj.get("text");
|
||||
if(text.isJsonObject() && searchInObject(text.getAsJsonObject()))
|
||||
if (text.isJsonObject() && searchInObject(text.getAsJsonObject()))
|
||||
return getWithId();
|
||||
else if(text.isJsonArray() && searchInExtra(text.getAsJsonArray()))
|
||||
else if (text.isJsonArray() && searchInExtra(text.getAsJsonArray()))
|
||||
return getWithId();
|
||||
else if(text.isJsonPrimitive() && searchInString(text.getAsString()))
|
||||
else if (text.isJsonPrimitive() && searchInString(text.getAsString()))
|
||||
return getWithId();
|
||||
}
|
||||
return null;
|
||||
@@ -122,7 +132,7 @@ public interface IComponentManager {
|
||||
else if (found)
|
||||
id += c;
|
||||
}
|
||||
return false;
|
||||
return id != "" && Utils.isInteger(id) && Chat.getChat(Integer.parseInt(id)).isPresent();
|
||||
}
|
||||
}
|
||||
}
|
||||
+65
-57
@@ -1,59 +1,77 @@
|
||||
package me.dadus33.chatitem.chatmanager.v1.basecomp.hook;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParseException;
|
||||
import com.google.gson.JsonParser;
|
||||
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
import me.dadus33.chatitem.Storage;
|
||||
import me.dadus33.chatitem.chatmanager.Chat;
|
||||
import me.dadus33.chatitem.chatmanager.ChatAction;
|
||||
import me.dadus33.chatitem.chatmanager.ChatManager;
|
||||
import me.dadus33.chatitem.chatmanager.v1.PacketEditingChatManager;
|
||||
import me.dadus33.chatitem.chatmanager.v1.basecomp.IComponentManager;
|
||||
import me.dadus33.chatitem.chatmanager.v1.json.JSONManipulator;
|
||||
import me.dadus33.chatitem.chatmanager.v1.packets.ChatItemPacket;
|
||||
import me.dadus33.chatitem.chatmanager.v1.packets.PacketContent.ContentModifier;
|
||||
import me.dadus33.chatitem.hook.DiscordSrvSupport;
|
||||
import me.dadus33.chatitem.utils.Messages;
|
||||
import me.dadus33.chatitem.utils.PacketUtils;
|
||||
import me.dadus33.chatitem.utils.ReflectionUtils;
|
||||
import me.dadus33.chatitem.utils.Utils;
|
||||
import net.kyori.adventure.key.Key;
|
||||
import net.kyori.adventure.nbt.api.BinaryTagHolder;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.TextComponent;
|
||||
import net.kyori.adventure.text.TranslatableComponent;
|
||||
import net.kyori.adventure.text.TextReplacementConfig;
|
||||
import net.kyori.adventure.text.event.ClickEvent;
|
||||
import net.kyori.adventure.text.event.HoverEvent;
|
||||
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
|
||||
|
||||
public class AdventureComponentManager implements IComponentManager {
|
||||
|
||||
|
||||
@Override
|
||||
public boolean hasConditions() {
|
||||
try {
|
||||
for (String cl : Arrays.asList("net.kyori.adventure.text.Component", "net.kyori.adventure.text.serializer.gson.GsonComponentSerializer"))
|
||||
Class.forName(cl);
|
||||
Class.forName(cl);
|
||||
} catch (Throwable e) { // can't support this, adventure comp not found
|
||||
ChatItem.debug("Can't load AdventureComponentManager : " + e.getMessage());
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void writeJson(ChatItemPacket packet, String json) {}
|
||||
|
||||
@Override
|
||||
public String getBaseComponentAsJSON(ChatItemPacket packet) {
|
||||
public void writeJson(ChatItemPacket packet, String json) {
|
||||
}
|
||||
|
||||
public void writeComponentToPacket(ChatItemPacket packet, Component next) {
|
||||
if(packet.getContent().getSpecificModifier(Component.class).readSafely(0) == null && ReflectionUtils.hasObject(packet.getPacket(), "unsignedContent")) { // hard way
|
||||
ReflectionUtils.setField(ReflectionUtils.getObject(packet.getPacket(), "unsignedContent"), "adventure", next);
|
||||
} else { // easy way
|
||||
packet.getContent().getSpecificModifier(Component.class).write(0, next);
|
||||
}
|
||||
}
|
||||
|
||||
public Component getComponentFromPacket(ChatItemPacket packet) {
|
||||
Component comp = packet.getContent().getSpecificModifier(Component.class).readSafely(0);
|
||||
if (comp == null)
|
||||
if (comp == null && packet.getPacketName().equalsIgnoreCase("ClientboundPlayerChatPacket") && ReflectionUtils.hasObject(packet.getPacket(), "unsignedContent")) { // if can get one more
|
||||
comp = (Component) ReflectionUtils.getObject(ReflectionUtils.getObject(packet.getPacket(), "unsignedContent"), "adventure");
|
||||
}
|
||||
return comp;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getBaseComponentAsJSON(ChatItemPacket packet) {
|
||||
Component comp = getComponentFromPacket(packet);
|
||||
if(comp == null) // if comp stay null
|
||||
return null;
|
||||
try {
|
||||
String json = GsonComponentSerializer.gson().serialize(comp);
|
||||
JsonObject jsonObj = JsonParser.parseString(json).getAsJsonObject();
|
||||
ChatItem.debug("AdventureJSON : " + json);
|
||||
JsonObject jsonObj = JSONManipulator.parseOrGet(json);
|
||||
if (jsonObj.has("with")) {
|
||||
JsonObject next = new JsonObject();
|
||||
next.add("extra", jsonObj.get("with"));
|
||||
@@ -61,64 +79,54 @@ public class AdventureComponentManager implements IComponentManager {
|
||||
}
|
||||
return json;
|
||||
} catch (JsonParseException e) { // ignore this and just let skip this
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
@Override
|
||||
public Object manageItem(Player p, Chat chat, ChatItemPacket packet, ItemStack item, Storage c) throws Exception {
|
||||
String itemName = ChatManager.getNameOfItem(chat.getPlayer(), item, c);
|
||||
return manage(p, chat, packet, itemName, HoverEvent.showItem(Key.key(item.getType().getKey().getKey()), item.getAmount(), BinaryTagHolder.of(PacketUtils.getNbtTag(item))));
|
||||
public Object manageContent(Player viewer, Chat chat, ChatItemPacket packet, String json, Storage c) throws Exception {
|
||||
ChatAction action = chat.getAction();
|
||||
if (action.isItem()) {
|
||||
ItemStack item = action.getItem();
|
||||
String itemName = ChatManager.getNameForChatAction(viewer, chat, c);
|
||||
ChatItem.debug("NBT tag: " + PacketUtils.getNbtTag(item));
|
||||
HoverEvent<?> hover;
|
||||
if(Utils.IS_PAPER)
|
||||
hover = item.asHoverEvent();
|
||||
else
|
||||
hover = HoverEvent.showItem(Key.key(item.getType().getKey().getKey()), item.getAmount(), BinaryTagHolder.of(PacketUtils.getNbtTag(item)));
|
||||
return manage(viewer, chat, packet, itemName, hover, null);
|
||||
}
|
||||
return manage(viewer, chat, packet, Messages.getMessage(action.getSlot().name().toLowerCase() + ".chat", "%cible%", chat.getPlayer().getName()),
|
||||
HoverEvent.showText(Component.text(Messages.getMessage(action.getSlot().name().toLowerCase() + ".hover", "%cible%", chat.getPlayer().getName()))),
|
||||
ClickEvent.runCommand(action.getCommand()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object manageEmpty(Player p, Chat chat, ChatItemPacket packet, Storage c) {
|
||||
public Object manageEmpty(Player viewer, Chat chat, ChatItemPacket packet, String json, Storage c) {
|
||||
Component builder = Component.text("");
|
||||
c.tooltipHand.forEach(s -> builder.append(Component.text(s)));
|
||||
Player sender = chat.getPlayer();
|
||||
String handName = c.handName.replace("{name}", sender.getName()).replace("{display-name}", sender.getDisplayName());
|
||||
return manage(p, chat, packet, handName, HoverEvent.showText(builder));
|
||||
ChatAction action = chat.getAction();
|
||||
if (action.isItem()) {
|
||||
return manage(viewer, chat, packet, ChatManager.getNameForChatAction(viewer, chat, c), HoverEvent.showText(builder), null);
|
||||
}
|
||||
return manage(viewer, chat, packet, Messages.getMessage(action.getSlot().name().toLowerCase() + ".chat", "%cible%", chat.getPlayer().getName()),
|
||||
HoverEvent.showText(Component.text(Messages.getMessage(action.getSlot().name().toLowerCase() + ".hover", "%cible%", chat.getPlayer().getName()))),
|
||||
ClickEvent.runCommand(action.getCommand()));
|
||||
}
|
||||
|
||||
private Object manage(Player p, Chat chat, ChatItemPacket packet, String replacement, HoverEvent<?> hover) {
|
||||
ContentModifier<Component> modifier = packet.getContent().getSpecificModifier(Component.class);
|
||||
Component comp = modifier.readSafely(0);
|
||||
private Object manage(Player viewer, Chat chat, ChatItemPacket packet, String replacement, HoverEvent<?> hover, ClickEvent click) {
|
||||
Component comp = getComponentFromPacket(packet);
|
||||
if (comp == null) {
|
||||
ChatItem.debug("The component is null.");
|
||||
return null;
|
||||
}
|
||||
comp = checkComponent(comp, hover, replacement, chat);
|
||||
ChatItem.debug("Result: " + GsonComponentSerializer.gson().serialize(comp));
|
||||
try {
|
||||
packet.setPacket(PacketEditingChatManager.createSystemChatPacket(GsonComponentSerializer.gson().serialize(comp)));
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return packet.getPacket();
|
||||
}
|
||||
|
||||
private Component checkComponent(Component comp, HoverEvent<?> hover, String itemName, Chat chat) {
|
||||
if (comp instanceof TextComponent) {
|
||||
TextComponent tc = (TextComponent) comp;
|
||||
if (ChatManager.containsSeparator(tc.content())) {
|
||||
ChatItem.debug("Changing text " + tc.content() + " to " + itemName);
|
||||
comp = tc.content(ChatManager.replaceSeparator(chat, tc.content(), itemName)).hoverEvent(hover);
|
||||
} else
|
||||
ChatItem.debug("No insert of text without separator: " + tc.content());
|
||||
} else if(comp instanceof TranslatableComponent) {
|
||||
TranslatableComponent tc = (TranslatableComponent) comp;
|
||||
List<Component> next = new ArrayList<>();
|
||||
for (Component extra : tc.args()) {
|
||||
next.add(checkComponent(extra, hover, itemName, chat));
|
||||
}
|
||||
comp = tc.args(next);
|
||||
} else
|
||||
ChatItem.debug("Not valid comp class " + comp.getClass().getSimpleName() + " : " + comp);
|
||||
List<Component> next = new ArrayList<>();
|
||||
for (Component extra : comp.children()) {
|
||||
next.add(checkComponent(extra, hover, itemName, chat));
|
||||
}
|
||||
return comp.children(next);
|
||||
comp = comp.replaceText(TextReplacementConfig.builder().matchLiteral(ChatManager.SEPARATOR + "" + chat.getId() + ChatManager.SEPARATOR_END).replacement(Component.text(replacement).hoverEvent(hover).clickEvent(click)).build());
|
||||
if(ChatItem.discordSrvSupport && DiscordSrvSupport.isSendingMessage() && viewer == chat.getPlayer())
|
||||
DiscordSrvSupport.sendChatMessage(chat.getPlayer(), comp, null);
|
||||
viewer.sendMessage(comp);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+15
-5
@@ -1,23 +1,29 @@
|
||||
package me.dadus33.chatitem.chatmanager.v1.basecomp.hook;
|
||||
|
||||
import com.google.gson.JsonParser;
|
||||
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
import me.dadus33.chatitem.chatmanager.v1.PacketEditingChatManager;
|
||||
import me.dadus33.chatitem.chatmanager.v1.basecomp.IComponentManager;
|
||||
import me.dadus33.chatitem.chatmanager.v1.packets.ChatItemPacket;
|
||||
import me.dadus33.chatitem.utils.PacketUtils;
|
||||
import me.dadus33.chatitem.hook.DiscordSrvSupport;
|
||||
|
||||
public class ComponentNMSManager implements IComponentManager {
|
||||
|
||||
@Override
|
||||
public boolean hasConditions() {
|
||||
return PacketUtils.COMPONENT_CLASS != null;
|
||||
return ChatItem.getPlatform().hasBaseComponentSerializer();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getBaseComponentAsJSON(ChatItemPacket packet) {
|
||||
Object chatBaseComp = packet.getContent().getSpecificModifier(PacketUtils.COMPONENT_CLASS).readSafely(0);
|
||||
Object chatBaseComp = packet.getContent().getChatComponents().readSafely(0);
|
||||
if (chatBaseComp != null) {
|
||||
try {
|
||||
return PacketUtils.CHAT_SERIALIZER.getMethod("a", PacketUtils.COMPONENT_CLASS).invoke(null, chatBaseComp).toString();
|
||||
Object o = ChatItem.getPlatform().baseComponentToJson(chatBaseComp);
|
||||
if(o != null && o instanceof String && JsonParser.parseString((String) o).isJsonObject()) {
|
||||
return (String) o;
|
||||
}
|
||||
} catch (Exception exc) {
|
||||
exc.printStackTrace();
|
||||
}
|
||||
@@ -27,8 +33,12 @@ public class ComponentNMSManager implements IComponentManager {
|
||||
|
||||
@Override
|
||||
public void writeJson(ChatItemPacket packet, String json) {
|
||||
// Not compatible with that for now
|
||||
if(ChatItem.discordSrvSupport && DiscordSrvSupport.isSendingMessage())
|
||||
ChatItem.debug("(v1 ComponentNMS) Can't send message to discord");
|
||||
// DiscordSrvSupport.sendChatMessage(p, comp, null);
|
||||
try {
|
||||
packet.setPacket(PacketEditingChatManager.createSystemChatPacket(json));
|
||||
packet.setPacket(PacketEditingChatManager.createSystemChatPacket(json, packet.getPacket()));
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
+3
-25
@@ -1,44 +1,22 @@
|
||||
package me.dadus33.chatitem.chatmanager.v1.basecomp.hook;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
import me.dadus33.chatitem.chatmanager.v1.PacketEditingChatManager;
|
||||
import me.dadus33.chatitem.chatmanager.v1.basecomp.IComponentManager;
|
||||
import me.dadus33.chatitem.chatmanager.v1.packets.ChatItemPacket;
|
||||
import me.dadus33.chatitem.utils.PacketUtils;
|
||||
|
||||
public class IChatBaseComponentManager implements IComponentManager {
|
||||
|
||||
private Method serializerGetJson;
|
||||
|
||||
public IChatBaseComponentManager() {
|
||||
try {
|
||||
Class<?> chatSerializer = PacketUtils.CHAT_SERIALIZER;
|
||||
//fromJson = chatSerializer.getMethod("a", String.class);
|
||||
for (Method m : chatSerializer.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: " + chatSerializer.getCanonicalName());
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasConditions() {
|
||||
return serializerGetJson != null;
|
||||
return ChatItem.getPlatform().hasBaseComponentSerializer();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getBaseComponentAsJSON(ChatItemPacket packet) {
|
||||
try {
|
||||
Object obj = packet.getContent().getChatComponents().readSafely(0);
|
||||
return obj == null ? null : (String) serializerGetJson.invoke(null, obj);
|
||||
return obj == null ? null : (String) ChatItem.getPlatform().baseComponentToJson(obj);
|
||||
} catch (Exception exc) {
|
||||
exc.printStackTrace();
|
||||
}
|
||||
@@ -48,7 +26,7 @@ public class IChatBaseComponentManager implements IComponentManager {
|
||||
@Override
|
||||
public void writeJson(ChatItemPacket packet, String json) {
|
||||
try {
|
||||
packet.setPacket(PacketEditingChatManager.createSystemChatPacket(json));
|
||||
packet.setPacket(PacketEditingChatManager.createSystemChatPacket(json, packet.getPacket()));
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
+2
-2
@@ -33,7 +33,7 @@ public class PCMComponentManager implements IComponentManager {
|
||||
Object chatBaseComp = ReflectionUtils.getMethod(pcmClass, PacketUtils.COMPONENT_CLASS).invoke(pcm);
|
||||
if(chatBaseComp != null)
|
||||
ChatItem.debug("[PCMManager] Founded " + chatBaseComp.getClass().getSimpleName());
|
||||
return chatBaseComp == null ? null : PacketUtils.CHAT_SERIALIZER.getMethod("a", PacketUtils.COMPONENT_CLASS).invoke(null, chatBaseComp).toString();
|
||||
return chatBaseComp == null ? null : ChatItem.getPlatform().baseComponentToJson(chatBaseComp);
|
||||
} catch (Exception exc) {
|
||||
exc.printStackTrace();
|
||||
}
|
||||
@@ -44,7 +44,7 @@ public class PCMComponentManager implements IComponentManager {
|
||||
@Override
|
||||
public void writeJson(ChatItemPacket packet, String json) {
|
||||
try {
|
||||
Object chatComp = PacketUtils.CHAT_SERIALIZER.getMethod("a", String.class).invoke(null, json);
|
||||
Object chatComp = ChatItem.getPlatform().jsonToBaseComponent(json);
|
||||
Class<?> pcmClass = PacketUtils.getNmsClass("PlayerChatMessage", "network.chat.");
|
||||
ContentModifier<Object> pcmModifier = packet.getContent().getSpecificModifier((Class<Object>) pcmClass);
|
||||
Object pcm = ReflectionUtils.getMethod(pcmClass, pcmClass, PacketUtils.COMPONENT_CLASS).invoke(pcmModifier.readSafely(0), chatComp);
|
||||
|
||||
+37
-13
@@ -3,7 +3,6 @@ package me.dadus33.chatitem.chatmanager.v1.basecomp.hook;
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonElement;
|
||||
@@ -13,12 +12,16 @@ import com.google.gson.JsonParser;
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
import me.dadus33.chatitem.Storage;
|
||||
import me.dadus33.chatitem.chatmanager.Chat;
|
||||
import me.dadus33.chatitem.chatmanager.ChatAction;
|
||||
import me.dadus33.chatitem.chatmanager.ChatManager;
|
||||
import me.dadus33.chatitem.chatmanager.v1.PacketEditingChatManager;
|
||||
import me.dadus33.chatitem.chatmanager.v1.basecomp.IComponentManager;
|
||||
import me.dadus33.chatitem.chatmanager.v1.packets.ChatItemPacket;
|
||||
import me.dadus33.chatitem.hook.DiscordSrvSupport;
|
||||
import me.dadus33.chatitem.utils.Messages;
|
||||
import me.dadus33.chatitem.utils.Utils;
|
||||
import net.md_5.bungee.api.chat.BaseComponent;
|
||||
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;
|
||||
@@ -53,27 +56,43 @@ public class StringComponentManager implements IComponentManager {
|
||||
@Override
|
||||
public void writeJson(ChatItemPacket packet, String json) {
|
||||
try {
|
||||
packet.setPacket(PacketEditingChatManager.createSystemChatPacket(json));
|
||||
packet.setPacket(PacketEditingChatManager.createSystemChatPacket(json, packet.getPacket()));
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object manageItem(Player p, Chat chat, ChatItemPacket packet, ItemStack item, Storage c) throws Exception {
|
||||
return manage(p, chat, packet, ChatManager.getNameOfItem(chat.getPlayer(), item, c), Utils.createItemHover(item));
|
||||
public Object manageContent(Player viewer, Chat chat, ChatItemPacket packet, String json, Storage c) throws Exception {
|
||||
ChatAction action = chat.getAction();
|
||||
if (action.isItem())
|
||||
return manage(viewer, chat, packet, ChatManager.getNameForChatAction(viewer, chat, c), Utils.createItemHover(action.getItem(), viewer), null);
|
||||
else
|
||||
return manage(viewer, chat, packet, ChatManager.getNameForChatAction(viewer, chat, c),
|
||||
Utils.createTextHover(Messages.getMessage(action.getSlot().name().toLowerCase() + ".hover", "%cible%", chat.getPlayer().getName())), Utils.createRunCommand(action.getCommand()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object manageEmpty(Player p, Chat chat, ChatItemPacket packet, Storage c) {
|
||||
public Object manageEmpty(Player viewer, Chat chat, ChatItemPacket packet, String json, Storage c) {
|
||||
ComponentBuilder builder = new ComponentBuilder("");
|
||||
c.tooltipHand.forEach(s -> builder.append(s));
|
||||
Player sender = chat.getPlayer();
|
||||
String handName = c.handName.replace("{name}", sender.getName()).replace("{display-name}", sender.getDisplayName());
|
||||
return manage(p, chat, packet, handName, Utils.createTextHover(builder.create()));
|
||||
HoverEvent hover;
|
||||
ClickEvent click;
|
||||
String rep;
|
||||
ChatAction action = chat.getAction();
|
||||
if (action.isItem()) {
|
||||
hover = Utils.createTextHover(builder.create());
|
||||
rep = ChatManager.getHandName(chat);
|
||||
click = null;
|
||||
} else {
|
||||
hover = Utils.createTextHover(Messages.getMessage(action.getSlot().name().toLowerCase() + ".hover", "%cible%", chat.getPlayer().getName()));
|
||||
rep = Messages.getMessage(action.getSlot().name().toLowerCase() + ".chat", "%cible%", chat.getPlayer().getName());
|
||||
click = Utils.createRunCommand(action.getCommand());
|
||||
}
|
||||
return manage(viewer, chat, packet, rep, hover, click);
|
||||
}
|
||||
|
||||
private Object manage(Player p, Chat chat, ChatItemPacket packet, String replacement, HoverEvent hover) {
|
||||
private Object manage(Player viewer, Chat chat, ChatItemPacket packet, String replacement, HoverEvent hover, ClickEvent click) {
|
||||
BaseComponent[] components = packet.getContent().getSpecificModifier(BaseComponent[].class).readSafely(0);
|
||||
if (components == null) {
|
||||
String json = packet.getContent().getStrings().readSafely(0);
|
||||
@@ -101,16 +120,19 @@ public class StringComponentManager implements IComponentManager {
|
||||
}
|
||||
}
|
||||
ChatItem.debug("Checking for " + components.length + " components");
|
||||
Arrays.asList(components).forEach(comp -> checkComponent(comp, hover, replacement, chat));
|
||||
Arrays.asList(components).forEach(comp -> checkComponent(comp, hover, click, replacement, chat));
|
||||
|
||||
if (ChatItem.discordSrvSupport && DiscordSrvSupport.isSendingMessage() && viewer == chat.getPlayer())
|
||||
DiscordSrvSupport.sendChatMessage(viewer, TextComponent.toLegacyText(components), null);
|
||||
try {
|
||||
packet.setPacket(PacketEditingChatManager.createSystemChatPacket(ComponentSerializer.toString(components)));
|
||||
packet.setPacket(PacketEditingChatManager.createSystemChatPacket(ComponentSerializer.toString(components), packet.getPacket()));
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return packet.getPacket();
|
||||
}
|
||||
|
||||
private void checkComponent(BaseComponent comp, HoverEvent hover, String itemName, Chat chat) {
|
||||
private void checkComponent(BaseComponent comp, HoverEvent hover, ClickEvent click, String itemName, Chat chat) {
|
||||
if (comp instanceof TextComponent) {
|
||||
TextComponent tc = (TextComponent) comp;
|
||||
if (ChatManager.containsSeparator(tc.getText())) {
|
||||
@@ -118,12 +140,14 @@ public class StringComponentManager implements IComponentManager {
|
||||
ChatItem.debug("Changing text " + oldText + " to " + itemName + ", extra: " + (tc.getExtra() == null ? "-" : tc.getExtra().size()));
|
||||
tc.setText(ChatManager.replaceSeparator(chat, oldText, itemName));
|
||||
tc.setHoverEvent(hover);
|
||||
if (click != null)
|
||||
tc.setClickEvent(click);
|
||||
} else
|
||||
ChatItem.debug("No insert of text without separator: " + tc.getText() + " (legacy: " + tc.toLegacyText() + ")");
|
||||
}
|
||||
if (comp.getExtra() != null) {
|
||||
for (BaseComponent extra : comp.getExtra()) {
|
||||
checkComponent(extra, hover, itemName, chat);
|
||||
checkComponent(extra, hover, click, itemName, chat);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,15 +4,8 @@ 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.Arrays;
|
||||
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;
|
||||
|
||||
@@ -24,10 +17,11 @@ import com.google.gson.JsonPrimitive;
|
||||
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
import me.dadus33.chatitem.chatmanager.Chat;
|
||||
import me.dadus33.chatitem.chatmanager.ChatAction;
|
||||
import me.dadus33.chatitem.chatmanager.ChatManager;
|
||||
import me.dadus33.chatitem.utils.Messages;
|
||||
import me.dadus33.chatitem.utils.PacketUtils;
|
||||
import me.dadus33.chatitem.utils.ReflectionUtils;
|
||||
import me.dadus33.chatitem.utils.Version;
|
||||
|
||||
public class JSONManipulator {
|
||||
|
||||
@@ -37,75 +31,93 @@ public class JSONManipulator {
|
||||
return instance;
|
||||
}
|
||||
|
||||
private static final List<String> SKIPPED = Arrays.asList("HSTRY_ENCHANTS");
|
||||
|
||||
public static final Class<?> CRAFT_ITEM_STACK_CLASS = PacketUtils.getObcClass("inventory.CraftItemStack");
|
||||
public static final Class<?> NMS_ITEM_STACK_CLASS = getNmsClass("ItemStack", "world.item.");
|
||||
public static final Method AS_NMS_COPY = ReflectionUtils.getMethod(CRAFT_ITEM_STACK_CLASS, "asNMSCopy", ItemStack.class);
|
||||
public static final Class<?> NBT_TAG_COMPOUND = getNmsClass("NBTTagCompound", "nbt.");
|
||||
public static final Class<?> NBT_TAG_COMPOUND = getNmsClass("NBTTagCompound", "nbt.", "CompoundTag");
|
||||
public static final Method SAVE_NMS_ITEM_STACK_METHOD = ReflectionUtils.getMethod(NMS_ITEM_STACK_CLASS, NBT_TAG_COMPOUND, NBT_TAG_COMPOUND);
|
||||
public static final Field MAP = ReflectionUtils.getField(NBT_TAG_COMPOUND, "map", "x");
|
||||
|
||||
private static final ConcurrentHashMap<Map.Entry<Version, ItemStack>, JsonObject> STACKS = new ConcurrentHashMap<>();
|
||||
|
||||
private JsonObject itemTooltip;
|
||||
private JsonArray classicTooltip;
|
||||
|
||||
public static JsonObject parseOrGet(String json) {
|
||||
if(json.startsWith("\"") && json.endsWith("\"")) {// seems to be simple line
|
||||
return JsonParser.parseString("{\"text\":" + json + "}").getAsJsonObject();
|
||||
}
|
||||
try {
|
||||
return JsonParser.parseString(json).getAsJsonObject();
|
||||
} catch (Exception e) {
|
||||
JsonObject obj = new JsonObject();
|
||||
obj.addProperty("text", json);
|
||||
return obj;
|
||||
}
|
||||
}
|
||||
|
||||
public String parse(Chat chat, String json, ItemStack item, String replacement, int protocol) throws Exception {
|
||||
JsonObject obj = JsonParser.parseString(json).getAsJsonObject();
|
||||
final AbstractMap.SimpleEntry<Version, ItemStack> p = new AbstractMap.SimpleEntry<>(Version.getVersion(protocol), item);
|
||||
public String parse(Chat chat, String json, ChatAction action, String replacement) throws Exception {
|
||||
JsonObject obj = parseOrGet(json);
|
||||
|
||||
JsonObject wrapper = new JsonObject(); // Create a wrapper object for the whole array
|
||||
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();
|
||||
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();
|
||||
if (action.isItem()) {
|
||||
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(item));
|
||||
String item = ChatItem.getPlatform().stringifyItem(action.getItem());
|
||||
hover.addProperty("value", item);
|
||||
hover.add("contents", parseOrGet(item));
|
||||
} else {
|
||||
hover.addProperty("action", "show_text");
|
||||
|
||||
if (use.size() == 1) {
|
||||
JsonElement extraElement = use.get(0);
|
||||
if (extraElement.isJsonPrimitive())
|
||||
wrapper.addProperty("text", extraElement.getAsString());
|
||||
else if (extraElement.isJsonObject())
|
||||
wrapper.addProperty("text", extraElement.getAsJsonObject().get("text").getAsString());
|
||||
else
|
||||
wrapper.add("extra", use); // add it only if
|
||||
} else if (!use.isEmpty())
|
||||
// Get the JSON representation of the item (well, not really JSON, but rather a
|
||||
// string representation of NBT data)
|
||||
JsonArray hoverArray = new JsonArray();
|
||||
hoverArray.add(Messages.getMessage(action.getSlot().name().toLowerCase() + ".hover", "%cible%", chat.getItemPlayer().getPlayer().getName()));
|
||||
hover.add("value", hoverArray);
|
||||
|
||||
JsonObject click = new JsonObject();
|
||||
click.addProperty("action", "run_command");
|
||||
click.addProperty("value", action.getCommand());
|
||||
wrapper.add("clickEvent", click);
|
||||
}
|
||||
|
||||
if (use.size() == 1) {
|
||||
JsonElement extraElement = use.get(0);
|
||||
if (extraElement.isJsonPrimitive())
|
||||
wrapper.addProperty("text", extraElement.getAsString());
|
||||
else if (extraElement.isJsonObject())
|
||||
wrapper.addProperty("text", extraElement.getAsJsonObject().get("text").getAsString());
|
||||
else
|
||||
wrapper.add("extra", use); // add it only if
|
||||
if (!wrapper.has("text"))
|
||||
wrapper.addProperty("text", ""); // The text field is compulsory, even if it's empty
|
||||
wrapper.add("hoverEvent", hover);
|
||||
} else if (!use.isEmpty())
|
||||
wrapper.add("extra", use); // add it only if
|
||||
if (!wrapper.has("text"))
|
||||
wrapper.addProperty("text", ""); // The text field is compulsory, even if it's empty
|
||||
ChatItem.debug("Wrapper " + wrapper + " > " + 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);
|
||||
}
|
||||
if (obj.size() == 1 && obj.has("text")) {
|
||||
itemTooltip.add("text", obj.get("text"));
|
||||
ChatItem.debug("[JsonManipulator] Parsed quick: " + obj.toString() + ", wrapper: " + itemTooltip);
|
||||
return ChatManager.replaceSeparator(chat, itemTooltip.toString(), replacement);
|
||||
wrapper.add("text", obj.get("text"));
|
||||
ChatItem.debug("[JsonManipulator] Parsed quick: " + obj.toString() + ", wrapper: " + wrapper);
|
||||
return ChatManager.replaceSeparator(chat, wrapper.toString(), replacement);
|
||||
}
|
||||
obj.add("extra", parseArray(obj.has("extra") ? obj.getAsJsonArray("extra") : new JsonArray(), itemTooltip));
|
||||
obj.add("extra", parseArray(obj.has("extra") ? obj.getAsJsonArray("extra") : new JsonArray(), wrapper));
|
||||
if (!obj.has("text")) {
|
||||
obj.addProperty("text", "");
|
||||
}
|
||||
ChatItem.debug("Parsed array for item: " + obj.toString() + ", wrapper: " + itemTooltip);
|
||||
return obj.toString();
|
||||
}
|
||||
|
||||
public String parseEmpty(String json, String repl, List<String> tooltip, Player sender) {
|
||||
JsonObject obj = JsonParser.parseString(json).getAsJsonObject();
|
||||
@SuppressWarnings("deprecation")
|
||||
public String parseEmpty(Chat chat, String json, List<String> tooltip, Player sender) {
|
||||
JsonObject obj = parseOrGet(json);
|
||||
JsonArray array = obj.has("extra") ? obj.getAsJsonArray("extra") : new JsonArray();
|
||||
JsonArray use = Translator.toJson(repl.replace("{name}", sender.getName()).replace("{display-name}", sender.getDisplayName()));
|
||||
JsonArray use = Translator.toJson(ChatManager.getNameForChatAction(chat.getPlayer(), chat, ChatItem.getInstance().getStorage()).replace("{name}", sender.getName()).replace("{display-name}", sender.getDisplayName()));
|
||||
JsonObject hover = JsonParser.parseString("{\"action\":\"show_text\", \"value\": \"\"}").getAsJsonObject();
|
||||
|
||||
StringBuilder oneLineTooltip = new StringBuilder("");
|
||||
@@ -133,28 +145,37 @@ public class JSONManipulator {
|
||||
|
||||
private JsonArray parseArray(JsonArray arr, JsonElement tooltip) {
|
||||
JsonArray replacer = new JsonArray();
|
||||
boolean isComplex = false;
|
||||
boolean separator = false;
|
||||
for (int i = 0; i < arr.size(); ++i) {
|
||||
JsonElement element = arr.get(i);
|
||||
if (element.isJsonNull()) {
|
||||
if(element.isJsonNull())
|
||||
continue;
|
||||
} else if (element.isJsonObject()) {
|
||||
isComplex = true;
|
||||
if(separator) {
|
||||
if(ChatManager.containsSeparatorEnd(element.toString()))
|
||||
separator = false;
|
||||
continue;
|
||||
}
|
||||
if (element.isJsonObject()) {
|
||||
JsonElement text = element.getAsJsonObject().get("text");
|
||||
if(text != null && ChatManager.containsSeparator(text.getAsString())) {
|
||||
if(!ChatManager.containsSeparatorEnd(text.getAsString())) // if the separator doesn't end in the same string as it's begin
|
||||
separator = true;
|
||||
}
|
||||
ChatItem.debug("Parsing object " + element.toString());
|
||||
addParsedJsonObjectToArray(element.getAsJsonObject(), replacer, tooltip);
|
||||
} else if (element.isJsonArray()) {
|
||||
isComplex = true;
|
||||
JsonArray jar = element.getAsJsonArray();
|
||||
if (jar.size() != 0) {
|
||||
jar = parseArray(element.getAsJsonArray(), tooltip);
|
||||
replacer.set(i, jar);
|
||||
}
|
||||
} else if (element.isJsonPrimitive() && isComplex) {
|
||||
ChatItem.debug("[JSONManipulator] Put " + element + " to trash as it's primitive with complex things");
|
||||
// ignore
|
||||
} else {
|
||||
addParsedStringToArray(element.getAsString(), replacer, element, tooltip);
|
||||
} else if(element.isJsonPrimitive()) {
|
||||
if(ChatManager.containsSeparator(element.getAsString())) {
|
||||
if(!ChatManager.containsSeparatorEnd(element.getAsString())) // if the separator doesn't end in the same string as it's begin
|
||||
separator = true;
|
||||
addParsedStringToArray(element.getAsString(), replacer, element, tooltip);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
return replacer;
|
||||
}
|
||||
@@ -198,17 +219,23 @@ public class JSONManipulator {
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
ChatItem.debug("[JSONManipulator] Parsed string " + msg + ", rep: " + rep);
|
||||
String current = "";
|
||||
boolean wasSep = false;
|
||||
for (String parts : msg.split("")) {
|
||||
if (ChatManager.equalsSeparator(parts)) {
|
||||
if (!current.isEmpty()) {
|
||||
rep.add(current);
|
||||
if(o.isJsonObject()) {
|
||||
JsonObject jsonObj = o.getAsJsonObject().deepCopy();
|
||||
jsonObj.addProperty("text", current); // edit text
|
||||
rep.add(jsonObj); // add with all basic coloring things
|
||||
} else {
|
||||
rep.add(current);
|
||||
}
|
||||
current = "";
|
||||
}
|
||||
rep.add(tooltip);
|
||||
@@ -220,74 +247,14 @@ public class JSONManipulator {
|
||||
current += parts;
|
||||
}
|
||||
}
|
||||
if (!current.isEmpty())
|
||||
rep.add(current);
|
||||
}
|
||||
|
||||
public static String stringifyItem(ItemStack is) {
|
||||
try {
|
||||
return stringifyItemInternal(is);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return "{}";
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings({ "deprecation" })
|
||||
public static String stringifyItemInternal(ItemStack is) throws Exception {
|
||||
Object nmsStack = JSONManipulator.AS_NMS_COPY.invoke(null, is);
|
||||
Object nmsTag = JSONManipulator.NBT_TAG_COMPOUND.newInstance();
|
||||
JSONManipulator.SAVE_NMS_ITEM_STACK_METHOD.invoke(nmsStack, nmsTag);
|
||||
HashMap<String, String> tagMap = new HashMap<>();
|
||||
Map<String, Object> nmsMap = (Map<String, Object>) JSONManipulator.MAP.get(nmsTag);
|
||||
String id = nmsMap.get("id").toString().replace("\"", "");
|
||||
Object realTag = nmsMap.get("tag");
|
||||
if (JSONManipulator.NBT_TAG_COMPOUND.isInstance(realTag)) { // We need to make sure this is indeed an
|
||||
// NBTTagCompound
|
||||
Map<String, Object> realMap = (Map<String, Object>) JSONManipulator.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());
|
||||
if (!current.isEmpty()) {
|
||||
if(o.isJsonObject()) {
|
||||
JsonObject jsonObj = o.getAsJsonObject().deepCopy();
|
||||
jsonObj.addProperty("text", current); // edit text
|
||||
rep.add(jsonObj); // add with all basic coloring things
|
||||
} else {
|
||||
rep.add(current);
|
||||
}
|
||||
}
|
||||
// TODO check for ID remapping
|
||||
// ItemRewriter.remapIds(Version.getVersion().MAX_VER, protocolVersion.MAX_VER,
|
||||
// is);
|
||||
StringBuilder sb = new StringBuilder("{id:");
|
||||
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 (SKIPPED.contains(entry.getKey()))
|
||||
continue;
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -46,10 +46,12 @@ public class Translator {
|
||||
if(!text.isEmpty()) // ignore this if no text before
|
||||
text += ColorManager.getColorString(colorCode);
|
||||
colorCode = "x";
|
||||
} else if(!colorCode.isEmpty() && !colorCode.startsWith("x")) { // already color and not hex
|
||||
text += ColorManager.COLOR_CHAR + colorCode; // add the color to text
|
||||
colorCode = args + "";
|
||||
} 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());
|
||||
@@ -58,20 +60,21 @@ public class Translator {
|
||||
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"
|
||||
} 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);
|
||||
ChatItem.debug("[Translator] Add color code " + colorCode + " to " + text + args + ", msg: " + message);
|
||||
colorCode = "";
|
||||
}
|
||||
// basic text, not waiting for code after '§'
|
||||
text += args;
|
||||
}
|
||||
}
|
||||
if(!text.isEmpty() || message.isEmpty()) {
|
||||
if(!next.has("color") || colorCode.length() == 1) // if no color or a color that can override it
|
||||
next.addProperty("color", (colorCode.length() == 1 ? ColorManager.getColor(colorCode).getName() : "white"));
|
||||
if(!text.isEmpty() || message.isEmpty() || next.size() > 0) {
|
||||
next.addProperty("text", text);
|
||||
if(!next.has("color"))
|
||||
next.addProperty("color", "white");
|
||||
ChatItem.debug("[Translator] Added content " + next + " to message" + message);
|
||||
message.add(next);
|
||||
}
|
||||
return message;
|
||||
|
||||
@@ -1,72 +0,0 @@
|
||||
package me.dadus33.chatitem.chatmanager.v1.listeners;
|
||||
|
||||
import static me.dadus33.chatitem.chatmanager.ChatManager.SEPARATOR;
|
||||
import static me.dadus33.chatitem.chatmanager.ChatManager.SEPARATOR_END;
|
||||
|
||||
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.Storage;
|
||||
import me.dadus33.chatitem.chatmanager.Chat;
|
||||
import me.dadus33.chatitem.chatmanager.ChatManager;
|
||||
import me.dadus33.chatitem.chatmanager.v1.PacketEditingChatManager;
|
||||
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(priority = EventPriority.LOWEST)
|
||||
public void onChat(AsyncPlayerChatEvent e) {
|
||||
if(ChatManager.isTestingEnabled() && !ChatManager.isTesting("packet"))
|
||||
return;
|
||||
if (ChatManager.containsSeparator(e.getMessage())) { // If the BELL character is found, we have to remove it
|
||||
e.setMessage(ChatManager.removeSeparator(e.getMessage()));
|
||||
}
|
||||
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().messageLimit.isEmpty())
|
||||
p.sendMessage(getStorage().messageLimit);
|
||||
return;
|
||||
}
|
||||
|
||||
Chat c = Chat.create(p, oldMsg);
|
||||
ChatItem.debug("(v1) Set placeholder to message " + c);
|
||||
e.setMessage(s.replace(firstPlaceholder, SEPARATOR + Integer.toString(c.getId()) + SEPARATOR_END));
|
||||
e.setFormat(e.getFormat().replace(oldMsg, e.getMessage())); // set own message for plugin that already put the message into the format
|
||||
}
|
||||
}
|
||||
+65
-100
@@ -1,15 +1,12 @@
|
||||
package me.dadus33.chatitem.chatmanager.v1.listeners;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
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;
|
||||
@@ -26,7 +23,6 @@ import me.dadus33.chatitem.chatmanager.v1.PacketEditingChatManager;
|
||||
import me.dadus33.chatitem.chatmanager.v1.basecomp.IComponentManager;
|
||||
import me.dadus33.chatitem.chatmanager.v1.basecomp.hook.AdventureComponentManager;
|
||||
import me.dadus33.chatitem.chatmanager.v1.basecomp.hook.ComponentNMSManager;
|
||||
import me.dadus33.chatitem.chatmanager.v1.basecomp.hook.IChatBaseComponentManager;
|
||||
import me.dadus33.chatitem.chatmanager.v1.basecomp.hook.PCMComponentManager;
|
||||
import me.dadus33.chatitem.chatmanager.v1.basecomp.hook.StringComponentManager;
|
||||
import me.dadus33.chatitem.chatmanager.v1.json.JSONManipulator;
|
||||
@@ -41,47 +37,38 @@ import me.dadus33.chatitem.utils.Version;
|
||||
public class ChatPacketManager extends PacketHandler {
|
||||
|
||||
private Object lastSentPacket = null;
|
||||
private Method serializerGetJson;
|
||||
private PacketEditingChatManager manager;
|
||||
private final List<IComponentManager> componentManager = 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 (IComponentManager getter : Arrays.asList(new StringComponentManager(), new IChatBaseComponentManager(), new ComponentNMSManager(), new PCMComponentManager())) {
|
||||
for (IComponentManager getter : Arrays.asList(new StringComponentManager(), new ComponentNMSManager(), new PCMComponentManager())) {
|
||||
tryRegister(getter);
|
||||
}
|
||||
try {
|
||||
if (Class.forName("net.kyori.adventure.text.Component") != null)
|
||||
tryRegister(new AdventureComponentManager());
|
||||
Class.forName("net.kyori.adventure.text.Component");
|
||||
tryRegister(new AdventureComponentManager());
|
||||
} catch (Exception e) {
|
||||
}
|
||||
ChatItem.getInstance().getLogger().info("Loaded " + componentManager.size() + " getter for base components.");
|
||||
ChatItem.debug("ComponentManager: " + String.join(", ", componentManager.stream().map(IComponentManager::getClass).map(Class::getSimpleName).collect(Collectors.toList())));
|
||||
}
|
||||
|
||||
private void tryRegister(IComponentManager getter) {
|
||||
if (getter.hasConditions())
|
||||
componentManager.add(getter);
|
||||
else
|
||||
ChatItem.debug("Component " + getter.getClass().getSimpleName() + " doesn't answer conditions");
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
@Override
|
||||
public void onSend(ChatItemPacket e) {
|
||||
if (!e.hasPlayer() || !e.getPacketType().equals(PacketType.Server.CHAT))
|
||||
return;
|
||||
if(ChatManager.isTestingEnabled() && !ChatManager.isTesting("packet"))
|
||||
if (ChatManager.isTestingEnabled() && !ChatManager.isTesting("packet"))
|
||||
return;
|
||||
if(!ChatManager.isSelected("packet"))
|
||||
return;
|
||||
if (lastSentPacket != null && lastSentPacket == e.getPacket())
|
||||
return; // prevent infinite loop
|
||||
@@ -91,10 +78,6 @@ public class ChatPacketManager extends PacketHandler {
|
||||
String json = "{}";
|
||||
IComponentManager choosedGetter = null;
|
||||
if (version.isNewerOrEquals(Version.V1_19)) {
|
||||
if (packet.getIntegers().readSafely(0, 0) > 1) { // not parsed chat message type
|
||||
ChatItem.debug("Invalid int: " + packet.getIntegers().read(0));
|
||||
return;
|
||||
}
|
||||
choosedGetter = new StringComponentManager();
|
||||
json = choosedGetter.getBaseComponentAsJSON(e); // if null, will be re-checked so anyway
|
||||
} else if (version.isNewerOrEquals(Version.V1_12)) {
|
||||
@@ -103,28 +86,23 @@ public class ChatPacketManager extends PacketHandler {
|
||||
return; // It's an actionbar message, ignoring
|
||||
} else if (version.isNewerOrEquals(Version.V1_8) && packet.getBytes().readSafely(0) == (byte) 2)
|
||||
return; // It's an actionbar message, ignoring
|
||||
if (json == null || choosedGetter == null) {
|
||||
if (json == null || choosedGetter == null || !ChatManager.containsSeparator(json)) {
|
||||
for (IComponentManager getters : componentManager) {
|
||||
String tmpJson = getters.getBaseComponentAsJSON(e);
|
||||
if (tmpJson != null) {
|
||||
json = ChatManager.fixSeparator(tmpJson);
|
||||
choosedGetter = getters;
|
||||
ChatItem.debug("Seems to have one nice manager with " + getters.getClass().getSimpleName() + " (json: " + json + ")");
|
||||
if (ChatManager.containsSeparator(json))
|
||||
break; // be sure it's valid one
|
||||
}
|
||||
} else
|
||||
ChatItem.debug("Null JSON for manager " + getters.getClass().getSimpleName());
|
||||
}
|
||||
}
|
||||
if (json == null || choosedGetter == null) {
|
||||
ChatItem.debug("Can't find valid json getter or json itself");
|
||||
ChatItem.debug("String: " + packet.getStrings().getContent());
|
||||
for (Field f : e.getPacket().getClass().getDeclaredFields()) {
|
||||
f.setAccessible(true);
|
||||
try {
|
||||
ChatItem.debug(f.getName() + ": " + f.get(e.getPacket()));
|
||||
} catch (Exception exc) {
|
||||
exc.printStackTrace();
|
||||
}
|
||||
}
|
||||
PacketUtils.printPacketToDebug(e.getPacket());
|
||||
return; // can't find something
|
||||
}
|
||||
if (!ChatManager.containsSeparator(json)) // if the message doesn't contain the BELL separator
|
||||
@@ -140,58 +118,63 @@ public class ChatPacketManager extends PacketHandler {
|
||||
if (getStorage().cooldown > 0 && !itemPlayer.hasPermission("chatitem.ignore-cooldown"))
|
||||
ChatManager.applyCooldown(itemPlayer);
|
||||
IComponentManager getter = choosedGetter;
|
||||
String fjson = json;
|
||||
ChatItem.debug("Final json used: " + fjson);
|
||||
e.setCancelled(true); // We cancel the packet as we're going to resends it anyways
|
||||
Bukkit.getScheduler().runTaskAsynchronously(ChatItem.getInstance(), () -> {
|
||||
CompletableFuture.runAsync(() -> {
|
||||
Player p = e.getPlayer();
|
||||
String message = null;
|
||||
try {
|
||||
ItemStack item = ChatManager.getUsableItem(itemPlayer);
|
||||
if (!ItemUtils.isEmpty(item)) {
|
||||
ItemStack copy = item.clone();
|
||||
|
||||
if (ItemPlayer.getPlayer(p).isBuggedClient()) { // if the guy that will receive it is bugged
|
||||
String act = getStorage().buggedClientAction;
|
||||
List<String> tooltip;
|
||||
if (act.equalsIgnoreCase("tooltip"))
|
||||
tooltip = getStorage().tooltipBuggedClient;
|
||||
else if (act.equalsIgnoreCase("item"))
|
||||
tooltip = ChatManager.getMaxLinesFromItem(p, copy);
|
||||
else if (act.equalsIgnoreCase("show_both")) {
|
||||
tooltip = ChatManager.getMaxLinesFromItem(p, copy);
|
||||
tooltip.addAll(getStorage().tooltipBuggedClient);
|
||||
} else
|
||||
tooltip = new ArrayList<>();
|
||||
message = JSONManipulator.getInstance().parseEmpty(getter.getBaseComponentAsJSON(e), ChatManager.styleItem(p, copy, getStorage()), tooltip, chat.getPlayer());
|
||||
if(message != null) {
|
||||
getter.writeJson(e, message);
|
||||
}
|
||||
lastSentPacket = e.getPacket();
|
||||
}
|
||||
if (copy.hasItemMeta()) {
|
||||
ItemMeta meta = copy.getItemMeta();
|
||||
if (meta instanceof BookMeta) { // filtering written books
|
||||
BookMeta bm = (BookMeta) copy.getItemMeta();
|
||||
bm.setPages(Collections.emptyList());
|
||||
copy.setItemMeta(bm);
|
||||
} else if (meta instanceof BlockStateMeta && Version.getVersion().isNewerOrEquals(Version.V1_9)) { // if it's a block
|
||||
BlockStateMeta bsm = (BlockStateMeta) copy.getItemMeta();
|
||||
if (bsm.hasBlockState() && bsm.getBlockState() instanceof ShulkerBox) {
|
||||
ShulkerBox sb = (ShulkerBox) bsm.getBlockState();
|
||||
for (ItemStack itemInv : sb.getInventory()) {
|
||||
stripData(itemInv);
|
||||
}
|
||||
bsm.setBlockState(sb);
|
||||
if(chat.getAction().isItem()) {
|
||||
ItemStack item = ChatManager.getUsableItem(itemPlayer, chat.getSlot());
|
||||
if (!ItemUtils.isEmpty(item)) {
|
||||
ItemStack copy = item.clone();
|
||||
|
||||
if (ItemPlayer.getPlayer(p).isBuggedClient()) { // if the guy that will receive it is bugged
|
||||
String act = getStorage().buggedClientAction;
|
||||
List<String> tooltip;
|
||||
if (act.equalsIgnoreCase("tooltip"))
|
||||
tooltip = getStorage().tooltipBuggedClient;
|
||||
else if (act.equalsIgnoreCase("item"))
|
||||
tooltip = ChatManager.getMaxLinesFromItem(p, copy);
|
||||
else if (act.equalsIgnoreCase("show_both")) {
|
||||
tooltip = ChatManager.getMaxLinesFromItem(p, copy);
|
||||
tooltip.addAll(getStorage().tooltipBuggedClient);
|
||||
} else
|
||||
tooltip = new ArrayList<>();
|
||||
message = JSONManipulator.getInstance().parseEmpty(chat, fjson, tooltip, chat.getPlayer());
|
||||
if (message != null) {
|
||||
getter.writeJson(e, message);
|
||||
}
|
||||
copy.setItemMeta(bsm);
|
||||
lastSentPacket = e.getPacket();
|
||||
}
|
||||
if (copy.hasItemMeta()) {
|
||||
ItemMeta meta = copy.getItemMeta();
|
||||
if (meta instanceof BookMeta) { // filtering written books
|
||||
BookMeta bm = (BookMeta) copy.getItemMeta();
|
||||
bm.setPages(Collections.emptyList());
|
||||
copy.setItemMeta(bm);
|
||||
} else if (meta instanceof BlockStateMeta && Version.getVersion().isNewerOrEquals(Version.V1_9)) { // if it's a block
|
||||
BlockStateMeta bsm = (BlockStateMeta) copy.getItemMeta();
|
||||
if (bsm.hasBlockState() && bsm.getBlockState() instanceof ShulkerBox) {
|
||||
ShulkerBox sb = (ShulkerBox) bsm.getBlockState();
|
||||
for (ItemStack itemInv : sb.getInventory()) {
|
||||
ItemUtils.stripData(itemInv);
|
||||
}
|
||||
bsm.setBlockState(sb);
|
||||
}
|
||||
copy.setItemMeta(bsm);
|
||||
}
|
||||
}
|
||||
lastSentPacket = getter.manageContent(p, chat, e, fjson, getStorage());
|
||||
} else {
|
||||
if (!getStorage().handDisabled) {
|
||||
lastSentPacket = getter.manageEmpty(p, chat, e, fjson, getStorage());
|
||||
}
|
||||
}
|
||||
lastSentPacket = getter.manageItem(p, chat, e, item, getStorage());
|
||||
} else {
|
||||
if (!getStorage().handDisabled) {
|
||||
lastSentPacket = getter.manageEmpty(p, chat, e, getStorage());
|
||||
}
|
||||
}
|
||||
if (lastSentPacket == null)
|
||||
} else
|
||||
lastSentPacket = getter.manageContent(p, chat, e, fjson, getStorage());
|
||||
if (lastSentPacket == null) // maybe sent by the manager directly
|
||||
ChatItem.debug("(v1) No packet to sent with manager " + getter.getClass().getName());
|
||||
else
|
||||
PacketUtils.sendPacket(p, lastSentPacket);
|
||||
@@ -201,24 +184,6 @@ public class ChatPacketManager extends PacketHandler {
|
||||
});
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
package me.dadus33.chatitem.chatmanager.v1.listeners;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
|
||||
import com.comphenix.protocol.PacketType;
|
||||
import com.comphenix.protocol.events.ListenerPriority;
|
||||
import com.comphenix.protocol.events.PacketAdapter;
|
||||
import com.comphenix.protocol.events.PacketEvent;
|
||||
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
import me.dadus33.chatitem.playerversion.hooks.DefaultVersionHook;
|
||||
import me.dadus33.chatitem.utils.Version;
|
||||
|
||||
public class HandshakeListener extends PacketAdapter {
|
||||
|
||||
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;
|
||||
}
|
||||
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(Version.stringifyAdress(e.getPlayer().getAddress()), version), 10L);
|
||||
}
|
||||
}
|
||||
@@ -22,4 +22,13 @@ public abstract class PacketManager {
|
||||
public void notifyHandlersSent(ChatItemPacket packet) {
|
||||
handlers.forEach((handler) -> handler.onSend(packet));
|
||||
}
|
||||
|
||||
public ChatItemPacket onPacketSent(PacketType type, Player sender, Object packet) {
|
||||
if(type == null) {
|
||||
return null;
|
||||
}
|
||||
ChatItemPacket customPacket = new ChatItemPacket(type, packet, sender);
|
||||
notifyHandlersSent(customPacket);
|
||||
return customPacket;
|
||||
}
|
||||
}
|
||||
+3
-17
@@ -1,8 +1,8 @@
|
||||
package me.dadus33.chatitem.chatmanager.v1.packets.custom;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
@@ -10,13 +10,10 @@ import org.bukkit.event.player.PlayerJoinEvent;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
|
||||
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;
|
||||
|
||||
@@ -32,18 +29,16 @@ public class CustomPacketManager extends PacketManager implements Listener {
|
||||
Version version = Version.getVersion();
|
||||
if (version.isNewerOrEquals(Version.V1_17))
|
||||
channel = new INC2Channel(this);
|
||||
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, () -> {
|
||||
CompletableFuture.runAsync(() -> {
|
||||
isStarted = true;
|
||||
for(Player p : Utils.getOnlinePlayers())
|
||||
addPlayer(p);
|
||||
}, 20);
|
||||
});
|
||||
}
|
||||
|
||||
public Plugin getPlugin() {
|
||||
@@ -80,13 +75,4 @@ public class CustomPacketManager extends PacketManager implements Listener {
|
||||
if(channel.getRemoveChannelExecutor() != null)
|
||||
channel.getRemoveChannelExecutor().shutdownNow();
|
||||
}
|
||||
|
||||
public ChatItemPacket onPacketSent(PacketType type, Player sender, Object packet) {
|
||||
if(type == null) {
|
||||
return null;
|
||||
}
|
||||
ChatItemPacket customPacket = new ChatItemPacket(type, packet, sender);
|
||||
notifyHandlersSent(customPacket);
|
||||
return customPacket;
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -78,7 +78,7 @@ public class ChannelInboundHandler extends ChannelInboundHandlerAdapter {
|
||||
int possibleProtocol = ints.readSafely(0, 0);
|
||||
if(possibleProtocol == Bukkit.getPort())
|
||||
possibleProtocol = ints.readSafely(1, 0);
|
||||
if(possibleProtocol == -1 || possibleProtocol == 255)
|
||||
if(possibleProtocol == -1 || possibleProtocol == 255 || possibleProtocol == Bukkit.getPort())
|
||||
possibleProtocol = ints.readSafely(2, 0);
|
||||
packetManager.protocolVersionPerChannel.put(channel, possibleProtocol);
|
||||
}
|
||||
|
||||
+3
-3
@@ -86,9 +86,9 @@ public class INC2Channel extends ChannelAbstract {
|
||||
|
||||
@Override
|
||||
public Channel getChannel(Player p) throws Exception {
|
||||
Class<?> networkClass = PacketUtils.getNmsClass("NetworkManager", "network.");
|
||||
Object networkManager = ReflectionUtils.getFirstWith(getPlayerConnection(p), PacketUtils.getNmsClass("PlayerConnection", "server.network."), networkClass);
|
||||
return ReflectionUtils.getFirstWith(networkManager, networkClass, Channel.class);
|
||||
Object playerConnection = getPlayerConnection(p);
|
||||
Object networkManager = ReflectionUtils.getFirstWith(playerConnection, PacketUtils.getNmsClass("NetworkManager", "network."));
|
||||
return ReflectionUtils.getFirstWith(networkManager, Channel.class);
|
||||
}
|
||||
|
||||
private class ChannelHandlerSent extends ChannelOutboundHandlerAdapter {
|
||||
|
||||
-166
@@ -1,166 +0,0 @@
|
||||
package me.dadus33.chatitem.chatmanager.v1.packets.custom.channel;
|
||||
|
||||
import static me.dadus33.chatitem.utils.PacketUtils.getPlayerConnection;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.List;
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.logging.Level;
|
||||
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
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;
|
||||
import net.minecraft.util.io.netty.channel.ChannelFuture;
|
||||
import net.minecraft.util.io.netty.channel.ChannelHandler;
|
||||
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 {
|
||||
Object dedicatedSrv = PacketUtils.getCraftServer();
|
||||
Object mcServer = dedicatedSrv.getClass().getMethod("getServer").invoke(dedicatedSrv);
|
||||
Object co = ReflectionUtils.getFirstWith(mcServer, PacketUtils.getNmsClass("MinecraftServer", "server."), PacketUtils.getNmsClass("ServerConnection", "network."));
|
||||
List<ChannelFuture> g = (List<ChannelFuture>) ReflectionUtils.getObject(co, "g", "e");
|
||||
g.forEach((channelFuture) -> {
|
||||
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>() {
|
||||
@Override
|
||||
protected void initChannel(Channel channel) {
|
||||
try {
|
||||
channel.eventLoop().submit(() -> {
|
||||
try {
|
||||
ChannelHandler interceptor = channel.pipeline().get(KEY_HANDSHAKE);
|
||||
// Inject our packet interceptor
|
||||
if (interceptor == null) {
|
||||
interceptor = new ChannelHandlerHandshakeReceive(channel);
|
||||
channel.pipeline().addBefore("packet_handler", KEY_HANDSHAKE, interceptor);
|
||||
}
|
||||
return interceptor;
|
||||
} catch (IllegalArgumentException e) {
|
||||
// Try again
|
||||
return channel.pipeline().get(KEY_HANDSHAKE);
|
||||
}
|
||||
});
|
||||
} catch (Exception e) {
|
||||
getPacketManager().getPlugin().getLogger().log(Level.SEVERE, "Cannot inject incomming channel " + channel, e);
|
||||
}
|
||||
}
|
||||
});
|
||||
ctx.fireChannelRead(msg);
|
||||
}
|
||||
});
|
||||
});
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void stopPipelines() {
|
||||
pipeline.remove(boundHandler);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addChannel(final Player player, String endChannelName) {
|
||||
getOrCreateAddChannelExecutor().execute(() -> {
|
||||
try {
|
||||
Channel channel = getChannel(player);
|
||||
// Managing outgoing packet (to the player)
|
||||
channel.pipeline().addAfter(KEY_HANDLER_SERVER, KEY_SERVER + endChannelName, new ChannelHandlerSent(player));
|
||||
} 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)");
|
||||
} catch (IllegalArgumentException e) {
|
||||
if(e.getMessage().contains("Duplicate")) {
|
||||
removeChannel(player, endChannelName);
|
||||
addChannel(player, endChannelName);
|
||||
} else
|
||||
getPacketManager().getPlugin().getLogger().severe("Error while loading Packet channel. " + e.getMessage() + ". Please, prefer restart than reload.");
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeChannel(Player player, String endChannelName) {
|
||||
getOrCreateRemoveChannelExecutor().execute(() -> {
|
||||
try {
|
||||
final Channel channel = getChannel(player);
|
||||
if(channel.pipeline().get(KEY_SERVER + endChannelName) != null)
|
||||
channel.pipeline().remove(KEY_SERVER + endChannelName);
|
||||
} catch (Exception e) {}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public Channel getChannel(Player p) throws Exception {
|
||||
Object playerConnection = getPlayerConnection(p);
|
||||
Object networkManager = playerConnection.getClass().getField("networkManager").get(playerConnection);
|
||||
|
||||
for (Field field : networkManager.getClass().getDeclaredFields())
|
||||
if (field.getType().equals(Channel.class)) {
|
||||
field.setAccessible(true);
|
||||
return (Channel) field.get(networkManager);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private class ChannelHandlerSent extends ChannelOutboundHandlerAdapter {
|
||||
|
||||
private final Player owner;
|
||||
|
||||
public ChannelHandlerSent(Player player) {
|
||||
this.owner = player;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(ChannelHandlerContext ctx, Object packet, ChannelPromise promise) throws Exception {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
private class ChannelHandlerHandshakeReceive extends ChannelInboundHandlerAdapter {
|
||||
|
||||
private final Channel channel;
|
||||
|
||||
public ChannelHandlerHandshakeReceive(Channel channel) {
|
||||
this.channel = channel;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void channelRead(ChannelHandlerContext ctx, Object packet) {
|
||||
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(1, 0));
|
||||
}
|
||||
super.channelRead(ctx, packet);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
-10
@@ -13,7 +13,6 @@ import com.comphenix.protocol.events.PacketAdapter;
|
||||
import com.comphenix.protocol.events.PacketEvent;
|
||||
|
||||
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;
|
||||
@@ -46,19 +45,10 @@ public class ProtocollibPacketManager extends PacketManager {
|
||||
e.setCancelled(packet.isCancelled());
|
||||
}
|
||||
});
|
||||
protocolManager.addPacketListener(new HandshakeListener(pl));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop() {
|
||||
protocolManager.removePacketListeners(ChatItem.getInstance());
|
||||
}
|
||||
|
||||
public ChatItemPacket onPacketSent(PacketType type, Player sender, Object packet) {
|
||||
if(type == null)
|
||||
return null;
|
||||
ChatItemPacket customPacket = new ChatItemPacket(type, packet, sender);
|
||||
notifyHandlersSent(customPacket);
|
||||
return customPacket;
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,7 @@
|
||||
package me.dadus33.chatitem.chatmanager.v2;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
@@ -16,58 +9,21 @@ 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.ItemSlot;
|
||||
import me.dadus33.chatitem.Storage;
|
||||
import me.dadus33.chatitem.chatmanager.Chat;
|
||||
import me.dadus33.chatitem.chatmanager.ChatAction;
|
||||
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.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.TextComponent;
|
||||
|
||||
@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) {
|
||||
@@ -78,18 +34,22 @@ public class ChatListener implements Listener {
|
||||
return manage.getStorage();
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
@EventHandler(priority = EventPriority.HIGH)
|
||||
public void onChat(AsyncPlayerChatEvent e) {
|
||||
if(ChatManager.isTestingEnabled() && !ChatManager.isTesting("chat"))
|
||||
return;
|
||||
if(!ChatManager.isSelected("chat"))
|
||||
return;
|
||||
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;
|
||||
for(ItemSlot slot : ItemSlot.values()) {
|
||||
for (String rep : slot.getPlaceholders()) {
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -97,240 +57,46 @@ public class ChatListener implements Listener {
|
||||
return;
|
||||
}
|
||||
Player p = e.getPlayer();
|
||||
String targetReplace = ChatManager.SEPARATOR + "";
|
||||
if(ChatManager.containsSeparator(e.getMessage())) { // fix for v1
|
||||
Chat chat = Chat.getFrom(e.getMessage());
|
||||
if(chat != null)
|
||||
e.setMessage(ChatManager.replaceSeparator(chat, e.getMessage(), c.placeholders.get(0)));
|
||||
}
|
||||
String placeholder = null;
|
||||
for (String rep : c.placeholders) {
|
||||
if (e.getMessage().contains(rep)) {
|
||||
placeholder = rep;
|
||||
break;
|
||||
if(chat != null) {
|
||||
targetReplace = ChatManager.SEPARATOR + "" + chat.getId() + ChatManager.SEPARATOR_END;
|
||||
e.setMessage(ChatManager.replaceSeparator(chat, e.getMessage(), chat.getSlot().getPlaceholders().get(0)));
|
||||
}
|
||||
}
|
||||
|
||||
if (placeholder == null) { // if not found
|
||||
ItemSlot slot = ItemSlot.getItemSlotFromMessage(e.getMessage());
|
||||
if (slot == 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))
|
||||
ChatAction action = ChatManager.getChatAction(slot, p);
|
||||
if(!ChatManager.canUsePlaceholder(p, action, slot, e))
|
||||
return;
|
||||
e.setCancelled(true);
|
||||
String format = e.getFormat();
|
||||
String msg, defMsg = e.getMessage();
|
||||
for (String rep : c.placeholders) {
|
||||
defMsg = defMsg.replace(rep, Character.toString(ChatManager.SEPARATOR));
|
||||
}
|
||||
if (Utils.countMatches(defMsg, Character.toString(ChatManager.SEPARATOR)) > getStorage().limit) {
|
||||
if (!getStorage().messageLimit.isEmpty())
|
||||
p.sendMessage(getStorage().messageLimit);
|
||||
String format = e.getFormat().replace(targetReplace, slot.getPlaceholders().get(0));
|
||||
ChatItem.debug("(v2) Using format: " + format + " and message: " + e.getMessage());
|
||||
String defMsg = slot.replacePlaceholdersToSeparator(e.getMessage());
|
||||
if (Utils.countMatches(defMsg, Character.toString(ChatManager.SEPARATOR)) > c.limit) {
|
||||
if (!c.messageLimit.isEmpty())
|
||||
p.sendMessage(c.messageLimit);
|
||||
return;
|
||||
}
|
||||
String msg;
|
||||
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());
|
||||
String itemName = ChatManager.getNameForChatAction(p, action, c);
|
||||
String loggedMessage = msg.replace(ChatManager.SEPARATOR + "", itemName);
|
||||
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()));
|
||||
DiscordSrvSupport.sendChatMessage(p, defMsg.replace(ChatManager.SEPARATOR + "", itemName), e);
|
||||
Set<Player> recipients = e.getRecipients().isEmpty() ? new HashSet<>(Bukkit.getOnlinePlayers()) : e.getRecipients();
|
||||
ChatItem.debug("Msg: " + msg.replace(ChatColor.COLOR_CHAR, '&') + ", format: " + format + " to " + recipients.size() + " players");
|
||||
recipients.forEach((pl) -> showItem(pl, p, item, msg));
|
||||
ChatItem.debug("(v2) Msg: " + ChatItem.replace(p, msg).replace(ChatColor.COLOR_CHAR, '&') + ", format: " + format + " to " + recipients.size() + " players");
|
||||
recipients.forEach((pl) -> ChatItem.getPlatform().sendMessage(pl, p, action, ChatItem.replace(p, 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, removing = false;
|
||||
for (char args : msg.toCharArray()) {
|
||||
if (args == '§') { // begin of color
|
||||
if (colorCode.isEmpty() && !text.isEmpty()) { // text before this char
|
||||
ChatItem.debug("Append '" + text.replace(ChatColor.COLOR_CHAR, '&') + "' (len: " + text.length() + ")");
|
||||
if(text.length() > 2 && text.startsWith("§") && text.substring(2) == ChatColor.stripColor(text)
|
||||
&& color != null && color != ChatColor.WHITE) {
|
||||
text = text.substring(2); // remove some code which should not be here
|
||||
}
|
||||
appendToComponentBuilder(builder, createComponent(text, color));
|
||||
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 = "";
|
||||
if(ChatManager.containsSeparatorEnd(msg))
|
||||
removing = true;
|
||||
} else if(args == ChatManager.SEPARATOR_END) {
|
||||
removing = false;
|
||||
} else if(!removing) { // not removing content
|
||||
// basic text, not waiting for code after '§'
|
||||
text += args;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!text.isEmpty())
|
||||
appendToComponentBuilder(builder, createComponent(text, color));
|
||||
to.spigot().sendMessage(builder.create());
|
||||
}
|
||||
|
||||
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("");
|
||||
appendToComponentBuilder(itemComponent, fixColorComponent(ChatManager.getNameOfItem(to, item, c), ChatColor.WHITE, item));
|
||||
ChatItem.debug("Item for " + to.getName() + " (ver: " + ItemPlayer.getPlayer(to).getVersion().name() + ") : " + PacketUtils.getNbtTag(item));
|
||||
// itemComponent.event(new HoverEvent(Action.SHOW_ITEM, itemBaseComponent));
|
||||
appendToComponentBuilder(builder, itemComponent.create());
|
||||
} else {
|
||||
String handName = c.handName;
|
||||
ComponentBuilder handComp = new ComponentBuilder("");
|
||||
ComponentBuilder handTooltip = new ComponentBuilder("");
|
||||
int stay = c.tooltipHand.size();
|
||||
for (String line : c.tooltipHand) {
|
||||
stay--;
|
||||
handTooltip.append(ColorManager.fixColor(line.replace("{name}", origin.getName()).replace("{display-name}", origin.getDisplayName())));
|
||||
if (stay > 0)
|
||||
handTooltip.append("\n");
|
||||
}
|
||||
handComp.event(Utils.createTextHover(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());
|
||||
}
|
||||
}
|
||||
|
||||
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) {
|
||||
return fixColorComponent(message, color, null);
|
||||
}
|
||||
|
||||
public static BaseComponent[] fixColorComponent(String message, ChatColor color, @Nullable ItemStack item) {
|
||||
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 " + (ColorManager.isHexColor(color) && builder.getParts().isEmpty() ? ColorManager.removeColorAtBegin(text) : text));
|
||||
appendToComponentBuilder(builder, createComponent(ColorManager.isHexColor(color) ? ColorManager.removeColorAtBegin(text) : text, color, item));
|
||||
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);
|
||||
ChatItem.debug("Color: " + color + ", text: " + text + ", code: " + colorCode);
|
||||
colorCode = "";
|
||||
}
|
||||
// basic text, not waiting for code after '§'
|
||||
text += args;
|
||||
}
|
||||
}
|
||||
if (!text.isEmpty()) {
|
||||
appendToComponentBuilder(builder, createComponent(text, color, item));
|
||||
}
|
||||
return builder.create();
|
||||
}
|
||||
|
||||
private static BaseComponent[] createComponent(String text, ChatColor color) {
|
||||
return createComponent(text, color, null);
|
||||
}
|
||||
|
||||
private static BaseComponent[] createComponent(String text, ChatColor color, ItemStack item) {
|
||||
ComponentBuilder littleBuilder = new ComponentBuilder(text);
|
||||
if(color != null && color != ChatColor.RESET) // don't add reset thing
|
||||
littleBuilder.color(color);
|
||||
if (item != null) // add to all possible sub parts
|
||||
littleBuilder.event(Utils.createItemHover(item));
|
||||
return littleBuilder.create();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package me.dadus33.chatitem.chatmanager.v3;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.event.HandlerList;
|
||||
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
import me.dadus33.chatitem.Storage;
|
||||
import me.dadus33.chatitem.chatmanager.ChatManager;
|
||||
|
||||
public class PaperChatManager extends ChatManager {
|
||||
|
||||
private PaperListener paperListener;
|
||||
|
||||
public PaperChatManager(ChatItem pl) {
|
||||
paperListener = new PaperListener(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "Paper";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getId() {
|
||||
return "paper";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void load(ChatItem pl, Storage s) {
|
||||
super.load(pl, s);
|
||||
|
||||
Bukkit.getPluginManager().registerEvents(paperListener, pl);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void unload(ChatItem pl) {
|
||||
HandlerList.unregisterAll(paperListener);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package me.dadus33.chatitem.chatmanager.v3;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
|
||||
import io.papermc.paper.event.player.AsyncChatEvent;
|
||||
import me.dadus33.chatitem.C;
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
import me.dadus33.chatitem.ItemSlot;
|
||||
import me.dadus33.chatitem.Storage;
|
||||
import me.dadus33.chatitem.chatmanager.Chat;
|
||||
import me.dadus33.chatitem.chatmanager.ChatAction;
|
||||
import me.dadus33.chatitem.chatmanager.ChatManager;
|
||||
import me.dadus33.chatitem.utils.Messages;
|
||||
import net.kyori.adventure.audience.Audience;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.TextComponent;
|
||||
import net.kyori.adventure.text.TextReplacementConfig;
|
||||
import net.kyori.adventure.text.event.ClickEvent;
|
||||
import net.kyori.adventure.text.event.HoverEvent;
|
||||
import net.kyori.adventure.text.event.HoverEventSource;
|
||||
|
||||
public class PaperListener implements Listener {
|
||||
|
||||
private PaperChatManager manage;
|
||||
|
||||
public PaperListener(PaperChatManager manage) {
|
||||
this.manage = manage;
|
||||
}
|
||||
|
||||
public Storage getStorage() {
|
||||
return manage.getStorage();
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST)
|
||||
public void onChat(AsyncChatEvent e) {
|
||||
if (ChatManager.isTestingEnabled() && !ChatManager.isTesting("paper"))
|
||||
return;
|
||||
if (!ChatManager.isSelected("paper"))
|
||||
return;
|
||||
|
||||
Player p = e.getPlayer();
|
||||
Component message = e.message();
|
||||
String rawMessage = C.string(message);
|
||||
if (ChatManager.containsSeparator(rawMessage)) { // fix for v1
|
||||
Chat chat = Chat.getFrom(rawMessage);
|
||||
if (chat != null) {
|
||||
message = message.replaceText(TextReplacementConfig.builder().matchLiteral(ChatManager.SEPARATOR + "" + chat.getId() + ChatManager.SEPARATOR_END)
|
||||
.replacement(C.text(chat.getSlot().getPlaceholders().get(0))).build());
|
||||
rawMessage = C.string(message);
|
||||
}
|
||||
}
|
||||
ItemSlot slot = ItemSlot.getItemSlotFromMessage(rawMessage);
|
||||
ChatItem.debug("(v3) Raw message: " + rawMessage + ", slot: " + slot);
|
||||
if (slot == null) // if not found
|
||||
return;
|
||||
ChatAction action = ChatManager.getChatAction(slot, p);
|
||||
if (!ChatManager.canUsePlaceholder(p, action, slot, e))
|
||||
return;
|
||||
HoverEventSource<?> hoverEvent = null;
|
||||
if(action.isItem()) {
|
||||
if(!action.getItem().getType().equals(Material.AIR))
|
||||
hoverEvent = action.getItem().asHoverEvent();
|
||||
else {
|
||||
Component t = null;
|
||||
for(String line : Messages.getMessageList("general.hand.tooltip", "%cible%", p.getName())) {
|
||||
if(t == null) {
|
||||
t = Component.text("");
|
||||
} else
|
||||
t.append(Component.newline());
|
||||
t.append(C.text(line));
|
||||
}
|
||||
hoverEvent = HoverEvent.showText(t);
|
||||
}
|
||||
} else
|
||||
hoverEvent = HoverEvent.showText(C.text(Messages.getMessage(action.getSlot().name().toLowerCase() + ".hover", "%cible%", p.getName())));
|
||||
TextComponent like = C.text(ChatManager.getNameForChatAction(p, action, getStorage())).hoverEvent(hoverEvent);
|
||||
if (action.hasCommand())
|
||||
like.clickEvent(ClickEvent.runCommand(action.getCommand()));
|
||||
for (String s : slot.getPlaceholders())
|
||||
message = message.replaceText(TextReplacementConfig.builder().matchLiteral(s).replacement(like).build());
|
||||
if (ChatItem.getInstance().getConfig().getBoolean("manager-config.paper.send-ourself", false)) {
|
||||
for (Audience a : e.viewers().isEmpty() ? Bukkit.getOnlinePlayers() : e.viewers())
|
||||
a.sendMessage(e.renderer().render(p, p.displayName(), message, a));
|
||||
e.setCancelled(true);
|
||||
} else
|
||||
e.message(message);
|
||||
ChatItem.debug("Changed message to " + C.string(message));
|
||||
if (getStorage().cooldown > 0 && !p.hasPermission("chatitem.ignore-cooldown"))
|
||||
ChatManager.applyCooldown(p);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package me.dadus33.chatitem.chatmanager.v4;
|
||||
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
|
||||
import io.papermc.paper.event.player.AsyncChatEvent;
|
||||
import me.dadus33.chatitem.chatmanager.ChatManager;
|
||||
|
||||
public class OwnListener implements Listener {
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void onChat(AsyncChatEvent e) {
|
||||
if (ChatManager.isTestingEnabled() && !ChatManager.isTesting("ownformatter"))
|
||||
return;
|
||||
if (!ChatManager.isSelected("ownformatter"))
|
||||
return;
|
||||
if (e.isCancelled())
|
||||
return;
|
||||
e.setCancelled(true);
|
||||
/*Player p = e.getPlayer();
|
||||
Component msg = e.message();*/
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package me.dadus33.chatitem.chatmanager.v4;
|
||||
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
import me.dadus33.chatitem.chatmanager.ChatManager;
|
||||
|
||||
public class OwnManager extends ChatManager {
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "Own Formatter";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getId() {
|
||||
return "ownformatter";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void unload(ChatItem pl) {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -2,32 +2,43 @@ package me.dadus33.chatitem.commands;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
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.ItemSlot;
|
||||
import me.dadus33.chatitem.Storage;
|
||||
import me.dadus33.chatitem.chatmanager.ChatAction;
|
||||
import me.dadus33.chatitem.chatmanager.ChatManager;
|
||||
import me.dadus33.chatitem.chatmanager.v2.ChatListener;
|
||||
import me.dadus33.chatitem.invsee.InvShower;
|
||||
import me.dadus33.chatitem.listeners.InventoryListener;
|
||||
import me.dadus33.chatitem.utils.Colors;
|
||||
import me.dadus33.chatitem.utils.ItemUtils;
|
||||
import me.dadus33.chatitem.utils.Messages;
|
||||
import me.dadus33.chatitem.utils.Utils;
|
||||
import net.md_5.bungee.api.chat.ClickEvent;
|
||||
import net.md_5.bungee.api.chat.TextComponent;
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
public class ChatItemCommand implements CommandExecutor, TabExecutor {
|
||||
|
||||
private static final List<String> orders = Arrays.asList("packet", "chat", "both");
|
||||
private static final List<String> ORDERS;
|
||||
|
||||
static {
|
||||
if(Utils.IS_PAPER)
|
||||
ORDERS = Arrays.asList("chat", "paper", "packet", "all");
|
||||
else
|
||||
ORDERS = Arrays.asList("chat", "packet", "all");
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
|
||||
@@ -38,29 +49,18 @@ public class ChatItemCommand implements CommandExecutor, TabExecutor {
|
||||
Player p = (Player) sender;
|
||||
if (args.length == 0) {
|
||||
Messages.sendMessage(p, "chatitem-cmd.help");
|
||||
} else if (args[0].equalsIgnoreCase("admin")) {
|
||||
} else if (args[0].equalsIgnoreCase("admin") && p.hasPermission("chatitem.reload")) {
|
||||
InventoryListener.open(p);
|
||||
} else if (args[0].equalsIgnoreCase("reload")) {
|
||||
} else if (args[0].equalsIgnoreCase("reload") && p.hasPermission("chatitem.reload")) {
|
||||
ChatItem.reload(sender);
|
||||
} else if (args[0].equalsIgnoreCase("show")) {
|
||||
Player cible = args.length == 1 ? p : Bukkit.getPlayer(args[1]);
|
||||
if(cible == null) {
|
||||
Messages.sendMessage(p, "player-not-found", "%arg%", args[1]);
|
||||
return false;
|
||||
}
|
||||
Storage c = ChatItem.getInstance().getStorage();
|
||||
ItemStack item = ChatManager.getUsableItem(cible);
|
||||
ChatListener.showItem(p, cible, item, c.commandFormat.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) {
|
||||
Messages.sendMessage(p, "player-not-found", "%arg%", args[1]);
|
||||
return false;
|
||||
}
|
||||
Storage c = ChatItem.getInstance().getStorage();
|
||||
ItemStack item = ChatManager.getUsableItem(cible);
|
||||
for(Player all : Bukkit.getOnlinePlayers())
|
||||
ChatListener.showItem(all, cible, item, c.commandFormat.replace("%name%", cible.getName()).replace("%item%", ChatManager.SEPARATOR + ""));
|
||||
} else if (args[0].equalsIgnoreCase("ec") && ChatItem.getInstance().getStorage().cmdShow) {
|
||||
sendCommandFormatFrom(p, ItemSlot.ENDERCHEST, Bukkit.getOnlinePlayers());
|
||||
} else if (args[0].equalsIgnoreCase("inv") && ChatItem.getInstance().getStorage().cmdShow) {
|
||||
sendCommandFormatFrom(p, ItemSlot.INVENTORY, Bukkit.getOnlinePlayers());
|
||||
} else if (args[0].equalsIgnoreCase("show") && ChatItem.getInstance().getStorage().cmdShow) {
|
||||
sendCommandFormatFrom(p, ItemSlot.getItemSlotByKey(args.length <= 1 ? "" : args[1]), Arrays.asList(p));
|
||||
} else if (args[0].equalsIgnoreCase("broadcast") && ChatItem.getInstance().getStorage().cmdBroadcast) {
|
||||
sendCommandFormatFrom(p, ItemSlot.getItemSlotByKey(args.length <= 1 ? "" : args[1]), Bukkit.getOnlinePlayers());
|
||||
} else if (args[0].equalsIgnoreCase("link") || args[0].equalsIgnoreCase("links")) {
|
||||
ConfigurationSection config = ChatItem.getInstance().getConfig()
|
||||
.getConfigurationSection("messages.chatitem-cmd.links");
|
||||
@@ -77,61 +77,86 @@ public class ChatItemCommand implements CommandExecutor, TabExecutor {
|
||||
text.addExtra(linkComp);
|
||||
}
|
||||
p.spigot().sendMessage(text);
|
||||
} else if (args[0].equalsIgnoreCase("select")) {
|
||||
} else if (args[0].equalsIgnoreCase("select") && p.hasPermission("chatitem.reload")) {
|
||||
if(args.length == 1) {
|
||||
p.sendMessage(ChatColor.GRAY + "----------" + ChatColor.GOLD + " ChatItem - Setup " + ChatColor.GRAY + "----------");
|
||||
p.sendMessage(ChatColor.AQUA + "Welcome in the help of setup." + ChatColor.YELLOW + " Please follow step by simply answer to test.");
|
||||
sendCheckSelectMessage(p, orders.get(0));
|
||||
p.sendMessage(Colors.GRAY + "----------" + Colors.GOLD + " ChatItem - Setup " + Colors.GRAY + "----------");
|
||||
p.sendMessage(Colors.AQUA + "Welcome in the help of setup." + Colors.YELLOW + " Please follow step by simply answer to test.");
|
||||
sendCheckSelectMessage(p, ORDERS.get(0));
|
||||
} else {
|
||||
String tested = args[1];
|
||||
if(!orders.contains(tested)) {
|
||||
p.sendMessage(ChatColor.RED + "Unknow test for " + tested + ".");
|
||||
if(!ORDERS.contains(tested)) {
|
||||
p.sendMessage(Colors.RED + "Unknow test for " + tested + ".");
|
||||
return false;
|
||||
}
|
||||
if(args.length == 2) {
|
||||
p.sendMessage(ChatColor.RED + "Can't find if it works");
|
||||
p.sendMessage(Colors.RED + "Can't find if it works");
|
||||
return false;
|
||||
}
|
||||
if(args[2].equalsIgnoreCase("yes")) {
|
||||
ChatManager.setTesting(null);
|
||||
InventoryListener.setInConfig("manager", tested);
|
||||
p.sendMessage(ChatColor.GREEN + "Perfect ! Updating config ...");
|
||||
p.sendMessage(Colors.GREEN + "Perfect ! Updating config ...");
|
||||
ChatItem.reload(p);
|
||||
} else if(args[2].equalsIgnoreCase("no")) {
|
||||
int index = orders.indexOf(tested);
|
||||
if(orders.size() == (index + 1)) {
|
||||
p.sendMessage(ChatColor.RED + "Sad. Sorry but nothing is available. I suggest you to come on discord for more help. Do '/chatitem link' for all links.");
|
||||
int index = ORDERS.indexOf(tested);
|
||||
if(ORDERS.size() == (index + 1)) {
|
||||
p.sendMessage(Colors.RED + "Sad. Sorry but nothing is available. I suggest you to come on discord for more help. Do '/chatitem link' for all links.");
|
||||
ChatManager.setTesting(null);
|
||||
} else {
|
||||
p.sendMessage(ChatColor.RED + "Sad. Checking for next manager ...");
|
||||
sendCheckSelectMessage(p, orders.get(index + 1));
|
||||
p.sendMessage(Colors.RED + "Sad. Checking for next manager ...");
|
||||
sendCheckSelectMessage(p, ORDERS.get(index + 1));
|
||||
}
|
||||
} else {
|
||||
p.sendMessage(ChatColor.RED + "Can't find if it works");
|
||||
p.sendMessage(Colors.RED + "Can't find if it works");
|
||||
}
|
||||
}
|
||||
|
||||
} else if (args[0].equalsIgnoreCase("seeinv")) {
|
||||
if(args.length == 2 && Utils.isUUID(args[1])) {
|
||||
InvShower inv = InvShower.get(args[1]);
|
||||
if(inv == null) {
|
||||
Messages.sendMessage(p, "seeinv_not_found");
|
||||
} else {
|
||||
inv.open(p);
|
||||
}
|
||||
} // else just ignore
|
||||
} else {
|
||||
Messages.sendMessage(p, "chatitem-cmd.help");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private void sendCommandFormatFrom(Player p, ItemSlot slot, Collection<? extends Player> receivers) {
|
||||
if(slot == null) {
|
||||
Messages.sendMessage(p, "chatitem-cmd.help");
|
||||
return;
|
||||
}
|
||||
ChatAction action = ChatManager.getChatAction(slot, p);
|
||||
ChatItem.debug("Action: " + action);
|
||||
if(action.isItem() && ItemUtils.isEmpty(action.getItem())) {
|
||||
Messages.sendMessage(p, "empty-item");
|
||||
return;
|
||||
}
|
||||
for(Player all : receivers)
|
||||
ChatItem.getPlatform().sendMessage(all, p, action, slot.getShowMessage().replace("%name%", p.getName()).replace("%item%", ChatManager.SEPARATOR + ""));
|
||||
}
|
||||
|
||||
private void sendCheckSelectMessage(Player p, String testing) {
|
||||
ChatManager.setTesting(testing);
|
||||
p.chat("Checking for " + testing + ": [i]");
|
||||
|
||||
Bukkit.getScheduler().runTaskLater(ChatItem.getInstance(), () -> {
|
||||
TextComponent text = new TextComponent(ChatColor.GOLD + "Did it worked fine? ");
|
||||
TextComponent agree = new TextComponent(ChatColor.GREEN + "Yes");
|
||||
TextComponent text = new TextComponent(Colors.GOLD + "Did it worked fine? ");
|
||||
TextComponent agree = new TextComponent(Colors.GREEN + "Yes");
|
||||
agree.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/chatitem select " + testing + " yes"));
|
||||
agree.setHoverEvent(Utils.createTextHover(ChatColor.GRAY + "Click to say it worked fine"));
|
||||
agree.setHoverEvent(Utils.createTextHover(Colors.GRAY + "Click to say it worked fine"));
|
||||
text.addExtra(agree);
|
||||
text.addExtra(" ");
|
||||
TextComponent decline = new TextComponent(ChatColor.RED + "No");
|
||||
text.addExtra(", ");
|
||||
TextComponent decline = new TextComponent(Colors.RED + "No");
|
||||
decline.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/chatitem select " + testing + " no"));
|
||||
decline.setHoverEvent(Utils.createTextHover(ChatColor.GRAY + "Click to say it's not working as expected"));
|
||||
decline.setHoverEvent(Utils.createTextHover(Colors.GRAY + "Click to say it's not working as expected"));
|
||||
text.addExtra(decline);
|
||||
if(testing.equalsIgnoreCase("packet"))
|
||||
text.addExtra(" (This manager can have different result between 'chatitem select' and default chat for technical reasons. If nothing works, it's recommended to select it and try again)");
|
||||
p.spigot().sendMessage(text);
|
||||
}, 2);
|
||||
}
|
||||
@@ -140,10 +165,26 @@ public class ChatItemCommand implements CommandExecutor, TabExecutor {
|
||||
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);
|
||||
if(arg.length <= 2) {
|
||||
for (String s : Arrays.asList("help", "admin", "reload", "link", "show", "broadcast", "select"))
|
||||
if(arg.length <= 1) {
|
||||
if(sender.hasPermission("chatitem.reload")) {
|
||||
for (String s : Arrays.asList("admin", "reload", "select"))
|
||||
if (prefix.isEmpty() || s.startsWith(prefix))
|
||||
list.add(s);
|
||||
}
|
||||
if(ChatItem.getInstance().getStorage().cmdShow) {
|
||||
for (String s : Arrays.asList("show", "ec", "inv"))
|
||||
if (prefix.isEmpty() || s.startsWith(prefix))
|
||||
list.add(s);
|
||||
}
|
||||
if (ChatItem.getInstance().getStorage().cmdBroadcast && (prefix.isEmpty() || "broadcast".startsWith(prefix)))
|
||||
list.add("broadcast");
|
||||
for (String s : Arrays.asList("help", "link"))
|
||||
if (prefix.isEmpty() || s.startsWith(prefix))
|
||||
list.add(s);
|
||||
} else if(arg[0].equalsIgnoreCase("show") || arg[0].equalsIgnoreCase("broadcast")) {
|
||||
for (ItemSlot slot : ItemSlot.values())
|
||||
if (prefix.isEmpty() || slot.getKey().startsWith(prefix))
|
||||
list.add(slot.getKey());
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
@@ -1,15 +1,18 @@
|
||||
package me.dadus33.chatitem.hook;
|
||||
|
||||
import org.mineacademy.chatcontrol.settings.Settings;
|
||||
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
|
||||
public class ChatControlSupport {
|
||||
|
||||
public static void init(ChatItem pl) {
|
||||
Settings.Chat.Grammar.CAPITALIZE = false;
|
||||
Settings.Chat.Grammar.INSERT_DOT = false;
|
||||
try {
|
||||
Class<?> clz = Class.forName("org.mineacademy.chatcontrol.settings.Settings$Chat$Grammar");
|
||||
clz.getField("CAPITALIZE").setBoolean(null, false);
|
||||
clz.getField("INSERT_DOT").setBoolean(null, false);
|
||||
pl.getLogger().info("Loaded ChatControl support by disabling 2 options in 'Chat.Grammar' config.");
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
pl.getLogger().info("Loaded ChatControl support by disabling 2 options in 'Chat.Grammar' config.");
|
||||
}
|
||||
}
|
||||
@@ -1,17 +1,26 @@
|
||||
package me.dadus33.chatitem.hook;
|
||||
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.Event;
|
||||
|
||||
import github.scarsz.discordsrv.DiscordSRV;
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
|
||||
|
||||
public class DiscordSrvSupport {
|
||||
|
||||
public static boolean isSendingMessage() {
|
||||
return ChatItem.getInstance().getStorage().discordSrvSendMsg;
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
public static void sendChatMessage(Player p, String message) {
|
||||
public static void sendChatMessage(Player p, String message, Event e) {
|
||||
DiscordSRV pl = DiscordSRV.getPlugin();
|
||||
if (DiscordSRV.config().getBooleanElse("UseModernPaperChatEvent", false) && pl.isModernChatEventAvailable()) {
|
||||
return;
|
||||
}
|
||||
pl.processChatMessage(p, message, pl.getOptionalChannel("global"), false);
|
||||
pl.processChatMessage(p, message, pl.getOptionalChannel("global"), false, e);
|
||||
}
|
||||
|
||||
public static void sendChatMessage(Player p, Component message, Event e) {
|
||||
DiscordSRV pl = DiscordSRV.getPlugin();
|
||||
pl.processChatMessage(p, github.scarsz.discordsrv.dependencies.kyori.adventure.text.serializer.gson.GsonComponentSerializer.gson().deserialize(GsonComponentSerializer.gson().serialize(message)), pl.getOptionalChannel("global"), false, e);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package me.dadus33.chatitem.hook.ecoenchants;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.meta.ItemMeta;
|
||||
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
|
||||
public class EcoEnchantsSupport {
|
||||
|
||||
private static int supportedVersion = 0;
|
||||
|
||||
public static boolean hasSupport() {
|
||||
return supportedVersion > 0;
|
||||
}
|
||||
|
||||
public static boolean load() {
|
||||
String ver = ChatItem.getPlatform().getPluginVersion(Bukkit.getPluginManager().getPlugin("EcoEnchants"));
|
||||
if(ver.startsWith("8."))
|
||||
supportedVersion = 8;
|
||||
else if(ver.startsWith("10."))
|
||||
supportedVersion = 10;
|
||||
else if(ver.startsWith("11."))
|
||||
supportedVersion = 11;
|
||||
else if(ver.startsWith("12."))
|
||||
supportedVersion = 12;
|
||||
else {
|
||||
ChatItem.getInstance().getLogger().warning("Failed to find support version for EcoEnchants " + ver);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
public static ItemStack manageItem(ItemStack item) {
|
||||
if(supportedVersion == 8) {
|
||||
List<String> addLore = EcoEnchantsV8Support.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);
|
||||
ChatItem.debug("Added " + addLore.size() + " lores from EcoEnchants");
|
||||
} else
|
||||
ChatItem.debug("No lore to add from EcoEnchants");
|
||||
} else if(supportedVersion >= 10) {
|
||||
EcoEnchantsV10Support.display(item);
|
||||
}
|
||||
return item;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package me.dadus33.chatitem.hook.ecoenchants;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import com.willfp.eco.core.display.DisplayProperties;
|
||||
import com.willfp.ecoenchants.EcoEnchantsPlugin;
|
||||
import com.willfp.ecoenchants.display.EnchantDisplay;
|
||||
|
||||
public class EcoEnchantsV10Support {
|
||||
|
||||
private static EnchantDisplay enchantDisplay;
|
||||
|
||||
public static EnchantDisplay getEnchantDisplay() {
|
||||
if (enchantDisplay == null) {
|
||||
try {
|
||||
enchantDisplay = EnchantDisplay.class.getConstructor(EcoEnchantsPlugin.class).newInstance(Bukkit.getPluginManager().getPlugin("EcoEnchants"));
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return enchantDisplay;
|
||||
}
|
||||
|
||||
public static void display(ItemStack item) {
|
||||
try {
|
||||
DisplayProperties display = DisplayProperties.class.getDeclaredConstructor(boolean.class, boolean.class, ItemStack.class).newInstance(false, false, item);
|
||||
getEnchantDisplay().display(item, (Player) null, display, new Object[] { false });
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+2
-2
@@ -1,4 +1,4 @@
|
||||
package me.dadus33.chatitem.hook;
|
||||
package me.dadus33.chatitem.hook.ecoenchants;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
@@ -8,7 +8,7 @@ import org.bukkit.inventory.ItemStack;
|
||||
import com.willfp.ecoenchants.display.EnchantmentCache;
|
||||
import com.willfp.ecoenchants.enchantments.util.EnchantChecks;
|
||||
|
||||
public class EcoEnchantsSupport {
|
||||
public class EcoEnchantsV8Support {
|
||||
|
||||
public static List<String> getLores(ItemStack item) {
|
||||
List<String> lores = new ArrayList<>();
|
||||
@@ -0,0 +1,40 @@
|
||||
package me.dadus33.chatitem.hook.placeholders;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.scoreboard.Team;
|
||||
|
||||
import com.earth2me.essentials.Essentials;
|
||||
import com.earth2me.essentials.User;
|
||||
import com.earth2me.essentials.utils.FormatUtil;
|
||||
|
||||
public class EssentialsPlaceholdersHook implements IPlaceholders {
|
||||
|
||||
private Essentials getEssentials() {
|
||||
return ((Essentials) Bukkit.getPluginManager().getPlugin("Essentials"));
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
@Override
|
||||
public String replace(Player p, String text) {
|
||||
User user = getEssentials().getUser(p);
|
||||
if (user == null) {
|
||||
return null;
|
||||
}
|
||||
String world = user.getWorld().getName();
|
||||
String username = user.getName();
|
||||
String nickname = user.getFormattedNickname();
|
||||
Player player = user.getBase();
|
||||
Team team = player.getScoreboard().getPlayerTeam(player);
|
||||
|
||||
return text.replace("{GROUP}", user.getGroup()).replace("{WORLD}", getEssentials().getSettings().getWorldAlias(world)).replace("{WORLDNAME}", world)
|
||||
.replace("{SHORTWORLDNAME}", world.substring(0, 1).toUpperCase(Locale.ENGLISH)).replace("{TEAMNAME}", team == null ? "" : team.getDisplayName())
|
||||
.replace("{TEAMPREFIX}", team == null ? "" : team.getPrefix()).replace("{TEAMSUFFIX}", team == null ? "" : team.getSuffix())
|
||||
.replace("{PREFIX}", FormatUtil.replaceFormat(getEssentials().getPermissionsHandler().getPrefix(player)))
|
||||
.replace("{SUFFIX}", FormatUtil.replaceFormat(getEssentials().getPermissionsHandler().getSuffix(player))).replace("{USERNAME}", username)
|
||||
.replace("{NICKNAME}", nickname == null ? username : nickname);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package me.dadus33.chatitem.hook.placeholders;
|
||||
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
public interface IPlaceholders {
|
||||
|
||||
String replace(Player p, String text);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package me.dadus33.chatitem.hook.placeholders;
|
||||
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import be.maximvdw.placeholderapi.PlaceholderAPI;
|
||||
|
||||
public class MVdWPlaceholderAPIHook implements IPlaceholders {
|
||||
|
||||
@Override
|
||||
public String replace(Player p, String text) {
|
||||
return PlaceholderAPI.replacePlaceholders(p, text);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package me.dadus33.chatitem.hook.placeholders;
|
||||
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
public class OwnPlaceholder implements IPlaceholders {
|
||||
|
||||
@Override
|
||||
public String replace(Player p, String text) {
|
||||
return text.replace("{name}", p.getName()).replace("%name%", p.getName());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package me.dadus33.chatitem.hook.placeholders;
|
||||
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import me.clip.placeholderapi.PlaceholderAPI;
|
||||
|
||||
public class PlaceholderAPIHook implements IPlaceholders {
|
||||
|
||||
@Override
|
||||
public String replace(Player p, String text) {
|
||||
return PlaceholderAPI.setPlaceholders(p, text);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package me.dadus33.chatitem.hook.placeholders;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.plugin.RegisteredServiceProvider;
|
||||
|
||||
import net.milkbowl.vault.chat.Chat;
|
||||
|
||||
public class VaultPlaceholderHook implements IPlaceholders {
|
||||
|
||||
private Chat chat = null;
|
||||
|
||||
public Chat getChat() {
|
||||
if (chat == null) {
|
||||
RegisteredServiceProvider<Chat> rs = Bukkit.getServicesManager().getRegistration(Chat.class);
|
||||
if (rs != null) // chat well setup
|
||||
chat = rs.getProvider();
|
||||
}
|
||||
return chat;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String replace(Player p, String text) {
|
||||
Chat chat = getChat();
|
||||
if (chat == null)
|
||||
return text;
|
||||
return text.replace("{prefix}", chat.getPlayerPrefix(p)).replace("{suffix}", chat.getPlayerSuffix(p)).replace("%prefix%", chat.getPlayerPrefix(p)).replace("%suffix%", chat.getPlayerSuffix(p));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package me.dadus33.chatitem.invsee;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.UUID;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
|
||||
public abstract class InvShower {
|
||||
|
||||
private static final HashMap<String, InvShower> INV_SHOWER = new HashMap<>();
|
||||
public static InvShower get(String s) {
|
||||
return INV_SHOWER.get(s);
|
||||
}
|
||||
public static void add(String s, InvShower shower) {
|
||||
INV_SHOWER.put(s, shower);
|
||||
}
|
||||
public static HashMap<String, InvShower> getInvShower() {
|
||||
return INV_SHOWER;
|
||||
}
|
||||
|
||||
static {
|
||||
Bukkit.getScheduler().runTaskTimer(ChatItem.getInstance(), () -> {
|
||||
for(Entry<String, InvShower> entries : new HashMap<>(INV_SHOWER).entrySet())
|
||||
if(entries.getValue().hasExpired())
|
||||
INV_SHOWER.remove(entries.getKey());
|
||||
}, 200, 200);
|
||||
}
|
||||
|
||||
protected final long time;
|
||||
protected final UUID uuid;
|
||||
protected final String name;
|
||||
|
||||
public InvShower(String id, Player cible) {
|
||||
this.time = System.currentTimeMillis() + ChatItem.getInstance().getConfig().getInt("general.other-placeholders." + id + ".time-expire", 1800) * 1000;
|
||||
this.uuid = cible.getUniqueId();
|
||||
this.name = cible.getName();
|
||||
}
|
||||
|
||||
public UUID getUuid() {
|
||||
return uuid;
|
||||
}
|
||||
|
||||
public long getTimeExpire() {
|
||||
return time;
|
||||
}
|
||||
|
||||
public boolean hasExpired() {
|
||||
return System.currentTimeMillis() > time || Bukkit.getPlayer(uuid) == null || !Bukkit.getPlayer(uuid).isOnline();
|
||||
}
|
||||
|
||||
public abstract void open(Player p);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package me.dadus33.chatitem.invsee.hook;
|
||||
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.Inventory;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
import me.dadus33.chatitem.invsee.InvShower;
|
||||
import me.dadus33.chatitem.listeners.holder.CustomInventoryHolder;
|
||||
import me.dadus33.chatitem.utils.ItemUtils;
|
||||
import me.dadus33.chatitem.utils.Messages;
|
||||
|
||||
public class EnderChestShower extends InvShower {
|
||||
|
||||
private final ItemStack[] items;
|
||||
|
||||
public EnderChestShower(Player cible) {
|
||||
super("enderchest", cible);
|
||||
|
||||
Inventory ec = cible.getEnderChest();
|
||||
ItemStack[] tmp = ec.getContents();
|
||||
items = new ItemStack[tmp.length];
|
||||
for(int i = 0; i < ec.getSize(); i++)
|
||||
items[i] = ItemUtils.copyIfExist(tmp[i]);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void open(Player p) {
|
||||
Inventory inv = ChatItem.getPlatform().createInventory(new CustomInventoryHolder(), items.length, Messages.getMessage("enderchest.name", "%cible%", name));
|
||||
|
||||
for(int i = 0; i < items.length; i++)
|
||||
inv.setItem(i, items[i]);
|
||||
|
||||
p.openInventory(inv);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package me.dadus33.chatitem.invsee.hook;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.Inventory;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.PlayerInventory;
|
||||
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
import me.dadus33.chatitem.invsee.InvShower;
|
||||
import me.dadus33.chatitem.listeners.holder.CustomInventoryHolder;
|
||||
import me.dadus33.chatitem.utils.ItemUtils;
|
||||
import me.dadus33.chatitem.utils.Messages;
|
||||
|
||||
public class PlayerInventoryShower extends InvShower {
|
||||
|
||||
private final HashMap<Integer, ItemStack> items = new HashMap<>();
|
||||
private final int level;
|
||||
|
||||
public PlayerInventoryShower(Player cible) {
|
||||
super("inventory", cible);
|
||||
this.level = cible.getLevel();
|
||||
|
||||
PlayerInventory pi = cible.getInventory();
|
||||
items.put(4, ItemUtils.copyIfExist(pi.getHelmet()));
|
||||
items.put(5, ItemUtils.copyIfExist(pi.getChestplate()));
|
||||
items.put(6, ItemUtils.copyIfExist(pi.getLeggings()));
|
||||
items.put(7, ItemUtils.copyIfExist(pi.getBoots()));
|
||||
|
||||
for(int i = 0; i < pi.getContents().length && i < (54 - 18); i++)
|
||||
items.put(i + 18, ItemUtils.copyIfExist(pi.getContents()[i]));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void open(Player p) {
|
||||
Inventory inv = ChatItem.getPlatform().createInventory(new CustomInventoryHolder(), 54, Messages.getMessage("inventory.name", "%cible%", name));
|
||||
|
||||
for(int i = 0; i < 18; i++)
|
||||
inv.setItem(i, ItemUtils.ITEM_EMPTY_BROWN);
|
||||
|
||||
inv.setItem(2, new ItemStack(ItemUtils.getMaterialWithCompatibility("EXPERIENCE_BOTTLE", "EXP_BOTTLE"), level == 0 ? 1 : (level >= 64 ? 64 : level)));
|
||||
|
||||
items.forEach(inv::setItem);
|
||||
|
||||
p.openInventory(inv);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -30,7 +30,7 @@ public interface INamer {
|
||||
*/
|
||||
String getName(Player p, ItemStack item, Storage storage);
|
||||
|
||||
enum Priority {
|
||||
public enum Priority {
|
||||
MAJOR(4),
|
||||
IMPORTANT(3),
|
||||
MEDIUM(2),
|
||||
|
||||
@@ -45,8 +45,7 @@ public class NamerManager {
|
||||
* @param namer the namer to add
|
||||
*/
|
||||
public static void addNamer(INamer namer) {
|
||||
List<INamer> namers = getOrCreate(namer.getPriority());
|
||||
namers.add(namer);
|
||||
getOrCreate(namer.getPriority()).add(namer);
|
||||
}
|
||||
|
||||
private static List<INamer> getOrCreate(Priority p){
|
||||
@@ -68,8 +67,10 @@ public class NamerManager {
|
||||
continue;
|
||||
for(INamer namer : allNamers) {
|
||||
String tmpName = namer.getName(p, item, storage);
|
||||
if(tmpName != null)
|
||||
if(tmpName != null && tmpName != "") {
|
||||
ChatItem.debug("Using namer " + namer.getClass().getSimpleName() + ", value: " + tmpName);
|
||||
return tmpName;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null; // this should NEVER append
|
||||
|
||||
@@ -16,7 +16,7 @@ public class ChatItemTranslationNamer implements INamer {
|
||||
|
||||
@Override
|
||||
public String getName(Player p, ItemStack item, Storage storage) {
|
||||
return Translation.get(item);
|
||||
return Translation.getOr(item, null);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -4,9 +4,11 @@ import org.bukkit.ChatColor;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
import me.dadus33.chatitem.Storage;
|
||||
import me.dadus33.chatitem.itemnamer.INamer;
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
public class ItemDisplayNamer implements INamer {
|
||||
|
||||
@Override
|
||||
@@ -16,10 +18,9 @@ public class ItemDisplayNamer implements INamer {
|
||||
|
||||
@Override
|
||||
public String getName(Player p, ItemStack item, Storage storage) {
|
||||
if(item.hasItemMeta() && item.getItemMeta().hasDisplayName()) {
|
||||
String name = item.getItemMeta().getDisplayName();
|
||||
String name = ChatItem.getPlatform().getItemDisplayName(item);
|
||||
if(name != null && name != "")
|
||||
return storage.colorIfColored ? ChatColor.stripColor(name) : name;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
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;
|
||||
@@ -12,116 +9,143 @@ 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.InventoryHolder;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
import me.dadus33.chatitem.Storage;
|
||||
import me.dadus33.chatitem.Translation;
|
||||
import me.dadus33.chatitem.listeners.holder.AdminHolder;
|
||||
import me.dadus33.chatitem.listeners.holder.ChatItemHolder;
|
||||
import me.dadus33.chatitem.listeners.holder.CustomInventoryHolder;
|
||||
import me.dadus33.chatitem.utils.ItemUtils;
|
||||
import me.dadus33.chatitem.utils.Messages;
|
||||
import me.dadus33.chatitem.utils.Utils;
|
||||
|
||||
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 AdminHolder))
|
||||
if (!(e.getWhoClicked() instanceof Player))
|
||||
return;
|
||||
Player p = (Player) e.getWhoClicked();
|
||||
|
||||
Inventory topInventory = Utils.getTopInventory(e);
|
||||
InventoryHolder openInventoryHolder = topInventory == null ? null : topInventory.getHolder();
|
||||
|
||||
if (openInventoryHolder != null && openInventoryHolder instanceof CustomInventoryHolder) {
|
||||
e.setCancelled(true);
|
||||
return;
|
||||
}
|
||||
if (e.getClickedInventory() == null)
|
||||
return;
|
||||
|
||||
InventoryHolder holder = e.getClickedInventory().getHolder();
|
||||
if (holder == null || !(holder instanceof ChatItemHolder)) {
|
||||
if (e.getClick().equals(ClickType.DOUBLE_CLICK) && topInventory != null) {
|
||||
if (openInventoryHolder != null && openInventoryHolder instanceof ChatItemHolder) {
|
||||
e.setCancelled(true);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (holder instanceof CustomInventoryHolder) {
|
||||
e.setCancelled(true);
|
||||
return;
|
||||
}
|
||||
if (!(holder instanceof AdminHolder))
|
||||
return;
|
||||
e.setCancelled(true);
|
||||
Player p = (Player) e.getWhoClicked();
|
||||
if (e.getCurrentItem() == null)
|
||||
return;
|
||||
ItemStack item = e.getCurrentItem();
|
||||
Material type = item.getType();
|
||||
Storage c = ChatItem.getInstance().getStorage();
|
||||
if(type.equals(ItemUtils.MATERIAL_CLOSE)) {
|
||||
if (type.equals(ItemUtils.MATERIAL_CLOSE)) {
|
||||
p.closeInventory();
|
||||
} else if(type.equals(Material.BOOK)) {
|
||||
} else if (type.equals(Material.BOOK)) {
|
||||
TranslationInventoryListener.open(p, 0);
|
||||
} else if(type.equals(Material.PAPER)) {
|
||||
AdminHolder holder = (AdminHolder) e.getClickedInventory().getHolder();
|
||||
String key = holder.keyBySlot.get(e.getSlot());
|
||||
if(key != null) {
|
||||
} else if (type.equals(Material.PAPER)) {
|
||||
String key = ((AdminHolder) holder).keyBySlot.get(e.getSlot());
|
||||
if (key != null) {
|
||||
setInConfig("manager", key);
|
||||
p.closeInventory();
|
||||
ChatItem.reload(p);
|
||||
}
|
||||
} else if(type.equals(ItemUtils.INK_SAC)) {
|
||||
} else if (type.equals(ItemUtils.INK_SAC)) {
|
||||
setInConfig("general.color-if-already-colored", c.colorIfColored = !c.colorIfColored);
|
||||
open(p);
|
||||
} else if(type.equals(Material.REDSTONE)) {
|
||||
setInConfig("general.deny-if-no-item", c.denyIfNoItem = !c.denyIfNoItem);
|
||||
open(p);
|
||||
} else if(type.equals(Material.STICK)) {
|
||||
} else if (type.equals(Material.STICK)) {
|
||||
setInConfig("general.hand.disabled", c.handDisabled = !c.handDisabled);
|
||||
open(p);
|
||||
} else if(type.equals(Material.BLAZE_ROD)) {
|
||||
} else if (type.equals(Material.BLAZE_ROD)) {
|
||||
setInConfig("general.check-update", c.checkUpdate = !c.checkUpdate);
|
||||
open(p);
|
||||
} else if(type.equals(ItemUtils.FIREWORK_CHARGE)) {
|
||||
} 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))
|
||||
} else if (type.equals(Material.IRON_DOOR)) {
|
||||
if (e.getClick().equals(ClickType.RIGHT))
|
||||
c.limit--;
|
||||
else if(e.getClick().equals(ClickType.LEFT))
|
||||
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))
|
||||
} else if (type.equals(Material.APPLE)) {
|
||||
if (e.getClick().equals(ClickType.RIGHT))
|
||||
c.cooldown--;
|
||||
else if(e.getClick().equals(ClickType.LEFT))
|
||||
else if (e.getClick().equals(ClickType.LEFT))
|
||||
c.cooldown++;
|
||||
setInConfig("general.cooldown", c.cooldown);
|
||||
open(p);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static void setInConfig(String key, Object val) {
|
||||
ChatItem pl = ChatItem.getInstance();
|
||||
pl.getConfig().set(key, val);
|
||||
pl.saveConfig();
|
||||
}
|
||||
|
||||
|
||||
public static void open(Player p) {
|
||||
AdminHolder holder = new AdminHolder();
|
||||
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, "-"));
|
||||
|
||||
Inventory inv = ChatItem.getPlatform().createInventory(holder, 27, Messages.getMessage("admin-inv.name"));
|
||||
for (int i = 0; i < inv.getSize(); i++)
|
||||
inv.setItem(i, ChatItem.getPlatform().createItemStack(ItemUtils.WHITE_STAINED_GLASS, "-"));
|
||||
|
||||
int slot = 0;
|
||||
for(String manager : Arrays.asList("both", "auto", "packet", "chat")) {
|
||||
for (String manager : Arrays.asList("all", "packet", "chat", "paper")) { //, "ownformatter")) {
|
||||
if ((manager == "paper" || manager == "ownformatter") && !Utils.IS_PAPER)
|
||||
continue;
|
||||
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.colorIfColored));
|
||||
inv.setItem(19, getBoolChangeItem(Material.REDSTONE, "deny-no-item", c.denyIfNoItem));
|
||||
inv.setItem(20, getBoolChangeItem(Material.STICK, "hand-disabled", c.handDisabled));
|
||||
inv.setItem(21, getAmountChangeItem(Material.IRON_DOOR, "limit-per-message", c.limit));
|
||||
inv.setItem(22, getAmountChangeItem(Material.APPLE, "cooldown", c.cooldown));
|
||||
inv.setItem(23, getBoolChangeItem(Material.BLAZE_ROD, "check-update", c.checkUpdate));
|
||||
inv.setItem(24, createItem(Material.BOOK, Messages.getMessage("admin-inv.language.name"),
|
||||
Messages.getMessage("admin-inv.language.lore", "%name%", Translation.getMessages().get("language.name").getAsString())));
|
||||
|
||||
inv.setItem(26, createItem(ItemUtils.MATERIAL_CLOSE, Messages.getMessage("admin-inv.close")));
|
||||
inv.setItem(24, ChatItem.getPlatform().createTranslatedItemStack(Material.BOOK, "admin-inv.language", "%name%", Translation.getMessage("language.name")));
|
||||
|
||||
inv.setItem(26, ChatItem.getPlatform().createItemStack(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"));
|
||||
return ChatItem.getPlatform().createItemStack(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"));
|
||||
return ChatItem.getPlatform().createItemStack(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));
|
||||
return ChatItem.getPlatform().createTranslatedItemStack(Material.PAPER, "admin-inv.manager." + manager, placeholders);
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import net.md_5.bungee.api.chat.TextComponent;
|
||||
|
||||
public class JoinListener implements Listener {
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
@EventHandler
|
||||
public void onJoin(PlayerJoinEvent e) {
|
||||
Player p = e.getPlayer();
|
||||
|
||||
@@ -1,14 +1,9 @@
|
||||
package me.dadus33.chatitem.listeners;
|
||||
|
||||
import static me.dadus33.chatitem.utils.ItemUtils.createItem;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.enchantments.Enchantment;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
@@ -21,6 +16,7 @@ import org.bukkit.inventory.meta.ItemMeta;
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
import me.dadus33.chatitem.Translation;
|
||||
import me.dadus33.chatitem.listeners.holder.TranslationHolder;
|
||||
import me.dadus33.chatitem.utils.Colors;
|
||||
import me.dadus33.chatitem.utils.ItemUtils;
|
||||
import me.dadus33.chatitem.utils.Messages;
|
||||
|
||||
@@ -55,7 +51,7 @@ public class TranslationInventoryListener implements Listener {
|
||||
pl.getConfig().set("general.language", lang);
|
||||
pl.saveConfig();
|
||||
Translation.loadLang(lang);
|
||||
p.sendMessage(ChatColor.GREEN + "Language changed to " + Translation.getMessages().get("language.name").getAsString());
|
||||
p.sendMessage(Colors.GREEN + "Language changed to " + Translation.getMessages().get("language.name").getAsString());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -64,25 +60,25 @@ public class TranslationInventoryListener implements Listener {
|
||||
int perPage = 45;
|
||||
List<String> langs = new ArrayList<>(Translation.getAllLangs().keySet());
|
||||
TranslationHolder holder = new TranslationHolder(page);
|
||||
Inventory inv = Bukkit.createInventory(holder, 54, "Change language - " + ChatColor.GOLD + " Page " + (page + 1) + " / " + ((langs.size() / perPage) + 1));
|
||||
Inventory inv = ChatItem.getPlatform().createInventory(holder, 54, "Change language - " + Colors.GOLD + " Page " + (page + 1) + " / " + ((langs.size() / perPage) + 1));
|
||||
for(int i = 0; i < 9; i ++)
|
||||
inv.setItem(i, new ItemStack(ItemUtils.GRAY_STAINED_GLASS_PANE));
|
||||
inv.setItem(0, createItem(Material.ARROW, ChatColor.GRAY + "Back"));
|
||||
inv.setItem(0, ChatItem.getPlatform().createItemStack(Material.ARROW, Colors.GRAY + "Back"));
|
||||
|
||||
if(page > 0)
|
||||
inv.setItem(3, createItem(Material.ARROW, ChatColor.RED + "Previous page"));
|
||||
inv.setItem(3, ChatItem.getPlatform().createItemStack(Material.ARROW, Colors.RED + "Previous page"));
|
||||
if(langs.size() > (perPage * (page + 1)))
|
||||
inv.setItem(5, createItem(Material.ARROW, ChatColor.GREEN + "Next page"));
|
||||
inv.setItem(5, ChatItem.getPlatform().createItemStack(Material.ARROW, Colors.GREEN + "Next page"));
|
||||
|
||||
inv.setItem(8, createItem(ItemUtils.MATERIAL_CLOSE, Messages.getMessage("admin-inv.close")));
|
||||
inv.setItem(8, ChatItem.getPlatform().createItemStack(ItemUtils.MATERIAL_CLOSE, Messages.getMessage("admin-inv.close")));
|
||||
|
||||
int slot = 9;
|
||||
for(int i = (page * perPage); i < langs.size() && (i < ((page + 1) * perPage)); i++) {
|
||||
String lang = langs.get(i);
|
||||
holder.langBySlot.put(slot, lang);
|
||||
ItemStack item = createItem(Material.PAPER, ChatColor.GOLD + Translation.getAllLangs().get(lang), ChatColor.GRAY + "Clic to select this language");
|
||||
ItemStack item = ChatItem.getPlatform().createItemStack(Material.PAPER, Colors.GOLD + Translation.getAllLangs().get(lang), Colors.GRAY + "Clic to select this language");
|
||||
if(lang.equalsIgnoreCase(ChatItem.getInstance().getStorage().language)) {
|
||||
item.addUnsafeEnchantment(Enchantment.DURABILITY, 1);
|
||||
item.addUnsafeEnchantment(ItemUtils.getEnchant("DURABILITY", "UNBREAKING"), 1);
|
||||
ItemMeta meta = item.getItemMeta();
|
||||
meta.addItemFlags(ItemFlag.HIDE_ENCHANTS);
|
||||
item.setItemMeta(meta);
|
||||
|
||||
@@ -2,16 +2,8 @@ package me.dadus33.chatitem.listeners.holder;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
import org.bukkit.inventory.Inventory;
|
||||
import org.bukkit.inventory.InventoryHolder;
|
||||
|
||||
public class AdminHolder implements InventoryHolder {
|
||||
public class AdminHolder extends ChatItemHolder {
|
||||
|
||||
public final HashMap<Integer, String> keyBySlot = new HashMap<>();
|
||||
|
||||
@Override
|
||||
public Inventory getInventory() {
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package me.dadus33.chatitem.listeners.holder;
|
||||
|
||||
import org.bukkit.inventory.Inventory;
|
||||
import org.bukkit.inventory.InventoryHolder;
|
||||
|
||||
public abstract class ChatItemHolder implements InventoryHolder {
|
||||
|
||||
@Override
|
||||
public Inventory getInventory() {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package me.dadus33.chatitem.listeners.holder;
|
||||
|
||||
public class CustomInventoryHolder extends ChatItemHolder {
|
||||
|
||||
}
|
||||
@@ -2,10 +2,7 @@ package me.dadus33.chatitem.listeners.holder;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
import org.bukkit.inventory.Inventory;
|
||||
import org.bukkit.inventory.InventoryHolder;
|
||||
|
||||
public class TranslationHolder implements InventoryHolder {
|
||||
public class TranslationHolder extends ChatItemHolder {
|
||||
|
||||
public final HashMap<Integer, String> langBySlot = new HashMap<>();
|
||||
private final int page;
|
||||
@@ -17,9 +14,4 @@ public class TranslationHolder implements InventoryHolder {
|
||||
public int getPage() {
|
||||
return page;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Inventory getInventory() {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package me.dadus33.chatitem.platform;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.Inventory;
|
||||
import org.bukkit.inventory.InventoryHolder;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
|
||||
import me.dadus33.chatitem.chatmanager.ChatAction;
|
||||
import me.dadus33.chatitem.utils.Messages;
|
||||
import me.dadus33.chatitem.utils.Version;
|
||||
|
||||
public interface IPlatform {
|
||||
|
||||
String getName();
|
||||
|
||||
Inventory createInventory(InventoryHolder holder, int slot, String name);
|
||||
|
||||
ItemStack createItemStack(Material type, String name);
|
||||
|
||||
default ItemStack createTranslatedItemStack(Material type, String key, Object... placeholders) {
|
||||
return createItemStack(type, Messages.getMessage(key + ".name", placeholders), Messages.getMessageList(key + ".lore", placeholders));
|
||||
}
|
||||
|
||||
default ItemStack createItemStack(Material type, String name, String... lore) {
|
||||
return createItemStack(type, name, Arrays.asList(lore));
|
||||
}
|
||||
|
||||
ItemStack createItemStack(Material type, String name, List<String> lore);
|
||||
|
||||
String getItemDisplayName(ItemStack item);
|
||||
|
||||
String getPluginVersion(Plugin plugin);
|
||||
|
||||
Version getMinecraftVersion();
|
||||
|
||||
String getNMSVersion();
|
||||
|
||||
boolean hasBaseComponentSerializer();
|
||||
|
||||
String baseComponentToJson(Object obj);
|
||||
|
||||
Object jsonToBaseComponent(String json);
|
||||
|
||||
void sendMessage(Player to, Player origin, ChatAction action, String msg);
|
||||
|
||||
String stringifyItem(ItemStack item);
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
package me.dadus33.chatitem.platform.hook;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.Inventory;
|
||||
import org.bukkit.inventory.InventoryHolder;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.meta.ItemMeta;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
|
||||
import me.dadus33.chatitem.C;
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
import me.dadus33.chatitem.chatmanager.ChatAction;
|
||||
import me.dadus33.chatitem.chatmanager.ChatManager;
|
||||
import me.dadus33.chatitem.platform.IPlatform;
|
||||
import me.dadus33.chatitem.utils.Messages;
|
||||
import me.dadus33.chatitem.utils.ReflectionUtils;
|
||||
import me.dadus33.chatitem.utils.Version;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.TextComponent;
|
||||
import net.kyori.adventure.text.TextReplacementConfig;
|
||||
import net.kyori.adventure.text.event.ClickEvent;
|
||||
import net.kyori.adventure.text.event.HoverEvent;
|
||||
import net.kyori.adventure.text.event.HoverEvent.ShowItem;
|
||||
import net.kyori.adventure.text.event.HoverEventSource;
|
||||
import net.kyori.adventure.text.format.NamedTextColor;
|
||||
|
||||
public class PaperPlatform implements IPlatform {
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "PaperMC";
|
||||
}
|
||||
|
||||
@Override
|
||||
public Inventory createInventory(InventoryHolder holder, int slot, String name) {
|
||||
return Bukkit.createInventory(holder, slot, C.text(name));
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemStack createItemStack(Material type, String name) {
|
||||
ItemStack item = new ItemStack(type);
|
||||
ItemMeta meta = (ItemMeta) item.getItemMeta();
|
||||
meta.displayName(C.text(name).color(NamedTextColor.WHITE));
|
||||
item.setItemMeta(meta);
|
||||
return item;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemStack createItemStack(Material type, String name, List<String> lore) {
|
||||
ItemStack item = new ItemStack(type);
|
||||
ItemMeta meta = (ItemMeta) item.getItemMeta();
|
||||
meta.displayName(C.text(name).color(NamedTextColor.WHITE));
|
||||
meta.lore(lore.stream().map(C::text).collect(Collectors.toList()));
|
||||
item.setItemMeta(meta);
|
||||
return item;
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
@Override
|
||||
public String getItemDisplayName(ItemStack item) {
|
||||
// actually the get Displayname for better ... See:
|
||||
// https://github.com/KyoriPowered/adventure-platform/issues/185
|
||||
// return
|
||||
// LegacyComponentSerializer.legacySection().serialize(item.displayName());
|
||||
return item.hasItemMeta() && item.getItemMeta().hasDisplayName() ? item.getItemMeta().getDisplayName() : null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPluginVersion(Plugin plugin) {
|
||||
return plugin.getPluginMeta().getVersion();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Version getMinecraftVersion() {
|
||||
return Version.getVersionByName("v" + Bukkit.getMinecraftVersion().replace(".", "_"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getNMSVersion() {
|
||||
String[] parts = Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",");
|
||||
return parts.length <= 3 ? "" : parts[3];
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasBaseComponentSerializer() {
|
||||
return SpigotPlatform.getBaseComponentToJsonMethod() != null;
|
||||
}
|
||||
|
||||
private Object getRegistry() throws Exception {
|
||||
Class<?> serverClass = Class.forName("net.minecraft.server.MinecraftServer");
|
||||
return serverClass.getDeclaredMethod("registryAccess").invoke(serverClass.getDeclaredMethod("getServer").invoke(null));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String baseComponentToJson(Object obj) {
|
||||
Method m = SpigotPlatform.getBaseComponentToJsonMethod();
|
||||
if (m == null)
|
||||
return null;
|
||||
try {
|
||||
Object[] args = new Object[m.getParameterCount()];
|
||||
args[0] = obj;
|
||||
if (args.length > 1 && ReflectionUtils.isClassExist("net.minecraft.core.HolderLookup$Provider")) {
|
||||
Class<?> c = Class.forName("net.minecraft.core.HolderLookup$Provider");
|
||||
if (m.getParameterTypes()[1].isAssignableFrom(c)) {
|
||||
args[1] = getRegistry();
|
||||
}
|
||||
}
|
||||
return (String) m.invoke(null, args);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object jsonToBaseComponent(String json) {
|
||||
Method m = SpigotPlatform.getJsonToBaseComponentMethod();
|
||||
try {
|
||||
Object[] args = new Object[m.getParameterCount()];
|
||||
args[0] = json;
|
||||
if (args.length > 1 && ReflectionUtils.isClassExist("net.minecraft.core.HolderLookup$Provider")) {
|
||||
Class<?> c = Class.forName("net.minecraft.core.HolderLookup$Provider");
|
||||
if (m.getParameterTypes()[1].isAssignableFrom(c)) {
|
||||
args[1] = getRegistry();
|
||||
}
|
||||
}
|
||||
return m.invoke(null, args);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendMessage(Player to, Player origin, ChatAction action, String msg) {
|
||||
HoverEventSource<?> hoverEvent = null;
|
||||
if (action.isItem()) {
|
||||
if (!action.getItem().getType().equals(Material.AIR))
|
||||
hoverEvent = action.getItem().asHoverEvent();
|
||||
else {
|
||||
Component t = null;
|
||||
for (String line : Messages.getMessageList("general.hand.tooltip", "%cible%", origin.getName())) {
|
||||
if (t == null) {
|
||||
t = Component.text("");
|
||||
} else
|
||||
t.append(Component.newline());
|
||||
t.append(C.text(line));
|
||||
}
|
||||
hoverEvent = HoverEvent.showText(t);
|
||||
}
|
||||
} else
|
||||
hoverEvent = HoverEvent.showText(C.text(Messages.getMessage(action.getSlot().name().toLowerCase() + ".hover", "%cible%", origin.getName())));
|
||||
TextComponent like = Component.text(ChatManager.getNameForChatAction(origin, action, ChatItem.getInstance().getStorage())).hoverEvent(hoverEvent);
|
||||
if (action.hasCommand())
|
||||
like = like.clickEvent(ClickEvent.runCommand(action.getCommand()));
|
||||
|
||||
to.sendMessage(C.text(msg).replaceText(TextReplacementConfig.builder().matchLiteral(ChatManager.SEPARATOR + "").replacement(like).build()));
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
@Override
|
||||
public String stringifyItem(ItemStack item) {
|
||||
ShowItem si = item.asHoverEvent().value();
|
||||
String json = "{id:\"" + si.item().asString() + "\",count:" + item.getAmount();
|
||||
if(si.nbt() != null) {
|
||||
json += ",tag:{" + si.nbt().string() + "}";
|
||||
} else if(Version.getVersion().isNewerOrEquals(Version.V1_20_6)) { // since MC 1.20.5 in fact
|
||||
json += ",components:" + (item.hasItemMeta() ? item.getItemMeta().getAsString() : "{}");
|
||||
}
|
||||
json += "}";
|
||||
ChatItem.debug("Item stringified: " + json);
|
||||
return json;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,450 @@
|
||||
package me.dadus33.chatitem.platform.hook;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.Inventory;
|
||||
import org.bukkit.inventory.InventoryHolder;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.meta.ItemMeta;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
import me.dadus33.chatitem.ItemPlayer;
|
||||
import me.dadus33.chatitem.Storage;
|
||||
import me.dadus33.chatitem.chatmanager.ChatAction;
|
||||
import me.dadus33.chatitem.chatmanager.ChatManager;
|
||||
import me.dadus33.chatitem.chatmanager.v1.json.JSONManipulator;
|
||||
import me.dadus33.chatitem.platform.IPlatform;
|
||||
import me.dadus33.chatitem.playernamer.PlayerNamerManager;
|
||||
import me.dadus33.chatitem.utils.ColorManager;
|
||||
import me.dadus33.chatitem.utils.Colors;
|
||||
import me.dadus33.chatitem.utils.ItemUtils;
|
||||
import me.dadus33.chatitem.utils.Messages;
|
||||
import me.dadus33.chatitem.utils.PacketUtils;
|
||||
import me.dadus33.chatitem.utils.ReflectionUtils;
|
||||
import me.dadus33.chatitem.utils.Utils;
|
||||
import me.dadus33.chatitem.utils.Version;
|
||||
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.TextComponent;
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
public class SpigotPlatform implements IPlatform {
|
||||
|
||||
private static boolean shouldUseAppendMethod = false;
|
||||
|
||||
static {
|
||||
try {
|
||||
try {
|
||||
ComponentBuilder.class.getDeclaredMethod("append", BaseComponent[].class);
|
||||
shouldUseAppendMethod = true;
|
||||
} catch (Exception e) {
|
||||
shouldUseAppendMethod = false;
|
||||
}
|
||||
ChatItem.getInstance().getLogger().info(shouldUseAppendMethod ? "Use ComponentBuilder's method." : "Use own ComponentBuilder append method.");
|
||||
} catch (Exception e) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "Spigot";
|
||||
}
|
||||
|
||||
@Override
|
||||
public Inventory createInventory(InventoryHolder holder, int slot, String name) {
|
||||
return Bukkit.createInventory(holder, slot, name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemStack createItemStack(Material type, String name) {
|
||||
ItemStack item = new ItemStack(type);
|
||||
ItemMeta meta = (ItemMeta) item.getItemMeta();
|
||||
meta.setDisplayName(Colors.RESET + name);
|
||||
item.setItemMeta(meta);
|
||||
return item;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemStack createItemStack(Material type, String name, List<String> lore) {
|
||||
ItemStack item = new ItemStack(type);
|
||||
ItemMeta meta = (ItemMeta) item.getItemMeta();
|
||||
meta.setDisplayName(Colors.RESET + name);
|
||||
meta.setLore(lore);
|
||||
item.setItemMeta(meta);
|
||||
return item;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getItemDisplayName(ItemStack item) {
|
||||
return item.hasItemMeta() && item.getItemMeta().hasDisplayName() ? item.getItemMeta().getDisplayName() : null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPluginVersion(Plugin plugin) {
|
||||
return plugin.getDescription().getVersion();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Version getMinecraftVersion() {
|
||||
return Version.getVersionByName(getNMSVersion().replace("_R4", "_6"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getNMSVersion() {
|
||||
return Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3];
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasBaseComponentSerializer() {
|
||||
return getBaseComponentToJsonMethod() != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String baseComponentToJson(Object obj) {
|
||||
Method m = getBaseComponentToJsonMethod();
|
||||
try {
|
||||
Object[] args = new Object[m.getParameterCount()];
|
||||
args[0] = obj;
|
||||
if (args.length > 1 && ReflectionUtils.isClassExist("net.minecraft.core.HolderLookup$a")) {
|
||||
Class<?> c = Class.forName("net.minecraft.core.HolderLookup$a");
|
||||
if (m.getParameterTypes()[1].isAssignableFrom(c)) {
|
||||
args[1] = getRegistry();
|
||||
}
|
||||
}
|
||||
return (String) m.invoke(null, args);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object jsonToBaseComponent(String json) {
|
||||
Method m = getJsonToBaseComponentMethod();
|
||||
try {
|
||||
Object[] args = new Object[m.getParameterCount()];
|
||||
args[0] = json;
|
||||
if (args.length > 1 && ReflectionUtils.isClassExist("net.minecraft.core.HolderLookup$a")) {
|
||||
Class<?> c = Class.forName("net.minecraft.core.HolderLookup$a");
|
||||
if (m.getParameterTypes()[1].isAssignableFrom(c)) {
|
||||
args[1] = getRegistry();
|
||||
}
|
||||
}
|
||||
return m.invoke(null, args);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private Object getRegistry() throws Exception {
|
||||
Class<?> serverClass = Class.forName("net.minecraft.server.MinecraftServer");
|
||||
return serverClass.getDeclaredMethod("ba").invoke(serverClass.getDeclaredMethod("getServer").invoke(null));
|
||||
}
|
||||
|
||||
public static Method getBaseComponentToJsonMethod() {
|
||||
Class<?> chatSerializerClass = PacketUtils.getNmsClass("IChatBaseComponent$ChatSerializer", "network.chat.", "ChatSerializer", "Component$Serializer");
|
||||
Class<?> chatBaseComponentClass = PacketUtils.getNmsClass("IChatBaseComponent", "network.chat.", "Component");
|
||||
if (chatSerializerClass == null || chatBaseComponentClass == null)
|
||||
return null;
|
||||
try {
|
||||
for (Method m : chatSerializerClass.getDeclaredMethods()) {
|
||||
if (m.getParameterTypes()[0].equals(chatBaseComponentClass) && m.getReturnType().equals(String.class)) {
|
||||
return m;
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static Method getJsonToBaseComponentMethod() {
|
||||
Class<?> chatSerializerClass = PacketUtils.getNmsClass("IChatBaseComponent$ChatSerializer", "network.chat.", "ChatSerializer", "Component$Serializer");
|
||||
Class<?> chatBaseComponentClass = PacketUtils.getNmsClass("IChatBaseComponent", "network.chat.", "Component");
|
||||
Class<?> chatMutableComponentClass = PacketUtils.getNmsClass("IChatMutableComponent", "network.chat.");
|
||||
if (chatSerializerClass == null || chatBaseComponentClass == null)
|
||||
return null;
|
||||
try {
|
||||
for (Method m : chatSerializerClass.getDeclaredMethods()) {
|
||||
if (m.getParameterCount() == 0)
|
||||
continue;
|
||||
if (m.getParameterTypes()[0].equals(String.class)
|
||||
&& (m.getReturnType().isAssignableFrom(chatBaseComponentClass) || (chatMutableComponentClass != null && m.getReturnType().equals(chatMutableComponentClass)))) {
|
||||
m.setAccessible(true);
|
||||
return m;
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendMessage(Player to, Player origin, ChatAction action, String msg) {
|
||||
ComponentBuilder builder = new ComponentBuilder("");
|
||||
ChatColor color = ChatColor.WHITE;
|
||||
String colorCode = "", text = "";
|
||||
boolean waiting = false, removing = false;
|
||||
for (char args : msg.toCharArray()) {
|
||||
if (args == '§') { // begin of color
|
||||
if (colorCode.isEmpty() && !text.isEmpty()) { // text before this char
|
||||
if (text.length() > 2 && text.startsWith("§") && text.substring(2) == ChatColor.stripColor(text) && color != null && color != ChatColor.WHITE) {
|
||||
text = text.substring(2); // remove some code which should not be here
|
||||
}
|
||||
appendToComponentBuilder(builder, createComponent(to, text, color, action));
|
||||
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;
|
||||
} else if (args == 'x') {
|
||||
if (!colorCode.isEmpty()) {
|
||||
color = ColorManager.getColor(colorCode);
|
||||
colorCode = ""; // clean for previous things
|
||||
}
|
||||
}
|
||||
colorCode += args;
|
||||
} 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
|
||||
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(to, text, color, action));
|
||||
if (action.isItem())
|
||||
addItem(builder, to, origin, action.getItem(), action);
|
||||
else
|
||||
addCommand(builder, to, origin, action.getCommand(), action);
|
||||
text = "";
|
||||
if (ChatManager.containsSeparatorEnd(msg))
|
||||
removing = true;
|
||||
} else if (args == ChatManager.SEPARATOR_END) {
|
||||
removing = false;
|
||||
} else if (!removing) { // not removing content
|
||||
// basic text, not waiting for code after '§'
|
||||
text += args;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!text.isEmpty())
|
||||
appendToComponentBuilder(builder, createComponent(to, text, color, action));
|
||||
to.spigot().sendMessage(builder.create());
|
||||
}
|
||||
|
||||
public static void addItem(ComponentBuilder builder, Player to, Player origin, ItemStack item, ChatAction action) {
|
||||
Storage c = ChatItem.getInstance().getStorage();
|
||||
if (!ItemUtils.isEmpty(item)) {
|
||||
ComponentBuilder itemComponent = new ComponentBuilder("");
|
||||
appendToComponentBuilder(itemComponent, fixColorComponent(to, ChatManager.getNameOfItem(origin, item, to, c), ChatColor.WHITE, action));
|
||||
ChatItem.debug("Item for " + to.getName() + " (ver: " + ItemPlayer.getPlayer(to).getVersion().name() + ") : " + PacketUtils.getNbtTag(item));
|
||||
// itemComponent.event(new HoverEvent(Action.SHOW_ITEM, itemBaseComponent));
|
||||
appendToComponentBuilder(builder, itemComponent.create());
|
||||
} else {
|
||||
String handName = c.handName;
|
||||
ComponentBuilder handComp = new ComponentBuilder("");
|
||||
ComponentBuilder handTooltip = new ComponentBuilder("");
|
||||
int stay = c.tooltipHand.size();
|
||||
for (String line : c.tooltipHand) {
|
||||
stay--;
|
||||
handTooltip.append(ColorManager.fixColor(line.replace("{name}", origin.getName()).replace("{display-name}", origin.getDisplayName())));
|
||||
if (stay > 0)
|
||||
handTooltip.append("\n");
|
||||
}
|
||||
handComp.event(Utils.createTextHover(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());
|
||||
}
|
||||
}
|
||||
|
||||
public static void addCommand(ComponentBuilder builder, Player to, Player origin, String command, ChatAction action) {
|
||||
ComponentBuilder itemComponent = new ComponentBuilder("");
|
||||
appendToComponentBuilder(itemComponent, fixColorComponent(to, Messages.getMessage(action.getSlot().name().toLowerCase() + ".chat", "%cible%", origin.getName()), ChatColor.WHITE, action));
|
||||
appendToComponentBuilder(builder, itemComponent.create());
|
||||
}
|
||||
|
||||
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(Player to, String message, ChatColor color, ChatAction action) {
|
||||
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 " + (ColorManager.isHexColor(color) && builder.getParts().isEmpty() ? ColorManager.removeColorAtBegin(text) : text));
|
||||
appendToComponentBuilder(builder, createComponent(to, ColorManager.isHexColor(color) ? ColorManager.removeColorAtBegin(text) : text, color, action));
|
||||
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
|
||||
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, createComponent(to, text, color, action));
|
||||
}
|
||||
return builder.create();
|
||||
}
|
||||
|
||||
private static BaseComponent[] createComponent(Player to, String text, ChatColor color, ChatAction action) {
|
||||
ComponentBuilder littleBuilder = new ComponentBuilder(ChatItem.replace(action.getOrigin(), text));
|
||||
if (color != null && !Colors.isFormatting(color)) // don't add reset thing
|
||||
littleBuilder.color(color);
|
||||
if (action.isItem()) {
|
||||
if (action.getItem().getType().equals(Material.AIR))
|
||||
littleBuilder.event(Utils.createTextHover(String.join("\n", ChatItem.getInstance().getStorage().tooltipHand)));
|
||||
else
|
||||
littleBuilder.event(Utils.createItemHover(action.getItem(), to));
|
||||
} else {
|
||||
littleBuilder.event(Utils.createTextHover(Messages.getMessage(action.getSlot().name().toLowerCase() + ".hover")));
|
||||
if (action.hasCommand())
|
||||
littleBuilder.event(Utils.createRunCommand(action.getCommand()));
|
||||
}
|
||||
return littleBuilder.create();
|
||||
}
|
||||
|
||||
private static final List<String> SKIPPED = Arrays.asList("HSTRY_ENCHANTS");
|
||||
|
||||
@Override
|
||||
public String stringifyItem(ItemStack item) {
|
||||
try {
|
||||
ChatItem.debug("[JSONManipulator] stringifying item");
|
||||
Object nmsStack = JSONManipulator.AS_NMS_COPY.invoke(null, item);
|
||||
Object nmsTag = JSONManipulator.NBT_TAG_COMPOUND.newInstance();
|
||||
JSONManipulator.SAVE_NMS_ITEM_STACK_METHOD.invoke(nmsStack, nmsTag);
|
||||
HashMap<String, String> tagMap = new HashMap<>();
|
||||
Map<String, Object> nmsMap = (Map<String, Object>) JSONManipulator.MAP.get(nmsTag);
|
||||
String id = nmsMap.get("id").toString().replace("\"", "");
|
||||
Object realTag = nmsMap.get("tag");
|
||||
if (JSONManipulator.NBT_TAG_COMPOUND.isInstance(realTag)) { // We need to make sure this is indeed an
|
||||
// NBTTagCompound
|
||||
Map<String, Object> realMap = (Map<String, Object>) JSONManipulator.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:");
|
||||
sb.append("\"").append(id).append("\"").append(","); // Append the id
|
||||
sb.append("Count:").append(item.getAmount()).append("b"); // Append the amount
|
||||
|
||||
if (!tagMap.containsKey("Damage")) { // for new versions
|
||||
sb.append(",Damage:").append(item.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 (SKIPPED.contains(entry.getKey()))
|
||||
continue;
|
||||
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(":");
|
||||
}
|
||||
sb.append(Utils.cleanStr(entry.getValue()));
|
||||
}
|
||||
sb.append("}}"); // End of tag and end of item
|
||||
return sb.toString();
|
||||
} catch (Exception e) {
|
||||
return "{}";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,12 @@
|
||||
package me.dadus33.chatitem.playernamer;
|
||||
|
||||
import me.dadus33.chatitem.playernamer.hook.HexNicksV3PlayerNamer;
|
||||
import org.bukkit.Bukkit;
|
||||
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
import me.dadus33.chatitem.playernamer.hook.DefaultPlayerNamer;
|
||||
import me.dadus33.chatitem.playernamer.hook.HexNicksPlayerNamer;
|
||||
import me.dadus33.chatitem.playernamer.hook.HexNicksV2PlayerNamer;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
|
||||
public class PlayerNamerManager {
|
||||
|
||||
@@ -17,11 +19,24 @@ public class PlayerNamerManager {
|
||||
}
|
||||
|
||||
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());
|
||||
Plugin plugin = Bukkit.getPluginManager().getPlugin("HexNicks");
|
||||
|
||||
|
||||
if (plugin != null) {
|
||||
char majorVersion = ChatItem.getPlatform().getPluginVersion(plugin).charAt(0);
|
||||
|
||||
if (majorVersion == '3')
|
||||
setPlayerNamer(new HexNicksV3PlayerNamer());
|
||||
else
|
||||
setPlayerNamer(new HexNicksV2PlayerNamer());
|
||||
|
||||
pl.getLogger().info("Enable support for HexNicks plugin v" + majorVersion);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
|
||||
setPlayerNamer(new DefaultPlayerNamer());
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package me.dadus33.chatitem.playernamer.hook;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import me.dadus33.chatitem.playernamer.IPlayerNamer;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.serializer.bungeecord.BungeeComponentSerializer;
|
||||
import net.md_5.bungee.api.chat.BaseComponent;
|
||||
|
||||
public class HexNicksV2PlayerNamer implements IPlayerNamer {
|
||||
|
||||
@Override
|
||||
public BaseComponent[] getName(Player p) {
|
||||
try {
|
||||
Object api = Class.forName("dev.majek.hexnicks.Nicks").getDeclaredMethod("api").invoke(null);
|
||||
CompletableFuture<Component> storedNick = (CompletableFuture<Component>) api.getClass().getDeclaredMethod("getStoredNick", Player.class).invoke(api, p);
|
||||
return BungeeComponentSerializer.get().serialize(storedNick.join());
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return new BaseComponent[0];
|
||||
}
|
||||
|
||||
}
|
||||
+6
-6
@@ -1,17 +1,17 @@
|
||||
package me.dadus33.chatitem.playernamer.hook;
|
||||
|
||||
import dev.majek.hexnicks.HexNicks;
|
||||
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 {
|
||||
public class HexNicksV3PlayerNamer implements IPlayerNamer {
|
||||
|
||||
@Override
|
||||
public BaseComponent[] getName(Player p) {
|
||||
return BungeeComponentSerializer.get().serialize(Nicks.api().getStoredNick(p).join());
|
||||
}
|
||||
@Override
|
||||
public BaseComponent[] getName(Player p) {
|
||||
return BungeeComponentSerializer.get().serialize(HexNicks.api().getStoredNick(p).join());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,7 +1,5 @@
|
||||
package me.dadus33.chatitem.playerversion.hooks;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import me.dadus33.chatitem.playerversion.IPlayerVersion;
|
||||
@@ -9,10 +7,8 @@ import me.dadus33.chatitem.utils.Version;
|
||||
|
||||
public class DefaultVersionHook implements IPlayerVersion {
|
||||
|
||||
public static final HashMap<String, Integer> PROTOCOL_PER_ADDRESS = new HashMap<>();
|
||||
|
||||
@Override
|
||||
public int getProtocolVersion(Player p) {
|
||||
return PROTOCOL_PER_ADDRESS.getOrDefault(Version.stringifyAdress(p.getAddress()), Version.getVersion().MAX_VER);
|
||||
return Version.getVersion().MAX_VER;
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,8 @@ import net.md_5.bungee.api.ChatColor;
|
||||
|
||||
public class ColorManager {
|
||||
|
||||
public static final List<String> COLORS = Arrays.asList("4", "c", "6", "e", "2", "a", "b", "3", "1", "9", "d", "5", "f", "7", "8", "0");
|
||||
public static final char COLOR_CHAR = '§';
|
||||
public static final List<String> COLORS = Arrays.asList("4", "c", "6", "e", "2", "a", "b", "3", "1", "9", "d", "5", "f", "7", "8", "0", "k", "l", "m", "n", "o", "r");
|
||||
|
||||
public static boolean isHexColor(ChatColor c) {
|
||||
return Version.getVersion().isNewerOrEquals(Version.V1_16) && c.getName().startsWith("#");
|
||||
@@ -82,7 +83,7 @@ public class ColorManager {
|
||||
String colorCode = "", text = "";
|
||||
boolean waiting = false;
|
||||
for (char args : message.toCharArray()) {
|
||||
if (args == '§') { // begin of color
|
||||
if (args == COLOR_CHAR) { // 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
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
package me.dadus33.chatitem.utils;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import com.google.common.base.Preconditions;
|
||||
|
||||
import net.md_5.bungee.api.ChatColor;
|
||||
|
||||
public class Colors {
|
||||
|
||||
public static final String YELLOW = ColorManager.COLOR_CHAR + "e";
|
||||
public static final String AQUA = ColorManager.COLOR_CHAR + "b";
|
||||
public static final String GOLD = ColorManager.COLOR_CHAR + "6";
|
||||
public static final String GRAY = ColorManager.COLOR_CHAR + "7";
|
||||
public static final String RED = ColorManager.COLOR_CHAR + "c";
|
||||
public static final String GREEN = ColorManager.COLOR_CHAR + "a";
|
||||
public static final String RESET = ColorManager.COLOR_CHAR + "r";
|
||||
|
||||
|
||||
public static String color(String s) {
|
||||
return s == null || s.isEmpty() ? s : translateAlternateColorCodes('&', s);
|
||||
}
|
||||
|
||||
public static String translateAlternateColorCodes(char altColorChar, @NotNull String textToTranslate) {
|
||||
Preconditions.checkArgument(textToTranslate != null, "Cannot translate null text");
|
||||
|
||||
char[] b = textToTranslate.toCharArray();
|
||||
for (int i = 0; i < b.length - 1; i++) {
|
||||
if (b[i] == altColorChar && ColorManager.COLORS.contains(b[i + 1] + "")) {
|
||||
b[i] = ColorManager.COLOR_CHAR;
|
||||
b[i + 1] = Character.toLowerCase(b[i + 1]);
|
||||
}
|
||||
}
|
||||
return new String(b);
|
||||
}
|
||||
|
||||
public static boolean isFormatting(ChatColor c) {
|
||||
return Arrays.asList(ChatColor.RESET, ChatColor.BOLD, ChatColor.MAGIC, ChatColor.UNDERLINE, ChatColor.ITALIC, ChatColor.STRIKETHROUGH).contains(c);
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,14 @@
|
||||
package me.dadus33.chatitem.utils;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.enchantments.Enchantment;
|
||||
import org.bukkit.inventory.ItemFlag;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.meta.ItemMeta;
|
||||
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
|
||||
public class ItemUtils {
|
||||
|
||||
public static final Material MATERIAL_CLOSE = getMaterialWithCompatibility("BARRIER", "REDSTONE_BLOCK");
|
||||
@@ -24,8 +24,11 @@ public class ItemUtils {
|
||||
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 final Material BROWN_STAINED_GLASS_PANE = getMaterialWithCompatibility("BROWN_STAINED_GLASS_PANE", "STAINED_GLASS_PANE");
|
||||
public static final Material GRAY_STAINED_GLASS_PANE = getMaterialWithCompatibility("GRAY_STAINED_GLASS_PANE", "STAINED_GLASS_PANE");
|
||||
public static final Material WHITE_STAINED_GLASS = getMaterialWithCompatibility("WHITE_STAINED_GLASS_PANE", "STAINED_GLASS_PANE");
|
||||
|
||||
public static final ItemStack ITEM_EMPTY_BROWN = ChatItem.getPlatform().createItemStack(BROWN_STAINED_GLASS_PANE, "");
|
||||
|
||||
public static Material getMaterialWithCompatibility(String... tempMat) {
|
||||
for(String s : tempMat) {
|
||||
@@ -39,54 +42,49 @@ public class ItemUtils {
|
||||
}
|
||||
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);
|
||||
}
|
||||
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 ItemStack copyIfExist(ItemStack item) {
|
||||
return isEmpty(item) ? null : item.clone();
|
||||
}
|
||||
|
||||
public static boolean isEmpty(ItemStack item) {
|
||||
return item == null || item.getType().equals(Material.AIR);
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
public static 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")
|
||||
public static Enchantment getEnchant(String... names) {
|
||||
for(String name : names) {
|
||||
Enchantment possible = Enchantment.getByName(name);
|
||||
if(possible != null)
|
||||
return possible;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package me.dadus33.chatitem.utils;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
@@ -9,18 +10,18 @@ import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
import me.dadus33.chatitem.chatmanager.v1.json.JSONManipulator;
|
||||
|
||||
public class PacketUtils {
|
||||
|
||||
public static final String VERSION = Bukkit.getServer().getClass().getPackage().getName().replace(".", ",")
|
||||
.split(",")[3];
|
||||
public static final String NMS_PREFIX;
|
||||
public static final String OBC_PREFIX;
|
||||
public static final boolean IS_THERMOS;
|
||||
public static final Class<?> CHAT_SERIALIZER, COMPONENT_CLASS;
|
||||
public static final Method ICB_FROM_JSON;
|
||||
|
||||
public static final boolean IS_THERMOS = Utils.isClassExist("thermos.Thermos");
|
||||
public static final Class<?> COMPONENT_CLASS;
|
||||
|
||||
private static Method getNbtMethod, sendPacketMethod;
|
||||
|
||||
/**
|
||||
* This Map is to reduce Reflection action which take more resources than just
|
||||
* RAM action
|
||||
@@ -28,45 +29,33 @@ public class PacketUtils {
|
||||
private static final Map<String, Class<?>> ALL_CLASS = Collections.synchronizedMap(new HashMap<String, Class<?>>());
|
||||
|
||||
static {
|
||||
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 + ".";
|
||||
CHAT_SERIALIZER = getNmsClass("IChatBaseComponent$ChatSerializer", "network.chat.", "ChatSerializer");
|
||||
String version = ChatItem.getPlatform().getNMSVersion();
|
||||
NMS_PREFIX = Version.getVersion().isNewerOrEquals(Version.V1_17) || IS_THERMOS ? "net.minecraft." : "net.minecraft.server." + (version == "" ? "" : version + ".");
|
||||
OBC_PREFIX = "org.bukkit.craftbukkit." + (version == "" ? "" : version + ".");
|
||||
COMPONENT_CLASS = getNmsClass("IChatBaseComponent", "network.chat.");
|
||||
ICB_FROM_JSON = getMethod("a", CHAT_SERIALIZER, String.class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the Class in NMS, with a processing reducer
|
||||
*
|
||||
* @param name of the NMS class (in net.minecraft.server package ONLY, because
|
||||
* it's NMS)
|
||||
* @param name of the NMS class (in net.minecraft.server package ONLY, because it's NMS)
|
||||
* @return clazz the searched class
|
||||
*/
|
||||
public static Class<?> getNmsClass(String name, String packagePrefix, String... alias) {
|
||||
return ALL_CLASS.computeIfAbsent(name, (a) -> {
|
||||
String fullPrefix = NMS_PREFIX
|
||||
+ (Version.getVersion().isNewerOrEquals(Version.V1_17) || IS_THERMOS ? packagePrefix : "");
|
||||
String fullPrefix = NMS_PREFIX + (Version.getVersion().isNewerOrEquals(Version.V1_17) || IS_THERMOS ? packagePrefix : "");
|
||||
try {
|
||||
Class<?> clazz = Class.forName(fullPrefix + name);
|
||||
if (clazz != null)
|
||||
return clazz;
|
||||
} catch (ClassNotFoundException e) {
|
||||
if (alias.length == 0)
|
||||
e.printStackTrace(); // no alias, print error
|
||||
// else ignore and go check for alias
|
||||
}
|
||||
} catch (ClassNotFoundException e) {}
|
||||
|
||||
for (String className : alias) {
|
||||
try {
|
||||
Class<?> clazz = Class.forName(fullPrefix + className);
|
||||
if (clazz != null)
|
||||
return clazz;
|
||||
} catch (ClassNotFoundException e) {
|
||||
if (className == alias[alias.length - 1]) // if it's last alias, print error
|
||||
e.printStackTrace();
|
||||
}
|
||||
} catch (ClassNotFoundException e) {}
|
||||
}
|
||||
return null;
|
||||
});
|
||||
@@ -120,15 +109,6 @@ public class PacketUtils {
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean isClassExist(String name) {
|
||||
try {
|
||||
Class.forName(name);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get NMS player connection of specified player
|
||||
*
|
||||
@@ -138,10 +118,7 @@ public class PacketUtils {
|
||||
public static Object getPlayerConnection(Player p) {
|
||||
try {
|
||||
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);
|
||||
return ReflectionUtils.getFirstWith(entityPlayer, entityPlayer.getClass(), getNmsClass("PlayerConnection", "server.network."));
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
@@ -172,10 +149,17 @@ public class PacketUtils {
|
||||
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);
|
||||
if(sendPacketMethod == null) {
|
||||
Version v = Version.getVersion();
|
||||
if(v.isNewerOrEquals(Version.V1_20)) {
|
||||
Class<?> packetSrvClass = getNmsClass("ServerCommonPacketListenerImpl", "server.network.");
|
||||
if(packetSrvClass != null)
|
||||
sendPacketMethod = packetSrvClass.getDeclaredMethod("b", getNmsClass("Packet", "network.protocol."));
|
||||
}
|
||||
if(sendPacketMethod == null)
|
||||
sendPacketMethod = playerConnection.getClass().getMethod(Version.getVersion().isNewerOrEquals(Version.V1_18) ? "a" : "sendPacket", getNmsClass("Packet", "network.protocol."));
|
||||
}
|
||||
sendPacketMethod.invoke(playerConnection, packet);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
@@ -190,11 +174,23 @@ public class PacketUtils {
|
||||
*/
|
||||
public static String getNbtTag(ItemStack item) {
|
||||
try {
|
||||
Object nmsStack = JSONManipulator.AS_NMS_COPY.invoke(null, item);
|
||||
Version v = Version.getVersion();
|
||||
Object tag = getNmsClass("ItemStack", "world.item.")
|
||||
.getMethod(v.equals(Version.V1_18) ? "t" : (v.isNewerOrEquals(Version.V1_19) ? "u" : "getTag"))
|
||||
.invoke(nmsStack);
|
||||
if (getNbtMethod == null) {
|
||||
Class<?> itemClass = getNmsClass("ItemStack", "world.item.");
|
||||
Version v = Version.getVersion();
|
||||
if(v.isNewerOrEquals(Version.V1_20_6))
|
||||
getNbtMethod = itemClass.getDeclaredMethod("d"); // return DataComponentPatch's object
|
||||
else if (v.equals(Version.V1_20))
|
||||
getNbtMethod = itemClass.getDeclaredMethod("w");
|
||||
else if (v.equals(Version.V1_19))
|
||||
getNbtMethod = itemClass.getDeclaredMethod("u");
|
||||
else if (v.equals(Version.V1_18))
|
||||
getNbtMethod = itemClass.getDeclaredMethod("t");
|
||||
else
|
||||
getNbtMethod = itemClass.getDeclaredMethod("getTag");
|
||||
|
||||
getNbtMethod.setAccessible(true);
|
||||
}
|
||||
Object tag = getNbtMethod.invoke(JSONManipulator.AS_NMS_COPY.invoke(null, item));
|
||||
return tag == null ? "{}" : tag.toString();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
@@ -202,12 +198,21 @@ public class PacketUtils {
|
||||
return "{}";
|
||||
}
|
||||
|
||||
private static Method getMethod(String name, Class<?> clazz, Class<?>... params) {
|
||||
try {
|
||||
return clazz.getDeclaredMethod(name, params);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
public static void printPacketToDebug(Object packet) {
|
||||
if(!ChatItem.hasDebug())
|
||||
return;
|
||||
if(packet == null) {
|
||||
ChatItem.debug("Packet is null");
|
||||
return;
|
||||
}
|
||||
ChatItem.debug("Packet with Class: " + packet.getClass().getSimpleName());
|
||||
for (Field f : packet.getClass().getDeclaredFields()) {
|
||||
f.setAccessible(true);
|
||||
try {
|
||||
ChatItem.debug(f.getName() + ": " + f.get(packet));
|
||||
} catch (Exception exc) {
|
||||
exc.printStackTrace();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package me.dadus33.chatitem.utils;
|
||||
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Modifier;
|
||||
@@ -17,6 +18,17 @@ public class ReflectionUtils {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static Method getMethodByName(Class<?> clazz, String methodName) {
|
||||
try {
|
||||
for(Method m : clazz.getDeclaredMethods())
|
||||
if(m.getName().equals(methodName))
|
||||
return m;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static Method getMethod(Class<?> clazz, Class<?> returned, Class<?>... params) {
|
||||
try {
|
||||
@@ -71,6 +83,20 @@ public class ReflectionUtils {
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean hasObject(Object source, String... field) {
|
||||
if(source == null)
|
||||
return false;
|
||||
for(String fieldName : field) {
|
||||
try {
|
||||
source.getClass().getDeclaredField(fieldName);
|
||||
return true;
|
||||
} catch (NoSuchFieldException e) {
|
||||
// ignore because going to next item
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the specified field name in the object source
|
||||
*
|
||||
@@ -79,6 +105,8 @@ public class ReflectionUtils {
|
||||
* @return the requested object of the field
|
||||
*/
|
||||
public static Object getObject(Object source, String... field) {
|
||||
if(source == null)
|
||||
return null;
|
||||
try {
|
||||
for(String fieldName : field) {
|
||||
try {
|
||||
@@ -104,6 +132,8 @@ public class ReflectionUtils {
|
||||
* @return the requested field
|
||||
*/
|
||||
public static Field getField(Object source, String field) {
|
||||
if(source == null)
|
||||
return null;
|
||||
try {
|
||||
Field f = source.getClass().getDeclaredField(field);
|
||||
f.setAccessible(true);
|
||||
@@ -130,6 +160,19 @@ public class ReflectionUtils {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
* @param searchingFor the class of the required field
|
||||
* @return the field (or null if not found)
|
||||
* @throws Exception if something gone wrong
|
||||
*/
|
||||
public static <T> T getFirstWith(Object from, Class<T> searchingFor) throws Exception {
|
||||
return getFirstWith(from, from.getClass(), searchingFor);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the first object which have the searching for class type
|
||||
*
|
||||
@@ -146,6 +189,8 @@ public class ReflectionUtils {
|
||||
return (T) f.get(from);
|
||||
}
|
||||
}
|
||||
if(!clazz.getSuperclass().equals(Object.class))
|
||||
return getFirstWith(from, clazz.getSuperclass(), searchingFor);
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -167,4 +212,20 @@ public class ReflectionUtils {
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static boolean isClassExist(String name) {
|
||||
try {
|
||||
Class.forName(name);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static Constructor<?> getConstructor(Class<?> clazz, Class<?>... params) {
|
||||
try {
|
||||
return clazz.getConstructor(params);
|
||||
} catch (Exception e) {}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,8 @@ import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.net.ConnectException;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.MalformedURLException;
|
||||
@@ -15,17 +17,23 @@ import java.nio.file.Files;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.StringJoiner;
|
||||
import java.util.TreeMap;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import org.bukkit.enchantments.Enchantment;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.inventory.InventoryEvent;
|
||||
import org.bukkit.inventory.Inventory;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import me.dadus33.chatitem.ChatItem;
|
||||
import me.dadus33.chatitem.chatmanager.v1.json.JSONManipulator;
|
||||
import me.dadus33.chatitem.chatmanager.ChatManager;
|
||||
import me.dadus33.chatitem.playerversion.PlayerVersionManager;
|
||||
import net.md_5.bungee.api.chat.BaseComponent;
|
||||
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.ItemTag;
|
||||
@@ -34,8 +42,10 @@ import net.md_5.bungee.api.chat.hover.content.Text;
|
||||
|
||||
public class Utils {
|
||||
|
||||
private final static TreeMap<Integer, String> ROMAN_KEYS = new TreeMap<>();
|
||||
private final static HashMap<String, String> ENCHANTS_NAMES = new HashMap<>();
|
||||
public static final boolean IS_PAPER = isClassExist("io.papermc.paper.event.player.AsyncChatEvent");
|
||||
private static final Pattern UUID_PATTERN = Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$");
|
||||
private static final TreeMap<Integer, String> ROMAN_KEYS = new TreeMap<>();
|
||||
private static final HashMap<String, String> ENCHANTS_NAMES = new HashMap<>();
|
||||
|
||||
static {
|
||||
ROMAN_KEYS.put(1000, "M");
|
||||
@@ -114,7 +124,7 @@ public class Utils {
|
||||
connection.setUseCaches(true);
|
||||
connection.setConnectTimeout(5000);
|
||||
connection.setReadTimeout(5000);
|
||||
connection.setRequestProperty("User-Agent", "ChatItem " + pl.getDescription().getVersion());
|
||||
connection.setRequestProperty("User-Agent", "ChatItem");
|
||||
connection.setDoOutput(true);
|
||||
connection.setRequestMethod("GET");
|
||||
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
|
||||
@@ -156,12 +166,22 @@ public class Utils {
|
||||
return b;
|
||||
}
|
||||
|
||||
public static boolean isBeforeChatJson(Player p) {
|
||||
return !PlayerVersionManager.getPlayerVersionAdapter().getPlayerVersion(p).isNewerOrEquals(Version.V1_16) && Version.getVersion().isNewerOrEquals(Version.V1_16);
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
public static HoverEvent createItemHover(ItemStack item) {
|
||||
public static HoverEvent createItemHover(ItemStack item, Player to) {
|
||||
if(isBeforeChatJson(to)) {
|
||||
ComponentBuilder comp = new ComponentBuilder("");
|
||||
for(String line : ChatManager.getMaxLinesFromItem(to, item))
|
||||
comp.append(line + "\n");
|
||||
return createTextHover(comp.create());
|
||||
}
|
||||
if(Version.getVersion().isNewerOrEquals(Version.V1_13)) {
|
||||
return new HoverEvent(HoverEvent.Action.SHOW_ITEM, new Item(item.getType().getKey().getKey(), item.getAmount(), ItemTag.ofNbt(PacketUtils.getNbtTag(item))));
|
||||
} else {
|
||||
return new HoverEvent(HoverEvent.Action.SHOW_ITEM, new ComponentBuilder(JSONManipulator.stringifyItem(item)).create());
|
||||
return new HoverEvent(HoverEvent.Action.SHOW_ITEM, new ComponentBuilder(ChatItem.getPlatform().stringifyItem(item)).create());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -178,6 +198,10 @@ public class Utils {
|
||||
}
|
||||
}
|
||||
|
||||
public static ClickEvent createRunCommand(String command) {
|
||||
return new ClickEvent(ClickEvent.Action.RUN_COMMAND, command);
|
||||
}
|
||||
|
||||
public static boolean isInteger(String s) {
|
||||
try {
|
||||
Integer.parseInt(s);
|
||||
@@ -213,11 +237,15 @@ public class Utils {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean isUUID(String s) {
|
||||
return s != null && UUID_PATTERN.matcher(s.toLowerCase()).matches();
|
||||
}
|
||||
|
||||
public static YamlConfiguration copyLoadFile(File folder, String filename, String baseFile) {
|
||||
File legacyConfig = new File(folder, filename);
|
||||
if(!legacyConfig.exists())
|
||||
Utils.copyFile(baseFile, legacyConfig);
|
||||
copyFile(baseFile, legacyConfig);
|
||||
return YamlConfiguration.loadConfiguration(legacyConfig);
|
||||
}
|
||||
|
||||
@@ -228,4 +256,46 @@ public class Utils {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static String arrayToString(Object[] a) {
|
||||
StringJoiner sj = new StringJoiner(", ");
|
||||
for(Object o : a)
|
||||
sj.add(o == null ? "null" : o.toString());
|
||||
return sj.toString();
|
||||
}
|
||||
|
||||
public static boolean isClassExist(String name) {
|
||||
try {
|
||||
Class.forName(name);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static String cleanStr(String s) {
|
||||
return s.startsWith("'") && s.endsWith("'") ? s.substring(1, s.length() - 1) : s;
|
||||
}
|
||||
|
||||
/**
|
||||
* In API versions 1.20.6 and earlier, InventoryView is a class.
|
||||
* In versions 1.21 and later, it is an interface.
|
||||
* This method uses reflection to get the top Inventory object from the
|
||||
* InventoryView associated with an InventoryEvent, to avoid runtime errors.
|
||||
* @param event The generic InventoryEvent with an InventoryView to inspect.
|
||||
* @return The top Inventory object from the event's InventoryView.
|
||||
*/
|
||||
public static Inventory getTopInventory(InventoryEvent event) {
|
||||
try {
|
||||
Object view = event.getView();
|
||||
if(view == null)
|
||||
return null;
|
||||
Method getTopInventory = view.getClass().getMethod("getTopInventory");
|
||||
getTopInventory.setAccessible(true);
|
||||
return (Inventory) getTopInventory.invoke(view);
|
||||
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -2,26 +2,27 @@ 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, 761, 1000),
|
||||
UNSUPPORTED(0, 5, 7),
|
||||
V1_8(6, 47, 8),
|
||||
V1_9(49, 110, 9), // 1.9.X - Starts with 49 as 48 was an april fools update
|
||||
V1_10(201, 210, 10), // 1.10.X - Starts with 201 because why not.
|
||||
V1_11(301, 316, 11),
|
||||
V1_12(317, 340, 12),
|
||||
V1_13(341, 440, 13),
|
||||
V1_14(441, 500, 14),
|
||||
V1_15(550, 578, 15),
|
||||
V1_16(700, 754, 16),
|
||||
V1_17(755, 756, 17),
|
||||
V1_18(757, 758, 18),
|
||||
V1_19(759, 762, 19),
|
||||
V1_20(763, 765, 20),
|
||||
V1_20_6(766, 766, 20.6),
|
||||
V1_21(767, 1000, 21),
|
||||
HIGHER(Integer.MAX_VALUE, -1, Integer.MAX_VALUE);
|
||||
|
||||
// Latest version should always have the upper limit set to Integer.MAX_VALUE so
|
||||
@@ -29,17 +30,11 @@ public enum Version {
|
||||
|
||||
public final int MIN_VER;
|
||||
public final int MAX_VER;
|
||||
public final int index; // Represents how new the version is (0 - extremely old)
|
||||
public final double index; // Represents how new the version is (0 - extremely old)
|
||||
|
||||
private static final Version SERVER_VERSION;
|
||||
public static final String BUKKIT_VERSION;
|
||||
private static final Version SERVER_VERSION = ChatItem.getPlatform().getMinecraftVersion();
|
||||
|
||||
static {
|
||||
BUKKIT_VERSION = Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3];
|
||||
SERVER_VERSION = getVersionByName(BUKKIT_VERSION);
|
||||
}
|
||||
|
||||
Version(int min, int max, int index) {
|
||||
Version(int min, int max, double index) {
|
||||
this.MIN_VER = min;
|
||||
this.MAX_VER = max;
|
||||
this.index = index;
|
||||
@@ -54,6 +49,9 @@ public enum Version {
|
||||
}
|
||||
|
||||
public static Version getVersionByName(String name) {
|
||||
try {
|
||||
return Version.valueOf(name.toUpperCase());
|
||||
} catch (Exception e) {}
|
||||
for (Version v : Version.values())
|
||||
if (name.toLowerCase().startsWith(v.name().toLowerCase()))
|
||||
return v;
|
||||
@@ -61,12 +59,7 @@ public enum Version {
|
||||
}
|
||||
|
||||
public static Version getVersion(int protocolVersion) {
|
||||
for (Version ver : Version.values()) {
|
||||
if (protocolVersion >= ver.MIN_VER && protocolVersion <= ver.MAX_VER) {
|
||||
return ver;
|
||||
}
|
||||
}
|
||||
return HIGHER;
|
||||
return getVersion(protocolVersion, HIGHER);
|
||||
}
|
||||
|
||||
public static Version getVersion(int protocolVersion, Version def) {
|
||||
|
||||
+110
-20
@@ -1,7 +1,7 @@
|
||||
# Config for ChatItem
|
||||
# For info visit
|
||||
# Spigotmc: https://www.spigotmc.org/resources/chatitem.19064/
|
||||
# Discord: https://discord.gg/ttA5CjMhk7
|
||||
# Spigotmc: https://www.spigotmc.org/resources/19064/
|
||||
# Discord: https://discord.gg/yng5PPf62h
|
||||
|
||||
# Version info, DON'T TOUCH
|
||||
config-version: 13
|
||||
@@ -17,7 +17,7 @@ config-version: 13
|
||||
# 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"
|
||||
manager: "all"
|
||||
|
||||
#General configuration
|
||||
general:
|
||||
@@ -27,6 +27,61 @@ general:
|
||||
- "{i}"
|
||||
- "[item]"
|
||||
- "{item}"
|
||||
other-placeholders:
|
||||
# Show what is in the head
|
||||
helmet:
|
||||
# Enable it or not
|
||||
enabled: true
|
||||
# Disallow showing empty item
|
||||
deny-if-no-item: true
|
||||
# Placeholders to use in chat
|
||||
keys:
|
||||
- "[head]"
|
||||
- "{head}"
|
||||
show: "&6%name%'s helmet is %item%"
|
||||
# Show the CHESTPLATE not the enderchest or whatever
|
||||
chestplate:
|
||||
enabled: true
|
||||
deny-if-no-item: true
|
||||
keys:
|
||||
- "[chest]"
|
||||
- "{chest}"
|
||||
show: "&6%name%'s chestplate is %item%"
|
||||
# Show leggings
|
||||
leggings:
|
||||
enabled: true
|
||||
deny-if-no-item: true
|
||||
keys:
|
||||
- "[legs]"
|
||||
- "{legs}"
|
||||
show: "&6%name%'s leggings are %item%"
|
||||
# Show what is their feets
|
||||
boots:
|
||||
enabled: true
|
||||
deny-if-no-item: true
|
||||
keys:
|
||||
- "[feet]"
|
||||
- "{feet}"
|
||||
show: "&6%name%'s boots are %item%"
|
||||
inventory:
|
||||
enabled: true
|
||||
deny-if-no-item: true
|
||||
# Time in seconds before the placeholder expire
|
||||
time-expire: 1800
|
||||
keys:
|
||||
- "[inv]"
|
||||
- "{inv}"
|
||||
show: "&6%name%'s inventory is %item%"
|
||||
enderchest:
|
||||
enabled: true
|
||||
deny-if-no-item: true
|
||||
# Time in seconds before the placeholder expire
|
||||
time-expire: 1800
|
||||
keys:
|
||||
- "[ec]"
|
||||
- "{ec}"
|
||||
show: "&6%name%'s enderchest is %item%"
|
||||
|
||||
# The format of the item placeholders.
|
||||
name-format: "&b&l&o{name}{amount}&r"
|
||||
# The format of the {amount} placeholder.
|
||||
@@ -69,7 +124,7 @@ general:
|
||||
- "&7Failed to parse item for your client"
|
||||
|
||||
# Format used with using /chatitem show
|
||||
command-format: "&6%name%'s item is %item%"
|
||||
show: "&6%name%'s item is %item%"
|
||||
|
||||
# Here you can set when the players should see the no-permission message (defined in the 'Messages' section bellow).
|
||||
# 'normal' dictates whether the user should see the message when using the placeholder in normal chat, and 'command'
|
||||
@@ -89,10 +144,18 @@ general:
|
||||
cooldown: 60
|
||||
# All items that are not allowed to be showed
|
||||
ignored_items:
|
||||
- "AIR"
|
||||
- "SOME_ITEM"
|
||||
# Check if the plugin have update
|
||||
check-update: true
|
||||
language: "en_us"
|
||||
language: "en_gb"
|
||||
sub-commands:
|
||||
broadcast: true
|
||||
show: true
|
||||
# This part of config is in WIP. Please ignore it.
|
||||
ownformatter:
|
||||
format: "%name%: %message%"
|
||||
# End of WIP config section.
|
||||
|
||||
|
||||
|
||||
# Messages section. You can disable any of them by simply leaving them empty, like this: ""
|
||||
@@ -100,6 +163,8 @@ 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!"
|
||||
# Send for some command to prevent wrong messages
|
||||
empty-item: "&cCan't show empty item"
|
||||
# The message sent after the configuration file is successfully reloaded.
|
||||
reload-success: "&b&lSuccessful reload!"
|
||||
# The message sent if the player is on cooldown from sending a placeholder.
|
||||
@@ -122,9 +187,9 @@ messages:
|
||||
chatitem-cmd:
|
||||
help:
|
||||
- "&6/chatitem admin : &7Manage some options"
|
||||
- "&6/chatitem links : &7See all links which are usefull"
|
||||
- "&6/chatitem links : &7See all links which are useful"
|
||||
links:
|
||||
begin: "&aAll usefull links: "
|
||||
begin: "&aAll useful links: "
|
||||
list:
|
||||
1:
|
||||
message: "\n&7- &eSpigotmc updates"
|
||||
@@ -169,19 +234,12 @@ messages:
|
||||
lore: "&7Actual: &e%name%"
|
||||
# Change name and lore of all managers
|
||||
manager:
|
||||
both:
|
||||
name: "&6Use both manager&7: &aPacket & Chat"
|
||||
all:
|
||||
name: "&6Use all manager&7: &aPacket, Chat & Paper"
|
||||
lore:
|
||||
- "&aTry both manager. Very usefull when you have lot of plugins"
|
||||
- "&aTry all managers to be sure at least one success. Default options."
|
||||
- "&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."
|
||||
- "&eShould works with all types of plugins. (Previously named 'both' instead of 'all')"
|
||||
- ""
|
||||
- "&7Since ChatItem v2.1"
|
||||
packet:
|
||||
@@ -195,11 +253,26 @@ messages:
|
||||
chat:
|
||||
name: "&6Change basic message"
|
||||
lore:
|
||||
- "&aVery quick and usefull for server without plugin message !"
|
||||
- "&aVery quick and useful for server without plugin message !"
|
||||
- "&aIt enable to use ChatItem without packet reading."
|
||||
- "&eIt's more optimized than others manager"
|
||||
- ""
|
||||
- "&7Since ChatItem v2.0"
|
||||
paper:
|
||||
name: "&6Use paper messaging"
|
||||
lore:
|
||||
- "&aPaper has his own messaging system."
|
||||
- "&aChatItem can you this system to be easier to manage"
|
||||
- "&eAdapted for paper user, and could be used with more plugin that others"
|
||||
- ""
|
||||
- "&7Since ChatItem v2.6"
|
||||
ownformatter:
|
||||
name: "&6ChatItem formatter"
|
||||
lore:
|
||||
- "&aChatItem format the chat for you."
|
||||
- "&aNo longer needs another chat plugin."
|
||||
- ""
|
||||
- "&7Since ChatItem v2.7"
|
||||
# The item that show the actual manager
|
||||
actual:
|
||||
name: '&6Actual manager: %manager%'
|
||||
@@ -211,3 +284,20 @@ messages:
|
||||
hours: " hours"
|
||||
enabled: "&aEnabled"
|
||||
disabled: "&cDisabled"
|
||||
seeinv_not_found: "&cImpossible to find this inventory. Are you coming too late ?"
|
||||
inventory:
|
||||
name: "%cible%'s inventory"
|
||||
chat: "%cible%'s inventory"
|
||||
hover: "&7Click to see inventory"
|
||||
enderchest:
|
||||
name: "%cible%'s enderchest"
|
||||
chat: "%cible%'s enderchest"
|
||||
hover: "&7Click to see enderchest"
|
||||
|
||||
# If ChatItem send message using DiscordSRV
|
||||
# This option will be ignored if you don't have it
|
||||
discord-srv-send-our: true
|
||||
|
||||
manager-config:
|
||||
paper:
|
||||
send-ourself: false
|
||||
@@ -2,9 +2,10 @@ name: ChatItem
|
||||
main: me.dadus33.chatitem.ChatItem
|
||||
version: ${project.version}
|
||||
|
||||
softdepend: [ViaVersion, ProtocolSupport, ProtocolLib, LangUtils, HexNicks, EcoEnchants, DiscordSRV, ChatControl, ChatManager]
|
||||
softdepend: [ViaVersion, ProtocolSupport, ProtocolLib, LangUtils, HexNicks, EcoEnchants, DiscordSRV, ChatControl, ChatManager, PlaceholderAPI, MVdWPlaceholderAPI, Vault]
|
||||
authors: [dadus33, WOLFI3654, Elikill58]
|
||||
api-version: 1.13
|
||||
folia-supported: true
|
||||
|
||||
commands:
|
||||
cireload:
|
||||
@@ -13,7 +14,6 @@ commands:
|
||||
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