Compare commits
No commits in common. "feature-command.nodes" and "master" have entirely different histories.
feature-co
...
master
117 changed files with 5282 additions and 5838 deletions
1
.gitignore
vendored
1
.gitignore
vendored
|
@ -225,4 +225,3 @@ dependency-reduced-pom.xml
|
|||
|
||||
TBMC/
|
||||
/.apt_generated/
|
||||
.attach_pid*
|
||||
|
|
|
@ -35,11 +35,11 @@
|
|||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.8.1</version>
|
||||
<version>3.8.0</version>
|
||||
<configuration>
|
||||
<proc>none</proc>
|
||||
<source>17</source>
|
||||
<target>17</target>
|
||||
<compilerArgument>-proc:none</compilerArgument>
|
||||
<source>8</source>
|
||||
<target>8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
|
|
1
Chroma-Core/lombok.config
Normal file
1
Chroma-Core/lombok.config
Normal file
|
@ -0,0 +1 @@
|
|||
lombok.var.flagUsage = ALLOW
|
|
@ -27,65 +27,31 @@
|
|||
</resources>
|
||||
<finalName>Chroma-Core</finalName>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.jetbrains.kotlin</groupId>
|
||||
<artifactId>kotlin-maven-plugin</artifactId>
|
||||
<version>${kotlin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>compile</id>
|
||||
<phase>process-sources</phase>
|
||||
<goals>
|
||||
<goal>compile</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<sourceDirs>
|
||||
<sourceDir>${project.basedir}/src/main/kotlin</sourceDir>
|
||||
<sourceDir>${project.basedir}/src/main/java</sourceDir>
|
||||
</sourceDirs>
|
||||
</configuration>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>test-compile</id>
|
||||
<goals>
|
||||
<goal>test-compile</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<sourceDirs>
|
||||
<sourceDir>${project.basedir}/src/test/kotlin</sourceDir>
|
||||
<sourceDir>${project.basedir}/src/test/java</sourceDir>
|
||||
</sourceDirs>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-shade-plugin</artifactId>
|
||||
<version>3.4.1</version>
|
||||
<version>3.2.1</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>shade</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<artifactSet>
|
||||
<includes>
|
||||
<configuration>
|
||||
<artifactSet>
|
||||
<includes>
|
||||
<include>me.lucko:commodore</include>
|
||||
<include>org.jetbrains.kotlin:kotlin-stdlib</include>
|
||||
<include>com.github.shynixn.mccoroutine:mccoroutine-bukkit-api</include>
|
||||
<include>com.github.shynixn.mccoroutine:mccoroutine-bukkit-core</include>
|
||||
<include>org.javatuples:javatuples</include>
|
||||
</includes>
|
||||
</artifactSet>
|
||||
<relocations>
|
||||
<relocation>
|
||||
<pattern>me.lucko.commodore</pattern>
|
||||
<!-- vvv Replace with the package of your plugin vvv -->
|
||||
<shadedPattern>buttondevteam.core.commodore</shadedPattern>
|
||||
</relocation>
|
||||
</relocations>
|
||||
</configuration>
|
||||
</artifactSet>
|
||||
<relocations>
|
||||
<relocation>
|
||||
<pattern>me.lucko.commodore</pattern>
|
||||
<!-- vvv Replace with the package of your plugin vvv -->
|
||||
<shadedPattern>buttondevteam.core.commodore</shadedPattern>
|
||||
</relocation>
|
||||
</relocations>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
@ -138,8 +104,8 @@
|
|||
</build>
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>papermc</id>
|
||||
<url>https://repo.papermc.io/repository/maven-public/</url>
|
||||
<id>spigot-repo</id>
|
||||
<url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
|
||||
</repository>
|
||||
<repository>
|
||||
<id>jitpack.io</id>
|
||||
|
@ -170,9 +136,9 @@
|
|||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.papermc.paper</groupId>
|
||||
<artifactId>paper-api</artifactId>
|
||||
<version>1.19-R0.1-SNAPSHOT</version>
|
||||
<groupId>org.spigotmc</groupId>
|
||||
<artifactId>spigot-api</artifactId>
|
||||
<version>1.12.2-R0.1-SNAPSHOT</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
|
@ -226,40 +192,13 @@
|
|||
<dependency>
|
||||
<groupId>me.lucko</groupId>
|
||||
<artifactId>commodore</artifactId>
|
||||
<version>2.2</version>
|
||||
<version>1.11</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jetbrains.kotlin</groupId>
|
||||
<artifactId>kotlin-stdlib</artifactId>
|
||||
<version>${kotlin.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jetbrains.kotlinx</groupId>
|
||||
<artifactId>kotlinx-coroutines-core</artifactId>
|
||||
<version>1.6.4</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.github.shynixn.mccoroutine</groupId>
|
||||
<artifactId>mccoroutine-bukkit-api</artifactId>
|
||||
<version>2.11.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.github.shynixn.mccoroutine</groupId>
|
||||
<artifactId>mccoroutine-bukkit-core</artifactId>
|
||||
<version>2.11.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.github.seeseemelk</groupId>
|
||||
<artifactId>MockBukkit-v1.19</artifactId>
|
||||
<version>2.29.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/org.jetbrains.kotlin/kotlin-test -->
|
||||
<dependency>
|
||||
<groupId>org.jetbrains.kotlin</groupId>
|
||||
<artifactId>kotlin-test-junit</artifactId>
|
||||
<version>1.9.0</version>
|
||||
<groupId>org.javatuples</groupId>
|
||||
<artifactId>javatuples</artifactId>
|
||||
<version>1.2</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<organization>
|
||||
|
@ -277,8 +216,7 @@
|
|||
<!-- github server corresponds to entry in ~/.m2/settings.xml -->
|
||||
<github.global.server>github</github.global.server>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<noprefix.version>2.0.0</noprefix.version>
|
||||
<kotlin.version>1.8.20</kotlin.version>
|
||||
<noprefix.version>1.0.1</noprefix.version>
|
||||
</properties>
|
||||
<scm>
|
||||
<url>https://github.com/TBMCPlugins/mvn-repo</url>
|
||||
|
|
|
@ -0,0 +1,38 @@
|
|||
package buttondevteam.core;
|
||||
|
||||
import buttondevteam.lib.architecture.ButtonPlugin;
|
||||
import buttondevteam.lib.chat.Command2;
|
||||
import buttondevteam.lib.chat.CommandClass;
|
||||
import buttondevteam.lib.chat.ICommand2MC;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Optional;
|
||||
|
||||
@CommandClass
|
||||
public class ChromaCommand extends ICommand2MC {
|
||||
public ChromaCommand() {
|
||||
getManager().addParamConverter(ButtonPlugin.class, name ->
|
||||
(ButtonPlugin) Optional.ofNullable(Bukkit.getPluginManager().getPlugin(name))
|
||||
.filter(plugin -> plugin instanceof ButtonPlugin).orElse(null),
|
||||
"No Chroma plugin found by that name.", () -> Arrays.stream(Bukkit.getPluginManager().getPlugins())
|
||||
.filter(plugin -> plugin instanceof ButtonPlugin).map(Plugin::getName)::iterator);
|
||||
}
|
||||
|
||||
@Command2.Subcommand
|
||||
public void reload(CommandSender sender, @Command2.OptionalArg ButtonPlugin plugin) {
|
||||
if (plugin == null)
|
||||
plugin = MainPlugin.Instance;
|
||||
if (plugin.tryReloadConfig())
|
||||
sender.sendMessage("§b" + plugin.getName() + " config reloaded.");
|
||||
else
|
||||
sender.sendMessage("§cFailed to reload config. Check console.");
|
||||
}
|
||||
|
||||
@Command2.Subcommand
|
||||
public void def(CommandSender sender) {
|
||||
sender.sendMessage(ButtonPlugin.getCommand2MC().getCommandsText());
|
||||
}
|
||||
}
|
|
@ -1,47 +0,0 @@
|
|||
package buttondevteam.core
|
||||
|
||||
import buttondevteam.lib.architecture.ButtonPlugin
|
||||
import buttondevteam.lib.architecture.ButtonPlugin.Companion.command2MC
|
||||
import buttondevteam.lib.chat.Command2.OptionalArg
|
||||
import buttondevteam.lib.chat.Command2.Subcommand
|
||||
import buttondevteam.lib.chat.Command2MCSender
|
||||
import buttondevteam.lib.chat.CommandClass
|
||||
import buttondevteam.lib.chat.ICommand2MC
|
||||
import org.bukkit.Bukkit
|
||||
import org.bukkit.ChatColor
|
||||
import org.bukkit.command.CommandSender
|
||||
import java.util.*
|
||||
|
||||
@CommandClass
|
||||
class ChromaCommand : ICommand2MC() {
|
||||
init {
|
||||
manager.addParamConverter(
|
||||
ButtonPlugin::class.java, { name ->
|
||||
Bukkit.getPluginManager().getPlugin(name)
|
||||
?.let { if (it is ButtonPlugin) it else null }
|
||||
},
|
||||
"No Chroma plugin found by that name."
|
||||
) {
|
||||
Iterable {
|
||||
Arrays.stream(Bukkit.getPluginManager().plugins)
|
||||
.filter { it is ButtonPlugin }.map { it.name }.iterator()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Subcommand
|
||||
fun reload(sender: CommandSender, @OptionalArg plugin: ButtonPlugin?) {
|
||||
val pl = plugin ?: this.plugin
|
||||
if (pl.tryReloadConfig())
|
||||
sender.sendMessage("${ChatColor.AQUA}${pl.name} config reloaded.")
|
||||
else
|
||||
sender.sendMessage("${ChatColor.RED}Failed to reload config. Check console.")
|
||||
}
|
||||
|
||||
@Subcommand
|
||||
override fun def(sender: Command2MCSender): Boolean {
|
||||
sender.sendMessage("${ChatColor.GOLD}---- Commands ----")
|
||||
sender.sendMessage(command2MC.getCommandList(sender))
|
||||
return true
|
||||
}
|
||||
}
|
|
@ -0,0 +1,102 @@
|
|||
package buttondevteam.core;
|
||||
|
||||
import buttondevteam.lib.TBMCCoreAPI;
|
||||
import buttondevteam.lib.architecture.ButtonPlugin;
|
||||
import buttondevteam.lib.architecture.Component;
|
||||
import buttondevteam.lib.chat.Command2;
|
||||
import buttondevteam.lib.chat.Command2.Subcommand;
|
||||
import buttondevteam.lib.chat.CommandClass;
|
||||
import buttondevteam.lib.chat.CustomTabCompleteMethod;
|
||||
import buttondevteam.lib.chat.ICommand2MC;
|
||||
import lombok.val;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
@CommandClass(modOnly = true, helpText = {
|
||||
"Component command",
|
||||
"Can be used to enable/disable/list components"
|
||||
})
|
||||
public class ComponentCommand extends ICommand2MC {
|
||||
public ComponentCommand() {
|
||||
getManager().addParamConverter(Plugin.class, arg -> Bukkit.getPluginManager().getPlugin(arg), "Plugin not found!",
|
||||
() -> Arrays.stream(Bukkit.getPluginManager().getPlugins()).map(Plugin::getName)::iterator);
|
||||
}
|
||||
|
||||
@Subcommand(helpText = {
|
||||
"Enable component",
|
||||
"Temporarily or permanently enables a component."
|
||||
})
|
||||
public boolean enable(CommandSender sender, Plugin plugin, String component, @Command2.OptionalArg boolean permanent) {
|
||||
if (plugin instanceof ButtonPlugin) {
|
||||
if (!((ButtonPlugin) plugin).justReload()) {
|
||||
sender.sendMessage("§cCouldn't reload config, check console.");
|
||||
return true;
|
||||
}
|
||||
} else
|
||||
plugin.reloadConfig(); //Reload config so the new config values are read - All changes are saved to disk on disable
|
||||
return enable_disable(sender, plugin, component, true, permanent);
|
||||
}
|
||||
|
||||
@Subcommand(helpText = {
|
||||
"Disable component",
|
||||
"Temporarily or permanently disables a component."
|
||||
})
|
||||
public boolean disable(CommandSender sender, Plugin plugin, String component, @Command2.OptionalArg boolean permanent) {
|
||||
return enable_disable(sender, plugin, component, false, permanent);
|
||||
}
|
||||
|
||||
@Subcommand(helpText = {
|
||||
"List components",
|
||||
"Lists all of the registered Chroma components"
|
||||
})
|
||||
public boolean list(CommandSender sender, @Command2.OptionalArg String plugin) {
|
||||
sender.sendMessage("§6List of components:");
|
||||
Component.getComponents().values().stream().filter(c -> plugin == null || c.getPlugin().getName().equalsIgnoreCase(plugin)) //If plugin is null, don't check
|
||||
.map(c -> c.getPlugin().getName() + " - " + c.getClass().getSimpleName() + " - " + (c.isEnabled() ? "en" : "dis") + "abled").forEach(sender::sendMessage);
|
||||
return true;
|
||||
}
|
||||
|
||||
@CustomTabCompleteMethod(param = "component", subcommand = {"enable", "disable"})
|
||||
public Iterable<String> componentTabcomplete(Plugin plugin) {
|
||||
return getPluginComponents(plugin).map(c -> c.getClass().getSimpleName())::iterator;
|
||||
}
|
||||
|
||||
@CustomTabCompleteMethod(param = "plugin", subcommand = {"list", "enable", "disable"}, ignoreTypeCompletion = true)
|
||||
public Iterable<String> pluginTabcomplete() {
|
||||
return Component.getComponents().values().stream().map(Component::getPlugin)
|
||||
.distinct().map(Plugin::getName)::iterator;
|
||||
}
|
||||
|
||||
private boolean enable_disable(CommandSender sender, Plugin plugin, String component, boolean enable, boolean permanent) {
|
||||
try {
|
||||
val oc = getComponentOrError(plugin, component, sender);
|
||||
if (!oc.isPresent())
|
||||
return true;
|
||||
Component.setComponentEnabled(oc.get(), enable);
|
||||
if (permanent)
|
||||
oc.get().shouldBeEnabled.set(enable);
|
||||
sender.sendMessage(oc.get().getClass().getSimpleName() + " " + (enable ? "en" : "dis") + "abled " + (permanent ? "permanently" : "temporarily") + ".");
|
||||
} catch (Exception e) {
|
||||
TBMCCoreAPI.SendException("Couldn't " + (enable ? "en" : "dis") + "able component " + component + "!", e, (JavaPlugin) plugin);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private Stream<Component<? extends JavaPlugin>> getPluginComponents(Plugin plugin) {
|
||||
return Component.getComponents().values().stream()
|
||||
.filter(c -> plugin.getName().equals(c.getPlugin().getName()));
|
||||
}
|
||||
|
||||
private Optional<Component<?>> getComponentOrError(Plugin plugin, String arg, CommandSender sender) {
|
||||
val oc = getPluginComponents(plugin).filter(c -> c.getClass().getSimpleName().equalsIgnoreCase(arg)).findAny();
|
||||
if (!oc.isPresent())
|
||||
sender.sendMessage("§cComponent not found!"); //^ Much simpler to solve in the new command system
|
||||
return oc;
|
||||
}
|
||||
}
|
|
@ -1,99 +0,0 @@
|
|||
package buttondevteam.core
|
||||
|
||||
import buttondevteam.lib.TBMCCoreAPI
|
||||
import buttondevteam.lib.architecture.ButtonPlugin
|
||||
import buttondevteam.lib.architecture.Component
|
||||
import buttondevteam.lib.architecture.Component.Companion.components
|
||||
import buttondevteam.lib.architecture.Component.Companion.setComponentEnabled
|
||||
import buttondevteam.lib.chat.Command2.OptionalArg
|
||||
import buttondevteam.lib.chat.Command2.Subcommand
|
||||
import buttondevteam.lib.chat.CommandClass
|
||||
import buttondevteam.lib.chat.CustomTabCompleteMethod
|
||||
import buttondevteam.lib.chat.ICommand2MC
|
||||
import org.bukkit.Bukkit
|
||||
import org.bukkit.ChatColor
|
||||
import org.bukkit.command.CommandSender
|
||||
import org.bukkit.plugin.Plugin
|
||||
import org.bukkit.plugin.java.JavaPlugin
|
||||
import java.util.*
|
||||
import java.util.stream.Stream
|
||||
|
||||
@CommandClass(modOnly = true, helpText = ["Component command", "Can be used to enable/disable/list components"])
|
||||
class ComponentCommand : ICommand2MC() {
|
||||
init {
|
||||
manager.addParamConverter(
|
||||
Plugin::class.java, { arg -> Bukkit.getPluginManager().getPlugin(arg) },
|
||||
"Plugin not found!"
|
||||
) { Bukkit.getPluginManager().plugins.map { obj -> obj.name } }
|
||||
}
|
||||
|
||||
@Subcommand(helpText = ["Enable component", "Temporarily or permanently enables a component."])
|
||||
fun enable(sender: CommandSender, plugin: Plugin, component: String, @OptionalArg permanent: Boolean): Boolean {
|
||||
if (plugin is ButtonPlugin) {
|
||||
if (!plugin.tryReloadConfig()) {
|
||||
sender.sendMessage("${ChatColor.RED}Couldn't reload config, check console.")
|
||||
return true
|
||||
}
|
||||
} else plugin.reloadConfig() //Reload config so the new config values are read - All changes are saved to disk on disable
|
||||
return enable_disable(sender, plugin, component, true, permanent)
|
||||
}
|
||||
|
||||
@Subcommand(helpText = ["Disable component", "Temporarily or permanently disables a component."])
|
||||
fun disable(sender: CommandSender, plugin: Plugin, component: String, @OptionalArg permanent: Boolean): Boolean {
|
||||
return enable_disable(sender, plugin, component, false, permanent)
|
||||
}
|
||||
|
||||
@Subcommand(helpText = ["List components", "Lists all of the registered Chroma components"])
|
||||
fun list(sender: CommandSender, @OptionalArg plugin: String?): Boolean {
|
||||
sender.sendMessage("${ChatColor.GOLD}List of components:")
|
||||
//If plugin is null, don't check for it
|
||||
components.values.stream().filter { c -> plugin == null || c.plugin.name.equals(plugin, ignoreCase = true) }
|
||||
.map { c -> "${c.plugin.name} - ${c.javaClass.simpleName} - ${if (c.isEnabled) "en" else "dis"}abled" }
|
||||
.forEach { message -> sender.sendMessage(message) }
|
||||
return true
|
||||
}
|
||||
|
||||
@CustomTabCompleteMethod(param = "component", subcommand = ["enable", "disable"])
|
||||
fun componentTabcomplete(plugin: Plugin): Iterable<String> {
|
||||
return Iterable { getPluginComponents(plugin).map { c -> c.javaClass.simpleName }.iterator() }
|
||||
}
|
||||
|
||||
@CustomTabCompleteMethod(param = "plugin", subcommand = ["list", "enable", "disable"], ignoreTypeCompletion = true)
|
||||
fun pluginTabcomplete(): Iterable<String> {
|
||||
return Iterable { components.values.stream().map { it.plugin }.distinct().map { it.name }.iterator() }
|
||||
}
|
||||
|
||||
private fun enable_disable(
|
||||
sender: CommandSender,
|
||||
plugin: Plugin,
|
||||
component: String,
|
||||
enable: Boolean,
|
||||
permanent: Boolean
|
||||
): Boolean {
|
||||
try {
|
||||
val oc = getComponentOrError(plugin, component, sender)
|
||||
if (!oc.isPresent) return true
|
||||
setComponentEnabled(oc.get(), enable)
|
||||
if (permanent) oc.get().shouldBeEnabled = enable
|
||||
sender.sendMessage("${oc.get().javaClass.simpleName} ${if (enable) "en" else "dis"}abled ${if (permanent) "permanently" else "temporarily"}.")
|
||||
} catch (e: Exception) {
|
||||
TBMCCoreAPI.SendException(
|
||||
"Couldn't " + (if (enable) "en" else "dis") + "able component " + component + "!",
|
||||
e,
|
||||
plugin as JavaPlugin
|
||||
)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
private fun getPluginComponents(plugin: Plugin): Stream<Component<out JavaPlugin>> {
|
||||
return components.values.stream().filter { c -> plugin.name == c.plugin.name }
|
||||
}
|
||||
|
||||
private fun getComponentOrError(plugin: Plugin, arg: String, sender: CommandSender): Optional<Component<*>> {
|
||||
// TODO: Extend param converter to support accessing previous params
|
||||
val oc = getPluginComponents(plugin).filter { it.javaClass.simpleName.equals(arg, ignoreCase = true) }.findAny()
|
||||
if (!oc.isPresent) sender.sendMessage("${ChatColor.RED}Component not found!")
|
||||
return oc
|
||||
}
|
||||
}
|
|
@ -0,0 +1,66 @@
|
|||
package buttondevteam.core;
|
||||
|
||||
import buttondevteam.lib.TBMCCoreAPI;
|
||||
import buttondevteam.lib.architecture.ButtonPlugin;
|
||||
import buttondevteam.lib.architecture.Component;
|
||||
import lombok.val;
|
||||
|
||||
public final class ComponentManager {
|
||||
private ComponentManager() {}
|
||||
|
||||
private static boolean componentsEnabled = false;
|
||||
|
||||
/**
|
||||
* This flag is used to enable components registered after the others were enabled.
|
||||
* @return Whether already registered components have been enabled
|
||||
*/
|
||||
public static boolean areComponentsEnabled() { return componentsEnabled; }
|
||||
|
||||
/**
|
||||
* Enables components based on a configuration - any component registered afterwards will be also enabled
|
||||
*/
|
||||
public static void enableComponents() {
|
||||
//Component.getComponents().values().stream().filter(c->cs.getConfigurationSection(c.getClass().getSimpleName()).getBoolean("enabled")).forEach(c-> {
|
||||
Component.getComponents().values().stream().filter(c -> c.shouldBeEnabled.get()).forEach(c -> {
|
||||
try {
|
||||
Component.setComponentEnabled(c, true);
|
||||
} catch (Exception | NoClassDefFoundError e) {
|
||||
TBMCCoreAPI.SendException("Failed to enable one of the components: " + c.getClass().getSimpleName(), e, c);
|
||||
}
|
||||
});
|
||||
componentsEnabled = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Unregister all components of a plugin that are enabled - called on {@link ButtonPlugin} disable
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <T extends ButtonPlugin> void unregComponents(T plugin) {
|
||||
while (!plugin.getComponentStack().empty()) //Unregister in reverse order
|
||||
Component.unregisterComponent(plugin, (Component<T>) plugin.getComponentStack().pop()); //Components are pushed on register
|
||||
//componentsEnabled = false; - continue enabling new components after a plugin gets disabled
|
||||
}
|
||||
|
||||
/**
|
||||
* Will also return false if the component is not registered.
|
||||
*
|
||||
* @param cl The component class
|
||||
* @return Whether the component is registered and enabled
|
||||
*/
|
||||
public static boolean isEnabled(Class<? extends Component> cl) {
|
||||
val c = Component.getComponents().get(cl);
|
||||
return c != null && c.isEnabled();
|
||||
}
|
||||
|
||||
/**
|
||||
* Will also return null if the component is not registered.
|
||||
*
|
||||
* @param cl The component class
|
||||
* @return The component if it's registered and enabled
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <T extends Component> T getIfEnabled(Class<T> cl) {
|
||||
val c = Component.getComponents().get(cl);
|
||||
return c != null && c.isEnabled() ? (T) c : null;
|
||||
}
|
||||
}
|
|
@ -1,81 +0,0 @@
|
|||
package buttondevteam.core
|
||||
|
||||
import buttondevteam.lib.TBMCCoreAPI
|
||||
import buttondevteam.lib.architecture.ButtonPlugin
|
||||
import buttondevteam.lib.architecture.Component
|
||||
import buttondevteam.lib.architecture.Component.Companion.components
|
||||
import buttondevteam.lib.architecture.Component.Companion.setComponentEnabled
|
||||
import buttondevteam.lib.architecture.Component.Companion.unregisterComponent
|
||||
import org.bukkit.plugin.java.JavaPlugin
|
||||
|
||||
object ComponentManager {
|
||||
private var componentsEnabled = false
|
||||
|
||||
/**
|
||||
* This flag is used to enable components registered after the others were enabled.
|
||||
* @return Whether already registered components have been enabled
|
||||
*/
|
||||
fun areComponentsEnabled(): Boolean {
|
||||
return componentsEnabled
|
||||
}
|
||||
|
||||
/**
|
||||
* Enables components based on a configuration - any component registered afterwards will be also enabled
|
||||
*/
|
||||
fun enableComponents() {
|
||||
components.values.stream().filter { c: Component<out JavaPlugin> -> c.shouldBeEnabled }
|
||||
.forEach { c ->
|
||||
try {
|
||||
setComponentEnabled(c, true)
|
||||
} catch (e: Exception) {
|
||||
TBMCCoreAPI.SendException("Failed to enable one of the components: " + c.javaClass.simpleName, e, c)
|
||||
} catch (e: NoClassDefFoundError) {
|
||||
TBMCCoreAPI.SendException("Failed to enable one of the components: " + c.javaClass.simpleName, e, c)
|
||||
}
|
||||
}
|
||||
componentsEnabled = true
|
||||
}
|
||||
|
||||
/**
|
||||
* Unregister all components of a plugin that are enabled - called on [ButtonPlugin] disable
|
||||
*/
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
fun <T : ButtonPlugin> unregComponents(plugin: T) {
|
||||
while (!plugin.componentStack.empty()) //Unregister in reverse order
|
||||
unregisterComponent(plugin, plugin.componentStack.pop() as Component<T>) //Components are pushed on register
|
||||
}
|
||||
|
||||
/**
|
||||
* Will also return false if the component is not registered.
|
||||
*
|
||||
* @param cl The component class
|
||||
* @return Whether the component is registered and enabled
|
||||
*/
|
||||
@JvmStatic
|
||||
fun isEnabled(cl: Class<out Component<*>?>?): Boolean {
|
||||
val c = components[cl]
|
||||
return c != null && c.isEnabled
|
||||
}
|
||||
|
||||
/**
|
||||
* Will also return null if the component is not registered.
|
||||
*
|
||||
* @param cl The component class
|
||||
* @return The component if it's registered and enabled
|
||||
*/
|
||||
@JvmStatic
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
fun <T : Component<*>> getIfEnabled(cl: Class<T>): T? {
|
||||
val c = components[cl]
|
||||
return if (c != null && c.isEnabled) c as T else null
|
||||
}
|
||||
|
||||
/**
|
||||
* It will return null if the component is not registered. Use this method if you don't want to check if the component is enabled.
|
||||
*/
|
||||
@JvmStatic
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
fun <T : Component<*>> get(cl: Class<T>): T? {
|
||||
return components[cl] as T?
|
||||
}
|
||||
}
|
173
Chroma-Core/src/main/java/buttondevteam/core/MainPlugin.java
Executable file
173
Chroma-Core/src/main/java/buttondevteam/core/MainPlugin.java
Executable file
|
@ -0,0 +1,173 @@
|
|||
package buttondevteam.core;
|
||||
|
||||
import buttondevteam.core.component.channel.Channel;
|
||||
import buttondevteam.core.component.channel.ChannelComponent;
|
||||
import buttondevteam.core.component.channel.ChatRoom;
|
||||
import buttondevteam.core.component.members.MemberComponent;
|
||||
import buttondevteam.core.component.randomtp.RandomTPComponent;
|
||||
import buttondevteam.core.component.restart.RestartComponent;
|
||||
import buttondevteam.core.component.spawn.SpawnComponent;
|
||||
import buttondevteam.core.component.towny.TownyComponent;
|
||||
import buttondevteam.lib.TBMCCoreAPI;
|
||||
import buttondevteam.lib.architecture.ButtonPlugin;
|
||||
import buttondevteam.lib.architecture.Component;
|
||||
import buttondevteam.lib.architecture.ConfigData;
|
||||
import buttondevteam.lib.chat.Color;
|
||||
import buttondevteam.lib.chat.TBMCChatAPI;
|
||||
import buttondevteam.lib.player.ChromaGamerBase;
|
||||
import buttondevteam.lib.player.TBMCPlayer;
|
||||
import buttondevteam.lib.player.TBMCPlayerBase;
|
||||
import com.earth2me.essentials.Essentials;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import net.milkbowl.vault.economy.Economy;
|
||||
import net.milkbowl.vault.permission.Permission;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.command.BlockCommandSender;
|
||||
import org.bukkit.command.Command;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.command.ConsoleCommandSender;
|
||||
import org.bukkit.entity.HumanEntity;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.plugin.PluginDescriptionFile;
|
||||
import org.bukkit.plugin.RegisteredServiceProvider;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.util.Arrays;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class MainPlugin extends ButtonPlugin {
|
||||
public static MainPlugin Instance;
|
||||
public static Permission permission;
|
||||
@Nullable
|
||||
public static Essentials ess;
|
||||
|
||||
private Logger logger;
|
||||
@Nullable
|
||||
private Economy economy;
|
||||
/**
|
||||
* Whether the Core's chat handler should be enabled.
|
||||
* Other chat plugins handling messages from other platforms should set this to false.
|
||||
*/
|
||||
@Getter
|
||||
@Setter
|
||||
private boolean chatHandlerEnabled = true;
|
||||
|
||||
/**
|
||||
* Sets whether the plugin should write a list of installed plugins in a txt file.
|
||||
* It can be useful if some other software needs to know the plugins.
|
||||
*/
|
||||
private final ConfigData<Boolean> writePluginList = getIConfig().getData("writePluginList", false);
|
||||
|
||||
/**
|
||||
* The chat format to use for messages from other platforms if Chroma-Chat is not installed.
|
||||
*/
|
||||
ConfigData<String> chatFormat = getIConfig().getData("chatFormat", "[{origin}|" +
|
||||
"{channel}] <{name}> {message}");
|
||||
|
||||
/**
|
||||
* Print some debug information.
|
||||
*/
|
||||
public final ConfigData<Boolean> test = getIConfig().getData("test", false);
|
||||
|
||||
/**
|
||||
* If a Chroma command clashes with another plugin's command, this setting determines whether the Chroma command should be executed or the other plugin's.
|
||||
*/
|
||||
public final ConfigData<Boolean> prioritizeCustomCommands = getIConfig().getData("prioritizeCustomCommands", false);
|
||||
|
||||
@Override
|
||||
public void pluginEnable() {
|
||||
Instance = this;
|
||||
PluginDescriptionFile pdf = getDescription();
|
||||
logger = getLogger();
|
||||
if (!setupPermissions())
|
||||
throw new NullPointerException("No permission plugin found!");
|
||||
if (!setupEconomy()) //Though Essentials always provides economy, but we don't require Essentials
|
||||
getLogger().warning("No economy plugin found! Components using economy will not be registered.");
|
||||
saveConfig();
|
||||
Component.registerComponent(this, new RestartComponent());
|
||||
Component.registerComponent(this, new ChannelComponent());
|
||||
Component.registerComponent(this, new RandomTPComponent());
|
||||
Component.registerComponent(this, new MemberComponent());
|
||||
if (Bukkit.getPluginManager().isPluginEnabled("Multiverse-Core"))
|
||||
Component.registerComponent(this, new SpawnComponent());
|
||||
if (Bukkit.getPluginManager().isPluginEnabled("Towny")) //It fails to load the component class otherwise
|
||||
Component.registerComponent(this, new TownyComponent());
|
||||
/*if (Bukkit.getPluginManager().isPluginEnabled("Votifier") && economy != null)
|
||||
Component.registerComponent(this, new VotifierComponent(economy));*/
|
||||
ComponentManager.enableComponents();
|
||||
registerCommand(new ComponentCommand());
|
||||
registerCommand(new ChromaCommand());
|
||||
TBMCCoreAPI.RegisterEventsForExceptions(new PlayerListener(), this);
|
||||
TBMCCoreAPI.RegisterEventsForExceptions(getCommand2MC(), this);
|
||||
ChromaGamerBase.addConverter(commandSender -> Optional.ofNullable(commandSender instanceof ConsoleCommandSender || commandSender instanceof BlockCommandSender
|
||||
? TBMCPlayer.getPlayer(new UUID(0, 0), TBMCPlayer.class) : null)); //Console & cmdblocks
|
||||
ChromaGamerBase.addConverter(sender -> Optional.ofNullable(sender instanceof Player
|
||||
? TBMCPlayer.getPlayer(((Player) sender).getUniqueId(), TBMCPlayer.class) : null)); //Players, has higher priority
|
||||
TBMCCoreAPI.RegisterUserClass(TBMCPlayerBase.class, TBMCPlayer::new);
|
||||
TBMCChatAPI.RegisterChatChannel(Channel.GlobalChat = new Channel("§fg§f", Color.White, "g", null)); //The /ooc ID has moved to the config
|
||||
TBMCChatAPI.RegisterChatChannel(
|
||||
Channel.AdminChat = new Channel("§cADMIN§f", Color.Red, "a", Channel.inGroupFilter(null)));
|
||||
TBMCChatAPI.RegisterChatChannel(
|
||||
Channel.ModChat = new Channel("§9MOD§f", Color.Blue, "mod", Channel.inGroupFilter("mod")));
|
||||
TBMCChatAPI.RegisterChatChannel(new Channel("§6DEV§f", Color.Gold, "dev", Channel.inGroupFilter("developer")));
|
||||
TBMCChatAPI.RegisterChatChannel(new ChatRoom("§cRED§f", Color.DarkRed, "red"));
|
||||
TBMCChatAPI.RegisterChatChannel(new ChatRoom("§6ORANGE§f", Color.Gold, "orange"));
|
||||
TBMCChatAPI.RegisterChatChannel(new ChatRoom("§eYELLOW§f", Color.Yellow, "yellow"));
|
||||
TBMCChatAPI.RegisterChatChannel(new ChatRoom("§aGREEN§f", Color.Green, "green"));
|
||||
TBMCChatAPI.RegisterChatChannel(new ChatRoom("§bBLUE§f", Color.Blue, "blue"));
|
||||
TBMCChatAPI.RegisterChatChannel(new ChatRoom("§5PURPLE§f", Color.DarkPurple, "purple"));
|
||||
Supplier<Iterable<String>> playerSupplier = () -> Bukkit.getOnlinePlayers().stream().map(HumanEntity::getName)::iterator;
|
||||
getCommand2MC().addParamConverter(OfflinePlayer.class, Bukkit::getOfflinePlayer, "Player not found!", playerSupplier);
|
||||
getCommand2MC().addParamConverter(Player.class, Bukkit::getPlayer, "Online player not found!", playerSupplier);
|
||||
if (writePluginList.get()) {
|
||||
try {
|
||||
Files.write(new File("plugins", "plugins.txt").toPath(), Arrays.stream(Bukkit.getPluginManager().getPlugins()).map(p -> (CharSequence) p.getDataFolder().getName())::iterator);
|
||||
} catch (IOException e) {
|
||||
TBMCCoreAPI.SendException("Failed to write plugin list!", e, this);
|
||||
}
|
||||
}
|
||||
if (getServer().getPluginManager().isPluginEnabled("Essentials"))
|
||||
ess = Essentials.getPlugin(Essentials.class);
|
||||
logger.info(pdf.getName() + " has been Enabled (V." + pdf.getVersion() + ") Test: " + test.get() + ".");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void pluginDisable() {
|
||||
logger.info("Saving player data...");
|
||||
ChromaGamerBase.saveUsers();
|
||||
logger.info("Player data saved.");
|
||||
}
|
||||
|
||||
private boolean setupPermissions() {
|
||||
permission = setupProvider(Permission.class);
|
||||
return (permission != null);
|
||||
}
|
||||
|
||||
private boolean setupEconomy() {
|
||||
economy = setupProvider(Economy.class);
|
||||
return (economy != null);
|
||||
}
|
||||
|
||||
private <T> T setupProvider(Class<T> cl) {
|
||||
RegisteredServiceProvider<T> provider = getServer().getServicesManager()
|
||||
.getRegistration(cl);
|
||||
if (provider != null)
|
||||
return provider.getProvider();
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
|
||||
if (command.getName().equals("dontrunthiscmd")) return true; //Used in chat preprocess for console
|
||||
sender.sendMessage("§cThis command isn't available."); //In theory, unregistered commands use this method
|
||||
return true;
|
||||
}
|
||||
}
|
|
@ -1,200 +0,0 @@
|
|||
package buttondevteam.core
|
||||
|
||||
import buttondevteam.core.component.channel.Channel
|
||||
import buttondevteam.core.component.channel.ChannelComponent
|
||||
import buttondevteam.core.component.channel.ChatRoom
|
||||
import buttondevteam.core.component.members.MemberComponent
|
||||
import buttondevteam.core.component.randomtp.RandomTPComponent
|
||||
import buttondevteam.core.component.restart.RestartComponent
|
||||
import buttondevteam.core.component.spawn.SpawnComponent
|
||||
import buttondevteam.core.component.towny.TownyComponent
|
||||
import buttondevteam.lib.ChromaUtils
|
||||
import buttondevteam.lib.TBMCCoreAPI
|
||||
import buttondevteam.lib.architecture.ButtonPlugin
|
||||
import buttondevteam.lib.architecture.Component.Companion.registerComponent
|
||||
import buttondevteam.lib.architecture.ConfigData
|
||||
import buttondevteam.lib.chat.TBMCChatAPI
|
||||
import buttondevteam.lib.player.ChromaGamerBase
|
||||
import buttondevteam.lib.player.TBMCPlayer
|
||||
import buttondevteam.lib.player.TBMCPlayerBase
|
||||
import buttondevteam.lib.test.TestPermissions
|
||||
import com.earth2me.essentials.Essentials
|
||||
import net.milkbowl.vault.economy.Economy
|
||||
import net.milkbowl.vault.permission.Permission
|
||||
import org.bukkit.Bukkit
|
||||
import org.bukkit.ChatColor
|
||||
import org.bukkit.OfflinePlayer
|
||||
import org.bukkit.command.BlockCommandSender
|
||||
import org.bukkit.command.Command
|
||||
import org.bukkit.command.CommandSender
|
||||
import org.bukkit.command.ConsoleCommandSender
|
||||
import org.bukkit.entity.Player
|
||||
import org.bukkit.plugin.PluginDescriptionFile
|
||||
import org.bukkit.plugin.java.JavaPluginLoader
|
||||
import java.io.File
|
||||
import java.util.*
|
||||
import java.util.function.Supplier
|
||||
|
||||
class MainPlugin : ButtonPlugin {
|
||||
private var economy: Economy? = null
|
||||
|
||||
/**
|
||||
* Whether the Core's chat handler should be enabled.
|
||||
* Other chat plugins handling messages from other platforms should set this to false.
|
||||
*/
|
||||
var isChatHandlerEnabled = true
|
||||
|
||||
/**
|
||||
* The chat format to use for messages from other platforms if Chroma-Chat is not installed.
|
||||
*/
|
||||
@JvmField
|
||||
var chatFormat = iConfig.getData("chatFormat", "[{origin}|{channel}] <{name}> {message}")
|
||||
|
||||
/**
|
||||
* Print some debug information.
|
||||
*/
|
||||
@JvmField
|
||||
val test = iConfig.getData("test", false)
|
||||
|
||||
/**
|
||||
* If a Chroma command clashes with another plugin's command, this setting determines whether the Chroma command should be executed or the other plugin's.
|
||||
*/
|
||||
val prioritizeCustomCommands = iConfig.getData("prioritizeCustomCommands", false)
|
||||
|
||||
/**
|
||||
* The permission group to use for players who are not in the server.
|
||||
*/ // TODO: Combine the channel access test with command permissions (with a generic implementation)
|
||||
val externalPlayerPermissionGroup get() = iConfig.getData("externalPlayerPermissionGroup", "default")
|
||||
|
||||
constructor() : super()
|
||||
constructor(loader: JavaPluginLoader, description: PluginDescriptionFile, dataFolder: File, file: File, @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN") test: java.lang.Boolean) : super(loader, description, dataFolder, file) {
|
||||
ChromaUtils.isTest = test.booleanValue()
|
||||
}
|
||||
|
||||
|
||||
public override fun pluginEnable() {
|
||||
instance = this
|
||||
val pdf = description
|
||||
setupPermissions(ChromaUtils.isTest)
|
||||
if (!setupEconomy() && !ChromaUtils.isTest) //Though Essentials always provides economy, but we don't require Essentials
|
||||
logger.warning("No economy plugin found! Components using economy will not be registered.")
|
||||
ConfigData.saveNow(config) // Run pending save tasks
|
||||
registerComponent(this, RestartComponent())
|
||||
registerComponent(this, ChannelComponent())
|
||||
registerComponent(this, RandomTPComponent())
|
||||
registerComponent(this, MemberComponent())
|
||||
if (Bukkit.getPluginManager().isPluginEnabled("Multiverse-Core"))
|
||||
registerComponent(this, SpawnComponent())
|
||||
if (Bukkit.getPluginManager().isPluginEnabled("Towny")) //It fails to load the component class otherwise
|
||||
registerComponent(this, TownyComponent())
|
||||
/*if (Bukkit.getPluginManager().isPluginEnabled("Votifier") && economy != null)
|
||||
Component.registerComponent(this, new VotifierComponent(economy));*/
|
||||
ComponentManager.enableComponents()
|
||||
registerCommand(ComponentCommand())
|
||||
registerCommand(ChromaCommand())
|
||||
TBMCCoreAPI.RegisterEventsForExceptions(PlayerListener(this), this)
|
||||
TBMCCoreAPI.RegisterEventsForExceptions(command2MC, this)
|
||||
//Console & cmdblocks
|
||||
ChromaGamerBase.addConverter { commandSender: CommandSender ->
|
||||
Optional.ofNullable(
|
||||
if (commandSender is ConsoleCommandSender || commandSender is BlockCommandSender)
|
||||
TBMCPlayerBase.getConsole()
|
||||
else null
|
||||
)
|
||||
}
|
||||
//Players, has higher priority
|
||||
ChromaGamerBase.addConverter { sender: CommandSender ->
|
||||
Optional.ofNullable(
|
||||
if (sender is Player) TBMCPlayerBase.getPlayer(sender.uniqueId, TBMCPlayer::class.java) else null
|
||||
)
|
||||
}
|
||||
TBMCCoreAPI.RegisterUserClass(TBMCPlayerBase::class.java) { TBMCPlayer() }
|
||||
TBMCChatAPI.registerChatChannel(Channel("${ChatColor.WHITE}g${ChatColor.WHITE}", ChatColor.WHITE, "g", null)
|
||||
.also { Channel.globalChat = it }) //The /ooc ID has moved to the config
|
||||
TBMCChatAPI.registerChatChannel(Channel(
|
||||
"${ChatColor.RED}ADMIN${ChatColor.WHITE}",
|
||||
ChatColor.RED,
|
||||
"a",
|
||||
Channel.inGroupFilter(null)
|
||||
)
|
||||
.also { Channel.adminChat = it })
|
||||
TBMCChatAPI.registerChatChannel(Channel(
|
||||
"${ChatColor.BLUE}MOD${ChatColor.WHITE}",
|
||||
ChatColor.BLUE,
|
||||
"mod",
|
||||
Channel.inGroupFilter("mod")
|
||||
)
|
||||
.also { Channel.modChat = it })
|
||||
TBMCChatAPI.registerChatChannel(
|
||||
Channel(
|
||||
"${ChatColor.GOLD}DEV${ChatColor.WHITE}",
|
||||
ChatColor.GOLD,
|
||||
"dev",
|
||||
Channel.inGroupFilter("developer")
|
||||
)
|
||||
) // TODO: Make groups configurable
|
||||
TBMCChatAPI.registerChatChannel(ChatRoom("${ChatColor.RED}RED${ChatColor.WHITE}", ChatColor.DARK_RED, "red"))
|
||||
TBMCChatAPI.registerChatChannel(ChatRoom("${ChatColor.GOLD}ORANGE${ChatColor.WHITE}", ChatColor.GOLD, "orange"))
|
||||
TBMCChatAPI.registerChatChannel(ChatRoom("${ChatColor.YELLOW}YELLOW${ChatColor.WHITE}", ChatColor.YELLOW, "yellow"))
|
||||
TBMCChatAPI.registerChatChannel(ChatRoom("${ChatColor.GREEN}GREEN${ChatColor.WHITE}", ChatColor.GREEN, "green"))
|
||||
TBMCChatAPI.registerChatChannel(ChatRoom("${ChatColor.AQUA}BLUE${ChatColor.WHITE}", ChatColor.BLUE, "blue"))
|
||||
TBMCChatAPI.registerChatChannel(ChatRoom("${ChatColor.LIGHT_PURPLE}PURPLE${ChatColor.WHITE}", ChatColor.DARK_PURPLE, "purple"))
|
||||
val playerSupplier = Supplier { Bukkit.getOnlinePlayers().map { obj -> obj.name }.asIterable() }
|
||||
command2MC.addParamConverter(
|
||||
OfflinePlayer::class.java,
|
||||
{ name -> Bukkit.getOfflinePlayer(name) },
|
||||
"Player not found!",
|
||||
playerSupplier
|
||||
)
|
||||
command2MC.addParamConverter(
|
||||
Player::class.java,
|
||||
{ name -> Bukkit.getPlayer(name) },
|
||||
"Online player not found!",
|
||||
playerSupplier
|
||||
)
|
||||
if (server.pluginManager.isPluginEnabled("Essentials")) ess = getPlugin(Essentials::class.java)
|
||||
logger.info(pdf.name + " has been Enabled (V." + pdf.version + ") Test: " + test.get() + ".")
|
||||
}
|
||||
|
||||
public override fun pluginDisable() {
|
||||
logger.info("Saving player data...")
|
||||
ChromaGamerBase.saveUsers()
|
||||
logger.info("Player data saved.")
|
||||
}
|
||||
|
||||
private fun setupPermissions(test: Boolean) {
|
||||
permission = setupProvider(Permission::class.java)
|
||||
?: if (test) TestPermissions()
|
||||
else throw NullPointerException("No permission plugin found!")
|
||||
}
|
||||
|
||||
private fun setupEconomy(): Boolean {
|
||||
economy = setupProvider(Economy::class.java)
|
||||
return economy != null
|
||||
}
|
||||
|
||||
private fun <T> setupProvider(cl: Class<T>): T? {
|
||||
val provider = server.servicesManager
|
||||
.getRegistration(cl)
|
||||
return provider?.provider
|
||||
}
|
||||
|
||||
override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<String>): Boolean {
|
||||
if (command.name == "dontrunthiscmd") return true //Used in chat preprocess for console
|
||||
sender.sendMessage("${ChatColor.RED}This command isn't available.") //In theory, unregistered commands use this method
|
||||
return true
|
||||
}
|
||||
|
||||
companion object {
|
||||
@JvmStatic
|
||||
lateinit var instance: MainPlugin
|
||||
private set
|
||||
|
||||
lateinit var permission: Permission
|
||||
|
||||
@JvmField
|
||||
var ess: Essentials? = null
|
||||
|
||||
val isInitialized get() = ::instance.isInitialized
|
||||
}
|
||||
}
|
116
Chroma-Core/src/main/java/buttondevteam/core/PlayerListener.java
Executable file
116
Chroma-Core/src/main/java/buttondevteam/core/PlayerListener.java
Executable file
|
@ -0,0 +1,116 @@
|
|||
package buttondevteam.core;
|
||||
|
||||
import buttondevteam.lib.*;
|
||||
import buttondevteam.lib.architecture.ButtonPlugin;
|
||||
import buttondevteam.lib.chat.ChatMessage;
|
||||
import buttondevteam.lib.chat.Command2MCSender;
|
||||
import buttondevteam.lib.chat.TBMCChatAPI;
|
||||
import buttondevteam.lib.player.ChromaGamerBase;
|
||||
import buttondevteam.lib.player.TBMCPlayer;
|
||||
import buttondevteam.lib.player.TBMCPlayerBase;
|
||||
import lombok.val;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.Cancellable;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.AsyncPlayerChatEvent;
|
||||
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
|
||||
import org.bukkit.event.player.PlayerJoinEvent;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
import org.bukkit.event.server.ServerCommandEvent;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public class PlayerListener implements Listener {
|
||||
|
||||
@EventHandler(priority = EventPriority.NORMAL)
|
||||
public void OnPlayerJoin(PlayerJoinEvent event) {
|
||||
var p = event.getPlayer();
|
||||
TBMCPlayer player = TBMCPlayerBase.getPlayer(p.getUniqueId(), TBMCPlayer.class);
|
||||
String pname = player.PlayerName.get();
|
||||
if (pname.length() == 0) {
|
||||
player.PlayerName.set(p.getName());
|
||||
MainPlugin.Instance.getLogger().info("Player name saved: " + player.PlayerName.get());
|
||||
} else if (!p.getName().equals(pname)) {
|
||||
MainPlugin.Instance.getLogger().info(pname + " renamed to " + p.getName());
|
||||
player.PlayerName.set(p.getName());
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.NORMAL)
|
||||
public void OnPlayerLeave(PlayerQuitEvent event) {
|
||||
TBMCPlayerBase.getPlayer(event.getPlayer().getUniqueId(), TBMCPlayer.class).uncache();
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST)
|
||||
public void onSystemChat(TBMCSystemChatEvent event) {
|
||||
if (event.isHandled())
|
||||
return; // Only handle here if ButtonChat couldn't - ButtonChat doesn't even handle this
|
||||
if (Arrays.stream(event.getExceptions()).anyMatch("Minecraft"::equalsIgnoreCase))
|
||||
return;
|
||||
Bukkit.getOnlinePlayers().stream().filter(event::shouldSendTo)
|
||||
.forEach(p -> p.sendMessage(event.getChannel().DisplayName.get().substring(0, 2) + event.getMessage()));
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onPlayerChatPreprocess(PlayerCommandPreprocessEvent event) {
|
||||
handlePreprocess(event.getPlayer(), event.getMessage(), event);
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onSystemChatPreprocess(ServerCommandEvent event) {
|
||||
handlePreprocess(event.getSender(), "/" + event.getCommand(), event);
|
||||
if (event.isCancelled()) event.setCommand("dontrunthiscmd"); //Bugfix
|
||||
}
|
||||
|
||||
private void handlePreprocess(CommandSender sender, String message, Cancellable event) {
|
||||
if (event.isCancelled()) return;
|
||||
val cg = ChromaGamerBase.getFromSender(sender);
|
||||
if (cg == null) throw new RuntimeException("Couldn't get user from sender for " + sender.getName() + "!");
|
||||
val ev = new TBMCCommandPreprocessEvent(sender, cg.channel.get(), message, sender);
|
||||
Bukkit.getPluginManager().callEvent(ev);
|
||||
if (ev.isCancelled())
|
||||
event.setCancelled(true); //Cancel the original event
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onTBMCPreprocess(TBMCCommandPreprocessEvent event) {
|
||||
if (event.isCancelled()) return;
|
||||
try {
|
||||
event.setCancelled(ButtonPlugin.getCommand2MC().handleCommand(new Command2MCSender(event.getSender(), event.getChannel(), event.getPermCheck()), event.getMessage()));
|
||||
} catch (Exception e) {
|
||||
TBMCCoreAPI.SendException("Command processing failed for sender '" + event.getSender() + "' and message '" + event.getMessage() + "'", e, MainPlugin.Instance);
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGH) //The one in the chat plugin is set to highest
|
||||
public void onPlayerChat(AsyncPlayerChatEvent event) {
|
||||
if (event.isCancelled())
|
||||
return; //The chat plugin should cancel it after this handler
|
||||
val cp = TBMCPlayer.getPlayer(event.getPlayer().getUniqueId(), TBMCPlayer.class);
|
||||
TBMCChatAPI.SendChatMessage(ChatMessage.builder(event.getPlayer(), cp, event.getMessage()).build());
|
||||
//Not cancelling the original event here, it's cancelled in the chat plugin
|
||||
//This way other plugins can deal with the MC formatting if the chat plugin isn't present, but other platforms still get the message
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGH) //The one in the chat plugin is set to highest
|
||||
public void onPlayerChat(TBMCChatEvent event) {
|
||||
if (event.isCancelled())
|
||||
return;
|
||||
if (!MainPlugin.Instance.isChatHandlerEnabled()) return;
|
||||
if (event.getOrigin().equals("Minecraft")) return; //Let other plugins handle MC messages
|
||||
var channel = event.getChannel();
|
||||
String msg = MainPlugin.Instance.chatFormat.get()
|
||||
.replace("{channel}", channel.DisplayName.get())
|
||||
.replace("{origin}", event.getOrigin().substring(0, 1))
|
||||
.replace("{name}", ChromaUtils.getDisplayName(event.getSender()))
|
||||
.replace("{message}", String.format("§%x%s", channel.Color.get().ordinal(), event.getMessage()));
|
||||
for (Player player : Bukkit.getOnlinePlayers())
|
||||
if (event.shouldSendTo(player))
|
||||
player.sendMessage(msg);
|
||||
Bukkit.getConsoleSender().sendMessage(msg);
|
||||
}
|
||||
}
|
|
@ -1,113 +0,0 @@
|
|||
package buttondevteam.core
|
||||
|
||||
import buttondevteam.lib.TBMCChatEvent
|
||||
import buttondevteam.lib.TBMCCommandPreprocessEvent
|
||||
import buttondevteam.lib.TBMCCoreAPI
|
||||
import buttondevteam.lib.TBMCSystemChatEvent
|
||||
import buttondevteam.lib.architecture.ButtonPlugin
|
||||
import buttondevteam.lib.chat.ChatMessage
|
||||
import buttondevteam.lib.chat.Command2MCSender
|
||||
import buttondevteam.lib.chat.TBMCChatAPI
|
||||
import buttondevteam.lib.player.ChromaGamerBase
|
||||
import buttondevteam.lib.player.TBMCPlayer
|
||||
import buttondevteam.lib.player.TBMCPlayerBase
|
||||
import buttondevteam.lib.player.TBMCPlayerBase.Companion.asTBMC
|
||||
import org.bukkit.Bukkit
|
||||
import org.bukkit.command.CommandSender
|
||||
import org.bukkit.event.Cancellable
|
||||
import org.bukkit.event.EventHandler
|
||||
import org.bukkit.event.EventPriority
|
||||
import org.bukkit.event.Listener
|
||||
import org.bukkit.event.player.AsyncPlayerChatEvent
|
||||
import org.bukkit.event.player.PlayerCommandPreprocessEvent
|
||||
import org.bukkit.event.player.PlayerJoinEvent
|
||||
import org.bukkit.event.player.PlayerQuitEvent
|
||||
import org.bukkit.event.server.ServerCommandEvent
|
||||
|
||||
class PlayerListener(val plugin: MainPlugin) : Listener {
|
||||
@EventHandler(priority = EventPriority.NORMAL)
|
||||
fun onPlayerJoin(event: PlayerJoinEvent) {
|
||||
val p = event.player
|
||||
val player = TBMCPlayerBase.getPlayer(p.uniqueId, TBMCPlayer::class.java)
|
||||
val pname = player.playerName
|
||||
if (pname.isEmpty()) {
|
||||
player.playerName = p.name
|
||||
plugin.logger.info("Player name saved: " + player.playerName)
|
||||
} else if (p.name != pname) {
|
||||
plugin.logger.info(pname + " renamed to " + p.name)
|
||||
player.playerName = p.name
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.NORMAL)
|
||||
fun onPlayerLeave(event: PlayerQuitEvent) {
|
||||
TBMCPlayerBase.getPlayer(event.player.uniqueId, TBMCPlayer::class.java).uncache()
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST)
|
||||
fun onSystemChat(event: TBMCSystemChatEvent) {
|
||||
if (event.isHandled) return
|
||||
if (event.exceptions.any { "Minecraft".equals(it, ignoreCase = true) }) return
|
||||
Bukkit.getOnlinePlayers().stream().filter { event.shouldSendTo(it.asTBMC()) }
|
||||
.forEach { it.sendMessage(event.channel.displayName.get().substring(0, 2) + event.message) }
|
||||
// TODO: Replace the substring call with a proper color code getter.
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
fun onPlayerChatPreprocess(event: PlayerCommandPreprocessEvent) {
|
||||
handlePreprocess(event.player, event.message, event)
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
fun onSystemChatPreprocess(event: ServerCommandEvent) {
|
||||
handlePreprocess(event.sender, "/" + event.command, event)
|
||||
if (event.isCancelled) event.command = "dontrunthiscmd" //Bugfix
|
||||
}
|
||||
|
||||
private fun handlePreprocess(sender: CommandSender, message: String, event: Cancellable) {
|
||||
if (event.isCancelled) return
|
||||
val cg = ChromaGamerBase.getFromSender(sender)
|
||||
val ev = TBMCCommandPreprocessEvent(cg, cg.channel.get(), message, cg)
|
||||
Bukkit.getPluginManager().callEvent(ev)
|
||||
if (ev.isCancelled) event.isCancelled = true //Cancel the original event
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
fun onTBMCPreprocess(event: TBMCCommandPreprocessEvent) {
|
||||
if (event.isCancelled) return
|
||||
try {
|
||||
val sender = Command2MCSender(event.sender, event.channel, event.permCheck)
|
||||
event.isCancelled = ButtonPlugin.command2MC.handleCommand(sender, event.message)
|
||||
} catch (e: Exception) {
|
||||
TBMCCoreAPI.SendException(
|
||||
"Command processing failed for sender '${event.sender}' and message '${event.message}'",
|
||||
e,
|
||||
plugin
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGH) //The one in the chat plugin is set to highest
|
||||
fun onPlayerChat(event: AsyncPlayerChatEvent) {
|
||||
if (event.isCancelled) return //The chat plugin should cancel it after this handler
|
||||
val cp = TBMCPlayerBase.getPlayer(event.player.uniqueId, TBMCPlayer::class.java)
|
||||
TBMCChatAPI.sendChatMessage(ChatMessage.builder(cp, event.message).build())
|
||||
//Not cancelling the original event here, it's cancelled in the chat plugin
|
||||
//This way other plugins can deal with the MC formatting if the chat plugin isn't present, but other platforms still get the message
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGH) //The one in the chat plugin is set to highest
|
||||
fun onPlayerChat(event: TBMCChatEvent) {
|
||||
if (event.isCancelled) return
|
||||
if (!plugin.isChatHandlerEnabled) return
|
||||
if (event.origin == "Minecraft") return //Let other plugins handle MC messages
|
||||
val channel = event.channel
|
||||
val msg = plugin.chatFormat.get()
|
||||
.replace("{channel}", channel.displayName.get())
|
||||
.replace("{origin}", event.origin.substring(0, 1))
|
||||
.replace("{name}", event.user.name)
|
||||
.replace("{message}", String.format("§%x%s", channel.color.get().ordinal, event.message))
|
||||
for (player in Bukkit.getOnlinePlayers()) if (event.shouldSendTo(player.asTBMC())) player.sendMessage(msg)
|
||||
Bukkit.getConsoleSender().sendMessage(msg)
|
||||
}
|
||||
}
|
50
Chroma-Core/src/main/java/buttondevteam/core/TestPrepare.java
Executable file
50
Chroma-Core/src/main/java/buttondevteam/core/TestPrepare.java
Executable file
|
@ -0,0 +1,50 @@
|
|||
package buttondevteam.core;
|
||||
|
||||
import buttondevteam.core.component.channel.Channel;
|
||||
import buttondevteam.core.component.channel.ChannelComponent;
|
||||
import buttondevteam.lib.ChromaUtils;
|
||||
import buttondevteam.lib.architecture.Component;
|
||||
import buttondevteam.lib.chat.Color;
|
||||
import buttondevteam.lib.chat.TBMCChatAPI;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Server;
|
||||
import org.bukkit.plugin.PluginManager;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
import org.bukkit.scheduler.BukkitScheduler;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.invocation.InvocationOnMock;
|
||||
import org.mockito.stubbing.Answer;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class TestPrepare {
|
||||
|
||||
public static void PrepareServer() {
|
||||
ChromaUtils.setTest(); //Needs to be in a separate class because of the potential lack of Mockito
|
||||
Bukkit.setServer(Mockito.mock(Server.class, new Answer<Object>() {
|
||||
|
||||
@Override
|
||||
public Object answer(InvocationOnMock invocation) {
|
||||
if (returns(invocation, String.class))
|
||||
return "test";
|
||||
if (returns(invocation, Logger.class))
|
||||
return Logger.getAnonymousLogger();
|
||||
if (returns(invocation, PluginManager.class))
|
||||
return Mockito.mock(PluginManager.class);
|
||||
if (returns(invocation, Collection.class))
|
||||
return Collections.EMPTY_LIST;
|
||||
if (returns(invocation, BukkitScheduler.class))
|
||||
return Mockito.mock(BukkitScheduler.class);
|
||||
return null;
|
||||
}
|
||||
|
||||
boolean returns(InvocationOnMock invocation, Class<?> cl) {
|
||||
return cl.isAssignableFrom(invocation.getMethod().getReturnType());
|
||||
}
|
||||
}));
|
||||
Component.registerComponent(Mockito.mock(JavaPlugin.class), new ChannelComponent());
|
||||
TBMCChatAPI.RegisterChatChannel(Channel.GlobalChat = new Channel("§fg§f", Color.White, "g", null));
|
||||
}
|
||||
}
|
237
Chroma-Core/src/main/java/buttondevteam/core/component/channel/Channel.java
Executable file
237
Chroma-Core/src/main/java/buttondevteam/core/component/channel/Channel.java
Executable file
|
@ -0,0 +1,237 @@
|
|||
package buttondevteam.core.component.channel;
|
||||
|
||||
import buttondevteam.core.ComponentManager;
|
||||
import buttondevteam.core.MainPlugin;
|
||||
import buttondevteam.lib.architecture.Component;
|
||||
import buttondevteam.lib.architecture.ConfigData;
|
||||
import buttondevteam.lib.architecture.IHaveConfig;
|
||||
import buttondevteam.lib.chat.Color;
|
||||
import com.google.common.collect.Lists;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.function.BiPredicate;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* Represents a chat channel. May only be instantiated after the channel component is registered.
|
||||
*/
|
||||
public class Channel {
|
||||
/**
|
||||
* Specifies a score that means it's OK to send - but it does not define any groups, only send or not send. See {@link #GROUP_EVERYONE}
|
||||
*/
|
||||
public static final int SCORE_SEND_OK = 0;
|
||||
/**
|
||||
* Specifies a score that means the user doesn't have permission to see or send the message. Any negative value has the same effect.
|
||||
*/
|
||||
public static final int SCORE_SEND_NOPE = -1;
|
||||
/**
|
||||
* Send the message to everyone <i>who has access to the channel</i> - this does not necessarily mean all players
|
||||
*/
|
||||
public static final String GROUP_EVERYONE = "everyone";
|
||||
|
||||
private static ChannelComponent component;
|
||||
|
||||
private String defDisplayName;
|
||||
private Color defColor;
|
||||
|
||||
private IHaveConfig config;
|
||||
|
||||
public final ConfigData<Boolean> Enabled;
|
||||
|
||||
/**
|
||||
* Must start with a color code
|
||||
*/
|
||||
public final ConfigData<String> DisplayName;
|
||||
|
||||
public final ConfigData<Color> Color;
|
||||
public final String ID;
|
||||
|
||||
public ConfigData<String[]> IDs;
|
||||
|
||||
/**
|
||||
* Filters both the sender and the targets
|
||||
*/
|
||||
private final Function<CommandSender, RecipientTestResult> filteranderrormsg;
|
||||
|
||||
private static final List<Channel> channels = new ArrayList<>();
|
||||
|
||||
/**
|
||||
* Creates a channel.
|
||||
*
|
||||
* @param displayname The name that should appear at the start of the message. <b>A chat color is expected at the beginning (§9).</b>
|
||||
* @param color The default color of the messages sent in the channel
|
||||
* @param command The command to be used for the channel <i>without /</i>. For example "mod". It's also used for scoreboard objective names.
|
||||
* @param filteranderrormsg Checks all senders against the criteria provided here and sends the message if the index matches the sender's - if no score at all, displays the error.<br>
|
||||
* May be null to send to everyone.
|
||||
*/
|
||||
public Channel(String displayname, Color color, String command,
|
||||
Function<CommandSender, RecipientTestResult> filteranderrormsg) {
|
||||
defDisplayName = displayname;
|
||||
defColor = color;
|
||||
ID = command;
|
||||
this.filteranderrormsg = filteranderrormsg;
|
||||
init();
|
||||
Enabled = component.getConfig().getData(ID + ".enabled", true);
|
||||
DisplayName = component.getConfig().getData(ID + ".displayName", defDisplayName);
|
||||
Color = component.getConfig().getData(ID + ".color", defColor, c -> buttondevteam.lib.chat.Color.valueOf((String) c), Enum::toString);
|
||||
//noinspection unchecked
|
||||
IDs = component.getConfig().getData(ID + ".IDs", new String[0], l -> ((List<String>) l).toArray(new String[0]), Lists::newArrayList);
|
||||
}
|
||||
|
||||
/**
|
||||
* Must be only called from a subclass - otherwise it'll throw an exception.
|
||||
*
|
||||
* @see Channel#Channel(String, Color, String, Function)
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
protected <T extends Channel> Channel(String displayname, Color color, String command,
|
||||
BiFunction<T, CommandSender, RecipientTestResult> filteranderrormsg) {
|
||||
defDisplayName = displayname;
|
||||
defColor = color;
|
||||
ID = command;
|
||||
this.filteranderrormsg = s -> filteranderrormsg.apply((T) this, s);
|
||||
init();
|
||||
Enabled = component.getConfig().getData(ID + ".enabled", true);
|
||||
DisplayName = component.getConfig().getData(ID + ".displayName", defDisplayName);
|
||||
Color = component.getConfig().getData(ID + ".color", defColor, c -> buttondevteam.lib.chat.Color.valueOf((String) c), Enum::toString);
|
||||
//noinspection unchecked
|
||||
IDs = component.getConfig().getData(ID + ".IDs", new String[0], l -> ((List<String>) l).toArray(new String[0]), Lists::newArrayList);
|
||||
}
|
||||
|
||||
private static void init() {
|
||||
if (component == null)
|
||||
component = (ChannelComponent) Component.getComponents().get(ChannelComponent.class);
|
||||
if (component == null)
|
||||
throw new RuntimeException("Attempting to create a channel before the component is registered!");
|
||||
}
|
||||
|
||||
public boolean isGlobal() {
|
||||
return filteranderrormsg == null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Note: Errors are sent to the sender automatically
|
||||
*
|
||||
* @param sender The user we're sending to
|
||||
* @param score The (source) score to compare with the user's
|
||||
*/
|
||||
public boolean shouldSendTo(CommandSender sender, int score) {
|
||||
return score == getMCScore(sender); //If there's any error, the score won't be equal
|
||||
}
|
||||
|
||||
/**
|
||||
* Note: Errors are sent to the sender automatically
|
||||
*/
|
||||
public int getMCScore(CommandSender sender) {
|
||||
return getRTR(sender).score; //No need to check if there was an error
|
||||
}
|
||||
|
||||
/**
|
||||
* Note: Errors are sent to the sender automatically<br>
|
||||
* <p>
|
||||
* Null means don't send
|
||||
*/
|
||||
@Nullable
|
||||
public String getGroupID(CommandSender sender) {
|
||||
return getRTR(sender).groupID; //No need to check if there was an error
|
||||
}
|
||||
|
||||
public RecipientTestResult getRTR(CommandSender sender) {
|
||||
if (filteranderrormsg == null)
|
||||
return new RecipientTestResult(SCORE_SEND_OK, GROUP_EVERYONE);
|
||||
return filteranderrormsg.apply(sender);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a stream of the enabled channels
|
||||
*
|
||||
* @return Only the enabled channels
|
||||
*/
|
||||
public static Stream<Channel> getChannels() {
|
||||
return channels.stream().filter(ch -> ch.Enabled.get());
|
||||
}
|
||||
|
||||
/**
|
||||
* Return all channels whether they're enabled or not
|
||||
*
|
||||
* @return A list of all channels
|
||||
*/
|
||||
public static List<Channel> getChannelList() {
|
||||
return Collections.unmodifiableList(channels);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convenience method for the function parameter of {@link #Channel(String, Color, String, Function)}. It checks if the sender is OP or optionally has the specified group. The error message is
|
||||
* generated automatically.
|
||||
*
|
||||
* @param permgroup The group that can access the channel or <b>null</b> to only allow OPs.
|
||||
* @return If has access
|
||||
*/
|
||||
public static Function<CommandSender, RecipientTestResult> inGroupFilter(String permgroup) {
|
||||
return noScoreResult(
|
||||
s -> s.isOp() || (permgroup != null && (s instanceof Player && MainPlugin.permission != null && MainPlugin.permission.playerInGroup((Player) s, permgroup))),
|
||||
"You need to be a(n) " + (permgroup != null ? permgroup : "OP") + " to use this channel.");
|
||||
}
|
||||
|
||||
public static Function<CommandSender, RecipientTestResult> noScoreResult(Predicate<CommandSender> filter,
|
||||
String errormsg) {
|
||||
return s -> filter.test(s) ? new RecipientTestResult(SCORE_SEND_OK, GROUP_EVERYONE) : new RecipientTestResult(errormsg);
|
||||
}
|
||||
|
||||
public static <T extends Channel> BiFunction<T, CommandSender, RecipientTestResult> noScoreResult(
|
||||
BiPredicate<T, CommandSender> filter, String errormsg) {
|
||||
return (this_, s) -> filter.test(this_, s) ? new RecipientTestResult(SCORE_SEND_OK, GROUP_EVERYONE) : new RecipientTestResult(errormsg);
|
||||
}
|
||||
|
||||
public static Channel GlobalChat;
|
||||
public static Channel AdminChat;
|
||||
public static Channel ModChat;
|
||||
|
||||
public static void RegisterChannel(Channel channel) {
|
||||
if (!channel.isGlobal() && !ComponentManager.isEnabled(ChannelComponent.class))
|
||||
return; //Allow registering the global chat (and I guess other chats like the RP chat)
|
||||
channels.add(channel);
|
||||
component.registerChannelCommand(channel);
|
||||
Bukkit.getScheduler().runTask(MainPlugin.Instance, () -> Bukkit.getPluginManager().callEvent(new ChatChannelRegisterEvent(channel))); // Wait for server start
|
||||
}
|
||||
|
||||
public static class RecipientTestResult {
|
||||
public final String errormessage;
|
||||
public final int score; // Anything below 0 is "never send"
|
||||
public final String groupID;
|
||||
public static final RecipientTestResult ALL = new RecipientTestResult(SCORE_SEND_OK, GROUP_EVERYONE);
|
||||
|
||||
/**
|
||||
* Creates a result that indicates an <b>error</b>
|
||||
*
|
||||
* @param errormessage The error message to show the sender if they don't meet the criteria.
|
||||
*/
|
||||
public RecipientTestResult(String errormessage) {
|
||||
this.errormessage = errormessage;
|
||||
this.score = SCORE_SEND_NOPE;
|
||||
this.groupID = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a result that indicates a <b>success</b>
|
||||
*
|
||||
* @param score The score that identifies the target group. <b>Must be non-negative.</b> For example, the index of the town or nation to send to.
|
||||
* @param groupID The ID of the target group.
|
||||
*/
|
||||
public RecipientTestResult(int score, String groupID) {
|
||||
if (score < 0) throw new IllegalArgumentException("Score must be non-negative!");
|
||||
this.score = score;
|
||||
this.groupID = groupID;
|
||||
this.errormessage = null;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,225 +0,0 @@
|
|||
package buttondevteam.core.component.channel
|
||||
|
||||
import buttondevteam.core.ComponentManager.get
|
||||
import buttondevteam.lib.architecture.IHaveConfig
|
||||
import buttondevteam.lib.player.ChromaGamerBase
|
||||
import org.bukkit.Bukkit
|
||||
import org.bukkit.ChatColor
|
||||
import java.util.*
|
||||
import java.util.function.Function
|
||||
import java.util.function.Predicate
|
||||
import java.util.stream.Stream
|
||||
|
||||
/**
|
||||
* Represents a chat channel. May only be instantiated after the channel component is registered.
|
||||
*/
|
||||
open class Channel
|
||||
/**
|
||||
* Creates a channel.
|
||||
*
|
||||
* @param filterAndErrorMSG Checks all senders against the criteria provided here and sends the message if the index matches the sender's - if no score at all, displays the error.
|
||||
*
|
||||
* May be null to send to everyone.
|
||||
*/(
|
||||
/**
|
||||
* The name that should appear at the start of the message. **A chat color is expected at the beginning (§9).**
|
||||
*/
|
||||
private val defDisplayName: String,
|
||||
/**
|
||||
* The default color of the messages sent in the channel
|
||||
*/
|
||||
private val defColor: ChatColor,
|
||||
/**
|
||||
* The channel identifier. It's the same as the command to be used for the channel *without / *. For example "mod".
|
||||
* It's also used for scoreboard objective names.
|
||||
*/
|
||||
val identifier: String,
|
||||
/**
|
||||
* A function that determines who has permission to see the channel.
|
||||
* If the sender doesn't have access, they cannot send the message.
|
||||
* Only those with access can see the messages.
|
||||
* If null, everyone has access.
|
||||
*/
|
||||
private val filterAndErrorMSG: Function<ChromaGamerBase, RecipientTestResult>?
|
||||
) {
|
||||
private val config: IHaveConfig? = null // TODO: Use this
|
||||
|
||||
@JvmField
|
||||
val isEnabled = component.config.getData("${this.identifier}.enabled", true)
|
||||
|
||||
/**
|
||||
* Must start with a color code
|
||||
*/
|
||||
@JvmField
|
||||
val displayName = component.config.getData("${this.identifier}.displayName", this.defDisplayName)
|
||||
|
||||
@JvmField
|
||||
val color = component.config.getData(
|
||||
"${this.identifier}.color",
|
||||
this.defColor, { c -> ChatColor.getByChar(c as Char) ?: this.defColor }, ChatColor::getChar
|
||||
)
|
||||
|
||||
@JvmField
|
||||
val extraIdentifiers = component.config.getListData("${this.identifier}.IDs", listOf<String>())
|
||||
|
||||
val isGlobal: Boolean
|
||||
get() = filterAndErrorMSG == null
|
||||
|
||||
/**
|
||||
* Note: Errors are sent to the sender automatically
|
||||
*
|
||||
* @param sender The user we're sending to
|
||||
* @param score The (source) score to compare with the user's
|
||||
*/
|
||||
fun shouldSendTo(sender: ChromaGamerBase, score: Int): Boolean {
|
||||
return score == getMCScore(sender) //If there's any error, the score won't be equal
|
||||
}
|
||||
|
||||
/**
|
||||
* Note: Errors are sent to the sender automatically
|
||||
*/
|
||||
fun getMCScore(sender: ChromaGamerBase): Int {
|
||||
return getRTR(sender).score //No need to check if there was an error
|
||||
}
|
||||
|
||||
/**
|
||||
* Note: Errors are sent to the sender automatically
|
||||
*
|
||||
* Null means don't send
|
||||
*/
|
||||
fun getGroupID(sender: ChromaGamerBase): String? {
|
||||
return getRTR(sender).groupID //No need to check if there was an error
|
||||
}
|
||||
|
||||
fun getRTR(sender: ChromaGamerBase): RecipientTestResult {
|
||||
return filterAndErrorMSG?.apply(sender) ?: RecipientTestResult(SCORE_SEND_OK, GROUP_EVERYONE)
|
||||
}
|
||||
|
||||
class RecipientTestResult {
|
||||
@JvmField
|
||||
val errormessage: String?
|
||||
|
||||
@JvmField
|
||||
val score // Anything below 0 is "never send"
|
||||
: Int
|
||||
|
||||
@JvmField
|
||||
val groupID: String?
|
||||
|
||||
/**
|
||||
* Creates a result that indicates an **error**
|
||||
*
|
||||
* @param errormessage The error message to show the sender if they don't meet the criteria.
|
||||
*/
|
||||
constructor(errormessage: String?) {
|
||||
this.errormessage = errormessage
|
||||
score = SCORE_SEND_NOPE
|
||||
groupID = null
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a result that indicates a **success**
|
||||
*
|
||||
* @param score The score that identifies the target group. **Must be non-negative.** For example, the index of the town or nation to send to.
|
||||
* @param groupID The ID of the target group.
|
||||
*/
|
||||
constructor(score: Int, groupID: String?) {
|
||||
require(score >= 0) { "Score must be non-negative!" }
|
||||
this.score = score
|
||||
this.groupID = groupID
|
||||
errormessage = null
|
||||
}
|
||||
|
||||
companion object {
|
||||
@JvmField
|
||||
val ALL = RecipientTestResult(SCORE_SEND_OK, GROUP_EVERYONE)
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
/**
|
||||
* Specifies a score that means it's OK to send - but it does not define any groups, only send or not send. See [.GROUP_EVERYONE]
|
||||
*/
|
||||
const val SCORE_SEND_OK = 0
|
||||
|
||||
/**
|
||||
* Specifies a score that means the user doesn't have permission to see or send the message. Any negative value has the same effect.
|
||||
*/
|
||||
const val SCORE_SEND_NOPE = -1
|
||||
|
||||
/**
|
||||
* Send the message to everyone *who has access to the channel* - this does not necessarily mean all players
|
||||
*/
|
||||
const val GROUP_EVERYONE = "everyone"
|
||||
private val component: ChannelComponent by lazy {
|
||||
get(ChannelComponent::class.java)
|
||||
?: throw RuntimeException("Attempting to create a channel before the component is registered!")
|
||||
}
|
||||
private val channels: MutableList<Channel> = ArrayList()
|
||||
|
||||
/**
|
||||
* Get a stream of the enabled channels
|
||||
*
|
||||
* @return Only the enabled channels
|
||||
*/
|
||||
@JvmStatic
|
||||
fun getChannels(): Stream<Channel> {
|
||||
return channels.stream().filter { ch: Channel -> ch.isEnabled.get() }
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
val channelList: List<Channel>
|
||||
/**
|
||||
* Return all channels whether they're enabled or not
|
||||
*
|
||||
* @return A list of all channels
|
||||
*/
|
||||
get() = Collections.unmodifiableList(channels)
|
||||
|
||||
/**
|
||||
* Convenience method for the function parameter of [.Channel]. It checks if the sender is OP or optionally has the specified group. The error message is
|
||||
* generated automatically.
|
||||
*
|
||||
* @param permgroup The group that can access the channel or **null** to only allow OPs.
|
||||
* @return If has access
|
||||
*/
|
||||
@JvmStatic
|
||||
fun inGroupFilter(permgroup: String?): Function<ChromaGamerBase, RecipientTestResult> {
|
||||
return Function { it.checkChannelInGroup(permgroup) }
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun noScoreResult(
|
||||
filter: Predicate<ChromaGamerBase>,
|
||||
errormsg: String?
|
||||
): Function<ChromaGamerBase, RecipientTestResult> {
|
||||
return Function { noScoreResult(filter, errormsg, it) }
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun noScoreResult(
|
||||
filter: Predicate<ChromaGamerBase>,
|
||||
errormsg: String?,
|
||||
user: ChromaGamerBase
|
||||
): RecipientTestResult {
|
||||
return if (filter.test(user)) RecipientTestResult(SCORE_SEND_OK, GROUP_EVERYONE)
|
||||
else RecipientTestResult(errormsg)
|
||||
}
|
||||
|
||||
lateinit var globalChat: Channel
|
||||
lateinit var adminChat: Channel
|
||||
lateinit var modChat: Channel
|
||||
|
||||
@JvmStatic
|
||||
fun registerChannel(channel: Channel) {
|
||||
if (!channel.isGlobal && !component.isEnabled) return //Allow registering the global chat (and I guess other chats like the RP chat)
|
||||
channels.add(channel)
|
||||
component.registerChannelCommand(channel)
|
||||
Bukkit.getScheduler().runTask(component.plugin,
|
||||
Runnable {
|
||||
Bukkit.getPluginManager().callEvent(ChatChannelRegisterEvent(channel))
|
||||
}) // Wait for server start
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,83 @@
|
|||
package buttondevteam.core.component.channel;
|
||||
|
||||
import buttondevteam.lib.ChromaUtils;
|
||||
import buttondevteam.lib.TBMCSystemChatEvent;
|
||||
import buttondevteam.lib.architecture.Component;
|
||||
import buttondevteam.lib.chat.*;
|
||||
import buttondevteam.lib.player.ChromaGamerBase;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
|
||||
/**
|
||||
* Manages chat channels. If disabled, only global channels will be registered.
|
||||
*/
|
||||
public class ChannelComponent extends Component<JavaPlugin> {
|
||||
static TBMCSystemChatEvent.BroadcastTarget roomJoinLeave;
|
||||
|
||||
@Override
|
||||
protected void register(JavaPlugin plugin) {
|
||||
super.register(plugin);
|
||||
roomJoinLeave = TBMCSystemChatEvent.BroadcastTarget.add("roomJoinLeave"); //Even if it's disabled, global channels continue to work
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void unregister(JavaPlugin plugin) {
|
||||
super.unregister(plugin);
|
||||
TBMCSystemChatEvent.BroadcastTarget.remove(roomJoinLeave);
|
||||
roomJoinLeave = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void enable() {
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void disable() {
|
||||
}
|
||||
|
||||
void registerChannelCommand(Channel channel) {
|
||||
if (!ChromaUtils.isTest())
|
||||
registerCommand(new ChannelCommand(channel));
|
||||
}
|
||||
|
||||
@CommandClass
|
||||
@RequiredArgsConstructor
|
||||
private static class ChannelCommand extends ICommand2MC {
|
||||
private final Channel channel;
|
||||
|
||||
@Override
|
||||
public String getCommandPath() {
|
||||
return channel.ID;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String[] getCommandPaths() {
|
||||
return channel.IDs.get();
|
||||
}
|
||||
|
||||
@Command2.Subcommand
|
||||
public void def(Command2MCSender senderMC, @Command2.OptionalArg @Command2.TextArg String message) {
|
||||
var sender = senderMC.getSender();
|
||||
var user = ChromaGamerBase.getFromSender(sender);
|
||||
if (user == null) {
|
||||
sender.sendMessage("§cYou can't use channels from this platform.");
|
||||
return;
|
||||
}
|
||||
if (message == null) {
|
||||
Channel oldch = user.channel.get();
|
||||
if (oldch instanceof ChatRoom)
|
||||
((ChatRoom) oldch).leaveRoom(sender);
|
||||
if (oldch.equals(channel))
|
||||
user.channel.set(Channel.GlobalChat);
|
||||
else {
|
||||
user.channel.set(channel);
|
||||
if (channel instanceof ChatRoom)
|
||||
((ChatRoom) channel).joinRoom(sender);
|
||||
}
|
||||
sender.sendMessage("§6You are now talking in: §b" + user.channel.get().DisplayName.get());
|
||||
} else
|
||||
TBMCChatAPI.SendChatMessage(ChatMessage.builder(sender, user, message).fromCommand(true)
|
||||
.permCheck(senderMC.getPermCheck()).build(), channel);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,60 +0,0 @@
|
|||
package buttondevteam.core.component.channel
|
||||
|
||||
import buttondevteam.lib.ChromaUtils
|
||||
import buttondevteam.lib.TBMCSystemChatEvent.BroadcastTarget
|
||||
import buttondevteam.lib.architecture.Component
|
||||
import buttondevteam.lib.chat.*
|
||||
import buttondevteam.lib.chat.Command2.*
|
||||
import org.bukkit.ChatColor
|
||||
import org.bukkit.plugin.java.JavaPlugin
|
||||
|
||||
/**
|
||||
* Manages chat channels. If disabled, only global channels will be registered.
|
||||
*/
|
||||
class ChannelComponent : Component<JavaPlugin>() {
|
||||
override fun register(plugin: JavaPlugin) {
|
||||
super.register(plugin)
|
||||
roomJoinLeave = BroadcastTarget.add("roomJoinLeave") //Even if it's disabled, global channels continue to work
|
||||
}
|
||||
|
||||
override fun unregister(plugin: JavaPlugin) {
|
||||
super.unregister(plugin)
|
||||
BroadcastTarget.remove(roomJoinLeave)
|
||||
roomJoinLeave = null
|
||||
}
|
||||
|
||||
override fun enable() {}
|
||||
override fun disable() {}
|
||||
fun registerChannelCommand(channel: Channel) {
|
||||
if (!ChromaUtils.isTest) registerCommand(ChannelCommand(channel))
|
||||
}
|
||||
|
||||
@CommandClass
|
||||
private class ChannelCommand(private val channel: Channel) : ICommand2MC() {
|
||||
override val commandPath: String
|
||||
get() = channel.identifier
|
||||
override val commandPaths: Array<String>
|
||||
get() = channel.extraIdentifiers.get().toTypedArray()
|
||||
|
||||
@Subcommand
|
||||
fun def(senderMC: Command2MCSender, @OptionalArg @TextArg message: String?) {
|
||||
val user = senderMC.sender
|
||||
if (message == null) {
|
||||
val oldch = user.channel.get()
|
||||
if (oldch is ChatRoom) oldch.leaveRoom(user)
|
||||
if (oldch == channel) user.channel.set(Channel.globalChat) else {
|
||||
user.channel.set(channel)
|
||||
if (channel is ChatRoom) channel.joinRoom(user)
|
||||
}
|
||||
user.sendMessage("${ChatColor.GOLD}You are now talking in: ${ChatColor.AQUA}" + user.channel.get().displayName.get())
|
||||
} else TBMCChatAPI.sendChatMessage(
|
||||
ChatMessage.builder(user, message).fromCommand(true)
|
||||
.permCheck(senderMC.permCheck).build(), channel
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
var roomJoinLeave: BroadcastTarget? = null
|
||||
}
|
||||
}
|
28
Chroma-Core/src/main/java/buttondevteam/core/component/channel/ChatRoom.java
Executable file
28
Chroma-Core/src/main/java/buttondevteam/core/component/channel/ChatRoom.java
Executable file
|
@ -0,0 +1,28 @@
|
|||
package buttondevteam.core.component.channel;
|
||||
|
||||
import buttondevteam.lib.TBMCSystemChatEvent;
|
||||
import buttondevteam.lib.chat.Color;
|
||||
import buttondevteam.lib.chat.TBMCChatAPI;
|
||||
import org.bukkit.command.CommandSender;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class ChatRoom extends Channel {
|
||||
private final List<CommandSender> usersInRoom = new ArrayList<>();
|
||||
|
||||
public ChatRoom(String displayname, Color color, String command) {
|
||||
<ChatRoom>super(displayname, color, command, noScoreResult((this_, s) -> this_.usersInRoom.contains(s),
|
||||
"Not implemented yet. Please report it to the devs along with which platform you're trying to talk from."));
|
||||
}
|
||||
|
||||
public void joinRoom(CommandSender sender) {
|
||||
usersInRoom.add(sender);
|
||||
TBMCChatAPI.SendSystemMessage(this, RecipientTestResult.ALL, sender.getName() + " joined the room", TBMCSystemChatEvent.BroadcastTarget.ALL); //Always show message in the same kind of channel
|
||||
}
|
||||
|
||||
public void leaveRoom(CommandSender sender) {
|
||||
usersInRoom.remove(sender);
|
||||
TBMCChatAPI.SendSystemMessage(this, RecipientTestResult.ALL, sender.getName() + " left the room", ChannelComponent.roomJoinLeave);
|
||||
}
|
||||
}
|
|
@ -1,35 +0,0 @@
|
|||
package buttondevteam.core.component.channel
|
||||
|
||||
import buttondevteam.lib.TBMCSystemChatEvent
|
||||
import buttondevteam.lib.chat.TBMCChatAPI
|
||||
import buttondevteam.lib.player.ChromaGamerBase
|
||||
import org.bukkit.ChatColor
|
||||
|
||||
class ChatRoom(displayname: String, color: ChatColor, command: String) : Channel(
|
||||
displayname, color, command, null // TODO: Custom filter for rooms using abstract method
|
||||
) {
|
||||
private val usersInRoom: MutableList<ChromaGamerBase> = ArrayList()
|
||||
private fun isInRoom(sender: ChromaGamerBase): Boolean {
|
||||
return usersInRoom.contains(sender)
|
||||
}
|
||||
|
||||
fun joinRoom(sender: ChromaGamerBase) {
|
||||
usersInRoom.add(sender)
|
||||
TBMCChatAPI.SendSystemMessage(
|
||||
this,
|
||||
RecipientTestResult.ALL,
|
||||
sender.name + " joined the room",
|
||||
TBMCSystemChatEvent.BroadcastTarget.ALL
|
||||
) //Always show message in the same kind of channel
|
||||
}
|
||||
|
||||
fun leaveRoom(sender: ChromaGamerBase) {
|
||||
usersInRoom.remove(sender)
|
||||
TBMCChatAPI.SendSystemMessage(
|
||||
this,
|
||||
RecipientTestResult.ALL,
|
||||
sender.name + " left the room",
|
||||
ChannelComponent.roomJoinLeave
|
||||
)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,72 @@
|
|||
package buttondevteam.core.component.members;
|
||||
|
||||
import buttondevteam.core.MainPlugin;
|
||||
import buttondevteam.lib.chat.Command2;
|
||||
import buttondevteam.lib.chat.CommandClass;
|
||||
import buttondevteam.lib.chat.ICommand2MC;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@CommandClass(path = "member", helpText = { //
|
||||
"Member command", //
|
||||
"Add or remove server members.", //
|
||||
})
|
||||
public class MemberCommand extends ICommand2MC {
|
||||
private final MemberComponent component;
|
||||
|
||||
public MemberCommand(MemberComponent component) {
|
||||
this.component = component;
|
||||
}
|
||||
|
||||
@Command2.Subcommand(permGroup = Command2.Subcommand.MOD_GROUP)
|
||||
public boolean add(CommandSender sender, OfflinePlayer player) {
|
||||
return addRemove(sender, player, true);
|
||||
}
|
||||
|
||||
@Command2.Subcommand(permGroup = Command2.Subcommand.MOD_GROUP)
|
||||
public boolean remove(CommandSender sender, OfflinePlayer player) {
|
||||
return addRemove(sender, player, false);
|
||||
}
|
||||
|
||||
public boolean addRemove(CommandSender sender, OfflinePlayer op, boolean add) {
|
||||
Bukkit.getScheduler().runTaskAsynchronously(MainPlugin.Instance, () -> {
|
||||
if (!op.hasPlayedBefore()) {
|
||||
sender.sendMessage("§cCannot find player or haven't played before.");
|
||||
return;
|
||||
}
|
||||
if (add ? MainPlugin.permission.playerAddGroup(null, op, component.memberGroup.get())
|
||||
: MainPlugin.permission.playerRemoveGroup(null, op, component.memberGroup.get()))
|
||||
sender.sendMessage("§b" + op.getName() + " " + (add ? "added" : "removed") + " as a member!");
|
||||
else
|
||||
sender.sendMessage("§cFailed to " + (add ? "add" : "remove") + " " + op.getName() + " as a member!");
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
@Command2.Subcommand
|
||||
public void def(Player player) {
|
||||
String msg;
|
||||
if (!component.checkNotMember(player))
|
||||
msg = "You are a member.";
|
||||
else {
|
||||
double pt = component.getPlayTime(player);
|
||||
long rt = component.getRegTime(player);
|
||||
if (pt == -1 || rt == -1) {
|
||||
Boolean result = component.addPlayerAsMember(player);
|
||||
if (result == null)
|
||||
msg = "Can't assign member group because groups are not supported by the permissions plugin.";
|
||||
else if (result)
|
||||
msg = "You meet all the requirements.";
|
||||
else
|
||||
msg = "You should be a member but failed to add you to the group.";
|
||||
} else
|
||||
msg = String.format("You need to play for %.2f hours total or play for %d more days to become a member.",
|
||||
pt, TimeUnit.MILLISECONDS.toDays(rt));
|
||||
}
|
||||
player.sendMessage(msg);
|
||||
}
|
||||
}
|
|
@ -1,67 +0,0 @@
|
|||
package buttondevteam.core.component.members
|
||||
|
||||
import buttondevteam.core.MainPlugin
|
||||
import buttondevteam.lib.chat.Command2.Subcommand
|
||||
import buttondevteam.lib.chat.CommandClass
|
||||
import buttondevteam.lib.chat.ICommand2MC
|
||||
import buttondevteam.lib.chat.commands.MCCommandSettings
|
||||
import org.bukkit.Bukkit
|
||||
import org.bukkit.ChatColor
|
||||
import org.bukkit.OfflinePlayer
|
||||
import org.bukkit.command.CommandSender
|
||||
import org.bukkit.entity.Player
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
@CommandClass(
|
||||
path = "member", helpText = [ //
|
||||
"Member command", //
|
||||
"Add or remove server members."]
|
||||
)
|
||||
class MemberCommand() : ICommand2MC() {
|
||||
@Subcommand
|
||||
@MCCommandSettings(permGroup = MCCommandSettings.MOD_GROUP)
|
||||
fun add(sender: CommandSender, player: OfflinePlayer): Boolean {
|
||||
return addRemove(sender, player, true)
|
||||
}
|
||||
|
||||
@Subcommand
|
||||
@MCCommandSettings(permGroup = MCCommandSettings.MOD_GROUP)
|
||||
fun remove(sender: CommandSender, player: OfflinePlayer): Boolean {
|
||||
return addRemove(sender, player, false)
|
||||
}
|
||||
|
||||
private fun addRemove(sender: CommandSender, op: OfflinePlayer, add: Boolean): Boolean {
|
||||
Bukkit.getScheduler().runTaskAsynchronously(MainPlugin.instance, Runnable {
|
||||
val component = component as MemberComponent
|
||||
if (!op.hasPlayedBefore()) {
|
||||
sender.sendMessage("${ChatColor.RED}Cannot find player or haven't played before.")
|
||||
return@Runnable
|
||||
}
|
||||
if (if (add) MainPlugin.permission.playerAddGroup(null, op, component.memberGroup.get())
|
||||
else MainPlugin.permission.playerRemoveGroup(null, op, component.memberGroup.get())
|
||||
)
|
||||
sender.sendMessage("${ChatColor.AQUA}${op.name} ${if (add) "added" else "removed"} as a member!")
|
||||
else sender.sendMessage("${ChatColor.RED}Failed to ${if (add) "add" else "remove"} ${op.name} as a member!")
|
||||
})
|
||||
return true
|
||||
}
|
||||
|
||||
@Subcommand
|
||||
fun def(player: Player) {
|
||||
val component = component as MemberComponent
|
||||
val msg = if (!component.checkNotMember(player)) "You are a member." else {
|
||||
val pt = component.getPlayTime(player)
|
||||
val rt = component.getRegTime(player)
|
||||
if (pt == -1.0 || rt == -1L) {
|
||||
val result = component.addPlayerAsMember(player)
|
||||
if (result == null) "Can't assign member group because groups are not supported by the permissions plugin."
|
||||
else if (result) "You meet all the requirements."
|
||||
else "You should be a member but failed to add you to the group."
|
||||
} else String.format(
|
||||
"You need to play for %.2f hours total or play for %d more days to become a member.",
|
||||
pt, TimeUnit.MILLISECONDS.toDays(rt)
|
||||
)
|
||||
}
|
||||
player.sendMessage(msg)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,115 @@
|
|||
package buttondevteam.core.component.members;
|
||||
|
||||
import buttondevteam.core.MainPlugin;
|
||||
import buttondevteam.lib.architecture.Component;
|
||||
import buttondevteam.lib.architecture.ComponentMetadata;
|
||||
import buttondevteam.lib.architecture.ConfigData;
|
||||
import org.bukkit.Statistic;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.PlayerJoinEvent;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.AbstractMap;
|
||||
import java.util.Date;
|
||||
|
||||
import static buttondevteam.core.MainPlugin.permission;
|
||||
|
||||
/**
|
||||
* Allows giving a 'member' group over some time elapsed OR played.
|
||||
*/
|
||||
@ComponentMetadata(enabledByDefault = false)
|
||||
public class MemberComponent extends Component<MainPlugin> implements Listener {
|
||||
/**
|
||||
* The permission group to give to the player
|
||||
*/
|
||||
final ConfigData<String> memberGroup = getConfig().getData("memberGroup", "member");
|
||||
|
||||
/**
|
||||
* The amount of hours needed to play before promotion
|
||||
*/
|
||||
private final ConfigData<Integer> playedHours = getConfig().getData("playedHours", 12);
|
||||
|
||||
/**
|
||||
* The amount of days passed since first login
|
||||
*/
|
||||
private final ConfigData<Integer> registeredForDays = getConfig().getData("registeredForDays", 7);
|
||||
|
||||
private AbstractMap.SimpleEntry<Statistic, Integer> playtime;
|
||||
|
||||
@Override
|
||||
protected void enable() {
|
||||
registerListener(this);
|
||||
registerCommand(new MemberCommand(this));
|
||||
try {
|
||||
playtime = new AbstractMap.SimpleEntry<>(Statistic.valueOf("PLAY_ONE_MINUTE"), 60); //1.14
|
||||
} catch (IllegalArgumentException e) {
|
||||
playtime = new AbstractMap.SimpleEntry<>(Statistic.valueOf("PLAY_ONE_TICK"), 20 * 3600); //1.12
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void disable() {
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onPlayerJoin(PlayerJoinEvent event) {
|
||||
if (checkNotMember(event.getPlayer()) && (checkRegTime(event.getPlayer()) || checkPlayTime(event.getPlayer()))) {
|
||||
addPlayerAsMember(event.getPlayer());
|
||||
}
|
||||
}
|
||||
|
||||
public Boolean addPlayerAsMember(Player player) {
|
||||
try {
|
||||
if (permission.playerAddGroup(null, player, memberGroup.get())) {
|
||||
player.sendMessage("§bYou are a member now!");
|
||||
log("Added " + player.getName() + " as a member.");
|
||||
return true;
|
||||
} else {
|
||||
logWarn("Failed to assign the member role! Please make sure the member group exists or disable the component if it's unused.");
|
||||
return false;
|
||||
}
|
||||
} catch (UnsupportedOperationException e) {
|
||||
logWarn("Failed to assign the member role! Groups are not supported by the permissions implementation.");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean checkNotMember(Player player) {
|
||||
return permission != null && !permission.playerInGroup(player, memberGroup.get());
|
||||
}
|
||||
|
||||
public boolean checkRegTime(Player player) {
|
||||
return getRegTime(player) == -1;
|
||||
}
|
||||
|
||||
public boolean checkPlayTime(Player player) {
|
||||
return getPlayTime(player) > playtime.getValue() * playedHours.get();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns milliseconds
|
||||
*/
|
||||
public long getRegTime(Player player) {
|
||||
Instant date = new Date(player.getFirstPlayed()).toInstant().plus(registeredForDays.get(), ChronoUnit.DAYS);
|
||||
if (date.isAfter(Instant.now()))
|
||||
return date.toEpochMilli() - Instant.now().toEpochMilli();
|
||||
return -1;
|
||||
}
|
||||
|
||||
public int getPlayTimeTotal(Player player) {
|
||||
return player.getStatistic(playtime.getKey());
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns hours
|
||||
*/
|
||||
public double getPlayTime(Player player) {
|
||||
double pt = playedHours.get() - (double) getPlayTimeTotal(player) / playtime.getValue();
|
||||
if (pt < 0) return -1;
|
||||
return pt;
|
||||
}
|
||||
|
||||
}
|
|
@ -1,101 +0,0 @@
|
|||
package buttondevteam.core.component.members
|
||||
|
||||
import buttondevteam.core.MainPlugin
|
||||
import buttondevteam.lib.architecture.Component
|
||||
import buttondevteam.lib.architecture.ComponentMetadata
|
||||
import org.bukkit.Statistic
|
||||
import org.bukkit.entity.Player
|
||||
import org.bukkit.event.EventHandler
|
||||
import org.bukkit.event.Listener
|
||||
import org.bukkit.event.player.PlayerJoinEvent
|
||||
import java.time.Instant
|
||||
import java.time.temporal.ChronoUnit
|
||||
import java.util.*
|
||||
|
||||
/**
|
||||
* Allows giving a 'member' group over some time elapsed OR played.
|
||||
*/
|
||||
@ComponentMetadata(enabledByDefault = false)
|
||||
class MemberComponent : Component<MainPlugin>(), Listener {
|
||||
/**
|
||||
* The permission group to give to the player
|
||||
*/
|
||||
val memberGroup get() = config.getData("memberGroup", "member")
|
||||
|
||||
/**
|
||||
* The amount of hours needed to play before promotion
|
||||
*/
|
||||
private val playedHours get() = config.getData("playedHours", 12)
|
||||
|
||||
/**
|
||||
* The amount of days passed since first login
|
||||
*/
|
||||
private val registeredForDays get() = config.getData("registeredForDays", 7)
|
||||
private var playtime: Pair<Statistic, Int>? = null
|
||||
override fun enable() {
|
||||
registerListener(this)
|
||||
registerCommand(MemberCommand())
|
||||
playtime = try {
|
||||
Pair(Statistic.valueOf("PLAY_ONE_MINUTE"), 60) //1.14
|
||||
} catch (e: IllegalArgumentException) {
|
||||
Pair(Statistic.valueOf("PLAY_ONE_TICK"), 20 * 3600) //1.12
|
||||
}
|
||||
}
|
||||
|
||||
override fun disable() {}
|
||||
|
||||
@EventHandler
|
||||
fun onPlayerJoin(event: PlayerJoinEvent) {
|
||||
if (checkNotMember(event.player) && (checkRegTime(event.player) || checkPlayTime(event.player))) {
|
||||
addPlayerAsMember(event.player)
|
||||
}
|
||||
}
|
||||
|
||||
fun addPlayerAsMember(player: Player): Boolean? {
|
||||
return try {
|
||||
if (MainPlugin.permission.playerAddGroup(null, player, memberGroup.get())) {
|
||||
player.sendMessage("\${ChatColor.AQUA}You are a member now!")
|
||||
log("Added " + player.name + " as a member.")
|
||||
true
|
||||
} else {
|
||||
logWarn("Failed to assign the member role! Please make sure the member group exists or disable the component if it's unused.")
|
||||
false
|
||||
}
|
||||
} catch (e: UnsupportedOperationException) {
|
||||
logWarn("Failed to assign the member role! Groups are not supported by the permissions implementation.")
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
fun checkNotMember(player: Player?): Boolean {
|
||||
return !MainPlugin.permission.playerInGroup(player, memberGroup.get())
|
||||
}
|
||||
|
||||
fun checkRegTime(player: Player): Boolean {
|
||||
return getRegTime(player) == -1L
|
||||
}
|
||||
|
||||
fun checkPlayTime(player: Player): Boolean {
|
||||
return getPlayTime(player) > playtime!!.second * playedHours.get()
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns milliseconds
|
||||
*/
|
||||
fun getRegTime(player: Player): Long {
|
||||
val date = Date(player.firstPlayed).toInstant().plus(registeredForDays.get().toLong(), ChronoUnit.DAYS)
|
||||
return if (date.isAfter(Instant.now())) date.toEpochMilli() - Instant.now().toEpochMilli() else -1
|
||||
}
|
||||
|
||||
fun getPlayTimeTotal(player: Player): Int {
|
||||
return player.getStatistic(playtime!!.first)
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns hours
|
||||
*/
|
||||
fun getPlayTime(player: Player): Double {
|
||||
val pt = playedHours.get() - getPlayTimeTotal(player).toDouble() / playtime!!.second
|
||||
return if (pt < 0) (-1).toDouble() else pt
|
||||
}
|
||||
}
|
|
@ -7,9 +7,11 @@ import org.bukkit.*;
|
|||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import java.util.logging.Logger;
|
||||
|
||||
// @formatter:off
|
||||
@SuppressWarnings("FieldCanBeLocal")@CommandClass(helpText = {
|
||||
"Random Teleport",
|
||||
"§6---- Random Teleport ----",
|
||||
"Teleport player to random location within world border. Every five players teleport to the same general area, and then a new general area is randomly selected for the next five players."
|
||||
})
|
||||
public class RandomTP extends ICommand2MC
|
||||
|
@ -92,7 +94,7 @@ public class RandomTP extends ICommand2MC
|
|||
&& !newLocation())
|
||||
{
|
||||
//if unable to find new location, message player and return false
|
||||
player.sendMessage("§ccould not find a location in 10,000 attempts");
|
||||
player.sendMessage("§c could not find a location in 10,000 attempts");
|
||||
player.sendMessage("§c (sorry bud... I did try!)");
|
||||
return false;
|
||||
}
|
||||
|
@ -175,25 +177,37 @@ public class RandomTP extends ICommand2MC
|
|||
southHeadMaterial == Material.AIR &&
|
||||
eastHeadMaterial == Material.AIR &&
|
||||
westHeadMaterial == Material.AIR &&
|
||||
|
||||
|
||||
centerFeetMaterial == Material.AIR &&
|
||||
northFeetMaterial == Material.AIR &&
|
||||
southFeetMaterial == Material.AIR &&
|
||||
eastFeetMaterial == Material.AIR &&
|
||||
westFeetMaterial == Material.AIR &&
|
||||
|
||||
|
||||
centerGroundMaterial != Material.AIR &&
|
||||
northGroundMaterial != Material.AIR &&
|
||||
southGroundMaterial != Material.AIR &&
|
||||
eastGroundMaterial != Material.AIR &&
|
||||
westGroundMaterial != Material.AIR &&
|
||||
|
||||
|
||||
centerGroundMaterial != Material.STATIONARY_WATER &&
|
||||
northGroundMaterial != Material.STATIONARY_WATER &&
|
||||
southGroundMaterial != Material.STATIONARY_WATER &&
|
||||
eastGroundMaterial != Material.STATIONARY_WATER &&
|
||||
westGroundMaterial != Material.STATIONARY_WATER &&
|
||||
|
||||
centerGroundMaterial != Material.WATER &&
|
||||
northGroundMaterial != Material.WATER &&
|
||||
southGroundMaterial != Material.WATER &&
|
||||
eastGroundMaterial != Material.WATER &&
|
||||
westGroundMaterial != Material.WATER &&
|
||||
|
||||
|
||||
centerGroundMaterial != Material.STATIONARY_LAVA &&
|
||||
northGroundMaterial != Material.STATIONARY_LAVA &&
|
||||
southGroundMaterial != Material.STATIONARY_LAVA &&
|
||||
eastGroundMaterial != Material.STATIONARY_LAVA &&
|
||||
westGroundMaterial != Material.STATIONARY_LAVA &&
|
||||
|
||||
centerGroundMaterial != Material.LAVA &&
|
||||
northGroundMaterial != Material.LAVA &&
|
||||
southGroundMaterial != Material.LAVA &&
|
||||
|
|
|
@ -0,0 +1,44 @@
|
|||
package buttondevteam.core.component.restart;
|
||||
|
||||
import buttondevteam.core.component.channel.Channel;
|
||||
import buttondevteam.lib.chat.Command2;
|
||||
import buttondevteam.lib.chat.CommandClass;
|
||||
import buttondevteam.lib.chat.ICommand2MC;
|
||||
import buttondevteam.lib.chat.TBMCChatAPI;
|
||||
import lombok.Getter;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.command.CommandSender;
|
||||
|
||||
@CommandClass(path = "primerestart", modOnly = true, helpText = {
|
||||
"§6---- Prime restart ----", //
|
||||
"Restarts the server as soon as nobody is online.", //
|
||||
"To be loud, type something after, like /primerestart lol (it doesn't matter what you write)", //
|
||||
"To be silent, don't type anything" //
|
||||
})
|
||||
@RequiredArgsConstructor
|
||||
public class PrimeRestartCommand extends ICommand2MC {
|
||||
private final RestartComponent component;
|
||||
|
||||
@Command2.Subcommand
|
||||
public void def(CommandSender sender, @Command2.TextArg @Command2.OptionalArg String somethingrandom) {
|
||||
loud = somethingrandom != null;
|
||||
if (Bukkit.getOnlinePlayers().size() > 0) {
|
||||
sender.sendMessage("§bPlayers online, restart delayed.");
|
||||
if (loud)
|
||||
TBMCChatAPI.SendSystemMessage(Channel.GlobalChat, Channel.RecipientTestResult.ALL, ChatColor.DARK_RED + "The server will restart as soon as nobody is online.", component.getRestartBroadcast());
|
||||
plsrestart = true;
|
||||
} else {
|
||||
sender.sendMessage("§bNobody is online. Restarting now.");
|
||||
if (loud)
|
||||
TBMCChatAPI.SendSystemMessage(Channel.GlobalChat, Channel.RecipientTestResult.ALL, "§cNobody is online. Restarting server.", component.getRestartBroadcast());
|
||||
Bukkit.spigot().restart();
|
||||
}
|
||||
}
|
||||
|
||||
@Getter
|
||||
private static boolean plsrestart = false;
|
||||
@Getter
|
||||
private static boolean loud = false;
|
||||
}
|
|
@ -1,45 +0,0 @@
|
|||
package buttondevteam.core.component.restart
|
||||
|
||||
import buttondevteam.core.component.channel.Channel
|
||||
import buttondevteam.lib.chat.Command2.*
|
||||
import buttondevteam.lib.chat.CommandClass
|
||||
import buttondevteam.lib.chat.ICommand2MC
|
||||
import buttondevteam.lib.chat.TBMCChatAPI.SendSystemMessage
|
||||
import org.bukkit.Bukkit
|
||||
import org.bukkit.ChatColor
|
||||
import org.bukkit.command.CommandSender
|
||||
|
||||
@CommandClass(
|
||||
path = "primerestart", modOnly = true, helpText = ["Prime restart", //
|
||||
"Restarts the server as soon as nobody is online.", //
|
||||
"To be loud, type something after, like /primerestart lol (it doesn't matter what you write)", //
|
||||
"To be silent, don't type anything" //
|
||||
]
|
||||
)
|
||||
class PrimeRestartCommand : ICommand2MC() {
|
||||
@Subcommand
|
||||
fun def(sender: CommandSender, @TextArg @OptionalArg somethingrandom: String?) {
|
||||
val isLoud = somethingrandom != null
|
||||
val component = component as RestartComponent
|
||||
component.isLoud = isLoud
|
||||
if (Bukkit.getOnlinePlayers().isNotEmpty()) {
|
||||
sender.sendMessage("${ChatColor.AQUA}Players online, restart delayed.")
|
||||
if (isLoud) SendSystemMessage(
|
||||
Channel.globalChat,
|
||||
Channel.RecipientTestResult.ALL,
|
||||
"${ChatColor.DARK_RED}The server will restart as soon as nobody is online.",
|
||||
component.restartBroadcast
|
||||
)
|
||||
component.isPlsrestart = true
|
||||
} else {
|
||||
sender.sendMessage("${ChatColor.AQUA}Nobody is online. Restarting now.")
|
||||
if (isLoud) SendSystemMessage(
|
||||
Channel.globalChat,
|
||||
Channel.RecipientTestResult.ALL,
|
||||
"${ChatColor.RED}Nobody is online. Restarting server.",
|
||||
component.restartBroadcast
|
||||
)
|
||||
Bukkit.spigot().restart()
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,86 @@
|
|||
package buttondevteam.core.component.restart;
|
||||
|
||||
import buttondevteam.core.MainPlugin;
|
||||
import buttondevteam.core.component.channel.Channel;
|
||||
import buttondevteam.lib.TBMCSystemChatEvent;
|
||||
import buttondevteam.lib.architecture.Component;
|
||||
import buttondevteam.lib.architecture.ComponentMetadata;
|
||||
import buttondevteam.lib.architecture.ConfigData;
|
||||
import buttondevteam.lib.chat.IFakePlayer;
|
||||
import buttondevteam.lib.chat.TBMCChatAPI;
|
||||
import lombok.Getter;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.ZonedDateTime;
|
||||
|
||||
/**
|
||||
* Provides commands such as /schrestart (restart after a countdown) and /primerestart (restart when nobody is online).
|
||||
* Also can automatically restart at a given time.
|
||||
*/
|
||||
@ComponentMetadata(enabledByDefault = false)
|
||||
public class RestartComponent extends Component<MainPlugin> implements Listener {
|
||||
@Override
|
||||
public void enable() {
|
||||
var scheduledRestartCommand = new ScheduledRestartCommand(this);
|
||||
registerCommand(scheduledRestartCommand);
|
||||
registerCommand(new PrimeRestartCommand(this));
|
||||
registerListener(this);
|
||||
restartBroadcast = TBMCSystemChatEvent.BroadcastTarget.add("restartCountdown");
|
||||
|
||||
int restartAt = this.restartAt.get();
|
||||
if (restartAt < 0) return;
|
||||
int restart = syncStart(restartAt);
|
||||
log("Scheduled restart " + (restart / 3600. / 20.) + " hours from now");
|
||||
Bukkit.getScheduler().runTaskLater(getPlugin(), () -> scheduledRestartCommand.def(Bukkit.getConsoleSender(), 0), restart);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void disable() {
|
||||
TBMCSystemChatEvent.BroadcastTarget.remove(restartBroadcast);
|
||||
}
|
||||
|
||||
/**
|
||||
* Specifies the hour of day when the server should be restarted. Set to -1 to disable.
|
||||
*/
|
||||
private final ConfigData<Integer> restartAt = getConfig().getData("restartAt", 12);
|
||||
|
||||
private long lasttime = 0;
|
||||
@Getter
|
||||
private TBMCSystemChatEvent.BroadcastTarget restartBroadcast;
|
||||
|
||||
private int syncStart(int hour) {
|
||||
var now = ZonedDateTime.now(ZoneId.ofOffset("", ZoneOffset.UTC));
|
||||
int secs = now.getHour() * 3600 + now.getMinute() * 60 + now.getSecond();
|
||||
int diff = secs - hour * 3600;
|
||||
if (diff < 0) {
|
||||
diff += 24 * 3600;
|
||||
}
|
||||
int count = diff / (24 * 3600);
|
||||
int intervalPart = diff - count * 24 * 3600;
|
||||
int remaining = 24 * 3600 - intervalPart;
|
||||
return remaining * 20;
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onPlayerLeave(PlayerQuitEvent event) {
|
||||
if (PrimeRestartCommand.isPlsrestart()
|
||||
&& !event.getQuitMessage().equalsIgnoreCase("Server closed")
|
||||
&& !event.getQuitMessage().equalsIgnoreCase("Server is restarting")) {
|
||||
if (Bukkit.getOnlinePlayers().size() <= 1) {
|
||||
if (PrimeRestartCommand.isLoud())
|
||||
TBMCChatAPI.SendSystemMessage(Channel.GlobalChat, Channel.RecipientTestResult.ALL, "§cNobody is online anymore. Restarting.", restartBroadcast);
|
||||
Bukkit.spigot().restart();
|
||||
} else if (!(event.getPlayer() instanceof IFakePlayer) && System.nanoTime() - 10 * 60 * 1000000000L - lasttime > 0) { //10 minutes passed since last reminder
|
||||
lasttime = System.nanoTime();
|
||||
if (PrimeRestartCommand.isLoud())
|
||||
TBMCChatAPI.SendSystemMessage(Channel.GlobalChat, Channel.RecipientTestResult.ALL, ChatColor.DARK_RED + "The server will restart as soon as nobody is online.", restartBroadcast);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,96 +0,0 @@
|
|||
package buttondevteam.core.component.restart
|
||||
|
||||
import buttondevteam.core.MainPlugin
|
||||
import buttondevteam.core.component.channel.Channel
|
||||
import buttondevteam.lib.TBMCSystemChatEvent.BroadcastTarget
|
||||
import buttondevteam.lib.TBMCSystemChatEvent.BroadcastTarget.Companion.add
|
||||
import buttondevteam.lib.TBMCSystemChatEvent.BroadcastTarget.Companion.remove
|
||||
import buttondevteam.lib.architecture.Component
|
||||
import buttondevteam.lib.architecture.ComponentMetadata
|
||||
import buttondevteam.lib.chat.IFakePlayer
|
||||
import buttondevteam.lib.chat.TBMCChatAPI
|
||||
import org.bukkit.Bukkit
|
||||
import org.bukkit.ChatColor
|
||||
import org.bukkit.event.EventHandler
|
||||
import org.bukkit.event.Listener
|
||||
import org.bukkit.event.player.PlayerQuitEvent
|
||||
import java.time.ZoneId
|
||||
import java.time.ZoneOffset
|
||||
import java.time.ZonedDateTime
|
||||
|
||||
/**
|
||||
* Provides commands such as /schrestart (restart after a countdown) and /primerestart (restart when nobody is online).
|
||||
* Also can automatically restart at a given time.
|
||||
*/
|
||||
@ComponentMetadata(enabledByDefault = false)
|
||||
class RestartComponent : Component<MainPlugin>(), Listener {
|
||||
public override fun enable() {
|
||||
val scheduledRestartCommand = ScheduledRestartCommand()
|
||||
registerCommand(scheduledRestartCommand)
|
||||
registerCommand(PrimeRestartCommand())
|
||||
registerListener(this)
|
||||
restartBroadcast = add("restartCountdown")
|
||||
val restartAt = restartAt.get()
|
||||
if (restartAt < 0) return
|
||||
val restart = syncStart(restartAt)
|
||||
log("Scheduled restart " + restart / 3600.0 / 20.0 + " hours from now")
|
||||
Bukkit.getScheduler().runTaskLater(
|
||||
plugin,
|
||||
Runnable { scheduledRestartCommand.def(Bukkit.getConsoleSender(), 0) },
|
||||
restart.toLong()
|
||||
)
|
||||
}
|
||||
|
||||
public override fun disable() {
|
||||
remove(restartBroadcast)
|
||||
}
|
||||
|
||||
/**
|
||||
* Specifies the hour of day when the server should be restarted. Set to -1 to disable.
|
||||
*/
|
||||
private val restartAt get() = config.getData("restartAt", 12)
|
||||
private var lasttime: Long = 0
|
||||
|
||||
var isPlsrestart = false
|
||||
var isLoud = false
|
||||
|
||||
lateinit var restartBroadcast: BroadcastTarget
|
||||
private fun syncStart(hour: Int): Int {
|
||||
val now = ZonedDateTime.now(ZoneId.ofOffset("", ZoneOffset.UTC))
|
||||
val secs = now.hour * 3600 + now.minute * 60 + now.second
|
||||
var diff = secs - hour * 3600
|
||||
if (diff < 0) {
|
||||
diff += 24 * 3600
|
||||
}
|
||||
val count = diff / (24 * 3600)
|
||||
val intervalPart = diff - count * 24 * 3600
|
||||
val remaining = 24 * 3600 - intervalPart
|
||||
return remaining * 20
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
fun onPlayerLeave(event: PlayerQuitEvent) {
|
||||
if (isPlsrestart
|
||||
&& !event.quitMessage.equals("Server closed", ignoreCase = true)
|
||||
&& !event.quitMessage.equals("Server is restarting", ignoreCase = true)
|
||||
) {
|
||||
if (Bukkit.getOnlinePlayers().size <= 1) {
|
||||
if (isLoud) TBMCChatAPI.SendSystemMessage(
|
||||
Channel.globalChat,
|
||||
Channel.RecipientTestResult.ALL,
|
||||
"${ChatColor.RED}Nobody is online anymore. Restarting.",
|
||||
restartBroadcast
|
||||
)
|
||||
Bukkit.spigot().restart()
|
||||
} else if (event.player !is IFakePlayer && System.nanoTime() - 10 * 60 * 1000000000L - lasttime > 0) { //10 minutes passed since last reminder
|
||||
lasttime = System.nanoTime()
|
||||
if (isLoud) TBMCChatAPI.SendSystemMessage(
|
||||
Channel.globalChat,
|
||||
Channel.RecipientTestResult.ALL,
|
||||
ChatColor.DARK_RED.toString() + "The server will restart as soon as nobody is online.",
|
||||
restartBroadcast
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,68 @@
|
|||
package buttondevteam.core.component.restart;
|
||||
|
||||
import buttondevteam.core.MainPlugin;
|
||||
import buttondevteam.core.component.channel.Channel;
|
||||
import buttondevteam.lib.ScheduledServerRestartEvent;
|
||||
import buttondevteam.lib.chat.Command2;
|
||||
import buttondevteam.lib.chat.CommandClass;
|
||||
import buttondevteam.lib.chat.ICommand2MC;
|
||||
import buttondevteam.lib.chat.TBMCChatAPI;
|
||||
import lombok.Getter;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.Setter;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.boss.BarColor;
|
||||
import org.bukkit.boss.BarFlag;
|
||||
import org.bukkit.boss.BarStyle;
|
||||
import org.bukkit.boss.BossBar;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.scheduler.BukkitTask;
|
||||
|
||||
import javax.annotation.Nonnull;
|
||||
|
||||
@CommandClass(modOnly = true, path = "schrestart", helpText = {
|
||||
"Scheduled restart", //
|
||||
"This command restarts the server 1 minute after it's executed, warning players every 10 seconds.", //
|
||||
"You can optionally set the amount of seconds to wait before the restart." //
|
||||
})
|
||||
@RequiredArgsConstructor
|
||||
public class ScheduledRestartCommand extends ICommand2MC {
|
||||
@Getter
|
||||
@Setter
|
||||
private int restartCounter;
|
||||
private BukkitTask restarttask;
|
||||
private volatile BossBar restartbar;
|
||||
@Getter
|
||||
@Nonnull
|
||||
private final RestartComponent component;
|
||||
|
||||
@Command2.Subcommand
|
||||
public boolean def(CommandSender sender, @Command2.OptionalArg int seconds) {
|
||||
if (seconds == 0) seconds = 60;
|
||||
if (seconds < 10) {
|
||||
sender.sendMessage("§cError: Seconds must be at least 10.");
|
||||
return false;
|
||||
}
|
||||
final int restarttime = restartCounter = seconds * 20;
|
||||
restartbar = Bukkit.createBossBar("Server restart in " + seconds + "s", BarColor.RED, BarStyle.SOLID,
|
||||
BarFlag.DARKEN_SKY);
|
||||
restartbar.setProgress(1);
|
||||
Bukkit.getOnlinePlayers().forEach(p -> restartbar.addPlayer(p));
|
||||
sender.sendMessage("Scheduled restart in " + seconds);
|
||||
ScheduledServerRestartEvent e = new ScheduledServerRestartEvent(restarttime, this);
|
||||
Bukkit.getPluginManager().callEvent(e);
|
||||
restarttask = Bukkit.getScheduler().runTaskTimer(MainPlugin.Instance, () -> {
|
||||
if (restartCounter < 0) {
|
||||
restarttask.cancel();
|
||||
restartbar.getPlayers().forEach(p -> restartbar.removePlayer(p));
|
||||
Bukkit.spigot().restart();
|
||||
}
|
||||
if (restartCounter % 200 == 0 && Bukkit.getOnlinePlayers().size() > 0)
|
||||
TBMCChatAPI.SendSystemMessage(Channel.GlobalChat, Channel.RecipientTestResult.ALL, "§c-- The server is restarting in " + restartCounter / 20 + " seconds!", component.getRestartBroadcast());
|
||||
restartbar.setProgress(restartCounter / (double) restarttime);
|
||||
restartbar.setTitle(String.format("Server restart in %.2f", restartCounter / 20f));
|
||||
restartCounter--;
|
||||
}, 1, 1);
|
||||
return true;
|
||||
}
|
||||
}
|
|
@ -1,76 +0,0 @@
|
|||
package buttondevteam.core.component.restart
|
||||
|
||||
import buttondevteam.core.MainPlugin
|
||||
import buttondevteam.core.component.channel.Channel
|
||||
import buttondevteam.lib.ScheduledServerRestartEvent
|
||||
import buttondevteam.lib.chat.Command2.OptionalArg
|
||||
import buttondevteam.lib.chat.Command2.Subcommand
|
||||
import buttondevteam.lib.chat.CommandClass
|
||||
import buttondevteam.lib.chat.ICommand2MC
|
||||
import buttondevteam.lib.chat.TBMCChatAPI.SendSystemMessage
|
||||
import org.bukkit.Bukkit
|
||||
import org.bukkit.ChatColor
|
||||
import org.bukkit.boss.BarColor
|
||||
import org.bukkit.boss.BarFlag
|
||||
import org.bukkit.boss.BarStyle
|
||||
import org.bukkit.boss.BossBar
|
||||
import org.bukkit.command.CommandSender
|
||||
import org.bukkit.scheduler.BukkitTask
|
||||
import java.util.function.Consumer
|
||||
import kotlin.properties.Delegates
|
||||
|
||||
@CommandClass(
|
||||
modOnly = true, path = "schrestart", helpText = ["Scheduled restart", //
|
||||
"This command restarts the server 1 minute after it's executed, warning players every 10 seconds.", //
|
||||
"You can optionally set the amount of seconds to wait before the restart." //
|
||||
]
|
||||
)
|
||||
class ScheduledRestartCommand : ICommand2MC() {
|
||||
public var restartCounter = 0
|
||||
private lateinit var restartTask: BukkitTask
|
||||
|
||||
@Volatile
|
||||
private lateinit var restartBar: BossBar
|
||||
|
||||
private var restartInitialTicks by Delegates.notNull<Int>()
|
||||
|
||||
@Subcommand
|
||||
fun def(sender: CommandSender, @OptionalArg seconds: Int): Boolean {
|
||||
return restart(sender, if (seconds == 0) 60 else seconds)
|
||||
}
|
||||
|
||||
private fun restart(sender: CommandSender, seconds: Int): Boolean {
|
||||
if (seconds < 10) {
|
||||
sender.sendMessage("${ChatColor.RED}Error: Seconds must be at least 10.")
|
||||
return false
|
||||
}
|
||||
restartCounter = seconds * 20
|
||||
restartInitialTicks = restartCounter
|
||||
restartBar =
|
||||
Bukkit.createBossBar("Server restart in " + seconds + "s", BarColor.RED, BarStyle.SOLID, BarFlag.DARKEN_SKY)
|
||||
restartBar.progress = 1.0
|
||||
Bukkit.getOnlinePlayers().forEach { p -> restartBar.addPlayer(p) }
|
||||
sender.sendMessage("Scheduled restart in $seconds")
|
||||
val e = ScheduledServerRestartEvent(restartInitialTicks, this)
|
||||
Bukkit.getPluginManager().callEvent(e)
|
||||
restartTask = Bukkit.getScheduler().runTaskTimer(MainPlugin.instance, ::updateRestartTimer, 1, 1)
|
||||
return true
|
||||
}
|
||||
|
||||
private fun updateRestartTimer() {
|
||||
if (restartCounter < 0) {
|
||||
restartTask.cancel()
|
||||
restartBar.players.forEach(Consumer { p -> restartBar.removePlayer(p) })
|
||||
Bukkit.spigot().restart()
|
||||
}
|
||||
if (restartCounter % 200 == 0 && Bukkit.getOnlinePlayers().isNotEmpty()) SendSystemMessage(
|
||||
Channel.globalChat,
|
||||
Channel.RecipientTestResult.ALL,
|
||||
"${ChatColor.RED}-- The server is restarting in " + restartCounter / 20 + " seconds!",
|
||||
(component as RestartComponent).restartBroadcast
|
||||
)
|
||||
restartBar.progress = restartCounter / restartInitialTicks.toDouble()
|
||||
restartBar.setTitle(String.format("Server restart in %.2f", restartCounter / 20f))
|
||||
restartCounter--
|
||||
}
|
||||
}
|
|
@ -0,0 +1,133 @@
|
|||
package buttondevteam.core.component.spawn;
|
||||
|
||||
import buttondevteam.core.MainPlugin;
|
||||
import buttondevteam.lib.architecture.Component;
|
||||
import buttondevteam.lib.architecture.ComponentMetadata;
|
||||
import buttondevteam.lib.architecture.ConfigData;
|
||||
import buttondevteam.lib.chat.Command2;
|
||||
import buttondevteam.lib.chat.CommandClass;
|
||||
import buttondevteam.lib.chat.ICommand2MC;
|
||||
import com.earth2me.essentials.Trade;
|
||||
import com.google.common.io.ByteArrayDataInput;
|
||||
import com.google.common.io.ByteArrayDataOutput;
|
||||
import com.google.common.io.ByteStreams;
|
||||
import com.onarandombox.MultiverseCore.MultiverseCore;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.player.PlayerTeleportEvent;
|
||||
import org.bukkit.plugin.messaging.PluginMessageListener;
|
||||
|
||||
import java.io.*;
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/**
|
||||
* Provides a /spawn command that works with BungeeCord. Make sure to set up on each server.
|
||||
*/
|
||||
@ComponentMetadata(enabledByDefault = false)
|
||||
public class SpawnComponent extends Component<MainPlugin> implements PluginMessageListener {
|
||||
@Override
|
||||
protected void enable() {
|
||||
registerCommand(new SpawnCommand());
|
||||
if (targetServer.get().length() == 0) {
|
||||
spawnloc = MultiverseCore.getPlugin(MultiverseCore.class).getMVWorldManager().getFirstSpawnWorld()
|
||||
.getSpawnLocation();
|
||||
}
|
||||
|
||||
Bukkit.getServer().getMessenger().registerOutgoingPluginChannel(getPlugin(), "BungeeCord");
|
||||
Bukkit.getServer().getMessenger().registerIncomingPluginChannel(getPlugin(), "BungeeCord", this);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void disable() {
|
||||
Bukkit.getServer().getMessenger().unregisterIncomingPluginChannel(getPlugin(), "BungeeCord");
|
||||
Bukkit.getServer().getMessenger().unregisterOutgoingPluginChannel(getPlugin(), "BungeeCord");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPluginMessageReceived(String channel, Player player, byte[] message) {
|
||||
if (!channel.equals("BungeeCord")) {
|
||||
return;
|
||||
}
|
||||
if (targetServer.get().length() != 0)
|
||||
return;
|
||||
ByteArrayDataInput in = ByteStreams.newDataInput(message);
|
||||
String subchannel = in.readUTF();
|
||||
if ("ChromaCore-Spawn".equals(subchannel)) {
|
||||
// Use the code sample in the 'Response' sections below to read
|
||||
// the data.
|
||||
short len = in.readShort();
|
||||
byte[] msgbytes = new byte[len];
|
||||
in.readFully(msgbytes);
|
||||
|
||||
try {
|
||||
DataInputStream msgin = new DataInputStream(new ByteArrayInputStream(msgbytes));
|
||||
String somedata = msgin.readUTF(); // Read the data in the same way you wrote it
|
||||
if (!"SendToSpawn".equals(somedata)) {
|
||||
System.out.println("somedata: " + somedata);
|
||||
return;
|
||||
}
|
||||
player.teleport(spawnloc);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
} else
|
||||
System.out.println("Subchannel: " + subchannel);
|
||||
}
|
||||
|
||||
/**
|
||||
* The BungeeCord server that has the spawn. Set to empty if this server is the target.
|
||||
*/
|
||||
private final ConfigData<String> targetServer = getConfig().getData("targetServer", "");
|
||||
|
||||
private Location spawnloc;
|
||||
|
||||
@CommandClass(helpText = {
|
||||
"Spawn",
|
||||
"Teleport to spawn."
|
||||
})
|
||||
public class SpawnCommand extends ICommand2MC {
|
||||
@SuppressWarnings("UnstableApiUsage")
|
||||
@Command2.Subcommand
|
||||
public void def(Player player) {
|
||||
if (targetServer.get().length() == 0) {
|
||||
player.sendMessage("§bTeleporting to spawn...");
|
||||
try {
|
||||
if (MainPlugin.ess != null)
|
||||
MainPlugin.ess.getUser(player).getTeleport()
|
||||
.teleport(spawnloc, new Trade(BigDecimal.ZERO, MainPlugin.ess), PlayerTeleportEvent.TeleportCause.COMMAND);
|
||||
else
|
||||
player.teleport(spawnloc);
|
||||
} catch (Exception e) {
|
||||
player.sendMessage("§cFailed to teleport: " + e);
|
||||
}
|
||||
return;
|
||||
}
|
||||
ByteArrayDataOutput out = ByteStreams.newDataOutput();
|
||||
out.writeUTF("Connect");
|
||||
out.writeUTF(targetServer.get());
|
||||
|
||||
player.sendPluginMessage(getPlugin(), "BungeeCord", out.toByteArray());
|
||||
|
||||
Bukkit.getScheduler().runTask(getPlugin(), () -> { //Delay it a bit
|
||||
ByteArrayDataOutput outt = ByteStreams.newDataOutput();
|
||||
outt.writeUTF("ForwardToPlayer"); // So BungeeCord knows to forward it
|
||||
outt.writeUTF(player.getName());
|
||||
outt.writeUTF("ChromaCore-Spawn"); // The channel name to check if this your data
|
||||
|
||||
ByteArrayOutputStream msgbytes = new ByteArrayOutputStream();
|
||||
DataOutputStream msgout = new DataOutputStream(msgbytes);
|
||||
try {
|
||||
msgout.writeUTF("SendToSpawn"); // You can do anything you want with msgout
|
||||
} catch (IOException exception) {
|
||||
exception.printStackTrace();
|
||||
}
|
||||
|
||||
outt.writeShort(msgbytes.toByteArray().length);
|
||||
outt.write(msgbytes.toByteArray());
|
||||
|
||||
player.sendPluginMessage(getPlugin(), "BungeeCord", outt.toByteArray());
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,110 +0,0 @@
|
|||
package buttondevteam.core.component.spawn
|
||||
|
||||
import buttondevteam.core.MainPlugin
|
||||
import buttondevteam.lib.architecture.Component
|
||||
import buttondevteam.lib.architecture.ComponentMetadata
|
||||
import buttondevteam.lib.chat.Command2.Subcommand
|
||||
import buttondevteam.lib.chat.CommandClass
|
||||
import buttondevteam.lib.chat.ICommand2MC
|
||||
import com.earth2me.essentials.Trade
|
||||
import com.google.common.io.ByteStreams
|
||||
import com.onarandombox.MultiverseCore.MultiverseCore
|
||||
import org.bukkit.Bukkit
|
||||
import org.bukkit.Location
|
||||
import org.bukkit.entity.Player
|
||||
import org.bukkit.event.player.PlayerTeleportEvent
|
||||
import org.bukkit.plugin.messaging.PluginMessageListener
|
||||
import java.io.*
|
||||
import java.math.BigDecimal
|
||||
|
||||
/**
|
||||
* Provides a /spawn command that works with BungeeCord. Make sure to set up on each server.
|
||||
* Requires Multiverse-Core.
|
||||
*/
|
||||
@ComponentMetadata(enabledByDefault = false)
|
||||
class SpawnComponent : Component<MainPlugin>(), PluginMessageListener {
|
||||
override fun enable() {
|
||||
registerCommand(SpawnCommand())
|
||||
if (targetServer.get().isEmpty()) {
|
||||
spawnloc = MultiverseCore.getPlugin(MultiverseCore::class.java).mvWorldManager.firstSpawnWorld.spawnLocation
|
||||
}
|
||||
Bukkit.getServer().messenger.registerOutgoingPluginChannel(plugin, "BungeeCord")
|
||||
Bukkit.getServer().messenger.registerIncomingPluginChannel(plugin, "BungeeCord", this)
|
||||
}
|
||||
|
||||
override fun disable() {
|
||||
Bukkit.getServer().messenger.unregisterIncomingPluginChannel(plugin, "BungeeCord")
|
||||
Bukkit.getServer().messenger.unregisterOutgoingPluginChannel(plugin, "BungeeCord")
|
||||
}
|
||||
|
||||
override fun onPluginMessageReceived(channel: String, player: Player, message: ByteArray) {
|
||||
if (channel != "BungeeCord") {
|
||||
return
|
||||
}
|
||||
if (targetServer.get().isNotEmpty()) return
|
||||
val `in` = ByteStreams.newDataInput(message)
|
||||
val subchannel = `in`.readUTF()
|
||||
if ("ChromaCore-Spawn" == subchannel) {
|
||||
// Use the code sample in the 'Response' sections below to read
|
||||
// the data.
|
||||
val len = `in`.readShort()
|
||||
val msgbytes = ByteArray(len.toInt())
|
||||
`in`.readFully(msgbytes)
|
||||
try {
|
||||
val msgin = DataInputStream(ByteArrayInputStream(msgbytes))
|
||||
val somedata = msgin.readUTF() // Read the data in the same way you wrote it
|
||||
if ("SendToSpawn" != somedata) {
|
||||
println("somedata: $somedata")
|
||||
return
|
||||
}
|
||||
player.teleport(spawnloc!!)
|
||||
} catch (e: IOException) {
|
||||
e.printStackTrace()
|
||||
}
|
||||
} else println("Subchannel: $subchannel")
|
||||
}
|
||||
|
||||
/**
|
||||
* The BungeeCord server that has the spawn. Set to empty if this server is the target.
|
||||
*/
|
||||
private val targetServer get() = config.getData("targetServer", "")
|
||||
private var spawnloc: Location? = null
|
||||
|
||||
@CommandClass(helpText = ["Spawn", "Teleport to spawn."])
|
||||
inner class SpawnCommand : ICommand2MC() {
|
||||
@Subcommand
|
||||
fun def(player: Player) {
|
||||
if (targetServer.get().isEmpty()) {
|
||||
player.sendMessage("\${ChatColor.AQUA}Teleporting to spawn...")
|
||||
try {
|
||||
if (MainPlugin.ess != null) MainPlugin.ess!!.getUser(player).teleport
|
||||
.teleport(spawnloc, Trade(BigDecimal.ZERO, MainPlugin.ess), PlayerTeleportEvent.TeleportCause.COMMAND) else player.teleport(spawnloc!!)
|
||||
} catch (e: Exception) {
|
||||
player.sendMessage("\${ChatColor.RED}Failed to teleport: $e")
|
||||
}
|
||||
return
|
||||
}
|
||||
val out = ByteStreams.newDataOutput()
|
||||
out.writeUTF("Connect")
|
||||
out.writeUTF(targetServer.get())
|
||||
player.sendPluginMessage(plugin, "BungeeCord", out.toByteArray())
|
||||
Bukkit.getScheduler().runTask(plugin, Runnable {
|
||||
//Delay it a bit
|
||||
val outt = ByteStreams.newDataOutput()
|
||||
outt.writeUTF("ForwardToPlayer") // So BungeeCord knows to forward it
|
||||
outt.writeUTF(player.name)
|
||||
outt.writeUTF("ChromaCore-Spawn") // The channel name to check if this your data
|
||||
val msgbytes = ByteArrayOutputStream()
|
||||
val msgout = DataOutputStream(msgbytes)
|
||||
try {
|
||||
msgout.writeUTF("SendToSpawn") // You can do anything you want with msgout
|
||||
} catch (exception: IOException) {
|
||||
exception.printStackTrace()
|
||||
}
|
||||
outt.writeShort(msgbytes.toByteArray().size)
|
||||
outt.write(msgbytes.toByteArray())
|
||||
player.sendPluginMessage(plugin, "BungeeCord", outt.toByteArray())
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,61 @@
|
|||
package buttondevteam.core.component.towny;
|
||||
|
||||
import buttondevteam.core.MainPlugin;
|
||||
import buttondevteam.lib.chat.Command2;
|
||||
import buttondevteam.lib.chat.CommandClass;
|
||||
import buttondevteam.lib.chat.CustomTabComplete;
|
||||
import buttondevteam.lib.chat.ICommand2MC;
|
||||
import buttondevteam.lib.player.TBMCPlayer;
|
||||
import com.earth2me.essentials.Essentials;
|
||||
import com.earth2me.essentials.User;
|
||||
import com.palmergames.bukkit.towny.TownySettings;
|
||||
import com.palmergames.bukkit.towny.TownyUniverse;
|
||||
import com.palmergames.bukkit.towny.object.Resident;
|
||||
import com.palmergames.bukkit.towny.object.TownyObject;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.command.CommandSender;
|
||||
|
||||
import java.util.AbstractMap;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
@CommandClass(path = "chroma remresidents", modOnly = true, helpText = {
|
||||
"Removes invalid Towny residents from their towns (usually after a rename that didn't get caught by the plugin)",
|
||||
"If the delete eco account setting is off, then it will completely delete the resident",
|
||||
"(The economy account could still be used by the player)"
|
||||
})
|
||||
public class RemoveResidentsCommand extends ICommand2MC {
|
||||
@Command2.Subcommand
|
||||
public void def(CommandSender sender, @Command2.OptionalArg @CustomTabComplete("remove") String remove) {
|
||||
Bukkit.getScheduler().runTaskAsynchronously(getPlugin(), () -> {
|
||||
sender.sendMessage("Starting...");
|
||||
var ds = TownyUniverse.getInstance().getDataSource();
|
||||
var res = ds.getResidents().stream()
|
||||
.flatMap(r -> {
|
||||
var st = Stream.of(r) //https://stackoverflow.com/questions/37299312/in-java-8-lambdas-how-to-access-original-object-in-the-stream
|
||||
.map(TownyObject::getName);
|
||||
return (MainPlugin.ess == null
|
||||
? st.map(Bukkit::getOfflinePlayer)
|
||||
: st.map(MainPlugin.ess::getOfflineUser).map(User::getBase))
|
||||
.filter(p -> !p.hasPlayedBefore())
|
||||
.map(p -> new AbstractMap.SimpleEntry<>(r, p));
|
||||
}).collect(Collectors.toMap(AbstractMap.SimpleEntry::getKey, AbstractMap.SimpleEntry::getValue));
|
||||
if (MainPlugin.ess == null)
|
||||
sender.sendMessage("§cEssentials not found, players who haven't joined after changing their names are also listed here.");
|
||||
sender.sendMessage("Residents to remove:");
|
||||
res.values().forEach(op -> sender.sendMessage(op.getName()));
|
||||
if (TownySettings.isDeleteEcoAccount())
|
||||
sender.sendMessage("§bWill only remove from town, as delete eco account setting is on");
|
||||
else
|
||||
sender.sendMessage("§eWill completely delete the resident, delete eco account setting is off");
|
||||
if (remove != null && remove.equalsIgnoreCase("remove")) {
|
||||
sender.sendMessage("Removing residents..."); //Removes from town and deletes town if needed - doesn't delete the resident if the setting is on
|
||||
//If it did, that could mean the player's economy is deleted too, unless this setting is false
|
||||
res.keySet().forEach(TownySettings.isDeleteEcoAccount() ? ds::removeResident : ds::removeResidentList);
|
||||
sender.sendMessage("Done");
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
|
@ -1,53 +0,0 @@
|
|||
package buttondevteam.core.component.towny
|
||||
|
||||
import buttondevteam.core.MainPlugin
|
||||
import buttondevteam.lib.chat.Command2.OptionalArg
|
||||
import buttondevteam.lib.chat.Command2.Subcommand
|
||||
import buttondevteam.lib.chat.CommandClass
|
||||
import buttondevteam.lib.chat.CustomTabComplete
|
||||
import buttondevteam.lib.chat.ICommand2MC
|
||||
import com.palmergames.bukkit.towny.TownySettings
|
||||
import com.palmergames.bukkit.towny.TownyUniverse
|
||||
import com.palmergames.bukkit.towny.`object`.Resident
|
||||
import org.bukkit.Bukkit
|
||||
import org.bukkit.ChatColor
|
||||
import org.bukkit.OfflinePlayer
|
||||
import org.bukkit.command.CommandSender
|
||||
import java.util.*
|
||||
import java.util.function.Consumer
|
||||
|
||||
@CommandClass(
|
||||
path = "chroma remresidents",
|
||||
modOnly = true,
|
||||
helpText = ["Removes invalid Towny residents from their towns (usually after a rename that didn't get caught by the plugin)", "If the delete eco account setting is off, then it will completely delete the resident", "(The economy account could still be used by the player)"]
|
||||
)
|
||||
class RemoveResidentsCommand : ICommand2MC() {
|
||||
@Subcommand
|
||||
fun def(sender: CommandSender, @OptionalArg @CustomTabComplete("remove") remove: String?) {
|
||||
Bukkit.getScheduler().runTaskAsynchronously(plugin, Runnable {
|
||||
sender.sendMessage("Starting...")
|
||||
val ds = TownyUniverse.getInstance().dataSource
|
||||
val res: Map<Resident, OfflinePlayer> = ds.residents
|
||||
.mapNotNull { r ->
|
||||
val player = MainPlugin.ess?.getOfflineUser(r.name)?.base ?: Bukkit.getOfflinePlayer(r.name)
|
||||
if (player.hasPlayedBefore()) null else r to player
|
||||
}.associate { it }
|
||||
if (MainPlugin.ess == null)
|
||||
sender.sendMessage("${ChatColor.RED}Essentials not found, players who haven't joined after changing their names are also listed here.")
|
||||
sender.sendMessage("Residents to remove:")
|
||||
res.values.forEach { op: OfflinePlayer -> sender.sendMessage(op.name!!) }
|
||||
if (TownySettings.isDeleteEcoAccount()) sender.sendMessage("${ChatColor.AQUA}Will only remove from town, as delete eco account setting is on") else sender.sendMessage(
|
||||
"${ChatColor.YELLOW}Will completely delete the resident, delete eco account setting is off"
|
||||
)
|
||||
if (remove != null && remove.equals("remove", ignoreCase = true)) {
|
||||
sender.sendMessage("Removing residents...") //Removes from town and deletes town if needed - doesn't delete the resident if the setting is on
|
||||
//If it did, that could mean the player's economy is deleted too, unless this setting is false
|
||||
res.keys.forEach(if (TownySettings.isDeleteEcoAccount())
|
||||
Consumer { resident -> ds.removeResident(resident) }
|
||||
else
|
||||
Consumer { resident -> ds.removeResidentList(resident) })
|
||||
sender.sendMessage("Done")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
101
Chroma-Core/src/main/java/buttondevteam/lib/ChromaUtils.java
Normal file
101
Chroma-Core/src/main/java/buttondevteam/lib/ChromaUtils.java
Normal file
|
@ -0,0 +1,101 @@
|
|||
package buttondevteam.lib;
|
||||
|
||||
import buttondevteam.core.MainPlugin;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.Cancellable;
|
||||
import org.bukkit.event.Event;
|
||||
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public final class ChromaUtils {
|
||||
private ChromaUtils() {}
|
||||
|
||||
public static String getDisplayName(CommandSender sender) {
|
||||
if (sender instanceof IHaveFancyName)
|
||||
return ((IHaveFancyName) sender).getFancyName();
|
||||
if (sender instanceof Player)
|
||||
return ((Player) sender).getDisplayName();
|
||||
return sender.getName();
|
||||
}
|
||||
|
||||
public static String getFullDisplayName(CommandSender sender) {
|
||||
if (sender instanceof IHaveFancyName)
|
||||
return ((IHaveFancyName) sender).getFancyFullName();
|
||||
return getDisplayName(sender);
|
||||
}
|
||||
|
||||
public interface IHaveFancyName {
|
||||
/**
|
||||
* May not be null.
|
||||
*
|
||||
* @return The name to be displayed in most places.
|
||||
*/
|
||||
String getFancyName();
|
||||
|
||||
/**
|
||||
* May return null.
|
||||
*
|
||||
* @return The full name that can be used to uniquely identify the user.
|
||||
*/
|
||||
String getFancyFullName();
|
||||
}
|
||||
|
||||
public static Number convertNumber(Number number, Class<? extends Number> targetcl) {
|
||||
if (targetcl == long.class || Long.class.isAssignableFrom(targetcl))
|
||||
return number.longValue();
|
||||
else if (targetcl == int.class || Integer.class.isAssignableFrom(targetcl))
|
||||
return number.intValue(); //Needed because the parser can get longs
|
||||
else if (targetcl == short.class || Short.class.isAssignableFrom(targetcl))
|
||||
return number.shortValue();
|
||||
else if (targetcl == byte.class || Byte.class.isAssignableFrom(targetcl))
|
||||
return number.byteValue();
|
||||
else if (targetcl == float.class || Float.class.isAssignableFrom(targetcl))
|
||||
return number.floatValue();
|
||||
else if (targetcl == double.class || Double.class.isAssignableFrom(targetcl))
|
||||
return number.doubleValue();
|
||||
return number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calls the event always asynchronously. The return value is always false if async.
|
||||
*
|
||||
* @param event The event to call
|
||||
* @return The event cancelled state or false if async.
|
||||
*/
|
||||
public static <T extends Event & Cancellable> boolean callEventAsync(T event) {
|
||||
Supplier<Boolean> task = () -> {
|
||||
Bukkit.getPluginManager().callEvent(event);
|
||||
return event.isCancelled();
|
||||
};
|
||||
return doItAsync(task, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Does something always asynchronously. It will execute in the same thread if it's not the server thread.
|
||||
*
|
||||
* @param what What to do
|
||||
* @param def Default if async
|
||||
* @return The value supplied by the action or def if async.
|
||||
*/
|
||||
public static <T> T doItAsync(Supplier<T> what, T def) {
|
||||
if (Bukkit.isPrimaryThread())
|
||||
Bukkit.getScheduler().runTaskAsynchronously(MainPlugin.Instance, what::get);
|
||||
else
|
||||
return what.get();
|
||||
return def;
|
||||
}
|
||||
|
||||
private static boolean test = false;
|
||||
|
||||
/**
|
||||
* Returns true while unit testing.
|
||||
*/
|
||||
public static boolean isTest() { return test; }
|
||||
|
||||
/**
|
||||
* Call when unit testing.
|
||||
*/
|
||||
public static void setTest() { test = true; }
|
||||
}
|
|
@ -1,122 +0,0 @@
|
|||
package buttondevteam.lib
|
||||
|
||||
import buttondevteam.core.MainPlugin
|
||||
import buttondevteam.lib.test.TestException
|
||||
import org.bukkit.Bukkit
|
||||
import org.bukkit.command.CommandSender
|
||||
import org.bukkit.entity.Player
|
||||
import org.bukkit.event.Cancellable
|
||||
import org.bukkit.event.Event
|
||||
import java.util.function.Supplier
|
||||
|
||||
object ChromaUtils {
|
||||
@JvmStatic
|
||||
@Deprecated("Use ChromaGamingBase.name", ReplaceWith("ChromaGamerBase.getFromSender(sender).name"))
|
||||
fun getDisplayName(sender: CommandSender): String {
|
||||
return when (sender) {
|
||||
is IHaveFancyName -> sender.fancyName
|
||||
is Player -> sender.displayName
|
||||
else -> sender.name
|
||||
}
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun getFullDisplayName(sender: CommandSender): String {
|
||||
return when (sender) {
|
||||
is IHaveFancyName -> sender.fancyFullName
|
||||
else -> getDisplayName(sender)
|
||||
}
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun convertNumber(number: Number, targetcl: Class<out Number>): Number {
|
||||
return when {
|
||||
targetcl == Long::class.javaPrimitiveType || Long::class.javaObjectType.isAssignableFrom(targetcl) -> number.toLong()
|
||||
targetcl == Int::class.javaPrimitiveType || Int::class.javaObjectType.isAssignableFrom(targetcl) -> number.toInt() //Needed because the parser can get longs
|
||||
targetcl == Short::class.javaPrimitiveType || Short::class.javaObjectType.isAssignableFrom(targetcl) -> number.toShort()
|
||||
targetcl == Byte::class.javaPrimitiveType || Byte::class.javaObjectType.isAssignableFrom(targetcl) -> number.toByte()
|
||||
targetcl == Float::class.javaPrimitiveType || Float::class.javaObjectType.isAssignableFrom(targetcl) -> number.toFloat()
|
||||
targetcl == Double::class.javaPrimitiveType || Double::class.javaObjectType.isAssignableFrom(targetcl) -> number.toDouble()
|
||||
else -> number
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Calls the event always asynchronously. The return value is always false if async.
|
||||
*
|
||||
* @param event The event to call
|
||||
* @return The event cancelled state or false if async.
|
||||
*/
|
||||
@JvmStatic
|
||||
fun <T> callEventAsync(event: T): Boolean where T : Event, T : Cancellable {
|
||||
val task = Supplier {
|
||||
Bukkit.getPluginManager().callEvent(event)
|
||||
event.isCancelled
|
||||
}
|
||||
return doItAsync(task, false)
|
||||
}
|
||||
|
||||
/**
|
||||
* Does something always asynchronously. It will execute in the same thread if it's not the server thread.
|
||||
*
|
||||
* @param what What to do
|
||||
* @param def Default if async
|
||||
* @return The value supplied by the action or def if async.
|
||||
*/
|
||||
@JvmStatic
|
||||
fun <T> doItAsync(what: Supplier<T>, def: T): T {
|
||||
return if (Bukkit.isPrimaryThread()) {
|
||||
Bukkit.getScheduler().runTaskAsynchronously(MainPlugin.instance, Runnable { what.get() })
|
||||
def
|
||||
} else what.get()
|
||||
}
|
||||
|
||||
/**
|
||||
* Log a warning message if the plugin is initialized. If not, just print a regular message.
|
||||
*/
|
||||
fun logWarn(message: String) {
|
||||
if (MainPlugin.isInitialized) {
|
||||
MainPlugin.instance.logger.warning(message)
|
||||
} else {
|
||||
println(message)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Throws the exception directly during testing but only reports it when running on the server.
|
||||
* This way exceptions get reported properly when running, but they can be checked during testing.
|
||||
*
|
||||
* Useful in code blocks scheduled using the Bukkit API.
|
||||
*/
|
||||
fun throwWhenTested(exception: Throwable, message: String) {
|
||||
if (isTest) {
|
||||
// Propagate exception back to the tests
|
||||
throw TestException(message, exception)
|
||||
} else {
|
||||
// Otherwise we don't run the code directly, so we need to handle this here
|
||||
TBMCCoreAPI.SendException(message, exception, MainPlugin.instance)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true while unit testing.
|
||||
*/
|
||||
@JvmStatic
|
||||
var isTest = false
|
||||
|
||||
interface IHaveFancyName {
|
||||
/**
|
||||
* May not be null.
|
||||
*
|
||||
* @return The name to be displayed in most places.
|
||||
*/
|
||||
val fancyName: String
|
||||
|
||||
/**
|
||||
* May return null.
|
||||
*
|
||||
* @return The full name that can be used to uniquely identify the user.
|
||||
*/
|
||||
val fancyFullName: String
|
||||
}
|
||||
}
|
25
Chroma-Core/src/main/java/buttondevteam/lib/ScheduledServerRestartEvent.java
Executable file
25
Chroma-Core/src/main/java/buttondevteam/lib/ScheduledServerRestartEvent.java
Executable file
|
@ -0,0 +1,25 @@
|
|||
package buttondevteam.lib;
|
||||
|
||||
import buttondevteam.core.component.restart.ScheduledRestartCommand;
|
||||
import lombok.Getter;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.bukkit.event.Event;
|
||||
import org.bukkit.event.HandlerList;
|
||||
|
||||
@Getter
|
||||
@RequiredArgsConstructor
|
||||
public class ScheduledServerRestartEvent extends Event {
|
||||
private static final HandlerList handlers = new HandlerList();
|
||||
|
||||
private final int restartTicks;
|
||||
private final ScheduledRestartCommand command;
|
||||
|
||||
@Override
|
||||
public HandlerList getHandlers() {
|
||||
return handlers;
|
||||
}
|
||||
|
||||
public static HandlerList getHandlerList() {
|
||||
return handlers;
|
||||
}
|
||||
}
|
|
@ -1,16 +0,0 @@
|
|||
package buttondevteam.lib
|
||||
|
||||
import buttondevteam.core.component.restart.ScheduledRestartCommand
|
||||
import org.bukkit.event.Event
|
||||
import org.bukkit.event.HandlerList
|
||||
|
||||
class ScheduledServerRestartEvent(val restartTicks: Int, val command: ScheduledRestartCommand) : Event() {
|
||||
override fun getHandlers(): HandlerList {
|
||||
return handlerList
|
||||
}
|
||||
|
||||
companion object {
|
||||
@JvmStatic
|
||||
val handlerList = HandlerList()
|
||||
}
|
||||
}
|
73
Chroma-Core/src/main/java/buttondevteam/lib/TBMCChatEvent.java
Executable file
73
Chroma-Core/src/main/java/buttondevteam/lib/TBMCChatEvent.java
Executable file
|
@ -0,0 +1,73 @@
|
|||
package buttondevteam.lib;
|
||||
|
||||
import buttondevteam.core.component.channel.Channel;
|
||||
import buttondevteam.lib.chat.ChatMessage;
|
||||
import lombok.Getter;
|
||||
import lombok.experimental.Delegate;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.event.HandlerList;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
/**
|
||||
* Make sure to only send the message to users where {@link #shouldSendTo(CommandSender)} returns true.
|
||||
*
|
||||
* @author NorbiPeti
|
||||
*
|
||||
*/
|
||||
@Getter
|
||||
public class TBMCChatEvent extends TBMCChatEventBase {
|
||||
public TBMCChatEvent(Channel channel, ChatMessage cm, Channel.RecipientTestResult rtr) {
|
||||
super(channel, cm.getMessage(), rtr.score, rtr.groupID);
|
||||
this.cm = cm;
|
||||
}
|
||||
|
||||
private static final HandlerList handlers = new HandlerList();
|
||||
|
||||
@Delegate //<-- Backwards compatibility
|
||||
private ChatMessage cm;
|
||||
|
||||
private boolean isIgnoreSenderPermissions() {
|
||||
return cm.getPermCheck() != cm.getSender();
|
||||
}
|
||||
|
||||
/**
|
||||
* This will allow the sender of the message if {@link #isIgnoreSenderPermissions()} is true.
|
||||
*/
|
||||
@Override
|
||||
public boolean shouldSendTo(CommandSender sender) {
|
||||
if (isIgnoreSenderPermissions() && sender.equals(this.cm.getSender()))
|
||||
return true; //Allow sending the message no matter what
|
||||
return super.shouldSendTo(sender);
|
||||
}
|
||||
|
||||
/**
|
||||
* This will allow the sender of the message if {@link #isIgnoreSenderPermissions()} is true.
|
||||
*/
|
||||
@Override
|
||||
public int getMCScore(CommandSender sender) {
|
||||
if (isIgnoreSenderPermissions() && sender.equals(this.cm.getSender()))
|
||||
return getScore(); //Send in the correct group no matter what
|
||||
return super.getMCScore(sender);
|
||||
}
|
||||
|
||||
/**
|
||||
* This will allow the sender of the message if {@link #isIgnoreSenderPermissions()} is true.
|
||||
*/
|
||||
@Nullable
|
||||
@Override
|
||||
public String getGroupID(CommandSender sender) {
|
||||
if (isIgnoreSenderPermissions() && sender.equals(this.cm.getSender()))
|
||||
return getGroupID(); //Send in the correct group no matter what
|
||||
return super.getGroupID(sender);
|
||||
}
|
||||
|
||||
@Override
|
||||
public HandlerList getHandlers() {
|
||||
return handlers;
|
||||
}
|
||||
|
||||
public static HandlerList getHandlerList() {
|
||||
return handlers;
|
||||
}
|
||||
}
|
|
@ -1,60 +0,0 @@
|
|||
package buttondevteam.lib
|
||||
|
||||
import buttondevteam.core.component.channel.Channel
|
||||
import buttondevteam.core.component.channel.Channel.RecipientTestResult
|
||||
import buttondevteam.lib.chat.ChatMessage
|
||||
import buttondevteam.lib.player.ChromaGamerBase
|
||||
import org.bukkit.event.HandlerList
|
||||
|
||||
/**
|
||||
* Make sure to only send the message to users where [.shouldSendTo] returns true.
|
||||
*
|
||||
* @author NorbiPeti
|
||||
*/
|
||||
class TBMCChatEvent(
|
||||
channel: Channel,
|
||||
val chatMessage: ChatMessage,
|
||||
rtr: RecipientTestResult
|
||||
) : TBMCChatEventBase(channel, chatMessage.message, rtr.score, rtr.groupID!!) {
|
||||
|
||||
private val isIgnoreSenderPermissions: Boolean get() = chatMessage.permCheck !== chatMessage.user
|
||||
|
||||
/**
|
||||
* This will allow the sender of the message if [.isIgnoreSenderPermissions] is true.
|
||||
*/
|
||||
override fun shouldSendTo(sender: ChromaGamerBase): Boolean {
|
||||
return if (isIgnoreSenderPermissions && sender == chatMessage.user) true else super.shouldSendTo(sender) //Allow sending the message no matter what
|
||||
}
|
||||
|
||||
/**
|
||||
* This will allow the sender of the message if [.isIgnoreSenderPermissions] is true.
|
||||
*/
|
||||
override fun getMCScore(sender: ChromaGamerBase): Int {
|
||||
return if (isIgnoreSenderPermissions && sender == chatMessage.user) score else super.getMCScore(sender) //Send in the correct group no matter what
|
||||
}
|
||||
|
||||
/**
|
||||
* This will allow the sender of the message if [.isIgnoreSenderPermissions] is true.
|
||||
*/
|
||||
override fun getGroupID(sender: ChromaGamerBase): String? {
|
||||
return if (isIgnoreSenderPermissions && sender == chatMessage.user) groupID else super.getGroupID(sender) //Send in the correct group no matter what
|
||||
}
|
||||
|
||||
override fun getHandlers(): HandlerList {
|
||||
return handlerList
|
||||
}
|
||||
|
||||
/** @see ChatMessage.user */
|
||||
val user: ChromaGamerBase get() = chatMessage.user
|
||||
|
||||
/** @see ChatMessage.origin */
|
||||
val origin: String get() = chatMessage.origin
|
||||
|
||||
/** @see ChatMessage.isFromCommand */
|
||||
val isFromCommand get() = chatMessage.isFromCommand
|
||||
|
||||
companion object {
|
||||
@JvmStatic
|
||||
val handlerList = HandlerList()
|
||||
}
|
||||
}
|
59
Chroma-Core/src/main/java/buttondevteam/lib/TBMCChatEventBase.java
Executable file
59
Chroma-Core/src/main/java/buttondevteam/lib/TBMCChatEventBase.java
Executable file
|
@ -0,0 +1,59 @@
|
|||
package buttondevteam.lib;
|
||||
|
||||
import buttondevteam.core.component.channel.Channel;
|
||||
import lombok.Getter;
|
||||
import lombok.NonNull;
|
||||
import lombok.Setter;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.event.Cancellable;
|
||||
import org.bukkit.event.Event;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
@Getter
|
||||
public abstract class TBMCChatEventBase extends Event implements Cancellable {
|
||||
private final Channel channel;
|
||||
private @NonNull String message;
|
||||
private @Setter boolean cancelled;
|
||||
/**
|
||||
* The sender's score.
|
||||
*/
|
||||
private final int score;
|
||||
/**
|
||||
* The sender's group ID.
|
||||
*/
|
||||
private final String groupID;
|
||||
|
||||
@java.beans.ConstructorProperties({"channel", "message", "score", "groupID"})
|
||||
public TBMCChatEventBase(Channel channel, String message, int score, String groupID) {
|
||||
super(true);
|
||||
this.channel = channel;
|
||||
this.message = message;
|
||||
this.score = score;
|
||||
this.groupID = groupID;
|
||||
}
|
||||
|
||||
/**
|
||||
* Note: Errors are sent to the sender automatically
|
||||
*/
|
||||
public boolean shouldSendTo(CommandSender sender) {
|
||||
return channel.shouldSendTo(sender, score);
|
||||
}
|
||||
|
||||
/**
|
||||
* Note: Errors are sent to the sender automatically
|
||||
*/
|
||||
public int getMCScore(CommandSender sender) {
|
||||
return channel.getMCScore(sender);
|
||||
}
|
||||
|
||||
/**
|
||||
* Note: Errors are sent to the sender automatically<br>
|
||||
*
|
||||
* Null means don't send
|
||||
*/
|
||||
@Nullable
|
||||
public String getGroupID(CommandSender sender) {
|
||||
return channel.getGroupID(sender);
|
||||
}
|
||||
}
|
|
@ -1,48 +0,0 @@
|
|||
package buttondevteam.lib
|
||||
|
||||
import buttondevteam.core.component.channel.Channel
|
||||
import buttondevteam.lib.player.ChromaGamerBase
|
||||
import org.bukkit.event.Cancellable
|
||||
import org.bukkit.event.Event
|
||||
|
||||
abstract class TBMCChatEventBase(
|
||||
val channel: Channel,
|
||||
open val message: String,
|
||||
/**
|
||||
* The sender's score.
|
||||
*/
|
||||
val score: Int,
|
||||
/**
|
||||
* The sender's group ID.
|
||||
*/
|
||||
val groupID: String,
|
||||
) : Event(true), Cancellable {
|
||||
@JvmField
|
||||
var isCancelled: Boolean = false
|
||||
|
||||
/**
|
||||
* Note: Errors are sent to the sender automatically
|
||||
*/
|
||||
open fun shouldSendTo(sender: ChromaGamerBase): Boolean {
|
||||
return channel.shouldSendTo(sender, score)
|
||||
}
|
||||
|
||||
/**
|
||||
* Note: Errors are sent to the sender automatically
|
||||
*/
|
||||
open fun getMCScore(sender: ChromaGamerBase): Int {
|
||||
return channel.getMCScore(sender)
|
||||
}
|
||||
|
||||
/**
|
||||
* Note: Errors are sent to the sender automatically
|
||||
*
|
||||
* Null means don't send
|
||||
*/
|
||||
open fun getGroupID(sender: ChromaGamerBase): String? {
|
||||
return channel.getGroupID(sender)
|
||||
}
|
||||
|
||||
override fun isCancelled(): Boolean = isCancelled
|
||||
override fun setCancelled(cancel: Boolean) = run { isCancelled = cancel }
|
||||
}
|
44
Chroma-Core/src/main/java/buttondevteam/lib/TBMCChatPreprocessEvent.java
Executable file
44
Chroma-Core/src/main/java/buttondevteam/lib/TBMCChatPreprocessEvent.java
Executable file
|
@ -0,0 +1,44 @@
|
|||
package buttondevteam.lib;
|
||||
|
||||
import buttondevteam.core.component.channel.Channel;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.event.Cancellable;
|
||||
import org.bukkit.event.Event;
|
||||
import org.bukkit.event.HandlerList;
|
||||
|
||||
/**
|
||||
* Can be used to change messages before it's sent.
|
||||
* <b>Only called before sending messages with SendChatMessage.</b>
|
||||
*
|
||||
* @author NorbiPeti
|
||||
*
|
||||
*/
|
||||
@Getter
|
||||
public class TBMCChatPreprocessEvent extends Event implements Cancellable {
|
||||
private static final HandlerList handlers = new HandlerList();
|
||||
|
||||
private final Channel channel;
|
||||
private final CommandSender sender;
|
||||
@Setter
|
||||
private String message;
|
||||
@Setter
|
||||
private boolean cancelled;
|
||||
|
||||
public TBMCChatPreprocessEvent(CommandSender sender, Channel channel, String message) {
|
||||
super(true);
|
||||
this.sender = sender;
|
||||
this.channel = channel;
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
@Override
|
||||
public HandlerList getHandlers() {
|
||||
return handlers;
|
||||
}
|
||||
|
||||
public static HandlerList getHandlerList() {
|
||||
return handlers;
|
||||
}
|
||||
}
|
|
@ -1,30 +0,0 @@
|
|||
package buttondevteam.lib
|
||||
|
||||
import buttondevteam.core.component.channel.Channel
|
||||
import buttondevteam.lib.chat.Command2Sender
|
||||
import org.bukkit.event.Cancellable
|
||||
import org.bukkit.event.Event
|
||||
import org.bukkit.event.HandlerList
|
||||
|
||||
/**
|
||||
* Can be used to change messages before it's sent.
|
||||
* **Only called before sending messages with SendChatMessage.**
|
||||
*
|
||||
* @author NorbiPeti
|
||||
*/
|
||||
class TBMCChatPreprocessEvent(val sender: Command2Sender, val channel: Channel, var message: String) : Event(true),
|
||||
Cancellable {
|
||||
private var cancelled = false
|
||||
override fun getHandlers(): HandlerList {
|
||||
return handlerList
|
||||
}
|
||||
|
||||
override fun isCancelled() = cancelled
|
||||
|
||||
override fun setCancelled(cancelled: Boolean) = run { this.cancelled = cancelled }
|
||||
|
||||
companion object {
|
||||
@JvmStatic
|
||||
val handlerList = HandlerList()
|
||||
}
|
||||
}
|
39
Chroma-Core/src/main/java/buttondevteam/lib/TBMCCommandPreprocessEvent.java
Executable file
39
Chroma-Core/src/main/java/buttondevteam/lib/TBMCCommandPreprocessEvent.java
Executable file
|
@ -0,0 +1,39 @@
|
|||
package buttondevteam.lib;
|
||||
|
||||
import buttondevteam.core.component.channel.Channel;
|
||||
import lombok.Getter;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.Setter;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.event.Cancellable;
|
||||
import org.bukkit.event.Event;
|
||||
import org.bukkit.event.HandlerList;
|
||||
|
||||
/**
|
||||
* Can be used to change or handle commands before they're sent.
|
||||
* <b>Called on using player, console and Discord commands.</b>
|
||||
*
|
||||
* @author NorbiPeti
|
||||
*/
|
||||
@Getter
|
||||
@RequiredArgsConstructor
|
||||
public class TBMCCommandPreprocessEvent extends Event implements Cancellable {
|
||||
private static final HandlerList handlers = new HandlerList();
|
||||
|
||||
private final CommandSender sender;
|
||||
private final Channel channel;
|
||||
@Setter
|
||||
private final String message;
|
||||
private final CommandSender permCheck;
|
||||
@Setter
|
||||
private boolean cancelled;
|
||||
|
||||
@Override
|
||||
public HandlerList getHandlers() {
|
||||
return handlers;
|
||||
}
|
||||
|
||||
public static HandlerList getHandlerList() {
|
||||
return handlers;
|
||||
}
|
||||
}
|
|
@ -1,34 +0,0 @@
|
|||
package buttondevteam.lib
|
||||
|
||||
import buttondevteam.core.component.channel.Channel
|
||||
import buttondevteam.lib.player.ChromaGamerBase
|
||||
import org.bukkit.event.Cancellable
|
||||
import org.bukkit.event.Event
|
||||
import org.bukkit.event.HandlerList
|
||||
|
||||
/**
|
||||
* Can be used to change or handle commands before they're sent.
|
||||
* **Called on using player, console and Discord commands.**
|
||||
*
|
||||
* @author NorbiPeti
|
||||
*/
|
||||
class TBMCCommandPreprocessEvent(
|
||||
val sender: ChromaGamerBase,
|
||||
val channel: Channel,
|
||||
val message: String,
|
||||
val permCheck: ChromaGamerBase
|
||||
) : Event(), Cancellable {
|
||||
private var cancelled = false
|
||||
override fun getHandlers(): HandlerList {
|
||||
return handlerList
|
||||
}
|
||||
|
||||
override fun isCancelled() = cancelled
|
||||
|
||||
override fun setCancelled(cancelled: Boolean) = run { this.cancelled = cancelled }
|
||||
|
||||
companion object {
|
||||
@JvmStatic
|
||||
val handlerList = HandlerList()
|
||||
}
|
||||
}
|
176
Chroma-Core/src/main/java/buttondevteam/lib/TBMCCoreAPI.java
Executable file
176
Chroma-Core/src/main/java/buttondevteam/lib/TBMCCoreAPI.java
Executable file
|
@ -0,0 +1,176 @@
|
|||
package buttondevteam.lib;
|
||||
|
||||
import buttondevteam.core.MainPlugin;
|
||||
import buttondevteam.lib.architecture.Component;
|
||||
import buttondevteam.lib.player.ChromaGamerBase;
|
||||
import buttondevteam.lib.potato.DebugPotato;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.URL;
|
||||
import java.net.URLConnection;
|
||||
import java.util.*;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public class TBMCCoreAPI {
|
||||
static final List<String> coders = new ArrayList<String>() {
|
||||
private static final long serialVersionUID = -4462159250738367334L;
|
||||
|
||||
{
|
||||
add("Alisolarflare");
|
||||
add("NorbiPeti");
|
||||
add("iie");
|
||||
add("thewindmillman");
|
||||
add("mayskam1995");
|
||||
}
|
||||
};
|
||||
|
||||
public static String DownloadString(String urlstr) throws IOException {
|
||||
URL url = new URL(urlstr);
|
||||
URLConnection con = url.openConnection();
|
||||
con.setRequestProperty("User-Agent", "TBMCPlugins");
|
||||
InputStream in = con.getInputStream();
|
||||
String encoding = con.getContentEncoding();
|
||||
encoding = encoding == null ? "UTF-8" : encoding;
|
||||
Scanner s = new Scanner(in).useDelimiter("\\A");
|
||||
String body = s.hasNext() ? s.next() : "";
|
||||
in.close();
|
||||
return body;
|
||||
}
|
||||
|
||||
private static final HashMap<String, Throwable> exceptionsToSend = new HashMap<>();
|
||||
private static final List<String> debugMessagesToSend = new ArrayList<>();
|
||||
|
||||
/**
|
||||
* Send exception to the {@link TBMCExceptionEvent}.
|
||||
*
|
||||
* @param sourcemsg A message that is shown at the top of the exception (before the exception's message)
|
||||
* @param e The exception to send
|
||||
*/
|
||||
public static void SendException(String sourcemsg, Throwable e, Component<?> component) {
|
||||
SendException(sourcemsg, e, false, component::logWarn);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send exception to the {@link TBMCExceptionEvent}.
|
||||
*
|
||||
* @param sourcemsg A message that is shown at the top of the exception (before the exception's message)
|
||||
* @param e The exception to send
|
||||
*/
|
||||
public static void SendException(String sourcemsg, Throwable e, JavaPlugin plugin) {
|
||||
SendException(sourcemsg, e, false, plugin.getLogger()::warning);
|
||||
}
|
||||
|
||||
public static void SendException(String sourcemsg, Throwable e, boolean debugPotato, Consumer<String> logWarn) {
|
||||
try {
|
||||
SendUnsentExceptions();
|
||||
TBMCExceptionEvent event = new TBMCExceptionEvent(sourcemsg, e);
|
||||
Bukkit.getPluginManager().callEvent(event);
|
||||
synchronized (exceptionsToSend) {
|
||||
if (!event.isHandled())
|
||||
exceptionsToSend.put(sourcemsg, e);
|
||||
}
|
||||
logWarn.accept(sourcemsg);
|
||||
e.printStackTrace();
|
||||
if (debugPotato) {
|
||||
List<Player> devsOnline = new ArrayList<>();
|
||||
for (Player player : Bukkit.getOnlinePlayers()) {
|
||||
if (coders.contains(player.getName())) {
|
||||
devsOnline.add(player);
|
||||
}
|
||||
}
|
||||
if (!devsOnline.isEmpty()) {
|
||||
DebugPotato potato = new DebugPotato()
|
||||
.setMessage(new String[]{ //
|
||||
"§b§o" + e.getClass().getSimpleName(), //
|
||||
"§c§o" + sourcemsg, //
|
||||
"§a§oFind a dev to fix this issue"})
|
||||
.setType(e instanceof IOException ? "Throwable Potato"
|
||||
: e instanceof ClassCastException ? "Squished Potato"
|
||||
: e instanceof NullPointerException ? "Plain Potato"
|
||||
: e instanceof StackOverflowError ? "Chips" : "Error Potato");
|
||||
for (Player dev : devsOnline) {
|
||||
potato.Send(dev);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception ee) {
|
||||
System.err.println("Failed to send exception!");
|
||||
ee.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static void sendDebugMessage(String debugMessage) {
|
||||
SendUnsentDebugMessages();
|
||||
TBMCDebugMessageEvent event = new TBMCDebugMessageEvent(debugMessage);
|
||||
Bukkit.getPluginManager().callEvent(event);
|
||||
synchronized (debugMessagesToSend) {
|
||||
if (!event.isSent())
|
||||
debugMessagesToSend.add(debugMessage);
|
||||
}
|
||||
}
|
||||
|
||||
private static EventExceptionCoreHandler eventExceptionCoreHandler;
|
||||
|
||||
/**
|
||||
* Registers Bukkit events, handling the exceptions occurring in those events
|
||||
*
|
||||
* @param listener The class that handles the events
|
||||
* @param plugin The plugin which the listener belongs to
|
||||
*/
|
||||
public static void RegisterEventsForExceptions(Listener listener, Plugin plugin) {
|
||||
if (eventExceptionCoreHandler == null) eventExceptionCoreHandler = new EventExceptionCoreHandler();
|
||||
EventExceptionHandler.registerEvents(listener, plugin, eventExceptionCoreHandler);
|
||||
}
|
||||
|
||||
public static <T extends ChromaGamerBase> void RegisterUserClass(Class<T> userclass, Supplier<T> constructor) {
|
||||
ChromaGamerBase.RegisterPluginUserClass(userclass, constructor);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send exceptions that haven't been sent (their events didn't get handled). This method is used by the DiscordPlugin's ready event
|
||||
*/
|
||||
public static void SendUnsentExceptions() {
|
||||
synchronized (exceptionsToSend) {
|
||||
if (exceptionsToSend.size() > 20) {
|
||||
exceptionsToSend.clear(); // Don't call more and more events if all the handler plugins are unloaded
|
||||
Bukkit.getLogger().warning("Unhandled exception list is over 20! Clearing!");
|
||||
}
|
||||
for (Iterator<Entry<String, Throwable>> iterator = exceptionsToSend.entrySet().iterator(); iterator.hasNext(); ) {
|
||||
Entry<String, Throwable> entry = iterator.next();
|
||||
TBMCExceptionEvent event = new TBMCExceptionEvent(entry.getKey(), entry.getValue());
|
||||
Bukkit.getPluginManager().callEvent(event);
|
||||
if (event.isHandled())
|
||||
iterator.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void SendUnsentDebugMessages() {
|
||||
synchronized (debugMessagesToSend) {
|
||||
if (debugMessagesToSend.size() > 20) {
|
||||
debugMessagesToSend.clear(); // Don't call more and more DebugMessages if all the handler plugins are unloaded
|
||||
Bukkit.getLogger().warning("Unhandled Debug Message list is over 20! Clearing!");
|
||||
}
|
||||
for (Iterator<String> iterator = debugMessagesToSend.iterator(); iterator.hasNext(); ) {
|
||||
String message = iterator.next();
|
||||
TBMCDebugMessageEvent event = new TBMCDebugMessageEvent(message);
|
||||
Bukkit.getPluginManager().callEvent(event);
|
||||
if (event.isSent())
|
||||
iterator.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean IsTestServer() {
|
||||
if (MainPlugin.Instance == null) return true;
|
||||
return MainPlugin.Instance.test.get();
|
||||
}
|
||||
}
|
|
@ -1,179 +0,0 @@
|
|||
package buttondevteam.lib
|
||||
|
||||
import buttondevteam.core.MainPlugin
|
||||
import buttondevteam.lib.architecture.Component
|
||||
import buttondevteam.lib.player.ChromaGamerBase
|
||||
import buttondevteam.lib.player.ChromaGamerBase.Companion.registerPluginUserClass
|
||||
import buttondevteam.lib.potato.DebugPotato
|
||||
import org.bukkit.Bukkit
|
||||
import org.bukkit.ChatColor
|
||||
import org.bukkit.entity.Player
|
||||
import org.bukkit.event.Listener
|
||||
import org.bukkit.plugin.Plugin
|
||||
import org.bukkit.plugin.java.JavaPlugin
|
||||
import java.io.IOException
|
||||
import java.net.URL
|
||||
import java.util.*
|
||||
import java.util.function.Consumer
|
||||
import java.util.function.Supplier
|
||||
|
||||
object TBMCCoreAPI {
|
||||
val coders: List<String> = listOf("Alisolarflare", "NorbiPeti", "iie", "thewindmillman", "mayskam1995")
|
||||
|
||||
@JvmStatic
|
||||
@Throws(IOException::class)
|
||||
fun DownloadString(urlstr: String?): String {
|
||||
val url = URL(urlstr)
|
||||
val con = url.openConnection()
|
||||
con.setRequestProperty("User-Agent", "TBMCPlugins")
|
||||
val `in` = con.getInputStream()
|
||||
var encoding = con.contentEncoding
|
||||
encoding = encoding ?: "UTF-8"
|
||||
val s = Scanner(`in`).useDelimiter("\\A")
|
||||
val body = if (s.hasNext()) s.next() else ""
|
||||
`in`.close()
|
||||
return body
|
||||
}
|
||||
|
||||
private val exceptionsToSend = HashMap<String, Throwable>()
|
||||
private val debugMessagesToSend: MutableList<String> = ArrayList()
|
||||
|
||||
/**
|
||||
* Send exception to the [TBMCExceptionEvent].
|
||||
*
|
||||
* @param sourcemsg A message that is shown at the top of the exception (before the exception's message)
|
||||
* @param e The exception to send
|
||||
*/
|
||||
@JvmStatic
|
||||
fun SendException(sourcemsg: String, e: Throwable, component: Component<*>) {
|
||||
SendException(sourcemsg, e, false) { message: String? -> component.logWarn(message!!) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Send exception to the [TBMCExceptionEvent].
|
||||
*
|
||||
* @param sourcemsg A message that is shown at the top of the exception (before the exception's message)
|
||||
* @param e The exception to send
|
||||
*/
|
||||
@JvmStatic
|
||||
fun SendException(sourcemsg: String, e: Throwable, plugin: JavaPlugin) {
|
||||
SendException(sourcemsg, e, false) { msg: String? -> plugin.logger.warning(msg) }
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun SendException(sourcemsg: String, e: Throwable, debugPotato: Boolean, logWarn: Consumer<String?>) {
|
||||
try {
|
||||
SendUnsentExceptions()
|
||||
val event = TBMCExceptionEvent(sourcemsg, e)
|
||||
Bukkit.getPluginManager().callEvent(event)
|
||||
synchronized(exceptionsToSend) { if (!event.isHandled) exceptionsToSend[sourcemsg] = e }
|
||||
logWarn.accept(sourcemsg)
|
||||
e.printStackTrace()
|
||||
if (debugPotato) {
|
||||
val devsOnline: MutableList<Player> = ArrayList()
|
||||
for (player in Bukkit.getOnlinePlayers()) {
|
||||
if (coders.contains(player.name)) {
|
||||
devsOnline.add(player)
|
||||
}
|
||||
}
|
||||
if (devsOnline.isNotEmpty()) {
|
||||
val potato = DebugPotato()
|
||||
.setMessage(
|
||||
arrayOf( //
|
||||
"${ChatColor.AQUA}${ChatColor.ITALIC}" + e.javaClass.simpleName, //
|
||||
"${ChatColor.RED}${ChatColor.ITALIC}$sourcemsg", //
|
||||
"${ChatColor.GREEN}${ChatColor.ITALIC}Find a dev to fix this issue"
|
||||
)
|
||||
)
|
||||
.setType(
|
||||
when (e) {
|
||||
is IOException -> "Throwable Potato"
|
||||
is ClassCastException -> "Squished Potato"
|
||||
is NullPointerException -> "Plain Potato"
|
||||
is StackOverflowError -> "Chips"
|
||||
else -> "Error Potato"
|
||||
}
|
||||
)
|
||||
for (dev in devsOnline) {
|
||||
potato.Send(dev)
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (ee: Exception) {
|
||||
System.err.println("Failed to send exception!")
|
||||
ee.printStackTrace()
|
||||
}
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun sendDebugMessage(debugMessage: String) {
|
||||
SendUnsentDebugMessages()
|
||||
val event = TBMCDebugMessageEvent(debugMessage)
|
||||
Bukkit.getPluginManager().callEvent(event)
|
||||
synchronized(debugMessagesToSend) { if (!event.isSent) debugMessagesToSend.add(debugMessage) }
|
||||
}
|
||||
|
||||
private var eventExceptionCoreHandler: EventExceptionCoreHandler? = null
|
||||
|
||||
/**
|
||||
* Registers Bukkit events, handling the exceptions occurring in those events
|
||||
*
|
||||
* @param listener The class that handles the events
|
||||
* @param plugin The plugin which the listener belongs to
|
||||
*/
|
||||
@JvmStatic
|
||||
fun RegisterEventsForExceptions(listener: Listener, plugin: Plugin) {
|
||||
if (eventExceptionCoreHandler == null) eventExceptionCoreHandler = EventExceptionCoreHandler()
|
||||
EventExceptionHandler.registerEvents(listener, plugin, eventExceptionCoreHandler)
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun <T : ChromaGamerBase> RegisterUserClass(userclass: Class<T>, constructor: Supplier<T>) {
|
||||
registerPluginUserClass(userclass, constructor)
|
||||
}
|
||||
|
||||
/**
|
||||
* Send exceptions that haven't been sent (their events didn't get handled). This method is used by the DiscordPlugin's ready event
|
||||
*/
|
||||
@JvmStatic
|
||||
fun SendUnsentExceptions() {
|
||||
synchronized(exceptionsToSend) {
|
||||
if (exceptionsToSend.size > 20) {
|
||||
exceptionsToSend.clear() // Don't call more and more events if all the handler plugins are unloaded
|
||||
Bukkit.getLogger().warning("Unhandled exception list is over 20! Clearing!")
|
||||
}
|
||||
val iterator: MutableIterator<Map.Entry<String, Throwable>> = exceptionsToSend.entries.iterator()
|
||||
while (iterator.hasNext()) {
|
||||
val (key, value) = iterator.next()
|
||||
val event = TBMCExceptionEvent(key, value)
|
||||
Bukkit.getPluginManager().callEvent(event)
|
||||
if (event.isHandled) iterator.remove()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun SendUnsentDebugMessages() {
|
||||
synchronized(debugMessagesToSend) {
|
||||
if (debugMessagesToSend.size > 20) {
|
||||
debugMessagesToSend.clear() // Don't call more and more DebugMessages if all the handler plugins are unloaded
|
||||
Bukkit.getLogger().warning("Unhandled Debug Message list is over 20! Clearing!")
|
||||
}
|
||||
val iterator = debugMessagesToSend.iterator()
|
||||
while (iterator.hasNext()) {
|
||||
val message = iterator.next()
|
||||
val event = TBMCDebugMessageEvent(message)
|
||||
Bukkit.getPluginManager().callEvent(event)
|
||||
if (event.isSent) iterator.remove()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the server is a test/dev/staging server
|
||||
*/
|
||||
@JvmStatic
|
||||
fun IsTestServer(): Boolean {
|
||||
return MainPlugin.instance.test.get()
|
||||
}
|
||||
}
|
43
Chroma-Core/src/main/java/buttondevteam/lib/TBMCExceptionEvent.java
Executable file
43
Chroma-Core/src/main/java/buttondevteam/lib/TBMCExceptionEvent.java
Executable file
|
@ -0,0 +1,43 @@
|
|||
package buttondevteam.lib;
|
||||
|
||||
import lombok.Getter;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.event.Event;
|
||||
import org.bukkit.event.HandlerList;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* This event gets called (ideally) each time an exception occurs in a TBMC plugin. To call it, use {@link TBMCCoreAPI#SendException(String, Throwable)}.
|
||||
* </p>
|
||||
*
|
||||
* @author Norbi
|
||||
*
|
||||
*/
|
||||
@Getter
|
||||
public class TBMCExceptionEvent extends Event {
|
||||
private static final HandlerList handlers = new HandlerList();
|
||||
|
||||
private final String sourceMessage;
|
||||
private final Throwable exception;
|
||||
private boolean handled;
|
||||
|
||||
@java.beans.ConstructorProperties({"sourceMessage", "exception"})
|
||||
public TBMCExceptionEvent(String sourceMessage, Throwable exception) {
|
||||
super(!Bukkit.isPrimaryThread());
|
||||
this.sourceMessage = sourceMessage;
|
||||
this.exception = exception;
|
||||
}
|
||||
|
||||
public void setHandled() {
|
||||
handled = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public HandlerList getHandlers() {
|
||||
return handlers;
|
||||
}
|
||||
|
||||
public static HandlerList getHandlerList() {
|
||||
return handlers;
|
||||
}
|
||||
}
|
|
@ -1,24 +0,0 @@
|
|||
package buttondevteam.lib
|
||||
|
||||
import org.bukkit.Bukkit
|
||||
import org.bukkit.event.Event
|
||||
import org.bukkit.event.HandlerList
|
||||
|
||||
/**
|
||||
* This event gets called (ideally) each time an exception occurs in a TBMC plugin. To call it, use [TBMCCoreAPI.SendException].
|
||||
*
|
||||
*
|
||||
* @author Norbi
|
||||
*/
|
||||
class TBMCExceptionEvent(val sourceMessage: String, val exception: Throwable) : Event(!Bukkit.isPrimaryThread()) {
|
||||
var isHandled = false
|
||||
|
||||
override fun getHandlers(): HandlerList {
|
||||
return handlerList
|
||||
}
|
||||
|
||||
companion object {
|
||||
@JvmStatic
|
||||
val handlerList = HandlerList()
|
||||
}
|
||||
}
|
74
Chroma-Core/src/main/java/buttondevteam/lib/TBMCSystemChatEvent.java
Executable file
74
Chroma-Core/src/main/java/buttondevteam/lib/TBMCSystemChatEvent.java
Executable file
|
@ -0,0 +1,74 @@
|
|||
package buttondevteam.lib;
|
||||
|
||||
import buttondevteam.core.component.channel.Channel;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.Getter;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.val;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.event.HandlerList;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import java.util.HashSet;
|
||||
import java.util.Objects;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* Make sure to only send the message to users who {@link #shouldSendTo(CommandSender)} returns true.
|
||||
*
|
||||
* @author NorbiPeti
|
||||
*
|
||||
*/
|
||||
@Getter
|
||||
public class TBMCSystemChatEvent extends TBMCChatEventBase {
|
||||
private final String[] exceptions;
|
||||
private final BroadcastTarget target;
|
||||
private boolean handled;
|
||||
|
||||
public void setHandled() {
|
||||
handled = true;
|
||||
}
|
||||
|
||||
public TBMCSystemChatEvent(Channel channel, String message, int score, String groupid, String[] exceptions, BroadcastTarget target) { // TODO: Rich message
|
||||
super(channel, message, score, groupid);
|
||||
this.exceptions = exceptions;
|
||||
this.target = target;
|
||||
}
|
||||
|
||||
private static final HandlerList handlers = new HandlerList();
|
||||
|
||||
@Override
|
||||
public HandlerList getHandlers() {
|
||||
return handlers;
|
||||
}
|
||||
|
||||
public static HandlerList getHandlerList() {
|
||||
return handlers;
|
||||
}
|
||||
|
||||
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
|
||||
public static class BroadcastTarget {
|
||||
private final @Getter String name;
|
||||
private static final HashSet<BroadcastTarget> targets = new HashSet<>();
|
||||
public static final BroadcastTarget ALL = new BroadcastTarget("ALL");
|
||||
|
||||
public static BroadcastTarget add(String name) {
|
||||
val bt = new BroadcastTarget(Objects.requireNonNull(name));
|
||||
targets.add(bt);
|
||||
return bt;
|
||||
}
|
||||
|
||||
public static void remove(BroadcastTarget target) {
|
||||
targets.remove(target);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static BroadcastTarget get(String name) {
|
||||
return targets.stream().filter(bt -> bt.name.equalsIgnoreCase(name)).findAny().orElse(null);
|
||||
}
|
||||
|
||||
public static Stream<BroadcastTarget> stream() {
|
||||
return targets.stream();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,62 +0,0 @@
|
|||
package buttondevteam.lib
|
||||
|
||||
import buttondevteam.core.component.channel.Channel
|
||||
import org.bukkit.event.HandlerList
|
||||
import java.util.*
|
||||
import java.util.stream.Stream
|
||||
|
||||
/**
|
||||
* Make sure to only send the message to users who [.shouldSendTo] returns true.
|
||||
*
|
||||
* @author NorbiPeti
|
||||
*/ // TODO: Rich message
|
||||
class TBMCSystemChatEvent(
|
||||
channel: Channel,
|
||||
message: String,
|
||||
score: Int,
|
||||
groupid: String,
|
||||
val exceptions: Array<out String>,
|
||||
val target: BroadcastTarget
|
||||
) : TBMCChatEventBase(channel, message, score, groupid) {
|
||||
var isHandled = false
|
||||
|
||||
override fun getHandlers(): HandlerList {
|
||||
return handlerList
|
||||
}
|
||||
|
||||
class BroadcastTarget private constructor(val name: String) {
|
||||
companion object {
|
||||
private val targets = HashSet<BroadcastTarget?>()
|
||||
@JvmField
|
||||
val ALL = BroadcastTarget("ALL")
|
||||
|
||||
@JvmStatic
|
||||
fun add(name: String): BroadcastTarget {
|
||||
val bt = BroadcastTarget(Objects.requireNonNull(name))
|
||||
targets.add(bt)
|
||||
return bt
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun remove(target: BroadcastTarget?) {
|
||||
targets.remove(target)
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
operator fun get(name: String?): BroadcastTarget? {
|
||||
return targets.stream().filter { bt: BroadcastTarget? -> bt!!.name.equals(name, ignoreCase = true) }
|
||||
.findAny().orElse(null)
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun stream(): Stream<BroadcastTarget?> {
|
||||
return targets.stream()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
@JvmStatic
|
||||
val handlerList = HandlerList()
|
||||
}
|
||||
}
|
|
@ -0,0 +1,171 @@
|
|||
package buttondevteam.lib.architecture;
|
||||
|
||||
import buttondevteam.buttonproc.HasConfig;
|
||||
import buttondevteam.core.ComponentManager;
|
||||
import buttondevteam.lib.TBMCCoreAPI;
|
||||
import buttondevteam.lib.chat.Command2MC;
|
||||
import buttondevteam.lib.chat.ICommand2MC;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.Getter;
|
||||
import org.bukkit.configuration.InvalidConfigurationException;
|
||||
import org.bukkit.configuration.file.FileConfiguration;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
import java.util.Arrays;
|
||||
import java.util.Optional;
|
||||
import java.util.Stack;
|
||||
|
||||
@HasConfig(global = true)
|
||||
public abstract class ButtonPlugin extends JavaPlugin {
|
||||
@Getter //Needs to be static as we don't know the plugin when a command is handled
|
||||
private static final Command2MC command2MC = new Command2MC();
|
||||
@Getter(AccessLevel.PROTECTED)
|
||||
private final IHaveConfig iConfig = new IHaveConfig(this::saveConfig);
|
||||
private CommentedConfiguration yaml;
|
||||
@Getter(AccessLevel.PROTECTED)
|
||||
private IHaveConfig data; //TODO
|
||||
/**
|
||||
* Used to unregister components in the right order - and to reload configs
|
||||
*/
|
||||
@Getter
|
||||
private final Stack<Component<?>> componentStack = new Stack<>();
|
||||
|
||||
protected abstract void pluginEnable();
|
||||
|
||||
/**
|
||||
* Called after the components are unregistered
|
||||
*/
|
||||
protected abstract void pluginDisable();
|
||||
|
||||
/**
|
||||
* Called before the components are unregistered
|
||||
*/
|
||||
protected void pluginPreDisable() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public final void onEnable() {
|
||||
if (!loadConfig()) {
|
||||
getLogger().warning("Please fix the issues and restart the server to load the plugin.");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
pluginEnable();
|
||||
} catch (Exception e) {
|
||||
TBMCCoreAPI.SendException("Error while enabling plugin " + getName() + "!", e, this);
|
||||
}
|
||||
if (configGenAllowed(this)) //If it's not disabled (by default it's not)
|
||||
IHaveConfig.pregenConfig(this, null);
|
||||
}
|
||||
|
||||
private boolean loadConfig() {
|
||||
var config = getConfig();
|
||||
if (config == null)
|
||||
return false;
|
||||
var section = config.getConfigurationSection("global");
|
||||
if (section == null) section = config.createSection("global");
|
||||
iConfig.reset(section);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public final void onDisable() {
|
||||
try {
|
||||
pluginPreDisable();
|
||||
ComponentManager.unregComponents(this);
|
||||
pluginDisable();
|
||||
if (ConfigData.saveNow(getConfig()))
|
||||
getLogger().info("Saved configuration changes.");
|
||||
getCommand2MC().unregisterCommands(this);
|
||||
} catch (Exception e) {
|
||||
TBMCCoreAPI.SendException("Error while disabling plugin " + getName() + "!", e, this);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void reloadConfig() {
|
||||
tryReloadConfig();
|
||||
}
|
||||
|
||||
public boolean tryReloadConfig() {
|
||||
if (!justReload()) return false;
|
||||
loadConfig();
|
||||
componentStack.forEach(c -> Component.updateConfig(this, c));
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean justReload() {
|
||||
if (yaml != null && ConfigData.saveNow(getConfig())) {
|
||||
getLogger().warning("Saved pending configuration changes to the file, didn't reload. Apply your changes again.");
|
||||
return false;
|
||||
}
|
||||
var file = new File(getDataFolder(), "config.yml");
|
||||
var yaml = new CommentedConfiguration(file);
|
||||
if (file.exists()) {
|
||||
try {
|
||||
yaml.load(file);
|
||||
} catch (IOException | InvalidConfigurationException e) {
|
||||
getLogger().warning("Failed to load config! Check for syntax errors.");
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
this.yaml = yaml;
|
||||
var res = getTextResource("configHelp.yml");
|
||||
if (res == null)
|
||||
return true;
|
||||
var yc = YamlConfiguration.loadConfiguration(res);
|
||||
for (var kv : yc.getValues(true).entrySet())
|
||||
if (kv.getValue() instanceof String)
|
||||
yaml.addComment(kv.getKey().replace(".generalDescriptionInsteadOfAConfig", ""),
|
||||
Arrays.stream(((String) kv.getValue()).split("\n"))
|
||||
.map(str -> "# " + str.trim()).toArray(String[]::new));
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public FileConfiguration getConfig() {
|
||||
if (yaml == null)
|
||||
justReload();
|
||||
if (yaml == null) return new YamlConfiguration(); //Return a temporary instance
|
||||
return yaml;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void saveConfig() {
|
||||
try {
|
||||
if (yaml != null)
|
||||
yaml.save();
|
||||
} catch (Exception e) {
|
||||
TBMCCoreAPI.SendException("Failed to save config", e, this);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers command and sets its plugin.
|
||||
*
|
||||
* @param command The command to register
|
||||
*/
|
||||
protected void registerCommand(ICommand2MC command) {
|
||||
command.registerToPlugin(this);
|
||||
getCommand2MC().registerCommand(command);
|
||||
}
|
||||
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.TYPE)
|
||||
public @interface ConfigOpts {
|
||||
boolean disableConfigGen() default false;
|
||||
}
|
||||
|
||||
public static boolean configGenAllowed(Object obj) {
|
||||
return !Optional.ofNullable(obj.getClass().getAnnotation(ConfigOpts.class))
|
||||
.map(ConfigOpts::disableConfigGen).orElse(false);
|
||||
}
|
||||
}
|
|
@ -1,159 +0,0 @@
|
|||
package buttondevteam.lib.architecture
|
||||
|
||||
import buttondevteam.buttonproc.HasConfig
|
||||
import buttondevteam.core.ComponentManager
|
||||
import buttondevteam.lib.TBMCCoreAPI
|
||||
import buttondevteam.lib.chat.Command2MC
|
||||
import buttondevteam.lib.chat.ICommand2MC
|
||||
import org.bukkit.Bukkit
|
||||
import org.bukkit.configuration.InvalidConfigurationException
|
||||
import org.bukkit.configuration.file.FileConfiguration
|
||||
import org.bukkit.configuration.file.YamlConfiguration
|
||||
import org.bukkit.plugin.PluginDescriptionFile
|
||||
import org.bukkit.plugin.java.JavaPlugin
|
||||
import org.bukkit.plugin.java.JavaPluginLoader
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.util.*
|
||||
import java.util.function.Consumer
|
||||
|
||||
@HasConfig(global = true)
|
||||
abstract class ButtonPlugin : JavaPlugin {
|
||||
protected val iConfig = IHaveConfig(::saveConfig, section)
|
||||
private var yaml: YamlConfiguration? = null
|
||||
|
||||
/**
|
||||
* May change if the config is reloaded
|
||||
*/
|
||||
private val section get() = config.getConfigurationSection("global") ?: config.createSection("global")
|
||||
|
||||
protected val data //TODO
|
||||
: IHaveConfig? = null
|
||||
|
||||
/**
|
||||
* Used to unregister components in the right order - and to reload configs
|
||||
*/
|
||||
val componentStack = Stack<Component<*>>()
|
||||
|
||||
// Support testing with the protected constructor (MockBukkit)
|
||||
constructor() : super()
|
||||
protected constructor(loader: JavaPluginLoader, description: PluginDescriptionFile, dataFolder: File, file: File) : super(loader, description, dataFolder, file)
|
||||
|
||||
protected abstract fun pluginEnable()
|
||||
|
||||
/**
|
||||
* Called after the components are unregistered
|
||||
*/
|
||||
protected abstract fun pluginDisable()
|
||||
|
||||
/**
|
||||
* Called before the components are unregistered
|
||||
*/
|
||||
protected open fun pluginPreDisable() {}
|
||||
override fun onEnable() {
|
||||
if (!isConfigLoaded) {
|
||||
logger.warning("Please fix the issues and restart the server to load the plugin.")
|
||||
Bukkit.getPluginManager().disablePlugin(this)
|
||||
return
|
||||
}
|
||||
try {
|
||||
pluginEnable()
|
||||
} catch (e: Exception) {
|
||||
TBMCCoreAPI.SendException("Error while enabling plugin $name!", e, this)
|
||||
}
|
||||
if (configGenAllowed(this)) //If it's not disabled (by default it's not)
|
||||
IHaveConfig.pregenConfig(this, null)
|
||||
}
|
||||
|
||||
override fun onDisable() {
|
||||
try {
|
||||
if (!isConfigLoaded) return
|
||||
pluginPreDisable()
|
||||
ComponentManager.unregComponents(this)
|
||||
pluginDisable()
|
||||
if (ConfigData.saveNow(config)) logger.info("Saved configuration changes.")
|
||||
command2MC.unregisterCommands(this)
|
||||
} catch (e: Exception) {
|
||||
TBMCCoreAPI.SendException("Error while disabling plugin $name!", e, this)
|
||||
}
|
||||
}
|
||||
|
||||
override fun reloadConfig() {
|
||||
tryReloadConfig()
|
||||
}
|
||||
|
||||
fun tryReloadConfig(): Boolean {
|
||||
if (!saveAndReloadYaml()) return false
|
||||
iConfig.reload(section)
|
||||
componentStack.forEach(Consumer { c -> c.updateConfig() })
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether the config was loaded successfully. Otherwise, an empty config is used.
|
||||
*/
|
||||
private fun saveAndReloadYaml(): Boolean {
|
||||
if (isConfigLoaded && ConfigData.saveNow(config)) {
|
||||
logger.warning("Saved pending configuration changes to the file, didn't reload. Apply your changes again.")
|
||||
return false
|
||||
}
|
||||
val file = File(dataFolder, "config.yml")
|
||||
val yaml = YamlConfiguration()
|
||||
if (file.exists()) {
|
||||
try {
|
||||
yaml.load(file)
|
||||
} catch (e: IOException) {
|
||||
logger.warning("Failed to load config! Check for syntax errors.")
|
||||
e.printStackTrace()
|
||||
return false
|
||||
} catch (e: InvalidConfigurationException) {
|
||||
logger.warning("Failed to load config! Check for syntax errors.")
|
||||
e.printStackTrace()
|
||||
return false
|
||||
}
|
||||
}
|
||||
this.yaml = yaml
|
||||
val res = getTextResource("configHelp.yml") ?: return true
|
||||
val yc = YamlConfiguration.loadConfiguration(res)
|
||||
for ((key, value) in yc.getValues(true))
|
||||
if (value is String) yaml.setComments(
|
||||
key.replace(".generalDescriptionInsteadOfAConfig", ""),
|
||||
value.split("\n").map { str -> "# " + str.trim { it <= ' ' } }
|
||||
)
|
||||
return true
|
||||
}
|
||||
|
||||
override fun getConfig(): FileConfiguration {
|
||||
if (!isConfigLoaded) saveAndReloadYaml()
|
||||
return yaml ?: YamlConfiguration() //Return a temporary instance
|
||||
}
|
||||
|
||||
override fun saveConfig() {
|
||||
if (isConfigLoaded) super.saveConfig()
|
||||
}
|
||||
|
||||
val isConfigLoaded get() = yaml != null
|
||||
|
||||
/**
|
||||
* Registers command and sets its plugin.
|
||||
*
|
||||
* @param command The command to register
|
||||
*/
|
||||
fun registerCommand(command: ICommand2MC) {
|
||||
command.registerToPlugin(this)
|
||||
command2MC.registerCommand(command)
|
||||
}
|
||||
|
||||
@Retention(AnnotationRetention.RUNTIME)
|
||||
@Target(AnnotationTarget.ANNOTATION_CLASS, AnnotationTarget.CLASS)
|
||||
annotation class ConfigOpts(val disableConfigGen: Boolean = false)
|
||||
companion object {
|
||||
//Needs to be static as we don't know the plugin when a command is handled
|
||||
@JvmStatic
|
||||
val command2MC = Command2MC()
|
||||
fun configGenAllowed(obj: Any): Boolean {
|
||||
return !Optional.ofNullable(obj.javaClass.getAnnotation(ConfigOpts::class.java))
|
||||
.map { it.disableConfigGen }.orElse(false)
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,229 @@
|
|||
package buttondevteam.lib.architecture;
|
||||
|
||||
import org.bukkit.configuration.InvalidConfigurationException;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import org.bukkit.configuration.file.YamlConstructor;
|
||||
import org.bukkit.configuration.file.YamlRepresenter;
|
||||
import org.yaml.snakeyaml.DumperOptions;
|
||||
import org.yaml.snakeyaml.Yaml;
|
||||
import org.yaml.snakeyaml.representer.Representer;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.util.HashMap;
|
||||
|
||||
/**
|
||||
* A copy of Towny's CommentedConfiguration: https://github.com/TownyAdvanced/Towny/blob/master/src/com/palmergames/bukkit/config/CommentedConfiguration.java
|
||||
* Modified to remove dependency on the FileMgmt class
|
||||
*
|
||||
* @author dumptruckman & Articdive
|
||||
*/
|
||||
public class CommentedConfiguration extends YamlConfiguration {
|
||||
private HashMap<String, String> comments;
|
||||
private File file;
|
||||
|
||||
private final DumperOptions yamlOptions = new DumperOptions();
|
||||
private final Representer yamlRepresenter = new YamlRepresenter();
|
||||
private final Yaml yaml = new Yaml(new YamlConstructor(), yamlRepresenter, yamlOptions);
|
||||
|
||||
public CommentedConfiguration(File file) {
|
||||
|
||||
super();
|
||||
comments = new HashMap<>();
|
||||
this.file = file;
|
||||
}
|
||||
|
||||
public boolean load() {
|
||||
|
||||
boolean loaded = true;
|
||||
|
||||
try {
|
||||
this.load(file);
|
||||
} catch (InvalidConfigurationException | IOException e) {
|
||||
loaded = false;
|
||||
}
|
||||
|
||||
return loaded;
|
||||
}
|
||||
|
||||
public void save() throws IOException {
|
||||
|
||||
boolean saved = true;
|
||||
|
||||
// Save the config just like normal
|
||||
try {
|
||||
this.save(file);
|
||||
|
||||
} catch (Exception e) {
|
||||
saved = false;
|
||||
}
|
||||
|
||||
// if there's comments to add and it saved fine, we need to add comments
|
||||
if (!comments.isEmpty() && saved) {
|
||||
// String array of each line in the config file
|
||||
String[] yamlContents = Files.readAllLines(file.toPath()).toArray(new String[0]);
|
||||
|
||||
// This will hold the newly formatted line
|
||||
StringBuilder newContents = new StringBuilder();
|
||||
// This holds the current path the lines are at in the config
|
||||
String currentPath = "";
|
||||
// This flags if the line is a node or unknown text.
|
||||
boolean node;
|
||||
// The depth of the path. (number of words separated by periods - 1)
|
||||
int depth = 0;
|
||||
|
||||
// Loop through the config lines
|
||||
for (String line : yamlContents) {
|
||||
// If the line is a node (and not something like a list value)
|
||||
if (line.contains(": ") || (line.length() > 1 && line.charAt(line.length() - 1) == ':')) {
|
||||
|
||||
// This is a node so flag it as one
|
||||
node = true;
|
||||
|
||||
// Grab the index of the end of the node name
|
||||
int index;
|
||||
index = line.indexOf(": ");
|
||||
if (index < 0) {
|
||||
index = line.length() - 1;
|
||||
}
|
||||
// If currentPath is empty, store the node name as the currentPath. (this is only on the first iteration, i think)
|
||||
if (currentPath.isEmpty()) {
|
||||
currentPath = line.substring(0, index);
|
||||
} else {
|
||||
// Calculate the whitespace preceding the node name
|
||||
int whiteSpace = 0;
|
||||
for (int n = 0; n < line.length(); n++) {
|
||||
if (line.charAt(n) == ' ') {
|
||||
whiteSpace++;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// Find out if the current depth (whitespace * 2) is greater/lesser/equal to the previous depth
|
||||
if (whiteSpace / 2 > depth) {
|
||||
// Path is deeper. Add a . and the node name
|
||||
currentPath += "." + line.substring(whiteSpace, index);
|
||||
depth++;
|
||||
} else if (whiteSpace / 2 < depth) {
|
||||
// Path is shallower, calculate current depth from whitespace (whitespace / 2) and subtract that many levels from the currentPath
|
||||
int newDepth = whiteSpace / 2;
|
||||
for (int i = 0; i < depth - newDepth; i++) {
|
||||
currentPath = currentPath.replace(currentPath.substring(currentPath.lastIndexOf(".")), "");
|
||||
}
|
||||
// Grab the index of the final period
|
||||
int lastIndex = currentPath.lastIndexOf(".");
|
||||
if (lastIndex < 0) {
|
||||
// if there isn't a final period, set the current path to nothing because we're at root
|
||||
currentPath = "";
|
||||
} else {
|
||||
// If there is a final period, replace everything after it with nothing
|
||||
currentPath = currentPath.replace(currentPath.substring(currentPath.lastIndexOf(".")), "");
|
||||
currentPath += ".";
|
||||
}
|
||||
// Add the new node name to the path
|
||||
currentPath += line.substring(whiteSpace, index);
|
||||
// Reset the depth
|
||||
depth = newDepth;
|
||||
} else {
|
||||
// Path is same depth, replace the last path node name to the current node name
|
||||
int lastIndex = currentPath.lastIndexOf(".");
|
||||
if (lastIndex < 0) {
|
||||
// if there isn't a final period, set the current path to nothing because we're at root
|
||||
currentPath = "";
|
||||
} else {
|
||||
// If there is a final period, replace everything after it with nothing
|
||||
currentPath = currentPath.replace(currentPath.substring(currentPath.lastIndexOf(".")), "");
|
||||
currentPath += ".";
|
||||
}
|
||||
//currentPath = currentPath.replace(currentPath.substring(currentPath.lastIndexOf(".")), "");
|
||||
currentPath += line.substring(whiteSpace, index);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
} else {
|
||||
node = false;
|
||||
}
|
||||
|
||||
if (node) {
|
||||
// If there's a comment for the current path, retrieve it and flag that path as already commented
|
||||
String comment = comments.get(currentPath);
|
||||
|
||||
if (comment != null) {
|
||||
// Add the comment to the beginning of the current line
|
||||
line = comment + System.getProperty("line.separator") + line + System.getProperty("line.separator");
|
||||
} else {
|
||||
// Add a new line as it is a node, but has no comment
|
||||
line += System.getProperty("line.separator");
|
||||
}
|
||||
}
|
||||
// Add the (modified) line to the total config String
|
||||
if (!node) {
|
||||
newContents.append(line).append(System.getProperty("line.separator"));
|
||||
} else {
|
||||
newContents.append(line);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Due to a Bukkit Bug with the Configuration
|
||||
* we just need to remove any extra comments at the start of a file.
|
||||
*/
|
||||
while (newContents.toString().startsWith(" " + System.getProperty("line.separator"))) {
|
||||
newContents = new StringBuilder(newContents.toString().replaceFirst(" " + System.getProperty("line.separator"), ""));
|
||||
}
|
||||
Files.write(file.toPath(), newContents.toString().getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a comment just before the specified path. The comment can be
|
||||
* multiple lines. An empty string will indicate a blank line.
|
||||
*
|
||||
* @param path Configuration path to add comment.
|
||||
* @param commentLines Comments to add. One String per line.
|
||||
*/
|
||||
public void addComment(String path, String... commentLines) {
|
||||
|
||||
StringBuilder commentstring = new StringBuilder();
|
||||
StringBuilder leadingSpaces = new StringBuilder();
|
||||
for (int n = 0; n < path.length(); n++) {
|
||||
if (path.charAt(n) == '.') {
|
||||
leadingSpaces.append(" ");
|
||||
}
|
||||
}
|
||||
for (String line : commentLines) {
|
||||
if (!line.isEmpty()) {
|
||||
line = leadingSpaces + line;
|
||||
} else {
|
||||
line = " ";
|
||||
}
|
||||
if (commentstring.length() > 0) {
|
||||
commentstring.append(System.getProperty("line.separator"));
|
||||
}
|
||||
commentstring.append(line);
|
||||
}
|
||||
comments.put(path, commentstring.toString());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String saveToString() {
|
||||
yamlOptions.setIndent(options().indent());
|
||||
yamlOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
|
||||
yamlOptions.setWidth(10000);
|
||||
yamlRepresenter.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
|
||||
|
||||
|
||||
String dump = yaml.dump(getValues(false));
|
||||
|
||||
|
||||
if (dump.equals(BLANK_CONFIG)) {
|
||||
dump = "";
|
||||
}
|
||||
|
||||
return dump;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,274 @@
|
|||
package buttondevteam.lib.architecture;
|
||||
|
||||
import buttondevteam.buttonproc.HasConfig;
|
||||
import buttondevteam.core.ComponentManager;
|
||||
import buttondevteam.lib.TBMCCoreAPI;
|
||||
import buttondevteam.lib.architecture.exceptions.UnregisteredComponentException;
|
||||
import buttondevteam.lib.chat.ICommand2MC;
|
||||
import lombok.Getter;
|
||||
import lombok.NonNull;
|
||||
import lombok.val;
|
||||
import org.bukkit.configuration.ConfigurationSection;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* Configuration is based on class name
|
||||
*/
|
||||
@HasConfig(global = false) //Used for obtaining javadoc
|
||||
public abstract class Component<TP extends JavaPlugin> {
|
||||
@SuppressWarnings("rawtypes") private static HashMap<Class<? extends Component>, Component<? extends JavaPlugin>> components = new HashMap<>();
|
||||
|
||||
@Getter
|
||||
private boolean enabled = false;
|
||||
@Getter
|
||||
@NonNull
|
||||
private TP plugin;
|
||||
private @Getter final IHaveConfig config = new IHaveConfig(null);
|
||||
private @Getter IHaveConfig data; //TODO
|
||||
|
||||
public final ConfigData<Boolean> shouldBeEnabled = config.getData("enabled",
|
||||
Optional.ofNullable(getClass().getAnnotation(ComponentMetadata.class)).map(ComponentMetadata::enabledByDefault).orElse(true));
|
||||
|
||||
/**
|
||||
* Registers a component checking it's dependencies and calling {@link #register(JavaPlugin)}.<br>
|
||||
* Make sure to register the dependencies first.<br>
|
||||
* The component will be enabled automatically, regardless of when it was registered.<br>
|
||||
* <b>If not using {@link ButtonPlugin}, call {@link ComponentManager#unregComponents(ButtonPlugin)} on plugin disable.</b>
|
||||
*
|
||||
* @param component The component to register
|
||||
* @return Whether the component is registered successfully (it may have failed to enable)
|
||||
*/
|
||||
public static <T extends JavaPlugin> boolean registerComponent(T plugin, Component<T> component) {
|
||||
return registerUnregisterComponent(plugin, component, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Unregisters a component by calling {@link #unregister(JavaPlugin)}.<br>
|
||||
* Make sure to unregister the dependencies last.<br>
|
||||
* <b>Components will be unregistered in opposite order of registering by default by {@link ButtonPlugin} or {@link ComponentManager#unregComponents(ButtonPlugin)}.</b>
|
||||
*
|
||||
* @param component The component to unregister
|
||||
* @return Whether the component is unregistered successfully (it also got disabled)
|
||||
*/
|
||||
public static <T extends JavaPlugin> boolean unregisterComponent(T plugin, Component<T> component) {
|
||||
return registerUnregisterComponent(plugin, component, false);
|
||||
}
|
||||
|
||||
public static <T extends JavaPlugin> boolean registerUnregisterComponent(T plugin, Component<T> component, boolean register) {
|
||||
try {
|
||||
val metaAnn = component.getClass().getAnnotation(ComponentMetadata.class);
|
||||
if (metaAnn != null) {
|
||||
@SuppressWarnings("rawtypes") Class<? extends Component>[] dependencies = metaAnn.depends();
|
||||
for (val dep : dependencies) { //TODO: Support dependencies at enable/disable as well
|
||||
if (!components.containsKey(dep)) {
|
||||
plugin.getLogger().warning("Failed to " + (register ? "" : "un") + "register component " + component.getClassName() + " as a required dependency is missing/disabled: " + dep.getSimpleName());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (register) {
|
||||
if (components.containsKey(component.getClass())) {
|
||||
TBMCCoreAPI.SendException("Failed to register component " + component.getClassName(), new IllegalArgumentException("The component is already registered!"), plugin);
|
||||
return false;
|
||||
}
|
||||
component.plugin = plugin;
|
||||
component.config.setSaveAction(plugin::saveConfig);
|
||||
updateConfig(plugin, component);
|
||||
component.register(plugin);
|
||||
components.put(component.getClass(), component);
|
||||
if (plugin instanceof ButtonPlugin)
|
||||
((ButtonPlugin) plugin).getComponentStack().push(component);
|
||||
if (ComponentManager.areComponentsEnabled() && component.shouldBeEnabled.get()) {
|
||||
try { //Enable components registered after the previous ones getting enabled
|
||||
setComponentEnabled(component, true);
|
||||
return true;
|
||||
} catch (Exception | NoClassDefFoundError e) {
|
||||
TBMCCoreAPI.SendException("Failed to enable component " + component.getClassName() + "!", e, component);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (!components.containsKey(component.getClass()))
|
||||
return true; //Already unregistered
|
||||
if (component.enabled) {
|
||||
try {
|
||||
setComponentEnabled(component, false);
|
||||
} catch (Exception | NoClassDefFoundError e) {
|
||||
TBMCCoreAPI.SendException("Failed to disable component " + component.getClassName() + "!", e, component);
|
||||
return false; //If failed to disable, won't unregister either
|
||||
}
|
||||
}
|
||||
component.unregister(plugin);
|
||||
components.remove(component.getClass());
|
||||
}
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
TBMCCoreAPI.SendException("Failed to " + (register ? "" : "un") + "register component " + component.getClassName() + "!", e, plugin);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Enables or disables the given component. If the component fails to enable, it will be disabled.
|
||||
*
|
||||
* @param component The component to register
|
||||
* @param enabled Whether it's enabled or not
|
||||
*/
|
||||
public static void setComponentEnabled(Component<?> component, boolean enabled) throws UnregisteredComponentException {
|
||||
if (!components.containsKey(component.getClass()))
|
||||
throw new UnregisteredComponentException(component);
|
||||
if (component.enabled == enabled) return; //Don't do anything
|
||||
if (component.enabled = enabled) {
|
||||
try {
|
||||
updateConfig(component.getPlugin(), component);
|
||||
component.enable();
|
||||
if (ButtonPlugin.configGenAllowed(component)) {
|
||||
IHaveConfig.pregenConfig(component, null);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
try { //Automatically disable components that fail to enable properly
|
||||
setComponentEnabled(component, false);
|
||||
throw e;
|
||||
} catch (Exception ex) {
|
||||
Throwable t = ex;
|
||||
for (var th = t; th != null; th = th.getCause())
|
||||
t = th; //Set if not null
|
||||
if (t != e)
|
||||
t.initCause(e);
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
component.disable();
|
||||
ButtonPlugin.getCommand2MC().unregisterCommands(component);
|
||||
}
|
||||
}
|
||||
|
||||
public static void updateConfig(JavaPlugin plugin, Component<?> component) {
|
||||
if (plugin.getConfig() != null) { //Production
|
||||
var compconf = plugin.getConfig().getConfigurationSection("components");
|
||||
if (compconf == null) compconf = plugin.getConfig().createSection("components");
|
||||
var configSect = compconf.getConfigurationSection(component.getClassName());
|
||||
if (configSect == null)
|
||||
configSect = compconf.createSection(component.getClassName());
|
||||
component.config.reset(configSect);
|
||||
} //Testing: it's already set
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the currently registered components<br>
|
||||
*
|
||||
* @return The currently registered components
|
||||
*/
|
||||
@SuppressWarnings("rawtypes")
|
||||
public static Map<Class<? extends Component>, Component<? extends JavaPlugin>> getComponents() {
|
||||
return Collections.unmodifiableMap(components);
|
||||
}
|
||||
|
||||
public void log(String message) {
|
||||
plugin.getLogger().info("[" + getClassName() + "] " + message);
|
||||
}
|
||||
|
||||
public void logWarn(String message) {
|
||||
plugin.getLogger().warning("[" + getClassName() + "] " + message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers the module, when called by the JavaPlugin class.
|
||||
* This gets fired when the plugin is enabled. Use {@link #enable()} to register commands and such.
|
||||
*
|
||||
* @param plugin Plugin object
|
||||
*/
|
||||
@SuppressWarnings({"unused"})
|
||||
protected void register(JavaPlugin plugin) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Unregisters the module, when called by the JavaPlugin class.
|
||||
* This gets fired when the plugin is disabled.
|
||||
* Do any cleanups needed within this method.
|
||||
*
|
||||
* @param plugin Plugin object
|
||||
*/
|
||||
@SuppressWarnings({"unused"})
|
||||
protected void unregister(JavaPlugin plugin) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Enables the module, when called by the JavaPlugin class. Call
|
||||
* registerCommand() and registerListener() within this method.<br>
|
||||
* To access the plugin, use {@link #getPlugin()}.
|
||||
*/
|
||||
protected abstract void enable();
|
||||
|
||||
/**
|
||||
* Disables the module, when called by the JavaPlugin class. Do
|
||||
* any cleanups needed within this method.
|
||||
* To access the plugin, use {@link #getPlugin()}.
|
||||
*/
|
||||
protected abstract void disable();
|
||||
|
||||
/**
|
||||
* Registers a command to the component. Make sure to use {@link buttondevteam.lib.chat.CommandClass} and {@link buttondevteam.lib.chat.Command2.Subcommand}.
|
||||
* You don't need to register the command in plugin.yml.
|
||||
*
|
||||
* @param command Custom coded command class
|
||||
*/
|
||||
protected final void registerCommand(ICommand2MC command) {
|
||||
if (plugin instanceof ButtonPlugin)
|
||||
command.registerToPlugin((ButtonPlugin) plugin);
|
||||
command.registerToComponent(this);
|
||||
ButtonPlugin.getCommand2MC().registerCommand(command);
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a Listener to this component
|
||||
*
|
||||
* @param listener The event listener to register
|
||||
* @return The provided listener
|
||||
*/
|
||||
protected final Listener registerListener(Listener listener) {
|
||||
TBMCCoreAPI.RegisterEventsForExceptions(listener, plugin);
|
||||
return listener;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a map of configs that are under the given key.
|
||||
*
|
||||
* @param key The key to use
|
||||
* @param defaultProvider A mapping between config paths and config generators
|
||||
* @return A map containing configs
|
||||
*/
|
||||
protected Map<String, IHaveConfig> getConfigMap(String key, Map<String, Consumer<IHaveConfig>> defaultProvider) {
|
||||
val c = getConfig().getConfig();
|
||||
var cs = c.getConfigurationSection(key);
|
||||
if (cs == null) cs = c.createSection(key);
|
||||
val res = cs.getValues(false).entrySet().stream().filter(e -> e.getValue() instanceof ConfigurationSection)
|
||||
.collect(Collectors.toMap(Map.Entry::getKey, kv -> {
|
||||
var conf = new IHaveConfig(getPlugin()::saveConfig);
|
||||
conf.reset((ConfigurationSection) kv.getValue());
|
||||
return conf;
|
||||
}));
|
||||
if (res.size() == 0) {
|
||||
for (val entry : defaultProvider.entrySet()) {
|
||||
val conf = new IHaveConfig(getPlugin()::saveConfig);
|
||||
conf.reset(cs.createSection(entry.getKey()));
|
||||
entry.getValue().accept(conf);
|
||||
res.put(entry.getKey(), conf);
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
private String getClassName() {
|
||||
return getClass().getSimpleName();
|
||||
}
|
||||
}
|
|
@ -1,289 +0,0 @@
|
|||
package buttondevteam.lib.architecture
|
||||
|
||||
import buttondevteam.buttonproc.HasConfig
|
||||
import buttondevteam.core.ComponentManager
|
||||
import buttondevteam.lib.TBMCCoreAPI
|
||||
import buttondevteam.lib.architecture.exceptions.UnregisteredComponentException
|
||||
import buttondevteam.lib.chat.ICommand2MC
|
||||
import org.bukkit.configuration.ConfigurationSection
|
||||
import org.bukkit.event.Listener
|
||||
import org.bukkit.plugin.java.JavaPlugin
|
||||
import java.util.*
|
||||
import java.util.function.Consumer
|
||||
import java.util.stream.Collectors
|
||||
|
||||
/**
|
||||
* Configuration is based on class name
|
||||
*/
|
||||
@HasConfig(global = false) //Used for obtaining javadoc
|
||||
abstract class Component<TP : JavaPlugin> {
|
||||
var isEnabled = false
|
||||
|
||||
val config: IHaveConfig = IHaveConfig({ logWarn("Attempted to save config with null section!") }, null)
|
||||
lateinit var plugin: TP
|
||||
private set
|
||||
|
||||
private val data //TODO
|
||||
: IHaveConfig? = null
|
||||
|
||||
var shouldBeEnabled by config.getData("enabled", javaClass.getAnnotation(ComponentMetadata::class.java)?.enabledByDefault ?: true)
|
||||
|
||||
fun log(message: String) {
|
||||
plugin.logger.info("[$className] $message")
|
||||
}
|
||||
|
||||
fun logWarn(message: String) {
|
||||
plugin.logger.warning("[$className] $message")
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers the module, when called by the JavaPlugin class.
|
||||
* This gets fired when the plugin is enabled. Use [.enable] to register commands and such.
|
||||
*
|
||||
* @param plugin Plugin object
|
||||
*/
|
||||
protected open fun register(plugin: JavaPlugin) {}
|
||||
|
||||
/**
|
||||
* Unregisters the module, when called by the JavaPlugin class.
|
||||
* This gets fired when the plugin is disabled.
|
||||
* Do any cleanups needed within this method.
|
||||
*
|
||||
* @param plugin Plugin object
|
||||
*/
|
||||
protected open fun unregister(plugin: JavaPlugin) {}
|
||||
|
||||
/**
|
||||
* Enables the module, when called by the JavaPlugin class. Call
|
||||
* registerCommand() and registerListener() within this method.
|
||||
*
|
||||
* To access the plugin, use [.getPlugin].
|
||||
*/
|
||||
protected abstract fun enable()
|
||||
|
||||
/**
|
||||
* Disables the module, when called by the JavaPlugin class. Do
|
||||
* any cleanups needed within this method.
|
||||
* To access the plugin, use [.getPlugin].
|
||||
*/
|
||||
protected abstract fun disable()
|
||||
|
||||
/**
|
||||
* Registers a command to the component. Make sure to use [buttondevteam.lib.chat.CommandClass] and [buttondevteam.lib.chat.Command2.Subcommand].
|
||||
* You don't need to register the command in plugin.yml.
|
||||
*
|
||||
* @param command Custom coded command class
|
||||
*/
|
||||
fun registerCommand(command: ICommand2MC) {
|
||||
if (plugin is ButtonPlugin) command.registerToPlugin(plugin as ButtonPlugin) // TODO: Require ButtonPlugin
|
||||
command.registerToComponent(this)
|
||||
ButtonPlugin.command2MC.registerCommand(command)
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a Listener to this component
|
||||
*
|
||||
* @param listener The event listener to register
|
||||
* @return The provided listener
|
||||
*/
|
||||
protected fun registerListener(listener: Listener): Listener {
|
||||
TBMCCoreAPI.RegisterEventsForExceptions(listener, plugin)
|
||||
return listener
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a map of configs that are under the given key.
|
||||
*
|
||||
* @param key The key to use
|
||||
* @param defaultProvider A mapping between config paths and config generators
|
||||
* @return A map containing configs
|
||||
*/
|
||||
fun getConfigMap(key: String, defaultProvider: Map<String, Consumer<IHaveConfig>>): Map<String, IHaveConfig> {
|
||||
val c: ConfigurationSection? = config.config
|
||||
if (c == null) {
|
||||
logWarn("Config section is null when getting config map")
|
||||
return defaultProvider.mapValues { kv -> IHaveConfig(plugin::saveConfig, null).also { kv.value.accept(it) } }
|
||||
}
|
||||
val cs = c.getConfigurationSection(key) ?: c.createSection(key)
|
||||
val res = cs.getValues(false).entries.stream()
|
||||
.filter { (_, value) -> value is ConfigurationSection }
|
||||
.collect(Collectors.toMap(
|
||||
{ it.key },
|
||||
{ (_, value) -> IHaveConfig(plugin::saveConfig, value as ConfigurationSection) }
|
||||
))
|
||||
if (res.isEmpty()) {
|
||||
defaultProvider.mapValuesTo(res) { kv -> IHaveConfig(plugin::saveConfig, cs.createSection(kv.key)).also { kv.value.accept(it) } }
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
private val className: String get() = javaClass.simpleName
|
||||
|
||||
internal fun updateConfig() {
|
||||
this.config.reload(getConfigSection(), plugin::saveConfig)
|
||||
}
|
||||
|
||||
private fun getConfigSection(): ConfigurationSection {
|
||||
var compconf = plugin.config.getConfigurationSection("components")
|
||||
if (compconf == null) compconf = plugin.config.createSection("components")
|
||||
var configSect = compconf.getConfigurationSection(className)
|
||||
if (configSect == null) configSect = compconf.createSection(className)
|
||||
return configSect
|
||||
// TODO: Support tests (provide Bukkit configuration for tests)
|
||||
}
|
||||
|
||||
companion object {
|
||||
private val _components = HashMap<Class<out Component<*>>, Component<out JavaPlugin>>()
|
||||
|
||||
/**
|
||||
* Returns the currently registered components
|
||||
*
|
||||
* @return The currently registered components
|
||||
*/
|
||||
@JvmStatic
|
||||
val components: Map<Class<out Component<*>>, Component<out JavaPlugin>>
|
||||
get() {
|
||||
return Collections.unmodifiableMap(_components)
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a component checking it's dependencies and calling [.register].
|
||||
*
|
||||
* Make sure to register the dependencies first.
|
||||
*
|
||||
* The component will be enabled automatically, regardless of when it was registered.
|
||||
*
|
||||
* **If not using [ButtonPlugin], call [ComponentManager.unregComponents] on plugin disable.**
|
||||
*
|
||||
* @param component The component to register
|
||||
* @return Whether the component is registered successfully (it may have failed to enable)
|
||||
*/
|
||||
@JvmStatic
|
||||
fun <T : JavaPlugin> registerComponent(plugin: T, component: Component<T>): Boolean {
|
||||
return registerUnregisterComponent(plugin, component, true)
|
||||
}
|
||||
|
||||
/**
|
||||
* Unregisters a component by calling [.unregister].
|
||||
*
|
||||
* Make sure to unregister the dependencies last.
|
||||
*
|
||||
* **Components will be unregistered in opposite order of registering by default by [ButtonPlugin] or [ComponentManager.unregComponents].**
|
||||
*
|
||||
* @param component The component to unregister
|
||||
* @return Whether the component is unregistered successfully (it also got disabled)
|
||||
*/
|
||||
@JvmStatic
|
||||
fun <T : JavaPlugin> unregisterComponent(plugin: T, component: Component<T>): Boolean {
|
||||
return registerUnregisterComponent(plugin, component, false)
|
||||
}
|
||||
|
||||
private fun <T : JavaPlugin> registerUnregisterComponent(
|
||||
plugin: T,
|
||||
component: Component<T>,
|
||||
register: Boolean
|
||||
): Boolean {
|
||||
return try {
|
||||
val metaAnn = component.javaClass.getAnnotation(ComponentMetadata::class.java)
|
||||
if (metaAnn != null) {
|
||||
val dependencies = metaAnn.depends
|
||||
for (dep in dependencies) { //TODO: Support dependencies at enable/disable as well
|
||||
if (!components.containsKey(dep.java)) {
|
||||
plugin.logger.warning("Failed to ${if (register) "" else "un"}register component ${component.className} as a required dependency is missing/disabled: ${dep.simpleName}")
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
if (register) {
|
||||
if (components.containsKey(component.javaClass)) {
|
||||
TBMCCoreAPI.SendException(
|
||||
"Failed to register component " + component.className,
|
||||
IllegalArgumentException("The component is already registered!"),
|
||||
plugin
|
||||
)
|
||||
return false
|
||||
}
|
||||
component.register(plugin)
|
||||
component.plugin = plugin
|
||||
component.updateConfig()
|
||||
_components[component.javaClass] = component
|
||||
if (plugin is ButtonPlugin) plugin.componentStack.push(component)
|
||||
if (ComponentManager.areComponentsEnabled() && component.shouldBeEnabled) {
|
||||
return try { //Enable components registered after the previous ones getting enabled
|
||||
setComponentEnabled(component, true)
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
TBMCCoreAPI.SendException(
|
||||
"Failed to enable component " + component.className + "!",
|
||||
e,
|
||||
component
|
||||
)
|
||||
true
|
||||
} catch (e: NoClassDefFoundError) {
|
||||
TBMCCoreAPI.SendException("Failed to enable component " + component.className + "!", e, component)
|
||||
true
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (!components.containsKey(component.javaClass)) return true //Already unregistered
|
||||
if (component.isEnabled) {
|
||||
try {
|
||||
setComponentEnabled(component, false)
|
||||
} catch (e: Exception) {
|
||||
TBMCCoreAPI.SendException("Failed to disable component ${component.className}!", e, component)
|
||||
return false //If failed to disable, won't unregister either
|
||||
} catch (e: NoClassDefFoundError) {
|
||||
TBMCCoreAPI.SendException("Failed to disable component ${component.className}!", e, component)
|
||||
return false
|
||||
}
|
||||
}
|
||||
component.unregister(plugin)
|
||||
_components.remove(component.javaClass)
|
||||
}
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
TBMCCoreAPI.SendException("Failed to ${if (register) "" else "un"}register component ${component.className}!", e, plugin)
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Enables or disables the given component. If the component fails to enable, it will be disabled.
|
||||
*
|
||||
* @param component The component to register
|
||||
* @param enabled Whether it's enabled or not
|
||||
*/
|
||||
@JvmStatic
|
||||
@Throws(UnregisteredComponentException::class)
|
||||
fun setComponentEnabled(component: Component<*>, enabled: Boolean) {
|
||||
if (!components.containsKey(component.javaClass)) throw UnregisteredComponentException(component)
|
||||
if (component.isEnabled == enabled) return //Don't do anything
|
||||
if (enabled.also { component.isEnabled = it }) {
|
||||
try {
|
||||
component.updateConfig()
|
||||
component.enable()
|
||||
if (ButtonPlugin.configGenAllowed(component)) {
|
||||
IHaveConfig.pregenConfig(component, null)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
try { //Automatically disable components that fail to enable properly
|
||||
setComponentEnabled(component, false)
|
||||
throw e
|
||||
} catch (ex: Exception) {
|
||||
var t: Throwable = ex
|
||||
var th: Throwable? = t
|
||||
while (th != null) {
|
||||
t = th //Set if not null
|
||||
th = th.cause
|
||||
}
|
||||
if (t !== e) t.initCause(e)
|
||||
throw ex
|
||||
}
|
||||
}
|
||||
} else {
|
||||
component.disable()
|
||||
ButtonPlugin.command2MC.unregisterCommands(component)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,252 @@
|
|||
package buttondevteam.lib.architecture;
|
||||
|
||||
import buttondevteam.core.MainPlugin;
|
||||
import buttondevteam.lib.ChromaUtils;
|
||||
import lombok.*;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.configuration.Configuration;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import org.bukkit.scheduler.BukkitTask;
|
||||
|
||||
import java.lang.reflect.Array;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.function.Function;
|
||||
|
||||
/**
|
||||
* Use the getter/setter constructor if {@link T} isn't a primitive type or String.<br>
|
||||
* Use {@link Component#getConfig()} or {@link ButtonPlugin#getIConfig()} then {@link IHaveConfig#getData(String, Object)} to get an instance.
|
||||
*/
|
||||
public class ConfigData<T> {
|
||||
private static final HashMap<Configuration, SaveTask> saveTasks = new HashMap<>();
|
||||
/**
|
||||
* May be null for testing
|
||||
*/
|
||||
private IHaveConfig config;
|
||||
@Getter
|
||||
@Setter(AccessLevel.PACKAGE)
|
||||
private String path;
|
||||
protected final T def;
|
||||
private final Object primitiveDef;
|
||||
/**
|
||||
* The parameter is of a primitive type as returned by {@link YamlConfiguration#get(String)}
|
||||
*/
|
||||
private final Function<Object, T> getter;
|
||||
/**
|
||||
* The result should be a primitive type or string that can be retrieved correctly later
|
||||
*/
|
||||
private final Function<T, Object> setter;
|
||||
|
||||
/**
|
||||
* The config value should not change outside this instance
|
||||
*/
|
||||
private T value;
|
||||
|
||||
ConfigData(IHaveConfig config, String path, T def, Object primitiveDef, Function<Object, T> getter, Function<T, Object> setter) {
|
||||
if (def == null) {
|
||||
if (primitiveDef == null)
|
||||
throw new IllegalArgumentException("Either def or primitiveDef must be set.");
|
||||
if (getter == null)
|
||||
throw new IllegalArgumentException("A getter and setter must be present when using primitiveDef.");
|
||||
def = getter.apply(primitiveDef);
|
||||
} else if (primitiveDef == null)
|
||||
if (setter == null)
|
||||
primitiveDef = def;
|
||||
else
|
||||
primitiveDef = setter.apply(def);
|
||||
if ((getter == null) != (setter == null))
|
||||
throw new IllegalArgumentException("Both setters and getters must be present (or none if def is primitive).");
|
||||
this.config = config;
|
||||
this.path = path;
|
||||
this.def = def;
|
||||
this.primitiveDef = primitiveDef;
|
||||
this.getter = getter;
|
||||
this.setter = setter;
|
||||
get(); //Generate config automatically
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ConfigData{" + "path='" + path + '\'' + ", value=" + value + '}';
|
||||
}
|
||||
|
||||
void reset() {
|
||||
value = null;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public T get() {
|
||||
if (value != null) return value; //Speed things up
|
||||
var config = this.config.getConfig();
|
||||
Object val;
|
||||
if (config == null || !config.isSet(path)) { //Call set() if config == null
|
||||
val = primitiveDef;
|
||||
if ((def == null || this instanceof ReadOnlyConfigData) && config != null) //In Discord's case def may be null
|
||||
setInternal(primitiveDef); //If read-only then we still need to save the default value so it can be set
|
||||
else
|
||||
set(def); //Save default value - def is always set
|
||||
} else
|
||||
val = config.get(path); //config==null: testing
|
||||
if (val == null) //If it's set to null explicitly
|
||||
val = primitiveDef;
|
||||
BiFunction<Object, Object, Object> convert = (_val, _def) -> {
|
||||
if (_def instanceof Number) //If we expect a number
|
||||
if (_val instanceof Number)
|
||||
_val = ChromaUtils.convertNumber((Number) _val,
|
||||
(Class<? extends Number>) _def.getClass());
|
||||
else
|
||||
_val = _def; //If we didn't get a number, return default (which is a number)
|
||||
else if (_val instanceof List && _def != null && _def.getClass().isArray())
|
||||
_val = ((List<T>) _val).toArray((T[]) Array.newInstance(_def.getClass().getComponentType(), 0));
|
||||
return _val;
|
||||
};
|
||||
if (getter != null) {
|
||||
val = convert.apply(val, primitiveDef);
|
||||
T hmm = getter.apply(val);
|
||||
if (hmm == null) hmm = def; //Set if the getter returned null
|
||||
return hmm;
|
||||
}
|
||||
val = convert.apply(val, def);
|
||||
return value = (T) val; //Always cache, if not cached yet
|
||||
}
|
||||
|
||||
public void set(T value) {
|
||||
if (this instanceof ReadOnlyConfigData)
|
||||
return; //Safety for Discord channel/role data
|
||||
Object val;
|
||||
if (setter != null && value != null)
|
||||
val = setter.apply(value);
|
||||
else val = value;
|
||||
if (config.getConfig() != null)
|
||||
setInternal(val);
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
private void setInternal(Object val) {
|
||||
config.getConfig().set(path, val);
|
||||
signalChange(config);
|
||||
}
|
||||
|
||||
static void signalChange(IHaveConfig config) {
|
||||
var cc = config.getConfig();
|
||||
var sa = config.getSaveAction();
|
||||
if (!saveTasks.containsKey(cc.getRoot())) {
|
||||
synchronized (saveTasks) {
|
||||
saveTasks.put(cc.getRoot(), new SaveTask(Bukkit.getScheduler().runTaskLaterAsynchronously(MainPlugin.Instance, () -> {
|
||||
synchronized (saveTasks) {
|
||||
saveTasks.remove(cc.getRoot());
|
||||
sa.run();
|
||||
}
|
||||
}, 100), sa));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@AllArgsConstructor
|
||||
private static class SaveTask {
|
||||
BukkitTask task;
|
||||
Runnable saveAction;
|
||||
}
|
||||
|
||||
public static boolean saveNow(Configuration config) {
|
||||
synchronized (saveTasks) {
|
||||
SaveTask st = saveTasks.get(config);
|
||||
if (st != null) {
|
||||
st.task.cancel();
|
||||
saveTasks.remove(config);
|
||||
st.saveAction.run();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static <T> ConfigData.ConfigDataBuilder<T> builder(IHaveConfig config, String path) {
|
||||
return new ConfigDataBuilder<T>(config, path);
|
||||
}
|
||||
|
||||
@RequiredArgsConstructor(access = AccessLevel.PACKAGE)
|
||||
public static class ConfigDataBuilder<T> {
|
||||
private final IHaveConfig config;
|
||||
private final String path;
|
||||
private T def;
|
||||
private Object primitiveDef;
|
||||
private Function<Object, T> getter;
|
||||
private Function<T, Object> setter;
|
||||
|
||||
/**
|
||||
* The default value to use, as used in code. If not a primitive type, use the {@link #getter(Function)} and {@link #setter(Function)} methods.
|
||||
* <br/>
|
||||
* To set the value as it is stored, use {@link #primitiveDef(Object)}.
|
||||
*
|
||||
* @param def The default value
|
||||
* @return This builder
|
||||
*/
|
||||
public ConfigDataBuilder<T> def(T def) {
|
||||
this.def = def;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* The default value to use, as stored in yaml. Must be a primitive type. Make sure to use the {@link #getter(Function)} and {@link #setter(Function)} methods.
|
||||
* <br/>
|
||||
* To set the value as used in the code, use {@link #def(Object)}.
|
||||
*
|
||||
* @param primitiveDef The default value
|
||||
* @return This builder
|
||||
*/
|
||||
public ConfigDataBuilder<T> primitiveDef(Object primitiveDef) {
|
||||
this.primitiveDef = primitiveDef;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* A function to use to obtain the runtime object from the yaml representation (usually string).
|
||||
* The {@link #setter(Function)} must also be set.
|
||||
*
|
||||
* @param getter A function that receives the primitive type and returns the runtime type
|
||||
* @return This builder
|
||||
*/
|
||||
public ConfigDataBuilder<T> getter(Function<Object, T> getter) {
|
||||
this.getter = getter;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* A function to use to obtain the yaml representation (usually string) from the runtime object.
|
||||
* The {@link #getter(Function)} must also be set.
|
||||
*
|
||||
* @param setter A function that receives the runtime type and returns the primitive type
|
||||
* @return This builder
|
||||
*/
|
||||
public ConfigDataBuilder<T> setter(Function<T, Object> setter) {
|
||||
this.setter = setter;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a modifiable config representation. Use if you want to change the value <i>in code</i>.
|
||||
*
|
||||
* @return A ConfigData instance.
|
||||
*/
|
||||
public ConfigData<T> build() {
|
||||
ConfigData<T> config = new ConfigData<>(this.config, path, def, primitiveDef, getter, setter);
|
||||
this.config.onConfigBuild(config);
|
||||
return config;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a read-only config representation. Use if you only want the value to be changed <i>in the config</i>.
|
||||
*
|
||||
* @return A ReadOnlyConfigData instance.
|
||||
*/
|
||||
public ReadOnlyConfigData<T> buildReadOnly() {
|
||||
ReadOnlyConfigData<T> config = new ReadOnlyConfigData<>(this.config, path, def, primitiveDef, getter, setter);
|
||||
this.config.onConfigBuild(config);
|
||||
return config;
|
||||
}
|
||||
|
||||
public String toString() {return "ConfigData.ConfigDataBuilder(config=" + this.config + ", path=" + this.path + ", def=" + this.def + ", primitiveDef=" + this.primitiveDef + ", getter=" + this.getter + ", setter=" + this.setter + ")";}
|
||||
}
|
||||
}
|
|
@ -1,153 +0,0 @@
|
|||
package buttondevteam.lib.architecture
|
||||
|
||||
import buttondevteam.core.MainPlugin
|
||||
import buttondevteam.lib.ChromaUtils
|
||||
import buttondevteam.lib.architecture.config.IConfigData
|
||||
import org.bukkit.Bukkit
|
||||
import org.bukkit.configuration.Configuration
|
||||
import org.bukkit.scheduler.BukkitTask
|
||||
import java.lang.reflect.Array.newInstance
|
||||
import java.util.function.Function
|
||||
|
||||
/**
|
||||
* Use the getter/setter constructor if [T] isn't a primitive type or String.
|
||||
*
|
||||
* Use [Component.config] or [ButtonPlugin.iConfig] then [IHaveConfig.getData] to get an instance.
|
||||
*
|
||||
* **Note:** The instance can become outdated if the config is reloaded.
|
||||
* @param config The config object to use for the whole file
|
||||
* @param path The path to the config value
|
||||
* @param primitiveDef The default value, as stored in the config. Non-nullable as it needs to be saved to the config
|
||||
* @param getter Function to convert primtive types to [T]. The parameter is of a primitive type as returned by [Configuration.get]
|
||||
* @param setter Function to convert [T] to a primitive type. The result should be a primitive type or string that can be retrieved correctly later
|
||||
* @param readOnly If true, changing the value will have no effect
|
||||
* @param T The type of the config value. May be nullable if the getter cannot always return a value
|
||||
*/
|
||||
class ConfigData<T : Any?> internal constructor(
|
||||
val config: IHaveConfig,
|
||||
override val path: String,
|
||||
private val primitiveDef: Any,
|
||||
private val getter: Function<Any, T>,
|
||||
private val setter: Function<T, Any>,
|
||||
private val readOnly: Boolean
|
||||
) : IConfigData<T> {
|
||||
|
||||
/**
|
||||
* The config value should not change outside this instance
|
||||
*/
|
||||
private var value: T? = null
|
||||
|
||||
init {
|
||||
get(true) //Generate config automatically
|
||||
}
|
||||
|
||||
override fun toString(): String {
|
||||
return "ConfigData{path='$path', value=$value}"
|
||||
}
|
||||
|
||||
override fun get(): T {
|
||||
return get(false)
|
||||
}
|
||||
|
||||
private fun get(initialGet: Boolean): T {
|
||||
val cachedValue = value
|
||||
if (cachedValue != null) return cachedValue //Speed things up
|
||||
val config = config.config
|
||||
val freshValue = config?.get(path) ?: primitiveDef.also { setInternal(it, initialGet) }
|
||||
return getter.apply(convertPrimitiveType(freshValue)).also { value = it }
|
||||
}
|
||||
|
||||
override fun reload() {
|
||||
value = null
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Converts a value to [T] from the representation returned by [Configuration.get].
|
||||
*/
|
||||
@Suppress("UNCHECKED_CAST", "DEPRECATION")
|
||||
private fun convertPrimitiveType(value: Any): Any {
|
||||
return if (primitiveDef is Number) //If we expect a number
|
||||
if (value is Number) ChromaUtils.convertNumber(value, primitiveDef.javaClass)
|
||||
else primitiveDef //If we didn't get a number, return default (which is a number)
|
||||
else if (value is List<*> && primitiveDef.javaClass.isArray) // If we got a list and we expected an array
|
||||
value.toArray { newInstance(primitiveDef.javaClass.componentType, it) as Array<T> }
|
||||
else value
|
||||
}
|
||||
|
||||
override fun set(value: T) {
|
||||
if (readOnly) return //Safety for Discord channel/role data
|
||||
val `val` = setter.apply(value)
|
||||
setInternal(`val`)
|
||||
this.value = value
|
||||
}
|
||||
|
||||
private fun setInternal(`val`: Any?, initialSet: Boolean = false) { // TODO: Remove initialSet when #109 is done
|
||||
val config = config.config
|
||||
if (config != null) {
|
||||
config.set(path, `val`)
|
||||
signalChange(this.config)
|
||||
} else if (!initialSet) {
|
||||
ChromaUtils.logWarn("Attempted to get/set config value with no config! Path: $path, value: $`val`")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param task The running task, if it was scheduled
|
||||
*/
|
||||
private class SaveTask(val task: BukkitTask?, val saveAction: Runnable)
|
||||
|
||||
companion object {
|
||||
private val saveTasks = HashMap<Configuration, SaveTask>()
|
||||
|
||||
/**
|
||||
* Signals that the config has changed and should be saved
|
||||
*/
|
||||
fun signalChange(config: IHaveConfig) {
|
||||
val cc = config.config
|
||||
val sa = config.saveAction
|
||||
val root = cc?.root
|
||||
if (root == null) {
|
||||
ChromaUtils.logWarn("Attempted to save config with no root! Name: ${cc?.name ?: "NONEXISTENT CONFIG"}")
|
||||
return
|
||||
}
|
||||
if (!MainPlugin.isInitialized) {
|
||||
// If the plugin isn't initialized, we can't schedule a task - do it when the plugin is enabled
|
||||
synchronized(saveTasks) {
|
||||
saveTasks.put(root, SaveTask(null, sa))
|
||||
}
|
||||
} else if (!saveTasks.containsKey(cc.root)) {
|
||||
synchronized(saveTasks) {
|
||||
saveTasks.put(
|
||||
root,
|
||||
SaveTask(Bukkit.getScheduler().runTaskLaterAsynchronously(MainPlugin.instance, Runnable {
|
||||
synchronized(saveTasks) {
|
||||
saveTasks.remove(root)
|
||||
sa.run()
|
||||
}
|
||||
}, 100), sa)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves the config immediately, if it's scheduled to be saved. Used to save configs when the plugin is disabled or reloaded.
|
||||
*
|
||||
* Also performs cleanup of the save task, so it must be called when the ConfigData is invalidated (which is the above two cases).
|
||||
*/
|
||||
@JvmStatic
|
||||
fun saveNow(config: Configuration): Boolean {
|
||||
synchronized(saveTasks) {
|
||||
val st = saveTasks[config]
|
||||
if (st != null) {
|
||||
st.task?.cancel()
|
||||
saveTasks.remove(config)
|
||||
st.saveAction.run()
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,256 @@
|
|||
package buttondevteam.lib.architecture;
|
||||
|
||||
import buttondevteam.core.MainPlugin;
|
||||
import buttondevteam.lib.TBMCCoreAPI;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import lombok.val;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.configuration.ConfigurationSection;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.util.*;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* A config system
|
||||
*/
|
||||
public final class IHaveConfig {
|
||||
private final HashMap<String, ConfigData<?>> datamap = new HashMap<>();
|
||||
/**
|
||||
* Returns the Bukkit ConfigurationSection. Use {@link #signalChange()} after changing it.
|
||||
*/
|
||||
@Getter
|
||||
private ConfigurationSection config;
|
||||
@Getter
|
||||
@Setter
|
||||
private Runnable saveAction;
|
||||
|
||||
/**
|
||||
* May be used in testing.
|
||||
*
|
||||
* @param saveAction What to do to save the config to disk. Don't use get methods until it's non-null.
|
||||
*/
|
||||
public IHaveConfig(Runnable saveAction) {
|
||||
this.saveAction = saveAction;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a config object for the given path. The def or primitiveDef must be set. If a getter is present, a setter must be present as well.
|
||||
*
|
||||
* @param path The dot-separated path relative to this config instance
|
||||
* @param <T> The runtime type of the config value
|
||||
* @return A ConfigData builder to set how to obtain the value
|
||||
*/
|
||||
public <T> ConfigData.ConfigDataBuilder<T> getConfig(String path) {
|
||||
return ConfigData.builder(this, path);
|
||||
}
|
||||
|
||||
void onConfigBuild(ConfigData<?> config) {
|
||||
datamap.put(config.getPath(), config);
|
||||
}
|
||||
|
||||
/**
|
||||
* This method overload should only be used with primitives or String.
|
||||
*
|
||||
* @param path The path in config to use
|
||||
* @param def The value to use by default
|
||||
* @param <T> The type of this variable (only use primitives or String)
|
||||
* @return The data object that can be used to get or set the value
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T> ConfigData<T> getData(String path, T def) {
|
||||
ConfigData<?> data = datamap.get(path);
|
||||
if (data == null) datamap.put(path, data = new ConfigData<>(this, path, def, def, null, null));
|
||||
return (ConfigData<T>) data;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method overload may be used with any class.
|
||||
*
|
||||
* @param path The path in config to use
|
||||
* @param def The value to use by default
|
||||
* @param getter A function that converts a primitive representation to the correct value
|
||||
* @param setter A function that converts a value to a primitive representation
|
||||
* @param <T> The type of this variable (can be any class)
|
||||
* @return The data object that can be used to get or set the value
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T> ConfigData<T> getData(String path, T def, Function<Object, T> getter, Function<T, Object> setter) {
|
||||
ConfigData<?> data = datamap.get(path);
|
||||
if (data == null)
|
||||
datamap.put(path, data = new ConfigData<>(this, path, def, setter.apply(def), getter, setter));
|
||||
return (ConfigData<T>) data;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method overload may be used with any class. The given default value will be run through the getter.
|
||||
*
|
||||
* @param path The path in config to use
|
||||
* @param primitiveDef The <b>primitive</b> value to use by default
|
||||
* @param getter A function that converts a primitive representation to the correct value
|
||||
* @param setter A function that converts a value to a primitive representation
|
||||
* @param <T> The type of this variable (can be any class)
|
||||
* @return The data object that can be used to get or set the value
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T> ConfigData<T> getDataPrimDef(String path, Object primitiveDef, Function<Object, T> getter, Function<T, Object> setter) {
|
||||
ConfigData<?> data = datamap.get(path);
|
||||
if (data == null)
|
||||
datamap.put(path, data = new ConfigData<>(this, path, getter.apply(primitiveDef), primitiveDef, getter, setter));
|
||||
return (ConfigData<T>) data;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method overload may be used with any class. The given default value will be run through the getter.
|
||||
*
|
||||
* @param path The path in config to use
|
||||
* @param primitiveDef The <b>primitive</b> value to use by default
|
||||
* @param getter A function that converts a primitive representation to the correct value
|
||||
* @param setter A function that converts a value to a primitive representation
|
||||
* @param <T> The type of this variable (can be any class)
|
||||
* @return The data object that can be used to get or set the value
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T> ReadOnlyConfigData<T> getReadOnlyDataPrimDef(String path, Object primitiveDef, Function<Object, T> getter, Function<T, Object> setter) {
|
||||
ConfigData<?> data = datamap.get(path);
|
||||
if (data == null)
|
||||
datamap.put(path, data = new ReadOnlyConfigData<>(this, path, getter.apply(primitiveDef), primitiveDef, getter, setter));
|
||||
return (ReadOnlyConfigData<T>) data;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method overload should only be used with primitves or String.
|
||||
*
|
||||
* @param path The path in config to use
|
||||
* @param def The value to use by default
|
||||
* @param <T> The type of this variable (only use primitives or String)
|
||||
* @return The data object that can be used to get or set the value
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T> ConfigData<T> getData(String path, Supplier<T> def) {
|
||||
ConfigData<?> data = datamap.get(path);
|
||||
if (data == null) {
|
||||
val defval = def.get();
|
||||
datamap.put(path, data = new ConfigData<>(this, path, defval, defval, null, null));
|
||||
}
|
||||
return (ConfigData<T>) data;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method overload may be used with any class.
|
||||
*
|
||||
* @param path The path in config to use
|
||||
* @param def The value to use by default
|
||||
* @param getter A function that converts a primitive representation to the correct value
|
||||
* @param setter A function that converts a value to a primitive representation
|
||||
* @param <T> The type of this variable (can be any class)
|
||||
* @return The data object that can be used to get or set the value
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T> ConfigData<T> getData(String path, Supplier<T> def, Function<Object, T> getter, Function<T, Object> setter) {
|
||||
ConfigData<?> data = datamap.get(path);
|
||||
if (data == null) {
|
||||
val defval = def.get();
|
||||
datamap.put(path, data = new ConfigData<>(this, path, defval, setter.apply(defval), getter, setter));
|
||||
}
|
||||
return (ConfigData<T>) data;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method overload should only be used with primitves or String.
|
||||
*
|
||||
* @param path The path in config to use
|
||||
* @param <T> The type of this variable (only use primitives or String)
|
||||
* @return The data object that can be used to get or set the value
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T> ListConfigData<T> getListData(String path) {
|
||||
ConfigData<?> data = datamap.get(path);
|
||||
if (data == null)
|
||||
datamap.put(path, data = new ListConfigData<>(this, path, new ListConfigData.List<T>()));
|
||||
return (ListConfigData<T>) data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Schedules a save operation. Use after changing the ConfigurationSection directly.
|
||||
*/
|
||||
public void signalChange() {
|
||||
ConfigData.signalChange(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears all caches and loads everything from yaml.
|
||||
*/
|
||||
public void reset(ConfigurationSection config) {
|
||||
this.config = config;
|
||||
datamap.forEach((path, data) -> data.reset());
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates the config YAML.
|
||||
*
|
||||
* @param obj The object which has config methods
|
||||
* @param configMap The result from {@link Component#getConfigMap(String, Map)}. May be null.
|
||||
*/
|
||||
public static void pregenConfig(Object obj, @Nullable Map<String, IHaveConfig> configMap) {
|
||||
val ms = obj.getClass().getDeclaredMethods();
|
||||
for (val m : ms) {
|
||||
if (!m.getReturnType().getName().equals(ConfigData.class.getName())) continue;
|
||||
final String mName;
|
||||
{
|
||||
var name = m.getName();
|
||||
var ind = name.lastIndexOf('$');
|
||||
if (ind == -1) mName = name;
|
||||
else mName = name.substring(ind + 1);
|
||||
}
|
||||
try {
|
||||
m.setAccessible(true);
|
||||
List<ConfigData<?>> configList;
|
||||
if (m.getParameterCount() == 0) {
|
||||
configList = Collections.singletonList((ConfigData<?>) m.invoke(obj));
|
||||
} else if (m.getParameterCount() == 1 && m.getParameterTypes()[0] == IHaveConfig.class) {
|
||||
if (configMap == null) continue; //Hope it will get called with the param later
|
||||
configList = configMap.entrySet().stream().map(kv ->
|
||||
{
|
||||
try {
|
||||
return (ConfigData<?>) m.invoke(obj, kv.getValue());
|
||||
} catch (IllegalAccessException | InvocationTargetException e) {
|
||||
String msg = "Failed to pregenerate " + mName + " for " + obj + " using config " + kv.getKey() + "!";
|
||||
if (obj instanceof Component<?>)
|
||||
TBMCCoreAPI.SendException(msg, e, (Component<?>) obj);
|
||||
else if (obj instanceof JavaPlugin)
|
||||
TBMCCoreAPI.SendException(msg, e, (JavaPlugin) obj);
|
||||
else
|
||||
TBMCCoreAPI.SendException(msg, e, false, Bukkit.getLogger()::warning);
|
||||
return null;
|
||||
}
|
||||
}).filter(Objects::nonNull).collect(Collectors.toList());
|
||||
} else {
|
||||
if (TBMCCoreAPI.IsTestServer())
|
||||
MainPlugin.Instance.getLogger().warning("Method " + mName + " returns a config but its parameters are unknown: " + Arrays.toString(m.getParameterTypes()));
|
||||
continue;
|
||||
}
|
||||
for (val c : configList) {
|
||||
if (c.getPath().length() == 0)
|
||||
c.setPath(mName);
|
||||
else if (!c.getPath().equals(mName))
|
||||
MainPlugin.Instance.getLogger().warning("Config name does not match: " + c.getPath() + " instead of " + mName);
|
||||
c.get(); //Saves the default value if needed - also checks validity
|
||||
}
|
||||
} catch (Exception e) {
|
||||
String msg = "Failed to pregenerate " + mName + " for " + obj + "!";
|
||||
if (obj instanceof Component<?>)
|
||||
TBMCCoreAPI.SendException(msg, e, (Component<?>) obj);
|
||||
else if (obj instanceof JavaPlugin)
|
||||
TBMCCoreAPI.SendException(msg, e, (JavaPlugin) obj);
|
||||
else
|
||||
TBMCCoreAPI.SendException(msg, e, false, Bukkit.getLogger()::warning);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,138 +0,0 @@
|
|||
package buttondevteam.lib.architecture
|
||||
|
||||
import buttondevteam.lib.architecture.config.ConfigDataDelegate
|
||||
import buttondevteam.lib.architecture.config.IConfigData
|
||||
import buttondevteam.lib.architecture.config.ListConfigDataDelegate
|
||||
import buttondevteam.lib.architecture.config.delegate
|
||||
import org.bukkit.configuration.ConfigurationSection
|
||||
import java.util.function.Function
|
||||
|
||||
/**
|
||||
* A config system
|
||||
* May be used in testing.
|
||||
*/
|
||||
class IHaveConfig(
|
||||
/**
|
||||
* The way the underlying configuration gets saved to disk
|
||||
*/
|
||||
saveAction: Runnable,
|
||||
config: ConfigurationSection?
|
||||
) {
|
||||
/**
|
||||
* The way the underlying configuration gets saved to disk
|
||||
*/
|
||||
var saveAction = saveAction
|
||||
private set
|
||||
|
||||
/**
|
||||
* Returns the Bukkit ConfigurationSection. Use [.signalChange] after changing it.
|
||||
*/
|
||||
var config = config
|
||||
private set
|
||||
private val datamap = HashMap<String, IConfigData<*>>()
|
||||
|
||||
/**
|
||||
* You may use this method with any data type, but always provide getters and setters that convert to primitive types
|
||||
* if you're not using primitive types directly.
|
||||
* These primitive types are strings, numbers, characters, booleans and lists of these things.
|
||||
*
|
||||
* @param path The path in config to use
|
||||
* @param def The value to use by default
|
||||
* @param getter A function that converts a primitive representation to the correct value
|
||||
* @param setter A function that converts a value to a primitive representation
|
||||
* @param readOnly If true, changing the value will have no effect
|
||||
* @param <T> The type of this variable (can be any class)
|
||||
* @return The data object that can be used to get or set the value
|
||||
</T> */
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
@JvmOverloads
|
||||
fun <T> getData(
|
||||
path: String,
|
||||
def: T,
|
||||
getter: Function<Any, T>? = null,
|
||||
setter: Function<T, Any>? = null,
|
||||
readOnly: Boolean = false
|
||||
): ConfigDataDelegate<T> {
|
||||
val safeSetter = setter ?: Function { it ?: throw RuntimeException("No setter specified for nullable config data $path!") }
|
||||
return getData(path, getter ?: Function { it as T }, safeSetter, safeSetter.apply(def), readOnly)
|
||||
}
|
||||
|
||||
/**
|
||||
* You may use this method with any data type and provide a primitive default value.
|
||||
* These primitive types are strings, numbers, characters, booleans and lists of these things.
|
||||
*
|
||||
* @param path The path in config to use
|
||||
* @param primitiveDef The **primitive** value to use by default
|
||||
* @param getter A function that converts a primitive representation to the correct value
|
||||
* @param setter A function that converts a value to a primitive representation
|
||||
* @param <T> The type of this variable (can be any class)
|
||||
* @return The data object that can be used to get or set the value
|
||||
</T> */
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
@JvmOverloads
|
||||
fun <T> getData(
|
||||
path: String,
|
||||
getter: Function<Any, T>,
|
||||
setter: Function<T, Any>,
|
||||
primitiveDef: Any,
|
||||
readOnly: Boolean = false
|
||||
): ConfigDataDelegate<T> {
|
||||
val data =
|
||||
datamap[path] ?: ConfigData(this, path, primitiveDef, getter, setter, readOnly).also { datamap[path] = it }
|
||||
return (data as ConfigData<T>).delegate()
|
||||
}
|
||||
|
||||
/**
|
||||
* This method overload should only be used with primitves or String.
|
||||
*
|
||||
* @param path The path in config to use
|
||||
* @param <T> The type of this variable (only use primitives or String)
|
||||
* @return The data object that can be used to get or set the value
|
||||
</T> */
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
@JvmOverloads
|
||||
fun <T> getListData(
|
||||
path: String,
|
||||
def: List<T>,
|
||||
elementGetter: Function<Any?, T>? = null,
|
||||
elementSetter: Function<T, Any?>? = null,
|
||||
readOnly: Boolean = false
|
||||
): ListConfigDataDelegate<T> {
|
||||
var data = datamap[path]
|
||||
if (data == null) datamap[path] = ListConfigData(
|
||||
this,
|
||||
path,
|
||||
ArrayList(def),
|
||||
elementGetter ?: Function { it as T },
|
||||
elementSetter ?: Function { it },
|
||||
readOnly
|
||||
).also { data = it }
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
return (data as ListConfigData<T>).delegate()
|
||||
}
|
||||
|
||||
/**
|
||||
* Schedules a save operation. Use after changing the ConfigurationSection directly.
|
||||
*/
|
||||
fun signalChange() {
|
||||
ConfigData.signalChange(this)
|
||||
}
|
||||
|
||||
fun reload(section: ConfigurationSection, saveAction: Runnable = this.saveAction) {
|
||||
config = section
|
||||
this.saveAction = saveAction
|
||||
datamap.forEach { it.value.reload() }
|
||||
}
|
||||
|
||||
companion object {
|
||||
/**
|
||||
* Generates the config YAML.
|
||||
*
|
||||
* @param obj The object which has config methods
|
||||
* @param configMap The result from [Component.getConfigMap]. May be null.
|
||||
*/
|
||||
fun pregenConfig(obj: Any, configMap: Map<String, IHaveConfig?>?) {
|
||||
// TODO: The configs are generated by ConfigData on creation
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,124 @@
|
|||
package buttondevteam.lib.architecture;
|
||||
|
||||
import lombok.val;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Comparator;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.function.UnaryOperator;
|
||||
|
||||
public class ListConfigData<T> extends ConfigData<ListConfigData.List<T>> {
|
||||
@SuppressWarnings("unchecked")
|
||||
ListConfigData(IHaveConfig config, String path, List<T> def) {
|
||||
super(config, path, def, new ArrayList<>(def), list -> {
|
||||
var l = new List<>((ArrayList<T>) list);
|
||||
l.listConfig = def.listConfig;
|
||||
return l;
|
||||
}, ArrayList::new);
|
||||
def.listConfig = this; //Can't make the List class non-static or pass this in the super() constructor
|
||||
}
|
||||
|
||||
public static class List<T> extends ArrayList<T> {
|
||||
private ListConfigData<T> listConfig;
|
||||
|
||||
public List(@NotNull Collection<? extends T> c) {
|
||||
super(c);
|
||||
}
|
||||
|
||||
public List() {
|
||||
}
|
||||
|
||||
private void update() {
|
||||
listConfig.set(this); //Update the config model and start save task if needed
|
||||
}
|
||||
|
||||
@Override
|
||||
public T set(int index, T element) {
|
||||
T ret = super.set(index, element);
|
||||
update();
|
||||
return ret;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean add(T t) {
|
||||
val ret = super.add(t);
|
||||
update();
|
||||
return ret;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void add(int index, T element) {
|
||||
super.add(index, element);
|
||||
update();
|
||||
}
|
||||
|
||||
@Override
|
||||
public T remove(int index) {
|
||||
T ret = super.remove(index);
|
||||
update();
|
||||
return ret;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean remove(Object o) {
|
||||
val ret = super.remove(o);
|
||||
update();
|
||||
return ret;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean addAll(Collection<? extends T> c) {
|
||||
val ret = super.addAll(c);
|
||||
update();
|
||||
return ret;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean addAll(int index, Collection<? extends T> c) {
|
||||
val ret = super.addAll(index, c);
|
||||
update();
|
||||
return ret;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void removeRange(int fromIndex, int toIndex) {
|
||||
super.removeRange(fromIndex, toIndex);
|
||||
update();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean removeAll(Collection<?> c) {
|
||||
val ret = super.removeAll(c);
|
||||
update();
|
||||
return ret;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean retainAll(Collection<?> c) {
|
||||
val ret = super.retainAll(c);
|
||||
update();
|
||||
return ret;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean removeIf(Predicate<? super T> filter) {
|
||||
val ret = super.removeIf(filter);
|
||||
update();
|
||||
return ret;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void replaceAll(UnaryOperator<T> operator) {
|
||||
super.replaceAll(operator);
|
||||
update();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sort(Comparator<? super T> c) {
|
||||
super.sort(c);
|
||||
update();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,24 +0,0 @@
|
|||
package buttondevteam.lib.architecture
|
||||
|
||||
import buttondevteam.lib.architecture.config.ConfigList
|
||||
import buttondevteam.lib.architecture.config.IConfigData
|
||||
import buttondevteam.lib.architecture.config.IListConfigData
|
||||
import java.util.function.Function
|
||||
|
||||
class ListConfigData<T> internal constructor(
|
||||
config: IHaveConfig,
|
||||
path: String,
|
||||
primitiveDef: ArrayList<*>,
|
||||
internal val elementGetter: Function<Any?, T>,
|
||||
internal val elementSetter: Function<T, Any?>,
|
||||
readOnly: Boolean
|
||||
) : IConfigData<ConfigList<T>>, IListConfigData<T> {
|
||||
val listConfig: ConfigData<ConfigList<T>> =
|
||||
ConfigData(config, path, primitiveDef, { ConfigList((it as ArrayList<*>).toMutableList(), this) }, { it }, readOnly)
|
||||
|
||||
override val path get() = listConfig.path
|
||||
override fun get() = listConfig.get()
|
||||
override fun set(value: ConfigList<T>) = listConfig.set(value)
|
||||
override fun reload() = listConfig.reload()
|
||||
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
package buttondevteam.lib.architecture;
|
||||
|
||||
import java.util.function.Function;
|
||||
|
||||
public class ReadOnlyConfigData<T> extends ConfigData<T> {
|
||||
ReadOnlyConfigData(IHaveConfig config, String path, T def, Object primitiveDef, Function<Object, T> getter, Function<T, Object> setter) {
|
||||
super(config, path, def, primitiveDef, getter, setter);
|
||||
}
|
||||
|
||||
ReadOnlyConfigData(IHaveConfig config, String path, T def, Object primitiveDef) {
|
||||
super(config, path, def, primitiveDef, null, null);
|
||||
}
|
||||
}
|
|
@ -1,13 +0,0 @@
|
|||
package buttondevteam.lib.architecture.config
|
||||
|
||||
import kotlin.reflect.KProperty
|
||||
|
||||
open class ConfigDataDelegate<T>(private val data: IConfigData<T>) : IConfigData<T> by data {
|
||||
operator fun getValue(thisRef: Any?, property: KProperty<*>): T = data.get()
|
||||
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) = data.set(value)
|
||||
}
|
||||
|
||||
class ListConfigDataDelegate<T>(data: IListConfigData<T>) : ConfigDataDelegate<ConfigList<T>>(data), IListConfigData<T>
|
||||
|
||||
fun <T> IConfigData<T>.delegate() = ConfigDataDelegate(this)
|
||||
fun <T> IListConfigData<T>.delegate() = ListConfigDataDelegate(this)
|
|
@ -1,146 +0,0 @@
|
|||
package buttondevteam.lib.architecture.config
|
||||
|
||||
import buttondevteam.lib.architecture.ConfigData
|
||||
import buttondevteam.lib.architecture.ListConfigData
|
||||
import java.util.function.Predicate
|
||||
import java.util.function.UnaryOperator
|
||||
|
||||
class ConfigList<T>(
|
||||
backingList: MutableList<Any?>,
|
||||
private val parentConfig: ListConfigData<T>
|
||||
) : MutableList<T> {
|
||||
private val primitiveList = backingList
|
||||
override val size: Int get() = primitiveList.size
|
||||
private fun update() {
|
||||
val config = parentConfig.listConfig.config
|
||||
ConfigData.signalChange(config) //Update the config model and start save task if needed
|
||||
}
|
||||
|
||||
override fun set(index: Int, element: T): T {
|
||||
val ret = primitiveList.set(index, parentConfig.elementSetter.apply(element))
|
||||
update()
|
||||
return parentConfig.elementGetter.apply(ret)
|
||||
}
|
||||
|
||||
override fun add(element: T): Boolean {
|
||||
val ret = primitiveList.add(parentConfig.elementSetter.apply(element))
|
||||
update()
|
||||
return ret
|
||||
}
|
||||
|
||||
override fun add(index: Int, element: T) {
|
||||
primitiveList.add(index, parentConfig.elementSetter.apply(element))
|
||||
update()
|
||||
}
|
||||
|
||||
override fun removeAt(index: Int): T {
|
||||
val ret = primitiveList.removeAt(index)
|
||||
update()
|
||||
return parentConfig.elementGetter.apply(ret)
|
||||
}
|
||||
|
||||
override fun subList(fromIndex: Int, toIndex: Int): MutableList<T> =
|
||||
ConfigList(primitiveList.subList(fromIndex, toIndex), parentConfig)
|
||||
|
||||
override fun remove(element: T): Boolean {
|
||||
val ret = primitiveList.remove(parentConfig.elementSetter.apply(element))
|
||||
update()
|
||||
return ret
|
||||
}
|
||||
|
||||
override fun addAll(elements: Collection<T>): Boolean {
|
||||
val ret = primitiveList.addAll(elements.map { parentConfig.elementSetter.apply(it) })
|
||||
update()
|
||||
return ret
|
||||
}
|
||||
|
||||
override fun addAll(index: Int, elements: Collection<T>): Boolean {
|
||||
val ret = primitiveList.addAll(index, elements.map { parentConfig.elementSetter.apply(it) })
|
||||
update()
|
||||
return ret
|
||||
}
|
||||
|
||||
override fun removeAll(elements: Collection<T>): Boolean {
|
||||
val ret = primitiveList.removeAll(elements.map { parentConfig.elementSetter.apply(it) })
|
||||
update()
|
||||
return ret
|
||||
}
|
||||
|
||||
override fun retainAll(elements: Collection<T>): Boolean {
|
||||
val ret = primitiveList.retainAll(elements.map { parentConfig.elementSetter.apply(it) })
|
||||
update()
|
||||
return ret
|
||||
}
|
||||
|
||||
override fun removeIf(filter: Predicate<in T>): Boolean {
|
||||
val ret = primitiveList.removeIf { filter.test(parentConfig.elementGetter.apply(it)) }
|
||||
update()
|
||||
return ret
|
||||
}
|
||||
|
||||
override fun replaceAll(operator: UnaryOperator<T>) {
|
||||
primitiveList.replaceAll { parentConfig.elementSetter.apply(operator.apply(parentConfig.elementGetter.apply(it))) }
|
||||
update()
|
||||
}
|
||||
|
||||
override fun sort(c: Comparator<in T>) {
|
||||
primitiveList.sortWith { o1, o2 -> c.compare(parentConfig.elementGetter.apply(o1), parentConfig.elementGetter.apply(o2)) }
|
||||
update()
|
||||
}
|
||||
|
||||
override fun clear() {
|
||||
primitiveList.clear()
|
||||
update()
|
||||
}
|
||||
|
||||
override fun get(index: Int): T = parentConfig.elementGetter.apply(primitiveList[index])
|
||||
override fun isEmpty(): Boolean = primitiveList.isEmpty()
|
||||
|
||||
override fun lastIndexOf(element: T): Int = primitiveList.lastIndexOf(parentConfig.elementSetter.apply(element))
|
||||
override fun indexOf(element: T): Int = primitiveList.indexOf(parentConfig.elementSetter.apply(element))
|
||||
override fun containsAll(elements: Collection<T>): Boolean =
|
||||
primitiveList.containsAll(elements.map { parentConfig.elementSetter.apply(it) })
|
||||
|
||||
override fun contains(element: T): Boolean = primitiveList.contains(parentConfig.elementSetter.apply(element))
|
||||
override fun iterator(): MutableIterator<T> {
|
||||
return object : MutableIterator<T> {
|
||||
private val iterator = primitiveList.iterator()
|
||||
override fun hasNext(): Boolean = iterator.hasNext()
|
||||
override fun next(): T = parentConfig.elementGetter.apply(iterator.next())
|
||||
override fun remove() {
|
||||
iterator.remove()
|
||||
update()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun listIterator(): MutableListIterator<T> {
|
||||
return listIterator(0)
|
||||
}
|
||||
|
||||
override fun listIterator(index: Int): MutableListIterator<T> {
|
||||
return object : MutableListIterator<T> {
|
||||
private val iterator = primitiveList.listIterator(index)
|
||||
override fun hasNext(): Boolean = iterator.hasNext()
|
||||
override fun next(): T = parentConfig.elementGetter.apply(iterator.next())
|
||||
override fun remove() {
|
||||
iterator.remove()
|
||||
update()
|
||||
}
|
||||
|
||||
override fun hasPrevious(): Boolean = iterator.hasPrevious()
|
||||
override fun nextIndex(): Int = iterator.nextIndex()
|
||||
override fun previous(): T = parentConfig.elementGetter.apply(iterator.previous())
|
||||
override fun previousIndex(): Int = iterator.previousIndex()
|
||||
override fun add(element: T) {
|
||||
iterator.add(parentConfig.elementSetter.apply(element))
|
||||
update()
|
||||
}
|
||||
|
||||
override fun set(element: T) {
|
||||
iterator.set(parentConfig.elementSetter.apply(element))
|
||||
update()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,25 +0,0 @@
|
|||
package buttondevteam.lib.architecture.config
|
||||
|
||||
interface IConfigData<T> {
|
||||
/**
|
||||
* Gets the value from the config using the getter specified for the config. If the config is not set, the default value is returned.
|
||||
*/
|
||||
fun get(): T
|
||||
|
||||
/**
|
||||
* Sets the value in the config using the setter specified for the config. If the config is read-only, this does nothing.
|
||||
*/
|
||||
fun set(value: T)
|
||||
|
||||
/**
|
||||
* Reload the config from the file.
|
||||
*/
|
||||
fun reload()
|
||||
|
||||
/**
|
||||
* The path to the config value.
|
||||
*/
|
||||
val path: String
|
||||
}
|
||||
|
||||
interface IListConfigData<T> : IConfigData<ConfigList<T>>
|
|
@ -0,0 +1,57 @@
|
|||
package buttondevteam.lib.chat;
|
||||
|
||||
import buttondevteam.lib.player.ChromaGamerBase;
|
||||
import lombok.Builder;
|
||||
import lombok.Getter;
|
||||
import lombok.NonNull;
|
||||
import lombok.Setter;
|
||||
import org.bukkit.command.CommandSender;
|
||||
|
||||
@Builder
|
||||
@Getter
|
||||
public class ChatMessage {
|
||||
/**
|
||||
* The sender which sends the message.
|
||||
*/
|
||||
private final CommandSender sender;
|
||||
/**
|
||||
* The Chroma user which sends the message.
|
||||
*/
|
||||
private final ChromaGamerBase user;
|
||||
/**
|
||||
* The message to send as the user.
|
||||
*/
|
||||
@Setter
|
||||
private String message;
|
||||
/**
|
||||
* Indicates whether the message comes from running a command (like /tableflip). Implemented to be used from Discord.
|
||||
*/
|
||||
private boolean fromCommand;
|
||||
/**
|
||||
* The sender which we should check for permissions. Same as {@link #sender} by default.
|
||||
*/
|
||||
private CommandSender permCheck;
|
||||
/**
|
||||
* The origin of the message, "Minecraft" or "Discord" for example. May be displayed to the user.<br>
|
||||
* <b>This is the user class capitalized folder name.</b>
|
||||
*/
|
||||
private final String origin;
|
||||
|
||||
/**
|
||||
* The sender which we should check for permissions. Same as {@link #sender} by default.
|
||||
*
|
||||
* @return The perm check or the sender
|
||||
*/
|
||||
public CommandSender getPermCheck() {
|
||||
return permCheck == null ? sender : permCheck;
|
||||
}
|
||||
|
||||
private static ChatMessageBuilder builder() {
|
||||
return new ChatMessageBuilder();
|
||||
}
|
||||
|
||||
@NonNull
|
||||
public static ChatMessageBuilder builder(CommandSender sender, ChromaGamerBase user, String message) {
|
||||
return builder().sender(sender).user(user).message(message).origin(user.getFolder().substring(0, 1).toUpperCase() + user.getFolder().substring(1));
|
||||
}
|
||||
}
|
|
@ -1,72 +0,0 @@
|
|||
package buttondevteam.lib.chat
|
||||
|
||||
import buttondevteam.lib.player.ChromaGamerBase
|
||||
import java.util.*
|
||||
|
||||
class ChatMessage internal constructor(
|
||||
/**
|
||||
* The Chroma user who sent the message.
|
||||
*/
|
||||
val user: ChromaGamerBase,
|
||||
/**
|
||||
* The message to send as the user.
|
||||
*/
|
||||
var message: String,
|
||||
/**
|
||||
* Indicates whether the message comes from running a command (like /tableflip). Implemented to be used from Discord.
|
||||
*/
|
||||
val isFromCommand: Boolean,
|
||||
/**
|
||||
* The sender which we should check for permissions. Same as [.sender] by default.
|
||||
*/
|
||||
val permCheck: ChromaGamerBase,
|
||||
/**
|
||||
* The origin of the message, "Minecraft" or "Discord" for example. May be displayed to the user.
|
||||
*
|
||||
* **This is the user class capitalized folder name by default.**
|
||||
*/
|
||||
val origin: String
|
||||
) {
|
||||
|
||||
class ChatMessageBuilder internal constructor(
|
||||
private var user: ChromaGamerBase,
|
||||
private var message: String,
|
||||
private var origin: String
|
||||
) {
|
||||
private var fromCommand = false
|
||||
private var permCheck: ChromaGamerBase? = null
|
||||
|
||||
fun fromCommand(fromCommand: Boolean): ChatMessageBuilder {
|
||||
this.fromCommand = fromCommand
|
||||
return this
|
||||
}
|
||||
|
||||
fun permCheck(permCheck: ChromaGamerBase): ChatMessageBuilder {
|
||||
this.permCheck = permCheck
|
||||
return this
|
||||
}
|
||||
|
||||
fun origin(origin: String): ChatMessageBuilder {
|
||||
this.origin = origin
|
||||
return this
|
||||
}
|
||||
|
||||
fun build(): ChatMessage {
|
||||
return ChatMessage(user, message, fromCommand, permCheck ?: user, origin)
|
||||
}
|
||||
|
||||
override fun toString(): String {
|
||||
return "ChatMessage.ChatMessageBuilder(user=$user, message=$message, fromCommand=$fromCommand, permCheck=$permCheck, origin=$origin)"
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
@JvmStatic
|
||||
fun builder(user: ChromaGamerBase, message: String): ChatMessageBuilder {
|
||||
return ChatMessageBuilder(
|
||||
user, message,
|
||||
user.folder.replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.getDefault()) else it.toString() }
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
30
Chroma-Core/src/main/java/buttondevteam/lib/chat/Color.java
Executable file
30
Chroma-Core/src/main/java/buttondevteam/lib/chat/Color.java
Executable file
|
@ -0,0 +1,30 @@
|
|||
package buttondevteam.lib.chat;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
@RequiredArgsConstructor
|
||||
@Getter
|
||||
public enum Color implements TellrawSerializableEnum {
|
||||
Black("black", 0, 0, 0),
|
||||
DarkBlue("dark_blue", 0, 0, 170),
|
||||
DarkGreen("dark_green", 0, 170, 0),
|
||||
DarkAqua("dark_aqua", 0, 170, 170),
|
||||
DarkRed("dark_red", 170, 0, 0),
|
||||
DarkPurple("dark_purple", 0, 170, 0),
|
||||
Gold("gold", 255, 170,0),
|
||||
Gray("gray", 170, 170, 170),
|
||||
DarkGray("dark_gray", 85, 85, 85),
|
||||
Blue("blue", 85, 85, 255),
|
||||
Green("green", 85, 255, 85),
|
||||
Aqua("aqua", 85, 255, 255),
|
||||
Red("red", 255, 85,85),
|
||||
LightPurple("light_purple", 255, 85, 255),
|
||||
Yellow("yellow", 255, 255, 85),
|
||||
White("white", 255, 255, 255);
|
||||
|
||||
private final String name;
|
||||
private final int red;
|
||||
private final int green;
|
||||
private final int blue;
|
||||
}
|
440
Chroma-Core/src/main/java/buttondevteam/lib/chat/Command2.java
Normal file
440
Chroma-Core/src/main/java/buttondevteam/lib/chat/Command2.java
Normal file
|
@ -0,0 +1,440 @@
|
|||
package buttondevteam.lib.chat;
|
||||
|
||||
import buttondevteam.core.MainPlugin;
|
||||
import buttondevteam.lib.ChromaUtils;
|
||||
import buttondevteam.lib.TBMCCoreAPI;
|
||||
import buttondevteam.lib.player.ChromaGamerBase;
|
||||
import com.google.common.base.Defaults;
|
||||
import com.google.common.primitives.Primitives;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.val;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.io.InputStreamReader;
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.text.NumberFormat;
|
||||
import java.text.ParseException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* The method name is the subcommand, use underlines (_) to add further subcommands.
|
||||
* The args may be null if the conversion failed and it's optional.
|
||||
*/
|
||||
public abstract class Command2<TC extends ICommand2<TP>, TP extends Command2Sender> {
|
||||
protected Command2() {
|
||||
commandHelp.add("§6---- Commands ----");
|
||||
}
|
||||
|
||||
/**
|
||||
* Parameters annotated with this receive all of the remaining arguments
|
||||
*/
|
||||
@Target(ElementType.PARAMETER)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface TextArg {
|
||||
}
|
||||
|
||||
/**
|
||||
* Methods annotated with this will be recognised as subcommands
|
||||
*/
|
||||
@Target(ElementType.METHOD)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface Subcommand {
|
||||
/**
|
||||
* Allowed for OPs only by default
|
||||
*/
|
||||
String MOD_GROUP = "mod";
|
||||
|
||||
/**
|
||||
* Help text to show players. A usage message will be also shown below it.
|
||||
*/
|
||||
String[] helpText() default {};
|
||||
|
||||
/**
|
||||
* The main permission which allows using this command (individual access can be still revoked with "chroma.command.X").
|
||||
* Used to be "tbmc.admin". The {@link #MOD_GROUP} is provided to use with this.
|
||||
*/
|
||||
String permGroup() default "";
|
||||
|
||||
String[] aliases() default {};
|
||||
}
|
||||
|
||||
@Target(ElementType.PARAMETER)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface OptionalArg {
|
||||
}
|
||||
|
||||
@AllArgsConstructor
|
||||
protected static class SubcommandData<T extends ICommand2<?>> {
|
||||
public final Method method;
|
||||
public final T command;
|
||||
public final String[] parameters;
|
||||
public String[] helpText;
|
||||
}
|
||||
|
||||
/*protected static class SubcommandHelpData<T extends ICommand2> extends SubcommandData<T> {
|
||||
private final TreeSet<String> ht = new TreeSet<>();
|
||||
private BukkitTask task;
|
||||
|
||||
public SubcommandHelpData(Method method, T command, String[] helpText) {
|
||||
super(method, command, helpText);
|
||||
}
|
||||
|
||||
public void addSubcommand(String command) {
|
||||
ht.add(command);
|
||||
if (task == null)
|
||||
task = Bukkit.getScheduler().runTask(MainPlugin.Instance, () -> {
|
||||
helpText = new String[ht.size() + 1]; //This will only run after the server is started List<E> list = new ArrayList<E>(size());
|
||||
helpText[0] = "§6---- Subcommands ----"; //TODO: There may be more to the help text
|
||||
int i = 1;
|
||||
for (Iterator<String> iterator = ht.iterator();
|
||||
iterator.hasNext() && i < helpText.length; i++) {
|
||||
String e = iterator.next();
|
||||
helpText[i] = e;
|
||||
}
|
||||
task = null; //Run again, if needed
|
||||
});
|
||||
}
|
||||
}*/
|
||||
|
||||
@RequiredArgsConstructor
|
||||
protected static class ParamConverter<T> {
|
||||
public final Function<String, T> converter;
|
||||
public final String errormsg;
|
||||
public final Supplier<Iterable<String>> allSupplier;
|
||||
}
|
||||
|
||||
protected final HashMap<String, SubcommandData<TC>> subcommands = new HashMap<>();
|
||||
protected final HashMap<Class<?>, ParamConverter<?>> paramConverters = new HashMap<>();
|
||||
|
||||
private final ArrayList<String> commandHelp = new ArrayList<>(); //Mainly needed by Discord
|
||||
|
||||
private char commandChar;
|
||||
|
||||
/**
|
||||
* Adds a param converter that obtains a specific object from a string parameter.
|
||||
* The converter may return null.
|
||||
*
|
||||
* @param <T> The type of the result
|
||||
* @param cl The class of the result object
|
||||
* @param converter The converter to use
|
||||
* @param allSupplier The supplier of all possible values (ideally)
|
||||
*/
|
||||
public <T> void addParamConverter(Class<T> cl, Function<String, T> converter, String errormsg,
|
||||
Supplier<Iterable<String>> allSupplier) {
|
||||
paramConverters.put(cl, new ParamConverter<>(converter, errormsg, allSupplier));
|
||||
}
|
||||
|
||||
public boolean handleCommand(TP sender, String commandline) {
|
||||
for (int i = commandline.length(); i != -1; i = commandline.lastIndexOf(' ', i - 1)) {
|
||||
String subcommand = commandline.substring(0, i).toLowerCase();
|
||||
SubcommandData<TC> sd = subcommands.get(subcommand);
|
||||
if (sd == null) continue;
|
||||
boolean sync = Bukkit.isPrimaryThread();
|
||||
Bukkit.getScheduler().runTaskAsynchronously(MainPlugin.Instance, () -> {
|
||||
try {
|
||||
handleCommandAsync(sender, commandline, sd, subcommand, sync);
|
||||
} catch (Exception e) {
|
||||
TBMCCoreAPI.SendException("Command execution failed for sender " + sender.getName() + "(" + sender.getClass().getCanonicalName() + ") and message " + commandline, e, MainPlugin.Instance);
|
||||
}
|
||||
});
|
||||
return true; //We found a method
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
//Needed because permission checking may load the (perhaps offline) sender's file which is disallowed on the main thread
|
||||
|
||||
/**
|
||||
* Handles a command asynchronously
|
||||
*
|
||||
* @param sender The command sender
|
||||
* @param commandline The command line the sender sent
|
||||
* @param sd The subcommand data
|
||||
* @param subcommand The subcommand text
|
||||
* @param sync Whether the command was originally sync
|
||||
* @throws Exception If something's not right
|
||||
*/
|
||||
private void handleCommandAsync(TP sender, String commandline, SubcommandData<TC> sd, String subcommand, boolean sync) throws Exception {
|
||||
if (sd.method == null || sd.command == null) { //Main command not registered, but we have subcommands
|
||||
sender.sendMessage(sd.helpText);
|
||||
return;
|
||||
}
|
||||
if (!hasPermission(sender, sd.command, sd.method)) {
|
||||
sender.sendMessage("§cYou don't have permission to use this command");
|
||||
return;
|
||||
}
|
||||
val params = new ArrayList<Object>(sd.method.getParameterCount());
|
||||
int j = subcommand.length(), pj;
|
||||
Class<?>[] parameterTypes = sd.method.getParameterTypes();
|
||||
if (parameterTypes.length == 0)
|
||||
throw new Exception("No sender parameter for method '" + sd.method + "'");
|
||||
val sendertype = parameterTypes[0];
|
||||
final ChromaGamerBase cg;
|
||||
if (sendertype.isAssignableFrom(sender.getClass()))
|
||||
params.add(sender); //The command either expects a CommandSender or it is a Player, or some other expected type
|
||||
else if (sender instanceof Command2MCSender
|
||||
&& sendertype.isAssignableFrom(((Command2MCSender) sender).getSender().getClass()))
|
||||
params.add(((Command2MCSender) sender).getSender());
|
||||
else if (ChromaGamerBase.class.isAssignableFrom(sendertype)
|
||||
&& sender instanceof Command2MCSender
|
||||
&& (cg = ChromaGamerBase.getFromSender(((Command2MCSender) sender).getSender())) != null
|
||||
&& cg.getClass() == sendertype) //The command expects a user of our system
|
||||
params.add(cg);
|
||||
else {
|
||||
sender.sendMessage("§cYou need to be a " + sendertype.getSimpleName() + " to use this command.");
|
||||
sender.sendMessage(sd.helpText); //Send what the command is about, could be useful for commands like /member where some subcommands aren't player-only
|
||||
return;
|
||||
}
|
||||
val paramArr = sd.method.getParameters();
|
||||
for (int i1 = 1; i1 < parameterTypes.length; i1++) {
|
||||
Class<?> cl = parameterTypes[i1];
|
||||
pj = j + 1; //Start index
|
||||
if (pj == commandline.length() + 1) { //No param given
|
||||
if (paramArr[i1].isAnnotationPresent(OptionalArg.class)) {
|
||||
if (cl.isPrimitive())
|
||||
params.add(Defaults.defaultValue(cl));
|
||||
else if (Number.class.isAssignableFrom(cl)
|
||||
|| Number.class.isAssignableFrom(cl))
|
||||
params.add(Defaults.defaultValue(Primitives.unwrap(cl)));
|
||||
else
|
||||
params.add(null);
|
||||
continue; //Fill the remaining params with nulls
|
||||
} else {
|
||||
sender.sendMessage(sd.helpText); //Required param missing
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (paramArr[i1].isVarArgs()) {
|
||||
params.add(commandline.substring(j + 1).split(" +"));
|
||||
continue;
|
||||
}
|
||||
j = commandline.indexOf(' ', j + 1); //End index
|
||||
if (j == -1 || paramArr[i1].isAnnotationPresent(TextArg.class)) //Last parameter
|
||||
j = commandline.length();
|
||||
String param = commandline.substring(pj, j);
|
||||
if (cl == String.class) {
|
||||
params.add(param);
|
||||
continue;
|
||||
} else if (Number.class.isAssignableFrom(cl) || cl.isPrimitive()) {
|
||||
try {
|
||||
if (cl == boolean.class) {
|
||||
params.add(Boolean.parseBoolean(param));
|
||||
continue;
|
||||
}
|
||||
if (cl == char.class) {
|
||||
if (param.length() != 1) {
|
||||
sender.sendMessage("§c'" + param + "' is not a character.");
|
||||
return;
|
||||
}
|
||||
params.add(param.charAt(0));
|
||||
continue;
|
||||
}
|
||||
//noinspection unchecked
|
||||
Number n = ChromaUtils.convertNumber(NumberFormat.getInstance().parse(param), (Class<? extends Number>) cl);
|
||||
params.add(n);
|
||||
} catch (ParseException e) {
|
||||
sender.sendMessage("§c'" + param + "' is not a number.");
|
||||
return;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
val conv = paramConverters.get(cl);
|
||||
if (conv == null)
|
||||
throw new Exception("No suitable converter found for parameter type '" + cl.getCanonicalName() + "' for command '" + sd.method + "'");
|
||||
val cparam = conv.converter.apply(param);
|
||||
if (cparam == null) {
|
||||
sender.sendMessage(conv.errormsg); //Param conversion failed - ex. plugin not found
|
||||
return;
|
||||
}
|
||||
params.add(cparam);
|
||||
}
|
||||
Runnable lol = () -> {
|
||||
try {
|
||||
sd.method.setAccessible(true); //It may be part of a private class
|
||||
val ret = sd.method.invoke(sd.command, params.toArray()); //I FORGOT TO TURN IT INTO AN ARRAY (for a long time)
|
||||
if (ret instanceof Boolean) {
|
||||
if (!(boolean) ret) //Show usage
|
||||
sender.sendMessage(sd.helpText);
|
||||
} else if (ret != null)
|
||||
throw new Exception("Wrong return type! Must return a boolean or void. Return value: " + ret);
|
||||
} catch (InvocationTargetException e) {
|
||||
TBMCCoreAPI.SendException("An error occurred in a command handler for " + subcommand + "!", e.getCause(), MainPlugin.Instance);
|
||||
} catch (Exception e) {
|
||||
TBMCCoreAPI.SendException("Command handling failed for sender " + sender + " and subcommand " + subcommand, e, MainPlugin.Instance);
|
||||
}
|
||||
};
|
||||
if (sync)
|
||||
Bukkit.getScheduler().runTask(MainPlugin.Instance, lol);
|
||||
else
|
||||
lol.run();
|
||||
} //TODO: Add to the help
|
||||
|
||||
public abstract void registerCommand(TC command);
|
||||
|
||||
protected List<SubcommandData<TC>> registerCommand(TC command, char commandChar) {
|
||||
return registerCommand(command, command.getCommandPath(), commandChar);
|
||||
}
|
||||
|
||||
protected List<SubcommandData<TC>> registerCommand(TC command, String path, @SuppressWarnings("SameParameterValue") char commandChar) {
|
||||
this.commandChar = commandChar;
|
||||
int x = path.indexOf(' ');
|
||||
val mainPath = commandChar + path.substring(0, x == -1 ? path.length() : x);
|
||||
//var scmdmap = subcommandStrings.computeIfAbsent(mainPath, k -> new HashSet<>()); //Used to display subcommands
|
||||
val scmdHelpList = new ArrayList<String>();
|
||||
Method mainMethod = null;
|
||||
boolean nosubs = true;
|
||||
boolean isSubcommand = x != -1;
|
||||
try { //Register the default handler first so it can be reliably overwritten
|
||||
mainMethod = command.getClass().getMethod("def", Command2Sender.class);
|
||||
val cc = command.getClass().getAnnotation(CommandClass.class);
|
||||
var ht = cc == null || isSubcommand ? new String[0] : cc.helpText(); //If it's not the main command, don't add it
|
||||
if (ht.length > 0)
|
||||
ht[0] = "§6---- " + ht[0] + " ----";
|
||||
scmdHelpList.addAll(Arrays.asList(ht));
|
||||
if (!isSubcommand)
|
||||
scmdHelpList.add("§6Subcommands:");
|
||||
if (!commandHelp.contains(mainPath))
|
||||
commandHelp.add(mainPath);
|
||||
} catch (Exception e) {
|
||||
TBMCCoreAPI.SendException("Could not register default handler for command /" + path, e, MainPlugin.Instance);
|
||||
}
|
||||
var addedSubcommands = new ArrayList<SubcommandData<TC>>();
|
||||
for (val method : command.getClass().getMethods()) {
|
||||
val ann = method.getAnnotation(Subcommand.class);
|
||||
if (ann == null) continue; //Don't call the method on non-subcommands because they're not in the yaml
|
||||
var ht = command.getHelpText(method, ann);
|
||||
if (ht != null) { //The method is a subcommand
|
||||
val subcommand = commandChar + path + //Add command path (class name by default)
|
||||
getCommandPath(method.getName(), ' '); //Add method name, unless it's 'def'
|
||||
var params = new String[method.getParameterCount() - 1];
|
||||
ht = getParameterHelp(method, ht, subcommand, params);
|
||||
var sd = new SubcommandData<>(method, command, params, ht);
|
||||
registerCommand(path, method.getName(), ann, sd);
|
||||
for (String p : command.getCommandPaths())
|
||||
registerCommand(p, method.getName(), ann, sd);
|
||||
addedSubcommands.add(sd);
|
||||
scmdHelpList.add(subcommand);
|
||||
nosubs = false;
|
||||
}
|
||||
}
|
||||
if (nosubs && scmdHelpList.size() > 0)
|
||||
scmdHelpList.remove(scmdHelpList.size() - 1); //Remove Subcommands header
|
||||
if (mainMethod != null && !subcommands.containsKey(commandChar + path)) { //Command specified by the class
|
||||
var sd = new SubcommandData<>(mainMethod, command, null, scmdHelpList.toArray(new String[0]));
|
||||
subcommands.put(commandChar + path, sd);
|
||||
addedSubcommands.add(sd);
|
||||
}
|
||||
if (isSubcommand) { //The class itself is a subcommand
|
||||
val scmd = subcommands.computeIfAbsent(mainPath, p -> new SubcommandData<>(null, null, new String[0], new String[]{"§6---- Subcommands ----"}));
|
||||
val scmdHelp = Arrays.copyOf(scmd.helpText, scmd.helpText.length + scmdHelpList.size());
|
||||
for (int i = 0; i < scmdHelpList.size(); i++)
|
||||
scmdHelp[scmd.helpText.length + i] = scmdHelpList.get(i);
|
||||
scmd.helpText = scmdHelp;
|
||||
}
|
||||
return addedSubcommands;
|
||||
}
|
||||
|
||||
private String[] getParameterHelp(Method method, String[] ht, String subcommand, String[] parameters) {
|
||||
val str = method.getDeclaringClass().getResourceAsStream("/commands.yml");
|
||||
if (str == null)
|
||||
TBMCCoreAPI.SendException("Error while getting command data!", new Exception("Resource not found!"), MainPlugin.Instance);
|
||||
else {
|
||||
if (ht.length > 0)
|
||||
ht[0] = "§6---- " + ht[0] + " ----";
|
||||
YamlConfiguration yc = YamlConfiguration.loadConfiguration(new InputStreamReader(str)); //Generated by ButtonProcessor
|
||||
val ccs = yc.getConfigurationSection(method.getDeclaringClass().getCanonicalName().replace('$', '.'));
|
||||
if (ccs != null) {
|
||||
val cs = ccs.getConfigurationSection(method.getName());
|
||||
if (cs != null) {
|
||||
val mname = cs.getString("method");
|
||||
val params = cs.getString("params");
|
||||
//val goodname = method.getName() + "(" + Arrays.stream(method.getGenericParameterTypes()).map(cl -> cl.getTypeName()).collect(Collectors.joining(",")) + ")";
|
||||
int i = mname.indexOf('('); //Check only the name - the whole method is still stored for backwards compatibility and in case it may be useful
|
||||
if (i != -1 && method.getName().equals(mname.substring(0, i)) && params != null) {
|
||||
String[] both = Arrays.copyOf(ht, ht.length + 1);
|
||||
both[ht.length] = "§6Usage:§r " + subcommand + " " + params;
|
||||
ht = both;
|
||||
var paramArray = params.split(" ");
|
||||
for (int j = 0; j < paramArray.length && j < parameters.length; j++)
|
||||
parameters[j] = paramArray[j];
|
||||
} else
|
||||
TBMCCoreAPI.SendException("Error while getting command data for " + method + "!", new Exception("Method '" + method + "' != " + mname + " or params is " + params), MainPlugin.Instance);
|
||||
} else
|
||||
MainPlugin.Instance.getLogger().warning("Failed to get command data for " + method + " (cs is null)! Make sure to use 'clean install' when building the project.");
|
||||
} else
|
||||
MainPlugin.Instance.getLogger().warning("Failed to get command data for " + method + " (ccs is null)! Make sure to use 'clean install' when building the project.");
|
||||
}
|
||||
return ht;
|
||||
}
|
||||
|
||||
private void registerCommand(String path, String methodName, Subcommand ann, SubcommandData<TC> sd) {
|
||||
val subcommand = commandChar + path + getCommandPath(methodName, ' ');
|
||||
subcommands.put(subcommand, sd);
|
||||
for (String alias : ann.aliases())
|
||||
subcommands.put(commandChar + path + alias, sd);
|
||||
}
|
||||
|
||||
public abstract boolean hasPermission(TP sender, TC command, Method subcommand);
|
||||
|
||||
public String[] getCommandsText() {
|
||||
return commandHelp.toArray(new String[0]);
|
||||
}
|
||||
|
||||
public String[] getHelpText(String path) {
|
||||
val scmd = subcommands.get(path);
|
||||
if (scmd == null) return null;
|
||||
return scmd.helpText;
|
||||
}
|
||||
|
||||
/*public Set<String> getAllSubcommands() {
|
||||
return Collections.unmodifiableSet(subcommands.keySet());
|
||||
}*/
|
||||
|
||||
/**
|
||||
* Unregisters all of the subcommands in the given command.
|
||||
*
|
||||
* @param command The command object
|
||||
*/
|
||||
public void unregisterCommand(ICommand2<TP> command) {
|
||||
var path = command.getCommandPath();
|
||||
for (val method : command.getClass().getMethods()) {
|
||||
val ann = method.getAnnotation(Subcommand.class);
|
||||
if (ann == null) continue;
|
||||
unregisterCommand(path, method.getName(), ann);
|
||||
for (String p : command.getCommandPaths())
|
||||
unregisterCommand(p, method.getName(), ann);
|
||||
}
|
||||
}
|
||||
|
||||
private void unregisterCommand(String path, String methodName, Subcommand ann) {
|
||||
val subcommand = commandChar + path + getCommandPath(methodName, ' ');
|
||||
subcommands.remove(subcommand);
|
||||
for (String alias : ann.aliases())
|
||||
subcommands.remove(commandChar + path + alias);
|
||||
}
|
||||
|
||||
/**
|
||||
* It will start with the given replace char.
|
||||
*
|
||||
* @param methodName The method's name, method.getName()
|
||||
* @param replaceChar The character to use between subcommands
|
||||
* @return The command path starting with the replace char.
|
||||
*/
|
||||
@NotNull
|
||||
public String getCommandPath(String methodName, char replaceChar) {
|
||||
return methodName.equals("def") ? "" : replaceChar + methodName.replace('_', replaceChar).toLowerCase();
|
||||
}
|
||||
}
|
|
@ -1,506 +0,0 @@
|
|||
package buttondevteam.lib.chat
|
||||
|
||||
import buttondevteam.core.MainPlugin
|
||||
import buttondevteam.lib.ChromaUtils
|
||||
import buttondevteam.lib.chat.commands.*
|
||||
import buttondevteam.lib.chat.commands.CommandUtils.coreCommand
|
||||
import buttondevteam.lib.chat.commands.CommandUtils.coreCommandNoOp
|
||||
import buttondevteam.lib.chat.commands.CommandUtils.coreExecutable
|
||||
import buttondevteam.lib.chat.commands.CommandUtils.getDefaultForEasilyRepresentable
|
||||
import buttondevteam.lib.chat.commands.CommandUtils.isCommand
|
||||
import buttondevteam.lib.chat.commands.CommandUtils.isEasilyRepresentable
|
||||
import buttondevteam.lib.chat.commands.CommandUtils.subcommandData
|
||||
import buttondevteam.lib.chat.commands.CommandUtils.subcommandDataNoOp
|
||||
import com.mojang.brigadier.CommandDispatcher
|
||||
import com.mojang.brigadier.arguments.*
|
||||
import com.mojang.brigadier.builder.ArgumentBuilder
|
||||
import com.mojang.brigadier.context.CommandContext
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException
|
||||
import com.mojang.brigadier.tree.CommandNode
|
||||
import com.mojang.brigadier.tree.LiteralCommandNode
|
||||
import org.bukkit.Bukkit
|
||||
import org.bukkit.ChatColor
|
||||
import java.lang.reflect.InvocationTargetException
|
||||
import java.lang.reflect.Method
|
||||
import java.util.function.Function
|
||||
import java.util.function.Predicate
|
||||
import java.util.function.Supplier
|
||||
|
||||
/**
|
||||
* The method name is the subcommand, use underlines (_) to add further subcommands.
|
||||
* The args may be null if the conversion failed and it's optional.
|
||||
*/
|
||||
abstract class Command2<TC : ICommand2<TP>, TP : Command2Sender>(
|
||||
/**
|
||||
* The first character in the command line that shows that it's a command.
|
||||
*/
|
||||
private val commandChar: Char,
|
||||
|
||||
/**
|
||||
* Whether the command's actual code has to be run on the primary thread.
|
||||
*/
|
||||
private val runOnPrimaryThread: Boolean
|
||||
) {
|
||||
/**
|
||||
* Parameters annotated with this receive all the remaining arguments
|
||||
*/
|
||||
@Target(AnnotationTarget.VALUE_PARAMETER)
|
||||
@Retention(AnnotationRetention.RUNTIME)
|
||||
annotation class TextArg
|
||||
|
||||
/**
|
||||
* Methods annotated with this will be recognised as subcommands
|
||||
*/
|
||||
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER)
|
||||
@Retention(AnnotationRetention.RUNTIME)
|
||||
annotation class Subcommand(
|
||||
/**
|
||||
* Help text to show players. A usage message will be also shown below it.
|
||||
*/
|
||||
val helpText: Array<String> = [],
|
||||
/**
|
||||
* Aliases for the subcommand that can be used to invoke it in addition to the method name.
|
||||
*/
|
||||
val aliases: Array<String> = [] // TODO
|
||||
) {
|
||||
}
|
||||
|
||||
@Target(AnnotationTarget.VALUE_PARAMETER)
|
||||
@Retention(AnnotationRetention.RUNTIME)
|
||||
annotation class OptionalArg
|
||||
|
||||
protected class ParamConverter<T>(
|
||||
val converter: Function<String, T?>,
|
||||
val errormsg: String,
|
||||
val allSupplier: Supplier<Iterable<String>>
|
||||
)
|
||||
|
||||
protected val paramConverters = HashMap<Class<*>, ParamConverter<*>>()
|
||||
private val dispatcher = CommandDispatcher<TP>()
|
||||
|
||||
/**
|
||||
* Adds a param converter that obtains a specific object from a string parameter.
|
||||
* The converter may return null to signal an error.
|
||||
*
|
||||
* @param <T> The type of the result
|
||||
* @param cl The class of the result object
|
||||
* @param converter The converter to use
|
||||
* @param allSupplier The supplier of all possible values (ideally)
|
||||
</T> */
|
||||
open fun <T> addParamConverter(
|
||||
cl: Class<T>,
|
||||
converter: Function<String, T?>,
|
||||
errormsg: String,
|
||||
allSupplier: Supplier<Iterable<String>>
|
||||
) {
|
||||
paramConverters[cl] = ParamConverter(converter, errormsg, allSupplier)
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle the given command line as sent by the sender.
|
||||
*
|
||||
* @param sender The sender who sent the command
|
||||
* @param commandline The command line, including the leading command char
|
||||
*
|
||||
* @return Whether the main command exists
|
||||
*/
|
||||
open fun handleCommand(sender: TP, commandline: String): Boolean {
|
||||
val results = dispatcher.parse(commandline.removePrefix("/"), sender)
|
||||
if (results.reader.canRead()) {
|
||||
return if (results.context.nodes.isNotEmpty()) {
|
||||
for ((node, ex) in results.exceptions) {
|
||||
sender.sendMessage("${ChatColor.RED}${ex.message}")
|
||||
executeHelpText(results.context.build(results.reader.string))
|
||||
}
|
||||
true
|
||||
} else {
|
||||
false // Unknown command
|
||||
}
|
||||
}
|
||||
val executeCommand: () -> Unit = {
|
||||
try {
|
||||
dispatcher.execute(results)
|
||||
} catch (e: CommandSyntaxException) {
|
||||
sender.sendMessage(e.message)
|
||||
} catch (e: Exception) {
|
||||
ChromaUtils.throwWhenTested(e, "Command execution failed for sender ${sender.name}(${sender.javaClass.canonicalName}) and message $commandline")
|
||||
}
|
||||
}
|
||||
if (ChromaUtils.isTest) {
|
||||
executeCommand()
|
||||
} else {
|
||||
//Needed because permission checking may load the (perhaps offline) sender's file which is disallowed on the main thread
|
||||
Bukkit.getScheduler().runTaskAsynchronously(MainPlugin.instance, executeCommand)
|
||||
}
|
||||
return true //We found a method
|
||||
}
|
||||
|
||||
//TODO: Add to the help
|
||||
open fun convertSenderType(sender: TP, senderType: Class<*>): Any? {
|
||||
//The command either expects a CommandSender or it is a Player, or some other expected type
|
||||
if (senderType.isAssignableFrom(sender.javaClass)) return sender
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a command in the command system. The way this command gets registered may change depending on the implementation.
|
||||
* Always invoke [.registerCommandSuper] when implementing this method.
|
||||
*
|
||||
* @param command The command to register
|
||||
*/
|
||||
abstract fun registerCommand(command: TC)
|
||||
|
||||
/**
|
||||
* Registers a command in the Command2 system, so it can be looked up and executed.
|
||||
*
|
||||
* @param command The command to register
|
||||
* @return The Brigadier command node if you need it for something (like tab completion)
|
||||
*/
|
||||
protected fun registerCommandSuper(command: TC): List<CoreExecutableNode<TP, TC>> {
|
||||
val registeredNodes = mutableListOf<CoreExecutableNode<TP, TC>>()
|
||||
for (meth in command.javaClass.methods) {
|
||||
val ann = meth.getAnnotation(Subcommand::class.java) ?: continue
|
||||
val fullPath = command.commandPath + CommandUtils.getCommandPath(meth.name, ' ')
|
||||
assert(fullPath.isNotBlank()) { "No path found for command class ${command.javaClass.name} and method ${meth.name}" }
|
||||
val (lastNode, remainingPath) = registerNodeFromPath(fullPath)
|
||||
val execNode = getExecutableNode(meth, command, ann, remainingPath, CommandArgumentHelpManager(command), fullPath)
|
||||
lastNode.addChild(execNode)
|
||||
registeredNodes.add(execNode)
|
||||
}
|
||||
if (registeredNodes.isEmpty()) {
|
||||
throw RuntimeException("There are no subcommands defined in the command class ${command.javaClass.simpleName}!")
|
||||
}
|
||||
return registeredNodes.toList()
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the node that can actually execute the given subcommand.
|
||||
*
|
||||
* @param method The subcommand method
|
||||
* @param command The command object
|
||||
* @param ann The subcommand annotation
|
||||
* @param remainingPath The command path
|
||||
* @param argHelpManager The object that gets the usage text from code
|
||||
* @param fullPath The full command path as registered
|
||||
* @return The executable node
|
||||
*/
|
||||
private fun getExecutableNode(
|
||||
method: Method, command: TC, ann: Subcommand, remainingPath: String,
|
||||
argHelpManager: CommandArgumentHelpManager<TC, TP>, fullPath: String
|
||||
): CoreExecutableNode<TP, TC> {
|
||||
val (params, senderType) = getCommandParametersAndSender(method, argHelpManager) // Param order is important
|
||||
val paramMap = HashMap<String, CommandArgument>()
|
||||
for (param in params) {
|
||||
paramMap[param.name] = param
|
||||
}
|
||||
val helpText = command.getHelpText(method, ann)
|
||||
val node = CoreCommandBuilder.literal(
|
||||
remainingPath, senderType, paramMap, params, command,
|
||||
{ helpText }, // TODO: Help text getter support
|
||||
{ sender: TP, data: SubcommandData<TC, TP> -> hasPermission(sender, data) },
|
||||
method.annotations.filterNot { it is Subcommand }.toTypedArray(),
|
||||
fullPath,
|
||||
method
|
||||
).executes(this::executeHelpText)
|
||||
|
||||
fun getArgNodes(parent: ArgumentBuilder<TP, *>, params: MutableList<CommandArgument>): Boolean {
|
||||
val param = params.removeFirst()
|
||||
val argType = getArgumentType(param)
|
||||
val arg = CoreArgumentBuilder.argument<TP, _>(param.name, argType, param.optional)
|
||||
if (params.isEmpty()) {
|
||||
arg.executes { context: CommandContext<TP> -> executeCommand(context) }
|
||||
} else {
|
||||
arg.executes(::executeHelpText)
|
||||
}
|
||||
if (params.isNotEmpty()) {
|
||||
if (getArgNodes(arg, params)) {
|
||||
arg.executes { context: CommandContext<TP> -> executeCommand(context) }
|
||||
}
|
||||
}
|
||||
parent.then(arg)
|
||||
return param.optional
|
||||
}
|
||||
|
||||
if (params.isEmpty() || getArgNodes(node, params.toMutableList())) {
|
||||
node.executes(::executeCommand)
|
||||
}
|
||||
return node.build().coreExecutable() ?: error("Command node should be executable but isn't: $fullPath")
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers all necessary no-op nodes for the given path.
|
||||
*
|
||||
* @param path The full command path
|
||||
* @return The last no-op node that can be used to register the executable node,
|
||||
* the main command node and the last part of the command path (that isn't registered yet)
|
||||
*/
|
||||
private fun registerNodeFromPath(path: String): Pair<CommandNode<TP>, String> {
|
||||
val split = path.split(" ")
|
||||
var parent: CommandNode<TP> = dispatcher.root
|
||||
split.dropLast(1).forEach { part ->
|
||||
val child = parent.getChild(part)
|
||||
if (child == null) parent.addChild(CoreCommandBuilder.literalNoOp<TP, TC>(part) { emptyArray() }
|
||||
.executes(::executeHelpText).build().also { parent = it })
|
||||
else parent = child
|
||||
}
|
||||
return Pair(parent, split.last())
|
||||
}
|
||||
|
||||
fun getCommandList(sender: TP): Array<String> {
|
||||
return commandNodes.filter { it.data.hasPermission(sender) }
|
||||
.map { commandChar + it.data.fullPath }.sorted().toTypedArray()
|
||||
}
|
||||
|
||||
/**
|
||||
* Get parameter data for the given subcommand. Attempts to read it from the commands file, if it fails, it will return generic info.
|
||||
* The first parameter is always the sender both in the methods themselves and in the returned array.
|
||||
*
|
||||
* @param method The method the subcommand is created from
|
||||
* @return Parameter data objects and the sender type
|
||||
* @throws RuntimeException If there is no sender parameter declared in the method
|
||||
*/
|
||||
private fun getCommandParametersAndSender(
|
||||
method: Method,
|
||||
argHelpManager: CommandArgumentHelpManager<TC, TP>
|
||||
): Pair<List<CommandArgument>, Class<*>> {
|
||||
val parameters = method.parameters
|
||||
if (parameters.isEmpty()) throw RuntimeException("No sender parameter for method '$method'")
|
||||
val usage = argHelpManager.getParameterHelpForMethod(method)?.ifEmpty { null }
|
||||
val paramNames = usage?.split(" ")
|
||||
return Pair(
|
||||
parameters.drop(1).zip(paramNames ?: (1 until parameters.size).map { i -> "param$i" })
|
||||
.map { (param, name) ->
|
||||
val numAnn = param.getAnnotation(NumberArg::class.java)
|
||||
CommandArgument(
|
||||
name, param.type,
|
||||
param.isVarArgs || param.isAnnotationPresent(TextArg::class.java),
|
||||
if (numAnn == null) Pair(Double.MIN_VALUE, Double.MAX_VALUE) else Pair(
|
||||
numAnn.lowerLimit,
|
||||
numAnn.upperLimit
|
||||
),
|
||||
param.isAnnotationPresent(OptionalArg::class.java),
|
||||
name, param.annotations.filterNot { it is OptionalArg || it is NumberArg || it is TextArg }.toTypedArray()
|
||||
)
|
||||
}, parameters[0].type
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the Chroma representation of the argument declaration into Brigadier format.
|
||||
* It does part of the command argument type processing.
|
||||
*
|
||||
* @param arg Our representation of the command argument
|
||||
* @return The Brigadier representation of the command argument
|
||||
*/
|
||||
private fun getArgumentType(arg: CommandArgument?): ArgumentType<out Any> {
|
||||
val ptype = arg!!.type
|
||||
val (lowerLimit, upperLimit) = arg.limits
|
||||
return if (arg.greedy) StringArgumentType.greedyString()
|
||||
else if (ptype == String::class.java) StringArgumentType.word()
|
||||
else if (ptype == Int::class.javaPrimitiveType || ptype == Int::class.javaObjectType
|
||||
|| ptype == Byte::class.javaPrimitiveType || ptype == Byte::class.javaObjectType
|
||||
|| ptype == Short::class.javaPrimitiveType || ptype == Short::class.javaObjectType
|
||||
)
|
||||
IntegerArgumentType.integer(lowerLimit.toInt(), upperLimit.toInt())
|
||||
else if (ptype == Long::class.javaPrimitiveType || ptype == Long::class.javaObjectType)
|
||||
LongArgumentType.longArg(lowerLimit.toLong(), upperLimit.toLong())
|
||||
else if (ptype == Float::class.javaPrimitiveType || ptype == Float::class.javaObjectType)
|
||||
FloatArgumentType.floatArg(lowerLimit.toFloat(), upperLimit.toFloat())
|
||||
else if (ptype == Double::class.javaPrimitiveType || ptype == Double::class.javaObjectType)
|
||||
DoubleArgumentType.doubleArg(lowerLimit, upperLimit)
|
||||
else if (ptype == Char::class.javaPrimitiveType || ptype == Char::class.javaObjectType)
|
||||
StringArgumentType.word()
|
||||
else if (ptype == Boolean::class.javaPrimitiveType || ptype == Boolean::class.javaObjectType)
|
||||
BoolArgumentType.bool()
|
||||
else StringArgumentType.word()
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays the help text based on the executed command. Each command node might have a help text stored.
|
||||
* The help text is displayed either because of incorrect usage or it's explicitly requested.
|
||||
*
|
||||
* @param context The command context
|
||||
* @return Vanilla command success level (0)
|
||||
*/
|
||||
private fun executeHelpText(context: CommandContext<TP>): Int { // TODO: Add usage string automatically (and dynamically?)
|
||||
val node = context.nodes.lastOrNull()?.node ?: error("No nodes found when executing help text for ${context.input}!")
|
||||
val helpText = node.subcommandDataNoOp()?.getHelpText(context.source) ?: error("No subcommand data found when executing help text for ${context.input}")
|
||||
if (node.isCommand()) {
|
||||
val subs = getSubcommands(node.coreCommandNoOp()!!)
|
||||
.filter { it.data.hasPermission(context.source) }
|
||||
.map { commandChar + it.data.fullPath }.sorted()
|
||||
val messages = if (subs.isNotEmpty()) {
|
||||
helpText + "${ChatColor.GOLD}---- Subcommands ----" + subs
|
||||
} else {
|
||||
helpText
|
||||
}
|
||||
context.source.sendMessage(messages)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes the command itself by calling the subcommand method associated with the input command node.
|
||||
*
|
||||
* @param context The command context
|
||||
* @return Vanilla command success level (0)
|
||||
*/
|
||||
protected open fun executeCommand(context: CommandContext<TP>): Int {
|
||||
val sd = context.nodes.lastOrNull()?.node?.subcommandData<_, TC>() ?: error("Could not find suitable command node for command ${context.input}")
|
||||
val sender = context.source
|
||||
|
||||
if (!sd.hasPermission(sender)) {
|
||||
CommandUtils.reportUserError(sender, "${ChatColor.RED}You don't have permission to use this command")
|
||||
return 1
|
||||
}
|
||||
// TODO: WIP
|
||||
|
||||
val convertedSender = convertSenderType(sender, sd.senderType)
|
||||
if (convertedSender == null) {
|
||||
//TODO: Should have a prettier display of Command2 classes here
|
||||
val type = sd.senderType.simpleName.fold("") { s, ch -> s + if (ch.isUpperCase()) " " + ch.lowercase() else ch }.trim()
|
||||
CommandUtils.reportUserError(sender, "${ChatColor.RED}You need to be a $type to use this command.")
|
||||
executeHelpText(context) //Send what the command is about, could be useful for commands like /member where some subcommands aren't player-only
|
||||
return 0
|
||||
}
|
||||
|
||||
val params = executeGetArguments(sd, context, sender) ?: return executeHelpText(context)
|
||||
|
||||
// TODO: Varargs support? (colors?)
|
||||
// TODO: Character handling (strlen)
|
||||
|
||||
executeInvokeCommand(sd, sender, convertedSender, params, context)
|
||||
return 0
|
||||
}
|
||||
|
||||
private fun executeGetArguments(sd: SubcommandData<TC, TP>, context: CommandContext<TP>, sender: TP): MutableList<Any?>? {
|
||||
val params = mutableListOf<Any?>()
|
||||
for (argument in sd.argumentsInOrder) {
|
||||
try {
|
||||
if (argument.type.isEasilyRepresentable()) {
|
||||
val userArgument = context.getArgument(argument.name, argument.type)
|
||||
params.add(userArgument)
|
||||
} else {
|
||||
val userArgument = context.getArgument(argument.name, String::class.java)
|
||||
val converter = paramConverters[argument.type]
|
||||
?: error("No suitable converter found for ${argument.type} ${argument.name}")
|
||||
val result = converter.converter.apply(userArgument)
|
||||
if (result == null) {
|
||||
CommandUtils.reportUserError(sender, "${ChatColor.RED}Error: ${converter.errormsg}")
|
||||
return null
|
||||
}
|
||||
params.add(result)
|
||||
}
|
||||
} catch (e: IllegalArgumentException) {
|
||||
if (ChromaUtils.isTest && e.message?.contains("No such argument '${argument.name}' exists on this command") != true) {
|
||||
println("For command ${sd.fullPath}:")
|
||||
e.printStackTrace()
|
||||
}
|
||||
if (argument.optional) {
|
||||
params.add(argument.type.getDefaultForEasilyRepresentable())
|
||||
} else {
|
||||
return null
|
||||
}
|
||||
}
|
||||
}
|
||||
return params
|
||||
}
|
||||
|
||||
/**
|
||||
* Invokes the command method with the given sender and parameters.
|
||||
*/
|
||||
private fun executeInvokeCommand(sd: SubcommandData<TC, TP>, sender: TP, actualSender: Any, params: List<Any?>, context: CommandContext<TP>) {
|
||||
val invokeCommand = {
|
||||
try {
|
||||
val ret = sd.executeCommand(actualSender, *params.toTypedArray())
|
||||
if (ret is Boolean) {
|
||||
if (!ret) //Show usage
|
||||
executeHelpText(context)
|
||||
} else if (ret != null)
|
||||
throw Exception("Wrong return type! Must return a boolean or void. Return value: $ret")
|
||||
} catch (e: InvocationTargetException) {
|
||||
ChromaUtils.throwWhenTested(e.cause ?: e, "An error occurred in a command handler for ${sd.fullPath}!")
|
||||
} catch (e: Exception) {
|
||||
ChromaUtils.throwWhenTested(e, "Command handling failed for sender $sender and subcommand ${sd.fullPath}")
|
||||
}
|
||||
}
|
||||
if (runOnPrimaryThread && !ChromaUtils.isTest)
|
||||
Bukkit.getScheduler().runTask(MainPlugin.instance, invokeCommand)
|
||||
else
|
||||
invokeCommand()
|
||||
}
|
||||
|
||||
abstract fun hasPermission(sender: TP, data: SubcommandData<TC, TP>): Boolean
|
||||
|
||||
/**
|
||||
* Get all registered command nodes. This returns all registered Chroma commands with all the information about them.
|
||||
*
|
||||
* @return A set of command node objects containing the commands
|
||||
*/
|
||||
val commandNodes: Set<CoreExecutableNode<TP, TC>>
|
||||
get() = getSubcommands(true, dispatcher.root).toSet()
|
||||
|
||||
/**
|
||||
* Get a node that belongs to the given command.
|
||||
*
|
||||
* @param command The exact name of the command
|
||||
* @return A command node
|
||||
*/
|
||||
fun getCommandNode(command: String): CoreCommandNode<TP, NoOpSubcommandData>? { // TODO: What should this return? No-op? Executable? What's the use case?
|
||||
return dispatcher.root.getChild(command)?.coreCommand()
|
||||
}
|
||||
|
||||
/**
|
||||
* Unregister all subcommands that were registered with the given command class.
|
||||
*
|
||||
* @param command The command class (object) to unregister
|
||||
*/
|
||||
fun unregisterCommand(command: ICommand2<TP>) {
|
||||
dispatcher.root.children.removeIf { node: CommandNode<TP> -> node.coreExecutable<TP, TC>()?.data?.command === command }
|
||||
}
|
||||
|
||||
/**
|
||||
* Unregisters all commands that match the given predicate.
|
||||
*
|
||||
* @param condition The condition for removing a given command
|
||||
*/
|
||||
fun unregisterCommandIf(condition: Predicate<CoreCommandNode<TP, SubcommandData<TC, TP>>>, nested: Boolean) {
|
||||
unregisterCommandIf(condition, dispatcher.root, nested)
|
||||
}
|
||||
|
||||
private fun unregisterCommandIf(
|
||||
condition: Predicate<CoreCommandNode<TP, SubcommandData<TC, TP>>>,
|
||||
root: CommandNode<TP>,
|
||||
nested: Boolean
|
||||
) {
|
||||
// Can't use getCoreChildren() here because the collection needs to be modifiable
|
||||
if (nested) for (child in root.children)
|
||||
child.coreCommand<_, NoOpSubcommandData>()?.let { unregisterCommandIf(condition, it, true) }
|
||||
root.children.removeIf { node ->
|
||||
node.coreExecutable<TP, TC>()
|
||||
?.let { condition.test(it) }
|
||||
?: node.children.isEmpty()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all subcommands of the specified command. Only returns executable nodes.
|
||||
*
|
||||
* @param mainCommand The command to get the subcommands of
|
||||
* @param deep Whether to get all subcommands recursively or only the direct children
|
||||
*/
|
||||
fun getSubcommands(
|
||||
mainCommand: LiteralCommandNode<TP>,
|
||||
deep: Boolean = true
|
||||
): List<CoreExecutableNode<TP, TC>> {
|
||||
return mainCommand.coreCommand<_, NoOpSubcommandData>()?.let { getSubcommands(deep, it) } ?: emptyList()
|
||||
}
|
||||
|
||||
private fun getSubcommands(
|
||||
deep: Boolean = true,
|
||||
root: CommandNode<TP>
|
||||
): List<CoreExecutableNode<TP, TC>> {
|
||||
return root.children.mapNotNull { it.coreExecutable<TP, TC>() } +
|
||||
if (deep) root.children.flatMap { child -> child.coreCommand<_, NoOpSubcommandData>()?.let { getSubcommands(deep, it) } ?: emptyList() } else emptyList()
|
||||
}
|
||||
}
|
482
Chroma-Core/src/main/java/buttondevteam/lib/chat/Command2MC.java
Normal file
482
Chroma-Core/src/main/java/buttondevteam/lib/chat/Command2MC.java
Normal file
|
@ -0,0 +1,482 @@
|
|||
package buttondevteam.lib.chat;
|
||||
|
||||
import buttondevteam.core.MainPlugin;
|
||||
import buttondevteam.lib.TBMCCoreAPI;
|
||||
import buttondevteam.lib.architecture.ButtonPlugin;
|
||||
import buttondevteam.lib.architecture.Component;
|
||||
import buttondevteam.lib.player.ChromaGamerBase;
|
||||
import com.mojang.brigadier.arguments.*;
|
||||
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
|
||||
import com.mojang.brigadier.builder.RequiredArgumentBuilder;
|
||||
import com.mojang.brigadier.tree.CommandNode;
|
||||
import com.mojang.brigadier.tree.LiteralCommandNode;
|
||||
import lombok.val;
|
||||
import me.lucko.commodore.Commodore;
|
||||
import me.lucko.commodore.CommodoreProvider;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.command.*;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.permissions.Permission;
|
||||
import org.bukkit.permissions.PermissionDefault;
|
||||
import org.javatuples.Triplet;
|
||||
|
||||
import java.lang.annotation.Annotation;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Parameter;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class Command2MC extends Command2<ICommand2MC, Command2MCSender> implements Listener {
|
||||
/**
|
||||
* Don't use directly, use the method in Component and ButtonPlugin to automatically unregister the command when needed.
|
||||
*
|
||||
* @param command The command to register
|
||||
*/
|
||||
@Override
|
||||
public void registerCommand(ICommand2MC command) {
|
||||
/*String mainpath;
|
||||
var plugin = command.getPlugin();
|
||||
{
|
||||
String cpath = command.getCommandPath();
|
||||
int i = cpath.indexOf(' ');
|
||||
mainpath = cpath.substring(0, i == -1 ? cpath.length() : i);
|
||||
}*/
|
||||
var subcmds = super.registerCommand(command, '/');
|
||||
var bcmd = registerOfficially(command, subcmds);
|
||||
if (bcmd != null)
|
||||
for (String alias : bcmd.getAliases())
|
||||
super.registerCommand(command, command.getCommandPath().replaceFirst("^" + bcmd.getName(), Matcher.quoteReplacement(alias)), '/');
|
||||
|
||||
var perm = "chroma.command." + command.getCommandPath().replace(' ', '.');
|
||||
if (Bukkit.getPluginManager().getPermission(perm) == null) //Check needed for plugin reset
|
||||
Bukkit.getPluginManager().addPermission(new Permission(perm,
|
||||
PermissionDefault.TRUE)); //Allow commands by default, it will check mod-only
|
||||
for (val method : command.getClass().getMethods()) {
|
||||
if (!method.isAnnotationPresent(Subcommand.class)) continue;
|
||||
var path = getCommandPath(method.getName(), '.');
|
||||
if (path.length() > 0) {
|
||||
var subperm = perm + path;
|
||||
if (Bukkit.getPluginManager().getPermission(subperm) == null) //Check needed for plugin reset
|
||||
Bukkit.getPluginManager().addPermission(new Permission(subperm,
|
||||
PermissionDefault.TRUE)); //Allow commands by default, it will check mod-only
|
||||
}
|
||||
String pg = permGroup(command, method);
|
||||
if (pg.length() == 0) continue;
|
||||
String permGroup = "chroma." + pg;
|
||||
if (Bukkit.getPluginManager().getPermission(permGroup) == null) //It may occur multiple times
|
||||
Bukkit.getPluginManager().addPermission(new Permission(permGroup,
|
||||
PermissionDefault.OP)); //Do not allow any commands that belong to a group
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasPermission(Command2MCSender sender, ICommand2MC command, Method method) {
|
||||
return hasPermission(sender.getSender(), command, method);
|
||||
}
|
||||
|
||||
public boolean hasPermission(CommandSender sender, ICommand2MC command, Method method) {
|
||||
if (sender instanceof ConsoleCommandSender) return true; //Always allow the console
|
||||
if (command == null) return true; //Allow viewing the command - it doesn't do anything anyway
|
||||
String pg;
|
||||
boolean p = true;
|
||||
var cmdperm = "chroma.command." + command.getCommandPath().replace(' ', '.');
|
||||
var path = getCommandPath(method.getName(), '.');
|
||||
String[] perms = {
|
||||
path.length() > 0 ? cmdperm + path : null,
|
||||
cmdperm,
|
||||
(pg = permGroup(command, method)).length() > 0 ? "chroma." + pg : null
|
||||
};
|
||||
for (String perm : perms) {
|
||||
if (perm != null) {
|
||||
if (p) { //Use OfflinePlayer to avoid fetching player data
|
||||
if (sender instanceof OfflinePlayer)
|
||||
p = MainPlugin.permission.playerHas(sender instanceof Player ? ((Player) sender).getLocation().getWorld().getName() : null, (OfflinePlayer) sender, perm);
|
||||
else
|
||||
p = false; //Use sender's method
|
||||
if (!p) p = sender.hasPermission(perm);
|
||||
} else break; //If any of the permissions aren't granted then don't allow
|
||||
}
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the first group found in the hierarchy starting from the command method <b>or</b> the mod group if <i>any</i></i> of the superclasses are mod only.
|
||||
*
|
||||
* @param method The subcommand to check
|
||||
* @return The permission group for the subcommand or empty string
|
||||
*/
|
||||
private String permGroup(ICommand2MC command, Method method) {
|
||||
if (method != null) {
|
||||
val sc = method.getAnnotation(Subcommand.class);
|
||||
if (sc != null && sc.permGroup().length() > 0) {
|
||||
return sc.permGroup();
|
||||
}
|
||||
}
|
||||
if (getAnnForValue(command.getClass(), CommandClass.class, CommandClass::modOnly, false))
|
||||
return Subcommand.MOD_GROUP;
|
||||
return getAnnForValue(command.getClass(), CommandClass.class, CommandClass::permGroup, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* Loops until it finds a value that is <b>not</b> the same as def
|
||||
*
|
||||
* @param sourceCl The class which has the annotation
|
||||
* @param annCl The annotation to get
|
||||
* @param annMethod The annotation method to check
|
||||
* @param def The value to ignore when looking for the result
|
||||
* @param <T> The annotation type
|
||||
* @param <V> The type of the value
|
||||
* @return The value returned by the first superclass or def
|
||||
*/
|
||||
private <T extends Annotation, V> V getAnnForValue(Class<?> sourceCl, Class<T> annCl, Function<T, V> annMethod, V def) {
|
||||
for (Class<?> cl = sourceCl; cl != null; cl = cl.getSuperclass()) {
|
||||
val cc = cl.getAnnotation(annCl);
|
||||
V r;
|
||||
if (cc != null && (r = annMethod.apply(cc)) != def) return r;
|
||||
}
|
||||
return def;
|
||||
}
|
||||
|
||||
/**
|
||||
* Automatically colors the message red.
|
||||
* {@see super#addParamConverter}
|
||||
*/
|
||||
@Override
|
||||
public <T> void addParamConverter(Class<T> cl, Function<String, T> converter, String errormsg, Supplier<Iterable<String>> allSupplier) {
|
||||
super.addParamConverter(cl, converter, "§c" + errormsg, allSupplier);
|
||||
}
|
||||
|
||||
public void unregisterCommands(ButtonPlugin plugin) {
|
||||
/*var cmds = subcommands.values().stream().map(sd -> sd.command).filter(cmd -> plugin.equals(cmd.getPlugin())).toArray(ICommand2MC[]::new);
|
||||
for (var cmd : cmds)
|
||||
unregisterCommand(cmd);*/
|
||||
subcommands.values().removeIf(sd -> Optional.ofNullable(sd.command).map(ICommand2MC::getPlugin).map(plugin::equals).orElse(false));
|
||||
}
|
||||
|
||||
public void unregisterCommands(Component<?> component) {
|
||||
/*var cmds = subcommands.values().stream().map(sd -> sd.command).filter(cmd -> component.equals(cmd.getComponent())).toArray(ICommand2MC[]::new);
|
||||
for (var cmd : cmds)
|
||||
unregisterCommand(cmd);*/
|
||||
subcommands.values().removeIf(sd -> Optional.ofNullable(sd.command).map(ICommand2MC::getComponent)
|
||||
.map(comp -> component.getClass().getSimpleName().equals(comp.getClass().getSimpleName())).orElse(false));
|
||||
}
|
||||
|
||||
/*@EventHandler
|
||||
public void onTabComplete(TabCompleteEvent event) {
|
||||
try {
|
||||
event.getCompletions().clear(); //Remove player names
|
||||
} catch (UnsupportedOperationException e) {
|
||||
//System.out.println("Tabcomplete: " + event.getBuffer());
|
||||
//System.out.println("First completion: " + event.getCompletions().stream().findFirst().orElse("no completions"));
|
||||
//System.out.println("Listeners: " + Arrays.toString(event.getHandlers().getRegisteredListeners()));
|
||||
}
|
||||
}*/
|
||||
|
||||
@Override
|
||||
public boolean handleCommand(Command2MCSender sender, String commandline) {
|
||||
return handleCommand(sender, commandline, true);
|
||||
}
|
||||
|
||||
private boolean handleCommand(Command2MCSender sender, String commandline, boolean checkPlugin) {
|
||||
int i = commandline.indexOf(' ');
|
||||
String mainpath = commandline.substring(1, i == -1 ? commandline.length() : i); //Without the slash
|
||||
PluginCommand pcmd;
|
||||
if (!checkPlugin
|
||||
|| MainPlugin.Instance.prioritizeCustomCommands.get()
|
||||
|| (pcmd = Bukkit.getPluginCommand(mainpath)) == null //Our commands aren't PluginCommands
|
||||
|| pcmd.getPlugin() instanceof ButtonPlugin) //Unless it's specified in the plugin.yml
|
||||
return super.handleCommand(sender, commandline);
|
||||
else
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean shouldRegisterOfficially = true;
|
||||
|
||||
private Command registerOfficially(ICommand2MC command, List<SubcommandData<ICommand2MC>> subcmds) {
|
||||
if (!shouldRegisterOfficially || command.getPlugin() == null) return null;
|
||||
try {
|
||||
var cmdmap = (SimpleCommandMap) Bukkit.getServer().getClass().getMethod("getCommandMap").invoke(Bukkit.getServer());
|
||||
var path = command.getCommandPath();
|
||||
int x = path.indexOf(' ');
|
||||
var mainPath = path.substring(0, x == -1 ? path.length() : x);
|
||||
Command bukkitCommand;
|
||||
{ //Commands conflicting with Essentials have to be registered in plugin.yml
|
||||
var oldcmd = cmdmap.getCommand(command.getPlugin().getName() + ":" + mainPath); //The label with the fallback prefix is always registered
|
||||
if (oldcmd == null) {
|
||||
bukkitCommand = new BukkitCommand(mainPath);
|
||||
cmdmap.register(command.getPlugin().getName(), bukkitCommand);
|
||||
} else {
|
||||
bukkitCommand = oldcmd;
|
||||
if (bukkitCommand instanceof PluginCommand)
|
||||
((PluginCommand) bukkitCommand).setExecutor(this::executeCommand);
|
||||
}
|
||||
bukkitCommand = oldcmd == null ? new BukkitCommand(mainPath) : oldcmd;
|
||||
}
|
||||
if (CommodoreProvider.isSupported())
|
||||
TabcompleteHelper.registerTabcomplete(command, subcmds, bukkitCommand);
|
||||
return bukkitCommand;
|
||||
} catch (Exception e) {
|
||||
if (command.getComponent() == null)
|
||||
TBMCCoreAPI.SendException("Failed to register command in command map!", e, command.getPlugin());
|
||||
else
|
||||
TBMCCoreAPI.SendException("Failed to register command in command map!", e, command.getComponent());
|
||||
shouldRegisterOfficially = false;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean executeCommand(CommandSender sender, Command command, String label, String[] args) {
|
||||
var user = ChromaGamerBase.getFromSender(sender);
|
||||
if (user == null) {
|
||||
TBMCCoreAPI.SendException("Failed to run Bukkit command for user!", new Throwable("No Chroma user found"), MainPlugin.Instance);
|
||||
sender.sendMessage("§cAn internal error occurred.");
|
||||
return true;
|
||||
}
|
||||
handleCommand(new Command2MCSender(sender, user.channel.get(), sender),
|
||||
("/" + command.getName() + " " + String.join(" ", args)).trim(), false); ///trim(): remove space if there are no args
|
||||
return true;
|
||||
}
|
||||
|
||||
private static class BukkitCommand extends Command {
|
||||
protected BukkitCommand(String name) {
|
||||
super(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean execute(CommandSender sender, String commandLabel, String[] args) {
|
||||
return ButtonPlugin.getCommand2MC().executeCommand(sender, this, commandLabel, args);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> tabComplete(CommandSender sender, String alias, String[] args, Location location) throws IllegalArgumentException {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
}
|
||||
|
||||
private static class TabcompleteHelper {
|
||||
private static Commodore commodore;
|
||||
|
||||
private static LiteralCommandNode<Object> appendSubcommand(String path, CommandNode<Object> parent,
|
||||
SubcommandData<ICommand2MC> subcommand) {
|
||||
LiteralCommandNode<Object> scmd;
|
||||
if ((scmd = (LiteralCommandNode<Object>) parent.getChild(path)) != null)
|
||||
return scmd;
|
||||
var scmdBuilder = LiteralArgumentBuilder.literal(path);
|
||||
if (subcommand != null)
|
||||
scmdBuilder.requires(o -> {
|
||||
var sender = commodore.getBukkitSender(o);
|
||||
return ButtonPlugin.getCommand2MC().hasPermission(sender, subcommand.command, subcommand.method);
|
||||
});
|
||||
scmd = scmdBuilder.build();
|
||||
parent.addChild(scmd);
|
||||
return scmd;
|
||||
}
|
||||
|
||||
private static void registerTabcomplete(ICommand2MC command2MC, List<SubcommandData<ICommand2MC>> subcmds, Command bukkitCommand) {
|
||||
if (commodore == null) {
|
||||
commodore = CommodoreProvider.getCommodore(MainPlugin.Instance); //Register all to the Core, it's easier
|
||||
commodore.register(LiteralArgumentBuilder.literal("un").redirect(RequiredArgumentBuilder.argument("unsomething",
|
||||
StringArgumentType.word()).suggests((context, builder) -> builder.suggest("untest").buildFuture()).build()));
|
||||
}
|
||||
String[] path = command2MC.getCommandPath().split(" ");
|
||||
var shouldRegister = new AtomicBoolean(true);
|
||||
@SuppressWarnings("unchecked") var maincmd = commodore.getRegisteredNodes().stream()
|
||||
.filter(node -> node.getLiteral().equalsIgnoreCase(path[0]))
|
||||
.filter(node -> { shouldRegister.set(false); return true; })
|
||||
.map(node -> (LiteralCommandNode<Object>) node).findAny()
|
||||
.orElseGet(() -> LiteralArgumentBuilder.literal(path[0]).build()); //Commodore 1.8 removes previous nodes
|
||||
var cmd = maincmd;
|
||||
for (int i = 1; i < path.length; i++) {
|
||||
var scmd = subcmds.stream().filter(sd -> sd.method.getName().equals("def")).findAny().orElse(null);
|
||||
cmd = appendSubcommand(path[i], cmd, scmd); //Add each part of the path as a child of the previous one
|
||||
}
|
||||
final var customTCmethods = Arrays.stream(command2MC.getClass().getDeclaredMethods()) //val doesn't recognize the type arguments
|
||||
.flatMap(method -> Stream.of(Optional.ofNullable(method.getAnnotation(CustomTabCompleteMethod.class)))
|
||||
.filter(Optional::isPresent).map(Optional::get) // Java 9 has .stream()
|
||||
.flatMap(ctcm -> {
|
||||
var paths = Optional.of(ctcm.subcommand()).filter(s -> s.length > 0)
|
||||
.orElseGet(() -> new String[]{
|
||||
ButtonPlugin.getCommand2MC().getCommandPath(method.getName(), ' ').trim()
|
||||
});
|
||||
return Arrays.stream(paths).map(name -> new Triplet<>(name, ctcm, method));
|
||||
})).collect(Collectors.toList());
|
||||
for (SubcommandData<ICommand2MC> subcmd : subcmds) {
|
||||
String subpathAsOne = ButtonPlugin.getCommand2MC().getCommandPath(subcmd.method.getName(), ' ').trim();
|
||||
String[] subpath = subpathAsOne.split(" ");
|
||||
CommandNode<Object> scmd = cmd;
|
||||
if (subpath[0].length() > 0) { //If the method is def, it will contain one empty string
|
||||
for (String s : subpath) {
|
||||
scmd = appendSubcommand(s, scmd, subcmd); //Add method name part of the path (could_be_multiple())
|
||||
}
|
||||
}
|
||||
Parameter[] parameters = subcmd.method.getParameters();
|
||||
for (int i = 1; i < parameters.length; i++) { //Skip sender
|
||||
Parameter parameter = parameters[i];
|
||||
ArgumentType<?> type;
|
||||
final Class<?> ptype = parameter.getType();
|
||||
final boolean customParamType;
|
||||
{
|
||||
boolean customParamTypeTemp = false;
|
||||
if (ptype == String.class)
|
||||
if (parameter.isAnnotationPresent(TextArg.class))
|
||||
type = StringArgumentType.greedyString();
|
||||
else
|
||||
type = StringArgumentType.word();
|
||||
else if (ptype == int.class || ptype == Integer.class
|
||||
|| ptype == byte.class || ptype == Byte.class
|
||||
|| ptype == short.class || ptype == Short.class)
|
||||
type = IntegerArgumentType.integer(); //TODO: Min, max
|
||||
else if (ptype == long.class || ptype == Long.class)
|
||||
type = LongArgumentType.longArg();
|
||||
else if (ptype == float.class || ptype == Float.class)
|
||||
type = FloatArgumentType.floatArg();
|
||||
else if (ptype == double.class || ptype == Double.class)
|
||||
type = DoubleArgumentType.doubleArg();
|
||||
else if (ptype == char.class || ptype == Character.class)
|
||||
type = StringArgumentType.word();
|
||||
else if (ptype == boolean.class || ptype == Boolean.class)
|
||||
type = BoolArgumentType.bool();
|
||||
else if (parameter.isVarArgs())
|
||||
type = StringArgumentType.greedyString();
|
||||
else {
|
||||
type = StringArgumentType.word();
|
||||
customParamTypeTemp = true;
|
||||
}
|
||||
customParamType = customParamTypeTemp;
|
||||
}
|
||||
val param = subcmd.parameters[i - 1];
|
||||
val customTC = Optional.ofNullable(parameter.getAnnotation(CustomTabComplete.class))
|
||||
.map(CustomTabComplete::value);
|
||||
var customTCmethod = customTCmethods.stream().filter(t -> subpathAsOne.equalsIgnoreCase(t.getValue0()))
|
||||
.filter(t -> param.replaceAll("[\\[\\]<>]", "").equalsIgnoreCase(t.getValue1().param()))
|
||||
.findAny();
|
||||
var argb = RequiredArgumentBuilder.argument(param, type)
|
||||
.suggests((context, builder) -> {
|
||||
if (parameter.isVarArgs()) { //Do it before the builder is used
|
||||
int nextTokenStart = context.getInput().lastIndexOf(' ') + 1;
|
||||
builder = builder.createOffset(nextTokenStart);
|
||||
}
|
||||
if (customTC.isPresent())
|
||||
for (val ctc : customTC.get())
|
||||
builder.suggest(ctc);
|
||||
boolean ignoreCustomParamType = false;
|
||||
if (customTCmethod.isPresent()) {
|
||||
var tr = customTCmethod.get();
|
||||
if (tr.getValue1().ignoreTypeCompletion())
|
||||
ignoreCustomParamType = true;
|
||||
final var method = tr.getValue2();
|
||||
val params = method.getParameters();
|
||||
val args = new Object[params.length];
|
||||
for (int j = 0, k = 0; j < args.length && k < subcmd.parameters.length; j++) {
|
||||
val paramObj = params[j];
|
||||
if (CommandSender.class.isAssignableFrom(paramObj.getType())) {
|
||||
args[j] = commodore.getBukkitSender(context.getSource());
|
||||
continue;
|
||||
}
|
||||
val paramValueString = context.getArgument(subcmd.parameters[k], String.class);
|
||||
if (paramObj.getType() == String.class) {
|
||||
args[j] = paramValueString;
|
||||
continue;
|
||||
}
|
||||
val converter = getParamConverter(params[j].getType(), command2MC);
|
||||
if (converter == null)
|
||||
break;
|
||||
val paramValue = converter.converter.apply(paramValueString);
|
||||
if (paramValue == null) //For example, the player provided an invalid plugin name
|
||||
break;
|
||||
args[j] = paramValue;
|
||||
k++; //Only increment if not CommandSender
|
||||
}
|
||||
if (args.length == 0 || args[args.length - 1] != null) { //Arguments filled entirely
|
||||
try {
|
||||
val suggestions = method.invoke(command2MC, args);
|
||||
if (suggestions instanceof Iterable) {
|
||||
//noinspection unchecked
|
||||
for (Object suggestion : (Iterable<Object>) suggestions)
|
||||
if (suggestion instanceof String)
|
||||
builder.suggest((String) suggestion);
|
||||
else
|
||||
throw new ClassCastException("Bad return type! It should return an Iterable<String> or a String[].");
|
||||
} else if (suggestions instanceof String[])
|
||||
for (String suggestion : (String[]) suggestions)
|
||||
builder.suggest(suggestion);
|
||||
else
|
||||
throw new ClassCastException("Bad return type! It should return a String[] or an Iterable<String>.");
|
||||
} catch (Exception e) {
|
||||
String msg = "Failed to run tabcomplete method " + method.getName() + " for command " + command2MC.getClass().getSimpleName();
|
||||
if (command2MC.getComponent() == null)
|
||||
TBMCCoreAPI.SendException(msg, e, command2MC.getPlugin());
|
||||
else
|
||||
TBMCCoreAPI.SendException(msg, e, command2MC.getComponent());
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!ignoreCustomParamType && customParamType) {
|
||||
val converter = getParamConverter(ptype, command2MC);
|
||||
if (converter != null) {
|
||||
var suggestions = converter.allSupplier.get();
|
||||
for (String suggestion : suggestions)
|
||||
builder.suggest(suggestion);
|
||||
}
|
||||
}
|
||||
if (ptype == boolean.class || ptype == Boolean.class)
|
||||
builder.suggest("true").suggest("false");
|
||||
final String loweredInput = builder.getRemaining().toLowerCase();
|
||||
return builder.suggest(param).buildFuture().whenComplete((s, e) -> //The list is automatically ordered
|
||||
s.getList().add(s.getList().remove(0))) //So we need to put the <param> at the end after that
|
||||
.whenComplete((ss, e) -> ss.getList().removeIf(s -> {
|
||||
String text = s.getText();
|
||||
return !text.startsWith("<") && !text.startsWith("[") && !text.toLowerCase().startsWith(loweredInput);
|
||||
}));
|
||||
});
|
||||
var arg = argb.build();
|
||||
scmd.addChild(arg);
|
||||
scmd = arg;
|
||||
}
|
||||
}
|
||||
if (shouldRegister.get()) {
|
||||
commodore.register(maincmd);
|
||||
//MinecraftArgumentTypes.getByKey(NamespacedKey.minecraft(""))
|
||||
String pluginName = command2MC.getPlugin().getName().toLowerCase();
|
||||
var prefixedcmd = LiteralArgumentBuilder.literal(pluginName + ":" + path[0])
|
||||
.redirect(maincmd).build();
|
||||
commodore.register(prefixedcmd);
|
||||
for (String alias : bukkitCommand.getAliases()) {
|
||||
commodore.register(LiteralArgumentBuilder.literal(alias).redirect(maincmd).build());
|
||||
commodore.register(LiteralArgumentBuilder.literal(pluginName + ":" + alias).redirect(maincmd).build());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static ParamConverter<?> getParamConverter(Class<?> cl, ICommand2MC command2MC) {
|
||||
val converter = ButtonPlugin.getCommand2MC().paramConverters.get(cl);
|
||||
if (converter == null) {
|
||||
String msg = "Could not find a suitable converter for type " + cl.getSimpleName();
|
||||
Exception exception = new NullPointerException("converter is null");
|
||||
if (command2MC.getComponent() == null)
|
||||
TBMCCoreAPI.SendException(msg, exception, command2MC.getPlugin());
|
||||
else
|
||||
TBMCCoreAPI.SendException(msg, exception, command2MC.getComponent());
|
||||
return null;
|
||||
}
|
||||
return converter;
|
||||
}
|
||||
}
|
|
@ -1,315 +0,0 @@
|
|||
package buttondevteam.lib.chat
|
||||
|
||||
import buttondevteam.core.MainPlugin
|
||||
import buttondevteam.lib.ChromaUtils
|
||||
import buttondevteam.lib.TBMCCoreAPI
|
||||
import buttondevteam.lib.architecture.ButtonPlugin
|
||||
import buttondevteam.lib.architecture.Component
|
||||
import buttondevteam.lib.chat.commands.CommandUtils
|
||||
import buttondevteam.lib.chat.commands.CommandUtils.coreArgument
|
||||
import buttondevteam.lib.chat.commands.MCCommandSettings
|
||||
import buttondevteam.lib.chat.commands.SubcommandData
|
||||
import buttondevteam.lib.player.ChromaGamerBase
|
||||
import buttondevteam.lib.player.TBMCPlayerBase
|
||||
import com.mojang.brigadier.arguments.StringArgumentType
|
||||
import com.mojang.brigadier.builder.LiteralArgumentBuilder.literal
|
||||
import com.mojang.brigadier.builder.RequiredArgumentBuilder
|
||||
import com.mojang.brigadier.builder.RequiredArgumentBuilder.argument
|
||||
import com.mojang.brigadier.tree.LiteralCommandNode
|
||||
import me.lucko.commodore.Commodore
|
||||
import me.lucko.commodore.CommodoreProvider
|
||||
import org.bukkit.Bukkit
|
||||
import org.bukkit.ChatColor
|
||||
import org.bukkit.Location
|
||||
import org.bukkit.command.*
|
||||
import org.bukkit.event.Listener
|
||||
import org.bukkit.permissions.Permission
|
||||
import org.bukkit.permissions.PermissionDefault
|
||||
import java.util.*
|
||||
import java.util.function.Function
|
||||
import java.util.function.Supplier
|
||||
|
||||
class Command2MC : Command2<ICommand2MC, Command2MCSender>('/', true), Listener {
|
||||
/**
|
||||
* Don't use directly, use the method in Component and ButtonPlugin to automatically unregister the command when needed.
|
||||
*
|
||||
* @param command The command to register
|
||||
*/
|
||||
override fun registerCommand(command: ICommand2MC) {
|
||||
val nodes = super.registerCommandSuper(command)
|
||||
val permPrefix = "chroma.command."
|
||||
//Allow commands by default, it will check mod-only
|
||||
for (node in nodes) {
|
||||
val bcmd = registerOfficially(command, node)
|
||||
// TODO: Support aliases
|
||||
val subperm = permPrefix + node.data.fullPath.replace(' ', '.')
|
||||
if (Bukkit.getPluginManager().getPermission(subperm) == null) //Check needed for plugin reset
|
||||
Bukkit.getPluginManager().addPermission(Permission(subperm, PermissionDefault.TRUE))
|
||||
val pg = permGroup(node.data)
|
||||
if (pg.isEmpty()) continue
|
||||
val permGroup = "chroma.$pg"
|
||||
//Do not allow any commands that belong to a group by default
|
||||
if (Bukkit.getPluginManager().getPermission(permGroup) == null) //It may occur multiple times
|
||||
Bukkit.getPluginManager().addPermission(Permission(permGroup, PermissionDefault.OP))
|
||||
}
|
||||
}
|
||||
|
||||
override fun hasPermission(sender: Command2MCSender, data: SubcommandData<ICommand2MC, Command2MCSender>): Boolean {
|
||||
val defWorld = if (ChromaUtils.isTest) "TestWorld" else Bukkit.getWorlds().first().name
|
||||
val check = if (sender.permCheck !is TBMCPlayerBase) ({
|
||||
MainPlugin.permission.groupHas(
|
||||
defWorld,
|
||||
MainPlugin.instance.externalPlayerPermissionGroup.get(),
|
||||
it
|
||||
)
|
||||
})
|
||||
else if (sender.permCheck.isConsole) ({ true }) //Always allow the console
|
||||
else ({ perm: String ->
|
||||
MainPlugin.permission.playerHas(
|
||||
sender.permCheck.player?.location?.world?.name ?: defWorld,
|
||||
sender.permCheck.offlinePlayer,
|
||||
perm
|
||||
)
|
||||
})
|
||||
|
||||
var p = true
|
||||
val cmdperm = "chroma.command.${data.fullPath.replace(' ', '.')}"
|
||||
// TODO: Register a permission for the main command as well - the previous implementation relied on the way the commands were defined
|
||||
val perms = arrayOf(
|
||||
cmdperm,
|
||||
permGroup(data).let { if (it.isEmpty()) null else "chroma.$it" }
|
||||
)
|
||||
for (perm in perms) {
|
||||
if (perm != null) {
|
||||
if (p) { //Use OfflinePlayer to avoid fetching player data
|
||||
p = check(perm)
|
||||
} else break //If any of the permissions aren't granted then don't allow
|
||||
}
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the first group found in the hierarchy starting from the command method **or** the mod group if *any* of the superclasses are mod only.
|
||||
*
|
||||
* @param data The data of the subcommand to check
|
||||
* @return The permission group for the subcommand or empty string
|
||||
*/
|
||||
private fun permGroup(data: SubcommandData<ICommand2MC, Command2MCSender>): String {
|
||||
val group = data.annotations.filterIsInstance<MCCommandSettings>().map {
|
||||
if (it.permGroup.isEmpty() && it.modOnly) MCCommandSettings.MOD_GROUP else "" // TODO: This doesn't seem to return the perm groups themselves
|
||||
}.firstOrNull()
|
||||
return group ?: ""
|
||||
}
|
||||
|
||||
/**
|
||||
* Automatically colors the message red.
|
||||
* {@see super#addParamConverter}
|
||||
*/
|
||||
override fun <T> addParamConverter(
|
||||
cl: Class<T>,
|
||||
converter: Function<String, T?>,
|
||||
errormsg: String,
|
||||
allSupplier: Supplier<Iterable<String>>
|
||||
) {
|
||||
super.addParamConverter(cl, converter, "${ChatColor.RED}$errormsg", allSupplier)
|
||||
}
|
||||
|
||||
override fun convertSenderType(sender: Command2MCSender, senderType: Class<*>): Any? {
|
||||
val original = super.convertSenderType(sender, senderType)
|
||||
if (original != null) {
|
||||
return original
|
||||
}
|
||||
val cg = sender.sender
|
||||
if (senderType.isAssignableFrom(cg.javaClass))
|
||||
return cg
|
||||
// Check Bukkit sender type
|
||||
if (cg is TBMCPlayerBase) {
|
||||
if (senderType.isAssignableFrom(cg.offlinePlayer.javaClass)) return cg.offlinePlayer
|
||||
if (cg.player?.javaClass?.let { senderType.isAssignableFrom(it) } == true) return cg.player
|
||||
}
|
||||
//The command expects a user of our system
|
||||
if (ChromaGamerBase::class.java.isAssignableFrom(senderType)) {
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
return sender.sender.getAs(senderType as Class<out ChromaGamerBase>)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
fun unregisterCommands(plugin: ButtonPlugin) {
|
||||
unregisterCommandIf({ node -> node.data.command.plugin == plugin }, true)
|
||||
}
|
||||
|
||||
fun unregisterCommands(component: Component<*>) {
|
||||
unregisterCommandIf({ node -> node.data.command.component == component }, true)
|
||||
}
|
||||
|
||||
override fun handleCommand(sender: Command2MCSender, commandline: String): Boolean {
|
||||
return handleCommand(sender, commandline, true)
|
||||
}
|
||||
|
||||
private fun handleCommand(sender: Command2MCSender, commandline: String, checkPlugin: Boolean): Boolean {
|
||||
val i = commandline.indexOf(' ')
|
||||
val mainpath = commandline.substring(1, if (i == -1) commandline.length else i) //Without the slash
|
||||
//Our commands aren't PluginCommands, unless it's specified in the plugin.yml
|
||||
// So we need to handle the command if it's not a plugin command or if it's a plugin command, but for a ButtonPlugin
|
||||
return if (!checkPlugin || MainPlugin.instance.prioritizeCustomCommands.get()
|
||||
|| Bukkit.getPluginCommand(mainpath)?.let { it.plugin is ButtonPlugin } != false
|
||||
)
|
||||
super.handleCommand(sender, commandline) else false
|
||||
}
|
||||
|
||||
private var shouldRegisterOfficially = true
|
||||
private fun registerOfficially(command: ICommand2MC, node: CoreCommandNode<Command2MCSender, *>): Command? {
|
||||
return if (!shouldRegisterOfficially) null else try {
|
||||
val cmdmap =
|
||||
Bukkit.getServer().javaClass.getMethod("getCommandMap").invoke(Bukkit.getServer()) as SimpleCommandMap
|
||||
val path = command.commandPath
|
||||
val x = path.indexOf(' ')
|
||||
val mainPath = path.substring(0, if (x == -1) path.length else x)
|
||||
val bukkitCommand: Command
|
||||
//Commands conflicting with Essentials have to be registered in plugin.yml
|
||||
//The label with the fallback prefix is always registered
|
||||
val oldcmd = cmdmap.getCommand("${command.plugin.name}:$mainPath")
|
||||
if (oldcmd == null) {
|
||||
bukkitCommand = BukkitCommand(mainPath)
|
||||
cmdmap.register(command.plugin.name, bukkitCommand)
|
||||
} else {
|
||||
bukkitCommand = oldcmd
|
||||
if (bukkitCommand is PluginCommand) bukkitCommand.setExecutor(this::executeCommand)
|
||||
}
|
||||
TabcompleteHelper.registerTabcomplete(command, node, bukkitCommand)
|
||||
bukkitCommand
|
||||
} catch (e: Exception) {
|
||||
val component = command.component
|
||||
if (component == null)
|
||||
TBMCCoreAPI.SendException("Failed to register command in command map!", e, command.plugin)
|
||||
else
|
||||
TBMCCoreAPI.SendException("Failed to register command in command map!", e, component)
|
||||
shouldRegisterOfficially = false
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
private fun executeCommand(sender: CommandSender, command: Command, label: String, args: Array<String>): Boolean {
|
||||
val user = ChromaGamerBase.getFromSender(sender) // TODO: Senders should only be used for TBMCPlayerBase classes.
|
||||
///trim(): remove space if there are no args
|
||||
handleCommand(
|
||||
Command2MCSender(user as TBMCPlayerBase, user.channel.get(), user),
|
||||
("/${command.name} ${args.joinToString(" ")}").trim { it <= ' ' }, false
|
||||
)
|
||||
return true
|
||||
}
|
||||
|
||||
private class BukkitCommand(name: String) : Command(name) {
|
||||
override fun execute(sender: CommandSender, commandLabel: String, args: Array<String>): Boolean {
|
||||
return ButtonPlugin.command2MC.executeCommand(sender, this, commandLabel, args)
|
||||
}
|
||||
|
||||
@Throws(IllegalArgumentException::class)
|
||||
override fun tabComplete(sender: CommandSender, alias: String, args: Array<String>): List<String> {
|
||||
return emptyList()
|
||||
}
|
||||
|
||||
@Throws(IllegalArgumentException::class)
|
||||
override fun tabComplete(sender: CommandSender, alias: String, args: Array<out String>?, location: Location?): MutableList<String> {
|
||||
return mutableListOf()
|
||||
}
|
||||
}
|
||||
|
||||
private object TabcompleteHelper {
|
||||
private val commodore: Commodore by lazy {
|
||||
val commodore = CommodoreProvider.getCommodore(MainPlugin.instance) //Register all to the Core, it's easier
|
||||
commodore.register(
|
||||
literal<Any?>("un") // TODO: This is a test
|
||||
.redirect(argument<Any?, String>("unsomething", StringArgumentType.word())
|
||||
.suggests { _, builder -> builder.suggest("untest").buildFuture() }.build()
|
||||
)
|
||||
)
|
||||
commodore
|
||||
}
|
||||
|
||||
fun registerTabcomplete(command2MC: ICommand2MC, commandNode: CoreCommandNode<Command2MCSender, *>, bukkitCommand: Command) {
|
||||
if (!CommodoreProvider.isSupported()) {
|
||||
if (ChromaUtils.isTest) {
|
||||
return
|
||||
} else {
|
||||
throw UnsupportedOperationException("Commodore is not supported! Please use 1.14 or higher. Server version: ${Bukkit.getVersion()}")
|
||||
}
|
||||
}
|
||||
// TODO: Allow extending annotation processing for methods and parameters
|
||||
val customTabCompleteMethods = command2MC.javaClass.declaredMethods
|
||||
.flatMap { method ->
|
||||
method.getAnnotation(CustomTabCompleteMethod::class.java)?.let { ctcmAnn ->
|
||||
(ctcmAnn.subcommand.takeIf { it.isNotEmpty() }
|
||||
?: arrayOf(CommandUtils.getCommandPath(method.name, ' ').trim { it <= ' ' }))
|
||||
.map { name -> Triple(name, ctcmAnn, method) }
|
||||
} ?: emptyList()
|
||||
}
|
||||
val mcNode = CommandUtils.mapSubcommands(commandNode) { node ->
|
||||
val builder = node.createBuilder()
|
||||
val argNode = node.coreArgument() ?: return@mapSubcommands builder
|
||||
val subpath = "" // TODO: This needs the same processing as the command path to have the same flexibility
|
||||
val argData = argNode.commandData.arguments[argNode.name] ?: return@mapSubcommands builder
|
||||
val customTCTexts = argData.annotations.filterIsInstance<CustomTabComplete>().flatMap { it.value.asList() }
|
||||
val customTCmethod = customTabCompleteMethods.firstOrNull { (name, ann, _) ->
|
||||
name == subpath && argData.name.replace("[\\[\\]<>]".toRegex(), "") == ann.param
|
||||
}
|
||||
(builder as RequiredArgumentBuilder<Command2MCSender, *>).suggests { context, b ->
|
||||
val sbuilder = if (argData.greedy) { //Do it before the builder is used
|
||||
val nextTokenStart = context.input.lastIndexOf(' ') + 1
|
||||
b.createOffset(nextTokenStart)
|
||||
} else b
|
||||
// Suggest custom tab complete texts
|
||||
for (ctc in customTCTexts) {
|
||||
sbuilder.suggest(ctc)
|
||||
}
|
||||
val ignoreCustomParamType = false // TODO: This should be set by the @CustomTabCompleteMethod annotation
|
||||
// TODO: Custom tab complete method handling
|
||||
if (!ignoreCustomParamType) {
|
||||
val converter = getParamConverter(argData.type, command2MC)
|
||||
if (converter != null) {
|
||||
val suggestions = converter.allSupplier.get()
|
||||
for (suggestion in suggestions) sbuilder.suggest(suggestion)
|
||||
}
|
||||
}
|
||||
if (argData.type === Boolean::class.javaPrimitiveType || argData.type === Boolean::class.javaObjectType)
|
||||
sbuilder.suggest("true").suggest("false")
|
||||
val loweredInput = sbuilder.remaining.lowercase(Locale.getDefault())
|
||||
// The list is automatically ordered, so we need to put the <param> at the end after that
|
||||
// We're also removing all suggestions that don't start with the input
|
||||
sbuilder.suggest(argData.name).buildFuture().whenComplete { ss, _ ->
|
||||
ss.list.add(ss.list.removeAt(0))
|
||||
}.whenComplete { ss, _ ->
|
||||
ss.list.removeIf { s ->
|
||||
s.text.lowercase().let { !it.startsWith("<") && !it.startsWith("[") && !it.startsWith(loweredInput) }
|
||||
}
|
||||
}
|
||||
}
|
||||
builder
|
||||
}
|
||||
|
||||
commodore.register(mcNode as LiteralCommandNode<*>)
|
||||
commodore.register(literal<Command2MCSender>("${command2MC.plugin.name.lowercase()}:${mcNode.name}").redirect(mcNode))
|
||||
for (alias in bukkitCommand.aliases) {
|
||||
commodore.register(literal<Command2MCSender>(alias).redirect(mcNode))
|
||||
commodore.register(literal<Command2MCSender>("${command2MC.plugin.name.lowercase()}:${alias}").redirect(mcNode))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private fun getParamConverter(cl: Class<*>, command2MC: ICommand2MC): ParamConverter<*>? {
|
||||
val converter = ButtonPlugin.command2MC.paramConverters[cl]
|
||||
if (converter == null) {
|
||||
val msg = "Could not find a suitable converter for type " + cl.simpleName
|
||||
val exception: Exception = NullPointerException("converter is null")
|
||||
val component = command2MC.component
|
||||
if (component == null) TBMCCoreAPI.SendException(msg, exception, command2MC.plugin)
|
||||
else TBMCCoreAPI.SendException(msg, exception, component)
|
||||
return null
|
||||
}
|
||||
return converter
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,28 @@
|
|||
package buttondevteam.lib.chat;
|
||||
|
||||
import buttondevteam.core.component.channel.Channel;
|
||||
import lombok.Getter;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.bukkit.command.CommandSender;
|
||||
|
||||
@RequiredArgsConstructor
|
||||
public class Command2MCSender implements Command2Sender {
|
||||
private @Getter final CommandSender sender;
|
||||
private @Getter final Channel channel;
|
||||
private @Getter final CommandSender permCheck;
|
||||
|
||||
@Override
|
||||
public void sendMessage(String message) {
|
||||
sender.sendMessage(message);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendMessage(String[] message) {
|
||||
sender.sendMessage(message);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return sender.getName();
|
||||
}
|
||||
}
|
|
@ -1,20 +0,0 @@
|
|||
package buttondevteam.lib.chat
|
||||
|
||||
import buttondevteam.core.component.channel.Channel
|
||||
import buttondevteam.lib.player.ChromaGamerBase
|
||||
|
||||
open class Command2MCSender(val sender: ChromaGamerBase, val channel: Channel, val permCheck: ChromaGamerBase) : Command2Sender {
|
||||
// TODO: Remove this class and only use the user classes.
|
||||
// TODO: The command context should be stored separately.
|
||||
override fun sendMessage(message: String) {
|
||||
sender.sendMessage(message)
|
||||
}
|
||||
|
||||
override fun sendMessage(message: Array<String>) {
|
||||
sender.sendMessage(message)
|
||||
}
|
||||
|
||||
override fun getName(): String {
|
||||
return sender.name
|
||||
}
|
||||
}
|
|
@ -1,49 +0,0 @@
|
|||
package buttondevteam.lib.chat
|
||||
|
||||
import com.mojang.brigadier.arguments.ArgumentType
|
||||
import com.mojang.brigadier.builder.ArgumentBuilder
|
||||
import com.mojang.brigadier.suggestion.SuggestionProvider
|
||||
|
||||
class CoreArgumentBuilder<S : Command2Sender, T>(
|
||||
private val name: String,
|
||||
private val type: ArgumentType<T>,
|
||||
private val optional: Boolean
|
||||
) : ArgumentBuilder<S, CoreArgumentBuilder<S, T>>() {
|
||||
private var suggestionsProvider: SuggestionProvider<S>? = null
|
||||
fun suggests(provider: SuggestionProvider<S>): CoreArgumentBuilder<S, T> {
|
||||
suggestionsProvider = provider
|
||||
return this
|
||||
}
|
||||
|
||||
override fun getThis(): CoreArgumentBuilder<S, T> {
|
||||
return this
|
||||
}
|
||||
|
||||
override fun build(): CoreArgumentCommandNode<S, T> {
|
||||
val result = CoreArgumentCommandNode(
|
||||
name,
|
||||
type,
|
||||
command,
|
||||
requirement,
|
||||
redirect,
|
||||
redirectModifier,
|
||||
isFork,
|
||||
suggestionsProvider,
|
||||
optional
|
||||
)
|
||||
for (node in arguments) {
|
||||
result.addChild(node)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
override fun then(argument: ArgumentBuilder<S, *>?): CoreArgumentBuilder<S, T> {
|
||||
return super.then(argument)
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun <S : Command2Sender, T> argument(name: String, type: ArgumentType<T>, optional: Boolean): CoreArgumentBuilder<S, T> {
|
||||
return CoreArgumentBuilder(name, type, optional)
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,37 +0,0 @@
|
|||
package buttondevteam.lib.chat
|
||||
|
||||
import buttondevteam.lib.chat.commands.CommandUtils.coreArgument
|
||||
import buttondevteam.lib.chat.commands.SubcommandData
|
||||
import com.mojang.brigadier.Command
|
||||
import com.mojang.brigadier.RedirectModifier
|
||||
import com.mojang.brigadier.arguments.ArgumentType
|
||||
import com.mojang.brigadier.builder.RequiredArgumentBuilder
|
||||
import com.mojang.brigadier.suggestion.SuggestionProvider
|
||||
import com.mojang.brigadier.tree.ArgumentCommandNode
|
||||
import com.mojang.brigadier.tree.CommandNode
|
||||
import java.util.function.Predicate
|
||||
|
||||
class CoreArgumentCommandNode<S : Command2Sender, T>(
|
||||
name: String?, type: ArgumentType<T>?, command: Command<S>?, requirement: Predicate<S>?, redirect: CommandNode<S>?, modifier: RedirectModifier<S>?, forks: Boolean, customSuggestions: SuggestionProvider<S>?,
|
||||
val optional: Boolean
|
||||
) :
|
||||
ArgumentCommandNode<S, T>(name, type, command, requirement, redirect, modifier, forks, customSuggestions) {
|
||||
private var _commandData: SubcommandData<*, S>? = null
|
||||
var commandData: SubcommandData<*, S>
|
||||
get() {
|
||||
return _commandData
|
||||
?: throw UninitializedPropertyAccessException("Command data has not been initialized")
|
||||
}
|
||||
internal set(value) {
|
||||
_commandData = value
|
||||
children.forEach { it.coreArgument()?.commandData = value }
|
||||
}
|
||||
|
||||
override fun getUsageText(): String {
|
||||
return if (optional) "[$name]" else "<$name>"
|
||||
}
|
||||
|
||||
override fun createBuilder(): RequiredArgumentBuilder<S, T> {
|
||||
return super.createBuilder()
|
||||
}
|
||||
}
|
|
@ -1,90 +0,0 @@
|
|||
package buttondevteam.lib.chat
|
||||
|
||||
import buttondevteam.lib.chat.commands.CommandArgument
|
||||
import buttondevteam.lib.chat.commands.CommandUtils.coreArgument
|
||||
import buttondevteam.lib.chat.commands.NoOpSubcommandData
|
||||
import buttondevteam.lib.chat.commands.SubcommandData
|
||||
import com.mojang.brigadier.builder.ArgumentBuilder
|
||||
import com.mojang.brigadier.builder.LiteralArgumentBuilder
|
||||
import java.lang.reflect.Method
|
||||
|
||||
class CoreCommandBuilder<S : Command2Sender, TC : ICommand2<S>, TSD : NoOpSubcommandData> private constructor(
|
||||
literal: String,
|
||||
val data: TSD
|
||||
) : LiteralArgumentBuilder<S>(literal) {
|
||||
|
||||
override fun getThis(): CoreCommandBuilder<S, TC, TSD> {
|
||||
return this
|
||||
}
|
||||
|
||||
override fun build(): CoreCommandNode<S, TSD> {
|
||||
val result = CoreCommandNode<_, _>(
|
||||
literal,
|
||||
command,
|
||||
requirement,
|
||||
this.redirect,
|
||||
this.redirectModifier,
|
||||
this.isFork,
|
||||
data
|
||||
)
|
||||
for (node in arguments) {
|
||||
result.addChild(node)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
override fun then(argument: ArgumentBuilder<S, *>): LiteralArgumentBuilder<S> {
|
||||
super.then(argument)
|
||||
if (data is SubcommandData<*, *>) {
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
arguments.forEach { it.coreArgument()?.commandData = data as SubcommandData<*, S> }
|
||||
}
|
||||
return this
|
||||
}
|
||||
|
||||
companion object {
|
||||
/**
|
||||
* Start building an executable command node.
|
||||
*
|
||||
* @param name The subcommand name as written by the user
|
||||
* @param senderType The expected command sender type based on the subcommand method
|
||||
* @param arguments A map of the command arguments with their names as keys
|
||||
* @param argumentsInOrder A list of the command arguments in the order they are expected
|
||||
* @param command The command object that has this subcommand
|
||||
* @param helpTextGetter Custom help text that can depend on the context. The function receives the sender as the command itself receives it.
|
||||
* @param hasPermission A function that determines whether the user has permission to run this subcommand
|
||||
* @param annotations All annotations implemented by the method that executes the command
|
||||
* @param fullPath The full command path of this subcommand.
|
||||
*/
|
||||
fun <S : Command2Sender, TC : ICommand2<S>> literal(
|
||||
name: String,
|
||||
senderType: Class<*>,
|
||||
arguments: Map<String, CommandArgument>,
|
||||
argumentsInOrder: List<CommandArgument>,
|
||||
command: TC,
|
||||
helpTextGetter: (Any) -> Array<String>,
|
||||
hasPermission: (S, SubcommandData<TC, S>) -> Boolean,
|
||||
annotations: Array<Annotation>,
|
||||
fullPath: String,
|
||||
method: Method
|
||||
): CoreCommandBuilder<S, TC, SubcommandData<TC, S>> {
|
||||
return CoreCommandBuilder(
|
||||
name,
|
||||
SubcommandData(senderType, arguments, argumentsInOrder, command, helpTextGetter, hasPermission, annotations, fullPath, method)
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Start building a no-op command node.
|
||||
*
|
||||
* @param name The subcommand name as written by the user
|
||||
* @param helpTextGetter Custom help text that can depend on the context. The function receives the sender as the command itself receives it.
|
||||
*/
|
||||
fun <S : Command2Sender, TC : ICommand2<S>> literalNoOp(
|
||||
name: String,
|
||||
helpTextGetter: (Any) -> Array<String>,
|
||||
): CoreCommandBuilder<S, TC, NoOpSubcommandData> {
|
||||
return CoreCommandBuilder(name, NoOpSubcommandData(helpTextGetter))
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,22 +0,0 @@
|
|||
package buttondevteam.lib.chat
|
||||
|
||||
import buttondevteam.lib.chat.commands.NoOpSubcommandData
|
||||
import buttondevteam.lib.chat.commands.SubcommandData
|
||||
import com.mojang.brigadier.Command
|
||||
import com.mojang.brigadier.RedirectModifier
|
||||
import com.mojang.brigadier.tree.CommandNode
|
||||
import com.mojang.brigadier.tree.LiteralCommandNode
|
||||
import java.util.function.Predicate
|
||||
|
||||
class CoreCommandNode<T : Command2Sender, TSD : NoOpSubcommandData>(
|
||||
literal: String,
|
||||
command: Command<T>,
|
||||
requirement: Predicate<T>,
|
||||
redirect: CommandNode<T>?,
|
||||
modifier: RedirectModifier<T>?,
|
||||
forks: Boolean,
|
||||
val data: TSD
|
||||
) : LiteralCommandNode<T>(literal, command, requirement, redirect, modifier, forks)
|
||||
|
||||
typealias CoreExecutableNode<TP, TC> = CoreCommandNode<TP, SubcommandData<TC, TP>>
|
||||
typealias CoreNoOpNode<TP> = CoreCommandNode<TP, NoOpSubcommandData>
|
102
Chroma-Core/src/main/java/buttondevteam/lib/chat/ICommand2.java
Normal file
102
Chroma-Core/src/main/java/buttondevteam/lib/chat/ICommand2.java
Normal file
|
@ -0,0 +1,102 @@
|
|||
package buttondevteam.lib.chat;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.val;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.util.function.Function;
|
||||
|
||||
public abstract class ICommand2<TP extends Command2Sender> {
|
||||
/**
|
||||
* Default handler for commands, can be used to copy the args too.
|
||||
*
|
||||
* @param sender The sender which ran the command
|
||||
* @return The success of the command
|
||||
*/
|
||||
public boolean def(TP sender) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convenience method. Return with this.
|
||||
*
|
||||
* @param sender The sender of the command
|
||||
* @param message The message to send to the sender
|
||||
* @return Always true so that the usage isn't shown
|
||||
*/
|
||||
protected boolean respond(TP sender, String message) {
|
||||
sender.sendMessage(message);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return null to not add any help text, return an empty array to only print subcommands.<br>
|
||||
* By default, returns null if the Subcommand annotation is not present and returns an empty array if no help text can be found.
|
||||
*
|
||||
* @param method The method of the subcommand
|
||||
* @return The help text, empty array or null
|
||||
*/
|
||||
public String[] getHelpText(Method method, Command2.Subcommand ann) {
|
||||
val cc = getClass().getAnnotation(CommandClass.class);
|
||||
return ann.helpText().length != 0 || cc == null ? ann.helpText() : cc.helpText(); //If cc is null then it's empty array
|
||||
}
|
||||
|
||||
private final String path;
|
||||
@Getter
|
||||
private final Command2<?, TP> manager; //TIL that if I use a raw type on a variable then none of the type args will work (including what's defined on a method, not on the type)
|
||||
|
||||
public <T extends ICommand2<TP>> ICommand2(Command2<T, TP> manager) {
|
||||
path = getcmdpath();
|
||||
this.manager = manager;
|
||||
}
|
||||
|
||||
/**
|
||||
* The command's path, or name if top-level command.<br>
|
||||
* For example:<br>
|
||||
* "u admin updateplugin" or "u" for the top level one<br>
|
||||
* <u>The path must be lowercase!</u><br>
|
||||
*
|
||||
* @return The command path, <i>which is the command class name by default</i> (removing any "command" from it) - Change via the {@link CommandClass} annotation
|
||||
*/
|
||||
public String getCommandPath() {
|
||||
return path;
|
||||
}
|
||||
|
||||
private static final String[] EMPTY_PATHS = new String[0];
|
||||
|
||||
/**
|
||||
* All of the command's paths it will be invoked on. Does not include aliases or the default path.
|
||||
* Must be lowercase and must include the full path.
|
||||
*
|
||||
* @return The full command paths that this command should be registered under in addition to the default one.
|
||||
*/
|
||||
public String[] getCommandPaths() {
|
||||
return EMPTY_PATHS;
|
||||
}
|
||||
|
||||
private String getcmdpath() {
|
||||
if (!getClass().isAnnotationPresent(CommandClass.class))
|
||||
throw new RuntimeException(
|
||||
"No @CommandClass annotation on command class " + getClass().getSimpleName() + "!");
|
||||
Function<Class<?>, String> getFromClass = cl -> cl.getSimpleName().toLowerCase().replace("commandbase", "") // <-- ...
|
||||
.replace("command", "");
|
||||
String path = getClass().getAnnotation(CommandClass.class).path(),
|
||||
prevpath = path = path.length() == 0 ? getFromClass.apply(getClass()) : path;
|
||||
for (Class<?> cl = getClass().getSuperclass(); cl != null
|
||||
&& !cl.getPackage().getName().equals(ICommand2MC.class.getPackage().getName()); cl = cl
|
||||
.getSuperclass()) { //
|
||||
String newpath;
|
||||
if (!cl.isAnnotationPresent(CommandClass.class)
|
||||
|| (newpath = cl.getAnnotation(CommandClass.class).path()).length() == 0
|
||||
|| newpath.equals(prevpath)) {
|
||||
if ((Modifier.isAbstract(cl.getModifiers()) && !cl.isAnnotationPresent(CommandClass.class))
|
||||
|| cl.getAnnotation(CommandClass.class).excludeFromPath()) // <--
|
||||
continue;
|
||||
newpath = getFromClass.apply(cl);
|
||||
}
|
||||
path = (prevpath = newpath) + " " + path;
|
||||
}
|
||||
return path;
|
||||
}
|
||||
}
|
|
@ -1,100 +0,0 @@
|
|||
package buttondevteam.lib.chat
|
||||
|
||||
import buttondevteam.lib.chat.Command2.Subcommand
|
||||
import java.lang.reflect.Method
|
||||
import java.lang.reflect.Modifier
|
||||
|
||||
/**
|
||||
* This class is used as a base class for all the specific command implementations.
|
||||
* It primarily holds information about the command itself and how it should be run, ideally in a programmer-friendly way.
|
||||
* Any inferred and processed information about this command will be stored in the command manager (Command2*).
|
||||
*
|
||||
* @param TP The sender's type
|
||||
</TP> */
|
||||
abstract class ICommand2<TP : Command2Sender>(val manager: Command2<*, TP>) {
|
||||
/**
|
||||
* Default handler for commands, can be used to copy the args too.
|
||||
*
|
||||
* @param sender The sender which ran the command
|
||||
* @return The success of the command
|
||||
*/
|
||||
open fun def(sender: TP): Boolean {
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* Convenience method. Return with this.
|
||||
*
|
||||
* @param sender The sender of the command
|
||||
* @param message The message to send to the sender
|
||||
* @return Always true so that the usage isn't shown
|
||||
*/
|
||||
@Suppress("unused")
|
||||
protected fun respond(sender: TP, message: String): Boolean {
|
||||
sender.sendMessage(message)
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Return null to not add any help text, return an empty array to only print subcommands.
|
||||
*
|
||||
* By default, returns null if the Subcommand annotation is not present and returns an empty array if no help text can be found.
|
||||
*
|
||||
* @param method The method of the subcommand
|
||||
* @return The help text, empty array or null
|
||||
*/
|
||||
open fun getHelpText(method: Method, ann: Subcommand): Array<String> {
|
||||
val cc = javaClass.getAnnotation(CommandClass::class.java)
|
||||
return if (ann.helpText.isNotEmpty() || cc == null) ann.helpText else cc.helpText //If cc is null then it's empty array
|
||||
}
|
||||
|
||||
/**
|
||||
* The command's path, or name if top-level command.
|
||||
*
|
||||
* For example:
|
||||
*
|
||||
* "u admin updateplugin" or "u" for the top level one
|
||||
*
|
||||
* __The path must be lowercase!__
|
||||
*
|
||||
* @return The command path, *which is the command class name by default* (removing any "command" from it) - Change via the [CommandClass] annotation
|
||||
*/
|
||||
open val commandPath: String = getcmdpath()
|
||||
|
||||
open val commandPaths: Array<String>
|
||||
/**
|
||||
* All of the command's paths it will be invoked on. Does not include aliases or the default path.
|
||||
* Must be lowercase and must include the full path.
|
||||
*
|
||||
* @return The full command paths that this command should be registered under in addition to the default one.
|
||||
*/
|
||||
get() = EMPTY_PATHS // TODO: Deal with this (used for channel IDs)
|
||||
|
||||
private fun getcmdpath(): String {
|
||||
if (!javaClass.isAnnotationPresent(CommandClass::class.java))
|
||||
throw RuntimeException("No @CommandClass annotation on command class ${javaClass.simpleName}!")
|
||||
val classList = mutableListOf<Class<*>>(javaClass)
|
||||
while (true) {
|
||||
val superClass = classList.last().superclass
|
||||
if (superClass != null && superClass.getPackage().name != ICommand2MC::class.java.getPackage().name) {
|
||||
classList.add(superClass)
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
return classList.reversed().associateWith { it.getAnnotation(CommandClass::class.java) }
|
||||
.mapNotNull {
|
||||
if (it.value?.path.isNullOrEmpty())
|
||||
if (it.value?.excludeFromPath ?: Modifier.isAbstract(it.key.modifiers))
|
||||
null
|
||||
else
|
||||
it.key.simpleName.lowercase().removeSuffix("commandbase").removeSuffix("command")
|
||||
else
|
||||
it.value.path
|
||||
}.joinToString(" ")
|
||||
}
|
||||
|
||||
companion object {
|
||||
private val EMPTY_PATHS = emptyArray<String>()
|
||||
}
|
||||
}
|
|
@ -0,0 +1,46 @@
|
|||
package buttondevteam.lib.chat;
|
||||
|
||||
import buttondevteam.lib.architecture.ButtonPlugin;
|
||||
import buttondevteam.lib.architecture.Component;
|
||||
import lombok.Getter;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
@SuppressWarnings("JavadocReference")
|
||||
public abstract class ICommand2MC extends ICommand2<Command2MCSender> {
|
||||
@Getter
|
||||
private ButtonPlugin plugin;
|
||||
@Getter
|
||||
@Nullable
|
||||
private Component<?> component;
|
||||
|
||||
public ICommand2MC() {
|
||||
super(ButtonPlugin.getCommand2MC());
|
||||
}
|
||||
|
||||
/**
|
||||
* Called from {@link buttondevteam.lib.architecture.Component#registerCommand(ICommand2MC)} and {@link ButtonPlugin#registerCommand(ICommand2MC)}
|
||||
*/
|
||||
public void registerToPlugin(ButtonPlugin plugin) {
|
||||
if (this.plugin == null)
|
||||
this.plugin = plugin;
|
||||
else
|
||||
throw new IllegalStateException("The command is already assigned to a plugin!");
|
||||
}
|
||||
|
||||
/**
|
||||
* Called from {@link buttondevteam.lib.architecture.Component#registerCommand(ICommand2MC)}
|
||||
*/
|
||||
public void registerToComponent(Component<?> component) {
|
||||
if (this.component == null)
|
||||
this.component = component;
|
||||
else
|
||||
throw new IllegalStateException("The command is already assigned to a component!");
|
||||
}
|
||||
|
||||
/*@Override
|
||||
public <TX extends ICommand2<Command2MCSender>> void onRegister(Command2<TX, Command2MCSender> manager) {
|
||||
super.onRegister(manager);
|
||||
onRegister((Command2MC) manager); //If ICommand2 is inherited with the same type arg, this would fail but I don't want to add another type param to ICommand2
|
||||
} //For example: class IOffender extends ICommand2<Command2MCSender>*/
|
||||
}
|
|
@ -1,36 +0,0 @@
|
|||
package buttondevteam.lib.chat
|
||||
|
||||
import buttondevteam.lib.architecture.ButtonPlugin
|
||||
import buttondevteam.lib.architecture.ButtonPlugin.Companion.command2MC
|
||||
import buttondevteam.lib.architecture.Component
|
||||
|
||||
abstract class ICommand2MC : ICommand2<Command2MCSender>(command2MC) {
|
||||
private var _plugin: ButtonPlugin? = null
|
||||
var plugin: ButtonPlugin
|
||||
get() = _plugin ?: error("The command is not registered to a Button plugin!")
|
||||
private set(value) {
|
||||
if (_plugin != null) error("The command is already assigned to a Button plugin!")
|
||||
_plugin = value
|
||||
}
|
||||
private var _component: Component<*>? = null
|
||||
var component: Component<*>?
|
||||
get() = _component
|
||||
private set(value) {
|
||||
if (_component != null) error("The command is already assigned to a component!")
|
||||
_component = value
|
||||
}
|
||||
|
||||
/**
|
||||
* Called from [buttondevteam.lib.architecture.Component.registerCommand] and [ButtonPlugin.registerCommand]
|
||||
*/
|
||||
fun registerToPlugin(plugin: ButtonPlugin) {
|
||||
this.plugin = plugin
|
||||
}
|
||||
|
||||
/**
|
||||
* Called from [buttondevteam.lib.architecture.Component.registerCommand]
|
||||
*/
|
||||
fun registerToComponent(component: Component<*>) {
|
||||
this.component = component
|
||||
}
|
||||
}
|
14
Chroma-Core/src/main/java/buttondevteam/lib/chat/Priority.java
Executable file
14
Chroma-Core/src/main/java/buttondevteam/lib/chat/Priority.java
Executable file
|
@ -0,0 +1,14 @@
|
|||
package buttondevteam.lib.chat;
|
||||
|
||||
public enum Priority {
|
||||
Low(0), Normal(1), High(2);
|
||||
private final int val;
|
||||
|
||||
Priority(int v) {
|
||||
val = v;
|
||||
}
|
||||
|
||||
public int GetValue() {
|
||||
return val;
|
||||
}
|
||||
}
|
97
Chroma-Core/src/main/java/buttondevteam/lib/chat/TBMCChatAPI.java
Executable file
97
Chroma-Core/src/main/java/buttondevteam/lib/chat/TBMCChatAPI.java
Executable file
|
@ -0,0 +1,97 @@
|
|||
package buttondevteam.lib.chat;
|
||||
|
||||
import buttondevteam.core.component.channel.Channel;
|
||||
import buttondevteam.core.component.channel.Channel.RecipientTestResult;
|
||||
import buttondevteam.lib.ChromaUtils;
|
||||
import buttondevteam.lib.TBMCChatEvent;
|
||||
import buttondevteam.lib.TBMCChatPreprocessEvent;
|
||||
import buttondevteam.lib.TBMCSystemChatEvent;
|
||||
import lombok.val;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.command.CommandSender;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public class TBMCChatAPI {
|
||||
/**
|
||||
* Sends a chat message to Minecraft. Make sure that the channel is registered with {@link #RegisterChatChannel(Channel)}.<br>
|
||||
* This will also send the error message to the sender, if they can't send the message.
|
||||
*
|
||||
* @param cm The message to send
|
||||
* @return The event cancelled state
|
||||
*/
|
||||
public static boolean SendChatMessage(ChatMessage cm) {
|
||||
return SendChatMessage(cm, cm.getUser().channel.get());
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a chat message to Minecraft. Make sure that the channel is registered with {@link #RegisterChatChannel(Channel)}.<br>
|
||||
* This will also send the error message to the sender, if they can't send the message.
|
||||
*
|
||||
* @param cm The message to send
|
||||
* @param channel The MC channel to send in
|
||||
* @return The event cancelled state
|
||||
*/
|
||||
public static boolean SendChatMessage(ChatMessage cm, Channel channel) {
|
||||
if (!Channel.getChannelList().contains(channel))
|
||||
throw new RuntimeException("Channel " + channel.DisplayName.get() + " not registered!");
|
||||
if (!channel.Enabled.get()) {
|
||||
cm.getSender().sendMessage("§cThe channel '" + channel.DisplayName.get() + "' is disabled!");
|
||||
return true; //Cancel sending if channel is disabled
|
||||
}
|
||||
Supplier<Boolean> task = () -> {
|
||||
val permcheck = cm.getPermCheck();
|
||||
RecipientTestResult rtr = getScoreOrSendError(channel, permcheck);
|
||||
int score = rtr.score;
|
||||
if (score == Channel.SCORE_SEND_NOPE || rtr.groupID == null)
|
||||
return true;
|
||||
TBMCChatPreprocessEvent eventPre = new TBMCChatPreprocessEvent(cm.getSender(), channel, cm.getMessage());
|
||||
Bukkit.getPluginManager().callEvent(eventPre);
|
||||
if (eventPre.isCancelled())
|
||||
return true;
|
||||
cm.setMessage(eventPre.getMessage());
|
||||
TBMCChatEvent event;
|
||||
event = new TBMCChatEvent(channel, cm, rtr);
|
||||
Bukkit.getPluginManager().callEvent(event);
|
||||
return event.isCancelled();
|
||||
};
|
||||
return ChromaUtils.doItAsync(task, false); //Not cancelled if async
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a regular message to Minecraft. Make sure that the channel is registered with {@link #RegisterChatChannel(Channel)}.
|
||||
*
|
||||
* @param channel The channel to send to
|
||||
* @param rtr The score&group to use to find the group - use {@link RecipientTestResult#ALL} if the channel doesn't have scores
|
||||
* @param message The message to send
|
||||
* @param exceptions Platforms where this message shouldn't be sent (same as {@link ChatMessage#getOrigin()}
|
||||
* @return The event cancelled state
|
||||
*/
|
||||
public static boolean SendSystemMessage(Channel channel, RecipientTestResult rtr, String message, TBMCSystemChatEvent.BroadcastTarget target, String... exceptions) {
|
||||
if (!Channel.getChannelList().contains(channel))
|
||||
throw new RuntimeException("Channel " + channel.DisplayName.get() + " not registered!");
|
||||
if (!channel.Enabled.get())
|
||||
return true; //Cancel sending
|
||||
if (!Arrays.asList(exceptions).contains("Minecraft"))
|
||||
Bukkit.getConsoleSender().sendMessage("[" + channel.DisplayName.get() + "] " + message);
|
||||
TBMCSystemChatEvent event = new TBMCSystemChatEvent(channel, message, rtr.score, rtr.groupID, exceptions, target);
|
||||
return ChromaUtils.callEventAsync(event);
|
||||
}
|
||||
|
||||
private static RecipientTestResult getScoreOrSendError(Channel channel, CommandSender sender) {
|
||||
RecipientTestResult result = channel.getRTR(sender);
|
||||
if (result.errormessage != null)
|
||||
sender.sendMessage("§c" + result.errormessage);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a chat channel. See {@link Channel#Channel(String, Color, String, java.util.function.Function)} for details.
|
||||
*
|
||||
* @param channel A new {@link Channel} to register
|
||||
*/
|
||||
public static void RegisterChatChannel(Channel channel) {
|
||||
Channel.RegisterChannel(channel);
|
||||
}
|
||||
}
|
|
@ -1,92 +0,0 @@
|
|||
package buttondevteam.lib.chat
|
||||
|
||||
import buttondevteam.core.component.channel.Channel
|
||||
import buttondevteam.core.component.channel.Channel.Companion.channelList
|
||||
import buttondevteam.core.component.channel.Channel.Companion.registerChannel
|
||||
import buttondevteam.core.component.channel.Channel.RecipientTestResult
|
||||
import buttondevteam.lib.ChromaUtils.callEventAsync
|
||||
import buttondevteam.lib.ChromaUtils.doItAsync
|
||||
import buttondevteam.lib.TBMCChatEvent
|
||||
import buttondevteam.lib.TBMCChatPreprocessEvent
|
||||
import buttondevteam.lib.TBMCSystemChatEvent
|
||||
import buttondevteam.lib.TBMCSystemChatEvent.BroadcastTarget
|
||||
import buttondevteam.lib.player.ChromaGamerBase
|
||||
import org.bukkit.Bukkit
|
||||
import org.bukkit.ChatColor
|
||||
import java.util.function.Supplier
|
||||
|
||||
object TBMCChatAPI {
|
||||
/**
|
||||
* Sends a chat message to Minecraft. Make sure that the channel is registered with [.RegisterChatChannel].
|
||||
*
|
||||
* This will also send the error message to the sender, if they can't send the message.
|
||||
*
|
||||
* @param cm The message to send
|
||||
* @param channel The MC channel to send in
|
||||
* @return The event cancelled state
|
||||
*/
|
||||
@JvmOverloads
|
||||
@JvmStatic
|
||||
fun sendChatMessage(cm: ChatMessage, channel: Channel = cm.user.channel.get()): Boolean {
|
||||
if (!channelList.contains(channel))
|
||||
throw RuntimeException("Channel ${channel.displayName.get()} not registered!")
|
||||
if (!channel.isEnabled.get()) {
|
||||
cm.user.sendMessage("${ChatColor.RED}The channel '${channel.displayName.get()}' is disabled!")
|
||||
return true //Cancel sending if channel is disabled
|
||||
}
|
||||
val task = Supplier {
|
||||
val rtr = getScoreOrSendError(channel, cm.permCheck)
|
||||
val score = rtr.score
|
||||
if (score == Channel.SCORE_SEND_NOPE || rtr.groupID == null) return@Supplier true
|
||||
val eventPre = TBMCChatPreprocessEvent(cm.user, channel, cm.message)
|
||||
Bukkit.getPluginManager().callEvent(eventPre)
|
||||
if (eventPre.isCancelled) return@Supplier true
|
||||
cm.message = eventPre.message
|
||||
val event = TBMCChatEvent(channel, cm, rtr)
|
||||
Bukkit.getPluginManager().callEvent(event)
|
||||
event.isCancelled
|
||||
}
|
||||
return doItAsync(task, false) //Not cancelled if async
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a regular message to Minecraft. Make sure that the channel is registered with [.RegisterChatChannel].
|
||||
*
|
||||
* @param channel The channel to send to
|
||||
* @param rtr The score&group to use to find the group - use [RecipientTestResult.ALL] if the channel doesn't have scores
|
||||
* @param message The message to send
|
||||
* @param exceptions Platforms where this message shouldn't be sent (same as [ChatMessage.origin]
|
||||
* @return The event cancelled state
|
||||
*/
|
||||
@JvmStatic
|
||||
fun SendSystemMessage(
|
||||
channel: Channel,
|
||||
rtr: RecipientTestResult,
|
||||
message: String,
|
||||
target: BroadcastTarget?,
|
||||
vararg exceptions: String
|
||||
): Boolean {
|
||||
if (!channelList.contains(channel)) throw RuntimeException("Channel " + channel.displayName.get() + " not registered!")
|
||||
if (!channel.isEnabled.get()) return true //Cancel sending
|
||||
if (!exceptions.contains("Minecraft")) Bukkit.getConsoleSender()
|
||||
.sendMessage("[" + channel.displayName.get() + "] " + message)
|
||||
val event = TBMCSystemChatEvent(channel, message, rtr.score, rtr.groupID!!, exceptions, target!!)
|
||||
return callEventAsync(event)
|
||||
}
|
||||
|
||||
private fun getScoreOrSendError(channel: Channel, sender: ChromaGamerBase): RecipientTestResult {
|
||||
val result = channel.getRTR(sender)
|
||||
if (result.errormessage != null) sender.sendMessage("${ChatColor.RED}" + result.errormessage)
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a chat channel. See [Channel] for details.
|
||||
*
|
||||
* @param channel A new [Channel] to register
|
||||
*/
|
||||
@JvmStatic
|
||||
fun registerChatChannel(channel: Channel) {
|
||||
registerChannel(channel)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
package buttondevteam.lib.chat;
|
||||
|
||||
public interface TellrawSerializableEnum {
|
||||
String getName();
|
||||
}
|
|
@ -1,14 +0,0 @@
|
|||
package buttondevteam.lib.chat.commands
|
||||
|
||||
/**
|
||||
* A command argument's information to be used to construct the command.
|
||||
*/
|
||||
class CommandArgument(
|
||||
val name: String, // TODO: Remove <> from name and add it where appropriate
|
||||
val type: Class<*>,
|
||||
val greedy: Boolean,
|
||||
val limits: Pair<Double, Double>,
|
||||
val optional: Boolean,
|
||||
val description: String,
|
||||
val annotations: Array<Annotation>
|
||||
)
|
|
@ -1,82 +0,0 @@
|
|||
package buttondevteam.lib.chat.commands
|
||||
|
||||
import buttondevteam.core.MainPlugin
|
||||
import buttondevteam.lib.ChromaUtils
|
||||
import buttondevteam.lib.TBMCCoreAPI
|
||||
import buttondevteam.lib.chat.Command2Sender
|
||||
import buttondevteam.lib.chat.ICommand2
|
||||
import org.bukkit.configuration.ConfigurationSection
|
||||
import org.bukkit.configuration.file.YamlConfiguration
|
||||
import java.io.IOException
|
||||
import java.io.InputStreamReader
|
||||
import java.lang.reflect.Method
|
||||
|
||||
/**
|
||||
* Deals with reading the commands.yml file from the plugin. The file is generated by ButtonProcessor at compile-time.
|
||||
* Only used when registering commands.
|
||||
*
|
||||
* @param command The command object to use
|
||||
*/
|
||||
class CommandArgumentHelpManager<TC : ICommand2<TP>, TP : Command2Sender>(command: TC) {
|
||||
private var commandConfig: ConfigurationSection? = null
|
||||
|
||||
/**
|
||||
* Read the yaml file for the given command class.
|
||||
*/
|
||||
init {
|
||||
val commandClass = command.javaClass
|
||||
// It will load it for each class, but it would be complicated to solve that
|
||||
// Most plugins don't have a lot of command classes anyway
|
||||
try {
|
||||
commandClass.getResourceAsStream("/commands.yml").use { str ->
|
||||
if (str == null) {
|
||||
if (!ChromaUtils.isTest) {
|
||||
ChromaUtils.logWarn("Failed to get command data for $commandClass! No commands.yml file found.")
|
||||
}
|
||||
return@use
|
||||
}
|
||||
val config = YamlConfiguration.loadConfiguration(InputStreamReader(str))
|
||||
commandConfig = config.getConfigurationSection(commandClass.canonicalName.replace('$', '.'))
|
||||
if (commandConfig == null) {
|
||||
MainPlugin.instance.logger.warning("Failed to get command data for $commandClass! Make sure to use 'clean install' when building the project.")
|
||||
}
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
TBMCCoreAPI.SendException("Error while getting command data!", e, MainPlugin.instance)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a parameter help string for the given subcommand method by reading it from the plugin.
|
||||
*
|
||||
* @param method The subcommand method
|
||||
* @return The parameter part of the usage string for the command
|
||||
*/
|
||||
fun getParameterHelpForMethod(method: Method): String? {
|
||||
val cs = commandConfig?.getConfigurationSection(method.name)
|
||||
if (cs == null) {
|
||||
if (!ChromaUtils.isTest) {
|
||||
MainPlugin.instance.logger.warning("Failed to get command data for $method! Make sure to use 'clean install' when building the project.")
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
fun fail(message: String): String? {
|
||||
TBMCCoreAPI.SendException(
|
||||
"Error while getting command data for $method!",
|
||||
Exception(message),
|
||||
MainPlugin.instance
|
||||
)
|
||||
return null
|
||||
}
|
||||
|
||||
val mname = cs.getString("method") ?: return fail("Method is null")
|
||||
val params = cs.getString("params") ?: return fail("Params is null")
|
||||
//Check only the name - the whole method is still stored for backwards compatibility and in case it may be useful
|
||||
val i = mname.indexOf('(')
|
||||
if (i != -1 && method.name == mname.substring(0, i)) {
|
||||
return params
|
||||
} else fail("Method '$method' != $mname")
|
||||
return null
|
||||
}
|
||||
}
|
|
@ -1,117 +0,0 @@
|
|||
package buttondevteam.lib.chat.commands
|
||||
|
||||
import buttondevteam.lib.ChromaUtils
|
||||
import buttondevteam.lib.chat.*
|
||||
import buttondevteam.lib.test.TestCommandFailedException
|
||||
import com.google.common.base.Defaults
|
||||
import com.google.common.primitives.Primitives
|
||||
import com.mojang.brigadier.builder.ArgumentBuilder
|
||||
import com.mojang.brigadier.tree.CommandNode
|
||||
import java.util.*
|
||||
|
||||
object CommandUtils {
|
||||
/**
|
||||
* Returns the path of the given subcommand excluding the class' path. It will start with the given replace char.
|
||||
*
|
||||
* @param methodName The method's name, method.getName()
|
||||
* @param replaceChar The character to use between subcommands
|
||||
* @return The command path starting with the replacement char.
|
||||
*/
|
||||
fun getCommandPath(methodName: String, replaceChar: Char): String {
|
||||
return if (methodName == "def") "" else replaceChar.toString() + methodName.replace('_', replaceChar)
|
||||
.lowercase(Locale.getDefault())
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends the given message (with no additional formatting) to the given sender or throws a special exception during testing.
|
||||
*/
|
||||
fun reportUserError(sender: Command2Sender, message: String) {
|
||||
if (ChromaUtils.isTest) throw TestCommandFailedException(message)
|
||||
else sender.sendMessage(message)
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs the given action on the given node and all of its nodes recursively and creates new nodes.
|
||||
*/
|
||||
fun <S : Command2Sender> mapSubcommands(node: CommandNode<S>, action: (CommandNode<S>) -> ArgumentBuilder<S, *>): CommandNode<S> {
|
||||
val newNode = action(node)
|
||||
node.children.map { mapSubcommands(it, action) }.forEach(newNode::then)
|
||||
return newNode.build()
|
||||
}
|
||||
|
||||
/**
|
||||
* Casts the node to whatever you say if it's a command node. Use responsibly. Returns null if an argument node.
|
||||
*
|
||||
* Command nodes are nodes that are subcommands. They may do something or just print their help text.
|
||||
* They are definitely not argument nodes.
|
||||
*/
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
fun <TP : Command2Sender, TSD : NoOpSubcommandData> CommandNode<TP>.coreCommand(): CoreCommandNode<TP, TSD>? {
|
||||
return if (this.isCommand()) this as CoreCommandNode<TP, TSD>
|
||||
else null
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the node as a probably-not-executable core command node or return null if it's an argument node.
|
||||
*
|
||||
* This method will work for any node as opposed to [CommandUtils.coreCommand].
|
||||
*/
|
||||
fun <TP : Command2Sender> CommandNode<TP>.coreCommandNoOp(): CoreCommandNode<TP, NoOpSubcommandData>? {
|
||||
return coreCommand()
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the node as an executable core command node or returns null if it's a no-op node.
|
||||
*
|
||||
* Executable nodes are valid command nodes that do something other than printing help text.
|
||||
*/
|
||||
fun <TP : Command2Sender, TC : ICommand2<*>> CommandNode<TP>.coreExecutable(): CoreExecutableNode<TP, TC>? {
|
||||
return if (isExecutable()) coreCommand() else null
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the node as an argument node or returns null if it's not one.
|
||||
*
|
||||
* Argument nodes are children of executable command nodes.
|
||||
*/
|
||||
fun <TP : Command2Sender> CommandNode<TP>.coreArgument(): CoreArgumentCommandNode<TP, *>? {
|
||||
return if (this is CoreArgumentCommandNode<*, *>) this as CoreArgumentCommandNode<TP, *> else null
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether the current node is an executable or help text command node.
|
||||
*/
|
||||
fun <TP : Command2Sender> CommandNode<TP>.isCommand(): Boolean {
|
||||
return this is CoreCommandNode<*, *>
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether the current node is an executable command node.
|
||||
*/
|
||||
fun <TP : Command2Sender> CommandNode<TP>.isExecutable(): Boolean {
|
||||
return coreCommand<TP, NoOpSubcommandData>()?.data is SubcommandData<*, *>
|
||||
}
|
||||
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
fun <TP : Command2Sender, TC : ICommand2<TP>> CommandNode<TP>.subcommandData(): SubcommandData<TC, TP>? {
|
||||
return coreArgument()?.commandData as SubcommandData<TC, TP>?
|
||||
?: coreExecutable<TP, TC>()?.data
|
||||
}
|
||||
|
||||
fun <TP : Command2Sender> CommandNode<TP>.subcommandDataNoOp(): NoOpSubcommandData? {
|
||||
return subcommandData() ?: coreCommandNoOp()?.data
|
||||
}
|
||||
|
||||
fun Class<*>.isEasilyRepresentable(): Boolean {
|
||||
return isPrimitive || Number::class.java.isAssignableFrom(this)
|
||||
|| String::class.java.isAssignableFrom(this)
|
||||
}
|
||||
|
||||
fun Class<*>.getDefaultForEasilyRepresentable(): Any? {
|
||||
return if (isPrimitive) {
|
||||
Defaults.defaultValue(this)
|
||||
} else if (Number::class.java.isAssignableFrom(this)) {
|
||||
Defaults.defaultValue(Primitives.unwrap(this))
|
||||
} else null
|
||||
}
|
||||
}
|
|
@ -1,25 +0,0 @@
|
|||
package buttondevteam.lib.chat.commands
|
||||
|
||||
import java.lang.annotation.Inherited
|
||||
|
||||
@Inherited
|
||||
@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION)
|
||||
annotation class MCCommandSettings(
|
||||
/**
|
||||
* The main permission which allows using this command (individual access can be still revoked with "chroma.command.X").
|
||||
* Used to be "tbmc.admin". The [.MOD_GROUP] is provided to use with this.
|
||||
*/
|
||||
val permGroup: String = "",
|
||||
/**
|
||||
* Whether the (sub)command is mod only. This means it requires the chroma.mod permission.
|
||||
* This is just a shorthand for providing MOD_GROUP for permGroup.
|
||||
*/
|
||||
val modOnly: Boolean = false
|
||||
) {
|
||||
companion object {
|
||||
/**
|
||||
* Allowed for OPs only by default
|
||||
*/
|
||||
const val MOD_GROUP = "mod"
|
||||
}
|
||||
}
|
|
@ -1,19 +0,0 @@
|
|||
package buttondevteam.lib.chat.commands
|
||||
|
||||
open class NoOpSubcommandData(
|
||||
/**
|
||||
* Custom help text that depends on the context. Overwrites the static one.
|
||||
* The function receives the sender as the command itself receives it.
|
||||
*/
|
||||
private val helpTextGetter: (Any) -> Array<String>
|
||||
) {
|
||||
/**
|
||||
* Get help text for this subcommand. Returns an empty array if it's not specified.
|
||||
*
|
||||
* @param sender The sender running the command
|
||||
* @return Help text shown to the user
|
||||
*/
|
||||
fun getHelpText(sender: Any): Array<String> {
|
||||
return helpTextGetter(sender)
|
||||
}
|
||||
}
|
|
@ -1,20 +0,0 @@
|
|||
package buttondevteam.lib.chat.commands;
|
||||
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
|
||||
/**
|
||||
* A command argument that can have a number as a value.
|
||||
*/
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface NumberArg {
|
||||
/**
|
||||
* The highest value that can be used for this argument.
|
||||
*/
|
||||
double upperLimit() default Double.POSITIVE_INFINITY;
|
||||
|
||||
/**
|
||||
* The lowest value that can be used for this argument.
|
||||
*/
|
||||
double lowerLimit() default Double.NEGATIVE_INFINITY;
|
||||
}
|
|
@ -1,83 +0,0 @@
|
|||
package buttondevteam.lib.chat.commands
|
||||
|
||||
import buttondevteam.lib.chat.Command2Sender
|
||||
import buttondevteam.lib.chat.ICommand2
|
||||
import java.lang.reflect.Method
|
||||
|
||||
/**
|
||||
* Stores information about the subcommand that can be used to construct the Brigadier setup and to get information while executing the command.
|
||||
*
|
||||
* @param TC Command class type
|
||||
* @param TP Command sender type
|
||||
*/
|
||||
class SubcommandData<TC : ICommand2<*>, TP : Command2Sender>(
|
||||
/**
|
||||
* The type of the sender running the command.
|
||||
* The actual sender type may not be represented by Command2Sender (TP).
|
||||
* In that case it has to match the expected type.
|
||||
*/
|
||||
val senderType: Class<*>,
|
||||
|
||||
/**
|
||||
* Command arguments collected from the subcommand method.
|
||||
* Used to construct the arguments for Brigadier and to hold extra information.
|
||||
*/
|
||||
val arguments: Map<String, CommandArgument>,
|
||||
|
||||
/**
|
||||
* Command arguments in the order they appear in code and in game.
|
||||
*/
|
||||
val argumentsInOrder: List<CommandArgument>,
|
||||
|
||||
/**
|
||||
* The original command class that this data belongs to.
|
||||
*/
|
||||
val command: TC,
|
||||
/**
|
||||
* Custom help text that depends on the context. Overwrites the static one.
|
||||
* The function receives the sender as the command itself receives it.
|
||||
*/
|
||||
helpTextGetter: (Any) -> Array<String>,
|
||||
|
||||
/**
|
||||
* A function that determines whether the user has permission to run this subcommand.
|
||||
*/
|
||||
private val permissionCheck: (TP, SubcommandData<TC, TP>) -> Boolean,
|
||||
|
||||
/**
|
||||
* All annotations implemented by the method that executes the command. Can be used to add custom metadata when implementing a platform.
|
||||
*/
|
||||
val annotations: Array<Annotation>,
|
||||
|
||||
/**
|
||||
* The space-separated full command path of this subcommand.
|
||||
*/
|
||||
val fullPath: String,
|
||||
|
||||
/**
|
||||
* The method to run when executing the command.
|
||||
*/
|
||||
private val method: Method
|
||||
) : NoOpSubcommandData(helpTextGetter) {
|
||||
|
||||
/**
|
||||
* Check if the user has permission to execute this subcommand.
|
||||
*
|
||||
* @param sender The sender running the command
|
||||
* @return Whether the user has permission
|
||||
*/
|
||||
fun hasPermission(sender: TP): Boolean {
|
||||
return permissionCheck(sender, this)
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the command and return the result. Doesn't perform any checks.
|
||||
*
|
||||
* @param sender The actual sender as expected by the method
|
||||
* @param args The rest of the method args
|
||||
*/
|
||||
fun executeCommand(sender: Any, vararg args: Any?): Any? {
|
||||
method.isAccessible = true
|
||||
return method.invoke(command, sender, *args)
|
||||
}
|
||||
}
|
316
Chroma-Core/src/main/java/buttondevteam/lib/player/ChromaGamerBase.java
Executable file
316
Chroma-Core/src/main/java/buttondevteam/lib/player/ChromaGamerBase.java
Executable file
|
@ -0,0 +1,316 @@
|
|||
package buttondevteam.lib.player;
|
||||
|
||||
import buttondevteam.core.MainPlugin;
|
||||
import buttondevteam.core.component.channel.Channel;
|
||||
import buttondevteam.lib.TBMCCoreAPI;
|
||||
import buttondevteam.lib.architecture.ConfigData;
|
||||
import buttondevteam.lib.architecture.IHaveConfig;
|
||||
import lombok.Getter;
|
||||
import lombok.val;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import java.io.File;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
@ChromaGamerEnforcer
|
||||
public abstract class ChromaGamerBase {
|
||||
private static final String TBMC_PLAYERS_DIR = "TBMC/players/";
|
||||
private static final ArrayList<Function<CommandSender, ? extends Optional<? extends ChromaGamerBase>>> senderConverters = new ArrayList<>();
|
||||
/**
|
||||
* Holds data per user class
|
||||
*/
|
||||
private static final HashMap<Class<? extends ChromaGamerBase>, StaticUserData<?>> staticDataMap = new HashMap<>();
|
||||
|
||||
/**
|
||||
* Use {@link #getConfig()} where possible; the 'id' must be always set
|
||||
*/
|
||||
//protected YamlConfiguration plugindata;
|
||||
|
||||
@Getter
|
||||
protected final IHaveConfig config = new IHaveConfig(this::save);
|
||||
protected CommonUserData<?> commonUserData;
|
||||
|
||||
/**
|
||||
* Used for connecting with every type of user ({@link #connectWith(ChromaGamerBase)}) and to init the configs.
|
||||
*/
|
||||
public static <T extends ChromaGamerBase> void RegisterPluginUserClass(Class<T> userclass, Supplier<T> constructor) {
|
||||
Class<? extends T> cl;
|
||||
String folderName;
|
||||
if (userclass.isAnnotationPresent(UserClass.class)) {
|
||||
cl = userclass;
|
||||
folderName = userclass.getAnnotation(UserClass.class).foldername();
|
||||
} else if (userclass.isAnnotationPresent(AbstractUserClass.class)) {
|
||||
var ucl = userclass.getAnnotation(AbstractUserClass.class).prototype();
|
||||
if (!userclass.isAssignableFrom(ucl))
|
||||
throw new RuntimeException("The prototype class (" + ucl.getSimpleName() + ") must be a subclass of the userclass parameter (" + userclass.getSimpleName() + ")!");
|
||||
//noinspection unchecked
|
||||
cl = (Class<? extends T>) ucl;
|
||||
folderName = userclass.getAnnotation(AbstractUserClass.class).foldername();
|
||||
} else // <-- Really important
|
||||
throw new RuntimeException("Class not registered as a user class! Use @UserClass or TBMCPlayerBase");
|
||||
var sud = new StaticUserData<T>(folderName);
|
||||
sud.getConstructors().put(cl, constructor);
|
||||
sud.getConstructors().put(userclass, constructor); // Alawys register abstract and prototype class (TBMCPlayerBase and TBMCPlayer)
|
||||
staticDataMap.put(userclass, sud);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the folder name for the given player class.
|
||||
*
|
||||
* @param cl The class to get the folder from (like {@link TBMCPlayerBase} or one of it's subclasses)
|
||||
* @return The folder name for the given type
|
||||
* @throws RuntimeException If the class doesn't have the {@link UserClass} annotation.
|
||||
*/
|
||||
public static <T extends ChromaGamerBase> String getFolderForType(Class<T> cl) {
|
||||
if (cl.isAnnotationPresent(UserClass.class))
|
||||
return cl.getAnnotation(UserClass.class).foldername();
|
||||
else if (cl.isAnnotationPresent(AbstractUserClass.class))
|
||||
return cl.getAnnotation(AbstractUserClass.class).foldername();
|
||||
throw new RuntimeException("Class not registered as a user class! Use @UserClass or @AbstractUserClass");
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the player class for the given folder name.
|
||||
*
|
||||
* @param foldername The folder to get the class from (like "minecraft")
|
||||
* @return The type for the given folder name or null if not found
|
||||
*/
|
||||
public static Class<? extends ChromaGamerBase> getTypeForFolder(String foldername) {
|
||||
synchronized (staticDataMap) {
|
||||
return staticDataMap.entrySet().stream().filter(e -> e.getValue().getFolder().equalsIgnoreCase(foldername))
|
||||
.map(Map.Entry::getKey).findAny().orElse(null);
|
||||
}
|
||||
}
|
||||
|
||||
/***
|
||||
* Retrieves a user from cache or loads it from disk.
|
||||
*
|
||||
* @param fname Filename without .yml, the user's identifier for that type
|
||||
* @param cl User class
|
||||
* @return The user object
|
||||
*/
|
||||
public static synchronized <T extends ChromaGamerBase> T getUser(String fname, Class<T> cl) {
|
||||
StaticUserData<?> staticUserData = null;
|
||||
for (var sud : staticDataMap.entrySet()) {
|
||||
if (sud.getKey().isAssignableFrom(cl)) {
|
||||
staticUserData = sud.getValue();
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (staticUserData == null)
|
||||
throw new RuntimeException("User class not registered! Use @UserClass or @AbstractUserClass");
|
||||
var commonUserData = staticUserData.getUserDataMap().get(fname);
|
||||
if (commonUserData == null) {
|
||||
final String folder = staticUserData.getFolder();
|
||||
final File file = new File(TBMC_PLAYERS_DIR + folder, fname + ".yml");
|
||||
file.getParentFile().mkdirs();
|
||||
var playerData = YamlConfiguration.loadConfiguration(file);
|
||||
commonUserData = new CommonUserData<>(playerData);
|
||||
playerData.set(staticUserData.getFolder() + "_id", fname);
|
||||
staticUserData.getUserDataMap().put(fname, commonUserData);
|
||||
}
|
||||
if (commonUserData.getUserCache().containsKey(cl))
|
||||
return (T) commonUserData.getUserCache().get(cl);
|
||||
T obj;
|
||||
if (staticUserData.getConstructors().containsKey(cl))
|
||||
//noinspection unchecked
|
||||
obj = (T) staticUserData.getConstructors().get(cl).get();
|
||||
else {
|
||||
try {
|
||||
obj = cl.getConstructor().newInstance();
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Failed to create new instance of user of type " + cl.getSimpleName() + "!", e);
|
||||
}
|
||||
}
|
||||
obj.commonUserData = commonUserData;
|
||||
obj.init();
|
||||
obj.scheduleUncache();
|
||||
return obj;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a converter to the start of the list.
|
||||
*
|
||||
* @param converter The converter that returns an object corresponding to the sender or null, if it's not the right type.
|
||||
*/
|
||||
public static <T extends ChromaGamerBase> void addConverter(Function<CommandSender, Optional<T>> converter) {
|
||||
senderConverters.add(0, converter);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get from the given sender. the object's type will depend on the sender's type. May be null, but shouldn't be.
|
||||
*
|
||||
* @param sender The sender to use
|
||||
* @return A user as returned by a converter or null if none can supply it
|
||||
*/
|
||||
public static ChromaGamerBase getFromSender(CommandSender sender) {
|
||||
for (val converter : senderConverters) {
|
||||
val ocg = converter.apply(sender);
|
||||
if (ocg.isPresent())
|
||||
return ocg.get();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static void saveUsers() {
|
||||
synchronized (staticDataMap) {
|
||||
for (var sud : staticDataMap.values())
|
||||
for (var cud : sud.getUserDataMap().values())
|
||||
ConfigData.saveNow(cud.getPlayerData()); //Calls save()
|
||||
}
|
||||
}
|
||||
|
||||
protected void init() {
|
||||
config.reset(commonUserData.getPlayerData());
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves the player. It'll handle all exceptions that may happen. Called automatically.
|
||||
*/
|
||||
protected void save() {
|
||||
try {
|
||||
if (commonUserData.getPlayerData().getKeys(false).size() > 0)
|
||||
commonUserData.getPlayerData().save(new File(TBMC_PLAYERS_DIR + getFolder(), getFileName() + ".yml"));
|
||||
} catch (Exception e) {
|
||||
TBMCCoreAPI.SendException("Error while saving player to " + getFolder() + "/" + getFileName() + ".yml!", e, MainPlugin.Instance);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the user from the cache. This will be called automatically after some time by default.
|
||||
*/
|
||||
public void uncache() {
|
||||
final var userCache = commonUserData.getUserCache();
|
||||
//noinspection SynchronizationOnLocalVariableOrMethodParameter
|
||||
synchronized (userCache) {
|
||||
if (userCache.containsKey(getClass()))
|
||||
if (userCache.remove(getClass()) != this)
|
||||
throw new IllegalStateException("A different player instance was cached!");
|
||||
}
|
||||
}
|
||||
|
||||
protected void scheduleUncache() {
|
||||
Bukkit.getScheduler().runTaskLaterAsynchronously(MainPlugin.Instance, this::uncache, 2 * 60 * 60 * 20); //2 hours
|
||||
}
|
||||
|
||||
/**
|
||||
* Connect two accounts. Do not use for connecting two Minecraft accounts or similar. Also make sure you have the "id" tag set.
|
||||
*
|
||||
* @param user The account to connect with
|
||||
*/
|
||||
public final <T extends ChromaGamerBase> void connectWith(T user) {
|
||||
// Set the ID, go through all linked files and connect them as well
|
||||
final String ownFolder = getFolder();
|
||||
final String userFolder = user.getFolder();
|
||||
if (ownFolder.equalsIgnoreCase(userFolder))
|
||||
throw new RuntimeException("Do not connect two accounts of the same type! Type: " + ownFolder);
|
||||
var ownData = commonUserData.getPlayerData();
|
||||
var userData = user.commonUserData.getPlayerData();
|
||||
userData.set(ownFolder + "_id", ownData.getString(ownFolder + "_id"));
|
||||
ownData.set(userFolder + "_id", userData.getString(userFolder + "_id"));
|
||||
config.signalChange();
|
||||
user.config.signalChange();
|
||||
Consumer<YamlConfiguration> sync = sourcedata -> {
|
||||
final String sourcefolder = sourcedata == ownData ? ownFolder : userFolder;
|
||||
final String id = sourcedata.getString(sourcefolder + "_id");
|
||||
for (val entry : staticDataMap.entrySet()) { // Set our ID in all files we can find, both from our connections and the new ones
|
||||
if (entry.getKey() == getClass() || entry.getKey() == user.getClass())
|
||||
continue;
|
||||
var entryFolder = entry.getValue().getFolder();
|
||||
final String otherid = sourcedata.getString(entryFolder + "_id");
|
||||
if (otherid == null)
|
||||
continue;
|
||||
ChromaGamerBase cg = getUser(otherid, entry.getKey());
|
||||
var cgData = cg.commonUserData.getPlayerData();
|
||||
cgData.set(sourcefolder + "_id", id); // Set new IDs
|
||||
for (val item : staticDataMap.entrySet()) {
|
||||
var itemFolder = item.getValue().getFolder();
|
||||
if (sourcedata.contains(itemFolder + "_id")) {
|
||||
cgData.set(itemFolder + "_id", sourcedata.getString(itemFolder + "_id")); // Set all existing IDs
|
||||
}
|
||||
}
|
||||
cg.config.signalChange();
|
||||
}
|
||||
};
|
||||
sync.accept(ownData);
|
||||
sync.accept(userData);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the ID for the T typed player object connected with this one or null if no connection found.
|
||||
*
|
||||
* @param cl The player class to get the ID from
|
||||
* @return The ID or null if not found
|
||||
*/
|
||||
public final <T extends ChromaGamerBase> String getConnectedID(Class<T> cl) {
|
||||
return commonUserData.getPlayerData().getString(getFolderForType(cl) + "_id");
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a player instance of the given type that represents the same player. This will return a new instance unless the player is cached.<br>
|
||||
* If the class is a subclass of the current class then the same ID is used, otherwise, a connected ID is used, if found.
|
||||
*
|
||||
* @param cl The target player class
|
||||
* @return The player as a {@link T} object or null if the user doesn't have an account there
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
@Nullable
|
||||
public final <T extends ChromaGamerBase> T getAs(Class<T> cl) {
|
||||
if (cl.getSimpleName().equals(getClass().getSimpleName()))
|
||||
return (T) this;
|
||||
String newfolder = getFolderForType(cl);
|
||||
if (newfolder == null)
|
||||
throw new RuntimeException("The specified class " + cl.getSimpleName() + " isn't registered!");
|
||||
if (newfolder.equals(getFolder())) // If in the same folder, the same filename is used
|
||||
return getUser(getFileName(), cl);
|
||||
var playerData = commonUserData.getPlayerData();
|
||||
if (!playerData.contains(newfolder + "_id"))
|
||||
return null;
|
||||
return getUser(playerData.getString(newfolder + "_id"), cl);
|
||||
}
|
||||
|
||||
/**
|
||||
* This method returns the filename for this player data. For example, for Minecraft-related data, MC UUIDs, for Discord data, Discord IDs, etc.<br>
|
||||
* <b>Does not include .yml</b>
|
||||
*/
|
||||
public final String getFileName() {
|
||||
return commonUserData.getPlayerData().getString(getFolder() + "_id");
|
||||
}
|
||||
|
||||
/**
|
||||
* This method returns the folder that this player data is stored in. For example: "minecraft".
|
||||
*/
|
||||
public final String getFolder() {
|
||||
return getFolderForType(getClass());
|
||||
}
|
||||
|
||||
/**
|
||||
* Get player information. This method calls the {@link TBMCPlayerGetInfoEvent} to get all the player information across the TBMC plugins.
|
||||
*
|
||||
* @param target The {@link InfoTarget} to return the info for.
|
||||
* @return The player information.
|
||||
*/
|
||||
public final String getInfo(InfoTarget target) {
|
||||
TBMCPlayerGetInfoEvent event = new TBMCPlayerGetInfoEvent(this, target);
|
||||
Bukkit.getServer().getPluginManager().callEvent(event);
|
||||
return event.getResult();
|
||||
}
|
||||
|
||||
public enum InfoTarget {
|
||||
MCHover, MCCommand, Discord
|
||||
}
|
||||
|
||||
//-----------------------------------------------------------------
|
||||
|
||||
public final ConfigData<Channel> channel = config.getData("channel", Channel.GlobalChat,
|
||||
id -> Channel.getChannels().filter(ch -> ch.ID.equalsIgnoreCase((String) id)).findAny().orElse(null), ch -> ch.ID);
|
||||
}
|
|
@ -1,337 +0,0 @@
|
|||
package buttondevteam.lib.player
|
||||
|
||||
import buttondevteam.core.MainPlugin
|
||||
import buttondevteam.core.component.channel.Channel
|
||||
import buttondevteam.core.component.channel.Channel.Companion.getChannels
|
||||
import buttondevteam.lib.TBMCCoreAPI
|
||||
import buttondevteam.lib.architecture.ConfigData.Companion.saveNow
|
||||
import buttondevteam.lib.architecture.IHaveConfig
|
||||
import buttondevteam.lib.chat.Command2Sender
|
||||
import org.bukkit.Bukkit
|
||||
import org.bukkit.command.CommandSender
|
||||
import org.bukkit.configuration.file.YamlConfiguration
|
||||
import java.io.File
|
||||
import java.util.*
|
||||
import java.util.function.Function
|
||||
import java.util.function.Supplier
|
||||
|
||||
@ChromaGamerEnforcer
|
||||
abstract class ChromaGamerBase : Command2Sender {
|
||||
val config: IHaveConfig = IHaveConfig({ save() }, null)
|
||||
|
||||
protected lateinit var commonUserData: CommonUserData<out ChromaGamerBase>
|
||||
protected open fun initConfig() {
|
||||
config.reload(commonUserData.playerData)
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves the player. It'll handle all exceptions that may happen. Called automatically.
|
||||
*/
|
||||
protected open fun save() {
|
||||
try {
|
||||
if (commonUserData.playerData.getKeys(false).size > 0)
|
||||
commonUserData.playerData.save(File(TBMC_PLAYERS_DIR + folder, "$fileName.yml"))
|
||||
} catch (e: Exception) {
|
||||
TBMCCoreAPI.SendException("Error while saving player to $folder/$fileName.yml!", e, MainPlugin.instance)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the user from the cache. This will be called automatically after some time by default.
|
||||
*/
|
||||
fun uncache() {
|
||||
val userCache = commonUserData.userCache
|
||||
synchronized(userCache) {
|
||||
if (userCache.containsKey(javaClass))
|
||||
check(userCache.remove(javaClass) === this) { "A different player instance was cached!" }
|
||||
}
|
||||
}
|
||||
|
||||
protected open fun scheduleUncache() {
|
||||
Bukkit.getScheduler().runTaskLaterAsynchronously(
|
||||
MainPlugin.instance,
|
||||
Runnable { uncache() },
|
||||
(2 * 60 * 60 * 20).toLong()
|
||||
) //2 hours
|
||||
}
|
||||
|
||||
/**
|
||||
* Connect two accounts. Do not use for connecting two Minecraft accounts or similar. Also make sure you have the "id" tag set.
|
||||
*
|
||||
* @param user The account to connect with
|
||||
*/
|
||||
fun <T : ChromaGamerBase> connectWith(user: T) {
|
||||
synchronized(staticDataMap) {
|
||||
// Set the ID, go through all linked files and connect them as well
|
||||
if (folder.equals(user.folder, ignoreCase = true))
|
||||
throw RuntimeException("Do not connect two accounts of the same type! Type: $folder")
|
||||
// This method acts from the point of view of the source, the target is the other way around
|
||||
fun sync(us: ChromaGamerBase, them: ChromaGamerBase) {
|
||||
val ourData = us.commonUserData.playerData
|
||||
// Iterate through the target and their connections and set all our IDs in them
|
||||
for (theirOtherClass in registeredClasses) {
|
||||
// Skip our own class because we have the IDs
|
||||
if (theirOtherClass == javaClass) continue
|
||||
val theirConnected = them.getAs(theirOtherClass) ?: continue
|
||||
val theirConnectedData = theirConnected.commonUserData.playerData
|
||||
// Set new IDs
|
||||
for (ourOtherFolder in registeredFolders) {
|
||||
if (ourData.contains(ourOtherFolder + "_id")) {
|
||||
theirConnectedData[ourOtherFolder + "_id"] =
|
||||
ourData.getString(ourOtherFolder + "_id") // Set all existing IDs
|
||||
}
|
||||
}
|
||||
theirConnected.config.signalChange()
|
||||
}
|
||||
}
|
||||
sync(this, user)
|
||||
sync(user, this)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the ID for the T typed player object connected with this one or null if no connection found.
|
||||
*
|
||||
* @param cl The player class to get the ID from
|
||||
* @return The ID or null if not found
|
||||
*/
|
||||
fun getConnectedID(cl: Class<out ChromaGamerBase>): String? {
|
||||
return getConnectedID(getStaticData(cl).folder)
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the ID for the given user type folder connected with this one or null if no connection found.
|
||||
*
|
||||
* @param folder The player type folder to get the ID from
|
||||
* @return The ID or null if not found
|
||||
*/
|
||||
fun getConnectedID(folder: String): String? {
|
||||
return commonUserData.playerData.getString(folder + "_id")
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a player instance of the given type that represents the same player. This will return a new instance unless the player is cached.
|
||||
*
|
||||
* If the class is a subclass of the current class then the same ID is used, otherwise, a connected ID is used, if found.
|
||||
*
|
||||
* @param cl The target player class
|
||||
* @return The player as a [T] object or null if the user doesn't have an account there
|
||||
*/
|
||||
fun <T : ChromaGamerBase> getAs(cl: Class<T>): T? {
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
if (cl.simpleName == javaClass.simpleName) return this as T
|
||||
val data = getStaticData(cl)
|
||||
if (data.folder == folder) // If in the same folder, the same filename is used
|
||||
return getUser(fileName, cl)
|
||||
return getConnectedID(data.folder)?.let { getUser(it, cl) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the filename for this player data. For example, for Minecraft-related data, MC UUIDs, for Discord data, Discord IDs, etc.
|
||||
*
|
||||
* **Does not include .yml**
|
||||
*/
|
||||
val fileName: String by lazy {
|
||||
commonUserData.playerData.getString(folder + "_id") ?: throw RuntimeException("ID not set!")
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the folder that this player data is stored in. For example: "minecraft".
|
||||
*/
|
||||
val folder: String by lazy { getStaticData(javaClass).folder }
|
||||
|
||||
/**
|
||||
* Get player information. This method calls the [TBMCPlayerGetInfoEvent] to get all the player information across the TBMC plugins.
|
||||
*
|
||||
* @param target The [InfoTarget] to return the info for.
|
||||
* @return The player information.
|
||||
*/
|
||||
fun getInfo(target: InfoTarget?): String {
|
||||
val event = TBMCPlayerGetInfoEvent(this, target)
|
||||
Bukkit.getServer().pluginManager.callEvent(event)
|
||||
return event.result
|
||||
}
|
||||
|
||||
enum class InfoTarget {
|
||||
MCHover, MCCommand, Discord
|
||||
}
|
||||
|
||||
//-----------------------------------------------------------------
|
||||
val channel
|
||||
get() = config.getData("channel", Channel.globalChat,
|
||||
{ id ->
|
||||
getChannels().filter { it.identifier.equals(id as String, ignoreCase = true) }
|
||||
.findAny().orElseThrow { RuntimeException("Channel $id not found!") }
|
||||
}, { ch -> ch.identifier })
|
||||
|
||||
/**
|
||||
* Check channel access by checking if the user is in the given group. If the group is null, check if the user is OP.
|
||||
*
|
||||
* Note that these groups originally come from Minecraft.
|
||||
*/ // TODO: Allow if a connected account has access
|
||||
abstract fun checkChannelInGroup(group: String?): Channel.RecipientTestResult
|
||||
|
||||
companion object {
|
||||
private const val TBMC_PLAYERS_DIR = "TBMC/players/"
|
||||
private val senderConverters = ArrayList<Function<CommandSender, out Optional<out ChromaGamerBase>>>()
|
||||
|
||||
/**
|
||||
* Holds data per user class
|
||||
*/
|
||||
private val staticDataMap = HashMap<Class<out ChromaGamerBase>, StaticUserData<out ChromaGamerBase>>()
|
||||
|
||||
/**
|
||||
* Used for connecting with every type of user ([.connectWith]) and to init the configs.
|
||||
* Also, to construct an instance if an abstract class is provided.
|
||||
*/
|
||||
@JvmStatic
|
||||
fun <T : ChromaGamerBase> registerPluginUserClass(userclass: Class<T>, constructor: Supplier<T>) {
|
||||
val prototype: Class<out T>
|
||||
val folderName: String
|
||||
if (userclass.isAnnotationPresent(UserClass::class.java)) {
|
||||
prototype = userclass
|
||||
folderName = userclass.getAnnotation(UserClass::class.java).foldername
|
||||
} else if (userclass.isAnnotationPresent(AbstractUserClass::class.java)) {
|
||||
val ucl = userclass.getAnnotation(AbstractUserClass::class.java).prototype.java
|
||||
if (!userclass.isAssignableFrom(ucl))
|
||||
throw RuntimeException("The prototype class (${ucl.simpleName}) must be a subclass of the userclass parameter (${userclass.simpleName})!")
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
prototype = ucl as Class<out T>
|
||||
folderName = userclass.getAnnotation(AbstractUserClass::class.java).foldername
|
||||
} else throw RuntimeException("Class not registered as a user class! Use @UserClass or TBMCPlayerBase")
|
||||
val sud = StaticUserData<T>(folderName)
|
||||
// Alawys register abstract and prototype class (TBMCPlayerBase and TBMCPlayer)
|
||||
sud.constructors[prototype] = constructor
|
||||
sud.constructors[userclass] = constructor
|
||||
staticDataMap[userclass] = sud
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the folder name for the given player class.
|
||||
*
|
||||
* @param cl The class to get the folder from (like [TBMCPlayerBase] or one of it's subclasses)
|
||||
* @return The folder name for the given type
|
||||
* @throws RuntimeException If the class doesn't have the [UserClass] annotation.
|
||||
*/
|
||||
fun <T : ChromaGamerBase> getFolderForType(cl: Class<T>): String {
|
||||
if (cl.isAnnotationPresent(UserClass::class.java))
|
||||
return cl.getAnnotation(UserClass::class.java).foldername
|
||||
else if (cl.isAnnotationPresent(AbstractUserClass::class.java))
|
||||
return cl.getAnnotation(AbstractUserClass::class.java).foldername
|
||||
throw RuntimeException("Class not registered as a user class! Use @UserClass or @AbstractUserClass")
|
||||
}
|
||||
|
||||
private inline val registeredFolders: Iterable<String> get() = staticDataMap.values.map { it.folder }
|
||||
|
||||
private inline val registeredClasses get() = staticDataMap.keys
|
||||
|
||||
/**
|
||||
* Returns the (per-user) static data for the given player class.
|
||||
* The static data is only stored once per user class so for example
|
||||
* if you have two different [TBMCPlayerBase] classes, the static data is the same for both.
|
||||
*
|
||||
* @param cl The class to get the data from (like [TBMCPlayerBase] or one of its subclasses)
|
||||
*/
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
private fun <T : ChromaGamerBase> getStaticData(cl: Class<out T>) = staticDataMap.entries
|
||||
.filter { (key, _) -> key.isAssignableFrom(cl) }
|
||||
.map { (_, value) -> value as StaticUserData<T> }
|
||||
.firstOrNull()
|
||||
?: throw RuntimeException("Class $cl not registered as a user class! Use registerUserClass()")
|
||||
|
||||
/**
|
||||
* Returns the player class for the given folder name.
|
||||
*
|
||||
* @param foldername The folder to get the class from (like "minecraft")
|
||||
* @return The type for the given folder name or null if not found
|
||||
*/
|
||||
@JvmStatic
|
||||
fun getTypeForFolder(foldername: String?): Class<out ChromaGamerBase>? {
|
||||
synchronized(staticDataMap) {
|
||||
return staticDataMap.filter { (_, value) -> value.folder.equals(foldername, ignoreCase = true) }
|
||||
.map { (key, _) -> key }.singleOrNull()
|
||||
}
|
||||
}
|
||||
|
||||
/***
|
||||
* Retrieves a user from cache or loads it from disk.
|
||||
*
|
||||
* @param fname Filename without .yml, the user's identifier for that type
|
||||
* @param cl User class
|
||||
* @return The user object
|
||||
*/
|
||||
@JvmStatic
|
||||
@Synchronized
|
||||
fun <T : S, S : ChromaGamerBase> getUser(fname: String, cl: Class<T>): T {
|
||||
val staticUserData: StaticUserData<S> = getStaticData(cl)
|
||||
|
||||
val commonUserData: CommonUserData<S> = staticUserData.userDataMap[fname]
|
||||
?: run {
|
||||
val folder = staticUserData.folder
|
||||
val file = File(TBMC_PLAYERS_DIR + folder, "$fname.yml")
|
||||
file.parentFile.mkdirs()
|
||||
val playerData = YamlConfiguration.loadConfiguration(file)
|
||||
playerData[staticUserData.folder + "_id"] = fname
|
||||
CommonUserData<S>(playerData)
|
||||
}.also { staticUserData.userDataMap[fname] = it }
|
||||
|
||||
return commonUserData.userCache[cl] ?: run {
|
||||
val obj = createNewUser(cl, staticUserData, commonUserData)
|
||||
commonUserData.userCache.put(obj)
|
||||
obj
|
||||
}
|
||||
}
|
||||
|
||||
private fun <T : S, S : ChromaGamerBase> createNewUser(
|
||||
cl: Class<T>,
|
||||
staticUserData: StaticUserData<S>,
|
||||
commonUserData: CommonUserData<S>
|
||||
): T {
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
val obj = staticUserData.constructors[cl]?.get() as T? ?: run {
|
||||
try {
|
||||
cl.getConstructor().newInstance()
|
||||
} catch (e: Exception) {
|
||||
throw RuntimeException("Failed to create new instance of user of type ${cl.simpleName}!", e)
|
||||
}
|
||||
}
|
||||
obj.commonUserData = commonUserData
|
||||
obj.initConfig()
|
||||
obj.scheduleUncache()
|
||||
return obj
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a converter to the start of the list.
|
||||
*
|
||||
* @param converter The converter that returns an object corresponding to the sender or null, if it's not the right type.
|
||||
*/
|
||||
@JvmStatic
|
||||
fun addConverter(converter: Function<CommandSender, Optional<out ChromaGamerBase>>) {
|
||||
senderConverters.add(0, converter)
|
||||
}
|
||||
|
||||
/**
|
||||
* Get from the given sender. the object's type will depend on the sender's type.
|
||||
* Throws an exception if the sender type is not supported.
|
||||
*
|
||||
* @param sender The sender to use
|
||||
* @return A user as returned by a converter
|
||||
*/
|
||||
@JvmStatic
|
||||
fun getFromSender(sender: CommandSender): ChromaGamerBase {
|
||||
for (converter in senderConverters) {
|
||||
val ocg = converter.apply(sender)
|
||||
if (ocg.isPresent) return ocg.get()
|
||||
}
|
||||
throw RuntimeException("No converter found for sender type ${sender::class.java.simpleName}")
|
||||
}
|
||||
|
||||
fun saveUsers() {
|
||||
synchronized(staticDataMap) {
|
||||
for (sud in staticDataMap.values) for (cud in sud.userDataMap.values) saveNow(cud.playerData) //Calls save()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
package buttondevteam.lib.player;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
/**
|
||||
* Per user, regardless of actual type
|
||||
*
|
||||
* @param <T> The user class, may be abstract
|
||||
*/
|
||||
@Getter
|
||||
@RequiredArgsConstructor
|
||||
public class CommonUserData<T extends ChromaGamerBase> {
|
||||
private final HashMap<Class<? extends T>, ? extends T> userCache = new HashMap<>();
|
||||
private final YamlConfiguration playerData;
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue