refactor: adventure rewrite

- also reformat project
This commit is contained in:
darksaid98 committed 2024-04-05 19:37:04 +02:00
1 parent e0281e10a8
commit 7a96244233
22 files changed
+3457 -3453

No files matched your search

+245 -249
View File
@@ -7,8 +7,8 @@ import com.palmergames.bukkit.TownyChat.Command.TownyChatCommand;
import com.palmergames.bukkit.TownyChat.Command.commandobjects.ChannelJoinAliasCommand; import com.palmergames.bukkit.TownyChat.Command.commandobjects.ChannelJoinAliasCommand;
import com.palmergames.bukkit.TownyChat.channels.Channel; import com.palmergames.bukkit.TownyChat.channels.Channel;
import com.palmergames.bukkit.TownyChat.channels.ChannelsHolder; import com.palmergames.bukkit.TownyChat.channels.ChannelsHolder;
import com.palmergames.bukkit.TownyChat.config.ChatSettings;
import com.palmergames.bukkit.TownyChat.config.ChannelsSettings; import com.palmergames.bukkit.TownyChat.config.ChannelsSettings;
import com.palmergames.bukkit.TownyChat.config.ChatSettings;
import com.palmergames.bukkit.TownyChat.listener.EssentialsDiscordHookListener; import com.palmergames.bukkit.TownyChat.listener.EssentialsDiscordHookListener;
import com.palmergames.bukkit.TownyChat.listener.TownyChatPlayerListener; import com.palmergames.bukkit.TownyChat.listener.TownyChatPlayerListener;
import com.palmergames.bukkit.TownyChat.tasks.onLoadedTask; import com.palmergames.bukkit.TownyChat.tasks.onLoadedTask;
@@ -19,7 +19,6 @@ import com.palmergames.bukkit.towny.scheduling.impl.BukkitTaskScheduler;
import com.palmergames.bukkit.towny.scheduling.impl.FoliaTaskScheduler; import com.palmergames.bukkit.towny.scheduling.impl.FoliaTaskScheduler;
import com.palmergames.util.FileMgmt; import com.palmergames.util.FileMgmt;
import com.palmergames.util.JavaUtil; import com.palmergames.util.JavaUtil;
import net.kyori.adventure.text.minimessage.MiniMessage; import net.kyori.adventure.text.minimessage.MiniMessage;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.command.Command; import org.bukkit.command.Command;
@@ -43,291 +42,288 @@ import java.util.concurrent.ConcurrentMap;
/** /**
* Chat plugin to manage all Towny chat * Chat plugin to manage all Towny chat
* * <p>
* Website: http://code.google.com/a/eclipselabs.org/p/towny/ * Website: http://code.google.com/a/eclipselabs.org/p/towny/
* *
* @author ElgarL * @author ElgarL
*/ */
public class Chat extends JavaPlugin { public class Chat extends JavaPlugin {
private TownyChatPlayerListener TownyPlayerListener; public static boolean usingPlaceholderAPI = false;
private ChannelsHolder channels; public static boolean usingEssentialsDiscord = false;
private static Chat chat = null;
protected PluginManager pm; private static String requiredTownyVersion = "0.98.0.0";
private static Chat chat = null; private static ConcurrentMap<UUID, Channel> playerChannelMap;
private final Object scheduler; private final Object scheduler;
private Towny towny = null; protected PluginManager pm;
private DynmapAPI dynMap = null; boolean chatConfigError = false;
private Essentials essentials = null; boolean channelsConfigError = false;
private BukkitAudiences adventure = null; private TownyChatPlayerListener TownyPlayerListener;
private MiniMessage miniMessage = null; private ChannelsHolder channels;
private Towny towny = null;
private DynmapAPI dynMap = null;
private Essentials essentials = null;
private BukkitAudiences adventure = null;
private MiniMessage miniMessage = null;
private static String requiredTownyVersion = "0.98.0.0"; public Chat() {
public static boolean usingPlaceholderAPI = false; chat = this;
public static boolean usingEssentialsDiscord = false; this.scheduler = townyVersionCheck() ? isFoliaClassPresent() ? new FoliaTaskScheduler(this) : new BukkitTaskScheduler(this) : null;
boolean chatConfigError = false; }
boolean channelsConfigError = false;
private static ConcurrentMap<UUID, Channel> playerChannelMap;
public Chat() { public static Chat getTownyChat() {
chat = this; return chat;
this.scheduler = townyVersionCheck() ? isFoliaClassPresent() ? new FoliaTaskScheduler(this) : new BukkitTaskScheduler(this) : null; }
}
@Override private static boolean isFoliaClassPresent() {
public void onEnable() { try {
pm = getServer().getPluginManager(); Class.forName("io.papermc.paper.threadedregions.RegionizedServer");
channels = new ChannelsHolder(this); return true;
playerChannelMap = new ConcurrentHashMap<>(); } catch (ClassNotFoundException e) {
adventure = BukkitAudiences.create(this); return false;
miniMessage = MiniMessage.builder().build(); }
}
checkPlugins();
if (towny == null || !townyVersionCheck()) {
disableWithMessage("Towny version does not meet required minimum version: " + requiredTownyVersion.toString());
return;
} else {
getLogger().info("Towny version " + towny.getDescription().getVersion() + " found.");
}
loadConfigs();
if (channelsConfigError || chatConfigError) {
disableWithMessage("The config could not be loaded.");
return;
}
/*
* This executes the task with a 1 tick delay avoiding the bukkit depends bug.
* TODO: What bug is this referencing? This goes back to the first version of TownyChat.
*/
getScheduler().run(new onLoadedTask(this));
getCommand("townychat").setExecutor(new TownyChatCommand(this)); @Override
getCommand("channel").setExecutor(new ChannelCommand(this)); public void onEnable() {
registerObjectCommands(); pm = getServer().getPluginManager();
} channels = new ChannelsHolder(this);
playerChannelMap = new ConcurrentHashMap<>();
private void disableWithMessage(String message) { adventure = BukkitAudiences.create(this);
getLogger().severe(message); miniMessage = MiniMessage.builder().build();
getLogger().severe("Disabling TownyChat...");
pm.disablePlugin(this);
}
private boolean townyVersionCheck() { checkPlugins();
try { if (towny == null || !townyVersionCheck()) {
return Towny.isTownyVersionSupported(requiredTownyVersion); disableWithMessage("Towny version does not meet required minimum version: " + requiredTownyVersion.toString());
} catch (NoSuchMethodError e) { return;
return false; } else {
} getLogger().info("Towny version " + towny.getDescription().getVersion() + " found.");
} }
private void loadConfigs() { loadConfigs();
FileMgmt.checkOrCreateFolders(new String[] { getRootPath(), getTownySettingsPath() }); if (channelsConfigError || chatConfigError) {
chatConfigError = !ChatSettings.loadCommentedChatConfig(); disableWithMessage("The config could not be loaded.");
channelsConfigError = !ChannelsSettings.loadCommentedChannelsConfig(); return;
} }
public static Chat getTownyChat() { /*
return chat; * This executes the task with a 1 tick delay avoiding the bukkit depends bug.
} * TODO: What bug is this referencing? This goes back to the first version of TownyChat.
*/
getScheduler().run(new onLoadedTask(this));
public @NonNull BukkitAudiences adventure() { getCommand("townychat").setExecutor(new TownyChatCommand(this));
if(this.adventure == null) { getCommand("channel").setExecutor(new ChannelCommand(this));
throw new IllegalStateException("Tried to access Adventure when the plugin was disabled!"); registerObjectCommands();
} }
return this.adventure;
}
public @NonNull MiniMessage getMiniMessage() { private void disableWithMessage(String message) {
return miniMessage; getLogger().severe(message);
} getLogger().severe("Disabling TownyChat...");
pm.disablePlugin(this);
}
@Override private boolean townyVersionCheck() {
public void onDisable() { try {
unregisterPermissions(); return Towny.isTownyVersionSupported(requiredTownyVersion);
// reset any handles } catch (NoSuchMethodError e) {
return false;
}
}
if (adventure != null) { private void loadConfigs() {
adventure.close(); FileMgmt.checkOrCreateFolders(new String[]{getRootPath(), getTownySettingsPath()});
adventure = null; chatConfigError = !ChatSettings.loadCommentedChatConfig();
} channelsConfigError = !ChannelsSettings.loadCommentedChannelsConfig();
miniMessage = null; }
dynMap = null;
towny = null;
pm = null;
channels = null;
playerChannelMap = null;
}
/**
* Perform a reload of this plugin.
*/
public void reload() {
onDisable();
onEnable();
}
/** public @NonNull BukkitAudiences adventure() {
* Attempt to hook any plugins we want to access. if (this.adventure == null) {
*/ throw new IllegalStateException("Tried to access Adventure when the plugin was disabled!");
private void checkPlugins() { }
Plugin test; return this.adventure;
}
test = pm.getPlugin("Towny"); public @NonNull MiniMessage getMiniMessage() {
if (test != null && test instanceof Towny) return miniMessage;
towny = (Towny) test; }
test = pm.getPlugin("dynmap"); @Override
if (test != null && pm.getPlugin("dynmap").isEnabled()) { public void onDisable() {
dynMap = (DynmapAPI) test; unregisterPermissions();
} // reset any handles
test = pm.getPlugin("PlaceholderAPI");
if (test != null) {
usingPlaceholderAPI = true;
}
test = pm.getPlugin("EssentialsDiscord"); if (adventure != null) {
if (test != null) { adventure.close();
usingEssentialsDiscord = true; adventure = null;
} }
miniMessage = null;
dynMap = null;
towny = null;
pm = null;
test = pm.getPlugin("Essentials"); channels = null;
if (test != null && JavaUtil.classExists("com.earth2me.essentials.Essentials")) { playerChannelMap = null;
this.essentials = (Essentials) test; }
}
} /**
* Perform a reload of this plugin.
*/
public void reload() {
onDisable();
onEnable();
}
public void registerEvents() { /**
* Attempt to hook any plugins we want to access.
if (TownyPlayerListener == null) { */
TownyPlayerListener = new TownyChatPlayerListener(this); private void checkPlugins() {
Plugin test;
if (TownyPlayerListener != null)
pm.registerEvents(TownyPlayerListener, this);
}
if (usingEssentialsDiscord) { test = pm.getPlugin("Towny");
pm.registerEvents(new EssentialsDiscordHookListener(this), this); if (test != null && test instanceof Towny)
} towny = (Towny) test;
}
public void registerPermissions() {
// Register all Permissions.
for (String perm : getChannelsHandler().getAllPermissions()) {
try {
pm.addPermission(new Permission(perm, new HashMap<String, Boolean>()));
} catch (IllegalArgumentException e) {
//permission already registered.
}
}
}
public void unregisterPermissions() {
// Register all Permissions.
for (String perm : getChannelsHandler().getAllPermissions()) {
pm.removePermission(new Permission(perm, new HashMap<String, Boolean>()));
}
}
public String getRootPath() {
return getTowny().getDataFolder().getPath();
}
public String getTownySettingsPath() { test = pm.getPlugin("dynmap");
return getRootPath() + File.separator + "settings"; if (test != null && pm.getPlugin("dynmap").isEnabled()) {
} dynMap = (DynmapAPI) test;
}
public String getChatConfigPath() { test = pm.getPlugin("PlaceholderAPI");
return getTownySettingsPath() + File.separator + "ChatConfig.yml"; if (test != null) {
} usingPlaceholderAPI = true;
}
public String getChannelsConfigPath() {
return getTownySettingsPath() + File.separator + "Channels.yml";
}
/** test = pm.getPlugin("EssentialsDiscord");
* @return the channels if (test != null) {
*/ usingEssentialsDiscord = true;
public ChannelsHolder getChannelsHandler() { }
return channels;
}
public Towny getTowny() { test = pm.getPlugin("Essentials");
return towny; if (test != null && JavaUtil.classExists("com.earth2me.essentials.Essentials")) {
} this.essentials = (Essentials) test;
}
public DynmapAPI getDynmap() { }
return dynMap;
}
public boolean isUsingEssentials() { public void registerEvents() {
return essentials != null;
}
public Essentials getEssentials() { if (TownyPlayerListener == null) {
return essentials; TownyPlayerListener = new TownyChatPlayerListener(this);
}
public boolean isEssentialsMuted(Player player) { if (TownyPlayerListener != null)
if (!isUsingEssentials()) pm.registerEvents(TownyPlayerListener, this);
return false; }
return EssentialsIntegration.isMuted(player);
}
public boolean isIgnoredByEssentials(Player sender, Player player) { if (usingEssentialsDiscord) {
if (!isUsingEssentials()) pm.registerEvents(new EssentialsDiscordHookListener(this), this);
return false; }
return EssentialsIntegration.ignoredByEssentials(sender, player); }
}
private void registerObjectCommands() { public void registerPermissions() {
List<Command> commands = new ArrayList<Command>(); // Register all Permissions.
for (Channel channel : channels.getAllChannels().values()) { // All channels for (String perm : getChannelsHandler().getAllPermissions()) {
for (String cmd : channel.getCommands()) { // All Commands of All Channels try {
commands.add(new ChannelJoinAliasCommand(cmd, channel, this)); pm.addPermission(new Permission(perm, new HashMap<String, Boolean>()));
} } catch (IllegalArgumentException e) {
} //permission already registered.
try { }
final Field bukkitCommandMap = Bukkit.getServer().getClass().getDeclaredField("commandMap"); }
}
bukkitCommandMap.setAccessible(true); public void unregisterPermissions() {
CommandMap commandMap = (CommandMap) bukkitCommandMap.get(Bukkit.getServer()); // Register all Permissions.
for (String perm : getChannelsHandler().getAllPermissions()) {
pm.removePermission(new Permission(perm, new HashMap<String, Boolean>()));
}
}
commandMap.registerAll("TownyChat", commands); public String getRootPath() {
} catch (NoSuchFieldException e) { return getTowny().getDataFolder().getPath();
e.printStackTrace(); }
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
public TownyChatPlayerListener getTownyPlayerListener() { public String getTownySettingsPath() {
return TownyPlayerListener; return getRootPath() + File.separator + "settings";
} }
public Channel getPlayerChannel(Player player) {
return playerChannelMap.get(player.getUniqueId());
}
public void setPlayerChannel(Player player, Channel channel) {
playerChannelMap.put(player.getUniqueId(), channel);
}
public TaskScheduler getScheduler() { public String getChatConfigPath() {
return (TaskScheduler) this.scheduler; return getTownySettingsPath() + File.separator + "ChatConfig.yml";
} }
private static boolean isFoliaClassPresent() { public String getChannelsConfigPath() {
try { return getTownySettingsPath() + File.separator + "Channels.yml";
Class.forName("io.papermc.paper.threadedregions.RegionizedServer"); }
return true;
} catch (ClassNotFoundException e) { /**
return false; * @return the channels
} */
} public ChannelsHolder getChannelsHandler() {
return channels;
}
public Towny getTowny() {
return towny;
}
public DynmapAPI getDynmap() {
return dynMap;
}
public boolean isUsingEssentials() {
return essentials != null;
}
public Essentials getEssentials() {
return essentials;
}
public boolean isEssentialsMuted(Player player) {
if (!isUsingEssentials())
return false;
return EssentialsIntegration.isMuted(player);
}
public boolean isIgnoredByEssentials(Player sender, Player player) {
if (!isUsingEssentials())
return false;
return EssentialsIntegration.ignoredByEssentials(sender, player);
}
private void registerObjectCommands() {
List<Command> commands = new ArrayList<Command>();
for (Channel channel : channels.getAllChannels().values()) { // All channels
for (String cmd : channel.getCommands()) { // All Commands of All Channels
commands.add(new ChannelJoinAliasCommand(cmd, channel, this));
}
}
try {
final Field bukkitCommandMap = Bukkit.getServer().getClass().getDeclaredField("commandMap");
bukkitCommandMap.setAccessible(true);
CommandMap commandMap = (CommandMap) bukkitCommandMap.get(Bukkit.getServer());
commandMap.registerAll("TownyChat", commands);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
public TownyChatPlayerListener getTownyPlayerListener() {
return TownyPlayerListener;
}
public Channel getPlayerChannel(Player player) {
return playerChannelMap.get(player.getUniqueId());
}
public void setPlayerChannel(Player player, Channel channel) {
playerChannelMap.put(player.getUniqueId(), channel);
}
public TaskScheduler getScheduler() {
return (TaskScheduler) this.scheduler;
}
} }
@@ -5,15 +5,14 @@ import com.palmergames.bukkit.TownyChat.channels.Channel;
import com.palmergames.bukkit.TownyChat.channels.channelTypes; import com.palmergames.bukkit.TownyChat.channels.channelTypes;
import com.palmergames.bukkit.TownyChat.events.PlayerJoinChatChannelEvent; import com.palmergames.bukkit.TownyChat.events.PlayerJoinChatChannelEvent;
import com.palmergames.bukkit.towny.TownyMessaging; import com.palmergames.bukkit.towny.TownyMessaging;
import com.palmergames.bukkit.towny.TownyUniverse;
import com.palmergames.bukkit.towny.command.BaseCommand; import com.palmergames.bukkit.towny.command.BaseCommand;
import com.palmergames.bukkit.towny.object.Translatable; import com.palmergames.bukkit.towny.object.Translatable;
import com.palmergames.bukkit.towny.object.Translation; import com.palmergames.bukkit.towny.object.Translation;
import com.palmergames.bukkit.towny.object.Translator; import com.palmergames.bukkit.towny.object.Translator;
import com.palmergames.bukkit.towny.TownyUniverse;
import com.palmergames.bukkit.util.ChatTools; import com.palmergames.bukkit.util.ChatTools;
import com.palmergames.bukkit.util.Colors; import com.palmergames.bukkit.util.Colors;
import com.palmergames.util.StringMgmt; import com.palmergames.util.StringMgmt;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandExecutor;
@@ -27,386 +26,386 @@ import java.util.Map;
public class ChannelCommand extends BaseCommand implements CommandExecutor { public class ChannelCommand extends BaseCommand implements CommandExecutor {
private static Chat plugin; private static final List<String> channel_help = new ArrayList<String>();
private static final List<String> channel_help = new ArrayList<String>(); private static Chat plugin;
static { static {
channel_help.add(ChatTools.formatTitle("/channel")); channel_help.add(ChatTools.formatTitle("/channel"));
//TODO: Add lang strings for description! //TODO: Add lang strings for description!
channel_help.add(ChatTools.formatCommand("", "/channel", "join [Channel]", "")); channel_help.add(ChatTools.formatCommand("", "/channel", "join [Channel]", ""));
channel_help.add(ChatTools.formatCommand("", "/channel", "leave [Channel]", "")); channel_help.add(ChatTools.formatCommand("", "/channel", "leave [Channel]", ""));
channel_help.add(ChatTools.formatCommand("", "/channel", "list ", "")); channel_help.add(ChatTools.formatCommand("", "/channel", "list ", ""));
channel_help.add(ChatTools.formatCommand("", "/channel", "mute [Channel] [Player]", "")); channel_help.add(ChatTools.formatCommand("", "/channel", "mute [Channel] [Player]", ""));
channel_help.add(ChatTools.formatCommand("", "/channel", "unmute [Channel] [Player]", "")); channel_help.add(ChatTools.formatCommand("", "/channel", "unmute [Channel] [Player]", ""));
channel_help.add(ChatTools.formatCommand("", "/channel", "mutelist [Channel]", "")); channel_help.add(ChatTools.formatCommand("", "/channel", "mutelist [Channel]", ""));
channel_help.add(ChatTools.formatCommand("", "/channel", "soundtoggle [Channel]", "")); channel_help.add(ChatTools.formatCommand("", "/channel", "soundtoggle [Channel]", ""));
} }
public ChannelCommand(Chat instance) { public ChannelCommand(Chat instance) {
plugin = instance; plugin = instance;
} }
@Override public static void parseChannelList(Player player) {
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { // If not our command
Map<String, Channel> chanList = plugin.getChannelsHandler().getAllChannels();
Translator translator = Translator.locale(Translation.getLocale(player));
if (sender instanceof Player) { TownyMessaging.sendMessage(player, ChatTools.formatTitle("Channels"));
Player player = (Player) sender; TownyMessaging.sendMessage(player, Colors.Gold + "Channel" + Colors.Gray + " - " + Colors.LightBlue + translator.of("tc_channel_list_status"));
if (command.getName().equalsIgnoreCase("channel")) { for (Map.Entry<String, Channel> channel : chanList.entrySet()) {
if (label.equalsIgnoreCase("join")) { if (channel.getValue().hasListenPermission(player))
parseChannelJoin(player, args); if (channel.getValue().isPresent(player.getName()))
return true; TownyMessaging.sendMessage(player, Colors.Gold + channel.getKey() + Colors.Gray + " - " + Colors.LightBlue + translator.of("tc_channel_list_in"));
} else
if (label.equalsIgnoreCase("leave")) { TownyMessaging.sendMessage(player, Colors.Gold + channel.getKey() + Colors.Gray + " - " + Colors.LightBlue + translator.of("tc_channel_list_out"));
parseChannelLeave(player, args); }
return true; }
}
if (label.equalsIgnoreCase("mutelist")) {
parseChannelMuteList(player, args);
return true;
}
if (label.equalsIgnoreCase("chmute")) {
parseChannelMute(player, args, true);
return true;
}
if (label.equalsIgnoreCase("chunmute")) {
parseChannelMute(player, args, false);
return true;
}
parseChannelCommand(player, args);
return true;
}
} else {
// Console
for (String line : channel_help) {
TownyMessaging.sendMessage(sender, Colors.strip(line));
return true;
}
}
return false;
}
private void parseChannelCommand(Player player, String[] split) { public static void parseChannelMuteList(Player player, String[] split) {
// So they just type /channel , We should probably send them to the help menu.. if (split.length == 0) {
if (split.length == 0 || split[0].equalsIgnoreCase("help") || split[0].equalsIgnoreCase("?")) { for (String line : channel_help) {
for (String line : channel_help) TownyMessaging.sendMessage(player, line);
TownyMessaging.sendMessage(player, line); }
} else if (split[0].equalsIgnoreCase("join")) { // /channel join [chn] (/label args[0] args[1] length = 2.) return;
parseChannelJoin(player, StringMgmt.remFirstArg(split)); }
} else if (split[0].equalsIgnoreCase("leave")) { String mutePerm = plugin.getChannelsHandler().getMutePermission();
parseChannelLeave(player, StringMgmt.remFirstArg(split)); String unmutePerm = plugin.getChannelsHandler().getUnmutePermission();
} else if (split[0].equalsIgnoreCase("mute")) { if ((mutePerm == null && unmutePerm == null) ||
parseChannelMute(player, StringMgmt.remFirstArg(split), true); (mutePerm != null && (!TownyUniverse.getInstance().getPermissionSource().testPermission(player, mutePerm))) ||
} else if (split[0].equalsIgnoreCase("unmute")) { (unmutePerm != null && (!TownyUniverse.getInstance().getPermissionSource().testPermission(player, unmutePerm)))) {
parseChannelMute(player, StringMgmt.remFirstArg(split), false); TownyMessaging.sendErrorMsg(player, Translatable.of("tc_err_you_dont_have_perm_mute_list"));
} else if (split[0].equalsIgnoreCase("mutelist")) { return;
parseChannelMuteList(player, StringMgmt.remFirstArg(split)); }
} else if (split[0].equalsIgnoreCase("list")) {
parseChannelList(player);
} else if (split[0].equalsIgnoreCase("soundtoggle")) {
parseChannelSoundToggle(player, StringMgmt.remFirstArg(split));
} else {
TownyMessaging.sendErrorMsg(player, Translatable.of("msg_err_invalid_sub"));
}
}
public static void parseChannelList(Player player) { Channel chan = plugin.getChannelsHandler().getChannel(split[0]);
// If not our command
Map<String, Channel> chanList = plugin.getChannelsHandler().getAllChannels();
Translator translator = Translator.locale(Translation.getLocale(player));
TownyMessaging.sendMessage(player, ChatTools.formatTitle("Channels")); // If we can't find the channel by name, look up all the channel commands for an alias
TownyMessaging.sendMessage(player, Colors.Gold + "Channel" + Colors.Gray + " - " + Colors.LightBlue + translator.of("tc_channel_list_status")); if (chan == null) {
for (Map.Entry<String, Channel> channel : chanList.entrySet()) { for (Channel chan2 : plugin.getChannelsHandler().getAllChannels().values()) {
if (channel.getValue().hasListenPermission(player)) for (String command : chan2.getCommands()) {
if (channel.getValue().isPresent(player.getName())) if (command.equalsIgnoreCase(split[0])) {
TownyMessaging.sendMessage(player, Colors.Gold + channel.getKey() + Colors.Gray + " - " + Colors.LightBlue + translator.of("tc_channel_list_in")); chan = chan2;
else break;
TownyMessaging.sendMessage(player, Colors.Gold + channel.getKey() + Colors.Gray + " - " + Colors.LightBlue + translator.of("tc_channel_list_out")); }
} }
} if (chan != null) {
break;
}
}
}
public static void parseChannelMuteList(Player player, String[] split) { if (chan == null) {
if (split.length == 0) { TownyMessaging.sendErrorMsg(player, Translatable.of("tc_err_no_channel_called_channel", split[0]));
for (String line : channel_help) { return;
TownyMessaging.sendMessage(player, line); }
}
return;
}
String mutePerm = plugin.getChannelsHandler().getMutePermission();
String unmutePerm = plugin.getChannelsHandler().getUnmutePermission();
if ((mutePerm == null && unmutePerm == null) ||
(mutePerm != null && (!TownyUniverse.getInstance().getPermissionSource().testPermission(player, mutePerm))) ||
(unmutePerm != null && (!TownyUniverse.getInstance().getPermissionSource().testPermission(player, unmutePerm)))) {
TownyMessaging.sendErrorMsg(player, Translatable.of("tc_err_you_dont_have_perm_mute_list"));
return;
}
Channel chan = plugin.getChannelsHandler().getChannel(split[0]); split[0] = chan.getName();
// If we can't find the channel by name, look up all the channel commands for an alias // TODO Support paging through this list
if (chan == null) { int count = 0;
for (Channel chan2 : plugin.getChannelsHandler().getAllChannels().values()) { String players = "";
for (String command : chan2.getCommands()) {
if (command.equalsIgnoreCase(split[0])) {
chan = chan2;
break;
}
}
if (chan != null) {
break;
}
}
}
if (chan == null) { if (chan.hasMuteList()) {
TownyMessaging.sendErrorMsg(player, Translatable.of("tc_err_no_channel_called_channel", split[0])); Iterator<String> iter = chan.getMuteList().iterator();
return; boolean first = true;
} while (iter.hasNext()) {
if (!first) {
players += Colors.Green + ", " + Colors.White;
}
players += iter.next();
count++;
}
}
split[0] = chan.getName(); if (count == 0) {
TownyMessaging.sendMessage(player, Translatable.of("tc_err_no_muted_players_in_channel", chan.getName()));
return;
}
// TODO Support paging through this list TownyMessaging.sendMessage(player, Translatable.of("tc_players_muted_in_channel", count, chan.getName(), players));
int count = 0; }
String players = "";
if (chan.hasMuteList()) { public static void parseChannelMute(Player player, String[] split, boolean mute) {
Iterator<String> iter = chan.getMuteList().iterator(); if (split.length < 2) {
boolean first = true; for (String line : channel_help) {
while (iter.hasNext()) { TownyMessaging.sendMessage(player, line);
if (!first) { }
players += Colors.Green + ", " + Colors.White; return;
} }
players += iter.next(); // Split[0] = Channelname
count++; // Split[1} = Player to be muted
} Player muteePlayer = Bukkit.getPlayer(split[1]);
} if (muteePlayer == null) {
TownyMessaging.sendErrorMsg(player, Translatable.of("tc_err_no_online_players_with_name", split[1]));
return;
}
Channel chan = plugin.getChannelsHandler().getChannel(split[0]);
if (count == 0) { // If we can't find the channel by name, look up all the channel commands for an alias
TownyMessaging.sendMessage(player, Translatable.of("tc_err_no_muted_players_in_channel", chan.getName())); if (chan == null) {
return; for (Channel chan2 : plugin.getChannelsHandler().getAllChannels().values()) {
} for (String command : chan2.getCommands()) {
if (command.equalsIgnoreCase(split[0])) {
chan = chan2;
break;
}
}
if (chan != null) {
break;
}
}
}
TownyMessaging.sendMessage(player, Translatable.of("tc_players_muted_in_channel", count, chan.getName(), players)); if (chan == null) {
} TownyMessaging.sendErrorMsg(player, Translatable.of("tc_err_no_channel_called_channel", split[0]));
return;
}
public static void parseChannelMute(Player player, String[] split, boolean mute) { if (mute) {
if (split.length < 2) { String mutePerm = plugin.getChannelsHandler().getMutePermission();
for (String line : channel_help) { if ((mutePerm == null) || (mutePerm != null && (!TownyUniverse.getInstance().getPermissionSource().testPermission(player, mutePerm)))) {
TownyMessaging.sendMessage(player, line); TownyMessaging.sendErrorMsg(player, Translatable.of("tc_err_you_dont_have_mute_perms"));
} return;
return; }
}
// Split[0] = Channelname
// Split[1} = Player to be muted
Player muteePlayer = Bukkit.getPlayer(split[1]);
if (muteePlayer == null) {
TownyMessaging.sendErrorMsg(player, Translatable.of("tc_err_no_online_players_with_name", split[1]));
return;
}
Channel chan = plugin.getChannelsHandler().getChannel(split[0]);
// If we can't find the channel by name, look up all the channel commands for an alias split[1] = muteePlayer.getName();
if (chan == null) {
for (Channel chan2 : plugin.getChannelsHandler().getAllChannels().values()) {
for (String command : chan2.getCommands()) {
if (command.equalsIgnoreCase(split[0])) {
chan = chan2;
break;
}
}
if (chan != null) {
break;
}
}
}
if (chan == null) { if (TownyUniverse.getInstance().getPermissionSource().isTownyAdmin(muteePlayer)) {
TownyMessaging.sendErrorMsg(player, Translatable.of("tc_err_no_channel_called_channel", split[0])); TownyMessaging.sendErrorMsg(player, Translatable.of("tc_err_you_cant_mute_admin"));
return; return;
} }
if (mute) { String unmutePerm = plugin.getChannelsHandler().getUnmutePermission();
String mutePerm = plugin.getChannelsHandler().getMutePermission(); if ((mutePerm != null && (TownyUniverse.getInstance().getPermissionSource().testPermission(muteePlayer, mutePerm))) ||
if ((mutePerm == null) || (mutePerm != null && (!TownyUniverse.getInstance().getPermissionSource().testPermission(player, mutePerm)))) { (unmutePerm != null && (TownyUniverse.getInstance().getPermissionSource().testPermission(muteePlayer, unmutePerm)))) {
TownyMessaging.sendErrorMsg(player, Translatable.of("tc_err_you_dont_have_mute_perms")); TownyMessaging.sendErrorMsg(player, Translatable.of("tc_err_you_cant_mute_chat_mod"));
return; return;
} }
split[1] = muteePlayer.getName(); if (!chan.mute(split[1])) {
TownyMessaging.sendMessage(player, Translatable.of("tc_player_already_muted_in_channel", chan.getName()));
return;
}
if (TownyUniverse.getInstance().getPermissionSource().isTownyAdmin(muteePlayer)) { TownyMessaging.sendMessage(player, Translatable.of("tc_player_is_now_muted_in_channel", split[1], chan.getName()));
TownyMessaging.sendErrorMsg(player, Translatable.of("tc_err_you_cant_mute_admin")); } else if (!mute) {
return; String unmutePerm = plugin.getChannelsHandler().getUnmutePermission();
} if ((unmutePerm == null) || (unmutePerm != null && (!TownyUniverse.getInstance().getPermissionSource().testPermission(player, unmutePerm)))) {
TownyMessaging.sendErrorMsg(player, Translatable.of("tc_err_you_dont_have_unmute_perm"));
return;
}
String unmutePerm = plugin.getChannelsHandler().getUnmutePermission(); split[1] = muteePlayer.getName();
if ((mutePerm != null && (TownyUniverse.getInstance().getPermissionSource().testPermission(muteePlayer, mutePerm))) ||
(unmutePerm != null && (TownyUniverse.getInstance().getPermissionSource().testPermission(muteePlayer, unmutePerm)))) {
TownyMessaging.sendErrorMsg(player, Translatable.of("tc_err_you_cant_mute_chat_mod"));
return;
}
if (!chan.mute(split[1])) {
TownyMessaging.sendMessage(player, Translatable.of("tc_player_already_muted_in_channel", chan.getName()));
return;
}
TownyMessaging.sendMessage(player, Translatable.of("tc_player_is_now_muted_in_channel", split[1], chan.getName()));
} else if (!mute) {
String unmutePerm = plugin.getChannelsHandler().getUnmutePermission();
if ((unmutePerm == null) || (unmutePerm != null && (!TownyUniverse.getInstance().getPermissionSource().testPermission(player, unmutePerm)))) {
TownyMessaging.sendErrorMsg(player, Translatable.of("tc_err_you_dont_have_unmute_perm"));
return;
}
split[1] = muteePlayer.getName();
if (!chan.unmute(split[1])) { if (!chan.unmute(split[1])) {
TownyMessaging.sendMessage(player, Translatable.of("tc_player_is_not_muted_in_channel", chan.getName())); TownyMessaging.sendMessage(player, Translatable.of("tc_player_is_not_muted_in_channel", chan.getName()));
return; return;
} }
TownyMessaging.sendMessage(player, Translatable.of("tc_player_is_now_unmuted_in_channel", split[1], chan.getName())); TownyMessaging.sendMessage(player, Translatable.of("tc_player_is_now_unmuted_in_channel", split[1], chan.getName()));
return; return;
} }
} }
public static void parseChannelLeave(Player player, String[] split) { public static void parseChannelLeave(Player player, String[] split) {
if (split.length == 0) { if (split.length == 0) {
for (String line : channel_help) { for (String line : channel_help) {
TownyMessaging.sendMessage(player, line); TownyMessaging.sendMessage(player, line);
} }
return; return;
} }
Channel chan = plugin.getChannelsHandler().getChannel(split[0]); Channel chan = plugin.getChannelsHandler().getChannel(split[0]);
// If we can't find the channel by name, look up all the channel commands for an alias // If we can't find the channel by name, look up all the channel commands for an alias
if (chan == null) { if (chan == null) {
for (Channel chan2 : plugin.getChannelsHandler().getAllChannels().values()) { for (Channel chan2 : plugin.getChannelsHandler().getAllChannels().values()) {
for (String command : chan2.getCommands()) { for (String command : chan2.getCommands()) {
if (command.equalsIgnoreCase(split[0])) { if (command.equalsIgnoreCase(split[0])) {
chan = chan2; chan = chan2;
break; break;
} }
} }
if (chan != null) { if (chan != null) {
break; break;
} }
} }
} }
if (chan == null) { if (chan == null) {
TownyMessaging.sendErrorMsg(player, Translatable.of("tc_err_no_channel_called_channel", split[0])); TownyMessaging.sendErrorMsg(player, Translatable.of("tc_err_no_channel_called_channel", split[0]));
return; return;
} }
// You can leave if: // You can leave if:
// - Towny recognizes your permissions plugin AND // - Towny recognizes your permissions plugin AND
// - channel has leaving permission set AND [by default they always do and you can provide your own permission name] // - channel has leaving permission set AND [by default they always do and you can provide your own permission name]
// - player has leaving permission set [by default they don't] // - player has leaving permission set [by default they don't]
String leavePerm = chan.getLeavePermission(); String leavePerm = chan.getLeavePermission();
if (leavePerm == null || if (leavePerm == null ||
(leavePerm != null && (!TownyUniverse.getInstance().getPermissionSource().testPermission(player, leavePerm)))) { (leavePerm != null && (!TownyUniverse.getInstance().getPermissionSource().testPermission(player, leavePerm)))) {
TownyMessaging.sendErrorMsg(player, Translatable.of("tc_err_you_cannot_leave_channel", chan.getName())); TownyMessaging.sendErrorMsg(player, Translatable.of("tc_err_you_cannot_leave_channel", chan.getName()));
return; return;
} }
// If we fail you weren't in there to start with // If we fail you weren't in there to start with
if (!chan.leave(player)) { if (!chan.leave(player)) {
TownyMessaging.sendMessage(player, Translatable.of("tc_you_already_left_channel", chan.getName())); TownyMessaging.sendMessage(player, Translatable.of("tc_you_already_left_channel", chan.getName()));
return; return;
} }
// Announce it // Announce it
TownyMessaging.sendMessage(player, Translatable.of("tc_you_left_channel", chan.getName())); TownyMessaging.sendMessage(player, Translatable.of("tc_you_left_channel", chan.getName()));
// Find what the next channel is if any // Find what the next channel is if any
Channel nextChannel = null; Channel nextChannel = null;
if (plugin.getChannelsHandler().getDefaultChannel() != null && plugin.getChannelsHandler().getDefaultChannel().isPresent(player.getName())) if (plugin.getChannelsHandler().getDefaultChannel() != null && plugin.getChannelsHandler().getDefaultChannel().isPresent(player.getName()))
nextChannel = plugin.getChannelsHandler().getDefaultChannel(); nextChannel = plugin.getChannelsHandler().getDefaultChannel();
if (nextChannel == null) if (nextChannel == null)
nextChannel = plugin.getChannelsHandler().getActiveChannel(player, channelTypes.GLOBAL); nextChannel = plugin.getChannelsHandler().getActiveChannel(player, channelTypes.GLOBAL);
// If the new channel is not us, announce it // If the new channel is not us, announce it
if (nextChannel != null && !chan.getName().equalsIgnoreCase(nextChannel.getName())) { if (nextChannel != null && !chan.getName().equalsIgnoreCase(nextChannel.getName())) {
TownyMessaging.sendMessage(player, Translatable.of("tc_you_are_now_talking_in_channel",nextChannel.getName())); TownyMessaging.sendMessage(player, Translatable.of("tc_you_are_now_talking_in_channel", nextChannel.getName()));
plugin.setPlayerChannel(player, nextChannel); plugin.setPlayerChannel(player, nextChannel);
} }
} }
public static void parseChannelJoin(Player player, String[] split) { public static void parseChannelJoin(Player player, String[] split) {
if (split.length == 0) { if (split.length == 0) {
for (String line : channel_help) { for (String line : channel_help) {
TownyMessaging.sendMessage(player, line); TownyMessaging.sendMessage(player, line);
} }
return; return;
} }
// Removed first argument of the list so now args[0] is the channel he wants to join // Removed first argument of the list so now args[0] is the channel he wants to join
// If we call this from /join, we just won't remove the argument! // If we call this from /join, we just won't remove the argument!
Channel chan = plugin.getChannelsHandler().getChannel(split[0]); Channel chan = plugin.getChannelsHandler().getChannel(split[0]);
if (chan == null) { // From Old JoinCommand (If we don't find a channel with said name, check aliases) if (chan == null) { // From Old JoinCommand (If we don't find a channel with said name, check aliases)
for (Channel chan2 : plugin.getChannelsHandler().getAllChannels().values()) { for (Channel chan2 : plugin.getChannelsHandler().getAllChannels().values()) {
for (String command : chan2.getCommands()) { for (String command : chan2.getCommands()) {
if (command.equalsIgnoreCase(split[0])) { if (command.equalsIgnoreCase(split[0])) {
chan = chan2; chan = chan2;
break; break;
} }
} }
if (chan != null) { if (chan != null) {
break; break;
} }
} }
} }
if (chan == null) { if (chan == null) {
TownyMessaging.sendErrorMsg(player, Translatable.of("tc_err_no_channel_called_channel", split[0])); TownyMessaging.sendErrorMsg(player, Translatable.of("tc_err_no_channel_called_channel", split[0]));
return; return;
} }
// You can join if: // You can join if:
// - Towny doesn't recognize your permissions plugin // - Towny doesn't recognize your permissions plugin
// - channel has no permission set OR [by default they don't] // - channel has no permission set OR [by default they don't]
// - channel has permission set AND: // - channel has permission set AND:
// - player has channel permission // - player has channel permission
if (!chan.hasListenPermission(player)) { if (!chan.hasListenPermission(player)) {
TownyMessaging.sendErrorMsg(player, Translatable.of("tc_err_you_cannot_join_channel", chan.getName())); TownyMessaging.sendErrorMsg(player, Translatable.of("tc_err_you_cannot_join_channel", chan.getName()));
return; return;
} }
if (!chan.join(player)) { if (!chan.join(player)) {
TownyMessaging.sendMessage(player, Translatable.of("tc_you_are_already_in_channel", chan.getName())); TownyMessaging.sendMessage(player, Translatable.of("tc_you_are_already_in_channel", chan.getName()));
return; return;
} }
Bukkit.getPluginManager().callEvent(new PlayerJoinChatChannelEvent(player, chan)); Bukkit.getPluginManager().callEvent(new PlayerJoinChatChannelEvent(player, chan));
TownyMessaging.sendMessage(player, Translatable.of("tc_you_joined_channel", Colors.translateColorCodes(chan.getMessageColour()) + chan.getName())); TownyMessaging.sendMessage(player, Translatable.of("tc_you_joined_channel", Colors.translateColorCodes(chan.getMessageColour()) + chan.getName()));
} }
public static void parseChannelSoundToggle(Player player, String[] split) { public static void parseChannelSoundToggle(Player player, String[] split) {
if (split.length == 0) { if (split.length == 0) {
for (String line : channel_help) { for (String line : channel_help) {
TownyMessaging.sendMessage(player, line); TownyMessaging.sendMessage(player, line);
} }
return; return;
} }
Channel chan = plugin.getChannelsHandler().getChannel(split[0]); Channel chan = plugin.getChannelsHandler().getChannel(split[0]);
if (chan == null) { if (chan == null) {
TownyMessaging.sendErrorMsg(player, Translatable.of("tc_err_no_channel_called_channel", split[0])); TownyMessaging.sendErrorMsg(player, Translatable.of("tc_err_no_channel_called_channel", split[0]));
return; return;
} }
if (chan.isSoundMuted(player)) { if (chan.isSoundMuted(player)) {
chan.unmuteSound(player); chan.unmuteSound(player);
TownyMessaging.sendMessage(player, Translatable.of("tc_player_channel_sound_unmuted")); TownyMessaging.sendMessage(player, Translatable.of("tc_player_channel_sound_unmuted"));
} else { } else {
chan.muteSound(player); chan.muteSound(player);
TownyMessaging.sendMessage(player, Translatable.of("tc_player_channel_sound_muted")); TownyMessaging.sendMessage(player, Translatable.of("tc_player_channel_sound_muted"));
} }
} }
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (sender instanceof Player) {
Player player = (Player) sender;
if (command.getName().equalsIgnoreCase("channel")) {
if (label.equalsIgnoreCase("join")) {
parseChannelJoin(player, args);
return true;
}
if (label.equalsIgnoreCase("leave")) {
parseChannelLeave(player, args);
return true;
}
if (label.equalsIgnoreCase("mutelist")) {
parseChannelMuteList(player, args);
return true;
}
if (label.equalsIgnoreCase("chmute")) {
parseChannelMute(player, args, true);
return true;
}
if (label.equalsIgnoreCase("chunmute")) {
parseChannelMute(player, args, false);
return true;
}
parseChannelCommand(player, args);
return true;
}
} else {
// Console
for (String line : channel_help) {
TownyMessaging.sendMessage(sender, Colors.strip(line));
return true;
}
}
return false;
}
private void parseChannelCommand(Player player, String[] split) {
// So they just type /channel , We should probably send them to the help menu..
if (split.length == 0 || split[0].equalsIgnoreCase("help") || split[0].equalsIgnoreCase("?")) {
for (String line : channel_help)
TownyMessaging.sendMessage(player, line);
} else if (split[0].equalsIgnoreCase("join")) { // /channel join [chn] (/label args[0] args[1] length = 2.)
parseChannelJoin(player, StringMgmt.remFirstArg(split));
} else if (split[0].equalsIgnoreCase("leave")) {
parseChannelLeave(player, StringMgmt.remFirstArg(split));
} else if (split[0].equalsIgnoreCase("mute")) {
parseChannelMute(player, StringMgmt.remFirstArg(split), true);
} else if (split[0].equalsIgnoreCase("unmute")) {
parseChannelMute(player, StringMgmt.remFirstArg(split), false);
} else if (split[0].equalsIgnoreCase("mutelist")) {
parseChannelMuteList(player, StringMgmt.remFirstArg(split));
} else if (split[0].equalsIgnoreCase("list")) {
parseChannelList(player);
} else if (split[0].equalsIgnoreCase("soundtoggle")) {
parseChannelSoundToggle(player, StringMgmt.remFirstArg(split));
} else {
TownyMessaging.sendErrorMsg(player, Translatable.of("msg_err_invalid_sub"));
}
}
} }
@@ -17,43 +17,44 @@ import java.util.List;
*/ */
public class TownyChatCommand extends BaseCommand implements CommandExecutor { public class TownyChatCommand extends BaseCommand implements CommandExecutor {
private Chat plugin; private static final List<String> townychat_help = new ArrayList<String>();
private static final List<String> townychat_help = new ArrayList<String>();
static { static {
townychat_help.add(ChatTools.formatTitle("/townychat")); townychat_help.add(ChatTools.formatTitle("/townychat"));
//TODO: Add lang strings for description! //TODO: Add lang strings for description!
townychat_help.add(ChatTools.formatCommand("", "/townychat", "reload", "")); townychat_help.add(ChatTools.formatCommand("", "/townychat", "reload", ""));
} }
public TownyChatCommand(Chat instance) { private Chat plugin;
this.plugin = instance;
} public TownyChatCommand(Chat instance) {
this.plugin = instance;
}
@Override @Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (cmd.getName().equalsIgnoreCase("townychat")) { if (cmd.getName().equalsIgnoreCase("townychat")) {
parseTownyChatCommand(sender, args); parseTownyChatCommand(sender, args);
return true; return true;
} }
return false; return false;
} }
private void parseTownyChatCommand(CommandSender sender, String[] split) { private void parseTownyChatCommand(CommandSender sender, String[] split) {
if (split.length == 0 || split[0].equalsIgnoreCase("help") || split[0].equalsIgnoreCase("?")) { if (split.length == 0 || split[0].equalsIgnoreCase("help") || split[0].equalsIgnoreCase("?")) {
for (String line : townychat_help) { for (String line : townychat_help) {
TownyMessaging.sendMessage(sender, line); TownyMessaging.sendMessage(sender, line);
} }
} else if (split[0].equalsIgnoreCase("reload")) { } else if (split[0].equalsIgnoreCase("reload")) {
plugin.reload(); plugin.reload();
TownyMessaging.sendMessage(sender, Translatable.of("tc_settings_reloaded")); TownyMessaging.sendMessage(sender, Translatable.of("tc_settings_reloaded"));
} else { } else {
TownyMessaging.sendErrorMsg(sender, Translatable.of("tc_err_unrecognized_command_format")); TownyMessaging.sendErrorMsg(sender, Translatable.of("tc_err_unrecognized_command_format"));
} }
} }
} }
@@ -1,95 +1,94 @@
package com.palmergames.bukkit.TownyChat.Command.commandobjects; package com.palmergames.bukkit.TownyChat.Command.commandobjects;
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.events.PlayerJoinChatChannelEvent; import com.palmergames.bukkit.TownyChat.events.PlayerJoinChatChannelEvent;
import com.palmergames.bukkit.towny.TownyMessaging; import com.palmergames.bukkit.towny.TownyMessaging;
import com.palmergames.bukkit.towny.object.Translatable; import com.palmergames.bukkit.towny.object.Translatable;
import com.palmergames.bukkit.towny.scheduling.TaskScheduler; import com.palmergames.bukkit.towny.scheduling.TaskScheduler;
import com.palmergames.bukkit.util.Colors; import com.palmergames.bukkit.util.Colors;
import com.palmergames.util.StringMgmt; import com.palmergames.util.StringMgmt;
import org.bukkit.Bukkit;
import org.bukkit.Bukkit; import org.bukkit.command.CommandSender;
import org.bukkit.command.CommandSender; import org.bukkit.command.defaults.BukkitCommand;
import org.bukkit.command.defaults.BukkitCommand; import org.bukkit.entity.Player;
import org.bukkit.entity.Player;
public class ChannelJoinAliasCommand extends BukkitCommand {
public class ChannelJoinAliasCommand extends BukkitCommand { public Channel channel;
public Channel channel; public Chat plugin;
public Chat plugin;
public ChannelJoinAliasCommand(String name, Channel channel, Chat plugin) {
public ChannelJoinAliasCommand(String name, Channel channel, Chat plugin) { super(name);
super(name); this.channel = channel;
this.channel = channel; this.plugin = plugin;
this.plugin = plugin; this.description = name + " - Channel command join alias for " + channel.getName();
this.description = name + " - Channel command join alias for " + channel.getName(); this.usageMessage = "/" + name;
this.usageMessage = "/" + name; }
}
@Override
@Override public boolean execute(CommandSender commandSender, String label, String[] args) {
public boolean execute(CommandSender commandSender, String label, String[] args) { if (commandSender instanceof Player) { // So a player has ran some /g command or something
if (commandSender instanceof Player) { // So a player has ran some /g command or something if (channel.getCommands().contains(this.getName())) { // Should in theory always be true.
if (channel.getCommands().contains(this.getName())) { // Should in theory always be true. final Player player = (Player) commandSender;
final Player player = (Player) commandSender; String message = "";
String message = ""; if (args.length > 0) {
if (args.length > 0) { message = StringMgmt.join(args, " ");
message = StringMgmt.join(args, " "); }
} if (message.isEmpty()) {
if (message.isEmpty()) { Channel chan = plugin.getPlayerChannel(player);
Channel chan = plugin.getPlayerChannel(player); if (chan != null && chan.getName().equalsIgnoreCase(channel.getName())) {
if (chan != null && chan.getName().equalsIgnoreCase(channel.getName())) { TownyMessaging.sendMessage(player, Translatable.of("tc_you_are_already_in_channel", channel.getName()));
TownyMessaging.sendMessage(player, Translatable.of("tc_you_are_already_in_channel", channel.getName())); return true;
return true; } else {
} else { // You can join a channel if:
// You can join a channel if: // - Towny doesn't recognize your permissions plugin
// - Towny doesn't recognize your permissions plugin // - channel has no permission set [by default they don't] OR
// - channel has no permission set [by default they don't] OR // - channel has permission set AND:
// - channel has permission set AND: // - player has channel permission
// - player has channel permission // - the Channel is designated as being joinable (which they are by default.)
// - the Channel is designated as being joinable (which they are by default.) if (!channel.hasSpeakPermission(player) || !channel.isFocusable()) {
if (!channel.hasSpeakPermission(player) || !channel.isFocusable()) { TownyMessaging.sendErrorMsg(player, Translatable.of("tc_err_you_cannot_join_channel", channel.getName()));
TownyMessaging.sendErrorMsg(player, Translatable.of("tc_err_you_cannot_join_channel", channel.getName())); return true;
return true; }
}
plugin.setPlayerChannel(player, channel);
plugin.setPlayerChannel(player, channel); TownyMessaging.sendMessage(player, Translatable.of("tc_you_are_now_talking_in_channel", Colors.translateColorCodes(channel.getMessageColour()) + channel.getName()));
TownyMessaging.sendMessage(player, Translatable.of("tc_you_are_now_talking_in_channel", Colors.translateColorCodes(channel.getMessageColour()) + channel.getName())); Bukkit.getPluginManager().callEvent(new PlayerJoinChatChannelEvent(player, channel));
Bukkit.getPluginManager().callEvent(new PlayerJoinChatChannelEvent(player, channel)); return true;
return true; }
} } else {
} else { if (channel.isMuted(player.getName())) {
if (channel.isMuted(player.getName())) { TownyMessaging.sendErrorMsg(player, Translatable.of("tc_err_you_are_currently_muted_in_channel", channel.getName()));
TownyMessaging.sendErrorMsg(player, Translatable.of("tc_err_you_are_currently_muted_in_channel", channel.getName())); return true;
return true; }
} // You can speak in a channel if:
// You can speak in a channel if: // - Towny doesn't recognize your permissions plugin
// - Towny doesn't recognize your permissions plugin // - channel has no permission set [by default they don't] OR
// - channel has no permission set [by default they don't] OR // - channel has permission set AND:
// - channel has permission set AND: // - player has channel permission
// - player has channel permission if (!channel.hasSpeakPermission(player)) {
if (!channel.hasSpeakPermission(player)) { TownyMessaging.sendErrorMsg(player, Translatable.of("tc_err_you_cannot_join_channel", channel.getName()));
TownyMessaging.sendErrorMsg(player, Translatable.of("tc_err_you_cannot_join_channel", channel.getName())); return true;
return true; }
}
plugin.getTownyPlayerListener().directedChat.put(player, channel.getName().toLowerCase());
plugin.getTownyPlayerListener().directedChat.put(player, channel.getName().toLowerCase());
final String msg = message;
final String msg = message;
// https://www.spigotmc.org/threads/plugins-triggering-commands-async.31815/
// https://www.spigotmc.org/threads/plugins-triggering-commands-async.31815/ TaskScheduler scheduler = plugin.getScheduler();
TaskScheduler scheduler = plugin.getScheduler(); if (!scheduler.isEntityThread(player)) {
if (!scheduler.isEntityThread(player)) { scheduler.run(player, () -> player.chat(msg));
scheduler.run(player, () -> player.chat(msg)); } else {
} else { player.chat(msg);
player.chat(msg); }
} return true;
return true; }
} }
} return true;
return true; } else {
} else { TownyMessaging.sendMsg("You may not use this command as the console!");
TownyMessaging.sendMsg("You may not use this command as the console!"); return false;
return false; }
} }
} }
}
@@ -18,212 +18,212 @@ import net.kyori.adventure.text.minimessage.tag.standard.StandardTags;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
public class TownyChatFormatter { public class TownyChatFormatter {
static TagResolver parser(LocalTownyChatEvent event) { static TagResolver parser(LocalTownyChatEvent event) {
return TagResolver.resolver( return TagResolver.resolver(
TagResolver.resolver("worldname", Tag.inserting(Component.text(getWorldTag(event)))), TagResolver.resolver("worldname", Tag.inserting(Component.text(getWorldTag(event)))),
TagResolver.resolver("town", Tag.inserting(Component.text(getTownName(event.getResident())))), TagResolver.resolver("town", Tag.inserting(Component.text(getTownName(event.getResident())))),
TagResolver.resolver("townformatted", Tag.inserting(Component.text(formatTownTag(event.getResident(), false, true)))), TagResolver.resolver("townformatted", Tag.inserting(Component.text(formatTownTag(event.getResident(), false, true)))),
TagResolver.resolver("towntag", Tag.inserting(Component.text(formatTownTag(event.getResident(), false, false)))), TagResolver.resolver("towntag", Tag.inserting(Component.text(formatTownTag(event.getResident(), false, false)))),
TagResolver.resolver("towntagoverride", Tag.inserting(Component.text(formatTownTag(event.getResident(), true, false)))), TagResolver.resolver("towntagoverride", Tag.inserting(Component.text(formatTownTag(event.getResident(), true, false)))),
TagResolver.resolver("nation", Tag.inserting(Component.text(getNationName(event.getResident())))), TagResolver.resolver("nation", Tag.inserting(Component.text(getNationName(event.getResident())))),
TagResolver.resolver("nationformatted", Tag.inserting(Component.text(formatNationTag(event.getResident(), false, true)))), TagResolver.resolver("nationformatted", Tag.inserting(Component.text(formatNationTag(event.getResident(), false, true)))),
TagResolver.resolver("nationtag", Tag.inserting(Component.text(formatNationTag(event.getResident(), false, false)))), TagResolver.resolver("nationtag", Tag.inserting(Component.text(formatNationTag(event.getResident(), false, false)))),
TagResolver.resolver("nationtagoverride", Tag.inserting(Component.text(formatNationTag(event.getResident(), true, false)))), TagResolver.resolver("nationtagoverride", Tag.inserting(Component.text(formatNationTag(event.getResident(), true, false)))),
TagResolver.resolver("townytag", Tag.inserting(Component.text(formatTownyTag(event.getResident(), false, true)))), TagResolver.resolver("townytag", Tag.inserting(Component.text(formatTownyTag(event.getResident(), false, true)))),
TagResolver.resolver("townyformatted", Tag.inserting(Component.text(formatTownyTag(event.getResident(), false, false)))), TagResolver.resolver("townyformatted", Tag.inserting(Component.text(formatTownyTag(event.getResident(), false, false)))),
TagResolver.resolver("townytagoverride", Tag.inserting(Component.text(formatTownyTag(event.getResident(), true, false)))), TagResolver.resolver("townytagoverride", Tag.inserting(Component.text(formatTownyTag(event.getResident(), true, false)))),
TagResolver.resolver("title", Tag.inserting(Component.text(getPrefix(event.getResident(), true)))), TagResolver.resolver("title", Tag.inserting(Component.text(getPrefix(event.getResident(), true)))),
TagResolver.resolver("surname", Tag.inserting(Component.text(getSuffix(event.getResident(), false)))), TagResolver.resolver("surname", Tag.inserting(Component.text(getSuffix(event.getResident(), false)))),
TagResolver.resolver("townynameprefix", Tag.inserting(Component.text(getNamePrefix(event.getResident())))), TagResolver.resolver("townynameprefix", Tag.inserting(Component.text(getNamePrefix(event.getResident())))),
TagResolver.resolver("townynamepostfix", Tag.inserting(Component.text(getNamePostfix(event.getResident())))), TagResolver.resolver("townynamepostfix", Tag.inserting(Component.text(getNamePostfix(event.getResident())))),
TagResolver.resolver("townyprefix", Tag.inserting(Component.text(getPrefix(event.getResident(), false)))), TagResolver.resolver("townyprefix", Tag.inserting(Component.text(getPrefix(event.getResident(), false)))),
TagResolver.resolver("townypostfix", Tag.inserting(Component.text(getSuffix(event.getResident(), false)))), TagResolver.resolver("townypostfix", Tag.inserting(Component.text(getSuffix(event.getResident(), false)))),
TagResolver.resolver("townycolor", Tag.inserting(Component.text(getTownyColour(event.getResident())))), TagResolver.resolver("townycolor", Tag.inserting(Component.text(getTownyColour(event.getResident())))),
TagResolver.resolver("group", Tag.inserting(Component.text(getVaultGroup(event.getEvent().getPlayer())))), TagResolver.resolver("group", Tag.inserting(Component.text(getVaultGroup(event.getEvent().getPlayer())))),
TagResolver.resolver("permprefix", Tag.inserting(Component.text(getVaultPrefixSuffix(event.getResident(), "prefix")))), TagResolver.resolver("permprefix", Tag.inserting(Component.text(getVaultPrefixSuffix(event.getResident(), "prefix")))),
TagResolver.resolver("permsuffix", Tag.inserting(Component.text(getVaultPrefixSuffix(event.getResident(), "suffix")))), TagResolver.resolver("permsuffix", Tag.inserting(Component.text(getVaultPrefixSuffix(event.getResident(), "suffix")))),
TagResolver.resolver("permuserprefix", Tag.inserting(Component.text(getVaultPrefixSuffix(event.getResident(), "userprefix")))), TagResolver.resolver("permuserprefix", Tag.inserting(Component.text(getVaultPrefixSuffix(event.getResident(), "userprefix")))),
TagResolver.resolver("permusersuffix", Tag.inserting(Component.text(getVaultPrefixSuffix(event.getResident(), "usersuffix")))), TagResolver.resolver("permusersuffix", Tag.inserting(Component.text(getVaultPrefixSuffix(event.getResident(), "usersuffix")))),
TagResolver.resolver("permgroupprefix", Tag.inserting(Component.text(getVaultPrefixSuffix(event.getResident(), "groupprefix")))), TagResolver.resolver("permgroupprefix", Tag.inserting(Component.text(getVaultPrefixSuffix(event.getResident(), "groupprefix")))),
TagResolver.resolver("permgroupsuffix", Tag.inserting(Component.text(getVaultPrefixSuffix(event.getResident(), "groupsuffix")))), TagResolver.resolver("permgroupsuffix", Tag.inserting(Component.text(getVaultPrefixSuffix(event.getResident(), "groupsuffix")))),
TagResolver.resolver("playername", Tag.inserting(Component.text(event.getEvent().getPlayer().getName()))), TagResolver.resolver("playername", Tag.inserting(Component.text(event.getEvent().getPlayer().getName()))),
TagResolver.resolver("primaryresidentrank", Tag.inserting(Component.text(getPrimaryRankPrefix(event.getResident())))) TagResolver.resolver("primaryresidentrank", Tag.inserting(Component.text(getPrimaryRankPrefix(event.getResident()))))
); );
} }
public static Component parseMessage(String message, LocalTownyChatEvent event) { public static Component parseMessage(String message, LocalTownyChatEvent event) {
final MiniMessage miniMessage = MiniMessage.builder() final MiniMessage miniMessage = MiniMessage.builder()
.tags(TagResolver.builder() .tags(TagResolver.builder()
.resolver(parser(event)) .resolver(parser(event))
.resolver(StandardTags.defaults()) .resolver(StandardTags.defaults())
.build()) .build())
.build(); .build();
return miniMessage.deserialize(message); return miniMessage.deserialize(message);
} }
public static TagResolver getChatFormat(LocalTownyChatEvent event) { public static TagResolver getChatFormat(LocalTownyChatEvent event) {
return TagResolver.builder() return TagResolver.builder()
.resolver(parser(event)) .resolver(parser(event))
.resolver(StandardTags.defaults()) .resolver(StandardTags.defaults())
.build(); .build();
} }
public static String getWorldTag(LocalTownyChatEvent event) { public static String getWorldTag(LocalTownyChatEvent event) {
return String.format(ChatSettings.getWorldTag(), event.getEvent().getPlayer().getWorld().getName()); return String.format(ChatSettings.getWorldTag(), event.getEvent().getPlayer().getWorld().getName());
} }
public static String getTownName(Resident resident) { public static String getTownName(Resident resident) {
return resident.hasTown() ? resident.getTownOrNull().getName() : ""; return resident.hasTown() ? resident.getTownOrNull().getName() : "";
} }
public static String getNationName(Resident resident) { public static String getNationName(Resident resident) {
return resident.hasNation() ? resident.getNationOrNull().getName() : ""; return resident.hasNation() ? resident.getNationOrNull().getName() : "";
} }
/** /**
* @param resident * @param resident
* @param override use full names if no tag is present * @param override use full names if no tag is present
* @param full Only use full names (no tags). * @param full Only use full names (no tags).
* @return string containing the correctly formatted nation/town data * @return string containing the correctly formatted nation/town data
*/ */
public static String formatTownyTag(Resident resident, Boolean override, Boolean full) { public static String formatTownyTag(Resident resident, Boolean override, Boolean full) {
if (resident.hasTown()) { if (resident.hasTown()) {
Town town = TownyAPI.getInstance().getResidentTownOrNull(resident); Town town = TownyAPI.getInstance().getResidentTownOrNull(resident);
String townTag = getTag(town); String townTag = getTag(town);
Nation nation = null; Nation nation = null;
String nationTag = null; String nationTag = null;
if (resident.hasNation()) { if (resident.hasNation()) {
nation = TownyAPI.getInstance().getResidentNationOrNull(resident); nation = TownyAPI.getInstance().getResidentNationOrNull(resident);
nationTag = getTag(nation); nationTag = getTag(nation);
} }
String nTag = "", tTag = ""; String nTag = "", tTag = "";
//Force use of full names only //Force use of full names only
if (full) { if (full) {
nationTag = ""; nationTag = "";
townTag = ""; townTag = "";
} }
// Load town tags/names // Load town tags/names
if (townTag != null && !townTag.isEmpty()) if (townTag != null && !townTag.isEmpty())
tTag = townTag; tTag = townTag;
else if (override || full) else if (override || full)
tTag = getName(town); tTag = getName(town);
// Load the nation tags/names // Load the nation tags/names
if ((nationTag != null) && !nationTag.isEmpty()) if ((nationTag != null) && !nationTag.isEmpty())
nTag = nationTag; nTag = nationTag;
else if (resident.hasNation() && (override || full)) else if (resident.hasNation() && (override || full))
nTag = getName(nation); nTag = getName(nation);
// 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.getBothTag().contains("%t") || ChatSettings.getBothTag().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.getBothTag().replace("%t", tTag).replace("%n", nTag); return ChatSettings.getBothTag().replace("%t", tTag).replace("%n", nTag);
} else { } else {
return String.format(ChatSettings.getBothTag(), nTag, tTag); return String.format(ChatSettings.getBothTag(), nTag, tTag);
} }
} }
if (!nTag.isEmpty()) { if (!nTag.isEmpty()) {
return String.format(ChatSettings.getNationTag(), nTag); return String.format(ChatSettings.getNationTag(), nTag);
} }
if (!tTag.isEmpty()) { if (!tTag.isEmpty()) {
return String.format(ChatSettings.getTownTag(), tTag); return String.format(ChatSettings.getTownTag(), tTag);
} }
} }
return ""; return "";
} }
public static String formatTownTag(Resident resident, Boolean override, Boolean full) { public static String formatTownTag(Resident resident, Boolean override, Boolean full) {
if (resident.hasTown()) { if (resident.hasTown()) {
Town town = TownyAPI.getInstance().getResidentTownOrNull(resident); Town town = TownyAPI.getInstance().getResidentTownOrNull(resident);
if (full) if (full)
return String.format(ChatSettings.getTownTag(), getName(town)); return String.format(ChatSettings.getTownTag(), getName(town));
else if (town.hasTag()) else if (town.hasTag())
return String.format(ChatSettings.getTownTag(), getTag(town)); return String.format(ChatSettings.getTownTag(), getTag(town));
else if (override) else if (override)
return String.format(ChatSettings.getTownTag(), getName(town)); return String.format(ChatSettings.getTownTag(), getName(town));
} }
return ""; return "";
} }
public static String formatNationTag(Resident resident, Boolean override, Boolean full) { public static String formatNationTag(Resident resident, Boolean override, Boolean full) {
if (resident.hasNation()) { if (resident.hasNation()) {
Nation nation = TownyAPI.getInstance().getResidentNationOrNull(resident); Nation nation = TownyAPI.getInstance().getResidentNationOrNull(resident);
if (full) if (full)
return String.format(ChatSettings.getNationTag(), getName(nation)); return String.format(ChatSettings.getNationTag(), getName(nation));
else if (nation.hasTag()) else if (nation.hasTag())
return String.format(ChatSettings.getNationTag(), getTag(nation)); return String.format(ChatSettings.getNationTag(), getTag(nation));
else if (override) else if (override)
return String.format(ChatSettings.getNationTag(), getName(nation)); return String.format(ChatSettings.getNationTag(), getName(nation));
} }
return ""; return "";
} }
public static String getNamePrefix(Resident resident) { public static String getNamePrefix(Resident resident) {
if (resident == null) if (resident == null)
return ""; return "";
if (resident.isKing()) if (resident.isKing())
return TownySettings.getKingPrefix(resident); return TownySettings.getKingPrefix(resident);
else if (resident.isMayor()) else if (resident.isMayor())
return TownySettings.getMayorPrefix(resident); return TownySettings.getMayorPrefix(resident);
return ""; return "";
} }
public static String getNamePostfix(Resident resident) { public static String getNamePostfix(Resident resident) {
if (resident == null) if (resident == null)
return ""; return "";
if (resident.isKing()) if (resident.isKing())
return TownySettings.getKingPostfix(resident); return TownySettings.getKingPostfix(resident);
else if (resident.isMayor()) else if (resident.isMayor())
return TownySettings.getMayorPostfix(resident); return TownySettings.getMayorPostfix(resident);
return ""; return "";
} }
public static String getPrimaryRankPrefix(Resident resident) { public static String getPrimaryRankPrefix(Resident resident) {
if (resident == null) if (resident == null)
return ""; return "";
String rank = resident.getPrimaryRankPrefix(); String rank = resident.getPrimaryRankPrefix();
return rank.isEmpty() ? "" : rank + " "; return rank.isEmpty() ? "" : rank + " ";
} }
private static String getName(Government gov) { private static String getName(Government gov) {
return StringMgmt.remUnderscore(gov.getName()); return StringMgmt.remUnderscore(gov.getName());
} }
private static String getTag(Government gov) {
return gov.getTag();
}
public static String getPrefix(Resident resident, boolean blank) { private static String getTag(Government gov) {
return resident.hasTitle() ? resident.getTitle() + " " : blank ? "" : getNamePrefix(resident); return gov.getTag();
} }
public static String getSuffix(Resident resident, boolean blank) { public static String getPrefix(Resident resident, boolean blank) {
return resident.hasSurname() ? " " + resident.getSurname() : blank ? "" : getNamePostfix(resident); return resident.hasTitle() ? resident.getTitle() + " " : blank ? "" : getNamePrefix(resident);
} }
public static String getTownyColour(Resident resident) { public static String getSuffix(Resident resident, boolean blank) {
return !resident.hasTown() return resident.hasSurname() ? " " + resident.getSurname() : blank ? "" : getNamePostfix(resident);
? ChatSettings.getNomadColour() }
: resident.isMayor() ? (resident.isKing() ? ChatSettings.getKingColour() : ChatSettings.getMayorColour()) : ChatSettings.getResidentColour();
}
public static String getVaultGroup(Player player) {
return TownyUniverse.getInstance().getPermissionSource().getPlayerGroup(player);
}
public static String getVaultPrefixSuffix(Resident resident, String slug) { public static String getTownyColour(Resident resident) {
return TownyUniverse.getInstance().getPermissionSource().getPrefixSuffix(resident, slug); return !resident.hasTown()
} ? ChatSettings.getNomadColour()
: resident.isMayor() ? (resident.isKing() ? ChatSettings.getKingColour() : ChatSettings.getMayorColour()) : ChatSettings.getResidentColour();
}
public static String getVaultGroup(Player player) {
return TownyUniverse.getInstance().getPermissionSource().getPlayerGroup(player);
}
public static String getVaultPrefixSuffix(Resident resident, String slug) {
return TownyUniverse.getInstance().getPermissionSource().getPrefixSuffix(resident, slug);
}
} }
@@ -1,17 +1,17 @@
package com.palmergames.bukkit.TownyChat; package com.palmergames.bukkit.TownyChat;
import java.util.function.Function; import com.palmergames.bukkit.TownyChat.listener.LocalTownyChatEvent;
import com.palmergames.bukkit.TownyChat.listener.LocalTownyChatEvent; import java.util.function.Function;
public class TownyChatReplacer { public class TownyChatReplacer {
private final Function<LocalTownyChatEvent, String> func; private final Function<LocalTownyChatEvent, String> func;
public TownyChatReplacer(Function<LocalTownyChatEvent, String> func) { public TownyChatReplacer(Function<LocalTownyChatEvent, String> func) {
this.func = func; this.func = func;
} }
public String getWith(LocalTownyChatEvent event) { public String getWith(LocalTownyChatEvent event) {
return func.apply(event); return func.apply(event);
} }
} }
File diff suppressed because it is too large. Load diff
@@ -3,196 +3,193 @@ package com.palmergames.bukkit.TownyChat.channels;
import com.palmergames.bukkit.TownyChat.Chat; import com.palmergames.bukkit.TownyChat.Chat;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import java.util.HashMap; import java.util.*;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
/** /**
* @author ElgarL * @author ElgarL
*
*/ */
public class ChannelsHolder { public class ChannelsHolder {
@SuppressWarnings("unused")
private Chat plugin;
private Channel defaultChan = null;
// Container for all channels
private Map<String,Channel> channels = new LinkedHashMap<>();
/** Constructor @SuppressWarnings("unused")
* private Chat plugin;
* @param plugin private Channel defaultChan = null;
*/ // Container for all channels
public ChannelsHolder(Chat plugin) { private Map<String, Channel> channels = new LinkedHashMap<>();
super();
this.plugin = plugin;
}
public void setDefaultChannel(Channel channel) { /**
defaultChan = channel; * Constructor
} *
* @param plugin
public Channel getDefaultChannel() { */
return defaultChan; public ChannelsHolder(Chat plugin) {
} super();
this.plugin = plugin;
}
/** public Channel getDefaultChannel() {
* @return the channels return defaultChan;
*/ }
public Map<String, Channel> getAllChannels() {
return channels;
}
/** public void setDefaultChannel(Channel channel) {
* @param channels the channels to set defaultChan = channel;
*/ }
public void setChannels(HashMap<String, Channel> channels) {
this.channels = channels;
}
@SuppressWarnings("unlikely-arg-type")
public void addChannel(Channel chan) {
if (isChannel(chan.getName()))
channels.remove(chan);
channels.put(chan.getName().toLowerCase(), chan);
}
public boolean isChannel(String channelName) {
return channels.containsKey(channelName.toLowerCase());
}
public Channel getChannel(String channelName) {
return channels.get(channelName.toLowerCase());
}
public Map<String, Channel> getChannels() {
return channels;
}
/**
* Find a channel we are able to talk in, and have not left, starting with the greatest range.
*
* @param player
* @param type
* @return channel or null if none.
*/
public Channel getActiveChannel(Player player, channelTypes type) {
return getActiveChannel(player, type, false);
}
/**
* Find a channel we are able to talk in, and have not left, starting with the greatest range.
*
* @param player
* @param type
* @param unlimitedRange true when a channel has to have an unlimited range.
* @return channel or null if none.
*/
public Channel getActiveChannel(Player player, channelTypes type, boolean unlimitedRange) {
Channel local = null;
Channel global = null;
Channel world = null;
String name = player.getName();
// Return the defaultChan if it is the correct type, and the player is present in that channel.
if (getDefaultChannel() != null && getDefaultChannel().isPresent(name) && getDefaultChannel().getType().equals(type) && getDefaultChannel().hasSpeakPermission(player)) {
if (!unlimitedRange || getDefaultChannel().getRange() < 1)
return getDefaultChannel();
}
for (Channel channel: channels.values()) {
if (!channel.isPresent(name)) continue;
if (!channel.getType().equals(type)) continue;
if (channel.hasSpeakPermission(player)) {
if (channel.getRange() == -1) {
global = channel;
} else if (channel.getRange() == 0) {
world = channel;
} else if (!unlimitedRange)
local = channel;
}
}
if (global != null)
return global;
if (world != null)
return world;
if (local != null)
return local;
return null;
}
/**
* Find a channel we are able to talk in, starting with the greatest range.
*
* @param player
* @param type
* @return channel or null if none.
*/
public Channel getChannel(Player player, channelTypes type) {
Channel local = null;
Channel global = null;
Channel world = null;
for (Channel channel: channels.values()) {
if (!channel.getType().equals(type)) continue;
if (channel.hasSpeakPermission(player)){
if (channel.getRange() == -1) {
global = channel;
} else if (channel.getRange() == 0) {
world = channel;
} else
local = channel;
}
}
if (global != null)
return global;
if (world != null)
return world;
if (local != null)
return local;
return null;
}
/**
* Fetch all channel permissions
*
* @return Set of all permission nodes
*/
public Set<String> getAllPermissions() {
Set<String> perms = new HashSet<String>();
for (Channel channel: channels.values()) {
if (!perms.contains(channel.getPermission()))
perms.add(channel.getPermission());
if (channel.hasListenPermission() && !perms.contains(channel.getListenPermissionNode()))
perms.add(channel.getListenPermissionNode());
if (channel.hasSpeakPermission() && !perms.contains(channel.getSpeakPermissionNode()))
perms.add(channel.getSpeakPermissionNode());
}
return perms;
}
public String getMutePermission() { /**
return "townychat.mod.mute"; * @return the channels
} */
public Map<String, Channel> getAllChannels() {
return channels;
}
public String getUnmutePermission() { @SuppressWarnings("unlikely-arg-type")
return "townychat.mod.unmute"; public void addChannel(Channel chan) {
} if (isChannel(chan.getName()))
channels.remove(chan);
channels.put(chan.getName().toLowerCase(), chan);
}
public boolean isChannel(String channelName) {
return channels.containsKey(channelName.toLowerCase());
}
public Channel getChannel(String channelName) {
return channels.get(channelName.toLowerCase());
}
public Map<String, Channel> getChannels() {
return channels;
}
/**
* @param channels the channels to set
*/
public void setChannels(HashMap<String, Channel> channels) {
this.channels = channels;
}
/**
* Find a channel we are able to talk in, and have not left, starting with the greatest range.
*
* @param player
* @param type
* @return channel or null if none.
*/
public Channel getActiveChannel(Player player, channelTypes type) {
return getActiveChannel(player, type, false);
}
/**
* Find a channel we are able to talk in, and have not left, starting with the greatest range.
*
* @param player
* @param type
* @param unlimitedRange true when a channel has to have an unlimited range.
* @return channel or null if none.
*/
public Channel getActiveChannel(Player player, channelTypes type, boolean unlimitedRange) {
Channel local = null;
Channel global = null;
Channel world = null;
String name = player.getName();
// Return the defaultChan if it is the correct type, and the player is present in that channel.
if (getDefaultChannel() != null && getDefaultChannel().isPresent(name) && getDefaultChannel().getType().equals(type) && getDefaultChannel().hasSpeakPermission(player)) {
if (!unlimitedRange || getDefaultChannel().getRange() < 1)
return getDefaultChannel();
}
for (Channel channel : channels.values()) {
if (!channel.isPresent(name)) continue;
if (!channel.getType().equals(type)) continue;
if (channel.hasSpeakPermission(player)) {
if (channel.getRange() == -1) {
global = channel;
} else if (channel.getRange() == 0) {
world = channel;
} else if (!unlimitedRange)
local = channel;
}
}
if (global != null)
return global;
if (world != null)
return world;
if (local != null)
return local;
return null;
}
/**
* Find a channel we are able to talk in, starting with the greatest range.
*
* @param player
* @param type
* @return channel or null if none.
*/
public Channel getChannel(Player player, channelTypes type) {
Channel local = null;
Channel global = null;
Channel world = null;
for (Channel channel : channels.values()) {
if (!channel.getType().equals(type)) continue;
if (channel.hasSpeakPermission(player)) {
if (channel.getRange() == -1) {
global = channel;
} else if (channel.getRange() == 0) {
world = channel;
} else
local = channel;
}
}
if (global != null)
return global;
if (world != null)
return world;
if (local != null)
return local;
return null;
}
/**
* Fetch all channel permissions
*
* @return Set of all permission nodes
*/
public Set<String> getAllPermissions() {
Set<String> perms = new HashSet<String>();
for (Channel channel : channels.values()) {
if (!perms.contains(channel.getPermission()))
perms.add(channel.getPermission());
if (channel.hasListenPermission() && !perms.contains(channel.getListenPermissionNode()))
perms.add(channel.getListenPermissionNode());
if (channel.hasSpeakPermission() && !perms.contains(channel.getSpeakPermissionNode()))
perms.add(channel.getSpeakPermissionNode());
}
return perms;
}
public String getMutePermission() {
return "townychat.mod.mute";
}
public String getUnmutePermission() {
return "townychat.mod.unmute";
}
} }
@@ -8,19 +8,16 @@ import com.palmergames.bukkit.TownyChat.events.PlayerJoinChatChannelEvent;
import com.palmergames.bukkit.TownyChat.listener.LocalTownyChatEvent; import com.palmergames.bukkit.TownyChat.listener.LocalTownyChatEvent;
import com.palmergames.bukkit.towny.TownyAPI; import com.palmergames.bukkit.towny.TownyAPI;
import com.palmergames.bukkit.towny.TownyMessaging; import com.palmergames.bukkit.towny.TownyMessaging;
import com.palmergames.bukkit.towny.TownyUniverse;
import com.palmergames.bukkit.towny.object.Nation; import com.palmergames.bukkit.towny.object.Nation;
import com.palmergames.bukkit.towny.object.Resident; import com.palmergames.bukkit.towny.object.Resident;
import com.palmergames.bukkit.towny.object.Town; import com.palmergames.bukkit.towny.object.Town;
import com.palmergames.bukkit.towny.TownyUniverse;
import com.palmergames.bukkit.util.Colors; import com.palmergames.bukkit.util.Colors;
import io.papermc.paper.event.player.AsyncChatEvent;
import me.clip.placeholderapi.PlaceholderAPI; import me.clip.placeholderapi.PlaceholderAPI;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.tag.Tag; import net.kyori.adventure.text.minimessage.tag.Tag;
import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver; import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver;
import net.kyori.adventure.text.minimessage.tag.standard.StandardTags;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.Sound; import org.bukkit.Sound;
@@ -29,355 +26,350 @@ import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.dynmap.DynmapAPI; import org.dynmap.DynmapAPI;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.util.ArrayList; import java.util.*;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UnknownFormatConversionException;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class StandardChannel extends Channel { public class StandardChannel extends Channel {
private Chat plugin; private Chat plugin;
public StandardChannel(Chat instance, String name) {
super(name);
this.plugin = instance;
}
@Override public StandardChannel(Chat instance, String name) {
public void chatProcess(AsyncPlayerChatEvent event) { super(name);
this.plugin = instance;
channelTypes channelType = this.getType(); }
Player player = event.getPlayer();
boolean notifyjoin = false;
Resident resident = TownyUniverse.getInstance().getResident(player.getUniqueId()); @Override
if (resident == null) public void chatProcess(AsyncChatEvent event) {
return;
Town town = TownyAPI.getInstance().getResidentTownOrNull(resident);
Nation nation = TownyAPI.getInstance().getResidentNationOrNull(resident);
// If the channel would require a town/nation which is null, cancel and fail early. channelTypes channelType = this.getType();
if (town == null && channelType.equals(channelTypes.TOWN) || Player player = event.getPlayer();
nation == null && (channelType.equals(channelTypes.NATION) || channelType.equals(channelTypes.ALLIANCE))) { boolean notifyjoin = false;
event.setCancelled(true);
return;
}
// If player sends a message to a channel they have left Resident resident = TownyUniverse.getInstance().getResident(player.getUniqueId());
// tell the channel to add the player back if (resident == null)
if (isAbsent(player.getName())) { return;
join(player); Town town = TownyAPI.getInstance().getResidentTownOrNull(resident);
notifyjoin = true; Nation nation = TownyAPI.getInstance().getResidentNationOrNull(resident);
Bukkit.getPluginManager().callEvent(new PlayerJoinChatChannelEvent(player, this));
}
// Set the channel specific format // If the channel would require a town/nation which is null, cancel and fail early.
String format = getFormat(player); if (town == null && channelType.equals(channelTypes.TOWN) ||
nation == null && (channelType.equals(channelTypes.NATION) || channelType.equals(channelTypes.ALLIANCE))) {
event.setCancelled(true);
return;
}
// Get the list of message recipients. // If player sends a message to a channel they have left
Set<Player> recipients = getRecipients(player, town, nation, channelType, event.getRecipients()); // tell the channel to add the player back
if (isAbsent(player.getName())) {
join(player);
notifyjoin = true;
Bukkit.getPluginManager().callEvent(new PlayerJoinChatChannelEvent(player, this));
}
// Try sending an alone message if it is called for. // Set the channel specific format
trySendingAloneMessage(player, recipients); String format = getFormat(player);
// format is left to store the original non-PAPI-parsed chat format. // Get the list of message recipients.
String newFormat = format; Set<Player> recipients = getRecipients(player, town, nation, channelType, event.getRecipients());
// Parse any PAPI placeholders.
if (Chat.usingPlaceholderAPI)
newFormat = PlaceholderAPI.setPlaceholders(player, format);
/* // Try sending an alone message if it is called for.
* Only modify GLOBAL channelType chat (general and local chat channels) if isModifyChat() is true. trySendingAloneMessage(player, recipients);
*/
if (!(channelType.equals(channelTypes.GLOBAL) && !ChatSettings.isModify_chat()))
applyFormats(event, format, newFormat, resident);
/* // format is left to store the original non-PAPI-parsed chat format.
* Set recipients for Bukkit to send this message to. String newFormat = format;
*/ // Parse any PAPI placeholders.
event.getRecipients().clear(); if (Chat.usingPlaceholderAPI)
event.getRecipients().addAll(recipients); newFormat = PlaceholderAPI.setPlaceholders(player, format);
// If the server has marked this Channel as hooked, fire the AsyncChatHookEvent. /*
// If the event is cancelled, cancel the chat entirely. * Only modify GLOBAL channelType chat (general and local chat channels) if isModifyChat() is true.
// Fires its own sendSpyMessage(). */
if (isHooked()) if (!(channelType.equals(channelTypes.GLOBAL) && !ChatSettings.isModify_chat()))
if (!sendOffHookedMessage(event, channelType)) { applyFormats(event, format, newFormat, resident);
event.setCancelled(true);
return;
}
// Send spy message if this was never hooked. /*
if (!isHooked()) * Set recipients for Bukkit to send this message to.
sendSpyMessage(event, channelType); */
event.viewers().clear();
event.viewers().addAll(recipients);
// Play the channel sound, if used. // If the server has marked this Channel as hooked, fire the AsyncChatHookEvent.
tryPlayChannelSound(event.getRecipients()); // If the event is cancelled, cancel the chat entirely.
// Fires its own sendSpyMessage().
if (isHooked())
if (!sendOffHookedMessage(event, channelType, recipients)) {
event.setCancelled(true);
return;
}
if (notifyjoin) // Send spy message if this was never hooked.
TownyMessaging.sendMessage(player, "You join " + Colors.translateColorCodes(getMessageColour()) + getName()); if (!isHooked())
sendSpyMessage(event, channelType, recipients);
/* // Play the channel sound, if used.
* Perform any last channel specific functions like logging this chat and tryPlayChannelSound(recipients);
* relaying to Dynmap.
*/
switch (channelType) {
case TOWN:
case NATION:
case ALLIANCE:
case DEFAULT:
break;
case PRIVATE:
case GLOBAL:
tryPostToDynmap(player, event.getMessage());
break;
}
}
private Set<Player> getRecipients(Player player, Town town, Nation nation, channelTypes channelType, Set<Player> recipients) { if (notifyjoin)
return switch (channelType) { TownyMessaging.sendMessage(player, "You join " + Colors.translateColorCodes(getMessageColour()) + getName());
case TOWN -> new HashSet<>(findRecipients(player, TownyAPI.getInstance().getOnlinePlayers(town)));
case NATION -> new HashSet<>(findRecipients(player, TownyAPI.getInstance().getOnlinePlayers(nation)));
case ALLIANCE -> new HashSet<>(findRecipients(player, TownyAPI.getInstance().getOnlinePlayersAlliance(nation)));
case DEFAULT -> new HashSet<>(findRecipients(player, new ArrayList<>(recipients)));
case GLOBAL, PRIVATE -> new HashSet<>(findRecipients(player, new ArrayList<>(recipients)));
};
}
/** /*
* Compile a list of valid recipients for this message. * Perform any last channel specific functions like logging this chat and
* * relaying to Dynmap.
* @param sender */
* @param playerList switch (channelType) {
* @return Set containing a list of players for this message. case TOWN:
*/ case NATION:
private Set<Player> findRecipients(Player sender, List<Player> playerList) { case ALLIANCE:
// Refresh the potential channels a player can see, if they are not currently in the channel. case DEFAULT:
playerList.stream().forEach(p -> refreshPlayer(this, p)); break;
return playerList.stream() case PRIVATE:
.filter(p -> hasListenPermission(p)) // Check permission. case GLOBAL:
.filter(p -> testDistance(sender, p, getRange())) // Within range. tryPostToDynmap(player, event.getMessage());
.filter(p -> !plugin.isIgnoredByEssentials(sender, p)) // Check essentials ignore. break;
.filter(p -> !isAbsent(p.getName())) // Check if player is purposefully absent. }
.collect(Collectors.toSet()); }
}
private void refreshPlayer(Channel channel, Player player) { private Set<Player> getRecipients(Player player, Town town, Nation nation, channelTypes channelType, Set<Player> recipients) {
if (!channel.isPresent(player.getName())) return switch (channelType) {
channel.forgetPlayer(player); case TOWN -> new HashSet<>(findRecipients(player, TownyAPI.getInstance().getOnlinePlayers(town)));
} case NATION -> new HashSet<>(findRecipients(player, TownyAPI.getInstance().getOnlinePlayers(nation)));
case ALLIANCE ->
new HashSet<>(findRecipients(player, TownyAPI.getInstance().getOnlinePlayersAlliance(nation)));
case DEFAULT -> new HashSet<>(findRecipients(player, new ArrayList<>(recipients)));
case GLOBAL, PRIVATE -> new HashSet<>(findRecipients(player, new ArrayList<>(recipients)));
};
}
/** /**
* Check the distance between players and return a result based upon the range setting * Compile a list of valid recipients for this message.
* -1 = no limit *
* 0 = same world * @param sender
* any positive value = distance in blocks * @param playerList
* * @return Set containing a list of players for this message.
* @param player1 */
* @param player2 private Set<Player> findRecipients(Player sender, List<Player> playerList) {
* @param range // Refresh the potential channels a player can see, if they are not currently in the channel.
* @return true if in range playerList.stream().forEach(p -> refreshPlayer(this, p));
*/ return playerList.stream()
private boolean testDistance(Player player1, Player player2, double range) { .filter(p -> testDistance(sender, p, getRange())) // Within range.
.filter(p -> !plugin.isIgnoredByEssentials(sender, p)) // Check essentials ignore.
// unlimited range (all worlds) .filter(p -> !isAbsent(p.getName())) // Check if player is purposefully absent.
if (range == -1) .collect(Collectors.toSet());
return true; }
// Same world only
if (range == 0)
return player1.getWorld().equals(player2.getWorld());
// Range check (same world)
return player1.getWorld().equals(player2.getWorld()) &&
player1.getLocation().distance(player2.getLocation()) < range;
}
private void trySendingAloneMessage(Player sender, Set<Player> recipients) { private void refreshPlayer(Channel channel, Player player) {
if (ChatSettings.isUsingAloneMessage() && if (!channel.isPresent(player.getName()))
recipients.stream().filter(p -> sender.canSee(p)).count() < 2) // sender will usually be a recipient of their own message. channel.forgetPlayer(player);
TownyMessaging.sendMessage(sender, ChatSettings.getUsingAloneMessageString()); }
}
private void applyFormats(AsyncPlayerChatEvent event, String originalFormat, String workingFormat, Resident resident) { /**
List<TagResolver> tagResolvers = new ArrayList<>(); * Check the distance between players and return a result based upon the range setting
* -1 = no limit
* 0 = same world
* any positive value = distance in blocks
*
* @param player1
* @param player2
* @param range
* @return true if in range
*/
private boolean testDistance(Player player1, Player player2, double range) {
// Parse out our own channelTag and msgcolour tags. // unlimited range (all worlds)
tagResolvers = parseTagAndMsgColour(tagResolvers); if (range == -1)
// Attempt to apply the new format. return true;
// Same world only
if (range == 0)
return player1.getWorld().equals(player2.getWorld());
// Range check (same world)
return player1.getWorld().equals(player2.getWorld()) &&
player1.getLocation().distance(player2.getLocation()) < range;
}
private void trySendingAloneMessage(Player sender, Set<Player> recipients) {
if (ChatSettings.isUsingAloneMessage() &&
recipients.stream().filter(p -> sender.canSee(p)).count() < 2) // sender will usually be a recipient of their own message.
TownyMessaging.sendMessage(sender, ChatSettings.getUsingAloneMessageString());
}
private void applyFormats(AsyncChatEvent event, String originalFormat, String workingFormat, Resident resident) {
List<TagResolver> tagResolvers = new ArrayList<>();
// Parse out our own channelTag and msgcolour tags.
tagResolvers = parseTagAndMsgColour(tagResolvers);
// Attempt to apply the new format.
// catchFormatConversionException(event, originalFormat, newFormat); // catchFormatConversionException(event, originalFormat, newFormat);
// Fire the LocalTownyChatEvent. // Fire the LocalTownyChatEvent.
LocalTownyChatEvent chatEvent = new LocalTownyChatEvent(event, resident); LocalTownyChatEvent chatEvent = new LocalTownyChatEvent(event, resident);
// Format the chat line, replacing the TownyChat chat tags. // Format the chat line, replacing the TownyChat chat tags.
tagResolvers.add(TownyChatFormatter.getChatFormat(chatEvent)); tagResolvers.add(TownyChatFormatter.getChatFormat(chatEvent));
// newFormat = TownyChatFormatter.getChatFormat(chatEvent); // newFormat = TownyChatFormatter.getChatFormat(chatEvent);
// Attempt to apply the new format. // Attempt to apply the new format.
// catchFormatConversionException(event, originalFormat, newFormat); // catchFormatConversionException(event, originalFormat, newFormat);
Component component = Chat.getTownyChat().getMiniMessage().deserialize(workingFormat, tagResolvers.toArray(new TagResolver[0])); // Component component = Chat.getTownyChat().getMiniMessage().deserialize(workingFormat, tagResolvers.toArray(new TagResolver[0]));
Audience.audience(event.getRecipients().stream().map(p -> Chat.getTownyChat().adventure().player(p)).toArray(Audience[]::new)).sendMessage(component);; // Audience.audience(event.getRecipients().stream().map(p -> Chat.getTownyChat().adventure().player(p)).toArray(Audience[]::new)).sendMessage(component);;
// event.setFormat(GsonComponentSerializer.gson().serialize(component)); // event.setFormat(GsonComponentSerializer.gson().serialize(component));
} }
private String parseTagAndMsgColour(String format) { private String parseTagAndMsgColour(String format) {
return format return format
.replace("{channelTag}", Colors.translateColorCodes(getChannelTag() != null ? getChannelTag() : "")) .replace("{channelTag}", Colors.translateColorCodes(getChannelTag() != null ? getChannelTag() : ""))
.replace("{msgcolour}", Colors.translateColorCodes(getMessageColour() != null ? getMessageColour() : "")); .replace("{msgcolour}", Colors.translateColorCodes(getMessageColour() != null ? getMessageColour() : ""));
} }
private List<TagResolver> parseTagAndMsgColour(List<TagResolver> tagResolvers) { private List<TagResolver> parseTagAndMsgColour(List<TagResolver> tagResolvers) {
tagResolvers.add( tagResolvers.add(
TagResolver.resolver( TagResolver.resolver(
TagResolver.resolver("channeltag", Tag.inserting(getChannelTag() != null ? Component.text(getChannelTag()) : Component.empty())), TagResolver.resolver("channeltag", Tag.inserting(getChannelTag() != null ? Component.text(getChannelTag()) : Component.empty())),
TagResolver.resolver("msgcolour", Tag.inserting(getMessageColour() != null ? Component.text(getMessageColour()) : Component.empty())) TagResolver.resolver("msgcolour", Tag.inserting(getMessageColour() != null ? Component.text(getMessageColour()) : Component.empty()))
) )
); );
return tagResolvers; return tagResolvers;
} }
private void catchFormatConversionException(AsyncPlayerChatEvent event, String format, String newFormat) { private void catchFormatConversionException(AsyncPlayerChatEvent event, String format, String newFormat) {
try { try {
event.setFormat(newFormat); event.setFormat(newFormat);
} catch (UnknownFormatConversionException e) { } catch (UnknownFormatConversionException e) {
// This exception is usually thrown when a PAPI placeholder did not get parsed // This exception is usually thrown when a PAPI placeholder did not get parsed
// and has left behind a % symbol followed by something that String#format // and has left behind a % symbol followed by something that String#format
// cannot handle. // cannot handle.
boolean percentSymbol = format.contains("%" + e.getConversion()); boolean percentSymbol = format.contains("%" + e.getConversion());
String errmsg = "TownyChat tried to apply a chat format that is not allowed: '" + String errmsg = "TownyChat tried to apply a chat format that is not allowed: '" +
newFormat + "', because of the " + e.getConversion() + " symbol" + newFormat + "', because of the " + e.getConversion() + " symbol" +
(percentSymbol ? ", found after a %. There is probably a PAPIPlaceholder that could not be parsed." : "." + (percentSymbol ? ", found after a %. There is probably a PAPIPlaceholder that could not be parsed." : "." +
" You should attempt to correct this in your towny\\settings\\chatconfig.yml file and use /townychat reload."); " You should attempt to correct this in your towny\\settings\\chatconfig.yml file and use /townychat reload.");
Chat.getTownyChat().getLogger().severe(errmsg); Chat.getTownyChat().getLogger().severe(errmsg);
if (percentSymbol) if (percentSymbol)
// Attempt to remove the unparsed placeholder and send this right back. // Attempt to remove the unparsed placeholder and send this right back.
catchFormatConversionException(event, format, purgePAPI(newFormat, "%" + e.getConversion())); catchFormatConversionException(event, format, purgePAPI(newFormat, "%" + e.getConversion()));
else else
// Just let the chat go, this results in an error in the log, and TownyChat not being able to format chat. // Just let the chat go, this results in an error in the log, and TownyChat not being able to format chat.
event.setFormat(format); event.setFormat(format);
} }
} }
private String purgePAPI(String format, String startOfPlaceholder) { private String purgePAPI(String format, String startOfPlaceholder) {
return format.replaceAll(startOfPlaceholder + ".*%", ""); return format.replaceAll(startOfPlaceholder + ".*%", "");
} }
/** /**
* Send off TownyChat's {@link AsyncChatHookEvent} which allows other plugins to * Send off TownyChat's {@link AsyncChatHookEvent} which allows other plugins to
* cancel or modify TownyChat's messaging. * cancel or modify TownyChat's messaging.
* *
* @param event {@link AsyncPlayerChatEvent} that has caused a message. * @param event {@link AsyncChatEvent} that has caused a message.
* @param channelType {@link channelTypes} which this message is being sent through. * @param channelType {@link channelTypes} which this message is being sent through.
* @return false if the AsyncChatHookEvent is cancelled. * @return false if the AsyncChatHookEvent is cancelled.
*/ */
private boolean sendOffHookedMessage(AsyncPlayerChatEvent event, channelTypes channelType) { private boolean sendOffHookedMessage(AsyncChatEvent event, channelTypes channelType, Set<Player> recipients) {
AsyncChatHookEvent hookEvent = new AsyncChatHookEvent(event, this, !Bukkit.getServer().isPrimaryThread()); AsyncChatHookEvent hookEvent = new AsyncChatHookEvent(event, this, !Bukkit.getServer().isPrimaryThread(), recipients);
Bukkit.getServer().getPluginManager().callEvent(hookEvent); Bukkit.getServer().getPluginManager().callEvent(hookEvent);
if (hookEvent.isCancelled()) if (hookEvent.isCancelled())
return false; return false;
/* /*
* Send spy message before another plugin changes any of the recipients, so we * Send spy message before another plugin changes any of the recipients, so we
* know which people can see it. * know which people can see it.
*/ */
sendSpyMessage(event, channelType); sendSpyMessage(event, channelType, recipients);
if (hookEvent.isChanged()) { if (hookEvent.isChanged()) {
event.setMessage(hookEvent.getMessage()); event.setMessage(hookEvent.getMessage());
event.setFormat(hookEvent.getFormat()); event.viewers().clear();
event.getRecipients().clear(); event.viewers().addAll(hookEvent.getRecipients());
event.getRecipients().addAll(hookEvent.getRecipients()); }
} return true;
return true; }
}
/** /**
* Sends messages to spies who have not already seen the message naturally. * Sends messages to spies who have not already seen the message naturally.
* *
* @param event - Chat Event. * @param event - Chat Event.
* @param type - Channel Type * @param type - Channel Type
*/ */
private void sendSpyMessage(AsyncPlayerChatEvent event, channelTypes type) { private void sendSpyMessage(AsyncChatEvent event, channelTypes type, Set<Player> recipients) {
Set<Player> recipients = event.getRecipients(); Set<Player> spies = getSpies();
Set<Player> spies = getSpies(); String format = formatSpyMessage(type, event.getPlayer());
String format = formatSpyMessage(type, event.getPlayer()); if (format == null) return;
if (format == null) return;
String message = Colors.translateColorCodes(event.getMessage());
// Remove spies who've already seen the message naturally.
spies.stream()
.filter(spy -> !recipients.contains(spy))
.forEach(spy -> TownyMessaging.sendMessage(spy, format + message));
}
/** String message = Colors.translateColorCodes(event.getMessage());
* @return A Set of online players who are spying. // Remove spies who've already seen the message naturally.
*/ spies.stream()
private Set<Player> getSpies() { .filter(spy -> !recipients.contains(spy))
// Compile the list of recipients with spy perms .forEach(spy -> TownyMessaging.sendMessage(spy, format + message));
return plugin.getServer().getOnlinePlayers().stream() }
.filter(p -> plugin.getTowny().hasPlayerMode(p, "spy"))
.collect(Collectors.toSet());
}
/** /**
* Formats look of message for spies * @return A Set of online players who are spying.
* */
* @param type - Channel Type. private Set<Player> getSpies() {
* @param player - Player who chatted. // Compile the list of recipients with spy perms
* @return format - Message format. return plugin.getServer().getOnlinePlayers().stream()
*/ .filter(p -> plugin.getTowny().hasPlayerMode(p, "spy"))
@Nullable .collect(Collectors.toSet());
private String formatSpyMessage(channelTypes type, Player player) { }
Resident resident = TownyUniverse.getInstance().getResident(player.getUniqueId());
if (resident == null)
return null;
String channelPrefix = Colors.translateColorCodes(getChannelTag() != null ? getChannelTag() : getName()) + " ";
if (isGovernmentChannel()) // Town, Nation, Alliance channels get an extra [Name] added after the channelPrefix.
channelPrefix = getGovtChannelSpyingPrefix(resident, type, channelPrefix);
return ChatColor.GOLD + "[SPY] " + ChatColor.WHITE + channelPrefix + resident.getName() + ": ";
}
private String getGovtChannelSpyingPrefix(Resident resident, channelTypes type, String channelPrefix) { /**
String slug = type.equals(channelTypes.TOWN) * Formats look of message for spies
? TownyAPI.getInstance().getResidentTownOrNull(resident).getName() // Town chat. *
: TownyAPI.getInstance().getResidentNationOrNull(resident).getName(); // Nation or Alliance chat. * @param type - Channel Type.
return channelPrefix + "[" + slug + "] "; * @param player - Player who chatted.
} * @return format - Message format.
*/
@Nullable
private String formatSpyMessage(channelTypes type, Player player) {
Resident resident = TownyUniverse.getInstance().getResident(player.getUniqueId());
if (resident == null)
return null;
String channelPrefix = Colors.translateColorCodes(getChannelTag() != null ? getChannelTag() : getName()) + " ";
if (isGovernmentChannel()) // Town, Nation, Alliance channels get an extra [Name] added after the channelPrefix.
channelPrefix = getGovtChannelSpyingPrefix(resident, type, channelPrefix);
return ChatColor.GOLD + "[SPY] " + ChatColor.WHITE + channelPrefix + resident.getName() + ": ";
}
/** private String getGovtChannelSpyingPrefix(Resident resident, channelTypes type, String channelPrefix) {
* Try to send a channel sound, if enabled. String slug = type.equals(channelTypes.TOWN)
* ? TownyAPI.getInstance().getResidentTownOrNull(resident).getName() // Town chat.
* @param recipients Set of Players that will receive the message and potentially the sound. : TownyAPI.getInstance().getResidentNationOrNull(resident).getName(); // Nation or Alliance chat.
*/ return channelPrefix + "[" + slug + "] ";
private void tryPlayChannelSound(Set<Player> recipients) { }
if (getChannelSound() == null)
return;
for (Player recipient : recipients) {
if (!isSoundMuted(recipient)) {
try {
recipient.playSound(recipient, Sound.valueOf(getChannelSound()), 1.0f, 1.0f);
} catch (IllegalArgumentException ex) {
plugin.getLogger().warning("Channel " + this.getName() + " has an invalid sound configured.");
setChannelSound(null);
break;
}
}
}
}
/** /**
* Try to send a message to dynmap's web chat. * Try to send a channel sound, if enabled.
* @param player Player which has spoken. *
* @param message Message being spoken. * @param recipients Set of Players that will receive the message and potentially the sound.
*/ */
private void tryPostToDynmap(Player player, String message) { private void tryPlayChannelSound(Set<Player> recipients) {
if (super.getRange() > 0) if (getChannelSound() == null)
return; return;
DynmapAPI dynMap = plugin.getDynmap(); for (Player recipient : recipients) {
if (dynMap != null) if (!isSoundMuted(recipient)) {
dynMap.postPlayerMessageToWeb(player, message); try {
} recipient.playSound(recipient, Sound.valueOf(getChannelSound()), 1.0f, 1.0f);
} catch (IllegalArgumentException ex) {
plugin.getLogger().warning("Channel " + this.getName() + " has an invalid sound configured.");
setChannelSound(null);
break;
}
}
}
}
/**
* Try to send a message to dynmap's web chat.
*
* @param player Player which has spoken.
* @param message Message being spoken.
*/
private void tryPostToDynmap(Player player, String message) {
if (super.getRange() > 0)
return;
DynmapAPI dynMap = plugin.getDynmap();
if (dynMap != null)
dynMap.postPlayerMessageToWeb(player, message);
}
} }
@@ -2,10 +2,10 @@ package com.palmergames.bukkit.TownyChat.channels;
public enum channelTypes { public enum channelTypes {
TOWN, TOWN,
NATION, NATION,
ALLIANCE, ALLIANCE,
DEFAULT, DEFAULT,
GLOBAL, GLOBAL,
PRIVATE PRIVATE
} }
@@ -1,156 +1,155 @@
package com.palmergames.bukkit.TownyChat.config; package com.palmergames.bukkit.TownyChat.config;
/** /**
* Dummy class used to make Channels.yml have update-able comments. * Dummy class used to make Channels.yml have update-able comments.
* *
* @author LlmDl * @author LlmDl
* */
*/ public enum ChannelsNodes {
public enum ChannelsNodes { COMMENTS("channelscomments", "",
COMMENTS("channelscomments", "", "# This file contains all configuration data for the TownyChat channels.",
"# 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.",
"# 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:",
"# Channels do not require all of the keys to be set. The keys which are required are:", "# - type",
"# - type", "# - commands",
"# - commands", "# The other keys are not required.",
"# The other keys are not required.", "# ",
"# ", "# The keys are as follows: commands, type, channeltag, messagecolour, permission, leavepermission, speakpermission, listenpermission, sound, range,",
"# The keys are as follows: commands, type, channeltag, messagecolour, permission, leavepermission, speakpermission, listenpermission, sound, range,", "# spam_time, focusable, default.",
"# 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.",
"# 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: ***",
"# *** Further Explanation of the available keys is below: ***", "#", "#",
"#","#", "# COMMANDS",
"# COMMANDS", "# --------",
"# --------", "# In order to swap channels, you must use the desired channel's command to enter the new chat and leave the old one.",
"# 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.",
"# 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.",
"# 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.",
"# eg: '/tc somewords' will send 'somewords' to the townchat channel.", "#", "#",
"#","#", "# TYPE",
"# 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",
"# 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.)",
"# section.)", "#", "#",
"#","#", "# CHANNELTAG",
"# CHANNELTAG", "# ----------",
"# ----------", "# channeltag is what defines how the chatconfig.yml's {channelTag} chat tag will appear in the channel.",
"# channeltag is what defines how the chatconfig.yml's {channelTag} chat tag will appear in the channel.", "#", "#",
"#","#", "# PERMISSION",
"# 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",
"# 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.",
"# when either spearkpermission or listenpermission is not set.", "#", "#",
"#","#", "# SPEAKPERMISSION",
"# 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",
"# 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.",
"# the channel's permission key when players are speaking.", "#", "#",
"#","#", "# LISTENPERMISSION",
"# 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",
"# 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.",
"# the channel's permission key when a player's ability to hear a channel is tested.", "#", "#",
"#","#", "# LEAVEPERMISSION",
"# 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",
"# 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}'.",
"# set this is automatically set to 'towny.chat.leave.{channelname}'.", "#", "#",
"#","#", "# MESSAGECOLOUR",
"# MESSAGECOLOUR", "# -------------",
"# -------------", "# messagecolour is what defines how the chatconfig.yml's {msgcolour} chat tag will appear in the channel.",
"# 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:",
"# 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",
"# 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.",
"# 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", "# -----",
"# -----", "# 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",
"# 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).",
"# in chat and cannot be 'heard' by others outside of the range. Range is in blocks (when set above 0).", "# ",
"# ", "# Options for range:",
"# Options for range:", "# -1 = no limits, everyone will hear messages if they have permission.",
"# -1 = no limits, everyone will hear messages if they have permission.", "# 0 = same world only",
"# 0 = same world only", "# any positive value = limited range in the same world.",
"# any positive value = limited range in the same world.", "#", "#",
"#","#", "# SPAM_TIME",
"# SPAM_TIME", "# ---------",
"# ---------", "# spam_time sets how long between chatting a player must wait, to prevent players from flooding chat with spam.",
"# spam_time sets how long between chatting a player must wait, to prevent players from flooding chat with spam.", "#", "#",
"#","#", "# FOCUSABLE",
"# 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",
"# 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'.",
"# there is no point to adding focusable: true. You make a channel un-focusable by adding the key/value 'focusable: false'.", "#", "#",
"#","#", "# DEFAULT",
"# DEFAULT", "# -------",
"# -------", "# default is a setting which decides which channel is the default when a player logs in to the server.",
"# default is a setting which decides which channel is the default when a player logs in to the server.", "#", "#",
"#","#", "# HOOKED",
"# 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",
"# 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.",
"# 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",
"# SOUND", "# -----",
"# -----", "# Each channel can have a sound by adding the key/value 'sound: SOUND_TO_USE'",
"# 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",
"# Sounds can be found here: https://hub.spigotmc.org/javadocs/bukkit/org/bukkit/Sound.html", "#", "#",
"#","#", "# Text Colouring Hints",
"# 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,",
"# 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"),
"# LightBlue = &b, Rose = &c, LightPurple = &d, Yellow = &e, White = &f"), CHANNELS_ROOT("Channels", "", "", "");
CHANNELS_ROOT("Channels", "", "", "");
private final String Root;
private final String Root; private final String Default;
private final String Default; private String[] comments;
private String[] comments;
private ChannelsNodes(String root, String def, String... comments) {
private ChannelsNodes(String root, String def, String... comments) {
this.Root = root;
this.Root = root; this.Default = def;
this.Default = def; this.comments = comments;
this.comments = comments; }
}
/**
/** * Retrieves the root for a config option
* Retrieves the root for a config option *
* * @return The root for a config option
* @return The root for a config option */
*/ public String getRoot() {
public String getRoot() {
return Root;
return Root; }
}
/**
/** * Retrieves the default value for a config path
* Retrieves the default value for a config path *
* * @return The default value for a config path
* @return The default value for a config path */
*/ public String getDefault() {
public String getDefault() {
return Default;
return Default; }
}
/**
/** * Retrieves the comment for a config path
* Retrieves the comment for a config path *
* * @return The comments for a config path
* @return The comments for a config path */
*/ public String[] getComments() {
public String[] getComments() {
if (comments != null) {
if (comments != null) { return comments;
return comments; }
}
String[] comments = new String[1];
String[] comments = new String[1]; comments[0] = "";
comments[0] = ""; return comments;
return comments; }
} }
}
@@ -1,446 +1,445 @@
package com.palmergames.bukkit.TownyChat.config; 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.channelTypes; import com.palmergames.bukkit.TownyChat.channels.channelTypes;
import com.palmergames.bukkit.config.CommentedConfiguration; import com.palmergames.bukkit.config.CommentedConfiguration;
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 com.palmergames.util.FileMgmt;
import com.palmergames.util.StringMgmt; import com.palmergames.util.StringMgmt;
import org.bukkit.Bukkit;
import org.bukkit.Bukkit; import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.ConfigurationSection;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.*; import java.util.*;
public class ChannelsSettings { public class ChannelsSettings {
private static final String CHANNELS_ROOT = "Channels"; private static final String CHANNELS_ROOT = "Channels";
private static CommentedConfiguration channelConfig, newChannelConfig; private final static List<String> DEFAULT_CHANNELS = Arrays.asList("general", "town", "nation", "alliance", "admin", "mod", "local");
private final static List<String> DEFAULT_CHANNELS = Arrays.asList("general","town","nation","alliance","admin","mod","local"); private static CommentedConfiguration channelConfig, newChannelConfig;
/** /**
* * @return true if the channels.yml has loaded.
* @return true if the channels.yml has loaded. * @throws IOException
* @throws IOException */
*/ public static boolean loadCommentedChannelsConfig() {
public static boolean loadCommentedChannelsConfig() { String filepath = Chat.getTownyChat().getChannelsConfigPath();
String filepath = Chat.getTownyChat().getChannelsConfigPath(); if (FileMgmt.checkOrCreateFile(filepath)) {
if (FileMgmt.checkOrCreateFile(filepath)) { File file = new File(filepath);
File file = new File(filepath);
// read the channels.yml into memory
// read the channels.yml into memory channelConfig = new CommentedConfiguration(file.toPath());
channelConfig = new CommentedConfiguration(file.toPath()); if (!channelConfig.load()) {
if (!channelConfig.load()) { 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; }
} setDefaults(file);
setDefaults(file); channelConfig.save();
channelConfig.save(); if (!loadChannels())
if (!loadChannels()) return false;
return false; }
} return true;
return true; }
}
/**
/** * Builds a new channels.yml reading old channels.yml data,
* Builds a new channels.yml reading old channels.yml data, * and setting new nodes to default values.
* and setting new nodes to default values. */
*/ private static void setDefaults(File file) {
private static void setDefaults(File file) { newChannelConfig = new CommentedConfiguration(file.toPath());
newChannelConfig = new CommentedConfiguration(file.toPath()); newChannelConfig.load();
newChannelConfig.load();
for (ChannelsNodes root : ChannelsNodes.values()) {
for (ChannelsNodes root : ChannelsNodes.values()) { if (root.getComments().length > 0)
if (root.getComments().length > 0) addComment(root.getRoot(), root.getComments());
addComment(root.getRoot(), root.getComments());
setNewProperty(root.getRoot(), getValue(root));
setNewProperty(root.getRoot(), getValue(root)); }
}
tryAndSetDefaultChannels();
tryAndSetDefaultChannels();
channelConfig = newChannelConfig;
channelConfig = newChannelConfig; newChannelConfig = null;
newChannelConfig = null; }
}
private static Object getValue(ChannelsNodes root) {
private static Object getValue(ChannelsNodes root) { String key = root.getRoot();
String key = root.getRoot(); return channelConfig.get(key) != null ? channelConfig.get(key) : root.getDefault();
return channelConfig.get(key) != null ? channelConfig.get(key) : root.getDefault(); }
}
private static void addComment(String root, String... comments) {
private static void addComment(String root, String... comments) { newChannelConfig.addComment(root, comments);
newChannelConfig.addComment(root, comments); }
}
private static void setNewProperty(String root, Object value) {
private static void setNewProperty(String root, Object value) { if (value == null) {
if (value == null) { value = "";
value = ""; }
} newChannelConfig.set(root, value.toString());
newChannelConfig.set(root, value.toString()); }
}
private static void tryAndSetDefaultChannels() {
private static void tryAndSetDefaultChannels() { if (channelConfig.contains(CHANNELS_ROOT)) {
if (channelConfig.contains(CHANNELS_ROOT)) { // There is already a root channels present, not our first run.
// There is already a root channels present, not our first run. newChannelConfig.set(CHANNELS_ROOT, channelConfig.get(CHANNELS_ROOT));
newChannelConfig.set(CHANNELS_ROOT, channelConfig.get(CHANNELS_ROOT)); } else {
} else { // Populate a fresh channels.yml.
// Populate a fresh channels.yml. Chat.getTownyChat().getLogger().info("TownyChat creating default channels.yml file.");
Chat.getTownyChat().getLogger().info("TownyChat creating default channels.yml file.");
newChannelConfig.createSection(CHANNELS_ROOT);
newChannelConfig.createSection(CHANNELS_ROOT); DEFAULT_CHANNELS.forEach(channel -> newChannelConfig.createSection(CHANNELS_ROOT + "." + channel));
DEFAULT_CHANNELS.forEach(channel -> newChannelConfig.createSection(CHANNELS_ROOT + "." + channel));
setConfigSection("general", generalDefaults());
setConfigSection("general", generalDefaults()); setConfigSection("town", townDefaults());
setConfigSection("town", townDefaults()); setConfigSection("nation", nationDefaults());
setConfigSection("nation", nationDefaults()); setConfigSection("alliance", allianceDefaults());
setConfigSection("alliance", allianceDefaults()); setConfigSection("admin", adminDefaults());
setConfigSection("admin", adminDefaults()); setConfigSection("mod", modDefaults());
setConfigSection("mod", modDefaults()); setConfigSection("local", localDefaults());
setConfigSection("local", localDefaults()); }
} }
}
private static void setConfigSection(String section, Map<String, Object> settings) {
private static void setConfigSection(String section, Map<String,Object> settings) { ConfigurationSection configurationSection = newChannelConfig.getConfigurationSection(CHANNELS_ROOT + "." + section);
ConfigurationSection configurationSection = newChannelConfig.getConfigurationSection(CHANNELS_ROOT + "." + section); settings.entrySet().stream().forEach(entry -> configurationSection.set(entry.getKey(), entry.getValue()));
settings.entrySet().stream().forEach(entry -> configurationSection.set(entry.getKey(), entry.getValue())); }
}
private static Map<String, Object> generalDefaults() {
private static Map<String, Object> generalDefaults() { Map<String, Object> channelMap = new LinkedHashMap<>();
Map<String, Object> channelMap = new LinkedHashMap<>(); channelMap.put("commands", "g");
channelMap.put("commands", "g"); channelMap.put("type", "GLOBAL");
channelMap.put("type", "GLOBAL"); channelMap.put("format", "{channelTag} {worldname}{townytagoverride}{townycolor}{permprefix}{group} {townyprefix}{modplayername}{townypostfix}{permsuffix}&f:{msgcolour} {msg}");
channelMap.put("format", "{channelTag} {worldname}{townytagoverride}{townycolor}{permprefix}{group} {townyprefix}{modplayername}{townypostfix}{permsuffix}&f:{msgcolour} {msg}"); channelMap.put("worldformats", new LinkedHashMap<>());
channelMap.put("worldformats", new LinkedHashMap<>()); channelMap.put("channelTag", "&f[g]");
channelMap.put("channelTag", "&f[g]"); channelMap.put("messagecolour", "&f");
channelMap.put("messagecolour", "&f"); channelMap.put("permission", "towny.chat.general");
channelMap.put("permission", "towny.chat.general"); channelMap.put("default", "true");
channelMap.put("default", "true"); channelMap.put("range", "-1");
channelMap.put("range", "-1"); channelMap.put("spam_time", "0.5");
channelMap.put("spam_time", "0.5"); return channelMap;
return channelMap; }
}
private static Map<String, Object> townDefaults() {
private static Map<String, Object> townDefaults() { Map<String, Object> channelMap = new LinkedHashMap<>();
Map<String, Object> channelMap = new LinkedHashMap<>(); channelMap.put("commands", "tc");
channelMap.put("commands", "tc"); channelMap.put("type", "TOWN");
channelMap.put("type", "TOWN"); channelMap.put("format", "{channelTag} {townycolor}{permprefix}{townyprefix}{playername}{townypostfix}{permsuffix}&f:{msgcolour} {msg}");
channelMap.put("format", "{channelTag} {townycolor}{permprefix}{townyprefix}{playername}{townypostfix}{permsuffix}&f:{msgcolour} {msg}"); channelMap.put("worldformats", new LinkedHashMap<>());
channelMap.put("worldformats", new LinkedHashMap<>()); channelMap.put("channelTag", "&f[&3TC&f]");
channelMap.put("channelTag", "&f[&3TC&f]"); channelMap.put("messagecolour", "&b");
channelMap.put("messagecolour", "&b"); channelMap.put("permission", "towny.chat.town");
channelMap.put("permission", "towny.chat.town"); channelMap.put("range", "-1");
channelMap.put("range", "-1"); channelMap.put("spam_time", "0.5");
channelMap.put("spam_time", "0.5"); return channelMap;
return channelMap; }
}
private static Map<String, Object> nationDefaults() {
private static Map<String, Object> nationDefaults() { Map<String, Object> channelMap = new LinkedHashMap<>();
Map<String, Object> channelMap = new LinkedHashMap<>(); channelMap.put("commands", "nc");
channelMap.put("commands", "nc"); channelMap.put("type", "NATION");
channelMap.put("type", "NATION"); channelMap.put("format", "{channelTag} {towntagoverride}{townycolor}{permprefix}{townyprefix}{playername}{townypostfix}{permsuffix}&f:{msgcolour} {msg}");
channelMap.put("format", "{channelTag} {towntagoverride}{townycolor}{permprefix}{townyprefix}{playername}{townypostfix}{permsuffix}&f:{msgcolour} {msg}"); channelMap.put("worldformats", new LinkedHashMap<>());
channelMap.put("worldformats", new LinkedHashMap<>()); channelMap.put("channelTag", "&f[&6NC&f]");
channelMap.put("channelTag", "&f[&6NC&f]"); channelMap.put("messagecolour", "&e");
channelMap.put("messagecolour", "&e"); channelMap.put("permission", "towny.chat.nation");
channelMap.put("permission", "towny.chat.nation"); channelMap.put("range", "-1");
channelMap.put("range", "-1"); channelMap.put("spam_time", "0.5");
channelMap.put("spam_time", "0.5"); return channelMap;
return channelMap; }
}
private static Map<String, Object> allianceDefaults() {
private static Map<String, Object> allianceDefaults() { Map<String, Object> channelMap = new LinkedHashMap<>();
Map<String, Object> channelMap = new LinkedHashMap<>(); channelMap.put("commands", "ac");
channelMap.put("commands", "ac"); channelMap.put("type", "ALLIANCE");
channelMap.put("type", "ALLIANCE"); channelMap.put("format", "{channelTag} {towntagoverride}{townycolor}{permprefix}{townyprefix}{playername}{townypostfix}{permsuffix}&f:{msgcolour} {msg}");
channelMap.put("format", "{channelTag} {towntagoverride}{townycolor}{permprefix}{townyprefix}{playername}{townypostfix}{permsuffix}&f:{msgcolour} {msg}"); channelMap.put("worldformats", new LinkedHashMap<>());
channelMap.put("worldformats", new LinkedHashMap<>()); channelMap.put("channelTag", "&f[&2AC&f]");
channelMap.put("channelTag", "&f[&2AC&f]"); channelMap.put("messagecolour", "&a");
channelMap.put("messagecolour", "&a"); channelMap.put("permission", "towny.chat.alliance");
channelMap.put("permission", "towny.chat.alliance"); channelMap.put("range", "-1");
channelMap.put("range", "-1"); channelMap.put("spam_time", "0.5");
channelMap.put("spam_time", "0.5"); return channelMap;
return channelMap; }
}
private static Map<String, Object> adminDefaults() {
private static Map<String, Object> adminDefaults() { Map<String, Object> channelMap = new LinkedHashMap<>();
Map<String, Object> channelMap = new LinkedHashMap<>(); channelMap.put("commands", "a,admin");
channelMap.put("commands", "a,admin"); channelMap.put("type", "DEFAULT");
channelMap.put("type", "DEFAULT"); channelMap.put("format", "{channelTag} {permprefix}{playername}{permsuffix}&f:{msgcolour} {msg}");
channelMap.put("format", "{channelTag} {permprefix}{playername}{permsuffix}&f:{msgcolour} {msg}"); channelMap.put("worldformats", new LinkedHashMap<>());
channelMap.put("worldformats", new LinkedHashMap<>()); channelMap.put("channelTag", "&f[&4ADMIN&f]");
channelMap.put("channelTag", "&f[&4ADMIN&f]"); channelMap.put("messagecolour", "&c");
channelMap.put("messagecolour", "&c"); channelMap.put("permission", "towny.chat.admin");
channelMap.put("permission", "towny.chat.admin"); channelMap.put("range", "-1");
channelMap.put("range", "-1"); return channelMap;
return channelMap; }
}
private static Map<String, Object> modDefaults() {
private static Map<String, Object> modDefaults() { Map<String, Object> channelMap = new LinkedHashMap<>();
Map<String, Object> channelMap = new LinkedHashMap<>(); channelMap.put("commands", "m,mod");
channelMap.put("commands", "m,mod"); channelMap.put("type", "DEFAULT");
channelMap.put("type", "DEFAULT"); channelMap.put("format", "{channelTag} {permprefix}{playername}{permsuffix}&f:{msgcolour} {msg}");
channelMap.put("format", "{channelTag} {permprefix}{playername}{permsuffix}&f:{msgcolour} {msg}"); channelMap.put("worldformats", new LinkedHashMap<>());
channelMap.put("worldformats", new LinkedHashMap<>()); channelMap.put("channelTag", "&f[&9MOD&f]");
channelMap.put("channelTag", "&f[&9MOD&f]"); channelMap.put("messagecolour", "&5");
channelMap.put("messagecolour", "&5"); channelMap.put("permission", "towny.chat.mod");
channelMap.put("permission", "towny.chat.mod"); channelMap.put("range", "-1");
channelMap.put("range", "-1"); return channelMap;
return channelMap; }
}
private static Map<String, Object> localDefaults() {
private static Map<String, Object> localDefaults() { Map<String, Object> channelMap = new LinkedHashMap<>();
Map<String, Object> channelMap = new LinkedHashMap<>(); channelMap.put("commands", "l,lc");
channelMap.put("commands", "l,lc"); channelMap.put("type", "GLOBAL");
channelMap.put("type", "GLOBAL"); channelMap.put("format", "{channelTag} {worldname}{townytagoverride}{townycolor}{permprefix}{group} {townyprefix}{modplayername}{townypostfix}{permsuffix}&f:{msgcolour} {msg}");
channelMap.put("format", "{channelTag} {worldname}{townytagoverride}{townycolor}{permprefix}{group} {townyprefix}{modplayername}{townypostfix}{permsuffix}&f:{msgcolour} {msg}"); channelMap.put("worldformats", new LinkedHashMap<>());
channelMap.put("worldformats", new LinkedHashMap<>()); channelMap.put("channelTag", "&f[local]");
channelMap.put("channelTag", "&f[local]"); channelMap.put("messagecolour", "&f");
channelMap.put("messagecolour", "&f"); channelMap.put("permission", "towny.chat.local");
channelMap.put("permission", "towny.chat.local"); channelMap.put("range", "100");
channelMap.put("range", "100"); return channelMap;
return channelMap; }
}
private static boolean loadChannels() {
private static boolean loadChannels() { ConfigurationSection configurationSection = channelConfig.getConfigurationSection(CHANNELS_ROOT);
ConfigurationSection configurationSection = channelConfig.getConfigurationSection(CHANNELS_ROOT); if (configurationSection == null) {
if (configurationSection == null) { Bukkit.getLogger().severe("[TownyChat] Failed to load Channels.yml!");
Bukkit.getLogger().severe("[TownyChat] Failed to load Channels.yml!"); Bukkit.getLogger().severe("[TownyChat] No channels root section was present!");
Bukkit.getLogger().severe("[TownyChat] No channels root section was present!"); return false;
return false; }
}
Set<String> channelsKeys = configurationSection.getKeys(false);
Set<String> channelsKeys = configurationSection.getKeys(false);
// This should never happen if the setDefaults(file) method has run.
// This should never happen if the setDefaults(file) method has run. if (channelsKeys.isEmpty()) {
if (channelsKeys.isEmpty()) { Bukkit.getLogger().severe("[TownyChat] Failed to load Channels.yml!");
Bukkit.getLogger().severe("[TownyChat] Failed to load Channels.yml!"); Bukkit.getLogger().severe("[TownyChat] No channels keys were present!");
Bukkit.getLogger().severe("[TownyChat] No channels keys were present!"); Bukkit.getLogger().severe("[TownyChat] Deleting your towny\\settings\\channels.yml can solve this problem.");
Bukkit.getLogger().severe("[TownyChat] Deleting your towny\\settings\\channels.yml can solve this problem."); return false;
return false; }
}
Chat plugin = Chat.getTownyChat();
Chat plugin = Chat.getTownyChat();
channelsKeys.forEach((channelName) -> {
channelsKeys.forEach((channelName)-> { Channel channel = new StandardChannel(plugin, channelName);
Channel channel = new StandardChannel(plugin, channelName); loadChannelSettings(channelName, channel);
loadChannelSettings(channelName, channel); plugin.getChannelsHandler().addChannel(channel);
plugin.getChannelsHandler().addChannel(channel); });
});
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) // This is because not everyone knows that you need to add a default: true into the channels.yml to make it the default channel!
// 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());
plugin.getChannelsHandler().setDefaultChannel(plugin.getChannelsHandler().getAllChannels().entrySet().iterator().next().getValue()); }
}
return true;
return true; }
}
private static void loadChannelSettings(String channelName, Channel channel) {
private static void loadChannelSettings(String channelName, Channel channel) { ChannelDetails data = new ChannelsSettings.ChannelDetails(channelConfig, channelName);
ChannelDetails data = new ChannelsSettings.ChannelDetails(channelConfig, channelName); // The following will always be present in some manner
// The following will always be present in some manner channel.setCommands(data.getCommands());
channel.setCommands(data.getCommands()); channel.setType(channelTypes.valueOf(data.getType()));
channel.setType(channelTypes.valueOf(data.getType())); channel.setFormat(data.getFormat());
channel.setFormat(data.getFormat()); channel.setWorldFormats(data.getWorldFormats());
channel.setWorldFormats(data.getWorldFormats()); channel.setRange(data.getRange());
channel.setRange(data.getRange()); channel.setHooked(data.isHooked());
channel.setHooked(data.isHooked()); channel.setFocusable(data.isFocusable());
channel.setFocusable(data.isFocusable()); channel.setLeavePermission(data.getLeavePermission());
channel.setLeavePermission(data.getLeavePermission()); // The following may not neccessarily be set.
// The following may not neccessarily be set. if (data.hasMessageColour())
if (data.hasMessageColour()) channel.setMessageColour(data.getMessageColour());
channel.setMessageColour(data.getMessageColour()); if (data.hasChannelTag())
if (data.hasChannelTag()) channel.setChannelTag(data.getChannelTag());
channel.setChannelTag(data.getChannelTag()); if (data.hasSound())
if (data.hasSound()) channel.setChannelSound(data.getSound());
channel.setChannelSound(data.getSound()); if (data.hasPermission())
if (data.hasPermission()) channel.setPermission(data.getPermission());
channel.setPermission(data.getPermission()); if (data.hasSpeakPermission())
if (data.hasSpeakPermission()) channel.setSpeakPermission(data.getSpeakPermission());
channel.setSpeakPermission(data.getSpeakPermission()); if (data.hasListenPermission())
if (data.hasListenPermission()) channel.setListenPermission(data.getListenPermission());
channel.setListenPermission(data.getListenPermission()); if (data.hasSpamTime())
if (data.hasSpamTime()) channel.setSpam_time(data.getSpamTime());
channel.setSpam_time(data.getSpamTime()); if (data.isDefault()) {
if (data.isDefault()) { Chat.getTownyChat().getChannelsHandler().setDefaultChannel(channel);
Chat.getTownyChat().getChannelsHandler().setDefaultChannel(channel); Chat.getTownyChat().getLogger().info("Default Channel set to " + channel.getName());
Chat.getTownyChat().getLogger().info("Default Channel set to " + channel.getName()); }
} }
}
static class ChannelDetails {
static class ChannelDetails { private Map<String, Object> channelSettingsMap = new HashMap<>();
private Map<String, Object> channelSettingsMap = new HashMap<>(); private String name;
private String name;
/**
/** * Constructor
* Constructor *
* * @param name Channel name
* @param name Channel name */
*/ public ChannelDetails(CommentedConfiguration channelsConfig, String name) {
public ChannelDetails(CommentedConfiguration channelsConfig, String name) { super();
super(); this.name = name;
this.name = name; String path = CHANNELS_ROOT + "." + this.name;
String path = CHANNELS_ROOT + "." + this.name; for (String key : channelsConfig.getConfigurationSection(path).getKeys(true)) {
for (String key : channelsConfig.getConfigurationSection(path).getKeys(true)) { String innerPath = path + "." + key;
String innerPath = path + "." + key; if (channelsConfig.get(innerPath) != null)
if (channelsConfig.get(innerPath) != null) channelSettingsMap.put(key, parseObject(channelsConfig.get(innerPath)));
channelSettingsMap.put(key, parseObject(channelsConfig.get(innerPath))); }
} }
}
private Object parseObject(Object object) {
private Object parseObject(Object object) { if (object instanceof @SuppressWarnings("rawtypes")List list)
if (object instanceof @SuppressWarnings("rawtypes") List list) return StringMgmt.join(list, ",");
return StringMgmt.join(list, ","); if (object instanceof String string)
if (object instanceof String string) return string;
return string; if (object instanceof Boolean b)
if (object instanceof Boolean b) return b;
return b; if (object instanceof Double d)
if (object instanceof Double d) return d;
return d; return "";
return ""; }
}
/**
/** * @return the name
* @return the name */
*/ public String getName() {
public String getName() { return name;
return name; }
}
public String getType() {
public String getType() { return (String) channelSettingsMap.getOrDefault("type", "DEFAULT");
return (String) channelSettingsMap.getOrDefault("type", "DEFAULT"); }
}
public String getFormat() {
public String getFormat() { return (String) channelSettingsMap.getOrDefault("format", "{channelTag} {worldname}{townytagoverride}{townycolor}{permprefix}{group} {townyprefix}{modplayername}{townypostfix}{permsuffix}&f:{msgcolour} {msg}");
return (String) channelSettingsMap.getOrDefault("format", "{channelTag} {worldname}{townytagoverride}{townycolor}{permprefix}{group} {townyprefix}{modplayername}{townypostfix}{permsuffix}&f:{msgcolour} {msg}"); }
}
public HashMap<String, Channel.WorldFormat> getWorldFormats() {
public HashMap<String, Channel.WorldFormat> getWorldFormats() { HashMap<String, Channel.WorldFormat> worldFormats = new HashMap<>();
HashMap<String, Channel.WorldFormat> worldFormats = new HashMap<>(); if (!ChatSettings.isPer_world())
if (!ChatSettings.isPer_world()) return worldFormats;
return worldFormats;
if (!channelSettingsMap.containsKey("worldformats"))
if (!channelSettingsMap.containsKey("worldformats")) return worldFormats;
return worldFormats;
for (TownyWorld world : TownyUniverse.getInstance().getTownyWorlds()) {
for (TownyWorld world : TownyUniverse.getInstance().getTownyWorlds()) { String worldName = world.getName();
String worldName = world.getName(); String path = "worldformats." + worldName;
String path = "worldformats." + worldName; if (channelSettingsMap.containsKey(path)) {
if (channelSettingsMap.containsKey(path)) { worldFormats.put(
worldFormats.put( worldName.toLowerCase(Locale.ROOT),
worldName.toLowerCase(Locale.ROOT), new Channel.WorldFormat(worldName, (String) channelSettingsMap.getOrDefault(path, getFormat()))
new Channel.WorldFormat(worldName, (String) channelSettingsMap.getOrDefault(path, getFormat())) );
); }
} }
} return worldFormats;
return worldFormats; }
}
public boolean hasChannelTag() {
public boolean hasChannelTag() { return channelSettingsMap.containsKey("channeltag");
return channelSettingsMap.containsKey("channeltag"); }
}
public String getChannelTag() {
public String getChannelTag() { return (String) channelSettingsMap.getOrDefault("channeltag", "");
return (String) channelSettingsMap.getOrDefault("channeltag", ""); }
}
public boolean hasMessageColour() {
public boolean hasMessageColour() { return channelSettingsMap.containsKey("messagecolour");
return channelSettingsMap.containsKey("messagecolour"); }
}
public String getMessageColour() {
public String getMessageColour() { return (String) channelSettingsMap.getOrDefault("messagecolour", "");
return (String) channelSettingsMap.getOrDefault("messagecolour", ""); }
}
public boolean hasPermission() {
public boolean hasPermission() { return channelSettingsMap.containsKey("permission");
return channelSettingsMap.containsKey("permission"); }
}
public String getPermission() {
public String getPermission() { return (String) channelSettingsMap.getOrDefault("permission", "");
return (String) channelSettingsMap.getOrDefault("permission", ""); }
}
public boolean hasLeavePermission() {
public boolean hasLeavePermission() { return channelSettingsMap.containsKey("leavepermission");
return channelSettingsMap.containsKey("leavepermission"); }
}
public String getLeavePermission() {
public String getLeavePermission() { return (String) channelSettingsMap.getOrDefault("leavepermission", "towny.chat.leave." + name);
return (String) channelSettingsMap.getOrDefault("leavepermission", "towny.chat.leave." + name); }
}
public boolean hasListenPermission() {
public boolean hasListenPermission() { return channelSettingsMap.containsKey("listenpermission");
return channelSettingsMap.containsKey("listenpermission"); }
}
public String getListenPermission() {
public String getListenPermission() { return (String) channelSettingsMap.getOrDefault("listenpermission", "");
return (String) channelSettingsMap.getOrDefault("listenpermission", ""); }
}
public boolean hasSpeakPermission() {
public boolean hasSpeakPermission() { return channelSettingsMap.containsKey("speakpermission");
return channelSettingsMap.containsKey("speakpermission"); }
}
public String getSpeakPermission() {
public String getSpeakPermission() { return (String) channelSettingsMap.getOrDefault("speakpermission", "");
return (String) channelSettingsMap.getOrDefault("speakpermission", ""); }
}
public boolean hasSound() {
public boolean hasSound() { return channelSettingsMap.containsKey("sound");
return channelSettingsMap.containsKey("sound"); }
}
public String getSound() {
public String getSound() { return (String) channelSettingsMap.getOrDefault("sound", "");
return (String) channelSettingsMap.getOrDefault("sound", ""); }
}
public boolean hasSpamTime() {
public boolean hasSpamTime() { return channelSettingsMap.containsKey("spam_time");
return channelSettingsMap.containsKey("spam_time"); }
}
public double getSpamTime() {
public double getSpamTime() { return Double.valueOf((String) channelSettingsMap.get("spam_time"));
return Double.valueOf((String) channelSettingsMap.get("spam_time")); }
}
public double getRange() {
public double getRange() { return Double.valueOf((String) channelSettingsMap.getOrDefault("range", -1));
return Double.valueOf((String) channelSettingsMap.getOrDefault("range", -1)); }
}
public boolean isHooked() {
public boolean isHooked() { return getBoolean(channelSettingsMap.getOrDefault("hooked", false));
return getBoolean(channelSettingsMap.getOrDefault("hooked", false)); }
}
public boolean isFocusable() {
public boolean isFocusable() { return getBoolean(channelSettingsMap.getOrDefault("focusable", true));
return getBoolean(channelSettingsMap.getOrDefault("focusable", true)); }
}
public boolean isDefault() {
public boolean isDefault() { return getBoolean(channelSettingsMap.getOrDefault("default", false));
return getBoolean(channelSettingsMap.getOrDefault("default", false)); }
}
public List<String> getCommands() {
public List<String> getCommands() { Object object = channelSettingsMap.get("commands");
Object object = channelSettingsMap.get("commands"); if (object instanceof String string) {
if (object instanceof String string) { return Arrays.asList(string.split(","));
return Arrays.asList(string.split(",")); }
} // As a fall-back we make a command from the channel name, this should not
// As a fall-back we make a command from the channel name, this should not // happen often or at all.
// happen often or at all. return Collections.singletonList(name + "chat");
return Collections.singletonList(name + "chat"); }
}
private boolean getBoolean(Object value) {
private boolean getBoolean(Object value) { if (value instanceof Boolean) {
if (value instanceof Boolean) { return (Boolean) value;
return (Boolean) value; } else if (value instanceof String) {
} else if (value instanceof String) { return Boolean.parseBoolean(value.toString());
return Boolean.parseBoolean(value.toString()); } else if (value instanceof Integer) {
} else if (value instanceof Integer) { return Integer.parseInt(value.toString()) != 0;
return Integer.parseInt(value.toString()) != 0; }
} return false;
return false; }
} }
}
} }
@@ -1,201 +1,200 @@
package com.palmergames.bukkit.TownyChat.config; package com.palmergames.bukkit.TownyChat.config;
public enum ChatConfigNodes { public enum ChatConfigNodes {
VERSION_HEADER("version", "", ""), VERSION_HEADER("version", "", ""),
VERSION( VERSION(
"version.version", "version.version",
"", "",
"# This is the current version of Towny. Please do not edit."), "# This is the current version of Towny. Please do not edit."),
LAST_RUN_VERSION( LAST_RUN_VERSION(
"version.last_run_version", "version.last_run_version",
"", "",
"# This is for showing the changelog on updates. Please do not edit."), "# This is for showing the changelog on updates. Please do not edit."),
CHATCONFIGCOMMENTS( CHATCONFIGCOMMENTS(
"chatconfigcomments", "chatconfigcomments",
"", "",
"", "",
"############################################################", "############################################################",
"# +------------------------------------------------------+ #", "# +------------------------------------------------------+ #",
"# | ChatConfig.yml | #", "# | ChatConfig.yml | #",
"# +------------------------------------------------------+ #", "# +------------------------------------------------------+ #",
"############################################################", "############################################################",
"#", "#",
"# The formats below will specify the changes made to the player chat when talking.", "# The formats below will specify the changes made to the player chat when talking.",
"#", "#",
"# {worldname} - Displays the world the player is currently in.", "# {worldname} - Displays the world the player is currently in.",
"# {town} - Displays town name if a member of a town.", "# {town} - Displays town name if a member of a town.",
"# {townformatted} - Displays town name (if a member of a town) using tag_format.town.", "# {townformatted} - Displays town name (if a member of a town) using tag_format.town.",
"# {towntag} - Displays the formated town tag (if a member of a town) using modify_chat.tag_format.town.", "# {towntag} - Displays the formated town tag (if a member of a town) using modify_chat.tag_format.town.",
"# {towntagoverride} - Displays the formated town tag (if a member of a town and present) or falls back to the full name (using modify_chat.tag_format.town).", "# {towntagoverride} - Displays the formated town tag (if a member of a town and present) or falls back to the full name (using modify_chat.tag_format.town).",
"#", "#",
"# {nation} - Displays nation name if a member of a nation.", "# {nation} - Displays nation name if a member of a nation.",
"# {nationformatted} - Displays nation name (if a member of a nation) using tag_format.town.", "# {nationformatted} - Displays nation name (if a member of a nation) using tag_format.town.",
"# {nationtag} - Displays the formated nation tag (if a member of a nation) using modify_chat.tag_format.nation.", "# {nationtag} - Displays the formated nation tag (if a member of a nation) using modify_chat.tag_format.nation.",
"# {nationtagoverride} - Displays the formated nation tag (if a member of a nation and present) or falls back to the full name (using modify_chat.tag_format.nation).", "# {nationtagoverride} - Displays the formated nation tag (if a member of a nation and present) or falls back to the full name (using modify_chat.tag_format.nation).",
"#", "#",
"# {townytag} - Displays the formated town/nation tag as specified in modify_chat.tag_format.both.", "# {townytag} - Displays the formated town/nation tag as specified in modify_chat.tag_format.both.",
"# {townyformatted} - Displays the formated full town/nation names as specified in modify_chat.tag_format.both.", "# {townyformatted} - Displays the formated full town/nation names as specified in modify_chat.tag_format.both.",
"# {townytagoverride} - Displays the formated town/nation tag (if present) or falls back to the full names (using modify_chat.tag_format.both).", "# {townytagoverride} - Displays the formated town/nation tag (if present) or falls back to the full names (using modify_chat.tag_format.both).",
"#", "#",
"# {title} - Towny resident Title.", "# {title} - Towny resident Title.",
"# {surname} - Towny resident Surname.", "# {surname} - Towny resident Surname.",
"# {townynameprefix} - Towny name prefix taken from the townLevel/nationLevels.", "# {townynameprefix} - Towny name prefix taken from the townLevel/nationLevels.",
"# {townynamepostfix} - Towny name postfix taken from the townLevel/nationLevels.", "# {townynamepostfix} - Towny name postfix taken from the townLevel/nationLevels.",
"# {townyprefix} - Towny resident title, or townynameprefix if no title exists.", "# {townyprefix} - Towny resident title, or townynameprefix if no title exists.",
"# {townypostfix} - Towny resident surname, or townynamepostfix if no surname exists", "# {townypostfix} - Towny resident surname, or townynamepostfix if no surname exists",
"#", "#",
"# {townycolor} - Towny name colour for king/mayor/resident.", "# {townycolor} - Towny name colour for king/mayor/resident.",
"# {group} - Players group name pulled from your permissions plugin.", "# {group} - Players group name pulled from your permissions plugin.",
"# {permuserprefix} - Permission user prefix.", "# {permuserprefix} - Permission user prefix.",
"# {permusersuffix} - Permission user suffix.", "# {permusersuffix} - Permission user suffix.",
"# {permgroupprefix} - Permission group prefix.", "# {permgroupprefix} - Permission group prefix.",
"# {permgroupsuffix} - Permission group suffix.", "# {permgroupsuffix} - Permission group suffix.",
"# {permprefix} - Permission group and user prefix.", "# {permprefix} - Permission group and user prefix.",
"# {permsuffix} - Permission group and user suffix.", "# {permsuffix} - Permission group and user suffix.",
"#", "#",
"# {primaryresidentrank} - When a resident has a primary rank with a prefix this will display their prefix with a space added to the end.", "# {primaryresidentrank} - When a resident has a primary rank with a prefix this will display their prefix with a space added to the end.",
"#", "#",
"# {playername} - Default player name.", "# {playername} - Default player name.",
"# {modplayername} - Modified player name (use if Towny is over writing some other plugins changes).", "# {modplayername} - Modified player name (use if Towny is over writing some other plugins changes).",
"# {msg} - The message sent.", "# {msg} - The message sent.",
"#", "#",
"# {channelTag} - Defined in the channels entry in Channels.yml.", "# {channelTag} - Defined in the channels entry in Channels.yml.",
"# {msgcolour} - Defined in the channels entry in Channels.yml.", "# {msgcolour} - Defined in the channels entry in Channels.yml.",
"#", "#",
"# Text colouring", "# Text colouring",
"# --------------", "# --------------",
"# Black = &0, Navy = &1, Green = &2, Blue = &3, Red = &4", "# Black = &0, Navy = &1, Green = &2, Blue = &3, Red = &4",
"# Purple = &5, Gold = &6, LightGray = &7, Gray = &8", "# Purple = &5, Gold = &6, LightGray = &7, Gray = &8",
"# DarkPurple = &9, LightGreen = &a, LightBlue = &b", "# DarkPurple = &9, LightGreen = &a, LightBlue = &b",
"# Rose = &c, LightPurple = &d, Yellow = &e, White = &f", "# Rose = &c, LightPurple = &d, Yellow = &e, White = &f",
"#", "#",
"# Text altering", "# Text altering",
"# -------------", "# -------------",
"# Bold = &l, Italics = &o, Underlined = &n,", "# Bold = &l, Italics = &o, Underlined = &n,",
"# Magic = &k, Strike = &m, Reset = &r", "# Magic = &k, Strike = &m, Reset = &r",
"#", "#",
"# Hex Chat Coloring", "# Hex Chat Coloring",
"# -----------------", "# -----------------",
"# Valid formats: ", "# Valid formats: ",
"# #RRGGBB", "# #RRGGBB",
"# &#RRGGBB", "# &#RRGGBB",
"# {#RRGGBB}"), "# {#RRGGBB}"),
TAG_FORMATS( TAG_FORMATS(
"tag_formats", "tag_formats",
"", "",
""), ""),
TAG_FORMATS_WORLD( TAG_FORMATS_WORLD(
"tag_formats.world", "tag_formats.world",
"&f[&f%s&f] "), "&f[&f%s&f] "),
TAG_FORMATS_TOWN( TAG_FORMATS_TOWN(
"tag_formats.town", "tag_formats.town",
"&f[&3%s&f] "), "&f[&3%s&f] "),
TAG_FORMATS_NATION( TAG_FORMATS_NATION(
"tag_formats.nation", "tag_formats.nation",
"&f[&e%s&f] "), "&f[&e%s&f] "),
TAG_FORMATS_BOTH( TAG_FORMATS_BOTH(
"tag_formats.both", "tag_formats.both",
"&f[&6%s&f|&3%s&f] ", "&f[&6%s&f|&3%s&f] ",
"# First %s is the nation tag, second is the town tag.", "# First %s is the nation tag, second is the town tag.",
"# You may also use %t for the town tag and %n for the nation tag!"), "# You may also use %t for the town tag and %n for the nation tag!"),
COLOUR( COLOUR(
"colour", "colour",
"", "",
""), ""),
COLOUR_KING( COLOUR_KING(
"colour.king", "colour.king",
"&6"), "&6"),
COLOUR_MAYOR( COLOUR_MAYOR(
"colour.mayor", "colour.mayor",
"&b"), "&b"),
COLOUR_RESIDENT( COLOUR_RESIDENT(
"colour.resident", "colour.resident",
"&f"), "&f"),
COLOUR_NOMAD( COLOUR_NOMAD(
"colour.nomad", "colour.nomad",
"&f"), "&f"),
MODIFY_CHAT( MODIFY_CHAT(
"modify_chat", "modify_chat",
"", "",
""), ""),
MODIFY_CHAT_ENABLE( MODIFY_CHAT_ENABLE(
"modify_chat.enable", "modify_chat.enable",
"true", "true",
"# When true Towny will format all ChannelTypes,", "# When true Towny will format all ChannelTypes,",
"# When false Towny will only format TOWN, NATION, ALLIANCE, DEFAULT types.", "# When false Towny will only format TOWN, NATION, ALLIANCE, DEFAULT types.",
"# When false Towny will not format GLOBAL types, leaving other chat plugins to do the work."), "# When false Towny will not format GLOBAL types, leaving other chat plugins to do the work."),
MODIFY_CHAT_PER_WORLD( MODIFY_CHAT_PER_WORLD(
"modify_chat.per_world", "modify_chat.per_world",
"false", "false",
"# If true the chat formats will be read from below to allow per world formatting.", "# If true the chat formats will be read from below to allow per world formatting.",
"# These can then be altered individually."), "# These can then be altered individually."),
MODIFY_CHAT_ALONE_MESSAGE( MODIFY_CHAT_ALONE_MESSAGE(
"modify_chat.alone_message", "modify_chat.alone_message",
"false", "false",
"# If true any player who speaks in a channel in which he cannot be heard,", "# If true any player who speaks in a channel in which he cannot be heard,",
"# either by being along in the channel or out-of-range of another player in his chat channel,", "# either by being along in the channel or out-of-range of another player in his chat channel,",
"# that player will see a message saying they cannot be heard."), "# that player will see a message saying they cannot be heard."),
MODIFY_CHAT_ALONE_MESSAGE_STRING( MODIFY_CHAT_ALONE_MESSAGE_STRING(
"modify_chat.alone_message_string", "modify_chat.alone_message_string",
"No one in range can hear you or you are alone in this channel.", "No one in range can hear you or you are alone in this channel.",
"# This allows you to set your alone message."), "# This allows you to set your alone message."),
DISPLAY_CHANNEL_JOIN_MESSAGE_ON_JOIN( DISPLAY_CHANNEL_JOIN_MESSAGE_ON_JOIN(
"display_channel_join_message_on_joining_the_server", "display_channel_join_message_on_joining_the_server",
"true", "true",
"", "",
"# If true players will see You have joined channel {channel} message on joining the server."), "# If true players will see You have joined channel {channel} message on joining the server."),
ALLOW_EXCLAMATION_POINT_SHOUTS( ALLOW_EXCLAMATION_POINT_SHOUTS(
"allow_exclamation_point_to_shout", "allow_exclamation_point_to_shout",
"true", "true",
"", "",
"# If true players that say !somewords will have their message sent to a global type channel with unlimited range (usually your general chat.)"); "# If true players that say !somewords will have their message sent to a global type channel with unlimited range (usually your general chat.)");
private final String Root;
private final String Default;
private String[] comments;
private final String Root; private ChatConfigNodes(String root, String def, String... comments) {
private final String Default;
private String[] comments;
private ChatConfigNodes(String root, String def, String... comments) { this.Root = root;
this.Default = def;
this.comments = comments;
}
this.Root = root; /**
this.Default = def; * Retrieves the root for a config option
this.comments = comments; *
} * @return The root for a config option
*/
public String getRoot() {
/** return Root;
* 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 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) {
* Retrieves the comment for a config path return comments;
* }
* @return The comments for a config path
*/
public String[] getComments() {
if (comments != null) { String[] comments = new String[1];
return comments; comments[0] = "";
} return comments;
}
String[] comments = new String[1];
comments[0] = "";
return comments;
}
} }
@@ -3,11 +3,8 @@ package com.palmergames.bukkit.TownyChat.config;
import com.palmergames.bukkit.TownyChat.Chat; import com.palmergames.bukkit.TownyChat.Chat;
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.object.TownyWorld;
import com.palmergames.util.FileMgmt; import com.palmergames.util.FileMgmt;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.configuration.ConfigurationSection;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
@@ -15,182 +12,181 @@ import java.io.IOException;
public class ChatSettings { public class ChatSettings {
private static CommentedConfiguration chatConfig, newChatConfig; private static CommentedConfiguration chatConfig, newChatConfig;
/**
*
* @return true if the chatconfig has loaded.
* @throws IOException
*/
public static boolean loadCommentedChatConfig() {
String filepath = Chat.getTownyChat().getChatConfigPath();
if (FileMgmt.checkOrCreateFile(filepath)) {
File file = new File(filepath);
// read the config.yml into memory /**
ChatSettings.chatConfig = new CommentedConfiguration(file.toPath()); * @return true if the chatconfig has loaded.
if (!chatConfig.load()) { * @throws IOException
Bukkit.getLogger().severe("[TownyChat] Failed to load ChatConfig!"); */
Bukkit.getLogger().severe("[TownyChat] Please check that the file passes a YAML Parser test:"); public static boolean loadCommentedChatConfig() {
Bukkit.getLogger().severe("[TownyChat] Online YAML Parser: https://yaml-online-parser.appspot.com/"); String filepath = Chat.getTownyChat().getChatConfigPath();
return false; if (FileMgmt.checkOrCreateFile(filepath)) {
} File file = new File(filepath);
setDefaults(file);
chatConfig.save();
}
return true;
}
/**
* Builds a new chatconfig reading old chatconfig data,
* and setting new nodes to default values.
*/
private static void setDefaults(File file) {
String version = Chat.getTownyChat().getDescription().getVersion(); // read the config.yml into memory
newChatConfig = new CommentedConfiguration(file.toPath()); ChatSettings.chatConfig = new CommentedConfiguration(file.toPath());
newChatConfig.load(); if (!chatConfig.load()) {
Bukkit.getLogger().severe("[TownyChat] Failed to load ChatConfig!");
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);
chatConfig.save();
}
return true;
}
for (ChatConfigNodes root : ChatConfigNodes.values()) { /**
if (root.getComments().length > 0) * Builds a new chatconfig reading old chatconfig data,
addComment(root.getRoot(), root.getComments()); * and setting new nodes to default values.
*/
private static void setDefaults(File file) {
if (root.getRoot() == ChatConfigNodes.VERSION.getRoot()) String version = Chat.getTownyChat().getDescription().getVersion();
setNewProperty(root.getRoot(), version); newChatConfig = new CommentedConfiguration(file.toPath());
else if (root.getRoot() == ChatConfigNodes.LAST_RUN_VERSION.getRoot()) newChatConfig.load();
setNewProperty(root.getRoot(), getLastRunVersion(version));
else
// A regular config node.
setNewProperty(root.getRoot(), (chatConfig.get(root.getRoot().toLowerCase()) != null) ? chatConfig.get(root.getRoot().toLowerCase()) : root.getDefault());
}
chatConfig = newChatConfig;
newChatConfig = null;
}
private static void addComment(String root, String... comments) { for (ChatConfigNodes root : ChatConfigNodes.values()) {
newChatConfig.addComment(root.toLowerCase(), comments); if (root.getComments().length > 0)
} addComment(root.getRoot(), root.getComments());
private static void setNewProperty(String root, Object value) {
if (value == null) {
value = "";
}
newChatConfig.set(root.toLowerCase(), value.toString());
}
private static String getLastRunVersion(String currentVersion) {
return getString(ConfigNodes.LAST_RUN_VERSION.getRoot(), currentVersion);
}
private static String getString(String root, String def) {
String data = chatConfig.getString(root.toLowerCase(), def);
if (data == null) {
sendError(root.toLowerCase() + " from ChatConfig.yml");
return "";
}
return data;
}
private static String getString(ChatConfigNodes node) {
return chatConfig.getString(node.getRoot().toLowerCase(), node.getDefault());
}
private static void sendError(String msg) {
Chat.getTownyChat().getLogger().warning("[TownyChat] Error could not read " + msg);
}
private static boolean getBoolean(ChatConfigNodes node) { if (root.getRoot() == ChatConfigNodes.VERSION.getRoot())
setNewProperty(root.getRoot(), version);
return Boolean.parseBoolean(chatConfig.getString(node.getRoot().toLowerCase(), node.getDefault())); else if (root.getRoot() == ChatConfigNodes.LAST_RUN_VERSION.getRoot())
} setNewProperty(root.getRoot(), getLastRunVersion(version));
else
// A regular config node.
setNewProperty(root.getRoot(), (chatConfig.get(root.getRoot().toLowerCase()) != null) ? chatConfig.get(root.getRoot().toLowerCase()) : root.getDefault());
}
chatConfig = newChatConfig;
newChatConfig = null;
}
/* private static void addComment(String root, String... comments) {
* Get ChatConfig variables. newChatConfig.addComment(root.toLowerCase(), comments);
*/ }
/** private static void setNewProperty(String root, Object value) {
* @return the modify_chat if (value == null) {
*/ value = "";
public static boolean isModify_chat() { }
return getBoolean(ChatConfigNodes.MODIFY_CHAT_ENABLE); newChatConfig.set(root.toLowerCase(), value.toString());
} }
/** private static String getLastRunVersion(String currentVersion) {
* @return the alone_message return getString(ConfigNodes.LAST_RUN_VERSION.getRoot(), currentVersion);
*/ }
public static boolean isUsingAloneMessage() {
return getBoolean(ChatConfigNodes.MODIFY_CHAT_ALONE_MESSAGE);
}
/** private static String getString(String root, String def) {
* @return the alone_message_string String data = chatConfig.getString(root.toLowerCase(), def);
*/ if (data == null) {
public static String getUsingAloneMessageString() { sendError(root.toLowerCase() + " from ChatConfig.yml");
return getString(ChatConfigNodes.MODIFY_CHAT_ALONE_MESSAGE_STRING); return "";
} }
return data;
}
/** private static String getString(ChatConfigNodes node) {
* @return the per_world return chatConfig.getString(node.getRoot().toLowerCase(), node.getDefault());
*/ }
public static boolean isPer_world() {
return getBoolean(ChatConfigNodes.MODIFY_CHAT_PER_WORLD);
}
/** private static void sendError(String msg) {
* @return the display_modes_set_on_join setting Chat.getTownyChat().getLogger().warning("[TownyChat] Error could not read " + msg);
*/ }
public static boolean getShowChannelMessageOnServerJoin() {
return getBoolean(ChatConfigNodes.DISPLAY_CHANNEL_JOIN_MESSAGE_ON_JOIN);
}
/** private static boolean getBoolean(ChatConfigNodes node) {
* @return true if preceding exclamation points shouts into global channel with unlimited range.
*/
public static boolean isExclamationPoint() {
return getBoolean(ChatConfigNodes.ALLOW_EXCLAMATION_POINT_SHOUTS);
}
/* return Boolean.parseBoolean(chatConfig.getString(node.getRoot().toLowerCase(), node.getDefault()));
* Get Tags formats. }
*/
public static String getWorldTag() { /*
return getString(ChatConfigNodes.TAG_FORMATS_WORLD); * Get ChatConfig variables.
} */
public static String getTownTag() { /**
return getString(ChatConfigNodes.TAG_FORMATS_TOWN); * @return the modify_chat
} */
public static boolean isModify_chat() {
return getBoolean(ChatConfigNodes.MODIFY_CHAT_ENABLE);
}
public static String getNationTag() { /**
return getString(ChatConfigNodes.TAG_FORMATS_NATION); * @return the alone_message
} */
public static boolean isUsingAloneMessage() {
return getBoolean(ChatConfigNodes.MODIFY_CHAT_ALONE_MESSAGE);
}
public static String getBothTag() { /**
return getString(ChatConfigNodes.TAG_FORMATS_BOTH); * @return the alone_message_string
} */
public static String getUsingAloneMessageString() {
return getString(ChatConfigNodes.MODIFY_CHAT_ALONE_MESSAGE_STRING);
}
/* /**
* Get Colour formats. * @return the per_world
*/ */
public static boolean isPer_world() {
return getBoolean(ChatConfigNodes.MODIFY_CHAT_PER_WORLD);
}
public static String getKingColour() { /**
return getString(ChatConfigNodes.COLOUR_KING); * @return the display_modes_set_on_join setting
} */
public static boolean getShowChannelMessageOnServerJoin() {
return getBoolean(ChatConfigNodes.DISPLAY_CHANNEL_JOIN_MESSAGE_ON_JOIN);
}
public static String getMayorColour() { /**
return getString(ChatConfigNodes.COLOUR_MAYOR); * @return true if preceding exclamation points shouts into global channel with unlimited range.
} */
public static boolean isExclamationPoint() {
return getBoolean(ChatConfigNodes.ALLOW_EXCLAMATION_POINT_SHOUTS);
}
public static String getResidentColour() { /*
return getString(ChatConfigNodes.COLOUR_RESIDENT); * Get Tags formats.
} */
public static String getNomadColour() { public static String getWorldTag() {
return getString(ChatConfigNodes.COLOUR_NOMAD); return getString(ChatConfigNodes.TAG_FORMATS_WORLD);
} }
private static String getOrDefault(String configPath, ChatConfigNodes channelNode) { public static String getTownTag() {
return String.valueOf(chatConfig.get(configPath, channelNode.getDefault())); return getString(ChatConfigNodes.TAG_FORMATS_TOWN);
} }
public static String getNationTag() {
return getString(ChatConfigNodes.TAG_FORMATS_NATION);
}
public static String getBothTag() {
return getString(ChatConfigNodes.TAG_FORMATS_BOTH);
}
/*
* Get Colour formats.
*/
public static String getKingColour() {
return getString(ChatConfigNodes.COLOUR_KING);
}
public static String getMayorColour() {
return getString(ChatConfigNodes.COLOUR_MAYOR);
}
public static String getResidentColour() {
return getString(ChatConfigNodes.COLOUR_RESIDENT);
}
public static String getNomadColour() {
return getString(ChatConfigNodes.COLOUR_NOMAD);
}
private static String getOrDefault(String configPath, ChatConfigNodes channelNode) {
return String.valueOf(chatConfig.get(configPath, channelNode.getDefault()));
}
} }
@@ -1,129 +1,134 @@
package com.palmergames.bukkit.TownyChat.events; package com.palmergames.bukkit.TownyChat.events;
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 net.kyori.adventure.audience.Audience; import io.papermc.paper.event.player.AsyncChatEvent;
import org.bukkit.entity.Player; import net.kyori.adventure.audience.Audience;
import org.bukkit.event.Event; import net.kyori.adventure.text.Component;
import org.bukkit.event.HandlerList; import org.bukkit.entity.Player;
import org.bukkit.event.player.AsyncPlayerChatEvent; import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import java.util.HashSet;
import java.util.Set; import java.util.Set;
/* /*
* Allows other plugins to hook into a chat message being accepted into any of the channels * Allows other plugins to hook into a chat message being accepted into any of the channels
* *
* In order to use this event, you will have to add the hooked: true flag to the channel you wish you hook in the channels.yml * In order to use this event, you will have to add the hooked: true flag to the channel you wish you hook in the channels.yml
* *
* ex: * ex:
* *
*Channels: *Channels:
* general: * general:
* commands: [g] * commands: [g]
* type: GLOBAL * type: GLOBAL
* hooked: true * hooked: true
* channeltag: '&f[g]' * channeltag: '&f[g]'
* messagecolour: '&f' * messagecolour: '&f'
* permission: 'towny.chat.general' * permission: 'towny.chat.general'
* range: '-1' * range: '-1'
*/ */
public class AsyncChatHookEvent extends Event { public class AsyncChatHookEvent extends Event {
private static final HandlerList handlers = new HandlerList(); private static final HandlerList handlers = new HandlerList();
protected AsyncPlayerChatEvent event; protected AsyncChatEvent event;
protected boolean changed; protected boolean changed;
protected Channel channel; protected Channel channel;
protected Set<Player> recipients; protected Set<Player> recipients;
protected Audience audience; protected Audience audience;
public AsyncChatHookEvent(AsyncPlayerChatEvent event, Channel channel, boolean async) { public AsyncChatHookEvent(AsyncChatEvent event, Channel channel, boolean async, Set<Player> recipients) {
super(async); super(async);
this.event = event; this.event = event;
this.changed = false; this.changed = false;
this.channel = channel; this.channel = channel;
this.recipients = new HashSet<>(event.getRecipients()); this.recipients = recipients;
this.audience = Audience.audience(getRecipients().stream().map(player -> Chat.getTownyChat().adventure().player(player)).toArray(Audience[]::new)); this.audience = Audience.audience(getRecipients().stream().map(player -> Chat.getTownyChat().adventure().player(player)).toArray(Audience[]::new));
} }
public Channel getChannel() { public static HandlerList getHandlerList() {
return channel; return handlers;
} }
/* public Channel getChannel() {
* Returns true if the hooked event was changed return channel;
*/ }
public boolean isChanged() {
return changed; /*
} * Returns true if the hooked event was changed
*/
/* public boolean isChanged() {
* Informs Chat if the event was changed or not return changed;
*/ }
public void setChanged(boolean changed) {
this.changed = changed; /*
} * Informs Chat if the event was changed or not
*/
public AsyncPlayerChatEvent getAsyncPlayerChatEvent() { public void setChanged(boolean changed) {
return event; this.changed = changed;
} }
public String getFormat() { public AsyncChatEvent getAsyncPlayerChatEvent() {
return event.getFormat(); return event;
} }
public String getMessage() { public String getFormat() {
return event.getMessage(); return "";
} }
public Set<Player> getRecipients() { public void setFormat(String format) {
return this.recipients; }
}
public String getMessage() {
public Audience getAudience() { return "";
return this.audience; }
}
public void setMessage(String message) {
public boolean isCancelled() { }
return event.isCancelled();
} public void setMessage(Component message) {
changed = true;
public Player getPlayer() { event.message(message);
return event.getPlayer(); }
}
public Component message() {
public void setRecipients(Set<Player> recipients) { return event.message();
changed = true; }
this.recipients.clear();
this.recipients.addAll(recipients); public Set<Player> getRecipients() {
setAudience(Audience.audience(this.recipients.stream().map(player -> Chat.getTownyChat().adventure().player(player)).toArray(Audience[]::new))); // Update audience as well return this.recipients;
} }
public void setAudience(Audience audience) { public void setRecipients(Set<Player> recipients) {
changed = true; changed = true;
this.audience = audience; this.recipients.clear();
} this.recipients.addAll(recipients);
setAudience(Audience.audience(this.recipients.stream().map(player -> Chat.getTownyChat().adventure().player(player)).toArray(Audience[]::new))); // Update audience as well
public void setFormat(String format) { }
changed = true;
event.setFormat(format); public Audience getAudience() {
} return this.audience;
}
public void setMessage(String message) {
changed = true; public void setAudience(Audience audience) {
event.setMessage(message); changed = true;
} this.audience = audience;
}
public void setCancelled(boolean cancel) {
changed = (cancel); public boolean isCancelled() {
event.setCancelled(cancel); return event.isCancelled();
} }
@Override public void setCancelled(boolean cancel) {
public HandlerList getHandlers() { changed = (cancel);
return handlers; event.setCancelled(cancel);
} }
public static HandlerList getHandlerList() { public Player getPlayer() {
return handlers; return event.getPlayer();
} }
}
@Override
public HandlerList getHandlers() {
return handlers;
}
}
@@ -1,41 +1,40 @@
package com.palmergames.bukkit.TownyChat.events; package com.palmergames.bukkit.TownyChat.events;
import com.palmergames.bukkit.TownyChat.channels.Channel; import com.palmergames.bukkit.TownyChat.channels.Channel;
import org.bukkit.Bukkit;
import org.bukkit.Bukkit; import org.bukkit.entity.Player;
import org.bukkit.entity.Player; import org.bukkit.event.Event;
import org.bukkit.event.Event; import org.bukkit.event.HandlerList;
import org.bukkit.event.HandlerList;
/**
/** * Created by Glare
* Created by Glare * Date: 12/14/2020
* Date: 12/14/2020 * Time: 4:56 PM
* Time: 4:56 PM */
*/ public class PlayerJoinChatChannelEvent extends Event {
public class PlayerJoinChatChannelEvent extends Event { private static final HandlerList HANDLERS = new HandlerList();
private static final HandlerList HANDLERS = new HandlerList(); private final Player player;
private final Player player; private final Channel channel;
private final Channel channel;
public PlayerJoinChatChannelEvent(Player player, Channel channel) {
public PlayerJoinChatChannelEvent(Player player, Channel channel) { super(!Bukkit.getServer().isPrimaryThread());
super(!Bukkit.getServer().isPrimaryThread()); this.player = player;
this.player = player; this.channel = channel;
this.channel = channel; }
}
public static HandlerList getHandlerList() {
public HandlerList getHandlers() { return HANDLERS;
return HANDLERS; }
}
public HandlerList getHandlers() {
public static HandlerList getHandlerList() { return HANDLERS;
return HANDLERS; }
}
public Player getPlayer() {
public Player getPlayer() { return player;
return player; }
}
public Channel getChannel() {
public Channel getChannel() { return channel;
return channel; }
} }
}
@@ -1,51 +1,51 @@
package com.palmergames.bukkit.TownyChat.listener; package com.palmergames.bukkit.TownyChat.listener;
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.channelTypes; import com.palmergames.bukkit.TownyChat.channels.channelTypes;
import net.essentialsx.api.v2.events.discord.DiscordChatMessageEvent; import net.essentialsx.api.v2.events.discord.DiscordChatMessageEvent;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
/** /**
* Listener which stops non-global or limited-range * Listener which stops non-global or limited-range
* chats from passing on to EssentialsDiscord. * chats from passing on to EssentialsDiscord.
* *
* @author JRoy * @author JRoy
* @since 0.90 * @since 0.90
*/ */
public class EssentialsDiscordHookListener implements Listener { public class EssentialsDiscordHookListener implements Listener {
private final Chat plugin; private final Chat plugin;
public EssentialsDiscordHookListener(Chat plugin) { public EssentialsDiscordHookListener(Chat plugin) {
this.plugin = plugin; this.plugin = plugin;
} }
@EventHandler() @EventHandler()
public void onDiscordChat(DiscordChatMessageEvent event) { public void onDiscordChat(DiscordChatMessageEvent event) {
String directChat = plugin.getTownyPlayerListener().directedChat.get(event.getPlayer()); String directChat = plugin.getTownyPlayerListener().directedChat.get(event.getPlayer());
if (directChat != null) { if (directChat != null) {
plugin.getTownyPlayerListener().directedChat.remove(event.getPlayer()); plugin.getTownyPlayerListener().directedChat.remove(event.getPlayer());
if (event.isCancelled()) { if (event.isCancelled()) {
return; return;
} }
Channel channel = plugin.getChannelsHandler().getChannel(directChat); Channel channel = plugin.getChannelsHandler().getChannel(directChat);
if (channel != null) { if (channel != null) {
event.setCancelled(channel.getType() != channelTypes.GLOBAL || channel.getRange() != -1); event.setCancelled(channel.getType() != channelTypes.GLOBAL || channel.getRange() != -1);
return; return;
} }
} }
for (Channel curChannel : plugin.getChannelsHandler().getAllChannels().values()) { for (Channel curChannel : plugin.getChannelsHandler().getAllChannels().values()) {
if (plugin.getPlayerChannel(event.getPlayer()) != null && plugin.getPlayerChannel(event.getPlayer()).getName().equals(curChannel.getName())) { if (plugin.getPlayerChannel(event.getPlayer()) != null && plugin.getPlayerChannel(event.getPlayer()).getName().equals(curChannel.getName())) {
event.setCancelled(curChannel.getType() != channelTypes.GLOBAL || curChannel.getRange() != -1); event.setCancelled(curChannel.getType() != channelTypes.GLOBAL || curChannel.getRange() != -1);
return; return;
} }
} }
Channel channel = plugin.getChannelsHandler().getActiveChannel(event.getPlayer(), channelTypes.GLOBAL); Channel channel = plugin.getChannelsHandler().getActiveChannel(event.getPlayer(), channelTypes.GLOBAL);
if (channel != null) { if (channel != null) {
event.setCancelled(channel.getType() != channelTypes.GLOBAL || channel.getRange() != -1); event.setCancelled(channel.getType() != channelTypes.GLOBAL || channel.getRange() != -1);
} }
} }
} }
@@ -1,56 +1,64 @@
package com.palmergames.bukkit.TownyChat.listener; package com.palmergames.bukkit.TownyChat.listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import com.palmergames.bukkit.towny.object.Resident; import com.palmergames.bukkit.towny.object.Resident;
import io.papermc.paper.event.player.AsyncChatEvent;
import net.kyori.adventure.text.Component;
import org.jetbrains.annotations.NotNull;
public class LocalTownyChatEvent { public class LocalTownyChatEvent {
private AsyncPlayerChatEvent event; private AsyncChatEvent event;
private Resident resident; private Resident resident;
public LocalTownyChatEvent(AsyncPlayerChatEvent event, Resident resident) {
this.event = event;
this.resident = resident;
}
/** public LocalTownyChatEvent(AsyncChatEvent event, Resident resident) {
* Get the resident associated with the chat event's talking player. this.event = event;
* @return resident associated with the chat event's talking player this.resident = resident;
*/ }
public Resident getResident() {
return resident; /**
} * Get the resident associated with the chat event's talking player.
*
/** * @return resident associated with the chat event's talking player
* */
* @return the PlayerChatEvent public Resident getResident() {
*/ return resident;
public AsyncPlayerChatEvent getEvent() { }
return event;
} /**
* @return the AsyncChatEvent
*/
/** public AsyncChatEvent getEvent() {
* Convenience method for setting the chat event's format. return event;
* @param format }
*/
public void setFormat(String format) { /**
event.setFormat(format); * Convenience method for getting the chat event's format
} *
* @return the chat event's format
/** */
* Convenience method for getting the chat event's format @Deprecated
* @return the chat event's format public String getFormat() {
*/ return "";
public String getFormat() { }
return event.getFormat();
} /**
* Convenience method for setting the chat event's format.
/** *
* Convenience method for getting the chat event's message * @param format
* @return the chat event's message */
*/ @Deprecated
public String getMessage() { public void setFormat(String format) {
return event.getMessage(); }
}
/**
* Convenience method for getting the chat event's message
*
* @return the chat event's message
*/
public String getMessage() {
return "";
}
public @NotNull Component message() {
return event.message();
}
} }
@@ -12,13 +12,11 @@ import com.palmergames.bukkit.towny.object.Translatable;
import com.palmergames.bukkit.towny.object.metadata.StringDataField; import com.palmergames.bukkit.towny.object.metadata.StringDataField;
import com.palmergames.bukkit.towny.utils.MetaDataUtil; import com.palmergames.bukkit.towny.utils.MetaDataUtil;
import com.palmergames.bukkit.util.Colors; import com.palmergames.bukkit.util.Colors;
import io.papermc.paper.event.player.AsyncChatEvent;
import me.clip.placeholderapi.PlaceholderAPI; import me.clip.placeholderapi.PlaceholderAPI;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.audience.Audiences;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.tag.Tag; import net.kyori.adventure.text.minimessage.tag.Tag;
import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver; import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
@@ -31,289 +29,289 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.UnknownFormatConversionException; import java.util.UnknownFormatConversionException;
import java.util.WeakHashMap; import java.util.WeakHashMap;
import java.util.stream.Collectors;
public class TownyChatPlayerListener implements Listener { public class TownyChatPlayerListener implements Listener {
private Chat plugin; public WeakHashMap<Player, String> directedChat = new WeakHashMap<>();
private Chat plugin;
public WeakHashMap<Player, String> directedChat = new WeakHashMap<>();
public TownyChatPlayerListener(Chat instance) { public TownyChatPlayerListener(Chat instance) {
this.plugin = instance; this.plugin = instance;
} }
@EventHandler(priority = EventPriority.LOW) @EventHandler(priority = EventPriority.LOW)
public void onPlayerJoin(final PlayerJoinEvent event) { public void onPlayerJoin(final PlayerJoinEvent event) {
plugin.getScheduler().runLater(event.getPlayer(), () -> loginPlayer(event.getPlayer()), 2L);
} plugin.getScheduler().runLater(event.getPlayer(), () -> loginPlayer(event.getPlayer()), 2L);
private void loginPlayer(Player player) { }
checkPlayerForOldMeta(player);
refreshPlayerChannels(player);
Channel channel = plugin.getChannelsHandler().getDefaultChannel(); private void loginPlayer(Player player) {
if (channel != null && channel.hasSpeakPermission(player)) { checkPlayerForOldMeta(player);
plugin.setPlayerChannel(player, channel);
if (ChatSettings.getShowChannelMessageOnServerJoin())
TownyMessaging.sendMessage(player, Translatable.of("tc_you_are_now_talking_in_channel", channel.getName()));
}
}
@EventHandler(priority = EventPriority.LOW) refreshPlayerChannels(player);
public void onPlayerQuit(final PlayerQuitEvent event) {
refreshPlayerChannels(event.getPlayer());
}
private void refreshPlayerChannels(Player player) {
plugin.getChannelsHandler().getAllChannels().values().stream().forEach(channel -> channel.forgetPlayer(player));
}
@EventHandler
public void onPlayerChat(AsyncPlayerChatEvent event) {
Player player = event.getPlayer();
// Check if the message contains colour codes we need to remove or parse. Channel channel = plugin.getChannelsHandler().getDefaultChannel();
testColourCodes(event, player); if (channel != null && channel.hasSpeakPermission(player)) {
plugin.setPlayerChannel(player, channel);
if (ChatSettings.getShowChannelMessageOnServerJoin())
TownyMessaging.sendMessage(player, Translatable.of("tc_you_are_now_talking_in_channel", channel.getName()));
}
}
// Check if essentials has this player muted. @EventHandler(priority = EventPriority.LOW)
if (!isEssentialsMuted(player)) { public void onPlayerQuit(final PlayerQuitEvent event) {
refreshPlayerChannels(event.getPlayer());
boolean forceGlobal = ChatSettings.isExclamationPoint() && event.getMessage().startsWith("!"); }
/* private void refreshPlayerChannels(Player player) {
* If this was directed chat send it via the relevant channel plugin.getChannelsHandler().getAllChannels().values().stream().forEach(channel -> channel.forgetPlayer(player));
*/ }
if (directedChat.containsKey(player)) {
Channel channel = plugin.getChannelsHandler().getChannel(directedChat.get(player));
if (channel != null) {
if (isMutedOrSpam(event, channel, player)) {
directedChat.remove(player);
return;
}
channel.chatProcess(event);
if (!Chat.usingEssentialsDiscord || event.isCancelled()) {
directedChat.remove(player);
}
return;
}
directedChat.remove(player);
}
/*
* Check the player for any channel modes.
*/
Channel channel = plugin.getPlayerChannel(player);
if (!forceGlobal && channel != null && channel.hasSpeakPermission(player)) {
if (isMutedOrSpam(event, channel, player))
return;
channel.chatProcess(event);
return;
}
/*
* Find a global channel this player has permissions for.
*/
channel = plugin.getChannelsHandler().getActiveChannel(player, channelTypes.GLOBAL, forceGlobal);
if (channel != null) {
if (isMutedOrSpam(event, channel, player))
return;
if (forceGlobal)
event.setMessage(event.getMessage().substring(1));
channel.chatProcess(event);
return;
}
}
/* @EventHandler
* We found no channels available so modify the chat (if enabled) and exit. public void onPlayerChat(AsyncChatEvent event) {
*/ Player player = event.getPlayer();
if (ChatSettings.isModify_chat()) {
Resident resident = TownyAPI.getInstance().getResident(player);
if (resident == null)
return;
// Nuke the channeltag and message colouring, but apply the remaining format.
String format = plugin.getPlayerChannel(player).getFormat(player);
// format is left to store the original non-PAPI-parsed chat format. // TODO START HERE ROOOOOSE :))) This is where the logic "begins"
List<TagResolver> tagResolvers = new ArrayList<>(); // Check if the message contains colour codes we need to remove or parse.
tagResolvers.add( testColourCodes(event, player);
TagResolver.resolver(
TagResolver.resolver("channeltag", Tag.inserting(Component.empty())),
TagResolver.resolver("msgcolour", Tag.inserting(Component.empty()))
)
);
String newFormat = format;
// Parse any PAPI placeholders. // Check if essentials has this player muted.
if (Chat.usingPlaceholderAPI) if (!isEssentialsMuted(player)) {
newFormat = PlaceholderAPI.setPlaceholders(player, format);
// Attempt to apply the new format. boolean forceGlobal = ChatSettings.isExclamationPoint() && event.getMessage().startsWith("!");
/*
* If this was directed chat send it via the relevant channel
*/
if (directedChat.containsKey(player)) {
Channel channel = plugin.getChannelsHandler().getChannel(directedChat.get(player));
if (channel != null) {
if (isMutedOrSpam(event, channel, player)) {
directedChat.remove(player);
return;
}
channel.chatProcess(event);
if (!Chat.usingEssentialsDiscord || event.isCancelled()) {
directedChat.remove(player);
}
return;
}
directedChat.remove(player);
}
/*
* Check the player for any channel modes.
*/
Channel channel = plugin.getPlayerChannel(player);
if (!forceGlobal && channel != null && channel.hasSpeakPermission(player)) {
if (isMutedOrSpam(event, channel, player))
return;
channel.chatProcess(event);
return;
}
/*
* Find a global channel this player has permissions for.
*/
channel = plugin.getChannelsHandler().getActiveChannel(player, channelTypes.GLOBAL, forceGlobal);
if (channel != null) {
if (isMutedOrSpam(event, channel, player))
return;
if (forceGlobal)
event.setMessage(event.getMessage().substring(1));
channel.chatProcess(event);
return;
}
}
/*
* We found no channels available so modify the chat (if enabled) and exit.
*/
if (ChatSettings.isModify_chat()) {
Resident resident = TownyAPI.getInstance().getResident(player);
if (resident == null)
return;
// Nuke the channeltag and message colouring, but apply the remaining format.
String format = plugin.getPlayerChannel(player).getFormat(player);
// format is left to store the original non-PAPI-parsed chat format.
List<TagResolver> tagResolvers = new ArrayList<>();
tagResolvers.add(
TagResolver.resolver(
TagResolver.resolver("channeltag", Tag.inserting(Component.empty())),
TagResolver.resolver("msgcolour", Tag.inserting(Component.empty()))
)
);
String newFormat = format;
// Parse any PAPI placeholders.
if (Chat.usingPlaceholderAPI)
newFormat = PlaceholderAPI.setPlaceholders(player, format);
// Attempt to apply the new format.
// catchFormatConversionException(event, format, newFormat); // catchFormatConversionException(event, format, newFormat);
// Fire the LocalTownyChatEvent. // Fire the LocalTownyChatEvent.
LocalTownyChatEvent chatEvent = new LocalTownyChatEvent(event, resident); LocalTownyChatEvent chatEvent = new LocalTownyChatEvent(event, resident);
// Format the chat line, replacing the TownyChat chat tags. // Format the chat line, replacing the TownyChat chat tags.
tagResolvers.add(TownyChatFormatter.getChatFormat(chatEvent)); tagResolvers.add(TownyChatFormatter.getChatFormat(chatEvent));
// newFormat = TownyChatFormatter.getChatFormat(chatEvent); // newFormat = TownyChatFormatter.getChatFormat(chatEvent);
// Attempt to apply the new format. // Attempt to apply the new format.
// catchFormatConversionException(event, format, newFormat); // catchFormatConversionException(event, format, newFormat);
// Set the format based on the global channelformat, with channeltag and msgcolour removed. // Set the format based on the global channelformat, with channeltag and msgcolour removed.
// event.setFormat(newFormat); // event.setFormat(newFormat);
Component component = Chat.getTownyChat().getMiniMessage().deserialize(newFormat, tagResolvers.toArray(new TagResolver[0])); // The lines below were added by dark
Audience.audience(event.getRecipients().stream().map(p -> Chat.getTownyChat().adventure().player(p)).toArray(Audience[]::new)).sendMessage(component);; // Component component = Chat.getTownyChat().getMiniMessage().deserialize(newFormat, tagResolvers.toArray(new TagResolver[0]));
// Audience.audience(event.getRecipients().stream().map(p -> Chat.getTownyChat().adventure().player(p)).toArray(Audience[]::new)).sendMessage(component);;
// event.setFormat(GsonComponentSerializer.gson().serialize(component)); // event.setFormat(GsonComponentSerializer.gson().serialize(component));
} }
} }
/** /**
* Remove colour tags that a player doesn't not have permission for, * Remove colour tags that a player doesn't not have permission for,
* and colour messages if the player is allowed. * and colour messages if the player is allowed.
* *
* @param event {@link AsyncPlayerChatEvent} which has been fired. * @param event {@link AsyncChatEvent} which has been fired.
* @param player {@link Player} which has spoken. * @param player {@link Player} which has spoken.
*/ */
private void testColourCodes(AsyncPlayerChatEvent event, Player player) { private void testColourCodes(AsyncChatEvent event, Player player) {
if ((event.getMessage().contains("&L") || event.getMessage().contains("&l")) if ((event.getMessage().contains("&L") || event.getMessage().contains("&l"))
&& !player.hasPermission("townychat.chat.format.bold")) && !player.hasPermission("townychat.chat.format.bold"))
event.setMessage(event.getMessage().replaceAll("&L", "").replaceAll("&l", "")); event.setMessage(event.getMessage().replaceAll("&L", "").replaceAll("&l", ""));
if ((event.getMessage().contains("&O") || event.getMessage().contains("&o")) if ((event.getMessage().contains("&O") || event.getMessage().contains("&o"))
&& !player.hasPermission("townychat.chat.format.italic")) && !player.hasPermission("townychat.chat.format.italic"))
event.setMessage(event.getMessage().replaceAll("&O", "").replaceAll("&o", "")); event.setMessage(event.getMessage().replaceAll("&O", "").replaceAll("&o", ""));
if ((event.getMessage().contains("&K") || event.getMessage().contains("&k")) if ((event.getMessage().contains("&K") || event.getMessage().contains("&k"))
&& !player.hasPermission("townychat.chat.format.magic")) && !player.hasPermission("townychat.chat.format.magic"))
event.setMessage(event.getMessage().replaceAll("&K", "").replaceAll("&k", "")); event.setMessage(event.getMessage().replaceAll("&K", "").replaceAll("&k", ""));
if ((event.getMessage().contains("&N") || event.getMessage().contains("&n")) if ((event.getMessage().contains("&N") || event.getMessage().contains("&n"))
&& !player.hasPermission("townychat.chat.format.underlined")) && !player.hasPermission("townychat.chat.format.underlined"))
event.setMessage(event.getMessage().replaceAll("&N", "").replaceAll("&n", "")); event.setMessage(event.getMessage().replaceAll("&N", "").replaceAll("&n", ""));
if ((event.getMessage().contains("&M") || event.getMessage().contains("&m")) if ((event.getMessage().contains("&M") || event.getMessage().contains("&m"))
&& !player.hasPermission("townychat.chat.format.strike")) && !player.hasPermission("townychat.chat.format.strike"))
event.setMessage(event.getMessage().replaceAll("&M", "").replaceAll("&m", "")); event.setMessage(event.getMessage().replaceAll("&M", "").replaceAll("&m", ""));
if ((event.getMessage().contains("&R") || event.getMessage().contains("&r")) if ((event.getMessage().contains("&R") || event.getMessage().contains("&r"))
&&!player.hasPermission("townychat.chat.format.reset")) && !player.hasPermission("townychat.chat.format.reset"))
event.setMessage(event.getMessage().replaceAll("&R", "").replaceAll("&r", "")); event.setMessage(event.getMessage().replaceAll("&R", "").replaceAll("&r", ""));
if (player.hasPermission("townychat.chat.color")) if (player.hasPermission("townychat.chat.color"))
event.setMessage(Colors.translateColorCodes(event.getMessage())); event.setMessage(Colors.translateColorCodes(event.getMessage()));
} }
/** /**
* Is this player Muted via Essentials? * Is this player Muted via Essentials?
* *
* @param player {@link Player} speaking. * @param player {@link Player} speaking.
* @return true if muted by Essentials. * @return true if muted by Essentials.
*/ */
private boolean isEssentialsMuted(Player player) { private boolean isEssentialsMuted(Player player) {
// Check if essentials has this player muted. // Check if essentials has this player muted.
if (plugin.isEssentialsMuted(player)) { if (plugin.isEssentialsMuted(player)) {
TownyMessaging.sendErrorMsg(player, Translatable.of("tc_err_unable_to_talk_essentials_mute")); TownyMessaging.sendErrorMsg(player, Translatable.of("tc_err_unable_to_talk_essentials_mute"));
return true; return true;
} }
return false; return false;
} }
/** /**
* Check if the player is channel-muted or channel-spamming and cancel the * Check if the player is channel-muted or channel-spamming and cancel the
* {@link AsyncPlayerChatEvent} if this is the case. * {@link AsyncChatEvent} if this is the case.
* *
* @param event {@link AsyncPlayerChatEvent} which has fired. * @param event {@link AsyncChatEvent} which has fired.
* @param channel {@link Channel} being spoken in to. * @param channel {@link Channel} being spoken in to.
* @param player {@link Player} speaking. * @param player {@link Player} speaking.
* @return true if the chat is muted or spammed. * @return true if the chat is muted or spammed.
*/ */
private boolean isMutedOrSpam(AsyncPlayerChatEvent event, Channel channel, Player player) { private boolean isMutedOrSpam(AsyncChatEvent event, Channel channel, Player player) {
if (channel.isMuted(player.getName())) { if (channel.isMuted(player.getName())) {
TownyMessaging.sendErrorMsg(player, Translatable.of("tc_err_you_are_currently_muted_in_channel", channel.getName())); TownyMessaging.sendErrorMsg(player, Translatable.of("tc_err_you_are_currently_muted_in_channel", channel.getName()));
event.setCancelled(true); event.setCancelled(true);
return true; return true;
} }
if (channel.isSpam(player)) { if (channel.isSpam(player)) {
event.setCancelled(true); event.setCancelled(true);
return true; return true;
} }
return false; return false;
} }
// From TownyChat 0.84-0.95 the symbol used to separate the channels in the meta // From TownyChat 0.84-0.95 the symbol used to separate the channels in the meta
// was not good for non-unicode-using mysql servers. // was not good for non-unicode-using mysql servers.
private void checkPlayerForOldMeta(Player player) { private void checkPlayerForOldMeta(Player player) {
Resident resident = TownyAPI.getInstance().getResident(player); Resident resident = TownyAPI.getInstance().getResident(player);
if (resident != null && playerHasTCMeta(resident)) if (resident != null && playerHasTCMeta(resident))
checkIfMetaContainsOldSplitter(resident); checkIfMetaContainsOldSplitter(resident);
} }
private boolean playerHasTCMeta(Resident resident) { private boolean playerHasTCMeta(Resident resident) {
StringDataField icsdf = new StringDataField("townychat_ignoredChannels", "", "Ignored TownyChat Channels"); StringDataField icsdf = new StringDataField("townychat_ignoredChannels", "", "Ignored TownyChat Channels");
StringDataField socsdf = new StringDataField("townychat_soundOffChannels", "", "TownyChat Channels with Sound Toggle Off"); StringDataField socsdf = new StringDataField("townychat_soundOffChannels", "", "TownyChat Channels with Sound Toggle Off");
return MetaDataUtil.hasMeta(resident, icsdf) || MetaDataUtil.hasMeta(resident, socsdf); return MetaDataUtil.hasMeta(resident, icsdf) || MetaDataUtil.hasMeta(resident, socsdf);
} }
private void checkIfMetaContainsOldSplitter(Resident resident) { private void checkIfMetaContainsOldSplitter(Resident resident) {
StringDataField icsdf = new StringDataField("townychat_ignoredChannels", "", "Ignored TownyChat Channels"); StringDataField icsdf = new StringDataField("townychat_ignoredChannels", "", "Ignored TownyChat Channels");
if (MetaDataUtil.hasMeta(resident, icsdf)) { if (MetaDataUtil.hasMeta(resident, icsdf)) {
String meta = MetaDataUtil.getString(resident, icsdf); String meta = MetaDataUtil.getString(resident, icsdf);
if (meta.contains("\uFF0c ")) { if (meta.contains("\uFF0c ")) {
meta = replaceSymbol(meta); meta = replaceSymbol(meta);
MetaDataUtil.setString(resident, icsdf, meta, true); MetaDataUtil.setString(resident, icsdf, meta, true);
} }
} }
StringDataField socsdf = new StringDataField("townychat_soundOffChannels", "", "TownyChat Channels with Sound Toggle Off"); StringDataField socsdf = new StringDataField("townychat_soundOffChannels", "", "TownyChat Channels with Sound Toggle Off");
if (MetaDataUtil.hasMeta(resident, socsdf)) { if (MetaDataUtil.hasMeta(resident, socsdf)) {
String meta = MetaDataUtil.getString(resident, socsdf); String meta = MetaDataUtil.getString(resident, socsdf);
if (meta.contains("\uFF0c ")) { if (meta.contains("\uFF0c ")) {
meta = replaceSymbol(meta); meta = replaceSymbol(meta);
MetaDataUtil.setString(resident, socsdf, meta, true); MetaDataUtil.setString(resident, socsdf, meta, true);
} }
} }
} }
private String replaceSymbol(String meta) { private String replaceSymbol(String meta) {
char[] charray = meta.toCharArray(); char[] charray = meta.toCharArray();
for (int i = 0; i < meta.length(); i++) { for (int i = 0; i < meta.length(); i++) {
char n = meta.charAt(i); char n = meta.charAt(i);
if (n == '\uFF0c') if (n == '\uFF0c')
charray[i] = ','; charray[i] = ',';
} }
return new String(charray); return new String(charray);
} }
private void catchFormatConversionException(AsyncPlayerChatEvent event, String format, String newFormat) { private void catchFormatConversionException(AsyncPlayerChatEvent event, String format, String newFormat) {
try { try {
event.setFormat(newFormat); event.setFormat(newFormat);
} catch (UnknownFormatConversionException e) { } catch (UnknownFormatConversionException e) {
// This exception is usually thrown when a PAPI placeholder did not get parsed // This exception is usually thrown when a PAPI placeholder did not get parsed
// and has left behind a % symbol followed by something that String#format // and has left behind a % symbol followed by something that String#format
// cannot handle. // cannot handle.
boolean percentSymbol = format.contains("%" + e.getConversion()); boolean percentSymbol = format.contains("%" + e.getConversion());
String errmsg = "TownyChat tried to apply a chat format that is not allowed: '" + String errmsg = "TownyChat tried to apply a chat format that is not allowed: '" +
newFormat + "', because of the " + e.getConversion() + " symbol" + newFormat + "', because of the " + e.getConversion() + " symbol" +
(percentSymbol ? ", found after a %. There is probably a PAPIPlaceholder that could not be parsed." : "." + (percentSymbol ? ", found after a %. There is probably a PAPIPlaceholder that could not be parsed." : "." +
" You should attempt to correct this in your towny\\settings\\chatconfig.yml file and use /townychat reload."); " You should attempt to correct this in your towny\\settings\\chatconfig.yml file and use /townychat reload.");
Chat.getTownyChat().getLogger().severe(errmsg); Chat.getTownyChat().getLogger().severe(errmsg);
if (percentSymbol) if (percentSymbol)
// Attempt to remove the unparsed placeholder and send this right back. // Attempt to remove the unparsed placeholder and send this right back.
catchFormatConversionException(event, format, purgePAPI(newFormat, "%" + e.getConversion())); catchFormatConversionException(event, format, purgePAPI(newFormat, "%" + e.getConversion()));
else else
// Just let the chat go, this results in an error in the log, and TownyChat not being able to format chat. // Just let the chat go, this results in an error in the log, and TownyChat not being able to format chat.
event.setFormat(format); event.setFormat(format);
} }
} }
private String purgePAPI(String format, String startOfPlaceholder) { private String purgePAPI(String format, String startOfPlaceholder) {
return format.replaceAll(startOfPlaceholder + ".*%", ""); return format.replaceAll(startOfPlaceholder + ".*%", "");
} }
} }
@@ -1,43 +1,42 @@
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;
/* /*
* *
* Created by ElgarL * Created by ElgarL
* *
*/ */
public class onLoadedTask implements Runnable { public class onLoadedTask implements Runnable {
Chat plugin; Chat plugin;
Towny towny; Towny towny;
public onLoadedTask(Chat plugin) { public onLoadedTask(Chat plugin) {
super(); super();
this.plugin = plugin; this.plugin = plugin;
this.towny = plugin.getTowny(); this.towny = plugin.getTowny();
} }
@Override @Override
public void run() { public void run() {
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()) { 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;
} }
plugin.getLogger().info("-******* TownyChat enabled *******-"); plugin.getLogger().info("-******* TownyChat enabled *******-");
plugin.registerPermissions(); plugin.registerPermissions();
plugin.registerEvents(); plugin.registerEvents();
} }
} }
} }
@@ -1,18 +1,17 @@
package com.palmergames.bukkit.TownyChat.util; package com.palmergames.bukkit.TownyChat.util;
import org.bukkit.entity.Player; import com.palmergames.bukkit.TownyChat.Chat;
import org.bukkit.entity.Player;
import com.palmergames.bukkit.TownyChat.Chat;
public class EssentialsIntegration {
public class EssentialsIntegration {
public static boolean ignoredByEssentials(Player sender, Player player) {
public static boolean ignoredByEssentials(Player sender, Player player) { com.earth2me.essentials.User targetUser = Chat.getTownyChat().getEssentials().getUser(player);
com.earth2me.essentials.User targetUser = Chat.getTownyChat().getEssentials().getUser(player); com.earth2me.essentials.User senderUser = Chat.getTownyChat().getEssentials().getUser(sender);
com.earth2me.essentials.User senderUser = Chat.getTownyChat().getEssentials().getUser(sender); return targetUser.isIgnoredPlayer(senderUser);
return targetUser.isIgnoredPlayer(senderUser); }
}
public static boolean isMuted(Player player) {
public static boolean isMuted(Player player) { return Chat.getTownyChat().getEssentials().getUser(player).isMuted();
return Chat.getTownyChat().getEssentials().getUser(player).isMuted(); }
} }
}
@@ -1,59 +1,59 @@
package com.palmergames.bukkit.TownyChat.util; package com.palmergames.bukkit.TownyChat.util;
import com.palmergames.bukkit.TownyChat.TownyChatReplacer;
import com.palmergames.bukkit.TownyChat.listener.LocalTownyChatEvent;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.function.Function; import java.util.function.Function;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import com.palmergames.bukkit.TownyChat.TownyChatReplacer;
import com.palmergames.bukkit.TownyChat.listener.LocalTownyChatEvent;
/** /**
* Register keyword regex's to be dynamically replaced. * Register keyword regex's to be dynamically replaced.
* * <p>
* Credits to: * Credits to:
* - http://stackoverflow.com/questions/1326682/java-replacing-multiple-different-substring-in-a-string-at-once-or-in-the-most-e/1326962#1326962 * - http://stackoverflow.com/questions/1326682/java-replacing-multiple-different-substring-in-a-string-at-once-or-in-the-most-e/1326962#1326962
* * <p>
* Improved in v 2.0 to use Java 8's Function. * Improved in v 2.0 to use Java 8's Function.
* *
* @author Chris H (Shade) 1.0, LlmDl 2.0 * @author Chris H (Shade) 1.0, LlmDl 2.0
* @version 2.0 * @version 2.0
*/ */
public class StringReplaceManager<E> { public class StringReplaceManager<E> {
private List<Pattern> replacementPatterns = new ArrayList<Pattern>(); private List<Pattern> replacementPatterns = new ArrayList<Pattern>();
private List<TownyChatReplacer> replacements = new ArrayList<TownyChatReplacer>(); private List<TownyChatReplacer> replacements = new ArrayList<TownyChatReplacer>();
public boolean registerReplacer(String chatSlug, Function<LocalTownyChatEvent, String> replacement) { public boolean registerReplacer(String chatSlug, Function<LocalTownyChatEvent, String> replacement) {
Pattern pattern = Pattern.compile(Pattern.quote(chatSlug)); Pattern pattern = Pattern.compile(Pattern.quote(chatSlug));
replacementPatterns.add(pattern); replacementPatterns.add(pattern);
replacements.add(new TownyChatReplacer(replacement)); replacements.add(new TownyChatReplacer(replacement));
return true; return true;
} }
public String replaceAll(String format, LocalTownyChatEvent e) { public String replaceAll(String format, LocalTownyChatEvent e) {
String out = format; String out = format;
for (int i = 0; i < replacementPatterns.size(); i++) { for (int i = 0; i < replacementPatterns.size(); i++) {
Matcher matcher = replacementPatterns.get(i).matcher(out); Matcher matcher = replacementPatterns.get(i).matcher(out);
TownyChatReplacer replacer = replacements.get(i); TownyChatReplacer replacer = replacements.get(i);
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
while (matcher.find()) { while (matcher.find()) {
if (replacer == null) { if (replacer == null) {
matcher.appendReplacement(sb, e.toString()); matcher.appendReplacement(sb, e.toString());
} else { } else {
try { try {
String replacement = Matcher.quoteReplacement(replacer.getWith(e)); String replacement = Matcher.quoteReplacement(replacer.getWith(e));
matcher.appendReplacement(sb, replacement); matcher.appendReplacement(sb, replacement);
} catch (Exception exception) { } catch (Exception exception) {
continue; continue;
} }
} }
} }
matcher.appendTail(sb); matcher.appendTail(sb);
out = sb.toString(); out = sb.toString();
} }
return out; return out;
} }
} }