Updated to 1.21 by switching to cosmos

This commit is contained in:
2025-06-21 00:53:55 +02:00
parent 1dd19f0543
commit fc7860145f
40 changed files with 965 additions and 1015 deletions
@@ -1,10 +1,11 @@
package com.alttd.chat.config;
import com.alttd.chat.objects.channels.CustomChannel;
import com.alttd.chat.util.ALogger;
import com.alttd.chat.util.Utility;
import com.google.common.collect.Lists;
import io.leangen.geantyref.TypeToken;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.ComponentLike;
import org.spongepowered.configurate.ConfigurationNode;
import org.spongepowered.configurate.ConfigurationOptions;
import org.spongepowered.configurate.serialize.SerializationException;
@@ -19,6 +20,7 @@ import java.lang.reflect.Modifier;
import java.util.*;
import java.util.regex.Pattern;
@SuppressWarnings("unused")
public final class Config {
private static final Pattern PATH_PATTERN = Pattern.compile("\\.");
private static final String HEADER = "";
@@ -31,6 +33,7 @@ public final class Config {
static boolean verbose;
public static File CONFIGPATH;
public static void init() {
CONFIGPATH = new File(File.separator + "mnt" + File.separator + "configs" + File.separator + "ChatPlugin");
CONFIG_FILE = new File(CONFIGPATH, "config.yml");
@@ -39,24 +42,24 @@ public final class Config {
.nodeStyle(NodeStyle.BLOCK)
.build();
if (!CONFIG_FILE.getParentFile().exists()) {
if(!CONFIG_FILE.getParentFile().mkdirs()) {
if (!CONFIG_FILE.getParentFile().mkdirs()) {
return;
}
}
if (!CONFIG_FILE.exists()) {
try {
if(!CONFIG_FILE.createNewFile()) {
if (!CONFIG_FILE.createNewFile()) {
return;
}
} catch (IOException error) {
error.printStackTrace();
ALogger.error(error.getMessage(), error);
}
}
try {
config = configLoader.load(ConfigurationOptions.defaults().header(HEADER).shouldCopyDefaults(false));
} catch (IOException e) {
e.printStackTrace();
ALogger.error(e.getMessage(), e);
}
verbose = getBoolean("verbose", true);
@@ -66,7 +69,7 @@ public final class Config {
try {
configLoader.save(config);
} catch (IOException e) {
e.printStackTrace();
ALogger.error(e.getMessage(), e);
}
}
@@ -78,7 +81,7 @@ public final class Config {
method.setAccessible(true);
method.invoke(instance);
} catch (InvocationTargetException | IllegalAccessException ex) {
ex.printStackTrace();
ALogger.error(ex.getMessage(), ex);
}
}
}
@@ -86,7 +89,7 @@ public final class Config {
try {
configLoader.save(config);
} catch (IOException ex) {
ex.printStackTrace();
ALogger.error(ex.getMessage(), ex);
}
}
@@ -94,7 +97,7 @@ public final class Config {
try {
configLoader.save(config);
} catch (IOException ex) {
ex.printStackTrace();
ALogger.error(ex.getMessage(), ex);
}
}
@@ -103,21 +106,22 @@ public final class Config {
}
private static void set(String path, Object def) {
if(config.node(splitPath(path)).virtual()) {
if (config.node(splitPath(path)).virtual()) {
try {
config.node(splitPath(path)).set(def);
} catch (SerializationException e) {
e.printStackTrace();
ALogger.error(e.getMessage(), e);
}
}
}
private static void setString(String path, String def) {
try {
if(config.node(splitPath(path)).virtual())
if (config.node(splitPath(path)).virtual()) {
config.node(splitPath(path)).set(io.leangen.geantyref.TypeToken.get(String.class), def);
} catch(SerializationException ex) {
ex.printStackTrace();
}
} catch (SerializationException ex) {
ALogger.error(ex.getMessage(), ex);
}
}
@@ -150,21 +154,23 @@ public final class Config {
try {
set(path, def);
return config.node(splitPath(path)).getList(TypeToken.get(String.class));
} catch(SerializationException ex) {
ex.printStackTrace();
} catch (SerializationException ex) {
ALogger.error(ex.getMessage(), ex);
}
return new ArrayList<>();
}
private static ConfigurationNode getNode(String path) {
if(config.node(splitPath(path)).virtual()) {
if (config.node(splitPath(path)).virtual()) {
//new RegexConfig("Dummy");
}
config.childrenMap();
return config.node(splitPath(path));
}
/** ONLY EDIT ANYTHING BELOW THIS LINE **/
/**
* ONLY EDIT ANYTHING BELOW THIS LINE
**/
public static List<String> PREFIXGROUPS = new ArrayList<>();
public static List<String> CONFLICTINGPREFIXGROUPS = new ArrayList<>();
public static List<String> STAFFGROUPS = new ArrayList<>();
@@ -173,13 +179,14 @@ public final class Config {
public static UUID CONSOLEUUID = UUID.randomUUID();
public static int EMOTELIMIT = 3;
public static String MENTIONPLAYERTAG = "<aqua>@</aqua>";
private static void settings() {
PREFIXGROUPS = getList("settings.prefix-groups",
Lists.newArrayList("discord", "socialmedia", "eventteam", "eventleader", "youtube", "twitch", "developer"));
Lists.newArrayList("discord", "socialmedia", "eventteam", "eventleader", "youtube", "twitch", "developer"));
CONFLICTINGPREFIXGROUPS = getList("settings.prefix-conflicts-groups",
Lists.newArrayList("eventteam", "eventleader"));
Lists.newArrayList("eventteam", "eventleader"));
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);
CONSOLEUUID = UUID.fromString(getString("settings.console-uuid", CONSOLEUUID.toString()));
MINIMIUMSTAFFRANK = getString("settings.minimum-staff-rank", MINIMIUMSTAFFRANK);
@@ -193,6 +200,7 @@ public final class Config {
public static String MESSAGERECIEVER = "<hover:show_text:Click to reply><click:suggest_command:/msg <sendername> ><light_purple>(<gray><sender></gray> on <server> -> Me)</hover> <message>";
public static String MESSAGESPY = "<gray>(<gray><sendername></gray> -> <receivername>) <message>";
public static String RECEIVER_DOES_NOT_EXIST = "<red><player> is not a valid player.</red>";
private static void messageCommand() {
MESSAGECOMMANDALIASES.clear();
REPLYCOMMANDALIASES.clear();
@@ -210,6 +218,7 @@ public final class Config {
public static String GCNOTENABLED = "You don't have global chat enabled.";
public static String GCONCOOLDOWN = "You have to wait <cooldown> seconds before using this feature again.";
public static int GCCOOLDOWN = 30;
private static void globalChat() {
GCFORMAT = getString("commands.globalchat.format", GCFORMAT);
GCPERMISSION = getString("commands.globalchat.view-chat-permission", GCPERMISSION);
@@ -221,6 +230,7 @@ public final class Config {
public static String CHATFORMAT = "<white><light_purple><prefixall> <gray><hover:show_text:Click to message <sendername>><click:suggest_command:/msg <sendername> ><sender></hover>: <white><message>";
public static String URLFORMAT = "<click:OPEN_URL:<clickurl>><url></click>";
private static void Chat() {
CHATFORMAT = getString("chat.format", CHATFORMAT);
URLFORMAT = getString("chat.urlformat", URLFORMAT);
@@ -228,17 +238,20 @@ public final class Config {
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)</hover> <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");
}
@@ -247,6 +260,7 @@ public final class Config {
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);
@@ -260,7 +274,7 @@ public final class Config {
public static String NO_PERMISSION = "<red>You don't have permission to use this command.</red>";
public static String NO_CONSOLE = "<red>This command can not be used by console</red>";
public static String CREATED_PARTY = "<green>You created a chat party called: " +
"'<gold><party_name></gold>' with the password: '<gold><party_password></gold>'</green>";
"'<gold><party_name></gold>' with the password: '<gold><party_password></gold>'</green>";
public static String NOT_IN_A_PARTY = "<red>You're not in a chat party.</red>";
public static String NOT_YOUR_PARTY = "<red>You don't own this chat party.</red>";
public static String NOT_A_PARTY = "<red>This chat party does not exist.</red>";
@@ -283,23 +297,24 @@ public final class Config {
public static String ALREADY_IN_THIS_PARTY = "<red>You're already in <party>!</red>";
public static String SENT_PARTY_INV = "<green>You send a chat party invite to <player>!</green>";
public static String JOIN_PARTY_CLICK_MESSAGE = "<click:run_command:'/party join <party> <party_password>'>" +
"<dark_aqua>You received an invite to join <party>, click this message to accept.</dark_aqua></click>";
"<dark_aqua>You received an invite to join <party>, click this message to accept.</dark_aqua></click>";
public static String PARTY_MEMBER_LOGGED_ON = "<dark_aqua>[ChatParty] <player> joined Altitude...</dark_aqua>";
public static String PARTY_MEMBER_LOGGED_OFF = "<dark_aqua>[ChatParty] <player> left Altitude...</dark_aqua>";
public static String RENAMED_PARTY = "<dark_aqua>[ChatParty] <owner> changed the party name from <old_name> to <new_name>!</dark_aqua>";
public static String CHANGED_PASSWORD = "<green>Password was set to <password></green>";
public static String DISBAND_PARTY_CONFIRM = "<green><bold>Are you sure you want to disband your party?</bold> " +
"Type <gold>/party disband confirm <party></gold> to confirm.";
"Type <gold>/party disband confirm <party></gold> to confirm.";
public static String DISBANDED_PARTY = "<dark_aqua>[ChatParty] <owner> has disbanded <party>, everyone has been removed.</dark_aqua>";
public static String PARTY_INFO = """
<gold><bold>Chat party info</bold>:
</gold><green>Name: <dark_aqua><party></dark_aqua>
Password: <dark_aqua><password></dark_aqua>
Owner: <owner>
Members: <members>""";
public static Component ONLINE_PREFIX = null;
public static Component OFFLINE_PREFIX = null;
<gold><bold>Chat party info</bold>:
</gold><green>Name: <dark_aqua><party></dark_aqua>
Password: <dark_aqua><password></dark_aqua>
Owner: <owner>
Members: <members>""";
public static ComponentLike ONLINE_PREFIX = null;
public static ComponentLike OFFLINE_PREFIX = null;
public static String PARTY_TOGGLED = "<dark_aqua>Party chat toggled <status>.</dark_aqua>";
private static void party() {
PARTY_FORMAT = getString("party.format", PARTY_FORMAT);
PARTY_SPY = getString("party.spy", PARTY_SPY);
@@ -349,6 +364,7 @@ public final class Config {
public static String PARTY_HELP_REMOVE = "<green>Remove a member from your party: <gold>/party remove <member_name></gold></green>";
public static String PARTY_HELP_DISBAND = "<green>Remove everyone from your party and disband it: <gold>/party disband</gold></green>";
public static String PARTY_HELP_CHAT = "<green>Talk in party chat: <gold>/p <message></gold></green>";
private static void partyHelp() {
PARTY_HELP_WRAPPER = getString("party.help.wrapper", PARTY_HELP_WRAPPER);
PARTY_HELP_HELP = getString("party.help.help", PARTY_HELP_HELP);
@@ -366,10 +382,11 @@ public final class Config {
}
public static String CUSTOM_CHANNEL_TOGGLED = "<yellow>Toggled <channel> <status>.</yellow>";
public static Component TOGGLED_ON = null;
public static Component TOGGLED_OFF = null;
public static ComponentLike TOGGLED_ON = null;
public static ComponentLike TOGGLED_OFF = null;
public static double LOCAL_DISTANCE;
public static String CHANNEL_SPY = "<i><gray>SPY:</gray> <dark_gray>(<dark_gray><sender> → <channel>) <message></dark_gray>";
private static void chatChannels() {
ConfigurationNode node = getNode("chat-channels");
if (node.empty()) {
@@ -383,10 +400,10 @@ public final class Config {
String channelName = Objects.requireNonNull(configurationNode.key()).toString();
String key = "chat-channels." + channelName + ".";
new CustomChannel(channelName,
getString(key + "format", ""),
getList(key + "servers", Collections.EMPTY_LIST),
getBoolean(key + "proxy", false),
getBoolean(key + "local", false)
getString(key + "format", ""),
getList(key + "servers", Collections.EMPTY_LIST),
getBoolean(key + "proxy", false),
getBoolean(key + "local", false)
);
}
@@ -399,6 +416,7 @@ public final class Config {
public static String SERVERMUTEPERMISSION = "chat.command.mute-server";
public static String SPYPERMISSION = "chat.socialspy";
private static void permissions() {
SERVERMUTEPERMISSION = getString("permissions.server-mute", SERVERMUTEPERMISSION);
SPYPERMISSION = getString("permissions.spy-permission", SPYPERMISSION);
@@ -409,6 +427,7 @@ public final class Config {
public static String DATABASE = "database";
public static String USERNAME = "root";
public static String PASSWORD = "root";
private static void database() {
IP = getString("database.ip", IP);
PORT = getString("database.port", PORT);
@@ -418,6 +437,7 @@ public final class Config {
}
public static String NOTIFICATIONFORMAT = "<red>[<prefix>] <displayname> <target> <input>";
private static void notificationSettings() {
NOTIFICATIONFORMAT = getString("settings.blockedmessage-notification", NOTIFICATIONFORMAT);
}
@@ -431,6 +451,7 @@ public final class Config {
public static String mailSent = "<green>Successfully send mail to <player_name></green>: <#2e8b57><message></#2e8b57>";
public static List<String> mailCommandAlias = new ArrayList<>();
public static int mailDisplayDelay = 5;
private static void mailSettings() {
mailHeader = getString("settings.mail.header", mailHeader);
mailBody = getString("settings.mail.message", mailBody);
@@ -445,6 +466,7 @@ public final class Config {
public static HashMap<String, Long> serverChannelId = new HashMap<>();
public static String REPORT_SENT = "<green>Your report was sent, staff will contact you asap to help resolve your issue!</green>";
public static String REPORT_TOO_SHORT = "<red>Please ensure your report is descriptive. We require at least 3 words per report</red>";
private static void loadChannelIds() {
serverChannelId.clear();
serverChannelId.put("general", getLong("discord-channel-id.general", (long) -1));
@@ -452,8 +474,9 @@ public final class Config {
Map<Object, ? extends ConfigurationNode> objectMap = node.childrenMap();
for (Object o : objectMap.keySet()) {
String key = (String) o;
if (key.equalsIgnoreCase("general"))
if (key.equalsIgnoreCase("general")) {
continue;
}
ConfigurationNode configurationNode = objectMap.get(o);
long channelId = configurationNode.getLong();
serverChannelId.put(key.toLowerCase(), channelId);
@@ -478,6 +501,7 @@ public final class Config {
public static String HELP_REPORT = "<red>/report <message></red>";
public static String FIRST_JOIN = "<green>* Welcome <light_purple><player></light_purple> to Altitude! They've joined for the first time.</green>";
private static void loadMessages() {
HELP_REPORT = getString("settings.mail.mail-sent", HELP_REPORT);
FIRST_JOIN = getString("settings.first-join.message", FIRST_JOIN);
@@ -486,6 +510,7 @@ public final class Config {
public static String EMOTELIST_HEADER = "<bold>Available Chat Emotes</bold><newline>";
public static String EMOTELIST_ITEM = "<insert:\"<regex>\"><gold><regex></gold> : <emote></insert><newline>";
public static String EMOTELIST_FOOTER = "<green>----<< <gray>Prev</gray> <page> <gray>/</gray> <pages> <gray>Next</gray> >>----";
private static void emoteListCommand() {
EMOTELIST_HEADER = getString("commands.emotelist.header", EMOTELIST_HEADER);
EMOTELIST_ITEM = getString("commands.emotelist.item", EMOTELIST_ITEM);
@@ -521,6 +546,7 @@ public final class Config {
public static List<String> NICK_BLOCKED_COLOR_CODESLIST = new ArrayList<>();
public static List<String> NICK_ALLOWED_COLOR_CODESLIST = new ArrayList<>();
public static String NICK_CURRENT = "<gold>Current nickname: <nickname><white>(<insert:\"<currentnickname>\"><currentnickname></insert>)";
private static void nicknameSettings() {
NICK_CHANGED = getString("nicknames.messages.nick-changed", NICK_CHANGED);
NICK_NOT_CHANGED = getString("nicknames.messages.nick-not-changed", NICK_NOT_CHANGED);
@@ -3,7 +3,7 @@ package com.alttd.chat.objects;
import com.alttd.chat.database.Queries;
import com.alttd.chat.objects.channels.Channel;
import com.alttd.chat.util.Utility;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.ComponentLike;
import java.util.ArrayList;
import java.util.List;
@@ -13,20 +13,20 @@ import java.util.stream.Collectors;
public class ChatUser {
private final UUID uuid; // player uuid
private int partyId; // the party they are in
private Channel toggledChannel;
private final Channel toggledChannel;
private String name; // the nickname, doesn't need to be saved with the chatuser object, could be saved but we can get it from the nicknamesview
private Component displayName; // the nickname, doesn't need to be saved with the chatuser object, could be saved but we can get it from the nicknamesview
// private Component prefix; // doesn't need saving, we get this from luckperms
// private Component staffPrefix; // doesn't need saving, we get this from luckperms
// private Component prefixAll; // doesn't need saving, we get this from luckperms
private ComponentLike displayName; // the nickname, doesn't need to be saved with the chatuser object, could be saved but we can get it from the nicknamesview
// private Component prefix; // doesn't need saving, we get this from luckperms
// private Component staffPrefix; // doesn't need saving, we get this from luckperms
// private Component prefixAll; // doesn't need saving, we get this from luckperms
//private boolean toggleGc; // should be saved, this toggles if the player can see and use global chat
private String replyTarget; // reply target for use in /msg i don't mind setting this to null on login, feedback?
private String replyContinueTarget; // reply target for use in /c
private long gcCooldown; // the time when they last used gc, is used for the cooldown, i wouldn't save this, but setting this to the login time means they can't use gc for 30 seconds after logging in
private boolean spy;
private List<Mail> mails; // mails aren't finalized yet, so for now a table sender, reciever, sendtime, readtime(if emtpy mail isn't read yet?, could also do a byte to control this), the actual message
private List<UUID> ignoredPlayers; // a list of UUID, a new table non unique, where one is is the player select * from ignores where ignoredby = thisplayer? where the result is the uuid of the player ignored by this player?
private List<UUID> ignoredBy; // a list of UUID, same table as above but select * from ignores where ignored = thisplayer? result should be the other user that ignored this player?
private final List<Mail> mails; // mails aren't finalized yet, so for now a table sender, reciever, sendtime, readtime(if emtpy mail isn't read yet?, could also do a byte to control this), the actual message
private final List<UUID> ignoredPlayers; // a list of UUID, a new table non unique, where one is is the player select * from ignores where ignoredby = thisplayer? where the result is the uuid of the player ignored by this player?
private final List<UUID> ignoredBy; // a list of UUID, same table as above but select * from ignores where ignored = thisplayer? result should be the other user that ignored this player?
private boolean isMuted;
public ChatUser(UUID uuid, int partyId, Channel toggledChannel) {
@@ -40,10 +40,10 @@ public class ChatUser {
}
setDisplayName(name);
// prefix = Utility.getPrefix(uuid, true); // TODO we need to update this, so cache and update when needed or always request it?
// staffPrefix = Utility.getStaffPrefix(uuid);
//
// prefixAll = Utility.getPrefix(uuid, false);
// prefix = Utility.getPrefix(uuid, true); // TODO we need to update this, so cache and update when needed or always request it?
// staffPrefix = Utility.getStaffPrefix(uuid);
//
// prefixAll = Utility.getPrefix(uuid, false);
replyTarget = "";
replyContinueTarget = "";
@@ -71,12 +71,7 @@ public class ChatUser {
return toggledChannel;
}
public void setToggledChannel(Channel channel) {
toggledChannel = channel;
Queries.setToggledChannel(toggledChannel, uuid); //TODO: Async pls - no CompleteableFuture<>!
}
public Component getDisplayName() {
public ComponentLike getDisplayName() {
return displayName;
}
@@ -84,17 +79,17 @@ public class ChatUser {
this.displayName = Utility.applyColor(displayName);
}
public Component getPrefix() {
public ComponentLike getPrefix() {
//return prefix;
return Utility.getPrefix(uuid, true); // No longer cache this data
}
public Component getStaffPrefix() {
public ComponentLike getStaffPrefix() {
//return staffPrefix;
return Utility.getStaffPrefix(uuid);
}
public Component getPrefixAll() {
public ComponentLike getPrefixAll() {
//return prefixAll;
return Utility.getPrefix(uuid, false);
}
@@ -145,10 +140,6 @@ public class ChatUser {
return ignoredBy;
}
public void addIgnoredBy(UUID uuid) {
ignoredBy.add(uuid);
}
public long getGcCooldown() {
return gcCooldown;
}
@@ -4,9 +4,9 @@ import com.alttd.chat.config.Config;
import com.alttd.chat.managers.RegexManager;
import com.alttd.chat.util.Utility;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.ComponentLike;
import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder;
import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver;
import org.bukkit.Bukkit;
import java.util.HashMap;
import java.util.Map;
@@ -16,7 +16,7 @@ public class EmoteList {
public static final Map<UUID, EmoteList> emoteLists = new HashMap<>();
public static final int pageSize = 7;
// public static int pages = RegexManager.getEmoteFilters().size() / pageSize;// TODO reload this when config is reloaded.
// public static int pages = RegexManager.getEmoteFilters().size() / pageSize;// TODO reload this when config is reloaded.
public static EmoteList getEmoteList(UUID uuid) {
synchronized (emoteLists) {
@@ -25,22 +25,23 @@ public class EmoteList {
}
private int page;
public Component showEmotePage() {
public ComponentLike showEmotePage() {
int startIndex = page * pageSize;
int pages = RegexManager.getEmoteFilters().size() / pageSize;
int endIndex = Math.min(startIndex + pageSize, RegexManager.getEmoteFilters().size());
TagResolver placeholders = TagResolver.resolver(
Placeholder.unparsed("page", String.valueOf(page)),
Placeholder.unparsed("pages", String.valueOf(pages))
);
Component list = Utility.parseMiniMessage(Config.EMOTELIST_HEADER, placeholders);
);
Component list = Utility.parseMiniMessage(Config.EMOTELIST_HEADER, placeholders).asComponent();
for (int i = startIndex; i < endIndex; i++) {
ChatFilter emote = RegexManager.getEmoteFilters().get(i);
TagResolver emotes = TagResolver.resolver(
Placeholder.parsed("regex", emote.getRegex()),
Placeholder.parsed("emote", emote.getReplacement())
);
);
list = list.append(Utility.parseMiniMessage(Config.EMOTELIST_ITEM, emotes));
}
list = list.append(Utility.parseMiniMessage(Config.EMOTELIST_FOOTER, placeholders));
@@ -60,5 +61,4 @@ public class EmoteList {
this.page = Math.max(page - 1, 0);
}
}
@@ -3,10 +3,6 @@ package com.alttd.chat.objects;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TextReplacementConfig;
import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
import org.intellij.lang.annotations.RegExp;
import javax.annotation.RegEx;
import java.util.regex.Pattern;
public class ModifiableString {
private Component text;
@@ -1,21 +1,21 @@
package com.alttd.chat.objects;
import com.alttd.chat.util.Utility;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.ComponentLike;
import java.util.UUID;
public class PartyUser {
protected UUID uuid;
protected Component displayName;
protected ComponentLike displayName;
protected String playerName;
public PartyUser(UUID uuid, String displayName, String playerName) {
this(uuid, Utility.applyColor(displayName), playerName);
}
public PartyUser(UUID uuid, Component displayName, String playerName) {
public PartyUser(UUID uuid, ComponentLike displayName, String playerName) {
this.uuid = uuid;
this.displayName = displayName;
this.playerName = playerName;
@@ -25,7 +25,7 @@ public class PartyUser {
return uuid;
}
public Component getDisplayName() {
public ComponentLike getDisplayName() {
return displayName;
}
@@ -3,11 +3,11 @@ package com.alttd.chat.util;
import com.alttd.chat.ChatAPI;
import com.alttd.chat.config.Config;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.ComponentLike;
import net.kyori.adventure.text.format.TextDecoration;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver;
import net.kyori.adventure.text.minimessage.tag.standard.StandardTags;
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;
@@ -16,19 +16,17 @@ import net.luckperms.api.node.Node;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class Utility {
private static final List<String> EMPTY_LIST = new ArrayList<>();
static final Pattern DEFAULT_URL_PATTERN = Pattern.compile("(https?://)?[-a-zA-Z0-9@:%._+~#=]{1,256}\\.[a-zA-Z0-9()]{1,6}\\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)");
static final Pattern URL_SCHEME_PATTERN = Pattern.compile("^[a-z][a-z0-9+\\-.]*:");
private static MiniMessage miniMessage = null;
public static String stringRegen = "\\{#[A-Fa-f0-9]{6}(<)?(>)?}";
public static HashMap<String, String> colors;
private static LegacyComponentSerializer legacySerializer;
static { // this might be in minimessage already?
colors = new HashMap<>();
colors.put("&0", "<black>");
@@ -48,41 +46,44 @@ public class Utility {
colors.put("&e", "<yellow>");
colors.put("&f", "<white>");
}
public static HashMap<String, Pair<TagResolver, List<String>>> formattingPerms = new HashMap<>();
static {
formattingPerms.put("chat.format.color",
new Pair<>(StandardTags.color(), colors.values().stream().toList()));
new Pair<>(StandardTags.color(), colors.values().stream().toList()));
formattingPerms.put("chat.format.bold",
new Pair<>(StandardTags.decorations(TextDecoration.BOLD), List.of("<bold>", "<b>")));
new Pair<>(StandardTags.decorations(TextDecoration.BOLD), List.of("<bold>", "<b>")));
formattingPerms.put("chat.format.italic",
new Pair<>(StandardTags.decorations(TextDecoration.ITALIC), List.of("<italic>", "<i>")));
new Pair<>(StandardTags.decorations(TextDecoration.ITALIC), List.of("<italic>", "<i>")));
formattingPerms.put("chat.format.underlined",
new Pair<>(StandardTags.decorations(TextDecoration.UNDERLINED), List.of("<underlined>", "<u>")));
new Pair<>(StandardTags.decorations(TextDecoration.UNDERLINED), List.of("<underlined>", "<u>")));
formattingPerms.put("chat.format.strikethrough",
new Pair<>(StandardTags.decorations(TextDecoration.STRIKETHROUGH), List.of("<strikethrough>", "<st>")));
new Pair<>(StandardTags.decorations(TextDecoration.STRIKETHROUGH), List.of("<strikethrough>", "<st>")));
formattingPerms.put("chat.format.obfuscated",
new Pair<>(StandardTags.decorations(TextDecoration.OBFUSCATED), List.of("<obfuscated>", "<obf>")));
new Pair<>(StandardTags.decorations(TextDecoration.OBFUSCATED), List.of("<obfuscated>", "<obf>")));
formattingPerms.put("chat.format.gradient",
new Pair<>(StandardTags.gradient(), EMPTY_LIST));
new Pair<>(StandardTags.gradient(), EMPTY_LIST));
formattingPerms.put("chat.format.font",
new Pair<>(StandardTags.font(), EMPTY_LIST));
new Pair<>(StandardTags.font(), EMPTY_LIST));
formattingPerms.put("chat.format.rainbow",
new Pair<>(StandardTags.rainbow(), List.of("<rainbow>")));
new Pair<>(StandardTags.rainbow(), List.of("<rainbow>")));
formattingPerms.put("chat.format.hover",
new Pair<>(StandardTags.hoverEvent(), EMPTY_LIST));
new Pair<>(StandardTags.hoverEvent(), EMPTY_LIST));
formattingPerms.put("chat.format.click",
new Pair<>(StandardTags.clickEvent(), EMPTY_LIST));
new Pair<>(StandardTags.clickEvent(), EMPTY_LIST));
formattingPerms.put("chat.format.transition",
new Pair<>(StandardTags.transition(), EMPTY_LIST));
new Pair<>(StandardTags.transition(), EMPTY_LIST));
formattingPerms.put("chat.format.reset",
new Pair<>(StandardTags.reset(), List.of("<reset>", "<r>")));
new Pair<>(StandardTags.reset(), List.of("<reset>", "<r>")));
formattingPerms.put("chat.format.newline",
new Pair<>(StandardTags.newline(), List.of("<newline>")));
new Pair<>(StandardTags.newline(), List.of("<newline>")));
}
public static String parseColors(String message) {
if (message == null) return "";
if (message == null) {
return "";
}
// 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()) {
@@ -93,15 +94,17 @@ public class Utility {
return message;
}
public static Component getPrefix(UUID uuid, boolean single) {
public static ComponentLike getPrefix(UUID uuid, boolean single) {
StringBuilder prefix = new StringBuilder();
LuckPerms luckPerms = ChatAPI.get().getLuckPerms();
User user = luckPerms.getUserManager().getUser(uuid);
List<String> prefixGroups = Config.PREFIXGROUPS;
if(user == null) return Component.empty();
if(!single) {
if (user == null) {
return Component.empty();
}
if (!single) {
Collection<Group> inheritedGroups = user.getInheritedGroups(user.getQueryOptions());
if(inheritedGroups.stream().map(Group::getName).collect(Collectors.toList()).contains("eventleader")) {
if (inheritedGroups.stream().anyMatch(group -> group.getName().equals("eventleader"))) {
prefixGroups.remove("eventteam"); // hardcoded for now, new prefix system would load this from config
}
inheritedGroups.stream()
@@ -113,21 +116,23 @@ public class Utility {
});
}
prefix.append(getUserPrefix(user));
// prefix.append(user.getCachedData().getMetaData().getPrefix());
return applyColor(prefix.toString());
}
public static Component getStaffPrefix(UUID uuid) {
public static ComponentLike getStaffPrefix(UUID uuid) {
StringBuilder prefix = new StringBuilder();
LuckPerms luckPerms = ChatAPI.get().getLuckPerms();
User user = luckPerms.getUserManager().getUser(uuid);
if(user == null) return Component.empty();
if(user.getCachedData().getPermissionData().checkPermission("group." + Config.MINIMIUMSTAFFRANK).asBoolean()) {
if (user == null) {
return Component.empty();
}
if (user.getCachedData().getPermissionData().checkPermission("group." + Config.MINIMIUMSTAFFRANK).asBoolean()) {
Group group = luckPerms.getGroupManager().getGroup(user.getPrimaryGroup());
if(group != null)
if (group != null) {
prefix.append(getGroupPrefix(group));
// prefix.append(group.getCachedData().getMetaData().getPrefix());
}
// prefix.append(group.getCachedData().getMetaData().getPrefix());
}
return applyColor(prefix.toString());
}
@@ -138,26 +143,32 @@ public class Utility {
if (group == null) {
return "";
}
return ChatAPI.get().getPrefixes().get(group.getName()).replace("<prefix>", user.getCachedData().getMetaData().getPrefix());
}
public static String getGroupPrefix(String groupName) {
Group group = ChatAPI.get().getLuckPerms().getGroupManager().getGroup(groupName);
if (group == null) {
String prefix = user.getCachedData().getMetaData().getPrefix();
if (prefix == null) {
ALogger.warn("User " + user.getUsername() + " has no prefix set!");
return "";
}
return getGroupPrefix(group);
return ChatAPI.get().getPrefixes().get(group.getName()).replace("<prefix>", prefix);
}
public static String getGroupPrefix(Group group) {
return ChatAPI.get().getPrefixes().get(group.getName()).replace("<prefix>", group.getCachedData().getMetaData().getPrefix());
String prefix = group.getCachedData().getMetaData().getPrefix();
if (prefix == null) {
ALogger.warn("Group " + group.getName() + " has no prefix set!");
return "";
}
return ChatAPI.get().getPrefixes().get(group.getName()).replace("<prefix>", prefix);
}
public static String getDisplayName(UUID uuid, String playerName) {
if (!playerName.isBlank()) return playerName;
if (!playerName.isBlank()) {
return playerName;
}
LuckPerms luckPerms = ChatAPI.get().getLuckPerms();
User user = luckPerms.getUserManager().getUser(uuid);
if(user == null) return "";
if (user == null) {
return "";
}
return user.getUsername();
}
@@ -165,20 +176,22 @@ public class Utility {
ChatAPI.get().getLuckPerms().getUserManager().modifyUser(uuid, user -> {
// Add the permission
user.data().add(Node.builder(permission)
.value(!user.getCachedData().getPermissionData().checkPermission(permission).asBoolean()).build());
.value(!user.getCachedData().getPermissionData().checkPermission(permission).asBoolean()).build());
});
}
public static boolean hasPermission(UUID uuid, String permission) {
LuckPerms luckPerms = ChatAPI.get().getLuckPerms();
User user = luckPerms.getUserManager().getUser(uuid);
if(user == null) return false;
if (user == null) {
return false;
}
return user.getCachedData().getPermissionData().checkPermission(permission).asBoolean();
}
public static Component applyColor(String message) {
public static ComponentLike applyColor(String message) {
String hexColor1 = "";
String hexColor2 = "";
String hexColor2;
StringBuilder stringBuilder = new StringBuilder();
message = parseColors(message);
boolean startsWithColor = false;
@@ -196,7 +209,7 @@ public class Utility {
for (String s : split) {
nextIndex += s.length();
int tmp = message.indexOf("}", nextIndex);
if (tmp < message.length() && tmp>=0) {
if (tmp < message.length() && tmp >= 0) {
list.add(message.substring(nextIndex, tmp + 1));
nextIndex = tmp + 1;
}
@@ -220,7 +233,7 @@ public class Utility {
} else if (bigger || lesser) {
hexColor2 = s.substring(1, s.length() - 2);
} else {
hexColor2 = s.substring(1, s.length() -1);
hexColor2 = s.substring(1, s.length() - 1);
}
if (firstLoop) {
@@ -241,12 +254,12 @@ public class Utility {
lastColorMatters = bigger;
i++;
}
if (split.length > i){
if (split.length > i) {
stringBuilder.append("<").append(hexColor1).append(">").append(split[i]);
}
}
return stringBuilder.length() == 0 ? Utility.parseMiniMessage(message)
: Utility.parseMiniMessage(stringBuilder.toString());
return stringBuilder.isEmpty() ? Utility.parseMiniMessage(message)
: Utility.parseMiniMessage(stringBuilder.toString());
}
public static boolean checkNickBrightEnough(String nickname) {
@@ -294,10 +307,9 @@ public class Utility {
Matcher matcher = DEFAULT_URL_PATTERN.matcher(message);
while (matcher.find()) {
String url = matcher.group();
String displayUrl = url;
String urlFormat = Config.URLFORMAT;
message = message.replace(url, urlFormat
.replaceAll("<url>", "<u>" + displayUrl + "</u>")
.replaceAll("<url>", "<u>" + url + "</u>")
.replaceAll("<clickurl>", formatUrl(url)));
}
return message;
@@ -310,11 +322,11 @@ public class Utility {
return "https://" + url;
}
public static Component parseMiniMessage(String message) {
public static ComponentLike parseMiniMessage(String message) {
return getMiniMessage().deserialize(message);
}
public static Component parseMiniMessage(String message, TagResolver placeholders) {
public static ComponentLike parseMiniMessage(String message, TagResolver placeholders) {
if (placeholders == null) {
return getMiniMessage().deserialize(message);
} else {
@@ -322,7 +334,7 @@ public class Utility {
}
}
public static Component parseMiniMessage(String message, TagResolver ... placeholders) {
public static ComponentLike parseMiniMessage(String message, TagResolver... placeholders) {
if (placeholders == null) {
return getMiniMessage().deserialize(message);
} else {
@@ -335,7 +347,9 @@ public class Utility {
}
public static MiniMessage getMiniMessage() {
if (miniMessage == null) miniMessage = MiniMessage.miniMessage();
if (miniMessage == null) {
miniMessage = MiniMessage.miniMessage();
}
return miniMessage;
}