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
19 files changed
+289 -285

No files matched your search

+26 -30
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,7 +42,7 @@ 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
@@ -51,30 +50,41 @@ import java.util.concurrent.ConcurrentMap;
public class Chat extends JavaPlugin { public class Chat extends JavaPlugin {
public static boolean usingPlaceholderAPI = false;
public static boolean usingEssentialsDiscord = false;
private static Chat chat = null;
private static String requiredTownyVersion = "0.98.0.0";
private static ConcurrentMap<UUID, Channel> playerChannelMap;
private final Object scheduler;
protected PluginManager pm;
boolean chatConfigError = false;
boolean channelsConfigError = false;
private TownyChatPlayerListener TownyPlayerListener; private TownyChatPlayerListener TownyPlayerListener;
private ChannelsHolder channels; private ChannelsHolder channels;
protected PluginManager pm;
private static Chat chat = null;
private final Object scheduler;
private Towny towny = null; private Towny towny = null;
private DynmapAPI dynMap = null; private DynmapAPI dynMap = null;
private Essentials essentials = null; private Essentials essentials = null;
private BukkitAudiences adventure = null; private BukkitAudiences adventure = null;
private MiniMessage miniMessage = null; private MiniMessage miniMessage = null;
private static String requiredTownyVersion = "0.98.0.0";
public static boolean usingPlaceholderAPI = false;
public static boolean usingEssentialsDiscord = false;
boolean chatConfigError = false;
boolean channelsConfigError = false;
private static ConcurrentMap<UUID, Channel> playerChannelMap;
public Chat() { public Chat() {
chat = this; chat = this;
this.scheduler = townyVersionCheck() ? isFoliaClassPresent() ? new FoliaTaskScheduler(this) : new BukkitTaskScheduler(this) : null; this.scheduler = townyVersionCheck() ? isFoliaClassPresent() ? new FoliaTaskScheduler(this) : new BukkitTaskScheduler(this) : null;
} }
public static Chat getTownyChat() {
return chat;
}
private static boolean isFoliaClassPresent() {
try {
Class.forName("io.papermc.paper.threadedregions.RegionizedServer");
return true;
} catch (ClassNotFoundException e) {
return false;
}
}
@Override @Override
public void onEnable() { public void onEnable() {
pm = getServer().getPluginManager(); pm = getServer().getPluginManager();
@@ -123,17 +133,13 @@ public class Chat extends JavaPlugin {
} }
private void loadConfigs() { private void loadConfigs() {
FileMgmt.checkOrCreateFolders(new String[] { getRootPath(), getTownySettingsPath() }); FileMgmt.checkOrCreateFolders(new String[]{getRootPath(), getTownySettingsPath()});
chatConfigError = !ChatSettings.loadCommentedChatConfig(); chatConfigError = !ChatSettings.loadCommentedChatConfig();
channelsConfigError = !ChannelsSettings.loadCommentedChannelsConfig(); channelsConfigError = !ChannelsSettings.loadCommentedChannelsConfig();
} }
public static Chat getTownyChat() {
return chat;
}
public @NonNull BukkitAudiences adventure() { public @NonNull BukkitAudiences adventure() {
if(this.adventure == null) { if (this.adventure == null) {
throw new IllegalStateException("Tried to access Adventure when the plugin was disabled!"); throw new IllegalStateException("Tried to access Adventure when the plugin was disabled!");
} }
return this.adventure; return this.adventure;
@@ -233,7 +239,6 @@ public class Chat extends JavaPlugin {
} }
} }
public String getRootPath() { public String getRootPath() {
return getTowny().getDataFolder().getPath(); return getTowny().getDataFolder().getPath();
} }
@@ -321,13 +326,4 @@ public class Chat extends JavaPlugin {
public TaskScheduler getScheduler() { public TaskScheduler getScheduler() {
return (TaskScheduler) this.scheduler; return (TaskScheduler) this.scheduler;
} }
private static boolean isFoliaClassPresent() {
try {
Class.forName("io.papermc.paper.threadedregions.RegionizedServer");
return true;
} catch (ClassNotFoundException e) {
return false;
}
}
} }
@@ -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,8 +26,8 @@ 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 {
@@ -48,69 +47,6 @@ public class ChannelCommand extends BaseCommand implements CommandExecutor {
plugin = instance; plugin = instance;
} }
@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"));
}
}
public static void parseChannelList(Player player) { public static void parseChannelList(Player player) {
// If not our command // If not our command
Map<String, Channel> chanList = plugin.getChannelsHandler().getAllChannels(); Map<String, Channel> chanList = plugin.getChannelsHandler().getAllChannels();
@@ -333,7 +269,7 @@ public class ChannelCommand extends BaseCommand implements CommandExecutor {
// 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);
} }
} }
@@ -409,4 +345,67 @@ public class ChannelCommand extends BaseCommand implements CommandExecutor {
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,7 +17,6 @@ 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 {
@@ -27,6 +26,8 @@ public class TownyChatCommand extends BaseCommand implements CommandExecutor {
townychat_help.add(ChatTools.formatCommand("", "/townychat", "reload", "")); townychat_help.add(ChatTools.formatCommand("", "/townychat", "reload", ""));
} }
private Chat plugin;
public TownyChatCommand(Chat instance) { public TownyChatCommand(Chat instance) {
this.plugin = instance; this.plugin = instance;
} }
@@ -8,7 +8,6 @@ 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;
@@ -1,9 +1,9 @@
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;
@@ -7,8 +7,8 @@ import com.palmergames.bukkit.towny.object.Resident;
import com.palmergames.bukkit.towny.object.Translatable; import com.palmergames.bukkit.towny.object.Translatable;
import com.palmergames.bukkit.towny.object.metadata.CustomDataField; import com.palmergames.bukkit.towny.object.metadata.CustomDataField;
import com.palmergames.bukkit.towny.object.metadata.StringDataField; import com.palmergames.bukkit.towny.object.metadata.StringDataField;
import io.papermc.paper.event.player.AsyncChatEvent;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import java.util.*; import java.util.*;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
@@ -16,19 +16,19 @@ import java.util.concurrent.ConcurrentMap;
public abstract class Channel { public abstract class Channel {
protected ConcurrentMap<String, Integer> absentPlayers = null;
protected ConcurrentMap<String, Integer> mutedPlayers = null;
private String name; private String name;
private List<String> commands; private List<String> commands;
private channelTypes type; private channelTypes type;
private String channelTag, format, messageColour, permission, leavePermission, channelSound, listenPermission, speakPermission; private String channelTag, format, messageColour, permission, leavePermission, channelSound, listenPermission, speakPermission;
private HashMap<String, WorldFormat> worldFormatGroups = new HashMap<>(); private HashMap<String, WorldFormat> worldFormatGroups = new HashMap<>();
private double range; private double range;
private boolean hooked=false; private boolean hooked = false;
private boolean autojoin=true; private boolean autojoin = true;
private boolean focusable = true; private boolean focusable = true;
private double spamtime; private double spamtime;
private WeakHashMap<Player, Long> spammers = new WeakHashMap<>(); private WeakHashMap<Player, Long> spammers = new WeakHashMap<>();
protected ConcurrentMap<String, Integer> absentPlayers = null;
protected ConcurrentMap<String, Integer> mutedPlayers = null;
/** /**
* Constructor * Constructor
@@ -38,30 +38,42 @@ public abstract class Channel {
public Channel(String name) { public Channel(String name) {
this.name = name; this.name = name;
} }
/** /**
* @return the name * @return the name
*/ */
public String getName() { public String getName() {
return name; return name;
} }
/** /**
* @return the commands * @return the commands
*/ */
public List<String> getCommands() { public List<String> getCommands() {
return commands; return commands;
} }
/** /**
* @param commands the commands to set * @param commands the commands to set
*/ */
public void setCommands(List<String> commands) { public void setCommands(List<String> commands) {
this.commands = commands; this.commands = commands;
} }
/** /**
* @return the type * @return the type
*/ */
public channelTypes getType() { public channelTypes getType() {
return type; return type;
} }
/**
* @param type the type to set
*/
public void setType(channelTypes type) {
this.type = type;
}
/** /**
* @return the format * @return the format
*/ */
@@ -77,13 +89,6 @@ public abstract class Channel {
return ""; return "";
} }
/**
* @param type the type to set
*/
public void setType(channelTypes type) {
this.type = type;
}
/** /**
* @param format the format to set * @param format the format to set
*/ */
@@ -104,52 +109,60 @@ public abstract class Channel {
public String getChannelTag() { public String getChannelTag() {
return channelTag; return channelTag;
} }
/** /**
* @param channelTag the channelTag to set * @param channelTag the channelTag to set
*/ */
public void setChannelTag(String channelTag) { public void setChannelTag(String channelTag) {
this.channelTag = channelTag; this.channelTag = channelTag;
} }
/** /**
* @return the messageColour * @return the messageColour
*/ */
public String getMessageColour() { public String getMessageColour() {
return messageColour; return messageColour;
} }
/** /**
* @param messageColour the messageColour to set * @param messageColour the messageColour to set
*/ */
public void setMessageColour(String messageColour) { public void setMessageColour(String messageColour) {
this.messageColour = messageColour; this.messageColour = messageColour;
} }
/** /**
* @return the permission * @return the permission
*/ */
public String getPermission() { public String getPermission() {
return permission; return permission;
} }
/** /**
* @param permission the permission to set * @param permission the permission to set
*/ */
public void setPermission(String permission) { public void setPermission(String permission) {
this.permission = permission; this.permission = permission;
} }
/** /**
* @return the range * @return the range
*/ */
public double getRange() { public double getRange() {
return range; return range;
} }
/** /**
* @param range the range to set * @param range the range to set
*/ */
public void setRange(double range) { public void setRange(double range) {
this.range = range; this.range = range;
} }
/** /**
* @param event the event to process * @param event the event to process
*/ */
public abstract void chatProcess(AsyncPlayerChatEvent event); public abstract void chatProcess(AsyncChatEvent event);
/* /*
* Used to reset channel settings for a given player * Used to reset channel settings for a given player
@@ -169,7 +182,7 @@ public abstract class Channel {
*/ */
public boolean leave(Player player) { public boolean leave(Player player) {
if (absentPlayers == null) { if (absentPlayers == null) {
absentPlayers = new ConcurrentHashMap<String, Integer> (); absentPlayers = new ConcurrentHashMap<String, Integer>();
} }
Integer res = absentPlayers.put(player.getName(), 1); Integer res = absentPlayers.put(player.getName(), 1);
@@ -221,7 +234,7 @@ public abstract class Channel {
*/ */
public boolean mute(String name) { public boolean mute(String name) {
if (mutedPlayers == null) { if (mutedPlayers == null) {
mutedPlayers = new ConcurrentHashMap<String, Integer> (); mutedPlayers = new ConcurrentHashMap<String, Integer>();
} }
Integer i = mutedPlayers.get(name); Integer i = mutedPlayers.get(name);
if (i != null) return false; if (i != null) return false;
@@ -305,25 +318,17 @@ public abstract class Channel {
return mutedPlayers.keySet(); return mutedPlayers.keySet();
} }
public void setHooked(boolean hooked) {
this.hooked = hooked;
}
public boolean isHooked() { public boolean isHooked() {
return hooked; return hooked;
} }
/** public void setHooked(boolean hooked) {
* deprecated since 0.110, this setting has been unused for an unknown amount of time. this.hooked = hooked;
* @param autojoin
*/
@Deprecated
public void setAutoJoin(boolean autojoin) {
this.autojoin = autojoin;
} }
/** /**
* deprecated since 0.110, this setting has been unused for an unknown amount of time. * deprecated since 0.110, this setting has been unused for an unknown amount of time.
*
* @param autojoin * @param autojoin
*/ */
@Deprecated @Deprecated
@@ -331,12 +336,24 @@ public abstract class Channel {
return autojoin; return autojoin;
} }
/**
* deprecated since 0.110, this setting has been unused for an unknown amount of time.
*
* @param autojoin
*/
@Deprecated
public void setAutoJoin(boolean autojoin) {
this.autojoin = autojoin;
}
public boolean isFocusable() { public boolean isFocusable() {
return focusable; return focusable;
} }
public void setFocusable(boolean focusable) { public void setFocusable(boolean focusable) {
this.focusable = focusable; this.focusable = focusable;
} }
public double getSpam_time() { public double getSpam_time() {
return spamtime; return spamtime;
} }
@@ -371,10 +388,10 @@ public abstract class Channel {
spammers.remove(player); spammers.remove(player);
} else { } else {
// No record found so ensure we don't trigger for spam // No record found so ensure we don't trigger for spam
spam -= ((getSpam_time() + 1)*1000); spam -= ((getSpam_time() + 1) * 1000);
} }
if (timeNow - spam < (getSpam_time()*1000)) { if (timeNow - spam < (getSpam_time() * 1000)) {
spammers.put(player, spam); spammers.put(player, spam);
TownyMessaging.sendErrorMsg(player, Translatable.of("tc_err_unable_to_talk_you_are_spamming")); TownyMessaging.sendErrorMsg(player, Translatable.of("tc_err_unable_to_talk_you_are_spamming"));
return true; return true;
@@ -510,6 +527,7 @@ public abstract class Channel {
public boolean isGovernmentChannel() { public boolean isGovernmentChannel() {
return type.equals(channelTypes.TOWN) || type.equals(channelTypes.NATION) || type.equals(channelTypes.ALLIANCE); return type.equals(channelTypes.TOWN) || type.equals(channelTypes.NATION) || type.equals(channelTypes.ALLIANCE);
} }
public boolean hasPermission(Player player) { public boolean hasPermission(Player player) {
return getPermission() != null && TownyUniverse.getInstance().getPermissionSource().testPermission(player, getPermission()); return getPermission() != null && TownyUniverse.getInstance().getPermissionSource().testPermission(player, getPermission());
} }
@@ -550,6 +568,7 @@ public abstract class Channel {
/** /**
* Get the specific format this channel has for this world * Get the specific format this channel has for this world
*
* @return format * @return format
*/ */
public String getFormat() { public String getFormat() {
@@ -3,15 +3,10 @@ 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 {
@@ -19,9 +14,10 @@ public class ChannelsHolder {
private Chat plugin; private Chat plugin;
private Channel defaultChan = null; private Channel defaultChan = null;
// Container for all channels // Container for all channels
private Map<String,Channel> channels = new LinkedHashMap<>(); private Map<String, Channel> channels = new LinkedHashMap<>();
/** Constructor /**
* Constructor
* *
* @param plugin * @param plugin
*/ */
@@ -30,14 +26,14 @@ public class ChannelsHolder {
this.plugin = plugin; this.plugin = plugin;
} }
public void setDefaultChannel(Channel channel) {
defaultChan = channel;
}
public Channel getDefaultChannel() { public Channel getDefaultChannel() {
return defaultChan; return defaultChan;
} }
public void setDefaultChannel(Channel channel) {
defaultChan = channel;
}
/** /**
* @return the channels * @return the channels
*/ */
@@ -45,13 +41,6 @@ public class ChannelsHolder {
return channels; return channels;
} }
/**
* @param channels the channels to set
*/
public void setChannels(HashMap<String, Channel> channels) {
this.channels = channels;
}
@SuppressWarnings("unlikely-arg-type") @SuppressWarnings("unlikely-arg-type")
public void addChannel(Channel chan) { public void addChannel(Channel chan) {
if (isChannel(chan.getName())) if (isChannel(chan.getName()))
@@ -71,6 +60,14 @@ public class ChannelsHolder {
public Map<String, Channel> getChannels() { public Map<String, Channel> getChannels() {
return channels; 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. * Find a channel we are able to talk in, and have not left, starting with the greatest range.
* *
@@ -105,7 +102,7 @@ public class ChannelsHolder {
return getDefaultChannel(); return getDefaultChannel();
} }
for (Channel channel: channels.values()) { for (Channel channel : channels.values()) {
if (!channel.isPresent(name)) continue; if (!channel.isPresent(name)) continue;
if (!channel.getType().equals(type)) continue; if (!channel.getType().equals(type)) continue;
if (channel.hasSpeakPermission(player)) { if (channel.hasSpeakPermission(player)) {
@@ -144,9 +141,9 @@ public class ChannelsHolder {
Channel global = null; Channel global = null;
Channel world = null; Channel world = null;
for (Channel channel: channels.values()) { for (Channel channel : channels.values()) {
if (!channel.getType().equals(type)) continue; if (!channel.getType().equals(type)) continue;
if (channel.hasSpeakPermission(player)){ if (channel.hasSpeakPermission(player)) {
if (channel.getRange() == -1) { if (channel.getRange() == -1) {
global = channel; global = channel;
} else if (channel.getRange() == 0) { } else if (channel.getRange() == 0) {
@@ -177,7 +174,7 @@ public class ChannelsHolder {
Set<String> perms = new HashSet<String>(); Set<String> perms = new HashSet<String>();
for (Channel channel: channels.values()) { for (Channel channel : channels.values()) {
if (!perms.contains(channel.getPermission())) if (!perms.contains(channel.getPermission()))
perms.add(channel.getPermission()); perms.add(channel.getPermission());
if (channel.hasListenPermission() && !perms.contains(channel.getListenPermissionNode())) if (channel.hasListenPermission() && !perms.contains(channel.getListenPermissionNode()))
@@ -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,11 +26,7 @@ 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 {
@@ -46,7 +39,7 @@ public class StandardChannel extends Channel {
} }
@Override @Override
public void chatProcess(AsyncPlayerChatEvent event) { public void chatProcess(AsyncChatEvent event) {
channelTypes channelType = this.getType(); channelTypes channelType = this.getType();
Player player = event.getPlayer(); Player player = event.getPlayer();
@@ -97,24 +90,24 @@ public class StandardChannel extends Channel {
/* /*
* Set recipients for Bukkit to send this message to. * Set recipients for Bukkit to send this message to.
*/ */
event.getRecipients().clear(); event.viewers().clear();
event.getRecipients().addAll(recipients); event.viewers().addAll(recipients);
// If the server has marked this Channel as hooked, fire the AsyncChatHookEvent. // If the server has marked this Channel as hooked, fire the AsyncChatHookEvent.
// If the event is cancelled, cancel the chat entirely. // If the event is cancelled, cancel the chat entirely.
// Fires its own sendSpyMessage(). // Fires its own sendSpyMessage().
if (isHooked()) if (isHooked())
if (!sendOffHookedMessage(event, channelType)) { if (!sendOffHookedMessage(event, channelType, recipients)) {
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
// Send spy message if this was never hooked. // Send spy message if this was never hooked.
if (!isHooked()) if (!isHooked())
sendSpyMessage(event, channelType); sendSpyMessage(event, channelType, recipients);
// Play the channel sound, if used. // Play the channel sound, if used.
tryPlayChannelSound(event.getRecipients()); tryPlayChannelSound(recipients);
if (notifyjoin) if (notifyjoin)
TownyMessaging.sendMessage(player, "You join " + Colors.translateColorCodes(getMessageColour()) + getName()); TownyMessaging.sendMessage(player, "You join " + Colors.translateColorCodes(getMessageColour()) + getName());
@@ -140,7 +133,8 @@ public class StandardChannel extends Channel {
return switch (channelType) { return switch (channelType) {
case TOWN -> new HashSet<>(findRecipients(player, TownyAPI.getInstance().getOnlinePlayers(town))); case TOWN -> new HashSet<>(findRecipients(player, TownyAPI.getInstance().getOnlinePlayers(town)));
case NATION -> new HashSet<>(findRecipients(player, TownyAPI.getInstance().getOnlinePlayers(nation))); case NATION -> new HashSet<>(findRecipients(player, TownyAPI.getInstance().getOnlinePlayers(nation)));
case ALLIANCE -> new HashSet<>(findRecipients(player, TownyAPI.getInstance().getOnlinePlayersAlliance(nation))); case ALLIANCE ->
new HashSet<>(findRecipients(player, TownyAPI.getInstance().getOnlinePlayersAlliance(nation)));
case DEFAULT -> new HashSet<>(findRecipients(player, new ArrayList<>(recipients))); case DEFAULT -> new HashSet<>(findRecipients(player, new ArrayList<>(recipients)));
case GLOBAL, PRIVATE -> new HashSet<>(findRecipients(player, new ArrayList<>(recipients))); case GLOBAL, PRIVATE -> new HashSet<>(findRecipients(player, new ArrayList<>(recipients)));
}; };
@@ -157,7 +151,6 @@ public class StandardChannel extends Channel {
// Refresh the potential channels a player can see, if they are not currently in the channel. // Refresh the potential channels a player can see, if they are not currently in the channel.
playerList.stream().forEach(p -> refreshPlayer(this, p)); playerList.stream().forEach(p -> refreshPlayer(this, p));
return playerList.stream() return playerList.stream()
.filter(p -> hasListenPermission(p)) // Check permission.
.filter(p -> testDistance(sender, p, getRange())) // Within range. .filter(p -> testDistance(sender, p, getRange())) // Within range.
.filter(p -> !plugin.isIgnoredByEssentials(sender, p)) // Check essentials ignore. .filter(p -> !plugin.isIgnoredByEssentials(sender, p)) // Check essentials ignore.
.filter(p -> !isAbsent(p.getName())) // Check if player is purposefully absent. .filter(p -> !isAbsent(p.getName())) // Check if player is purposefully absent.
@@ -201,7 +194,7 @@ public class StandardChannel extends Channel {
TownyMessaging.sendMessage(sender, ChatSettings.getUsingAloneMessageString()); TownyMessaging.sendMessage(sender, ChatSettings.getUsingAloneMessageString());
} }
private void applyFormats(AsyncPlayerChatEvent event, String originalFormat, String workingFormat, Resident resident) { private void applyFormats(AsyncChatEvent event, String originalFormat, String workingFormat, Resident resident) {
List<TagResolver> tagResolvers = new ArrayList<>(); List<TagResolver> tagResolvers = new ArrayList<>();
// Parse out our own channelTag and msgcolour tags. // Parse out our own channelTag and msgcolour tags.
@@ -216,8 +209,8 @@ public class StandardChannel extends Channel {
// 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));
} }
@@ -269,12 +262,12 @@ public class StandardChannel extends Channel {
* 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;
@@ -282,13 +275,12 @@ public class StandardChannel extends Channel {
* 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;
} }
@@ -299,8 +291,7 @@ public class StandardChannel extends Channel {
* @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;
@@ -370,6 +361,7 @@ public class StandardChannel extends Channel {
/** /**
* Try to send a message to dynmap's web chat. * Try to send a message to dynmap's web chat.
*
* @param player Player which has spoken. * @param player Player which has spoken.
* @param message Message being spoken. * @param message Message being spoken.
*/ */
@@ -4,7 +4,6 @@ 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", "",
@@ -22,7 +21,7 @@ public enum ChannelsNodes {
"# 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.",
@@ -30,36 +29,36 @@ public enum ChannelsNodes {
"# ", "# ",
"# 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.",
@@ -67,7 +66,7 @@ public enum ChannelsNodes {
"# 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",
@@ -77,30 +76,30 @@ public enum ChannelsNodes {
"# -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,",
@@ -9,9 +9,9 @@ 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.*;
@@ -19,11 +19,10 @@ import java.util.*;
public class ChannelsSettings { public class ChannelsSettings {
private static final String CHANNELS_ROOT = "Channels"; private static final String CHANNELS_ROOT = "Channels";
private final static List<String> DEFAULT_CHANNELS = Arrays.asList("general", "town", "nation", "alliance", "admin", "mod", "local");
private static CommentedConfiguration channelConfig, newChannelConfig; private static CommentedConfiguration channelConfig, newChannelConfig;
private final static List<String> DEFAULT_CHANNELS = Arrays.asList("general","town","nation","alliance","admin","mod","local");
/** /**
*
* @return true if the channels.yml has loaded. * @return true if the channels.yml has loaded.
* @throws IOException * @throws IOException
*/ */
@@ -106,7 +105,7 @@ public class ChannelsSettings {
} }
} }
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()));
} }
@@ -227,7 +226,7 @@ public class ChannelsSettings {
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);
@@ -295,7 +294,7 @@ public class ChannelsSettings {
} }
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;
@@ -151,7 +151,6 @@ public enum ChatConfigNodes {
"# 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 Root;
private final String Default; private final String Default;
private String[] comments; private String[] 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;
@@ -18,7 +15,6 @@ public class ChatSettings {
private static CommentedConfiguration chatConfig, newChatConfig; private static CommentedConfiguration chatConfig, newChatConfig;
/** /**
*
* @return true if the chatconfig has loaded. * @return true if the chatconfig has loaded.
* @throws IOException * @throws IOException
*/ */
@@ -2,13 +2,13 @@ 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 io.papermc.paper.event.player.AsyncChatEvent;
import net.kyori.adventure.audience.Audience; import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.Component;
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;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import java.util.HashSet;
import java.util.Set; import java.util.Set;
/* /*
@@ -30,21 +30,25 @@ import java.util.Set;
*/ */
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 static HandlerList getHandlerList() {
return handlers;
}
public Channel getChannel() { public Channel getChannel() {
return channel; return channel;
} }
@@ -63,34 +67,37 @@ public class AsyncChatHookEvent extends Event {
this.changed = changed; this.changed = changed;
} }
public AsyncPlayerChatEvent getAsyncPlayerChatEvent() { public AsyncChatEvent getAsyncPlayerChatEvent() {
return event; return event;
} }
public String getFormat() { public String getFormat() {
return event.getFormat(); return "";
}
public void setFormat(String format) {
} }
public String getMessage() { public String getMessage() {
return event.getMessage(); return "";
}
public void setMessage(String message) {
}
public void setMessage(Component message) {
changed = true;
event.message(message);
}
public Component message() {
return event.message();
} }
public Set<Player> getRecipients() { public Set<Player> getRecipients() {
return this.recipients; return this.recipients;
} }
public Audience getAudience() {
return this.audience;
}
public boolean isCancelled() {
return event.isCancelled();
}
public Player getPlayer() {
return event.getPlayer();
}
public void setRecipients(Set<Player> recipients) { public void setRecipients(Set<Player> recipients) {
changed = true; changed = true;
this.recipients.clear(); this.recipients.clear();
@@ -98,19 +105,17 @@ public class AsyncChatHookEvent extends Event {
setAudience(Audience.audience(this.recipients.stream().map(player -> Chat.getTownyChat().adventure().player(player)).toArray(Audience[]::new))); // Update audience as well setAudience(Audience.audience(this.recipients.stream().map(player -> Chat.getTownyChat().adventure().player(player)).toArray(Audience[]::new))); // Update audience as well
} }
public Audience getAudience() {
return this.audience;
}
public void setAudience(Audience audience) { public void setAudience(Audience audience) {
changed = true; changed = true;
this.audience = audience; this.audience = audience;
} }
public void setFormat(String format) { public boolean isCancelled() {
changed = true; return event.isCancelled();
event.setFormat(format);
}
public void setMessage(String message) {
changed = true;
event.setMessage(message);
} }
public void setCancelled(boolean cancel) { public void setCancelled(boolean cancel) {
@@ -118,12 +123,12 @@ public class AsyncChatHookEvent extends Event {
event.setCancelled(cancel); event.setCancelled(cancel);
} }
public Player getPlayer() {
return event.getPlayer();
}
@Override @Override
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
} }
public static HandlerList getHandlerList() {
return handlers;
}
} }
@@ -1,7 +1,6 @@
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;
@@ -23,11 +22,11 @@ public class PlayerJoinChatChannelEvent extends Event {
this.channel = channel; this.channel = channel;
} }
public HandlerList getHandlers() { public static HandlerList getHandlerList() {
return HANDLERS; return HANDLERS;
} }
public static HandlerList getHandlerList() { public HandlerList getHandlers() {
return HANDLERS; return HANDLERS;
} }
@@ -1,20 +1,22 @@
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) { public LocalTownyChatEvent(AsyncChatEvent event, Resident resident) {
this.event = event; this.event = event;
this.resident = resident; this.resident = resident;
} }
/** /**
* Get the resident associated with the chat event's talking player. * Get the resident associated with the chat event's talking player.
*
* @return resident associated with the chat event's talking player * @return resident associated with the chat event's talking player
*/ */
public Resident getResident() { public Resident getResident() {
@@ -22,35 +24,41 @@ public class LocalTownyChatEvent {
} }
/** /**
* * @return the AsyncChatEvent
* @return the PlayerChatEvent
*/ */
public AsyncPlayerChatEvent getEvent() { public AsyncChatEvent getEvent() {
return event; return event;
} }
/**
* Convenience method for setting the chat event's format.
* @param format
*/
public void setFormat(String format) {
event.setFormat(format);
}
/** /**
* Convenience method for getting the chat event's format * Convenience method for getting the chat event's format
*
* @return the chat event's format * @return the chat event's format
*/ */
@Deprecated
public String getFormat() { public String getFormat() {
return event.getFormat(); return "";
}
/**
* Convenience method for setting the chat event's format.
*
* @param format
*/
@Deprecated
public void setFormat(String format) {
} }
/** /**
* Convenience method for getting the chat event's message * Convenience method for getting the chat event's message
*
* @return the chat event's message * @return the chat event's message
*/ */
public String getMessage() { public String getMessage() {
return event.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,12 +29,10 @@ 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<>(); public WeakHashMap<Player, String> directedChat = new WeakHashMap<>();
private Chat plugin;
public TownyChatPlayerListener(Chat instance) { public TownyChatPlayerListener(Chat instance) {
this.plugin = instance; this.plugin = instance;
@@ -72,9 +68,10 @@ public class TownyChatPlayerListener implements Listener {
} }
@EventHandler @EventHandler
public void onPlayerChat(AsyncPlayerChatEvent event) { public void onPlayerChat(AsyncChatEvent event) {
Player player = event.getPlayer(); Player player = event.getPlayer();
// TODO START HERE ROOOOOSE :))) This is where the logic "begins"
// Check if the message contains colour codes we need to remove or parse. // Check if the message contains colour codes we need to remove or parse.
testColourCodes(event, player); testColourCodes(event, player);
@@ -168,8 +165,9 @@ public class TownyChatPlayerListener implements Listener {
// 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));
} }
} }
@@ -178,10 +176,10 @@ public class TownyChatPlayerListener implements Listener {
* 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", ""));
@@ -203,7 +201,7 @@ public class TownyChatPlayerListener implements Listener {
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"))
@@ -227,14 +225,14 @@ public class TownyChatPlayerListener implements Listener {
/** /**
* 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);
@@ -1,7 +1,6 @@
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;
/* /*
@@ -1,8 +1,7 @@
package com.palmergames.bukkit.TownyChat.util; package com.palmergames.bukkit.TownyChat.util;
import org.bukkit.entity.Player;
import com.palmergames.bukkit.TownyChat.Chat; import com.palmergames.bukkit.TownyChat.Chat;
import org.bukkit.entity.Player;
public class EssentialsIntegration { public class EssentialsIntegration {
@@ -1,21 +1,21 @@
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