Allow prefix data to be loaded from PrefixConfig

This commit is contained in:
destro174 2021-08-19 00:59:37 +02:00
parent 090ae5c438
commit a35ad9ebeb
7 changed files with 205 additions and 68 deletions

View File

@ -3,7 +3,9 @@ package com.alttd.chat;
import com.alttd.chat.database.DatabaseConnection;
import net.luckperms.api.LuckPerms;
public interface ChatAPI {
import java.util.HashMap;
public abstract interface ChatAPI {
static ChatAPI get() {
return ChatImplementation.get();
@ -17,4 +19,6 @@ public interface ChatAPI {
void ReloadChatFilters();
HashMap<String, String> getPrefixes();
}

View File

@ -1,13 +1,19 @@
package com.alttd.chat;
import com.alttd.chat.config.Config;
import com.alttd.chat.config.PrefixConfig;
import com.alttd.chat.database.DatabaseConnection;
import com.alttd.chat.database.Queries;
import com.alttd.chat.managers.ChatUserManager;
import com.alttd.chat.managers.PartyManager;
import com.alttd.chat.managers.RegexManager;
import com.alttd.chat.util.ALogger;
import net.luckperms.api.LuckPerms;
import net.luckperms.api.LuckPermsProvider;
import net.luckperms.api.model.group.Group;
import java.util.HashMap;
import java.util.Map;
public class ChatImplementation implements ChatAPI{
@ -16,6 +22,8 @@ public class ChatImplementation implements ChatAPI{
private LuckPerms luckPerms;
private DatabaseConnection databaseConnection;
private HashMap<String, String> prefixes;
public ChatImplementation() {
instance = this;
ReloadConfig();
@ -52,6 +60,7 @@ public class ChatImplementation implements ChatAPI{
@Override
public void ReloadConfig() {
Config.init();
loadPrefixes();
}
@Override
@ -59,4 +68,18 @@ public class ChatImplementation implements ChatAPI{
RegexManager.initialize();
}
@Override
public HashMap<String, String> getPrefixes() {
return prefixes;
}
private void loadPrefixes() {
prefixes = new HashMap<>();
getLuckPerms().getGroupManager().getLoadedGroups().stream()
.map(Group::getName).forEach(groupName -> prefixes.put(groupName, new PrefixConfig(groupName).PREFIXFORMAT));
for (Map.Entry<String, String> entry : prefixes.entrySet()) {
ALogger.info("prefix: " + entry.getKey() + " format: " + entry.getValue());
}
}
}

View File

@ -32,7 +32,7 @@ public final class Config {
public static File CONFIGPATH;
public static void init() { // todo setup share for the config
CONFIGPATH = new File(System.getProperty("user.home") + File.separator + "share" + File.separator + "ChatPlugin");
CONFIG_FILE = new File(CONFIGPATH, "config.yml");;
CONFIG_FILE = new File(CONFIGPATH, "config.yml");
configLoader = YAMLConfigurationLoader.builder()
.setFile(CONFIG_FILE)
.setFlowStyle(DumperOptions.FlowStyle.BLOCK)
@ -68,6 +68,7 @@ public final class Config {
e.printStackTrace();
}
}
public static void readConfig(Class<?> clazz, Object instance) {
for (Method method : clazz.getDeclaredMethods()) {
if (Modifier.isPrivate(method.getModifiers())) {
@ -155,7 +156,6 @@ public final class Config {
return config.getNode(splitPath(path));
}
/** ONLY EDIT ANYTHING BELOW THIS LINE **/
public static List<String> PREFIXGROUPS = new ArrayList<>();
public static List<String> CONFLICTINGPREFIXGROUPS = new ArrayList<>();
@ -168,7 +168,6 @@ public final class Config {
Lists.newArrayList("discord", "socialmedia", "eventteam", "eventleader", "youtube", "twitch", "developer"));
CONFLICTINGPREFIXGROUPS = getList("settings.prefix-conflicts-groups",
Lists.newArrayList("eventteam", "eventleader"));
STAFFGROUPS = getList("settings.staff-groups",
Lists.newArrayList("trainee", "moderator", "headmod", "admin", "manager", "owner"));
CONSOLENAME = getString("settings.console-name", CONSOLENAME);

View File

@ -0,0 +1,152 @@
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.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.regex.Pattern;
public final class PrefixConfig {
private static final Pattern PATH_PATTERN = Pattern.compile("\\.");
private static final String HEADER =
"This file is used to store all of the prefix settings used in the Altitude Chat plugin.\n"
+ "Legacy and MiniMessage formatting can be applied to these settings.\n";
private static File CONFIG_FILE;
public static ConfigurationNode config;
public static YAMLConfigurationLoader configLoader;
private static String prefixName;
private static String configPath;
private static String defaultPath;
public PrefixConfig(String prefix) {
prefixName = prefix;
configPath = "prefix-settings." + prefixName + ".";
defaultPath = "prefix-settings.default.";
init();
}
public static File CONFIGPATH;
public void init() {
CONFIGPATH = new File(System.getProperty("user.home") + File.separator + "share" + File.separator + "ChatPlugin");
CONFIG_FILE = new File(CONFIGPATH, "prefix.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();
}
readConfig(PrefixConfig.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());
}
}
public 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(defaultPath + path, def);
return config.getNode(splitPath(configPath + path)).getBoolean(
config.getNode(splitPath(defaultPath + path)).getBoolean(def));
}
private static double getDouble(String path, double def) {
set(defaultPath + path, def);
return config.getNode(splitPath(configPath + path)).getDouble(
config.getNode(splitPath(defaultPath + path)).getDouble(def));
}
private static int getInt(String path, int def) {
set(defaultPath + path, def);
return config.getNode(splitPath(configPath + path)).getInt(
config.getNode(splitPath(defaultPath + path)).getInt(def));
}
private static String getString(String path, String def) {
set(defaultPath + path, def);
return config.getNode(splitPath(configPath + path)).getString(
config.getNode(splitPath(defaultPath + path)).getString(def));
}
/** ONLY EDIT ANYTHING BELOW THIS LINE **/
public static String PREFIXFORMAT = "<prefix>";
private static void PrefixSettings() {
PREFIXFORMAT = getString("format", PREFIXFORMAT);
}
}

View File

@ -4,10 +4,7 @@ import com.alttd.chat.database.Queries;
import com.alttd.chat.objects.ChatUser;
import com.alttd.chat.objects.Mail;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.*;
import java.util.stream.Collectors;
public final class ChatUserManager {

View File

@ -18,6 +18,7 @@ import org.jetbrains.annotations.NotNull;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class Utility {
@ -63,11 +64,12 @@ public class Utility {
LuckPerms luckPerms = ChatAPI.get().getLuckPerms();
User user = luckPerms.getUserManager().getUser(uuid);
List<String> prefixGroups = Config.PREFIXGROUPS;
if(prefixGroups.containsAll(Config.CONFLICTINGPREFIXGROUPS))
prefixGroups.remove("eventteam"); // hardcoded for now, new prefix system would load this from config
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")) {
prefixGroups.remove("eventteam"); // hardcoded for now, new prefix system would load this from config
}
inheritedGroups.stream()
.sorted(Comparator.comparingInt(o -> o.getWeight().orElse(0)))
.forEach(group -> {
@ -95,22 +97,23 @@ public class Utility {
}
public static String getGroupPrefix(Group group) {
switch (group.getName()) { // hardcoded for now, new prefix system would load this from config
case "discord":
return "<hover:show_text:'&dNitro Booster in our discord'>" + group.getCachedData().getMetaData().getPrefix() + "</hover>";
case "socialmedia":
return "<hover:show_text:'&6Social Media, this person manages our Socials'>" + group.getCachedData().getMetaData().getPrefix() + "</hover>";
case "eventteam":
return "<hover:show_text:'&6Event Team, this person is part of the event team'>" + group.getCachedData().getMetaData().getPrefix() + "</hover>";
case "eventleader":
return "<hover:show_text:'&6Event Leader, this person is an event leader'>" + group.getCachedData().getMetaData().getPrefix() + "</hover>";
case "youtube":
return "<hover:show_text:'&6This person creates Altitude content on YouTube'>" + group.getCachedData().getMetaData().getPrefix() + "</hover>";
case "twitch":
return "<hover:show_text:'&6This person creates Altitude content on Twitch'>" + group.getCachedData().getMetaData().getPrefix() + "</hover>";
default:
return group.getCachedData().getMetaData().getPrefix();
}
return ChatAPI.get().getPrefixes().get(group.getName()).replace("<prefix>", group.getCachedData().getMetaData().getPrefix());
// switch (group.getName()) { // hardcoded for now, new prefix system would load this from config
// case "discord":
// return "<hover:show_text:'&dNitro Booster in our discord'>" + group.getCachedData().getMetaData().getPrefix() + "</hover>";
// case "socialmedia":
// return "<hover:show_text:'&6Social Media, this person manages our Socials'>" + group.getCachedData().getMetaData().getPrefix() + "</hover>";
// case "eventteam":
// return "<hover:show_text:'&6Event Team, this person is part of the event team'>" + group.getCachedData().getMetaData().getPrefix() + "</hover>";
// case "eventleader":
// return "<hover:show_text:'&6Event Leader, this person is an event leader'>" + group.getCachedData().getMetaData().getPrefix() + "</hover>";
// case "youtube":
// return "<hover:show_text:'&6This person creates Altitude content on YouTube'>" + group.getCachedData().getMetaData().getPrefix() + "</hover>";
// case "twitch":
// return "<hover:show_text:'&6This person creates Altitude content on Twitch'>" + group.getCachedData().getMetaData().getPrefix() + "</hover>";
// default:
// return group.getCachedData().getMetaData().getPrefix();
// }
}
public static String getDisplayName(UUID uuid, String playerName) {

View File

@ -183,45 +183,4 @@ public class PluginMessage implements PluginMessageListener {
}.runTaskAsynchronously(ChatPlugin.getInstance());
}
}
/* // todo implement AdvancedChatFilter for this like this
// send pluginmessage to backend server and return a shatteredcomponent to be reparsed by proxy
// Start - move these to util
public Component itemComponent(ItemStack item) {
Component component = Component.text("[i]");
if(item.getType().equals(Material.AIR))
return component;
boolean dname = item.hasItemMeta() && item.getItemMeta().hasDisplayName();
if(dname) {
component = component.append(item.getItemMeta().displayName());
} else {
component = Component.text(materialToName(item.getType()));
}
component = component.hoverEvent(item.asHoverEvent());
return component;
}
private static String materialToName(Material m) {
if (m.equals(Material.TNT)) {
return "TNT";
}
String orig = m.toString().toLowerCase();
String[] splits = orig.split("_");
StringBuilder sb = new StringBuilder(orig.length());
int pos = 0;
for (String split : splits) {
sb.append(split);
int loc = sb.lastIndexOf(split);
char charLoc = sb.charAt(loc);
if (!(split.equalsIgnoreCase("of") || split.equalsIgnoreCase("and") ||
split.equalsIgnoreCase("with") || split.equalsIgnoreCase("on")))
sb.setCharAt(loc, Character.toUpperCase(charLoc));
if (pos != splits.length - 1)
sb.append(' ');
++pos;
}
return sb.toString();
}
// end - move these to util
}*/
}