Clean up message sanitization and properly strip section signs from nicks/messages

This commit is contained in:
Allink 2022-05-25 17:15:04 +01:00
parent dfd90af017
commit 0fc5b01b29
No known key found for this signature in database
GPG Key ID: 7F1F1B98F0FAAD13
4 changed files with 80 additions and 61 deletions

View File

@ -45,7 +45,7 @@ public class Command_vanish extends FreedomCommand
msg("You have unvanished.", ChatColor.GOLD); msg("You have unvanished.", ChatColor.GOLD);
FUtil.bcastMsg(plugin.rm.craftLoginMessage(playerSender, null)); FUtil.bcastMsg(plugin.rm.craftLoginMessage(playerSender, null));
FUtil.bcastMsg(playerSender.getName() + " joined the game.", ChatColor.YELLOW); FUtil.bcastMsg(playerSender.getName() + " joined the game.", ChatColor.YELLOW);
plugin.dc.messageChatChannel("**" + playerSender.getName() + " joined the server" + "**"); plugin.dc.messageChatChannel("**" + playerSender.getName() + " joined the server" + "**", true);
} }
PlayerData playerData = plugin.pl.getData(playerSender); PlayerData playerData = plugin.pl.getData(playerSender);
@ -91,7 +91,7 @@ public class Command_vanish extends FreedomCommand
{ {
msg("You have vanished.", ChatColor.GOLD); msg("You have vanished.", ChatColor.GOLD);
FUtil.bcastMsg(playerSender.getName() + " left the game.", ChatColor.YELLOW); FUtil.bcastMsg(playerSender.getName() + " left the game.", ChatColor.YELLOW);
plugin.dc.messageChatChannel("**" + playerSender.getName() + " left the server" + "**"); plugin.dc.messageChatChannel("**" + playerSender.getName() + " left the server" + "**", true);
} }
FLog.info(playerSender.getName() + " is now vanished."); FLog.info(playerSender.getName() + " is now vanished.");

View File

