Compare commits

...
22 Commits
Author SHA1 Message Date
Elikill58 144be87448 Upgrade to 2.2.1 2022-02-28 12:30:18 +01:00
Elikill58 217e7316b9 Add jitpack support 2022-02-26 14:10:11 +01:00
CatAndPaste 9bf2900bb5 Hot fix for hex-colored nicknames changed by Essentials-X. After the general hex-colored fix by Elikill58 that fixed 99% of the problem, first character formatting still was off (as you can see on screenshot: https://media.discordapp.net/attachments/171243756849201153/946441326205993010/unknown.png), this was caused by §r added to the begining of the name. I fixed an error by adding check for char 'r' in showItem function (ChatListener.java : 235). (#37) 2022-02-24 19:31:10 +01:00
Elikill58 23640b1772 Fix hex color ... again 2022-02-23 23:45:44 +01:00
Elikill58 fecf35b3a9 Add discord srv support and fix logged messages 2022-02-23 20:42:05 +01:00
Elikill58 8068fe6a7f Fix append for legacy versions 2022-02-23 19:31:23 +01:00
Elikill58 2f21538c76 Possible fix fox colors codes 2022-02-23 17:48:44 +01:00
Elikill58 340cad0b2f Fix item for old spigot version 2022-02-20 23:11:01 +01:00
Elikill58 0c51c73f31 Add option in inv to manage debug mode 2022-02-20 23:08:53 +01:00
Elikill58 717db94dc2 Prefer manage v1 rep if v2 is enabled 2022-02-20 23:02:11 +01:00
Elikill58 51e6708fcb Update which item is showed 2022-02-19 21:59:37 +01:00
Elikill58 a6f22d090a Fix some color for v1 2022-02-19 21:44:32 +01:00
Elikill58 979f39a171 If not comp, try to use chat base comp 2022-02-19 21:38:43 +01:00
Elikill58 0f057720b8 Prevent one method not found on some paper 2022-02-19 19:37:50 +01:00
Elikill58 a4eb8bd8fe Fix duplicated text 2022-02-19 19:21:11 +01:00
Elikill58 38a8f24c9c Add way to find ichatbase comp 2022-02-19 19:09:01 +01:00
Elikill58 82de0cf4dc Fix wrong parsing fields 2022-02-19 19:05:24 +01:00
Elikill58 13fcea5b57 Change how chat manager works 2022-02-19 15:52:35 +01:00
Elikill58 4292871294 Fix items messages (From XeonZ's config) 2022-02-18 11:06:22 +01:00
Elikill58 827c7f92ae Merge branch 'v2' of https://github.com/dadus33-plugins/ChatItem into v2 2022-02-16 16:16:58 +01:00
Elikill58 bcd28eddca Prevent instance error 2022-02-16 15:32:51 +01:00
outsparkled 4d873146dd Fix gson compatibility issues on 1.8 and clean up pom (#36)
* Fix gson compatibility issues on 1.8 and clean up pom

* re-add export_dir
2022-02-15 19:42:33 +01:00
16 changed files with 388 additions and 313 deletions

No files matched your search

+4
View File
@@ -0,0 +1,4 @@
jdk:
- openjdk11
install:
- mvn install
+34 -15
View File
@@ -6,7 +6,7 @@
<groupId>me.dadus33</groupId>
<artifactId>chatitem</artifactId>
<version>2.2</version>
<version>2.2.1</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
@@ -45,6 +45,15 @@
<id>elikill-repo</id>
<url>https://repo.eliapp.fr:8081/repository/internal/</url>
</repository>
<repository>
<id>dv8tion</id>
<name>m2-dv8tion</name>
<url>https://m2.dv8tion.net/releases</url>
</repository>
<repository>
<id>Scarsz-Nexus</id>
<url>https://nexus.scarsz.me/content/groups/public/</url>
</repository>
</repositories>
@@ -66,12 +75,19 @@
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.17.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.17.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.9.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.meowj</groupId>
@@ -101,7 +117,7 @@
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.53.Final</version>
<scope>compile</scope>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.github.GeyserMC</groupId>
@@ -118,7 +134,13 @@
<dependency>
<groupId>net.kyori</groupId>
<artifactId>adventure-api</artifactId>
<version>4.9.3</version>
<version>4.9.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.discordsrv</groupId>
<artifactId>discordsrv</artifactId>
<version>1.24.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
</dependencies>
@@ -137,7 +159,6 @@
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
@@ -148,14 +169,6 @@
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
<configuration>
<outputDirectory>${dir}</outputDirectory>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
@@ -168,6 +181,12 @@
</goals>
<configuration>
<minimizeJar>true</minimizeJar>
<relocations>
<relocation>
<pattern>com.google.gson</pattern>
<shadedPattern>me.dadus33.libs.gson</shadedPattern>
</relocation>
</relocations>
</configuration>
</execution>
</executions>
@@ -176,9 +195,9 @@
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<outputDirectory>${export_dir}</outputDirectory>
</configuration>
<configuration>
<outputDirectory>${export_dir}</outputDirectory>
</configuration>
</plugin>
</plugins>
</build>
+10 -14
View File
@@ -37,7 +37,7 @@ public class ChatItem extends JavaPlugin {
private static ChatItem instance;
private Log4jFilter filter;
private Storage storage;
private boolean hasNewVersion = false;
public static boolean discordSrvSupport = false, hasNewVersion = false;
private List<ChatManager> chatManager = new ArrayList<>();
private void chooseManagers() {
@@ -105,33 +105,29 @@ public class ChatItem extends JavaPlugin {
//Save the instance (we're basically a singleton)
instance = this;
//Load ProtocolManager
//pm = ProtocolLibrary.getProtocolManager();
//Load config
saveDefaultConfig();
storage = new Storage(getConfig());
//We halt the use of this system for now, until we can solve the infamous getProtocolVersion issue
//Till then, users of both ViaVersion and ProtocolSupport should do just fine
/*if(!protocolSupport && !viaVersion) {
//We only implement our own way of getting protocol versions if we have no other choice
pm.addPacketListener(new HandshakeListener(this, ListenerPriority.MONITOR, PacketType.Handshake.Client.SET_PROTOCOL));
}*/
//Commands
loadCommand(getCommand("cireload"), new CIReloadCommand());
loadCommand(getCommand("chatitem"), new ChatItemCommand());
// events
getServer().getPluginManager().registerEvents(new JoinListener(), this);
getServer().getPluginManager().registerEvents(new InventoryListener(), this);
PluginManager pm = getServer().getPluginManager();
pm.registerEvents(new JoinListener(), this);
pm.registerEvents(new InventoryListener(), this);
chooseManagers();
//Initialize Log4J filter (remove ugly console messages)
filter = new Log4jFilter(storage);
if(pm.getPlugin("DiscordSRV") != null) {
discordSrvSupport = true;
getLogger().info("Load DiscordSRV support.");
}
if(storage.CHECK_UPDATE) {
getServer().getScheduler().runTaskAsynchronously(this, () -> {
String urlName = "https://api.spigotmc.org/legacy/update.php?resource=19064";
@@ -180,7 +176,7 @@ public class ChatItem extends JavaPlugin {
}
public static void debug(String msg) {
if(getInstance().getConfig().getBoolean("debug", false))
if(getInstance().getStorage().DEBUG)
getInstance().getLogger().info("[Debug] " + msg);
}
}
@@ -46,7 +46,7 @@ import me.dadus33.chatitem.utils.PacketUtils;
import me.dadus33.chatitem.utils.Reflect;
import me.dadus33.chatitem.utils.Version;
@SuppressWarnings("unchecked")
@SuppressWarnings({"unchecked", "deprecation"})
public class JSONManipulatorCurrent implements JSONManipulator {
private static final Class<?> CRAFT_ITEM_STACK_CLASS = PacketUtils.getObcClass("inventory.CraftItemStack");
@@ -712,7 +712,6 @@ public class JSONManipulatorCurrent implements JSONManipulator {
return replacer;
}
@SuppressWarnings("deprecation")
private Item toItem(ItemStack is) throws Exception {
CompoundTag tag = new CompoundTag("tag");
@@ -6,7 +6,6 @@ import static me.dadus33.chatitem.chatmanager.ChatManager.SEPARATOR_STR;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.HashMap;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
@@ -24,6 +23,7 @@ import me.dadus33.chatitem.chatmanager.v1.packets.ChatItemPacket;
import me.dadus33.chatitem.chatmanager.v1.packets.PacketContent;
import me.dadus33.chatitem.chatmanager.v1.packets.PacketHandler;
import me.dadus33.chatitem.chatmanager.v1.packets.PacketType;
import me.dadus33.chatitem.utils.ItemUtils;
import me.dadus33.chatitem.utils.PacketUtils;
import me.dadus33.chatitem.utils.Storage;
import me.dadus33.chatitem.utils.Version;
@@ -80,10 +80,9 @@ public class ChatPacketManager extends PacketHandler {
return; // It means it's an actionbar message, and we ain't intercepting those
}
}
ChatItem.debug("UUID: " + e.getContent().getSpecificModifier(UUID.class).readSafely(0, null));
boolean usesBaseComponents = false;
PacketContent packet = e.getContent();
String json;
String json = "{}";
if (packet.getChatComponents().readSafely(0) == null) { // null check for some cases of messages sent using
// spigot's Chat Component API or other means
if (!manager.supportsChatComponentApi()) // only if the API is supported in this server distribution
@@ -91,20 +90,28 @@ public class ChatPacketManager extends PacketHandler {
// we shouldn't mess with anyways
BaseComponent[] components = packet.getSpecificModifier(BaseComponent[].class).readSafely(0);
if (components == null) {
ChatItem.debug("No base components");
return;
}
json = ComponentSerializer.toString(components);
Object chatBaseComp = packet.getSpecificModifier(PacketUtils.COMPONENT_CLASS).readSafely(0);
if(chatBaseComp == null) {
ChatItem.debug("No base components, without chat base comp");
return;
} else {
ChatItem.debug("No base components, with chatbasecomp: " + chatBaseComp);
try {
json = PacketUtils.CHAT_SERIALIZER.getMethod("a", PacketUtils.COMPONENT_CLASS).invoke(null, e.getPacket()).toString();
} catch (Exception exc) {
exc.printStackTrace();
}
}
} else
json = ComponentSerializer.toString(components);
usesBaseComponents = true;
} else {
try {
json = (String) serializerGetJson.invoke(null, packet.getChatComponents().readSafely(0));
} catch (Exception exc) {
exc.printStackTrace();
json = "{}";
}
}
boolean found = false;
for (String rep : getStorage().PLACEHOLDERS) {
if (json.contains(rep)) {
@@ -159,7 +166,7 @@ public class ChatPacketManager extends PacketHandler {
String message = null;
try {
if (!p.getItemInHand().getType().equals(Material.AIR)) {
if (!ItemUtils.isEmpty(p.getItemInHand())) {
ItemStack copy = p.getItemInHand().clone();
if (copy.getType().name().contains("_BOOK")) { // filtering written books
BookMeta bm = (BookMeta) copy.getItemMeta();
@@ -201,6 +208,7 @@ public class ChatPacketManager extends PacketHandler {
PacketUtils.sendPacket(e.getPlayer(), e.getPacket());
});
}
private Object jsonToChatComponent(String json) {
try {
return PacketUtils.CHAT_SERIALIZER.getMethod("a", String.class).invoke(null, json);
@@ -34,7 +34,7 @@ public class INC2Channel extends ChannelAbstract {
try {
Object mcServer = ReflectionUtils.callMethod(PacketUtils.getCraftServer(), Version.getVersion().equals(Version.V1_17) ? "getServer" : "b");
Object co = ReflectionUtils.getFirstWith(mcServer, PacketUtils.getNmsClass("MinecraftServer", "server."), PacketUtils.getNmsClass("ServerConnection", "server.network."));
((List<ChannelFuture>) ReflectionUtils.getField(co, "f")).forEach((channelFuture) -> {
((List<ChannelFuture>) ReflectionUtils.getObject(co, "f")).forEach((channelFuture) -> {
pipeline = channelFuture.channel().pipeline();
pipeline.addFirst(boundHandler);
});
@@ -37,7 +37,7 @@ public class NMUChannel extends ChannelAbstract {
Object mcServer = dedicatedSrv.getClass().getMethod("getServer").invoke(dedicatedSrv);
Object co = ReflectionUtils.getFirstWith(mcServer, PacketUtils.getNmsClass("MinecraftServer", "server."), PacketUtils.getNmsClass("ServerConnection", "network."));
@SuppressWarnings("unchecked")
List<ChannelFuture> g = (List<ChannelFuture>) ReflectionUtils.getField(co, "g");
List<ChannelFuture> g = (List<ChannelFuture>) ReflectionUtils.getObject(co, "g");
g.forEach((channelFuture) -> {
pipeline = channelFuture.channel().pipeline();
pipeline.addFirst(boundHandler = new ChannelInboundHandlerAdapter() {
@@ -1,7 +1,10 @@
package me.dadus33.chatitem.chatmanager.v2;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.Material;
@@ -11,25 +14,27 @@ import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import me.dadus33.chatitem.ChatItem;
import me.dadus33.chatitem.chatmanager.ChatManager;
import me.dadus33.chatitem.hook.DiscordSrvSupport;
import me.dadus33.chatitem.itemnamer.NamerManager;
import me.dadus33.chatitem.playernamer.PlayerNamerManager;
import me.dadus33.chatitem.utils.ColorManager;
import me.dadus33.chatitem.utils.ItemUtils;
import me.dadus33.chatitem.utils.PacketUtils;
import me.dadus33.chatitem.utils.ReflectionUtils;
import me.dadus33.chatitem.utils.Storage;
import me.dadus33.chatitem.utils.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.HoverEvent;
import net.md_5.bungee.api.chat.HoverEvent.Action;
import net.md_5.bungee.api.chat.TextComponent;
@SuppressWarnings("deprecation")
public class ChatListener implements Listener {
public final static char SEPARATOR = ((char) 0x0007);
private final static String NAME = "{name}";
private final static String AMOUNT = "{amount}";
private final static String TIMES = "{times}";
@@ -37,6 +42,7 @@ public class ChatListener implements Listener {
private final HashMap<String, Long> COOLDOWNS = new HashMap<>();
private ChatListenerChatManager manage;
private Method saveMethod;
private boolean shouldUseAppendMethod = false;
public ChatListener(ChatListenerChatManager manage) {
this.manage = manage;
@@ -51,13 +57,23 @@ public class ChatListener implements Listener {
}
}
}
try {
ComponentBuilder.class.getDeclaredMethod("append", BaseComponent[].class);
shouldUseAppendMethod = true;
} catch (Exception e) {
shouldUseAppendMethod = false;
}
} catch (Exception e) {
}
String appendMethodMsg = shouldUseAppendMethod ? "Use ComponentBuilder's method."
: "Use own ComponentBuilder append method.";
if (saveMethod == null)
ChatItem.getInstance().getLogger().info("Failed to find save method. Using default system...");
ChatItem.getInstance().getLogger()
.info("Failed to find save method. Using default system. " + appendMethodMsg);
else
ChatItem.getInstance().getLogger().info("Save method founded: " + saveMethod.getName() + ".");
ChatItem.getInstance().getLogger()
.info("Save method founded: " + saveMethod.getName() + ". " + appendMethodMsg);
}
public Storage getStorage() {
@@ -92,12 +108,13 @@ public class ChatListener implements Listener {
return builder.toString();
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
@EventHandler(priority = EventPriority.MONITOR)
public void onChat(AsyncPlayerChatEvent e) {
Storage c = getStorage();
if (e.isCancelled()) {
if (ChatItem.getInstance().getChatManager().size() == 1) { // only chat
String msg = e.getMessage().toLowerCase();
for (String rep : getStorage().PLACEHOLDERS) {
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");
@@ -109,48 +126,47 @@ public class ChatListener implements Listener {
return;
}
Player p = e.getPlayer();
for (String rep : getStorage().PLACEHOLDERS) {
if (e.getMessage().contains(rep + ChatManager.SEPARATOR + p.getName())) { // already managed by v1
return;
}
}
boolean found = false;
boolean found = false, hasv1 = false;
for (String key : e.getMessage().split(" ")) {
if (found)
for (String rep : c.PLACEHOLDERS) {
// v1 try to manage it, but the message have not been changed by another plugin
if (e.getMessage().contains(rep + ChatManager.SEPARATOR + p.getName())) {
hasv1 = true;
found = true;
ChatItem.debug("Found v1 placeholders in v2");
break;
}
if (e.getMessage().contains(rep)) {
found = true;
break;
for (String rep : getStorage().PLACEHOLDERS) {
if (key.equalsIgnoreCase(rep)) {
found = true;
break;
}
}
}
if (!found) {
ChatItem.debug("(v2) Can't found placeholder in: " + e.getMessage() + " > " + PlayerNamerManager.getPlayerNamer().getName(p));
return;
}
if (getStorage().PERMISSION_ENABLED && !p.hasPermission(getStorage().PERMISSION_NAME)) {
if (c.PERMISSION_ENABLED && !p.hasPermission(c.PERMISSION_NAME)) {
if (!getStorage().LET_MESSAGE_THROUGH) {
e.setCancelled(true);
}
if (!getStorage().NO_PERMISSION_MESSAGE.isEmpty() && getStorage().SHOW_NO_PERM_NORMAL) {
p.sendMessage(getStorage().NO_PERMISSION_MESSAGE);
if (!c.NO_PERMISSION_MESSAGE.isEmpty() && c.SHOW_NO_PERM_NORMAL) {
p.sendMessage(c.NO_PERMISSION_MESSAGE);
}
return;
}
if (p.getItemInHand().getType().equals(Material.AIR)) {
if (getStorage().DENY_IF_NO_ITEM) {
if (c.DENY_IF_NO_ITEM) {
e.setCancelled(true);
if (!getStorage().DENY_MESSAGE.isEmpty())
e.getPlayer().sendMessage(getStorage().DENY_MESSAGE);
if (!c.DENY_MESSAGE.isEmpty())
e.getPlayer().sendMessage(c.DENY_MESSAGE);
return;
}
if (getStorage().HAND_DISABLED) {
if (c.HAND_DISABLED) {
return;
}
}
if (getStorage().COOLDOWN > 0 && !p.hasPermission("chatitem.ignore-cooldown")) {
if (c.COOLDOWN > 0 && !p.hasPermission("chatitem.ignore-cooldown")) { // use cooldown
if (COOLDOWNS.containsKey(p.getName())) {
long start = COOLDOWNS.get(p.getName());
long current = System.currentTimeMillis() / 1000;
@@ -158,133 +174,97 @@ public class ChatListener implements Listener {
if (elapsed >= getStorage().COOLDOWN) {
COOLDOWNS.remove(p.getName());
} else {
if (!getStorage().LET_MESSAGE_THROUGH) {
if (!c.LET_MESSAGE_THROUGH) {
e.setCancelled(true);
}
if (!getStorage().COOLDOWN_MESSAGE.isEmpty()) {
long left = (start + getStorage().COOLDOWN) - current;
p.sendMessage(getStorage().COOLDOWN_MESSAGE.replace(LEFT, calculateTime(left)));
if (!c.COOLDOWN_MESSAGE.isEmpty()) {
long left = (start + c.COOLDOWN) - current;
p.sendMessage(c.COOLDOWN_MESSAGE.replace(LEFT, calculateTime(left)));
}
return;
}
}
COOLDOWNS.put(p.getName(), System.currentTimeMillis() / 1000);
}
e.setCancelled(true);
String format = e.getFormat(), defMsg = e.getMessage();
Bukkit.getConsoleSender().sendMessage(String.format(e.getFormat(), e.getPlayer().getDisplayName(), defMsg)); // show
// in
// log
boolean isAlreadyParsed = false;
if (format.contains("%1$s") && format.contains("%2$s")) // message not parsed but not default way
isAlreadyParsed = false;
if (format.equalsIgnoreCase(defMsg)) // is message already parsed
isAlreadyParsed = true;
if (format.equalsIgnoreCase("<%1$s> %2$s")) // default MC message
isAlreadyParsed = false;
String msg = isAlreadyParsed ? format : String.format(format, p.getDisplayName(), defMsg);
ItemStack item = p.getItemInHand();
ItemMeta meta = item == null ? null : item.getItemMeta();
if(Version.getVersion().isNewerOrEquals(Version.V1_16))
e.getRecipients().forEach((pl) -> showWithHex(pl, p, item, meta, format, msg));
else
e.getRecipients().forEach((pl) -> showWithoutHex(pl, p, item, meta, format, msg));
}
private void showWithoutHex(Player to, Player origin, ItemStack item, ItemMeta meta, String format, String msg) {
ComponentBuilder component = new ComponentBuilder();
ChatColor color = ChatColor.getByChar(getColorChat(format));
for (String args : msg.split(" ")) {
if (getStorage().PLACEHOLDERS.contains(args)) {
if (meta != null) {
ComponentBuilder itemComponent = new ComponentBuilder(
ChatListener.styleItem(to, item, getStorage()));
String itemJson = convertItemStackToJson(item);
itemComponent.event(new HoverEvent(Action.SHOW_ITEM, new ComponentBuilder(itemJson).create()));
component.append(itemComponent.create());
} else {
if (getStorage().HAND_DISABLED)
component.append(color + args);
else {
String handName = getStorage().HAND_NAME;
ComponentBuilder handComp = new ComponentBuilder();
ComponentBuilder handTooltip = new ComponentBuilder();
int stay = getStorage().HAND_TOOLTIP.size();
for (String line : getStorage().HAND_TOOLTIP) {
stay--;
handTooltip.append(line.replace("{name}", origin.getName()).replace("{display-name}",
origin.getDisplayName()));
if (stay > 0)
handTooltip.append("\n");
}
handComp.event(new HoverEvent(HoverEvent.Action.SHOW_TEXT, handTooltip.create()));
if (handName.contains("{name}")) {
String[] splitted = handName.split("{name}");
for (int i = 0; i < (splitted.length - 1); i++) {
handComp.append(new ComponentBuilder(splitted[i]).create());
handComp.append(PlayerNamerManager.getPlayerNamer().getName(origin));
}
handComp.append(new ComponentBuilder(splitted[splitted.length - 1]).create());
} else
handComp.append(handName.replace("{display-name}", origin.getDisplayName()));
component.append(handComp.create());
}
}
} else {
component.append(color + args);
}
component.append(" ");
char maybeNextCode = getColorChat(args);
if (maybeNextCode != 'r') {
color = ChatColor.getByChar(maybeNextCode);
}
String format = e.getFormat();
String msg, defMsg = e.getMessage();
for (String rep : c.PLACEHOLDERS) {
if (hasv1)
defMsg = defMsg.replace(rep + ChatManager.SEPARATOR + p.getName(), ChatManager.SEPARATOR + ""); // remove
// v1
// char
else
defMsg = defMsg.replace(rep, ChatManager.SEPARATOR + "");
}
to.spigot().sendMessage(component.create());
if (format.contains("%1$s") || format.contains("%2$s")) {
ChatItem.debug("Begin def msg: " + defMsg + "");
msg = (format.contains("%2$s") ? String.format(format, p.getDisplayName(), defMsg)
: String.format(format, p.getDisplayName()));
} else {
msg = format.replace(e.getMessage(), defMsg);
}
ItemStack item = p.getItemInHand();
String itemName = ItemUtils.isEmpty(item) ? (c.HAND_DISABLED ? c.PLACEHOLDERS.get(0) : c.HAND_NAME)
: styleItem(p, item, c);
String loggedMessage = msg.replace(ChatManager.SEPARATOR + "", itemName).replace("{name}", p.getName())
.replace("{display-name}", p.getDisplayName());
Bukkit.getConsoleSender().sendMessage(loggedMessage); // show in log
if (ChatItem.discordSrvSupport)
DiscordSrvSupport.sendchatMessage(p, loggedMessage);
ChatItem.debug("Msg: " + msg.replace(ChatColor.COLOR_CHAR, '&') + ", format: " + format);
e.getRecipients().forEach((pl) -> showItem(pl, p, item, msg));
}
private void showWithHex(Player to, Player origin, ItemStack item, ItemMeta meta, String format, String msg) {
ComponentBuilder component = new ComponentBuilder();
for (String args : msg.split(" ")) {
if (getStorage().PLACEHOLDERS.contains(args)) {
if (meta != null) {
ComponentBuilder itemComponent = new ComponentBuilder(
ChatListener.styleItem(to, item, getStorage()));
String itemJson = convertItemStackToJson(item);
itemComponent.event(new HoverEvent(Action.SHOW_ITEM, new ComponentBuilder(itemJson).create()));
component.append(itemComponent.create());
} else {
if (getStorage().HAND_DISABLED)
component.append(ColorManager.getChatWithHex(args));
else {
String handName = getStorage().HAND_NAME;
ComponentBuilder handComp = new ComponentBuilder();
ComponentBuilder handTooltip = new ComponentBuilder();
int stay = getStorage().HAND_TOOLTIP.size();
for (String line : getStorage().HAND_TOOLTIP) {
stay--;
handTooltip.append(line.replace("{name}", origin.getName()).replace("{display-name}",
origin.getDisplayName()));
if (stay > 0)
handTooltip.append("\n");
}
handComp.event(new HoverEvent(HoverEvent.Action.SHOW_TEXT, handTooltip.create()));
if (handName.contains("{name}")) {
String[] splitted = handName.split("{name}");
for (int i = 0; i < (splitted.length - 1); i++) {
handComp.append(new ComponentBuilder(splitted[i]).create());
handComp.append(PlayerNamerManager.getPlayerNamer().getName(origin));
}
handComp.append(new ComponentBuilder(splitted[splitted.length - 1]).create());
} else
handComp.append(handName.replace("{display-name}", origin.getDisplayName()));
component.append(handComp.create());
}
private void showItem(Player to, Player origin, ItemStack item, String msg) {
ComponentBuilder builder = new ComponentBuilder("");
ChatColor color = ChatColor.RESET;
String colorCode = "", text = "";
boolean waiting = false, isHex = false;
for (char args : msg.toCharArray()) {
if (args == '§') { // begin of color
if (colorCode.isEmpty() && !text.isEmpty()) { // text before this char
ChatItem.debug("Append " + text);
appendToComponentBuilder(builder, new ComponentBuilder(text).color(color).create());
text = "";
}
waiting = true; // waiting for color code
} else if (waiting) { // if waiting for code and valid str
// if it's hexademical value and with enough space for full color
waiting = false;
if(args == 'r' && colorCode.isEmpty()) {
color = ChatColor.RESET;
continue;
}
if(args == 'x' && colorCode.isEmpty())
isHex = true;
colorCode += args; // a color by itself
} else {
component.append(ColorManager.getChatWithHex(args));
waiting = false;
if(!colorCode.isEmpty()) {
if(isHex && colorCode.length() >= 7)
color = ColorManager.getColor(colorCode);
else if(colorCode.length() == 1) // if only one color code
color = ColorManager.getColor(colorCode);
else
text += ColorManager.getColorString(colorCode);
colorCode = "";
}
if (args == ChatManager.SEPARATOR
&& (!getStorage().HAND_DISABLED || (item != null && item.hasItemMeta()))) {
// here put the item
appendToComponentBuilder(builder, new ComponentBuilder(text).color(color).create());
addItem(builder, to, origin, item);
text = "";
} else {
// basic text, not waiting for code after '§'
text += args;
}
}
component.append(" ");
}
to.spigot().sendMessage(component.create());
if(!text.isEmpty())
appendToComponentBuilder(builder, new ComponentBuilder(text).color(color).create());
to.spigot().sendMessage(builder.create());
}
/**
@@ -313,22 +293,36 @@ public class ChatListener implements Listener {
}
}
/**
* Get the latest color chat
*
* @param msg the message that contains color
* @return the char of the color or 'r' if nothing found
*/
private char getColorChat(String msg) {
if (msg.length() < 2)
return 'r';
for (int i = msg.length() - 2; i > 0; i--) {
char s = msg.charAt(i);
if (ChatColor.COLOR_CHAR == s) {
return msg.charAt(i + 1);
public void addItem(ComponentBuilder builder, Player to, Player origin, ItemStack item) {
if (!ItemUtils.isEmpty(item)) {
ComponentBuilder itemComponent = new ComponentBuilder(ChatListener.styleItem(to, item, getStorage()));
String itemJson = convertItemStackToJson(item);
itemComponent.event(new HoverEvent(Action.SHOW_ITEM, new ComponentBuilder(itemJson).create()));
appendToComponentBuilder(builder, itemComponent.create());
} else {
String handName = getStorage().HAND_NAME;
ComponentBuilder handComp = new ComponentBuilder("");
ComponentBuilder handTooltip = new ComponentBuilder("");
int stay = getStorage().HAND_TOOLTIP.size();
for (String line : getStorage().HAND_TOOLTIP) {
stay--;
handTooltip.append(
line.replace("{name}", origin.getName()).replace("{display-name}", origin.getDisplayName()));
if (stay > 0)
handTooltip.append("\n");
}
handComp.event(new HoverEvent(HoverEvent.Action.SHOW_TEXT, handTooltip.create()));
if (handName.contains("{name}")) {
String[] splitted = handName.split("\\{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("{display-name}", origin.getDisplayName()));
appendToComponentBuilder(builder, handComp.create());
}
return 'r';
}
public static String styleItem(Player p, ItemStack item, Storage c) {
@@ -349,4 +343,27 @@ public class ChatListener implements Listener {
replacer = replacer.replace(NAME, NamerManager.getName(p, item, c));
return replacer;
}
@SuppressWarnings({ "unchecked" })
public 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();
}
}
}
}
@@ -12,72 +12,70 @@ import org.apache.logging.log4j.message.Message;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import me.dadus33.chatitem.chatmanager.v2.ChatListener;
import me.dadus33.chatitem.chatmanager.ChatManager;
import me.dadus33.chatitem.utils.Storage;
public class Log4jFilter implements Filter {
private Storage c;
private Storage c;
public Log4jFilter(Storage st){
c = st;
((Logger) LogManager.getRootLogger()).addFilter(this);
}
public Log4jFilter(Storage st) {
c = st;
((Logger) LogManager.getRootLogger()).addFilter(this);
}
@Override
public Result getOnMismatch() {
return NEUTRAL;
}
@Override
public Result getOnMismatch() {
return NEUTRAL;
}
@Override
public Result getOnMatch() {
return NEUTRAL;
}
@Override
public Result getOnMatch() {
return NEUTRAL;
}
@Override
public Result filter(Logger logger, Level level, Marker marker, String s, Object... objects) {
return checkMessage(s);
}
@Override
public Result filter(Logger logger, Level level, Marker marker, String s, Object... objects) {
return checkMessage(s);
}
@Override
public Result filter(Logger logger, Level level, Marker marker, Object o, Throwable throwable) {
return checkMessage(((Message) o).getFormattedMessage());
}
@Override
public Result filter(Logger logger, Level level, Marker marker, Object o, Throwable throwable) {
return checkMessage(((Message)o).getFormattedMessage());
}
@Override
public Result filter(Logger logger, Level level, Marker marker, Message message, Throwable throwable) {
return checkMessage(message.getFormattedMessage());
}
@Override
public Result filter(Logger logger, Level level, Marker marker, Message message, Throwable throwable) {
return checkMessage(message.getFormattedMessage());
}
@Override
public Result filter(LogEvent logEvent) {
return checkMessage(logEvent.getMessage().getFormattedMessage());
}
@Override
public Result filter(LogEvent logEvent) {
return checkMessage(logEvent.getMessage().getFormattedMessage());
}
public void stop() {
// seems to be required
}
public void stop() {
// seems to be required
}
private Result checkMessage(String msg){
if(msg==null){
return Result.NEUTRAL;
}
for(String placeholder : c.PLACEHOLDERS){
if(msg.contains(placeholder)){
for(Player p : Bukkit.getOnlinePlayers()){
if(msg.contains(ChatListener.SEPARATOR +p.getName())){
return Result.DENY;
}
}
private Result checkMessage(String msg) {
if (msg == null) {
return Result.NEUTRAL;
}
for (String placeholder : c.PLACEHOLDERS) {
if (msg.contains(placeholder)) {
for (Player p : Bukkit.getOnlinePlayers()) {
if (msg.contains(ChatManager.SEPARATOR + p.getName())) {
return Result.DENY;
}
}
}
}
return Result.NEUTRAL;
}
}
}
return Result.NEUTRAL;
}
public void setStorage(Storage nst){
this.c = nst;
}
public void setStorage(Storage nst) {
this.c = nst;
}
}
@@ -0,0 +1,16 @@
package me.dadus33.chatitem.hook;
import org.bukkit.entity.Player;
import github.scarsz.discordsrv.DiscordSRV;
public class DiscordSrvSupport {
public static void sendchatMessage(Player p, String message) {
DiscordSRV pl = DiscordSRV.getPlugin();
if (DiscordSRV.config().getBooleanElse("UseModernPaperChatEvent", false) && pl.isModernChatEventAvailable()) {
return;
}
pl.processChatMessage(p, message, pl.getOptionalChannel("global"), false);
}
}
@@ -50,6 +50,9 @@ public class InventoryListener implements Listener {
} else if(type.equals(Material.STICK)) {
setInConfig("general.hand.disabled", c.HAND_DISABLED = !c.HAND_DISABLED);
open(p);
} else if(type.equals(ItemUtils.FIREWORK_CHARGE)) {
setInConfig("debug", c.DEBUG = !c.DEBUG);
open(p);
} else if(type.equals(Material.IRON_DOOR)) {
if(e.getClick().equals(ClickType.RIGHT))
c.LIMIT--;
@@ -86,6 +89,8 @@ public class InventoryListener implements Listener {
inv.setItem(slot++, getManagerItem(manager));
}
inv.setItem(slot + 1, getManagerItem("actual", "%manager%", Messages.getMessage("admin-inv.manager." + c.MANAGER + ".name")));
inv.setItem(8, getBoolChangeItem(ItemUtils.FIREWORK_CHARGE, "debug", c.DEBUG));
inv.setItem(18, getBoolChangeItem(ItemUtils.INK_SAC, "color-if-already-colored", c.COLOR_IF_ALREADY_COLORED));
inv.setItem(19, getBoolChangeItem(Material.REDSTONE, "deny-no-item", c.DENY_IF_NO_ITEM));
@@ -2,51 +2,44 @@ package me.dadus33.chatitem.utils;
import me.dadus33.chatitem.ChatItem;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.ComponentBuilder;
public class ColorManager {
public static BaseComponent[] getChatWithHex(String msg) {
ChatItem.debug("Converting " + msg);
ComponentBuilder builder = new ComponentBuilder();
ChatColor color = ChatColor.WHITE;
String colorCode = "", text = "";
boolean waiting = false;
for(char c : msg.toCharArray()) {
if(c == '§') { // begin of color
if(colorCode.isEmpty() && !text.isEmpty()) { // text before this char
ChatItem.debug("Append " + text);
builder.append(new ComponentBuilder(text).color(color).create());
text = "";
}
waiting = true; // waiting for color code
} else if(waiting) { // if waiting for code and valid str
if(String.valueOf(c).matches("-?[0-9a-fA-F]+") && colorCode.length() <= 5) { // if it's hexademical value and with enough space for full color
colorCode += c; // add char to it
waiting = false;
} else {
color = ChatColor.getByChar(c); // a color by itself
colorCode = ""; // clean actual code, it's only to prevent some kind of issue
waiting = false;
}
} else {
if(!colorCode.isEmpty()) {
color = getColor(colorCode);
}
// basic text, not waiting for code after '§'
text += c;
colorCode = ""; // clean actual code
waiting = false;
}
}
if(!text.isEmpty())
builder.append(new ComponentBuilder(text).color(color).create()); // add last char
return builder.create();
public static String getColorString(String input) {
if(input == null || input.isEmpty())
return "";
String str = "";
if(Version.getVersion().isNewerOrEquals(Version.V1_16) && input.startsWith("x")) { // x mean it's an hex
ChatItem.debug("Removing char x at begin: " + input.substring(1));
input = input.substring(1);
if(input.length() >= 6) { // at least hex
str += ChatColor.of("#" + input.substring(0, 6)); // get first hex color code
ChatItem.debug("Str with hex: " + str);
if(input.length() > 6) // if as another color code
str += getColorString(input.substring(6)); // get color for after
return str;
} else
ChatItem.debug("Low len: " + input.length());
} else
ChatItem.debug("1.15 - for : " + input);
// not hex
for(char c : input.toCharArray())
str += ChatColor.getByChar(c);
return str;
}
private static ChatColor getColor(String input) {
return input.isEmpty() ? ChatColor.WHITE : (input.length() == 1 ? ChatColor.getByChar(input.charAt(0)) : ChatColor.of("#" + input));
public static ChatColor getColor(String input) {
if(input == null || input.isEmpty())
return ChatColor.RESET;
if(Version.getVersion().isNewerOrEquals(Version.V1_16) && input.startsWith("x")) { // x mean it's an hex
ChatItem.debug("Removing char x at begin: " + input.substring(1));
if(input.length() >= 7) { // at least hex, and 7 because we count the "x"
return ChatColor.of("#" + input.substring(1, 7)); // get first hex color code
} else
ChatItem.debug("Low len: " + input.length());
} else
ChatItem.debug("1.15 - for : " + input);
// not hex
return ChatColor.getByChar(input.charAt(0));
}
}
@@ -19,6 +19,7 @@ public class ItemUtils {
public static final Material WEB = getMaterialWithCompatibility("WEB", "COBWEB");
public static final Material FIREBALL = getMaterialWithCompatibility("FIREBALL", "FIRE_CHARGE");
public static final Material INK_SAC = getMaterialWithCompatibility("INK_SAC", "INK_SACK", "DYE", "GRAY_DYE");
public static final Material FIREWORK_CHARGE = getMaterialWithCompatibility("FIREWORK_CHARGE", "FIRE_CHARGE");
public static final Material BIRCH_WOOD_STAIRS = getMaterialWithCompatibility("BIRCH_WOOD_STAIRS", "BIRCH_STAIRS");
@@ -84,4 +85,8 @@ public class ItemUtils {
}
return stack;
}
public static boolean isEmpty(ItemStack item) {
return item == null || item.getType().equals(Material.AIR);
}
}
@@ -26,9 +26,9 @@ public class ReflectionUtils {
*
* @param source where we will find the field
* @param field the name of the field
* @return the requested field
* @return the requested object of the field
*/
public static Object getField(Object source, String field) {
public static Object getObject(Object source, String field) {
try {
Field f = source.getClass().getDeclaredField(field);
f.setAccessible(true);
@@ -39,6 +39,24 @@ public class ReflectionUtils {
}
}
/**
* Get the specified field name in the object source
*
* @param source where we will find the field
* @param field the name of the field
* @return the requested field
*/
public static Field getField(Object source, String field) {
try {
Field f = source.getClass().getDeclaredField(field);
f.setAccessible(true);
return f;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* Call method. Return the method return.
*
@@ -18,7 +18,7 @@ public class Storage {
private FileConfiguration conf;
public final HashMap<String, HashMap<Short, String>> TRANSLATIONS = new HashMap<>();
public boolean COLOR_IF_ALREADY_COLORED, FORCE_ADD_AMOUNT, LET_MESSAGE_THROUGH, DENY_IF_NO_ITEM,
public boolean COLOR_IF_ALREADY_COLORED, FORCE_ADD_AMOUNT, LET_MESSAGE_THROUGH, DENY_IF_NO_ITEM, DEBUG,
HAND_DISABLED, SHOW_NO_PERM_NORMAL, CHECK_UPDATE, SHOW_NO_PERM_COMMAND, PERMISSION_ENABLED;
public final String HAND_NAME, NAME_FORMAT, AMOUNT_FORMAT, MANAGER, PERMISSION_NAME;
public final String NO_PERMISSION_MESSAGE, DENY_MESSAGE, RELOAD_MESSAGE, COOLDOWN_MESSAGE, LIMIT_MESSAGE;
@@ -45,6 +45,7 @@ public class Storage {
TRANSLATIONS.put(key, entry);
}
DEBUG = conf.getBoolean("debug", false);
PLACEHOLDERS = ImmutableList.copyOf(conf.getStringList("general.placeholders"));
NAME_FORMAT = color(conf.getString("general.name-format", "&b&l&o{name} {amount}&r"));
AMOUNT_FORMAT = color(conf.getString("general.amount-format", "x{times}"));
+14 -18
View File
@@ -2,10 +2,10 @@
# For info visit
# Spigotmc: https://www.spigotmc.org/resources/chatitem.19064/
# Discord: https://discord.gg/ttA5CjMhk7
# Version info, DON'T TOUCH
config-version: 13
# By default, it's in "both" mode.
#
# Available mode :
@@ -50,7 +50,7 @@ general:
tooltip:
- "&7Nothing to see here"
- "&7Just the empty hand of {display-name}."
# Here you can choose which commands will the plugin attempt to parse. Console commands will all be ignored,
# however player commands will be taken into consideration. To add a command, simply add an element to the list
# bellow containing an alias (or name) for that command.
@@ -77,8 +77,8 @@ general:
cooldown: 60
# Check if the plugin have update
check-update: true
# Messages section. You can disable any of them by simply leaving them empty, like this: ""
messages:
# The message sent if showing off hands is disabled and the user isn't holding an item.
@@ -142,6 +142,7 @@ messages:
hand-disabled: "&6Hand disabled: %state%"
limit-per-message: "&6Limit per message: &a%state%"
cooldown: "&6Cooldown: &a%state%"
debug: "&6Debug: &a%state%"
# Change name and lore of all managers
manager:
both:
@@ -184,14 +185,14 @@ messages:
seconds: " seconds"
minutes: " minutes"
hours: " hours"
enabled: "&aEnabled"
disabled: "&cDisabled"
# Translations
# This is used to display prettier names in chat for items/blocks. Modifying this is usually unnecessary unless you know what you're doing.
translations:
## Blocks ##
STONE:
1: "Granite"
STONE:
0: "Stone"
1: "Granite"
@@ -784,8 +785,8 @@ translations:
STONE_PICKAXE:
0: "Stone Pickaxe"
STONE_AXE:
0: "Stone Axe
DIAMOND_SWORD: "
0: "Stone Axe"
DIAMOND_SWORD:
0: "Diamond Sword"
DIAMOND_SPADE:
0: "Diamond Shovel"
@@ -937,8 +938,6 @@ translations:
1: "Raw Salmon"
2: "Clownfish"
3: "Pufferfish"
COOKED_FISH:
0: "Cooked Fish"
COOKED_FISH:
0: "Cooked Salmon"
INK_SACK:
@@ -1070,9 +1069,6 @@ translations:
16394: "Splash Potion of Slowness"
16426: "Splash Potion of Slowness II"
16458: "Extended Splash Potion of Slowness"
16395: "Splash Potion of Leaping"
16427: "Splash Potion of Leaping II"
16459: "Extended Splash Potion of Leaping"
16396: "Splash Potion of Harming"
16428: "Splash Potion of Harming II"
16460: "Extended Splash Potion of Harming"
@@ -1153,8 +1149,8 @@ translations:
POISONOUS_POTATO:
0: "Poisonous Potato"
EMPTY_MAP:
0: "Empty Map
GOLDEN_CARROT: "
0: "Empty Map"
GOLDEN_CARROT:
0: "Golden Carrot"
SKULL_ITEM:
0: "Skeleton Head"