diff options
| author | Carson Fleming <cflems@cflems.net> | 2025-06-30 20:09:33 -0400 |
|---|---|---|
| committer | Carson Fleming <cflems@cflems.net> | 2025-06-30 20:09:33 -0400 |
| commit | 12f7aa2de5290e37ff417d29b7b95ba72c00d0d9 (patch) | |
| tree | 0cfa9b97c5b1cea54ad9f26baa3470189eada2ed | |
| download | mc-sandbox-12f7aa2de5290e37ff417d29b7b95ba72c00d0d9.tar.gz | |
Initial project with repair, enchant, fireball, fly, and powertool
19 files changed, 927 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9c90935 --- /dev/null +++ b/.gitignore @@ -0,0 +1,43 @@ +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### IntelliJ IDEA ### +.idea/ +#.idea/modules.xml +#.idea/jarRepositories.xml +#.idea/compiler.xml +#.idea/libraries/ +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..1a58fb4 --- /dev/null +++ b/build.gradle @@ -0,0 +1,14 @@ +apply plugin: 'java' +group = 'net.cflems.mc.sandbox' +version = '0.1.0' + +repositories { + mavenCentral() + maven { url = 'https://hub.spigotmc.org/nexus/content/repositories/snapshots/' } +} + +dependencies { + implementation 'org.spigotmc:spigot-api:1.21.6-R0.1-SNAPSHOT' +} + +defaultTasks 'clean', 'build' diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar Binary files differnew file mode 100644 index 0000000..249e583 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.jar diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..3147b7d --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Thu Jun 26 23:11:31 EDT 2025 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists @@ -0,0 +1,234 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..ac1b06f --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,89 @@ +@rem
+@rem Copyright 2015 the original author or authors.
+@rem
+@rem Licensed under the Apache License, Version 2.0 (the "License");
+@rem you may not use this file except in compliance with the License.
+@rem You may obtain a copy of the License at
+@rem
+@rem https://www.apache.org/licenses/LICENSE-2.0
+@rem
+@rem Unless required by applicable law or agreed to in writing, software
+@rem distributed under the License is distributed on an "AS IS" BASIS,
+@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@rem See the License for the specific language governing permissions and
+@rem limitations under the License.
+@rem
+
+@if "%DEBUG%" == "" @echo off
+@rem ##########################################################################
+@rem
+@rem Gradle startup script for Windows
+@rem
+@rem ##########################################################################
+
+@rem Set local scope for the variables with windows NT shell
+if "%OS%"=="Windows_NT" setlocal
+
+set DIRNAME=%~dp0
+if "%DIRNAME%" == "" set DIRNAME=.
+set APP_BASE_NAME=%~n0
+set APP_HOME=%DIRNAME%
+
+@rem Resolve any "." and ".." in APP_HOME to make it shorter.
+for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
+
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
+
+@rem Find java.exe
+if defined JAVA_HOME goto findJavaFromJavaHome
+
+set JAVA_EXE=java.exe
+%JAVA_EXE% -version >NUL 2>&1
+if "%ERRORLEVEL%" == "0" goto execute
+
+echo.
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:findJavaFromJavaHome
+set JAVA_HOME=%JAVA_HOME:"=%
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe
+
+if exist "%JAVA_EXE%" goto execute
+
+echo.
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:execute
+@rem Setup the command line
+
+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
+
+
+@rem Execute Gradle
+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
+
+:end
+@rem End local scope for the variables with windows NT shell
+if "%ERRORLEVEL%"=="0" goto mainEnd
+
+:fail
+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
+rem the _cmd.exe /c_ return code!
+if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
+exit /b 1
+
+:mainEnd
+if "%OS%"=="Windows_NT" endlocal
+
+:omega
diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..2951f16 --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'Sandbox' diff --git a/src/main/java/net/cflems/mc/sandbox/CommandUtils.java b/src/main/java/net/cflems/mc/sandbox/CommandUtils.java new file mode 100644 index 0000000..a954c5b --- /dev/null +++ b/src/main/java/net/cflems/mc/sandbox/CommandUtils.java @@ -0,0 +1,14 @@ +package net.cflems.mc.sandbox; + +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; + +public final class CommandUtils { + private static final String RESPONSE_PREFIX = ChatColor.GOLD + "[Sandbox] " + ChatColor.RESET; + + private CommandUtils() {} + + public static void respond(CommandSender sender, String message) { + sender.sendMessage(RESPONSE_PREFIX + message); + } +} diff --git a/src/main/java/net/cflems/mc/sandbox/PlayerTargetedCommand.java b/src/main/java/net/cflems/mc/sandbox/PlayerTargetedCommand.java new file mode 100644 index 0000000..8a553bc --- /dev/null +++ b/src/main/java/net/cflems/mc/sandbox/PlayerTargetedCommand.java @@ -0,0 +1,88 @@ +package net.cflems.mc.sandbox; + +import com.google.errorprone.annotations.CompileTimeConstant; +import java.util.Arrays; +import java.util.function.Consumer; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +public abstract class PlayerTargetedCommand implements CommandExecutor { + private final int minArgs; + private final int maxArgs; + private final String permission; + private final String permissionMessage; + private final String othersPermission; + private final String othersPermissionMessage; + + protected PlayerTargetedCommand( + int minArgs, + int maxArgs, + @CompileTimeConstant String permission, + String permissionMessage, + String othersPermissionMessage) { + this( + minArgs, + maxArgs, + permission, + permission + ".others", + permissionMessage, + othersPermissionMessage); + } + + protected PlayerTargetedCommand( + int minArgs, + int maxArgs, + @CompileTimeConstant String permission, + @CompileTimeConstant String othersPermission, + String permissionMessage, + String othersPermissionMessage) { + this.minArgs = minArgs; + this.maxArgs = maxArgs + 1; + this.permission = permission; + this.othersPermission = othersPermission; + this.permissionMessage = permissionMessage; + this.othersPermissionMessage = othersPermissionMessage; + } + + @SuppressWarnings("NullableProblems") + @Override + public final boolean onCommand( + CommandSender sender, org.bukkit.command.Command _command, String label, String[] args) { + if (!sender.hasPermission(permission)) { + CommandUtils.respond(sender, permissionMessage); + return true; + } + int numArgs = args.length; + if (numArgs < minArgs || numArgs > maxArgs) return false; + + Player player; + if (sender instanceof Player sendingPlayer && numArgs < maxArgs) { + player = sendingPlayer; + } else if (numArgs == maxArgs) { + player = sender.getServer().getPlayer(args[--numArgs]); + if (player == null) { + CommandUtils.respond( + sender, "Specified player not found, make sure to refer to them by name."); + return true; + } + if (player != sender && !sender.hasPermission(othersPermission)) { + CommandUtils.respond(sender, othersPermissionMessage); + return true; + } + } else { + CommandUtils.respond( + sender, "When executed from the console, a player must be explicitly specified."); + return true; + } + + return execute( + player, + label, + args.length > numArgs ? Arrays.copyOfRange(args, 0, numArgs) : args, + msg -> CommandUtils.respond(sender, msg)); + } + + protected abstract boolean execute( + Player player, String label, String[] args, Consumer<String> respond); +} diff --git a/src/main/java/net/cflems/mc/sandbox/Sandbox.java b/src/main/java/net/cflems/mc/sandbox/Sandbox.java new file mode 100644 index 0000000..34127f1 --- /dev/null +++ b/src/main/java/net/cflems/mc/sandbox/Sandbox.java @@ -0,0 +1,25 @@ +package net.cflems.mc.sandbox; + +import net.cflems.mc.sandbox.commands.Enchant; +import net.cflems.mc.sandbox.commands.Fireball; +import net.cflems.mc.sandbox.commands.Fly; +import net.cflems.mc.sandbox.commands.PowerTool; +import net.cflems.mc.sandbox.commands.Repair; +import net.cflems.mc.sandbox.listeners.PowerToolListener; +import net.cflems.mc.sandbox.storage.PowerToolStore; +import org.bukkit.plugin.java.JavaPlugin; + +public class Sandbox extends JavaPlugin { + public static final String PERMISSION_NAMESPACE = "sandbox"; + + @Override + public void onEnable() { + PowerToolStore powerToolStore = new PowerToolStore(getDataFolder()); + getServer().getPluginManager().registerEvents(new PowerToolListener(powerToolStore), this); + this.getCommand("enchant").setExecutor(new Enchant()); + this.getCommand("fly").setExecutor(new Fly()); + this.getCommand("repair").setExecutor(new Repair()); + this.getCommand("fireball").setExecutor(new Fireball()); + this.getCommand("powertool").setExecutor(new PowerTool(powerToolStore)); + } +} diff --git a/src/main/java/net/cflems/mc/sandbox/commands/Enchant.java b/src/main/java/net/cflems/mc/sandbox/commands/Enchant.java new file mode 100644 index 0000000..66ea806 --- /dev/null +++ b/src/main/java/net/cflems/mc/sandbox/commands/Enchant.java @@ -0,0 +1,55 @@ +package net.cflems.mc.sandbox.commands; + +import java.util.Locale; +import java.util.function.Consumer; +import net.cflems.mc.sandbox.PlayerTargetedCommand; +import net.cflems.mc.sandbox.Sandbox; +import org.bukkit.NamespacedKey; +import org.bukkit.Registry; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public final class Enchant extends PlayerTargetedCommand { + private static final int MIN_ARGS = 1; + private static final int MAX_ARGS = 2; + private static final String PERMISSION = Sandbox.PERMISSION_NAMESPACE + ".enchant"; + private static final String PERMISSION_MESSAGE = "You do not have permission to enchant items."; + private static final String OTHERS_PERMISSION_MESSAGE = + "You do not have permission to enchant other people's items."; + + public Enchant() { + super(MIN_ARGS, MAX_ARGS, PERMISSION, PERMISSION_MESSAGE, OTHERS_PERMISSION_MESSAGE); + } + + @Override + protected boolean execute(Player player, String _label, String[] args, Consumer<String> respond) { + NamespacedKey enchantmentKey = NamespacedKey.fromString(args[0].toLowerCase(Locale.ROOT)); + Enchantment enchantment = + enchantmentKey != null ? Registry.ENCHANTMENT.get(enchantmentKey) : null; + if (enchantment == null) { + respond.accept("No such enchantment was found."); + return true; + } + + int level; + if (args.length < 2) level = 1; + else { + try { + level = Integer.parseInt(args[1]); + } catch (NumberFormatException _e) { + level = -1; + } + if (level < 0 || level > 255) { + respond.accept("Level must be a valid integer between 0 and 255."); + return true; + } + } + + ItemStack mhItem = player.getInventory().getItemInMainHand(); + if (level > 0) mhItem.addUnsafeEnchantment(enchantment, level); + else mhItem.removeEnchantment(enchantment); + respond.accept("Item enchanted successfully."); + return true; + } +} diff --git a/src/main/java/net/cflems/mc/sandbox/commands/Fireball.java b/src/main/java/net/cflems/mc/sandbox/commands/Fireball.java new file mode 100644 index 0000000..47f5e0c --- /dev/null +++ b/src/main/java/net/cflems/mc/sandbox/commands/Fireball.java @@ -0,0 +1,29 @@ +package net.cflems.mc.sandbox.commands; + +import net.cflems.mc.sandbox.CommandUtils; +import net.cflems.mc.sandbox.Sandbox; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; + +public final class Fireball implements CommandExecutor { + private static final String PERMISSION = Sandbox.PERMISSION_NAMESPACE + ".fireball"; + + @SuppressWarnings("NullableProblems") + @Override + public boolean onCommand( + CommandSender sender, org.bukkit.command.Command _command, String _label, String[] args) { + if (args.length > 0) return false; + if (!(sender instanceof Player player)) { + CommandUtils.respond(sender, "Only players can use fireballs."); + return true; + } + if (!sender.hasPermission(PERMISSION)) { + CommandUtils.respond(sender, "You do not have permission to use fireballs."); + return true; + } + player.getWorld().spawnEntity(player.getEyeLocation().subtract(0, 1, 0), EntityType.FIREBALL); + return true; + } +} diff --git a/src/main/java/net/cflems/mc/sandbox/commands/Fly.java b/src/main/java/net/cflems/mc/sandbox/commands/Fly.java new file mode 100644 index 0000000..9e4a9bc --- /dev/null +++ b/src/main/java/net/cflems/mc/sandbox/commands/Fly.java @@ -0,0 +1,32 @@ +package net.cflems.mc.sandbox.commands; + +import java.util.function.Consumer; +import net.cflems.mc.sandbox.PlayerTargetedCommand; +import net.cflems.mc.sandbox.Sandbox; +import org.bukkit.entity.Player; + +public final class Fly extends PlayerTargetedCommand { + private static final int MIN_ARGS = 0; + private static final int MAX_ARGS = 0; + private static final String PERMISSION = Sandbox.PERMISSION_NAMESPACE + ".fly"; + private static final String PERMISSION_MESSAGE = "You do not have permission to toggle flight."; + private static final String OTHERS_PERMISSION_MESSAGE = + "You do not have permission to toggle other people's flight."; + + public Fly() { + super(MIN_ARGS, MAX_ARGS, PERMISSION, PERMISSION_MESSAGE, OTHERS_PERMISSION_MESSAGE); + } + + @Override + protected boolean execute(Player player, String _label, String[] args, Consumer<String> respond) { + boolean allow = !player.getAllowFlight(); + player.setAllowFlight(allow); + respond.accept( + "Flight is now " + + (allow ? "\u00a72ENABLED\u00a7r" : "\u00a74DISABLED\u00a7r") + + " for " + + player.getName() + + "."); + return true; + } +} diff --git a/src/main/java/net/cflems/mc/sandbox/commands/PowerTool.java b/src/main/java/net/cflems/mc/sandbox/commands/PowerTool.java new file mode 100644 index 0000000..e4683f6 --- /dev/null +++ b/src/main/java/net/cflems/mc/sandbox/commands/PowerTool.java @@ -0,0 +1,63 @@ +package net.cflems.mc.sandbox.commands; + +import net.cflems.mc.sandbox.CommandUtils; +import net.cflems.mc.sandbox.Sandbox; +import net.cflems.mc.sandbox.storage.NoMetaException; +import net.cflems.mc.sandbox.storage.PowerToolStore; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public final class PowerTool implements CommandExecutor { + private static final String PERMISSION = Sandbox.PERMISSION_NAMESPACE + ".powertool"; + private static final String RELOAD_PERMISSION = PERMISSION + ".reload"; + + private final PowerToolStore store; + + public PowerTool(PowerToolStore store) { + this.store = store; + } + + @SuppressWarnings("NullableProblems") + @Override + public boolean onCommand(CommandSender sender, Command _command, String _label, String[] args) { + if (args.length == 1 && args[0].equalsIgnoreCase("reload")) { + if (!sender.hasPermission(RELOAD_PERMISSION)) + CommandUtils.respond(sender, "You do not have permission to reload power tool bindings."); + else if (store.reload()) + CommandUtils.respond(sender, "Power tool bindings reloaded successfully."); + else + CommandUtils.respond( + sender, + "Failed to reload bindings, configuration file may be missing or malformatted."); + return true; + } + + if (!(sender instanceof Player player)) { + CommandUtils.respond(sender, "Only players can make power tools."); + return true; + } + if (!sender.hasPermission(PERMISSION)) { + CommandUtils.respond(sender, "You do not have permission to make power tools."); + return true; + } + + ItemStack mhItem = player.getInventory().getItemInMainHand(); + mhItem.getItemMeta(); + if (args.length > 0) { + String command = String.join(" ", args); + try { + store.add(mhItem, command); + CommandUtils.respond(sender, "Power tool created successfully."); + } catch (NoMetaException e) { + CommandUtils.respond(sender, "Power tools must be item types that can hold metadata."); + } + } else { + store.clear(mhItem); + CommandUtils.respond(sender, "Power tool bindings cleared for this item."); + } + return true; + } +} diff --git a/src/main/java/net/cflems/mc/sandbox/commands/Repair.java b/src/main/java/net/cflems/mc/sandbox/commands/Repair.java new file mode 100644 index 0000000..f62a0da --- /dev/null +++ b/src/main/java/net/cflems/mc/sandbox/commands/Repair.java @@ -0,0 +1,36 @@ +package net.cflems.mc.sandbox.commands; + +import java.util.function.Consumer; +import net.cflems.mc.sandbox.PlayerTargetedCommand; +import net.cflems.mc.sandbox.Sandbox; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.Damageable; +import org.bukkit.inventory.meta.ItemMeta; + +public final class Repair extends PlayerTargetedCommand { + private static final int MIN_ARGS = 0; + private static final int MAX_ARGS = 0; + private static final String PERMISSION = Sandbox.PERMISSION_NAMESPACE + ".repair"; + private static final String PERMISSION_MESSAGE = "You do not have permission to repair items."; + private static final String OTHERS_PERMISSION_MESSAGE = + "You do not have permission to repair other people's items."; + + public Repair() { + super(MIN_ARGS, MAX_ARGS, PERMISSION, PERMISSION_MESSAGE, OTHERS_PERMISSION_MESSAGE); + } + + @Override + protected boolean execute(Player player, String _label, String[] args, Consumer<String> respond) { + ItemStack mhItem = player.getInventory().getItemInMainHand(); + ItemMeta mhItemMeta = player.getInventory().getItemInMainHand().getItemMeta(); + if (mhItemMeta instanceof Damageable damageMeta) { + damageMeta.setDamage(0); + mhItem.setItemMeta(damageMeta); + respond.accept("Item was successfully repaired."); + } else { + respond.accept("Item is not damageable so it can't be repaired."); + } + return true; + } +} diff --git a/src/main/java/net/cflems/mc/sandbox/listeners/PowerToolListener.java b/src/main/java/net/cflems/mc/sandbox/listeners/PowerToolListener.java new file mode 100644 index 0000000..25949d2 --- /dev/null +++ b/src/main/java/net/cflems/mc/sandbox/listeners/PowerToolListener.java @@ -0,0 +1,42 @@ +package net.cflems.mc.sandbox.listeners; + +import java.util.List; +import net.cflems.mc.sandbox.CommandUtils; +import net.cflems.mc.sandbox.storage.PowerToolStore; +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractEvent; + +public final class PowerToolListener implements Listener { + private static final String USE_PT_PERMISSION = "sandbox.powertool.use"; + + private final PowerToolStore store; + + public PowerToolListener(PowerToolStore store) { + this.store = store; + } + + @EventHandler(priority = EventPriority.NORMAL) + public void onPlayerInteract(PlayerInteractEvent event) { + if (!event.hasItem() + || event.useItemInHand().equals(Event.Result.DENY) + || (event.getAction() != Action.RIGHT_CLICK_AIR + && event.getAction() != Action.RIGHT_CLICK_BLOCK)) return; + + List<String> commands = store.get(event.getItem()); + if (commands.isEmpty()) return; + + Player player = event.getPlayer(); + if (!player.hasPermission(USE_PT_PERMISSION)) { + CommandUtils.respond(player, "You do not have permission to use power tools."); + return; + } + + commands.forEach(player::performCommand); + event.setCancelled(true); + } +} diff --git a/src/main/java/net/cflems/mc/sandbox/storage/NoMetaException.java b/src/main/java/net/cflems/mc/sandbox/storage/NoMetaException.java new file mode 100644 index 0000000..3242216 --- /dev/null +++ b/src/main/java/net/cflems/mc/sandbox/storage/NoMetaException.java @@ -0,0 +1,3 @@ +package net.cflems.mc.sandbox.storage; + +public class NoMetaException extends RuntimeException {} diff --git a/src/main/java/net/cflems/mc/sandbox/storage/PowerToolStore.java b/src/main/java/net/cflems/mc/sandbox/storage/PowerToolStore.java new file mode 100644 index 0000000..bbbd2a5 --- /dev/null +++ b/src/main/java/net/cflems/mc/sandbox/storage/PowerToolStore.java @@ -0,0 +1,91 @@ +package net.cflems.mc.sandbox.storage; + +import com.google.common.base.Preconditions; +import java.io.File; +import java.io.IOException; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import javax.annotation.Nullable; +import javax.annotation.concurrent.GuardedBy; +import org.bukkit.Bukkit; +import org.bukkit.NamespacedKey; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.persistence.PersistentDataType; + +public final class PowerToolStore { + private static final NamespacedKey ID_KEY = + Preconditions.checkNotNull(NamespacedKey.fromString("sandbox:tool-id")); + + @GuardedBy("this") + private final File configFile; + + @GuardedBy("this") + private final FileConfiguration config; + + public PowerToolStore(File dataFolder) { + this.configFile = new File(dataFolder, "power-tools.yml"); + this.config = YamlConfiguration.loadConfiguration(configFile); + } + + public synchronized List<String> get(@Nullable ItemStack item) { + if (item == null) return List.of(); + return getId(item).map(id -> config.getStringList(id.toString())).orElseGet(List::of); + } + + public synchronized void add(ItemStack item, String command) { + String path = getId(item).orElseGet(() -> createId(item)).toString(); + List<String> bindings = config.getStringList(path); + bindings.add(command); + config.set(path, bindings); + saveConfig(); + } + + public synchronized void clear(ItemStack item) { + Optional<UUID> id = getId(item); + if (id.isEmpty()) return; + config.set(id.get().toString(), null); + saveConfig(); + } + + public synchronized boolean reload() { + try { + config.load(configFile); + return true; + } catch (Exception _e) { + return false; + } + } + + private Optional<UUID> getId(ItemStack item) { + ItemMeta itemMeta = item.getItemMeta(); + if (itemMeta == null) return Optional.empty(); + String id = itemMeta.getPersistentDataContainer().get(ID_KEY, PersistentDataType.STRING); + try { + return Optional.ofNullable(id).map(UUID::fromString); + } catch (IllegalArgumentException _e) { + return Optional.empty(); + } + } + + private UUID createId(ItemStack item) throws NoMetaException { + UUID id = UUID.randomUUID(); + ItemMeta itemMeta = item.getItemMeta(); + if (itemMeta == null) throw new NoMetaException(); + itemMeta.getPersistentDataContainer().set(ID_KEY, PersistentDataType.STRING, id.toString()); + item.setItemMeta(itemMeta); + return id; + } + + private void saveConfig() { + try { + config.save(configFile); + } catch (IOException e) { + Bukkit.getLogger() + .severe("Unable to save power tool bindings to disk, data may be lost on restart."); + } + } +} diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml new file mode 100644 index 0000000..ec4a04a --- /dev/null +++ b/src/main/resources/plugin.yml @@ -0,0 +1,62 @@ +name: Sandbox +website: https://mc.cflems.net +author: cflems +version: 0.1.0 +description: Make your Minecraft server into your personal sandbox. +main: net.cflems.mc.sandbox.Sandbox +load: POSTWORLD +api-version: '1.21.6' +depend: [ ] +commands: + enchant: + usage: /enchant <enchantment> [level] [player] + description: Enchants the item in your main hand. + fly: + usage: /fly [player] + description: Toggles your ability to fly. + repair: + usage: /repair [player] + description: Repairs the item in your main hand. + fireball: + usage: /fireball + description: Shoots a fireball. + powertool: + aliases: [ "pt" ] + usage: /powertool [command...] + description: Binds a command to the item in your main hand, or clears bound commands if none specified. +permissions: + sandbox.*: + default: op + description: Permission to do anything with this plugin. + children: + sandbox.enchant: true + sandbox.enchant.others: true + sandbox.repair: true + sandbox.repair.others: true + sandbox.fly: true + sandbox.fly.others: true + sandbox.fireball: true + sandbox.powertool: true + sandbox.powertool.use: true + sandbox.powertool.reload: true + sandbox.enchant: + description: Permission to enchant your items. + sandbox.enchant.others: + description: Permission to enchant other people's items. + sandbox.fly: + description: Permission to toggle flight. + sandbox.fly.others: + description: Permission to toggle other people's flight. + sandbox.repair: + description: Permission to repair your items. + sandbox.repair.others: + description: Permission to repair other people's items. + sandbox.fireball: + description: Permission to use fireballs. + sandbox.powertool: + description: Permission to modify power tools. + sandbox.powertool.use: + default: true + description: Permission to use power tools. + sandbox.powertool.reload: + description: Permission to reload power tool bindings from disk. |
