Add back api and server module

This commit is contained in:
len
2021-06-02 19:55:55 +02:00
parent b814a5b01b
commit 5d8d7b5dff
22 changed files with 100 additions and 61 deletions
@@ -0,0 +1,242 @@
package com.alttd.chat.config;
import com.google.common.base.Throwables;
import com.google.common.collect.Lists;
import com.google.common.reflect.TypeToken;
import ninja.leaping.configurate.ConfigurationNode;
import ninja.leaping.configurate.ConfigurationOptions;
import ninja.leaping.configurate.objectmapping.ObjectMappingException;
import ninja.leaping.configurate.yaml.YAMLConfigurationLoader;
import org.yaml.snakeyaml.DumperOptions;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
public final class Config {
private static final Pattern PATH_PATTERN = Pattern.compile("\\.");
private static final String HEADER = "";
private static File CONFIG_FILE;
public static ConfigurationNode config;
public static YAMLConfigurationLoader configLoader;
static int version;
static boolean verbose;
public static void init(File path) {
CONFIG_FILE = new File(path, "config.yml");;
// public static void init() { // todo setup share for the config
// CONFIG_FILE = new File(new File(System.getProperty("user.home")+File.separator+"ChatPlugin"), "config.yml");;
configLoader = YAMLConfigurationLoader.builder()
.setFile(CONFIG_FILE)
.setFlowStyle(DumperOptions.FlowStyle.BLOCK)
.build();
if (!CONFIG_FILE.getParentFile().exists()) {
if(!CONFIG_FILE.getParentFile().mkdirs()) {
return;
}
}
if (!CONFIG_FILE.exists()) {
try {
if(!CONFIG_FILE.createNewFile()) {
return;
}
} catch (IOException error) {
error.printStackTrace();
}
}
try {
config = configLoader.load(ConfigurationOptions.defaults().setHeader(HEADER));
} catch (IOException e) {
e.printStackTrace();
}
verbose = getBoolean("verbose", true);
version = getInt("config-version", 1);
readConfig(Config.class, null);
try {
configLoader.save(config);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void readConfig(Class<?> clazz, Object instance) {
for (Method method : clazz.getDeclaredMethods()) {
if (Modifier.isPrivate(method.getModifiers())) {
if (method.getParameterTypes().length == 0 && method.getReturnType() == Void.TYPE) {
try {
method.setAccessible(true);
method.invoke(instance);
} catch (InvocationTargetException | IllegalAccessException ex) {
throw Throwables.propagate(ex.getCause());
}
}
}
}
try {
configLoader.save(config);
} catch (IOException ex) {
throw Throwables.propagate(ex.getCause());
}
}
public static void saveConfig() {
try {
configLoader.save(config);
} catch (IOException ex) {
throw Throwables.propagate(ex.getCause());
}
}
private static Object[] splitPath(String key) {
return PATH_PATTERN.split(key);
}
private static void set(String path, Object def) {
if(config.getNode(splitPath(path)).isVirtual())
config.getNode(splitPath(path)).setValue(def);
}
private static void setString(String path, String def) {
try {
if(config.getNode(splitPath(path)).isVirtual())
config.getNode(splitPath(path)).setValue(TypeToken.of(String.class), def);
} catch(ObjectMappingException ex) {
}
}
private static boolean getBoolean(String path, boolean def) {
set(path, def);
return config.getNode(splitPath(path)).getBoolean(def);
}
private static double getDouble(String path, double def) {
set(path, def);
return config.getNode(splitPath(path)).getDouble(def);
}
private static int getInt(String path, int def) {
set(path, def);
return config.getNode(splitPath(path)).getInt(def);
}
private static String getString(String path, String def) {
setString(path, def);
return config.getNode(splitPath(path)).getString(def);
}
private static Long getLong(String path, Long def) {
set(path, def);
return config.getNode(splitPath(path)).getLong(def);
}
private static <T> List<String> getList(String path, T def) {
try {
set(path, def);
return config.getNode(splitPath(path)).getList(TypeToken.of(String.class));
} catch(ObjectMappingException ex) {
}
return new ArrayList<>();
}
private static ConfigurationNode getNode(String path) {
if(config.getNode(splitPath(path)).isVirtual()) {
//new RegexConfig("Dummy");
}
config.getChildrenMap();
return config.getNode(splitPath(path));
}
/** ONLY EDIT ANYTHING BELOW THIS LINE **/
public static List<String> PREFIXGROUPS = new ArrayList<>();
public static List<String> STAFFGROUPS = new ArrayList<>();
public static String MINIMIUMSTAFFRANK = "trainee";
public static String CONSOLENAME = "Console";
private static void settings() {
PREFIXGROUPS = getList("settings.prefix-groups",
Lists.newArrayList("discord", "socialmedia", "eventteam", "eventleader", "youtube", "twitch", "developer"));
STAFFGROUPS = getList("settings.staff-groups",
Lists.newArrayList("trainee", "moderator", "headmod", "admin", "manager", "owner"));
CONSOLENAME = getString("settings.console-name", CONSOLENAME);
MINIMIUMSTAFFRANK = getString("settings.minimum-staff-rank", MINIMIUMSTAFFRANK);
}
public static List<String> MESSAGECOMMANDALIASES = new ArrayList<>();
public static List<String> REPLYCOMMANDALIASES = new ArrayList<>();
public static String MESSAGESENDER = "<hover:show_text:Click to reply><click:suggest_command:/msg <receiver> ><light_purple>(Me -> <gray><receiver></gray>) <message>";
public static String MESSAGERECIEVER = "<hover:show_text:Click to reply><click:suggest_command:/msg <sender> ><light_purple>(<gray><sender></gray> on <server> -> Me) <message>";
private static void messageCommand() {
MESSAGECOMMANDALIASES.clear();
REPLYCOMMANDALIASES.clear();
MESSAGECOMMANDALIASES = getList("commands.message.aliases", Lists.newArrayList("msg", "whisper", "tell"));
REPLYCOMMANDALIASES = getList("commands.reply.aliases", Lists.newArrayList("r"));
MESSAGESENDER = getString("commands.message.sender-message", MESSAGESENDER);
MESSAGERECIEVER = getString("commands.message.reciever-message", MESSAGERECIEVER);
}
///broadcast <white><light_purple><prefix></light_purple> <gray>Momlly</gray> <hover:show_text:on Atoll><yellow>to Global</yellow></hover><gray>: We Love <gold>Teri</gold> and <light_purple>Kappa</light_purple></gray></white>
public static String GCFORMAT = "<white><light_purple><prefix></light_purple> <gray><sender></gray> <hover:show_text:on <server>><yellow>to Global</yellow></hover><gray>: <message>";
public static String GCPERMISSION = "proxy.globalchat";
public static List<String> GCALIAS = new ArrayList<>();
public static String GCNOTENABLED = "You don't have global chat enabled.";
private static void globalChat() {
MESSAGERECIEVER = getString("commands.globalchat.format", MESSAGERECIEVER);
GCPERMISSION = getString("commands.globalchat.view-chat-permission", GCPERMISSION);
GCALIAS.clear();
GCALIAS = getList("commands.globalchat.alias", Lists.newArrayList("gc", "global"));
GCNOTENABLED = getString("commands.globalchat.not-enabled", GCNOTENABLED);
}
public static List<String> GACECOMMANDALIASES = new ArrayList<>();
public static String GACFORMAT = "<hover:show_text:Click to reply><click:suggest_command:/acg ><yellow>(<sender> on <server> -> Team) <message>";
private static void globalAdminChat() {
GACECOMMANDALIASES = getList("commands.globaladminchat.aliases", Lists.newArrayList("acg"));
GACFORMAT = getString("commands.globaladminchat.format", GACFORMAT);
}
public static String MESSAGECHANNEL = "altitude:chatplugin";
private static void messageChannels() {
MESSAGECHANNEL = getString("settings.message-channel", MESSAGECHANNEL);
}
public static ConfigurationNode REGEXNODE = null;
private static void RegexNOde() {
REGEXNODE = getNode("regex-settings");
}
public static String SERVERSWTICHMESSAGEFROM = "<gray>* <player> comes from <from_server>...";
public static String SERVERSWTICHMESSAGETO = "<gray>* <player> leaves to <to_server>...";
public static String SERVERJOINMESSAGE = "<green>* <player> appears from thin air...";
public static String SERVERLEAVEMESSAGE = "<red>* <player> vanishes in the mist...";
private static void JoinLeaveMessages() {
SERVERSWTICHMESSAGEFROM = getString("messages.switch-server-from", SERVERSWTICHMESSAGEFROM);
SERVERSWTICHMESSAGETO = getString("messages.switch-server-to", SERVERSWTICHMESSAGETO);
SERVERJOINMESSAGE = getString("messages.join-server", SERVERJOINMESSAGE);
SERVERLEAVEMESSAGE = getString("messages.leave-server", SERVERLEAVEMESSAGE);
}
public static String DRIVER = "mysql";
public static String IP = "0.0.0.0";
public static String PORT = "3306";
public static String DATABASE = "database";
public static String USERNAME = "root";
public static String PASSWORD = "root";
private static void database() {
DRIVER = getString("database.driver" , DRIVER);
IP = getString("database.ip", IP);
PORT = getString("database.port", PORT);
DATABASE = getString("database.name", DATABASE);
USERNAME = getString("database.username", USERNAME);
PASSWORD = getString("database.password", PASSWORD);
}
}
@@ -0,0 +1,184 @@
package com.alttd.chat.config;
import com.google.common.base.Throwables;
import com.google.common.reflect.TypeToken;
import ninja.leaping.configurate.ConfigurationNode;
import ninja.leaping.configurate.ConfigurationOptions;
import ninja.leaping.configurate.commented.CommentedConfigurationNode;
import ninja.leaping.configurate.hocon.HoconConfigurationLoader;
import ninja.leaping.configurate.objectmapping.ObjectMappingException;
import ninja.leaping.configurate.yaml.YAMLConfigurationLoader;
import org.yaml.snakeyaml.DumperOptions;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
public final class RegexConfig {
private static final Pattern PATH_PATTERN = Pattern.compile("\\.");
private static final String HEADER =
"This file is used to store all of the chatfilters used in the Altitude Chat plugin.\n"
+ "Nodes must be build in this format.\n"
+ "TODO update this format\n";
private static File CONFIG_FILE;
public static ConfigurationNode config;
public static YAMLConfigurationLoader configLoader;
static int version;
static boolean verbose;
public static void init(File path) {
CONFIG_FILE = new File(path, "filters.yml");;
configLoader = YAMLConfigurationLoader.builder()
.setFile(CONFIG_FILE)
.setFlowStyle(DumperOptions.FlowStyle.BLOCK)
.build();
if (!CONFIG_FILE.getParentFile().exists()) {
if(!CONFIG_FILE.getParentFile().mkdirs()) {
return;
}
}
if (!CONFIG_FILE.exists()) {
try {
if(!CONFIG_FILE.createNewFile()) {
return;
}
} catch (IOException error) {
error.printStackTrace();
}
}
try {
config = configLoader.load(ConfigurationOptions.defaults().setHeader(HEADER));
} catch (IOException e) {
e.printStackTrace();
}
verbose = getBoolean("verbose", true);
version = getInt("config-version", 1);
readConfig(Config.class, null);
try {
configLoader.save(config);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void readConfig(Class<?> clazz, Object instance) {
for (Method method : clazz.getDeclaredMethods()) {
if (Modifier.isPrivate(method.getModifiers())) {
if (method.getParameterTypes().length == 0 && method.getReturnType() == Void.TYPE) {
try {
method.setAccessible(true);
method.invoke(instance);
} catch (InvocationTargetException | IllegalAccessException ex) {
throw Throwables.propagate(ex.getCause());
}
}
}
}
try {
configLoader.save(config);
} catch (IOException ex) {
throw Throwables.propagate(ex.getCause());
}
}
private static Object[] splitPath(String key) {
return PATH_PATTERN.split(key);
}
private static void set(String path, Object def) {
if(config.getNode(splitPath(path)).isVirtual())
config.getNode(splitPath(path)).setValue(def);
}
private static void setString(String path, String def) {
try {
if(config.getNode(splitPath(path)).isVirtual())
config.getNode(splitPath(path)).setValue(TypeToken.of(String.class), def);
} catch(ObjectMappingException ex) {
}
}
private static boolean getBoolean(String path, boolean def) {
set(path, def);
return config.getNode(splitPath(path)).getBoolean(def);
}
private static double getDouble(String path, double def) {
set(path, def);
return config.getNode(splitPath(path)).getDouble(def);
}
private static int getInt(String path, int def) {
set(path, def);
return config.getNode(splitPath(path)).getInt(def);
}
private static String getString(String path, String def) {
setString(path, def);
return config.getNode(splitPath(path)).getString(def);
}
private static Long getLong(String path, Long def) {
set(path, def);
return config.getNode(splitPath(path)).getLong(def);
}
private static <T> List<String> getList(String path, T def) {
try {
set(path, def);
return config.getNode(splitPath(path)).getList(TypeToken.of(String.class));
} catch(ObjectMappingException ex) {
}
return new ArrayList<>();
}
// public String REGEX = "REGEX";
// public String TYPE = "TYPE";
// public String REPLACEMENT = "REPLACEMENT";
// private void ServerSettings() {
// REGEX = getString("regex", REGEX);
// TYPE = getString("type", TYPE);
// REPLACEMENT = getString("replacement", REPLACEMENT);
// }
// Options:
// Filter: the regexstring
// replacements:
// exclusions: ["list", "of", "words"]
private void loadChatFilters() {
for (Map.Entry<Object, ? extends ConfigurationNode> entry : config.getChildrenMap().entrySet()) {
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 regex = "";
List<String> replacements = new ArrayList<>();
List<String> exclusions = new ArrayList<>();
Map<Object, ? extends ConfigurationNode> options = entry.getValue().getNode("options").getChildrenMap();
if (options.containsKey("filter")) {
regex = options.get("filter").getString();
}
if (options.containsKey("replacements")) {
options.get("replacements").getChildrenList().forEach(key -> {
replacements.add(key.getString());
});
}
if (options.containsKey("exclusions")) {
options.get("exclusions").getChildrenList().forEach(key -> {
exclusions.add(key.getString());
});
}
}
}
}
@@ -0,0 +1,78 @@
package com.alttd.chat.database;
import com.alttd.chat.config.Config;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseConnection {
private static DatabaseConnection instance;
private static Connection connection;
/**
* Sets information for the database and opens the connection.
*/
public DatabaseConnection() {
instance = this;
try {
instance.openConnection();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Opens the connection if it's not already open.
* @throws SQLException If it can't create the connection.
*/
public void openConnection() throws SQLException {
if (connection != null && !connection.isClosed()) {
return;
}
synchronized (this) {
if (connection != null && !connection.isClosed()) {
return;
}
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
connection = DriverManager.getConnection(
"jdbc:" + Config.DRIVER + "://" + Config.IP + ":" + Config.PORT + "/" + Config.DATABASE + "?autoReconnect=true",
Config.USERNAME, Config.PASSWORD);
}
}
/**
* Returns the connection for the database
* @return Returns the connection.
*/
public static Connection getConnection() {
try {
instance.openConnection();
}
catch (SQLException e) {
e.printStackTrace();
}
catch (Exception e){
e.printStackTrace();
}
return instance.connection;
}
/**
* Sets the connection for this instance
*/
public boolean initialize() {
instance = new DatabaseConnection();
return connection != null;
}
}
@@ -0,0 +1,370 @@
package com.alttd.chat.database;
import com.alttd.chat.managers.ChatUserManager;
import com.alttd.chat.objects.ChatUser;
import com.alttd.chat.objects.Party;
import com.alttd.chat.util.ALogger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
public class Queries {
//Create Tables
public static void createTables() {
List<String> tables = new ArrayList<>();
tables.add("CREATE TABLE IF NOT EXISTS ignored_users (`uuid` VARCHAR(36) NOT NULL, `ignored_uuid` VARCHAR(36) NOT NULL, PRIMARY KEY (`uuid`, `ignored_uuid`))");
tables.add("CREATE TABLE IF NOT EXISTS parties (`id` INT NOT NULL AUTO_INCREMENT, `owner_uuid` VARCHAR(36) NOT NULL, `party_name` VARCHAR(36) NOT NULL, `password` VARCHAR(36), PRIMARY KEY (`id`))");
tables.add("CREATE TABLE IF NOT EXISTS chat_users (`uuid` VARCHAR(36) NOT NULL, `party_id` INT NOT NULL, `toggled_chat` BIT(1) DEFAULT b'0', `force_tp` BIT(1) DEFAULT b'1', `toggled_gc` BIT(1) DEFAULT b'0', PRIMARY KEY (`uuid`))");
try {
Connection connection = DatabaseConnection.getConnection();
for (String query : tables) {
connection.prepareStatement(query).execute();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
//-----------------------------------------
//Nicknames
public static String getNickname(UUID uuid) {
// View has been created.
String query = "SELECT nickname FROM nicknames WHERE uuid = ?";
try {
Connection connection = DatabaseConnection.getConnection();
PreparedStatement statement = connection.prepareStatement(query);
statement.setString(1, uuid.toString());
ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
return resultSet.getString("nickname");
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
//-----------------------------------------
//Ignore
public static void getIgnoredUsers() { //TODO store this in a user object or something? -> ChatPlayer
HashMap<UUID, ArrayList<UUID>> ignoredUsers = new HashMap<>(); //TODO Replace with a proper way/location to store this in -> a list<UUID> in ChatPlayer?
String query = "SELECT * FROM ignored_users";
try {
Connection connection = DatabaseConnection.getConnection();
ResultSet resultSet = connection.prepareStatement(query).executeQuery();
while (resultSet.next()) {
UUID uuid = UUID.fromString(resultSet.getString("uuid"));
UUID ignoredUuid = UUID.fromString(resultSet.getString("ignored_uuid"));
ArrayList<UUID> uuids;
if (ignoredUsers.containsKey(uuid)) {
uuids = ignoredUsers.get(uuid);
} else {
uuids = new ArrayList<>();
}
uuids.add(ignoredUuid);
ignoredUsers.put(uuid, uuids);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void ignoreUser(UUID uuid, UUID ignoredUuid) {
//TODO this should be called from a function that already adds the user to the live ignored list, so this just adds it to the database
String query = "INSERT INTO ignored_users (uuid, ignored_uuid) VALUES (?, ?)";
try {
Connection connection = DatabaseConnection.getConnection();
PreparedStatement statement = connection.prepareStatement(query);
statement.setString(1, uuid.toString());
statement.setString(2, ignoredUuid.toString());
statement.execute();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void unIgnoreUser(UUID uuid, UUID ignoredUuid) {
//TODO this should be called from a function that already removes the user from the live ignored list, so this just removes it from the database
String query = "DELETE FROM ignored_users WHERE uuid = ? AND ignored_uuid = ?";
try {
Connection connection = DatabaseConnection.getConnection();
PreparedStatement statement = connection.prepareStatement(query);
statement.setString(1, uuid.toString());
statement.setString(2, ignoredUuid.toString());
statement.execute();
} catch (SQLException e) {
e.printStackTrace();
}
}
//-----------------------------------------
//Party
public static void getParties() {
HashMap<Integer, Party> parties = new HashMap<>(); //TODO Replace with a proper way/location to store this in
String query = "SELECT * FROM parties";
try {
Connection connection = DatabaseConnection.getConnection();
ResultSet resultSet = connection.prepareStatement(query).executeQuery();
while (resultSet.next()) {
int id = resultSet.getInt("id");
UUID ownerUuid = UUID.fromString(resultSet.getString("owner_uuid"));
String partyName = resultSet.getString("party_name");
String password = resultSet.getString("password");
parties.put(id, new Party(id, ownerUuid, partyName, password));
}
} catch (SQLException e) {
e.printStackTrace();
}
getChatUsers(parties); //TODO This parameter should be temporary, it should access the actual list of parties normally
}
public static Party addParty(UUID partyOwner, String partyName, String password) {
String query = "INSERT INTO parties (owner_uuid, party_name, password) VALUES (?, ?, ?)";
try {
Connection connection = DatabaseConnection.getConnection();
PreparedStatement statement = connection.prepareStatement(query);
statement.setString(1, partyOwner.toString());
statement.setString(2, partyName);
statement.setString(3, password.isEmpty() ? null : password);
statement.execute();
} catch (SQLException e) {
e.printStackTrace();
}
return getParty(partyOwner, partyName, password);
}
private static Party getParty(UUID partyOwner, String partyName, String password) {
String query = "SELECT * FROM parties WHERE owner_uuid = ? AND party_name = ?";
try {
Connection connection = DatabaseConnection.getConnection();
PreparedStatement statement = connection.prepareStatement(query);
statement.setString(1, partyOwner.toString());
statement.setString(2, partyName);
ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
int id = resultSet.getInt("id");
return new Party(id, partyOwner, partyName, password);
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public static void setPartyOwner(UUID uuid, int id) {
setStringWhereId("UPDATE parties set owner_uuid = ? WHERE id = ?", uuid.toString(), id);
}
public static void setPartyName(String name, int id) {
setStringWhereId("UPDATE parties set party_name = ? WHERE id = ?", name, id);
}
public static void setPartyPassword(String password, int id) {
setStringWhereId("UPDATE parties set password = ? WHERE id = ?", password, id);
}
private static void setStringWhereId(String query, String string, int id) {
try {
Connection connection = DatabaseConnection.getConnection();
PreparedStatement statement = connection.prepareStatement(query);
statement.setString(1, string);
statement.setInt(2, id);
statement.execute();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void removeParty(int id) {
String query = "DELETE FROM parties WHERE id = ?";
try {
Connection connection = DatabaseConnection.getConnection();
PreparedStatement statement = connection.prepareStatement(query);
statement.setInt(1, id);
statement.execute();
} catch (SQLException e) {
e.printStackTrace();
}
}
//-----------------------------------------
private static void getChatUsers(HashMap<Integer, Party> parties) { //TODO Get parties from cache somewhere
String query = "SELECT * FROM chat_users";
try {
Connection connection = DatabaseConnection.getConnection();
ResultSet resultSet = connection.prepareStatement(query).executeQuery();
while (resultSet.next()) {
UUID uuid = UUID.fromString(resultSet.getString("uuid"));
int partyId = resultSet.getInt("party_id");
boolean toggled_chat = resultSet.getInt("toggled_chat") == 1;
boolean force_tp = resultSet.getInt("force_tp") == 1;
boolean toggle_Gc = resultSet.getInt("toggled_gc") == 1;
if (partyId == 0) {
continue;
}
Party party = parties.get(partyId);
if (party == null) {
//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.");
continue;
}
party.addUser(new ChatUser(uuid, partyId, toggled_chat, force_tp, toggle_Gc));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void loadChatUsers() { //TODO Get parties from cache somewhere
String query = "SELECT * FROM chat_users";
try {
Connection connection = DatabaseConnection.getConnection();
ResultSet resultSet = connection.prepareStatement(query).executeQuery();
while (resultSet.next()) {
UUID uuid = UUID.fromString(resultSet.getString("uuid"));
int partyId = resultSet.getInt("party_id");
boolean toggled_chat = resultSet.getInt("toggled_chat") == 1;
boolean force_tp = resultSet.getInt("force_tp") == 1;
boolean toggle_Gc = resultSet.getInt("toggled_gc") == 1;
// could do a constructor for chatuser to accept the record?
ChatUserManager.addUser(new ChatUser(uuid, partyId, toggled_chat, force_tp, toggle_Gc));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void addUser(ChatUser user) {
String query = "INSERT INTO chat_users (uuid, party_id, toggled_chat, force_tp, toggled_gc) VALUES (?, ?, ?, ?, ?)";
try {
Connection connection = DatabaseConnection.getConnection();
PreparedStatement statement = connection.prepareStatement(query);
statement.setString(1, user.getUuid().toString());
statement.setInt(2, user.getPartyId());
statement.setInt(3, user.toggledPartyChat() ? 1 : 0);
statement.setInt(4, user.ForceTp() ? 1 : 0);
statement.setInt(5, user.isGcOn() ? 1 : 0);
statement.execute();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void setPartyChatState(boolean toggledChat, UUID uuid) {
setBitWhereId("UPDATE chat_users set toggled_chat = ? WHERE uuid = ?", toggledChat, uuid);
}
public static void setForceTpState(boolean forceTp, UUID uuid) {
setBitWhereId("UPDATE chat_users set force_tp = ? WHERE uuid = ?", forceTp, uuid);
}
private static void setBitWhereId(String query, boolean bool, UUID uuid) {
try {
Connection connection = DatabaseConnection.getConnection();
PreparedStatement statement = connection.prepareStatement(query);
statement.setInt(1, bool ? 1 : 0);
statement.setString(2, uuid.toString());
statement.execute();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void removeUser(UUID uuid) {
String query = "DELETE FROM chat_users WHERE uuid = ?";
try {
Connection connection = DatabaseConnection.getConnection();
PreparedStatement statement = connection.prepareStatement(query);
statement.setString(1, uuid.toString());
statement.execute();
} catch (SQLException e) {
e.printStackTrace();
}
}
//-----------------------------------------
}
@@ -0,0 +1,40 @@
package com.alttd.chat.managers;
import com.alttd.chat.database.Queries;
import com.alttd.chat.objects.ChatUser;
import com.alttd.chat.objects.Mail;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;
public final class ChatUserManager {
private static CopyOnWriteArrayList<ChatUser> chatUsers;// not sure on this, could cause errors later on
public static void initialize() {
chatUsers = new CopyOnWriteArrayList<>();
Queries.loadChatUsers();
}
public static void addUser(ChatUser user) {
if(getChatUser(user.getUuid()) != null)
chatUsers.add(user);
}
public static ChatUser getChatUser(UUID uuid) {
for(ChatUser user : chatUsers) {
if(user.getUuid() == uuid) {
return user;
}
}
return null;
}
public List<Mail> getUnReadMail(ChatUser user) {
return user.getMails().stream()
.filter(Mail::isUnRead)
.collect(Collectors.toList());
}
}
@@ -0,0 +1,54 @@
package com.alttd.chat.managers;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
// TODO rebuild this class, All regexes go in a single list where we use the ChatFilter object and a matcher
public class RegexManager {
private static final HashMap<Pattern, ArrayList<String>> cancelRegex = new HashMap<>();
private static final HashMap<String, String> replaceRegex = new HashMap<>();
// IDEA: Regex object -> RegexPattern, shatteredPattern, replacement, replacements
public static void initRegex() {
//RegexConfig.init(VelocityChat.getPlugin().getDataDirectory()); // TODO setup the dir
// LOAD REGEXES, sad way of doing it:(
// maiby a REGEXobject and a list<Regex> would be better here?
/*for(ConfigurationNode node : Config.REGEXNODE.getChildrenMap().values()) {
RegexConfig regexConfig = new RegexConfig(node.getString());
if (FilterType.getType(regexConfig.TYPE) == FilterType.BLOCK) {
cancelRegex.put(Pattern.compile(regexConfig.REGEX), Lists.newArrayList(regexConfig.REPLACEMENT));
} else if (FilterType.getType(regexConfig.TYPE) == FilterType.REPLACE) {
replaceRegex.put(regexConfig.REGEX, regexConfig.REPLACEMENT);
}
}*/
//TODO load data from config (a regex string, and it's exceptions if there are any)
cancelRegex.put(Pattern.compile("\\b([R]+[^\\w]?[4A]+[^\\w]?[P]+(([^\\w]?[E3]+[^\\w]?[DT]*)|([^\\w]?[I!1]+[^\\w]?[S5]+[^\\w]?[T7]+)|([^\\w]?[I!1]+[^\\w]?[N]+[^\\w]?[G69]+)))\\b"), new ArrayList<>());
//TODO load data from config (a regex string and what to replace it with)
replaceRegex.put(":pirate:", "pirate");
//TODO we might just be able to throw it all in one list and just go through it and check the type to see what to do if there is a match :eyes:
}
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) {
for (Map.Entry<String, String> entry : replaceRegex.entrySet()) {
text = text.replaceAll(entry.getKey(), entry.getValue());
}
return text;
}
}
@@ -0,0 +1,32 @@
package com.alttd.chat.objects;
public class ChatFilter {
private final String regex;
private final FilterType type;
private String replacement = "";
public ChatFilter(String regex, FilterType type) {
this.regex = regex;
this.type = type;
}
public ChatFilter(String regex, FilterType type, String replacement) {
this.regex = regex;
this.type = type;
this.replacement = replacement;
}
public String getRegex() {
return regex;
}
public FilterType getType() {
return type;
}
public String getReplacement() {
return replacement;
}
}
@@ -0,0 +1,125 @@
package com.alttd.chat.objects;
import com.alttd.chat.database.Queries;
import com.alttd.chat.util.Utility;
import java.util.LinkedList;
import java.util.UUID;
public class ChatUser {
private final UUID uuid;
private final int partyId;
private boolean toggledPartyChat;
private boolean forceTp;
private String displayName;
private String prefix;
private String staffPrefix;
private String prefixAll;
private boolean toggleGc;
private UUID replyTarget;
private LinkedList<Mail> mails;
public ChatUser(UUID uuid, int partyId, boolean toggled_chat, boolean force_tp, boolean toggle_Gc) {
this.uuid = uuid;
this.partyId = partyId;
this.toggledPartyChat = toggled_chat;
this.forceTp = force_tp;
displayName = Queries.getNickname(uuid);
if (displayName == null) {
displayName = Utility.getDisplayName(uuid);
}
prefix = Utility.getPrefix(uuid, true);
staffPrefix = Utility.getStaffPrefix(uuid);
prefixAll = Utility.getPrefix(uuid, false);
toggleGc = toggle_Gc;
replyTarget = null;
mails = new LinkedList<>(); // todo load mails
}
public UUID getUuid() {
return uuid;
}
public int getPartyId() {
return partyId;
}
public boolean toggledPartyChat() {
return toggledPartyChat;
}
public void togglePartyChat() {
toggledPartyChat = !toggledPartyChat;
Queries.setPartyChatState(toggledPartyChat, uuid); //TODO: Async pls - no CompleteableFuture<>!
}
public boolean ForceTp() {
return forceTp;
}
public void toggleForceTp() {
forceTp = !forceTp;
Queries.setForceTpState(forceTp, uuid); //TODO: Async pls - no CompleteableFuture<>!
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getPrefix() {
return prefix;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
public String getStaffPrefix() {
return staffPrefix;
}
public void setStaffPrefix(String staffPrefix) {
this.staffPrefix = staffPrefix;
}
public String getPrefixAll() {
return prefixAll;
}
public void setPrefixAll(String prefixAll) {
this.prefixAll = prefixAll;
}
public void toggleGc() {
toggleGc = !toggleGc;
}
public boolean isGcOn() {
return toggleGc;
}
public UUID getReplyTarget() {
return replyTarget;
}
public void setReplyTarget(UUID replyTarget) {
this.replyTarget = replyTarget;
}
public LinkedList<Mail> getMails() {
return mails;
}
public void addMail(Mail mail) {
mails.add(mail);
}
}
@@ -0,0 +1,22 @@
package com.alttd.chat.objects;
public enum FilterType {
REPLACE("replace"),
BLOCK("block");
private final String name;
FilterType(String name) {
this.name = name;
}
public static FilterType getType(String name) {
for (FilterType type : FilterType.values()) {
if (type.name.equalsIgnoreCase(name)) {
return type;
}
}
return null;
}
}
@@ -0,0 +1,54 @@
package com.alttd.chat.objects;
import java.util.UUID;
public class Mail {
private final UUID uuid; // the player
private final UUID sender; // the sender
private boolean read;
private final long sendTime; // any other option for this? does the db store recordcreation and edit time?
private long readTime; // any other option for this?
private final String message; // do we want staff to edit this after being send but being unread?
public Mail(UUID player, UUID sender, Boolean read, long sendTime, long readTime, String message) {
this.uuid = player;
this.sender = sender;
this.read = read;
this.sendTime = sendTime;
this.readTime = readTime;
this.message = message;
}
public UUID getUuid() {
return uuid;
}
public UUID getSender() {
return sender;
}
public boolean isUnRead() {
return read;
}
public void setRead(boolean read) {
this.read = read;
}
public long getSendTime() {
return sendTime;
}
public long getReadTime() {
return readTime;
}
public void setReadTime(long readTime) {
this.readTime = readTime;
}
public String getMessage() {
return message;
}
}
@@ -0,0 +1,80 @@
package com.alttd.chat.objects;
import com.alttd.chat.database.Queries;
import java.util.ArrayList;
import java.util.UUID;
public class Party {
private final int partyId;
private UUID ownerUuid;
private String partyName;
private String partyPassword;
private ArrayList<ChatUser> partyUsers; //TODO might need to be a map?
public Party(int partyId, UUID ownerUuid, String partyName, String partyPassword) {
this.partyId = partyId;
this.ownerUuid = ownerUuid;
this.partyName = partyName;
this.partyPassword = partyPassword;
partyUsers = new ArrayList<>();
}
public void addUser(ArrayList<ChatUser> partyUsers) {
this.partyUsers.addAll(partyUsers);
}
public void addUser(ChatUser partyUser) {
this.partyUsers.add(partyUser);
Queries.addUser(partyUser);
}
public void removeUser(ChatUser partyUser) {
partyUsers.remove(partyUser);
Queries.removeUser(partyUser.getUuid());
}
public int getPartyId() {
return partyId;
}
public UUID getOwnerUuid() {
return ownerUuid;
}
public void setOwnerUuid(UUID ownerUuid) {
this.ownerUuid = ownerUuid;
Queries.setPartyOwner(ownerUuid, partyId); //TODO: Async pls
}
public String getPartyName() {
return partyName;
}
public void setPartyName(String partyName) {
this.partyName = partyName;
Queries.setPartyName(partyName, partyId); //TODO: Async pls
}
public String getPartyPassword() {
return partyPassword;
}
public void setPartyPassword(String partyPassword) {
this.partyPassword = partyPassword;
Queries.setPartyPassword(partyPassword, partyId); //TODO: Async pls
}
public boolean hasPartyPassword() {
return !partyPassword.isEmpty();
}
public ArrayList<ChatUser> getPartyUsers() {
return partyUsers;
}
public void setPartyUsers(ArrayList<ChatUser> partyUsers) {
this.partyUsers = partyUsers;
}
}
@@ -0,0 +1,26 @@
package com.alttd.chat.util;
public class ALogger {
private static org.slf4j.Logger logger;
public ALogger(org.slf4j.Logger log) {
logger = log;
}
private void log(String message) {
logger.info(message);
}
public static void warn(String message) {
logger.warn(message);
}
public static void info(String message) {
logger.info(message);
}
public static void error(String message) {
logger.error(message);
}
}
@@ -0,0 +1,91 @@
package com.alttd.chat.util;
import com.alttd.chat.ChatAPI;
import com.alttd.chat.config.Config;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import net.luckperms.api.LuckPerms;
import net.luckperms.api.model.group.Group;
import net.luckperms.api.model.user.User;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.UUID;
public class Utility {
public static HashMap<String, String> colors;
static { // this might be in minimessage already?
colors = new HashMap<>(); // todo map all colors to minimessage
colors.put("&0", "<black>"); // and confirm these are correct
colors.put("&1", "<dark_blue>"); // could also add some default hex colors here?
colors.put("&2", "<dark_green>");
colors.put("&3", "<dark_aqua>");
colors.put("&4", "<dark_red>");
colors.put("&5", "<dark_purple>");
colors.put("&6", "<gold>");
colors.put("&7", "<gray>");
colors.put("&8", "<dark_gray>");
colors.put("&9", "<blue>");
colors.put("&a", "<green>");
colors.put("&b", "<aqua>");
colors.put("&c", "<red>");
colors.put("&d", "<light_purple>");
colors.put("&e", "<yellow>");
colors.put("&f", "<white>");
colors.put("&g", "<minecoin_gold>"); // is this a thing?
}
public static String parseColors(String message) {
// split string in sections and check those vs looping hashmap?:/
// think this is better, but will check numbers on this
for (String key : colors.keySet()) {
if (message.contains(key)) {
message = message.replace(key, colors.get(key));
}
}
return message;
}
public static String getPrefix(UUID uuid, boolean highest) {
StringBuilder prefix = new StringBuilder();
LuckPerms luckPerms = ChatAPI.get().getLuckPerms();
User user = luckPerms.getUserManager().getUser(uuid);
if(user == null) return "";
if(!highest) {
Collection<Group> inheritedGroups = user.getInheritedGroups(user.getQueryOptions());
inheritedGroups.stream()
.sorted(Comparator.comparingInt(o -> o.getWeight().orElse(0)))
.forEach(group -> {
if (Config.PREFIXGROUPS.contains(group.getName())) {
prefix.append("<white>[").append(group.getCachedData().getMetaData().getPrefix()).append("]</white>");
}
});
}
LegacyComponentSerializer.builder().character('&').hexColors();
prefix.append("<white>[").append(user.getCachedData().getMetaData().getPrefix()).append("]</white>");
return prefix.toString();
}
// @teri you don't reference the plugin instance from the API instance, this creates a circular reference and breaks on compile and will never run
public static String getStaffPrefix(UUID uuid) {
StringBuilder prefix = new StringBuilder();
LuckPerms luckPerms = ChatAPI.get().getLuckPerms();
User user = luckPerms.getUserManager().getUser(uuid);
if(user == null) return prefix.toString();
if(user.getCachedData().getPermissionData().checkPermission("group." + Config.MINIMIUMSTAFFRANK).asBoolean()) {
prefix.append("<white>[").append(user.getCachedData().getMetaData().getPrefix()).append("]</white>");
}
return prefix.toString();
}
public static String getDisplayName(UUID uuid) {
StringBuilder prefix = new StringBuilder();
LuckPerms luckPerms = ChatAPI.get().getLuckPerms();
User user = luckPerms.getUserManager().getUser(uuid);
if(user == null) return "";
return user.getUsername();
}
}