From b482c029d5ec033ed577b503850e12b98e6d59fe Mon Sep 17 00:00:00 2001 From: Miles Holder Date: Wed, 8 May 2024 14:40:14 -0500 Subject: [PATCH 01/13] cleanup broadcast --- .../parsed/arguments/GreedyStringArg.kt | 15 ++++++ modules/basics-broadcast/README.md | 8 ++++ .../basicsbroadcast/BasicsBroadcastModule.kt | 31 +++++++++--- .../basicsbroadcast/BroadcastCommand.kt | 23 +++++++++ .../basicsbroadcast/BroadcastExecutor.kt | 47 ------------------- .../BasicsExtinguishModule.kt | 26 ---------- 6 files changed, 70 insertions(+), 80 deletions(-) create mode 100644 core/src/main/kotlin/com/github/spigotbasics/core/command/parsed/arguments/GreedyStringArg.kt create mode 100644 modules/basics-broadcast/README.md create mode 100644 modules/basics-broadcast/src/main/kotlin/com/github/spigotbasics/modules/basicsbroadcast/BroadcastCommand.kt delete mode 100644 modules/basics-broadcast/src/main/kotlin/com/github/spigotbasics/modules/basicsbroadcast/BroadcastExecutor.kt diff --git a/core/src/main/kotlin/com/github/spigotbasics/core/command/parsed/arguments/GreedyStringArg.kt b/core/src/main/kotlin/com/github/spigotbasics/core/command/parsed/arguments/GreedyStringArg.kt new file mode 100644 index 00000000..41596083 --- /dev/null +++ b/core/src/main/kotlin/com/github/spigotbasics/core/command/parsed/arguments/GreedyStringArg.kt @@ -0,0 +1,15 @@ +package com.github.spigotbasics.core.command.parsed.arguments + +import org.bukkit.command.CommandSender + +class GreedyStringArg(name: String) : CommandArgument(name) { + override val greedy: Boolean = true + + override fun parse(sender: CommandSender, value: String): String { + return value + } + + override fun tabComplete(sender: CommandSender, typing: String): List { + return emptyList() + } +} diff --git a/modules/basics-broadcast/README.md b/modules/basics-broadcast/README.md new file mode 100644 index 00000000..32dc7f6a --- /dev/null +++ b/modules/basics-broadcast/README.md @@ -0,0 +1,8 @@ +| Command | Permission | +|-----------------------------------|-------------------------| +| `/broadcast ` | basics.broadcast | +| `/broadcast [--parsed] ` | basics.broadcast.parsed | + +> [!NOTE] +> the `--parsed` argument while optional also required the `basics.broadcast.parsed` +> permission when being used diff --git a/modules/basics-broadcast/src/main/kotlin/com/github/spigotbasics/modules/basicsbroadcast/BasicsBroadcastModule.kt b/modules/basics-broadcast/src/main/kotlin/com/github/spigotbasics/modules/basicsbroadcast/BasicsBroadcastModule.kt index a2cdd35e..79b867aa 100644 --- a/modules/basics-broadcast/src/main/kotlin/com/github/spigotbasics/modules/basicsbroadcast/BasicsBroadcastModule.kt +++ b/modules/basics-broadcast/src/main/kotlin/com/github/spigotbasics/modules/basicsbroadcast/BasicsBroadcastModule.kt @@ -1,17 +1,34 @@ package com.github.spigotbasics.modules.basicsbroadcast +import com.github.spigotbasics.core.command.parsed.arguments.AnyStringArg +import com.github.spigotbasics.core.command.parsed.arguments.GreedyStringArg +import com.github.spigotbasics.core.command.parsed.arguments.LiteralArg import com.github.spigotbasics.core.module.AbstractBasicsModule import com.github.spigotbasics.core.module.loader.ModuleInstantiationContext class BasicsBroadcastModule(context: ModuleInstantiationContext) : AbstractBasicsModule(context) { - val commandPerm = permissionManager.createSimplePermission("basics.broadcast", "Allows the user to broadcast messages") - val parsedPerm = permissionManager.createSimplePermission("basics.broadcast.parsed", "Allows the user to broadcast parsed messages") + private val commandPerm = permissionManager.createSimplePermission("basics.broadcast", "Allows the user to broadcast messages") + private val parsedPerm = permissionManager.createSimplePermission("basics.broadcast.parsed", "Allows the user to broadcast parsed messages") override fun onEnable() { - commandFactory.rawCommandBuilder("broadcast", commandPerm) - .description("Broadcasts a message to all players") - .usage("[--parsed] ") - .executor(BroadcastExecutor(this)) - .register() + commandFactory.parsedCommandBuilder("broadcast", commandPerm) + .mapContext { + usage = "[--parsed] " + description("Broadcast a message to your server") + + path { + arguments { + named("message", GreedyStringArg("message")) + } + } + + path { + arguments { + permissions(parsedPerm) + named("parsed", LiteralArg("--parsed")) + named("message", GreedyStringArg("message")) + } + } + }.executor(BroadcastCommand(this)).register() } } diff --git a/modules/basics-broadcast/src/main/kotlin/com/github/spigotbasics/modules/basicsbroadcast/BroadcastCommand.kt b/modules/basics-broadcast/src/main/kotlin/com/github/spigotbasics/modules/basicsbroadcast/BroadcastCommand.kt new file mode 100644 index 00000000..dfab688a --- /dev/null +++ b/modules/basics-broadcast/src/main/kotlin/com/github/spigotbasics/modules/basicsbroadcast/BroadcastCommand.kt @@ -0,0 +1,23 @@ +package com.github.spigotbasics.modules.basicsbroadcast + +import com.github.spigotbasics.core.command.parsed.CommandContextExecutor +import com.github.spigotbasics.core.command.parsed.context.MapContext +import org.bukkit.command.CommandSender +import org.bukkit.entity.Player + +class BroadcastCommand(private val module: BasicsBroadcastModule) : CommandContextExecutor { + + override fun execute(sender: CommandSender, context: MapContext) { + val parsed = context["parsed"] != null + val rawMessage = context["message"] as String + + val message = if (parsed) { + module.messageFactory.createMessage(rawMessage).concerns(sender as? Player) + } else { + module.messageFactory.createPlainMessage(rawMessage) + } + + message.sendToAllPlayers() + message.sendToConsole() + } +} diff --git a/modules/basics-broadcast/src/main/kotlin/com/github/spigotbasics/modules/basicsbroadcast/BroadcastExecutor.kt b/modules/basics-broadcast/src/main/kotlin/com/github/spigotbasics/modules/basicsbroadcast/BroadcastExecutor.kt deleted file mode 100644 index 2b29694b..00000000 --- a/modules/basics-broadcast/src/main/kotlin/com/github/spigotbasics/modules/basicsbroadcast/BroadcastExecutor.kt +++ /dev/null @@ -1,47 +0,0 @@ -package com.github.spigotbasics.modules.basicsbroadcast - -import com.github.spigotbasics.core.command.common.BasicsCommandExecutor -import com.github.spigotbasics.core.command.common.CommandResult -import com.github.spigotbasics.core.command.raw.RawCommandContext -import org.bukkit.entity.Player -import org.bukkit.util.StringUtil - -class BroadcastExecutor(private val module: BasicsBroadcastModule) : BasicsCommandExecutor(module) { - override fun execute(context: RawCommandContext): CommandResult { - context.readFlags() - - val parseMini = context.popFlag("--parsed") - failIfFlagsLeft(context) - - val args = context.args - - val text = args.joinToString(" ") - var message = messageFactory.createPlainMessage(text) - - if (parseMini) { - requirePermission(context.sender, module.parsedPerm) - message = messageFactory.createMessage(text).concerns(context.sender as? Player) - } - - message.sendToAllPlayers() - message.sendToConsole() - return CommandResult.SUCCESS - } - - override fun tabComplete(context: RawCommandContext): MutableList { - val options = mutableListOf() - if (context.sender.hasPermission(module.parsedPerm)) { - options += "--parsed" - } - - return if (context.args.size == 1) { - StringUtil.copyPartialMatches( - context.args[0], - options, - mutableListOf(), - ) - } else { - mutableListOf() - } - } -} diff --git a/modules/basics-extinguish/src/main/kotlin/com/github/spigotbasics/modules/basicsextinguish/BasicsExtinguishModule.kt b/modules/basics-extinguish/src/main/kotlin/com/github/spigotbasics/modules/basicsextinguish/BasicsExtinguishModule.kt index 8b5ea7d6..47b25aae 100644 --- a/modules/basics-extinguish/src/main/kotlin/com/github/spigotbasics/modules/basicsextinguish/BasicsExtinguishModule.kt +++ b/modules/basics-extinguish/src/main/kotlin/com/github/spigotbasics/modules/basicsextinguish/BasicsExtinguishModule.kt @@ -1,9 +1,6 @@ package com.github.spigotbasics.modules.basicsextinguish -import com.github.spigotbasics.core.command.common.BasicsCommandExecutor -import com.github.spigotbasics.core.command.common.CommandResult import com.github.spigotbasics.core.command.parsed.arguments.SelectorSinglePlayerArg -import com.github.spigotbasics.core.command.raw.RawCommandContext import com.github.spigotbasics.core.module.AbstractBasicsModule import com.github.spigotbasics.core.module.loader.ModuleInstantiationContext @@ -40,27 +37,4 @@ class BasicsExtinguishModule(context: ModuleInstantiationContext) : AbstractBasi } }.executor(BasicsExtinguishExecutor(this)).register() } - - private inner class ExtinguishExecutor(private val module: BasicsExtinguishModule) : BasicsCommandExecutor(module) { - override fun execute(context: RawCommandContext): CommandResult { - val player = - if (context.args.size == 1) { - requirePermission(context.sender, module.permExtinguishOthers) - requirePlayer(context.args[0]) - } else { - requirePlayer(context.sender) - } - - player.fireTicks = 0 - val message = - if (context.sender == player) { - module.messageExtinguished - } else { - module.messageExtinguishedOther - } - - message.concerns(player).sendToSender(context.sender) - return CommandResult.SUCCESS - } - } } From 9dc429a2c2c6dfdb03c32509170e6d026c732969 Mon Sep 17 00:00:00 2001 From: Miles Holder Date: Wed, 8 May 2024 17:06:51 -0500 Subject: [PATCH 02/13] cleanup chat format --- .../parsed/arguments/GreedyStringArg.kt | 10 +- .../basicsbroadcast/BasicsBroadcastModule.kt | 7 +- .../basicsbroadcast/BroadcastCommand.kt | 17 +-- modules/basics-chat-format/README.md | 27 ++++ .../BasicsChatFormatModule.kt | 119 +++++++++--------- .../basicschatformat/ChatColorCommand.kt | 69 ++++++++++ .../modules/basicschatformat/Messages.kt | 10 +- .../commmands/ColorChatCommand.kt | 53 -------- .../data/{ChatData.kt => ChatFormatData.kt} | 2 +- .../basicschatformat/data/ChatFormatStore.kt | 17 +++ .../data/packages/ChatColorPackage.kt | 33 +++++ .../data/packages/ColorType.kt | 8 ++ .../data/packages/GradientHexPackage.kt | 48 +++++++ .../data/packages/GradientNamedPackage.kt | 50 ++++++++ .../data/packages/HexColorPackage.kt | 36 ++++++ .../data/packages/NamedColorPackage.kt | 44 +++++++ .../{ => listener}/PaperChatEventListener.kt | 9 +- .../listener/SpigotChatEventListener.kt | 21 ++++ .../src/main/resources/basics-module.yml | 2 +- 19 files changed, 447 insertions(+), 135 deletions(-) create mode 100644 modules/basics-chat-format/README.md create mode 100644 modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/ChatColorCommand.kt delete mode 100644 modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/commmands/ColorChatCommand.kt rename modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/data/{ChatData.kt => ChatFormatData.kt} (58%) create mode 100644 modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/data/ChatFormatStore.kt create mode 100644 modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/data/packages/ChatColorPackage.kt create mode 100644 modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/data/packages/ColorType.kt create mode 100644 modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/data/packages/GradientHexPackage.kt create mode 100644 modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/data/packages/GradientNamedPackage.kt create mode 100644 modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/data/packages/HexColorPackage.kt create mode 100644 modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/data/packages/NamedColorPackage.kt rename modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/{ => listener}/PaperChatEventListener.kt (74%) create mode 100644 modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/listener/SpigotChatEventListener.kt diff --git a/core/src/main/kotlin/com/github/spigotbasics/core/command/parsed/arguments/GreedyStringArg.kt b/core/src/main/kotlin/com/github/spigotbasics/core/command/parsed/arguments/GreedyStringArg.kt index 41596083..df0afb63 100644 --- a/core/src/main/kotlin/com/github/spigotbasics/core/command/parsed/arguments/GreedyStringArg.kt +++ b/core/src/main/kotlin/com/github/spigotbasics/core/command/parsed/arguments/GreedyStringArg.kt @@ -5,11 +5,17 @@ import org.bukkit.command.CommandSender class GreedyStringArg(name: String) : CommandArgument(name) { override val greedy: Boolean = true - override fun parse(sender: CommandSender, value: String): String { + override fun parse( + sender: CommandSender, + value: String, + ): String { return value } - override fun tabComplete(sender: CommandSender, typing: String): List { + override fun tabComplete( + sender: CommandSender, + typing: String, + ): List { return emptyList() } } diff --git a/modules/basics-broadcast/src/main/kotlin/com/github/spigotbasics/modules/basicsbroadcast/BasicsBroadcastModule.kt b/modules/basics-broadcast/src/main/kotlin/com/github/spigotbasics/modules/basicsbroadcast/BasicsBroadcastModule.kt index 79b867aa..a33bbcca 100644 --- a/modules/basics-broadcast/src/main/kotlin/com/github/spigotbasics/modules/basicsbroadcast/BasicsBroadcastModule.kt +++ b/modules/basics-broadcast/src/main/kotlin/com/github/spigotbasics/modules/basicsbroadcast/BasicsBroadcastModule.kt @@ -1,6 +1,5 @@ package com.github.spigotbasics.modules.basicsbroadcast -import com.github.spigotbasics.core.command.parsed.arguments.AnyStringArg import com.github.spigotbasics.core.command.parsed.arguments.GreedyStringArg import com.github.spigotbasics.core.command.parsed.arguments.LiteralArg import com.github.spigotbasics.core.module.AbstractBasicsModule @@ -8,7 +7,11 @@ import com.github.spigotbasics.core.module.loader.ModuleInstantiationContext class BasicsBroadcastModule(context: ModuleInstantiationContext) : AbstractBasicsModule(context) { private val commandPerm = permissionManager.createSimplePermission("basics.broadcast", "Allows the user to broadcast messages") - private val parsedPerm = permissionManager.createSimplePermission("basics.broadcast.parsed", "Allows the user to broadcast parsed messages") + private val parsedPerm = + permissionManager.createSimplePermission( + "basics.broadcast.parsed", + "Allows the user to broadcast parsed messages", + ) override fun onEnable() { commandFactory.parsedCommandBuilder("broadcast", commandPerm) diff --git a/modules/basics-broadcast/src/main/kotlin/com/github/spigotbasics/modules/basicsbroadcast/BroadcastCommand.kt b/modules/basics-broadcast/src/main/kotlin/com/github/spigotbasics/modules/basicsbroadcast/BroadcastCommand.kt index dfab688a..8ca7c946 100644 --- a/modules/basics-broadcast/src/main/kotlin/com/github/spigotbasics/modules/basicsbroadcast/BroadcastCommand.kt +++ b/modules/basics-broadcast/src/main/kotlin/com/github/spigotbasics/modules/basicsbroadcast/BroadcastCommand.kt @@ -6,16 +6,19 @@ import org.bukkit.command.CommandSender import org.bukkit.entity.Player class BroadcastCommand(private val module: BasicsBroadcastModule) : CommandContextExecutor { - - override fun execute(sender: CommandSender, context: MapContext) { + override fun execute( + sender: CommandSender, + context: MapContext, + ) { val parsed = context["parsed"] != null val rawMessage = context["message"] as String - val message = if (parsed) { - module.messageFactory.createMessage(rawMessage).concerns(sender as? Player) - } else { - module.messageFactory.createPlainMessage(rawMessage) - } + val message = + if (parsed) { + module.messageFactory.createMessage(rawMessage).concerns(sender as? Player) + } else { + module.messageFactory.createPlainMessage(rawMessage) + } message.sendToAllPlayers() message.sendToConsole() diff --git a/modules/basics-chat-format/README.md b/modules/basics-chat-format/README.md new file mode 100644 index 00000000..51641113 --- /dev/null +++ b/modules/basics-chat-format/README.md @@ -0,0 +1,27 @@ +| Command | Permission | +|--------------------------|------------------| +| `/chatcolor set ` | basics.chatcolor | +| `/chatcolor reset` | basics.chatcolor | + +## Color Permissions + +Color permissions are given based upon certain permissions. Below will explain how you can grant permission +to specific colors alongside ranges of colors. + +### Giving Ranges + +There are a few ranges provided in basic by default. + +- `basics.chatcolor.named`, gives access to all named colors, e.g. red, blue, dark_green. +- `basics.chatcolor.hex`, gives access to all hex colors, e.g. #FF00FF, #00FF00, #EFABCE. +- `basics.chatcolor.gradient.named`, gives access to any gradient that is named, e.g. red:blue, gold:light_purple, yellow:green. +- `basics.chatcolor.gradient.hex`, gives access to any hex that is named, e.g. #FFF000:#000FFF, #EEFF00:#00FFEE. + +### Giving Specific Colors + +If you don't want to give players ranges, but rather specific colors you can do the following. An example will be given for each type + +- **Named**: `basics.chatcolor.red` +- **Hex**: `basics.chatcolor.#987FFE` +- **Named Gradient**: `basics.chatcolor.blue:red` +- **Hex Gradient**: `basics.chatcolor.#FFF000:#000FFF` diff --git a/modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/BasicsChatFormatModule.kt b/modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/BasicsChatFormatModule.kt index 9dd81bdf..8e72d6da 100644 --- a/modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/BasicsChatFormatModule.kt +++ b/modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/BasicsChatFormatModule.kt @@ -2,62 +2,81 @@ package com.github.spigotbasics.modules.basicschatformat import com.github.spigotbasics.core.Serialization import com.github.spigotbasics.core.Spiper +import com.github.spigotbasics.core.command.parsed.arguments.AnyStringArg import com.github.spigotbasics.core.config.ConfigName import com.github.spigotbasics.core.messages.Message import com.github.spigotbasics.core.module.AbstractBasicsModule import com.github.spigotbasics.core.module.loader.ModuleInstantiationContext import com.github.spigotbasics.core.storage.NamespacedStorage -import com.github.spigotbasics.modules.basicschatformat.commmands.ColorChatCommand -import com.github.spigotbasics.modules.basicschatformat.data.ChatData -import org.bukkit.event.EventPriority -import org.bukkit.event.player.AsyncPlayerChatEvent +import com.github.spigotbasics.modules.basicschatformat.data.ChatFormatData +import com.github.spigotbasics.modules.basicschatformat.data.ChatFormatStore +import com.github.spigotbasics.modules.basicschatformat.listener.PaperChatEventListener +import com.github.spigotbasics.modules.basicschatformat.listener.SpigotChatEventListener import java.util.UUID import java.util.concurrent.CompletableFuture import java.util.logging.Level -private fun String.escapeFormat(): String { - return this.replace("%", "%%") -} - class BasicsChatFormatModule(context: ModuleInstantiationContext) : AbstractBasicsModule(context) { - private var storage: NamespacedStorage? = null - private val chatData = mutableMapOf() - override val messages = getConfig(ConfigName.MESSAGES, Messages::class.java) + companion object { + lateinit var instance: BasicsChatFormatModule + } - val permissionChatColor = + private val permissionChatColor = permissionManager.createSimplePermission("basics.chatcolor", "Allows access to the /chatcolor command") - val format: Message - get() = config.getMessage("chat-format") - + val permissionNamedColors = + permissionManager.createSimplePermission("basics.chatcolor.named", "Allows access to all named colors") + val permissionHexColors = + permissionManager.createSimplePermission("basics.chatcolor.hex", "Allows access to all hex colors") + val permissionGradientNamed = + permissionManager.createSimplePermission( + "basics.chatcolor.gradient.named", + "Allows access to gradient with named colors only", + ) + val permissionGradientHex = + permissionManager.createSimplePermission( + "basics.chatcolor.gradient.hex", + "Allows access to gradient with hex colors only", + ) + + val chatFormat: Message = config.getMessage("chat-format") val messageColor: String get() = config.getString("default-message-color") ?: "white" + val chatFormatStore = ChatFormatStore(this) + override val messages: Messages = getConfig(ConfigName.MESSAGES, Messages::class.java) - val regex: Regex - get() = - Regex( - config.getString( - "regex-whitelist", - config.getString( - "regex-blacklist", - "\\b(bold|b|italic|em|i|underlined|u|strikethrough|st|obfuscated|obf)\\b", - )!!, - )!!, - ) + private lateinit var storage: NamespacedStorage override fun onEnable() { - storage = createStorage() + instance = this + storage = createStorage(name = "chat_format") if (Spiper.isPaper) { eventBus.subscribe(PaperChatEventListener(this)) } else { - eventBus.subscribe(AsyncPlayerChatEvent::class.java, this::changeChatFormatSpigot, EventPriority.HIGHEST) + eventBus.subscribe( + SpigotChatEventListener(this), + ) } - commandFactory.rawCommandBuilder("chatcolor", permissionChatColor) - .description("Sets your chat color") - .usage("[reset|]") - .executor(ColorChatCommand(this)) - .register() + commandFactory.parsedCommandBuilder("chatcolor", permissionChatColor).mapContext { + usage = "[reset|set] " + path { + playerOnly() + + arguments { + sub("set") + named("color", AnyStringArg("color")) + } + } + + path { + playerOnly() + + arguments { + sub("reset") + } + } + }.executor(ChatColorCommand(this)).register() } override fun reloadConfig() { @@ -65,52 +84,30 @@ class BasicsChatFormatModule(context: ModuleInstantiationContext) : AbstractBasi messages.reload() } - fun changeChatFormatSpigot(event: AsyncPlayerChatEvent) { - event.format = - format - .concerns(event.player) - .tagUnparsed("message", event.message) // TODO: To allow MiniMessage in chat, this should be parsed. - .tagParsed("message-color", "<${getChatDataOrDefault(event.player.uniqueId).color}>") - .toLegacyString().escapeFormat() - } - - fun getChatDataOrDefault(uuid: UUID) = chatData.getOrDefault(uuid, ChatData(messageColor)) - - fun setChatData( - uuid: UUID, - chatData: ChatData, - ) { - this.chatData[uuid] = chatData - } - override fun loadPlayerData(uuid: UUID): CompletableFuture = CompletableFuture.runAsync { - loadPlayerDataBlocking(uuid)?.let { chatData[uuid] = it } + loadPlayerDataBlocking(uuid)?.let { chatFormatStore.chatFormatData[uuid] = it } } override fun savePlayerData(uuid: UUID): CompletableFuture { - val chatDatum = chatData[uuid] + val chatDatum = chatFormatStore.chatFormatData[uuid] val storage = storage ?: error("Storage is null") return storage.setJsonElement(uuid.toString(), Serialization.toJson(chatDatum)) } override fun forgetPlayerData(uuid: UUID) { - chatData.remove(uuid) + chatFormatStore.chatFormatData.remove(uuid) } - private fun loadPlayerDataBlocking(uuid: UUID): ChatData? { - val storage = storage ?: error("Storage is null") + private fun loadPlayerDataBlocking(uuid: UUID): ChatFormatData? { + val storage = storage try { val json = storage.getJsonElement(uuid.toString()).join() ?: return null - return Serialization.fromJson(json, ChatData::class.java) + return Serialization.fromJson(json, ChatFormatData::class.java) } catch (e: Exception) { logger.log(Level.SEVERE, "Failed to load chat data for $uuid", e) } return null } - - fun resetChatColor(uniqueId: UUID) { - forgetPlayerData(uniqueId) - } } diff --git a/modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/ChatColorCommand.kt b/modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/ChatColorCommand.kt new file mode 100644 index 00000000..7f0add26 --- /dev/null +++ b/modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/ChatColorCommand.kt @@ -0,0 +1,69 @@ +package com.github.spigotbasics.modules.basicschatformat + +import com.github.spigotbasics.core.command.parsed.CommandContextExecutor +import com.github.spigotbasics.core.command.parsed.context.MapContext +import com.github.spigotbasics.modules.basicschatformat.data.ChatFormatData +import com.github.spigotbasics.modules.basicschatformat.data.packages.ChatColorPackage +import com.github.spigotbasics.modules.basicschatformat.data.packages.ColorType +import org.bukkit.command.CommandSender +import org.bukkit.entity.Player + +class ChatColorCommand(private val module: BasicsChatFormatModule) : CommandContextExecutor { + override fun execute( + sender: CommandSender, + context: MapContext, + ) { + val player = sender as Player + + val rawColor = context["color"] as String? + if (rawColor == null) { + module.forgetPlayerData(player.uniqueId) + module.messages.colorReset.concerns(player).sendToSender(player) + return + } + val color = clean(rawColor) + if (color == null) { + module.messages.colorInvalid(rawColor).concerns(player).sendToSender(player) + return + } + + var colorPackage: ChatColorPackage? = null + for (value in ColorType.entries) { + if (value.colorPackage.check(color)) { + colorPackage = value.colorPackage + break + } + } + + if (colorPackage == null) { + module.messages.colorInvalid(color).sendToSender(player) + return + } + + if (!colorPackage.hasPermission(player, color)) { + module.coreMessages.noPermission.concerns(player).sendToSender(player) + return + } + + val setupColor = colorPackage.setup(color) + module.chatFormatStore.setChatData(player.uniqueId, ChatFormatData(setupColor)) + module.messages.colorSet("<$setupColor>", rawColor).concerns(player).sendToSender(player) + } + + private fun clean(dirtyColor: String): String? { + val builder = StringBuilder() + for ((index, c) in dirtyColor.withIndex()) { + if (c == '<' && index != 0 || c == '>' && index != dirtyColor.length - 1) { + return null + } + + if (c == '<' || c == '>') { + continue + } + + builder.append(c) + } + + return builder.toString() + } +} diff --git a/modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/Messages.kt b/modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/Messages.kt index ed757000..6754b5fe 100644 --- a/modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/Messages.kt +++ b/modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/Messages.kt @@ -4,10 +4,12 @@ import com.github.spigotbasics.core.config.ConfigInstantiationContext import com.github.spigotbasics.core.config.SavedConfig class Messages(context: ConfigInstantiationContext) : SavedConfig(context) { - fun colorSet(color: String) = - getMessage("color-set") - .tagParsed("selected-color-parsed", "<$color>") - .tagUnparsed("selected-color-name", color) + fun colorSet( + colorParsed: String, + colorRaw: String, + ) = getMessage("color-set") + .tagParsed("selected-color-parsed", colorParsed) + .tagUnparsed("selected-color-name", colorRaw) fun colorInvalid(color: String) = getMessage("color-invalid") diff --git a/modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/commmands/ColorChatCommand.kt b/modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/commmands/ColorChatCommand.kt deleted file mode 100644 index 110049ae..00000000 --- a/modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/commmands/ColorChatCommand.kt +++ /dev/null @@ -1,53 +0,0 @@ -package com.github.spigotbasics.modules.basicschatformat.commmands - -import com.github.spigotbasics.core.command.common.BasicsCommandExecutor -import com.github.spigotbasics.core.command.common.CommandResult -import com.github.spigotbasics.core.command.raw.RawCommandContext -import com.github.spigotbasics.core.extensions.addAnd -import com.github.spigotbasics.core.extensions.partialMatches -import com.github.spigotbasics.modules.basicschatformat.BasicsChatFormatModule -import com.github.spigotbasics.modules.basicschatformat.data.ChatData -import org.bukkit.ChatColor -import org.bukkit.entity.Player - -class ColorChatCommand(private val module: BasicsChatFormatModule) : BasicsCommandExecutor(module) { - override fun execute(context: RawCommandContext): CommandResult { - if (context.sender !is Player) { - module.plugin.messages.commandNotFromConsole.sendToSender(context.sender) - return CommandResult.SUCCESS - } - val player = context.sender as Player - - val color: String - if (context.args.size == 1) { - if (context.args[0].equals("reset", ignoreCase = true)) { - module.resetChatColor(player.uniqueId) - module.messages.colorReset.sendToSender(player) - return CommandResult.SUCCESS - } - - color = context.args[0] - } else { - return CommandResult.USAGE - } - - if (color != module.messageColor && !module.regex.matches(color)) { - module.messages.colorInvalid(color).sendToSender(player) - return CommandResult.SUCCESS - } - - val chatDatum = ChatData(color) - module.setChatData(player.uniqueId, chatDatum) - module.messages.colorSet(color).sendToSender(player) - - return CommandResult.SUCCESS - } - - override fun tabComplete(context: RawCommandContext): List { - return if (context.args.size == 1) { - return ChatColor.entries.map { it.name.lowercase() }.addAnd("reset").partialMatches(context.args[0]) - } else { - mutableListOf() - } - } -} diff --git a/modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/data/ChatData.kt b/modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/data/ChatFormatData.kt similarity index 58% rename from modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/data/ChatData.kt rename to modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/data/ChatFormatData.kt index c626d9ae..f00d7b23 100644 --- a/modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/data/ChatData.kt +++ b/modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/data/ChatFormatData.kt @@ -1,3 +1,3 @@ package com.github.spigotbasics.modules.basicschatformat.data -data class ChatData(var color: String) +data class ChatFormatData(var color: String) diff --git a/modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/data/ChatFormatStore.kt b/modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/data/ChatFormatStore.kt new file mode 100644 index 00000000..58fa3ae7 --- /dev/null +++ b/modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/data/ChatFormatStore.kt @@ -0,0 +1,17 @@ +package com.github.spigotbasics.modules.basicschatformat.data + +import com.github.spigotbasics.modules.basicschatformat.BasicsChatFormatModule +import java.util.UUID + +class ChatFormatStore(private val module: BasicsChatFormatModule) { + val chatFormatData = mutableMapOf() + + fun setChatData( + uuid: UUID, + chatData: ChatFormatData, + ) { + this.chatFormatData[uuid] = chatData + } + + fun getChatDataOrDefault(uuid: UUID) = chatFormatData.getOrDefault(uuid, ChatFormatData(module.messageColor)) +} diff --git a/modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/data/packages/ChatColorPackage.kt b/modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/data/packages/ChatColorPackage.kt new file mode 100644 index 00000000..dda13b20 --- /dev/null +++ b/modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/data/packages/ChatColorPackage.kt @@ -0,0 +1,33 @@ +package com.github.spigotbasics.modules.basicschatformat.data.packages + +import org.bukkit.permissions.Permissible + +/** + * A Package of ChatColors that checks some format for the validity of a color + */ +interface ChatColorPackage { + /** + * Checks a given color string for its validity + * @param color the color to check + * @return true if the color is valid, otherwise false + */ + fun check(color: String): Boolean + + /** + * Sets up a color which has already been checked with [check] + * + * @param color the color + * @return the setup color for insertion + */ + fun setup(color: String): String + + /** + * Checks if a permissible has permission for a given color + * @param color the color to check + * @return true if the permissible to check is valid for this color + */ + fun hasPermission( + permissible: Permissible, + color: String, + ): Boolean +} diff --git a/modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/data/packages/ColorType.kt b/modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/data/packages/ColorType.kt new file mode 100644 index 00000000..516e30fb --- /dev/null +++ b/modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/data/packages/ColorType.kt @@ -0,0 +1,8 @@ +package com.github.spigotbasics.modules.basicschatformat.data.packages + +enum class ColorType(val colorPackage: ChatColorPackage) { + GRADIENT_NAMED(GradientNamedPackage), + GRADIENT_HEX(GradientHexPackage), + NAMED_COLOR(NamedColorPackage), + HEX_COLOR(HexColorPackage), +} diff --git a/modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/data/packages/GradientHexPackage.kt b/modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/data/packages/GradientHexPackage.kt new file mode 100644 index 00000000..e87b5d79 --- /dev/null +++ b/modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/data/packages/GradientHexPackage.kt @@ -0,0 +1,48 @@ +package com.github.spigotbasics.modules.basicschatformat.data.packages + +import com.github.spigotbasics.modules.basicschatformat.BasicsChatFormatModule +import org.bukkit.permissions.Permissible + +internal object GradientHexPackage : ChatColorPackage { + override fun check(color: String): Boolean { + val split = color.split(":") + if (split.size < 2 || split.size > 3) { + return false + } + + for (s in split) { + if (!HexColorPackage.check(s)) return false + } + return true + } + + override fun setup(color: String): String { + val builder = StringBuilder().append("gradient:") + val split = color.split(":") + for (s in split) { + builder.append(s).append(":") + } + + if (builder[builder.length - 1] == ':') { + builder.deleteAt(builder.length - 1) + } + return builder.toString() + } + + override fun hasPermission( + permissible: Permissible, + color: String, + ): Boolean { + if (permissible.hasPermission(BasicsChatFormatModule.instance.permissionGradientHex)) { + return true + } + + val split = color.split(":") + for (s in split) { + if (!HexColorPackage.hasPermission(permissible, s)) { + return false + } + } + return true + } +} diff --git a/modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/data/packages/GradientNamedPackage.kt b/modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/data/packages/GradientNamedPackage.kt new file mode 100644 index 00000000..039fc161 --- /dev/null +++ b/modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/data/packages/GradientNamedPackage.kt @@ -0,0 +1,50 @@ +package com.github.spigotbasics.modules.basicschatformat.data.packages + +import com.github.spigotbasics.modules.basicschatformat.BasicsChatFormatModule +import org.bukkit.permissions.Permissible + +internal object GradientNamedPackage : ChatColorPackage { + override fun check(color: String): Boolean { + val split = color.split(":") + if (split.size < 2 || split.size > 3) { + return false + } + + for (s in split) { + if (!NamedColorPackage.check(s)) { + return false + } + } + return true + } + + override fun setup(color: String): String { + val builder = StringBuilder().append("gradient:") + val split = color.split(":") + for (s in split) { + builder.append(s).append(":") + } + + if (builder[builder.length - 1] == ':') { + builder.deleteAt(builder.length - 1) + } + return builder.toString() + } + + override fun hasPermission( + permissible: Permissible, + color: String, + ): Boolean { + if (permissible.hasPermission(BasicsChatFormatModule.instance.permissionGradientNamed)) { + return true + } + + val split = color.split(":") + for (s in split) { + if (!NamedColorPackage.hasPermission(permissible, s)) { + return false + } + } + return true + } +} diff --git a/modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/data/packages/HexColorPackage.kt b/modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/data/packages/HexColorPackage.kt new file mode 100644 index 00000000..b6de9676 --- /dev/null +++ b/modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/data/packages/HexColorPackage.kt @@ -0,0 +1,36 @@ +package com.github.spigotbasics.modules.basicschatformat.data.packages + +import com.github.spigotbasics.modules.basicschatformat.BasicsChatFormatModule +import org.bukkit.permissions.Permissible + +internal object HexColorPackage : ChatColorPackage { + private val ZERO = Character.getNumericValue('0') + private val NINE = Character.getNumericValue('9') + private val UPPER_A = Character.getNumericValue('A') + private val LOWER_A = Character.getNumericValue('a') + private val UPPER_F = Character.getNumericValue('F') + private val LOWER_F = Character.getNumericValue('f') + + override fun check(color: String): Boolean { + for ((index, c) in color.withIndex()) { + if (index == 0) continue + val number = Character.getNumericValue(c) + if (!(number in ZERO..NINE || number in UPPER_A..UPPER_F || number in LOWER_A..LOWER_F)) return false + } + return color.startsWith("#") && color.length <= 7 + } + + override fun setup(color: String): String { + return "color:$color" + } + + override fun hasPermission( + permissible: Permissible, + color: String, + ): Boolean { + return permissible.hasPermission(BasicsChatFormatModule.instance.permissionHexColors) || + permissible.hasPermission( + "basics.chatcolor.${color.uppercase()}", + ) + } +} diff --git a/modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/data/packages/NamedColorPackage.kt b/modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/data/packages/NamedColorPackage.kt new file mode 100644 index 00000000..47e4eb0b --- /dev/null +++ b/modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/data/packages/NamedColorPackage.kt @@ -0,0 +1,44 @@ +package com.github.spigotbasics.modules.basicschatformat.data.packages + +import com.github.spigotbasics.modules.basicschatformat.BasicsChatFormatModule +import org.bukkit.permissions.Permissible + +internal object NamedColorPackage : ChatColorPackage { + private val NAMED_COLORS = + setOf( + "black", + "dark_blue", + "dark_green", + "dark_aqua", + "dark_red", + "dark_purple", + "gold", + "gray", + "dark_gray", + "blue", + "green", + "aqua", + "red", + "light_purple", + "yellow", + "white", + ) + + override fun check(color: String): Boolean { + return NAMED_COLORS.contains(color) + } + + override fun setup(color: String): String { + return "color:$color" + } + + override fun hasPermission( + permissible: Permissible, + color: String, + ): Boolean { + return permissible.hasPermission(BasicsChatFormatModule.instance.permissionNamedColors) || + permissible.hasPermission( + "basics.chatcolor.$color".lowercase(), + ) + } +} diff --git a/modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/PaperChatEventListener.kt b/modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/listener/PaperChatEventListener.kt similarity index 74% rename from modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/PaperChatEventListener.kt rename to modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/listener/PaperChatEventListener.kt index c249b281..79efc893 100644 --- a/modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/PaperChatEventListener.kt +++ b/modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/listener/PaperChatEventListener.kt @@ -1,5 +1,6 @@ -package com.github.spigotbasics.modules.basicschatformat +package com.github.spigotbasics.modules.basicschatformat.listener +import com.github.spigotbasics.modules.basicschatformat.BasicsChatFormatModule import com.github.spigotbasics.pipe.SerializedMiniMessage import com.github.spigotbasics.pipe.paper.NativeComponentConverter import io.papermc.paper.event.player.AsyncChatEvent @@ -19,14 +20,14 @@ class PaperChatEventListener(private val module: BasicsChatFormatModule) : Liste } } - fun formatMessage( + private fun formatMessage( player: Player, message: Component, ): Component { val serialized = - module.format.concerns(player) + module.chatFormat.concerns(player) .tagMiniMessage("message", SerializedMiniMessage(mini.serialize(message))) - .tagParsed("message-color", "<${module.getChatDataOrDefault(player.uniqueId).color}>") + .tagParsed("message-color", "<${module.chatFormatStore.getChatDataOrDefault(player.uniqueId).color}}>") .serialize() val component = NativeComponentConverter.toNativeComponent(serialized) return component diff --git a/modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/listener/SpigotChatEventListener.kt b/modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/listener/SpigotChatEventListener.kt new file mode 100644 index 00000000..437fc324 --- /dev/null +++ b/modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/listener/SpigotChatEventListener.kt @@ -0,0 +1,21 @@ +package com.github.spigotbasics.modules.basicschatformat.listener + +import com.github.spigotbasics.modules.basicschatformat.BasicsChatFormatModule +import org.bukkit.event.EventHandler +import org.bukkit.event.Listener +import org.bukkit.event.player.AsyncPlayerChatEvent + +private fun String.escapeFormat(): String { + return this.replace("%", "%%") +} + +class SpigotChatEventListener(private val module: BasicsChatFormatModule) : Listener { + @EventHandler + fun onSpigotChat(event: AsyncPlayerChatEvent) { + event.format = + module.chatFormat.concerns(event.player) + .tagUnparsed("message", event.message) // TODO: To allow MiniMessage in chat, this should be parsed. + .tagParsed("message-color", "<${module.chatFormatStore.getChatDataOrDefault(event.player.uniqueId).color}>").toLegacyString() + .escapeFormat() + } +} diff --git a/modules/basics-chat-format/src/main/resources/basics-module.yml b/modules/basics-chat-format/src/main/resources/basics-module.yml index e4e38064..16f47073 100644 --- a/modules/basics-chat-format/src/main/resources/basics-module.yml +++ b/modules/basics-chat-format/src/main/resources/basics-module.yml @@ -1,4 +1,4 @@ main-class: com.github.spigotbasics.modules.basicschatformat.BasicsChatFormatModule name: basics-chat-format version: ${moduleVersion} -description: "Custom chat formatting" \ No newline at end of file +description: "Custom chat formatting" From b805cdf9a16a2e4caea7f100b0955c547eeef47c Mon Sep 17 00:00:00 2001 From: Miles Holder Date: Wed, 8 May 2024 18:47:41 -0500 Subject: [PATCH 03/13] cleanup disposal --- .../BasicsChatFormatModule.kt | 2 +- modules/basics-disposal/README.md | 3 ++ .../basicsdisposal/BasicsDisposalModule.kt | 35 +++++++++++++------ 3 files changed, 29 insertions(+), 11 deletions(-) create mode 100644 modules/basics-disposal/README.md diff --git a/modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/BasicsChatFormatModule.kt b/modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/BasicsChatFormatModule.kt index 8e72d6da..8de8d908 100644 --- a/modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/BasicsChatFormatModule.kt +++ b/modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/BasicsChatFormatModule.kt @@ -91,7 +91,7 @@ class BasicsChatFormatModule(context: ModuleInstantiationContext) : AbstractBasi override fun savePlayerData(uuid: UUID): CompletableFuture { val chatDatum = chatFormatStore.chatFormatData[uuid] - val storage = storage ?: error("Storage is null") + val storage = storage return storage.setJsonElement(uuid.toString(), Serialization.toJson(chatDatum)) } diff --git a/modules/basics-disposal/README.md b/modules/basics-disposal/README.md new file mode 100644 index 00000000..d2222f56 --- /dev/null +++ b/modules/basics-disposal/README.md @@ -0,0 +1,3 @@ +| Command | Permission | +|-------------|-----------------| +| `/disposal` | basics.disposal | diff --git a/modules/basics-disposal/src/main/kotlin/com/github/spigotbasics/modules/basicsdisposal/BasicsDisposalModule.kt b/modules/basics-disposal/src/main/kotlin/com/github/spigotbasics/modules/basicsdisposal/BasicsDisposalModule.kt index b172c2b0..93b1710b 100644 --- a/modules/basics-disposal/src/main/kotlin/com/github/spigotbasics/modules/basicsdisposal/BasicsDisposalModule.kt +++ b/modules/basics-disposal/src/main/kotlin/com/github/spigotbasics/modules/basicsdisposal/BasicsDisposalModule.kt @@ -1,22 +1,37 @@ package com.github.spigotbasics.modules.basicsdisposal import com.github.spigotbasics.core.command.common.BasicsCommandContextHandler -import com.github.spigotbasics.core.command.common.CommandResult +import com.github.spigotbasics.core.command.parsed.CommandContextExecutor +import com.github.spigotbasics.core.command.parsed.context.MapContext import com.github.spigotbasics.core.module.AbstractBasicsModule import com.github.spigotbasics.core.module.loader.ModuleInstantiationContext import org.bukkit.Bukkit +import org.bukkit.command.CommandSender +import org.bukkit.entity.Player -class BasicsDisposalModule(context: ModuleInstantiationContext) : AbstractBasicsModule(context), BasicsCommandContextHandler { - val permission = permissionManager.createSimplePermission("basics.disposal", "Allows to dispose items using /disposal") +class BasicsDisposalModule(context: ModuleInstantiationContext) : + AbstractBasicsModule(context), + BasicsCommandContextHandler { + private val permission = + permissionManager.createSimplePermission("basics.disposal", "Allows to dispose items using /disposal") val title get() = messages.getMessage("inventory-title") override fun onEnable() { - commandFactory.rawCommandBuilder("disposal", permission) - .executor { content -> - val player = requirePlayer(content.sender) - val inv = Bukkit.createInventory(null, 6 * 9, title.toLegacyString()) - player.openInventory(inv) - CommandResult.SUCCESS - }.register() + commandFactory.parsedCommandBuilder("disposal", permission).mapContext { + path { + playerOnly() + } + }.executor( + object : CommandContextExecutor { + override fun execute( + sender: CommandSender, + context: MapContext, + ) { + val player = sender as Player + val inv = Bukkit.createInventory(null, 6 * 9, title.toLegacyString()) + player.openInventory(inv) + } + }, + ).register() } } From df5a4ef06180e412ef0f1ce149194511f6642545 Mon Sep 17 00:00:00 2001 From: Miles Holder Date: Thu, 9 May 2024 08:44:07 -0500 Subject: [PATCH 04/13] cleanup enchant --- .../parsed/arguments/BukkitRegistryArg.kt | 32 ++++ .../listener/SpigotChatEventListener.kt | 5 +- modules/basics-enchant/README.md | 12 +- .../basicsenchant/BasicsEnchantModule.kt | 139 +++++++----------- .../EnchantOperationMessageTag.kt | 23 --- .../modules/basicsenchant/Messages.kt | 76 ++++++++++ .../command/EnchantmentCommandOther.kt | 66 +++++++++ .../command/EnchantmentCommandSelf.kt | 37 +++++ .../src/main/resources/basics-module.yml | 4 +- .../src/main/resources/messages.yml | 13 +- 10 files changed, 290 insertions(+), 117 deletions(-) create mode 100644 core/src/main/kotlin/com/github/spigotbasics/core/command/parsed/arguments/BukkitRegistryArg.kt delete mode 100644 modules/basics-enchant/src/main/kotlin/com/github/spigotbasics/modules/basicsenchant/EnchantOperationMessageTag.kt create mode 100644 modules/basics-enchant/src/main/kotlin/com/github/spigotbasics/modules/basicsenchant/Messages.kt create mode 100644 modules/basics-enchant/src/main/kotlin/com/github/spigotbasics/modules/basicsenchant/command/EnchantmentCommandOther.kt create mode 100644 modules/basics-enchant/src/main/kotlin/com/github/spigotbasics/modules/basicsenchant/command/EnchantmentCommandSelf.kt diff --git a/core/src/main/kotlin/com/github/spigotbasics/core/command/parsed/arguments/BukkitRegistryArg.kt b/core/src/main/kotlin/com/github/spigotbasics/core/command/parsed/arguments/BukkitRegistryArg.kt new file mode 100644 index 00000000..28fbfbf6 --- /dev/null +++ b/core/src/main/kotlin/com/github/spigotbasics/core/command/parsed/arguments/BukkitRegistryArg.kt @@ -0,0 +1,32 @@ +package com.github.spigotbasics.core.command.parsed.arguments + +import org.bukkit.Bukkit +import org.bukkit.Keyed +import org.bukkit.NamespacedKey +import org.bukkit.Registry +import org.bukkit.command.CommandSender +import java.util.stream.Collectors + +class BukkitRegistryArg(name: String, registryClass: Class) : CommandArgument(name) { + private val registry: Registry = Bukkit.getRegistry(registryClass) ?: error("$registryClass is not a bukkit registry type") + + override fun parse( + sender: CommandSender, + value: String, + ): T? { + return if (value.isBlank()) null else registry.get(NamespacedKey.fromString(value) ?: return null) + } + + override fun tabComplete( + sender: CommandSender, + typing: String, + ): List { + return registry.stream().map { entry -> + val namespacedKeyed = entry.key + if (namespacedKeyed.namespace == NamespacedKey.MINECRAFT) { + return@map namespacedKeyed.key + } + return@map namespacedKeyed.toString() + }.collect(Collectors.toList()) + } +} diff --git a/modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/listener/SpigotChatEventListener.kt b/modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/listener/SpigotChatEventListener.kt index 437fc324..895d264a 100644 --- a/modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/listener/SpigotChatEventListener.kt +++ b/modules/basics-chat-format/src/main/kotlin/com/github/spigotbasics/modules/basicschatformat/listener/SpigotChatEventListener.kt @@ -15,7 +15,10 @@ class SpigotChatEventListener(private val module: BasicsChatFormatModule) : List event.format = module.chatFormat.concerns(event.player) .tagUnparsed("message", event.message) // TODO: To allow MiniMessage in chat, this should be parsed. - .tagParsed("message-color", "<${module.chatFormatStore.getChatDataOrDefault(event.player.uniqueId).color}>").toLegacyString() + .tagParsed( + "message-color", + "<${module.chatFormatStore.getChatDataOrDefault(event.player.uniqueId).color}>", + ).toLegacyString() .escapeFormat() } } diff --git a/modules/basics-enchant/README.md b/modules/basics-enchant/README.md index c2889dfe..68374091 100644 --- a/modules/basics-enchant/README.md +++ b/modules/basics-enchant/README.md @@ -1,9 +1,13 @@ -| Command | Permission | -|------------------------------|-----------------------| -| `/enchant [level]` | basics.enchant | +| Command | Permission | +|---------------------------------------|----------------------| +| `/enchant [level]` | basics.enchant | +| `/enchant [level]` | basics.enchant.other | > [!NOTE] > Players additionally require enchantment-specific permissions: `basics.enchant.`. > [!NOTE] -> Enchanting items with unsafe levels additionally requires permission `basics.enchant.unsafe`. +> Enchanting items with unsafe levels additionally requires permission `basics.enchant.unsafe.level`. + +> [!NOTE] +> Enchanting items with unsafe enchants additional requires permission `basics.enchant.unsafe.enchant` diff --git a/modules/basics-enchant/src/main/kotlin/com/github/spigotbasics/modules/basicsenchant/BasicsEnchantModule.kt b/modules/basics-enchant/src/main/kotlin/com/github/spigotbasics/modules/basicsenchant/BasicsEnchantModule.kt index 75785a7f..a38a2c7f 100644 --- a/modules/basics-enchant/src/main/kotlin/com/github/spigotbasics/modules/basicsenchant/BasicsEnchantModule.kt +++ b/modules/basics-enchant/src/main/kotlin/com/github/spigotbasics/modules/basicsenchant/BasicsEnchantModule.kt @@ -1,107 +1,78 @@ package com.github.spigotbasics.modules.basicsenchant -import com.github.spigotbasics.core.command.common.BasicsCommandExecutor -import com.github.spigotbasics.core.command.common.CommandResult -import com.github.spigotbasics.core.command.raw.RawCommandContext -import com.github.spigotbasics.core.extensions.partialMatches -import com.github.spigotbasics.core.extensions.toHumanReadable +import com.github.spigotbasics.core.command.parsed.arguments.BukkitRegistryArg +import com.github.spigotbasics.core.command.parsed.arguments.IntRangeArg +import com.github.spigotbasics.core.command.parsed.arguments.SelectorMultiEntityArg +import com.github.spigotbasics.core.command.parsed.arguments.SelectorSinglePlayerArg +import com.github.spigotbasics.core.config.ConfigName import com.github.spigotbasics.core.module.AbstractBasicsModule import com.github.spigotbasics.core.module.loader.ModuleInstantiationContext -import org.bukkit.Bukkit +import com.github.spigotbasics.modules.basicsenchant.command.EnchantmentCommandOther +import com.github.spigotbasics.modules.basicsenchant.command.EnchantmentCommandSelf import org.bukkit.enchantments.Enchantment -import org.bukkit.entity.Player class BasicsEnchantModule(context: ModuleInstantiationContext) : AbstractBasicsModule(context) { - val permission = + private val commandPermission = + permissionManager.createSimplePermission("basics.enchant", "Allows players access to the /enchant command") + private val commandOtherPermission = permissionManager.createSimplePermission( + "basics.enchant.other", + "Allows players access to the /enchant command to enchant others" + ) + val unsafeLevelsPermission = permissionManager.createSimplePermission( - "basics.enchant", - "Allows the player to enchant items", + "basics.enchant.unsafe.level", + "Allows assignment of unsafe levels for enchantments", ) - - val permissionUnsafeLevels = + val unsafeEnchantPermission = permissionManager.createSimplePermission( - "basics.enchant.allowunsafe", - "Allows the player to enchant items with unsafe levels", + "basics.enchant.unsafe.enchant", + "Allows assignment of unsafe enchantments to item", ) - val enchantments = Bukkit.getRegistry(Enchantment::class.java)?.map { it.key.key.lowercase() }?.toList() ?: emptyList() - - val enchantmentPermissions = - Bukkit.getRegistry(Enchantment::class.java)?.associateWith { enchantment -> - val name = enchantment.key.key.lowercase() - permissionManager.createSimplePermission( - "basics.enchant.$name", - "Allows the player to enchant items with the ${name.toHumanReadable()} enchantment", - ) - } ?: emptyMap() - - fun msgEnchantedSelf(tag: EnchantOperationMessageTag) = messages.getMessage("enchanted-self").tags(tag) - - // TODO: Cannot enchant others stuff yet - fun msgEnchantedOthers( - tag: EnchantOperationMessageTag, - player: Player, - ) = messages.getMessage("enchanted-others") - .tags(tag) - .concerns(player) - - fun msgRemovedSelf(tag: EnchantOperationMessageTag) = messages.getMessage("removed-self").tags(tag) + override val messages: Messages = getConfig(ConfigName.MESSAGES, Messages::class.java) override fun onEnable() { - commandFactory.rawCommandBuilder("enchant", permission) - .description("Enchants the item in the player's hand") - .usage(" [level]") - .executor(EnchantExecutor()) - .register() - } - - inner class EnchantExecutor : BasicsCommandExecutor(this@BasicsEnchantModule) { - override fun execute(context: RawCommandContext): CommandResult { - val player = requirePlayerOrMustSpecifyPlayerFromConsole(context.sender) // TODO: Create a requirePlayer(Sender) method - val args = context.args - if (args.size == 0) return CommandResult.USAGE - val item = requireItemInHand(player) - val enchantment = getEnchantment(args[0]) ?: throw failInvalidArgument(args[0]).asException() - var desiredLevel = (item.itemMeta?.getEnchantLevel(enchantment) ?: 0) + 1 - val maxLevel = enchantment.maxLevel - if (args.size > 1) { - desiredLevel = args[1].toIntOrNull() ?: throw failInvalidArgument(args[1]).asException() + val instance = this + commandFactory.parsedCommandBuilder("enchant", commandPermission).mapContext { + val basicExecutor = EnchantmentCommandSelf(instance) + val otherExecutor = EnchantmentCommandOther(instance) + usage = " [level]" + path { + playerOnly() + arguments { + named("enchantment", BukkitRegistryArg("enchantment", Enchantment::class.java)) + } + executor(basicExecutor) } - // Unsafe levels require extra perm - if (desiredLevel > maxLevel) { - requirePermission(context.sender, permissionUnsafeLevels) + path { + playerOnly() + arguments { + named("enchantment", BukkitRegistryArg("enchantment", Enchantment::class.java)) + named("level", IntRangeArg("level", { 0 }, { 255 })) + executor(basicExecutor) + } } - // Enchantment-specific permissions - enchantmentPermissions[enchantment]?.let { requirePermission(context.sender, it) } - - val tag = EnchantOperationMessageTag(item, enchantment, desiredLevel) - - if (desiredLevel == 0) { - item.removeEnchantment(enchantment) // TODO: message "removed enchantment" - msgRemovedSelf(tag).sendToPlayer(player) - return CommandResult.SUCCESS + path { + permissions(commandOtherPermission) + arguments { + named("targets", SelectorMultiEntityArg("targets")) + named("enchantment", BukkitRegistryArg("enchantment", Enchantment::class.java)) + named("level", IntRangeArg("level", { 0 }, { 255 })) + executor(otherExecutor) + } } - item.addUnsafeEnchantment( - enchantment, - desiredLevel, - ) // TODO: Separate permission for unsafe enchants, separate permission for max-level and for enchantment type - msgEnchantedSelf(tag).sendToPlayer(player) - return CommandResult.SUCCESS - } - - override fun tabComplete(context: RawCommandContext): List? { - val args = context.args - if (args.size == 1) { - return enchantments.partialMatches(args[0]) + path { + permissions(commandOtherPermission) + arguments { + named("player", SelectorSinglePlayerArg("player")) + named("enchantment", BukkitRegistryArg("enchantment", Enchantment::class.java)) + named("level", IntRangeArg("level", { 0 }, { 255 })) + executor(otherExecutor) + } } - return null - } - - private fun getEnchantment(name: String): Enchantment? { - return Bukkit.getRegistry(Enchantment::class.java)?.match(name.lowercase()) - } + }.register() } } diff --git a/modules/basics-enchant/src/main/kotlin/com/github/spigotbasics/modules/basicsenchant/EnchantOperationMessageTag.kt b/modules/basics-enchant/src/main/kotlin/com/github/spigotbasics/modules/basicsenchant/EnchantOperationMessageTag.kt deleted file mode 100644 index 49d37680..00000000 --- a/modules/basics-enchant/src/main/kotlin/com/github/spigotbasics/modules/basicsenchant/EnchantOperationMessageTag.kt +++ /dev/null @@ -1,23 +0,0 @@ -package com.github.spigotbasics.modules.basicsenchant - -import com.github.spigotbasics.core.extensions.toHumanReadable -import com.github.spigotbasics.core.extensions.toRoman -import com.github.spigotbasics.core.messages.tags.CustomTag -import com.github.spigotbasics.core.messages.tags.MessageTagProvider -import org.bukkit.enchantments.Enchantment -import org.bukkit.inventory.ItemStack - -data class EnchantOperationMessageTag( - val item: ItemStack, - val enchantment: Enchantment, - val level: Int, -) : MessageTagProvider { - override fun getMessageTags(): List { - return listOf( - CustomTag.parsed("item", item.type.name.toHumanReadable()), - CustomTag.parsed("enchantment", enchantment.key.key.toHumanReadable()), - CustomTag.parsed("level", level.toString()), - CustomTag.parsed("roman-level", level.toRoman()), - ) - } -} diff --git a/modules/basics-enchant/src/main/kotlin/com/github/spigotbasics/modules/basicsenchant/Messages.kt b/modules/basics-enchant/src/main/kotlin/com/github/spigotbasics/modules/basicsenchant/Messages.kt new file mode 100644 index 00000000..ae2b0c29 --- /dev/null +++ b/modules/basics-enchant/src/main/kotlin/com/github/spigotbasics/modules/basicsenchant/Messages.kt @@ -0,0 +1,76 @@ +package com.github.spigotbasics.modules.basicsenchant + +import com.github.spigotbasics.core.config.ConfigInstantiationContext +import com.github.spigotbasics.core.config.SavedConfig +import com.github.spigotbasics.core.extensions.toHumanReadable +import com.github.spigotbasics.core.extensions.toRoman +import com.github.spigotbasics.core.messages.Message +import org.bukkit.enchantments.Enchantment +import org.bukkit.entity.LivingEntity +import org.bukkit.entity.Player +import org.bukkit.inventory.ItemStack + +class Messages(context: ConfigInstantiationContext) : SavedConfig(context) { + fun enchantmentSelf( + item: ItemStack, + enchantment: Enchantment, + level: Int, + ): Message = modifyEnchantMessage(getMessage("enchanted-self"), item, enchantment, level) + + fun enchantEntity( + entity: LivingEntity, + item: ItemStack, + enchantment: Enchantment, + level: Int, + ): Message = + modifyEnchantMessage( + getMessage("enchanted-entity"), + item, + enchantment, + level, + ).tagParsed("entity", entity.type.key.key.toHumanReadable()) + + fun enchantPlayer( + player: Player, + item: ItemStack, + enchantment: Enchantment, + level: Int, + ): Message = modifyEnchantMessage(getMessage("enchanted-others"), item, enchantment, level).tagParsed("player", player.name) + + fun enchantInvalidCombinationSelf( + item: ItemStack, + enchantment: Enchantment, + ): Message = + getMessage("enchanted-invalid-combination-self") + .tagParsed("item", item.type.name.toHumanReadable()) + .tagParsed("enchantment", enchantment.key.key.toHumanReadable()) + + fun enchantInvalidCombinationEntity( + entity: LivingEntity, + item: ItemStack, + enchantment: Enchantment, + ): Message = + getMessage("enchanted-invalid-combination-entity") + .tagParsed("entity", entity.type.key.key.toHumanReadable()) + .tagParsed("item", item.type.name.toHumanReadable()) + .tagParsed("enchantment", enchantment.key.key.toHumanReadable()) + + fun enchantInvalidCombinationOther( + item: ItemStack, + enchantment: Enchantment, + ): Message = + getMessage("enchanted-invalid-combination-others") + .tagParsed("item", item.type.name.toHumanReadable()) + .tagParsed("enchantment", enchantment.key.key.toHumanReadable()) + + private fun modifyEnchantMessage( + message: Message, + item: ItemStack, + enchantment: Enchantment, + level: Int, + ): Message = + message.tagParsed("item", item.type.name.toHumanReadable()) + .tagParsed("enchantment", enchantment.key.key.toHumanReadable()) + .tagParsed("level", level.toString()) + .tagUnparsed("roman-level", level.toRoman()) +} diff --git a/modules/basics-enchant/src/main/kotlin/com/github/spigotbasics/modules/basicsenchant/command/EnchantmentCommandOther.kt b/modules/basics-enchant/src/main/kotlin/com/github/spigotbasics/modules/basicsenchant/command/EnchantmentCommandOther.kt new file mode 100644 index 00000000..e5183fd6 --- /dev/null +++ b/modules/basics-enchant/src/main/kotlin/com/github/spigotbasics/modules/basicsenchant/command/EnchantmentCommandOther.kt @@ -0,0 +1,66 @@ +package com.github.spigotbasics.modules.basicsenchant.command + +import com.github.spigotbasics.core.command.parsed.CommandContextExecutor +import com.github.spigotbasics.core.command.parsed.context.MapContext +import com.github.spigotbasics.core.messages.Message +import com.github.spigotbasics.modules.basicsenchant.BasicsEnchantModule +import org.bukkit.Material +import org.bukkit.command.CommandSender +import org.bukkit.enchantments.Enchantment +import org.bukkit.entity.LivingEntity +import org.bukkit.entity.Player + +class EnchantmentCommandOther(private val module: BasicsEnchantModule) : CommandContextExecutor { + override fun execute( + sender: CommandSender, + context: MapContext, + ) { + val targets = mutableListOf() + if (context["targets"] is List<*>) { + targets.addAll((context["targets"] as List<*>).filterIsInstance()) + } else if (context["player"] is Player) { + targets.add(context["player"] as LivingEntity) + } + + val enchantment = context["enchantment"] as Enchantment + val level = context["level"] as Int + + if (level > enchantment.maxLevel && !sender.hasPermission(module.unsafeLevelsPermission)) { + module.coreMessages.invalidValueForArgument("level", level.toString()).concerns(sender as? Player).sendToSender(sender) + return + } + + targets.forEach { + val equipment = it.equipment ?: return + val item = equipment.itemInMainHand + if (item.type == Material.AIR) { + return@forEach + } + + if (!enchantment.canEnchantItem(item) && sender.hasPermission(module.unsafeEnchantPermission)) { + val message: Message = + if (it is Player) { + module.messages.enchantInvalidCombinationOther(item, enchantment).concerns(it) + } else { + module.messages.enchantInvalidCombinationEntity(it, item, enchantment) + } + message.sendToSender(sender) + return + } + + val meta = item.itemMeta!! + meta.addEnchant(enchantment, level, sender.hasPermission(module.unsafeLevelsPermission)) + item.itemMeta = meta + equipment.setItemInMainHand(item) + + val message = + if (it is Player) { + module.messages.enchantPlayer(it, item, enchantment, level).concerns(it) + } else { + module.messages.enchantEntity(it, item, enchantment, level) + } + + message.sendToSender(sender) + } + } +} diff --git a/modules/basics-enchant/src/main/kotlin/com/github/spigotbasics/modules/basicsenchant/command/EnchantmentCommandSelf.kt b/modules/basics-enchant/src/main/kotlin/com/github/spigotbasics/modules/basicsenchant/command/EnchantmentCommandSelf.kt new file mode 100644 index 00000000..b71be38e --- /dev/null +++ b/modules/basics-enchant/src/main/kotlin/com/github/spigotbasics/modules/basicsenchant/command/EnchantmentCommandSelf.kt @@ -0,0 +1,37 @@ +package com.github.spigotbasics.modules.basicsenchant.command + +import com.github.spigotbasics.core.command.parsed.CommandContextExecutor +import com.github.spigotbasics.core.command.parsed.context.MapContext +import com.github.spigotbasics.modules.basicsenchant.BasicsEnchantModule +import org.bukkit.command.CommandSender +import org.bukkit.enchantments.Enchantment +import org.bukkit.entity.Player + +class EnchantmentCommandSelf(private val module: BasicsEnchantModule) : CommandContextExecutor { + override fun execute( + sender: CommandSender, + context: MapContext, + ) { + val player = sender as Player + val enchantment = context["enchantment"] as Enchantment + val level = context["level"] as Int? ?: 1 + + if (level > enchantment.maxLevel && !player.hasPermission(module.unsafeLevelsPermission)) { + module.coreMessages.invalidValueForArgument("level", level.toString()).concerns(player).sendToSender(sender) + return + } + + val itemInHand = player.inventory.itemInMainHand + + if (!enchantment.canEnchantItem(itemInHand) && player.hasPermission(module.unsafeEnchantPermission)) { + module.messages.enchantInvalidCombinationSelf(itemInHand, enchantment).concerns(player).sendToPlayer(sender) + return + } + + val meta = itemInHand.itemMeta!! + meta.addEnchant(enchantment, level, player.hasPermission("enchantment.level")) + itemInHand.itemMeta = meta + + module.messages.enchantmentSelf(itemInHand, enchantment, level) + } +} diff --git a/modules/basics-enchant/src/main/resources/basics-module.yml b/modules/basics-enchant/src/main/resources/basics-module.yml index d3babc73..63f0a535 100644 --- a/modules/basics-enchant/src/main/resources/basics-module.yml +++ b/modules/basics-enchant/src/main/resources/basics-module.yml @@ -1,4 +1,4 @@ -main-class: com.github.spigotbasics.modules.basicsenchant.BasicsEnchantModule +main-class: com.github.spigotbasics.modules.basicsenchant.v2.BasicsEnchantModule name: basics-enchant version: ${moduleVersion} -description: Allows enchanting items using /enchant \ No newline at end of file +description: Allows enchanting items using /enchant diff --git a/modules/basics-enchant/src/main/resources/messages.yml b/modules/basics-enchant/src/main/resources/messages.yml index d192bb48..b5dbfefa 100644 --- a/modules/basics-enchant/src/main/resources/messages.yml +++ b/modules/basics-enchant/src/main/resources/messages.yml @@ -1,5 +1,12 @@ -# Tags: <#item> +# Tags: <#item> <#enchantment> <#roman-level> enchanted-self: "Enchanted your <#item> with <#enchantment> <#roman-level>!" -# TODO: Cannot enchant others' items yet +# Tags: <#item> <#enchantment> <#roman-level> <#entity> +enchanted-entity: "Enchanted <#entity>'s <#item> with <#enchantment> <#roman-level>!" +# Tags: <#item> <#enchantment> <#roman-level> <#player-name-genitive-suffix> enchanted-others: "Enchanted <#player-name-genitive-suffix> <#item> with <#enchantment> <#roman-level>!" -removed-self: "Removed <#enchantment> from your <#item>!" +# Tags: <#item> <#enchantment> +enchanted-invalid-combination-self: "Can not enchant <#item> with <#enchantment> because it is not applicable to this item" +# Tags: <#item> <#enchantment> <#entity> +enchanted-invalid-combination-entity: "Can not enchant <#entity>'s <#item> with <#enchantment> because it is not applicable to this item" +# Tags: <#item> <#enchantment> <#player-name-genitive-suffix> +enchanted-invalid-combination-others: "Can not enchant <#player-name-genitive-suffix> <#item> with <#enchantment> because it is not applicable to this item" From 118ddbbd97512c05be720045e236a20f1f7ad679 Mon Sep 17 00:00:00 2001 From: Miles Holder Date: Thu, 9 May 2024 08:51:51 -0500 Subject: [PATCH 05/13] cleanup enderchest --- .../basicsenchant/BasicsEnchantModule.kt | 9 +++-- .../BasicsEnderchestModule.kt | 40 ++++++++++++++++--- 2 files changed, 40 insertions(+), 9 deletions(-) diff --git a/modules/basics-enchant/src/main/kotlin/com/github/spigotbasics/modules/basicsenchant/BasicsEnchantModule.kt b/modules/basics-enchant/src/main/kotlin/com/github/spigotbasics/modules/basicsenchant/BasicsEnchantModule.kt index a38a2c7f..96da9e73 100644 --- a/modules/basics-enchant/src/main/kotlin/com/github/spigotbasics/modules/basicsenchant/BasicsEnchantModule.kt +++ b/modules/basics-enchant/src/main/kotlin/com/github/spigotbasics/modules/basicsenchant/BasicsEnchantModule.kt @@ -14,10 +14,11 @@ import org.bukkit.enchantments.Enchantment class BasicsEnchantModule(context: ModuleInstantiationContext) : AbstractBasicsModule(context) { private val commandPermission = permissionManager.createSimplePermission("basics.enchant", "Allows players access to the /enchant command") - private val commandOtherPermission = permissionManager.createSimplePermission( - "basics.enchant.other", - "Allows players access to the /enchant command to enchant others" - ) + private val commandOtherPermission = + permissionManager.createSimplePermission( + "basics.enchant.other", + "Allows players access to the /enchant command to enchant others", + ) val unsafeLevelsPermission = permissionManager.createSimplePermission( "basics.enchant.unsafe.level", diff --git a/modules/basics-enderchest/src/main/kotlin/com/github/spigotbasics/modules/basicsenderchest/BasicsEnderchestModule.kt b/modules/basics-enderchest/src/main/kotlin/com/github/spigotbasics/modules/basicsenderchest/BasicsEnderchestModule.kt index 55f4bf2a..195182ef 100644 --- a/modules/basics-enderchest/src/main/kotlin/com/github/spigotbasics/modules/basicsenderchest/BasicsEnderchestModule.kt +++ b/modules/basics-enderchest/src/main/kotlin/com/github/spigotbasics/modules/basicsenderchest/BasicsEnderchestModule.kt @@ -1,7 +1,12 @@ package com.github.spigotbasics.modules.basicsenderchest +import com.github.spigotbasics.core.command.parsed.CommandContextExecutor +import com.github.spigotbasics.core.command.parsed.arguments.SelectorSinglePlayerArg +import com.github.spigotbasics.core.command.parsed.context.MapContext import com.github.spigotbasics.core.module.AbstractBasicsModule import com.github.spigotbasics.core.module.loader.ModuleInstantiationContext +import org.bukkit.command.CommandSender +import org.bukkit.entity.Player class BasicsEnderchestModule(context: ModuleInstantiationContext) : AbstractBasicsModule(context) { val permission = @@ -16,10 +21,35 @@ class BasicsEnderchestModule(context: ModuleInstantiationContext) : AbstractBasi val inventoryTitle get() = messages.getMessage("inventory-title") override fun onEnable() { - commandFactory.rawCommandBuilder("enderchest", permission) - .description("Opens your enderchest") - .usage("[player]") - .executor(EnderchestCommand(this)) - .register() + commandFactory.parsedCommandBuilder("enderchest", permission).mapContext { + usage = "[player]" + description("Opens your enderchest") + + path { + playerOnly() + } + + path { + permissions(permissionOthers) + playerOnly() + arguments { + named("player", SelectorSinglePlayerArg("player")) + } + } + }.executor( + object : CommandContextExecutor { + override fun execute( + sender: CommandSender, + context: MapContext, + ) { + val playerSender = sender as Player + val player = if (context["player"] != null) context["player"] as Player else sender as Player + val setTitle = player != sender + + val view = playerSender.openInventory(player.enderChest) + if (setTitle) view?.title = inventoryTitle.concerns(player).toLegacyString() + } + }, + ).register() } } From 030ae678bdae5b4603a0cf0e2a9011fecd5df8a0 Mon Sep 17 00:00:00 2001 From: Miles Holder Date: Thu, 9 May 2024 08:57:19 -0500 Subject: [PATCH 06/13] cleanup extinguish --- .../modules/basicsenderchest/BasicsEnderchestModule.kt | 2 +- modules/basics-extinguish/README.md | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) create mode 100644 modules/basics-extinguish/README.md diff --git a/modules/basics-enderchest/src/main/kotlin/com/github/spigotbasics/modules/basicsenderchest/BasicsEnderchestModule.kt b/modules/basics-enderchest/src/main/kotlin/com/github/spigotbasics/modules/basicsenderchest/BasicsEnderchestModule.kt index 195182ef..86d644bc 100644 --- a/modules/basics-enderchest/src/main/kotlin/com/github/spigotbasics/modules/basicsenderchest/BasicsEnderchestModule.kt +++ b/modules/basics-enderchest/src/main/kotlin/com/github/spigotbasics/modules/basicsenderchest/BasicsEnderchestModule.kt @@ -43,7 +43,7 @@ class BasicsEnderchestModule(context: ModuleInstantiationContext) : AbstractBasi context: MapContext, ) { val playerSender = sender as Player - val player = if (context["player"] != null) context["player"] as Player else sender as Player + val player = if (context["player"] != null) context["player"] as Player else playerSender val setTitle = player != sender val view = playerSender.openInventory(player.enderChest) diff --git a/modules/basics-extinguish/README.md b/modules/basics-extinguish/README.md new file mode 100644 index 00000000..efae0a87 --- /dev/null +++ b/modules/basics-extinguish/README.md @@ -0,0 +1,4 @@ +| Command | Permission | +|------------------------|--------------------------| +| `/extinguish` | basics.extinguish | +| `/extinguish ` | basics.extinguish.others | From 4f97b22af1b24016ca80f41dfbd773da0b3b3aaa Mon Sep 17 00:00:00 2001 From: Miles Holder Date: Thu, 9 May 2024 09:02:14 -0500 Subject: [PATCH 07/13] cleanup fly --- .../modules/basicsfly/BasicsFlyModule.kt | 62 ++++++++++--------- 1 file changed, 34 insertions(+), 28 deletions(-) diff --git a/modules/basics-fly/src/main/kotlin/com/github/spigotbasics/modules/basicsfly/BasicsFlyModule.kt b/modules/basics-fly/src/main/kotlin/com/github/spigotbasics/modules/basicsfly/BasicsFlyModule.kt index 61bc3dd6..d4635205 100644 --- a/modules/basics-fly/src/main/kotlin/com/github/spigotbasics/modules/basicsfly/BasicsFlyModule.kt +++ b/modules/basics-fly/src/main/kotlin/com/github/spigotbasics/modules/basicsfly/BasicsFlyModule.kt @@ -1,10 +1,11 @@ package com.github.spigotbasics.modules.basicsfly -import com.github.spigotbasics.core.command.common.BasicsCommandExecutor -import com.github.spigotbasics.core.command.common.CommandResult -import com.github.spigotbasics.core.command.raw.RawCommandContext +import com.github.spigotbasics.core.command.parsed.CommandContextExecutor +import com.github.spigotbasics.core.command.parsed.arguments.SelectorSinglePlayerArg +import com.github.spigotbasics.core.command.parsed.context.MapContext import com.github.spigotbasics.core.module.AbstractBasicsModule import com.github.spigotbasics.core.module.loader.ModuleInstantiationContext +import org.bukkit.command.CommandSender import org.bukkit.entity.Player class BasicsFlyModule(context: ModuleInstantiationContext) : AbstractBasicsModule(context) { @@ -28,35 +29,40 @@ class BasicsFlyModule(context: ModuleInstantiationContext) : AbstractBasicsModul private fun msgDisabledOthers(player: Player) = messages.getMessage("fly-disabled-others").concerns(player) override fun onEnable() { - commandFactory.rawCommandBuilder("fly", permission) - .description("Toggles fly mode") - .usage("[player]") - .executor(FlyCommandExecutor(this)) - .register() - } + commandFactory.parsedCommandBuilder("fly", permission).mapContext { + usage = "[player]" + description("Toggles fly mode") - inner class FlyCommandExecutor(private val module: BasicsFlyModule) : BasicsCommandExecutor(module) { - override fun execute(context: RawCommandContext): CommandResult { - val player = - if (context.args.size == 1) { - requirePermission(context.sender, module.permissionOthers) - requirePlayer(context.args[0]) - } else { - requirePlayer(context.sender) + path { + arguments { + playerOnly() } + } - player.allowFlight = !player.allowFlight - - val message = - when { - player.allowFlight && context.sender == player -> module.msgEnabled - !player.allowFlight && context.sender == player -> module.msgDisabled - player.allowFlight -> module.msgEnabledOthers(player) - else -> module.msgDisabledOthers(player) + path { + arguments { + named("player", SelectorSinglePlayerArg("player")) } + } + }.executor( + object : CommandContextExecutor { + override fun execute( + sender: CommandSender, + context: MapContext, + ) { + val target = if (context["player"] != null) context["player"] as Player else sender as Player + target.allowFlight = !target.allowFlight + val message = + when { + target.allowFlight && context.sender == target -> msgEnabled + !target.allowFlight && context.sender == target -> msgDisabled + target.allowFlight -> msgEnabledOthers(target) + else -> msgDisabledOthers(target) + } - message.sendToSender(context.sender) - return CommandResult.SUCCESS - } + message.sendToSender(context.sender) + } + }, + ).register() } } From a3a5f1d54867b5979fa5a47cc9ec7e2f0e6b225e Mon Sep 17 00:00:00 2001 From: Miles Holder Date: Fri, 10 May 2024 14:00:47 -0500 Subject: [PATCH 08/13] cleanup gamemode --- .../basicsgamemode/BasicsGamemodeModule.kt | 75 ++++++++++++----- .../basicsgamemode/GameModeArgument.kt | 42 ++++++++++ .../basicsgamemode/GamemodeExecutor.kt | 83 ------------------- 3 files changed, 94 insertions(+), 106 deletions(-) create mode 100644 modules/basics-gamemode/src/main/kotlin/com/github/spigotbasics/modules/basicsgamemode/GameModeArgument.kt delete mode 100644 modules/basics-gamemode/src/main/kotlin/com/github/spigotbasics/modules/basicsgamemode/GamemodeExecutor.kt diff --git a/modules/basics-gamemode/src/main/kotlin/com/github/spigotbasics/modules/basicsgamemode/BasicsGamemodeModule.kt b/modules/basics-gamemode/src/main/kotlin/com/github/spigotbasics/modules/basicsgamemode/BasicsGamemodeModule.kt index e064f487..7f46d7db 100644 --- a/modules/basics-gamemode/src/main/kotlin/com/github/spigotbasics/modules/basicsgamemode/BasicsGamemodeModule.kt +++ b/modules/basics-gamemode/src/main/kotlin/com/github/spigotbasics/modules/basicsgamemode/BasicsGamemodeModule.kt @@ -1,21 +1,26 @@ package com.github.spigotbasics.modules.basicsgamemode +import com.github.spigotbasics.core.command.parsed.CommandContextExecutor +import com.github.spigotbasics.core.command.parsed.arguments.SelectorSinglePlayerArg +import com.github.spigotbasics.core.command.parsed.context.MapContext import com.github.spigotbasics.core.messages.Message import com.github.spigotbasics.core.module.AbstractBasicsModule import com.github.spigotbasics.core.module.loader.ModuleInstantiationContext import org.bukkit.GameMode +import org.bukkit.command.CommandSender +import org.bukkit.entity.Player import org.bukkit.permissions.Permission class BasicsGamemodeModule(context: ModuleInstantiationContext) : AbstractBasicsModule(context) { - val msgChangedOthers get() = messages.getMessage("gamemode-changed-others") - val msgChangedSelf get() = messages.getMessage("gamemode-changed-self") - val nameSurvival get() = messages.getMessage("survival") - val nameCreative get() = messages.getMessage("creative") - val nameAdventure get() = messages.getMessage("adventure") - val nameSpectator get() = messages.getMessage("spectator") - - val perm = permissionManager.createSimplePermission("basics.gamemode", "Allows the player to change their game mode") + private val msgChangedOthers get() = messages.getMessage("gamemode-changed-others") + private val msgChangedSelf get() = messages.getMessage("gamemode-changed-self") + private val nameSurvival get() = messages.getMessage("survival") + private val nameCreative get() = messages.getMessage("creative") + private val nameAdventure get() = messages.getMessage("adventure") + private val nameSpectator get() = messages.getMessage("spectator") + private val perm = + permissionManager.createSimplePermission("basics.gamemode", "Allows the player to change their game mode") val permSurvival = permissionManager.createSimplePermission( "basics.gamemode.survival", @@ -37,28 +42,52 @@ class BasicsGamemodeModule(context: ModuleInstantiationContext) : AbstractBasics "Allows the player to change their game mode to spectator", ) - val permOthers = + private val permOthers = permissionManager.createSimplePermission( "basics.gamemode.others", "Allows the player to change other players' game modes", ) override fun onEnable() { - commandFactory.rawCommandBuilder("gamemode", perm) - .description("Changes the player's game mode") - .usage(" [player]") - .executor(GamemodeExecutor(this)) - .register() - } + val instance = this + commandFactory.parsedCommandBuilder("gamemode", perm).mapContext { + description("Changes the player's game mode") + usage = " [player]" + path { + playerOnly() + arguments { + named("gamemode", GameModeArgument(instance, "gamemode")) + } - fun toGameMode(input: String): GameMode? { - return when (input) { - "survival", "s", "0" -> GameMode.SURVIVAL - "creative", "c", "1" -> GameMode.CREATIVE - "adventure", "a", "2" -> GameMode.ADVENTURE - "spectator", "sp", "3" -> GameMode.SPECTATOR - else -> null - } + arguments { + permissions(permOthers) + named("gamemode", GameModeArgument(instance, "gamemode")) + named("target", SelectorSinglePlayerArg("target")) + } + } + }.executor( + object : CommandContextExecutor { + override fun execute( + sender: CommandSender, + context: MapContext, + ) { + val gameMode = context["gamemode"] as GameMode + val target = if (context["target"] == null) sender as Player else context["target"] as Player + + val permission = getPermission(gameMode) + if (!sender.hasPermission(permission)) { + coreMessages.noPermission(permission).concerns(target).sendToSender(sender) + return + } + + target.gameMode = gameMode + val message = if (target == sender) msgChangedSelf else msgChangedOthers + message.tagMessage("new-gamemode", getName(gameMode)) + .concerns(target) + .sendToSender(sender) + } + }, + ).register() } fun getPermission(gameMode: GameMode): Permission { diff --git a/modules/basics-gamemode/src/main/kotlin/com/github/spigotbasics/modules/basicsgamemode/GameModeArgument.kt b/modules/basics-gamemode/src/main/kotlin/com/github/spigotbasics/modules/basicsgamemode/GameModeArgument.kt new file mode 100644 index 00000000..b033ee87 --- /dev/null +++ b/modules/basics-gamemode/src/main/kotlin/com/github/spigotbasics/modules/basicsgamemode/GameModeArgument.kt @@ -0,0 +1,42 @@ +package com.github.spigotbasics.modules.basicsgamemode + +import com.github.spigotbasics.core.command.parsed.arguments.CommandArgument +import org.bukkit.GameMode +import org.bukkit.command.CommandSender + +class GameModeArgument(private val module: BasicsGamemodeModule, name: String) : CommandArgument(name) { + override fun parse( + sender: CommandSender, + value: String, + ): GameMode? { + return when (value) { + "survival", "s", "0" -> GameMode.SURVIVAL + "creative", "c", "1" -> GameMode.CREATIVE + "adventure", "a", "2" -> GameMode.ADVENTURE + "spectator", "sp", "3" -> GameMode.SPECTATOR + else -> null + } + } + + override fun tabComplete( + sender: CommandSender, + typing: String, + ): List { + val list = mutableListOf() + + if (sender.hasPermission(module.permSurvival)) { + list += "survival" + } + if (sender.hasPermission(module.permCreative)) { + list += "creative" + } + if (sender.hasPermission(module.permAdventure)) { + list += "adventure" + } + if (sender.hasPermission(module.permSpectator)) { + list += "spectator" + } + + return list + } +} diff --git a/modules/basics-gamemode/src/main/kotlin/com/github/spigotbasics/modules/basicsgamemode/GamemodeExecutor.kt b/modules/basics-gamemode/src/main/kotlin/com/github/spigotbasics/modules/basicsgamemode/GamemodeExecutor.kt deleted file mode 100644 index cfb1d991..00000000 --- a/modules/basics-gamemode/src/main/kotlin/com/github/spigotbasics/modules/basicsgamemode/GamemodeExecutor.kt +++ /dev/null @@ -1,83 +0,0 @@ -package com.github.spigotbasics.modules.basicsgamemode - -import com.github.spigotbasics.core.command.common.BasicsCommandExecutor -import com.github.spigotbasics.core.command.common.CommandResult -import com.github.spigotbasics.core.command.raw.RawCommandContext -import org.bukkit.command.CommandSender -import org.bukkit.entity.Player -import org.bukkit.util.StringUtil - -class GamemodeExecutor(val module: BasicsGamemodeModule) : BasicsCommandExecutor(module) { - override fun execute(context: RawCommandContext): CommandResult { - val args = context.args - val sender = context.sender - var target: Player - - if (args.isEmpty() || args.size > 2) { - return CommandResult.USAGE - } - - val gameModeName = args[0] - val gameMode = module.toGameMode(gameModeName) - if (gameMode == null) { - return failInvalidArgument(gameModeName) - } - - requirePermission(sender, module.getPermission(gameMode)) - - if (args.size == 1) { - target = requirePlayerOrMustSpecifyPlayerFromConsole(sender) - } else if (args.size == 2) { - requirePermission(sender, module.permOthers) - target = requirePlayer(args[1]) - } else { - return CommandResult.USAGE - } - - target.gameMode = gameMode - val message = if (target == sender) module.msgChangedSelf else module.msgChangedOthers - - message.tagMessage("new-gamemode", module.getName(gameMode)) - .concerns(target) - - message.sendToSender(sender) - return CommandResult.SUCCESS - } - - override fun tabComplete(context: RawCommandContext): MutableList? { - if (context.args.size == 1) { - return StringUtil.copyPartialMatches( - context.args[0], - getAllowedGameModeNames(context.sender), - mutableListOf(), - ) - } - - if (context.args.size == 2) { - if (context.sender.hasPermission(module.permOthers)) { - return null // null = normal list of players - } - } - - return mutableListOf() - } - - private fun getAllowedGameModeNames(sender: CommandSender): MutableList { - val list = mutableListOf() - - if (sender.hasPermission(module.permSurvival)) { - list += "survival" - } - if (sender.hasPermission(module.permCreative)) { - list += "creative" - } - if (sender.hasPermission(module.permAdventure)) { - list += "adventure" - } - if (sender.hasPermission(module.permSpectator)) { - list += "spectator" - } - - return list - } -} From 098601eb95333ce81483615652477cabf373f7f5 Mon Sep 17 00:00:00 2001 From: Miles Holder Date: Fri, 10 May 2024 14:20:38 -0500 Subject: [PATCH 09/13] cleanup health --- .../basicsgamemode/BasicsGamemodeModule.kt | 4 +- .../basicsgamemode/GameModeArgument.kt | 3 +- .../basicshealth/BasicsHealthModule.kt | 119 ++++++++---------- 3 files changed, 57 insertions(+), 69 deletions(-) diff --git a/modules/basics-gamemode/src/main/kotlin/com/github/spigotbasics/modules/basicsgamemode/BasicsGamemodeModule.kt b/modules/basics-gamemode/src/main/kotlin/com/github/spigotbasics/modules/basicsgamemode/BasicsGamemodeModule.kt index 7f46d7db..b67bcc79 100644 --- a/modules/basics-gamemode/src/main/kotlin/com/github/spigotbasics/modules/basicsgamemode/BasicsGamemodeModule.kt +++ b/modules/basics-gamemode/src/main/kotlin/com/github/spigotbasics/modules/basicsgamemode/BasicsGamemodeModule.kt @@ -58,9 +58,11 @@ class BasicsGamemodeModule(context: ModuleInstantiationContext) : AbstractBasics arguments { named("gamemode", GameModeArgument(instance, "gamemode")) } + } + path { + permissions(permOthers) arguments { - permissions(permOthers) named("gamemode", GameModeArgument(instance, "gamemode")) named("target", SelectorSinglePlayerArg("target")) } diff --git a/modules/basics-gamemode/src/main/kotlin/com/github/spigotbasics/modules/basicsgamemode/GameModeArgument.kt b/modules/basics-gamemode/src/main/kotlin/com/github/spigotbasics/modules/basicsgamemode/GameModeArgument.kt index b033ee87..5db00ab0 100644 --- a/modules/basics-gamemode/src/main/kotlin/com/github/spigotbasics/modules/basicsgamemode/GameModeArgument.kt +++ b/modules/basics-gamemode/src/main/kotlin/com/github/spigotbasics/modules/basicsgamemode/GameModeArgument.kt @@ -1,6 +1,7 @@ package com.github.spigotbasics.modules.basicsgamemode import com.github.spigotbasics.core.command.parsed.arguments.CommandArgument +import com.github.spigotbasics.core.extensions.partialMatches import org.bukkit.GameMode import org.bukkit.command.CommandSender @@ -37,6 +38,6 @@ class GameModeArgument(private val module: BasicsGamemodeModule, name: String) : list += "spectator" } - return list + return list.partialMatches(typing) } } diff --git a/modules/basics-health/src/main/kotlin/com/github/spigotbasics/modules/basicshealth/BasicsHealthModule.kt b/modules/basics-health/src/main/kotlin/com/github/spigotbasics/modules/basicshealth/BasicsHealthModule.kt index 6636fe44..063aaaf4 100644 --- a/modules/basics-health/src/main/kotlin/com/github/spigotbasics/modules/basicshealth/BasicsHealthModule.kt +++ b/modules/basics-health/src/main/kotlin/com/github/spigotbasics/modules/basicshealth/BasicsHealthModule.kt @@ -1,10 +1,11 @@ package com.github.spigotbasics.modules.basicshealth -import com.github.spigotbasics.core.command.common.BasicsCommandExecutor -import com.github.spigotbasics.core.command.common.CommandResult -import com.github.spigotbasics.core.command.raw.RawCommandContext +import com.github.spigotbasics.core.command.parsed.CommandContextExecutor +import com.github.spigotbasics.core.command.parsed.arguments.SelectorSinglePlayerArg +import com.github.spigotbasics.core.command.parsed.context.MapContext import com.github.spigotbasics.core.module.AbstractBasicsModule import com.github.spigotbasics.core.module.loader.ModuleInstantiationContext +import org.bukkit.command.CommandSender import org.bukkit.entity.Player class BasicsHealthModule(context: ModuleInstantiationContext) : AbstractBasicsModule(context) { @@ -38,79 +39,63 @@ class BasicsHealthModule(context: ModuleInstantiationContext) : AbstractBasicsMo private fun msgFedOthers(player: Player) = messages.getMessage("fed-others").concerns(player) override fun onEnable() { - commandFactory.rawCommandBuilder("heal", permHeal) - .description("Heals Players") - .usage("[player]") - .executor(HealCommandExecutor(this)) - .register() - commandFactory.rawCommandBuilder("feed", permFeed) - .description("Feeds Players") - .usage("[player]") - .executor(FeedCommandExecutor(this)) - .register() - } + commandFactory.parsedCommandBuilder("heal", permHeal).mapContext { + description("Heals Players") + usage = "[player]" - inner class HealCommandExecutor(private val module: BasicsHealthModule) : BasicsCommandExecutor(module) { - override fun execute(context: RawCommandContext): CommandResult { - val player = - if (context.args.size == 1) { - requirePermission(context.sender, module.permHealOthers) - requirePlayer(context.args[0]) - } else { - requirePlayer(context.sender) + path { + arguments { + playerOnly() } + } - player.health = player.healthScale - - val message = - if (context.sender == player) { - module.msgHealed - } else { - module.msgHealedOthers(player) + path { + arguments { + permissions(permHealOthers) + named("player", SelectorSinglePlayerArg("player")) } - - message.sendToSender(context.sender) - return CommandResult.SUCCESS - } - - override fun tabComplete(context: RawCommandContext): MutableList? { - return if (context.args.size == 1 && context.sender.hasPermission(module.permHealOthers)) { - null - } else { - mutableListOf() } - } - } - - inner class FeedCommandExecutor(private val module: BasicsHealthModule) : BasicsCommandExecutor(module) { - override fun execute(context: RawCommandContext): CommandResult { - val player = - if (context.args.size == 1) { - requirePermission(context.sender, module.permFeedOthers) - requirePlayer(context.args[0]) - } else { - requirePlayer(context.sender) + }.executor( + object : CommandContextExecutor { + override fun execute( + sender: CommandSender, + context: MapContext, + ) { + val target = if (context["player"] != null) context["player"] as Player else sender as Player + target.health = target.healthScale + val message = if (sender == target) msgHealed else msgHealedOthers(target) + message.sendToSender(sender) } + }, + ).register() + commandFactory.parsedCommandBuilder("feed", permFeed).mapContext { + description("Feeds Players") + usage = "[player]" - player.foodLevel = 20 - - val message = - if (context.sender == player) { - module.msgFed - } else { - module.msgFedOthers(player) + path { + arguments { + playerOnly() } + } - message.sendToSender(context.sender) - return CommandResult.SUCCESS - } - - override fun tabComplete(context: RawCommandContext): MutableList? { - return if (context.args.size == 1 && context.sender.hasPermission(module.permFeedOthers)) { - null - } else { - mutableListOf() + path { + permissions(permFeedOthers) + arguments { + named("player", SelectorSinglePlayerArg("player")) + } } - } + }.executor( + object : CommandContextExecutor { + override fun execute( + sender: CommandSender, + context: MapContext, + ) { + val target = if (context["player"] != null) context["player"] as Player else sender as Player + target.foodLevel = 20 + val message = if (sender == target) msgFed else msgFedOthers(target) + message.sendToSender(sender) + } + }, + ).register() } } From 630bc615d74580fb3c8a97507de7705bd048f389 Mon Sep 17 00:00:00 2001 From: Miles Holder Date: Tue, 14 May 2024 11:20:22 -0500 Subject: [PATCH 10/13] cleanup enchantments --- .../core/messages/CoreMessages.kt | 2 + core/src/main/resources/messages.yml | 3 +- gradle/libs.versions.toml | 2 +- .../src/main/resources/basics-module.yml | 2 +- .../basicshomes/v2/BasicsHomesModule.kt | 115 ++++++++++++++++++ .../modules/basicshomes/v2/HomeStore.kt | 47 +++++++ .../modules/basicshomes/v2/Messages.kt | 23 ++++ .../basicshomes/v2/command/CommandDelHome.kt | 29 +++++ .../basicshomes/v2/command/CommandHome.kt | 41 +++++++ .../basicshomes/v2/command/CommandHomeList.kt | 40 ++++++ .../basicshomes/v2/command/CommandSetHome.kt | 39 ++++++ .../basicshomes/v2/command/HomesArgument.kt | 28 +++++ .../src/main/resources/basics-module.yml | 4 +- .../src/main/resources/messages.yml | 21 ++-- nms/versions/1.20.4/build.gradle.kts | 2 +- nms/versions/1.20.6/build.gradle.kts | 2 +- 16 files changed, 382 insertions(+), 18 deletions(-) create mode 100644 modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/BasicsHomesModule.kt create mode 100644 modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/HomeStore.kt create mode 100644 modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/Messages.kt create mode 100644 modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/command/CommandDelHome.kt create mode 100644 modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/command/CommandHome.kt create mode 100644 modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/command/CommandHomeList.kt create mode 100644 modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/command/CommandSetHome.kt create mode 100644 modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/command/HomesArgument.kt diff --git a/core/src/main/kotlin/com/github/spigotbasics/core/messages/CoreMessages.kt b/core/src/main/kotlin/com/github/spigotbasics/core/messages/CoreMessages.kt index 1f4839a3..0bbdb849 100644 --- a/core/src/main/kotlin/com/github/spigotbasics/core/messages/CoreMessages.kt +++ b/core/src/main/kotlin/com/github/spigotbasics/core/messages/CoreMessages.kt @@ -35,6 +35,8 @@ class CoreMessages(context: ConfigInstantiationContext) : SavedConfig(context) { fun worldNotFound(name: String) = getMessage("world-not-found").tagUnparsed("argument", name) + fun worldNotLoaded(name: String) = getMessage("world-not-loaded").tagUnparsed("argument", name) + fun unsupportedServerSoftware(feature: String) = getMessage("unsupported-server-software").tagParsed("argument", feature) fun selectorIncludesEntities( diff --git a/core/src/main/resources/messages.yml b/core/src/main/resources/messages.yml index 8681c869..c091179a 100644 --- a/core/src/main/resources/messages.yml +++ b/core/src/main/resources/messages.yml @@ -25,6 +25,7 @@ missing-value-for-argument: "Missing value for <#argumen invalid-argument: "Invalid argument: <#argument>" player-not-found: "Player not found: <#argument>" world-not-found: "World not found: <#argument>" +world-not-loaded: "World not loaded: <#argument>" unsupported-server-software: "Your server software does not support Missing class/method: <#argument>'>this feature!" not-enough-arguments-given-for-argument: "Not enough arguments given for argument <#argument>!" @@ -40,4 +41,4 @@ command-module-disabled: "The module that registered this command is failed-to-load-data-on-join: "[Basics] Failed to load player data in time - please try to join again!" error-executing-command: "An error occured while executing this command!" -error-executing-command-op: "'>An error occured while executing this command! (Hover for stacktrace - only visible to OPs)" \ No newline at end of file +error-executing-command-op: "'>An error occured while executing this command! (Hover for stacktrace - only visible to OPs)" diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 740c7c94..f369639e 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -36,4 +36,4 @@ hikari = { group = "com.zaxxer", name = "HikariCP", version.ref = "hikari" } [plugins] shadow = { id = "com.github.johnrengelman.shadow", version.ref="shadow" } kotlin = { id = "org.jetbrains.kotlin.jvm", version.ref="kotlin" } -dokka = { id = "org.jetbrains.dokka", version.ref="dokka" } \ No newline at end of file +dokka = { id = "org.jetbrains.dokka", version.ref="dokka" } diff --git a/modules/basics-enchant/src/main/resources/basics-module.yml b/modules/basics-enchant/src/main/resources/basics-module.yml index 63f0a535..7092cac2 100644 --- a/modules/basics-enchant/src/main/resources/basics-module.yml +++ b/modules/basics-enchant/src/main/resources/basics-module.yml @@ -1,4 +1,4 @@ -main-class: com.github.spigotbasics.modules.basicsenchant.v2.BasicsEnchantModule +main-class: com.github.spigotbasics.modules.basicsenchant.BasicsEnchantModule name: basics-enchant version: ${moduleVersion} description: Allows enchanting items using /enchant diff --git a/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/BasicsHomesModule.kt b/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/BasicsHomesModule.kt new file mode 100644 index 00000000..67802480 --- /dev/null +++ b/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/BasicsHomesModule.kt @@ -0,0 +1,115 @@ +package com.github.spigotbasics.modules.basicshomes.v2 + +import com.github.spigotbasics.core.command.parsed.arguments.AnyStringArg +import com.github.spigotbasics.core.config.ConfigName +import com.github.spigotbasics.core.module.AbstractBasicsModule +import com.github.spigotbasics.core.module.loader.ModuleInstantiationContext +import com.github.spigotbasics.modules.basicshomes.v2.command.CommandDelHome +import com.github.spigotbasics.modules.basicshomes.v2.command.CommandHome +import com.github.spigotbasics.modules.basicshomes.v2.command.CommandHomeList +import com.github.spigotbasics.modules.basicshomes.v2.command.CommandSetHome +import com.github.spigotbasics.modules.basicshomes.v2.command.HomesArgument +import java.util.UUID +import java.util.concurrent.CompletableFuture + +class BasicsHomesModule(context: ModuleInstantiationContext) : AbstractBasicsModule(context) { + private val permissionHome = + permissionManager.createSimplePermission("basics.home", "Allows to access the /home command") + private val permissionSetHome = + permissionManager.createSimplePermission("basics.sethome", "Allows to access the /sethome command") + private val permissionDelHome = + permissionManager.createSimplePermission("basics.delhome", "Allows to access the /delhome command") + + val permissionSetHomeMultiple = + permissionManager.createSimplePermission( + "basics.sethome.multiple", + "Allows to set multiple named homes", + ) + val permissionSetHomeUnlimited = + permissionManager.createSimplePermission( + "basics.sethome.multiple.unlimited", + "Allows to set unlimited homes", + ) + + val regex get() = config.getString("regex", "[a-zA-Z_0-9-]+")!! + + private lateinit var homeStore: HomeStore + + override val messages: Messages = getConfig(ConfigName.MESSAGES, Messages::class.java) + + override fun onEnable() { + homeStore = HomeStore(this) + + commandFactory.parsedCommandBuilder("sethome", permissionSetHome).mapContext { + description("Teleports you to one of your homes") + usage = "[name]" + + path { + playerOnly() + } + + path { + // TODO: Permission Home Multiple + playerOnly() + arguments { + named("name", AnyStringArg("name")) + } + } + }.executor(CommandSetHome(this, homeStore)).register() + + commandFactory.parsedCommandBuilder("delhome", permissionDelHome).mapContext { + description("Deletes one of your homes") + usage = "[name]" + + path { + playerOnly() + } + + path { + playerOnly() + arguments { + named("home", HomesArgument("home", homeStore)) + } + } + }.executor(CommandDelHome(this, homeStore)).register() + + commandFactory.parsedCommandBuilder("homes", permissionHome).mapContext { + description("Provides a list of your homes") + + path { + playerOnly() + } + }.executor(CommandHomeList(this, homeStore)).register() + + commandFactory.parsedCommandBuilder("home", permissionHome).mapContext { + description("Teleports you to one of your homes") + + path { + playerOnly() + } + + path { + playerOnly() + arguments { + named("home", HomesArgument("home", homeStore)) + } + } + }.executor(CommandHome(this, homeStore)).register() + } + + override fun loadPlayerData(uuid: UUID): CompletableFuture { + return CompletableFuture.runAsync { + homeStore.loadHomeListBlocking(uuid) + } + } + + override fun savePlayerData(uuid: UUID): CompletableFuture { + return CompletableFuture.runAsync { + homeStore.saveHomeListBlocking(uuid) + } + } + + override fun forgetPlayerData(uuid: UUID) { + homeStore.forgetHomeList(uuid) + } +} diff --git a/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/HomeStore.kt b/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/HomeStore.kt new file mode 100644 index 00000000..85edca74 --- /dev/null +++ b/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/HomeStore.kt @@ -0,0 +1,47 @@ +package com.github.spigotbasics.modules.basicshomes.v2 + +import com.github.spigotbasics.core.Serialization +import com.github.spigotbasics.modules.basicshomes.data.Home +import com.github.spigotbasics.modules.basicshomes.data.HomeList +import com.google.gson.reflect.TypeToken +import java.util.UUID +import java.util.concurrent.ConcurrentHashMap +import java.util.logging.Level + +class HomeStore(private val module: BasicsHomesModule) { + private val store = module.createStorage() + private val homeCache = ConcurrentHashMap() + + fun getHomeList(uuid: UUID): HomeList { + return homeCache[uuid] ?: error("HomeList for $uuid doesn't exist") + } + + fun forgetHomeList(uuid: UUID) { + homeCache.remove(uuid) + } + + fun saveHomeListBlocking(uuid: UUID) { + val homes = homeCache[uuid] ?: error("HomeList for $uuid doesn't exist") + try { + store.setJsonElement(uuid.toString(), Serialization.toJson(homes.toList())) + } catch (exception: Exception) { + module.logger.log(Level.SEVERE, "Failed to save home list for $uuid", exception) + } + } + + fun loadHomeListBlocking(uuid: UUID) { + try { + val json = store.getJsonElement(uuid.toString()).get() + val list = + if (json == null) { + HomeList() + } else { + HomeList.fromList(Serialization.fromJson(json, object : TypeToken>() {})) + } + homeCache[uuid] = list + } catch (e: Exception) { + module.logger.log(Level.SEVERE, "Failed to load home list for $uuid", e) + homeCache[uuid] = HomeList() + } + } +} diff --git a/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/Messages.kt b/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/Messages.kt new file mode 100644 index 00000000..93de9116 --- /dev/null +++ b/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/Messages.kt @@ -0,0 +1,23 @@ +package com.github.spigotbasics.modules.basicshomes.v2 + +import com.github.spigotbasics.core.config.ConfigInstantiationContext +import com.github.spigotbasics.core.config.SavedConfig +import com.github.spigotbasics.modules.basicshomes.data.Home + +class Messages(context: ConfigInstantiationContext) : SavedConfig(context) { + val homeNotFound get() = getMessage("home-not-found") + val homeList get() = getMessage("home-list") + val homeListEntry get() = getMessage("home-list-entry") + val homeListSeparator get() = getMessage("home-list-separator") + val homeNoneSet get() = getMessage("home-none-set") + + fun homeTeleport(home: Home) = getMessage("home-teleport").tags(home) + + fun homeSet(home: Home) = getMessage("home-set").tags(home) + + fun homeRemoved(home: Home) = getMessage("home-remove").tags(home) + + fun homeLimitReached(limit: Int) = getMessage("home-limit-reached").tagParsed("limit", limit.toString()) + + fun homeRegexViolated(regex: String) = getMessage("home-invalid-name").tagParsed("regex", regex) +} diff --git a/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/command/CommandDelHome.kt b/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/command/CommandDelHome.kt new file mode 100644 index 00000000..3cde660f --- /dev/null +++ b/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/command/CommandDelHome.kt @@ -0,0 +1,29 @@ +package com.github.spigotbasics.modules.basicshomes.v2.command + +import com.github.spigotbasics.core.command.parsed.CommandContextExecutor +import com.github.spigotbasics.core.command.parsed.context.MapContext +import com.github.spigotbasics.modules.basicshomes.data.Home +import com.github.spigotbasics.modules.basicshomes.v2.BasicsHomesModule +import com.github.spigotbasics.modules.basicshomes.v2.HomeStore +import org.bukkit.command.CommandSender +import org.bukkit.entity.Player + +class CommandDelHome(private val module: BasicsHomesModule, private val homeStore: HomeStore) : + CommandContextExecutor { + override fun execute( + sender: CommandSender, + context: MapContext, + ) { + val player = sender as Player + val homeList = homeStore.getHomeList(player.uniqueId) + val home = if (context["home"] == null) homeList.getHome("home") else context["home"] as Home + + if (home == null) { + module.messages.homeNotFound.concerns(player).sendToSender(player) + return + } + + homeList.removeHome(home) + module.messages.homeRemoved(home).concerns(player).sendToSender(player) + } +} diff --git a/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/command/CommandHome.kt b/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/command/CommandHome.kt new file mode 100644 index 00000000..d7882afd --- /dev/null +++ b/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/command/CommandHome.kt @@ -0,0 +1,41 @@ +package com.github.spigotbasics.modules.basicshomes.v2.command + +import com.github.spigotbasics.core.Spiper +import com.github.spigotbasics.core.command.parsed.CommandContextExecutor +import com.github.spigotbasics.core.command.parsed.context.MapContext +import com.github.spigotbasics.core.exceptions.WorldNotLoadedException +import com.github.spigotbasics.modules.basicshomes.data.Home +import com.github.spigotbasics.modules.basicshomes.v2.BasicsHomesModule +import com.github.spigotbasics.modules.basicshomes.v2.HomeStore +import org.bukkit.command.CommandSender +import org.bukkit.entity.Player + +class CommandHome(private val module: BasicsHomesModule, private val homeStore: HomeStore) : + CommandContextExecutor { + override fun execute( + sender: CommandSender, + context: MapContext, + ) { + val player = sender as Player + val homeList = homeStore.getHomeList(player.uniqueId) + if (homeList.isEmpty()) { + module.messages.homeNoneSet.concerns(player).sendToSender(player) + return + } + + val home = if (context["home"] != null) context["home"] as Home else homeList.getHome("home") + + if (home == null) { + module.messages.homeNotFound.concerns(player).sendToSender(player) + return + } + + val location = home.location + try { + Spiper.teleportAsync(player, location.toLocation()) + module.messages.homeTeleport(home).concerns(player).sendToPlayer(player) + } catch (exception: WorldNotLoadedException) { + module.coreMessages.worldNotLoaded(location.world).concerns(player).sendToPlayer(player) + } + } +} diff --git a/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/command/CommandHomeList.kt b/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/command/CommandHomeList.kt new file mode 100644 index 00000000..d6b4c3fb --- /dev/null +++ b/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/command/CommandHomeList.kt @@ -0,0 +1,40 @@ +package com.github.spigotbasics.modules.basicshomes.v2.command + +import com.github.spigotbasics.core.command.parsed.CommandContextExecutor +import com.github.spigotbasics.core.command.parsed.context.MapContext +import com.github.spigotbasics.core.messages.Message +import com.github.spigotbasics.core.messages.tags.MESSAGE_SPECIFIC_TAG_PREFIX +import com.github.spigotbasics.modules.basicshomes.data.Home +import com.github.spigotbasics.modules.basicshomes.v2.BasicsHomesModule +import com.github.spigotbasics.modules.basicshomes.v2.HomeStore +import org.bukkit.command.CommandSender +import org.bukkit.entity.Player + +class CommandHomeList(private val module: BasicsHomesModule, private val homeStore: HomeStore) : + CommandContextExecutor { + override fun execute( + sender: CommandSender, + context: MapContext, + ) { + val player = sender as Player + val homeList = homeStore.getHomeList(player.uniqueId) + if (homeList.isEmpty()) { + module.messages.homeNoneSet.concerns(player).sendToSender(player) + return + } + homeListToMessage(homeList.toList()).concerns(player).sendToSender(player) + } + + private fun homeToMessage(home: Home) = module.messages.homeListEntry.tags(home) + + private fun homeListToMessage(homes: List): Message { + val message = + module.messageFactory.createMessage( + List(homes.size) { i -> "<${MESSAGE_SPECIFIC_TAG_PREFIX}home${i + 1}>" }.joinToString("\n"), + ) + + homes.mapIndexed { i, home -> message.tagMessage("home${i + 1}", homeToMessage(home)) } + message.tagMessage("separator", module.messages.homeListSeparator) + return module.messages.homeList.tagMessage("homes", message) + } +} diff --git a/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/command/CommandSetHome.kt b/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/command/CommandSetHome.kt new file mode 100644 index 00000000..e12ac9f0 --- /dev/null +++ b/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/command/CommandSetHome.kt @@ -0,0 +1,39 @@ +package com.github.spigotbasics.modules.basicshomes.v2.command + +import com.github.spigotbasics.core.command.parsed.CommandContextExecutor +import com.github.spigotbasics.core.command.parsed.context.MapContext +import com.github.spigotbasics.core.extensions.getPermissionNumberValue +import com.github.spigotbasics.core.model.toSimpleLocation +import com.github.spigotbasics.modules.basicshomes.data.Home +import com.github.spigotbasics.modules.basicshomes.v2.BasicsHomesModule +import com.github.spigotbasics.modules.basicshomes.v2.HomeStore +import org.bukkit.command.CommandSender +import org.bukkit.entity.Player + +class CommandSetHome(private val module: BasicsHomesModule, private val homeStore: HomeStore) : + CommandContextExecutor { + override fun execute( + sender: CommandSender, + context: MapContext, + ) { + val player = sender as Player + val name = if (context["name"] != null) context["name"] as String else "home" + + if (!name.matches(module.regex.toRegex())) { + module.messages.homeRegexViolated(module.regex).concerns(player).sendToSender(player) + return + } + + val homeList = homeStore.getHomeList(player.uniqueId) + + val maxAllowed = player.getPermissionNumberValue(module.permissionSetHomeMultiple.name) ?: 2 + if (!player.hasPermission(module.permissionSetHomeUnlimited) && homeList.size == maxAllowed) { + module.messages.homeLimitReached(maxAllowed).concerns(player).sendToSender(player) + return + } + + val home = Home(name, player.location.toSimpleLocation()) + homeList.addHome(home) + module.messages.homeSet(home).sendToSender(sender) + } +} diff --git a/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/command/HomesArgument.kt b/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/command/HomesArgument.kt new file mode 100644 index 00000000..2c5e4311 --- /dev/null +++ b/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/command/HomesArgument.kt @@ -0,0 +1,28 @@ +package com.github.spigotbasics.modules.basicshomes.v2.command + +import com.github.spigotbasics.core.command.parsed.arguments.CommandArgument +import com.github.spigotbasics.core.extensions.partialMatches +import com.github.spigotbasics.modules.basicshomes.data.Home +import com.github.spigotbasics.modules.basicshomes.v2.HomeStore +import org.bukkit.command.CommandSender +import org.bukkit.entity.Player + +class HomesArgument(name: String, private val homeStore: HomeStore) : CommandArgument(name) { + override fun parse( + sender: CommandSender, + value: String, + ): Home? { + assert(sender is Player) + val homeList = homeStore.getHomeList((sender as Player).uniqueId) + return homeList.getHome(value) + } + + override fun tabComplete( + sender: CommandSender, + typing: String, + ): List { + assert(sender is Player) + val homeList = homeStore.getHomeList((sender as Player).uniqueId) + return homeList.toList().map { it.name }.toList().partialMatches(typing) + } +} diff --git a/modules/basics-homes/src/main/resources/basics-module.yml b/modules/basics-homes/src/main/resources/basics-module.yml index 2ef8223f..ba4f356d 100644 --- a/modules/basics-homes/src/main/resources/basics-module.yml +++ b/modules/basics-homes/src/main/resources/basics-module.yml @@ -1,4 +1,4 @@ -main-class: com.github.spigotbasics.modules.basicshomes.BasicsHomesModule +main-class: com.github.spigotbasics.modules.basicshomes.v2.BasicsHomesModule name: basics-homes version: ${moduleVersion} -description: "Simple home management" \ No newline at end of file +description: "Simple home management" diff --git a/modules/basics-homes/src/main/resources/messages.yml b/modules/basics-homes/src/main/resources/messages.yml index 733fa9cb..34d5e426 100644 --- a/modules/basics-homes/src/main/resources/messages.yml +++ b/modules/basics-homes/src/main/resources/messages.yml @@ -1,26 +1,25 @@ -# TODO: Add some system to auto-apply all home-related placeholders, not just name -# Tags: <#home> // later / TODO: <#limit> <#regex> <#name> <#homes> <#x> <#y> <#z> <#world> -home-set: "Set home <#home> to your current location." -home-deleted: "Deleted home <#home>." -home-teleported: "Teleported to home <#home>." -home-not-found: "Home <#home> not found." +# Tags: <#home>, <#x>, <#y>, <#z>, <#world> +home-teleport: "Teleported to home <#home>." +home-set: "Set home, <#home> to your current location." +home-remove: "Deleted home <#home>." -home-none-set: "You don't have any homes set." +# Tags: <#home> +home-not-found: "Home not found." # Tags: <#limit> home-limit-reached: "You cannot set more than <#limit> homes." -# Tags: <#world> // TODO: Move to core messages -home-world-not-loaded: "World <#world> is not loaded." - # Tags: <#regex> home-invalid-name: "Invalid home name. Home names must match the following regex: <#regex>" # Tags: <#homes> (= home-list-entry + home-list-separator) home-list: - "Available homes (Click to teleport):" - - " <#homes>" + - "<#homes>" # Tags: <#name> <#x> <#y> <#z> <#world> home-list-entry: "<#home>\nX: <#x> | Y: <#y> | Z: <#z> | <#world>\nClick to teleport'>'><#home>" home-list-separator: ", " + +# No Tags +home-none-set: "You don't have any homes set." diff --git a/nms/versions/1.20.4/build.gradle.kts b/nms/versions/1.20.4/build.gradle.kts index 22d8c14e..547cc9c6 100644 --- a/nms/versions/1.20.4/build.gradle.kts +++ b/nms/versions/1.20.4/build.gradle.kts @@ -1,6 +1,6 @@ plugins { id("basics.nms-module") - id("io.papermc.paperweight.userdev") version "1.7.0" + id("io.papermc.paperweight.userdev") version "1.7.1" } dependencies { diff --git a/nms/versions/1.20.6/build.gradle.kts b/nms/versions/1.20.6/build.gradle.kts index 4de550d3..e57db97a 100644 --- a/nms/versions/1.20.6/build.gradle.kts +++ b/nms/versions/1.20.6/build.gradle.kts @@ -1,6 +1,6 @@ plugins { id("basics.nms-module") - id("io.papermc.paperweight.userdev") version "1.7.0" + id("io.papermc.paperweight.userdev") version "1.7.1" } dependencies { From 54bb99c1773e971dd80c7379962fa24d0d7a84b3 Mon Sep 17 00:00:00 2001 From: Miles Holder Date: Tue, 14 May 2024 16:01:54 -0500 Subject: [PATCH 11/13] cleanup msg --- .../modules/basicshomes/BasicsHomesModule.kt | 183 +++++++----------- .../modules/basicshomes/{v2 => }/HomeStore.kt | 2 +- .../modules/basicshomes/Messages.kt | 24 +-- .../{v2 => }/command/CommandDelHome.kt | 6 +- .../{v2 => }/command/CommandHome.kt | 6 +- .../{v2 => }/command/CommandHomeList.kt | 6 +- .../{v2 => }/command/CommandSetHome.kt | 6 +- .../{v2 => }/command/HomesArgument.kt | 4 +- .../basicshomes/commands/DelHomeCommand.kt | 37 ---- .../basicshomes/commands/HomeCommand.kt | 43 ---- .../basicshomes/commands/HomeListCommand.kt | 43 ---- .../basicshomes/commands/SetHomeCommand.kt | 92 --------- .../basicshomes/v2/BasicsHomesModule.kt | 115 ----------- .../modules/basicshomes/v2/Messages.kt | 23 --- .../src/main/resources/basics-module.yml | 2 +- .../modules/basicsmsg/BasicsMessageModule.kt | 59 ++++++ .../modules/basicsmsg/BasicsMsgModule.kt | 35 ---- .../modules/basicsmsg/LastMessagedStore.kt | 23 +++ .../modules/basicsmsg/Messages.kt | 19 ++ .../modules/basicsmsg/MsgExecutor.kt | 66 ------- .../basicsmsg/command/CommandMessage.kt | 39 ++++ .../basicsmsg/command/CommandRespond.kt | 34 ++++ .../src/main/resources/basics-module.yml | 4 +- .../resources/{config.yml => messages.yml} | 7 +- 24 files changed, 281 insertions(+), 597 deletions(-) rename modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/{v2 => }/HomeStore.kt (96%) rename modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/{v2 => }/command/CommandDelHome.kt (83%) rename modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/{v2 => }/command/CommandHome.kt (88%) rename modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/{v2 => }/command/CommandHomeList.kt (88%) rename modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/{v2 => }/command/CommandSetHome.kt (88%) rename modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/{v2 => }/command/HomesArgument.kt (87%) delete mode 100644 modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/commands/DelHomeCommand.kt delete mode 100644 modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/commands/HomeCommand.kt delete mode 100644 modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/commands/HomeListCommand.kt delete mode 100644 modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/commands/SetHomeCommand.kt delete mode 100644 modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/BasicsHomesModule.kt delete mode 100644 modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/Messages.kt create mode 100644 modules/basics-msg/src/main/kotlin/com/github/spigotbasics/modules/basicsmsg/BasicsMessageModule.kt delete mode 100644 modules/basics-msg/src/main/kotlin/com/github/spigotbasics/modules/basicsmsg/BasicsMsgModule.kt create mode 100644 modules/basics-msg/src/main/kotlin/com/github/spigotbasics/modules/basicsmsg/LastMessagedStore.kt create mode 100644 modules/basics-msg/src/main/kotlin/com/github/spigotbasics/modules/basicsmsg/Messages.kt delete mode 100644 modules/basics-msg/src/main/kotlin/com/github/spigotbasics/modules/basicsmsg/MsgExecutor.kt create mode 100644 modules/basics-msg/src/main/kotlin/com/github/spigotbasics/modules/basicsmsg/command/CommandMessage.kt create mode 100644 modules/basics-msg/src/main/kotlin/com/github/spigotbasics/modules/basicsmsg/command/CommandRespond.kt rename modules/basics-msg/src/main/resources/{config.yml => messages.yml} (54%) diff --git a/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/BasicsHomesModule.kt b/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/BasicsHomesModule.kt index 24cf244a..6b33a110 100644 --- a/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/BasicsHomesModule.kt +++ b/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/BasicsHomesModule.kt @@ -1,34 +1,25 @@ package com.github.spigotbasics.modules.basicshomes -import com.github.spigotbasics.common.Either -import com.github.spigotbasics.core.Serialization -import com.github.spigotbasics.core.command.raw.RawCommandContext +import com.github.spigotbasics.core.command.parsed.arguments.AnyStringArg import com.github.spigotbasics.core.config.ConfigName import com.github.spigotbasics.core.module.AbstractBasicsModule import com.github.spigotbasics.core.module.loader.ModuleInstantiationContext -import com.github.spigotbasics.core.storage.NamespacedStorage -import com.github.spigotbasics.modules.basicshomes.commands.DelHomeCommand -import com.github.spigotbasics.modules.basicshomes.commands.HomeCommand -import com.github.spigotbasics.modules.basicshomes.commands.HomeListCommand -import com.github.spigotbasics.modules.basicshomes.commands.SetHomeCommand -import com.github.spigotbasics.modules.basicshomes.data.Home -import com.github.spigotbasics.modules.basicshomes.data.HomeList -import com.google.gson.reflect.TypeToken -import org.bukkit.entity.Player +import com.github.spigotbasics.modules.basicshomes.command.CommandDelHome +import com.github.spigotbasics.modules.basicshomes.command.CommandHome +import com.github.spigotbasics.modules.basicshomes.command.CommandHomeList +import com.github.spigotbasics.modules.basicshomes.command.CommandSetHome +import com.github.spigotbasics.modules.basicshomes.command.HomesArgument import java.util.UUID import java.util.concurrent.CompletableFuture -import java.util.logging.Level class BasicsHomesModule(context: ModuleInstantiationContext) : AbstractBasicsModule(context) { - private val listType = object : TypeToken>() {} + private val permissionHome = + permissionManager.createSimplePermission("basics.home", "Allows to access the /home command") + private val permissionSetHome = + permissionManager.createSimplePermission("basics.sethome", "Allows to access the /sethome command") + private val permissionDelHome = + permissionManager.createSimplePermission("basics.delhome", "Allows to access the /delhome command") - private var storage: NamespacedStorage? = null - private val homes = mutableMapOf() - override val messages = getConfig(ConfigName.MESSAGES, Messages::class.java) - - val permissionHome = permissionManager.createSimplePermission("basics.home", "Allows to access the /home command") - - val permissionSetHome = permissionManager.createSimplePermission("basics.sethome", "Allows to access the /sethome command") val permissionSetHomeMultiple = permissionManager.createSimplePermission( "basics.sethome.multiple", @@ -40,113 +31,85 @@ class BasicsHomesModule(context: ModuleInstantiationContext) : AbstractBasicsMod "Allows to set unlimited homes", ) - val permissionDelHome = permissionManager.createSimplePermission("basics.delhome", "Allows to access the /delhome command") - val regex get() = config.getString("regex", "[a-zA-Z_0-9-]+")!! + private lateinit var homeStore: HomeStore + + override val messages: Messages = getConfig(ConfigName.MESSAGES, Messages::class.java) + override fun onEnable() { - storage = createStorage() - - commandFactory.rawCommandBuilder("home", permissionHome) - .description("Teleports you to one of your homes") - .usage("[name]") - .executor(HomeCommand(this)) - .register() - - commandFactory.rawCommandBuilder("homes", permissionHome) - .description("Lists your homes") - // .usage("/homes") - .executor(HomeListCommand(this)) - .register() - - commandFactory.rawCommandBuilder("sethome", permissionSetHome) - .description("Sets a home") - .usage("[name]") - .executor(SetHomeCommand(this)) - .register() - - commandFactory.rawCommandBuilder("delhome", permissionDelHome) - .description("Deletes a home") - .usage("[name]") - .executor(DelHomeCommand(this)) - .register() - } + homeStore = HomeStore(this) - fun getHomeList(uuid: UUID): HomeList { - return homes[uuid] ?: error("Home list is null") - } + commandFactory.parsedCommandBuilder("sethome", permissionSetHome).mapContext { + description("Teleports you to one of your homes") + usage = "[name]" - private fun loadHomeListBlocking(uuid: UUID): HomeList { - val storage = storage ?: error("Storage is null") - try { - val json = storage.getJsonElement(uuid.toString()).get() - return if (json == null) { - HomeList() - } else { - HomeList.fromList(Serialization.fromJson(json, listType)) + path { + playerOnly() } - } catch (e: Exception) { - logger.log(Level.SEVERE, "Failed to load home list for $uuid", e) - return HomeList() - } - } - override fun loadPlayerData(uuid: UUID): CompletableFuture { - return CompletableFuture.runAsync { - val homeList = loadHomeListBlocking(uuid) - homes[uuid] = homeList - } - } + path { + // TODO: Permission Home Multiple + playerOnly() + arguments { + named("name", AnyStringArg("name")) + } + } + }.executor(CommandSetHome(this, homeStore)).register() - override fun savePlayerData(uuid: UUID): CompletableFuture { - return CompletableFuture.runAsync { - val homes = homes[uuid] ?: error("Homes is null") - val storage = storage ?: error("Storage is null") - try { - storage.setJsonElement(uuid.toString(), Serialization.toJson(homes.toList())).get() - } catch (e: Exception) { - logger.log(Level.SEVERE, "Failed to save home list for $uuid", e) + commandFactory.parsedCommandBuilder("delhome", permissionDelHome).mapContext { + description("Deletes one of your homes") + usage = "[name]" + + path { + playerOnly() } - } - } - override fun forgetPlayerData(uuid: UUID) { - homes.remove(uuid) - } + path { + playerOnly() + arguments { + named("home", HomesArgument("home", homeStore)) + } + } + }.executor(CommandDelHome(this, homeStore)).register() - override fun reloadConfig() { - config.reload() - messages.reload() - } + commandFactory.parsedCommandBuilder("homes", permissionHome).mapContext { + description("Provides a list of your homes") - fun parseHomeCmd(context: RawCommandContext): Either { - if (context.sender !is Player) { - plugin.messages.commandNotFromConsole.sendToSender(context.sender) - return Either.Right(true) - } - val player = context.sender as Player + path { + playerOnly() + } + }.executor(CommandHomeList(this, homeStore)).register() - var homeName = "home" - if (context.args.size == 1) { - homeName = context.args[0] - } else if (context.args.size > 1) { - return Either.Right(false) - } + commandFactory.parsedCommandBuilder("home", permissionHome).mapContext { + description("Teleports you to one of your homes") - val homeList = getHomeList(player.uniqueId) + path { + playerOnly() + } - if (homeList.isEmpty()) { - messages.homeNoneSet.sendToSender(player) - return Either.Right(true) - } + path { + playerOnly() + arguments { + named("home", HomesArgument("home", homeStore)) + } + } + }.executor(CommandHome(this, homeStore)).register() + } - val home = homeList.getHome(homeName) + override fun loadPlayerData(uuid: UUID): CompletableFuture { + return CompletableFuture.runAsync { + homeStore.loadHomeListBlocking(uuid) + } + } - if (home == null) { - messages.homeNotFound(homeName).sendToSender(player) - return Either.Right(true) + override fun savePlayerData(uuid: UUID): CompletableFuture { + return CompletableFuture.runAsync { + homeStore.saveHomeListBlocking(uuid) } + } - return Either.Left(home) + override fun forgetPlayerData(uuid: UUID) { + homeStore.forgetHomeList(uuid) } } diff --git a/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/HomeStore.kt b/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/HomeStore.kt similarity index 96% rename from modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/HomeStore.kt rename to modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/HomeStore.kt index 85edca74..3dd2c7f8 100644 --- a/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/HomeStore.kt +++ b/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/HomeStore.kt @@ -1,4 +1,4 @@ -package com.github.spigotbasics.modules.basicshomes.v2 +package com.github.spigotbasics.modules.basicshomes import com.github.spigotbasics.core.Serialization import com.github.spigotbasics.modules.basicshomes.data.Home diff --git a/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/Messages.kt b/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/Messages.kt index 7bb77d3b..da1cd01b 100644 --- a/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/Messages.kt +++ b/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/Messages.kt @@ -5,23 +5,19 @@ import com.github.spigotbasics.core.config.SavedConfig import com.github.spigotbasics.modules.basicshomes.data.Home class Messages(context: ConfigInstantiationContext) : SavedConfig(context) { - fun homeSet(home: Home) = getMessage("home-set").tags(home) - - fun homeDeleted(home: Home) = getMessage("home-deleted").tags(home) - - fun homeTeleported(home: Home) = getMessage("home-teleported").tags(home) - - fun homeNotFound(name: String) = getMessage("home-not-found").tagUnparsed("home", name) - - val homeNoneSet get() = getMessage("home-none-set") - - fun homeLimitReached(limit: Int) = getMessage("home-limit-reached").tagUnparsed("limit", limit.toString()) - + val homeNotFound get() = getMessage("home-not-found") val homeList get() = getMessage("home-list") val homeListEntry get() = getMessage("home-list-entry") val homeListSeparator get() = getMessage("home-list-separator") + val homeNoneSet get() = getMessage("home-none-set") + + fun homeTeleport(home: Home) = getMessage("home-teleport").tags(home) + + fun homeSet(home: Home) = getMessage("home-set").tags(home) + + fun homeRemoved(home: Home) = getMessage("home-remove").tags(home) - fun homeInvalidName(regex: String) = getMessage("home-invalid-name").tagParsed("regex", regex) + fun homeLimitReached(limit: Int) = getMessage("home-limit-reached").tagParsed("limit", limit.toString()) - fun homeWorldNotLoaded(worldName: String) = getMessage("home-world-not-loaded").tagUnparsed("world", worldName) + fun homeRegexViolated(regex: String) = getMessage("home-invalid-name").tagParsed("regex", regex) } diff --git a/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/command/CommandDelHome.kt b/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/command/CommandDelHome.kt similarity index 83% rename from modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/command/CommandDelHome.kt rename to modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/command/CommandDelHome.kt index 3cde660f..a2405c8b 100644 --- a/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/command/CommandDelHome.kt +++ b/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/command/CommandDelHome.kt @@ -1,10 +1,10 @@ -package com.github.spigotbasics.modules.basicshomes.v2.command +package com.github.spigotbasics.modules.basicshomes.command import com.github.spigotbasics.core.command.parsed.CommandContextExecutor import com.github.spigotbasics.core.command.parsed.context.MapContext +import com.github.spigotbasics.modules.basicshomes.BasicsHomesModule +import com.github.spigotbasics.modules.basicshomes.HomeStore import com.github.spigotbasics.modules.basicshomes.data.Home -import com.github.spigotbasics.modules.basicshomes.v2.BasicsHomesModule -import com.github.spigotbasics.modules.basicshomes.v2.HomeStore import org.bukkit.command.CommandSender import org.bukkit.entity.Player diff --git a/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/command/CommandHome.kt b/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/command/CommandHome.kt similarity index 88% rename from modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/command/CommandHome.kt rename to modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/command/CommandHome.kt index d7882afd..74861af8 100644 --- a/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/command/CommandHome.kt +++ b/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/command/CommandHome.kt @@ -1,12 +1,12 @@ -package com.github.spigotbasics.modules.basicshomes.v2.command +package com.github.spigotbasics.modules.basicshomes.command import com.github.spigotbasics.core.Spiper import com.github.spigotbasics.core.command.parsed.CommandContextExecutor import com.github.spigotbasics.core.command.parsed.context.MapContext import com.github.spigotbasics.core.exceptions.WorldNotLoadedException +import com.github.spigotbasics.modules.basicshomes.BasicsHomesModule +import com.github.spigotbasics.modules.basicshomes.HomeStore import com.github.spigotbasics.modules.basicshomes.data.Home -import com.github.spigotbasics.modules.basicshomes.v2.BasicsHomesModule -import com.github.spigotbasics.modules.basicshomes.v2.HomeStore import org.bukkit.command.CommandSender import org.bukkit.entity.Player diff --git a/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/command/CommandHomeList.kt b/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/command/CommandHomeList.kt similarity index 88% rename from modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/command/CommandHomeList.kt rename to modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/command/CommandHomeList.kt index d6b4c3fb..45badfbe 100644 --- a/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/command/CommandHomeList.kt +++ b/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/command/CommandHomeList.kt @@ -1,12 +1,12 @@ -package com.github.spigotbasics.modules.basicshomes.v2.command +package com.github.spigotbasics.modules.basicshomes.command import com.github.spigotbasics.core.command.parsed.CommandContextExecutor import com.github.spigotbasics.core.command.parsed.context.MapContext import com.github.spigotbasics.core.messages.Message import com.github.spigotbasics.core.messages.tags.MESSAGE_SPECIFIC_TAG_PREFIX +import com.github.spigotbasics.modules.basicshomes.BasicsHomesModule +import com.github.spigotbasics.modules.basicshomes.HomeStore import com.github.spigotbasics.modules.basicshomes.data.Home -import com.github.spigotbasics.modules.basicshomes.v2.BasicsHomesModule -import com.github.spigotbasics.modules.basicshomes.v2.HomeStore import org.bukkit.command.CommandSender import org.bukkit.entity.Player diff --git a/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/command/CommandSetHome.kt b/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/command/CommandSetHome.kt similarity index 88% rename from modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/command/CommandSetHome.kt rename to modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/command/CommandSetHome.kt index e12ac9f0..fc7b85c9 100644 --- a/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/command/CommandSetHome.kt +++ b/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/command/CommandSetHome.kt @@ -1,12 +1,12 @@ -package com.github.spigotbasics.modules.basicshomes.v2.command +package com.github.spigotbasics.modules.basicshomes.command import com.github.spigotbasics.core.command.parsed.CommandContextExecutor import com.github.spigotbasics.core.command.parsed.context.MapContext import com.github.spigotbasics.core.extensions.getPermissionNumberValue import com.github.spigotbasics.core.model.toSimpleLocation +import com.github.spigotbasics.modules.basicshomes.BasicsHomesModule +import com.github.spigotbasics.modules.basicshomes.HomeStore import com.github.spigotbasics.modules.basicshomes.data.Home -import com.github.spigotbasics.modules.basicshomes.v2.BasicsHomesModule -import com.github.spigotbasics.modules.basicshomes.v2.HomeStore import org.bukkit.command.CommandSender import org.bukkit.entity.Player diff --git a/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/command/HomesArgument.kt b/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/command/HomesArgument.kt similarity index 87% rename from modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/command/HomesArgument.kt rename to modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/command/HomesArgument.kt index 2c5e4311..fde946f1 100644 --- a/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/command/HomesArgument.kt +++ b/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/command/HomesArgument.kt @@ -1,9 +1,9 @@ -package com.github.spigotbasics.modules.basicshomes.v2.command +package com.github.spigotbasics.modules.basicshomes.command import com.github.spigotbasics.core.command.parsed.arguments.CommandArgument import com.github.spigotbasics.core.extensions.partialMatches +import com.github.spigotbasics.modules.basicshomes.HomeStore import com.github.spigotbasics.modules.basicshomes.data.Home -import com.github.spigotbasics.modules.basicshomes.v2.HomeStore import org.bukkit.command.CommandSender import org.bukkit.entity.Player diff --git a/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/commands/DelHomeCommand.kt b/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/commands/DelHomeCommand.kt deleted file mode 100644 index f296434b..00000000 --- a/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/commands/DelHomeCommand.kt +++ /dev/null @@ -1,37 +0,0 @@ -package com.github.spigotbasics.modules.basicshomes.commands - -import com.github.spigotbasics.common.Either -import com.github.spigotbasics.core.command.common.BasicsCommandExecutor -import com.github.spigotbasics.core.command.common.CommandResult -import com.github.spigotbasics.core.command.raw.RawCommandContext -import com.github.spigotbasics.core.extensions.partialMatches -import com.github.spigotbasics.modules.basicshomes.BasicsHomesModule -import org.bukkit.entity.Player - -class DelHomeCommand(private val module: BasicsHomesModule) : BasicsCommandExecutor(module) { - private val messages = module.messages - - override fun execute(context: RawCommandContext): CommandResult { - val result = module.parseHomeCmd(context) - if (result is Either.Right) { - return if (result.value) CommandResult.SUCCESS else CommandResult.USAGE - } - - val home = (result as Either.Left).value - val player = requirePlayerOrMustSpecifyPlayerFromConsole(context.sender) - - module.getHomeList(player.uniqueId).removeHome(home) - messages.homeDeleted(home).sendToSender(player) - return CommandResult.SUCCESS - } - - override fun tabComplete(context: RawCommandContext): List { - val sender = context.sender - if (sender is Player) { - if (context.args.size == 1) { - return module.getHomeList(sender.uniqueId).listHomeNames().partialMatches(context.args[0]) - } - } - return mutableListOf() - } -} diff --git a/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/commands/HomeCommand.kt b/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/commands/HomeCommand.kt deleted file mode 100644 index dcb9696f..00000000 --- a/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/commands/HomeCommand.kt +++ /dev/null @@ -1,43 +0,0 @@ -package com.github.spigotbasics.modules.basicshomes.commands - -import com.github.spigotbasics.common.Either -import com.github.spigotbasics.core.Spiper -import com.github.spigotbasics.core.command.common.BasicsCommandExecutor -import com.github.spigotbasics.core.command.common.CommandResult -import com.github.spigotbasics.core.command.raw.RawCommandContext -import com.github.spigotbasics.core.exceptions.WorldNotLoadedException -import com.github.spigotbasics.core.extensions.partialMatches -import com.github.spigotbasics.modules.basicshomes.BasicsHomesModule -import org.bukkit.entity.Player -import org.bukkit.event.player.PlayerTeleportEvent - -class HomeCommand(private val module: BasicsHomesModule) : BasicsCommandExecutor(module) { - private val messages = module.messages - - override fun execute(context: RawCommandContext): CommandResult { - val result = module.parseHomeCmd(context) - if (result is Either.Right) { - return if (result.value) CommandResult.SUCCESS else CommandResult.USAGE - } - - val home = (result as Either.Left).value - val player = requirePlayerOrMustSpecifyPlayerFromConsole(context.sender) - - try { - Spiper.teleportAsync(player, home.location.toLocation(), PlayerTeleportEvent.TeleportCause.PLUGIN) - messages.homeTeleported(home).sendToSender(player) - } catch (e: WorldNotLoadedException) { - messages.homeWorldNotLoaded(home.location.world).sendToSender(player) - } - return CommandResult.SUCCESS - } - - override fun tabComplete(context: RawCommandContext): List { - if (context.sender !is Player) { - return mutableListOf() - } - val player = context.sender as Player - val homeList = module.getHomeList(player.uniqueId) - return homeList.listHomeNames().partialMatches(context.args[0]) - } -} diff --git a/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/commands/HomeListCommand.kt b/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/commands/HomeListCommand.kt deleted file mode 100644 index b5832a26..00000000 --- a/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/commands/HomeListCommand.kt +++ /dev/null @@ -1,43 +0,0 @@ -package com.github.spigotbasics.modules.basicshomes.commands - -import com.github.spigotbasics.core.command.common.BasicsCommandExecutor -import com.github.spigotbasics.core.command.common.CommandResult -import com.github.spigotbasics.core.command.raw.RawCommandContext -import com.github.spigotbasics.core.messages.Message -import com.github.spigotbasics.core.messages.tags.MESSAGE_SPECIFIC_TAG_PREFIX -import com.github.spigotbasics.modules.basicshomes.BasicsHomesModule -import com.github.spigotbasics.modules.basicshomes.data.Home - -class HomeListCommand(private val module: BasicsHomesModule) : BasicsCommandExecutor(module) { - private val messages = module.messages - - override fun execute(context: RawCommandContext): CommandResult { - if (context.args.isNotEmpty()) return CommandResult.USAGE - val player = notFromConsole(context.sender) - val homeList = module.getHomeList(player.uniqueId).toList() - if (homeList.isEmpty()) { - messages.homeNoneSet.sendToSender(player) - } else { - allHomes2msg(homeList).sendToSender(player) - } - - return CommandResult.SUCCESS - } - - fun home2msg(home: Home) = - messages.homeListEntry - .tags(home) - - fun allHomes2msg(homes: List): Message { - val messageList = - messageFactory.createMessage( - List(homes.size) { index -> "<${MESSAGE_SPECIFIC_TAG_PREFIX}home${index + 1}>" }.joinToString("<#separator>"), - ) - - homes.mapIndexed { index, home -> messageList.tagMessage("home${index + 1}", home2msg(home)) } - messageList.tagMessage("separator", messages.homeListSeparator) - - val message = messages.homeList.tagMessage("homes", messageList) - return message - } -} diff --git a/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/commands/SetHomeCommand.kt b/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/commands/SetHomeCommand.kt deleted file mode 100644 index f42133cd..00000000 --- a/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/commands/SetHomeCommand.kt +++ /dev/null @@ -1,92 +0,0 @@ -package com.github.spigotbasics.modules.basicshomes.commands - -import com.github.spigotbasics.core.command.common.BasicsCommandExecutor -import com.github.spigotbasics.core.command.common.CommandResult -import com.github.spigotbasics.core.command.raw.RawCommandContext -import com.github.spigotbasics.core.extensions.getPermissionNumberValue -import com.github.spigotbasics.core.extensions.partialMatches -import com.github.spigotbasics.modules.basicshomes.BasicsHomesModule -import com.github.spigotbasics.modules.basicshomes.data.Home -import org.bukkit.entity.Player - -class SetHomeCommand(private val module: BasicsHomesModule) : BasicsCommandExecutor(module) { - private val messages = module.messages - - override fun execute(context: RawCommandContext): CommandResult { - if (context.sender !is Player) { - return CommandResult.NOT_FROM_CONSOLE - } - - var homeName = "home" - - if (context.args.size > 1) { - return CommandResult.USAGE - } - - val player = context.sender as Player - val location = player.location - - val homeList = module.getHomeList(player.uniqueId) - val maxAllowed = player.getPermissionNumberValue(module.permissionSetHomeMultiple.name) ?: 2 - val allowUnlimited = player.hasPermission(module.permissionSetHomeUnlimited) - - if (context.args.size == 1) { - homeName = context.args[0] - - if (!player.hasPermission(module.permissionSetHomeMultiple)) { - // Player can only set one home ... - - if (homeList.isEmpty()) { - // ... and they haven't set one yet, that's okay. - } else if (homeList.size == 1 && homeList.getHome(homeName) != null) { - // ... and they're replacing their only home, that's okay. - } else { - // ... and they're not replacing that one, that's not okay. - messages.homeLimitReached(1) - .sendToSender(player) - - return CommandResult.SUCCESS - } - } - } - - val isOkay = - when { - // Player may set unlimited homes - allowUnlimited -> true - - // Player may set more homes - homeList.size < maxAllowed -> true - - // Player already set max homes, but is replacing an existing one - homeList.size == maxAllowed && homeList.getHome(homeName) != null -> true - - // Buy a rank, ffs - else -> false - } - - if (!isOkay) { - messages.homeLimitReached(maxAllowed).sendToSender(player) - return CommandResult.SUCCESS - } - - if (!homeName.matches(module.regex.toRegex())) { - messages.homeInvalidName(module.regex).sendToSender(player) - return CommandResult.SUCCESS - } - - val home = Home(homeName, location) - - homeList.addHome(home) - messages.homeSet(home).sendToSender(player) - return CommandResult.SUCCESS - } - - override fun tabComplete(context: RawCommandContext): List { - if (context.sender !is Player) { - return mutableListOf() - } - val player = context.sender as Player - return module.getHomeList(player.uniqueId).listHomeNames().partialMatches(context.args[0]) - } -} diff --git a/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/BasicsHomesModule.kt b/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/BasicsHomesModule.kt deleted file mode 100644 index 67802480..00000000 --- a/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/BasicsHomesModule.kt +++ /dev/null @@ -1,115 +0,0 @@ -package com.github.spigotbasics.modules.basicshomes.v2 - -import com.github.spigotbasics.core.command.parsed.arguments.AnyStringArg -import com.github.spigotbasics.core.config.ConfigName -import com.github.spigotbasics.core.module.AbstractBasicsModule -import com.github.spigotbasics.core.module.loader.ModuleInstantiationContext -import com.github.spigotbasics.modules.basicshomes.v2.command.CommandDelHome -import com.github.spigotbasics.modules.basicshomes.v2.command.CommandHome -import com.github.spigotbasics.modules.basicshomes.v2.command.CommandHomeList -import com.github.spigotbasics.modules.basicshomes.v2.command.CommandSetHome -import com.github.spigotbasics.modules.basicshomes.v2.command.HomesArgument -import java.util.UUID -import java.util.concurrent.CompletableFuture - -class BasicsHomesModule(context: ModuleInstantiationContext) : AbstractBasicsModule(context) { - private val permissionHome = - permissionManager.createSimplePermission("basics.home", "Allows to access the /home command") - private val permissionSetHome = - permissionManager.createSimplePermission("basics.sethome", "Allows to access the /sethome command") - private val permissionDelHome = - permissionManager.createSimplePermission("basics.delhome", "Allows to access the /delhome command") - - val permissionSetHomeMultiple = - permissionManager.createSimplePermission( - "basics.sethome.multiple", - "Allows to set multiple named homes", - ) - val permissionSetHomeUnlimited = - permissionManager.createSimplePermission( - "basics.sethome.multiple.unlimited", - "Allows to set unlimited homes", - ) - - val regex get() = config.getString("regex", "[a-zA-Z_0-9-]+")!! - - private lateinit var homeStore: HomeStore - - override val messages: Messages = getConfig(ConfigName.MESSAGES, Messages::class.java) - - override fun onEnable() { - homeStore = HomeStore(this) - - commandFactory.parsedCommandBuilder("sethome", permissionSetHome).mapContext { - description("Teleports you to one of your homes") - usage = "[name]" - - path { - playerOnly() - } - - path { - // TODO: Permission Home Multiple - playerOnly() - arguments { - named("name", AnyStringArg("name")) - } - } - }.executor(CommandSetHome(this, homeStore)).register() - - commandFactory.parsedCommandBuilder("delhome", permissionDelHome).mapContext { - description("Deletes one of your homes") - usage = "[name]" - - path { - playerOnly() - } - - path { - playerOnly() - arguments { - named("home", HomesArgument("home", homeStore)) - } - } - }.executor(CommandDelHome(this, homeStore)).register() - - commandFactory.parsedCommandBuilder("homes", permissionHome).mapContext { - description("Provides a list of your homes") - - path { - playerOnly() - } - }.executor(CommandHomeList(this, homeStore)).register() - - commandFactory.parsedCommandBuilder("home", permissionHome).mapContext { - description("Teleports you to one of your homes") - - path { - playerOnly() - } - - path { - playerOnly() - arguments { - named("home", HomesArgument("home", homeStore)) - } - } - }.executor(CommandHome(this, homeStore)).register() - } - - override fun loadPlayerData(uuid: UUID): CompletableFuture { - return CompletableFuture.runAsync { - homeStore.loadHomeListBlocking(uuid) - } - } - - override fun savePlayerData(uuid: UUID): CompletableFuture { - return CompletableFuture.runAsync { - homeStore.saveHomeListBlocking(uuid) - } - } - - override fun forgetPlayerData(uuid: UUID) { - homeStore.forgetHomeList(uuid) - } -} diff --git a/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/Messages.kt b/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/Messages.kt deleted file mode 100644 index 93de9116..00000000 --- a/modules/basics-homes/src/main/kotlin/com/github/spigotbasics/modules/basicshomes/v2/Messages.kt +++ /dev/null @@ -1,23 +0,0 @@ -package com.github.spigotbasics.modules.basicshomes.v2 - -import com.github.spigotbasics.core.config.ConfigInstantiationContext -import com.github.spigotbasics.core.config.SavedConfig -import com.github.spigotbasics.modules.basicshomes.data.Home - -class Messages(context: ConfigInstantiationContext) : SavedConfig(context) { - val homeNotFound get() = getMessage("home-not-found") - val homeList get() = getMessage("home-list") - val homeListEntry get() = getMessage("home-list-entry") - val homeListSeparator get() = getMessage("home-list-separator") - val homeNoneSet get() = getMessage("home-none-set") - - fun homeTeleport(home: Home) = getMessage("home-teleport").tags(home) - - fun homeSet(home: Home) = getMessage("home-set").tags(home) - - fun homeRemoved(home: Home) = getMessage("home-remove").tags(home) - - fun homeLimitReached(limit: Int) = getMessage("home-limit-reached").tagParsed("limit", limit.toString()) - - fun homeRegexViolated(regex: String) = getMessage("home-invalid-name").tagParsed("regex", regex) -} diff --git a/modules/basics-homes/src/main/resources/basics-module.yml b/modules/basics-homes/src/main/resources/basics-module.yml index ba4f356d..78c7903e 100644 --- a/modules/basics-homes/src/main/resources/basics-module.yml +++ b/modules/basics-homes/src/main/resources/basics-module.yml @@ -1,4 +1,4 @@ -main-class: com.github.spigotbasics.modules.basicshomes.v2.BasicsHomesModule +main-class: com.github.spigotbasics.modules.basicshomes.BasicsHomesModule name: basics-homes version: ${moduleVersion} description: "Simple home management" diff --git a/modules/basics-msg/src/main/kotlin/com/github/spigotbasics/modules/basicsmsg/BasicsMessageModule.kt b/modules/basics-msg/src/main/kotlin/com/github/spigotbasics/modules/basicsmsg/BasicsMessageModule.kt new file mode 100644 index 00000000..73e2c5cd --- /dev/null +++ b/modules/basics-msg/src/main/kotlin/com/github/spigotbasics/modules/basicsmsg/BasicsMessageModule.kt @@ -0,0 +1,59 @@ +package com.github.spigotbasics.modules.basicsmsg + +import com.github.spigotbasics.core.command.parsed.arguments.GreedyStringArg +import com.github.spigotbasics.core.command.parsed.arguments.SelectorSinglePlayerArg +import com.github.spigotbasics.core.config.ConfigName +import com.github.spigotbasics.core.module.AbstractBasicsModule +import com.github.spigotbasics.core.module.loader.ModuleInstantiationContext +import com.github.spigotbasics.modules.basicsmsg.command.CommandMessage +import com.github.spigotbasics.modules.basicsmsg.command.CommandRespond +import org.bukkit.event.player.PlayerJoinEvent +import org.bukkit.permissions.PermissionDefault + +class BasicsMessageModule(context: ModuleInstantiationContext) : AbstractBasicsModule(context) { + private val permissionPM = + permissionManager.createSimplePermission( + "basics.msg", + "Allows the player to send private messages", + PermissionDefault.TRUE, + ) + private val permissionRespond = + permissionManager.createSimplePermission( + "basics.respond", + "Allows the player a shortcut to respond to private messages", + PermissionDefault.TRUE, + ) + + val lastMessagedStore = LastMessagedStore() + + override val messages: Messages = getConfig(ConfigName.MESSAGES, Messages::class.java) + + override fun onEnable() { + eventBus.subscribe(PlayerJoinEvent::class.java) { lastMessagedStore.forgetLastMessagedUUID(it.player.uniqueId) } + commandFactory.parsedCommandBuilder("message", permissionPM).mapContext { + description("Sends a private message to another player") + usage = " " + aliases(listOf("msg", "tell", "whisper")) + + path { + arguments { + named("player", SelectorSinglePlayerArg("player")) + named("message", GreedyStringArg("message")) + } + } + }.executor(CommandMessage(messages, lastMessagedStore)).register() + + commandFactory.parsedCommandBuilder("respond", permissionRespond).mapContext { + description("Responds to the person the last message was sent to in this session") + usage = "" + aliases(listOf("r", "re")) + + path { + playerOnly() + arguments { + named("message", GreedyStringArg("message")) + } + } + }.executor(CommandRespond(messages, lastMessagedStore)).register() + } +} diff --git a/modules/basics-msg/src/main/kotlin/com/github/spigotbasics/modules/basicsmsg/BasicsMsgModule.kt b/modules/basics-msg/src/main/kotlin/com/github/spigotbasics/modules/basicsmsg/BasicsMsgModule.kt deleted file mode 100644 index 02448398..00000000 --- a/modules/basics-msg/src/main/kotlin/com/github/spigotbasics/modules/basicsmsg/BasicsMsgModule.kt +++ /dev/null @@ -1,35 +0,0 @@ -package com.github.spigotbasics.modules.basicsmsg - -import com.github.spigotbasics.core.messages.Message -import com.github.spigotbasics.core.module.AbstractBasicsModule -import com.github.spigotbasics.core.module.loader.ModuleInstantiationContext -import org.bukkit.permissions.PermissionDefault - -class BasicsMsgModule(context: ModuleInstantiationContext) : AbstractBasicsModule(context) { - val formatReceived: Message - get() = config.getMessage("format-received") - - val formatSent: Message - get() = config.getMessage("format-sent") - - val formatSelf: Message - get() = config.getMessage("format-self") - - val formatConsole: Message - get() = config.getMessage("format-console") - - val permission = - permissionManager.createSimplePermission( - "basics.msg", - "Allows the player to send private messages", - PermissionDefault.TRUE, - ) - - override fun onEnable() { - commandFactory.rawCommandBuilder("msg", permission) - .description("Sends a private message to another player") - .usage(" ") - .executor(MsgExecutor(this)) - .register() - } -} diff --git a/modules/basics-msg/src/main/kotlin/com/github/spigotbasics/modules/basicsmsg/LastMessagedStore.kt b/modules/basics-msg/src/main/kotlin/com/github/spigotbasics/modules/basicsmsg/LastMessagedStore.kt new file mode 100644 index 00000000..2409d024 --- /dev/null +++ b/modules/basics-msg/src/main/kotlin/com/github/spigotbasics/modules/basicsmsg/LastMessagedStore.kt @@ -0,0 +1,23 @@ +package com.github.spigotbasics.modules.basicsmsg + +import java.util.UUID + +class LastMessagedStore { + private val lastMessagedStore = mutableMapOf() + + fun setLastMessagedUUID( + sender: UUID, + receiver: UUID, + ) { + lastMessagedStore[sender] = receiver + lastMessagedStore[receiver] = sender + } + + fun getLastMessagedUUID(uuid: UUID): UUID? { + return lastMessagedStore[uuid] + } + + fun forgetLastMessagedUUID(uuid: UUID) { + lastMessagedStore.remove(uuid) + } +} diff --git a/modules/basics-msg/src/main/kotlin/com/github/spigotbasics/modules/basicsmsg/Messages.kt b/modules/basics-msg/src/main/kotlin/com/github/spigotbasics/modules/basicsmsg/Messages.kt new file mode 100644 index 00000000..bdf7f477 --- /dev/null +++ b/modules/basics-msg/src/main/kotlin/com/github/spigotbasics/modules/basicsmsg/Messages.kt @@ -0,0 +1,19 @@ +package com.github.spigotbasics.modules.basicsmsg + +import com.github.spigotbasics.core.config.ConfigInstantiationContext +import com.github.spigotbasics.core.config.SavedConfig + +class Messages(context: ConfigInstantiationContext) : SavedConfig(context) { + val noRecentMessages get() = getMessage("no-recent-messages") + val recentNotOnline get() = getMessage("recent-not-online") + + fun formatReceived(message: String) = getMessage("format-received").tagParsed("message", message) + + fun formatSent(message: String) = getMessage("format-sent").tagParsed("message", message) + + fun formatSelf(message: String) = getMessage("format-self").tagParsed("message", message) + + fun formatConsole(message: String) = getMessage("format-console").tagParsed("message", message) + + fun formatOther(message: String) = getMessage("format-other").tagParsed("message", message) +} diff --git a/modules/basics-msg/src/main/kotlin/com/github/spigotbasics/modules/basicsmsg/MsgExecutor.kt b/modules/basics-msg/src/main/kotlin/com/github/spigotbasics/modules/basicsmsg/MsgExecutor.kt deleted file mode 100644 index 17986a66..00000000 --- a/modules/basics-msg/src/main/kotlin/com/github/spigotbasics/modules/basicsmsg/MsgExecutor.kt +++ /dev/null @@ -1,66 +0,0 @@ -package com.github.spigotbasics.modules.basicsmsg - -import com.github.spigotbasics.core.command.common.BasicsCommandExecutor -import com.github.spigotbasics.core.command.common.CommandResult -import com.github.spigotbasics.core.command.raw.RawCommandContext -import org.bukkit.command.CommandSender -import org.bukkit.entity.Player - -class MsgExecutor(private val module: BasicsMsgModule) : BasicsCommandExecutor(module) { - override fun execute(context: RawCommandContext): CommandResult { - val sender = context.sender - if (context.args.size < 2) { - return CommandResult.USAGE - } - val player = requirePlayer(context.args[0]) - val message = context.args.drop(1).joinToString(" ") - if (sender is Player) { - if (player.player == sender) { - player2self(sender, message) - } else { - player2player(sender, player, message) - } - } else { - console2player(sender, player, message) - } - return CommandResult.SUCCESS - } - - override fun tabComplete(context: RawCommandContext): MutableList? { - if (context.args.size == 1) { - return null // null = normal list of players - } else { - return mutableListOf() - } - } - - private fun console2player( - sender: CommandSender, - player: Player, - message: String, - ) { - val msg = module.formatConsole - msg.tagUnparsed("message", message).sendToPlayer(player) - module.formatSent.concerns(player).tagUnparsed("message", message).sendToSender(sender) - } - - private fun player2player( - sender: Player, - receiver: Player, - message: String, - ) { - val receivedMsg = module.formatReceived - val sentMsg = module.formatSent - - receivedMsg.concerns(sender).tagUnparsed("message", message).sendToPlayer(receiver) - sentMsg.concerns(receiver).tagUnparsed("message", message).sendToPlayer(sender) - } - - private fun player2self( - player: Player, - message: String, - ) { - val msg = module.formatSelf - msg.concerns(player).tagUnparsed("message", message).sendToPlayer(player) - } -} diff --git a/modules/basics-msg/src/main/kotlin/com/github/spigotbasics/modules/basicsmsg/command/CommandMessage.kt b/modules/basics-msg/src/main/kotlin/com/github/spigotbasics/modules/basicsmsg/command/CommandMessage.kt new file mode 100644 index 00000000..eaa09611 --- /dev/null +++ b/modules/basics-msg/src/main/kotlin/com/github/spigotbasics/modules/basicsmsg/command/CommandMessage.kt @@ -0,0 +1,39 @@ +package com.github.spigotbasics.modules.basicsmsg.command + +import com.github.spigotbasics.core.command.parsed.CommandContextExecutor +import com.github.spigotbasics.core.command.parsed.context.MapContext +import com.github.spigotbasics.modules.basicsmsg.LastMessagedStore +import com.github.spigotbasics.modules.basicsmsg.Messages +import org.bukkit.command.CommandSender +import org.bukkit.command.ConsoleCommandSender +import org.bukkit.entity.Player + +class CommandMessage(private val messages: Messages, private val store: LastMessagedStore) : CommandContextExecutor { + override fun execute( + sender: CommandSender, + context: MapContext, + ) { + val player = context["player"] as Player + val message = context["message"] as String + + when (sender) { + is Player -> { + if (sender == player) { + messages.formatSelf(message).concerns(sender).sendToPlayer(player) + } else { + messages.formatSent(message).concerns(player).sendToPlayer(sender) + messages.formatReceived(message).concerns(sender).sendToPlayer(player) + store.setLastMessagedUUID(sender.uniqueId, player.uniqueId) + } + } + + is ConsoleCommandSender -> { + messages.formatConsole(message).sendToPlayer(player) + } + + else -> { + messages.formatOther(message).sendToSender(player) + } + } + } +} diff --git a/modules/basics-msg/src/main/kotlin/com/github/spigotbasics/modules/basicsmsg/command/CommandRespond.kt b/modules/basics-msg/src/main/kotlin/com/github/spigotbasics/modules/basicsmsg/command/CommandRespond.kt new file mode 100644 index 00000000..c25aa31f --- /dev/null +++ b/modules/basics-msg/src/main/kotlin/com/github/spigotbasics/modules/basicsmsg/command/CommandRespond.kt @@ -0,0 +1,34 @@ +package com.github.spigotbasics.modules.basicsmsg.command + +import com.github.spigotbasics.core.command.parsed.CommandContextExecutor +import com.github.spigotbasics.core.command.parsed.context.MapContext +import com.github.spigotbasics.modules.basicsmsg.LastMessagedStore +import com.github.spigotbasics.modules.basicsmsg.Messages +import org.bukkit.Bukkit +import org.bukkit.command.CommandSender +import org.bukkit.entity.Player + +class CommandRespond(private val messages: Messages, private val lastMessagedStore: LastMessagedStore) : + CommandContextExecutor { + override fun execute( + sender: CommandSender, + context: MapContext, + ) { + val player = sender as Player + val message = context["message"] as String + val targetUUID = lastMessagedStore.getLastMessagedUUID(player.uniqueId) + if (targetUUID == null) { + messages.noRecentMessages.sendToSender(player) + return + } + + val target = Bukkit.getPlayer(targetUUID) + if (target == null) { + messages.recentNotOnline.sendToSender(player) + return + } + + messages.formatSent(message).concerns(target).sendToPlayer(player) + messages.formatReceived(message).concerns(player).sendToPlayer(target) + } +} diff --git a/modules/basics-msg/src/main/resources/basics-module.yml b/modules/basics-msg/src/main/resources/basics-module.yml index 17f51aa4..9c712070 100644 --- a/modules/basics-msg/src/main/resources/basics-module.yml +++ b/modules/basics-msg/src/main/resources/basics-module.yml @@ -1,4 +1,4 @@ -main-class: com.github.spigotbasics.modules.basicsmsg.BasicsMsgModule +main-class: com.github.spigotbasics.modules.basicsmsg.BasicsMessageModule name: basics-msg version: ${moduleVersion} -description: "Simple private messaging" \ No newline at end of file +description: "Simple private messaging" diff --git a/modules/basics-msg/src/main/resources/config.yml b/modules/basics-msg/src/main/resources/messages.yml similarity index 54% rename from modules/basics-msg/src/main/resources/config.yml rename to modules/basics-msg/src/main/resources/messages.yml index 1268faab..1fa2d97f 100644 --- a/modules/basics-msg/src/main/resources/config.yml +++ b/modules/basics-msg/src/main/resources/messages.yml @@ -2,4 +2,9 @@ format-received: "[ » You ] <#message>" format-sent: "[ You » ] <#message>" format-self: "[ You » Yourself ] <#message>" -format-console: "[ Console » you ] <#message>" +format-console: "[ Console » You ] <#message>" +format-other: "[ Unknown » You ] <#message>" + +# Tags: NONE +no-recent-messages: "You have not recently messaged someone so you can not respond" +recent-not-online: "The player you last sent a message to is not online and can not be messaged" From 5020b80fd2a1782ad4f57d39173abee3b5713ae7 Mon Sep 17 00:00:00 2001 From: Miles Holder Date: Wed, 29 May 2024 15:22:04 -0500 Subject: [PATCH 12/13] cleanup repair --- modules/basics-msg/README.md | 7 +- modules/basics-repair/README.md | 12 +- .../basicsrepair/BasicsRepairModule.kt | 45 ++++++- .../modules/basicsrepair/CommandRepairAll.kt | 34 +++++ .../modules/basicsrepair/CommandRepairHand.kt | 34 +++++ .../modules/basicsrepair/RepairCommand.kt | 123 ------------------ .../modules/basicsrepair/RepairUtils.kt | 26 ++++ .../src/main/resources/messages.yml | 2 + 8 files changed, 144 insertions(+), 139 deletions(-) create mode 100644 modules/basics-repair/src/main/kotlin/com/github/spigotbasics/modules/basicsrepair/CommandRepairAll.kt create mode 100644 modules/basics-repair/src/main/kotlin/com/github/spigotbasics/modules/basicsrepair/CommandRepairHand.kt delete mode 100644 modules/basics-repair/src/main/kotlin/com/github/spigotbasics/modules/basicsrepair/RepairCommand.kt create mode 100644 modules/basics-repair/src/main/kotlin/com/github/spigotbasics/modules/basicsrepair/RepairUtils.kt diff --git a/modules/basics-msg/README.md b/modules/basics-msg/README.md index 4ef4a14a..bb3e92da 100644 --- a/modules/basics-msg/README.md +++ b/modules/basics-msg/README.md @@ -1,3 +1,4 @@ -| Command | Permission | -|---------------------------|------------| -| `/msg ` | basics.msg | +| Command | Permission | +|-------------------------------|----------------| +| `/message ` | basics.msg | +| `/respond ` | basics.respond | diff --git a/modules/basics-repair/README.md b/modules/basics-repair/README.md index d9e9ecae..86b48170 100644 --- a/modules/basics-repair/README.md +++ b/modules/basics-repair/README.md @@ -1,6 +1,6 @@ -| Command | Permission | -|--------------------------|----------------------| -| `/repair` | basics.repair | -| `/repair --all` | basics.repair.all | -| `/repair ` | basics.repair.others | -| `/repair --all ` | basics.repair.others | +| Command | Permission | +|----------------------|----------------------| +| `/repair` | basics.repair | +| `/repairall` | basics.repair.all | +| `/repair ` | basics.repair.others | +| `/repaiall ` | basics.repair.others | diff --git a/modules/basics-repair/src/main/kotlin/com/github/spigotbasics/modules/basicsrepair/BasicsRepairModule.kt b/modules/basics-repair/src/main/kotlin/com/github/spigotbasics/modules/basicsrepair/BasicsRepairModule.kt index 3461c45c..941838f8 100644 --- a/modules/basics-repair/src/main/kotlin/com/github/spigotbasics/modules/basicsrepair/BasicsRepairModule.kt +++ b/modules/basics-repair/src/main/kotlin/com/github/spigotbasics/modules/basicsrepair/BasicsRepairModule.kt @@ -1,5 +1,6 @@ package com.github.spigotbasics.modules.basicsrepair +import com.github.spigotbasics.core.command.parsed.arguments.SelectorSinglePlayerArg import com.github.spigotbasics.core.messages.Message import com.github.spigotbasics.core.module.AbstractBasicsModule import com.github.spigotbasics.core.module.loader.ModuleInstantiationContext @@ -17,16 +18,46 @@ class BasicsRepairModule(context: ModuleInstantiationContext) : AbstractBasicsMo val msgRepairAllSelf: Message get() = messages.getMessage("repair-all-self") - val permission = permissionManager.createSimplePermission("basics.repair", "Allows to repair your current items") + val msgNothingToRepair: Message get() = messages.getMessage("repair-no-item") + + private val permission = + permissionManager.createSimplePermission("basics.repair", "Allows to repair your current items") val permissionAll = permissionManager.createSimplePermission("basics.repair.all", "Allows to repair all your items") - val permissionOthers = permissionManager.createSimplePermission("basics.repair.others", "Allows to repair other players' items") + val permissionOthers = + permissionManager.createSimplePermission("basics.repair.others", "Allows to repair other players' items") override fun onEnable() { - commandFactory.rawCommandBuilder("repair", permission) - .usage("[--all] [player]") - .description("Repairs an item") - .executor(RepairCommand(this)) - .register() + commandFactory.parsedCommandBuilder("repair", permission).mapContext { + description("Repairs an Item") + usage = "[player]" + + path { + playerOnly() + } + + path { + arguments { + permissions(permissionOthers) + named("player", SelectorSinglePlayerArg("player")) + } + } + }.executor(CommandRepairHand(this)).register() + + commandFactory.parsedCommandBuilder("repairall", permissionAll).mapContext { + description("Repairs all Items") + usage = "[player]" + + path { + playerOnly() + } + + path { + arguments { + permissions(permissionOthers) + named("player", SelectorSinglePlayerArg("player")) + } + } + }.executor(CommandRepairAll(this)).register() } override fun reloadConfig() { diff --git a/modules/basics-repair/src/main/kotlin/com/github/spigotbasics/modules/basicsrepair/CommandRepairAll.kt b/modules/basics-repair/src/main/kotlin/com/github/spigotbasics/modules/basicsrepair/CommandRepairAll.kt new file mode 100644 index 00000000..b9596110 --- /dev/null +++ b/modules/basics-repair/src/main/kotlin/com/github/spigotbasics/modules/basicsrepair/CommandRepairAll.kt @@ -0,0 +1,34 @@ +package com.github.spigotbasics.modules.basicsrepair + +import com.github.spigotbasics.core.command.parsed.CommandContextExecutor +import com.github.spigotbasics.core.command.parsed.context.MapContext +import org.bukkit.command.CommandSender +import org.bukkit.entity.Player + +class CommandRepairAll(private val module: BasicsRepairModule) : CommandContextExecutor { + override fun execute( + sender: CommandSender, + context: MapContext, + ) { + val target = if (context["player"] != null) context["player"] as Player else sender as Player + + if (target == sender) { + runAllSelf(target) + } else { + runAllOther(sender, target) + } + } + + private fun runAllSelf(player: Player) { + repairAll(player) + module.msgRepairAllSelf.concerns(player).sendToPlayer(player) + } + + private fun runAllOther( + sender: CommandSender, + player: Player, + ) { + repairAll(player) + module.msgRepairAllOther.concerns(player.player).sendToSender(sender) + } +} diff --git a/modules/basics-repair/src/main/kotlin/com/github/spigotbasics/modules/basicsrepair/CommandRepairHand.kt b/modules/basics-repair/src/main/kotlin/com/github/spigotbasics/modules/basicsrepair/CommandRepairHand.kt new file mode 100644 index 00000000..2c347ffa --- /dev/null +++ b/modules/basics-repair/src/main/kotlin/com/github/spigotbasics/modules/basicsrepair/CommandRepairHand.kt @@ -0,0 +1,34 @@ +package com.github.spigotbasics.modules.basicsrepair + +import com.github.spigotbasics.core.command.parsed.CommandContextExecutor +import com.github.spigotbasics.core.command.parsed.context.MapContext +import org.bukkit.command.CommandSender +import org.bukkit.entity.Player + +class CommandRepairHand(private val module: BasicsRepairModule) : CommandContextExecutor { + override fun execute( + sender: CommandSender, + context: MapContext, + ) { + val target = if (context["player"] != null) context["player"] as Player else sender as Player + + if (target == sender) { + runHandSelf(target) + } else { + runHandOther(sender, target) + } + } + + private fun runHandSelf(player: Player) { + repairHand(player) + module.msgRepairHandSelf.concerns(player).sendToPlayer(player) + } + + private fun runHandOther( + sender: CommandSender, + player: Player, + ) { + repairHand(player) + module.msgRepairHandOther.concerns(player.player).sendToSender(sender) + } +} diff --git a/modules/basics-repair/src/main/kotlin/com/github/spigotbasics/modules/basicsrepair/RepairCommand.kt b/modules/basics-repair/src/main/kotlin/com/github/spigotbasics/modules/basicsrepair/RepairCommand.kt deleted file mode 100644 index 3e302e2a..00000000 --- a/modules/basics-repair/src/main/kotlin/com/github/spigotbasics/modules/basicsrepair/RepairCommand.kt +++ /dev/null @@ -1,123 +0,0 @@ -package com.github.spigotbasics.modules.basicsrepair - -import com.github.spigotbasics.core.command.TabCompleters -import com.github.spigotbasics.core.command.common.BasicsCommandExecutor -import com.github.spigotbasics.core.command.common.CommandResult -import com.github.spigotbasics.core.command.raw.RawCommandContext -import com.github.spigotbasics.core.extensions.startsWithIgnoreCase -import org.bukkit.command.CommandSender -import org.bukkit.entity.Player -import org.bukkit.inventory.ItemStack -import org.bukkit.inventory.meta.Damageable -import org.bukkit.util.StringUtil - -class RepairCommand(private val module: BasicsRepairModule) : BasicsCommandExecutor(module) { - override fun execute(context: RawCommandContext): CommandResult { - context.readFlags() - val args = context.args - val repairAll = context.popFlag("--all") - - if (repairAll) { - requirePermission(context.sender, module.permissionAll) - } - - val target = - if (args.size > 0) { - requirePlayer(args[0]) - } else { - requirePlayerOrMustSpecifyPlayerFromConsole(context.sender) - } - - if (target != context.sender) { - requirePermission(context.sender, module.permissionOthers) - } - - if (repairAll) { - if (target == context.sender) { - runAllSelf(target) - } else { - runAllOther(context.sender, target) - } - } else { - if (target == context.sender) { - runHandSelf(target) - } else { - runHandOther(context.sender, target) - } - } - - return CommandResult.SUCCESS - } - - override fun tabComplete(context: RawCommandContext): MutableList? { - val args = context.args - val sender = context.sender - val mayAll = sender.hasPermission(module.permissionAll) - val mayOthers = sender.hasPermission(module.permissionOthers) - - if (!mayAll && !mayOthers) return mutableListOf() - if (args.size == 1) { - if (mayAll && !mayOthers) { - return StringUtil.copyPartialMatches(args[0], listOf("--all"), mutableListOf()) - } else if (mayAll && mayOthers) { - return StringUtil.copyPartialMatches(args[0], listOf("--all") + TabCompleters.getPlayers(sender, args[0]), mutableListOf()) - } else if (!mayAll && mayOthers) { - return TabCompleters.getPlayers(sender, args[0]) - } - } else if (args.size == 2) { - if (mayAll && mayOthers && args[0].startsWithIgnoreCase("--")) { - return TabCompleters.getPlayers(sender, args[1]) - } - } - return mutableListOf() - } - - fun runHandSelf(player: Player) { - requireItemInHand(player) - repairHand(player) - module.msgRepairHandSelf.concerns(player).sendToPlayer(player) - } - - fun runHandOther( - sender: CommandSender, - player: Player, - ) { - requireItemInHandOther(player) - repairHand(player) - module.msgRepairHandOther.concerns(player.player).sendToSender(sender) - } - - fun runAllSelf(player: Player) { - repairAll(player) - module.msgRepairAllSelf.concerns(player).sendToPlayer(player) - } - - fun runAllOther( - sender: CommandSender, - player: Player, - ) { - repairAll(player) - module.msgRepairAllOther.concerns(player.player).sendToSender(sender) - } - - private fun repairHand(target: Player) { - repairItem(target.inventory.itemInMainHand) - } - - private fun repairAll(target: Player) { - for (content in target.inventory.contents) { - repairItem(content) - } - } - - private fun repairItem(item: ItemStack?) { - if (item == null || item.type.isAir) return - val meta = item.itemMeta - if (meta is Damageable) { - if (meta.hasDamage()) { - meta.damage = 0 - item.setItemMeta(meta) - } - } - } -} diff --git a/modules/basics-repair/src/main/kotlin/com/github/spigotbasics/modules/basicsrepair/RepairUtils.kt b/modules/basics-repair/src/main/kotlin/com/github/spigotbasics/modules/basicsrepair/RepairUtils.kt new file mode 100644 index 00000000..a536a428 --- /dev/null +++ b/modules/basics-repair/src/main/kotlin/com/github/spigotbasics/modules/basicsrepair/RepairUtils.kt @@ -0,0 +1,26 @@ +package com.github.spigotbasics.modules.basicsrepair + +import org.bukkit.entity.Player +import org.bukkit.inventory.ItemStack +import org.bukkit.inventory.meta.Damageable + +fun repairHand(target: Player) { + repairItem(target.inventory.itemInMainHand) +} + +fun repairAll(target: Player) { + for (content in target.inventory.contents) { + repairItem(content) + } +} + +fun repairItem(item: ItemStack?) { + if (item == null || item.type.isAir) return + val meta = item.itemMeta + if (meta is Damageable) { + if (meta.hasDamage()) { + meta.damage = 0 + item.setItemMeta(meta) + } + } +} diff --git a/modules/basics-repair/src/main/resources/messages.yml b/modules/basics-repair/src/main/resources/messages.yml index 4518a855..50455725 100644 --- a/modules/basics-repair/src/main/resources/messages.yml +++ b/modules/basics-repair/src/main/resources/messages.yml @@ -9,3 +9,5 @@ repair-all-other: "Repaired <#player-name-geniti # Repair message sent when you repair your own inventory repair-all-self: "Repaired your inventory" + +repair-no-item: "The target had no item in their hand" From adde1321f065d9a8e42bda0db91ba519198c7282 Mon Sep 17 00:00:00 2001 From: Miles Holder Date: Wed, 29 May 2024 15:50:09 -0500 Subject: [PATCH 13/13] cleanup weather --- modules/basics-weather/README.md | 3 + .../basicsweather/BasicsWeatherModule.kt | 69 ++++++++++++++----- .../basicsweather/BasicsWeatherType.kt | 34 +++++++++ .../basicsweather/BasicsWeatherTypeArg.kt | 21 ++++++ .../modules/basicsweather/WeatherCommand.kt | 46 ------------- .../src/main/resources/messages.yml | 5 +- 6 files changed, 114 insertions(+), 64 deletions(-) create mode 100644 modules/basics-weather/README.md create mode 100644 modules/basics-weather/src/main/kotlin/com/github/spigotbasics/modules/basicsweather/BasicsWeatherType.kt create mode 100644 modules/basics-weather/src/main/kotlin/com/github/spigotbasics/modules/basicsweather/BasicsWeatherTypeArg.kt delete mode 100644 modules/basics-weather/src/main/kotlin/com/github/spigotbasics/modules/basicsweather/WeatherCommand.kt diff --git a/modules/basics-weather/README.md b/modules/basics-weather/README.md new file mode 100644 index 00000000..bd6e8a8c --- /dev/null +++ b/modules/basics-weather/README.md @@ -0,0 +1,3 @@ +| Command | Permission | +|--------------------------------------|----------------| +| `/weather [duration]` | basics.weather | diff --git a/modules/basics-weather/src/main/kotlin/com/github/spigotbasics/modules/basicsweather/BasicsWeatherModule.kt b/modules/basics-weather/src/main/kotlin/com/github/spigotbasics/modules/basicsweather/BasicsWeatherModule.kt index 1ce107c2..0897b951 100644 --- a/modules/basics-weather/src/main/kotlin/com/github/spigotbasics/modules/basicsweather/BasicsWeatherModule.kt +++ b/modules/basics-weather/src/main/kotlin/com/github/spigotbasics/modules/basicsweather/BasicsWeatherModule.kt @@ -1,28 +1,65 @@ package com.github.spigotbasics.modules.basicsweather +import com.github.spigotbasics.core.command.parsed.CommandContextExecutor +import com.github.spigotbasics.core.command.parsed.arguments.IntArg +import com.github.spigotbasics.core.command.parsed.context.MapContext +import com.github.spigotbasics.core.messages.Message import com.github.spigotbasics.core.module.AbstractBasicsModule import com.github.spigotbasics.core.module.loader.ModuleInstantiationContext -import org.bukkit.WeatherType +import org.bukkit.command.CommandSender +import org.bukkit.entity.Player class BasicsWeatherModule(context: ModuleInstantiationContext) : AbstractBasicsModule(context) { - val perm = permissionManager.createSimplePermission("basics.weather", "Allows the user to change the weather") + private val permission = permissionManager.createSimplePermission("basics.weather") - val msgClear get() = messages.getMessage("clear") - val msgStorm get() = messages.getMessage("storm") - val msgWeatherChanged get() = messages.getMessage("weather-changed") + private val weatherChangedMessage + get() = messages.getMessage("weather-changed") + private val clearMessage + get() = messages.getMessage("clear") + private val rainMessage + get() = messages.getMessage("rain") + private val thunderMessage + get() = messages.getMessage("thunder") override fun onEnable() { - commandFactory.rawCommandBuilder("weather", perm) - .usage(" [duration]") - .executor(WeatherCommand(this)) - .register() - } + commandFactory.parsedCommandBuilder("weather", permission).mapContext { + usage = "" + description("Sets the weather of the world") + + path { + arguments { + playerOnly() + named("type", BasicsWeatherTypeArg("type")) + } + } + + path { + arguments { + playerOnly() + named("type", BasicsWeatherTypeArg("type")) + named("duration", IntArg("duration")) + } + } + }.executor( + object : CommandContextExecutor { + override fun execute( + sender: CommandSender, + context: MapContext, + ) { + val player = sender as Player + val type = context["type"] as BasicsWeatherType + val duration = context["duration"] as Int? + type.activate(player.world, duration) + val statusMessage: Message = + when (type) { + BasicsWeatherType.CLEAR -> clearMessage + BasicsWeatherType.RAIN -> rainMessage + BasicsWeatherType.THUNDER -> thunderMessage + } - fun weatherTypeFromString(str: String): WeatherType? { - return when (str.lowercase()) { - "sun", "clear", "sunny" -> WeatherType.CLEAR - "storm", "rain", "rainy", "stormy" -> WeatherType.DOWNFALL - else -> null - } + weatherChangedMessage.tagMessage("new-weather", statusMessage).concerns(player).sendToPlayer(player) + } + }, + ).register() } } diff --git a/modules/basics-weather/src/main/kotlin/com/github/spigotbasics/modules/basicsweather/BasicsWeatherType.kt b/modules/basics-weather/src/main/kotlin/com/github/spigotbasics/modules/basicsweather/BasicsWeatherType.kt new file mode 100644 index 00000000..35a38902 --- /dev/null +++ b/modules/basics-weather/src/main/kotlin/com/github/spigotbasics/modules/basicsweather/BasicsWeatherType.kt @@ -0,0 +1,34 @@ +package com.github.spigotbasics.modules.basicsweather + +import org.bukkit.World + +enum class BasicsWeatherType(val activate: (World, Int?) -> Unit) { + CLEAR({ world: World, duration: Int? -> + if (!world.isClearWeather) world.setStorm(false) + if (duration != null) world.clearWeatherDuration = duration + }), + RAIN({ world: World, duration: Int? -> + if (!world.hasStorm()) world.setStorm(true) + if (duration != null) world.weatherDuration = duration + }), + THUNDER({ world: World, duration: Int? -> + RAIN.activate(world, duration) + if (!world.isThundering) world.isThundering = true + if (duration != null) world.thunderDuration = duration + }), + ; + + companion object { + fun fromString(weatherType: String): BasicsWeatherType? { + return if (weatherType.equals("clear", true)) { + CLEAR + } else if (weatherType.equals("rain", true)) { + RAIN + } else if (weatherType.equals("thunder", true)) { + THUNDER + } else { + null + } + } + } +} diff --git a/modules/basics-weather/src/main/kotlin/com/github/spigotbasics/modules/basicsweather/BasicsWeatherTypeArg.kt b/modules/basics-weather/src/main/kotlin/com/github/spigotbasics/modules/basicsweather/BasicsWeatherTypeArg.kt new file mode 100644 index 00000000..bb0805cc --- /dev/null +++ b/modules/basics-weather/src/main/kotlin/com/github/spigotbasics/modules/basicsweather/BasicsWeatherTypeArg.kt @@ -0,0 +1,21 @@ +package com.github.spigotbasics.modules.basicsweather + +import com.github.spigotbasics.core.command.parsed.arguments.CommandArgument +import com.github.spigotbasics.core.extensions.partialMatches +import org.bukkit.command.CommandSender + +class BasicsWeatherTypeArg(name: String) : CommandArgument(name) { + override fun parse( + sender: CommandSender, + value: String, + ): BasicsWeatherType? { + return BasicsWeatherType.fromString(value) + } + + override fun tabComplete( + sender: CommandSender, + typing: String, + ): List { + return BasicsWeatherType.entries.map { it.name.lowercase() }.partialMatches(typing) + } +} diff --git a/modules/basics-weather/src/main/kotlin/com/github/spigotbasics/modules/basicsweather/WeatherCommand.kt b/modules/basics-weather/src/main/kotlin/com/github/spigotbasics/modules/basicsweather/WeatherCommand.kt deleted file mode 100644 index 58c219a9..00000000 --- a/modules/basics-weather/src/main/kotlin/com/github/spigotbasics/modules/basicsweather/WeatherCommand.kt +++ /dev/null @@ -1,46 +0,0 @@ -package com.github.spigotbasics.modules.basicsweather - -import com.github.spigotbasics.core.command.common.BasicsCommandExecutor -import com.github.spigotbasics.core.command.common.CommandResult -import com.github.spigotbasics.core.command.raw.RawCommandContext -import com.github.spigotbasics.core.extensions.partialMatches -import org.bukkit.WeatherType - -class WeatherCommand(val module: BasicsWeatherModule) : BasicsCommandExecutor(module) { - override fun execute(context: RawCommandContext): CommandResult? { - val player = requirePlayer(context.sender) - val args = context.args - if (args.isEmpty()) { - return CommandResult.USAGE - } - val weatherType = module.weatherTypeFromString(args[0]) ?: throw failInvalidArgument(args[0]).asException() - val world = player.world - - // TODO: Implement duration - -// val duration = if (args.size > 1) { -// val dur = args[1].toIntOrNull() ?: throw failInvalidArgument(args[1]).asException() -// if (dur < 0) { -// throw failInvalidArgument(args[1]).asException() -// } -// dur -// } else { -// 0 -// } - - val weatherName = - when (weatherType) { - WeatherType.CLEAR -> module.msgClear - WeatherType.DOWNFALL -> module.msgStorm - } - - val message = module.msgWeatherChanged.tagMessage("new-weather", weatherName) - world.setStorm(weatherType == WeatherType.DOWNFALL) - message.sendToSender(context.sender) - return CommandResult.SUCCESS - } - - override fun tabComplete(context: RawCommandContext): List { - return listOf("clear", "storm").partialMatches(context.args[0]) - } -} diff --git a/modules/basics-weather/src/main/resources/messages.yml b/modules/basics-weather/src/main/resources/messages.yml index 695c5af2..0350eb0c 100644 --- a/modules/basics-weather/src/main/resources/messages.yml +++ b/modules/basics-weather/src/main/resources/messages.yml @@ -1,5 +1,6 @@ # Tags: <#new-weather> weather-changed: "Set the weather to <#new-weather>." -storm: "storm" -clear: "clear" \ No newline at end of file +clear: "clear" +rain: "rain" +thunder: "thunder"