Fix nickname regex bug

The previous implementation didn't consider tbe case when the last player in the list doesn't have a nickname, leaving an empty "always match" part which messed up the formatting
@FigyTuna
Also added editorconfig for GitHub formatting
This commit is contained in:
Norbi Peti 2019-01-02 23:30:46 +01:00
parent 720740dea3
commit aed7864a15
No known key found for this signature in database
GPG key ID: DBA4C4549A927E56
2 changed files with 364 additions and 347 deletions

19
.editorconfig Normal file
View file

@ -0,0 +1,19 @@
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = false
indent_style = space
indent_size = 4
[*.json]
indent_style = space
indent_size = 2
[*.java]
indent_style = tab
tab_width = 4
[{*.yml, *.yaml}]
indent_style = space
indent_size = 2

View file

@ -1,347 +1,345 @@
package buttondevteam.chat; package buttondevteam.chat;
import buttondevteam.chat.commands.UnlolCommand; import buttondevteam.chat.commands.UnlolCommand;
import buttondevteam.chat.commands.ucmds.admin.DebugCommand; import buttondevteam.chat.commands.ucmds.admin.DebugCommand;
import buttondevteam.chat.formatting.ChatFormatter; import buttondevteam.chat.formatting.ChatFormatter;
import buttondevteam.chat.formatting.TellrawEvent; import buttondevteam.chat.formatting.TellrawEvent;
import buttondevteam.chat.formatting.TellrawPart; import buttondevteam.chat.formatting.TellrawPart;
import buttondevteam.chat.formatting.TellrawSerializer; import buttondevteam.chat.formatting.TellrawSerializer;
import buttondevteam.chat.listener.PlayerListener; import buttondevteam.chat.listener.PlayerListener;
import buttondevteam.lib.TBMCChatEvent; import buttondevteam.lib.TBMCChatEvent;
import buttondevteam.lib.TBMCChatEventBase; import buttondevteam.lib.TBMCChatEventBase;
import buttondevteam.lib.TBMCCoreAPI; import buttondevteam.lib.TBMCCoreAPI;
import buttondevteam.lib.chat.Channel; import buttondevteam.lib.chat.Channel;
import buttondevteam.lib.chat.Color; import buttondevteam.lib.chat.Color;
import buttondevteam.lib.chat.Priority; import buttondevteam.lib.chat.Priority;
import buttondevteam.lib.chat.TellrawSerializableEnum; import buttondevteam.lib.chat.TellrawSerializableEnum;
import buttondevteam.lib.player.ChromaGamerBase; import buttondevteam.lib.player.ChromaGamerBase;
import buttondevteam.lib.player.TBMCPlayer; import buttondevteam.lib.player.TBMCPlayer;
import buttondevteam.lib.player.TBMCPlayerBase; import buttondevteam.lib.player.TBMCPlayerBase;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
import lombok.val; import lombok.val;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Sound; import org.bukkit.Sound;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.scoreboard.Objective; import org.bukkit.scoreboard.Objective;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import java.util.*; import java.util.*;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.regex.Pattern; import java.util.regex.Pattern;
public class ChatProcessing { public class ChatProcessing {
private static final Pattern NULL_MENTION_PATTERN = Pattern.compile("null"); private static final Pattern NULL_MENTION_PATTERN = Pattern.compile("null");
private static final Pattern CYAN_PATTERN = Pattern.compile("cyan"); private static final Pattern CYAN_PATTERN = Pattern.compile("cyan");
private static final Pattern ESCAPE_PATTERN = Pattern.compile("\\\\"); private static final Pattern ESCAPE_PATTERN = Pattern.compile("\\\\");
private static final Pattern CONSOLE_PING_PATTERN = Pattern.compile("(?i)" + Pattern.quote("@console")); private static final Pattern CONSOLE_PING_PATTERN = Pattern.compile("(?i)" + Pattern.quote("@console"));
private static final Pattern HASHTAG_PATTERN = Pattern.compile("#(\\w+)"); private static final Pattern HASHTAG_PATTERN = Pattern.compile("#(\\w+)");
private static final Pattern URL_PATTERN = Pattern.compile("(http[\\w:/?=$\\-_.+!*'(),&]+(?:#[\\w]+)?)"); private static final Pattern URL_PATTERN = Pattern.compile("(http[\\w:/?=$\\-_.+!*'(),&]+(?:#[\\w]+)?)");
public static final Pattern ENTIRE_MESSAGE_PATTERN = Pattern.compile(".+"); public static final Pattern ENTIRE_MESSAGE_PATTERN = Pattern.compile(".+");
private static final Pattern UNDERLINED_PATTERN = Pattern.compile("_"); private static final Pattern UNDERLINED_PATTERN = Pattern.compile("_");
private static final Pattern ITALIC_PATTERN = Pattern.compile("\\*"); private static final Pattern ITALIC_PATTERN = Pattern.compile("\\*");
private static final Pattern BOLD_PATTERN = Pattern.compile("\\*\\*"); private static final Pattern BOLD_PATTERN = Pattern.compile("\\*\\*");
private static final Pattern CODE_PATTERN = Pattern.compile("`"); private static final Pattern CODE_PATTERN = Pattern.compile("`");
private static final Pattern MASKED_LINK_PATTERN = Pattern.compile("\\[([^\\[\\]])\\]\\(([^()])\\)"); private static final Pattern MASKED_LINK_PATTERN = Pattern.compile("\\[([^\\[\\]])\\]\\(([^()])\\)");
private static final Pattern SOMEONE_PATTERN = Pattern.compile("@someone"); //TODO private static final Pattern SOMEONE_PATTERN = Pattern.compile("@someone"); //TODO
private static final Pattern STRIKETHROUGH_PATTERN = Pattern.compile("~~"); private static final Pattern STRIKETHROUGH_PATTERN = Pattern.compile("~~");
private static final Color[] RainbowPresserColors = new Color[]{Color.Red, Color.Gold, Color.Yellow, Color.Green, private static final Color[] RainbowPresserColors = new Color[]{Color.Red, Color.Gold, Color.Yellow, Color.Green,
Color.Blue, Color.DarkPurple}; Color.Blue, Color.DarkPurple};
private static boolean pingedconsole = false; private static boolean pingedconsole = false;
public static final ChatFormatter ESCAPE_FORMATTER = ChatFormatter.builder().regex(ESCAPE_PATTERN).build(); public static final ChatFormatter ESCAPE_FORMATTER = ChatFormatter.builder().regex(ESCAPE_PATTERN).build();
private static ArrayList<ChatFormatter> commonFormatters = Lists.newArrayList( private static ArrayList<ChatFormatter> commonFormatters = Lists.newArrayList(
ChatFormatter.builder().regex(BOLD_PATTERN).bold(true).removeCharCount((short) 2).type(ChatFormatter.Type.Range) ChatFormatter.builder().regex(BOLD_PATTERN).bold(true).removeCharCount((short) 2).type(ChatFormatter.Type.Range)
.priority(Priority.High).build(), .priority(Priority.High).build(),
ChatFormatter.builder().regex(ITALIC_PATTERN).italic(true).removeCharCount((short) 1).type(ChatFormatter.Type.Range).build(), ChatFormatter.builder().regex(ITALIC_PATTERN).italic(true).removeCharCount((short) 1).type(ChatFormatter.Type.Range).build(),
ChatFormatter.builder().regex(UNDERLINED_PATTERN).underlined(true).removeCharCount((short) 1).type(ChatFormatter.Type.Range) ChatFormatter.builder().regex(UNDERLINED_PATTERN).underlined(true).removeCharCount((short) 1).type(ChatFormatter.Type.Range)
.build(), .build(),
ChatFormatter.builder().regex(STRIKETHROUGH_PATTERN).strikethrough(true).removeCharCount((short) 2).type(ChatFormatter.Type.Range) ChatFormatter.builder().regex(STRIKETHROUGH_PATTERN).strikethrough(true).removeCharCount((short) 2).type(ChatFormatter.Type.Range)
.build(), .build(),
ESCAPE_FORMATTER, ChatFormatter.builder().regex(URL_PATTERN).underlined(true).openlink("$1").type(ChatFormatter.Type.Excluder).build(), ESCAPE_FORMATTER, ChatFormatter.builder().regex(URL_PATTERN).underlined(true).openlink("$1").type(ChatFormatter.Type.Excluder).build(),
ChatFormatter.builder().regex(NULL_MENTION_PATTERN).color(Color.DarkRed).build(), // Properly added a bug as a feature ChatFormatter.builder().regex(NULL_MENTION_PATTERN).color(Color.DarkRed).build(), // Properly added a bug as a feature
ChatFormatter.builder().regex(CONSOLE_PING_PATTERN).color(Color.Aqua).onmatch((match, builder) -> { ChatFormatter.builder().regex(CONSOLE_PING_PATTERN).color(Color.Aqua).onmatch((match, builder) -> {
if (!pingedconsole) { if (!pingedconsole) {
System.out.print("\007"); System.out.print("\007");
pingedconsole = true; // Will set it to false in ProcessChat pingedconsole = true; // Will set it to false in ProcessChat
} }
return match; return match;
}).priority(Priority.High).build(), }).priority(Priority.High).build(),
ChatFormatter.builder().regex(HASHTAG_PATTERN).color(Color.Blue).openlink("https://twitter.com/hashtag/$1") ChatFormatter.builder().regex(HASHTAG_PATTERN).color(Color.Blue).openlink("https://twitter.com/hashtag/$1")
.priority(Priority.High).build(), .priority(Priority.High).build(),
ChatFormatter.builder().regex(CYAN_PATTERN).color(Color.Aqua).build(), // #55 ChatFormatter.builder().regex(CYAN_PATTERN).color(Color.Aqua).build(), // #55
ChatFormatter.builder().regex(CODE_PATTERN).color(Color.DarkGray).removeCharCount((short) 1).type(ChatFormatter.Type.Range) ChatFormatter.builder().regex(CODE_PATTERN).color(Color.DarkGray).removeCharCount((short) 1).type(ChatFormatter.Type.Range)
.build(), .build(),
ChatFormatter.builder().regex(MASKED_LINK_PATTERN).underlined(true).onmatch((match, builder) -> { ChatFormatter.builder().regex(MASKED_LINK_PATTERN).underlined(true).onmatch((match, builder) -> {
return match; // TODO! return match; // TODO!
}).build()); }).build());
private static Gson gson = new GsonBuilder() private static Gson gson = new GsonBuilder()
.registerTypeHierarchyAdapter(TellrawSerializableEnum.class, new TellrawSerializer.TwEnum()) .registerTypeHierarchyAdapter(TellrawSerializableEnum.class, new TellrawSerializer.TwEnum())
.registerTypeHierarchyAdapter(Collection.class, new TellrawSerializer.TwCollection()) .registerTypeHierarchyAdapter(Collection.class, new TellrawSerializer.TwCollection())
.registerTypeAdapter(Boolean.class, new TellrawSerializer.TwBool()) .registerTypeAdapter(Boolean.class, new TellrawSerializer.TwBool())
.registerTypeAdapter(boolean.class, new TellrawSerializer.TwBool()).disableHtmlEscaping().create(); .registerTypeAdapter(boolean.class, new TellrawSerializer.TwBool()).disableHtmlEscaping().create();
private static final String[] testPlayers = {"Koiiev", "iie", "Alisolarflare", "NorbiPeti", "Arsen_Derby_FTW", "carrot_lynx"}; private static final String[] testPlayers = {"Koiiev", "iie", "Alisolarflare", "NorbiPeti", "Arsen_Derby_FTW", "carrot_lynx"};
static final String MCORIGIN = "Minecraft"; //Shouldn't change, like ever - TBMCPlayer.getFolderForType(TBMCPlayer.class) capitalized static final String MCORIGIN = "Minecraft"; //Shouldn't change, like ever - TBMCPlayer.getFolderForType(TBMCPlayer.class) capitalized
private ChatProcessing() { private ChatProcessing() {
} }
public static boolean ProcessChat(TBMCChatEvent e) { public static boolean ProcessChat(TBMCChatEvent e) {
Channel channel = e.getChannel(); Channel channel = e.getChannel();
CommandSender sender = e.getSender(); CommandSender sender = e.getSender();
String message = e.getMessage(); String message = e.getMessage();
long processstart = System.nanoTime(); long processstart = System.nanoTime();
Player player = (sender instanceof Player ? (Player) sender : null); Player player = (sender instanceof Player ? (Player) sender : null);
User user = PluginMain.essentials.getUser(player); User user = PluginMain.essentials.getUser(player);
if (player != null) { if (player != null) {
user.updateActivity(true); //Could talk in a private channel, so broadcast user.updateActivity(true); //Could talk in a private channel, so broadcast
if (user.isMuted()) if (user.isMuted())
return true; return true;
} }
doFunStuff(sender, e, message); doFunStuff(sender, e, message);
ChatPlayer mp; ChatPlayer mp;
if (player != null) if (player != null)
mp = TBMCPlayerBase.getPlayer(player.getUniqueId(), ChatPlayer.class); mp = TBMCPlayerBase.getPlayer(player.getUniqueId(), ChatPlayer.class);
else //Due to the online player map, getPlayer() can be more efficient than getAs() else //Due to the online player map, getPlayer() can be more efficient than getAs()
mp = e.getUser().getAs(ChatPlayer.class); //May be null mp = e.getUser().getAs(ChatPlayer.class); //May be null
Color colormode = channel.color; Color colormode = channel.color;
if (mp != null && mp.OtherColorMode != null) if (mp != null && mp.OtherColorMode != null)
colormode = mp.OtherColorMode; colormode = mp.OtherColorMode;
if (message.startsWith(">")) if (message.startsWith(">"))
colormode = Color.Green; colormode = Color.Green;
// If greentext, ignore channel or player colors // If greentext, ignore channel or player colors
ArrayList<ChatFormatter> formatters = addFormatters(colormode); ArrayList<ChatFormatter> formatters = addFormatters(colormode);
if (colormode == channel.color && mp != null && mp.RainbowPresserColorMode) { // Only overwrite channel color if (colormode == channel.color && mp != null && mp.RainbowPresserColorMode) { // Only overwrite channel color
final AtomicInteger rpc = new AtomicInteger(0); final AtomicInteger rpc = new AtomicInteger(0);
formatters.add(ChatFormatter.builder().color(colormode).onmatch((match, cf) -> { formatters.add(ChatFormatter.builder().color(colormode).onmatch((match, cf) -> {
cf.setColor(RainbowPresserColors[rpc.getAndUpdate(i -> ++i < RainbowPresserColors.length ? i : 0)]); cf.setColor(RainbowPresserColors[rpc.getAndUpdate(i -> ++i < RainbowPresserColors.length ? i : 0)]);
return match; return match;
}).build()); }).build());
} }
pingedconsole = false; // Will set it to true onmatch (static constructor) pingedconsole = false; // Will set it to true onmatch (static constructor)
final String channelidentifier = getChannelID(channel, sender, e.getOrigin()); final String channelidentifier = getChannelID(channel, sender, e.getOrigin());
TellrawPart json = createTellraw(sender, message, player, mp, e.getUser(), channelidentifier, e.getOrigin()); TellrawPart json = createTellraw(sender, message, player, mp, e.getUser(), channelidentifier, e.getOrigin());
long combinetime = System.nanoTime(); long combinetime = System.nanoTime();
ChatFormatter.Combine(formatters, message, json); ChatFormatter.Combine(formatters, message, json);
combinetime = System.nanoTime() - combinetime; combinetime = System.nanoTime() - combinetime;
String jsonstr = toJson(json); String jsonstr = toJson(json);
if (jsonstr.length() >= 32767) { if (jsonstr.length() >= 32767) {
sender.sendMessage( sender.sendMessage(
"§cError: Message too long. Try shortening it, or remove hashtags and other formatting."); "§cError: Message too long. Try shortening it, or remove hashtags and other formatting.");
return true; return true;
} }
DebugCommand.SendDebugMessage(jsonstr); DebugCommand.SendDebugMessage(jsonstr);
try { try {
if (!channel.isGlobal()) { if (!channel.isGlobal()) {
Objective obj = PluginMain.SB.getObjective(channel.ID); Objective obj = PluginMain.SB.getObjective(channel.ID);
int score = -1; int score = -1;
for (Player p : Bukkit.getOnlinePlayers()) { for (Player p : Bukkit.getOnlinePlayers()) {
final int mcScore; final int mcScore;
if (player != null if (player != null
&& PluginMain.essentials.getUser(p).isIgnoredPlayer(PluginMain.essentials.getUser(player))) && PluginMain.essentials.getUser(p).isIgnoredPlayer(PluginMain.essentials.getUser(player)))
mcScore = -1; // Don't send the message to them mcScore = -1; // Don't send the message to them
else else
mcScore = VanillaUtils.getMCScoreIfChatOn(p, e); mcScore = VanillaUtils.getMCScoreIfChatOn(p, e);
obj.getScore(p.getName()) obj.getScore(p.getName())
.setScore(p.getUniqueId().equals(player == null ? null : player.getUniqueId()) // p.UniqueID==player?.UniqueID .setScore(p.getUniqueId().equals(player == null ? null : player.getUniqueId()) // p.UniqueID==player?.UniqueID
? score = mcScore : mcScore); ? score = mcScore : mcScore);
} }
if (score == -1) // Even if the player object isn't null, it may not be in OnlinePlayers if (score == -1) // Even if the player object isn't null, it may not be in OnlinePlayers
score = e.getMCScore(sender); score = e.getMCScore(sender);
if (score < 0) // Never send messages to score below 0 if (score < 0) // Never send messages to score below 0
sender.sendMessage("§cYou don't have permission to send this message or something went wrong"); sender.sendMessage("§cYou don't have permission to send this message or something went wrong");
else { else {
PluginMain.Instance.getServer().dispatchCommand(PluginMain.Console, PluginMain.Instance.getServer().dispatchCommand(PluginMain.Console,
String.format("tellraw @a[score_%s=%d,score_%s_min=%d] %s", channel.ID, score, channel.ID, String.format("tellraw @a[score_%s=%d,score_%s_min=%d] %s", channel.ID, score, channel.ID,
score, jsonstr)); score, jsonstr));
if (e.getChannel().ID.equals(PluginMain.TownChat.ID) if (e.getChannel().ID.equals(PluginMain.TownChat.ID)
|| e.getChannel().ID.equals(PluginMain.NationChat.ID)) { || e.getChannel().ID.equals(PluginMain.NationChat.ID)) {
((List<TellrawPart>) json.getExtra()).add(0, new TellrawPart("[SPY]")); ((List<TellrawPart>) json.getExtra()).add(0, new TellrawPart("[SPY]"));
jsonstr = toJson(json); jsonstr = toJson(json);
Bukkit.getServer().dispatchCommand(PluginMain.Console, String.format( Bukkit.getServer().dispatchCommand(PluginMain.Console, String.format(
"tellraw @a[score_%s=1000,score_%s_min=1000] %s", channel.ID, channel.ID, jsonstr)); "tellraw @a[score_%s=1000,score_%s_min=1000] %s", channel.ID, channel.ID, jsonstr));
} }
} }
} else } else
PluginMain.Instance.getServer().dispatchCommand(PluginMain.Console, PluginMain.Instance.getServer().dispatchCommand(PluginMain.Console,
String.format("tellraw @a %s", jsonstr)); String.format("tellraw @a %s", jsonstr));
} catch (Exception ex) { } catch (Exception ex) {
TBMCCoreAPI.SendException("An error occured while sending a chat message!", ex); TBMCCoreAPI.SendException("An error occured while sending a chat message!", ex);
sender.sendMessage("§cAn error occured while sending the message."); sender.sendMessage("§cAn error occured while sending the message.");
return true; return true;
} }
PluginMain.Instance.getServer().getConsoleSender() PluginMain.Instance.getServer().getConsoleSender()
.sendMessage(String.format("%s <%s§r> %s", channelidentifier, getSenderName(sender, player), message)); .sendMessage(String.format("%s <%s§r> %s", channelidentifier, getSenderName(sender, player), message));
DebugCommand.SendDebugMessage( DebugCommand.SendDebugMessage(
"-- Full ChatProcessing time: " + (System.nanoTime() - processstart) / 1000000f + " ms"); "-- Full ChatProcessing time: " + (System.nanoTime() - processstart) / 1000000f + " ms");
DebugCommand.SendDebugMessage("-- ChatFormatter.Combine time: " + combinetime / 1000000f + " ms"); DebugCommand.SendDebugMessage("-- ChatFormatter.Combine time: " + combinetime / 1000000f + " ms");
return false; return false;
} }
static String toJson(TellrawPart json) { static String toJson(TellrawPart json) {
return gson.toJson(json); return gson.toJson(json);
} }
static TellrawPart createTellraw(CommandSender sender, String message, @Nullable Player player, static TellrawPart createTellraw(CommandSender sender, String message, @Nullable Player player,
@Nullable ChatPlayer mp, @Nullable ChromaGamerBase cg, final String channelidentifier, @Nullable ChatPlayer mp, @Nullable ChromaGamerBase cg, final String channelidentifier,
String origin) { String origin) {
TellrawPart json = new TellrawPart(""); TellrawPart json = new TellrawPart("");
if (mp != null && mp.ChatOnly) { if (mp != null && mp.ChatOnly) {
json.addExtra(new TellrawPart("[C]") json.addExtra(new TellrawPart("[C]")
.setHoverEvent(TellrawEvent.create(TellrawEvent.HoverAction.SHOW_TEXT, "Chat only"))); .setHoverEvent(TellrawEvent.create(TellrawEvent.HoverAction.SHOW_TEXT, "Chat only")));
} }
json.addExtra( json.addExtra(
new TellrawPart(channelidentifier) new TellrawPart(channelidentifier)
.setHoverEvent( .setHoverEvent(
TellrawEvent.create(TellrawEvent.HoverAction.SHOW_TEXT, TellrawEvent.create(TellrawEvent.HoverAction.SHOW_TEXT,
new TellrawPart((MCORIGIN.equals(origin) ? "" : "From " + origin + "n") new TellrawPart((MCORIGIN.equals(origin) ? "" : "From " + origin + "n")
+ "Copy message").setColor(Color.Blue))) + "Copy message").setColor(Color.Blue)))
.setClickEvent(TellrawEvent.create(TellrawEvent.ClickAction.SUGGEST_COMMAND, message))); .setClickEvent(TellrawEvent.create(TellrawEvent.ClickAction.SUGGEST_COMMAND, message)));
if (PluginMain.permission.has(sender, "tbmc.badge.diamond")) if (PluginMain.permission.has(sender, "tbmc.badge.diamond"))
json.addExtra(new TellrawPart("[P]").setColor(Color.Aqua).setBold(true) json.addExtra(new TellrawPart("[P]").setColor(Color.Aqua).setBold(true)
.setHoverEvent(TellrawEvent.create(TellrawEvent.HoverAction.SHOW_TEXT, "Diamond Patreon supporter"))); .setHoverEvent(TellrawEvent.create(TellrawEvent.HoverAction.SHOW_TEXT, "Diamond Patreon supporter")));
else if (PluginMain.permission.has(sender, "tbmc.badge.gold")) else if (PluginMain.permission.has(sender, "tbmc.badge.gold"))
json.addExtra(new TellrawPart("[P]").setColor(Color.Gold).setBold(true) json.addExtra(new TellrawPart("[P]").setColor(Color.Gold).setBold(true)
.setHoverEvent(TellrawEvent.create(TellrawEvent.HoverAction.SHOW_TEXT, "Gold Patreon supporter"))); .setHoverEvent(TellrawEvent.create(TellrawEvent.HoverAction.SHOW_TEXT, "Gold Patreon supporter")));
json.addExtra(new TellrawPart(" <")); json.addExtra(new TellrawPart(" <"));
TellrawPart hovertp = new TellrawPart(""); TellrawPart hovertp = new TellrawPart("");
if (cg != null) if (cg != null)
hovertp.addExtra(new TellrawPart(cg.getInfo(ChromaGamerBase.InfoTarget.MCHover))); hovertp.addExtra(new TellrawPart(cg.getInfo(ChromaGamerBase.InfoTarget.MCHover)));
json.addExtra(new TellrawPart(getSenderName(sender, player)) json.addExtra(new TellrawPart(getSenderName(sender, player))
.setHoverEvent(TellrawEvent.create(TellrawEvent.HoverAction.SHOW_TEXT, hovertp))); .setHoverEvent(TellrawEvent.create(TellrawEvent.HoverAction.SHOW_TEXT, hovertp)));
json.addExtra(new TellrawPart("> ")); json.addExtra(new TellrawPart("> "));
return json; return json;
} }
private static String getSenderName(CommandSender sender, Player player) { private static String getSenderName(CommandSender sender, Player player) {
if (player == null) if (player == null)
return sender.getName(); return sender.getName();
return player.getDisplayName(); return player.getDisplayName();
} }
static String getChannelID(Channel channel, CommandSender sender, String origin) { static String getChannelID(Channel channel, CommandSender sender, String origin) {
return ("[" + (MCORIGIN.equals(origin) ? "" : "§8" + origin.substring(0, 1) + "§r|") + channel.DisplayName) return ("[" + (MCORIGIN.equals(origin) ? "" : "§8" + origin.substring(0, 1) + "§r|") + channel.DisplayName)
+ "]"; + "]";
} }
static ArrayList<ChatFormatter> addFormatters(Color colormode) { static ArrayList<ChatFormatter> addFormatters(Color colormode) {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
ArrayList<ChatFormatter> formatters = (ArrayList<ChatFormatter>) commonFormatters.clone(); ArrayList<ChatFormatter> formatters = (ArrayList<ChatFormatter>) commonFormatters.clone();
formatters.add( formatters.add(
ChatFormatter.builder().regex(ENTIRE_MESSAGE_PATTERN).color(colormode).priority(Priority.Low).build()); ChatFormatter.builder().regex(ENTIRE_MESSAGE_PATTERN).color(colormode).priority(Priority.Low).build());
boolean nottest; //Not assigning a default value, so that it can only be used in the if boolean nottest; //Not assigning a default value, so that it can only be used in the if
if ((nottest = Bukkit.getOnlinePlayers().size() > 0) || Bukkit.getVersion().equals("test")) { if ((nottest = Bukkit.getOnlinePlayers().size() > 0) || Bukkit.getVersion().equals("test")) {
StringBuilder namesb = new StringBuilder("(?i)("); StringBuilder namesb = new StringBuilder("(?i)(");
if (nottest) if (nottest)
for (Player p : Bukkit.getOnlinePlayers()) for (Player p : Bukkit.getOnlinePlayers())
namesb.append(p.getName()).append("|"); namesb.append(p.getName()).append("|");
else else
for (String testPlayer : testPlayers) for (String testPlayer : testPlayers)
namesb.append(testPlayer).append("|"); namesb.append(testPlayer).append("|");
namesb.deleteCharAt(namesb.length() - 1); namesb.deleteCharAt(namesb.length() - 1);
namesb.append(")"); namesb.append(")");
StringBuilder nicksb = new StringBuilder("(?i)("); StringBuilder nicksb = new StringBuilder("(?i)(");
boolean addNickFormatter = false; boolean addNickFormatter = false;
final int size = Bukkit.getOnlinePlayers().size(); int index = 0;
int index = 0; for (Player p : Bukkit.getOnlinePlayers()) {
for (Player p : Bukkit.getOnlinePlayers()) { final String nick = PlayerListener.nicknames.inverse().get(p.getUniqueId());
final String nick = PlayerListener.nicknames.inverse().get(p.getUniqueId()); if (nick != null) {
if (nick != null) { nicksb.append(nick).append("|");
nicksb.append(nick); addNickFormatter = true; //Add it even if there's only 1 player online (it was in the if)
if (index < size - 1) }
nicksb.append("|"); index++;
addNickFormatter = true; //Add it even if there's only 1 player online (it was in the if) }
} nicksb.deleteCharAt(nicksb.length() - 1);
index++; nicksb.append(")");
}
nicksb.append(")"); Consumer<String> error = message -> {
if (PluginMain.Instance != null)
Consumer<String> error = message -> { PluginMain.Instance.getLogger().warning(message);
if (PluginMain.Instance != null) else
PluginMain.Instance.getLogger().warning(message); System.out.println(message);
else };
System.out.println(message);
}; formatters.add(ChatFormatter.builder().regex(Pattern.compile(namesb.toString())).color(Color.Aqua)
.onmatch((match, builder) -> {
formatters.add(ChatFormatter.builder().regex(Pattern.compile(namesb.toString())).color(Color.Aqua) Player p = Bukkit.getPlayer(match);
.onmatch((match, builder) -> { Optional<String> pn = nottest ? Optional.empty()
Player p = Bukkit.getPlayer(match); : Arrays.stream(testPlayers).filter(tp -> tp.equalsIgnoreCase(match)).findAny();
Optional<String> pn = nottest ? Optional.empty() if (nottest ? p == null : !pn.isPresent()) {
: Arrays.stream(testPlayers).filter(tp -> tp.equalsIgnoreCase(match)).findAny(); error.accept("Error: Can't find player " + match + " but was reported as online.");
if (nottest ? p == null : !pn.isPresent()) { return "§c" + match + "§r";
error.accept("Error: Can't find player " + match + " but was reported as online."); }
return "§c" + match + "§r"; ChatPlayer mpp = TBMCPlayer.getPlayer(nottest ? p.getUniqueId() : new UUID(0, 0), ChatPlayer.class);
} if (nottest) {
ChatPlayer mpp = TBMCPlayer.getPlayer(nottest ? p.getUniqueId() : new UUID(0, 0), ChatPlayer.class); if (PlayerListener.NotificationSound == null)
if (nottest) { p.playSound(p.getLocation(), Sound.ENTITY_ARROW_HIT_PLAYER, 1.0f, 0.5f); // TODO: Airhorn
if (PlayerListener.NotificationSound == null) else
p.playSound(p.getLocation(), Sound.ENTITY_ARROW_HIT_PLAYER, 1.0f, 0.5f); // TODO: Airhorn p.playSound(p.getLocation(), PlayerListener.NotificationSound, 1.0f,
else (float) PlayerListener.NotificationPitch);
p.playSound(p.getLocation(), PlayerListener.NotificationSound, 1.0f, }
(float) PlayerListener.NotificationPitch); String color = String.format("§%x", (mpp.GetFlairColor() == 0x00 ? 0xb : mpp.GetFlairColor()));
} return color + (nottest ? p.getName() : pn.get()) + "§r"; //Fix name casing, except when testing
String color = String.format("§%x", (mpp.GetFlairColor() == 0x00 ? 0xb : mpp.GetFlairColor())); }).priority(Priority.High).type(ChatFormatter.Type.Excluder).build());
return color + (nottest ? p.getName() : pn.get()) + "§r"; //Fix name casing, except when testing
}).priority(Priority.High).type(ChatFormatter.Type.Excluder).build()); if (addNickFormatter)
formatters.add(ChatFormatter.builder().regex((Pattern.compile(nicksb.toString()))).color(Color.Aqua)
if (addNickFormatter) .onmatch((match, builder) -> {
formatters.add(ChatFormatter.builder().regex((Pattern.compile(nicksb.toString()))).color(Color.Aqua) if (PlayerListener.nicknames.containsKey(match.toLowerCase())) { //Made a stream and all that but I can actually store it lowercased
.onmatch((match, builder) -> { Player p = Bukkit.getPlayer(PlayerListener.nicknames.get(match.toLowerCase()));
if (PlayerListener.nicknames.containsKey(match.toLowerCase())) { //Made a stream and all that but I can actually store it lowercased if (p == null) {
Player p = Bukkit.getPlayer(PlayerListener.nicknames.get(match.toLowerCase())); error.accept("Error: Can't find player nicknamed "
if (p == null) { + match.toLowerCase() + " but was reported as online.");
error.accept("Error: Can't find player nicknamed " return "§c" + match + "§r";
+ match.toLowerCase() + " but was reported as online."); }
return "§c" + match + "§r"; if (PlayerListener.NotificationSound == null)
} p.playSound(p.getLocation(), Sound.ENTITY_ARROW_HIT_PLAYER, 1.0f, 0.5f);
if (PlayerListener.NotificationSound == null) else
p.playSound(p.getLocation(), Sound.ENTITY_ARROW_HIT_PLAYER, 1.0f, 0.5f); p.playSound(p.getLocation(), PlayerListener.NotificationSound, 1.0f,
else (float) PlayerListener.NotificationPitch);
p.playSound(p.getLocation(), PlayerListener.NotificationSound, 1.0f, return PluginMain.essentials.getUser(p).getNickname();
(float) PlayerListener.NotificationPitch); }
return PluginMain.essentials.getUser(p).getNickname(); error.accept("Player nicknamed " + match.toLowerCase()
} + " not found in nickname map but was reported as online.");
error.accept("Player nicknamed " + match.toLowerCase() return "§c" + match + "§r";
+ " not found in nickname map but was reported as online."); }).priority(Priority.High).type(ChatFormatter.Type.Excluder).build());
return "§c" + match + "§r"; }
}).priority(Priority.High).type(ChatFormatter.Type.Excluder).build()); return formatters;
} }
return formatters;
} static void doFunStuff(CommandSender sender, TBMCChatEventBase event, String message) {
if (PlayerListener.ActiveF && !PlayerListener.Fs.contains(sender) && message.equalsIgnoreCase("F"))
static void doFunStuff(CommandSender sender, TBMCChatEventBase event, String message) { PlayerListener.Fs.add(sender);
if (PlayerListener.ActiveF && !PlayerListener.Fs.contains(sender) && message.equalsIgnoreCase("F"))
PlayerListener.Fs.add(sender); String msg = message.toLowerCase();
val lld = new UnlolCommand.LastlolData(sender, event, System.nanoTime());
String msg = message.toLowerCase(); boolean add;
val lld = new UnlolCommand.LastlolData(sender, event, System.nanoTime()); if (add = msg.contains("lol"))
boolean add; lld.setLolornot(true);
if (add = msg.contains("lol")) else {
lld.setLolornot(true); for (int i = 0; i < PlayerListener.LaughStrings.length; i++) {
else { if (add = msg.contains(PlayerListener.LaughStrings[i])) {
for (int i = 0; i < PlayerListener.LaughStrings.length; i++) { lld.setLolornot(false);
if (add = msg.contains(PlayerListener.LaughStrings[i])) { break;
lld.setLolornot(false); }
break; }
} }
} if (add)
} UnlolCommand.Lastlol.put(event.getChannel(), lld);
if (add) }
UnlolCommand.Lastlol.put(event.getChannel(), lld); }
}
}