Merge pull request #2 from darksaid98/feat/adventure

This commit is contained in:
darksaid98 authored and GitHub committed 2025-09-28 03:17:58 +02:00
commit e16bbe0c7f
28 files changed
+3700 -3827

No files matched your search

+218 -165
View File
@@ -1,166 +1,219 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" <project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.palmergames.bukkit</groupId> <groupId>com.palmergames.bukkit</groupId>
<artifactId>TownyChat</artifactId> <artifactId>TownyChat</artifactId>
<packaging>jar</packaging> <packaging>jar</packaging>
<version>0.115</version> <version>0.115</version>
<licenses> <licenses>
<license> <license>
<name>CC BY-NC-ND 3.0</name> <name>CC BY-NC-ND 3.0</name>
<url>http://creativecommons.org/licenses/by-nc-nd/3.0/</url> <url>http://creativecommons.org/licenses/by-nc-nd/3.0/</url>
<comments>Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported</comments> <comments>Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported</comments>
</license> </license>
</licenses> </licenses>
<organization> <organization>
<name>TownyAdvanced</name> <name>TownyAdvanced</name>
<url>https://github.com/TownyAdvanced</url> <url>https://github.com/TownyAdvanced</url>
</organization> </organization>
<properties> <properties>
<java.version>17</java.version> <java.version>17</java.version>
<project.bukkitAPIVersion>1.16</project.bukkitAPIVersion> <project.bukkitAPIVersion>1.16</project.bukkitAPIVersion>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<towny.version>0.100.0.0</towny.version> <towny.version>0.100.0.0</towny.version>
</properties> </properties>
<!-- For use with GitHub Package Registry --> <!-- For use with GitHub Package Registry -->
<distributionManagement> <distributionManagement>
<repository> <repository>
<id>github</id> <id>github</id>
<name>GitHub TownyAdvanced Apache Maven Packages</name> <name>GitHub TownyAdvanced Apache Maven Packages</name>
<url>https://maven.pkg.github.com/TownyAdvanced</url> <url>https://maven.pkg.github.com/TownyAdvanced</url>
</repository> </repository>
</distributionManagement> </distributionManagement>
<scm> <scm>
<connection>scm:git:https://github.com/TownyAdvanced/TownyChat.git</connection> <connection>scm:git:https://github.com/TownyAdvanced/TownyChat.git</connection>
<developerConnection>scm:git:https://github.com/TownyAdvanced/TownyChat.git</developerConnection> <developerConnection>scm:git:https://github.com/TownyAdvanced/TownyChat.git</developerConnection>
<url>https://github.com/TownyAdvanced/TownyChat</url> <url>https://github.com/TownyAdvanced/TownyChat</url>
</scm> </scm>
<repositories> <repositories>
<repository> <repository>
<id>spigot-repo</id> <id>spigot-repo</id>
<url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url> <url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
</repository> </repository>
<repository> <repository>
<id>papermc</id> <id>papermc</id>
<url>https://repo.papermc.io/repository/maven-public/</url> <url>https://repo.papermc.io/repository/maven-public/</url>
</repository> </repository>
<repository> <repository>
<id>essentials-releases</id> <id>essentials-releases</id>
<url>https://repo.essentialsx.net/releases/</url> <url>https://repo.essentialsx.net/releases/</url>
</repository> </repository>
<repository> <repository>
<id>dynmap-repo</id> <id>dynmap-repo</id>
<url>https://repo.mikeprimm.com</url> <url>https://repo.mikeprimm.com</url>
</repository> </repository>
<repository> <repository>
<id>glaremasters repo</id> <id>glaremasters repo</id>
<url>https://repo.glaremasters.me/repository/towny/</url> <url>https://repo.glaremasters.me/repository/towny/</url>
</repository> </repository>
<repository> <repository>
<id>placeholderapi</id> <id>placeholderapi</id>
<url>https://repo.extendedclip.com/content/repositories/placeholderapi/</url> <url>https://repo.extendedclip.com/content/repositories/placeholderapi/</url>
</repository> </repository>
<repository> <repository>
<id>jitpack.io</id> <id>milkdrinkers-releases</id>
<url>https://jitpack.io</url> <name>Milkdrinkers Maven Repository</name>
</repository> <url>https://maven.athyrium.eu/releases</url>
</repositories> </repository>
<repository>
<dependencies> <id>jitpack.io</id>
<dependency> <url>https://jitpack.io</url>
<groupId>com.palmergames.bukkit.towny</groupId> </repository>
<artifactId>towny</artifactId> </repositories>
<version>${towny.version}</version>
<scope>provided</scope> <dependencies>
</dependency> <dependency>
<dependency> <groupId>com.palmergames.bukkit.towny</groupId>
<groupId>org.spigotmc</groupId> <artifactId>towny</artifactId>
<artifactId>spigot-api</artifactId> <version>${towny.version}</version>
<version>1.20.2-R0.1-SNAPSHOT</version> <scope>provided</scope>
<scope>provided</scope> </dependency>
</dependency> <dependency>
<dependency> <groupId>io.papermc.paper</groupId>
<groupId>net.essentialsx</groupId> <artifactId>paper-api</artifactId>
<artifactId>EssentialsX</artifactId> <version>1.20.4-R0.1-SNAPSHOT</version>
<version>2.19.0</version> <scope>provided</scope>
<scope>provided</scope> </dependency>
<exclusions> <dependency>
<exclusion> <groupId>com.github.milkdrinkers</groupId>
<groupId>org.bstats</groupId> <artifactId>colorparser</artifactId>
<artifactId>bstats-bukkit</artifactId> <version>2.0.3</version>
</exclusion> </dependency>
</exclusions> <dependency>
</dependency> <groupId>net.essentialsx</groupId>
<dependency> <artifactId>EssentialsX</artifactId>
<groupId>us.dynmap</groupId> <version>2.19.0</version>
<artifactId>dynmap-api</artifactId> <scope>provided</scope>
<version>3.0-SNAPSHOT</version> <exclusions>
<scope>provided</scope> <exclusion>
</dependency> <groupId>org.bstats</groupId>
<dependency> <artifactId>bstats-bukkit</artifactId>
<groupId>me.clip</groupId> </exclusion>
<artifactId>placeholderapi</artifactId> </exclusions>
<version>2.11.5</version> </dependency>
<scope>provided</scope> <dependency>
</dependency> <groupId>us.dynmap</groupId>
<dependency> <artifactId>dynmap-api</artifactId>
<groupId>com.github.EssentialsX.Essentials</groupId> <version>3.0-SNAPSHOT</version>
<artifactId>EssentialsXDiscord</artifactId> <scope>provided</scope>
<version>57600f333c</version> </dependency>
<scope>provided</scope> <dependency>
<exclusions> <groupId>me.clip</groupId>
<exclusion> <artifactId>placeholderapi</artifactId>
<groupId>net.dv8tion</groupId> <version>2.11.6</version>
<artifactId>JDA</artifactId> <scope>provided</scope>
</exclusion> </dependency>
</exclusions> <dependency>
</dependency> <groupId>com.github.EssentialsX.Essentials</groupId>
<dependency> <artifactId>EssentialsXDiscord</artifactId>
<groupId>org.jetbrains</groupId> <version>57600f333c</version>
<artifactId>annotations</artifactId> <scope>provided</scope>
<version>16.0.2</version> <exclusions>
</dependency> <exclusion>
<dependency> <groupId>net.dv8tion</groupId>
<groupId>com.github.bsideup.jabel</groupId> <artifactId>JDA</artifactId>
<artifactId>jabel-javac-plugin</artifactId> </exclusion>
<version>1.0.0</version> </exclusions>
<scope>provided</scope> </dependency>
</dependency> <dependency>
</dependencies> <groupId>org.jetbrains</groupId>
<artifactId>annotations</artifactId>
<build> <version>24.1.0</version>
<defaultGoal>clean package</defaultGoal> </dependency>
<plugins> <dependency>
<plugin> <groupId>net.kyori</groupId>
<groupId>org.apache.maven.plugins</groupId> <artifactId>adventure-api</artifactId>
<artifactId>maven-compiler-plugin</artifactId> <version>4.17.0</version>
<version>3.11.0</version> </dependency>
<configuration> <dependency>
<release>8</release> <groupId>net.kyori</groupId>
<source>${java.version}</source> <artifactId>adventure-text-minimessage</artifactId>
<target>${java.version}</target> <version>4.17.0</version>
<compilerArgs> </dependency>
<arg>-Xplugin:jabel</arg> <dependency>
</compilerArgs> <groupId>net.kyori</groupId>
</configuration> <artifactId>adventure-text-serializer-legacy</artifactId>
</plugin> <version>4.17.0</version>
</plugins> </dependency>
</dependencies>
<sourceDirectory>src</sourceDirectory>
<resources> <build>
<resource> <defaultGoal>clean package</defaultGoal>
<directory>resources</directory> <plugins>
<filtering>true</filtering> <plugin>
</resource> <groupId>org.apache.maven.plugins</groupId>
</resources> <artifactId>maven-shade-plugin</artifactId>
</build> <version>3.5.1</version>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
<minimizeJar>true</minimizeJar>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.MF</exclude>
<exclude>META-INF/**/*.xml</exclude>
<exclude>META-INF/**/*.properties</exclude>
</excludes>
</filter>
</filters>
<relocations>
<relocation>
<pattern>com.github.milkdrinkers.colorparser</pattern>
<shadedPattern>${project.groupId}.${project.artifactId}.libs.colorparser</shadedPattern>
</relocation>
<relocation>
<pattern>org.jetbrains</pattern>
<shadedPattern>${project.groupId}.${project.artifactId}.libs.jetbrains</shadedPattern>
</relocation>
</relocations>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.12.1</version>
<configuration>
<source>17</source>
<target>17</target>
<release>17</release>
</configuration>
</plugin>
</plugins>
<sourceDirectory>src</sourceDirectory>
<resources>
<resource>
<directory>resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project> </project>
+317 -309
View File
@@ -1,310 +1,318 @@
package com.palmergames.bukkit.TownyChat; package com.palmergames.bukkit.TownyChat;
import com.earth2me.essentials.Essentials; import com.earth2me.essentials.Essentials;
import com.palmergames.bukkit.TownyChat.Command.ChannelCommand; import com.palmergames.adventure.platform.bukkit.BukkitAudiences;
import com.palmergames.bukkit.TownyChat.Command.TownyChatCommand; import com.palmergames.bukkit.TownyChat.Command.ChannelCommand;
import com.palmergames.bukkit.TownyChat.Command.commandobjects.ChannelJoinAliasCommand; import com.palmergames.bukkit.TownyChat.Command.TownyChatCommand;
import com.palmergames.bukkit.TownyChat.channels.Channel; import com.palmergames.bukkit.TownyChat.Command.commandobjects.ChannelJoinAliasCommand;
import com.palmergames.bukkit.TownyChat.channels.ChannelsHolder; import com.palmergames.bukkit.TownyChat.channels.Channel;
import com.palmergames.bukkit.TownyChat.config.ChatSettings; import com.palmergames.bukkit.TownyChat.channels.ChannelsHolder;
import com.palmergames.bukkit.TownyChat.config.ChannelsSettings; import com.palmergames.bukkit.TownyChat.config.ChannelsSettings;
import com.palmergames.bukkit.TownyChat.listener.EssentialsDiscordHookListener; import com.palmergames.bukkit.TownyChat.config.ChatSettings;
import com.palmergames.bukkit.TownyChat.listener.TownyChatPlayerListener; import com.palmergames.bukkit.TownyChat.listener.EssentialsDiscordHookListener;
import com.palmergames.bukkit.TownyChat.tasks.onLoadedTask; import com.palmergames.bukkit.TownyChat.listener.TownyChatPlayerListener;
import com.palmergames.bukkit.TownyChat.util.EssentialsIntegration; import com.palmergames.bukkit.TownyChat.tasks.onLoadedTask;
import com.palmergames.bukkit.towny.Towny; import com.palmergames.bukkit.TownyChat.util.EssentialsIntegration;
import com.palmergames.bukkit.towny.scheduling.TaskScheduler; import com.palmergames.bukkit.towny.Towny;
import com.palmergames.bukkit.towny.scheduling.impl.BukkitTaskScheduler; import com.palmergames.bukkit.towny.scheduling.TaskScheduler;
import com.palmergames.bukkit.towny.scheduling.impl.FoliaTaskScheduler; import com.palmergames.bukkit.towny.scheduling.impl.BukkitTaskScheduler;
import com.palmergames.util.FileMgmt; import com.palmergames.bukkit.towny.scheduling.impl.FoliaTaskScheduler;
import com.palmergames.util.JavaUtil; import com.palmergames.util.FileMgmt;
import com.palmergames.util.JavaUtil;
import org.bukkit.Bukkit; import net.kyori.adventure.text.minimessage.MiniMessage;
import org.bukkit.command.Command; import org.bukkit.Bukkit;
import org.bukkit.command.CommandMap; import org.bukkit.command.Command;
import org.bukkit.entity.Player; import org.bukkit.command.CommandMap;
import org.bukkit.permissions.Permission; import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin; import org.bukkit.permissions.Permission;
import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.PluginManager;
import org.dynmap.DynmapAPI; import org.bukkit.plugin.java.JavaPlugin;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.io.File; import org.dynmap.DynmapAPI;
import java.lang.reflect.Field; import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.HashMap; import java.io.File;
import java.util.List; import java.lang.reflect.Field;
import java.util.UUID; import java.util.ArrayList;
import java.util.concurrent.ConcurrentHashMap; import java.util.HashMap;
import java.util.concurrent.ConcurrentMap; import java.util.List;
import java.util.UUID;
/** import java.util.concurrent.ConcurrentHashMap;
* Chat plugin to manage all Towny chat import java.util.concurrent.ConcurrentMap;
*
* Website: http://code.google.com/a/eclipselabs.org/p/towny/ /**
* * Chat plugin to manage all Towny chat
* @author ElgarL * <p>
*/ * Website: http://code.google.com/a/eclipselabs.org/p/towny/
*
public class Chat extends JavaPlugin { * @author ElgarL
*/
private TownyChatPlayerListener TownyPlayerListener;
private ChannelsHolder channels; public class Chat extends JavaPlugin {
protected PluginManager pm; public static boolean usingPlaceholderAPI = false;
private static Chat chat = null; public static boolean usingEssentialsDiscord = false;
private final Object scheduler; private static Chat chat = null;
private Towny towny = null; private static String requiredTownyVersion = "0.98.0.0";
private DynmapAPI dynMap = null; private static ConcurrentMap<UUID, Channel> playerChannelMap;
private Essentials essentials = null; private final Object scheduler;
protected PluginManager pm;
private static String requiredTownyVersion = "0.100.0.0"; boolean chatConfigError = false;
public static boolean usingPlaceholderAPI = false; boolean channelsConfigError = false;
public static boolean usingEssentialsDiscord = false; private TownyChatPlayerListener TownyPlayerListener;
boolean chatConfigError = false; private ChannelsHolder channels;
boolean channelsConfigError = false; private Towny towny = null;
private static ConcurrentMap<UUID, Channel> playerChannelMap; private DynmapAPI dynMap = null;
private Essentials essentials = null;
public Chat() { private BukkitAudiences adventure = null;
chat = this;
this.scheduler = townyVersionCheck() ? isFoliaClassPresent() ? new FoliaTaskScheduler(this) : new BukkitTaskScheduler(this) : null; public Chat() {
} chat = this;
this.scheduler = townyVersionCheck() ? isFoliaClassPresent() ? new FoliaTaskScheduler(this) : new BukkitTaskScheduler(this) : null;
@Override }
public void onEnable() {
pm = getServer().getPluginManager(); public static Chat getTownyChat() {
channels = new ChannelsHolder(this); return chat;
playerChannelMap = new ConcurrentHashMap<>(); }
checkPlugins(); private static boolean isFoliaClassPresent() {
if (towny == null || !townyVersionCheck()) { try {
disableWithMessage("Towny version does not meet required minimum version: " + requiredTownyVersion.toString()); Class.forName("io.papermc.paper.threadedregions.RegionizedServer");
return; return true;
} else { } catch (ClassNotFoundException e) {
getLogger().info("Towny version " + towny.getDescription().getVersion() + " found."); return false;
} }
}
loadConfigs();
if (channelsConfigError || chatConfigError) { @Override
disableWithMessage("The config could not be loaded."); public void onEnable() {
return; pm = getServer().getPluginManager();
} channels = new ChannelsHolder(this);
playerChannelMap = new ConcurrentHashMap<>();
/* adventure = BukkitAudiences.create(this);
* 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. checkPlugins();
*/ if (towny == null || !townyVersionCheck()) {
getScheduler().run(new onLoadedTask(this)); disableWithMessage("Towny version does not meet required minimum version: " + requiredTownyVersion.toString());
return;
getCommand("townychat").setExecutor(new TownyChatCommand(this)); } else {
getCommand("channel").setExecutor(new ChannelCommand(this)); getLogger().info("Towny version " + towny.getDescription().getVersion() + " found.");
registerObjectCommands(); }
}
loadConfigs();
private void disableWithMessage(String message) { if (channelsConfigError || chatConfigError) {
getLogger().severe(message); disableWithMessage("The config could not be loaded.");
getLogger().severe("Disabling TownyChat..."); return;
pm.disablePlugin(this); }
}
/*
private boolean townyVersionCheck() { * This executes the task with a 1 tick delay avoiding the bukkit depends bug.
try { * TODO: What bug is this referencing? This goes back to the first version of TownyChat.
return Towny.isTownyVersionSupported(requiredTownyVersion); */
} catch (NoSuchMethodError e) { getScheduler().run(new onLoadedTask(this));
return false;
} getCommand("townychat").setExecutor(new TownyChatCommand(this));
} getCommand("channel").setExecutor(new ChannelCommand(this));
registerObjectCommands();
private void loadConfigs() { }
FileMgmt.checkOrCreateFolders(new String[] { getRootPath(), getTownySettingsPath() });
chatConfigError = !ChatSettings.loadCommentedChatConfig(); private void disableWithMessage(String message) {
channelsConfigError = !ChannelsSettings.loadCommentedChannelsConfig(); getLogger().severe(message);
} getLogger().severe("Disabling TownyChat...");
pm.disablePlugin(this);
public static Chat getTownyChat() { }
return chat;
} private boolean townyVersionCheck() {
try {
@Override return Towny.isTownyVersionSupported(requiredTownyVersion);
public void onDisable() { } catch (NoSuchMethodError e) {
unregisterPermissions(); return false;
// reset any handles }
}
dynMap = null;
towny = null; private void loadConfigs() {
pm = null; FileMgmt.checkOrCreateFolders(new String[]{getRootPath(), getTownySettingsPath()});
chatConfigError = !ChatSettings.loadCommentedChatConfig();
channels = null; channelsConfigError = !ChannelsSettings.loadCommentedChannelsConfig();
playerChannelMap = null; }
}
public @NonNull BukkitAudiences adventure() {
/** if (this.adventure == null) {
* Perform a reload of this plugin. throw new IllegalStateException("Tried to access Adventure when the plugin was disabled!");
*/ }
public void reload() { return this.adventure;
onDisable(); }
onEnable();
} @Override
public void onDisable() {
/** unregisterPermissions();
* Attempt to hook any plugins we want to access. // reset any handles
*/
private void checkPlugins() { if (adventure != null) {
Plugin test; adventure.close();
adventure = null;
test = pm.getPlugin("Towny"); }
if (test != null && test instanceof Towny) dynMap = null;
towny = (Towny) test; towny = null;
pm = null;
test = pm.getPlugin("dynmap");
if (test != null && pm.getPlugin("dynmap").isEnabled()) { channels = null;
dynMap = (DynmapAPI) test; playerChannelMap = null;
} }
test = pm.getPlugin("PlaceholderAPI"); /**
if (test != null) { * Perform a reload of this plugin.
usingPlaceholderAPI = true; */
} public void reload() {
onDisable();
test = pm.getPlugin("EssentialsDiscord"); onEnable();
if (test != null) { }
usingEssentialsDiscord = true;
} /**
* Attempt to hook any plugins we want to access.
test = pm.getPlugin("Essentials"); */
if (test != null && JavaUtil.classExists("com.earth2me.essentials.Essentials")) { private void checkPlugins() {
this.essentials = (Essentials) test; Plugin test;
}
test = pm.getPlugin("Towny");
} if (test instanceof Towny)
towny = (Towny) test;
public void registerEvents() {
test = pm.getPlugin("dynmap");
if (TownyPlayerListener == null) { if (test != null && pm.getPlugin("dynmap").isEnabled()) {
TownyPlayerListener = new TownyChatPlayerListener(this); dynMap = (DynmapAPI) test;
}
if (TownyPlayerListener != null)
pm.registerEvents(TownyPlayerListener, this); test = pm.getPlugin("PlaceholderAPI");
} if (test != null) {
usingPlaceholderAPI = true;
if (usingEssentialsDiscord) { }
pm.registerEvents(new EssentialsDiscordHookListener(this), this);
} test = pm.getPlugin("EssentialsDiscord");
} if (test != null) {
usingEssentialsDiscord = true;
public void registerPermissions() { }
// Register all Permissions.
for (String perm : getChannelsHandler().getAllPermissions()) { test = pm.getPlugin("Essentials");
try { if (test != null && JavaUtil.classExists("com.earth2me.essentials.Essentials")) {
pm.addPermission(new Permission(perm, new HashMap<String, Boolean>())); this.essentials = (Essentials) test;
} catch (IllegalArgumentException e) { }
//permission already registered.
} }
}
} public void registerEvents() {
if (TownyPlayerListener == null) {
public void unregisterPermissions() { TownyPlayerListener = new TownyChatPlayerListener(this);
// Register all Permissions. pm.registerEvents(TownyPlayerListener, this);
for (String perm : getChannelsHandler().getAllPermissions()) { }
pm.removePermission(new Permission(perm, new HashMap<String, Boolean>()));
} if (usingEssentialsDiscord) {
} pm.registerEvents(new EssentialsDiscordHookListener(this), this);
}
}
public String getRootPath() {
return getTowny().getDataFolder().getPath(); public void registerPermissions() {
} // Register all Permissions.
for (String perm : getChannelsHandler().getAllPermissions()) {
public String getTownySettingsPath() { try {
return getRootPath() + File.separator + "settings"; pm.addPermission(new Permission(perm, new HashMap<String, Boolean>()));
} } catch (IllegalArgumentException e) {
//permission already registered.
public String getChatConfigPath() { }
return getTownySettingsPath() + File.separator + "ChatConfig.yml"; }
} }
public String getChannelsConfigPath() { public void unregisterPermissions() {
return getTownySettingsPath() + File.separator + "Channels.yml"; // Register all Permissions.
} for (String perm : getChannelsHandler().getAllPermissions()) {
pm.removePermission(new Permission(perm, new HashMap<String, Boolean>()));
/** }
* @return the channels }
*/
public ChannelsHolder getChannelsHandler() { public String getRootPath() {
return channels; return getTowny().getDataFolder().getPath();
} }
public Towny getTowny() { public String getTownySettingsPath() {
return towny; return getRootPath() + File.separator + "settings";
} }
public DynmapAPI getDynmap() { public String getChatConfigPath() {
return dynMap; return getTownySettingsPath() + File.separator + "ChatConfig.yml";
} }
public boolean isUsingEssentials() { public String getChannelsConfigPath() {
return essentials != null; return getTownySettingsPath() + File.separator + "Channels.yml";
} }
public Essentials getEssentials() { /**
return essentials; * @return the channels
} */
public ChannelsHolder getChannelsHandler() {
public boolean isEssentialsMuted(Player player) { return channels;
if (!isUsingEssentials()) }
return false;
return EssentialsIntegration.isMuted(player); public Towny getTowny() {
} return towny;
}
public boolean isIgnoredByEssentials(Player sender, Player player) {
if (!isUsingEssentials()) public DynmapAPI getDynmap() {
return false; return dynMap;
return EssentialsIntegration.ignoredByEssentials(sender, player); }
}
public boolean isUsingEssentials() {
private void registerObjectCommands() { return essentials != null;
List<Command> commands = new ArrayList<Command>(); }
for (Channel channel : channels.getAllChannels().values()) { // All channels
for (String cmd : channel.getCommands()) { // All Commands of All Channels public Essentials getEssentials() {
commands.add(new ChannelJoinAliasCommand(cmd, channel, this)); return essentials;
} }
}
try { public boolean isEssentialsMuted(Player player) {
final Field bukkitCommandMap = Bukkit.getServer().getClass().getDeclaredField("commandMap"); if (!isUsingEssentials())
return false;
bukkitCommandMap.setAccessible(true); return EssentialsIntegration.isMuted(player);
CommandMap commandMap = (CommandMap) bukkitCommandMap.get(Bukkit.getServer()); }
commandMap.registerAll("TownyChat", commands); public boolean isIgnoredByEssentials(Player sender, Player player) {
} catch (NoSuchFieldException e) { if (!isUsingEssentials())
e.printStackTrace(); return false;
} catch (IllegalAccessException e) { return EssentialsIntegration.ignoredByEssentials(sender, player);
e.printStackTrace(); }
}
} private void registerObjectCommands() {
List<Command> commands = new ArrayList<Command>();
public TownyChatPlayerListener getTownyPlayerListener() { for (Channel channel : channels.getAllChannels().values()) { // All channels
return TownyPlayerListener; for (String cmd : channel.getCommands()) { // All Commands of All Channels
} commands.add(new ChannelJoinAliasCommand(cmd, channel, this));
}
public Channel getPlayerChannel(Player player) { }
return playerChannelMap.get(player.getUniqueId()); try {
} final Field bukkitCommandMap = Bukkit.getServer().getClass().getDeclaredField("commandMap");
public void setPlayerChannel(Player player, Channel channel) { bukkitCommandMap.setAccessible(true);
playerChannelMap.put(player.getUniqueId(), channel); CommandMap commandMap = (CommandMap) bukkitCommandMap.get(Bukkit.getServer());
}
commandMap.registerAll("TownyChat", commands);
public TaskScheduler getScheduler() { } catch (NoSuchFieldException | IllegalAccessException e) {
return (TaskScheduler) this.scheduler; e.printStackTrace();
} }
}
private static boolean isFoliaClassPresent() {
try { public TownyChatPlayerListener getTownyPlayerListener() {
Class.forName("io.papermc.paper.threadedregions.RegionizedServer"); return TownyPlayerListener;
return true; }
} catch (ClassNotFoundException e) {
return false; 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;
}
} }
@@ -2,18 +2,17 @@ package com.palmergames.bukkit.TownyChat.Command;
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 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; }
} }
} }
}
@@ -1,217 +0,0 @@
package com.palmergames.bukkit.TownyChat;
import org.bukkit.entity.Player;
import com.palmergames.bukkit.TownyChat.config.ChatSettings;
import com.palmergames.bukkit.TownyChat.listener.LocalTownyChatEvent;
import com.palmergames.bukkit.TownyChat.util.StringReplaceManager;
import com.palmergames.bukkit.towny.TownyAPI;
import com.palmergames.bukkit.towny.TownySettings;
import com.palmergames.bukkit.towny.object.Government;
import com.palmergames.bukkit.towny.object.Nation;
import com.palmergames.bukkit.towny.object.Resident;
import com.palmergames.bukkit.towny.object.Town;
import com.palmergames.bukkit.util.Colors;
import com.palmergames.util.StringMgmt;
import com.palmergames.bukkit.towny.TownyUniverse;
public class TownyChatFormatter {
private static StringReplaceManager<LocalTownyChatEvent> replacer = new StringReplaceManager<LocalTownyChatEvent>();
static {
replacer.registerReplacer("{worldname}", event -> getWorldTag(event));
replacer.registerReplacer("{town}", event -> getTownName(event.getResident()));
replacer.registerReplacer("{townformatted}", event -> formatTownTag(event.getResident(), false, true));
replacer.registerReplacer("{towntag}", event -> formatTownTag(event.getResident(), false, false));
replacer.registerReplacer("{towntagoverride}", event -> formatTownTag(event.getResident(), true, false));
replacer.registerReplacer("{nation}", event -> getNationName(event.getResident()));
replacer.registerReplacer("{nationformatted}", event -> formatNationTag(event.getResident(), false, true));
replacer.registerReplacer("{nationtag}", event -> formatNationTag(event.getResident(), false, false));
replacer.registerReplacer("{nationtagoverride}", event -> formatNationTag(event.getResident(), true, false));
replacer.registerReplacer("{townytag}", event -> formatTownyTag(event.getResident(), false, false));
replacer.registerReplacer("{townyformatted}", event -> formatTownyTag(event.getResident(), false, true));
replacer.registerReplacer("{townytagoverride}", event -> formatTownyTag(event.getResident(), true, false));
replacer.registerReplacer("{title}", event -> getPrefix(event.getResident(), true));
replacer.registerReplacer("{surname}", event -> getSuffix(event.getResident(), false));
replacer.registerReplacer("{townynameprefix}", event -> getNamePrefix(event.getResident()));
replacer.registerReplacer("{townynamepostfix}", event -> getNamePostfix(event.getResident()));
replacer.registerReplacer("{townyprefix}", event -> getPrefix(event.getResident(), false));
replacer.registerReplacer("{townypostfix}", event -> getSuffix(event.getResident(), false));
replacer.registerReplacer("{townycolor}", event -> getTownyColour(event.getResident()));
replacer.registerReplacer("{group}", event -> getVaultGroup(event.getEvent().getPlayer()));
replacer.registerReplacer("{permprefix}", event -> getVaultPrefixSuffix(event.getResident(), "prefix"));
replacer.registerReplacer("{permsuffix}", event -> getVaultPrefixSuffix(event.getResident(), "suffix"));
replacer.registerReplacer("{permuserprefix}", event -> getVaultPrefixSuffix(event.getResident(), "userprefix"));
replacer.registerReplacer("{permusersuffix}", event -> getVaultPrefixSuffix(event.getResident(), "usersuffix"));
replacer.registerReplacer("{permgroupprefix}", event -> getVaultPrefixSuffix(event.getResident(), "groupprefix"));
replacer.registerReplacer("{permgroupsuffix}", event -> getVaultPrefixSuffix(event.getResident(), "groupsuffix"));
replacer.registerReplacer("{playername}", event -> event.getEvent().getPlayer().getName());
replacer.registerReplacer("{primaryresidentrank}", event -> getPrimaryRankPrefix(event.getResident()));
}
public static String getChatFormat(LocalTownyChatEvent event) {
String out = replacer.replaceAll(event.getFormat(), event) // Replace the townychat tags with their values.
.replace("%", "") // Prevent user-inputted tags from breaking chat format.
.replace("{modplayername}", "%1$s") // Other plugins will replace this with the DisplayName.
.replace("{msg}", "%2$s"); // Replace the {msg} here so it's not regex parsed.
return Colors.translateColorCodes(out);
}
public static String getWorldTag(LocalTownyChatEvent event) {
return String.format(ChatSettings.getWorldTag(), event.getEvent().getPlayer().getWorld().getName());
}
public static String getTownName(Resident resident) {
return resident.hasTown() ? resident.getTownOrNull().getName() : "";
}
public static String getNationName(Resident resident) {
return resident.hasNation() ? resident.getNationOrNull().getName() : "";
}
/**
* @param resident
* @param override use full names if no tag is present
* @param full Only use full names (no tags).
* @return string containing the correctly formatted nation/town data
*/
public static String formatTownyTag(Resident resident, Boolean override, Boolean full) {
if (resident.hasTown()) {
Town town = TownyAPI.getInstance().getResidentTownOrNull(resident);
String townTag = getTag(town);
Nation nation = null;
String nationTag = null;
if (resident.hasNation()) {
nation = TownyAPI.getInstance().getResidentNationOrNull(resident);
nationTag = getTag(nation);
}
String nTag = "", tTag = "";
//Force use of full names only
if (full) {
nationTag = "";
townTag = "";
}
// Load town tags/names
if (townTag != null && !townTag.isEmpty())
tTag = townTag;
else if (override || full)
tTag = getName(town);
// Load the nation tags/names
if ((nationTag != null) && !nationTag.isEmpty())
nTag = nationTag;
else if (resident.hasNation() && (override || full))
nTag = getName(nation);
// Output depending on what tags are present
if ((!tTag.isEmpty()) && (!nTag.isEmpty())) {
if (ChatSettings.getBothTag().contains("%t") || ChatSettings.getBothTag().contains("%n")) {
// Then it contains %s & %s
// Small suttle change so that an issue is solved, it is documented in the config.
// But only after addition of this. (v0.50)
return ChatSettings.getBothTag().replace("%t", tTag).replace("%n", nTag);
} else {
return String.format(ChatSettings.getBothTag(), nTag, tTag);
}
}
if (!nTag.isEmpty()) {
return String.format(ChatSettings.getNationTag(), nTag);
}
if (!tTag.isEmpty()) {
return String.format(ChatSettings.getTownTag(), tTag);
}
}
return "";
}
public static String formatTownTag(Resident resident, Boolean override, Boolean full) {
if (resident.hasTown()) {
Town town = TownyAPI.getInstance().getResidentTownOrNull(resident);
if (full)
return String.format(ChatSettings.getTownTag(), getName(town));
else if (town.hasTag())
return String.format(ChatSettings.getTownTag(), getTag(town));
else if (override)
return String.format(ChatSettings.getTownTag(), getName(town));
}
return "";
}
public static String formatNationTag(Resident resident, Boolean override, Boolean full) {
if (resident.hasNation()) {
Nation nation = TownyAPI.getInstance().getResidentNationOrNull(resident);
if (full)
return String.format(ChatSettings.getNationTag(), getName(nation));
else if (nation.hasTag())
return String.format(ChatSettings.getNationTag(), getTag(nation));
else if (override)
return String.format(ChatSettings.getNationTag(), getName(nation));
}
return "";
}
public static String getNamePrefix(Resident resident) {
if (resident == null)
return "";
if (resident.isKing())
return TownySettings.getKingPrefix(resident);
else if (resident.isMayor())
return TownySettings.getMayorPrefix(resident);
return "";
}
public static String getNamePostfix(Resident resident) {
if (resident == null)
return "";
if (resident.isKing())
return TownySettings.getKingPostfix(resident);
else if (resident.isMayor())
return TownySettings.getMayorPostfix(resident);
return "";
}
public static String getPrimaryRankPrefix(Resident resident) {
if (resident == null)
return "";
String rank = resident.getPrimaryRankPrefix();
return rank.isEmpty() ? "" : rank + " ";
}
private static String getName(Government gov) {
return StringMgmt.remUnderscore(gov.getName());
}
private static String getTag(Government gov) {
return gov.getTag();
}
public static String getPrefix(Resident resident, boolean blank) {
return resident.hasTitle() ? resident.getTitle() + " " : blank ? "" : getNamePrefix(resident);
}
public static String getSuffix(Resident resident, boolean blank) {
return resident.hasSurname() ? " " + resident.getSurname() : blank ? "" : getNamePostfix(resident);
}
public static String getTownyColour(Resident resident) {
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 +0,0 @@
package com.palmergames.bukkit.TownyChat;
import java.util.function.Function;
import com.palmergames.bukkit.TownyChat.listener.LocalTownyChatEvent;
public class TownyChatReplacer {
private final Function<LocalTownyChatEvent, String> func;
public TownyChatReplacer(Function<LocalTownyChatEvent, String> func) {
this.func = func;
}
public String getWith(LocalTownyChatEvent event) {
return func.apply(event);
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,10 @@
package com.palmergames.bukkit.TownyChat.channels;
public enum ChannelTypes {
TOWN,
NATION,
ALLIANCE,
DEFAULT,
GLOBAL,
PRIVATE
}
@@ -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";
}
} }
@@ -1,20 +1,28 @@
package com.palmergames.bukkit.TownyChat.channels; package com.palmergames.bukkit.TownyChat.channels;
import com.github.milkdrinkers.colorparser.ColorParser;
import com.palmergames.bukkit.TownyChat.Chat; import com.palmergames.bukkit.TownyChat.Chat;
import com.palmergames.bukkit.TownyChat.TownyChatFormatter;
import com.palmergames.bukkit.TownyChat.config.ChatSettings;
import com.palmergames.bukkit.TownyChat.events.AsyncChatHookEvent; import com.palmergames.bukkit.TownyChat.events.AsyncChatHookEvent;
import com.palmergames.bukkit.TownyChat.util.Adventure;
import com.palmergames.bukkit.TownyChat.util.TownyChatFormatter;
import com.palmergames.bukkit.TownyChat.config.ChatSettings;
import com.palmergames.bukkit.TownyChat.events.PlayerJoinChatChannelEvent; import com.palmergames.bukkit.TownyChat.events.PlayerJoinChatChannelEvent;
import com.palmergames.bukkit.TownyChat.listener.LocalTownyChatEvent; import com.palmergames.bukkit.TownyChat.listener.InternalTownyChatEvent;
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.minimessage.MiniMessage;
import net.kyori.adventure.text.minimessage.tag.Tag;
import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver;
import net.kyori.adventure.text.minimessage.tag.standard.StandardTags;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.Sound; import org.bukkit.Sound;
@@ -23,338 +31,295 @@ 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 final Chat plugin;
private Chat plugin; public StandardChannel(Chat instance, String name) {
super(name);
public StandardChannel(Chat instance, String name) { this.plugin = instance;
super(name); }
this.plugin = instance;
}
@Override @Deprecated
public void chatProcess(AsyncPlayerChatEvent event) { public void chatProcess(AsyncPlayerChatEvent e) {
IllegalCallerException illegalCallerException = new IllegalCallerException("A plugin is using the deprecated method Channel#chatProcess(AsyncPlayerChatEvent) which is no longer supported. Please use Channel#chatProcess(AsyncChatEvent)!");
channelTypes channelType = this.getType(); Chat.getTownyChat().getComponentLogger().warn(
Player player = event.getPlayer(); Component.text(illegalCallerException + Arrays.toString(illegalCallerException.getStackTrace()))
boolean notifyjoin = false; );
}
Resident resident = TownyUniverse.getInstance().getResident(player.getUniqueId()); public void chatProcess(AsyncChatEvent e) {
if (resident == null) ChannelTypes channelType = this.getType();
return; Player p = e.getPlayer();
Town town = TownyAPI.getInstance().getResidentTownOrNull(resident); Resident res = TownyAPI.getInstance().getResident(p);
Nation nation = TownyAPI.getInstance().getResidentNationOrNull(resident); boolean notifyjoin = false;
// If the channel would require a town/nation which is null, cancel and fail early. if (res == null) {
if (town == null && channelType.equals(channelTypes.TOWN) || e.setCancelled(true);
nation == null && (channelType.equals(channelTypes.NATION) || channelType.equals(channelTypes.ALLIANCE))) { return;
event.setCancelled(true); }
return;
}
// If player sends a message to a channel they have left Town town = TownyAPI.getInstance().getResidentTownOrNull(res);
// tell the channel to add the player back Nation nation = TownyAPI.getInstance().getResidentNationOrNull(res);
if (isAbsent(player.getName())) {
join(player);
notifyjoin = true;
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 = ChatSettings.getChannelFormat(player, channelType); if (
town == null && channelType.equals(ChannelTypes.TOWN) ||
nation == null && (channelType.equals(ChannelTypes.NATION) || channelType.equals(ChannelTypes.ALLIANCE))
) {
e.setCancelled(true);
return;
}
// Get the list of message recipients. // If player sends a message in a channel they have left, rejoin the channel
Set<Player> recipients = getRecipients(player, town, nation, channelType, event.getRecipients()); if (isAbsent(p.getName())) {
join(p);
notifyjoin = true;
Bukkit.getPluginManager().callEvent(new PlayerJoinChatChannelEvent(p, this));
}
// Try sending an alone message if it is called for. final String channelMessageString = Chat.usingPlaceholderAPI ?
trySendingAloneMessage(player, recipients); PlaceholderAPI.setPlaceholders(p, getFormat(p)) :
getFormat(p);
// format is left to store the original non-PAPI-parsed chat format. final InternalTownyChatEvent chatEvent = new InternalTownyChatEvent(e, res);
String newFormat = format; final Component finalMessage = MiniMessage.builder()
// Parse any PAPI placeholders. .tags(
if (Chat.usingPlaceholderAPI) TagResolver.builder()
newFormat = PlaceholderAPI.setPlaceholders(player, format); .resolvers(
TownyChatFormatter.parser(chatEvent),
TagResolver.resolver(
"channeltag", Tag.inserting(ColorParser.of(this.getChannelTag()).parseLegacy().build())
),
TagResolver.resolver(
"msgcolour", Tag.inserting(ColorParser.of(this.getMessageColour()).parseLegacy().build())
),
StandardTags.defaults(),
TagResolver.resolver( // TODO Parse color codes, the player has permissions to use
"msg", Tag.inserting(e.message())
)
)
.build()
)
.build().deserialize(channelMessageString);
/* // Get recipients
* Only modify GLOBAL channelType chat (general and local chat channels) if isModifyChat() is true. final Set<Player> recipients = getRecipients(p, town, nation, channelType);
*/
if (!(channelType.equals(channelTypes.GLOBAL) && !ChatSettings.isModify_chat()))
applyFormats(event, format, newFormat, resident);
/* // Try sending an alone message if the player is alone in a channel.
* Set recipients for Bukkit to send this message to. trySendingAloneMessage(p, recipients);
*/
event.getRecipients().clear();
event.getRecipients().addAll(recipients);
// If the server has marked this Channel as hooked, fire the AsyncChatHookEvent. // Calculate recipients and set recipients
// If the event is cancelled, cancel the chat entirely. e.message(finalMessage);
// Fires its own sendSpyMessage(). e.viewers().clear();
if (isHooked()) e.viewers().add(Audience.audience(recipients));
if (!sendOffHookedMessage(event, channelType)) {
event.setCancelled(true);
return;
}
// Send spy message if this was never hooked. // If the server has marked this Channel as hooked, fire the AsyncChatHookEvent.
if (!isHooked()) // If the event is cancelled, cancel the chat entirely.
sendSpyMessage(event, channelType); // Fires its own sendSpyMessage().
if (isHooked()) {
AsyncChatHookEvent hookEvent = new AsyncChatHookEvent(e, this, recipients);
Bukkit.getServer().getPluginManager().callEvent(hookEvent);
if (hookEvent.isCancelled()) {
e.setCancelled(true);
return;
}
// Play the channel sound, if used. e.viewers().clear();
tryPlayChannelSound(event.getRecipients()); e.viewers().add(Audience.audience(hookEvent.getRecipients()));
if (notifyjoin) /*
TownyMessaging.sendMessage(player, "You join " + Colors.translateColorCodes(getMessageColour()) + getName()); * Send spy message before another plugin changes any of the recipients, so we
* know which people can see it.
*/
sendSpyMessage(e, channelType, recipients);
}
/* // Add console as listener and set custom rendered for message
* Perform any last channel specific functions like logging this chat and e.viewers().add(Bukkit.getServer().getConsoleSender());
* relaying to Dynmap. e.renderer(
*/ (source, sourceDisplayName, message, viewer) -> e.message()
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) { /*
return switch (channelType) { * Send spy message before another plugin changes any of the recipients, so we
case TOWN -> new HashSet<>(findRecipients(player, TownyAPI.getInstance().getOnlinePlayers(town))); * know which people can see it.
case NATION -> new HashSet<>(findRecipients(player, TownyAPI.getInstance().getOnlinePlayers(nation))); */
case ALLIANCE -> new HashSet<>(findRecipients(player, TownyAPI.getInstance().getOnlinePlayersAlliance(nation))); sendSpyMessage(e, channelType, recipients);
case DEFAULT -> new HashSet<>(findRecipients(player, new ArrayList<>(recipients)));
case GLOBAL, PRIVATE -> new HashSet<>(findRecipients(player, new ArrayList<>(recipients)));
};
}
/** // Play the channel sound, if used.
* Compile a list of valid recipients for this message. tryPlayChannelSound(recipients);
*
* @param sender
* @param playerList
* @return Set containing a list of players for this message.
*/
private Set<Player> findRecipients(Player sender, List<Player> playerList) {
// Refresh the potential channels a player can see, if they are not currently in the channel.
playerList.stream().forEach(p -> refreshPlayer(this, p));
return playerList.stream()
.filter(p -> hasListenPermission(p)) // Check permission.
.filter(p -> testDistance(sender, p, getRange())) // Within range.
.filter(p -> !plugin.isIgnoredByEssentials(sender, p)) // Check essentials ignore.
.filter(p -> !isAbsent(p.getName())) // Check if player is purposefully absent.
.collect(Collectors.toSet());
}
private void refreshPlayer(Channel channel, Player player) { if (notifyjoin)
if (!channel.isPresent(player.getName())) TownyMessaging.sendMessage(p, "You join " + Colors.translateColorCodes(getMessageColour()) + getName());
channel.forgetPlayer(player);
}
/** /*
* Check the distance between players and return a result based upon the range setting * Perform any last channel specific functions like logging this chat and
* -1 = no limit * relaying to Dynmap.
* 0 = same world */
* any positive value = distance in blocks switch (channelType) {
* case TOWN:
* @param player1 case NATION:
* @param player2 case ALLIANCE:
* @param range case DEFAULT:
* @return true if in range break;
*/ case PRIVATE:
private boolean testDistance(Player player1, Player player2, double range) { case GLOBAL:
tryPostToDynmap(p, e.message());
// unlimited range (all worlds) break;
if (range == -1) }
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 Set<Player> getRecipients(Player player, Town town, Nation nation, ChannelTypes channelType) {
if (ChatSettings.isUsingAloneMessage() && return switch (channelType) {
recipients.stream().filter(p -> sender.canSee(p)).count() < 2) // sender will usually be a recipient of their own message. case TOWN -> new HashSet<>(findRecipients(player, TownyAPI.getInstance().getOnlinePlayers(town)));
TownyMessaging.sendMessage(sender, ChatSettings.getUsingAloneMessageString()); case NATION -> new HashSet<>(findRecipients(player, TownyAPI.getInstance().getOnlinePlayers(nation)));
} case ALLIANCE -> new HashSet<>(findRecipients(player, TownyAPI.getInstance().getOnlinePlayersAlliance(nation)));
case DEFAULT, GLOBAL, PRIVATE -> new HashSet<>(findRecipients(player, new ArrayList<>(Bukkit.getOnlinePlayers())));
};
}
private void applyFormats(AsyncPlayerChatEvent event, String originalFormat, String workingFormat, Resident resident) { /**
// Parse out our own channelTag and msgcolour tags. * Compile a list of valid recipients for this message.
String newFormat = parseTagAndMsgColour(workingFormat); *
// Attempt to apply the new format. * @param sender
catchFormatConversionException(event, originalFormat, newFormat); * @param playerList
* @return Set containing a list of players for this message.
// Fire the LocalTownyChatEvent. */
LocalTownyChatEvent chatEvent = new LocalTownyChatEvent(event, resident); private Set<Player> findRecipients(Player sender, List<Player> playerList) {
// Format the chat line, replacing the TownyChat chat tags. // Refresh the potential channels a player can see, if they are not currently in the channel.
newFormat = TownyChatFormatter.getChatFormat(chatEvent); playerList.forEach(p -> refreshPlayer(this, p));
// Attempt to apply the new format. return playerList.stream()
catchFormatConversionException(event, originalFormat, newFormat); .filter(p -> testDistance(sender, p, getRange())) // Within range.
} .filter(p -> !plugin.isIgnoredByEssentials(sender, p)) // Check essentials ignore.
.filter(p -> !isAbsent(p.getName())) // Check if player is purposefully absent.
.collect(Collectors.toSet());
}
private String parseTagAndMsgColour(String format) { private void refreshPlayer(Channel channel, Player player) {
return format if (!channel.isPresent(player.getName()))
.replace("{channelTag}", Colors.translateColorCodes(getChannelTag() != null ? getChannelTag() : "")) channel.forgetPlayer(player);
.replace("{msgcolour}", Colors.translateColorCodes(getMessageColour() != null ? getMessageColour() : "")); }
}
private void catchFormatConversionException(AsyncPlayerChatEvent event, String format, String newFormat) { /**
try { * Check the distance between players and return a result based upon the range setting
event.setFormat(newFormat); * -1 = no limit
} catch (UnknownFormatConversionException e) { * 0 = same world
// This exception is usually thrown when a PAPI placeholder did not get parsed * any positive value = distance in blocks
// and has left behind a % symbol followed by something that String#format *
// cannot handle. * @param player1
boolean percentSymbol = format.contains("%" + e.getConversion()); * @param player2
String errmsg = "TownyChat tried to apply a chat format that is not allowed: '" + * @param range
newFormat + "', because of the " + e.getConversion() + " symbol" + * @return true if in range
(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."); private boolean testDistance(Player player1, Player player2, double range) {
Chat.getTownyChat().getLogger().severe(errmsg);
if (percentSymbol) // unlimited range (all worlds)
// Attempt to remove the unparsed placeholder and send this right back. if (range == -1)
catchFormatConversionException(event, format, purgePAPI(newFormat, "%" + e.getConversion())); return true;
else
// Just let the chat go, this results in an error in the log, and TownyChat not being able to format chat.
event.setFormat(format);
}
}
private String purgePAPI(String format, String startOfPlaceholder) { // Same world only
return format.replaceAll(startOfPlaceholder + ".*%", ""); if (range == 0)
} return player1.getWorld().equals(player2.getWorld());
/** // Range check (same world)
* Send off TownyChat's {@link AsyncChatHookEvent} which allows other plugins to return player1.getWorld().equals(player2.getWorld()) &&
* cancel or modify TownyChat's messaging. player1.getLocation().distance(player2.getLocation()) < range;
* }
* @param event {@link AsyncPlayerChatEvent} that has caused a message.
* @param channelType {@link channelTypes} which this message is being sent through.
* @return false if the AsyncChatHookEvent is cancelled.
*/
private boolean sendOffHookedMessage(AsyncPlayerChatEvent event, channelTypes channelType) {
AsyncChatHookEvent hookEvent = new AsyncChatHookEvent(event, this, !Bukkit.getServer().isPrimaryThread());
Bukkit.getServer().getPluginManager().callEvent(hookEvent);
if (hookEvent.isCancelled())
return false;
/*
* Send spy message before another plugin changes any of the recipients, so we
* know which people can see it.
*/
sendSpyMessage(event, channelType);
if (hookEvent.isChanged()) { private void trySendingAloneMessage(Player sender, Set<Player> recipients) {
event.setMessage(hookEvent.getMessage()); if (ChatSettings.isUsingAloneMessage() &&
event.setFormat(hookEvent.getFormat()); recipients.stream().filter(sender::canSee).count() < 2) // sender will usually be a recipient of their own message.
event.getRecipients().clear(); TownyMessaging.sendMessage(sender, ChatSettings.getUsingAloneMessageString());
event.getRecipients().addAll(hookEvent.getRecipients()); }
}
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 = Adventure.plainText().serialize(event.message());
* @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, Component message) {
if (super.getRange() > 0)
return;
DynmapAPI dynMap = plugin.getDynmap();
if (dynMap != null)
dynMap.postPlayerMessageToWeb(player, Adventure.plainText().serialize(message));
}
} }
@@ -1,11 +0,0 @@
package com.palmergames.bukkit.TownyChat.channels;
public enum channelTypes {
TOWN,
NATION,
ALLIANCE,
DEFAULT,
GLOBAL,
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,426 +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.util.FileMgmt; import com.palmergames.bukkit.towny.TownyUniverse;
import com.palmergames.util.StringMgmt; import com.palmergames.bukkit.towny.object.TownyWorld;
import com.palmergames.util.FileMgmt;
import org.bukkit.Bukkit; import com.palmergames.util.StringMgmt;
import org.bukkit.configuration.ConfigurationSection; import org.bukkit.Bukkit;
import java.io.File; import org.bukkit.configuration.ConfigurationSection;
import java.io.IOException;
import java.util.Arrays; import java.io.File;
import java.util.Collections; import java.io.IOException;
import java.util.HashMap; import java.util.*;
import java.util.LinkedHashMap;
import java.util.List; public class ChannelsSettings {
import java.util.Map;
import java.util.Set; private static final String CHANNELS_ROOT = "Channels";
private final static List<String> DEFAULT_CHANNELS = Arrays.asList("general", "town", "nation", "alliance", "admin", "mod", "local");
public class ChannelsSettings { private static CommentedConfiguration channelConfig, newChannelConfig;
private static final String CHANNELS_ROOT = "Channels"; /**
private static CommentedConfiguration channelConfig, newChannelConfig; * @return true if the channels.yml has loaded.
private final static List<String> DEFAULT_CHANNELS = Arrays.asList("general","town","nation","alliance","admin","mod","local"); * @throws IOException
*/
private static final String CHANNEL_TAG = "channeltag"; public static boolean loadCommentedChannelsConfig() {
private static final String LEGACY_CHANNEL_TAG = "channelTag"; String filepath = Chat.getTownyChat().getChannelsConfigPath();
private static final String SPAM_TIME = "spam_time"; if (FileMgmt.checkOrCreateFile(filepath)) {
private static final String RANGE = "range"; File file = new File(filepath);
private static final String DEFAULT = "default";
private static final String PERMISSION = "permission"; // read the channels.yml into memory
private static final String MESSAGECOLOUR = "messagecolour"; channelConfig = new CommentedConfiguration(file.toPath());
private static final String TYPE = "type"; if (!channelConfig.load()) {
private static final String COMMANDS = "commands"; Bukkit.getLogger().severe("[TownyChat] Failed to load Channels.yml!");
private static final String FOCUSABLE = "focusable"; Bukkit.getLogger().severe("[TownyChat] Please check that the file passes a YAML Parser test:");
private static final String HOOKED = "hooked"; Bukkit.getLogger().severe("[TownyChat] Online YAML Parser: https://yaml-online-parser.appspot.com/");
private static final String SOUND = "sound"; return false;
private static final String SPEAKPERMISSION = "speakpermission"; }
private static final String LISTENPERMISSION = "listenpermission"; setDefaults(file);
private static final String LEAVEPERMISSION = "leavepermission"; channelConfig.save();
if (!loadChannels())
/** return false;
* }
* @return true if the channels.yml has loaded. return true;
* @throws IOException }
*/
public static boolean loadCommentedChannelsConfig() { /**
String filepath = Chat.getTownyChat().getChannelsConfigPath(); * Builds a new channels.yml reading old channels.yml data,
if (FileMgmt.checkOrCreateFile(filepath)) { * and setting new nodes to default values.
File file = new File(filepath); */
private static void setDefaults(File file) {
// read the channels.yml into memory newChannelConfig = new CommentedConfiguration(file.toPath());
channelConfig = new CommentedConfiguration(file.toPath()); newChannelConfig.load();
if (!channelConfig.load()) {
Bukkit.getLogger().severe("[TownyChat] Failed to load Channels.yml!"); for (ChannelsNodes root : ChannelsNodes.values()) {
Bukkit.getLogger().severe("[TownyChat] Please check that the file passes a YAML Parser test:"); if (root.getComments().length > 0)
Bukkit.getLogger().severe("[TownyChat] Online YAML Parser: https://yaml-online-parser.appspot.com/"); addComment(root.getRoot(), root.getComments());
return false;
} setNewProperty(root.getRoot(), getValue(root));
setDefaults(file); }
channelConfig.save();
if (!loadChannels()) tryAndSetDefaultChannels();
return false;
} channelConfig = newChannelConfig;
return true; newChannelConfig = null;
} }
/** private static Object getValue(ChannelsNodes root) {
* Builds a new channels.yml reading old channels.yml data, String key = root.getRoot();
* and setting new nodes to default values. return channelConfig.get(key) != null ? channelConfig.get(key) : root.getDefault();
*/ }
private static void setDefaults(File file) {
newChannelConfig = new CommentedConfiguration(file.toPath()); private static void addComment(String root, String... comments) {
newChannelConfig.load(); newChannelConfig.addComment(root, comments);
}
for (ChannelsNodes root : ChannelsNodes.values()) {
if (root.getComments().length > 0) private static void setNewProperty(String root, Object value) {
addComment(root.getRoot(), root.getComments()); if (value == null) {
value = "";
setNewProperty(root.getRoot(), getValue(root)); }
} newChannelConfig.set(root, value.toString());
}
tryAndSetDefaultChannels();
private static void tryAndSetDefaultChannels() {
channelConfig = newChannelConfig; if (channelConfig.contains(CHANNELS_ROOT)) {
newChannelConfig = null; // There is already a root channels present, not our first run.
} newChannelConfig.set(CHANNELS_ROOT, channelConfig.get(CHANNELS_ROOT));
} else {
private static Object getValue(ChannelsNodes root) { // Populate a fresh channels.yml.
String key = root.getRoot(); Chat.getTownyChat().getLogger().info("TownyChat creating default channels.yml file.");
return channelConfig.get(key) != null ? channelConfig.get(key) : root.getDefault();
} newChannelConfig.createSection(CHANNELS_ROOT);
DEFAULT_CHANNELS.forEach(channel -> newChannelConfig.createSection(CHANNELS_ROOT + "." + channel));
private static void addComment(String root, String... comments) {
newChannelConfig.addComment(root, comments); setConfigSection("general", generalDefaults());
} setConfigSection("town", townDefaults());
setConfigSection("nation", nationDefaults());
private static void setNewProperty(String root, Object value) { setConfigSection("alliance", allianceDefaults());
if (value == null) { setConfigSection("admin", adminDefaults());
value = ""; setConfigSection("mod", modDefaults());
} setConfigSection("local", localDefaults());
newChannelConfig.set(root, value.toString()); }
} }
private static void tryAndSetDefaultChannels() { private static void setConfigSection(String section, Map<String, Object> settings) {
if (channelConfig.contains(CHANNELS_ROOT)) { ConfigurationSection configurationSection = newChannelConfig.getConfigurationSection(CHANNELS_ROOT + "." + section);
// There is already a root channels present, not our first run. settings.entrySet().stream().forEach(entry -> configurationSection.set(entry.getKey(), entry.getValue()));
newChannelConfig.set(CHANNELS_ROOT, channelConfig.get(CHANNELS_ROOT)); }
} else {
// Populate a fresh channels.yml. private static Map<String, Object> generalDefaults() {
Chat.getTownyChat().getLogger().info("TownyChat creating default channels.yml file."); Map<String, Object> channelMap = new LinkedHashMap<>();
channelMap.put("commands", "g");
newChannelConfig.createSection(CHANNELS_ROOT); channelMap.put("type", "GLOBAL");
DEFAULT_CHANNELS.forEach(channel -> newChannelConfig.createSection(CHANNELS_ROOT + "." + channel)); channelMap.put("format", "{channelTag} {worldname}{townytagoverride}{townycolor}{permprefix}{group} {townyprefix}{modplayername}{townypostfix}{permsuffix}&f:{msgcolour} {msg}");
channelMap.put("worldformats", new LinkedHashMap<>());
setConfigSection("general", generalDefaults()); channelMap.put("channelTag", "&f[g]");
setConfigSection("town", townDefaults()); channelMap.put("messagecolour", "&f");
setConfigSection("nation", nationDefaults()); channelMap.put("permission", "towny.chat.general");
setConfigSection("alliance", allianceDefaults()); channelMap.put("default", "true");
setConfigSection("admin", adminDefaults()); channelMap.put("range", "-1");
setConfigSection("mod", modDefaults()); channelMap.put("spam_time", "0.5");
setConfigSection("local", localDefaults()); return channelMap;
} }
}
private static Map<String, Object> townDefaults() {
private static void setConfigSection(String section, Map<String,Object> settings) { Map<String, Object> channelMap = new LinkedHashMap<>();
ConfigurationSection configurationSection = newChannelConfig.getConfigurationSection(CHANNELS_ROOT + "." + section); channelMap.put("commands", "tc");
settings.entrySet().stream().forEach(entry -> configurationSection.set(entry.getKey(), entry.getValue())); channelMap.put("type", "TOWN");
} channelMap.put("format", "{channelTag} {townycolor}{permprefix}{townyprefix}{playername}{townypostfix}{permsuffix}&f:{msgcolour} {msg}");
channelMap.put("worldformats", new LinkedHashMap<>());
private static Map<String, Object> generalDefaults() { channelMap.put("channelTag", "&f[&3TC&f]");
Map<String, Object> channelMap = new LinkedHashMap<>(); channelMap.put("messagecolour", "&b");
channelMap.put(COMMANDS, "g"); channelMap.put("permission", "towny.chat.town");
channelMap.put(TYPE, "GLOBAL"); channelMap.put("range", "-1");
channelMap.put(CHANNEL_TAG, "&f[g]"); channelMap.put("spam_time", "0.5");
channelMap.put(MESSAGECOLOUR, "&f"); return channelMap;
channelMap.put(PERMISSION, "towny.chat.general"); }
channelMap.put(DEFAULT, "true");
channelMap.put(RANGE, "-1"); private static Map<String, Object> nationDefaults() {
channelMap.put(SPAM_TIME, "0.5"); Map<String, Object> channelMap = new LinkedHashMap<>();
return channelMap; channelMap.put("commands", "nc");
} channelMap.put("type", "NATION");
channelMap.put("format", "{channelTag} {towntagoverride}{townycolor}{permprefix}{townyprefix}{playername}{townypostfix}{permsuffix}&f:{msgcolour} {msg}");
private static Map<String, Object> townDefaults() { channelMap.put("worldformats", new LinkedHashMap<>());
Map<String, Object> channelMap = new LinkedHashMap<>(); channelMap.put("channelTag", "&f[&6NC&f]");
channelMap.put(COMMANDS, "tc"); channelMap.put("messagecolour", "&e");
channelMap.put(TYPE, "TOWN"); channelMap.put("permission", "towny.chat.nation");
channelMap.put(CHANNEL_TAG, "&f[&3TC&f]"); channelMap.put("range", "-1");
channelMap.put(MESSAGECOLOUR, "&b"); channelMap.put("spam_time", "0.5");
channelMap.put(PERMISSION, "towny.chat.town"); return channelMap;
channelMap.put(RANGE, "-1"); }
channelMap.put(SPAM_TIME, "0.5");
return channelMap; private static Map<String, Object> allianceDefaults() {
} Map<String, Object> channelMap = new LinkedHashMap<>();
channelMap.put("commands", "ac");
private static Map<String, Object> nationDefaults() { channelMap.put("type", "ALLIANCE");
Map<String, Object> channelMap = new LinkedHashMap<>(); channelMap.put("format", "{channelTag} {towntagoverride}{townycolor}{permprefix}{townyprefix}{playername}{townypostfix}{permsuffix}&f:{msgcolour} {msg}");
channelMap.put(COMMANDS, "nc"); channelMap.put("worldformats", new LinkedHashMap<>());
channelMap.put(TYPE, "NATION"); channelMap.put("channelTag", "&f[&2AC&f]");
channelMap.put(CHANNEL_TAG, "&f[&6NC&f]"); channelMap.put("messagecolour", "&a");
channelMap.put(MESSAGECOLOUR, "&e"); channelMap.put("permission", "towny.chat.alliance");
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> adminDefaults() {
private static Map<String, Object> allianceDefaults() { Map<String, Object> channelMap = new LinkedHashMap<>();
Map<String, Object> channelMap = new LinkedHashMap<>(); channelMap.put("commands", "a,admin");
channelMap.put(COMMANDS, "ac"); channelMap.put("type", "DEFAULT");
channelMap.put(TYPE, "ALLIANCE"); channelMap.put("format", "{channelTag} {permprefix}{playername}{permsuffix}&f:{msgcolour} {msg}");
channelMap.put(CHANNEL_TAG, "&f[&2AC&f]"); channelMap.put("worldformats", new LinkedHashMap<>());
channelMap.put(MESSAGECOLOUR, "&a"); channelMap.put("channelTag", "&f[&4ADMIN&f]");
channelMap.put(PERMISSION, "towny.chat.alliance"); channelMap.put("messagecolour", "&c");
channelMap.put(RANGE, "-1"); channelMap.put("permission", "towny.chat.admin");
channelMap.put(SPAM_TIME, "0.5"); channelMap.put("range", "-1");
return channelMap; return channelMap;
} }
private static Map<String, Object> adminDefaults() { private static Map<String, Object> modDefaults() {
Map<String, Object> channelMap = new LinkedHashMap<>(); Map<String, Object> channelMap = new LinkedHashMap<>();
channelMap.put(COMMANDS, "a,admin"); channelMap.put("commands", "m,mod");
channelMap.put(TYPE, "DEFAULT"); channelMap.put("type", "DEFAULT");
channelMap.put(CHANNEL_TAG, "&f[&4ADMIN&f]"); channelMap.put("format", "{channelTag} {permprefix}{playername}{permsuffix}&f:{msgcolour} {msg}");
channelMap.put(MESSAGECOLOUR, "&c"); channelMap.put("worldformats", new LinkedHashMap<>());
channelMap.put(PERMISSION, "towny.chat.admin"); channelMap.put("channelTag", "&f[&9MOD&f]");
channelMap.put(RANGE, "-1"); channelMap.put("messagecolour", "&5");
return channelMap; channelMap.put("permission", "towny.chat.mod");
} channelMap.put("range", "-1");
return channelMap;
private static Map<String, Object> modDefaults() { }
Map<String, Object> channelMap = new LinkedHashMap<>();
channelMap.put(COMMANDS, "m,mod"); private static Map<String, Object> localDefaults() {
channelMap.put(TYPE, "DEFAULT"); Map<String, Object> channelMap = new LinkedHashMap<>();
channelMap.put(CHANNEL_TAG, "&f[&9MOD&f]"); channelMap.put("commands", "l,lc");
channelMap.put(MESSAGECOLOUR, "&5"); channelMap.put("type", "GLOBAL");
channelMap.put(PERMISSION, "towny.chat.mod"); channelMap.put("format", "{channelTag} {worldname}{townytagoverride}{townycolor}{permprefix}{group} {townyprefix}{modplayername}{townypostfix}{permsuffix}&f:{msgcolour} {msg}");
channelMap.put(RANGE, "-1"); channelMap.put("worldformats", new LinkedHashMap<>());
return channelMap; channelMap.put("channelTag", "&f[local]");
} channelMap.put("messagecolour", "&f");
channelMap.put("permission", "towny.chat.local");
private static Map<String, Object> localDefaults() { channelMap.put("range", "100");
Map<String, Object> channelMap = new LinkedHashMap<>(); return channelMap;
channelMap.put(COMMANDS, "l,lc"); }
channelMap.put(TYPE, "GLOBAL");
channelMap.put(CHANNEL_TAG, "&f[local]"); private static boolean loadChannels() {
channelMap.put(MESSAGECOLOUR, "&f"); ConfigurationSection configurationSection = channelConfig.getConfigurationSection(CHANNELS_ROOT);
channelMap.put(PERMISSION, "towny.chat.local"); if (configurationSection == null) {
channelMap.put(RANGE, "100"); Bukkit.getLogger().severe("[TownyChat] Failed to load Channels.yml!");
return channelMap; Bukkit.getLogger().severe("[TownyChat] No channels root section was present!");
} return false;
}
private static boolean loadChannels() {
ConfigurationSection configurationSection = channelConfig.getConfigurationSection(CHANNELS_ROOT); Set<String> channelsKeys = configurationSection.getKeys(false);
if (configurationSection == null) {
Bukkit.getLogger().severe("[TownyChat] Failed to load Channels.yml!"); // This should never happen if the setDefaults(file) method has run.
Bukkit.getLogger().severe("[TownyChat] No channels root section was present!"); if (channelsKeys.isEmpty()) {
return false; Bukkit.getLogger().severe("[TownyChat] Failed to load Channels.yml!");
} Bukkit.getLogger().severe("[TownyChat] No channels keys were present!");
Bukkit.getLogger().severe("[TownyChat] Deleting your towny\\settings\\channels.yml can solve this problem.");
Set<String> channelsKeys = configurationSection.getKeys(false); return false;
}
// This should never happen if the setDefaults(file) method has run.
if (channelsKeys.isEmpty()) { Chat plugin = Chat.getTownyChat();
Bukkit.getLogger().severe("[TownyChat] Failed to load Channels.yml!");
Bukkit.getLogger().severe("[TownyChat] No channels keys were present!"); channelsKeys.forEach((channelName) -> {
Bukkit.getLogger().severe("[TownyChat] Deleting your towny\\settings\\channels.yml can solve this problem."); Channel channel = new StandardChannel(plugin, channelName);
return false; loadChannelSettings(channelName, channel);
} plugin.getChannelsHandler().addChannel(channel);
});
Chat plugin = Chat.getTownyChat();
if (plugin.getChannelsHandler().getDefaultChannel() == null) {
channelsKeys.forEach((channelName)-> { // If there is no default channel set it to the first one that was parsed (the top one in the config)
Channel channel = new StandardChannel(plugin, channelName); // This is because not everyone knows that you need to add a default: true into the channels.yml to make it the default channel!
loadChannelSettings(channelName, channel); plugin.getChannelsHandler().setDefaultChannel(plugin.getChannelsHandler().getAllChannels().entrySet().iterator().next().getValue());
plugin.getChannelsHandler().addChannel(channel); }
});
return true;
if (plugin.getChannelsHandler().getDefaultChannel() == null) { }
// If there is no default channel set it to the first one that was parsed (the top one in the config)
// This is because not everyone knows that you need to add a default: true into the channels.yml to make it the default channel! private static void loadChannelSettings(String channelName, Channel channel) {
plugin.getChannelsHandler().setDefaultChannel(plugin.getChannelsHandler().getAllChannels().entrySet().iterator().next().getValue()); ChannelDetails data = new ChannelsSettings.ChannelDetails(channelConfig, channelName);
} // The following will always be present in some manner
channel.setCommands(data.getCommands());
return true; channel.setType(ChannelTypes.valueOf(data.getType()));
} channel.setFormat(data.getFormat());
channel.setWorldFormats(data.getWorldFormats());
private static void loadChannelSettings(String channelName, Channel channel) { channel.setRange(data.getRange());
ChannelDetails data = new ChannelsSettings.ChannelDetails(channelConfig, channelName); channel.setHooked(data.isHooked());
// The following will always be present in some manner channel.setFocusable(data.isFocusable());
channel.setCommands(data.getCommands()); channel.setLeavePermission(data.getLeavePermission());
channel.setType(channelTypes.valueOf(data.getType())); // The following may not neccessarily be set.
channel.setRange(data.getRange()); if (data.hasMessageColour())
channel.setHooked(data.isHooked()); channel.setMessageColour(data.getMessageColour());
channel.setFocusable(data.isFocusable()); if (data.hasChannelTag())
channel.setLeavePermission(data.getLeavePermission()); channel.setChannelTag(data.getChannelTag());
// The following may not neccessarily be set. if (data.hasSound())
if (data.hasMessageColour()) channel.setChannelSound(data.getSound());
channel.setMessageColour(data.getMessageColour()); if (data.hasPermission())
if (data.hasChannelTag()) channel.setPermission(data.getPermission());
channel.setChannelTag(data.getChannelTag()); if (data.hasSpeakPermission())
if (data.hasSound()) channel.setSpeakPermission(data.getSpeakPermission());
channel.setChannelSound(data.getSound()); if (data.hasListenPermission())
if (data.hasPermission()) channel.setListenPermission(data.getListenPermission());
channel.setPermission(data.getPermission()); if (data.hasSpamTime())
if (data.hasSpeakPermission()) channel.setSpam_time(data.getSpamTime());
channel.setSpeakPermission(data.getSpeakPermission()); if (data.isDefault()) {
if (data.hasListenPermission()) Chat.getTownyChat().getChannelsHandler().setDefaultChannel(channel);
channel.setListenPermission(data.getListenPermission()); Chat.getTownyChat().getLogger().info("Default Channel set to " + channel.getName());
if (data.hasSpamTime()) }
channel.setSpam_time(data.getSpamTime()); }
if (data.isDefault()) {
Chat.getTownyChat().getChannelsHandler().setDefaultChannel(channel); static class ChannelDetails {
Chat.getTownyChat().getLogger().info("Default Channel set to " + channel.getName()); private Map<String, Object> channelSettingsMap = new HashMap<>();
} private String name;
}
/**
static class ChannelDetails { * Constructor
private Map<String, Object> channelSettingsMap = new HashMap<>(); *
private String name; * @param name Channel name
*/
/** public ChannelDetails(CommentedConfiguration channelsConfig, String name) {
* Constructor super();
* this.name = name;
* @param name Channel name String path = CHANNELS_ROOT + "." + this.name;
*/ for (String key : channelsConfig.getConfigurationSection(path).getKeys(true)) {
public ChannelDetails(CommentedConfiguration channelsConfig, String name) { String innerPath = path + "." + key;
super(); if (channelsConfig.get(innerPath) != null)
this.name = name; channelSettingsMap.put(key, parseObject(channelsConfig.get(innerPath)));
String path = CHANNELS_ROOT + "." + this.name; }
for (String key : channelsConfig.getConfigurationSection(path).getKeys(true)) { }
String innerPath = path + "." + key;
if (channelsConfig.get(innerPath) != null) private Object parseObject(Object object) {
channelSettingsMap.put(key, parseObject(channelsConfig.get(innerPath))); if (object instanceof @SuppressWarnings("rawtypes")List list)
} return StringMgmt.join(list, ",");
} if (object instanceof String string)
return string;
private Object parseObject(Object object) { if (object instanceof Boolean b)
if (object instanceof @SuppressWarnings("rawtypes") List list) return b;
return StringMgmt.join(list, ","); if (object instanceof Double d)
if (object instanceof String string) return d;
return string; return "";
if (object instanceof Boolean b) }
return b;
if (object instanceof Double d) /**
return d; * @return the name
return ""; */
} public String getName() {
return name;
/** }
* @return the name
*/ public String getType() {
public String getName() { return (String) channelSettingsMap.getOrDefault("type", "DEFAULT");
return name; }
}
public String getFormat() {
public String getType() { return (String) channelSettingsMap.getOrDefault("format", "{channelTag} {worldname}{townytagoverride}{townycolor}{permprefix}{group} {townyprefix}{modplayername}{townypostfix}{permsuffix}&f:{msgcolour} {msg}");
return (String) channelSettingsMap.getOrDefault(TYPE, "DEFAULT"); }
}
public HashMap<String, Channel.WorldFormat> getWorldFormats() {
public boolean hasChannelTag() { HashMap<String, Channel.WorldFormat> worldFormats = new HashMap<>();
return channelSettingsMap.containsKey(CHANNEL_TAG) || channelSettingsMap.containsKey(LEGACY_CHANNEL_TAG); if (!ChatSettings.isPer_world())
} return worldFormats;
public String getChannelTag() { if (!channelSettingsMap.containsKey("worldformats"))
String slug = channelSettingsMap.containsKey(LEGACY_CHANNEL_TAG) ? LEGACY_CHANNEL_TAG : CHANNEL_TAG; return worldFormats;
return (String) channelSettingsMap.getOrDefault(slug, "");
} for (TownyWorld world : TownyUniverse.getInstance().getTownyWorlds()) {
String worldName = world.getName();
public boolean hasMessageColour() { String path = "worldformats." + worldName;
return channelSettingsMap.containsKey(MESSAGECOLOUR); if (channelSettingsMap.containsKey(path)) {
} worldFormats.put(
worldName.toLowerCase(Locale.ROOT),
public String getMessageColour() { new Channel.WorldFormat(worldName, (String) channelSettingsMap.getOrDefault(path, getFormat()))
return (String) channelSettingsMap.getOrDefault(MESSAGECOLOUR, ""); );
} }
}
public boolean hasPermission() { return worldFormats;
return channelSettingsMap.containsKey(PERMISSION); }
}
public boolean hasChannelTag() {
public String getPermission() { return channelSettingsMap.containsKey("channeltag");
return (String) channelSettingsMap.getOrDefault(PERMISSION, ""); }
}
public String getChannelTag() {
public boolean hasLeavePermission() { return (String) channelSettingsMap.getOrDefault("channeltag", "");
return channelSettingsMap.containsKey(LEAVEPERMISSION); }
}
public boolean hasMessageColour() {
public String getLeavePermission() { return channelSettingsMap.containsKey("messagecolour");
return (String) channelSettingsMap.getOrDefault(LEAVEPERMISSION, "towny.chat.leave." + name); }
}
public String getMessageColour() {
public boolean hasListenPermission() { return (String) channelSettingsMap.getOrDefault("messagecolour", "");
return channelSettingsMap.containsKey(LISTENPERMISSION); }
}
public boolean hasPermission() {
public String getListenPermission() { return channelSettingsMap.containsKey("permission");
return (String) channelSettingsMap.getOrDefault(LISTENPERMISSION, ""); }
}
public String getPermission() {
public boolean hasSpeakPermission() { return (String) channelSettingsMap.getOrDefault("permission", "");
return channelSettingsMap.containsKey(SPEAKPERMISSION); }
}
public boolean hasLeavePermission() {
public String getSpeakPermission() { return channelSettingsMap.containsKey("leavepermission");
return (String) channelSettingsMap.getOrDefault(SPEAKPERMISSION, ""); }
}
public String getLeavePermission() {
public boolean hasSound() { return (String) channelSettingsMap.getOrDefault("leavepermission", "towny.chat.leave." + name);
return channelSettingsMap.containsKey(SOUND); }
}
public boolean hasListenPermission() {
public String getSound() { return channelSettingsMap.containsKey("listenpermission");
return (String) channelSettingsMap.getOrDefault(SOUND, ""); }
}
public String getListenPermission() {
public boolean hasSpamTime() { return (String) channelSettingsMap.getOrDefault("listenpermission", "");
return channelSettingsMap.containsKey(SPAM_TIME); }
}
public boolean hasSpeakPermission() {
public double getSpamTime() { return channelSettingsMap.containsKey("speakpermission");
return Double.valueOf((String) channelSettingsMap.get(SPAM_TIME)); }
}
public String getSpeakPermission() {
public double getRange() { return (String) channelSettingsMap.getOrDefault("speakpermission", "");
return Double.valueOf((String) channelSettingsMap.getOrDefault(RANGE, -1)); }
}
public boolean hasSound() {
public boolean isHooked() { return channelSettingsMap.containsKey("sound");
return getBoolean(channelSettingsMap.getOrDefault(HOOKED, false)); }
}
public String getSound() {
public boolean isFocusable() { return (String) channelSettingsMap.getOrDefault("sound", "");
return getBoolean(channelSettingsMap.getOrDefault(FOCUSABLE, true)); }
}
public boolean hasSpamTime() {
public boolean isDefault() { return channelSettingsMap.containsKey("spam_time");
return getBoolean(channelSettingsMap.getOrDefault(DEFAULT, false)); }
}
public double getSpamTime() {
public List<String> getCommands() { return Double.valueOf((String) channelSettingsMap.get("spam_time"));
Object object = channelSettingsMap.get(COMMANDS); }
if (object instanceof String string) {
return Arrays.asList(string.split(",")); public double getRange() {
} return Double.valueOf((String) channelSettingsMap.getOrDefault("range", -1));
// As a fall-back we make a command from the channel name, this should not }
// happen often or at all.
return Collections.singletonList(name + "chat"); public boolean isHooked() {
} return getBoolean(channelSettingsMap.getOrDefault("hooked", false));
}
private boolean getBoolean(Object value) {
if (value instanceof Boolean) { public boolean isFocusable() {
return (Boolean) value; return getBoolean(channelSettingsMap.getOrDefault("focusable", true));
} else if (value instanceof String) { }
return Boolean.parseBoolean(value.toString());
} else if (value instanceof Integer) { public boolean isDefault() {
return Integer.parseInt(value.toString()) != 0; return getBoolean(channelSettingsMap.getOrDefault("default", false));
} }
return false;
} public List<String> getCommands() {
} Object object = channelSettingsMap.get("commands");
if (object instanceof String string) {
return Arrays.asList(string.split(","));
}
// As a fall-back we make a command from the channel name, this should not
// happen often or at all.
return Collections.singletonList(name + "chat");
}
private boolean getBoolean(Object value) {
if (value instanceof Boolean) {
return (Boolean) value;
} else if (value instanceof String) {
return Boolean.parseBoolean(value.toString());
} else if (value instanceof Integer) {
return Integer.parseInt(value.toString()) != 0;
}
return false;
}
}
} }
@@ -1,228 +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(
CHANNEL_FORMATS( "tag_formats",
"channel_formats", "",
"", ""),
""), TAG_FORMATS_WORLD(
CHANNEL_FORMATS_GLOBAL( "tag_formats.world",
"channel_formats.global", "&f[&f%s&f] "),
"{channelTag} {worldname}{townytagoverride}{townycolor}{permprefix}{group} {townyprefix}{modplayername}{townypostfix}{permsuffix}&f:{msgcolour} {msg}", TAG_FORMATS_TOWN(
"# This is the format which will be used for GLOBAL chat/channels.", "tag_formats.town",
"# This is also the format used when you have modify_chat.enable: true, but use other plugins to handle chat."), "&f[&3%s&f] "),
CHANNEL_FORMATS_TOWN( TAG_FORMATS_NATION(
"channel_formats.town", "tag_formats.nation",
"{channelTag} {townycolor}{permprefix}{townyprefix}{playername}{townypostfix}{permsuffix}&f:{msgcolour} {msg}", "&f[&e%s&f] "),
"# TOWN channel types."), TAG_FORMATS_BOTH(
CHANNEL_FORMATS_NATION( "tag_formats.both",
"channel_formats.nation", "&f[&6%s&f|&3%s&f] ",
"{channelTag} {towntagoverride}{townycolor}{permprefix}{townyprefix}{playername}{townypostfix}{permsuffix}&f:{msgcolour} {msg}", "# First %s is the nation tag, second is the town tag.",
"# NATION channel types."), "# You may also use %t for the town tag and %n for the nation tag!"),
CHANNEL_FORMATS_ALLIANCE( COLOUR(
"channel_formats.alliance", "colour",
"{channelTag} {towntagoverride}{townycolor}{permprefix}{townyprefix}{playername}{townypostfix}{permsuffix}&f:{msgcolour} {msg}", "",
"# ALLIANCE channel types."), ""),
CHANNEL_FORMATS_DEFAULT( COLOUR_KING(
"channel_formats.default", "colour.king",
"{channelTag} {permprefix}{playername}{permsuffix}&f:{msgcolour} {msg}", "&6"),
"# DEFAULT channel types."), COLOUR_MAYOR(
TAG_FORMATS( "colour.mayor",
"tag_formats", "&b"),
"", COLOUR_RESIDENT(
""), "colour.resident",
TAG_FORMATS_WORLD( "&f"),
"tag_formats.world", COLOUR_NOMAD(
"&f[&f%s&f] "), "colour.nomad",
TAG_FORMATS_TOWN( "&f"),
"tag_formats.town", MODIFY_CHAT(
"&f[&3%s&f] "), "modify_chat",
TAG_FORMATS_NATION( "",
"tag_formats.nation", ""),
"&f[&e%s&f] "),
TAG_FORMATS_BOTH(
"tag_formats.both",
"&f[&6%s&f|&3%s&f] ",
"# 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!"),
COLOUR(
"colour",
"",
""),
COLOUR_KING(
"colour.king",
"&6"),
COLOUR_MAYOR(
"colour.mayor",
"&b"),
COLOUR_RESIDENT(
"colour.resident",
"&f"),
COLOUR_NOMAD(
"colour.nomad",
"&f"),
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.)");
WORLDS("worlds","","");
private final String Root; private final String Root;
private final String Default; private final String Default;
private String[] comments; private String[] comments;
private ChatConfigNodes(String root, String def, String... comments) { private ChatConfigNodes(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,341 +1,193 @@
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.channelTypes;
import com.palmergames.bukkit.config.CommentedConfiguration; import com.palmergames.bukkit.config.CommentedConfiguration;
import com.palmergames.bukkit.config.ConfigNodes; import com.palmergames.bukkit.config.ConfigNodes;
import com.palmergames.bukkit.towny.TownyUniverse;
import com.palmergames.bukkit.towny.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 org.bukkit.entity.Player;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.HashMap; import java.util.Objects;
import java.util.Locale;
import java.util.Map;
public class ChatSettings { public class ChatSettings {
private static Map<String, WorldFormat> worldFormatGroups = new HashMap<String, WorldFormat>(); 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.WORLDS.getRoot()) String version = Chat.getTownyChat().getDescription().getVersion();
setWorldDefaults(); // Per-worlds section. newChatConfig = new CommentedConfiguration(file.toPath());
else if (root.getRoot() == ChatConfigNodes.VERSION.getRoot()) newChatConfig.load();
setNewProperty(root.getRoot(), version);
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 setWorldDefaults() {
if (isPer_world()) {
for (TownyWorld world : TownyUniverse.getInstance().getTownyWorlds()) {
String path = "worlds." + world;
if (!chatConfig.contains(path )
|| !chatConfig.contains(path + ".global")
|| !chatConfig.contains(path + ".town")
|| !chatConfig.contains(path + ".nation")
|| !chatConfig.contains(path + ".alliance")
|| !chatConfig.contains(path + ".default")) {
newChatConfig.createSection(path);
ConfigurationSection worldsection = newChatConfig.getConfigurationSection(path);
worldsection.set("global", getOrDefault(path + ".global", ChatConfigNodes.CHANNEL_FORMATS_GLOBAL));
worldsection.set("town", getOrDefault(path + ".town", ChatConfigNodes.CHANNEL_FORMATS_TOWN));
worldsection.set("nation", getOrDefault(path + ".nation", ChatConfigNodes.CHANNEL_FORMATS_NATION));
worldsection.set("alliance", getOrDefault(path + ".alliance", ChatConfigNodes.CHANNEL_FORMATS_ALLIANCE));
worldsection.set("default", getOrDefault(path + ".default", ChatConfigNodes.CHANNEL_FORMATS_DEFAULT));
}
}
} else {
if (chatConfig.contains(ChatConfigNodes.WORLDS.getRoot()))
newChatConfig.set(ChatConfigNodes.WORLDS.getRoot(), chatConfig.get(ChatConfigNodes.WORLDS.getRoot()));
}
}
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 (Objects.equals(root.getRoot(), ChatConfigNodes.VERSION.getRoot()))
setNewProperty(root.getRoot(), version);
return Boolean.parseBoolean(chatConfig.getString(node.getRoot().toLowerCase(), node.getDefault())); else if (Objects.equals(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);
} }
/* public static String getTownTag() {
* Get ChannelType Formats return getString(ChatConfigNodes.TAG_FORMATS_TOWN);
*/ }
public static String getChannelFormat(Player player, channelTypes type) { public static String getNationTag() {
if (isPer_world()) { return getString(ChatConfigNodes.TAG_FORMATS_NATION);
String worldName = player.getWorld().getName().toLowerCase(Locale.ROOT); }
if (worldFormatGroups.containsKey(worldName)) {
String format = worldFormatGroups.get(worldName).getFormat(type);
if (format != null && !format.isEmpty())
return format;
}
}
return switch(type) {
case GLOBAL, PRIVATE -> getString(ChatConfigNodes.CHANNEL_FORMATS_GLOBAL);
case NATION -> getString(ChatConfigNodes.CHANNEL_FORMATS_NATION);
case TOWN -> getString(ChatConfigNodes.CHANNEL_FORMATS_TOWN);
case ALLIANCE -> getString(ChatConfigNodes.CHANNEL_FORMATS_ALLIANCE);
case DEFAULT -> getString(ChatConfigNodes.CHANNEL_FORMATS_DEFAULT);
};
}
public static void loadWorldFormats() { public static String getBothTag() {
if (!isPer_world()) return getString(ChatConfigNodes.TAG_FORMATS_BOTH);
return; }
for (TownyWorld world : TownyUniverse.getInstance().getTownyWorlds()) {
String worldName = world.getName();
String path = "worlds." + worldName;
if (chatConfig.contains(path)) {
ChatSettings.WorldFormat worldFormat = new ChatSettings().new WorldFormat(worldName);
worldFormat.setGLOBAL(getOrDefault(path + ".global", ChatConfigNodes.CHANNEL_FORMATS_GLOBAL));
worldFormat.setDEFAULT(getOrDefault(path + ".default", ChatConfigNodes.CHANNEL_FORMATS_DEFAULT));
worldFormat.setTOWN(getOrDefault(path + ".town", ChatConfigNodes.CHANNEL_FORMATS_TOWN));
worldFormat.setNATION(getOrDefault(path + ".nation", ChatConfigNodes.CHANNEL_FORMATS_NATION));
worldFormat.setALLIANCE(getOrDefault(path + ".alliance", ChatConfigNodes.CHANNEL_FORMATS_ALLIANCE));
addWorldFormat(worldFormat);
}
}
}
private static String getOrDefault(String configPath, ChatConfigNodes channelNode) {
return String.valueOf(chatConfig.get(configPath, channelNode.getDefault()));
}
private static void addWorldFormat(WorldFormat format) { /*
worldFormatGroups.put(format.getName().toLowerCase(Locale.ROOT), format); * Get Colour formats.
} */
public class WorldFormat { public static String getKingColour() {
return getString(ChatConfigNodes.COLOUR_KING);
}
/** public static String getMayorColour() {
* Constructor return getString(ChatConfigNodes.COLOUR_MAYOR);
* }
* @param name
*/
public WorldFormat(String name) {
super();
this.name = name.toLowerCase();
}
public String getFormat(channelTypes type) { public static String getResidentColour() {
return switch(type) { return getString(ChatConfigNodes.COLOUR_RESIDENT);
case GLOBAL, PRIVATE -> GLOBAL; }
case NATION -> NATION;
case TOWN -> TOWN;
case ALLIANCE -> ALLIANCE;
case DEFAULT -> DEFAULT;
};
}
private String name, GLOBAL, TOWN, NATION, ALLIANCE, DEFAULT; public static String getNomadColour() {
return getString(ChatConfigNodes.COLOUR_NOMAD);
/** }
* @return the name
*/
public String getName() {
return name;
}
/**
* @param GLOBAL the GLOBAL format to set
*/
public void setGLOBAL(String GLOBAL) {
this.GLOBAL = GLOBAL;
}
/** private static String getOrDefault(String configPath, ChatConfigNodes channelNode) {
* @param TOWN the TOWN format to set return String.valueOf(chatConfig.get(configPath, channelNode.getDefault()));
*/ }
public void setTOWN(String TOWN) {
this.TOWN = TOWN;
}
/**
* @param NATION the NATION format to set
*/
public void setNATION(String NATION) {
this.NATION = NATION;
}
/**
* @param ALLIANCE the ALLIANCE format to set
*/
public void setALLIANCE(String ALLIANCE) {
this.ALLIANCE = ALLIANCE;
}
/**
* @param DEFAULT the DEFAULT format to set
*/
public void setDEFAULT(String DEFAULT) {
this.DEFAULT = DEFAULT;
}
}
} }
@@ -1,115 +1,134 @@
package com.palmergames.bukkit.TownyChat.events; package com.palmergames.bukkit.TownyChat.events;
import com.palmergames.bukkit.TownyChat.channels.Channel; import com.github.milkdrinkers.colorparser.ColorParser;
import org.bukkit.entity.Player; import com.palmergames.bukkit.TownyChat.channels.Channel;
import org.bukkit.event.Event; import com.palmergames.bukkit.TownyChat.util.Adventure;
import org.bukkit.event.HandlerList; import io.papermc.paper.event.player.AsyncChatEvent;
import org.bukkit.event.player.AsyncPlayerChatEvent; import net.kyori.adventure.text.Component;
import org.bukkit.entity.Player;
import java.util.HashSet; import org.bukkit.event.Cancellable;
import java.util.Set; import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
/* import org.jetbrains.annotations.NotNull;
* Allows other plugins to hook into a chat message being accepted into any of the channels
* import java.util.Set;
* 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: * Allows other plugins to hook into a chat message being accepted into any of the channels
* *
*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
* general: *
* commands: [g] * ex:
* type: GLOBAL *
* hooked: true *Channels:
* channeltag: '&f[g]' * general:
* messagecolour: '&f' * commands: [g]
* permission: 'towny.chat.general' * type: GLOBAL
* range: '-1' * hooked: true
*/ * channeltag: '&f[g]'
public class AsyncChatHookEvent extends Event { * messagecolour: '&f'
private static final HandlerList handlers = new HandlerList(); * permission: 'towny.chat.general'
protected AsyncPlayerChatEvent event; * range: '-1'
protected boolean changed; */
protected Channel channel; public class AsyncChatHookEvent extends Event implements Cancellable {
protected Set<Player> recipients; private static final HandlerList HANDLER_LIST = new HandlerList();
private String legacyMessage;
public AsyncChatHookEvent(AsyncPlayerChatEvent event, Channel channel, boolean async) { private boolean cancelled;
super(async);
this.event = event; public static HandlerList getHandlerList() {
this.changed = false; return HANDLER_LIST;
this.channel = channel; }
this.recipients = new HashSet<>(event.getRecipients());
} @Override
public @NotNull HandlerList getHandlers() {
public Channel getChannel() { return HANDLER_LIST;
return channel; }
}
@Override
/* public boolean isCancelled() {
* Returns true if the hooked event was changed return this.cancelled;
*/ }
public boolean isChanged() {
return changed; @Override
} public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
/* }
* Informs Chat if the event was changed or not
*/ private final AsyncChatEvent event;
public void setChanged(boolean changed) { private final Channel channel;
this.changed = changed; private final Set<Player> recipients;
}
public AsyncChatHookEvent(AsyncChatEvent e, Channel channel, Set<Player> recipients) {
public AsyncPlayerChatEvent getAsyncPlayerChatEvent() { super(e.isAsynchronous());
return event; this.event = e;
} this.cancelled = e.isCancelled();
this.legacyMessage = Adventure.plainText().serialize(message());
public String getFormat() {
return event.getFormat(); this.channel = channel;
} this.recipients = recipients;
}
public String getMessage() {
return event.getMessage(); public AsyncChatEvent getEvent() {
} return event;
}
public Set<Player> getRecipients() {
return this.recipients; @Deprecated
} public String getFormat() {
return "undefined";
public boolean isCancelled() { }
return event.isCancelled();
} @Deprecated
public void setFormat(String format) {
public Player getPlayer() { }
return event.getPlayer();
} @Deprecated
public String getMessage() {
public void setRecipients(Set<Player> recipients) { return legacyMessage;
changed = true; }
this.recipients.clear();
this.recipients.addAll(recipients); @Deprecated
} public void setMessage(String message) {
legacyMessage = message;
public void setFormat(String format) { }
changed = true;
event.setFormat(format); public Component message() {
} return event.message();
}
public void setMessage(String message) {
changed = true; public void message(Component message) {
event.setMessage(message); event.message(message);
} }
public void setCancelled(boolean cancel) { public Set<Player> getRecipients() {
changed = (cancel); return this.recipients;
event.setCancelled(cancel); }
}
public void setRecipients(Set<Player> recipients) {
@Override this.recipients.clear();
public HandlerList getHandlers() { this.recipients.addAll(recipients);
return handlers; }
}
public Player getPlayer() {
public static HandlerList getHandlerList() { return event.getPlayer();
return handlers; }
}
} public Channel getChannel() {
return channel;
}
/*
* Returns true if the hooked event was changed
*/
@Deprecated(forRemoval = true)
public boolean isChanged() {
return true;
}
/*
* Informs Chat if the event was changed or not
*/
@Deprecated(forRemoval = true)
public void setChanged(boolean changed) {
}
}
@@ -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; }
} }
}
@@ -0,0 +1,100 @@
package com.palmergames.bukkit.TownyChat.handler;
import com.palmergames.bukkit.TownyChat.Chat;
import com.palmergames.bukkit.TownyChat.channels.Channel;
import com.palmergames.bukkit.TownyChat.channels.ChannelTypes;
import com.palmergames.bukkit.TownyChat.config.ChatSettings;
import com.palmergames.bukkit.TownyChat.util.Adventure;
import com.palmergames.bukkit.towny.TownyMessaging;
import com.palmergames.bukkit.towny.object.Translatable;
import io.papermc.paper.event.player.AsyncChatEvent;
import net.kyori.adventure.text.Component;
import org.bukkit.entity.Player;
import java.util.WeakHashMap;
public class ChatEventProcess {
public static void processChatEvent(AsyncChatEvent e, WeakHashMap<Player, String> directedChat) {
if (e.isCancelled())
return;
Player p = e.getPlayer();
// Save the message
final Component originalMessage = e.originalMessage();
final String originalMessageString = Adventure.plainText().serialize(originalMessage);
// Check if the player is muted by essentials
if (isEssentialsMuted(p)) {
e.setCancelled(true);
return;
}
final boolean userForcedGlobal = ChatSettings.isExclamationPoint() && originalMessageString.startsWith("!");
// If the player is using /g or /n to send their message
final boolean isDirectedChat = directedChat.containsKey(p);
// Get the user channel or select the first global channel
Channel channel = isDirectedChat ? Chat.getTownyChat().getChannelsHandler().getChannel(directedChat.get(p)) : Chat.getTownyChat().getPlayerChannel(p);
if (channel == null || !channel.hasSpeakPermission(p)) {
channel = Chat.getTownyChat().getChannelsHandler().getActiveChannel(p, ChannelTypes.GLOBAL, userForcedGlobal);
}
// No valid channel
if (channel == null) {
e.setCancelled(true);
if (isDirectedChat)
directedChat.remove(p);
return;
}
// If muted
if (isMutedOrSpam(e, channel, p)) {
e.setCancelled(true);
if (isDirectedChat)
directedChat.remove(p);
return;
}
// Post to chat
channel.chatProcess(e);
// Remove player from directed chat if using it
if (isDirectedChat && (!Chat.usingEssentialsDiscord || e.isCancelled())) {
directedChat.remove(p);
}
}
/**
* Check if the player is channel-muted or channel-spamming and cancel the
* {@link AsyncChatEvent} if this is the case.
*
* @param e {@link AsyncChatEvent} which has fired.
* @param channel {@link Channel} being spoken in to.
* @param p {@link Player} speaking.
* @return true if the chat is muted or spammed.
*/
private static boolean isMutedOrSpam(AsyncChatEvent e, Channel channel, Player p) {
if (channel.isMuted(p.getName())) {
TownyMessaging.sendErrorMsg(p, Translatable.of("tc_err_you_are_currently_muted_in_channel", channel.getName()));
return true;
}
return channel.isSpam(p);
}
/**
* Is this player Muted via Essentials?
*
* @param p {@link Player} speaking.
* @return true if muted by Essentials.
*/
private static boolean isEssentialsMuted(Player p) {
// Check if essentials has this player muted.
if (Chat.getTownyChat().isEssentialsMuted(p)) {
TownyMessaging.sendErrorMsg(p, Translatable.of("tc_err_unable_to_talk_essentials_mute"));
return true;
}
return false;
}
}
@@ -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);
} }
} }
} }
@@ -0,0 +1,76 @@
package com.palmergames.bukkit.TownyChat.listener;
import com.palmergames.bukkit.towny.object.Resident;
import io.papermc.paper.event.player.AsyncChatEvent;
import net.kyori.adventure.text.Component;
@Deprecated(forRemoval = true)
public class InternalTownyChatEvent {
private final AsyncChatEvent event;
private final Resident resident;
public InternalTownyChatEvent(AsyncChatEvent event, Resident resident) {
this.event = event;
this.resident = resident;
}
/**
* Get the resident associated with the chat event's talking player.
*
* @return resident associated with the chat event's talking player
*/
public Resident getResident() {
return resident;
}
/**
* @return the AsyncChatEvent
*/
public AsyncChatEvent getEvent() {
return event;
}
/**
* Convenience method for getting the chat event's format
*
* @return the chat event's format
*/
@Deprecated(forRemoval = true)
public String getFormat() {
return "";
}
/**
* Convenience method for setting the chat event's format.
*
* @param format the chat event's format
*/
@Deprecated(forRemoval = true)
public void setFormat(String format) {
}
/**
* Convenience method for getting the chat event's message
*
* @return the chat event's message
*/
public String getMessage() {
return "";
}
/**
* Get the event message
* @return event message
*/
public Component message() {
return event.message();
}
/**
* Set the event message
* @param message event message
*/
public void message(Component message) {
event.message(message);
}
}
@@ -1,56 +0,0 @@
package com.palmergames.bukkit.TownyChat.listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import com.palmergames.bukkit.towny.object.Resident;
public class LocalTownyChatEvent {
private AsyncPlayerChatEvent event;
private Resident resident;
public LocalTownyChatEvent(AsyncPlayerChatEvent event, Resident resident) {
this.event = event;
this.resident = resident;
}
/**
* Get the resident associated with the chat event's talking player.
* @return resident associated with the chat event's talking player
*/
public Resident getResident() {
return resident;
}
/**
*
* @return the PlayerChatEvent
*/
public AsyncPlayerChatEvent getEvent() {
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
* @return the chat event's format
*/
public String getFormat() {
return event.getFormat();
}
/**
* Convenience method for getting the chat event's message
* @return the chat event's message
*/
public String getMessage() {
return event.getMessage();
}
}
@@ -1,10 +1,9 @@
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.TownyChatFormatter;
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.config.ChatSettings; import com.palmergames.bukkit.TownyChat.config.ChatSettings;
import com.palmergames.bukkit.TownyChat.handler.ChatEventProcess;
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.object.Resident; import com.palmergames.bukkit.towny.object.Resident;
@@ -12,289 +11,136 @@ 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 net.kyori.adventure.text.Component;
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;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerQuitEvent;
import java.util.UnknownFormatConversionException;
import java.util.WeakHashMap; import java.util.WeakHashMap;
public class TownyChatPlayerListener implements Listener { public class TownyChatPlayerListener implements Listener {
private Chat plugin; public WeakHashMap<Player, String> directedChat = new WeakHashMap<>();
private final 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(PlayerJoinEvent e) {
final Player p = e.getPlayer();
plugin.getScheduler().runLater(event.getPlayer(), () -> loginPlayer(event.getPlayer()), 2L); plugin.getScheduler().runLater(p, () -> {
checkPlayerForOldMeta(p);
} refreshPlayerChannels(p);
private void loginPlayer(Player player) { Channel channel = plugin.getChannelsHandler().getDefaultChannel();
checkPlayerForOldMeta(player); if (channel != null && channel.hasSpeakPermission(p)) {
plugin.setPlayerChannel(p, channel);
refreshPlayerChannels(player); if (ChatSettings.getShowChannelMessageOnServerJoin())
TownyMessaging.sendMessage(p, Translatable.of("tc_you_are_now_talking_in_channel", channel.getName()));
}
}, 2L);
}
Channel channel = plugin.getChannelsHandler().getDefaultChannel(); @EventHandler(priority = EventPriority.LOW)
if (channel != null && channel.hasSpeakPermission(player)) { public void onPlayerQuit(PlayerQuitEvent e) {
plugin.setPlayerChannel(player, channel); refreshPlayerChannels(e.getPlayer());
if (ChatSettings.getShowChannelMessageOnServerJoin()) }
TownyMessaging.sendMessage(player, Translatable.of("tc_you_are_now_talking_in_channel", channel.getName()));
}
}
@EventHandler(priority = EventPriority.LOW) private void refreshPlayerChannels(Player p) {
public void onPlayerQuit(final PlayerQuitEvent event) { plugin.getChannelsHandler().getAllChannels().values().forEach(channel -> channel.forgetPlayer(p));
refreshPlayerChannels(event.getPlayer()); }
}
private void refreshPlayerChannels(Player player) {
plugin.getChannelsHandler().getAllChannels().values().stream().forEach(channel -> channel.forgetPlayer(player));
}
@EventHandler(ignoreCancelled = true)
public void onPlayerChat(AsyncPlayerChatEvent event) {
Player player = event.getPlayer();
// Check if the message contains colour codes we need to remove or parse. @EventHandler(priority = EventPriority.HIGH)
testColourCodes(event, player); public void onPlayerChat(AsyncChatEvent e) {
ChatEventProcess.processChatEvent(e, directedChat);
}
// Check if essentials has this player muted. /**
if (!isEssentialsMuted(player)) { * Remove colour tags that a player doesn't not have permission for,
* and colour messages if the player is allowed.
boolean forceGlobal = ChatSettings.isExclamationPoint() ? event.getMessage().startsWith("!") : false; *
* @param event {@link AsyncChatEvent} which has been fired.
* @param player {@link Player} which has spoken.
*/
private void testColourCodes(AsyncChatEvent event, Player player) {
Component message = event.message();
String messageString = message.toString();
/* if ((messageString.contains("&L") || messageString.contains("&l"))
* If this was directed chat send it via the relevant channel && !player.hasPermission("townychat.chat.format.bold"))
*/ event.message(Component.text(messageString.replaceAll("&L", "").replaceAll("&l", "")));
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;
}
}
/* if ((messageString.contains("&O") || messageString.contains("&o"))
* We found no channels available so modify the chat (if enabled) and exit. && !player.hasPermission("townychat.chat.format.italic"))
*/ event.message(Component.text(messageString.replaceAll("&O", "").replaceAll("&o", "")));
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 = ChatSettings.getChannelFormat(player, channelTypes.GLOBAL).replace("{channelTag}", "").replace("{msgcolour}", "");
// format is left to store the original non-PAPI-parsed chat format. if ((messageString.contains("&K") || messageString.contains("&k"))
String newFormat = format; && !player.hasPermission("townychat.chat.format.magic"))
event.message(Component.text(messageString.replaceAll("&K", "").replaceAll("&k", "")));
// Parse any PAPI placeholders. if ((messageString.contains("&N") || messageString.contains("&n"))
if (Chat.usingPlaceholderAPI) && !player.hasPermission("townychat.chat.format.underlined"))
newFormat = PlaceholderAPI.setPlaceholders(player, format); event.message(Component.text(messageString.replaceAll("&N", "").replaceAll("&n", "")));
// Attempt to apply the new format. if ((messageString.contains("&M") || messageString.contains("&m"))
catchFormatConversionException(event, format, newFormat); && !player.hasPermission("townychat.chat.format.strike"))
event.message(Component.text(messageString.replaceAll("&M", "").replaceAll("&m", "")));
// Fire the LocalTownyChatEvent. if ((messageString.contains("&R") || messageString.contains("&r"))
LocalTownyChatEvent chatEvent = new LocalTownyChatEvent(event, resident); && !player.hasPermission("townychat.chat.format.reset"))
event.message(Component.text(messageString.replaceAll("&R", "").replaceAll("&r", "")));
// Format the chat line, replacing the TownyChat chat tags. if (player.hasPermission("townychat.chat.color"))
newFormat = TownyChatFormatter.getChatFormat(chatEvent); event.message(Component.text(Colors.translateColorCodes(messageString)));
}
// Attempt to apply the new format. // From TownyChat 0.84-0.95 the symbol used to separate the channels in the meta
catchFormatConversionException(event, format, newFormat); // was not good for non-unicode-using mysql servers.
private void checkPlayerForOldMeta(Player player) {
Resident resident = TownyAPI.getInstance().getResident(player);
if (resident != null && playerHasTCMeta(resident))
checkIfMetaContainsOldSplitter(resident);
}
// Set the format based on the global channelformat, with channeltag and msgcolour removed. private boolean playerHasTCMeta(Resident resident) {
event.setFormat(newFormat); StringDataField icsdf = new StringDataField("townychat_ignoredChannels", "", "Ignored TownyChat Channels");
} StringDataField socsdf = new StringDataField("townychat_soundOffChannels", "", "TownyChat Channels with Sound Toggle Off");
} return MetaDataUtil.hasMeta(resident, icsdf) || MetaDataUtil.hasMeta(resident, socsdf);
}
/** private void checkIfMetaContainsOldSplitter(Resident resident) {
* Remove colour tags that a player doesn't not have permission for, StringDataField icsdf = new StringDataField("townychat_ignoredChannels", "", "Ignored TownyChat Channels");
* and colour messages if the player is allowed. if (MetaDataUtil.hasMeta(resident, icsdf)) {
* String meta = MetaDataUtil.getString(resident, icsdf);
* @param event {@link AsyncPlayerChatEvent} which has been fired. if (meta.contains("\uFF0c ")) {
* @param player {@link Player} which has spoken. meta = replaceSymbol(meta);
*/ MetaDataUtil.setString(resident, icsdf, meta, true);
private void testColourCodes(AsyncPlayerChatEvent event, Player player) { }
if ((event.getMessage().contains("&L") || event.getMessage().contains("&l")) }
&& !player.hasPermission("townychat.chat.format.bold")) StringDataField socsdf = new StringDataField("townychat_soundOffChannels", "", "TownyChat Channels with Sound Toggle Off");
event.setMessage(event.getMessage().replaceAll("&L", "").replaceAll("&l", "")); if (MetaDataUtil.hasMeta(resident, socsdf)) {
String meta = MetaDataUtil.getString(resident, socsdf);
if (meta.contains("\uFF0c ")) {
meta = replaceSymbol(meta);
MetaDataUtil.setString(resident, socsdf, meta, true);
}
}
}
if ((event.getMessage().contains("&O") || event.getMessage().contains("&o")) private String replaceSymbol(String meta) {
&& !player.hasPermission("townychat.chat.format.italic")) char[] charray = meta.toCharArray();
event.setMessage(event.getMessage().replaceAll("&O", "").replaceAll("&o", "")); for (int i = 0; i < meta.length(); i++) {
char n = meta.charAt(i);
if (n == '\uFF0c')
charray[i] = ',';
}
return new String(charray);
}
if ((event.getMessage().contains("&K") || event.getMessage().contains("&k"))
&& !player.hasPermission("townychat.chat.format.magic"))
event.setMessage(event.getMessage().replaceAll("&K", "").replaceAll("&k", ""));
if ((event.getMessage().contains("&N") || event.getMessage().contains("&n"))
&& !player.hasPermission("townychat.chat.format.underlined"))
event.setMessage(event.getMessage().replaceAll("&N", "").replaceAll("&n", ""));
if ((event.getMessage().contains("&M") || event.getMessage().contains("&m"))
&& !player.hasPermission("townychat.chat.format.strike"))
event.setMessage(event.getMessage().replaceAll("&M", "").replaceAll("&m", ""));
if ((event.getMessage().contains("&R") || event.getMessage().contains("&r"))
&&!player.hasPermission("townychat.chat.format.reset"))
event.setMessage(event.getMessage().replaceAll("&R", "").replaceAll("&r", ""));
if (player.hasPermission("townychat.chat.color"))
event.setMessage(Colors.translateColorCodes(event.getMessage()));
}
/**
* Is this player Muted via Essentials?
*
* @param player {@link Player} speaking.
* @return true if muted by Essentials.
*/
private boolean isEssentialsMuted(Player player) {
// Check if essentials has this player muted.
if (plugin.isEssentialsMuted(player)) {
TownyMessaging.sendErrorMsg(player, Translatable.of("tc_err_unable_to_talk_essentials_mute"));
return true;
}
return false;
}
/**
* Check if the player is channel-muted or channel-spamming and cancel the
* {@link AsyncPlayerChatEvent} if this is the case.
*
* @param event {@link AsyncPlayerChatEvent} which has fired.
* @param channel {@link Channel} being spoken in to.
* @param player {@link Player} speaking.
* @return true if the chat is muted or spammed.
*/
private boolean isMutedOrSpam(AsyncPlayerChatEvent event, Channel channel, Player player) {
if (channel.isMuted(player.getName())) {
TownyMessaging.sendErrorMsg(player, Translatable.of("tc_err_you_are_currently_muted_in_channel", channel.getName()));
event.setCancelled(true);
return true;
}
if (channel.isSpam(player)) {
event.setCancelled(true);
return true;
}
return false;
}
// 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.
private void checkPlayerForOldMeta(Player player) {
Resident resident = TownyAPI.getInstance().getResident(player);
if (resident != null && playerHasTCMeta(resident))
checkIfMetaContainsOldSplitter(resident);
}
private boolean playerHasTCMeta(Resident resident) {
StringDataField icsdf = new StringDataField("townychat_ignoredChannels", "", "Ignored TownyChat Channels");
StringDataField socsdf = new StringDataField("townychat_soundOffChannels", "", "TownyChat Channels with Sound Toggle Off");
return MetaDataUtil.hasMeta(resident, icsdf) || MetaDataUtil.hasMeta(resident, socsdf);
}
private void checkIfMetaContainsOldSplitter(Resident resident) {
StringDataField icsdf = new StringDataField("townychat_ignoredChannels", "", "Ignored TownyChat Channels");
if (MetaDataUtil.hasMeta(resident, icsdf)) {
String meta = MetaDataUtil.getString(resident, icsdf);
if (meta.contains("\uFF0c ")) {
meta = replaceSymbol(meta);
MetaDataUtil.setString(resident, icsdf, meta, true);
}
}
StringDataField socsdf = new StringDataField("townychat_soundOffChannels", "", "TownyChat Channels with Sound Toggle Off");
if (MetaDataUtil.hasMeta(resident, socsdf)) {
String meta = MetaDataUtil.getString(resident, socsdf);
if (meta.contains("\uFF0c ")) {
meta = replaceSymbol(meta);
MetaDataUtil.setString(resident, socsdf, meta, true);
}
}
}
private String replaceSymbol(String meta) {
char[] charray = meta.toCharArray();
for (int i = 0; i < meta.length(); i++) {
char n = meta.charAt(i);
if (n == '\uFF0c')
charray[i] = ',';
}
return new String(charray);
}
private void catchFormatConversionException(AsyncPlayerChatEvent event, String format, String newFormat) {
try {
event.setFormat(newFormat);
} catch (UnknownFormatConversionException e) {
// 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
// cannot handle.
boolean percentSymbol = format.contains("%" + e.getConversion());
String errmsg = "TownyChat tried to apply a chat format that is not allowed: '" +
newFormat + "', because of the " + e.getConversion() + " symbol" +
(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.");
Chat.getTownyChat().getLogger().severe(errmsg);
if (percentSymbol)
// Attempt to remove the unparsed placeholder and send this right back.
catchFormatConversionException(event, format, purgePAPI(newFormat, "%" + e.getConversion()));
else
// Just let the chat go, this results in an error in the log, and TownyChat not being able to format chat.
event.setFormat(format);
}
}
private String purgePAPI(String format, String startOfPlaceholder) {
return format.replaceAll(startOfPlaceholder + ".*%", "");
}
} }
@@ -1,44 +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;
} }
ChatSettings.loadWorldFormats(); plugin.getLogger().info("-******* TownyChat enabled *******-");
plugin.getLogger().info("-******* TownyChat enabled *******-"); plugin.registerPermissions();
plugin.registerPermissions(); plugin.registerEvents();
plugin.registerEvents(); }
}
}
}
} }
@@ -0,0 +1,17 @@
package com.palmergames.bukkit.TownyChat.util;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
public class Adventure {
private static final PlainTextComponentSerializer plainText = PlainTextComponentSerializer.plainText();
private static final MiniMessage miniMessage = MiniMessage.miniMessage();
public static PlainTextComponentSerializer plainText() {
return plainText;
}
public static MiniMessage miniMessage() {
return miniMessage;
}
}
@@ -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 +0,0 @@
package com.palmergames.bukkit.TownyChat.util;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.regex.Matcher;
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.
*
* Credits to:
* - http://stackoverflow.com/questions/1326682/java-replacing-multiple-different-substring-in-a-string-at-once-or-in-the-most-e/1326962#1326962
*
* Improved in v 2.0 to use Java 8's Function.
*
* @author Chris H (Shade) 1.0, LlmDl 2.0
* @version 2.0
*/
public class StringReplaceManager<E> {
private List<Pattern> replacementPatterns = new ArrayList<Pattern>();
private List<TownyChatReplacer> replacements = new ArrayList<TownyChatReplacer>();
public boolean registerReplacer(String chatSlug, Function<LocalTownyChatEvent, String> replacement) {
Pattern pattern = Pattern.compile(Pattern.quote(chatSlug));
replacementPatterns.add(pattern);
replacements.add(new TownyChatReplacer(replacement));
return true;
}
public String replaceAll(String format, LocalTownyChatEvent e) {
String out = format;
for (int i = 0; i < replacementPatterns.size(); i++) {
Matcher matcher = replacementPatterns.get(i).matcher(out);
TownyChatReplacer replacer = replacements.get(i);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
if (replacer == null) {
matcher.appendReplacement(sb, e.toString());
} else {
try {
String replacement = Matcher.quoteReplacement(replacer.getWith(e));
matcher.appendReplacement(sb, replacement);
} catch (Exception exception) {
continue;
}
}
}
matcher.appendTail(sb);
out = sb.toString();
}
return out;
}
}
@@ -0,0 +1,221 @@
package com.palmergames.bukkit.TownyChat.util;
import com.github.milkdrinkers.colorparser.ColorParser;
import com.palmergames.bukkit.TownyChat.config.ChatSettings;
import com.palmergames.bukkit.TownyChat.listener.InternalTownyChatEvent;
import com.palmergames.bukkit.towny.TownyAPI;
import com.palmergames.bukkit.towny.TownySettings;
import com.palmergames.bukkit.towny.TownyUniverse;
import com.palmergames.bukkit.towny.object.Government;
import com.palmergames.bukkit.towny.object.Nation;
import com.palmergames.bukkit.towny.object.Resident;
import com.palmergames.bukkit.towny.object.Town;
import com.palmergames.util.StringMgmt;
import net.kyori.adventure.text.minimessage.tag.Tag;
import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
public class TownyChatFormatter {
public static @NotNull TagResolver parser(InternalTownyChatEvent e) {
final Player p = e.getEvent().getPlayer();
final Resident res = e.getResident();
return TagResolver.resolver(
TagResolver.resolver("worldname", Tag.inserting(ColorParser.of(getWorldTag(e)).parseLegacy().build())),
TagResolver.resolver("town", Tag.inserting(ColorParser.of(getTownName(res)).parseLegacy().build())),
TagResolver.resolver("townformatted", Tag.inserting(ColorParser.of(formatTownTag(res, false, true)).parseLegacy().build())),
TagResolver.resolver("towntag", Tag.inserting(ColorParser.of(formatTownTag(res, false, false)).parseLegacy().build())),
TagResolver.resolver("towntagoverride", Tag.inserting(ColorParser.of(formatTownTag(res, true, false)).parseLegacy().build())),
TagResolver.resolver("nation", Tag.inserting(ColorParser.of(getNationName(res)).parseLegacy().build())),
TagResolver.resolver("nationformatted", Tag.inserting(ColorParser.of(formatNationTag(res, false, true)).parseLegacy().build())),
TagResolver.resolver("nationtag", Tag.inserting(ColorParser.of(formatNationTag(res, false, false)).parseLegacy().build())),
TagResolver.resolver("nationtagoverride", Tag.inserting(ColorParser.of(formatNationTag(res, true, false)).parseLegacy().build())),
TagResolver.resolver("townytag", Tag.inserting(ColorParser.of(formatTownyTag(res, false, true)).parseLegacy().build())),
TagResolver.resolver("townyformatted", Tag.inserting(ColorParser.of(formatTownyTag(res, false, false)).parseLegacy().build())),
TagResolver.resolver("townytagoverride", Tag.inserting(ColorParser.of(formatTownyTag(res, true, false)).parseLegacy().build())),
TagResolver.resolver("title", Tag.inserting(ColorParser.of(getPrefix(res, true)).parseLegacy().build())),
TagResolver.resolver("surname", Tag.inserting(ColorParser.of(getSuffix(res, false)).parseLegacy().build())),
TagResolver.resolver("townynameprefix", Tag.inserting(ColorParser.of(getNamePrefix(res)).parseLegacy().build())),
TagResolver.resolver("townynamepostfix", Tag.inserting(ColorParser.of(getNamePostfix(res)).parseLegacy().build())),
TagResolver.resolver("townyprefix", Tag.inserting(ColorParser.of(getPrefix(res, false)).parseLegacy().build())),
TagResolver.resolver("townypostfix", Tag.inserting(ColorParser.of(getSuffix(res, false)).parseLegacy().build())),
TagResolver.resolver("townycolor", Tag.inserting(ColorParser.of(getTownyColour(res)).parseLegacy().build())),
TagResolver.resolver("group", Tag.inserting(ColorParser.of(getVaultGroup(p)).parseLegacy().build())),
TagResolver.resolver("permprefix", Tag.inserting(ColorParser.of(getVaultPrefixSuffix(res, "prefix")).parseLegacy().build())),
TagResolver.resolver("permsuffix", Tag.inserting(ColorParser.of(getVaultPrefixSuffix(res, "suffix")).parseLegacy().build())),
TagResolver.resolver("permuserprefix", Tag.inserting(ColorParser.of(getVaultPrefixSuffix(res, "userprefix")).parseLegacy().build())),
TagResolver.resolver("permusersuffix", Tag.inserting(ColorParser.of(getVaultPrefixSuffix(res, "usersuffix")).parseLegacy().build())),
TagResolver.resolver("permgroupprefix", Tag.inserting(ColorParser.of(getVaultPrefixSuffix(res, "groupprefix")).parseLegacy().build())),
TagResolver.resolver("permgroupsuffix", Tag.inserting(ColorParser.of(getVaultPrefixSuffix(res, "groupsuffix")).parseLegacy().build())),
TagResolver.resolver("playername", Tag.inserting(ColorParser.of(p.getName()).parseLegacy().build())),
TagResolver.resolver("modplayername", Tag.inserting(ColorParser.of(Adventure.plainText().serialize(p.displayName())).parseLegacy().build())),
TagResolver.resolver("primaryresidentrank", Tag.inserting(ColorParser.of(getPrimaryRankPrefix(res)).parseLegacy().build()))
);
}
public static String getWorldTag(InternalTownyChatEvent event) {
return String.format(ChatSettings.getWorldTag(), event.getEvent().getPlayer().getWorld().getName());
}
public static String getTownName(Resident resident) {
return resident.getTownOrNull() != null ? resident.getTownOrNull().getName() : "";
}
public static String getNationName(Resident resident) {
return resident.getNationOrNull() != null ? resident.getNationOrNull().getName() : "";
}
/**
* @param resident the resident
* @param override use full names if no tag is present
* @param full Only use full names (no tags).
* @return string containing the correctly formatted nation/town data
*/
public static String formatTownyTag(Resident resident, Boolean override, Boolean full) {
Town town = TownyAPI.getInstance().getResidentTownOrNull(resident);
if (town == null)
return "";
String townTag = getTag(town);
Nation nation = TownyAPI.getInstance().getResidentNationOrNull(resident);
String nationTag = nation != null ? getTag(nation) : "";
String nTag = "", tTag = "";
// Force use of full names only
if (full) {
nationTag = "";
townTag = "";
}
// Load town tags/names
if (townTag != null && !townTag.isEmpty())
tTag = townTag;
else if (override || full)
tTag = getName(town);
// Load the nation tags/names
if ((nationTag != null) && !nationTag.isEmpty())
nTag = nationTag;
else if (nation != null && (override || full))
nTag = getName(nation);
// Output depending on what tags are present
if ((!tTag.isEmpty()) && (!nTag.isEmpty())) {
if (ChatSettings.getBothTag().contains("%t") || ChatSettings.getBothTag().contains("%n")) {
// Then it contains %s & %s
// Small suttle change so that an issue is solved, it is documented in the config.
// But only after addition of this. (v0.50)
return ChatSettings.getBothTag().replace("%t", tTag).replace("%n", nTag);
} else {
return String.format(ChatSettings.getBothTag(), nTag, tTag);
}
}
if (!nTag.isEmpty()) {
return String.format(ChatSettings.getNationTag(), nTag);
}
if (!tTag.isEmpty()) {
return String.format(ChatSettings.getTownTag(), tTag);
}
return "";
}
public static String formatTownTag(Resident resident, Boolean override, Boolean full) {
Town town = TownyAPI.getInstance().getResidentTownOrNull(resident);
if (town == null)
return "";
if (full)
return String.format(ChatSettings.getTownTag(), getName(town));
else if (town.hasTag())
return String.format(ChatSettings.getTownTag(), getTag(town));
else if (override)
return String.format(ChatSettings.getTownTag(), getName(town));
return "";
}
public static String formatNationTag(Resident res, Boolean override, Boolean full) {
Nation nation = TownyAPI.getInstance().getResidentNationOrNull(res);
if (nation == null)
return "";
if (full)
return String.format(ChatSettings.getNationTag(), getName(nation));
else if (nation.hasTag())
return String.format(ChatSettings.getNationTag(), getTag(nation));
else if (override)
return String.format(ChatSettings.getNationTag(), getName(nation));
return "";
}
public static String getNamePrefix(Resident res) {
if (res == null)
return "";
if (res.isKing())
return TownySettings.getKingPrefix(res);
else if (res.isMayor())
return TownySettings.getMayorPrefix(res);
return "";
}
public static String getNamePostfix(Resident res) {
if (res == null)
return "";
if (res.isKing())
return TownySettings.getKingPostfix(res);
else if (res.isMayor())
return TownySettings.getMayorPostfix(res);
return "";
}
public static String getPrimaryRankPrefix(Resident res) {
if (res == null)
return "";
String rank = res.getPrimaryRankPrefix();
return rank.isEmpty() ? "" : rank + " ";
}
private static String getName(Government gov) {
return StringMgmt.remUnderscore(gov.getName());
}
private static String getTag(Government gov) {
return gov.getTag();
}
public static String getPrefix(Resident res, boolean isBlank) {
return res.hasTitle() ? res.getTitle() + " " : isBlank ? "" : getNamePrefix(res);
}
public static String getSuffix(Resident res, boolean isBlank) {
return res.hasSurname() ? " " + res.getSurname() : isBlank ? "" : getNamePostfix(res);
}
public static String getTownyColour(Resident res) {
return !res.hasTown()
? ChatSettings.getNomadColour()
: res.isMayor() ? (res.isKing() ? ChatSettings.getKingColour() : ChatSettings.getMayorColour()) : ChatSettings.getResidentColour();
}
public static String getVaultGroup(Player p) {
return TownyUniverse.getInstance().getPermissionSource().getPlayerGroup(p);
}
public static String getVaultPrefixSuffix(Resident res, String slug) {
return TownyUniverse.getInstance().getPermissionSource().getPrefixSuffix(res, slug);
}
}