@ -13,6 +13,8 @@ import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import javax.security.auth.login.LoginException; import javax.security.auth.login.LoginException;
import com.google.common.collect.ImmutableList;
import me.totalfreedom.totalfreedommod.FreedomService; import me.totalfreedom.totalfreedommod.FreedomService;
import me.totalfreedom.totalfreedommod.admin.Admin; import me.totalfreedom.totalfreedommod.admin.Admin;
import me.totalfreedom.totalfreedommod.config.ConfigEntry; import me.totalfreedom.totalfreedommod.config.ConfigEntry;
@ -37,8 +39,12 @@ import net.dv8tion.jda.api.requests.GatewayIntent;
import net.dv8tion.jda.api.utils.ChunkingFilter; import net.dv8tion.jda.api.utils.ChunkingFilter;
import net.dv8tion.jda.api.utils.MemberCachePolicy; import net.dv8tion.jda.api.utils.MemberCachePolicy;
import net.dv8tion.jda.internal.utils.concurrent.CountingThreadFactory; import net.dv8tion.jda.internal.utils.concurrent.CountingThreadFactory;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils; import org.apache.commons.lang.WordUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.bukkit.GameRule; import org.bukkit.GameRule;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
@ -56,6 +62,7 @@ public class Discord extends FreedomService
public ScheduledThreadPoolExecutor RATELIMIT_EXECUTOR; public ScheduledThreadPoolExecutor RATELIMIT_EXECUTOR;
public List<CompletableFuture<Message>> sentMessages = new ArrayList<>(); public List<CompletableFuture<Message>> sentMessages = new ArrayList<>();
public Boolean enabled = false; public Boolean enabled = false;
private final ImmutableList<String> DISCORD_SUBDOMAINS = ImmutableList.of("discordapp.com", "discord.com", "discord.gg");
private final Pattern DISCORD_MENTION_PATTERN = Pattern.compile("(<@!?([0-9]{16,20})>)"); private final Pattern DISCORD_MENTION_PATTERN = Pattern.compile("(<@!?([0-9]{16,20})>)");
public static String getCode(PlayerData playerData) public static String getCode(PlayerData playerData)
@ -215,7 +222,7 @@ public class Discord extends FreedomService
} }
} }
sentMessages.clear(); sentMessages.clear();
messageChatChannel("**Message queue cleared**"); messageChatChannel("**Message queue cleared**", true);
} }
public void sendPteroInfo(PlayerData playerData, String username, String password) public void sendPteroInfo(PlayerData playerData, String username, String password)
@ -246,13 +253,7 @@ public class Discord extends FreedomService
public String generateCode(int size) public String generateCode(int size)
{ {
StringBuilder code = new StringBuilder(); return RandomStringUtils.randomNumeric(size);
SplittableRandom random = new SplittableRandom();
for (int i = 0; i < size; i++)
{
code.append(random.nextInt(10));
}
return code.toString();
} }
@EventHandler(priority = EventPriority.MONITOR) @EventHandler(priority = EventPriority.MONITOR)
@ -265,9 +266,11 @@ public class Discord extends FreedomService
return; return;
} }
if (event.getDeathMessage() != null) Component deathMessage = event.deathMessage();
if (deathMessage != null)
{ {
messageChatChannel("**" + event.getDeathMessage() + "**"); messageChatChannel("**" + PlainTextComponentSerializer.plainText().serialize(deathMessage) + "**", true);
} }
} }
@ -282,7 +285,7 @@ public class Discord extends FreedomService
{ {
if (!plugin.al.isVanished(event.getPlayer().getName())) if (!plugin.al.isVanished(event.getPlayer().getName()))
{ {
messageChatChannel("**" + event.getPlayer().getName() + " joined the server" + "**"); messageChatChannel("**" + event.getPlayer().getName() + " joined the server" + "**", true);
} }
} }
@ -291,69 +294,78 @@ public class Discord extends FreedomService
{ {
if (!plugin.al.isVanished(event.getPlayer().getName())) if (!plugin.al.isVanished(event.getPlayer().getName()))
{ {
messageChatChannel("**" + event.getPlayer().getName() + " left the server" + "**"); messageChatChannel("**" + event.getPlayer().getName() + " left the server" + "**", true);
} }
} }
public void messageChatChannel(String message) public String sanitizeChatMessage(String message)
{ {
String chat_channel_id = ConfigEntry.DISCORD_CHAT_CHANNEL_ID.getString(); String newMessage = message;
if (message.contains("@everyone") || message.contains("@here"))
if (message.contains("@"))
{ {
message = StringUtils.remove(message, "@"); // \u200B is Zero Width Space, invisible on Discord
newMessage = message.replaceAll("@", "@\u200B");
} }
if (message.toLowerCase().contains("discord.gg")) if (message.toLowerCase().contains("discord.gg")) // discord.gg/invite works as an invite
{ {
return; return "";
}
for (String subdomain : DISCORD_SUBDOMAINS)
{
if (message.toLowerCase().contains(subdomain + "/invite"))
{
return "";
}
} }
if (message.contains("§")) if (message.contains("§"))
{ {
message = StringUtils.remove(message, "§"); newMessage = message.replaceAll("§", "");
} }
return deformat(newMessage);
}
Matcher DISCORD_MENTION_MATCHER = DISCORD_MENTION_PATTERN.matcher(message); public void messageChatChannel(String message)
while (DISCORD_MENTION_MATCHER.find())
{ {
String mention = DISCORD_MENTION_MATCHER.group(1); messageChatChannel(message, false);
message = message.replace(mention, mention.replace("@",""));
} }
public void messageChatChannel(String message, boolean system)
{
String chat_channel_id = ConfigEntry.DISCORD_CHAT_CHANNEL_ID.getString();
String sanitizedMessage = (system) ? message : sanitizeChatMessage(message);
if (sanitizedMessage.isBlank()) return;
if (enabled && !chat_channel_id.isEmpty()) if (enabled && !chat_channel_id.isEmpty())
{ {
CompletableFuture<Message> sentMessage = Objects.requireNonNull(bot.getTextChannelById(chat_channel_id)).sendMessage(deformat(message)).submit(true); CompletableFuture<Message> sentMessage = Objects.requireNonNull(bot.getTextChannelById(chat_channel_id)).sendMessage(sanitizedMessage).submit(true);
sentMessages.add(sentMessage); sentMessages.add(sentMessage);
} }
} }
public void messageAdminChatChannel(String message) public void messageAdminChatChannel(String message)
{
messageAdminChatChannel(message, false);
}
public void messageAdminChatChannel(String message, boolean system)
{ {
String chat_channel_id = ConfigEntry.DISCORD_ADMINCHAT_CHANNEL_ID.getString(); String chat_channel_id = ConfigEntry.DISCORD_ADMINCHAT_CHANNEL_ID.getString();
if (message.contains("@everyone") || message.contains("@here"))
String sanitizedMessage = sanitizeChatMessage(message);
if (sanitizedMessage.isBlank()) return;
if (enabled && !chat_channel_id.isEmpty())
{ {
message = StringUtils.remove(message, "@"); CompletableFuture<Message> sentMessage = Objects.requireNonNull(bot.getTextChannelById(chat_channel_id)).sendMessage(sanitizedMessage).submit(true);
} sentMessages.add(sentMessage);
if (message.toLowerCase().contains("discord.gg"))
{
return;
}
if (message.contains("§"))
{
message = StringUtils.remove(message, "§");
}
Matcher DISCORD_MENTION_MATCHER = DISCORD_MENTION_PATTERN.matcher(message);
while (DISCORD_MENTION_MATCHER.find())
{
String mention = DISCORD_MENTION_MATCHER.group(1);
message = message.replace(mention, mention.replace("@",""));
} }
if (enabled && !chat_channel_id.isEmpty()) if (enabled && !chat_channel_id.isEmpty())
@ -366,7 +378,7 @@ public class Discord extends FreedomService
public String formatBotTag() public String formatBotTag()
{ {
SelfUser user = bot.getSelfUser(); SelfUser user = bot.getSelfUser();
return user.getName() + "#" + user.getDiscriminator(); return user.getAsTag();
} }
@Override @Override
@ -374,7 +386,7 @@ public class Discord extends FreedomService
{ {
if (bot != null) if (bot != null)
{ {
messageChatChannel("**Server has stopped**"); messageChatChannel("**Server has stopped**", true);
} }
FLog.info("Discord integration has successfully shutdown."); FLog.info("Discord integration has successfully shutdown.");
@ -382,7 +394,7 @@ public class Discord extends FreedomService
public String deformat(String input) public String deformat(String input)
{ {
return input.replace("_", "\\_"); return input.replaceAll("([_\\\\`*>|])", "\\\\$1");
} }
public boolean sendReport(Player reporter, Player reported, String reason) public boolean sendReport(Player reporter, Player reported, String reason)
@ -400,6 +412,7 @@ public class Discord extends FreedomService
Guild server = bot.getGuildById(ConfigEntry.DISCORD_SERVER_ID.getString()); Guild server = bot.getGuildById(ConfigEntry.DISCORD_SERVER_ID.getString());
if (server == null) if (server == null)
{ {
FLog.severe("The Discord server ID specified is invalid, or the bot is not on the server."); FLog.severe("The Discord server ID specified is invalid, or the bot is not on the server.");
return false; return false;
@ -436,7 +449,7 @@ public class Discord extends FreedomService
{ {
public void start() public void start()
{ {
messageChatChannel("**Server has started**"); messageChatChannel("**Server has started**", true);
} }
} }
} }

View File

@ -5,6 +5,7 @@ import me.totalfreedom.totalfreedommod.config.ConfigEntry;
import me.totalfreedom.totalfreedommod.rank.Rank; import me.totalfreedom.totalfreedommod.rank.Rank;
import me.totalfreedom.totalfreedommod.rank.Title; import me.totalfreedom.totalfreedommod.rank.Title;
import me.totalfreedom.totalfreedommod.util.FLog; import me.totalfreedom.totalfreedommod.util.FLog;
import me.totalfreedom.totalfreedommod.util.FUtil;
import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.entities.Message;
@ -55,13 +56,13 @@ public class DiscordToMinecraftListener extends ListenerAdapter
emsg.append(" "); emsg.append(" ");
// User // User
TextComponent user = new TextComponent(ChatColor.stripColor(member.getEffectiveName())); TextComponent user = new TextComponent(FUtil.stripColors(member.getEffectiveName()));
user.setColor(ChatColor.RED.asBungee()); user.setColor(ChatColor.RED.asBungee());
emsg.append(user); emsg.append(user);
// Message // Message
emsg.append(ChatColor.DARK_GRAY + ": " + ChatColor.RESET emsg.append(ChatColor.DARK_GRAY + ": " + ChatColor.RESET
+ ChatColor.stripColor(msg.getContentDisplay()), ComponentBuilder.FormatRetention.NONE); + FUtil.stripColors(msg.getContentDisplay()), ComponentBuilder.FormatRetention.NONE);
// Attachments // Attachments
if (!msg.getAttachments().isEmpty()) if (!msg.getAttachments().isEmpty())
@ -86,7 +87,7 @@ public class DiscordToMinecraftListener extends ListenerAdapter
{ {
if (TotalFreedomMod.getPlugin().pl.getData(player).doesDisplayDiscord()) if (TotalFreedomMod.getPlugin().pl.getData(player).doesDisplayDiscord())
{ {
player.spigot().sendMessage(components); player.sendMessage(components);
} }
} }

View File

@ -550,6 +550,11 @@ public class FUtil
return string; return string;
} }
public static String stripColors(String string)
{
return string.replaceAll("§", "");
}
public static Date getUnixDate(long unix) public static Date getUnixDate(long unix)
{ {
return new Date(unix); return new Date(unix);