use of com.loohp.interactivechat.libs.com.cryptomorin.xseries.XMaterial in project InteractiveChat-DiscordSRV-Addon by LOOHP.
the class OutboundToDiscordEvents method processGameMessage.
@SuppressWarnings("deprecation")
public Component processGameMessage(ICPlayer icSender, Component component) {
boolean reserializer = DiscordSRV.config().getBoolean("Experiment_MCDiscordReserializer_ToDiscord");
PlaceholderCooldownManager cooldownManager = InteractiveChatDiscordSrvAddon.plugin.placeholderCooldownManager;
long now = cooldownManager.checkMessage(icSender.getUniqueId(), PlainTextComponentSerializer.plainText().serialize(component)).getTimeNow();
GameMessagePreProcessEvent gameMessagePreProcessEvent = new GameMessagePreProcessEvent(icSender, component, false);
Bukkit.getPluginManager().callEvent(gameMessagePreProcessEvent);
if (gameMessagePreProcessEvent.isCancelled()) {
return null;
}
component = ComponentFlattening.flatten(gameMessagePreProcessEvent.getComponent());
String plain = InteractiveChatComponentSerializer.plainText().serialize(component);
if (InteractiveChat.useItem && PlayerUtils.hasPermission(icSender.getUniqueId(), "interactivechat.module.item", true, 200)) {
Debug.debug("onGameToDiscord processing item display");
if (!cooldownManager.isPlaceholderOnCooldownAt(icSender.getUniqueId(), InteractiveChat.placeholderList.values().stream().filter(each -> each.getKeyword().equals(InteractiveChat.itemPlaceholder)).findFirst().get(), now)) {
Matcher matcher = InteractiveChat.itemPlaceholder.matcher(plain);
if (matcher.find()) {
ItemStack item = PlayerUtils.getHeldItem(icSender);
boolean isAir = item.getType().equals(Material.AIR);
XMaterial xMaterial = XMaterialUtils.matchXMaterial(item);
String itemStr = PlainTextComponentSerializer.plainText().serialize(ComponentStringUtils.convertTranslatables(ComponentModernizing.modernize(ItemStackUtils.getDisplayName(item)), InteractiveChatDiscordSrvAddon.plugin.resourceManager.getLanguageManager().getTranslateFunction().ofLanguage(InteractiveChatDiscordSrvAddon.plugin.language)));
itemStr = ComponentStringUtils.stripColorAndConvertMagic(itemStr);
int amount = item.getAmount();
if (isAir) {
amount = 1;
}
String replaceText = PlaceholderParser.parse(icSender, (amount == 1 ? ComponentStringUtils.stripColorAndConvertMagic(InteractiveChat.itemSingularReplaceText) : ComponentStringUtils.stripColorAndConvertMagic(InteractiveChat.itemReplaceText).replace("{Amount}", String.valueOf(amount))).replace("{Item}", itemStr));
if (reserializer) {
replaceText = MessageUtil.reserializeToDiscord(github.scarsz.discordsrv.dependencies.kyori.adventure.text.Component.text(replaceText));
}
AtomicBoolean replaced = new AtomicBoolean(false);
Component replaceComponent = LegacyComponentSerializer.legacySection().deserialize(replaceText);
component = ComponentReplacing.replace(component, InteractiveChat.itemPlaceholder.pattern(), true, (groups) -> {
replaced.set(true);
return replaceComponent;
});
if (replaced.get() && InteractiveChatDiscordSrvAddon.plugin.itemImage) {
int inventoryId = DATA_ID_PROVIDER.getNext();
int position = matcher.start();
String title = PlaceholderParser.parse(icSender, ComponentStringUtils.stripColorAndConvertMagic(InteractiveChat.itemTitle));
Inventory inv = null;
if (item.hasItemMeta() && item.getItemMeta() instanceof BlockStateMeta) {
BlockState bsm = ((BlockStateMeta) item.getItemMeta()).getBlockState();
if (bsm instanceof InventoryHolder) {
Inventory container = ((InventoryHolder) bsm).getInventory();
if (!container.isEmpty()) {
inv = Bukkit.createInventory(null, InventoryUtils.toMultipleOf9(container.getSize()));
for (int j = 0; j < container.getSize(); j++) {
if (container.getItem(j) != null) {
if (!container.getItem(j).getType().equals(Material.AIR)) {
inv.setItem(j, container.getItem(j).clone());
}
}
}
}
}
}
GameMessageProcessItemEvent gameMessageProcessItemEvent = new GameMessageProcessItemEvent(icSender, title, component, false, inventoryId, item.clone(), inv);
Bukkit.getPluginManager().callEvent(gameMessageProcessItemEvent);
if (!gameMessageProcessItemEvent.isCancelled()) {
component = gameMessageProcessItemEvent.getComponent();
title = gameMessageProcessItemEvent.getTitle();
if (gameMessageProcessItemEvent.hasInventory()) {
DATA.put(inventoryId, new ImageDisplayData(icSender, position, title, ImageDisplayType.ITEM_CONTAINER, gameMessageProcessItemEvent.getItemStack().clone(), new TitledInventoryWrapper(ItemStackUtils.getDisplayName(item, null), gameMessageProcessItemEvent.getInventory())));
} else {
DATA.put(inventoryId, new ImageDisplayData(icSender, position, title, ImageDisplayType.ITEM, gameMessageProcessItemEvent.getItemStack().clone()));
}
}
component = component.append(Component.text("<ICD=" + inventoryId + ">"));
}
}
}
}
if (InteractiveChat.useInventory && PlayerUtils.hasPermission(icSender.getUniqueId(), "interactivechat.module.inventory", true, 200)) {
Debug.debug("onGameToDiscord processing inventory display");
if (!cooldownManager.isPlaceholderOnCooldownAt(icSender.getUniqueId(), InteractiveChat.placeholderList.values().stream().filter(each -> each.getKeyword().equals(InteractiveChat.invPlaceholder)).findFirst().get(), now)) {
Matcher matcher = InteractiveChat.invPlaceholder.matcher(plain);
if (matcher.find()) {
String replaceText = PlaceholderParser.parse(icSender, ComponentStringUtils.stripColorAndConvertMagic(InteractiveChat.invReplaceText));
if (reserializer) {
replaceText = MessageUtil.reserializeToDiscord(github.scarsz.discordsrv.dependencies.kyori.adventure.text.Component.text(replaceText));
}
AtomicBoolean replaced = new AtomicBoolean(false);
Component replaceComponent = LegacyComponentSerializer.legacySection().deserialize(replaceText);
component = ComponentReplacing.replace(component, InteractiveChat.invPlaceholder.pattern(), true, (groups) -> {
replaced.set(true);
return replaceComponent;
});
if (replaced.get() && InteractiveChatDiscordSrvAddon.plugin.invImage) {
int inventoryId = DATA_ID_PROVIDER.getNext();
int position = matcher.start();
Inventory inv = Bukkit.createInventory(null, 45);
for (int j = 0; j < icSender.getInventory().getSize(); j++) {
if (icSender.getInventory().getItem(j) != null) {
if (!icSender.getInventory().getItem(j).getType().equals(Material.AIR)) {
inv.setItem(j, icSender.getInventory().getItem(j).clone());
}
}
}
String title = PlaceholderParser.parse(icSender, ComponentStringUtils.stripColorAndConvertMagic(InteractiveChat.invTitle));
GameMessageProcessPlayerInventoryEvent gameMessageProcessPlayerInventoryEvent = new GameMessageProcessPlayerInventoryEvent(icSender, title, component, false, inventoryId, inv);
Bukkit.getPluginManager().callEvent(gameMessageProcessPlayerInventoryEvent);
if (!gameMessageProcessPlayerInventoryEvent.isCancelled()) {
component = gameMessageProcessPlayerInventoryEvent.getComponent();
title = gameMessageProcessPlayerInventoryEvent.getTitle();
DATA.put(inventoryId, new ImageDisplayData(icSender, position, title, ImageDisplayType.INVENTORY, true, new TitledInventoryWrapper(Component.translatable(TranslationKeyUtils.getDefaultContainerTitle()), gameMessageProcessPlayerInventoryEvent.getInventory())));
}
component = component.append(Component.text("<ICD=" + inventoryId + ">"));
}
}
}
}
if (InteractiveChat.useEnder && PlayerUtils.hasPermission(icSender.getUniqueId(), "interactivechat.module.enderchest", true, 200)) {
Debug.debug("onGameToDiscord processing enderchest display");
if (!cooldownManager.isPlaceholderOnCooldownAt(icSender.getUniqueId(), InteractiveChat.placeholderList.values().stream().filter(each -> each.getKeyword().equals(InteractiveChat.enderPlaceholder)).findFirst().get(), now)) {
Matcher matcher = InteractiveChat.enderPlaceholder.matcher(plain);
if (matcher.find()) {
String replaceText = PlaceholderParser.parse(icSender, ComponentStringUtils.stripColorAndConvertMagic(InteractiveChat.enderReplaceText));
if (reserializer) {
replaceText = MessageUtil.reserializeToDiscord(github.scarsz.discordsrv.dependencies.kyori.adventure.text.Component.text(replaceText));
}
AtomicBoolean replaced = new AtomicBoolean(false);
Component replaceComponent = LegacyComponentSerializer.legacySection().deserialize(replaceText);
component = ComponentReplacing.replace(component, InteractiveChat.enderPlaceholder.pattern(), true, (groups) -> {
replaced.set(true);
return replaceComponent;
});
if (replaced.get() && InteractiveChatDiscordSrvAddon.plugin.enderImage) {
int inventoryId = DATA_ID_PROVIDER.getNext();
int position = matcher.start();
Inventory inv = Bukkit.createInventory(null, InventoryUtils.toMultipleOf9(icSender.getEnderChest().getSize()));
for (int j = 0; j < icSender.getEnderChest().getSize(); j++) {
if (icSender.getEnderChest().getItem(j) != null) {
if (!icSender.getEnderChest().getItem(j).getType().equals(Material.AIR)) {
inv.setItem(j, icSender.getEnderChest().getItem(j).clone());
}
}
}
String title = PlaceholderParser.parse(icSender, ComponentStringUtils.stripColorAndConvertMagic(InteractiveChat.enderTitle));
GameMessageProcessInventoryEvent gameMessageProcessInventoryEvent = new GameMessageProcessInventoryEvent(icSender, title, component, false, inventoryId, inv);
Bukkit.getPluginManager().callEvent(gameMessageProcessInventoryEvent);
if (!gameMessageProcessInventoryEvent.isCancelled()) {
component = gameMessageProcessInventoryEvent.getComponent();
title = gameMessageProcessInventoryEvent.getTitle();
DATA.put(inventoryId, new ImageDisplayData(icSender, position, title, ImageDisplayType.ENDERCHEST, new TitledInventoryWrapper(Component.translatable(TranslationKeyUtils.getEnderChestContainerTitle()), gameMessageProcessInventoryEvent.getInventory())));
}
component = component.append(Component.text("<ICD=" + inventoryId + ">"));
}
}
}
}
Debug.debug("onGameToDiscord processing custom placeholders");
for (ICPlaceholder placeholder : InteractiveChatAPI.getICPlaceholderList()) {
if (!placeholder.isBuildIn()) {
CustomPlaceholder customP = (CustomPlaceholder) placeholder;
if (!InteractiveChat.useCustomPlaceholderPermissions || (InteractiveChat.useCustomPlaceholderPermissions && PlayerUtils.hasPermission(icSender.getUniqueId(), customP.getPermission(), true, 200))) {
boolean onCooldown = cooldownManager.isPlaceholderOnCooldownAt(icSender.getUniqueId(), customP, now);
Matcher matcher = customP.getKeyword().matcher(plain);
if (matcher.find() && !onCooldown) {
String replaceText;
if (customP.getReplace().isEnabled()) {
replaceText = ChatColorUtils.translateAlternateColorCodes('&', PlaceholderParser.parse(icSender, customP.getReplace().getReplaceText()));
} else {
replaceText = null;
}
List<Component> toAppend = new LinkedList<>();
Set<String> shown = new HashSet<>();
component = ComponentReplacing.replace(component, customP.getKeyword().pattern(), true, (result, matchedComponents) -> {
String replaceString = replaceText == null ? result.group() : CustomStringUtils.applyReplacementRegex(replaceText, result, 1);
if (!shown.contains(replaceString)) {
shown.add(replaceString);
int position = result.start();
if (InteractiveChatDiscordSrvAddon.plugin.hoverEnabled && !InteractiveChatDiscordSrvAddon.plugin.hoverIgnore.contains(customP.getPosition())) {
HoverClickDisplayData.Builder hoverClick = new HoverClickDisplayData.Builder().player(icSender).postion(position).color(DiscordDataRegistry.DISCORD_HOVER_COLOR).displayText(ChatColorUtils.stripColor(replaceString));
boolean usingHoverClick = false;
if (customP.getHover().isEnabled()) {
usingHoverClick = true;
String hoverText = ChatColorUtils.translateAlternateColorCodes('&', PlaceholderParser.parse(icSender, CustomStringUtils.applyReplacementRegex(customP.getHover().getText(), result, 1)));
Color color = ColorUtils.getFirstColor(hoverText);
hoverClick.hoverText(LegacyComponentSerializer.legacySection().deserialize(hoverText));
if (color != null) {
hoverClick.color(color);
}
}
if (customP.getClick().isEnabled()) {
usingHoverClick = true;
hoverClick.clickAction(customP.getClick().getAction()).clickValue(CustomStringUtils.applyReplacementRegex(customP.getClick().getValue(), result, 1));
}
if (usingHoverClick) {
int hoverId = DATA_ID_PROVIDER.getNext();
DATA.put(hoverId, hoverClick.build());
toAppend.add(Component.text("<ICD=" + hoverId + ">"));
}
}
}
return replaceText == null ? Component.empty().children(matchedComponents) : LegacyComponentSerializer.legacySection().deserialize(replaceString);
});
for (Component componentToAppend : toAppend) {
component = component.append(componentToAppend);
}
}
}
}
}
if (InteractiveChat.t && WebData.getInstance() != null) {
for (CustomPlaceholder customP : WebData.getInstance().getSpecialPlaceholders()) {
boolean onCooldown = cooldownManager.isPlaceholderOnCooldownAt(icSender.getUniqueId(), customP, now);
Matcher matcher = customP.getKeyword().matcher(plain);
if (matcher.find() && !onCooldown) {
String replaceText;
if (customP.getReplace().isEnabled()) {
replaceText = ChatColorUtils.translateAlternateColorCodes('&', PlaceholderParser.parse(icSender, customP.getReplace().getReplaceText()));
} else {
replaceText = null;
}
List<Component> toAppend = new LinkedList<>();
Set<String> shown = new HashSet<>();
component = ComponentReplacing.replace(component, customP.getKeyword().pattern(), true, (result, matchedComponents) -> {
String replaceString = replaceText == null ? result.group() : CustomStringUtils.applyReplacementRegex(replaceText, result, 1);
if (!shown.contains(replaceString)) {
shown.add(replaceString);
int position = result.start();
if (InteractiveChatDiscordSrvAddon.plugin.hoverEnabled && !InteractiveChatDiscordSrvAddon.plugin.hoverIgnore.contains(customP.getPosition())) {
HoverClickDisplayData.Builder hoverClick = new HoverClickDisplayData.Builder().player(icSender).postion(position).color(DiscordDataRegistry.DISCORD_HOVER_COLOR).displayText(ChatColorUtils.stripColor(replaceString));
boolean usingHoverClick = false;
if (customP.getHover().isEnabled()) {
usingHoverClick = true;
String hoverText = ChatColorUtils.translateAlternateColorCodes('&', PlaceholderParser.parse(icSender, CustomStringUtils.applyReplacementRegex(customP.getHover().getText(), result, 1)));
Color color = ColorUtils.getFirstColor(hoverText);
hoverClick.hoverText(LegacyComponentSerializer.legacySection().deserialize(hoverText));
if (color != null) {
hoverClick.color(color);
}
}
if (customP.getClick().isEnabled()) {
usingHoverClick = true;
hoverClick.clickAction(customP.getClick().getAction()).clickValue(CustomStringUtils.applyReplacementRegex(customP.getClick().getValue(), result, 1));
}
if (usingHoverClick) {
int hoverId = DATA_ID_PROVIDER.getNext();
DATA.put(hoverId, hoverClick.build());
toAppend.add(Component.text("<ICD=" + hoverId + ">"));
}
}
}
return replaceText == null ? Component.empty().children(matchedComponents) : LegacyComponentSerializer.legacySection().deserialize(replaceString);
});
for (Component componentToAppend : toAppend) {
component = component.append(componentToAppend);
}
}
}
}
DiscordSRV srv = InteractiveChatDiscordSrvAddon.discordsrv;
if (InteractiveChatDiscordSrvAddon.plugin.translateMentions) {
Debug.debug("onGameToDiscord processing mentions");
List<MentionPair> distinctMentionPairs = new ArrayList<>();
Set<UUID> processedReceivers = new HashSet<>();
synchronized (InteractiveChat.mentionPair) {
for (MentionPair pair : InteractiveChat.mentionPair) {
if (!processedReceivers.contains(pair.getReciever())) {
distinctMentionPairs.add(pair);
processedReceivers.add(pair.getReciever());
}
}
}
for (MentionPair pair : distinctMentionPairs) {
if (pair.getSender().equals(icSender.getUniqueId())) {
UUID receiverUUID = pair.getReciever();
Set<String> names = new HashSet<>();
ICPlayer receiver = ICPlayerFactory.getICPlayer(receiverUUID);
if (receiver != null) {
names.add(ChatColorUtils.stripColor(receiver.getName()));
List<String> list = InteractiveChatAPI.getNicknames(receiver.getUniqueId());
for (String name : list) {
names.add(ChatColorUtils.stripColor(name));
}
}
String userId = srv.getAccountLinkManager().getDiscordId(receiverUUID);
if (userId != null) {
User user = srv.getJda().getUserById(userId);
if (user != null) {
String discordMention = user.getAsMention();
for (String name : names) {
component = ComponentReplacing.replace(component, CustomStringUtils.escapeMetaCharacters(Registry.MENTION_TAG_CONVERTER.getTagStyle(InteractiveChat.mentionPrefix + name)), true, LegacyComponentSerializer.legacySection().deserialize(discordMention));
}
}
}
}
}
}
GameMessagePostProcessEvent gameMessagePostProcessEvent = new GameMessagePostProcessEvent(icSender, component, false);
Bukkit.getPluginManager().callEvent(gameMessagePostProcessEvent);
if (gameMessagePostProcessEvent.isCancelled()) {
return null;
}
component = gameMessagePostProcessEvent.getComponent();
return component;
}
use of com.loohp.interactivechat.libs.com.cryptomorin.xseries.XMaterial in project InteractiveChat-DiscordSRV-Addon by LOOHP.
the class DiscordItemStackUtils method getDiscordDescription.
public static DiscordDescription getDiscordDescription(ItemStack item, Player player) throws Exception {
String language = InteractiveChatDiscordSrvAddon.plugin.language;
if (!item.getType().equals(Material.AIR) && InteractiveChat.ecoHook) {
item = EcoHook.setEcoLores(item, player);
}
if (item == null) {
item = new ItemStack(Material.AIR);
}
XMaterial xMaterial = XMaterialUtils.matchXMaterial(item);
String name = PlainTextComponentSerializer.plainText().serialize(LegacyComponentSerializer.legacySection().deserialize(InteractiveChatComponentSerializer.bungeecordApiLegacy().serialize(ItemStackUtils.getDisplayName(item), language)));
if (item.getAmount() == 1 || item == null || item.getType().equals(Material.AIR)) {
name = InteractiveChatDiscordSrvAddon.plugin.itemDisplaySingle.replace("{Item}", ComponentStringUtils.stripColorAndConvertMagic(name)).replace("{Amount}", String.valueOf(item.getAmount()));
} else {
name = InteractiveChatDiscordSrvAddon.plugin.itemDisplayMultiple.replace("{Item}", ComponentStringUtils.stripColorAndConvertMagic(name)).replace("{Amount}", String.valueOf(item.getAmount()));
}
boolean hasMeta = item.hasItemMeta();
StringBuilder description = new StringBuilder();
if (xMaterial.equals(XMaterial.WRITTEN_BOOK) && hasMeta && item.getItemMeta() instanceof BookMeta) {
BookMeta meta = (BookMeta) item.getItemMeta();
String author = meta.getAuthor();
if (author != null) {
description.append(LanguageUtils.getTranslation(TranslationKeyUtils.getBookAuthor(), language).replaceFirst("%1\\$s", ChatColorUtils.stripColor(author))).append("\n");
}
Generation generation = meta.getGeneration();
if (generation == null) {
generation = Generation.ORIGINAL;
}
description.append(LanguageUtils.getTranslation(TranslationKeyUtils.getBookGeneration(generation), language)).append("\n");
description.append("\n");
}
if (xMaterial.equals(XMaterial.SHIELD) && (!hasMeta || (hasMeta && !item.getItemMeta().hasItemFlag(ItemFlag.HIDE_POTION_EFFECTS)))) {
if (NBTEditor.contains(item, "BlockEntityTag")) {
List<Pattern> patterns = Collections.emptyList();
if (!(item.getItemMeta() instanceof BannerMeta)) {
if (item.getItemMeta() instanceof BlockStateMeta) {
BlockStateMeta bmeta = (BlockStateMeta) item.getItemMeta();
if (bmeta.hasBlockState()) {
Banner bannerBlockMeta = (Banner) bmeta.getBlockState();
patterns = bannerBlockMeta.getPatterns();
}
}
} else {
BannerMeta meta = (BannerMeta) item.getItemMeta();
patterns = meta.getPatterns();
}
for (Pattern pattern : patterns) {
PatternTypeWrapper type = PatternTypeWrapper.fromPatternType(pattern.getPattern());
description.append(LanguageUtils.getTranslation(TranslationKeyUtils.getBannerPatternName(type, pattern.getColor()), language)).append("\n");
}
}
}
if (xMaterial.isOneOf(Arrays.asList("CONTAINS:Banner")) && (!hasMeta || (hasMeta && !item.getItemMeta().hasItemFlag(ItemFlag.HIDE_POTION_EFFECTS)))) {
List<Pattern> patterns = Collections.emptyList();
if (!(item.getItemMeta() instanceof BannerMeta)) {
if (item.getItemMeta() instanceof BlockStateMeta) {
BlockStateMeta bmeta = (BlockStateMeta) item.getItemMeta();
Banner bannerBlockMeta = (Banner) bmeta.getBlockState();
patterns = bannerBlockMeta.getPatterns();
}
} else {
BannerMeta meta = (BannerMeta) item.getItemMeta();
patterns = meta.getPatterns();
}
for (Pattern pattern : patterns) {
PatternTypeWrapper type = PatternTypeWrapper.fromPatternType(pattern.getPattern());
description.append(LanguageUtils.getTranslation(TranslationKeyUtils.getBannerPatternName(type, pattern.getColor()), language)).append("\n");
}
}
if (xMaterial.equals(XMaterial.TROPICAL_FISH_BUCKET)) {
List<String> translations = TranslationKeyUtils.getTropicalFishBucketName(item);
if (translations.size() > 0) {
description.append(LanguageUtils.getTranslation(translations.get(0), language)).append("\n");
if (translations.size() > 1) {
description.append(translations.stream().skip(1).map(each -> LanguageUtils.getTranslation(each, language)).collect(Collectors.joining(", "))).append("\n");
}
description.append("\n");
}
}
if (xMaterial.isOneOf(Arrays.asList("CONTAINS:Music_Disc"))) {
description.append(LanguageUtils.getTranslation(TranslationKeyUtils.getMusicDiscName(item), language)).append("\n");
}
if (xMaterial.equals(XMaterial.FIREWORK_ROCKET)) {
if (InteractiveChat.version.isNewerOrEqualTo(MCVersion.V1_12) && NBTEditor.contains(item, "Fireworks", "Flight")) {
int flight = NBTEditor.getByte(item, "Fireworks", "Flight");
description.append(LanguageUtils.getTranslation(TranslationKeyUtils.getRocketFlightDuration(), language)).append(" ").append(flight).append("\n");
}
}
if (xMaterial.equals(XMaterial.CROSSBOW)) {
CrossbowMeta meta = (CrossbowMeta) item.getItemMeta();
List<ItemStack> charged = meta.getChargedProjectiles();
if (charged != null && !charged.isEmpty()) {
ItemStack charge = charged.get(0);
String chargeItemName = getDiscordDescription(charge, player).getName();
description.append(LanguageUtils.getTranslation(TranslationKeyUtils.getCrossbowProjectile(), language)).append(" [**").append(chargeItemName).append("**]\n\n");
}
}
if (InteractiveChat.version.isNewerOrEqualTo(MCVersion.V1_12) && FilledMapUtils.isFilledMap(item)) {
MapMeta map = (MapMeta) item.getItemMeta();
MapView mapView;
int id;
if (InteractiveChat.version.isNewerOrEqualTo(MCVersion.V1_13_1)) {
mapView = map.getMapView();
id = mapView.getId();
} else if (InteractiveChat.version.equals(MCVersion.V1_13)) {
short shortId = (short) bukkitMapViewClassGetIdMethod.invoke(map);
mapView = (MapView) bukkitBukkitClassGetMapShortMethod.invoke(null, shortId);
id = shortId;
} else {
short shortId = item.getDurability();
mapView = (MapView) bukkitBukkitClassGetMapShortMethod.invoke(null, shortId);
id = shortId;
}
int scale = mapView.getScale().getValue();
if (!InteractiveChat.version.isLegacy()) {
description.append(LanguageUtils.getTranslation(TranslationKeyUtils.getFilledMapId(), language).replaceFirst("%s", id + "")).append("\n");
} else {
name += " (#" + id + ")";
}
description.append(LanguageUtils.getTranslation(TranslationKeyUtils.getFilledMapScale(), language).replaceFirst("%s", (int) Math.pow(2, scale) + "")).append("\n");
description.append(LanguageUtils.getTranslation(TranslationKeyUtils.getFilledMapLevel(), language).replaceFirst("%s", scale + "").replaceFirst("%s", "4")).append("\n");
description.append("\n");
}
if (InteractiveChat.version.isNewerOrEqualTo(MCVersion.V1_12) && !hasMeta || (hasMeta && !item.getItemMeta().hasItemFlag(ItemFlag.HIDE_POTION_EFFECTS))) {
if (item.getItemMeta() instanceof PotionMeta) {
PotionMeta meta = (PotionMeta) item.getItemMeta();
List<PotionEffect> effects = new ArrayList<>();
List<PotionEffect> base = PotionUtils.getBasePotionEffect(item);
if (base != null) {
effects.addAll(base);
}
effects.addAll(meta.getCustomEffects());
if (effects.isEmpty()) {
description.append("**").append(LanguageUtils.getTranslation(TranslationKeyUtils.getNoEffect(), language)).append("**\n");
} else {
for (PotionEffect effect : effects) {
String key = TranslationKeyUtils.getEffect(effect.getType());
String translation = LanguageUtils.getTranslation(key, language);
if (key.equals(translation)) {
description.append("**").append(WordUtils.capitalize(effect.getType().getName().toLowerCase().replace("_", " ")));
} else {
description.append("**").append(translation);
}
int amplifier = effect.getAmplifier();
String effectLevelTranslation = LanguageUtils.getTranslation(TranslationKeyUtils.getEffectLevel(amplifier), language);
if (effectLevelTranslation.length() > 0) {
description.append(" ").append(effectLevelTranslation);
}
if (!effect.getType().isInstant()) {
if (xMaterial.equals(XMaterial.LINGERING_POTION)) {
description.append(" (").append(TimeUtils.getReadableTimeBetween(0, effect.getDuration() / 4 * 50L, ":", ChronoUnit.MINUTES, ChronoUnit.SECONDS, true)).append(")");
} else {
description.append(" (").append(TimeUtils.getReadableTimeBetween(0, effect.getDuration() * 50L, ":", ChronoUnit.MINUTES, ChronoUnit.SECONDS, true)).append(")");
}
}
description.append("**\n");
}
}
if (!description.toString().equals("")) {
description.append("\n");
}
}
}
if (!hasMeta || (hasMeta && !item.getItemMeta().hasItemFlag(ItemFlag.HIDE_ENCHANTS))) {
if (hasMeta && item.getItemMeta() instanceof EnchantmentStorageMeta) {
for (Entry<Enchantment, Integer> entry : CustomMapUtils.sortMapByValue(((EnchantmentStorageMeta) item.getItemMeta()).getStoredEnchants()).entrySet()) {
Enchantment ench = entry.getKey();
int level = entry.getValue();
String key = TranslationKeyUtils.getEnchantment(ench);
String translation = LanguageUtils.getTranslation(key, language);
String enchName;
if (key.equals(translation)) {
enchName = WordUtils.capitalize(ench.getName().toLowerCase().replace("_", " "));
} else {
enchName = translation;
}
if (enchName != null) {
description.append("**").append(enchName).append(ench.getMaxLevel() == 1 && level == 1 ? "" : " " + LanguageUtils.getTranslation(TranslationKeyUtils.getEnchantmentLevel(level), language)).append("**\n");
}
}
} else {
for (Entry<Enchantment, Integer> entry : CustomMapUtils.sortMapByValue(item.getEnchantments()).entrySet()) {
Enchantment ench = entry.getKey();
int level = entry.getValue();
String key = TranslationKeyUtils.getEnchantment(ench);
String translation = LanguageUtils.getTranslation(key, language);
String enchName;
if (key.equals(translation)) {
enchName = WordUtils.capitalize(ench.getName().toLowerCase().replace("_", " "));
} else {
enchName = translation;
}
if (enchName != null) {
description.append("**").append(enchName).append(ench.getMaxLevel() == 1 && level == 1 ? "" : " " + LanguageUtils.getTranslation(TranslationKeyUtils.getEnchantmentLevel(level), language)).append("**\n");
}
}
}
}
if (hasMeta && item.getItemMeta() instanceof LeatherArmorMeta && !item.getItemMeta().hasItemFlag(ItemFlag.HIDE_DYE)) {
LeatherArmorMeta meta = (LeatherArmorMeta) item.getItemMeta();
if (NBTEditor.contains(item, "display", "color")) {
if (!description.toString().equals("")) {
description.append("\n");
}
Color color = new Color(meta.getColor().asRGB());
String hex = ColorUtils.rgb2Hex(color).toUpperCase();
description.append(LanguageUtils.getTranslation(TranslationKeyUtils.getDyeColor(), language).replaceFirst("%s", hex)).append("\n");
}
}
if (hasMeta) {
ItemMeta meta = item.getItemMeta();
if (meta.hasLore()) {
if (!description.toString().equals("")) {
description.append("\n");
}
String lore = String.join("\n", meta.getLore());
if (DiscordSRV.config().getBoolean("Experiment_MCDiscordReserializer_ToDiscord")) {
if (InteractiveChatDiscordSrvAddon.plugin.escapeDiscordMarkdownInItems) {
lore = lore.replaceAll(DiscordDataRegistry.getMarkdownSpecialPattern(), "\\\\$1");
}
lore = DiscordSerializer.INSTANCE.serialize(ComponentStringUtils.toDiscordSRVComponent(LEGACY_SERIALIZER.deserialize(lore)));
} else {
lore = ComponentStringUtils.stripColorAndConvertMagic(String.join("\n", meta.getLore()));
if (InteractiveChatDiscordSrvAddon.plugin.escapeDiscordMarkdownInItems) {
lore = lore.replaceAll(DiscordDataRegistry.getMarkdownSpecialPattern(), "\\\\$1");
}
}
description.append(lore).append("\n");
}
}
if (InteractiveChat.version.isNewerOrEqualTo(MCVersion.V1_12) && hasMeta && NBTEditor.contains(item, "AttributeModifiers") && NBTEditor.getSize(item, "AttributeModifiers") > 0 && !item.getItemMeta().hasItemFlag(ItemFlag.HIDE_ATTRIBUTES)) {
boolean useMainHand = false;
List<String> mainHand = new LinkedList<>();
boolean useOffhand = false;
List<String> offHand = new LinkedList<>();
boolean useFeet = false;
List<String> feet = new LinkedList<>();
boolean useLegs = false;
List<String> legs = new LinkedList<>();
boolean useChest = false;
List<String> chest = new LinkedList<>();
boolean useHead = false;
List<String> head = new LinkedList<>();
ListTag<CompoundTag> attributeList = (ListTag<CompoundTag>) new SNBTDeserializer().fromString(NBTEditor.getNBTCompound(item, "tag", "AttributeModifiers").toJson());
for (CompoundTag attributeTag : attributeList) {
String attributeName = attributeTag.getString("AttributeName").replace("minecraft:", "");
double amount = attributeTag.getDouble("Amount");
int operation = attributeTag.containsKey("Operation") ? attributeTag.getInt("Operation") : 0;
String attributeComponent = LanguageUtils.getTranslation(TranslationKeyUtils.getAttributeModifierKey(amount, operation), language).replaceFirst("%s", ATTRIBUTE_FORMAT.format(Math.abs(amount)) + "").replaceFirst("%s", LanguageUtils.getTranslation(TranslationKeyUtils.getAttributeKey(attributeName), language)).replace("%%", "%");
if (attributeTag.containsKey("Slot")) {
String slot = attributeTag.getString("Slot");
switch(slot) {
case "mainhand":
if (amount != 0) {
mainHand.add(attributeComponent);
}
useMainHand = true;
break;
case "offhand":
if (amount != 0) {
offHand.add(attributeComponent);
}
useOffhand = true;
break;
case "feet":
if (amount != 0) {
feet.add(attributeComponent);
}
useFeet = true;
break;
case "legs":
if (amount != 0) {
legs.add(attributeComponent);
}
useLegs = true;
break;
case "chest":
if (amount != 0) {
chest.add(attributeComponent);
}
useChest = true;
break;
case "head":
if (amount != 0) {
head.add(attributeComponent);
}
useHead = true;
break;
}
} else {
if (amount != 0) {
mainHand.add(attributeComponent);
offHand.add(attributeComponent);
feet.add(attributeComponent);
legs.add(attributeComponent);
chest.add(attributeComponent);
head.add(attributeComponent);
}
useMainHand = true;
useOffhand = true;
useFeet = true;
useLegs = true;
useChest = true;
useHead = true;
}
}
if (useMainHand) {
description.append("\n");
description.append(LanguageUtils.getTranslation(TranslationKeyUtils.getModifierSlotKey(EquipmentSlot.HAND), language)).append("\n");
for (String each : mainHand) {
description.append(each).append("\n");
}
}
if (useOffhand) {
description.append("\n");
description.append(LanguageUtils.getTranslation(TranslationKeyUtils.getModifierSlotKey(EquipmentSlot.OFF_HAND), language)).append("\n");
for (String each : offHand) {
description.append(each).append("\n");
}
}
if (useFeet) {
description.append("\n");
description.append(LanguageUtils.getTranslation(TranslationKeyUtils.getModifierSlotKey(EquipmentSlot.FEET), language)).append("\n");
for (String each : feet) {
description.append(each).append("\n");
}
}
if (useLegs) {
description.append("\n");
description.append(LanguageUtils.getTranslation(TranslationKeyUtils.getModifierSlotKey(EquipmentSlot.LEGS), language)).append("\n");
for (String each : legs) {
description.append(each).append("\n");
}
}
if (useChest) {
description.append("\n");
description.append(LanguageUtils.getTranslation(TranslationKeyUtils.getModifierSlotKey(EquipmentSlot.CHEST), language)).append("\n");
for (String each : chest) {
description.append(each).append("\n");
}
}
if (useHead) {
description.append("\n");
description.append(LanguageUtils.getTranslation(TranslationKeyUtils.getModifierSlotKey(EquipmentSlot.HEAD), language)).append("\n");
for (String each : head) {
description.append(each).append("\n");
}
}
}
if (hasMeta && isUnbreakable(item) && !item.getItemMeta().hasItemFlag(ItemFlag.HIDE_UNBREAKABLE)) {
if (!description.toString().equals("")) {
description.append("\n");
}
description.append("**").append(LanguageUtils.getTranslation(TranslationKeyUtils.getUnbreakable(), language)).append("**\n");
}
if (InteractiveChat.version.isNewerOrEqualTo(MCVersion.V1_12) && hasMeta && !item.getItemMeta().hasItemFlag(ItemFlag.HIDE_DESTROYS)) {
if (NBTEditor.contains(item, "CanDestroy") && NBTEditor.getSize(item, "CanDestroy") > 0) {
description.append("\n");
description.append(LanguageUtils.getTranslation(TranslationKeyUtils.getCanDestroy(), language)).append("\n");
ListTag<StringTag> materialList = (ListTag<StringTag>) new SNBTDeserializer().fromString(NBTEditor.getNBTCompound(item, "tag", "CanDestroy").toJson());
for (StringTag materialTag : materialList) {
XMaterial parsedXMaterial = XMaterialUtils.matchXMaterial(materialTag.getValue().replace("minecraft:", "").toUpperCase());
if (parsedXMaterial == null) {
description.append(WordUtils.capitalizeFully(materialTag.getValue().replace("_", " ").toLowerCase())).append("\n");
} else {
description.append(LanguageUtils.getTranslation(LanguageUtils.getTranslationKey(parsedXMaterial.parseItem()), language)).append("\n");
}
}
}
}
if (InteractiveChat.version.isNewerOrEqualTo(MCVersion.V1_12) && hasMeta && !item.getItemMeta().hasItemFlag(ItemFlag.HIDE_PLACED_ON)) {
if (NBTEditor.contains(item, "CanPlaceOn") && NBTEditor.getSize(item, "CanPlaceOn") > 0) {
description.append("\n");
description.append(LanguageUtils.getTranslation(TranslationKeyUtils.getCanPlace(), language)).append("\n");
ListTag<StringTag> materialList = (ListTag<StringTag>) new SNBTDeserializer().fromString(NBTEditor.getNBTCompound(item, "tag", "CanPlaceOn").toJson());
for (StringTag materialTag : materialList) {
XMaterial parsedXMaterial = XMaterialUtils.matchXMaterial(materialTag.getValue().replace("minecraft:", "").toUpperCase());
if (parsedXMaterial == null) {
description.append(WordUtils.capitalizeFully(materialTag.getValue().replace("_", " ").toLowerCase())).append("\n");
} else {
description.append(LanguageUtils.getTranslation(LanguageUtils.getTranslationKey(parsedXMaterial.parseItem()), language)).append("\n");
}
}
}
}
if (item.getType().getMaxDurability() > 0) {
int durability = item.getType().getMaxDurability() - (InteractiveChat.version.isLegacy() ? item.getDurability() : ((Damageable) item.getItemMeta()).getDamage());
int maxDur = item.getType().getMaxDurability();
if (durability < maxDur) {
if (!description.toString().equals("")) {
description.append("\n");
}
description.append("**").append(LanguageUtils.getTranslation(TranslationKeyUtils.getDurability(), language).replaceFirst("%s", String.valueOf(durability)).replaceFirst("%s", String.valueOf(maxDur))).append("**\n");
}
}
return new DiscordDescription(name, description.toString().trim().isEmpty() ? null : description.toString());
}
Aggregations