This commit is contained in:
len 2021-06-13 13:53:49 +02:00
parent bfadd18020
commit a5c23d842d
24 changed files with 139 additions and 166 deletions

1
.gitignore vendored
View File

@ -4,6 +4,7 @@
testserver testserver
run run
galaxy galaxy
notes
# Compiled class file # Compiled class file
*.class *.class

View File

@ -3,8 +3,6 @@ package com.alttd.chat;
import com.alttd.chat.database.DatabaseConnection; import com.alttd.chat.database.DatabaseConnection;
import net.luckperms.api.LuckPerms; import net.luckperms.api.LuckPerms;
import java.util.UUID;
public interface ChatAPI { public interface ChatAPI {
static ChatAPI get() { static ChatAPI get() {

View File

@ -20,8 +20,8 @@ public class ChatImplementation implements ChatAPI{
Config.init(); Config.init();
luckPerms = getLuckPerms(); luckPerms = getLuckPerms();
databaseConnection = getDataBase(); //databaseConnection = getDataBase(); // todo fix sql
Queries.createTables(); //Queries.createTables(); // todo fix sql
ChatUserManager.initialize(); // loads all the users from the db and adds them. ChatUserManager.initialize(); // loads all the users from the db and adds them.
RegexManager.initialize(); // load the filters and regexes from config RegexManager.initialize(); // load the filters and regexes from config

View File

@ -17,6 +17,7 @@ import java.lang.reflect.Modifier;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.UUID;
import java.util.regex.Pattern; import java.util.regex.Pattern;
public final class Config { public final class Config {
@ -162,12 +163,14 @@ public final class Config {
public static List<String> STAFFGROUPS = new ArrayList<>(); public static List<String> STAFFGROUPS = new ArrayList<>();
public static String MINIMIUMSTAFFRANK = "trainee"; public static String MINIMIUMSTAFFRANK = "trainee";
public static String CONSOLENAME = "Console"; public static String CONSOLENAME = "Console";
public static UUID CONSOLEUUID = UUID.randomUUID();
private static void settings() { private static void settings() {
PREFIXGROUPS = getList("settings.prefix-groups", PREFIXGROUPS = getList("settings.prefix-groups",
Lists.newArrayList("discord", "socialmedia", "eventteam", "eventleader", "youtube", "twitch", "developer")); Lists.newArrayList("discord", "socialmedia", "eventteam", "eventleader", "youtube", "twitch", "developer"));
STAFFGROUPS = getList("settings.staff-groups", STAFFGROUPS = getList("settings.staff-groups",
Lists.newArrayList("trainee", "moderator", "headmod", "admin", "manager", "owner")); Lists.newArrayList("trainee", "moderator", "headmod", "admin", "manager", "owner"));
CONSOLENAME = getString("settings.console-name", CONSOLENAME); CONSOLENAME = getString("settings.console-name", CONSOLENAME);
CONSOLEUUID = UUID.fromString(getString("settings.console-uuid", CONSOLEUUID.toString()));
MINIMIUMSTAFFRANK = getString("settings.minimum-staff-rank", MINIMIUMSTAFFRANK); MINIMIUMSTAFFRANK = getString("settings.minimum-staff-rank", MINIMIUMSTAFFRANK);
} }

View File

@ -2,11 +2,11 @@ package com.alttd.chat.config;
import com.alttd.chat.managers.RegexManager; import com.alttd.chat.managers.RegexManager;
import com.alttd.chat.objects.ChatFilter; import com.alttd.chat.objects.ChatFilter;
import com.alttd.chat.util.ALogger;
import com.google.common.base.Throwables; import com.google.common.base.Throwables;
import com.google.common.reflect.TypeToken; import com.google.common.reflect.TypeToken;
import ninja.leaping.configurate.ConfigurationNode; import ninja.leaping.configurate.ConfigurationNode;
import ninja.leaping.configurate.ConfigurationOptions; import ninja.leaping.configurate.ConfigurationOptions;
import ninja.leaping.configurate.commented.CommentedConfigurationNode;
import ninja.leaping.configurate.objectmapping.ObjectMappingException; import ninja.leaping.configurate.objectmapping.ObjectMappingException;
import ninja.leaping.configurate.yaml.YAMLConfigurationLoader; import ninja.leaping.configurate.yaml.YAMLConfigurationLoader;
import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.DumperOptions;
@ -33,9 +33,6 @@ public final class RegexConfig {
public static ConfigurationNode config; public static ConfigurationNode config;
public static YAMLConfigurationLoader configLoader; public static YAMLConfigurationLoader configLoader;
static int version;
static boolean verbose;
public static void init() { public static void init() {
CONFIG_FILE = new File(Config.CONFIGPATH, "filters.yml");; CONFIG_FILE = new File(Config.CONFIGPATH, "filters.yml");;
configLoader = YAMLConfigurationLoader.builder() configLoader = YAMLConfigurationLoader.builder()
@ -64,10 +61,7 @@ public final class RegexConfig {
e.printStackTrace(); e.printStackTrace();
} }
verbose = getBoolean("verbose", true); readConfig(RegexConfig.class, null);
version = getInt("config-version", 1);
readConfig(Config.class, null);
try { try {
configLoader.save(config); configLoader.save(config);
} catch (IOException e) { } catch (IOException e) {
@ -146,7 +140,9 @@ public final class RegexConfig {
return new ArrayList<>(); return new ArrayList<>();
} }
private void loadChatFilters() { public static List<String> ChatFilters = new ArrayList<>();
private static void loadChatFilters() {
ALogger.info("loading filters");
// for (Map.Entry<Object, ? extends ConfigurationNode> entry : config.getChildrenMap().entrySet()) { // for (Map.Entry<Object, ? extends ConfigurationNode> entry : config.getChildrenMap().entrySet()) {
// String name = entry.getKey().toString(); // the name in the config this filter has // String name = entry.getKey().toString(); // the name in the config this filter has
// String type = entry.getValue().getNode("type").getString(); // the type of filter, block or replace // String type = entry.getValue().getNode("type").getString(); // the type of filter, block or replace
@ -170,19 +166,18 @@ public final class RegexConfig {
// } // }
Map<String, Object> properties = new HashMap<>(); Map<String, Object> properties = new HashMap<>();
config.getChildrenMap().forEach((key, value) -> { config.getChildrenMap().entrySet().forEach(entry -> {
if (value.hasMapChildren()) { try {
String rkey = key.toString(); String name = entry.getKey().toString();
properties.put("name", rkey); String type = entry.getValue().getNode("type").getString();
for (Map.Entry<Object, ? extends ConfigurationNode> vl : value.getChildrenMap().entrySet()) { String regex = entry.getValue().getNode("regex").getString();
properties.put(rkey + "." + vl.getKey(), vl.getValue().getValue()); String replacement = entry.getValue().getNode("replacement").getString();
} List<String> exclusions = entry.getValue().getNode("exclusions").getList(TypeToken.of(String.class), new ArrayList<>());
} else { ChatFilter chatFilter = new ChatFilter(name, type, regex, replacement, exclusions);
properties.put(key.toString(), value.getValue()); RegexManager.addFilter(chatFilter);
} catch(ObjectMappingException ex) {
} }
}); });
ChatFilter chatFilter = new ChatFilter(properties);
RegexManager.addFilter(chatFilter);
} }
} }

View File

@ -39,12 +39,12 @@ public class DatabaseConnection {
return; return;
} }
try { try {
Class.forName("com.mysql.jdbc.Driver"); Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {
e.printStackTrace(); e.printStackTrace();
} }
connection = DriverManager.getConnection( connection = DriverManager.getConnection(
"jdbc:" + Config.DRIVER + "://" + Config.IP + ":" + Config.PORT + "/" + Config.DATABASE + "?autoReconnect=true", "jdbc:" + Config.DRIVER + "://" + Config.IP + ":" + Config.PORT + "/" + Config.DATABASE + "?autoReconnect=true&enabledTLSProtocols=TLSv1.1",
Config.USERNAME, Config.PASSWORD); Config.USERNAME, Config.PASSWORD);
} }
} }

View File

@ -3,7 +3,6 @@ package com.alttd.chat.database;
import com.alttd.chat.managers.ChatUserManager; import com.alttd.chat.managers.ChatUserManager;
import com.alttd.chat.objects.ChatUser; import com.alttd.chat.objects.ChatUser;
import com.alttd.chat.objects.Party; import com.alttd.chat.objects.Party;
import com.alttd.chat.util.ALogger;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
@ -272,7 +271,6 @@ public class Queries {
if (party == null) { if (party == null) {
//TODO log this properly //TODO log this properly
ALogger.error("INCORRECT LOGGING: party was empty, the party id stored in the database with user " + uuid + " was invalid.");
System.out.println("INCORRECT LOGGING: party was empty, the party id stored in the database with user " + uuid + " was invalid."); System.out.println("INCORRECT LOGGING: party was empty, the party id stored in the database with user " + uuid + " was invalid.");
continue; continue;
} }

View File

@ -4,6 +4,7 @@ import com.alttd.chat.database.Queries;
import com.alttd.chat.objects.ChatUser; import com.alttd.chat.objects.ChatUser;
import com.alttd.chat.objects.Mail; import com.alttd.chat.objects.Mail;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArrayList;
@ -11,25 +12,27 @@ import java.util.stream.Collectors;
public final class ChatUserManager { public final class ChatUserManager {
private static CopyOnWriteArrayList<ChatUser> chatUsers;// not sure on this, could cause errors later on private static ArrayList<ChatUser> chatUsers;// not sure on this, could cause errors later on
public static void initialize() { public static void initialize() {
chatUsers = new CopyOnWriteArrayList<>(); chatUsers = new ArrayList<>();
Queries.loadChatUsers(); //Queries.loadChatUsers(); // todo fix sql
} }
public static void addUser(ChatUser user) { public static void addUser(ChatUser user) {
if(getChatUser(user.getUuid()) != null) if(getChatUser(user.getUuid()) == null)
chatUsers.add(user); chatUsers.add(user);
} }
public static ChatUser getChatUser(UUID uuid) { public static ChatUser getChatUser(UUID uuid) {
for(ChatUser user : chatUsers) { for(ChatUser user : chatUsers) {
if(user.getUuid() == uuid) { if(uuid.compareTo(user.getUuid()) == 0) {
return user; return user;
} }
} }
return null; ChatUser user = new ChatUser(uuid, -1, false, false);
chatUsers.add(user);
return user; // create a new user?
} }
public List<Mail> getUnReadMail(ChatUser user) { public List<Mail> getUnReadMail(ChatUser user) {

View File

@ -2,7 +2,7 @@ package com.alttd.chat.managers;
import com.alttd.chat.config.RegexConfig; import com.alttd.chat.config.RegexConfig;
import com.alttd.chat.objects.ChatFilter; import com.alttd.chat.objects.ChatFilter;
import com.alttd.chat.objects.FilterType; import com.alttd.chat.util.ALogger;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -18,22 +18,15 @@ public class RegexManager {
} }
public static void addFilter(ChatFilter filter) { public static void addFilter(ChatFilter filter) {
ALogger.info("Adding " + filter.getName());
chatFilters.add(filter); chatFilters.add(filter);
} }
// public static boolean violatesFilter(String text) {
// for (Map.Entry<Pattern, ArrayList<String>> entry : cancelRegex.entrySet()) {
// Matcher matcher = entry.getKey().matcher(text);
// while (matcher.find()) {
// if (!entry.getValue().contains(matcher.group())) return true;
// }
// }
// return false;
// }
public static String replaceText(String text) { // TODO loop all objects in the list and check if they violate based on the MATCHER public static String replaceText(String text) { // TODO loop all objects in the list and check if they violate based on the MATCHER
for(ChatFilter chatFilter : chatFilters) { for(ChatFilter chatFilter : chatFilters) {
switch (chatFilter.getType()) { switch (chatFilter.getType()) {
case CHAT:
break;
case REPLACE: case REPLACE:
text = chatFilter.replaceText(text); text = chatFilter.replaceText(text);
break; break;
@ -44,9 +37,6 @@ public class RegexManager {
break; break;
} }
} }
// for (Map.Entry<String, String> entry : replaceRegex.entrySet()) {
// text = text.replaceAll(entry.getKey(), entry.getValue());
// }
return text; return text;
} }

View File

@ -1,48 +1,45 @@
package com.alttd.chat.objects; package com.alttd.chat.objects;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
public class ChatFilter { public class ChatFilter {
private final Properties properties = new Properties(); private final String name;
private final Pattern pattern;
private final FilterType filterType; private final FilterType filterType;
private final String regex;
private final Pattern pattern;
private final String replacement;
private final List<String> exclusions;
public ChatFilter(Map<String, Object> props) { public ChatFilter(String name, String type, String regex, String replacement, List<String> exclusions) {
addDefaults(); this.name = name;
properties.keySet().stream().filter(props::containsKey).forEach((nkey) -> properties.put(nkey, props.get(nkey))); this.filterType = FilterType.getType(type);
pattern = Pattern.compile(getRegex()); this.regex = regex;
filterType = FilterType.getType((String) properties.get("type")); this.pattern = Pattern.compile(getRegex());
this.replacement = replacement;
this.exclusions = exclusions;
} }
private void addDefaults() { public String getName() {
properties.put("name", ""); return this.name;
properties.put("type", null);
properties.put("regex", "");
properties.put("replacement", "");
properties.put("exclusions", new ArrayList<String>());
} }
public String getRegex() { public String getRegex() {
return (String) properties.get("regex"); return this.regex;
} }
public FilterType getType() { public FilterType getType() {
return filterType; return this.filterType;
} }
public String getReplacement() { public String getReplacement() {
return (String) properties.get("replacement"); return this.replacement;
} }
@SuppressWarnings("unchecked")
public List<String> getExclusions() { public List<String> getExclusions() {
return (List<String>) properties.get("exclusions"); return this.exclusions;
} }
public boolean matches(String input) { public boolean matches(String input) {
@ -53,8 +50,8 @@ public class ChatFilter {
public String replaceText(String input) { public String replaceText(String input) {
Matcher matcher = pattern.matcher(input); Matcher matcher = pattern.matcher(input);
while (matcher.find()) { while (matcher.find()) {
String group = matcher.group(); String group = matcher.group(); // todo debug
if(!getExclusions().contains(group)) { // doesn't work well with capitals, use a stream filter? if(getExclusions().stream().noneMatch(s -> s.equalsIgnoreCase(group))) { // idk how heavy this is:/
input = input.replace(group, getReplacement()); input = input.replace(group, getReplacement());
} }
} }

View File

@ -27,10 +27,10 @@ public class ChatUser {
this.partyId = partyId; this.partyId = partyId;
this.toggledPartyChat = toggledChat; this.toggledPartyChat = toggledChat;
displayName = Queries.getNickname(uuid); //displayName = Queries.getNickname(uuid); // todo fix sql
if (displayName == null) { //if (displayName == null) {
displayName = Utility.getDisplayName(uuid); displayName = Utility.getDisplayName(uuid);
} //}
prefix = Utility.getPrefix(uuid, true); prefix = Utility.getPrefix(uuid, true);
staffPrefix = Utility.getStaffPrefix(uuid); staffPrefix = Utility.getStaffPrefix(uuid);

View File

@ -2,6 +2,8 @@ package com.alttd.chat.objects;
public enum FilterType { public enum FilterType {
REPLACE("replace"), REPLACE("replace"),
CHAT("chat"),
REPLACEMATCHER("replacematcher"),
BLOCK("block"); BLOCK("block");
private final String name; private final String name;

View File

@ -4,7 +4,7 @@ public class ALogger {
private static org.slf4j.Logger logger; private static org.slf4j.Logger logger;
public ALogger(org.slf4j.Logger log) { public static void init(org.slf4j.Logger log) {
logger = log; logger = log;
} }

View File

@ -3,6 +3,7 @@ package com.alttd.chat;
import com.alttd.chat.commands.GlobalChat; import com.alttd.chat.commands.GlobalChat;
import com.alttd.chat.config.Config; import com.alttd.chat.config.Config;
import com.alttd.chat.handler.ChatHandler; import com.alttd.chat.handler.ChatHandler;
import com.alttd.chat.listeners.ChatListener;
import com.alttd.chat.listeners.PlayerListener; import com.alttd.chat.listeners.PlayerListener;
import com.alttd.chat.listeners.PluginMessage; import com.alttd.chat.listeners.PluginMessage;
import com.alttd.chat.util.ALogger; import com.alttd.chat.util.ALogger;
@ -22,10 +23,10 @@ public class ChatPlugin extends JavaPlugin {
@Override @Override
public void onEnable() { public void onEnable() {
instance = this; instance = this;
new ALogger(this.getSLF4JLogger()); ALogger.init(getSLF4JLogger());
chatAPI = new ChatImplementation(); chatAPI = new ChatImplementation();
chatHandler = new ChatHandler(); chatHandler = new ChatHandler();
registerListener(new PlayerListener()); registerListener(new PlayerListener(), new ChatListener());
registerCommand("globalchat", new GlobalChat()); registerCommand("globalchat", new GlobalChat());
messageChannel = Config.MESSAGECHANNEL; messageChannel = Config.MESSAGECHANNEL;

View File

@ -3,6 +3,7 @@ package com.alttd.chat.handler;
import com.alttd.chat.ChatPlugin; import com.alttd.chat.ChatPlugin;
import com.alttd.chat.config.Config; import com.alttd.chat.config.Config;
import com.alttd.chat.managers.ChatUserManager; import com.alttd.chat.managers.ChatUserManager;
import com.alttd.chat.managers.RegexManager;
import com.alttd.chat.objects.ChatUser; import com.alttd.chat.objects.ChatUser;
import com.alttd.chat.util.Utility; import com.alttd.chat.util.Utility;
import com.google.common.io.ByteArrayDataOutput; import com.google.common.io.ByteArrayDataOutput;
@ -10,6 +11,7 @@ import com.google.common.io.ByteStreams;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage; import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.minimessage.Template; import net.kyori.adventure.text.minimessage.Template;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@ -44,17 +46,21 @@ public class ChatHandler {
player.sendMessage(miniMessage.parse(Config.GCONCOOLDOWN, Template.of("cooldown", timeLeft+""))); player.sendMessage(miniMessage.parse(Config.GCONCOOLDOWN, Template.of("cooldown", timeLeft+"")));
return; return;
} }
String senderName, prefix = "";
senderName = player.getDisplayName(); // TODO this can be a component Component senderName = player.displayName();
// can also be cached in the chatuser object? String prefix = user.getPrefix();
prefix = user.getPrefix();
message = Utility.parseColors(message); message = RegexManager.replaceText(message); // todo a better way for this
if(!player.hasPermission("chat.format")) if(message == null) return; // the message was blocked
if(!player.hasPermission("chat.format")) {
message = miniMessage.stripTokens(message); message = miniMessage.stripTokens(message);
} else {
message = Utility.parseColors(message);
}
if(message.contains("[i]")) if(message.contains("[i]"))
message = message.replace("[i]", "<[i]>"); message = message.replace("[i]", "<[i]>"); // end of todo
List<Template> templates = new ArrayList<>(List.of( List<Template> templates = new ArrayList<>(List.of(
Template.of("sender", senderName), Template.of("sender", senderName),
@ -71,14 +77,14 @@ public class ChatHandler {
private void sendPluginMessage(Player player, String channel, Component component) { private void sendPluginMessage(Player player, String channel, Component component) {
ByteArrayDataOutput out = ByteStreams.newDataOutput(); ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF(channel); out.writeUTF(channel);
out.writeUTF(miniMessage.serialize(component)); // todo use a better component serializer ~ look into kyori out.writeUTF(GsonComponentSerializer.gson().serialize(component)); // todo use a better component serializer ~ look into kyori
player.sendPluginMessage(plugin, Config.MESSAGECHANNEL, out.toByteArray()); player.sendPluginMessage(plugin, Config.MESSAGECHANNEL, out.toByteArray());
} }
// Start - move these to util // Start - move these to util
public Component itemComponent(ItemStack item) { public static Component itemComponent(ItemStack item) {
Component component = Component.text("[i]"); Component component = Component.text("[i]");
if(item.getType().equals(Material.AIR)) if(item.getType().equals(Material.AIR)) // do we want to show the <players hand>?
return component; return component;
boolean dname = item.hasItemMeta() && item.getItemMeta().hasDisplayName(); boolean dname = item.hasItemMeta() && item.getItemMeta().hasDisplayName();
if(dname) { if(dname) {

View File

@ -1,15 +1,25 @@
package com.alttd.chat.listeners; package com.alttd.chat.listeners;
import io.papermc.paper.event.player.AsyncChatEvent; import com.alttd.chat.managers.ChatUserManager;
import org.bukkit.entity.Player; import com.alttd.chat.objects.ChatUser;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import java.util.UUID;
public class PlayerListener implements Listener { public class PlayerListener implements Listener {
@EventHandler(ignoreCancelled = true) @EventHandler
public void onPlayerChat(AsyncChatEvent event) { private void onPlayerLogin(PlayerJoinEvent event) {
Player player = event.getPlayer(); UUID uuid = event.getPlayer().getUniqueId();
// TODO ChatUser user = ChatUserManager.getChatUser(uuid);
if(user != null) return;
// todo actually load the users from db
ChatUserManager.addUser(new ChatUser(uuid, -1, false, false));
} }
} }

View File

@ -71,6 +71,12 @@
<version>4.1.0</version> <version>4.1.0</version>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.24</version>
<scope>provided</scope>
</dependency>
</dependencies> </dependencies>
<properties> <properties>
<maven.compiler.target>11</maven.compiler.target> <maven.compiler.target>11</maven.compiler.target>

View File

@ -95,8 +95,8 @@
<dependency> <dependency>
<groupId>mysql</groupId> <groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId> <artifactId>mysql-connector-java</artifactId>
<version>5.1.49</version> <version>8.0.24</version>
<scope>runtime</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>net.kyori</groupId> <groupId>net.kyori</groupId>

View File

@ -8,7 +8,6 @@ import com.alttd.chat.handlers.ServerHandler;
import com.alttd.chat.listeners.ChatListener; import com.alttd.chat.listeners.ChatListener;
import com.alttd.chat.listeners.ProxyPlayerListener; import com.alttd.chat.listeners.ProxyPlayerListener;
import com.alttd.chat.listeners.PluginMessageListener; import com.alttd.chat.listeners.PluginMessageListener;
import com.alttd.chat.managers.RegexManager;
import com.alttd.chat.util.ALogger; import com.alttd.chat.util.ALogger;
import com.google.inject.Inject; import com.google.inject.Inject;
import com.velocitypowered.api.event.Subscribe; import com.velocitypowered.api.event.Subscribe;
@ -19,8 +18,6 @@ import com.velocitypowered.api.plugin.annotation.DataDirectory;
import com.velocitypowered.api.proxy.ProxyServer; import com.velocitypowered.api.proxy.ProxyServer;
import com.velocitypowered.api.proxy.messages.ChannelIdentifier; import com.velocitypowered.api.proxy.messages.ChannelIdentifier;
import com.velocitypowered.api.proxy.messages.MinecraftChannelIdentifier; import com.velocitypowered.api.proxy.messages.MinecraftChannelIdentifier;
import net.luckperms.api.LuckPerms;
import net.luckperms.api.LuckPermsProvider;
import org.slf4j.Logger; import org.slf4j.Logger;
import java.io.File; import java.io.File;
@ -54,8 +51,7 @@ public class VelocityChat {
@Subscribe @Subscribe
public void onProxyInitialization(ProxyInitializeEvent event) { public void onProxyInitialization(ProxyInitializeEvent event) {
new ALogger(logger); ALogger.init(logger);
//Config.init(getDataDirectory());
chatAPI = new ChatImplementation(); chatAPI = new ChatImplementation();
serverHandler = new ServerHandler(); serverHandler = new ServerHandler();

View File

@ -24,7 +24,7 @@ public class GlobalAdminChat {
.executes(context -> { .executes(context -> {
VelocityChat.getPlugin().getChatHandler().globalAdminChat(context.getSource(), context.getArgument("message", String.class)); VelocityChat.getPlugin().getChatHandler().globalAdminChat(context.getSource(), context.getArgument("message", String.class));
return 1; return 1;
}) // TODO call in the same way as gc? })
) )
.executes(context -> 0) .executes(context -> 0)
.build(); .build();

View File

@ -15,29 +15,29 @@ import com.velocitypowered.api.proxy.ProxyServer;
public class GlobalChat { public class GlobalChat {
public GlobalChat(ProxyServer proxyServer) { public GlobalChat(ProxyServer proxyServer) {
LiteralCommandNode<CommandSource> command = LiteralArgumentBuilder // LiteralCommandNode<CommandSource> command = LiteralArgumentBuilder
.<CommandSource>literal("globalchat") // .<CommandSource>literal("globalchat")
.requires(ctx -> ctx.hasPermission("command.proxy.globalchat"))// TODO permission system? load permissions from config? // .requires(ctx -> ctx.hasPermission("command.proxy.globalchat"))// TODO permission system? load permissions from config?
.requires(ctx -> ctx instanceof Player) // players only can use this // .requires(ctx -> ctx instanceof Player) // players only can use this
.then(RequiredArgumentBuilder // .then(RequiredArgumentBuilder
.<CommandSource, String>argument("message", StringArgumentType.greedyString()) // .<CommandSource, String>argument("message", StringArgumentType.greedyString())
.executes(context -> { // .executes(context -> {
VelocityChat.getPlugin().getChatHandler().globalChat((Player) context.getSource(), context.getArgument("message", String.class)); // VelocityChat.getPlugin().getChatHandler().globalChat((Player) context.getSource(), context.getArgument("message", String.class));
return 1; // return 1;
}) // })
) // )
.executes(context -> 0) // todo info message /usage // .executes(context -> 0) // todo info message /usage
.build(); // .build();
//
BrigadierCommand brigadierCommand = new BrigadierCommand(command); // BrigadierCommand brigadierCommand = new BrigadierCommand(command);
//
CommandMeta.Builder metaBuilder = proxyServer.getCommandManager().metaBuilder(brigadierCommand); // CommandMeta.Builder metaBuilder = proxyServer.getCommandManager().metaBuilder(brigadierCommand);
//
for (String alias : Config.GCALIAS) { // for (String alias : Config.GCALIAS) {
metaBuilder.aliases(alias); // metaBuilder.aliases(alias);
} // }
CommandMeta meta = metaBuilder.build(); // CommandMeta meta = metaBuilder.build();
//
proxyServer.getCommandManager().register(meta, brigadierCommand); // proxyServer.getCommandManager().register(meta, brigadierCommand);
} }
} }

View File

@ -2,52 +2,19 @@ package com.alttd.chat.handlers;
import com.alttd.chat.VelocityChat; import com.alttd.chat.VelocityChat;
import com.alttd.chat.config.Config; import com.alttd.chat.config.Config;
import com.alttd.chat.managers.ChatUserManager;
import com.alttd.chat.managers.RegexManager; import com.alttd.chat.managers.RegexManager;
import com.alttd.chat.objects.ChatUser;
import com.alttd.chat.util.Utility; import com.alttd.chat.util.Utility;
import com.velocitypowered.api.command.CommandSource; import com.velocitypowered.api.command.CommandSource;
import com.velocitypowered.api.proxy.Player; import com.velocitypowered.api.proxy.Player;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage; import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.minimessage.Template; import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List;
import java.util.Map; import java.util.Map;
public class ChatHandler { public class ChatHandler {
public void globalChat(Player player, String message) {
ChatUser user = ChatUserManager.getChatUser(player.getUniqueId());
if(user == null) return;
MiniMessage miniMessage = MiniMessage.get();
if(!user.isGcOn()) {
player.sendMessage(miniMessage.parse(Config.GCNOTENABLED));// GC IS OFF INFORM THEM ABOUT THIS and cancel
return;
}
message = Utility.parseColors(message);
if(!player.hasPermission("chat.format")) // Todo PR fix for '<3' to minimessage
message = miniMessage.stripTokens(message);
message = RegexManager.replaceText(message); // this filters the message TODO should staff be able to bypass filters?
List<Template> templates = new ArrayList<>(List.of(
Template.of("sender", user.getDisplayName()),
Template.of("prefix", user.getPrefix()),
Template.of("message", message),
Template.of("server", player.getCurrentServer().isPresent() ? player.getCurrentServer().get().getServerInfo().getName() : "Altitude")
/*,Template.of("[i]", itemComponent(sender.getInventory().getItemInMainHand()))*/ //Todo move this into ChatFilters
));
Component component = miniMessage.parse(Config.GCFORMAT, templates);
VelocityChat.getPlugin().getServerHandler().sendGlobalChat(component);
}
public void privateMessage(CommandSource commandSource, Player recipient, String message) { public void privateMessage(CommandSource commandSource, Player recipient, String message) {
// todo get the chatUserinstance of both players and or console - @teri should console be able to /msg? // todo get the chatUserinstance of both players and or console - @teri should console be able to /msg?
String senderName; String senderName;
@ -92,9 +59,7 @@ public class ChatHandler {
} }
public void globalAdminChat(String message) { public void globalAdminChat(String message) {
MiniMessage miniMessage = MiniMessage.get(); Component component = GsonComponentSerializer.gson().deserialize(message);
Component component = miniMessage.parse(Config.GACFORMAT);
VelocityChat.getPlugin().getProxy().getAllPlayers().stream().filter(target -> target.hasPermission("command.proxy.globaladminchat")/*TODO permission*/).forEach(target -> { VelocityChat.getPlugin().getProxy().getAllPlayers().stream().filter(target -> target.hasPermission("command.proxy.globaladminchat")/*TODO permission*/).forEach(target -> {
target.sendMessage(component); target.sendMessage(component);

View File

@ -6,6 +6,7 @@ import com.alttd.chat.data.ServerWrapper;
import com.velocitypowered.api.proxy.Player; import com.velocitypowered.api.proxy.Player;
import com.velocitypowered.api.proxy.server.RegisteredServer; import com.velocitypowered.api.proxy.server.RegisteredServer;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
@ -36,10 +37,12 @@ public class ServerHandler {
} }
} }
public void sendGlobalChat(Component message) { public void sendGlobalChat(String message) {
Component component = GsonComponentSerializer.gson().deserialize(message);
servers.stream() servers.stream()
.filter(serverWrapper -> serverWrapper.globalChat()) .filter(serverWrapper -> serverWrapper.globalChat())
.forEach(serverWrapper -> serverWrapper.getRegisteredServer().sendMessage(message)); .forEach(serverWrapper -> serverWrapper.getRegisteredServer().sendMessage(component));
} }
public List<ServerWrapper> getServers() public List<ServerWrapper> getServers()

View File

@ -33,8 +33,7 @@ public class PluginMessageListener {
VelocityChat.getPlugin().getLogger().info("server " + event.getSource()); VelocityChat.getPlugin().getLogger().info("server " + event.getSource());
switch (channel) { switch (channel) {
case "globalchat": case "globalchat":
// todo this is obsolete VelocityChat.getPlugin().getServerHandler().sendGlobalChat(in.readUTF());
//VelocityChat.getPlugin().getServerHandler().sendGlobalChat(in.readUTF());
break; break;
case "globaladminchat": case "globaladminchat":
VelocityChat.getPlugin().getChatHandler().globalAdminChat(in.readUTF()); VelocityChat.getPlugin().getChatHandler().globalAdminChat(in.readUTF());