diff --git a/resources/changelog.txt b/resources/changelog.txt index 0db7231..90d3785 100644 --- a/resources/changelog.txt +++ b/resources/changelog.txt @@ -475,4 +475,7 @@ v0.110: - The channels in the channels.yml may now be given listenpermission and speakpermission keys, whose values will be the permission node require to either speak or listen to the channel. - When these are set on a channel they will make the permission key of the channel redundant and unused. - Closes https://github.com/TownyAdvanced/Towny/issues/1020. - - Update min. Towny version to 0.100.0.0. \ No newline at end of file + - Update min. Towny version to 0.100.0.0. + - Add CommentedConfiguration support to the channels.yml. + - The Comments in the file have been updated to include missing channel flags. + - It is now possible to update the file comments as new flags are added. \ No newline at end of file diff --git a/src/com/palmergames/bukkit/TownyChat/Chat.java b/src/com/palmergames/bukkit/TownyChat/Chat.java index 98e56f4..d80f0bb 100644 --- a/src/com/palmergames/bukkit/TownyChat/Chat.java +++ b/src/com/palmergames/bukkit/TownyChat/Chat.java @@ -7,7 +7,6 @@ import com.palmergames.bukkit.TownyChat.Command.commandobjects.ChannelJoinAliasC import com.palmergames.bukkit.TownyChat.channels.Channel; import com.palmergames.bukkit.TownyChat.channels.ChannelsHolder; import com.palmergames.bukkit.TownyChat.config.ChatSettings; -import com.palmergames.bukkit.TownyChat.config.ChannelConfigurationHandler; import com.palmergames.bukkit.TownyChat.config.ChannelsSettings; import com.palmergames.bukkit.TownyChat.listener.EssentialsDiscordHookListener; import com.palmergames.bukkit.TownyChat.listener.TownyChatPlayerListener; @@ -51,7 +50,6 @@ public class Chat extends JavaPlugin { private TownyChatPlayerListener TownyPlayerListener; private ChannelsHolder channels; - private ChannelConfigurationHandler channelsConfig; protected PluginManager pm; private static Chat chat = null; @@ -75,7 +73,6 @@ public class Chat extends JavaPlugin { @Override public void onEnable() { pm = getServer().getPluginManager(); - channelsConfig = new ChannelConfigurationHandler(this); channels = new ChannelsHolder(this); playerChannelMap = new ConcurrentHashMap<>(); @@ -121,7 +118,7 @@ public class Chat extends JavaPlugin { private void loadConfigs() { FileMgmt.checkOrCreateFolders(new String[] { getRootPath(), getTownySettingsPath() }); chatConfigError = !ChatSettings.loadCommentedChatConfig(); - channelsConfigError = !ChannelsSettings.loadCommentedChannelsConfig();//!channelsConfig.loadChannels(); + channelsConfigError = !ChannelsSettings.loadCommentedChannelsConfig(); } public static Chat getTownyChat() { @@ -137,7 +134,6 @@ public class Chat extends JavaPlugin { towny = null; pm = null; - channelsConfig = null; channels = null; playerChannelMap = null; } @@ -238,13 +234,6 @@ public class Chat extends JavaPlugin { return channels; } - /** - * @return the data - */ - public ChannelConfigurationHandler getConfigurationHandler() { - return channelsConfig; - } - public Towny getTowny() { return towny; } @@ -286,7 +275,7 @@ public class Chat extends JavaPlugin { bukkitCommandMap.setAccessible(true); CommandMap commandMap = (CommandMap) bukkitCommandMap.get(Bukkit.getServer()); - commandMap.registerAll("towny", commands); + commandMap.registerAll("TownyChat", commands); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { diff --git a/src/com/palmergames/bukkit/TownyChat/channels/Channel.java b/src/com/palmergames/bukkit/TownyChat/channels/Channel.java index 1e718bb..c97dffe 100644 --- a/src/com/palmergames/bukkit/TownyChat/channels/Channel.java +++ b/src/com/palmergames/bukkit/TownyChat/channels/Channel.java @@ -284,10 +284,20 @@ public abstract class Channel { return hooked; } + /** + * deprecated since 0.110, this setting has been unused for an unknown amount of time. + * @param autojoin + */ + @Deprecated public void setAutoJoin(boolean autojoin) { this.autojoin = autojoin; } + /** + * deprecated since 0.110, this setting has been unused for an unknown amount of time. + * @param autojoin + */ + @Deprecated public boolean isAutoJoin() { return autojoin; } diff --git a/src/com/palmergames/bukkit/TownyChat/config/ChannelConfigurationHandler.java b/src/com/palmergames/bukkit/TownyChat/config/ChannelConfigurationHandler.java deleted file mode 100644 index 62c434e..0000000 --- a/src/com/palmergames/bukkit/TownyChat/config/ChannelConfigurationHandler.java +++ /dev/null @@ -1,238 +0,0 @@ -package com.palmergames.bukkit.TownyChat.config; - -import com.palmergames.bukkit.TownyChat.Chat; -import com.palmergames.bukkit.TownyChat.channels.Channel; -import com.palmergames.bukkit.TownyChat.channels.StandardChannel; -import com.palmergames.bukkit.TownyChat.channels.channelTypes; -import org.bukkit.Bukkit; -import org.yaml.snakeyaml.LoaderOptions; -import org.yaml.snakeyaml.Yaml; -import org.yaml.snakeyaml.reader.UnicodeReader; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - - - -public class ChannelConfigurationHandler { - - private Chat plugin; - - /** Constructor - * - * @param plugin - */ - public ChannelConfigurationHandler(Chat plugin) { - super(); - this.plugin = plugin; - } - - - /** - * Load all Channels from the Channels.yml - * If it doesn't exist, create it from - * the resource in this jar. - * - * @return true if the channels were loaded - */ - @SuppressWarnings("unchecked") - public boolean loadChannels() { - - String filename = Chat.getTownyChat().getChannelsConfigPath(); - - Map channelsMap; - try { - channelsMap = getMap(filename, "Channels.yml"); - } catch (Exception e) { - 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] Online YAML Parser: https://yaml-online-parser.appspot.com/"); - return false; - } - if (channelsMap == null || !channelsMap.containsKey("Channels")) - return false; - - // Parse the channels - Map allChannelNodes = (Map) channelsMap.get("Channels"); - if (allChannelNodes == null) - return false; - - // Load channels if the file is NOT empty - for (String channelKey : allChannelNodes.keySet()) { - - Map thisChannelNode = (Map) allChannelNodes.get(channelKey); - Channel channel = new StandardChannel(plugin, channelKey.toLowerCase()); - - for (String key : thisChannelNode.keySet()) { - Object element = thisChannelNode.get(key); - - if (key.equalsIgnoreCase("commands")) - if (element instanceof ArrayList) - channel.setCommands((List) element); - else if (element instanceof String) - channel.setCommands(Arrays.asList(element.toString())); - - if (key.equalsIgnoreCase("type")) - if (element instanceof String) - channel.setType(channelTypes.valueOf(element.toString())); - - if (key.equalsIgnoreCase("hooked")) { - if (element instanceof Boolean) { - channel.setHooked((Boolean)element); - } else if (element instanceof String) { - channel.setHooked(Boolean.parseBoolean(element.toString())); - } else if (element instanceof Integer) { - channel.setHooked(Integer.parseInt(element.toString()) != 0); - } - } - - if (key.equalsIgnoreCase("autojoin")) { - if (element instanceof Boolean) { - channel.setAutoJoin((Boolean)element); - } else if (element instanceof String) { - channel.setAutoJoin(Boolean.parseBoolean(element.toString())); - } else if (element instanceof Integer) { - channel.setAutoJoin(Integer.parseInt(element.toString()) != 0); - } - } - - if (key.equalsIgnoreCase("focusable")) { - if (element instanceof Boolean) { - channel.setFocusable((Boolean)element); - } else if (element instanceof String) { - channel.setFocusable(Boolean.parseBoolean(element.toString())); - } else if (element instanceof Integer) { - channel.setFocusable(Integer.parseInt(element.toString()) != 0); - } - } - - if (key.equalsIgnoreCase("default")) { - boolean set = false; - if (element instanceof Boolean) { - set = (element != null && ((Boolean)element) == true); - } else if (element instanceof String) { - set = Boolean.parseBoolean((String)element); - } else if (element instanceof Integer) { - set = (element != null && ((Integer)element) != 0); - } - if (set) { - plugin.getChannelsHandler().setDefaultChannel(channel); - plugin.getLogger().info("Default Channel set to " + channel.getName()); - } - } - - if (key.equalsIgnoreCase("spam_time")) { - channel.setSpam_time(Double.valueOf(element.toString())); - } - - if (key.equalsIgnoreCase("channeltag")) - if (element instanceof String) - channel.setChannelTag(element.toString()); - - if (key.equalsIgnoreCase("messagecolour")) - if (element instanceof String) - channel.setMessageColour(element.toString()); - - if (key.equalsIgnoreCase("permission")) - if (element instanceof String) - channel.setPermission(element.toString()); - - if (key.equalsIgnoreCase("leavepermission")) - if (element instanceof String) - channel.setLeavePermission(element.toString()); - - if (key.equalsIgnoreCase("listenpermission")) - if (element instanceof String) - channel.setListenPermission(element.toString()); - - if (key.equalsIgnoreCase("speakpermission")) - if (element instanceof String) - channel.setSpeakPermission(element.toString()); - - if (key.equalsIgnoreCase("range")) - channel.setRange(Double.valueOf(element.toString())); - - if (key.equalsIgnoreCase("sound")) - channel.setChannelSound(String.valueOf(element)); - } - - // If no leave permission is set, create a default permission name - if (channel.getLeavePermission() == null) { - channel.setLeavePermission("towny.chat.leave." + channel.getName().toLowerCase()); - } - plugin.getChannelsHandler().addChannel(channel); - } - 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) - // This is because not everyone knows that you need to add a default: true into the channels.yml to make it the default channel! - plugin.getChannelsHandler().setDefaultChannel(plugin.getChannelsHandler().getAllChannels().entrySet().iterator().next().getValue()); - } - return true; - - } - - @SuppressWarnings("unchecked") - public static Map getMap(String filepath, String resource) { - - File f = new File(filepath); - if (!(f.exists() && f.isFile())) { - // Populate a new file - try { - try (FileOutputStream fos = new FileOutputStream(f)) { - fos.write(getResourceFileAsString("/" + resource).getBytes(StandardCharsets.UTF_8)); - } - } catch (IOException e) { - // No resource file found - e.printStackTrace(); - return null; - } - } - - f = new File(filepath); - - Yaml yamlChannels = new Yaml(new LoaderOptions()); - Object channelsRootDataNode; - - try (FileInputStream fileInputStream = new FileInputStream(f)) { - 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); - } - - if (channelsRootDataNode instanceof Map) - return (Map) channelsRootDataNode; - - return null; - } - - /** - * Reads given resource file as a string. - * - * @param fileName path to the resource file - * @return the file's contents - * @throws IOException if read fails for any reason - */ - static String getResourceFileAsString(String fileName) throws IOException { - if (fileName == null) - return ""; - try (InputStream is = ChannelConfigurationHandler.class.getResourceAsStream(fileName); - InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8); - BufferedReader reader = new BufferedReader(isr)) { - return reader.lines().collect(Collectors.joining(System.lineSeparator())); - } - } -} diff --git a/src/com/palmergames/bukkit/TownyChat/config/ChannelsNodes.java b/src/com/palmergames/bukkit/TownyChat/config/ChannelsNodes.java new file mode 100644 index 0000000..099a375 --- /dev/null +++ b/src/com/palmergames/bukkit/TownyChat/config/ChannelsNodes.java @@ -0,0 +1,156 @@ +package com.palmergames.bukkit.TownyChat.config; + +/** + * Dummy class used to make Channels.yml have update-able comments. + * + * @author LlmDl + * + */ +public enum ChannelsNodes { + COMMENTS("channelscomments", "", + "# This file contains all configuration data for the TownyChat channels.", + "# Each channel is a map of keys and values. You can add and remove channels, as you see fit.", + "# ", + "# Channels do not require all of the keys to be set. The keys which are required are:", + "# - type", + "# - commands", + "# The other keys are not required.", + "# ", + "# The keys are as follows: commands, type, channeltag, messagecolour, permission, leavepermission, speakpermission, listenpermission, sound, range,", + "# spam_time, focusable, default.", + "# ", + "# The TYPE key will determine what formatting is used in a channel. Types' formats are configured in the chatconfig.yml file in the channel_formats section.", + "# ", + "# *** Further Explanation of the available keys is below: ***", + "#","#", + "# COMMANDS", + "# --------", + "# In order to swap channels, you must use the desired channel's command to enter the new chat and leave the old one.", + "# eg: /tc (would put you in town chat) and typing it again would not change your channel. To get back to general chat, you can do /g.", + "# ", + "# Commands can also be used to speak into a channel, without leaving the channel you are speaking in.", + "# eg: '/tc somewords' will send 'somewords' to the townchat channel.", + "#","#", + "# TYPE", + "# ----", + "# The channel type is either GLOBAL, TOWN, NATION, ALLIANCE, or DEFAULT. These specify what chat formating is used from the chatconfig.yml's channel_formats", + "# section.)", + "#","#", + "# CHANNELTAG", + "# ----------", + "# channeltag is what defines how the chatconfig.yml's {channelTag} chat tag will appear in the channel.", + "#","#", + "# PERMISSION", + "# ----------", + "# permission is an optional key in a channel, when it is set the given value will be the permission node required to listen/speak in the channel. It is used", + "# when either spearkpermission or listenpermission is not set.", + "#","#", + "# SPEAKPERMISSION", + "# ---------------", + "# speakpermission is an optional key in a channel, when it is set the given value will be the permission node required to speak in the channel, overriding", + "# the channel's permission key when players are speaking.", + "#","#", + "# LISTENPERMISSION", + "# ----------------", + "# listenpermission is an optional key in a channel, when it is set the given value will be the permission node required to listen to the channel, overriding", + "# the channel's permission key when a player's ability to hear a channel is tested.", + "#","#", + "# LEAVEPERMISSION", + "# ---------------", + "# leavepermission is an optional key in a channel, when it is set the given value will be the permission node required to listen to the channel, when not", + "# set this is automatically set to 'towny.chat.leave.{channelname}'.", + "#","#", + "# MESSAGECOLOUR", + "# -------------", + "# messagecolour is what defines how the chatconfig.yml's {msgcolour} chat tag will appear in the channel.", + "# ", + "# Tip: if you want to have message colour determined per-rank on your server this is possible:", + "# in your chatconfig.yml's channel_formats section add {permsuffix} or {permgroupsuffix} after the {msgcolour} tag. Then in your permission plugin give the", + "# ranks you want to have coloured chat a suffix consisting of a colour code. Ranks without a suffix set will have the normal channel message colour used.", + "#","#", + "# RANGE", + "# -----", + "# range is what defines whether a channel has distance-based or world-based listening logic. Someone outside of the configured range will not see messages", + "# in chat and cannot be 'heard' by others outside of the range. Range is in blocks (when set above 0).", + "# ", + "# Options for range:", + "# -1 = no limits, everyone will hear messages if they have permission.", + "# 0 = same world only", + "# any positive value = limited range in the same world.", + "#","#", + "# SPAM_TIME", + "# ---------", + "# spam_time sets how long between chatting a player must wait, to prevent players from flooding chat with spam.", + "#","#", + "# FOCUSABLE", + "# ---------", + "# focusable is a setting which allows players to set their focused channel, ie: using the /tc command with no message. Channels are focusable by default, so", + "# there is no point to adding focusable: true. You make a channel un-focusable by adding the key/value 'focusable: false'.", + "#","#", + "# DEFAULT", + "# -------", + "# default is a setting which decides which channel is the default when a player logs in to the server.", + "#","#", + "# HOOKED", + "# ------", + "# hooked is a setting which decides if a channel can be view by other plugins which are using the TownyChat AsyncChatHookEvent. You may find that a plugin", + "# you are using will ask for 'hooked: true' to be added to a channel, in order for that plugin to further modify chat being spoken in town/nation channels.", + "#","#", + "# SOUND", + "# -----", + "# Each channel can have a sound by adding the key/value 'sound: SOUND_TO_USE'", + "# Sounds can be found here: https://hub.spigotmc.org/javadocs/bukkit/org/bukkit/Sound.html", + "#","#", + "# Text Colouring Hints", + "# --------------------", + "# Black = &0, Navy = &1, Green = &2, Blue = &3, Red = &4, Purple = &5, Gold = &6, LightGray = &7, Gray = &8, DarkPurple = &9, LightGreen = &a,", + "# LightBlue = &b, Rose = &c, LightPurple = &d, Yellow = &e, White = &f"), + CHANNELS_ROOT("Channels", "", "", ""); + + private final String Root; + private final String Default; + private String[] comments; + + private ChannelsNodes(String root, String def, String... comments) { + + this.Root = root; + this.Default = def; + this.comments = comments; + } + + /** + * Retrieves the root for a config option + * + * @return The root for a config option + */ + public String getRoot() { + + return Root; + } + + /** + * Retrieves the default value for a config path + * + * @return The default value for a config path + */ + public String getDefault() { + + return Default; + } + + /** + * Retrieves the comment for a config path + * + * @return The comments for a config path + */ + public String[] getComments() { + + if (comments != null) { + return comments; + } + + String[] comments = new String[1]; + comments[0] = ""; + return comments; + } +} diff --git a/src/com/palmergames/bukkit/TownyChat/config/ChannelsSettings.java b/src/com/palmergames/bukkit/TownyChat/config/ChannelsSettings.java new file mode 100644 index 0000000..1d7a286 --- /dev/null +++ b/src/com/palmergames/bukkit/TownyChat/config/ChannelsSettings.java @@ -0,0 +1,409 @@ +package com.palmergames.bukkit.TownyChat.config; + +import com.palmergames.bukkit.TownyChat.Chat; +import com.palmergames.bukkit.TownyChat.channels.Channel; +import com.palmergames.bukkit.TownyChat.channels.StandardChannel; +import com.palmergames.bukkit.TownyChat.channels.channelTypes; +import com.palmergames.bukkit.config.CommentedConfiguration; +import com.palmergames.util.FileMgmt; +import com.palmergames.util.StringMgmt; + +import org.bukkit.Bukkit; +import org.bukkit.configuration.ConfigurationSection; +import java.io.File; +import java.io.IOException; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; + +public class ChannelsSettings { + + private static final String CHANNELS_ROOT = "Channels"; + private static CommentedConfiguration channelConfig, newChannelConfig; + private final static List DEFAULT_CHANNELS = Arrays.asList("general","town","nation","alliance","admin","mod","local"); + + /** + * + * @return true if the channels.yml has loaded. + * @throws IOException + */ + public static boolean loadCommentedChannelsConfig() { + String filepath = Chat.getTownyChat().getChannelsConfigPath(); + if (FileMgmt.checkOrCreateFile(filepath)) { + File file = new File(filepath); + + // read the config.yml into memory + channelConfig = new CommentedConfiguration(file.toPath()); + if (!channelConfig.load()) { + 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] Online YAML Parser: https://yaml-online-parser.appspot.com/"); + return false; + } + setDefaults(file); + channelConfig.save(); + if (!loadChannels()) + return false; + } + return true; + } + + /** + * Builds a new channels.yml reading old channels.yml data, + * and setting new nodes to default values. + */ + private static void setDefaults(File file) { + newChannelConfig = new CommentedConfiguration(file.toPath()); + newChannelConfig.load(); + + for (ChannelsNodes root : ChannelsNodes.values()) { + if (root.getComments().length > 0) + addComment(root.getRoot(), root.getComments()); + + setNewProperty(root.getRoot(), getValue(root)); + } + + tryAndSetDefaultChannels(); + + channelConfig = newChannelConfig; + newChannelConfig = null; + } + + private static Object getValue(ChannelsNodes root) { + String key = root.getRoot(); + return channelConfig.get(key) != null ? channelConfig.get(key) : root.getDefault(); + } + + private static void addComment(String root, String... comments) { + newChannelConfig.addComment(root, comments); + } + + private static void setNewProperty(String root, Object value) { + if (value == null) { + value = ""; + } + newChannelConfig.set(root, value.toString()); + } + + private static void tryAndSetDefaultChannels() { + + if (channelConfig.contains(CHANNELS_ROOT)) { + // There is already a root channels present, not our first run. + newChannelConfig.set(CHANNELS_ROOT, channelConfig.get(CHANNELS_ROOT)); + } else { + // Populate a fresh channels.yml. + Chat.getTownyChat().getLogger().info("TownyChat creating default channels.yml file."); + + newChannelConfig.createSection(CHANNELS_ROOT); + for (String channel : DEFAULT_CHANNELS) + newChannelConfig.createSection(CHANNELS_ROOT + "." + channel); + + ConfigurationSection configurationSection = newChannelConfig.getConfigurationSection(CHANNELS_ROOT); + configurationSection.set("general", generalDefaults()); + configurationSection.set("town", townDefaults()); + configurationSection.set("nation", nationDefaults()); + configurationSection.set("alliance", allianceDefaults()); + configurationSection.set("admin", adminDefaults()); + configurationSection.set("mod", modDefaults()); + configurationSection.set("local", localDefaults()); + } + } + + private static Map generalDefaults() { + Map channelMap = new LinkedHashMap<>(); + channelMap.put("commands", "g"); + channelMap.put("type", "GLOBAL"); + channelMap.put("channelTag", "&f[g]"); + channelMap.put("messagecolour", "&f"); + channelMap.put("permission", "towny.chat.general"); + channelMap.put("default", "true"); + channelMap.put("range", "-1"); + channelMap.put("spam_time", "0.5"); + return channelMap; + } + + private static Map townDefaults() { + Map channelMap = new LinkedHashMap<>(); + channelMap.put("commands", "tc"); + channelMap.put("type", "TOWN"); + channelMap.put("channelTag", "&f[&3TC&f]"); + channelMap.put("messagecolour", "&b"); + channelMap.put("permission", "towny.chat.town"); + channelMap.put("range", "-1"); + channelMap.put("spam_time", "0.5"); + return channelMap; + } + + private static Map nationDefaults() { + Map channelMap = new LinkedHashMap<>(); + channelMap.put("commands", "nc"); + channelMap.put("type", "NATION"); + channelMap.put("channelTag", "&f[&6NC&f]"); + channelMap.put("messagecolour", "&e"); + channelMap.put("permission", "towny.chat.nation"); + channelMap.put("range", "-1"); + channelMap.put("spam_time", "0.5"); + return channelMap; + } + + private static Map allianceDefaults() { + Map channelMap = new LinkedHashMap<>(); + channelMap.put("commands", "ac"); + channelMap.put("type", "ALLIANCE"); + channelMap.put("channelTag", "&f[&2AC&f]"); + channelMap.put("messagecolour", "&a"); + channelMap.put("permission", "towny.chat.alliance"); + channelMap.put("range", "-1"); + channelMap.put("spam_time", "0.5"); + return channelMap; + } + + private static Map adminDefaults() { + Map channelMap = new LinkedHashMap<>(); + channelMap.put("commands", "a,admin"); + channelMap.put("type", "DEFAULT"); + channelMap.put("channelTag", "&f[&4ADMIN&f]"); + channelMap.put("messagecolour", "&c"); + channelMap.put("permission", "towny.chat.admin"); + channelMap.put("range", "-1"); + return channelMap; + } + + private static Map modDefaults() { + Map channelMap = new LinkedHashMap<>(); + channelMap.put("commands", "m,mod"); + channelMap.put("type", "DEFAULT"); + channelMap.put("channelTag", "&f[&9MOD&f]"); + channelMap.put("messagecolour", "&5"); + channelMap.put("permission", "towny.chat.mod"); + channelMap.put("range", "-1"); + return channelMap; + } + + private static Map localDefaults() { + Map channelMap = new LinkedHashMap<>(); + channelMap.put("commands", "l,lc"); + channelMap.put("type", "GLOBAL"); + channelMap.put("channelTag", "&f[local]"); + channelMap.put("messagecolour", "&f"); + channelMap.put("permission", "towny.chat.local"); + channelMap.put("default", "true"); + channelMap.put("range", "100"); + return channelMap; + } + + private static boolean loadChannels() { + ConfigurationSection configurationSection = channelConfig.getConfigurationSection(CHANNELS_ROOT); + if (configurationSection == null) { + Bukkit.getLogger().severe("[TownyChat] Failed to load Channels.yml!"); + Bukkit.getLogger().severe("[TownyChat] No channels root section was present!"); + return false; + } + + Set channelsKeys = configurationSection.getKeys(false); + + // This should never happen if the setDefaults(file) method has run. + if (channelsKeys.isEmpty()) { + Bukkit.getLogger().severe("[TownyChat] Failed to load Channels.yml!"); + Bukkit.getLogger().severe("[TownyChat] No channels keys were present!"); + Bukkit.getLogger().severe("[TownyChat] Deleting your towny\\settings\\channels.yml can solve this problem."); + return false; + } + + Chat plugin = Chat.getTownyChat(); + + channelsKeys.forEach((channelName)-> { + Channel channel = new StandardChannel(plugin, channelName.toLowerCase(Locale.ROOT)); + loadChannelSettings(channelName, channel); + plugin.getChannelsHandler().addChannel(channel); + }); + + 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) + // This is because not everyone knows that you need to add a default: true into the channels.yml to make it the default channel! + plugin.getChannelsHandler().setDefaultChannel(plugin.getChannelsHandler().getAllChannels().entrySet().iterator().next().getValue()); + } + + return true; + } + + private static void loadChannelSettings(String channelName, Channel channel) { + ChannelDetails data = new ChannelsSettings.ChannelDetails(channelConfig, channelName); + // The following will always be present in some manner + channel.setCommands(data.getCommands()); + channel.setType(channelTypes.valueOf(data.getType())); + channel.setRange(data.getRange()); + channel.setHooked(data.isHooked()); + channel.setFocusable(data.isFocusable()); + channel.setLeavePermission(data.getLeavePermission()); + // The following may not neccessarily be set. + if (data.hasMessageColour()) + channel.setMessageColour(data.getMessageColour()); + if (data.hasChannelTag()) + channel.setChannelTag(data.getChannelTag()); + if (data.hasSound()) + channel.setChannelSound(data.getSound()); + if (data.hasPermission()) + channel.setPermission(data.getPermission()); + if (data.hasSpeakPermission()) + channel.setSpeakPermission(data.getSpeakPermission()); + if (data.hasListenPermission()) + channel.setListenPermission(data.getListenPermission()); + if (data.hasSpamTime()) + channel.setSpam_time(data.getSpamTime()); + if (data.isDefault()) { + Chat.getTownyChat().getChannelsHandler().setDefaultChannel(channel); + Chat.getTownyChat().getLogger().info("Default Channel set to " + channel.getName()); + } + } + + static class ChannelDetails { + private Map channelSettingsMap = new HashMap<>(); + private String name; + + /** + * Constructor + * + * @param name Channel name + */ + public ChannelDetails(CommentedConfiguration channelsConfig, String name) { + super(); + this.name = name.toLowerCase(Locale.ROOT); + String path = CHANNELS_ROOT + "." + this.name; + for (String key : channelsConfig.getConfigurationSection(path).getKeys(true)) { + String innerPath = path + "." + key; + if (channelsConfig.get(innerPath) != null) + channelSettingsMap.put(key, parseObject(channelsConfig.get(innerPath))); + } + } + + private Object parseObject(Object object) { + if (object instanceof @SuppressWarnings("rawtypes") List list) + return StringMgmt.join(list, ","); + if (object instanceof String string) + return string; + if (object instanceof Boolean b) + return b; + if (object instanceof Double d) + return d; + return ""; + } + + /** + * @return the name + */ + public String getName() { + return name; + } + + public String getType() { + return (String) channelSettingsMap.getOrDefault("type", "DEFAULT"); + } + + public boolean hasChannelTag() { + return channelSettingsMap.containsKey("channeltag"); + } + + public String getChannelTag() { + return (String) channelSettingsMap.getOrDefault("channeltag", ""); + } + + public boolean hasMessageColour() { + return channelSettingsMap.containsKey("messagecolour"); + } + + public String getMessageColour() { + return (String) channelSettingsMap.getOrDefault("messagecolour", ""); + } + + public boolean hasPermission() { + return channelSettingsMap.containsKey("permission"); + } + + public String getPermission() { + return (String) channelSettingsMap.getOrDefault("permission", ""); + } + + public boolean hasLeavePermission() { + return channelSettingsMap.containsKey("leavepermission"); + } + + public String getLeavePermission() { + return (String) channelSettingsMap.getOrDefault("leavepermission", "towny.chat.leave." + name); + } + + public boolean hasListenPermission() { + return channelSettingsMap.containsKey("listenpermission"); + } + + public String getListenPermission() { + return (String) channelSettingsMap.getOrDefault("listenpermission", ""); + } + + public boolean hasSpeakPermission() { + return channelSettingsMap.containsKey("speakpermission"); + } + + public String getSpeakPermission() { + return (String) channelSettingsMap.getOrDefault("speakpermission", ""); + } + + public boolean hasSound() { + return channelSettingsMap.containsKey("sound"); + } + + public String getSound() { + return (String) channelSettingsMap.getOrDefault("sound", ""); + } + + public boolean hasSpamTime() { + return channelSettingsMap.containsKey("spam_time"); + } + + public double getSpamTime() { + return Double.valueOf((String) channelSettingsMap.get("spam_time")); + } + + public double getRange() { + return Double.valueOf((String) channelSettingsMap.getOrDefault("range", -1)); + } + + public boolean isHooked() { + return getBoolean(channelSettingsMap.getOrDefault("hooked", false)); + } + + public boolean isFocusable() { + return getBoolean(channelSettingsMap.getOrDefault("focusable", true)); + } + + public boolean isDefault() { + return getBoolean(channelSettingsMap.getOrDefault("default", false)); + } + + public List getCommands() { + Object object = channelSettingsMap.get("commands"); + if (object instanceof String string) { + return Arrays.asList(string.split(",")); + } + // As a fall-back we make a command from the channel name, this should not + // happen often or at all. + return Collections.singletonList(name + "chat"); + } + + private boolean getBoolean(Object value) { + if (value instanceof Boolean) { + return (Boolean) value; + } else if (value instanceof String) { + return Boolean.parseBoolean(value.toString()); + } else if (value instanceof Integer) { + return Integer.parseInt(value.toString()) != 0; + } + return false; + } + } +} \ No newline at end of file