Finished Kotlin conversion, Command2MC stuff remains

This commit is contained in:
Norbi Peti 2023-04-17 21:04:00 +02:00
parent 1d88d3e859
commit 30a2fe0b68
No known key found for this signature in database
GPG key ID: DBA4C4549A927E56
23 changed files with 564 additions and 643 deletions

View file

@ -1 +0,0 @@
lombok.var.flagUsage = ALLOW

View file

@ -14,7 +14,7 @@ import java.util.Optional;
@CommandClass
public class ChromaCommand extends ICommand2MC {
public ChromaCommand() {
getManager().addParamConverter(ButtonPlugin.class, name ->
manager.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())

View file

@ -1,102 +1,98 @@
package buttondevteam.core;
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 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.command.CommandSender
import org.bukkit.plugin.Plugin
import org.bukkit.plugin.java.JavaPlugin
import java.util.*
import java.util.stream.Stream
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"])
class ComponentCommand : ICommand2MC() {
init {
manager.addParamConverter(
Plugin::class.java, { arg -> Bukkit.getPluginManager().getPlugin(arg) },
"Plugin not found!"
) { Bukkit.getPluginManager().plugins.map { obj -> obj.name } }
}
@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."])
fun enable(sender: CommandSender, plugin: Plugin, component: String, @OptionalArg permanent: Boolean): Boolean {
if (plugin is ButtonPlugin) {
if (!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 = {
"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."])
fun disable(sender: CommandSender, plugin: Plugin, component: String, @OptionalArg permanent: Boolean): Boolean {
return enable_disable(sender, plugin, component, false, 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"])
fun list(sender: CommandSender, @OptionalArg plugin: String?): Boolean {
sender.sendMessage("§6List 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
}
@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"])
fun componentTabcomplete(plugin: Plugin): Iterable<String> {
return Iterable { getPluginComponents(plugin).map { c -> c.javaClass.simpleName }.iterator() }
}
@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)
fun pluginTabcomplete(): Iterable<String> {
return Iterable { components.values.stream().map { it.plugin }.distinct().map { it.name }.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 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.set(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 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 fun getPluginComponents(plugin: Plugin): Stream<Component<out JavaPlugin>> {
return components.values.stream().filter { c -> plugin.name == c.plugin.name }
}
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;
}
}
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("§cComponent not found!")
return oc
}
}

View file

@ -91,13 +91,13 @@ class MainPlugin : ButtonPlugin() {
)
}
TBMCCoreAPI.RegisterUserClass(TBMCPlayerBase::class.java) { TBMCPlayer() }
TBMCChatAPI.RegisterChatChannel(Channel("§fg§f", Color.White, "g", null)
TBMCChatAPI.registerChatChannel(Channel("§fg§f", Color.White, "g", null)
.also { Channel.globalChat = it }) //The /ooc ID has moved to the config
TBMCChatAPI.RegisterChatChannel(Channel("§cADMIN§f", Color.Red, "a", Channel.inGroupFilter(null))
TBMCChatAPI.registerChatChannel(Channel("§cADMIN§f", Color.Red, "a", Channel.inGroupFilter(null))
.also { Channel.adminChat = it })
TBMCChatAPI.RegisterChatChannel(Channel("§9MOD§f", Color.Blue, "mod", Channel.inGroupFilter("mod"))
TBMCChatAPI.registerChatChannel(Channel("§9MOD§f", Color.Blue, "mod", Channel.inGroupFilter("mod"))
.also { Channel.modChat = it })
TBMCChatAPI.RegisterChatChannel(
TBMCChatAPI.registerChatChannel(
Channel(
"§6DEV§f",
Color.Gold,
@ -105,12 +105,12 @@ class MainPlugin : ButtonPlugin() {
Channel.inGroupFilter("developer")
)
) // TODO: Make groups configurable
TBMCChatAPI.RegisterChatChannel(ChatRoom("§cRED§f", Color.DarkRed, "red"))
TBMCChatAPI.RegisterChatChannel(ChatRoom("§6ORANGE§f", Color.Gold, "orange"))
TBMCChatAPI.RegisterChatChannel(ChatRoom("§eYELLOW§f", Color.Yellow, "yellow"))
TBMCChatAPI.RegisterChatChannel(ChatRoom("§aGREEN§f", Color.Green, "green"))
TBMCChatAPI.RegisterChatChannel(ChatRoom("§bBLUE§f", Color.Blue, "blue"))
TBMCChatAPI.RegisterChatChannel(ChatRoom("§5PURPLE§f", Color.DarkPurple, "purple"))
TBMCChatAPI.registerChatChannel(ChatRoom("§cRED§f", Color.DarkRed, "red"))
TBMCChatAPI.registerChatChannel(ChatRoom("§6ORANGE§f", Color.Gold, "orange"))
TBMCChatAPI.registerChatChannel(ChatRoom("§eYELLOW§f", Color.Yellow, "yellow"))
TBMCChatAPI.registerChatChannel(ChatRoom("§aGREEN§f", Color.Green, "green"))
TBMCChatAPI.registerChatChannel(ChatRoom("§bBLUE§f", Color.Blue, "blue"))
TBMCChatAPI.registerChatChannel(ChatRoom("§5PURPLE§f", Color.DarkPurple, "purple"))
val playerSupplier = Supplier { Bukkit.getOnlinePlayers().map { obj -> obj.name }.asIterable() }
command2MC.addParamConverter(
OfflinePlayer::class.java,

View file

@ -88,7 +88,7 @@ class PlayerListener(val plugin: MainPlugin) : Listener {
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(event.player, cp, event.message).build())
TBMCChatAPI.sendChatMessage(ChatMessage.builder(event.player, 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
}

View file

@ -45,6 +45,6 @@ public class TestPrepare {
}
}));
Component.registerComponent(Mockito.mock(JavaPlugin.class), new ChannelComponent());
TBMCChatAPI.RegisterChatChannel(Channel.globalChat = new Channel("§fg§f", Color.White, "g", null));
TBMCChatAPI.registerChatChannel(Channel.globalChat = new Channel("§fg§f", Color.White, "g", null));
}
}

View file

@ -31,13 +31,10 @@ class ChannelComponent : Component<JavaPlugin>() {
@CommandClass
private class ChannelCommand(private val channel: Channel) : ICommand2MC() {
override fun getCommandPath(): String {
return channel.identifier
}
override fun getCommandPaths(): Array<String> {
return channel.extraIdentifiers.get().toTypedArray()
}
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?) {
@ -55,7 +52,7 @@ class ChannelComponent : Component<JavaPlugin>() {
if (channel is ChatRoom) channel.joinRoom(sender)
}
sender.sendMessage("§6You are now talking in: §b" + user.channel.get().displayName.get())
} else TBMCChatAPI.SendChatMessage(
} else TBMCChatAPI.sendChatMessage(
ChatMessage.builder(sender, user, message).fromCommand(true)
.permCheck(senderMC.permCheck).build(), channel
)

View file

@ -1,44 +1,48 @@
package buttondevteam.core.component.restart;
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;
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 = {
"§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;
@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" //
]
)
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("§bPlayers 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("§bNobody is online. Restarting now.")
if (isLoud) SendSystemMessage(
Channel.globalChat,
Channel.RecipientTestResult.ALL,
"${ChatColor.RED}Nobody is online. Restarting server.",
component.restartBroadcast
)
Bukkit.spigot().restart()
}
}
@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;
}
companion object {
}
}

View file

@ -9,7 +9,6 @@ import buttondevteam.lib.architecture.Component
import buttondevteam.lib.architecture.ComponentMetadata
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
@ -26,9 +25,9 @@ import java.time.ZonedDateTime
@ComponentMetadata(enabledByDefault = false)
class RestartComponent : Component<MainPlugin>(), Listener {
public override fun enable() {
val scheduledRestartCommand = ScheduledRestartCommand(this)
val scheduledRestartCommand = ScheduledRestartCommand()
registerCommand(scheduledRestartCommand)
registerCommand(PrimeRestartCommand(this))
registerCommand(PrimeRestartCommand())
registerListener(this)
restartBroadcast = add("restartCountdown")
val restartAt = restartAt.get()
@ -52,8 +51,10 @@ class RestartComponent : Component<MainPlugin>(), Listener {
private val restartAt = config.getData("restartAt", 12)
private var lasttime: Long = 0
@Getter
private var restartBroadcast: BroadcastTarget? = null
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
@ -69,12 +70,12 @@ class RestartComponent : Component<MainPlugin>(), Listener {
@EventHandler
fun onPlayerLeave(event: PlayerQuitEvent) {
if (PrimeRestartCommand.isPlsrestart()
if (isPlsrestart
&& !event.quitMessage.equals("Server closed", ignoreCase = true)
&& !event.quitMessage.equals("Server is restarting", ignoreCase = true)
) {
if (Bukkit.getOnlinePlayers().size <= 1) {
if (PrimeRestartCommand.isLoud()) TBMCChatAPI.SendSystemMessage(
if (isLoud) TBMCChatAPI.SendSystemMessage(
Channel.globalChat,
Channel.RecipientTestResult.ALL,
"§cNobody is online anymore. Restarting.",
@ -83,7 +84,7 @@ class RestartComponent : Component<MainPlugin>(), Listener {
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 (PrimeRestartCommand.isLoud()) TBMCChatAPI.SendSystemMessage(
if (isLoud) TBMCChatAPI.SendSystemMessage(
Channel.globalChat,
Channel.RecipientTestResult.ALL,
ChatColor.DARK_RED.toString() + "The server will restart as soon as nobody is online.",

View file

@ -1,68 +1,75 @@
package buttondevteam.core.component.restart;
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 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.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
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." //
]
)
class ScheduledRestartCommand : ICommand2MC() {
private var restartCounter = 0
private lateinit var restartTask: BukkitTask
@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;
@Volatile
private lateinit var restartBar: BossBar
@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;
}
}
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("§cError: 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,
"§c-- 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--
}
}

View file

@ -1,25 +1,15 @@
package buttondevteam.lib;
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;
import buttondevteam.core.component.restart.ScheduledRestartCommand
import org.bukkit.event.Event
import org.bukkit.event.HandlerList
@Getter
@RequiredArgsConstructor
public class ScheduledServerRestartEvent extends Event {
private static final HandlerList handlers = new HandlerList();
class ScheduledServerRestartEvent(val restartTicks: Int, val command: ScheduledRestartCommand) : Event() {
override fun getHandlers(): HandlerList {
return handlerList
}
private final int restartTicks;
private final ScheduledRestartCommand command;
@Override
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
companion object {
val handlerList = HandlerList()
}
}

View file

@ -1,73 +1,55 @@
package buttondevteam.lib;
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;
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.command.CommandSender
import org.bukkit.event.HandlerList
/**
* Make sure to only send the message to users where {@link #shouldSendTo(CommandSender)} returns true.
*
* @author NorbiPeti
* Make sure to only send the message to users where [.shouldSendTo] returns true.
*
* @author NorbiPeti
*/
@Getter
public class TBMCChatEvent extends TBMCChatEventBase {
public TBMCChatEvent(Channel channel, ChatMessage cm, Channel.RecipientTestResult rtr) {
super(channel, cm.message, rtr.score, rtr.groupID);
this.cm = cm;
}
class TBMCChatEvent(
channel: Channel,
private val cm: ChatMessage,
rtr: RecipientTestResult
) : TBMCChatEventBase(channel, cm.message, rtr.score, rtr.groupID!!) {
private static final HandlerList handlers = new HandlerList();
@Delegate //<-- Backwards compatibility
private ChatMessage cm;
private boolean isIgnoreSenderPermissions() {
return cm.getPermCheck() != cm.sender;
}
private val isIgnoreSenderPermissions: Boolean get() = cm.permCheck !== cm.sender
/**
* This will allow the sender of the message if {@link #isIgnoreSenderPermissions()} is true.
* This will allow the sender of the message if [.isIgnoreSenderPermissions] is true.
*/
@Override
public boolean shouldSendTo(CommandSender sender) {
if (isIgnoreSenderPermissions() && sender.equals(this.cm.sender))
return true; //Allow sending the message no matter what
return super.shouldSendTo(sender);
override fun shouldSendTo(sender: CommandSender): Boolean {
return if (isIgnoreSenderPermissions && sender == cm.sender) true else super.shouldSendTo(sender) //Allow sending the message no matter what
}
/**
* This will allow the sender of the message if {@link #isIgnoreSenderPermissions()} is true.
* This will allow the sender of the message if [.isIgnoreSenderPermissions] is true.
*/
@Override
public int getMCScore(CommandSender sender) {
if (isIgnoreSenderPermissions() && sender.equals(this.cm.sender))
return getScore(); //Send in the correct group no matter what
return super.getMCScore(sender);
override fun getMCScore(sender: CommandSender): Int {
return if (isIgnoreSenderPermissions && sender == cm.sender) score else super.getMCScore(sender) //Send in the correct group no matter what
}
/**
* This will allow the sender of the message if {@link #isIgnoreSenderPermissions()} is true.
* This will allow the sender of the message if [.isIgnoreSenderPermissions] is true.
*/
@Nullable
@Override
public String getGroupID(CommandSender sender) {
if (isIgnoreSenderPermissions() && sender.equals(this.cm.sender))
return getGroupID(); //Send in the correct group no matter what
return super.getGroupID(sender);
override fun getGroupID(sender: CommandSender): String? {
return if (isIgnoreSenderPermissions && sender == cm.sender) groupID else super.getGroupID(sender) //Send in the correct group no matter what
}
@Override
public HandlerList getHandlers() {
return handlers;
}
override fun getHandlers(): HandlerList {
return handlerList
}
public static HandlerList getHandlerList() {
return handlers;
}
}
val sender: CommandSender get() = cm.sender
val user: ChromaGamerBase get() = cm.user
val origin: String get() = cm.origin
companion object {
val handlerList = HandlerList()
}
}

View file

@ -1,59 +1,47 @@
package buttondevteam.lib;
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 buttondevteam.core.component.channel.Channel
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;
abstract class TBMCChatEventBase(
val channel: Channel,
open val message: String,
/**
* The sender's score.
*/
private final int score;
val score: Int,
/**
* The sender's group ID.
*/
private final String groupID;
val groupID: String,
) : Event(true), Cancellable {
var isCancelled: Boolean = false
@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
*/
open fun shouldSendTo(sender: CommandSender): Boolean {
return channel.shouldSendTo(sender, score)
}
/**
* Note: Errors are sent to the sender automatically<br>
* Note: Errors are sent to the sender automatically
*/
open fun getMCScore(sender: CommandSender): Int {
return channel.getMCScore(sender)
}
/**
* Note: Errors are sent to the sender automatically<br></br>
*
* Null means don't send
*/
@Nullable
public String getGroupID(CommandSender sender) {
return channel.getGroupID(sender);
open fun getGroupID(sender: CommandSender): String? {
return channel.getGroupID(sender)
}
}
override fun isCancelled(): Boolean = isCancelled
override fun setCancelled(cancel: Boolean) = run { isCancelled = cancel }
}

View file

@ -1,44 +1,29 @@
package buttondevteam.lib;
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;
import buttondevteam.core.component.channel.Channel
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
* **Only called before sending messages with SendChatMessage.**
*
* @author NorbiPeti
*/
@Getter
public class TBMCChatPreprocessEvent extends Event implements Cancellable {
private static final HandlerList handlers = new HandlerList();
class TBMCChatPreprocessEvent(val sender: CommandSender, val channel: Channel, var message: String) : Event(true),
Cancellable {
private var cancelled = false
override fun getHandlers(): HandlerList {
return handlerList
}
private final Channel channel;
private final CommandSender sender;
@Setter
private String message;
@Setter
private boolean cancelled;
override fun isCancelled() = cancelled
public TBMCChatPreprocessEvent(CommandSender sender, Channel channel, String message) {
super(true);
this.sender = sender;
this.channel = channel;
this.message = message;
}
override fun setCancelled(cancelled: Boolean) = run { this.cancelled = cancelled }
@Override
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
}
companion object {
val handlerList = HandlerList()
}
}

View file

@ -1,39 +1,33 @@
package buttondevteam.lib;
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;
import buttondevteam.core.component.channel.Channel
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>
* **Called on using player, console and Discord commands.**
*
* @author NorbiPeti
*/
@Getter
@RequiredArgsConstructor
public class TBMCCommandPreprocessEvent extends Event implements Cancellable {
private static final HandlerList handlers = new HandlerList();
class TBMCCommandPreprocessEvent(
val sender: CommandSender,
val channel: Channel,
val message: String,
val permCheck: CommandSender
) : Event(), Cancellable {
private var cancelled = false
override fun getHandlers(): HandlerList {
return handlerList
}
private final CommandSender sender;
private final Channel channel;
@Setter
private final String message;
private final CommandSender permCheck;
@Setter
private boolean cancelled;
override fun isCancelled() = cancelled
@Override
public HandlerList getHandlers() {
return handlers;
}
override fun setCancelled(cancelled: Boolean) = run { this.cancelled = cancelled }
public static HandlerList getHandlerList() {
return handlers;
}
}
companion object {
val handlerList = HandlerList()
}
}

View file

@ -1,43 +1,23 @@
package buttondevteam.lib;
package buttondevteam.lib
import lombok.Getter;
import org.bukkit.Bukkit;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
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
* This event gets called (ideally) each time an exception occurs in a TBMC plugin. To call it, use [TBMCCoreAPI.SendException].
*
*
* @author Norbi
*/
@Getter
public class TBMCExceptionEvent extends Event {
private static final HandlerList handlers = new HandlerList();
class TBMCExceptionEvent(val sourceMessage: String, val exception: Throwable) : Event(!Bukkit.isPrimaryThread()) {
var isHandled = false
private final String sourceMessage;
private final Throwable exception;
private boolean handled;
override fun getHandlers(): HandlerList {
return handlerList
}
@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;
}
}
companion object {
val handlerList = HandlerList()
}
}

View file

@ -35,6 +35,7 @@ class IHaveConfig(
* @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,
@ -57,6 +58,7 @@ class IHaveConfig(
* @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>,
@ -77,6 +79,7 @@ class IHaveConfig(
* @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>,

View file

@ -1,30 +1,24 @@
package buttondevteam.lib.chat;
package buttondevteam.lib.chat
import lombok.Getter;
import lombok.RequiredArgsConstructor;
enum class Color(private val cname: String, val red: Int, val green: Int, val blue: Int) : 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);
@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;
}
override fun getName(): String {
return cname
}
}

View file

@ -82,7 +82,9 @@ abstract class Command2<TC : ICommand2<TP>, TP : Command2Sender>(
* @param allSupplier The supplier of all possible values (ideally)
</T> */
open fun <T> addParamConverter(
cl: Class<T>, converter: Function<String, T?>, errormsg: String,
cl: Class<T>,
converter: Function<String, T?>,
errormsg: String,
allSupplier: Supplier<Iterable<String>>
) {
paramConverters[cl] = ParamConverter(converter, errormsg, allSupplier)

View file

@ -1,33 +1,41 @@
package buttondevteam.lib.chat;
package buttondevteam.lib.chat
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.builder.ArgumentBuilder;
import com.mojang.brigadier.suggestion.SuggestionProvider;
import lombok.RequiredArgsConstructor;
import com.mojang.brigadier.arguments.ArgumentType
import com.mojang.brigadier.builder.ArgumentBuilder
import com.mojang.brigadier.suggestion.SuggestionProvider
@RequiredArgsConstructor
public class CoreArgumentBuilder<S, T> extends ArgumentBuilder<S, CoreArgumentBuilder<S, T>> {
private final String name;
private final ArgumentType<T> type;
private final boolean optional;
private SuggestionProvider<S> suggestionsProvider = null;
class CoreArgumentBuilder<S, 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
}
public static <S, T> CoreArgumentBuilder<S, T> argument(String name, ArgumentType<T> type, boolean optional) {
return new CoreArgumentBuilder<S, T>(name, type, optional);
}
override fun getThis(): CoreArgumentBuilder<S, T> {
return this
}
public CoreArgumentBuilder<S, T> suggests(SuggestionProvider<S> provider) {
this.suggestionsProvider = provider;
return this;
}
override fun build(): CoreArgumentCommandNode<S, T> {
return CoreArgumentCommandNode(
name,
type,
command,
requirement,
redirect,
redirectModifier,
isFork,
suggestionsProvider,
optional
)
}
@Override
protected CoreArgumentBuilder<S, T> getThis() {
return this;
}
@Override
public CoreArgumentCommandNode<S, T> build() {
return new CoreArgumentCommandNode<>(name, type, getCommand(), getRequirement(), getRedirect(), getRedirectModifier(), isFork(), suggestionsProvider, optional);
}
}
companion object {
fun <S, T> argument(name: String, type: ArgumentType<T>, optional: Boolean): CoreArgumentBuilder<S, T> {
return CoreArgumentBuilder(name, type, optional)
}
}
}

View file

@ -1,110 +1,112 @@
package buttondevteam.lib.chat;
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;
import buttondevteam.lib.chat.Command2.Subcommand
import java.lang.reflect.Method
import java.lang.reflect.Modifier
import java.util.*
import java.util.function.Function
/**
* 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
*/
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
*/
@SuppressWarnings("unused")
public boolean def(TP sender) {
return false;
}
* @param TP The sender's type
</TP> */
abstract class ICommand2<TP : Command2Sender>(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
*/
@Suppress("UNUSED_PARAMETER")
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
*/
protected boolean respond(TP sender, String message) {
sender.sendMessage(message);
return true;
}
/**
* 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 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.<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
}
/**
* Return null to not add any help text, return an empty array to only print subcommands.<br></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
*/
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
}
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)
private val path: String
val manager: Command2<*, TP>
open val commandPath: String
/**
* The command's path, or name if top-level command.<br></br>
* For example:<br></br>
* "u admin updateplugin" or "u" for the top level one<br></br>
* <u>The path must be lowercase!</u><br></br>
*
* @return The command path, *which is the command class name by default* (removing any "command" from it) - Change via the [CommandClass] annotation
*/
get() = path
public <T extends ICommand2<TP>> ICommand2(Command2<T, TP> manager) {
path = getcmdpath();
this.manager = manager;
}
init {
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;
}
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() =// TODO: Deal with this (used for channel IDs)
EMPTY_PATHS
private static final String[] EMPTY_PATHS = new String[0];
private fun getcmdpath(): String {
if (!javaClass.isAnnotationPresent(CommandClass::class.java)) throw RuntimeException(
"No @CommandClass annotation on command class " + javaClass.simpleName + "!"
)
val getFromClass = Function { cl: Class<*> ->
cl.simpleName.lowercase(Locale.getDefault()).replace("commandbase", "") // <-- ...
.replace("command", "")
}
var path = javaClass.getAnnotation(CommandClass::class.java).path
var prevpath = if (path.isEmpty()) getFromClass.apply(javaClass) else path.also { path = it }
var cl: Class<*>? = javaClass.superclass
while (cl != null && cl.getPackage().name != ICommand2MC::class.java.getPackage().name) {
//
var newpath: String
val ccann: CommandClass? = cl.getAnnotation(CommandClass::class.java)
if (ccann?.path.isNullOrEmpty() || ccann?.path == prevpath) {
if (ccann?.excludeFromPath ?: Modifier.isAbstract(cl.modifiers)) {
cl = cl.superclass
continue
}
newpath = getFromClass.apply(cl)
} else newpath = ccann!!.path
path = "$newpath $path"
prevpath = newpath
cl = cl.superclass
}
return path
}
/**
* 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() { // TODO: Deal with this (used for channel IDs)
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;
}
}
companion object {
private val EMPTY_PATHS = emptyArray<String>()
}
}

View file

@ -1,46 +1,36 @@
package buttondevteam.lib.chat;
package buttondevteam.lib.chat
import buttondevteam.lib.architecture.ButtonPlugin;
import buttondevteam.lib.architecture.Component;
import lombok.Getter;
import buttondevteam.lib.architecture.ButtonPlugin
import buttondevteam.lib.architecture.ButtonPlugin.Companion.command2MC
import buttondevteam.lib.architecture.Component
import javax.annotation.Nullable;
abstract class ICommand2MC : ICommand2<Command2MCSender>(command2MC) {
private var _plugin: ButtonPlugin? = null
var plugin: ButtonPlugin
get() = _plugin ?: throw IllegalStateException("The command is not registered to a plugin!")
private set(value) {
if (_plugin != null) throw IllegalStateException("The command is already assigned to a plugin!")
_plugin = value
}
private var _component: Component<*>? = null
var component: Component<*>
get() = _component ?: throw IllegalStateException("The command is not registered to a component!")
private set(value) {
if (_component != null) throw IllegalStateException("The command is already assigned to a component!")
_component = value
}
@SuppressWarnings("JavadocReference")
public abstract class ICommand2MC extends ICommand2<Command2MCSender> {
@Getter
private ButtonPlugin plugin;
@Getter
@Nullable
private Component<?> component;
/**
* Called from [buttondevteam.lib.architecture.Component.registerCommand] and [ButtonPlugin.registerCommand]
*/
fun registerToPlugin(plugin: ButtonPlugin) {
this.plugin = plugin
}
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>*/
}
/**
* Called from [buttondevteam.lib.architecture.Component.registerCommand]
*/
fun registerToComponent(component: Component<*>) {
this.component = component
}
}

View file

@ -32,7 +32,7 @@ object TBMCChatAPI {
* @return The event cancelled state
*/
@JvmOverloads
fun SendChatMessage(cm: ChatMessage, channel: Channel = cm.user.channel.get()): Boolean {
fun sendChatMessage(cm: ChatMessage, channel: Channel = cm.user.channel.get()): Boolean {
if (!channelList.contains(channel)) throw RuntimeException(
"Channel " + channel.displayName.get() + " not registered!"
)
@ -41,8 +41,7 @@ object TBMCChatAPI {
return true //Cancel sending if channel is disabled
}
val task = Supplier {
val permcheck = cm.getPermCheck()
val rtr = getScoreOrSendError(channel, permcheck)
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.sender, channel, cm.message)
@ -93,7 +92,7 @@ object TBMCChatAPI {
* @param channel A new [Channel] to register
*/
@JvmStatic
fun RegisterChatChannel(channel: Channel) {
fun registerChatChannel(channel: Channel) {
registerChannel(channel)
}
}