Redo chatconfig loading.

This commit is contained in:
LlmDl committed 2022-10-03 10:43:14 -05:00
1 parent 355ad72e03
commit 5c454b9f01
9 files changed
+146 -541

No files matched your search

+10 -3
View File
@@ -25,6 +25,7 @@ import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
import org.dynmap.DynmapAPI; import org.dynmap.DynmapAPI;
import java.io.File;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
@@ -48,6 +49,7 @@ public class Chat extends JavaPlugin {
private ConfigurationHandler channelsConfig; private ConfigurationHandler channelsConfig;
protected PluginManager pm; protected PluginManager pm;
private static Chat chat = null;
private Towny towny = null; private Towny towny = null;
private DynmapAPI dynMap = null; private DynmapAPI dynMap = null;
@@ -61,6 +63,7 @@ public class Chat extends JavaPlugin {
@Override @Override
public void onEnable() { public void onEnable() {
chat = this;
pm = getServer().getPluginManager(); pm = getServer().getPluginManager();
channelsConfig = new ConfigurationHandler(this); channelsConfig = new ConfigurationHandler(this);
channels = new ChannelsHolder(this); channels = new ChannelsHolder(this);
@@ -106,11 +109,16 @@ public class Chat extends JavaPlugin {
private void loadConfigs() { private void loadConfigs() {
FileMgmt.checkFolders(new String[] { getRootPath(), getChannelsPath() }); FileMgmt.checkFolders(new String[] { getRootPath(), getChannelsPath() });
if (!ChatSettings.loadCommentedConfig(getChannelsPath() + FileMgmt.fileSeparator() + "ChatConfig.yml", this.getDescription().getVersion())) if (!ChatSettings.loadCommentedConfig(getChannelsPath() + File.separator + "ChatConfig.yml"))
chatConfigError = true; chatConfigError = true;
if (!channelsConfig.loadChannels(getChannelsPath(), "Channels.yml")) if (!channelsConfig.loadChannels(getChannelsPath(), "Channels.yml"))
channelsConfigError = true; channelsConfigError = true;
} }
public static Chat getTownyChat() {
return chat;
}
@Override @Override
public void onDisable() { public void onDisable() {
unregisterPermissions(); unregisterPermissions();
@@ -198,7 +206,7 @@ public class Chat extends JavaPlugin {
} }
public String getChannelsPath() { public String getChannelsPath() {
return getRootPath() + FileMgmt.fileSeparator() + "settings"; return getRootPath() + File.separator + "settings";
} }
/** /**
@@ -219,7 +227,6 @@ public class Chat extends JavaPlugin {
return towny; return towny;
} }
public DynmapAPI getDynmap() { public DynmapAPI getDynmap() {
return dynMap; return dynMap;
} }
@@ -106,13 +106,13 @@ public class TownyChatFormatter {
// Output depending on what tags are present // Output depending on what tags are present
if ((!tTag.isEmpty()) && (!nTag.isEmpty())) { if ((!tTag.isEmpty()) && (!nTag.isEmpty())) {
if (ChatSettings.getBothTags().contains("%t") || ChatSettings.getBothTags().contains("%n")) { if (ChatSettings.getBothTag().contains("%t") || ChatSettings.getBothTag().contains("%n")) {
// Then it contains %s & %s // Then it contains %s & %s
// Small suttle change so that an issue is solved, it is documented in the config. // Small suttle change so that an issue is solved, it is documented in the config.
// But only after addition of this. (v0.50) // But only after addition of this. (v0.50)
return ChatSettings.getBothTags().replace("%t", tTag).replace("%n", nTag); return ChatSettings.getBothTag().replace("%t", tTag).replace("%n", nTag);
} else { } else {
return String.format(ChatSettings.getBothTags(), nTag, tTag); return String.format(ChatSettings.getBothTag(), nTag, tTag);
} }
} }
@@ -67,7 +67,7 @@ public class StandardChannel extends Channel {
} }
// Set the channel specific format // Set the channel specific format
String format = getFormat(player, channelType); String format = ChatSettings.getChannelFormat(player, channelType);
// Get the list of message recipients. // Get the list of message recipients.
Set<Player> recipients = getRecipients(player, town, nation, channelType, event.getRecipients()); Set<Player> recipients = getRecipients(player, town, nation, channelType, event.getRecipients());
@@ -130,16 +130,6 @@ public class StandardChannel extends Channel {
} }
} }
private String getFormat(Player player, channelTypes channelType) {
return switch(channelType) {
case TOWN -> ChatSettings.getRelevantFormatGroup(player).getTOWN();
case NATION -> ChatSettings.getRelevantFormatGroup(player).getNATION();
case ALLIANCE -> ChatSettings.getRelevantFormatGroup(player).getALLIANCE();
case DEFAULT -> ChatSettings.getRelevantFormatGroup(player).getDEFAULT();
case GLOBAL, PRIVATE -> ChatSettings.getRelevantFormatGroup(player).getGLOBAL();
};
}
private Set<Player> getRecipients(Player player, Town town, Nation nation, channelTypes channelType, Set<Player> recipients) { private Set<Player> getRecipients(Player player, Town town, Nation nation, channelTypes channelType, Set<Player> recipients) {
return switch (channelType) { return switch (channelType) {
case TOWN -> new HashSet<>(findRecipients(player, TownyAPI.getInstance().getOnlinePlayers(town))); case TOWN -> new HashSet<>(findRecipients(player, TownyAPI.getInstance().getOnlinePlayers(town)));
@@ -16,22 +16,6 @@ public class channelFormats {
private String name, GLOBAL, TOWN, NATION, ALLIANCE, DEFAULT; private String name, GLOBAL, TOWN, NATION, ALLIANCE, DEFAULT;
/**
* @return a clone of this channelFormats
*/
public channelFormats clone(String name) {
channelFormats clone = new channelFormats(name.toLowerCase());
clone.setGLOBAL(this.getGLOBAL());
clone.setTOWN(this.getTOWN());
clone.setNATION(this.getNATION());
clone.setALLIANCE(this.getALLIANCE());
clone.setDEFAULT(this.getDEFAULT());
return clone;
}
/** /**
* @return the name * @return the name
*/ */
@@ -1,11 +1,13 @@
package com.palmergames.bukkit.TownyChat.config; package com.palmergames.bukkit.TownyChat.config;
import com.palmergames.bukkit.TownyChat.Chat;
import com.palmergames.bukkit.TownyChat.channels.channelFormats; import com.palmergames.bukkit.TownyChat.channels.channelFormats;
import com.palmergames.bukkit.TownyChat.util.FileMgmt; import com.palmergames.bukkit.TownyChat.channels.channelTypes;
import com.palmergames.bukkit.config.CommentedConfiguration; import com.palmergames.bukkit.config.CommentedConfiguration;
import com.palmergames.bukkit.config.ConfigNodes; import com.palmergames.bukkit.config.ConfigNodes;
import com.palmergames.bukkit.towny.TownyUniverse; import com.palmergames.bukkit.towny.TownyUniverse;
import com.palmergames.bukkit.towny.object.TownyWorld; import com.palmergames.bukkit.towny.object.TownyWorld;
import com.palmergames.util.FileMgmt;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.ConfigurationSection;
@@ -14,18 +16,13 @@ import org.bukkit.entity.Player;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Locale;
import java.util.Map; import java.util.Map;
public class ChatSettings extends tag_formats { public class ChatSettings {
private static boolean modify_chat; private static Map<String, channelFormats> worldFormatGroups = new HashMap<String, channelFormats>();
private static boolean per_world;
private static boolean alone_message;
private static boolean display_modes_set_on_join;
private static String alone_message_string;
private static Map<String, channelFormats> formatGroups = new HashMap<String, channelFormats>();
private static CommentedConfiguration chatConfig, newChatConfig; private static CommentedConfiguration chatConfig, newChatConfig;
/** /**
@@ -35,10 +32,10 @@ public class ChatSettings extends tag_formats {
* @return * @return
* @throws IOException * @throws IOException
*/ */
public static boolean loadCommentedConfig(String filepath, String version) { public static boolean loadCommentedConfig(String filepath) {
File file = FileMgmt.CheckYMLExists(new File(filepath)); if (FileMgmt.checkOrCreateFile(filepath)) {
if (file != null) { File file = new File(filepath);
// read the config.yml into memory // read the config.yml into memory
ChatSettings.chatConfig = new CommentedConfiguration(file.toPath()); ChatSettings.chatConfig = new CommentedConfiguration(file.toPath());
@@ -48,11 +45,7 @@ public class ChatSettings extends tag_formats {
Bukkit.getLogger().severe("[TownyChat] Online YAML Parser: https://yaml-online-parser.appspot.com/"); Bukkit.getLogger().severe("[TownyChat] Online YAML Parser: https://yaml-online-parser.appspot.com/");
return false; return false;
} }
setDefaults(version, file); setDefaults(file);
try {
// Pre-1.18.1 this option does not exist.
chatConfig.options().width(500);
} catch (NoSuchMethodError ignored) {}
chatConfig.save(); chatConfig.save();
} }
return true; return true;
@@ -62,48 +55,47 @@ public class ChatSettings extends tag_formats {
* Builds a new chatconfig reading old chatconfig data, * Builds a new chatconfig reading old chatconfig data,
* and setting new nodes to default values. * and setting new nodes to default values.
*/ */
private static void setDefaults(String version, File file) { private static void setDefaults(File file) {
String version = Chat.getTownyChat().getDescription().getVersion();
newChatConfig = new CommentedConfiguration(file.toPath()); newChatConfig = new CommentedConfiguration(file.toPath());
newChatConfig.load(); newChatConfig.load();
for (ChatConfigNodes root : ChatConfigNodes.values()) { for (ChatConfigNodes root : ChatConfigNodes.values()) {
if (root.getComments().length > 0) if (root.getComments().length > 0)
addComment(root.getRoot(), root.getComments()); addComment(root.getRoot(), root.getComments());
if (root.getRoot() == ChatConfigNodes.WORLDS.getRoot()) {
// Per-worlds section.
// setNewProperty(root.getRoot(), root.getDefault());
setWorldDefaults();
} else if (root.getRoot() == ChatConfigNodes.VERSION.getRoot()) { if (root.getRoot() == ChatConfigNodes.WORLDS.getRoot())
setWorldDefaults(); // Per-worlds section.
else if (root.getRoot() == ChatConfigNodes.VERSION.getRoot())
setNewProperty(root.getRoot(), version); setNewProperty(root.getRoot(), version);
} else if (root.getRoot() == ChatConfigNodes.LAST_RUN_VERSION.getRoot()) else if (root.getRoot() == ChatConfigNodes.LAST_RUN_VERSION.getRoot())
setNewProperty(root.getRoot(), getLastRunVersion(version)); setNewProperty(root.getRoot(), getLastRunVersion(version));
else { else
// A regular config node. // A regular config node.
setNewProperty(root.getRoot(), (chatConfig.get(root.getRoot().toLowerCase()) != null) ? chatConfig.get(root.getRoot().toLowerCase()) : root.getDefault()); setNewProperty(root.getRoot(), (chatConfig.get(root.getRoot().toLowerCase()) != null) ? chatConfig.get(root.getRoot().toLowerCase()) : root.getDefault());
} }
}
chatConfig = newChatConfig; chatConfig = newChatConfig;
newChatConfig = null; newChatConfig = null;
} }
private static void setWorldDefaults() { private static void setWorldDefaults() {
if (perWorld()) { if (isPer_world()) {
for (TownyWorld world : TownyUniverse.getInstance().getTownyWorlds()) { for (TownyWorld world : TownyUniverse.getInstance().getTownyWorlds()) {
if (!chatConfig.contains("worlds." + world ) String path = "worlds." + world;
|| !chatConfig.contains("worlds." + world + ".global") if (!chatConfig.contains(path )
|| !chatConfig.contains("worlds." + world + ".town") || !chatConfig.contains(path + ".global")
|| !chatConfig.contains("worlds." + world + ".nation") || !chatConfig.contains(path + ".town")
|| !chatConfig.contains("worlds." + world + ".alliance") || !chatConfig.contains(path + ".nation")
|| !chatConfig.contains("worlds." + world + ".default")) { || !chatConfig.contains(path + ".alliance")
newChatConfig.createSection("worlds." + world); || !chatConfig.contains(path + ".default")) {
ConfigurationSection worldsection = newChatConfig.getConfigurationSection("worlds." + world); newChatConfig.createSection(path);
worldsection.set("global", (chatConfig.get("worlds." + world + ".global")!= null) ? chatConfig.get("worlds." + world + ".global") : ChatConfigNodes.CHANNEL_FORMATS_GLOBAL.getDefault()); ConfigurationSection worldsection = newChatConfig.getConfigurationSection(path);
worldsection.set("town", (chatConfig.get("worlds." + world + ".town")!= null) ? chatConfig.get("worlds." + world + ".town") : ChatConfigNodes.CHANNEL_FORMATS_TOWN.getDefault()); worldsection.set("global", getOrDefault(path + ".global", ChatConfigNodes.CHANNEL_FORMATS_GLOBAL));
worldsection.set("nation", (chatConfig.get("worlds." + world + ".nation")!= null) ? chatConfig.get("worlds." + world + ".nation") : ChatConfigNodes.CHANNEL_FORMATS_NATION.getDefault()); worldsection.set("town", getOrDefault(path + ".town", ChatConfigNodes.CHANNEL_FORMATS_TOWN));
worldsection.set("alliance", (chatConfig.get("worlds." + world + ".alliance")!= null) ? chatConfig.get("worlds." + world + ".alliance") : ChatConfigNodes.CHANNEL_FORMATS_ALLIANCE.getDefault()); worldsection.set("nation", getOrDefault(path + ".nation", ChatConfigNodes.CHANNEL_FORMATS_NATION));
worldsection.set("default", (chatConfig.get("worlds." + world + ".default")!= null) ? chatConfig.get("worlds." + world + ".default") : ChatConfigNodes.CHANNEL_FORMATS_DEFAULT.getDefault()); worldsection.set("alliance", getOrDefault(path + ".alliance", ChatConfigNodes.CHANNEL_FORMATS_ALLIANCE));
worldsection.set("default", getOrDefault(path + ".default", ChatConfigNodes.CHANNEL_FORMATS_DEFAULT));
} }
} }
} else { } else {
@@ -112,7 +104,7 @@ public class ChatSettings extends tag_formats {
} }
} }
public static void addComment(String root, String... comments) { private static void addComment(String root, String... comments) {
newChatConfig.addComment(root.toLowerCase(), comments); newChatConfig.addComment(root.toLowerCase(), comments);
} }
@@ -123,11 +115,11 @@ public class ChatSettings extends tag_formats {
newChatConfig.set(root.toLowerCase(), value.toString()); newChatConfig.set(root.toLowerCase(), value.toString());
} }
public static String getLastRunVersion(String currentVersion) { private static String getLastRunVersion(String currentVersion) {
return getString(ConfigNodes.LAST_RUN_VERSION.getRoot(), currentVersion); return getString(ConfigNodes.LAST_RUN_VERSION.getRoot(), currentVersion);
} }
public static String getString(String root, String def) { private static String getString(String root, String def) {
String data = chatConfig.getString(root.toLowerCase(), def); String data = chatConfig.getString(root.toLowerCase(), def);
if (data == null) { if (data == null) {
sendError(root.toLowerCase() + " from ChatConfig.yml"); sendError(root.toLowerCase() + " from ChatConfig.yml");
@@ -136,13 +128,12 @@ public class ChatSettings extends tag_formats {
return data; return data;
} }
private static void sendError(String msg) { private static String getString(ChatConfigNodes node) {
System.out.println("[TownyChat] Error could not read " + msg); return chatConfig.getString(node.getRoot().toLowerCase(), node.getDefault());
} }
private static boolean perWorld() { private static void sendError(String msg) {
Chat.getTownyChat().getLogger().warning("[TownyChat] Error could not read " + msg);
return getBoolean(ChatConfigNodes.MODIFY_CHAT_PER_WORLD);
} }
private static boolean getBoolean(ChatConfigNodes node) { private static boolean getBoolean(ChatConfigNodes node) {
@@ -150,273 +141,137 @@ public class ChatSettings extends tag_formats {
return Boolean.parseBoolean(chatConfig.getString(node.getRoot().toLowerCase(), node.getDefault())); return Boolean.parseBoolean(chatConfig.getString(node.getRoot().toLowerCase(), node.getDefault()));
} }
/** /*
* @return the formatGroups * Get ChatConfig variables.
*/ */
public static Map<String, channelFormats> getFormatGroups() {
return formatGroups;
}
/**
* @param formatGroups
* the formatGroups to set
*/
public static void setFormatGroups(Map<String, channelFormats> formatGroups) {
ChatSettings.formatGroups = formatGroups;
}
/**
* @return the formatGroup
*/
public static channelFormats getFormatGroup(String name) {
return formatGroups.get(name.toLowerCase());
}
public static boolean hasFormatGroup(String groupName) {
return formatGroups.containsKey(groupName.toLowerCase());
}
public static void addFormatGroup(channelFormats group) {
if (hasFormatGroup(group.getName()))
formatGroups.remove(group.getName());
formatGroups.put(group.getName(), group);
}
public static void removeFormatGroup(String name) {
if (hasFormatGroup(name.toLowerCase()))
formatGroups.remove(name.toLowerCase());
}
public static channelFormats getRelevantFormatGroup (Player player) {
if (isPer_world()) {
String name = player.getWorld().getName();
if (hasFormatGroup(name))
return getFormatGroup(name);
}
return getFormatGroup("channel_formats");
}
/** /**
* @return the modify_chat * @return the modify_chat
*/ */
public static boolean isModify_chat() { public static boolean isModify_chat() {
return modify_chat; return getBoolean(ChatConfigNodes.MODIFY_CHAT_ENABLE);
}
/**
* @param modify_chat
* the modify_chat to set
*/
public static void setModify_chat(boolean modify_chat) {
ChatSettings.modify_chat = modify_chat;
} }
/** /**
* @return the alone_message * @return the alone_message
*/ */
public static boolean isUsingAloneMessage() { public static boolean isUsingAloneMessage() {
return alone_message; return getBoolean(ChatConfigNodes.MODIFY_CHAT_ALONE_MESSAGE);
}
/**
* @param alone_message
*/
public static boolean setUsingAloneMessage(boolean alone_message) {
return ChatSettings.alone_message = alone_message;
}
/**
* @param alone_message_string
* @return
*/
public static String setUsingAloneMessageString(String alone_message_string) {
return ChatSettings.alone_message_string = alone_message_string;
} }
/** /**
* @return the alone_message_string * @return the alone_message_string
*/ */
public static String getUsingAloneMessageString() { public static String getUsingAloneMessageString() {
return ChatSettings.alone_message_string; return getString(ChatConfigNodes.MODIFY_CHAT_ALONE_MESSAGE_STRING);
}
/**
* @param display_modes_set_on_join
*/
public static boolean setDisplayModesSetOnJoin(boolean display_modes_set_on_join) {
return ChatSettings.display_modes_set_on_join = display_modes_set_on_join;
}
/**
* @return the display_modes_set_on_join setting
*/
public static boolean getShowChannelMessageOnServerJoin() {
return display_modes_set_on_join;
} }
/** /**
* @return the per_world * @return the per_world
*/ */
public static boolean isPer_world() { public static boolean isPer_world() {
return per_world; return getBoolean(ChatConfigNodes.MODIFY_CHAT_PER_WORLD);
} }
/** /**
* @param per_world * @return the display_modes_set_on_join setting
* the per_world to set
*/ */
public static void setPer_world(boolean per_world) { public static boolean getShowChannelMessageOnServerJoin() {
ChatSettings.per_world = per_world; return getBoolean(ChatConfigNodes.DISPLAY_CHANNEL_JOIN_MESSAGE_ON_JOIN);
} }
/*
* Get Tags formats.
/**
* Adds customizable channel formats for each world.
*
* @return true if new worlds we're found
*/ */
public static boolean populateWorldFormats() {
boolean updated = false;
for (TownyWorld world : TownyUniverse.getInstance().getTownyWorlds()) {
if (!hasFormatGroup(world.getName())) {
addFormatGroup(getFormatGroup("channel_formats").clone(world.getName()));
updated = true;
}
}
return updated;
}
}
//////////////////////////////////////////////////
class tag_formats extends chat_colours{
private static String WorldTag, TownTag, NationTag, BothTags;
/**
* @return the World tag
*/
public static String getWorldTag() { public static String getWorldTag() {
return WorldTag; return getString(ChatConfigNodes.TAG_FORMATS_WORLD);
} }
/**
* @param tag the World tag to set
*/
public static void setWorldTag(String tag) {
tag_formats.WorldTag = tag;
}
/**
* @return the TownTag
*/
public static String getTownTag() { public static String getTownTag() {
return TownTag; return getString(ChatConfigNodes.TAG_FORMATS_TOWN);
} }
/**
* @param tag the TOWN tag to set
*/
public static void setTownTag(String tag) {
tag_formats.TownTag = tag;
}
/**
* @return NationTag
*/
public static String getNationTag() { public static String getNationTag() {
return NationTag; return getString(ChatConfigNodes.TAG_FORMATS_NATION);
} }
/** public static String getBothTag() {
* @param tag the NATION tag to set return getString(ChatConfigNodes.TAG_FORMATS_BOTH);
}
/*
* Get Colour formats.
*/ */
public static void setNationTag(String tag) {
tag_formats.NationTag = tag;
}
/**
* @return BothTags the nation and town tags
*/
public static String getBothTags() {
return BothTags;
}
/**
* @param tag the Nation and Town tags to set
*/
public static void setBothTags(String tag) {
tag_formats.BothTags = tag;
}
}
class chat_colours {
private static String KING, MAYOR, RESIDENT, NOMAD;
/**
* @return KING the KING colour
*/
public static String getKingColour() { public static String getKingColour() {
return KING; return getString(ChatConfigNodes.COLOUR_KING);
} }
/**
* @param colour the colour to set
*/
public static void setKingColour(String colour) {
chat_colours.KING = colour;
}
/**
* @return MAYOR the MAYOR colour
*/
public static String getMayorColour() { public static String getMayorColour() {
return MAYOR; return getString(ChatConfigNodes.COLOUR_MAYOR);
} }
/**
* @param colour the colour to set
*/
public static void setMayorColour(String colour) {
chat_colours.MAYOR = colour;
}
/**
* @return RESIDENT the RESIDENT colour
*/
public static String getResidentColour() { public static String getResidentColour() {
return RESIDENT; return getString(ChatConfigNodes.COLOUR_RESIDENT);
} }
/**
* @param colour the RESIDENT colour tag to set
*/
public static void setResidentColour(String colour) {
chat_colours.RESIDENT = colour;
}
/**
* @return NOMAD the NOMAD colour
*/
public static String getNomadColour() { public static String getNomadColour() {
return NOMAD; return getString(ChatConfigNodes.COLOUR_NOMAD);
} }
/** /*
* @param colour the NOMAD colour tag to set * Get ChannelType Formats
*/ */
public static void setNomadColour(String colour) {
chat_colours.NOMAD = colour;
}}
public static String getChannelFormat(Player player, channelTypes type) {
if (isPer_world()) {
String name = player.getWorld().getName().toLowerCase(Locale.ROOT);
if (worldFormatGroups.containsKey(name)) {
channelFormats worldFormat = worldFormatGroups.get(name);
String format = switch (type) {
case GLOBAL, PRIVATE -> worldFormat.getGLOBAL();
case NATION -> worldFormat.getNATION();
case TOWN -> worldFormat.getTOWN();
case ALLIANCE -> worldFormat.getALLIANCE();
case DEFAULT -> worldFormat.getDEFAULT();
};
if (format != null && !format.isEmpty())
return format;
}
}
return switch(type) {
case GLOBAL, PRIVATE -> getString(ChatConfigNodes.CHANNEL_FORMATS_GLOBAL);
case NATION -> getString(ChatConfigNodes.CHANNEL_FORMATS_NATION);
case TOWN -> getString(ChatConfigNodes.CHANNEL_FORMATS_TOWN);
case ALLIANCE -> getString(ChatConfigNodes.CHANNEL_FORMATS_ALLIANCE);
case DEFAULT -> getString(ChatConfigNodes.CHANNEL_FORMATS_DEFAULT);
};
}
public static void loadWorldFormats() {
if (!isPer_world())
return;
for (TownyWorld world : TownyUniverse.getInstance().getTownyWorlds()) {
String worldName = world.getName();
String path = "worlds." + worldName;
if (chatConfig.contains(path)) {
channelFormats worldFormat = new channelFormats(worldName);
worldFormat.setGLOBAL(getOrDefault(path + ".global", ChatConfigNodes.CHANNEL_FORMATS_GLOBAL));
worldFormat.setDEFAULT(getOrDefault(path + ".default", ChatConfigNodes.CHANNEL_FORMATS_DEFAULT));
worldFormat.setTOWN(getOrDefault(path + ".town", ChatConfigNodes.CHANNEL_FORMATS_TOWN));
worldFormat.setNATION(getOrDefault(path + ".nation", ChatConfigNodes.CHANNEL_FORMATS_NATION));
worldFormat.setALLIANCE(getOrDefault(path + ".alliance", ChatConfigNodes.CHANNEL_FORMATS_ALLIANCE));
addWorldFormat(worldFormat);
}
}
}
private static String getOrDefault(String configPath, ChatConfigNodes channelNode) {
return (String) chatConfig.get(configPath != null ? configPath : channelNode.getDefault());
}
private static void addWorldFormat(channelFormats format) {
worldFormatGroups.put(format.getName().toLowerCase(Locale.ROOT), format);
}
}
@@ -3,11 +3,11 @@ package com.palmergames.bukkit.TownyChat.config;
import com.palmergames.bukkit.TownyChat.Chat; import com.palmergames.bukkit.TownyChat.Chat;
import com.palmergames.bukkit.TownyChat.channels.Channel; import com.palmergames.bukkit.TownyChat.channels.Channel;
import com.palmergames.bukkit.TownyChat.channels.StandardChannel; import com.palmergames.bukkit.TownyChat.channels.StandardChannel;
import com.palmergames.bukkit.TownyChat.channels.channelFormats;
import com.palmergames.bukkit.TownyChat.channels.channelTypes; import com.palmergames.bukkit.TownyChat.channels.channelTypes;
import com.palmergames.bukkit.TownyChat.util.FileMgmt; import com.palmergames.bukkit.TownyChat.util.FileMgmt;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import java.io.File;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
@@ -41,27 +41,26 @@ public class ConfigurationHandler {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public boolean loadChannels(String filepath, String defaultRes) { public boolean loadChannels(String filepath, String defaultRes) {
String filename = filepath + FileMgmt.fileSeparator() + defaultRes; String filename = filepath + File.separator + defaultRes;
Map<String, Object> file; Map<String, Object> file;
try { try {
file = FileMgmt.getFile(filename, defaultRes, null); file = FileMgmt.getFile(filename, defaultRes);
} catch (Exception e) { } catch (Exception e) {
Bukkit.getLogger().severe("[TownyChat] Failed to load Channels.yml!"); Bukkit.getLogger().severe("[TownyChat] Failed to load Channels.yml!");
Bukkit.getLogger().severe("[TownyChat] Please check that the file passes a YAML Parser test:"); Bukkit.getLogger().severe("[TownyChat] Please check that the file passes a YAML Parser test:");
Bukkit.getLogger().severe("[TownyChat] Online YAML Parser: https://yaml-online-parser.appspot.com/"); Bukkit.getLogger().severe("[TownyChat] Online YAML Parser: https://yaml-online-parser.appspot.com/");
return false; return false;
} }
if (file != null) { if (file == null || !file.containsKey("Channels"))
return false;
for (String rootNode : file.keySet()) {
if (rootNode.equalsIgnoreCase("Channels")) {
// Parse the channels // Parse the channels
Map<String, Object> allChannelNodes = (Map<String, Object>) file.get(rootNode); Map<String, Object> allChannelNodes = (Map<String, Object>) file.get("Channels");
if (allChannelNodes == null)
return false;
// Load channels if the file is NOT empty // Load channels if the file is NOT empty
if (allChannelNodes != null) {
for (String channelKey : allChannelNodes.keySet()) { for (String channelKey : allChannelNodes.keySet()) {
Map<String, Object> thisChannelNode = (Map<String, Object>) allChannelNodes.get(channelKey); Map<String, Object> thisChannelNode = (Map<String, Object>) allChannelNodes.get(channelKey);
@@ -147,8 +146,6 @@ public class ConfigurationHandler {
channel.setLeavePermission("towny.chat.leave." + channel.getName().toLowerCase()); channel.setLeavePermission("towny.chat.leave." + channel.getName().toLowerCase());
} }
plugin.getChannelsHandler().addChannel(channel); plugin.getChannelsHandler().addChannel(channel);
//System.out.print("Channel: " + channel.getName() + " : Type : " + channel.getType().name());
} }
if (plugin.getChannelsHandler().getDefaultChannel() == null) { if (plugin.getChannelsHandler().getDefaultChannel() == null) {
// If there is no default channel set it to the first one that was parsed (the top one in the config) // If there is no default channel set it to the first one that was parsed (the top one in the config)
@@ -158,151 +155,5 @@ public class ConfigurationHandler {
return true; return true;
} }
}
}
}
return false;
}
/**
* Load the ChatConfig.yml
*
* If it doesn't exist, create it from the resource in this jar.
*
* @param filepath
* @param defaultRes
* @return true if the config was loaded
*/
@SuppressWarnings({ "unchecked" })
public boolean loadConfig(String filepath, String defaultRes) {
String filename = filepath + FileMgmt.fileSeparator() + defaultRes;
// Pass the plugin reference so it can load the defaults if needed.
Map<String, Object> file = FileMgmt.getFile(filename);
if (file != null) {
for (String Key : file.keySet()) {
if (Key.equalsIgnoreCase("modify_chat")) {
Map<String, Object> subNodes = (Map<String, Object>) file.get(Key);
for (String element : subNodes.keySet()) {
if (element.equalsIgnoreCase("enable"))
ChatSettings.setModify_chat(Boolean.valueOf(subNodes.get(element).toString()));
if (element.equalsIgnoreCase("per_world"))
ChatSettings.setPer_world(Boolean.valueOf(subNodes.get(element).toString()));
if (element.equalsIgnoreCase("alone_message"))
ChatSettings.setUsingAloneMessage(Boolean.valueOf(subNodes.get(element).toString()));
if (element.equalsIgnoreCase("alone_message_string"))
ChatSettings.setUsingAloneMessageString(String.valueOf(subNodes.get(element).toString()));
}
}
if (Key.equalsIgnoreCase("display_channel_join_message_on_joining_the_server"))
ChatSettings.setDisplayModesSetOnJoin(Boolean.valueOf(file.get(Key).toString()));
if (Key.equalsIgnoreCase("colour")) {
Map<String, Object> subNodes = (Map<String, Object>) file.get(Key);
for (String element : subNodes.keySet()) {
if (element.equalsIgnoreCase("king"))
ChatSettings.setKingColour(subNodes.get(element).toString());
if (element.equalsIgnoreCase("mayor"))
ChatSettings.setMayorColour(subNodes.get(element).toString());
if (element.equalsIgnoreCase("resident"))
ChatSettings.setResidentColour(subNodes.get(element).toString());
if (element.equalsIgnoreCase("nomad"))
ChatSettings.setNomadColour(subNodes.get(element).toString());
}
} }
if (Key.equalsIgnoreCase("tag_formats")) {
Map<String, Object> subNodes = (Map<String, Object>) file.get(Key);
for (String element : subNodes.keySet()) {
if (element.equalsIgnoreCase("world"))
ChatSettings.setWorldTag(subNodes.get(element).toString());
if (element.equalsIgnoreCase("town"))
ChatSettings.setTownTag(subNodes.get(element).toString());
if (element.equalsIgnoreCase("nation"))
ChatSettings.setNationTag(subNodes.get(element).toString());
if (element.equalsIgnoreCase("both"))
ChatSettings.setBothTags(subNodes.get(element).toString());
}
}
if (Key.equalsIgnoreCase("channel_formats")) {
Map<String, Object> subNodes = (Map<String, Object>) file.get(Key);
channelFormats group = new channelFormats(Key);
for (String element : subNodes.keySet()) {
if (element.equalsIgnoreCase("global"))
group.setGLOBAL(subNodes.get(element).toString());
if (element.equalsIgnoreCase("town"))
group.setTOWN(subNodes.get(element).toString());
if (element.equalsIgnoreCase("nation"))
group.setNATION(subNodes.get(element).toString());
if (element.equalsIgnoreCase("alliance"))
group.setALLIANCE(subNodes.get(element).toString());
if (element.equalsIgnoreCase("default"))
group.setDEFAULT(subNodes.get(element).toString());
}
ChatSettings.addFormatGroup(group);
}
if (Key.equalsIgnoreCase("worlds")) {
Map<String, Object> allWorlds = (Map<String, Object>) file.get(Key);
if (allWorlds != null) {
for (String worlds : allWorlds.keySet()) {
Map<String, Object> world = (Map<String, Object>) allWorlds.get(worlds);
channelFormats group = new channelFormats(worlds);
for (String element : world.keySet()) {
if (element.equalsIgnoreCase("global"))
group.setGLOBAL(world.get(element).toString());
if (element.equalsIgnoreCase("town"))
group.setTOWN(world.get(element).toString());
if (element.equalsIgnoreCase("nation"))
group.setNATION(world.get(element).toString());
if (element.equalsIgnoreCase("alliance"))
group.setALLIANCE(world.get(element).toString());
if (element.equalsIgnoreCase("default"))
group.setDEFAULT(world.get(element).toString());
}
ChatSettings.addFormatGroup(group);
}
}
}
}
return true;
}
return false;
}
}
@@ -182,7 +182,7 @@ public class TownyChatPlayerListener implements Listener {
* We found no channels available so modify the chat (if enabled) and exit. * We found no channels available so modify the chat (if enabled) and exit.
*/ */
if (ChatSettings.isModify_chat()) { if (ChatSettings.isModify_chat()) {
event.setFormat(ChatSettings.getRelevantFormatGroup(player).getGLOBAL().replace("{channelTag}", "").replace("{msgcolour}", "")); event.setFormat(ChatSettings.getChannelFormat(player, channelTypes.GLOBAL).replace("{channelTag}", "").replace("{msgcolour}", ""));
Resident resident = TownyUniverse.getInstance().getResident(player.getUniqueId()); Resident resident = TownyUniverse.getInstance().getResident(player.getUniqueId());
LocalTownyChatEvent chatEvent = new LocalTownyChatEvent(event, resident); LocalTownyChatEvent chatEvent = new LocalTownyChatEvent(event, resident);
@@ -1,6 +1,7 @@
package com.palmergames.bukkit.TownyChat.tasks; package com.palmergames.bukkit.TownyChat.tasks;
import com.palmergames.bukkit.TownyChat.Chat; import com.palmergames.bukkit.TownyChat.Chat;
import com.palmergames.bukkit.TownyChat.config.ChatSettings;
import com.palmergames.bukkit.towny.Towny; import com.palmergames.bukkit.towny.Towny;
/* /*
@@ -25,13 +26,14 @@ public class onLoadedTask implements Runnable {
if (this.towny.isEnabled()) { if (this.towny.isEnabled()) {
// Setup our config here as we now have Towny loaded. // Setup our config here as we now have Towny loaded.
if (this.towny.isError() || (!plugin.getConfigurationHandler().loadConfig(plugin.getChannelsPath(), "ChatConfig.yml"))) { if (this.towny.isError()) {
plugin.getLogger().severe("Disabling TownyChat..."); plugin.getLogger().severe("Disabling TownyChat...");
plugin.getServer().getPluginManager().disablePlugin(plugin); plugin.getServer().getPluginManager().disablePlugin(plugin);
return; return;
} }
ChatSettings.loadWorldFormats();
plugin.getLogger().info("-******* TownyChat enabled *******-"); plugin.getLogger().info("-******* TownyChat enabled *******-");
plugin.registerPermissions(); plugin.registerPermissions();
plugin.registerEvents(); plugin.registerEvents();
@@ -13,7 +13,6 @@ import java.io.StringWriter;
import java.io.Writer; import java.io.Writer;
import java.util.Map; import java.util.Map;
import com.palmergames.bukkit.TownyChat.Chat;
import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor; import org.yaml.snakeyaml.constructor.SafeConstructor;
import org.yaml.snakeyaml.reader.UnicodeReader; import org.yaml.snakeyaml.reader.UnicodeReader;
@@ -30,38 +29,7 @@ public class FileMgmt {
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static Map<String, Object> getFile(String filepath) { public static Map<String, Object> getFile(String filepath, String resource) {
try {
File f = new File(filepath);
Yaml yamlChannels = new Yaml(new SafeConstructor());
Object channelsRootDataNode;
FileInputStream fileInputStream = new FileInputStream(f);
try {
channelsRootDataNode = yamlChannels.load(new UnicodeReader(fileInputStream));
if (channelsRootDataNode == null) {
throw new NullPointerException();
}
} catch (Exception ex) {
throw new IllegalArgumentException("The following file couldn't pass on Parser.\n" + f.getPath(), ex);
} finally {
fileInputStream.close();
}
if (channelsRootDataNode instanceof Map)
return (Map<String, Object>) channelsRootDataNode;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@SuppressWarnings("unchecked")
public static Map<String, Object> getFile(String filepath, String resource, Chat plugin) {
try { try {
File f = new File(filepath); File f = new File(filepath);
@@ -108,7 +76,7 @@ public class FileMgmt {
} }
// pass a resource name and it will return it's contents as a string // pass a resource name and it will return it's contents as a string
public static String convertStreamToString(String name) throws IOException { private static String convertStreamToString(String name) throws IOException {
if (name != null) { if (name != null) {
Writer writer = new StringWriter(); Writer writer = new StringWriter();
InputStream is = FileMgmt.class.getResourceAsStream(name); InputStream is = FileMgmt.class.getResourceAsStream(name);
@@ -144,7 +112,7 @@ public class FileMgmt {
* @param FileName * @param FileName
* @return true on success * @return true on success
*/ */
public static boolean stringToFile(String source, String FileName) { private static boolean stringToFile(String source, String FileName) {
if (source != null) { if (source != null) {
// Save the string to file (*.yml) // Save the string to file (*.yml)
@@ -159,18 +127,6 @@ public class FileMgmt {
} }
public static File CheckYMLExists(File file) {
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
return file;
}
/** /**
* Writes the contents of a string to a file. * Writes the contents of a string to a file.
* *
@@ -181,7 +137,7 @@ public class FileMgmt {
* @return True on success. * @return True on success.
* @throws IOException * @throws IOException
*/ */
public static boolean stringToFile(String source, File file) throws IOException { private static boolean stringToFile(String source, File file) throws IOException {
try { try {
@@ -199,44 +155,4 @@ public class FileMgmt {
} }
} }
public static String fileSeparator() {
return System.getProperty("file.separator");
}
/**
* Pass a file and it will return it's contents as a string.
*
* @param file File to read.
* @return Contents of file. String will be empty in case of any errors.
*/
public static String convertFileToString(File file) {
if (file != null && file.exists() && file.canRead() && !file.isDirectory()) {
Writer writer = new StringWriter();
InputStream is = null;
char[] buffer = new char[1024];
try {
is = new FileInputStream(file);
Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
reader.close();
} catch (IOException e) {
System.out.println("Exception ");
} finally {
if (is != null) {
try {
is.close();
} catch (IOException ignore) {
}
}
}
return writer.toString();
} else {
return "";
}
}
} }